diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index f5749203..c8a63d91 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -6,13 +6,13 @@ var Bn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>( Transform type: ${this.transformType} -`}},pt=960,yt=cA.concave;function TA(t,A,e,n,s){return t<<10|A<<9|e<<8|n<<7|s}var Pe=[new j({srcEnum:TA(yt,0,1,0,K.noteOnVelocity),dest:g.initialAttenuation,amt:pt,secSrcEnum:0,transform:0}),new j({srcEnum:129,dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new j({srcEnum:TA(yt,0,1,1,m.mainVolume),dest:g.initialAttenuation,amt:pt,secSrcEnum:0,transform:0}),new j({srcEnum:13,dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new j({srcEnum:526,dest:g.fineTune,amt:12700,secSrcEnum:16,transform:0}),new j({srcEnum:650,dest:g.pan,amt:500,secSrcEnum:0,transform:0}),new j({srcEnum:TA(yt,0,1,1,m.expressionController),dest:g.initialAttenuation,amt:pt,secSrcEnum:0,transform:0}),new j({srcEnum:219,dest:g.reverbEffectsSend,amt:750,secSrcEnum:0,transform:0}),new j({srcEnum:221,dest:g.chorusEffectsSend,amt:750,secSrcEnum:0,transform:0}),new j({srcEnum:TA(cA.linear,0,0,0,K.polyPressure),dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new j({srcEnum:TA(cA.linear,0,0,1,m.tremoloDepth),dest:g.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new j({srcEnum:TA(cA.linear,1,0,1,m.releaseTime),dest:g.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new j({srcEnum:TA(cA.linear,1,0,1,m.brightness),dest:g.initialFilterFc,amt:6e3,secSrcEnum:0,transform:0}),new j({srcEnum:TA(cA.linear,1,0,1,m.timbreHarmonicContent),dest:g.initialFilterQ,amt:250,secSrcEnum:0,transform:0})];var EA=128,Ke=147,St=new Int16Array(Ke).fill(0),dA=(t,A)=>St[t]=A<<7;dA(m.mainVolume,100);dA(m.balance,64);dA(m.expressionController,127);dA(m.pan,64);dA(m.timbreHarmonicContent,64);dA(m.releaseTime,64);dA(m.attackTime,64);dA(m.brightness,64);dA(m.soundController6,64);dA(m.soundController7,64);dA(m.soundController8,64);dA(m.soundController9,64);dA(m.generalPurposeController6,64);dA(m.generalPurposeController8,64);dA(EA+K.pitchWheel,64);dA(EA+K.pitchWheelRange,2);var gA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Dt=Object.keys(gA).length,kt=new Float32Array(Dt);kt[gA.modulationMultiplier]=1;var fA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6};function yn(t=!1){let A={midiControllers:new Int16Array(Ke),lockedControllers:Array(Ke).fill(!1),customControllers:new Float32Array(Dt),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:fA.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},velocityOverride: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 wt={velocityOverride:128};var Sn="spessasynth-worklet-system",Dn=350,SA=9,Ve=16,Oe="gs";var bA={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 n=8*(A-1);n>=0;n-=8)e|=t[t.currentIndex++]<>>0}function kn(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=we(t.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=n,e.status){case F.noteOn:let s=t.messageData[1];if(s>0)this.synth.noteOn(e.channel,t.messageData[0],s),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:s});else{this.synth.noteOff(e.channel,t.messageData[0]);let I=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);I!==-1&&this.playingNotes.splice(I,1)}break;case F.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(I=>I.midiNote===t.messageData[0]&&I.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case F.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case F.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case F.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case F.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case F.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case F.systemExclusive:this.synth.systemExclusive(t.messageData,n);break;case F.setTempo:this.oneTickToSeconds=60/(No(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),T("invalid tempo! falling back to 120 BPM"));break;case F.timeSignature:case F.endOfTrack:case F.midiChannelPrefix:case F.songPosition:case F.activeSensing:case F.keySignature:case F.sequenceNumber:case F.sequenceSpecific:break;case F.text:case F.lyric:case F.copyright:case F.trackName:case F.marker:case F.cuePoint:case F.instrumentName:case F.programName:this.post(wA.textEvent,[t.messageData,e.status]);break;case F.midiPort:this.assignMIDIPort(A,t.messageData[0]);break;case F.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:T(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(F).find(I=>F[I]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function wn(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function No(t){return t.messageData.currentIndex=0,6e7/zA(t.messageData,3)}function Fn(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(n.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 Rn(){let t=0,A=1/0;return this.tracks.forEach((e,n)=>{this.eventIndex[n]>=e.length||e[this.eventIndex[n]].ticks>>0}function Ee(t,A,e){for(let n=0;n>n*8&255}function J(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function lA(t,A){Ee(t,A,4)}function jA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function Gn(t){return t>127?t-256:t}function V(t,A,e=void 0,n=!0){if(e){let s=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(s.buffer)}else{let s=!1,o="";for(let I=0;I127){if(n){s=!0;continue}else if(C===0){s=!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 n=0;nA.length)for(let n=0;ne.header!=="LIST"?!1:(e.chunkData.currentIndex=0,V(e.chunkData,4)===A))}function Xe(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var We={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 _e=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 Be(t,A){let e=0;for(;t>0;){let n=A.tempoChanges.find(o=>o.ticksSt[t]=A<<7;dA(m.mainVolume,100);dA(m.balance,64);dA(m.expressionController,127);dA(m.pan,64);dA(m.timbreHarmonicContent,64);dA(m.releaseTime,64);dA(m.attackTime,64);dA(m.brightness,64);dA(m.soundController6,64);dA(m.soundController7,64);dA(m.soundController8,64);dA(m.soundController9,64);dA(m.generalPurposeController6,64);dA(m.generalPurposeController8,64);dA(EA+K.pitchWheel,64);dA(EA+K.pitchWheelRange,2);var gA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Dt=Object.keys(gA).length,kt=new Float32Array(Dt);kt[gA.modulationMultiplier]=1;var fA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6};function yn(t=!1){let A={midiControllers:new Int16Array(Ke),lockedControllers:Array(Ke).fill(!1),customControllers:new Float32Array(Dt),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:fA.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},velocityOverride: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 wt={velocityOverride:128};var Sn="spessasynth-worklet-system",Dn=350,SA=9,Ve=16,Oe="gs";var bA={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 n=8*(A-1);n>=0;n-=8)e|=t[t.currentIndex++]<>>0}function kn(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=we(t.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=n,e.status){case F.noteOn:let s=t.messageData[1];if(s>0)this.synth.noteOn(e.channel,t.messageData[0],s),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:s});else{this.synth.noteOff(e.channel,t.messageData[0]);let I=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);I!==-1&&this.playingNotes.splice(I,1)}break;case F.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(I=>I.midiNote===t.messageData[0]&&I.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case F.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case F.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case F.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case F.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case F.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case F.systemExclusive:this.synth.systemExclusive(t.messageData,n);break;case F.setTempo:this.oneTickToSeconds=60/(No(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),T("invalid tempo! falling back to 120 BPM"));break;case F.timeSignature:case F.endOfTrack:case F.midiChannelPrefix:case F.songPosition:case F.activeSensing:case F.keySignature:case F.sequenceNumber:case F.sequenceSpecific:break;case F.text:case F.lyric:case F.copyright:case F.trackName:case F.marker:case F.cuePoint:case F.instrumentName:case F.programName:this.post(wA.textEvent,[t.messageData,e.status]);break;case F.midiPort:this.assignMIDIPort(A,t.messageData[0]);break;case F.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:T(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(F).find(I=>F[I]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function wn(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function No(t){return t.messageData.currentIndex=0,6e7/zA(t.messageData,3)}function Fn(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(n.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 Rn(){let t=0,A=1/0;return this.tracks.forEach((e,n)=>{this.eventIndex[n]>=e.length||e[this.eventIndex[n]].ticks>>0}function Ee(t,A,e){for(let n=0;n>n*8&255}function J(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function lA(t,A){Ee(t,A,4)}function jA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function Gn(t){return t>127?t-256:t}function V(t,A,e=void 0,n=!0){if(e){let s=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(s.buffer)}else{let s=!1,o="";for(let I=0;I127){if(n){s=!0;continue}else if(C===0){s=!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 n=0;nA.length)for(let n=0;ne.header!=="LIST"?!1:(e.chunkData.currentIndex=0,V(e.chunkData,4)===A))}function Xe(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var We={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 _e=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 Be(t,A){let e=0;for(;t>0;){let n=A.tempoChanges.find(o=>o.ticks0&&(b+=this.tracks[S-1][this.tracks[S-1].length-1].ticks);w.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=b),_=cn[i>>4],(i&240)===F.noteOn){G.add(sA);let rA=w.data[w.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,rA),this.keyRange.max=Math.max(this.keyRange.max,rA)}x=i;break}let v=new Y(_),z=w.data.slice(w.data.currentIndex,w.data.currentIndex+_);w.data.currentIndex+=_,v.set(z,0);let oA=new Ie(b,i,v);switch(k.push(oA),sA){case-2:switch(i){case F.setTempo:this.tempoChanges.push({ticks:b,tempo:6e7/zA(z,3)});break;case F.marker:switch(V(v,v.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=b;break;case"loopend":c=b}v.currentIndex=0;break;case F.midiPort:let CA=v[0];this.midiPorts[S]=CA,this.midiPortChannelOffsets[CA]===void 0&&(this.midiPortChannelOffsets[CA]=l,l+=16);break;case F.copyright:o||(this.copyright+=V(v,v.length,void 0,!1)+` +`," "),I=!0),this.RMIDInfo.IALB&&!this.RMIDInfo.IPRD&&(this.RMIDInfo.IPRD=this.RMIDInfo.IALB),this.RMIDInfo.PRD&&!this.RMIDInfo.IALB&&(this.RMIDInfo.IALB=this.RMIDInfo.IPRD),this.bankOffset=1,this.RMIDInfo[We.bankOffset]&&(this.bankOffset=S(this.RMIDInfo[We.bankOffset],2))}}C&&(this.bankOffset=0)}else s=n;let B=this.readMIDIChunk(s);if(B.type!=="MThd")throw Z(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${B.type}"`);if(B.size!==6)throw Z(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${B.size}`);this.format=zA(B.data,2),this.tracksAmount=zA(B.data,2),this.timeDivision=zA(B.data,2),this.keyRange={min:127,max:0},this.lyrics=[],this.tempoChanges=[{ticks:0,tempo:120}];let d=null,c=null;this.lastVoiceEventTick=0,this.midiPorts=[];let l=0;this.midiPortChannelOffsets=[],this.usedChannelsOnTrack=[],this.tracks=[];for(let y=0;y0&&(b+=this.tracks[y-1][this.tracks[y-1].length-1].ticks);w.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=b),_=cn[i>>4],(i&240)===F.noteOn){G.add(sA);let rA=w.data[w.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,rA),this.keyRange.max=Math.max(this.keyRange.max,rA)}x=i;break}let v=new Y(_),z=w.data.slice(w.data.currentIndex,w.data.currentIndex+_);w.data.currentIndex+=_,v.set(z,0);let oA=new Ie(b,i,v);switch(k.push(oA),sA){case-2:switch(i){case F.setTempo:this.tempoChanges.push({ticks:b,tempo:6e7/zA(z,3)});break;case F.marker:switch(V(v,v.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=b;break;case"loopend":c=b}v.currentIndex=0;break;case F.midiPort:let CA=v[0];this.midiPorts[y]=CA,this.midiPortChannelOffsets[CA]===void 0&&(this.midiPortChannelOffsets[CA]=l,l+=16);break;case F.copyright:o||(this.copyright+=V(v,v.length,void 0,!1)+` `);break;case F.lyric:this.lyrics.push(v)}break;case-3:if(v.slice(0,7).every((rA,CA)=>bo[CA]===rA)){let rA=v.slice(7,z.length-3),CA=V(rA,rA.length)+` -`;this.copyright+=CA,p(`%cDecoded Roland SC message! %c${CA}`,r.recognized,r.value)}break;default:if((i&240)===F.controllerChange)switch(v[0]){case 2:case 116:d=b;break;case 4:case 117:c===null?c=b:c=0;break;case 0:C&&v[1]!==0&&v[1]!==127&&(p("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(k),this.usedChannelsOnTrack.push(G),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,r.info,r.value,r.info,r.value)}p("%cAll tracks parsed correctly!",r.recognized),yA("%cCorrecting loops, ports and detecting notes...",r.info);let u=[];for(let S of this.tracks){let k=S.find(w=>(w.messageStatusByte&240)===F.noteOn);k&&u.push(k.ticks)}this.firstNoteOn=Math.min(...u),p(`%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},p(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let y=0;for(let S of this.midiPorts)if(S!==-1){y=S;break}if(this.midiPorts=this.midiPorts.map(S=>S===-1?y:S),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?p("%cNo additional MIDI Ports detected.",r.info):p("%cMIDI Ports detected!",r.recognized),!I)if(this.tracks.length>1){if(this.tracks[0].find(S=>S.messageStatusByte>=F.noteOn&&S.messageStatusBytek.messageStatusByte===F.trackName);S&&(this.rawMidiName=S.messageData,this.midiName=V(S.messageData,S.messageData.length,void 0,!1))}}else{let S=this.tracks[0].find(k=>k.messageStatusByte===F.trackName);S&&(this.rawMidiName=S.messageData,this.midiName=V(S.messageData,S.messageData.length,void 0,!1))}if(this.fileName=e,this.midiName=this.midiName.trim(),this.midiName.length===0){p("%cNo name detected. Using the alt name!",r.info),this.midiName=hn(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let S=0;Sl>c?l:c),n=[];for(let c=0;c{I[y]>=u.length||u[I[y]].ticks0;){let c=h(),l=t.tracks[c];if(I[c]>=l.length){C--;continue}let u=l[I[c]];if(I[c]++,u.messageStatusByte===F.midiPort){B[c]=u.messageData[0];continue}let y=u.messageStatusByte&240;if(y!==F.noteOn&&y!==F.controllerChange&&y!==F.programChange&&y!==F.systemExclusive)continue;let S=(u.messageStatusByte&15)+t.midiPortChannelOffsets[B[c]]||0,k=n[S];switch(y){case F.programChange:k.program=u.messageData[0],s(k);break;case F.controllerChange:if(u.messageData[0]!==m.bankSelect||d==="gs"&&k.drums)continue;let w=u.messageData[1],G=Math.max(0,w-t.bankOffset);if(d==="xg"){let $=w===120||w===126||w===127;$!==k.drums?(k.drums=$,k.bank=k.drums?128:G,s(k)):k.bank=k.drums?128:G;continue}n[S].bank=G;break;case F.noteOn:if(u.messageData[1]===0)continue;s(k),o[k.string].add(`${u.messageData[0]}-${u.messageData[1]}`);break;case F.systemExclusive:if(u.messageData[0]!==65||u.messageData[2]!==66||u.messageData[3]!==18||u.messageData[4]!==64||!(u.messageData[5]&16)||u.messageData[6]!==21){u.messageData[0]===67&&u.messageData[2]===76&&u.messageData[5]===126&&u.messageData[6]===0&&(d="xg");continue}let x=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+t.midiPortChannelOffsets[B[c]],b=!!(u.messageData[7]>0&&u.messageData[5]>>4);k=n[x],k.drums=b,k.bank=b?128:0,s(k);break}}for(let c of Object.keys(o))o[c].size===0&&(p(`%cDetected change but no keys for %c${c}`,r.info,r.value),delete o[c]);return Z(),o}function Mn(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=Be(this.midiData.firstNoteOn,this.midiData),p(`%cTotal song time: ${mt(Math.ceil(this.duration)).time}`,r.recognized),this.post(wA.songChange,[new Ze(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(T(`%cVery short song: (${mt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function bn(t){this.songs=t.reduce((A,e)=>{if(e.duration)return A.push(e),A;try{A.push(new ze(e.binary,e.altName||""))}catch(n){return this.post(wA.midiError,n.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 Ln(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Un(){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[m.mainVolume]=100;PA[m.expressionController]=127;PA[m.pan]=64;PA[m.releaseTime]=64;PA[m.brightness]=64;PA[m.reverbDepth]=0;function Tn(t,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let e=this.synth.workletProcessorChannels.length,n=Array(e).fill(8192),s=[];for(let C=0;CC===m.dataDecrement||C===m.dataIncrement||C===m.dataEntryMsb||C===m.dataDecrement||C===m.lsbForControl6DataEntry||C===m.RPNLsb||C===m.RPNMsb||C===m.NRPNLsb||C===m.NRPNMsb||C===m.bankSelect||C===m.lsbForControl0BankSelect||C===m.resetAllControllers,I=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let B=we(h.messageStatusByte),d=B.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(B.status){case F.noteOn:case F.noteOff:case F.keySignature:break;case F.pitchBend:n[d]=h.messageData[1]<<7|h.messageData[0];break;case F.programChange:let l=s[d];l.program=h.messageData[0],l.actualBank=l.bank;break;case F.controllerChange:let u=h.messageData[0];if(o(u)){let y=h.messageData[1];if(u===m.bankSelect){s[d].bank=y;break}this.sendMIDIMessages?this.sendMIDICC(d,u,y):this.synth.controllerChange(d,u,y)}else I[d]===void 0&&(I[d]=Array.from(PA)),I[d][u]=h.messageData[1];break;default:this._processEvent(h,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-h.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7,n[C]&127),I[C]!==void 0&&I[C].forEach((h,B)=>{h!==PA[B]&&!o(B)&&this.sendMIDICC(C,B,h)}),s[C].program>=0&&s[C].actualBank>=0){let h=s[C].actualBank;this.sendMIDICC(C,m.bankSelect,h),this.sendMIDIProgramChange(C,s[C].program)}}else for(let C=0;C>7,n[C]&127),I[C]!==void 0&&I[C].forEach((h,B)=>{h!==PA[B]&&!o(B)&&this.synth.controllerChange(C,B,h)}),s[C].program>=0&&s[C].actualBank>=0){let h=s[C].actualBank;this.synth.controllerChange(C,m.bankSelect,h),this.synth.programChange(C,s[C].program)}return!0}function Hn(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 Yn(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(wA.timeChange,currentTime-Be(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Jn(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function vn(t,A){switch(t){default:break;case bA.loadNewSongList:this.loadNewSongList(A);break;case bA.pause:this.pause();break;case bA.play:this.play(A);break;case bA.stop:this.stop();break;case bA.setTime:this.currentTime=A;break;case bA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case bA.setPlaybackRate:this.playbackRate=A;break;case bA.setLoop:this.loop=A;break;case bA.changeSong:A?this.nextSong():this.previousSong();break;case bA.getMIDI:this.post(wA.getMIDI,this.midiData);break;case bA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function qn(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:pA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Pn(t){this.post(wA.midiEvent,t)}function Kn(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|t,A,e])}function Vn(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|t,A])}function On(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|t,e,A])}function Zn(){if(this.sendMIDIMessages){this.sendMIDIMessage([F.reset]);for(let t=0;tthis.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&AXn?440*Math.pow(2,(t-6900)/1200):Rt[~~t-je]}var xt=-1660,Lo=1600,Gt=new Float32Array((Lo-xt)*100+1);for(let t=0;t.5?1:0,n?e*2-1:e;case cA.concave:return n?(e=e*2-1,e<0?-ZA[~~(e*-BA)]:ZA[~~(e*BA)]):ZA[~~(e*BA)];case cA.convex:return n?(e=e*2-1,e<0?-ne[~~(e*-BA)]:ne[~~(e*BA)]):ne[~~(e*BA)]}}var Mt=1,Nt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)n-=o;let C=~~n,h=C+1;for(;h>=e.loopEnd;)h-=o;let B=n-C,d=s[h],c=s[C];A[I]=c+(d-c)*B,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end){t.finished=!0;return}let h=n-I,B=s[C],d=s[I];A[o]=d+(B-d)*h,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function _n(t,A){let e=t.sample,n=e.cursor,s=e.loopEnd-e.loopStart,o=e.sampleData;if(t.sample.isLooping)for(let I=0;I=e.loopEnd;)n-=s;let C=~~n+1;for(;C>=e.loopEnd;)C-=s;A[I]=o[C],n+=e.playbackStep*t.currentTuningCalculated}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let I=0;I=e.end){t.finished=!0;return}A[I]=o[C],n+=e.playbackStep*t.currentTuningCalculated}}e.cursor=n}function zn(t,A){let e=t.sample,n=e.cursor,s=e.sampleData;if(e.isLooping){let o=e.loopEnd-e.loopStart;for(let I=0;I=e.loopEnd;)n-=o;let C=~~n,h=C+1,B=h+1,d=B+1,c=n-C;h>=e.loopEnd&&(h-=o),B>=e.loopEnd&&(B-=o),d>=e.loopEnd&&(d-=o);let l=s[C],u=s[h],y=s[B],S=s[d],k=.5*(y-l),w=l-2.5*u+2*y-.5*S,G=.5*(S-l)+1.5*(u-y);A[I]=((G*c+w)*c+k)*c+u,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end||h>=e.end||B>=e.end){t.finished=!0;return}let c=s[I],l=s[C],u=s[h],y=s[B],S=.5*(u-c),k=c-2.5*l+2*u-.5*y,w=.5*(y-c)+1.5*(l-u);A[o]=((w*d+k)*d+S)*d+l,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function jn(t,A,e,n,s,o,I,C,h){if(!isNaN(e[0])){if(I>0){let B=o[0],d=o[1];I=Math.min(I,1e3);let c=I/1300,l=t*c,u=A*c;for(let y=0;y0){let B=C[0],d=C[1];h=Math.min(h,1e3);let c=h/1300,l=t*c,u=A*c;for(let y=0;y0)for(let B=0;B0)for(let B=0;B13499&&A.filter.reasonanceCb===0)return;let o=A.filter;(o.cutoffCents!==n||o.reasonanceCb!==A.modulatedGenerators[g.initialFilterQ])&&(o.cutoffCents=n,o.reasonanceCb=A.modulatedGenerators[g.initialFilterQ],t.calculateCoefficients(o));for(let I=0;I=bt}static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=KA(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static recalculate(A){let e=A.volumeEnvelope,n=B=>Math.max(0,Math.floor(HA(B)*e.sampleRate));e.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[g.initialAttenuation],1440))/10,e.sustainDbRelative=Math.min(JA,A.modulatedGenerators[g.sustainVolEnv]/10);let s=Math.min(JA,e.sustainDbRelative);e.attackDuration=n(A.modulatedGenerators[g.attackVolEnv]);let o=A.modulatedGenerators[g.decayVolEnv],I=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvDecay],C=s/JA;e.decayDuration=n(o+I)*C,e.releaseDuration=n(A.modulatedGenerators[g.releaseVolEnv]),e.delayEnd=n(A.modulatedGenerators[g.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let h=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvHold];if(e.holdEnd=n(A.modulatedGenerators[g.holdVolEnv]+h)+e.attackEnd,e.decayEnd=e.decayDuration+e.holdEnd,e.state===0&&e.attackEnd===0&&(e.state=2),A.isInRelease){let B=Math.max(0,Math.min(JA,e.sustainDbRelative)),d=B/JA;switch(e.decayDuration=n(o+I)*d,e.state){case 0:e.releaseStartDb=JA;break;case 1:let c=1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration;e.releaseStartDb=20*Math.log10(c)*-1;break;case 2:e.releaseStartDb=0;break;case 3:e.releaseStartDb=(1-(e.decayEnd-e.releaseStartTimeSamples)/e.decayDuration)*B;break;case 4:e.releaseStartDb=B;break}e.releaseStartDb=Math.max(0,Math.min(e.releaseStartDb,JA)),e.releaseStartDb>=bt&&(A.finished=!0),e.currentReleaseGain=KA(e.releaseStartDb)}}static apply(A,e,n,s){let o=A.volumeEnvelope,I=n/10,C=s;if(A.isInRelease){let B=o.currentSampleTime-o.releaseStartTimeSamples;if(B>=o.releaseDuration){for(let c=0;c=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>=bt&&(A.finished=!0);;)if(o.attenuation+=(o.attenuationTarget-o.attenuation)*C,e[h]*=KA(o.sustainDbRelative+I+o.attenuation),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++h>=e.length)return}}};var As=Math.PI/2,es=.05;function ts(t,A,e,n,s,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,LA.startRelease(A),YA.startRelease(A),A.sample.loopingMode===3&&(A.sample.isLooping=!1)),A.modulatedGenerators[g.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let I=A.targetKey,C=A.modulatedGenerators[g.fineTune]+t.customControllers[gA.channelTuning]+t.customControllers[gA.channelTransposeFine]+t.customControllers[gA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],h=A.modulatedGenerators[g.coarseTune]+t.customControllers[gA.channelTuningSemitones],B=this.tunings[t.preset.program]?.[A.realKey];B?.midiNote>=0&&(I=B.midiNote,C+=B.centTuning),C+=(I-A.sample.rootKey)*A.modulatedGenerators[g.scaleTuning];let d=A.modulatedGenerators[g.vibLfoToPitch];if(d!==0){let oA=A.startTime+HA(A.modulatedGenerators[g.delayVibLFO]),rA=Fe(A.modulatedGenerators[g.freqVibLFO]),CA=$e(oA,rA,currentTime);C+=CA*(d*t.customControllers[gA.modulationMultiplier])}let c=A.modulatedGenerators[g.initialFilterFc],l=c,u=A.modulatedGenerators[g.modLfoToPitch],y=A.modulatedGenerators[g.modLfoToVolume],S=A.modulatedGenerators[g.modLfoToFilterFc],k=0;if(u+S+y!==0){let oA=A.startTime+HA(A.modulatedGenerators[g.delayModLFO]),rA=Fe(A.modulatedGenerators[g.freqModLFO]),CA=$e(oA,rA,currentTime);C+=CA*(u*t.customControllers[gA.modulationMultiplier]),k=-CA*y,l+=CA*S}if(t.channelVibrato.depth>0){let oA=$e(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);oA&&(C+=oA*t.channelVibrato.depth)}let w=A.modulatedGenerators[g.modEnvToPitch],G=A.modulatedGenerators[g.modEnvToFilterFc],x=YA.getValue(A,currentTime);l+=x*G,C+=x*w;let b=~~(C+h*100);b!==A.currentTuningCents&&(A.currentTuningCents=b,A.currentTuningCalculated=Math.pow(2,b/1200));let $=(Math.max(-500,Math.min(500,A.modulatedGenerators[g.pan]))+500)/1e3,i=new Float32Array(e.length);switch(this.interpolationType){case he.linear:default:Wn(A,i);break;case he.nearestNeighbor:_n(A,i);break;case he.fourthOrder:zn(A,i)}Qe.apply(A,i,l,c>13499),LA.apply(A,i,k,this.volumeEnvelopeSmoothingFactor),A.currentPan+=($-A.currentPan)*this.panSmoothingFactor;let sA=Math.cos(As*A.currentPan)*this.panLeft,_=Math.sin(As*A.currentPan)*this.panRight,v=this.oneOutputMode?0:A.modulatedGenerators[g.reverbEffectsSend],z=this.oneOutputMode?0:A.modulatedGenerators[g.chorusEffectsSend];jn(sA,_,i,e,n,s,v,o,z)}function To(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 ns(t){let A=[];for(let n of this.workletProcessorChannels)for(let s of n.voices)if(!s.finished){let o=To(n,s);A.push({channel:n,voice:s,priority:o})}A.sort((n,s)=>n.priority-s.priority);let e=A.slice(0,t);for(let{channel:n,voice:s}of e){let o=n.voices.indexOf(s);o>-1&&n.voices.splice(o,1)}}function ss(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimers=t);var Ho=function(t){var A,e,n,s,o,I,C,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",B="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do s=h.indexOf(t.charAt(d++)),o=h.indexOf(t.charAt(d++)),I=h.indexOf(t.charAt(d++)),C=h.indexOf(t.charAt(d++)),A=s<<2|o>>4,e=(15&o)<<4|I>>2,n=(3&I)<<6|C,B+=String.fromCharCode(A),I!==64&&(B+=String.fromCharCode(e)),C!==64&&(B+=String.fromCharCode(n));while(d1&&(i.thisProgram=process.argv[1].replace(/\\/g,"/")),i.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(a){if(!(a instanceof ye))throw a}),process.on("unhandledRejection",function(a,E){process.exit(1)}),i.quit=function(a){process.exit(a)},i.inspect=function(){return"[Emscripten Module object]"}):oA?(typeof read<"u"&&(i.read=function(E){return read(E)}),i.readBinary=function(E){var Q;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(Q=read(E,"binary"))=="object"),Q)},typeof scriptArgs<"u"?i.arguments=scriptArgs:typeof arguments<"u"&&(i.arguments=arguments),typeof quit=="function"&&(i.quit=function(a){quit(a)})):(_||v)&&(_?document.currentScript&&(rA=document.currentScript.src):rA=self.location.href,rA=rA.indexOf("blob:")!==0?rA.split("/").slice(0,-1).join("/")+"/":"",i.read=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.send(null),Q.responseText},v&&(i.readBinary=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.responseType="arraybuffer",Q.send(null),new Uint8Array(Q.response)}),i.readAsync=function(E,Q,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){Q(R.response);return}f()},R.onerror=f,R.send(null)},i.setWindowTitle=function(a){document.title=a});var Me=i.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),RA=i.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Me);for(t in sA)sA.hasOwnProperty(t)&&(i[t]=sA[t]);function Ne(a){var E=u;return u=u+a+15&-16,E}function Ot(a){var E=h[x>>2],Q=E+a+15&-16;return h[x>>2]=Q,Q>=hA&&!tn()?(h[x>>2]=E,0):E}function Zt(a,E){return E||(E=16),a=Math.ceil(a/E)*E}function fo(a){switch(a){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(a[a.length-1]==="*")return 4;if(a[0]!=="i")return 0;var E=parseInt(a.substr(1));return _A(E%8==0),E/8}}function fe(a){fe.shown||(fe.shown={}),fe.shown[a]||(fe.shown[a]=1,RA(a))}sA=void 0;var mo={"f64-rem":function(a,E){return a%E},debugger:function(){}},it=[];function Ko(a,E){for(var Q=0,f=Q;f>>0)+4294967296*+(E>>>0):+(a>>>0)+4294967296*+(0|E)}function It(a,E,Q){return Q&&Q.length?i["dynCall_"+a].apply(null,[E].concat(Q)):i["dynCall_"+a].call(null,E)}var be=0,Xt=0;function _A(a,E){a||OA("Assertion failed: "+E)}function Wt(a){var E=i["_"+a];return _A(E,"Cannot call unknown function "+a+", make sure it is exported"),E}var _t={stackSave:function(){lt()},stackRestore:function(){ct()},arrayToC:function(a){var E,Q,f=Je(a.length);return E=a,Q=f,s.set(E,Q),f},stringToC:function(a){var E=0;if(a!=null&&a!==0){var Q=(a.length<<2)+1;E=Je(Q),$t(a,E,Q)}return E}},po={string:_t.stringToC,array:_t.arrayToC};function zt(a,E,Q,f,R){var P=Wt(a),X=[],N=0;if(f)for(var QA=0;QA>0]=E;break;case"i16":I[a>>1]=E;break;case"i32":h[a>>2]=E;break;case"i64":tempI64=[E>>>0,+Fo(tempDouble=E)>=1?tempDouble>0?(0|Go(+an(tempDouble/4294967296),4294967295))>>>0:~~+Ro((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],h[a>>2]=tempI64[0],h[a+4>>2]=tempI64[1];break;case"float":d[a>>2]=E;break;case"double":c[a>>3]=E;break;default:OA("invalid type for setValue: "+Q)}}function Xo(a,E,Q){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return s[a>>0];case"i16":return I[a>>1];case"i32":case"i64":return h[a>>2];case"float":return d[a>>2];case"double":return c[a>>3];default:OA("invalid type for getValue: "+E)}return null}function Wo(a,E,Q,f){typeof a=="number"?(P=!0,X=a):(P=!1,X=a.length);var R=typeof E=="string"?E:null;if(N=Q==4?f:[typeof Ye=="function"?Ye:Ne,Je,Ne,Ot][Q===void 0?2:Q](Math.max(X,R?1:E.length)),P){for(f=N,_A((3&N)==0),QA=N+(-4&X);f>2]=0;for(QA=N+X;f>0]=0;return N}if(R==="i8")return a.subarray||a.slice?o.set(a,N):o.set(new Uint8Array(a),N),N;for(var P,X,N,QA,iA,aA,tA,q=0;q>0],(f!=0||E)&&(X++,!E||X!=E););E||(E=X);var N="";if(P<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(a,a+Math.min(E,1024))),N=N?N+R:R,a+=1024,E-=1024;return N}return Q=a,function(iA,aA){for(var tA=aA;iA[tA];)++tA;if(tA-aA>16&&iA.subarray&&jt)return jt.decode(iA.subarray(aA,tA));for(var q,mA,GA,xA,MA,ee,NA="";;){if(!(q=iA[aA++]))return NA;if(!(128&q)){NA+=String.fromCharCode(q);continue}if(mA=63&iA[aA++],(224&q)==192){NA+=String.fromCharCode((31&q)<<6|mA);continue}if(GA=63&iA[aA++],(240&q)==224?q=(15&q)<<12|mA<<6|GA:(xA=63&iA[aA++],(248&q)==240?q=(7&q)<<18|mA<<12|GA<<6|xA:(MA=63&iA[aA++],q=(252&q)==248?(3&q)<<24|mA<<18|GA<<12|xA<<6|MA:(1&q)<<30|mA<<24|GA<<18|xA<<12|MA<<6|(ee=63&iA[aA++]))),q<65536)NA+=String.fromCharCode(q);else{var Se=q-65536;NA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(o,Q)}function zo(a){for(var E="";;){var Q=s[a++>>0];if(!Q)return E;E+=String.fromCharCode(Q)}}function jo(a,E){return function(f,R,P){for(var X=0;X>0]=f.charCodeAt(X);P||(s[R>>0]=0)}(a,E,!1)}var jt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ue(a,E,Q,f){if(!(f>0))return 0;for(var R=Q,P=Q+f-1,X=0;X=55296&&N<=57343&&(N=65536+((1023&N)<<10)|1023&a.charCodeAt(++X)),N<=127){if(Q>=P)break;E[Q++]=N}else if(N<=2047){if(Q+1>=P)break;E[Q++]=192|N>>6,E[Q++]=128|63&N}else if(N<=65535){if(Q+2>=P)break;E[Q++]=224|N>>12,E[Q++]=128|N>>6&63,E[Q++]=128|63&N}else if(N<=2097151){if(Q+3>=P)break;E[Q++]=240|N>>18,E[Q++]=128|N>>12&63,E[Q++]=128|N>>6&63,E[Q++]=128|63&N}else if(N<=67108863){if(Q+4>=P)break;E[Q++]=248|N>>24,E[Q++]=128|N>>18&63,E[Q++]=128|N>>12&63,E[Q++]=128|N>>6&63,E[Q++]=128|63&N}else{if(Q+5>=P)break;E[Q++]=252|N>>30,E[Q++]=128|N>>24&63,E[Q++]=128|N>>18&63,E[Q++]=128|N>>12&63,E[Q++]=128|N>>6&63,E[Q++]=128|63&N}}return E[Q]=0,Q-R}function $t(a,E,Q){return Ue(a,o,E,Q)}function Te(a){for(var E=0,Q=0;Q=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&a.charCodeAt(++Q)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var An=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function $o(a){for(var E=a,Q=E>>1;I[Q];)++Q;if((E=Q<<1)-a>32&&An)return An.decode(o.subarray(a,E));for(var f=0,R="";;){var P=I[a+2*f>>1];if(P==0)return R;++f,R+=String.fromCharCode(P)}}function Ar(a,E,Q){if(Q===void 0&&(Q=2147483647),Q<2)return 0;for(var f=E,R=(Q-=2)<2*a.length?Q/2:a.length,P=0;P>1]=X,E+=2}return I[E>>1]=0,E-f}function er(a){return 2*a.length}function tr(a){for(var E=0,Q="";;){var f=h[a+4*E>>2];if(f==0)return Q;if(++E,f>=65536){var R=f-65536;Q+=String.fromCharCode(55296|R>>10,56320|1023&R)}else Q+=String.fromCharCode(f)}}function nr(a,E,Q){if(Q===void 0&&(Q=2147483647),Q<4)return 0;for(var f=E,R=f+Q-4,P=0;P=55296&&X<=57343&&(X=65536+((1023&X)<<10)|1023&a.charCodeAt(++P)),h[E>>2]=X,(E+=4)+4>R)break}return h[E>>2]=0,E-f}function sr(a){for(var E=0,Q=0;Q=55296&&f<=57343&&++Q,E+=4}return E}function or(a){var E=Te(a)+1,Q=Ye(E);return Q&&Ue(a,s,Q,E),Q}function rr(a){var E=Te(a)+1,Q=Je(E);return Ue(a,s,Q,E),Q}function ir(a){return a}function ar(){var a,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()),(a=E).replace(/__Z[\w\d_]+/g,function(Q){var f,R=f=Q;return Q===R?Q:Q+" ["+R+"]"})}function gt(a,E){return a%E>0&&(a+=E-a%E),a}function en(a){i.buffer=n=a}function Ct(){i.HEAP8=s=new Int8Array(n),i.HEAP16=I=new Int16Array(n),i.HEAP32=h=new Int32Array(n),i.HEAPU8=o=new Uint8Array(n),i.HEAPU16=C=new Uint16Array(n),i.HEAPU32=B=new Uint32Array(n),i.HEAPF32=d=new Float32Array(n),i.HEAPF64=c=new Float64Array(n)}function tn(){var a=i.usingWasm?65536:16777216,E=2147483648-a;if(h[x>>2]>E)return!1;var Q=hA;for(hA=Math.max(hA,16777216);hA>2];)hA=hA<=536870912?gt(2*hA,a):Math.min(gt((3*hA+2147483648)/4,a),E);var f=i.reallocBuffer(hA);return f&&f.byteLength==hA?(en(f),Ct(),!0):(hA=Q,!1)}l=u=S=k=w=G=x=0,y=!1,i.reallocBuffer||(i.reallocBuffer=function(a){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(n,a);else{var E,Q=s;E=new ArrayBuffer(a),new Int8Array(E).set(Q)}}catch{return!1}return!!xo(E)&&E});try{(b=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{b=function(E){return E.byteLength}}var Et=i.TOTAL_STACK||5242880,hA=i.TOTAL_MEMORY||16777216;function So(){return hA}function me(a){for(;a.length>0;){var E=a.shift();if(typeof E=="function"){E();continue}var Q=E.func;typeof Q=="number"?E.arg===void 0?i.dynCall_v(Q):i.dynCall_vi(Q,E.arg):Q(E.arg===void 0?null:E.arg)}}hA=0?a:E<=32?2*Math.abs(1<=f&&(E<=32||a>f)&&(a=-2*f+a),a}var Fo=Math.abs,Ro=Math.ceil,an=Math.floor,Go=Math.min,Ae=0,Qt=null,pe=null;function Qr(a){return a}i.preloadedImages={},i.preloadedAudios={};var In="data:application/octet-stream;base64,";function He(a){return String.prototype.startsWith?a.startsWith(In):a.indexOf(In)===0}(function(){var E="main.wast",Q="main.wasm",f="main.temp.asm.js";He(E)||(E=CA(E)),He(Q)||(Q=CA(Q)),He(f)||(f=CA(f));var R={global:null,env:null,asm2wasm:mo,parent:i},P=null;function X(tA){return tA}function N(){try{if(i.wasmBinary)return new Uint8Array(i.wasmBinary);if(i.readBinary)return i.readBinary(Q);throw"both async and sync fetching of the wasm failed"}catch(tA){OA(tA)}}i.asmPreload=i.asm;var QA=i.reallocBuffer,iA=function(tA){tA=gt(tA,i.usingWasm?65536:16777216);var q=i.buffer.byteLength;if(i.usingWasm)try{var mA=i.wasmMemory.grow((tA-q)/65536);return mA!==-1?i.buffer=i.wasmMemory.buffer:null}catch{return null}};i.reallocBuffer=function(tA){return aA==="asmjs"?QA(tA):iA(tA)};var aA="";i.asm=function(tA,q,mA){var GA;if(!(q=GA=q).table){var xA,MA=i.wasmTableSize;MA===void 0&&(MA=1024);var ee=i.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?ee!==void 0?q.table=new WebAssembly.Table({initial:MA,maximum:ee,element:"anyfunc"}):q.table=new WebAssembly.Table({initial:MA,element:"anyfunc"}):q.table=Array(MA),i.wasmTable=q.table}return q.memoryBase||(q.memoryBase=i.STATIC_BASE),q.tableBase||(q.tableBase=0),xA=function(Se,ie,dt){if(typeof WebAssembly!="object")return RA("no native wasm support detected"),!1;if(!(i.wasmMemory instanceof WebAssembly.Memory))return RA("no native wasm Memory in use"),!1;function ve(vA,qA){if((P=vA.exports).memory){var De,ft,En;De=P.memory,ft=i.buffer,De.byteLength0?Q:Te(a)+1,R=Array(f),P=Ue(a,R,0,R.length);return E&&(R.length=P),R}function dr(a){for(var E=[],Q=0;Q255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}u+=16,x=Ne(4),w=(S=k=Zt(u))+Et,G=Zt(w),h[x>>2]=G,y=!0,i.wasmTableSize=4,i.wasmMaxTableSize=4,i.asmGlobalArg={},i.asmLibraryArg={abort:OA,assert:_A,enlargeMemory:tn,getTotalMemory:So,abortOnCannotGrowMemory:function(){OA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+hA+", (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,Q,f){var R=lt();try{return i.dynCall_iii(E,Q,f)}catch(P){if(ct(R),typeof P!="number"&&P!=="longjmp")throw P;i.setThrew(1,0)}},___assert_fail:function(E,Q,f,R){OA("Assertion failed: "+Le(E)+", at: "+[Q?Le(Q):"unknown filename",f,R?Le(R):"unknown function"])},___setErrNo:function(E){return i.___errno_location&&(h[i.___errno_location()>>2]=E),E},_abort:function(){i.abort()},_emscripten_memcpy_big:function(E,Q,f){return o.set(o.subarray(Q,Q+f),E),E},_llvm_floor_f64:an,DYNAMICTOP_PTR:x,tempDoublePtr:kA,ABORT:be,STACKTOP:k,STACK_MAX:w};var gn=i.asm(i.asmGlobalArg,i.asmLibraryArg,n);i.asm=gn,i.___errno_location=function(){return i.asm.___errno_location.apply(null,arguments)};var xo=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 Ye=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 Je=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 ye(a){this.name="ExitStatus",this.message="Program terminated with exit("+a+")",this.status=a}function ut(a){a=a||i.arguments,!(Ae>0)&&(function(){if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)ko(i.preRun.shift());me(nn)}(),!(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,be||(ht||(ht=!0,me(Bt)),me(sn),i.onRuntimeInitialized&&i.onRuntimeInitialized(),function(){if(i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;)wo(i.postRun.shift());me(rn)}()))}}function fr(a,E){(!E||!i.noExitRuntime||a!==0)&&(i.noExitRuntime||(be=!0,Xt=a,k=$,me(on),Do=!0,i.onExit&&i.onExit(a)),i.quit(a,new ye(a)))}function OA(a){throw i.onAbort&&i.onAbort(a),a!==void 0?(Me(a),RA(a),a=JSON.stringify(a)):a="",be=!0,Xt=1,"abort("+a+"). Build with -s ASSERTIONS=1 for more info."}if(i.dynCall_iii=function(){return i.asm.dynCall_iii.apply(null,arguments)},i.asm=gn,i.ccall=zt,i.cwrap=function(E,Q,f,R){var P=(f=f||[]).every(function(X){return X==="number"});return Q!=="string"&&P&&!R?Wt(E):function(){return zt(E,Q,f,arguments,R)}},ye.prototype=Error(),ye.prototype.constructor=ye,pe=function a(){i.calledRun||ut(),i.calledRun||(pe=a)},i.run=ut,i.abort=OA,i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();i.noExitRuntime=!0,ut(),i.onRuntimeInitialized=()=>{os=!0,rs()},VA.decode=function(a){return function(Q){if(!os)throw Error("Not initialized");var f={};function R(ie){return new Int32Array(i.HEAPU8.buffer,ie,1)[0]}function P(ie,dt){var ve=new ArrayBuffer(dt*Float32Array.BYTES_PER_ELEMENT),ae=new Float32Array(ve);return ae.set(new Float32Array(i.HEAPU8.buffer,ie,dt)),ae}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 X,N,QA,iA,aA=f.open(),tA=(X=Q,N=Q.byteLength,QA=i._malloc(N),(iA=new Uint8Array(i.HEAPU8.buffer,QA,N)).set(new Uint8Array(X,0,N)),iA),q=i._malloc(4),mA=i._malloc(4),GA=f.decode(aA,tA.byteOffset,tA.byteLength,q,mA);if(i._free(tA.byteOffset),GA<0)throw f.close(aA),i._free(q),Error("stbvorbis decode failed: "+GA);for(var xA=f.channels(aA),MA=Array(xA),ee=new Int32Array(i.HEAPU32.buffer,R(q),xA),NA=0;NA=0&&(n=this.workletProcessorChannels[e]),t.messageType){case eA.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case eA.noteOff:this.noteOff(e,A);break;case eA.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case eA.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case eA.customcCcChange:n.customControllers[A[0]]=A[1];break;case eA.killNote:this.killNote(e,A);break;case eA.programChange:this.programChange(e,A[0],A[1]);break;case eA.channelPressure:this.channelPressure(e,A);break;case eA.polyPressure:this.polyPressure(e,A[0],A[1]);break;case eA.ccReset:e===UA?this.resetAllControllers():this.resetControllers(e);break;case eA.systemExclusive:this.systemExclusive(A);break;case eA.setChannelVibrato:if(e===UA)for(let I=0;I{let e=(A.midiControllers[EA+K.pitchWheelRange]>>7)+(A.midiControllers[EA+K.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[EA+K.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:pA.channelProperties,messageData:t})}function Yo(t,A,e){let n=t,s=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:n,centTuning:s*.0061}}function gs(t,A=0){let e=t[0];if(!(this.deviceID!==UA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:T(`%cUnrecognized SysEx: %c${uA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let s;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),p(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),p(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let h=(t[5]<<7|t[6])-8192;s=Math.floor(h/81.92),this.setMasterTuning(s),p(`%cMaster Fine Tuning. Cents: %c${s}`,r.info,r.value);break;case 4:s=(t[5]-64)*100,this.setMasterTuning(s),p(`%cMaster Coarse Tuning. Cents: %c${s}`,r.info,r.value);break;default:T(`%cUnrecognized MIDI Device Control Real-time message: %c${uA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(p("%cGM system on",r.info),this.system="gm"):t[3]===3?(p("%cGM2 system on",r.info),this.system="gm2"):(p("%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 I=t[o++],C=t[o++];for(let B=0;B>1&1)===1&&this.setOctaveTuning(15+A,h);for(let B=0;B<7;B++)(t[5]>>B&1)===1&&this.setOctaveTuning(7+B+A,h);for(let B=0;B<7;B++)(t[6]>>B&1)===1&&this.setOctaveTuning(B+A,h);p(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${h.join(" ")}`,r.info,r.value);break;default:T(`%cUnrecognized MIDI Tuning standard message: %c${uA(t)}`,r.warn,r.unrecognized);break}break;default:T(`%cUnrecognized MIDI Realtime/non realtime message: %c${uA(t)}`,r.warn,r.unrecognized)}break;case 65:let n=function(){T(`%cUnrecognized Roland %cGS %cSysEx: %c${uA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let s=t[7];if(t[6]===127){s===0?(p("%cGS Reset received!",r.info),this.resetAllControllers(!1),this.system="gs"):s===127&&(p("%cGS system off, switching to GM2",r.info),this.resetAllControllers(!1),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:n();break;case 21:let I=s>0&&t[5]>>4;this.setDrums(o,I),p(`%cChannel %c${o}%c ${I?"is now a drum channel":"now isn't a drum channel"}%c via: %c${uA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=s-64;this.transposeChannel(o,C),p(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${uA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let h=s;h===0&&(h=Math.floor(Math.random()*128)),this.controllerChange(o,m.pan,h);break;case 33:this.controllerChange(o,m.chorusDepth,s);break;case 34:this.controllerChange(o,m.reverbDepth,s);break;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 B=t.length-9,d=new Int8Array(12);for(let l=0;l=this.workletProcessorChannels.length)return;let o=t[6];switch(t[5]){case 1:this.controllerChange(s,m.bankSelect,o);break;case 2:this.controllerChange(s,m.lsbForControl0BankSelect,o);break;case 3:this.programChange(s,o);break;case 8:let I=this.workletProcessorChannels[s];if(I.drumChannel)return;let C=o-64;I.channelTransposeKeyShift=C;break;case 11:this.controllerChange(s,m.mainVolume,o);break;case 14:let h=o;h===0&&(h=Math.floor(Math.random()*127)),this.controllerChange(s,m.pan,h);break;case 19:this.controllerChange(s,m.reverbDepth,o);break;case 18:this.controllerChange(s,m.chorusDepth,o);break;default:T(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&T(`%cUnrecognized Yamaha XG SysEx: %c${uA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&T(`%cUnrecognized Yamaha SysEx: %c${uA(t)}`,r.warn,r.unrecognized);break}}function Cs(t,A,e){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=t[A.sourceIndex];else{let h=A.sourceIndex+EA;switch(A.sourceIndex){case K.noController:n=16383;break;case K.noteOnKeyNum:n=e.midiNote<<7;break;case K.noteOnVelocity:n=e.velocity<<7;break;case K.polyPressure:n=e.pressure<<7;break;default:n=t[h];break}}let s=oe[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let h=A.secSrcIndex+EA;switch(A.secSrcIndex){case K.noController:o=16383;break;case K.noteOnKeyNum:o=e.midiNote<<7;break;case K.noteOnVelocity:o=e.velocity<<7;break;case K.polyPressure:o=e.pressure<<7;break;default:o=t[h]}}let I=oe[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=s*I*A.transformAmount;return A.transformType===2&&(C=Math.abs(C)),A.currentValue=C,C}function XA(t,A,e=-1,n=0){let s=t.modulators,o=t.generators,I=t.modulatedGenerators;if(YA.recalculate(t),e===-1){I.set(o),s.forEach(B=>{let d=U[B.modulatorDestination],c=I[B.modulatorDestination]+Cs(A,B,t);I[B.modulatorDestination]=Math.max(d.min,Math.min(c,d.max))}),LA.recalculate(t);return}let C=new Set([g.initialAttenuation,g.delayVolEnv,g.attackVolEnv,g.holdVolEnv,g.decayVolEnv,g.sustainVolEnv,g.releaseVolEnv,g.keyNumToVolEnvHold,g.keyNumToVolEnvDecay]),h=new Set;s.forEach(B=>{if(B.sourceUsesCC===e&&B.sourceIndex===n||B.secSrcUsesCC===e&&B.secSrcIndex===n){let d=B.modulatorDestination;h.has(d)||(I[d]=o[d],Cs(A,B,t),s.forEach(c=>{if(c.modulatorDestination===d){let l=U[B.modulatorDestination],u=I[B.modulatorDestination]+c.currentValue;I[B.modulatorDestination]=Math.max(l.min,Math.min(u,l.max))}}),h.add(d))}}),[...h].some(B=>C.has(B))&&LA.recalculate(t)}var oe=[];for(let t=0;t<4;t++){oe[t]=[[new Float32Array(BA),new Float32Array(BA)],[new Float32Array(BA),new Float32Array(BA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||I.isMuted)return;let C=A+I.channelTransposeKeyShift,h=C;if(A>127||A<0)return;let B=I.preset.program;this.tunings[B]?.[A]?.midiNote>=0&&(h=this.tunings[B]?.[A].midiNote),I.velocityOverride>0&&(e=I.velocityOverride);let d=this.getWorkletVoices(t,h,e,I,o,C,n),c=I.voices;d.forEach(l=>{let u=l.generators[g.exclusiveClass];u!==0&&c.forEach(b=>{b.generators[g.exclusiveClass]===u&&(this.releaseVoice(b),b.modulatedGenerators[g.releaseVolEnv]=-7e3,b.modulatedGenerators[g.releaseModEnv]=-7e3,LA.recalculate(b),YA.recalculate(b))}),XA(l,I.midiControllers);let y=l.modulatedGenerators[g.startAddrsOffset]+l.modulatedGenerators[g.startAddrsCoarseOffset]*32768,S=l.modulatedGenerators[g.endAddrOffset]+l.modulatedGenerators[g.endAddrsCoarseOffset]*32768,k=l.modulatedGenerators[g.startloopAddrsOffset]+l.modulatedGenerators[g.startloopAddrsCoarseOffset]*32768,w=l.modulatedGenerators[g.endloopAddrsOffset]+l.modulatedGenerators[g.endloopAddrsCoarseOffset]*32768,G=l.sample,x=b=>Math.max(0,Math.min(G.sampleData.length-1,b));if(G.cursor=x(G.cursor+y),G.end=x(G.end+S),G.loopStart=x(G.loopStart+k),G.loopEnd=x(G.loopEnd+w),G.loopEndthis.voiceCap&&this.voiceKilling(d.length),c.push(...d),s&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Bs(t,A){if(A>127||A<0){T("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift;if(this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(s=>{s.realKey!==e||s.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(s):this.releaseVoice(s))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function hs(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.realKey===A&&(e.modulatedGenerators[g.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function Qs(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(n=>{n.isInRelease||this.releaseVoice(n)}),this.workletProcessorChannels[t].sustainedVoices.forEach(n=>{this.releaseVoice(n)}))}function cs(t=!1){p("%cStop all received!",r.info);for(let A=0;AXA(s,this.workletProcessorChannels[t].midiControllers,0,K.pitchWheel)),this.sendChannelProperties()}function Ss(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[EA+K.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(n=>XA(n,e.midiControllers,0,K.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function Ds(t,A,e){this.workletProcessorChannels[t].voices.forEach(n=>{n.midiNote===A&&(n.pressure=e,XA(n,this.workletProcessorChannels[t].midiControllers,0,K.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function ks(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function ws(t,A,e,n=!1){let s=this.workletProcessorChannels[t];if(s===void 0){T(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>127){if(!n)return;switch(A){default:return;case wt.velocityOverride:s.velocityOverride=e}}if(A>=m.lsbForControl1ModulationWheel&&A<=m.lsbForControl13EffectControl2&&A!==m.lsbForControl6DataEntry){let o=A-32;if(s.lockedControllers[o])return;s.midiControllers[o]=s.midiControllers[o]&16256|e&127,s.voices.forEach(I=>XA(I,s.midiControllers,1,o))}switch(A){case m.allNotesOff:this.stopAll(t);break;case m.allSoundOff:this.stopAll(t,!0);break;case m.bankSelect:let o=e;if(!n){switch(this.system){case"gm":p(`%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&&(s.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}s.drumChannel&&(o=128),o===128&&!s.drumChannel&&(o=s.midiControllers[m.bankSelect])}s.midiControllers[m.bankSelect]=o;break;case m.lsbForControl0BankSelect:this.system==="xg"?s.drumChannel||e!==127&&(s.midiControllers[m.bankSelect]=e):this.system==="gm2"&&(s.midiControllers[m.bankSelect]=e);break;case m.RPNLsb:s.RPValue=s.RPValue<<7|e,s.dataEntryState=fA.RPFine;break;case m.RPNMsb:s.RPValue=e,s.dataEntryState=fA.RPCoarse;break;case m.NRPNMsb:s.NRPCoarse=e,s.dataEntryState=fA.NRPCoarse;break;case m.NRPNLsb:s.NRPFine=e,s.dataEntryState=fA.NRPFine;break;case m.dataEntryMsb:this.dataEntryCoarse(t,e);break;case m.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case m.resetAllControllers:this.resetControllers(t);break;case m.sustainPedal:e>=64?s.holdPedal=!0:(s.holdPedal=!1,s.sustainedVoices.forEach(I=>{this.releaseVoice(I)}),s.sustainedVoices=[]);break;default:if(s.lockedControllers[A])return;s.midiControllers[A]=e<<7,s.voices.forEach(I=>XA(I,s.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function Fs(t){this.midiVolume=t,this.setMasterPan(this.pan)}function Rs(t){this.masterGain=t*Ut,this.setMasterPan(this.pan)}function Gs(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function xs(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function Ms(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 Ns(t,A,e,n){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=n,this.workletProcessorChannels[t].channelVibrato.depth=A)}function bs(t,A){let e=this.workletProcessorChannels[t],n=()=>{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 fA.Idle:break;case fA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;T(`%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;T(`%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;n(),e.channelVibrato.rate=A/64*8,p(`%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;n(),e.channelVibrato.depth=A/2,p(`%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;n(),e.channelVibrato.delay=A/64/3,p(`%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 I=A;this.controllerChange(t,m.brightness,A),p(`%cFilter cutoff for %c${t}%c is now set to %c${I}`,r.info,r.recognized,r.info,r.value)}break;case 24:let s=A-64;e.keyCentTuning[e.NRPFine]=s*100,p(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${s}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,m.reverbDepth,o),p(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:T(`%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[EA+K.pitchWheelRange]=A<<7,p(`%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 Ls(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[EA+K.pitchWheelRange]|=A;let n=(e.midiControllers[EA+K.pitchWheelRange]>>7)+A/127;p(`%cChannel ${t} bend range. Semitones: %c${n}`,r.info,r.value);break;case 1:let o=e.customControllers[gA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[gA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function Us(t=!0){t&&p("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A{this.workletProcessorChannels[A].lockedControllers[s]&&this.callEvent("controllerchange",{channel:A,controllerNumber:s,controllerValue:this.workletProcessorChannels[A].midiControllers[s]>>7})};if(n(m.mainVolume),n(m.pan),n(m.expressionController),n(m.modulationWheel),n(m.chorusDepth),n(m.reverbDepth),n(m.brightness),this.workletProcessorChannels[A].lockedControllers[EA+K.pitchWheel]){let s=this.workletProcessorChannels[A].midiControllers[EA+K.pitchWheel],o=s>>7,I=s&127;this.callEvent("pitchwheel",{channel:A,MSB:o,LSB:I})}}this.tunings=[],this.tunings=[];for(let A=0;127>A;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Oe}function Ts(t){let A=this.workletProcessorChannels[t],n=A.lockedControllers.reduce((o,I,C)=>(I&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(St),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,n.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let s=A.customControllers[gA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[gA.channelTransposeFine]=s,this.resetParameters(t)}function Hs(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=fA.Idle}function Ys(){let t=4;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==g.sampleID&&I.generatorType!==g.keyRange&&I.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+s),0);let A=new Y(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.generatorZoneStartIndex=e;for(let o of s.generators)J(A,o.generatorType),J(A,o.generatorValue),e++}return lA(A,0),nA(new AA("igen",A.length,A))}function Js(t,A,e,n,s){let o=this.samples.map((B,d)=>{e&&B.compressSample(n,s);let c=B.getRawData();return p(`%cEncoded sample %c${d}. ${B.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),c}),I=this.samples.reduce((B,d,c)=>B+o[c].length+46,0),C=new Y(I);this.samples.forEach((B,d)=>{let c=o[d],l,u,y=c.length;B.isCompressed?(l=C.currentIndex,u=l+c.length):(l=C.currentIndex/2,u=l+c.length/2,y+=46),t.push(l),C.set(c,C.currentIndex),C.currentIndex+=y,A.push(u)});let h=nA(new AA("smpl",C.length,C),new Y([115,100,116,97]));return nA(new AA("LIST",h.length,h))}function vs(t,A){let n=new Y(46*(this.samples.length+1));return this.samples.forEach((s,o)=>{FA(n,s.sampleName,20);let I=t[o];lA(n,I);let C=A[o];lA(n,C);let h=s.sampleLoopStartIndex+I,B=s.sampleLoopEndIndex+I;s.isCompressed&&(h-=I,B-=I),lA(n,h),lA(n,B),lA(n,s.sampleRate),n[n.currentIndex++]=s.samplePitch,n[n.currentIndex++]=s.samplePitchCorrection,J(n,s.sampleLink),J(n,s.sampleType)}),FA(n,"EOS",46),nA(new AA("shdr",n.length,n))}function qs(){let t=10;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new Y(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)J(A,o.sourceEnum),J(A,o.modulatorDestination),J(A,o.transformAmount),J(A,o.secondarySourceEnum),J(A,o.transformType),e++}return Ee(A,0,10),nA(new AA("imod",A.length,A))}function Ps(){let t=this.instruments.reduce((o,I)=>I.instrumentZones.length*4+o,4),A=new Y(t),e=0,n=0,s=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let I of o.instrumentZones)I.zoneID=e,J(A,n),J(A,s),n+=I.generators.length,s+=I.modulators.length,e++}return J(A,n),J(A,s),nA(new AA("ibag",A.length,A))}function Ks(){let t=this.instruments.length*22+22,A=new Y(t),e=0,n=0;for(let s of this.instruments)FA(A,s.instrumentName,20),J(A,e),e+=s.instrumentZones.length,s.instrumentID=n,n++;return FA(A,"EOI",20),J(A,e),nA(new AA("inst",A.length,A))}function Vs(){let t=4;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==g.instrument&&I.generatorType!==g.keyRange&&I.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+s),0);let A=new Y(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.generatorZoneStartIndex=e;for(let o of s.generators)J(A,o.generatorType),J(A,o.generatorValue);e+=s.generators.length}return J(A,0),J(A,0),nA(new AA("pgen",A.length,A))}function Os(){let t=10;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new Y(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)J(A,o.sourceEnum),J(A,o.modulatorDestination),J(A,o.transformAmount),J(A,o.secondarySourceEnum),J(A,o.transformType),e++}return Ee(A,0,10),nA(new AA("pmod",A.length,A))}function Zs(){let t=this.presets.reduce((o,I)=>I.presetZones.length*4+o,4),A=new Y(t),e=0,n=0,s=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let I of o.presetZones)I.zoneID=e,J(A,n),J(A,s),n+=I.generators.length,s+=I.modulators.length,e++}return J(A,n),J(A,s),nA(new AA("pbag",A.length,A))}function Xs(){let t=this.presets.length*38+38,A=new Y(t),e=0;for(let n of this.presets)FA(A,n.presetName,20),J(A,n.program),J(A,n.bank),J(A,e),lA(A,n.library),lA(A,n.genre),lA(A,n.morphology),e+=n.presetZones.length;return FA(A,"EOP",20),J(A,0),J(A,0),J(A,e),lA(A,0),lA(A,0),lA(A,0),nA(new AA("phdr",A.length,A))}var Jo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Ws(t=Jo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");yA("%cSaving soundfont...",r.info),p(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),p("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[b,$]of Object.entries(this.soundFontInfo))if(b==="ifil"||b==="iver"){let i=parseInt($.split(".")[0]),sA=parseInt($.split(".")[1]),_=new Y(4);J(_,i),J(_,sA),A.push(nA(new AA(b,4,_)))}else if(b==="DMOD")A.push(nA(new AA(b,$.length,$)));else{let i=new Y($.length);FA(i,$),A.push(nA(new AA(b,$.length,i)))}let e=ke([new Y([73,78,70,79]),...A]),n=nA(new AA("LIST",e.length,e));p("%cWriting SDTA...",r.info);let s=[],o=[],I=Js.call(this,s,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);p("%cWriting PDTA...",r.info),p("%cWriting SHDR...",r.info);let C=vs.call(this,s,o);p("%cWriting IGEN...",r.info);let h=Ys.call(this);p("%cWriting IMOD...",r.info);let B=qs.call(this);p("%cWriting IBAG...",r.info);let d=Ps.call(this);p("%cWriting INST...",r.info);let c=Ks.call(this),l=Vs.call(this);p("%cWriting PMOD...",r.info);let u=Os.call(this);p("%cWriting PBAG...",r.info);let y=Zs.call(this);p("%cWriting PHDR...",r.info);let S=Xs.call(this),k=ke([new Y([112,100,116,97]),S,y,u,l,c,d,B,h,C]),w=nA(new AA("LIST",k.length,k));p("%cWriting the output file...",r.info);let G=ke([new Y([115,102,98,107]),n,I,w]),x=nA(new AA("RIFF",G.length,G));return p(`%cSaved succesfully! Final file size: %c${x.length}`,r.info,r.recognized),Z(),x}var re=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Pe.map(e=>j.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}static mergeSoundfonts(...A){let e=A.shift(),n=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(I=>I.bank===o.bank&&I.program===o.program)===void 0&&n.push(o)});return new t({presets:n,info:e.soundFontInfo})}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()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPresetNoFallback(A,e,n=!1){let s=this.presets.find(o=>o.bank===A&&o.program===e);if(s)return s;if(n!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}getPreset(A,e){let n=this.presets.find(s=>s.bank===A&&s.program===e);return n||(A===128?(n=this.presets.find(s=>s.bank===128&&s.program===e),n||(n=this.presets.find(s=>s.bank===128))):n=this.presets.find(s=>s.program===e&&s.bank!==128),n&&T(`%cPreset ${A}.${e} not found. Replaced with %c${n.presetName} (${n.bank}.${n.program})`,r.warn,r.recognized)),n||(T(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),n=this.presets[0]),n}getPresetByName(A){let e=this.presets.find(n=>n.presetName===A);return e||(T("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}};re.prototype.write=Ws;function _s(t){yA("%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 n=A;n{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}getSamplesAndGenerators(A,e){let n=this.foundSamplesAndGenerators[A][e];if(n)return n;if(this.presetZones.length<1)return[];function s(c,l,u){return u>=c&&u<=l}function o(c,l){c.push(...l.filter(u=>!c.find(y=>y.generatorType===u.generatorType)))}function I(c,l){c.push(...l.filter(u=>!c.find(y=>j.isIdentical(u,y))))}let C=[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],B=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(c=>s(c.keyRange.min,c.keyRange.max,A)&&s(c.velRange.min,c.velRange.max,e)&&!c.isGlobal).forEach(c=>{if(c.instrument.instrumentZones.length<1)return;let l=c.generators,u=c.modulators,y=c.instrument.instrumentZones[0].isGlobal?[...c.instrument.instrumentZones[0].generators]:[],S=c.instrument.instrumentZones[0].isGlobal?[...c.instrument.instrumentZones[0].modulators]:[];c.instrument.instrumentZones.filter(w=>s(w.keyRange.min,w.keyRange.max,A)&&s(w.velRange.min,w.velRange.max,e)&&!w.isGlobal).forEach(w=>{let G=[...w.generators],x=[...w.modulators];o(l,h),o(G,y),I(u,B),I(x,S),I(x,this.defaultModulators);let b=[...x];for(let $=0;$j.isIdentical(i,_));sA!==-1?b[sA]=b[sA].sumTransform(i):b.push(i)}C.push({instrumentGenerators:G,presetGenerators:l,modulators:b,sample:w.sample,sampleID:w.generators.find($=>$.generatorType===g.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=C,C}};var Re=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var $A=class extends Re{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},le=class extends Re{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var ue=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}get useCount(){return this._useCount}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 ce{constructor(A,e){super(Pe),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new ue,this.DLSInstrument.addUseCount();let s=new le;s.instrument=this.DLSInstrument,this.presetZones=[s]}};function zs(t){this.verifyHeader(t,"LIST"),this.verifyText(V(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(u=>u.header==="insh");if(!e)throw Z(),new Error("No instrument header!");let n=D(e.chunkData,4),s=D(e.chunkData,4),o=D(e.chunkData,4),I=new At(s,o),C="unnamedPreset",h=DA(A,"INFO");if(h){let u=O(h.chunkData);for(;u.header!=="INAM";)u=O(h.chunkData);C=V(u.chunkData,u.chunkData.length).trim()}I.presetName=C,I.DLSInstrument.instrumentName=C,te(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let B=DA(A,"lrgn");if(!B)throw Z(),new Error("No region list!");let d=new $A;d.isGlobal=!0;let c=DA(A,"lart"),l=DA(A,"lar2");this.readLart(c,l,d),I.DLSInstrument.instrumentZones.push(d);for(let u=0;u>10&15;w===cA.linear&&k!==cA.linear&&(w=k);let G=n>>14&1,x=n>>15&1;I===g.initialAttenuation&&(x=!x),c=TA(w,G,x,C.isCC,C.enum)}let l=n>>4&15,u=n>>8&1,y=n>>9&1,S=TA(l,u,y,d.isCC,d.enum);if(h){let k=S;S=c,c=k}return new j({srcEnum:c,secSrcEnum:S,dest:I,transform:0,amt:s})}function Tt(t,A){let e=t.chunkData,n=[],s=[];D(e,4);let o=D(e,4);for(let I=0;I>16;if(C===0&&h===0&&d===0){let u;switch(B){case M.pan:u=new L(g.pan,l);break;case M.gain:u=new L(g.initialAttenuation,-l*10/.4);break;case M.filterCutoff:u=new L(g.initialFilterFc,l);break;case M.filterQ:u=new L(g.initialFilterQ,l);break;case M.modLfoFreq:u=new L(g.freqModLFO,l);break;case M.modLfoDelay:u=new L(g.delayModLFO,l);break;case M.vibLfoFreq:u=new L(g.freqVibLFO,l);break;case M.vibLfoDelay:u=new L(g.delayVibLFO,l);break;case M.volEnvDelay:u=new L(g.delayVolEnv,l);break;case M.volEnvAttack:u=new L(g.attackVolEnv,l);break;case M.volEnvHold:u=new L(g.holdVolEnv,l);break;case M.volEnvDecay:u=new L(g.decayVolEnv,l);break;case M.volEnvRelease:u=new L(g.releaseVolEnv,l);break;case M.volEnvSustain:let y=(1e3-l)/10;u=new L(g.sustainVolEnv,y*10);break;case M.modEnvDelay:u=new L(g.delayModEnv,l);break;case M.modEnvAttack:u=new L(g.attackModEnv,l);break;case M.modEnvHold:u=new L(g.holdModEnv,l);break;case M.modEnvDecay:u=new L(g.decayModEnv,l);break;case M.modEnvRelease:u=new L(g.releaseModEnv,l);break;case M.modEnvSustain:let S=1e3-l;u=new L(g.sustainModEnv,S);break;case M.reverbSend:u=new L(g.reverbEffectsSend,l);break;case M.chorusSend:u=new L(g.chorusEffectsSend,l);break;case M.pitch:let k=Math.floor(l/100),w=Math.floor(l-k*100);u=new L(g.fineTune,w),n.push(new L(g.coarseTune,k));break}u&&n.push(u)}else{let u=!0;if(h===W.none)if(C===W.modLfo&&B===M.pitch)n.push(new L(g.modLfoToPitch,l));else if(C===W.modLfo&&B===M.gain)n.push(new L(g.modLfoToVolume,l));else if(C===W.modLfo&&B===M.filterCutoff)n.push(new L(g.modLfoToFilterFc,l));else if(C===W.vibratoLfo&&B===M.pitch)n.push(new L(g.vibLfoToPitch,l));else if(C===W.modEnv&&B===M.pitch)n.push(new L(g.modEnvToPitch,l));else if(C===W.modEnv&&B===M.filterCutoff)n.push(new L(g.modEnvToFilterFc,l));else if(C===W.keyNum&&B===M.volEnvHold){n.push(new L(g.keyNumToVolEnvHold,l/-128));let y=Math.round(60/128*l);n.forEach(S=>{S.generatorType===g.holdVolEnv&&(S.generatorValue+=y)})}else if(C===W.keyNum&&B===M.volEnvDecay){n.push(new L(g.keyNumToVolEnvDecay,l/-128));let y=Math.round(60/128*l);n.forEach(S=>{S.generatorType===g.decayVolEnv&&(S.generatorValue+=y)})}else if(C===W.keyNum&&B===M.modEnvHold){n.push(new L(g.keyNumToModEnvHold,l/-128));let y=Math.round(60/128*l);n.forEach(S=>{S.generatorType===g.holdModEnv&&(S.generatorValue+=y)})}else if(C===W.keyNum&&B===M.modEnvDecay){n.push(new L(g.keyNumToModEnvDecay,l/-128));let y=Math.round(60/128*l);n.forEach(S=>{S.generatorType===g.decayModEnv&&(S.generatorValue+=y)})}else u=!1;else u=!1;if(u===!1){let y=$s(C,h,B,d,l);y?(s.push(y),p("%cSucceeded converting to SF2 Modulator!",r.recognized)):T("Failed converting to SF2 Modulator!")}}}return s.find(I=>I.modulatorDestination===g.reverbEffectsSend)===void 0&&s.push(new j({srcEnum:219,dest:g.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),s.find(I=>I.modulatorDestination===g.chorusEffectsSend)===void 0&&s.push(new j({srcEnum:221,dest:g.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&s.push(new j({srcEnum:129,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new j({srcEnum:13,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:s,generators:n}}function Ao(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(_=>_.header==="rgnh"),n=D(e.chunkData,2),s=D(e.chunkData,2),o=D(e.chunkData,2),I=D(e.chunkData,2),C=new et({min:n,max:s},{min:o,max:I});D(e.chunkData,2);let h=D(e.chunkData,2);h!==0&&C.generators.push(new L(g.exclusiveClass,h));let B=DA(A,"lart"),d=DA(A,"lar2");this.readLart(B,d,C),C.isGlobal=!1;let c=A.find(_=>_.header==="wsmp");D(c.chunkData,4);let l=D(c.chunkData,2),u=jA(c.chunkData[c.chunkData.currentIndex++],c.chunkData[c.chunkData.currentIndex++]),S=(D(c.chunkData,4)|0)/-655360;D(c.chunkData,4);let k=D(c.chunkData,4),w,G={start:0,end:0};if(k===0)w=0;else{D(c.chunkData,4),D(c.chunkData,4)===0?w=1:w=3,G.start=D(c.chunkData,4);let v=D(c.chunkData,4);G.end=G.start+v}let x=A.find(_=>_.header==="wlnk");if(x===void 0)return;D(x.chunkData,2),D(x.chunkData,2),D(x.chunkData,4);let b=D(x.chunkData,4),$=this.samples[b];if($===void 0)throw new Error("Invalid sample ID!");let sA=(S||$.sampleDbAttenuation)*10/.4;return C.setWavesample(sA,w,G,l,$,b,u),C}var de=class{constructor(A,e,n,s,o,I,C,h){this.sampleName=A,this.sampleRate=e,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=I,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=h,this.isCompressed=(I&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{T(`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 de{sampleDbAttenuation;sampleData;constructor(A,e,n,s,o,I,C,h){super(A,e,n,s,0,1,o,I-1),this.sampleData=C,this.sampleDbAttenuation=h}getAudioData(){return this.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 to(t){yA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexv.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");if(D(s.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(D(s.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=D(s.chunkData,4);D(s.chunkData,4),D(s.chunkData,2);let h=D(s.chunkData,2),B=h/8,d=Math.pow(2,B*8-1),c=Math.pow(2,B*8),l,u=!1;h===8?(l=255,u=!0):l=d;let y=n.find(v=>v.header==="data");if(!y)throw new Error("No data chunk in the wave chunk!");let S=y.size/B,k=new Float32Array(S);for(let v=0;v=d&&(z-=c),k[v]=z/l)}let w=60,G=0,x=0,b=k.length-1,$=0,i=n.find(v=>v.header==="wsmp");if(i){if(D(i.chunkData,4),w=D(i.chunkData,2),G=jA(i.chunkData[i.chunkData.currentIndex++],i.chunkData[i.chunkData.currentIndex++]),$=(D(i.chunkData,4)|0)/-655360,D(i.chunkData,4),D(i.chunkData,4)===1){D(i.chunkData,8),x=D(i.chunkData,4);let oA=D(i.chunkData,4);b=x+oA}}else T("No wsmp chunk in wave... using sane defaults.");let sA=DA(n,"INFO"),_=`Unnamed ${A}`;if(sA){let v=O(sA.chunkData);for(;v.header!=="INAM"&&sA.chunkData.currentIndex(w.messageStatusByte&240)===F.noteOn);k&&u.push(k.ticks)}this.firstNoteOn=Math.min(...u),p(`%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},p(`%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?p("%cNo additional MIDI Ports detected.",r.info):p("%cMIDI Ports detected!",r.recognized),!I)if(this.tracks.length>1){if(this.tracks[0].find(y=>y.messageStatusByte>=F.noteOn&&y.messageStatusBytek.messageStatusByte===F.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=V(y.messageData,y.messageData.length,void 0,!1))}}else{let y=this.tracks[0].find(k=>k.messageStatusByte===F.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=V(y.messageData,y.messageData.length,void 0,!1))}if(this.fileName=e,this.midiName=this.midiName.trim(),this.midiName.length===0){p("%cNo name detected. Using the alt name!",r.info),this.midiName=hn(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let y=0;yl>c?l:c),n=[];for(let c=0;c{I[D]>=u.length||u[I[D]].ticks0;){let c=h(),l=t.tracks[c];if(I[c]>=l.length){C--;continue}let u=l[I[c]];if(I[c]++,u.messageStatusByte===F.midiPort){B[c]=u.messageData[0];continue}let D=u.messageStatusByte&240;if(D!==F.noteOn&&D!==F.controllerChange&&D!==F.programChange&&D!==F.systemExclusive)continue;let y=(u.messageStatusByte&15)+t.midiPortChannelOffsets[B[c]]||0,k=n[y];switch(D){case F.programChange:k.program=u.messageData[0],s(k);break;case F.controllerChange:if(u.messageData[0]!==m.bankSelect||d==="gs"&&k.drums)continue;let w=u.messageData[1],G=Math.max(0,w-t.bankOffset);if(d==="xg"){let $=w===120||w===126||w===127;$!==k.drums?(k.drums=$,k.bank=k.drums?128:G,s(k)):k.bank=k.drums?128:G;continue}n[y].bank=G;break;case F.noteOn:if(u.messageData[1]===0)continue;s(k),o[k.string].add(`${u.messageData[0]}-${u.messageData[1]}`);break;case F.systemExclusive:if(u.messageData[0]!==65||u.messageData[2]!==66||u.messageData[3]!==18||u.messageData[4]!==64||!(u.messageData[5]&16)||u.messageData[6]!==21){u.messageData[0]===67&&u.messageData[2]===76&&u.messageData[5]===126&&u.messageData[6]===0&&(d="xg");continue}let x=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+t.midiPortChannelOffsets[B[c]],b=!!(u.messageData[7]>0&&u.messageData[5]>>4);k=n[x],k.drums=b,k.bank=b?128:0,s(k);break}}for(let c of Object.keys(o))o[c].size===0&&(p(`%cDetected change but no keys for %c${c}`,r.info,r.value),delete o[c]);return Z(),o}function Mn(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=Be(this.midiData.firstNoteOn,this.midiData),p(`%cTotal song time: ${mt(Math.ceil(this.duration)).time}`,r.recognized),this.post(wA.songChange,[new Ze(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(T(`%cVery short song: (${mt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function bn(t){this.songs=t.reduce((A,e)=>{if(e.duration)return A.push(e),A;try{A.push(new ze(e.binary,e.altName||""))}catch(n){return this.post(wA.midiError,n.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 Ln(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Un(){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[m.mainVolume]=100;PA[m.expressionController]=127;PA[m.pan]=64;PA[m.releaseTime]=64;PA[m.brightness]=64;PA[m.reverbDepth]=0;function Tn(t,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let e=this.synth.workletProcessorChannels.length,n=Array(e).fill(8192),s=[];for(let C=0;CC===m.dataDecrement||C===m.dataIncrement||C===m.dataEntryMsb||C===m.dataDecrement||C===m.lsbForControl6DataEntry||C===m.RPNLsb||C===m.RPNMsb||C===m.NRPNLsb||C===m.NRPNMsb||C===m.bankSelect||C===m.lsbForControl0BankSelect||C===m.resetAllControllers,I=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let B=we(h.messageStatusByte),d=B.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(B.status){case F.noteOn:case F.noteOff:case F.keySignature:break;case F.pitchBend:n[d]=h.messageData[1]<<7|h.messageData[0];break;case F.programChange:let l=s[d];l.program=h.messageData[0],l.actualBank=l.bank;break;case F.controllerChange:let u=h.messageData[0];if(o(u)){let D=h.messageData[1];if(u===m.bankSelect){s[d].bank=D;break}this.sendMIDIMessages?this.sendMIDICC(d,u,D):this.synth.controllerChange(d,u,D)}else I[d]===void 0&&(I[d]=Array.from(PA)),I[d][u]=h.messageData[1];break;default:this._processEvent(h,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-h.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7,n[C]&127),I[C]!==void 0&&I[C].forEach((h,B)=>{h!==PA[B]&&!o(B)&&this.sendMIDICC(C,B,h)}),s[C].program>=0&&s[C].actualBank>=0){let h=s[C].actualBank;this.sendMIDICC(C,m.bankSelect,h),this.sendMIDIProgramChange(C,s[C].program)}}else for(let C=0;C>7,n[C]&127),I[C]!==void 0&&I[C].forEach((h,B)=>{h!==PA[B]&&!o(B)&&this.synth.controllerChange(C,B,h)}),s[C].program>=0&&s[C].actualBank>=0){let h=s[C].actualBank;this.synth.controllerChange(C,m.bankSelect,h),this.synth.programChange(C,s[C].program)}return!0}function Hn(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 Yn(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(wA.timeChange,currentTime-Be(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Jn(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function vn(t,A){switch(t){default:break;case bA.loadNewSongList:this.loadNewSongList(A);break;case bA.pause:this.pause();break;case bA.play:this.play(A);break;case bA.stop:this.stop();break;case bA.setTime:this.currentTime=A;break;case bA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case bA.setPlaybackRate:this.playbackRate=A;break;case bA.setLoop:this.loop=A;break;case bA.changeSong:A?this.nextSong():this.previousSong();break;case bA.getMIDI:this.post(wA.getMIDI,this.midiData);break;case bA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function qn(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:pA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Pn(t){this.post(wA.midiEvent,t)}function Kn(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|t,A,e])}function Vn(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|t,A])}function On(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|t,e,A])}function Zn(){if(this.sendMIDIMessages){this.sendMIDIMessage([F.reset]);for(let t=0;tthis.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&AXn?440*Math.pow(2,(t-6900)/1200):Rt[~~t-je]}var xt=-1660,Lo=1600,Gt=new Float32Array((Lo-xt)*100+1);for(let t=0;t.5?1:0,n?e*2-1:e;case cA.concave:return n?(e=e*2-1,e<0?-ZA[~~(e*-BA)]:ZA[~~(e*BA)]):ZA[~~(e*BA)];case cA.convex:return n?(e=e*2-1,e<0?-ne[~~(e*-BA)]:ne[~~(e*BA)]):ne[~~(e*BA)]}}var Mt=1,Nt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)n-=o;let C=~~n,h=C+1;for(;h>=e.loopEnd;)h-=o;let B=n-C,d=s[h],c=s[C];A[I]=c+(d-c)*B,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end){t.finished=!0;return}let h=n-I,B=s[C],d=s[I];A[o]=d+(B-d)*h,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function _n(t,A){let e=t.sample,n=e.cursor,s=e.loopEnd-e.loopStart,o=e.sampleData;if(t.sample.isLooping)for(let I=0;I=e.loopEnd;)n-=s;let C=~~n+1;for(;C>=e.loopEnd;)C-=s;A[I]=o[C],n+=e.playbackStep*t.currentTuningCalculated}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let I=0;I=e.end){t.finished=!0;return}A[I]=o[C],n+=e.playbackStep*t.currentTuningCalculated}}e.cursor=n}function zn(t,A){let e=t.sample,n=e.cursor,s=e.sampleData;if(e.isLooping){let o=e.loopEnd-e.loopStart;for(let I=0;I=e.loopEnd;)n-=o;let C=~~n,h=C+1,B=h+1,d=B+1,c=n-C;h>=e.loopEnd&&(h-=o),B>=e.loopEnd&&(B-=o),d>=e.loopEnd&&(d-=o);let l=s[C],u=s[h],D=s[B],y=s[d],k=.5*(D-l),w=l-2.5*u+2*D-.5*y,G=.5*(y-l)+1.5*(u-D);A[I]=((G*c+w)*c+k)*c+u,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end||h>=e.end||B>=e.end){t.finished=!0;return}let c=s[I],l=s[C],u=s[h],D=s[B],y=.5*(u-c),k=c-2.5*l+2*u-.5*D,w=.5*(D-c)+1.5*(l-u);A[o]=((w*d+k)*d+y)*d+l,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function jn(t,A,e,n,s,o,I,C,h){if(!isNaN(e[0])){if(I>0){let B=o[0],d=o[1];I=Math.min(I,1e3);let c=I/1300;for(let l=0;l0){let B=C[0],d=C[1];h=Math.min(h,1e3);let c=h/1300,l=t*c,u=A*c;for(let D=0;D0)for(let B=0;B0)for(let B=0;B13499&&A.filter.reasonanceCb===0)return;let o=A.filter;(o.cutoffCents!==n||o.reasonanceCb!==A.modulatedGenerators[g.initialFilterQ])&&(o.cutoffCents=n,o.reasonanceCb=A.modulatedGenerators[g.initialFilterQ],t.calculateCoefficients(o));for(let I=0;I=bt}static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=KA(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static recalculate(A){let e=A.volumeEnvelope,n=B=>Math.max(0,Math.floor(HA(B)*e.sampleRate));e.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[g.initialAttenuation],1440))/10,e.sustainDbRelative=Math.min(JA,A.modulatedGenerators[g.sustainVolEnv]/10);let s=Math.min(JA,e.sustainDbRelative);e.attackDuration=n(A.modulatedGenerators[g.attackVolEnv]);let o=A.modulatedGenerators[g.decayVolEnv],I=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvDecay],C=s/JA;e.decayDuration=n(o+I)*C,e.releaseDuration=n(A.modulatedGenerators[g.releaseVolEnv]),e.delayEnd=n(A.modulatedGenerators[g.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let h=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvHold];if(e.holdEnd=n(A.modulatedGenerators[g.holdVolEnv]+h)+e.attackEnd,e.decayEnd=e.decayDuration+e.holdEnd,e.state===0&&e.attackEnd===0&&(e.state=2),A.isInRelease){let B=Math.max(0,Math.min(JA,e.sustainDbRelative)),d=B/JA;switch(e.decayDuration=n(o+I)*d,e.state){case 0:e.releaseStartDb=JA;break;case 1:let c=1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration;e.releaseStartDb=20*Math.log10(c)*-1;break;case 2:e.releaseStartDb=0;break;case 3:e.releaseStartDb=(1-(e.decayEnd-e.releaseStartTimeSamples)/e.decayDuration)*B;break;case 4:e.releaseStartDb=B;break}e.releaseStartDb=Math.max(0,Math.min(e.releaseStartDb,JA)),e.releaseStartDb>=bt&&(A.finished=!0),e.currentReleaseGain=KA(e.releaseStartDb)}}static apply(A,e,n,s){let o=A.volumeEnvelope,I=n/10,C=s;if(A.isInRelease){let B=o.currentSampleTime-o.releaseStartTimeSamples;if(B>=o.releaseDuration){for(let c=0;c=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>=bt&&(A.finished=!0);;)if(o.attenuation+=(o.attenuationTarget-o.attenuation)*C,e[h]*=KA(o.sustainDbRelative+I+o.attenuation),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++h>=e.length)return}}};var As=Math.PI/2,es=.05;function ts(t,A,e,n,s,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,LA.startRelease(A),YA.startRelease(A),A.sample.loopingMode===3&&(A.sample.isLooping=!1)),A.modulatedGenerators[g.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let I=A.targetKey,C=A.modulatedGenerators[g.fineTune]+t.customControllers[gA.channelTuning]+t.customControllers[gA.channelTransposeFine]+t.customControllers[gA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],h=A.modulatedGenerators[g.coarseTune]+t.customControllers[gA.channelTuningSemitones],B=this.tunings[t.preset.program]?.[A.realKey];B?.midiNote>=0&&(I=B.midiNote,C+=B.centTuning),C+=(I-A.sample.rootKey)*A.modulatedGenerators[g.scaleTuning];let d=A.modulatedGenerators[g.vibLfoToPitch];if(d!==0){let oA=A.startTime+HA(A.modulatedGenerators[g.delayVibLFO]),rA=Fe(A.modulatedGenerators[g.freqVibLFO]),CA=$e(oA,rA,currentTime);C+=CA*(d*t.customControllers[gA.modulationMultiplier])}let c=A.modulatedGenerators[g.initialFilterFc],l=c,u=A.modulatedGenerators[g.modLfoToPitch],D=A.modulatedGenerators[g.modLfoToVolume],y=A.modulatedGenerators[g.modLfoToFilterFc],k=0;if(u+y+D!==0){let oA=A.startTime+HA(A.modulatedGenerators[g.delayModLFO]),rA=Fe(A.modulatedGenerators[g.freqModLFO]),CA=$e(oA,rA,currentTime);C+=CA*(u*t.customControllers[gA.modulationMultiplier]),k=-CA*D,l+=CA*y}if(t.channelVibrato.depth>0){let oA=$e(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);oA&&(C+=oA*t.channelVibrato.depth)}let w=A.modulatedGenerators[g.modEnvToPitch],G=A.modulatedGenerators[g.modEnvToFilterFc],x=YA.getValue(A,currentTime);l+=x*G,C+=x*w;let b=~~(C+h*100);b!==A.currentTuningCents&&(A.currentTuningCents=b,A.currentTuningCalculated=Math.pow(2,b/1200));let $=(Math.max(-500,Math.min(500,A.modulatedGenerators[g.pan]))+500)/1e3,i=new Float32Array(e.length);switch(this.interpolationType){case he.linear:default:Wn(A,i);break;case he.nearestNeighbor:_n(A,i);break;case he.fourthOrder:zn(A,i)}Qe.apply(A,i,l,c>13499),LA.apply(A,i,k,this.volumeEnvelopeSmoothingFactor),A.currentPan+=($-A.currentPan)*this.panSmoothingFactor;let sA=Math.cos(As*A.currentPan)*this.panLeft,_=Math.sin(As*A.currentPan)*this.panRight,v=this.oneOutputMode?0:A.modulatedGenerators[g.reverbEffectsSend],z=this.oneOutputMode?0:A.modulatedGenerators[g.chorusEffectsSend];jn(sA,_,i,e,n,s,v,o,z)}function To(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 ns(t){let A=[];for(let n of this.workletProcessorChannels)for(let s of n.voices)if(!s.finished){let o=To(n,s);A.push({channel:n,voice:s,priority:o})}A.sort((n,s)=>n.priority-s.priority);let e=A.slice(0,t);for(let{channel:n,voice:s}of e){let o=n.voices.indexOf(s);o>-1&&n.voices.splice(o,1)}}function ss(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimers=t);var Ho=function(t){var A,e,n,s,o,I,C,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",B="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do s=h.indexOf(t.charAt(d++)),o=h.indexOf(t.charAt(d++)),I=h.indexOf(t.charAt(d++)),C=h.indexOf(t.charAt(d++)),A=s<<2|o>>4,e=(15&o)<<4|I>>2,n=(3&I)<<6|C,B+=String.fromCharCode(A),I!==64&&(B+=String.fromCharCode(e)),C!==64&&(B+=String.fromCharCode(n));while(d1&&(i.thisProgram=process.argv[1].replace(/\\/g,"/")),i.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(a){if(!(a instanceof ye))throw a}),process.on("unhandledRejection",function(a,E){process.exit(1)}),i.quit=function(a){process.exit(a)},i.inspect=function(){return"[Emscripten Module object]"}):oA?(typeof read<"u"&&(i.read=function(E){return read(E)}),i.readBinary=function(E){var Q;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(Q=read(E,"binary"))=="object"),Q)},typeof scriptArgs<"u"?i.arguments=scriptArgs:typeof arguments<"u"&&(i.arguments=arguments),typeof quit=="function"&&(i.quit=function(a){quit(a)})):(_||v)&&(_?document.currentScript&&(rA=document.currentScript.src):rA=self.location.href,rA=rA.indexOf("blob:")!==0?rA.split("/").slice(0,-1).join("/")+"/":"",i.read=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.send(null),Q.responseText},v&&(i.readBinary=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.responseType="arraybuffer",Q.send(null),new Uint8Array(Q.response)}),i.readAsync=function(E,Q,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){Q(R.response);return}f()},R.onerror=f,R.send(null)},i.setWindowTitle=function(a){document.title=a});var Me=i.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),RA=i.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Me);for(t in sA)sA.hasOwnProperty(t)&&(i[t]=sA[t]);function Ne(a){var E=u;return u=u+a+15&-16,E}function Ot(a){var E=h[x>>2],Q=E+a+15&-16;return h[x>>2]=Q,Q>=hA&&!tn()?(h[x>>2]=E,0):E}function Zt(a,E){return E||(E=16),a=Math.ceil(a/E)*E}function fo(a){switch(a){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(a[a.length-1]==="*")return 4;if(a[0]!=="i")return 0;var E=parseInt(a.substr(1));return _A(E%8==0),E/8}}function fe(a){fe.shown||(fe.shown={}),fe.shown[a]||(fe.shown[a]=1,RA(a))}sA=void 0;var mo={"f64-rem":function(a,E){return a%E},debugger:function(){}},it=[];function Ko(a,E){for(var Q=0,f=Q;f>>0)+4294967296*+(E>>>0):+(a>>>0)+4294967296*+(0|E)}function It(a,E,Q){return Q&&Q.length?i["dynCall_"+a].apply(null,[E].concat(Q)):i["dynCall_"+a].call(null,E)}var be=0,Xt=0;function _A(a,E){a||OA("Assertion failed: "+E)}function Wt(a){var E=i["_"+a];return _A(E,"Cannot call unknown function "+a+", make sure it is exported"),E}var _t={stackSave:function(){lt()},stackRestore:function(){ct()},arrayToC:function(a){var E,Q,f=Je(a.length);return E=a,Q=f,s.set(E,Q),f},stringToC:function(a){var E=0;if(a!=null&&a!==0){var Q=(a.length<<2)+1;E=Je(Q),$t(a,E,Q)}return E}},po={string:_t.stringToC,array:_t.arrayToC};function zt(a,E,Q,f,R){var P=Wt(a),X=[],N=0;if(f)for(var QA=0;QA>0]=E;break;case"i16":I[a>>1]=E;break;case"i32":h[a>>2]=E;break;case"i64":tempI64=[E>>>0,+Fo(tempDouble=E)>=1?tempDouble>0?(0|Go(+an(tempDouble/4294967296),4294967295))>>>0:~~+Ro((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],h[a>>2]=tempI64[0],h[a+4>>2]=tempI64[1];break;case"float":d[a>>2]=E;break;case"double":c[a>>3]=E;break;default:OA("invalid type for setValue: "+Q)}}function Xo(a,E,Q){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return s[a>>0];case"i16":return I[a>>1];case"i32":case"i64":return h[a>>2];case"float":return d[a>>2];case"double":return c[a>>3];default:OA("invalid type for getValue: "+E)}return null}function Wo(a,E,Q,f){typeof a=="number"?(P=!0,X=a):(P=!1,X=a.length);var R=typeof E=="string"?E:null;if(N=Q==4?f:[typeof Ye=="function"?Ye:Ne,Je,Ne,Ot][Q===void 0?2:Q](Math.max(X,R?1:E.length)),P){for(f=N,_A((3&N)==0),QA=N+(-4&X);f>2]=0;for(QA=N+X;f>0]=0;return N}if(R==="i8")return a.subarray||a.slice?o.set(a,N):o.set(new Uint8Array(a),N),N;for(var P,X,N,QA,iA,aA,tA,q=0;q>0],(f!=0||E)&&(X++,!E||X!=E););E||(E=X);var N="";if(P<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(a,a+Math.min(E,1024))),N=N?N+R:R,a+=1024,E-=1024;return N}return Q=a,function(iA,aA){for(var tA=aA;iA[tA];)++tA;if(tA-aA>16&&iA.subarray&&jt)return jt.decode(iA.subarray(aA,tA));for(var q,mA,GA,xA,MA,ee,NA="";;){if(!(q=iA[aA++]))return NA;if(!(128&q)){NA+=String.fromCharCode(q);continue}if(mA=63&iA[aA++],(224&q)==192){NA+=String.fromCharCode((31&q)<<6|mA);continue}if(GA=63&iA[aA++],(240&q)==224?q=(15&q)<<12|mA<<6|GA:(xA=63&iA[aA++],(248&q)==240?q=(7&q)<<18|mA<<12|GA<<6|xA:(MA=63&iA[aA++],q=(252&q)==248?(3&q)<<24|mA<<18|GA<<12|xA<<6|MA:(1&q)<<30|mA<<24|GA<<18|xA<<12|MA<<6|(ee=63&iA[aA++]))),q<65536)NA+=String.fromCharCode(q);else{var Se=q-65536;NA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(o,Q)}function zo(a){for(var E="";;){var Q=s[a++>>0];if(!Q)return E;E+=String.fromCharCode(Q)}}function jo(a,E){return function(f,R,P){for(var X=0;X>0]=f.charCodeAt(X);P||(s[R>>0]=0)}(a,E,!1)}var jt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ue(a,E,Q,f){if(!(f>0))return 0;for(var R=Q,P=Q+f-1,X=0;X=55296&&N<=57343&&(N=65536+((1023&N)<<10)|1023&a.charCodeAt(++X)),N<=127){if(Q>=P)break;E[Q++]=N}else if(N<=2047){if(Q+1>=P)break;E[Q++]=192|N>>6,E[Q++]=128|63&N}else if(N<=65535){if(Q+2>=P)break;E[Q++]=224|N>>12,E[Q++]=128|N>>6&63,E[Q++]=128|63&N}else if(N<=2097151){if(Q+3>=P)break;E[Q++]=240|N>>18,E[Q++]=128|N>>12&63,E[Q++]=128|N>>6&63,E[Q++]=128|63&N}else if(N<=67108863){if(Q+4>=P)break;E[Q++]=248|N>>24,E[Q++]=128|N>>18&63,E[Q++]=128|N>>12&63,E[Q++]=128|N>>6&63,E[Q++]=128|63&N}else{if(Q+5>=P)break;E[Q++]=252|N>>30,E[Q++]=128|N>>24&63,E[Q++]=128|N>>18&63,E[Q++]=128|N>>12&63,E[Q++]=128|N>>6&63,E[Q++]=128|63&N}}return E[Q]=0,Q-R}function $t(a,E,Q){return Ue(a,o,E,Q)}function Te(a){for(var E=0,Q=0;Q=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&a.charCodeAt(++Q)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var An=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function $o(a){for(var E=a,Q=E>>1;I[Q];)++Q;if((E=Q<<1)-a>32&&An)return An.decode(o.subarray(a,E));for(var f=0,R="";;){var P=I[a+2*f>>1];if(P==0)return R;++f,R+=String.fromCharCode(P)}}function Ar(a,E,Q){if(Q===void 0&&(Q=2147483647),Q<2)return 0;for(var f=E,R=(Q-=2)<2*a.length?Q/2:a.length,P=0;P>1]=X,E+=2}return I[E>>1]=0,E-f}function er(a){return 2*a.length}function tr(a){for(var E=0,Q="";;){var f=h[a+4*E>>2];if(f==0)return Q;if(++E,f>=65536){var R=f-65536;Q+=String.fromCharCode(55296|R>>10,56320|1023&R)}else Q+=String.fromCharCode(f)}}function nr(a,E,Q){if(Q===void 0&&(Q=2147483647),Q<4)return 0;for(var f=E,R=f+Q-4,P=0;P=55296&&X<=57343&&(X=65536+((1023&X)<<10)|1023&a.charCodeAt(++P)),h[E>>2]=X,(E+=4)+4>R)break}return h[E>>2]=0,E-f}function sr(a){for(var E=0,Q=0;Q=55296&&f<=57343&&++Q,E+=4}return E}function or(a){var E=Te(a)+1,Q=Ye(E);return Q&&Ue(a,s,Q,E),Q}function rr(a){var E=Te(a)+1,Q=Je(E);return Ue(a,s,Q,E),Q}function ir(a){return a}function ar(){var a,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()),(a=E).replace(/__Z[\w\d_]+/g,function(Q){var f,R=f=Q;return Q===R?Q:Q+" ["+R+"]"})}function gt(a,E){return a%E>0&&(a+=E-a%E),a}function en(a){i.buffer=n=a}function Ct(){i.HEAP8=s=new Int8Array(n),i.HEAP16=I=new Int16Array(n),i.HEAP32=h=new Int32Array(n),i.HEAPU8=o=new Uint8Array(n),i.HEAPU16=C=new Uint16Array(n),i.HEAPU32=B=new Uint32Array(n),i.HEAPF32=d=new Float32Array(n),i.HEAPF64=c=new Float64Array(n)}function tn(){var a=i.usingWasm?65536:16777216,E=2147483648-a;if(h[x>>2]>E)return!1;var Q=hA;for(hA=Math.max(hA,16777216);hA>2];)hA=hA<=536870912?gt(2*hA,a):Math.min(gt((3*hA+2147483648)/4,a),E);var f=i.reallocBuffer(hA);return f&&f.byteLength==hA?(en(f),Ct(),!0):(hA=Q,!1)}l=u=y=k=w=G=x=0,D=!1,i.reallocBuffer||(i.reallocBuffer=function(a){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(n,a);else{var E,Q=s;E=new ArrayBuffer(a),new Int8Array(E).set(Q)}}catch{return!1}return!!xo(E)&&E});try{(b=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{b=function(E){return E.byteLength}}var Et=i.TOTAL_STACK||5242880,hA=i.TOTAL_MEMORY||16777216;function So(){return hA}function me(a){for(;a.length>0;){var E=a.shift();if(typeof E=="function"){E();continue}var Q=E.func;typeof Q=="number"?E.arg===void 0?i.dynCall_v(Q):i.dynCall_vi(Q,E.arg):Q(E.arg===void 0?null:E.arg)}}hA=0?a:E<=32?2*Math.abs(1<=f&&(E<=32||a>f)&&(a=-2*f+a),a}var Fo=Math.abs,Ro=Math.ceil,an=Math.floor,Go=Math.min,Ae=0,Qt=null,pe=null;function Qr(a){return a}i.preloadedImages={},i.preloadedAudios={};var In="data:application/octet-stream;base64,";function He(a){return String.prototype.startsWith?a.startsWith(In):a.indexOf(In)===0}(function(){var E="main.wast",Q="main.wasm",f="main.temp.asm.js";He(E)||(E=CA(E)),He(Q)||(Q=CA(Q)),He(f)||(f=CA(f));var R={global:null,env:null,asm2wasm:mo,parent:i},P=null;function X(tA){return tA}function N(){try{if(i.wasmBinary)return new Uint8Array(i.wasmBinary);if(i.readBinary)return i.readBinary(Q);throw"both async and sync fetching of the wasm failed"}catch(tA){OA(tA)}}i.asmPreload=i.asm;var QA=i.reallocBuffer,iA=function(tA){tA=gt(tA,i.usingWasm?65536:16777216);var q=i.buffer.byteLength;if(i.usingWasm)try{var mA=i.wasmMemory.grow((tA-q)/65536);return mA!==-1?i.buffer=i.wasmMemory.buffer:null}catch{return null}};i.reallocBuffer=function(tA){return aA==="asmjs"?QA(tA):iA(tA)};var aA="";i.asm=function(tA,q,mA){var GA;if(!(q=GA=q).table){var xA,MA=i.wasmTableSize;MA===void 0&&(MA=1024);var ee=i.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?ee!==void 0?q.table=new WebAssembly.Table({initial:MA,maximum:ee,element:"anyfunc"}):q.table=new WebAssembly.Table({initial:MA,element:"anyfunc"}):q.table=Array(MA),i.wasmTable=q.table}return q.memoryBase||(q.memoryBase=i.STATIC_BASE),q.tableBase||(q.tableBase=0),xA=function(Se,ie,dt){if(typeof WebAssembly!="object")return RA("no native wasm support detected"),!1;if(!(i.wasmMemory instanceof WebAssembly.Memory))return RA("no native wasm Memory in use"),!1;function ve(vA,qA){if((P=vA.exports).memory){var De,ft,En;De=P.memory,ft=i.buffer,De.byteLength0?Q:Te(a)+1,R=Array(f),P=Ue(a,R,0,R.length);return E&&(R.length=P),R}function dr(a){for(var E=[],Q=0;Q255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}u+=16,x=Ne(4),w=(y=k=Zt(u))+Et,G=Zt(w),h[x>>2]=G,D=!0,i.wasmTableSize=4,i.wasmMaxTableSize=4,i.asmGlobalArg={},i.asmLibraryArg={abort:OA,assert:_A,enlargeMemory:tn,getTotalMemory:So,abortOnCannotGrowMemory:function(){OA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+hA+", (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,Q,f){var R=lt();try{return i.dynCall_iii(E,Q,f)}catch(P){if(ct(R),typeof P!="number"&&P!=="longjmp")throw P;i.setThrew(1,0)}},___assert_fail:function(E,Q,f,R){OA("Assertion failed: "+Le(E)+", at: "+[Q?Le(Q):"unknown filename",f,R?Le(R):"unknown function"])},___setErrNo:function(E){return i.___errno_location&&(h[i.___errno_location()>>2]=E),E},_abort:function(){i.abort()},_emscripten_memcpy_big:function(E,Q,f){return o.set(o.subarray(Q,Q+f),E),E},_llvm_floor_f64:an,DYNAMICTOP_PTR:x,tempDoublePtr:kA,ABORT:be,STACKTOP:k,STACK_MAX:w};var gn=i.asm(i.asmGlobalArg,i.asmLibraryArg,n);i.asm=gn,i.___errno_location=function(){return i.asm.___errno_location.apply(null,arguments)};var xo=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 Ye=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 Je=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 ye(a){this.name="ExitStatus",this.message="Program terminated with exit("+a+")",this.status=a}function ut(a){a=a||i.arguments,!(Ae>0)&&(function(){if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)ko(i.preRun.shift());me(nn)}(),!(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,be||(ht||(ht=!0,me(Bt)),me(sn),i.onRuntimeInitialized&&i.onRuntimeInitialized(),function(){if(i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;)wo(i.postRun.shift());me(rn)}()))}}function fr(a,E){(!E||!i.noExitRuntime||a!==0)&&(i.noExitRuntime||(be=!0,Xt=a,k=$,me(on),Do=!0,i.onExit&&i.onExit(a)),i.quit(a,new ye(a)))}function OA(a){throw i.onAbort&&i.onAbort(a),a!==void 0?(Me(a),RA(a),a=JSON.stringify(a)):a="",be=!0,Xt=1,"abort("+a+"). Build with -s ASSERTIONS=1 for more info."}if(i.dynCall_iii=function(){return i.asm.dynCall_iii.apply(null,arguments)},i.asm=gn,i.ccall=zt,i.cwrap=function(E,Q,f,R){var P=(f=f||[]).every(function(X){return X==="number"});return Q!=="string"&&P&&!R?Wt(E):function(){return zt(E,Q,f,arguments,R)}},ye.prototype=Error(),ye.prototype.constructor=ye,pe=function a(){i.calledRun||ut(),i.calledRun||(pe=a)},i.run=ut,i.abort=OA,i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();i.noExitRuntime=!0,ut(),i.onRuntimeInitialized=()=>{os=!0,rs()},VA.decode=function(a){return function(Q){if(!os)throw Error("Not initialized");var f={};function R(ie){return new Int32Array(i.HEAPU8.buffer,ie,1)[0]}function P(ie,dt){var ve=new ArrayBuffer(dt*Float32Array.BYTES_PER_ELEMENT),ae=new Float32Array(ve);return ae.set(new Float32Array(i.HEAPU8.buffer,ie,dt)),ae}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 X,N,QA,iA,aA=f.open(),tA=(X=Q,N=Q.byteLength,QA=i._malloc(N),(iA=new Uint8Array(i.HEAPU8.buffer,QA,N)).set(new Uint8Array(X,0,N)),iA),q=i._malloc(4),mA=i._malloc(4),GA=f.decode(aA,tA.byteOffset,tA.byteLength,q,mA);if(i._free(tA.byteOffset),GA<0)throw f.close(aA),i._free(q),Error("stbvorbis decode failed: "+GA);for(var xA=f.channels(aA),MA=Array(xA),ee=new Int32Array(i.HEAPU32.buffer,R(q),xA),NA=0;NA=0&&(n=this.workletProcessorChannels[e]),t.messageType){case eA.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case eA.noteOff:this.noteOff(e,A);break;case eA.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case eA.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case eA.customcCcChange:n.customControllers[A[0]]=A[1];break;case eA.killNote:this.killNote(e,A);break;case eA.programChange:this.programChange(e,A[0],A[1]);break;case eA.channelPressure:this.channelPressure(e,A);break;case eA.polyPressure:this.polyPressure(e,A[0],A[1]);break;case eA.ccReset:e===UA?this.resetAllControllers():this.resetControllers(e);break;case eA.systemExclusive:this.systemExclusive(A);break;case eA.setChannelVibrato:if(e===UA)for(let I=0;I{let e=(A.midiControllers[EA+K.pitchWheelRange]>>7)+(A.midiControllers[EA+K.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[EA+K.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:pA.channelProperties,messageData:t})}function Yo(t,A,e){let n=t,s=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:n,centTuning:s*.0061}}function gs(t,A=0){let e=t[0];if(!(this.deviceID!==UA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:T(`%cUnrecognized SysEx: %c${uA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let s;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),p(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),p(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let h=(t[5]<<7|t[6])-8192;s=Math.floor(h/81.92),this.setMasterTuning(s),p(`%cMaster Fine Tuning. Cents: %c${s}`,r.info,r.value);break;case 4:s=(t[5]-64)*100,this.setMasterTuning(s),p(`%cMaster Coarse Tuning. Cents: %c${s}`,r.info,r.value);break;default:T(`%cUnrecognized MIDI Device Control Real-time message: %c${uA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(p("%cGM system on",r.info),this.system="gm"):t[3]===3?(p("%cGM2 system on",r.info),this.system="gm2"):(p("%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 I=t[o++],C=t[o++];for(let B=0;B>1&1)===1&&this.setOctaveTuning(15+A,h);for(let B=0;B<7;B++)(t[5]>>B&1)===1&&this.setOctaveTuning(7+B+A,h);for(let B=0;B<7;B++)(t[6]>>B&1)===1&&this.setOctaveTuning(B+A,h);p(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${h.join(" ")}`,r.info,r.value);break;default:T(`%cUnrecognized MIDI Tuning standard message: %c${uA(t)}`,r.warn,r.unrecognized);break}break;default:T(`%cUnrecognized MIDI Realtime/non realtime message: %c${uA(t)}`,r.warn,r.unrecognized)}break;case 65:let n=function(){T(`%cUnrecognized Roland %cGS %cSysEx: %c${uA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let s=t[7];if(t[6]===127){s===0?(p("%cGS Reset received!",r.info),this.resetAllControllers(!1),this.system="gs"):s===127&&(p("%cGS system off, switching to GM2",r.info),this.resetAllControllers(!1),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:n();break;case 21:let I=s>0&&t[5]>>4;this.setDrums(o,I),p(`%cChannel %c${o}%c ${I?"is now a drum channel":"now isn't a drum channel"}%c via: %c${uA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=s-64;this.transposeChannel(o,C),p(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${uA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let h=s;h===0&&(h=Math.floor(Math.random()*128)),this.controllerChange(o,m.pan,h);break;case 33:this.controllerChange(o,m.chorusDepth,s);break;case 34:this.controllerChange(o,m.reverbDepth,s);break;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 B=t.length-9,d=new Int8Array(12);for(let l=0;l=this.workletProcessorChannels.length)return;let o=t[6];switch(t[5]){case 1:this.controllerChange(s,m.bankSelect,o);break;case 2:this.controllerChange(s,m.lsbForControl0BankSelect,o);break;case 3:this.programChange(s,o);break;case 8:let I=this.workletProcessorChannels[s];if(I.drumChannel)return;let C=o-64;I.channelTransposeKeyShift=C;break;case 11:this.controllerChange(s,m.mainVolume,o);break;case 14:let h=o;h===0&&(h=Math.floor(Math.random()*127)),this.controllerChange(s,m.pan,h);break;case 19:this.controllerChange(s,m.reverbDepth,o);break;case 18:this.controllerChange(s,m.chorusDepth,o);break;default:T(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&T(`%cUnrecognized Yamaha XG SysEx: %c${uA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&T(`%cUnrecognized Yamaha SysEx: %c${uA(t)}`,r.warn,r.unrecognized);break}}function Cs(t,A,e){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=t[A.sourceIndex];else{let h=A.sourceIndex+EA;switch(A.sourceIndex){case K.noController:n=16383;break;case K.noteOnKeyNum:n=e.midiNote<<7;break;case K.noteOnVelocity:n=e.velocity<<7;break;case K.polyPressure:n=e.pressure<<7;break;default:n=t[h];break}}let s=oe[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let h=A.secSrcIndex+EA;switch(A.secSrcIndex){case K.noController:o=16383;break;case K.noteOnKeyNum:o=e.midiNote<<7;break;case K.noteOnVelocity:o=e.velocity<<7;break;case K.polyPressure:o=e.pressure<<7;break;default:o=t[h]}}let I=oe[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=s*I*A.transformAmount;return A.transformType===2&&(C=Math.abs(C)),A.currentValue=C,C}function XA(t,A,e=-1,n=0){let s=t.modulators,o=t.generators,I=t.modulatedGenerators;if(YA.recalculate(t),e===-1){I.set(o),s.forEach(B=>{let d=U[B.modulatorDestination],c=I[B.modulatorDestination]+Cs(A,B,t);I[B.modulatorDestination]=Math.max(d.min,Math.min(c,d.max))}),LA.recalculate(t);return}let C=new Set([g.initialAttenuation,g.delayVolEnv,g.attackVolEnv,g.holdVolEnv,g.decayVolEnv,g.sustainVolEnv,g.releaseVolEnv,g.keyNumToVolEnvHold,g.keyNumToVolEnvDecay]),h=new Set;s.forEach(B=>{if(B.sourceUsesCC===e&&B.sourceIndex===n||B.secSrcUsesCC===e&&B.secSrcIndex===n){let d=B.modulatorDestination;h.has(d)||(I[d]=o[d],Cs(A,B,t),s.forEach(c=>{if(c.modulatorDestination===d){let l=U[B.modulatorDestination],u=I[B.modulatorDestination]+c.currentValue;I[B.modulatorDestination]=Math.max(l.min,Math.min(u,l.max))}}),h.add(d))}}),[...h].some(B=>C.has(B))&&LA.recalculate(t)}var oe=[];for(let t=0;t<4;t++){oe[t]=[[new Float32Array(BA),new Float32Array(BA)],[new Float32Array(BA),new Float32Array(BA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||I.isMuted)return;let C=A+I.channelTransposeKeyShift,h=C;if(A>127||A<0)return;let B=I.preset.program;this.tunings[B]?.[A]?.midiNote>=0&&(h=this.tunings[B]?.[A].midiNote),I.velocityOverride>0&&(e=I.velocityOverride);let d=this.getWorkletVoices(t,h,e,I,o,C,n),c=I.voices;d.forEach(l=>{let u=l.generators[g.exclusiveClass];u!==0&&c.forEach(b=>{b.generators[g.exclusiveClass]===u&&(this.releaseVoice(b),b.modulatedGenerators[g.releaseVolEnv]=-7e3,b.modulatedGenerators[g.releaseModEnv]=-7e3,LA.recalculate(b),YA.recalculate(b))}),XA(l,I.midiControllers);let D=l.modulatedGenerators[g.startAddrsOffset]+l.modulatedGenerators[g.startAddrsCoarseOffset]*32768,y=l.modulatedGenerators[g.endAddrOffset]+l.modulatedGenerators[g.endAddrsCoarseOffset]*32768,k=l.modulatedGenerators[g.startloopAddrsOffset]+l.modulatedGenerators[g.startloopAddrsCoarseOffset]*32768,w=l.modulatedGenerators[g.endloopAddrsOffset]+l.modulatedGenerators[g.endloopAddrsCoarseOffset]*32768,G=l.sample,x=b=>Math.max(0,Math.min(G.sampleData.length-1,b));if(G.cursor=x(G.cursor+D),G.end=x(G.end+y),G.loopStart=x(G.loopStart+k),G.loopEnd=x(G.loopEnd+w),G.loopEndthis.voiceCap&&this.voiceKilling(d.length),c.push(...d),s&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Bs(t,A){if(A>127||A<0){T("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift;if(this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(s=>{s.realKey!==e||s.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(s):this.releaseVoice(s))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function hs(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.realKey===A&&(e.modulatedGenerators[g.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function Qs(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(n=>{n.isInRelease||this.releaseVoice(n)}),this.workletProcessorChannels[t].sustainedVoices.forEach(n=>{this.releaseVoice(n)}))}function cs(t=!1){p("%cStop all received!",r.info);for(let A=0;AXA(s,this.workletProcessorChannels[t].midiControllers,0,K.pitchWheel)),this.sendChannelProperties()}function Ss(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[EA+K.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(n=>XA(n,e.midiControllers,0,K.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function Ds(t,A,e){this.workletProcessorChannels[t].voices.forEach(n=>{n.midiNote===A&&(n.pressure=e,XA(n,this.workletProcessorChannels[t].midiControllers,0,K.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function ks(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function ws(t,A,e,n=!1){let s=this.workletProcessorChannels[t];if(s===void 0){T(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>127){if(!n)return;switch(A){default:return;case wt.velocityOverride:s.velocityOverride=e}}if(A>=m.lsbForControl1ModulationWheel&&A<=m.lsbForControl13EffectControl2&&A!==m.lsbForControl6DataEntry){let o=A-32;if(s.lockedControllers[o])return;s.midiControllers[o]=s.midiControllers[o]&16256|e&127,s.voices.forEach(I=>XA(I,s.midiControllers,1,o))}switch(A){case m.allNotesOff:this.stopAll(t);break;case m.allSoundOff:this.stopAll(t,!0);break;case m.bankSelect:let o=e;if(!n){switch(this.system){case"gm":p(`%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&&(s.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}s.drumChannel&&(o=128),o===128&&!s.drumChannel&&(o=s.midiControllers[m.bankSelect])}s.midiControllers[m.bankSelect]=o;break;case m.lsbForControl0BankSelect:this.system==="xg"?s.drumChannel||e!==127&&(s.midiControllers[m.bankSelect]=e):this.system==="gm2"&&(s.midiControllers[m.bankSelect]=e);break;case m.RPNLsb:s.RPValue=s.RPValue<<7|e,s.dataEntryState=fA.RPFine;break;case m.RPNMsb:s.RPValue=e,s.dataEntryState=fA.RPCoarse;break;case m.NRPNMsb:s.NRPCoarse=e,s.dataEntryState=fA.NRPCoarse;break;case m.NRPNLsb:s.NRPFine=e,s.dataEntryState=fA.NRPFine;break;case m.dataEntryMsb:this.dataEntryCoarse(t,e);break;case m.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case m.resetAllControllers:this.resetControllers(t);break;case m.sustainPedal:e>=64?s.holdPedal=!0:(s.holdPedal=!1,s.sustainedVoices.forEach(I=>{this.releaseVoice(I)}),s.sustainedVoices=[]);break;default:if(s.lockedControllers[A])return;s.midiControllers[A]=e<<7,s.voices.forEach(I=>XA(I,s.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function Fs(t){this.midiVolume=t,this.setMasterPan(this.pan)}function Rs(t){this.masterGain=t*Ut,this.setMasterPan(this.pan)}function Gs(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function xs(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function Ms(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 Ns(t,A,e,n){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=n,this.workletProcessorChannels[t].channelVibrato.depth=A)}function bs(t,A){let e=this.workletProcessorChannels[t],n=()=>{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 fA.Idle:break;case fA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;T(`%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;T(`%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;n(),e.channelVibrato.rate=A/64*8,p(`%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;n(),e.channelVibrato.depth=A/2,p(`%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;n(),e.channelVibrato.delay=A/64/3,p(`%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 I=A;this.controllerChange(t,m.brightness,A),p(`%cFilter cutoff for %c${t}%c is now set to %c${I}`,r.info,r.recognized,r.info,r.value)}break;case 24:let s=A-64;e.keyCentTuning[e.NRPFine]=s*100,p(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${s}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,m.reverbDepth,o),p(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:T(`%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[EA+K.pitchWheelRange]=A<<7,p(`%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 Ls(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[EA+K.pitchWheelRange]|=A;let n=(e.midiControllers[EA+K.pitchWheelRange]>>7)+A/127;p(`%cChannel ${t} bend range. Semitones: %c${n}`,r.info,r.value);break;case 1:let o=e.customControllers[gA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[gA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function Us(t=!0){t&&p("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A{this.workletProcessorChannels[A].lockedControllers[s]&&this.callEvent("controllerchange",{channel:A,controllerNumber:s,controllerValue:this.workletProcessorChannels[A].midiControllers[s]>>7})};if(n(m.mainVolume),n(m.pan),n(m.expressionController),n(m.modulationWheel),n(m.chorusDepth),n(m.reverbDepth),n(m.brightness),this.workletProcessorChannels[A].lockedControllers[EA+K.pitchWheel]){let s=this.workletProcessorChannels[A].midiControllers[EA+K.pitchWheel],o=s>>7,I=s&127;this.callEvent("pitchwheel",{channel:A,MSB:o,LSB:I})}}this.tunings=[],this.tunings=[];for(let A=0;127>A;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Oe}function Ts(t){let A=this.workletProcessorChannels[t],n=A.lockedControllers.reduce((o,I,C)=>(I&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(St),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,n.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let s=A.customControllers[gA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[gA.channelTransposeFine]=s,this.resetParameters(t)}function Hs(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=fA.Idle}function Ys(){let t=4;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==g.sampleID&&I.generatorType!==g.keyRange&&I.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+s),0);let A=new Y(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.generatorZoneStartIndex=e;for(let o of s.generators)J(A,o.generatorType),J(A,o.generatorValue),e++}return lA(A,0),nA(new AA("igen",A.length,A))}function Js(t,A,e,n,s){let o=this.samples.map((B,d)=>{e&&B.compressSample(n,s);let c=B.getRawData();return p(`%cEncoded sample %c${d}. ${B.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),c}),I=this.samples.reduce((B,d,c)=>B+o[c].length+46,0),C=new Y(I);this.samples.forEach((B,d)=>{let c=o[d],l,u,D=c.length;B.isCompressed?(l=C.currentIndex,u=l+c.length):(l=C.currentIndex/2,u=l+c.length/2,D+=46),t.push(l),C.set(c,C.currentIndex),C.currentIndex+=D,A.push(u)});let h=nA(new AA("smpl",C.length,C),new Y([115,100,116,97]));return nA(new AA("LIST",h.length,h))}function vs(t,A){let n=new Y(46*(this.samples.length+1));return this.samples.forEach((s,o)=>{FA(n,s.sampleName,20);let I=t[o];lA(n,I);let C=A[o];lA(n,C);let h=s.sampleLoopStartIndex+I,B=s.sampleLoopEndIndex+I;s.isCompressed&&(h-=I,B-=I),lA(n,h),lA(n,B),lA(n,s.sampleRate),n[n.currentIndex++]=s.samplePitch,n[n.currentIndex++]=s.samplePitchCorrection,J(n,s.sampleLink),J(n,s.sampleType)}),FA(n,"EOS",46),nA(new AA("shdr",n.length,n))}function qs(){let t=10;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new Y(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)J(A,o.sourceEnum),J(A,o.modulatorDestination),J(A,o.transformAmount),J(A,o.secondarySourceEnum),J(A,o.transformType),e++}return Ee(A,0,10),nA(new AA("imod",A.length,A))}function Ps(){let t=this.instruments.reduce((o,I)=>I.instrumentZones.length*4+o,4),A=new Y(t),e=0,n=0,s=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let I of o.instrumentZones)I.zoneID=e,J(A,n),J(A,s),n+=I.generators.length,s+=I.modulators.length,e++}return J(A,n),J(A,s),nA(new AA("ibag",A.length,A))}function Ks(){let t=this.instruments.length*22+22,A=new Y(t),e=0,n=0;for(let s of this.instruments)FA(A,s.instrumentName,20),J(A,e),e+=s.instrumentZones.length,s.instrumentID=n,n++;return FA(A,"EOI",20),J(A,e),nA(new AA("inst",A.length,A))}function Vs(){let t=4;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==g.instrument&&I.generatorType!==g.keyRange&&I.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+s),0);let A=new Y(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.generatorZoneStartIndex=e;for(let o of s.generators)J(A,o.generatorType),J(A,o.generatorValue);e+=s.generators.length}return J(A,0),J(A,0),nA(new AA("pgen",A.length,A))}function Os(){let t=10;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new Y(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)J(A,o.sourceEnum),J(A,o.modulatorDestination),J(A,o.transformAmount),J(A,o.secondarySourceEnum),J(A,o.transformType),e++}return Ee(A,0,10),nA(new AA("pmod",A.length,A))}function Zs(){let t=this.presets.reduce((o,I)=>I.presetZones.length*4+o,4),A=new Y(t),e=0,n=0,s=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let I of o.presetZones)I.zoneID=e,J(A,n),J(A,s),n+=I.generators.length,s+=I.modulators.length,e++}return J(A,n),J(A,s),nA(new AA("pbag",A.length,A))}function Xs(){let t=this.presets.length*38+38,A=new Y(t),e=0;for(let n of this.presets)FA(A,n.presetName,20),J(A,n.program),J(A,n.bank),J(A,e),lA(A,n.library),lA(A,n.genre),lA(A,n.morphology),e+=n.presetZones.length;return FA(A,"EOP",20),J(A,0),J(A,0),J(A,e),lA(A,0),lA(A,0),lA(A,0),nA(new AA("phdr",A.length,A))}var Jo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Ws(t=Jo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");yA("%cSaving soundfont...",r.info),p(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),p("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[b,$]of Object.entries(this.soundFontInfo))if(b==="ifil"||b==="iver"){let i=parseInt($.split(".")[0]),sA=parseInt($.split(".")[1]),_=new Y(4);J(_,i),J(_,sA),A.push(nA(new AA(b,4,_)))}else if(b==="DMOD")A.push(nA(new AA(b,$.length,$)));else{let i=new Y($.length);FA(i,$),A.push(nA(new AA(b,$.length,i)))}let e=ke([new Y([73,78,70,79]),...A]),n=nA(new AA("LIST",e.length,e));p("%cWriting SDTA...",r.info);let s=[],o=[],I=Js.call(this,s,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);p("%cWriting PDTA...",r.info),p("%cWriting SHDR...",r.info);let C=vs.call(this,s,o);p("%cWriting IGEN...",r.info);let h=Ys.call(this);p("%cWriting IMOD...",r.info);let B=qs.call(this);p("%cWriting IBAG...",r.info);let d=Ps.call(this);p("%cWriting INST...",r.info);let c=Ks.call(this),l=Vs.call(this);p("%cWriting PMOD...",r.info);let u=Os.call(this);p("%cWriting PBAG...",r.info);let D=Zs.call(this);p("%cWriting PHDR...",r.info);let y=Xs.call(this),k=ke([new Y([112,100,116,97]),y,D,u,l,c,d,B,h,C]),w=nA(new AA("LIST",k.length,k));p("%cWriting the output file...",r.info);let G=ke([new Y([115,102,98,107]),n,I,w]),x=nA(new AA("RIFF",G.length,G));return p(`%cSaved succesfully! Final file size: %c${x.length}`,r.info,r.recognized),Z(),x}var re=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Pe.map(e=>j.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}static mergeSoundfonts(...A){let e=A.shift(),n=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(I=>I.bank===o.bank&&I.program===o.program)===void 0&&n.push(o)});return new t({presets:n,info:e.soundFontInfo})}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()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPresetNoFallback(A,e,n=!1){let s=this.presets.find(o=>o.bank===A&&o.program===e);if(s)return s;if(n!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}getPreset(A,e){let n=this.presets.find(s=>s.bank===A&&s.program===e);return n||(A===128?(n=this.presets.find(s=>s.bank===128&&s.program===e),n||(n=this.presets.find(s=>s.bank===128))):n=this.presets.find(s=>s.program===e&&s.bank!==128),n&&T(`%cPreset ${A}.${e} not found. Replaced with %c${n.presetName} (${n.bank}.${n.program})`,r.warn,r.recognized)),n||(T(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),n=this.presets[0]),n}getPresetByName(A){let e=this.presets.find(n=>n.presetName===A);return e||(T("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}};re.prototype.write=Ws;function _s(t){yA("%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 n=A;n{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}getSamplesAndGenerators(A,e){let n=this.foundSamplesAndGenerators[A][e];if(n)return n;if(this.presetZones.length<1)return[];function s(c,l,u){return u>=c&&u<=l}function o(c,l){c.push(...l.filter(u=>!c.find(D=>D.generatorType===u.generatorType)))}function I(c,l){c.push(...l.filter(u=>!c.find(D=>j.isIdentical(u,D))))}let C=[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],B=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(c=>s(c.keyRange.min,c.keyRange.max,A)&&s(c.velRange.min,c.velRange.max,e)&&!c.isGlobal).forEach(c=>{if(c.instrument.instrumentZones.length<1)return;let l=c.generators,u=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(w=>s(w.keyRange.min,w.keyRange.max,A)&&s(w.velRange.min,w.velRange.max,e)&&!w.isGlobal).forEach(w=>{let G=[...w.generators],x=[...w.modulators];o(l,h),o(G,D),I(u,B),I(x,y),I(x,this.defaultModulators);let b=[...x];for(let $=0;$j.isIdentical(i,_));sA!==-1?b[sA]=b[sA].sumTransform(i):b.push(i)}C.push({instrumentGenerators:G,presetGenerators:l,modulators:b,sample:w.sample,sampleID:w.generators.find($=>$.generatorType===g.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=C,C}};var Re=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var $A=class extends Re{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},le=class extends Re{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var ue=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}get useCount(){return this._useCount}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 ce{constructor(A,e){super(Pe),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new ue,this.DLSInstrument.addUseCount();let s=new le;s.instrument=this.DLSInstrument,this.presetZones=[s]}};function zs(t){this.verifyHeader(t,"LIST"),this.verifyText(V(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(u=>u.header==="insh");if(!e)throw Z(),new Error("No instrument header!");let n=S(e.chunkData,4),s=S(e.chunkData,4),o=S(e.chunkData,4),I=new At(s,o),C="unnamedPreset",h=DA(A,"INFO");if(h){let u=O(h.chunkData);for(;u.header!=="INAM";)u=O(h.chunkData);C=V(u.chunkData,u.chunkData.length).trim()}I.presetName=C,I.DLSInstrument.instrumentName=C,te(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let B=DA(A,"lrgn");if(!B)throw Z(),new Error("No region list!");let d=new $A;d.isGlobal=!0;let c=DA(A,"lart"),l=DA(A,"lar2");this.readLart(c,l,d),I.DLSInstrument.instrumentZones.push(d);for(let u=0;u>10&15;w===cA.linear&&k!==cA.linear&&(w=k);let G=n>>14&1,x=n>>15&1;I===g.initialAttenuation&&(x=!x),c=TA(w,G,x,C.isCC,C.enum)}let l=n>>4&15,u=n>>8&1,D=n>>9&1,y=TA(l,u,D,d.isCC,d.enum);if(h){let k=y;y=c,c=k}return new j({srcEnum:c,secSrcEnum:y,dest:I,transform:0,amt:s})}function Tt(t,A){let e=t.chunkData,n=[],s=[];S(e,4);let o=S(e,4);for(let I=0;I>16;if(C===0&&h===0&&d===0){let u;switch(B){case M.pan:u=new L(g.pan,l);break;case M.gain:u=new L(g.initialAttenuation,-l*10/.4);break;case M.filterCutoff:u=new L(g.initialFilterFc,l);break;case M.filterQ:u=new L(g.initialFilterQ,l);break;case M.modLfoFreq:u=new L(g.freqModLFO,l);break;case M.modLfoDelay:u=new L(g.delayModLFO,l);break;case M.vibLfoFreq:u=new L(g.freqVibLFO,l);break;case M.vibLfoDelay:u=new L(g.delayVibLFO,l);break;case M.volEnvDelay:u=new L(g.delayVolEnv,l);break;case M.volEnvAttack:u=new L(g.attackVolEnv,l);break;case M.volEnvHold:u=new L(g.holdVolEnv,l);break;case M.volEnvDecay:u=new L(g.decayVolEnv,l);break;case M.volEnvRelease:u=new L(g.releaseVolEnv,l);break;case M.volEnvSustain:let D=(1e3-l)/10;u=new L(g.sustainVolEnv,D*10);break;case M.modEnvDelay:u=new L(g.delayModEnv,l);break;case M.modEnvAttack:u=new L(g.attackModEnv,l);break;case M.modEnvHold:u=new L(g.holdModEnv,l);break;case M.modEnvDecay:u=new L(g.decayModEnv,l);break;case M.modEnvRelease:u=new L(g.releaseModEnv,l);break;case M.modEnvSustain:let y=1e3-l;u=new L(g.sustainModEnv,y);break;case M.reverbSend:u=new L(g.reverbEffectsSend,l);break;case M.chorusSend:u=new L(g.chorusEffectsSend,l);break;case M.pitch:let k=Math.floor(l/100),w=Math.floor(l-k*100);u=new L(g.fineTune,w),n.push(new L(g.coarseTune,k));break}u&&n.push(u)}else{let u=!0;if(h===W.none)if(C===W.modLfo&&B===M.pitch)n.push(new L(g.modLfoToPitch,l));else if(C===W.modLfo&&B===M.gain)n.push(new L(g.modLfoToVolume,l));else if(C===W.modLfo&&B===M.filterCutoff)n.push(new L(g.modLfoToFilterFc,l));else if(C===W.vibratoLfo&&B===M.pitch)n.push(new L(g.vibLfoToPitch,l));else if(C===W.modEnv&&B===M.pitch)n.push(new L(g.modEnvToPitch,l));else if(C===W.modEnv&&B===M.filterCutoff)n.push(new L(g.modEnvToFilterFc,l));else if(C===W.keyNum&&B===M.volEnvHold){n.push(new L(g.keyNumToVolEnvHold,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.holdVolEnv&&(y.generatorValue+=D)})}else if(C===W.keyNum&&B===M.volEnvDecay){n.push(new L(g.keyNumToVolEnvDecay,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.decayVolEnv&&(y.generatorValue+=D)})}else if(C===W.keyNum&&B===M.modEnvHold){n.push(new L(g.keyNumToModEnvHold,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.holdModEnv&&(y.generatorValue+=D)})}else if(C===W.keyNum&&B===M.modEnvDecay){n.push(new L(g.keyNumToModEnvDecay,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.decayModEnv&&(y.generatorValue+=D)})}else u=!1;else u=!1;if(u===!1){let D=$s(C,h,B,d,l);D?(s.push(D),p("%cSucceeded converting to SF2 Modulator!",r.recognized)):T("Failed converting to SF2 Modulator!")}}}return s.find(I=>I.modulatorDestination===g.reverbEffectsSend)===void 0&&s.push(new j({srcEnum:219,dest:g.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),s.find(I=>I.modulatorDestination===g.chorusEffectsSend)===void 0&&s.push(new j({srcEnum:221,dest:g.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&s.push(new j({srcEnum:129,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new j({srcEnum:13,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:s,generators:n}}function Ao(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(_=>_.header==="rgnh"),n=S(e.chunkData,2),s=S(e.chunkData,2),o=S(e.chunkData,2),I=S(e.chunkData,2),C=new et({min:n,max:s},{min:o,max:I});S(e.chunkData,2);let h=S(e.chunkData,2);h!==0&&C.generators.push(new L(g.exclusiveClass,h));let B=DA(A,"lart"),d=DA(A,"lar2");this.readLart(B,d,C),C.isGlobal=!1;let c=A.find(_=>_.header==="wsmp");S(c.chunkData,4);let l=S(c.chunkData,2),u=jA(c.chunkData[c.chunkData.currentIndex++],c.chunkData[c.chunkData.currentIndex++]),y=(S(c.chunkData,4)|0)/-655360;S(c.chunkData,4);let k=S(c.chunkData,4),w,G={start:0,end:0};if(k===0)w=0;else{S(c.chunkData,4),S(c.chunkData,4)===0?w=1:w=3,G.start=S(c.chunkData,4);let v=S(c.chunkData,4);G.end=G.start+v}let x=A.find(_=>_.header==="wlnk");if(x===void 0)return;S(x.chunkData,2),S(x.chunkData,2),S(x.chunkData,4);let b=S(x.chunkData,4),$=this.samples[b];if($===void 0)throw new Error("Invalid sample ID!");let sA=(y||$.sampleDbAttenuation)*10/.4;return C.setWavesample(sA,w,G,l,$,b,u),C}var de=class{constructor(A,e,n,s,o,I,C,h){this.sampleName=A,this.sampleRate=e,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=I,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=h,this.isCompressed=(I&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{T(`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 de{sampleDbAttenuation;sampleData;constructor(A,e,n,s,o,I,C,h){super(A,e,n,s,0,1,o,I-1),this.sampleData=C,this.sampleDbAttenuation=h}getAudioData(){return this.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 to(t){yA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexv.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");if(S(s.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(S(s.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=S(s.chunkData,4);S(s.chunkData,4),S(s.chunkData,2);let h=S(s.chunkData,2),B=h/8,d=Math.pow(2,B*8-1),c=Math.pow(2,B*8),l,u=!1;h===8?(l=255,u=!0):l=d;let D=n.find(v=>v.header==="data");if(!D)throw new Error("No data chunk in the wave chunk!");let y=D.size/B,k=new Float32Array(y);for(let v=0;v=d&&(z-=c),k[v]=z/l)}let w=60,G=0,x=0,b=k.length-1,$=0,i=n.find(v=>v.header==="wsmp");if(i){if(S(i.chunkData,4),w=S(i.chunkData,2),G=jA(i.chunkData[i.chunkData.currentIndex++],i.chunkData[i.chunkData.currentIndex++]),$=(S(i.chunkData,4)|0)/-655360,S(i.chunkData,4),S(i.chunkData,4)===1){S(i.chunkData,8),x=S(i.chunkData,4);let oA=S(i.chunkData,4);b=x+oA}}else T("No wsmp chunk in wave... using sane defaults.");let sA=DA(n,"INFO"),_=`Unnamed ${A}`;if(sA){let v=O(sA.chunkData);for(;v.header!=="INAM"&&sA.chunkData.currentIndexh.header==="colh");if(!o)throw Z(),new Error("No colh chunk!");this.instrumentAmount=D(o.chunkData,4),p(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let I=DA(n,"wvpl");this.readDLSSamples(I);let C=DA(n,"lins");if(!C)throw Z(),new Error("No lins chunk!");this.readDLSInstrumentList(C),this.presets.sort((h,B)=>h.program-B.program+(h.bank-B.bank)),p(`%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),Z()}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=_s;WA.prototype.readDLSInstrument=zs;WA.prototype.readRegion=eo;WA.prototype.readLart=Ao;WA.prototype.readDLSSamples=to;var Ht=class extends de{constructor(A,e,n,s,o,I,C,h,B,d,c,l,u){super(A,I,C,h,B,d,s-e/2,o-e/2),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=c,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=u}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,n=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let s=VA.decode(n.buffer);this.sampleData=s.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 T("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let s=0;st.chunkData.currentIndex;){let o=Po(s,t.chunkData,A,e);n.push(o),s++}return n.length>1&&n.pop(),n}function Po(t,A,e,n){let s=V(A,20),o=D(A,4)*2,I=D(A,4)*2,C=D(A,4),h=D(A,4),B=D(A,4),d=A[A.currentIndex++];d===255&&(d=60);let c=Gn(A[A.currentIndex++]),l=D(A,2),u=D(A,2);return new Ht(s,o,I,C,h,B,d,c,l,u,e,t,n)}var Yt=class extends L{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 Jt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Yt(t.chunkData));return A.length>1&&A.pop(),A}var vt=class extends ue{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=D(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;nt.chunkData.currentIndex;){let n=new vt(t);if(e.length>0){let s=n.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(s,A)}e.push(n)}return e.length>1&&e.pop(),e}var qt=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(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;en.generatorType===g.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function oo(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new qt(t.chunkData);if(s.length>0){let I=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(I,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Pt=class extends le{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(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;en.generatorType===g.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ro(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Pt(t.chunkData);if(s.length>0){let I=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(I,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Kt=class extends ce{constructor(A,e){super(e),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=D(A.chunkData,2),this.bank=D(A.chunkData,2),this.presetZoneStartIndex=D(A.chunkData,2),this.library=D(A.chunkData,4),this.genre=D(A.chunkData,4),this.morphology=D(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let n=this.presetZoneStartIndex;nt.chunkData.currentIndex;){let s=new Kt(t,e);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var Vt=class extends j{constructor(A){super({srcEnum:D(A,2),dest:D(A,2),amt:jA(A[A.currentIndex++],A[A.currentIndex++]),secSrcEnum:D(A,2),transform:D(A,2)})}};function nt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Vt(t.chunkData));return A}var st=class extends re{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new Y(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw Z(),new TypeError("No data!");let n=O(this.dataArray,!1);this.verifyHeader(n,"riff");let s=V(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw Z(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",I=O(this.dataArray);for(this.verifyHeader(I,"list"),V(I.chunkData,4);I.chunkData.length>I.chunkData.currentIndex;){let z=O(I.chunkData),oA;switch(z.header.toLowerCase()){case"ifil":case"iver":oA=`${D(z.chunkData,2)}.${D(z.chunkData,2)}`,this.soundFontInfo[z.header]=oA;break;case"icmt":oA=V(z.chunkData,z.chunkData.length,void 0,!1),this.soundFontInfo[z.header]=oA;break;case"dmod":let rA=nt(z);rA.pop(),oA=`Modulators: ${rA.length}`;let CA=this.defaultModulators;this.defaultModulators=rA,this.defaultModulators.push(...CA.filter(Me=>!this.defaultModulators.find(RA=>j.isIdentical(Me,RA)))),this.soundFontInfo[z.header]=z.chunkData;break;default:oA=V(z.chunkData,z.chunkData.length),this.soundFontInfo[z.header]=oA}p(`%c"${z.header}": %c"${oA}"`,r.info,r.recognized)}let C=O(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(V(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",r.warn);let h=O(this.dataArray,!1);this.verifyHeader(h,"smpl");let B;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{B=VA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(z){throw Z(),new Error(`SF2Pack Ogg Vorbis decode error: ${z}`)}p(`%cDecoded the smpl chunk! Length: %c${B.length}`,r.info,r.value)}else B=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,p("%cLoading preset data chunk...",r.warn);let d=O(this.dataArray);this.verifyHeader(d,"list"),V(d.chunkData,4);let c=O(d.chunkData);this.verifyHeader(c,"phdr");let l=O(d.chunkData);this.verifyHeader(l,"pbag");let u=O(d.chunkData);this.verifyHeader(u,"pmod");let y=O(d.chunkData);this.verifyHeader(y,"pgen");let S=O(d.chunkData);this.verifyHeader(S,"inst");let k=O(d.chunkData);this.verifyHeader(k,"ibag");let w=O(d.chunkData);this.verifyHeader(w,"imod");let G=O(d.chunkData);this.verifyHeader(G,"igen");let x=O(d.chunkData);this.verifyHeader(x,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...no(x,B,!o));let b=Jt(G),$=nt(w),i=oo(k,b,$,this.samples);this.instruments=so(S,i);let sA=Jt(y),_=nt(u),v=ro(l,sA,_,this.instruments);this.presets.push(...io(c,v,this.defaultModulators)),this.presets.sort((z,oA)=>z.program-oA.program+(z.bank-oA.bank)),p(`%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),Z(),o&&delete this.dataArray}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Ge(t){let A=t.slice(8,12),e=new Y(A);return V(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new st(t,!1)}function ao(t,A,e=!1){let n=this.workletProcessorChannels[t];if(n===void 0){T(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(n.lockPreset)return;let s=n.drumChannel?128:n.midiControllers[m.bankSelect],o,I;if(this.overrideSoundfont){let C=s===128?128:s-this.soundfontBankOffset,h=this.overrideSoundfont.getPresetNoFallback(C,A);h?(o=s,I=h,n.presetUsesOverride=!0):(I=this.soundfontManager.getPreset(s,A),o=I.bank,n.presetUsesOverride=!1)}else I=this.soundfontManager.getPreset(s,A),o=I.bank,n.presetUsesOverride=!1;this.setPreset(t,I),this.callEvent("programchange",{channel:t,program:I.program,bank:o,userCalled:e})}function Io(t,A){if(this.overrideSoundfont){let e=t===128?128:t-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(e,A);if(n)return n}return this.soundfontManager.getPreset(t,A)}function go(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 Co(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[m.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function Eo(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,n=t.find(s=>s.bank===e&&s.program===A.program);n!==void 0?n.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function Bo(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(n,e.preset.program)}),this.post({messageType:pA.ready,messageData:void 0}),this.sendPresetList(),p("%cSpessaSynth is ready!",r.recognized)}function Qo(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 co(){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,velocityOverride:e.velocityOverride,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:pA.synthesizerSnapshot,messageData:A})}function lo(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 n=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),n.midiControllers=A.midiControllers,n.lockedControllers=A.lockedControllers,n.customControllers=A.customControllers,n.channelVibrato=A.channelVibrato,n.lockGSNRPNParams=A.lockVibrato,n.channelTransposeKeyShift=A.channelTransposeKeyShift,n.channelOctaveTuning=A.channelOctaveTuning,n.velocityOverride=A.velocityOverride,n.lockPreset=!1,n.midiControllers[m.bankSelect]=A.bank,this.programChange(e,A.program),n.lockPreset=A.lockPreset}),p("%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 n=this.soundfontList[e],s=new Set;for(let o of n.soundfont.presets){let I=`${o.bank+n.bankOffset}-${o.program}`;s.has(I)||(s.add(I),A[I]=o.presetName)}}this.presetList=[];for(let[e,n]of Object.entries(A)){let s=e.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}}handleMessage(A,e){switch(A){case Ce.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ce.reloadSoundFont:this.reloadManager(e);break;case Ce.deleteSoundFont:this.deleteSoundFont(e);break;case Ce.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ge(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){T("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(n=>n.id===A);if(e===-1){T(`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,n){if(this.soundfontList.find(s=>s.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Ge(A),bankOffset:n}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,n)=>A.indexOf(e.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let n of this.soundfontList){let s=n.soundfont.getPresetNoFallback(A-n.bankOffset,e);if(s!==void 0)return s}if(A!==128){for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.program===e);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}else{for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.bank===128);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}}};var rt=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,e,n,s,o,I,C,h){this.sampleData=A,this.playbackStep=e,this.cursor=n,this.rootKey=s,this.loopStart=o,this.loopEnd=I,this.end=C,this.loopingMode=h,this.isLooping=this.loopingMode===1||this.loopingMode===3}},xe=class t{sample;filter=new Qe;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;realKey;constructor(A,e,n,s,o,I,C,h,B,d){this.sample=e,this.generators=B,this.modulatedGenerators=new Int16Array(B),this.modulators=d,this.velocity=s,this.midiNote=n,this.channelNumber=o,this.startTime=I,this.targetKey=C,this.realKey=h,this.volumeEnvelope=new LA(A,B[g.sustainVolEnv])}static copy(A,e){let n=A.sample,s=new rt(n.sampleData,n.playbackStep,n.cursor,n.rootKey,n.loopStart,n.loopEnd,n.end,n.loopingMode);return new t(A.volumeEnvelope.sampleRate,s,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.realKey,A.generators,A.modulators.map(o=>j.copy(o)))}};function uo(t,A,e,n,s,o,I=!1){let C,h=n.cachedVoices[A][e];return h!==void 0?h.map(B=>xe.copy(B,s)):(C=n.preset.getSamplesAndGenerators(A,e).reduce((d,c)=>{if(c.sample.sampleData===void 0)return T(`Discarding invalid sample: ${c.sample.sampleName}`),d;let l=new Int16Array(60);for(let x=0;x<60;x++)l[x]=pn(x,c.presetGenerators,c.instrumentGenerators);l[g.initialAttenuation]=Math.floor(l[g.initialAttenuation]*.4);let u=c.sample.samplePitch;l[g.overridingRootKey]>-1&&(u=l[g.overridingRootKey]);let y=A;l[g.keyNum]>-1&&(y=l[g.keyNum]);let S=c.sample.sampleLoopStartIndex,k=c.sample.sampleLoopEndIndex,w=l[g.sampleModes],G=new rt(c.sample.getAudioData(),c.sample.sampleRate/sampleRate*Math.pow(2,c.sample.samplePitchCorrection/1200),0,u,S,k,Math.floor(c.sample.sampleData.length)-1,w);return l[g.velocity]>-1&&(e=l[g.velocity]),I&&mn([{Sample:c.sample.sampleName,Generators:l,Modulators:c.modulators.map(x=>x.debugString()),Velocity:e,TargetKey:y,MidiNote:A,WorkletSample:G}]),d.push(new xe(sampleRate,G,A,e,t,s,y,o,l,c.modulators.map(x=>j.copy(x)))),d},[]),n.cachedVoices[A][e]=C.map(d=>xe.copy(d,s)),C)}var Lt=.03,Ut=1,H=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=UA,this.interpolationType=he.fourthOrder,this.processTickCallback=void 0,this.sequencer=new IA(this),this.transposition=0,this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Ut,this.midiVolume=1,this.voiceCap=Dn,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:pA.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()),p("%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]))),VA.isInitialized.then(()=>{this.postReady(),p("%cSpessaSynth is ready!",r.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:pA.ready,messageData:void 0})}debugMessage(){p({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let n=0;return this.workletProcessorChannels.forEach((s,o)=>{if(s.voices.length<1||s.isMuted)return;let I,C,h,B,d;if(this.oneOutputMode){let l=e[0];I=o%16*2,C=l[I],h=l[I+1]}else I=o%this._outputsAmount+2,C=e[I][0],h=e[I][1],B=e[0],d=e[1];let c=s.voices;s.voices=[],c.forEach(l=>{this.renderVoice(s,l,C,h,B,d),l.finished||s.voices.push(l)}),n+=s.voices.length}),n!==this.totalVoicesAmount&&(this.totalVoicesAmount=n,this.sendChannelProperties()),!0}};H.prototype.renderVoice=ts;H.prototype.releaseVoice=ss;H.prototype.voiceKilling=ns;H.prototype.getWorkletVoices=uo;H.prototype.handleMessage=is;H.prototype.sendChannelProperties=Is;H.prototype.callEvent=as;H.prototype.systemExclusive=gs;H.prototype.noteOn=Es;H.prototype.noteOff=Bs;H.prototype.polyPressure=Ds;H.prototype.killNote=hs;H.prototype.stopAll=Qs;H.prototype.stopAllChannels=cs;H.prototype.muteChannel=xs;H.prototype.setVibrato=Ns;H.prototype.disableAndLockGSNRPN=Ms;H.prototype.dataEntryCoarse=bs;H.prototype.dataEntryFine=Ls;H.prototype.createWorkletChannel=yn;H.prototype.controllerChange=ws;H.prototype.channelPressure=Ss;H.prototype.resetAllControllers=Us;H.prototype.resetControllers=Ts;H.prototype.resetParameters=Hs;H.prototype.setMasterGain=Rs;H.prototype.setMasterPan=Gs;H.prototype.setMIDIVolume=Fs;H.prototype.transposeAllChannels=ls;H.prototype.transposeChannel=us;H.prototype.setChannelTuning=ds;H.prototype.setChannelTuningSemitones=fs;H.prototype.setMasterTuning=ms;H.prototype.setModulationDepth=ps;H.prototype.pitchWheel=ys;H.prototype.setOctaveTuning=ks;H.prototype.programChange=ao;H.prototype.getPreset=Io;H.prototype.setPreset=go;H.prototype.setDrums=Co;H.prototype.reloadSoundFont=ho;H.prototype.clearSoundFont=Bo;H.prototype.setEmbeddedSoundFont=Qo;H.prototype.sendPresetList=Eo;H.prototype.sendSynthesizerSnapshot=co;H.prototype.applySynthesizerSnapshot=lo;registerProcessor(Sn,H);p("%cProcessor succesfully registered!",r.recognized); +`+this.soundFontInfo.ISBJ,delete this.soundFontInfo.ISBJ);for(let[h,B]of Object.entries(this.soundFontInfo))p(`%c"${h}": %c"${B}"`,r.info,r.recognized);let o=n.find(h=>h.header==="colh");if(!o)throw Z(),new Error("No colh chunk!");this.instrumentAmount=S(o.chunkData,4),p(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let I=DA(n,"wvpl");this.readDLSSamples(I);let C=DA(n,"lins");if(!C)throw Z(),new Error("No lins chunk!");this.readDLSInstrumentList(C),this.presets.sort((h,B)=>h.program-B.program+(h.bank-B.bank)),p(`%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),Z()}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=_s;WA.prototype.readDLSInstrument=zs;WA.prototype.readRegion=eo;WA.prototype.readLart=Ao;WA.prototype.readDLSSamples=to;var Ht=class extends de{constructor(A,e,n,s,o,I,C,h,B,d,c,l,u){super(A,I,C,h,B,d,s-e/2,o-e/2),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=c,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=u}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,n=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let s=VA.decode(n.buffer);this.sampleData=s.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 T("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let s=0;st.chunkData.currentIndex;){let o=Po(s,t.chunkData,A,e);n.push(o),s++}return n.length>1&&n.pop(),n}function Po(t,A,e,n){let s=V(A,20),o=S(A,4)*2,I=S(A,4)*2,C=S(A,4),h=S(A,4),B=S(A,4),d=A[A.currentIndex++];d===255&&(d=60);let c=Gn(A[A.currentIndex++]),l=S(A,2),u=S(A,2);return new Ht(s,o,I,C,h,B,d,c,l,u,e,t,n)}var Yt=class extends L{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 Jt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Yt(t.chunkData));return A.length>1&&A.pop(),A}var vt=class extends ue{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=S(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;nt.chunkData.currentIndex;){let n=new vt(t);if(e.length>0){let s=n.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(s,A)}e.push(n)}return e.length>1&&e.pop(),e}var qt=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;en.generatorType===g.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function oo(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new qt(t.chunkData);if(s.length>0){let I=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(I,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Pt=class extends le{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;en.generatorType===g.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ro(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Pt(t.chunkData);if(s.length>0){let I=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(I,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Kt=class extends ce{constructor(A,e){super(e),this.presetName=V(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 n=this.presetZoneStartIndex;nt.chunkData.currentIndex;){let s=new Kt(t,e);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var Vt=class extends j{constructor(A){super({srcEnum:S(A,2),dest:S(A,2),amt:jA(A[A.currentIndex++],A[A.currentIndex++]),secSrcEnum:S(A,2),transform:S(A,2)})}};function nt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Vt(t.chunkData));return A}var st=class extends re{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new Y(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw Z(),new TypeError("No data!");let n=O(this.dataArray,!1);this.verifyHeader(n,"riff");let s=V(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw Z(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",I=O(this.dataArray);for(this.verifyHeader(I,"list"),V(I.chunkData,4);I.chunkData.length>I.chunkData.currentIndex;){let z=O(I.chunkData),oA;switch(z.header.toLowerCase()){case"ifil":case"iver":oA=`${S(z.chunkData,2)}.${S(z.chunkData,2)}`,this.soundFontInfo[z.header]=oA;break;case"icmt":oA=V(z.chunkData,z.chunkData.length,void 0,!1),this.soundFontInfo[z.header]=oA;break;case"dmod":let rA=nt(z);rA.pop(),oA=`Modulators: ${rA.length}`;let CA=this.defaultModulators;this.defaultModulators=rA,this.defaultModulators.push(...CA.filter(Me=>!this.defaultModulators.find(RA=>j.isIdentical(Me,RA)))),this.soundFontInfo[z.header]=z.chunkData;break;default:oA=V(z.chunkData,z.chunkData.length),this.soundFontInfo[z.header]=oA}p(`%c"${z.header}": %c"${oA}"`,r.info,r.recognized)}let C=O(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(V(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",r.warn);let h=O(this.dataArray,!1);this.verifyHeader(h,"smpl");let B;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{B=VA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(z){throw Z(),new Error(`SF2Pack Ogg Vorbis decode error: ${z}`)}p(`%cDecoded the smpl chunk! Length: %c${B.length}`,r.info,r.value)}else B=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,p("%cLoading preset data chunk...",r.warn);let d=O(this.dataArray);this.verifyHeader(d,"list"),V(d.chunkData,4);let c=O(d.chunkData);this.verifyHeader(c,"phdr");let l=O(d.chunkData);this.verifyHeader(l,"pbag");let u=O(d.chunkData);this.verifyHeader(u,"pmod");let D=O(d.chunkData);this.verifyHeader(D,"pgen");let y=O(d.chunkData);this.verifyHeader(y,"inst");let k=O(d.chunkData);this.verifyHeader(k,"ibag");let w=O(d.chunkData);this.verifyHeader(w,"imod");let G=O(d.chunkData);this.verifyHeader(G,"igen");let x=O(d.chunkData);this.verifyHeader(x,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...no(x,B,!o));let b=Jt(G),$=nt(w),i=oo(k,b,$,this.samples);this.instruments=so(y,i);let sA=Jt(D),_=nt(u),v=ro(l,sA,_,this.instruments);this.presets.push(...io(c,v,this.defaultModulators)),this.presets.sort((z,oA)=>z.program-oA.program+(z.bank-oA.bank)),p(`%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),Z(),o&&delete this.dataArray}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Ge(t){let A=t.slice(8,12),e=new Y(A);return V(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new st(t,!1)}function ao(t,A,e=!1){let n=this.workletProcessorChannels[t];if(n===void 0){T(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(n.lockPreset)return;let s=n.drumChannel?128:n.midiControllers[m.bankSelect],o,I;if(this.overrideSoundfont){let C=s===128?128:s-this.soundfontBankOffset,h=this.overrideSoundfont.getPresetNoFallback(C,A);h?(o=s,I=h,n.presetUsesOverride=!0):(I=this.soundfontManager.getPreset(s,A),o=I.bank,n.presetUsesOverride=!1)}else I=this.soundfontManager.getPreset(s,A),o=I.bank,n.presetUsesOverride=!1;this.setPreset(t,I),this.callEvent("programchange",{channel:t,program:I.program,bank:o,userCalled:e})}function Io(t,A){if(this.overrideSoundfont){let e=t===128?128:t-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(e,A);if(n)return n}return this.soundfontManager.getPreset(t,A)}function go(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 Co(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[m.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function Eo(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,n=t.find(s=>s.bank===e&&s.program===A.program);n!==void 0?n.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function Bo(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(n,e.preset.program)}),this.post({messageType:pA.ready,messageData:void 0}),this.sendPresetList(),p("%cSpessaSynth is ready!",r.recognized)}function Qo(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 co(){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,velocityOverride:e.velocityOverride,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:pA.synthesizerSnapshot,messageData:A})}function lo(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 n=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),n.midiControllers=A.midiControllers,n.lockedControllers=A.lockedControllers,n.customControllers=A.customControllers,n.channelVibrato=A.channelVibrato,n.lockGSNRPNParams=A.lockVibrato,n.channelTransposeKeyShift=A.channelTransposeKeyShift,n.channelOctaveTuning=A.channelOctaveTuning,n.velocityOverride=A.velocityOverride,n.lockPreset=!1,n.midiControllers[m.bankSelect]=A.bank,this.programChange(e,A.program),n.lockPreset=A.lockPreset}),p("%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 n=this.soundfontList[e],s=new Set;for(let o of n.soundfont.presets){let I=`${o.bank+n.bankOffset}-${o.program}`;s.has(I)||(s.add(I),A[I]=o.presetName)}}this.presetList=[];for(let[e,n]of Object.entries(A)){let s=e.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}}handleMessage(A,e){switch(A){case Ce.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ce.reloadSoundFont:this.reloadManager(e);break;case Ce.deleteSoundFont:this.deleteSoundFont(e);break;case Ce.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ge(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){T("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(n=>n.id===A);if(e===-1){T(`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,n){if(this.soundfontList.find(s=>s.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Ge(A),bankOffset:n}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,n)=>A.indexOf(e.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let n of this.soundfontList){let s=n.soundfont.getPresetNoFallback(A-n.bankOffset,e);if(s!==void 0)return s}if(A!==128){for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.program===e);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}else{for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.bank===128);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}}};var rt=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,e,n,s,o,I,C,h){this.sampleData=A,this.playbackStep=e,this.cursor=n,this.rootKey=s,this.loopStart=o,this.loopEnd=I,this.end=C,this.loopingMode=h,this.isLooping=this.loopingMode===1||this.loopingMode===3}},xe=class t{sample;filter=new Qe;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;realKey;constructor(A,e,n,s,o,I,C,h,B,d){this.sample=e,this.generators=B,this.modulatedGenerators=new Int16Array(B),this.modulators=d,this.velocity=s,this.midiNote=n,this.channelNumber=o,this.startTime=I,this.targetKey=C,this.realKey=h,this.volumeEnvelope=new LA(A,B[g.sustainVolEnv])}static copy(A,e){let n=A.sample,s=new rt(n.sampleData,n.playbackStep,n.cursor,n.rootKey,n.loopStart,n.loopEnd,n.end,n.loopingMode);return new t(A.volumeEnvelope.sampleRate,s,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.realKey,A.generators,A.modulators.map(o=>j.copy(o)))}};function uo(t,A,e,n,s,o,I=!1){let C,h=n.cachedVoices[A][e];return h!==void 0?h.map(B=>xe.copy(B,s)):(C=n.preset.getSamplesAndGenerators(A,e).reduce((d,c)=>{if(c.sample.sampleData===void 0)return T(`Discarding invalid sample: ${c.sample.sampleName}`),d;let l=new Int16Array(60);for(let x=0;x<60;x++)l[x]=pn(x,c.presetGenerators,c.instrumentGenerators);l[g.initialAttenuation]=Math.floor(l[g.initialAttenuation]*.4);let u=c.sample.samplePitch;l[g.overridingRootKey]>-1&&(u=l[g.overridingRootKey]);let D=A;l[g.keyNum]>-1&&(D=l[g.keyNum]);let y=c.sample.sampleLoopStartIndex,k=c.sample.sampleLoopEndIndex,w=l[g.sampleModes],G=new rt(c.sample.getAudioData(),c.sample.sampleRate/sampleRate*Math.pow(2,c.sample.samplePitchCorrection/1200),0,u,y,k,Math.floor(c.sample.sampleData.length)-1,w);return l[g.velocity]>-1&&(e=l[g.velocity]),I&&mn([{Sample:c.sample.sampleName,Generators:l,Modulators:c.modulators.map(x=>x.debugString()),Velocity:e,TargetKey:D,MidiNote:A,WorkletSample:G}]),d.push(new xe(sampleRate,G,A,e,t,s,D,o,l,c.modulators.map(x=>j.copy(x)))),d},[]),n.cachedVoices[A][e]=C.map(d=>xe.copy(d,s)),C)}var Lt=.03,Ut=1,H=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=UA,this.interpolationType=he.fourthOrder,this.processTickCallback=void 0,this.sequencer=new IA(this),this.transposition=0,this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Ut,this.midiVolume=1,this.voiceCap=Dn,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:pA.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()),p("%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]))),VA.isInitialized.then(()=>{this.postReady(),p("%cSpessaSynth is ready!",r.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:pA.ready,messageData:void 0})}debugMessage(){p({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let n=0;return this.workletProcessorChannels.forEach((s,o)=>{if(s.voices.length<1||s.isMuted)return;let I,C,h,B,d;if(this.oneOutputMode){let l=e[0];I=o%16*2,C=l[I],h=l[I+1]}else I=o%this._outputsAmount+2,C=e[I][0],h=e[I][1],B=e[0],d=e[1];let c=s.voices;s.voices=[],c.forEach(l=>{this.renderVoice(s,l,C,h,B,d),l.finished||s.voices.push(l)}),n+=s.voices.length}),n!==this.totalVoicesAmount&&(this.totalVoicesAmount=n,this.sendChannelProperties()),!0}};H.prototype.renderVoice=ts;H.prototype.releaseVoice=ss;H.prototype.voiceKilling=ns;H.prototype.getWorkletVoices=uo;H.prototype.handleMessage=is;H.prototype.sendChannelProperties=Is;H.prototype.callEvent=as;H.prototype.systemExclusive=gs;H.prototype.noteOn=Es;H.prototype.noteOff=Bs;H.prototype.polyPressure=Ds;H.prototype.killNote=hs;H.prototype.stopAll=Qs;H.prototype.stopAllChannels=cs;H.prototype.muteChannel=xs;H.prototype.setVibrato=Ns;H.prototype.disableAndLockGSNRPN=Ms;H.prototype.dataEntryCoarse=bs;H.prototype.dataEntryFine=Ls;H.prototype.createWorkletChannel=yn;H.prototype.controllerChange=ws;H.prototype.channelPressure=Ss;H.prototype.resetAllControllers=Us;H.prototype.resetControllers=Ts;H.prototype.resetParameters=Hs;H.prototype.setMasterGain=Rs;H.prototype.setMasterPan=Gs;H.prototype.setMIDIVolume=Fs;H.prototype.transposeAllChannels=ls;H.prototype.transposeChannel=us;H.prototype.setChannelTuning=ds;H.prototype.setChannelTuningSemitones=fs;H.prototype.setMasterTuning=ms;H.prototype.setModulationDepth=ps;H.prototype.pitchWheel=ys;H.prototype.setOctaveTuning=ks;H.prototype.programChange=ao;H.prototype.getPreset=Io;H.prototype.setPreset=go;H.prototype.setDrums=Co;H.prototype.reloadSoundFont=ho;H.prototype.clearSoundFont=Bo;H.prototype.setEmbeddedSoundFont=Qo;H.prototype.sendPresetList=Eo;H.prototype.sendSynthesizerSnapshot=co;H.prototype.applySynthesizerSnapshot=lo;registerProcessor(Sn,H);p("%cProcessor succesfully registered!",r.recognized); diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/stereo_panner.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/stereo_panner.js index 703137eb..0456896d 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/stereo_panner.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/stereo_panner.js @@ -39,12 +39,10 @@ export function panVoice(gainLeft, // cap reverb reverbLevel = Math.min(reverbLevel, 1000); const reverbGain = reverbLevel / WORKLET_SYSTEM_REVERB_DIVIDER; - const reverbLeftGain = gainLeft * reverbGain; - const reverbRightGain = gainRight * reverbGain; for (let i = 0; i < inputBuffer.length; i++) { - reverbLeft[i] += reverbLeftGain * inputBuffer[i]; - reverbRight[i] += reverbRightGain * inputBuffer[i]; + reverbLeft[i] += reverbGain * inputBuffer[i]; + reverbRight[i] += reverbGain * inputBuffer[i]; } }