var Fs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>(typeof require<"u"?require:A)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function Hn(e){e=Math.floor(e);let A=Math.floor(e/60),t=Math.round(e-A*60);return{minutes:A,seconds:t,time:`${A.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`}}function Rs(e){return e.trim().replaceAll(".mid","").replaceAll(".kar","").replaceAll(".rmi","").replaceAll(".xmf","").replaceAll(".mxmf","").replaceAll("_"," ").trim()}function HA(e){let A="";for(let t=0;ts+o.length,0),t=new b(A),n=0;for(let s of e)t.set(s,n),n+=s.length;return t}var VA=class{ticks;messageStatusByte;messageData;constructor(A,t,n){this.ticks=A,this.messageStatusByte=t,this.messageData=n}};function xs(e){let A=e&240,t=e&15,n=t;switch(A){case 128:case 144:case 160:case 176:case 192:case 208:case 224:break;case 240:switch(t){case 0:n=-3;break;case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:n=-1;break;case 15:n=-2;break}break;default:n=-1}return n}var R={noteOff:128,noteOn:144,polyPressure:160,controllerChange:176,programChange:192,channelPressure:208,pitchBend:224,systemExclusive:240,timecode:241,songPosition:242,songSelect:243,tuneRequest:246,clock:248,start:250,continue:251,stop:252,activeSensing:254,reset:255,sequenceNumber:0,text:1,copyright:2,trackName:3,instrumentName:4,lyric:5,marker:6,cuePoint:7,programName:8,midiChannelPrefix:32,midiPort:33,endOfTrack:47,setTempo:81,smpteOffset:84,timeSignature:88,keySignature:89,sequenceSpecific:127};function Zt(e){let A=e&240,t=e&15,n=-1,s=e;return A>=128&&A<=224&&(n=t,s=A),{status:s,channel:n}}var y={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,filterResonance:71,releaseTime:72,attackTime:73,brightness:74,decayTime:75,vibratoRate:76,vibratoDepth:77,vibratoDelay:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,reverbDepth:91,tremoloDepth:92,chorusDepth:93,detuneDepth:94,phaserDepth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},Ms={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var Ns=!1,bs=!0,Xt=!1,Ls=!0;function Us(e,A,t,n){Ns=e,bs=A,Xt=t,Ls=n}function p(...e){Ns&&console.info(...e)}function Y(...e){bs&&console.warn(...e)}function Ts(...e){Ls&&console.table(...e)}function se(...e){Xt&&console.group(...e)}function yA(...e){Xt&&console.groupCollapsed(...e)}function V(){Xt&&console.groupEnd()}function oe(e,A){let t=0;for(let n=8*(A-1);n>=0;n-=8)t|=e[e.currentIndex++]<>>0}function Ft(e,A){let t=new Array(A).fill(0);for(let n=A-1;n>=0;n--)t[n]=e&255,e>>=8;return t}function vs(e,A){if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=Zt(e.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=n,t.status){case R.noteOn:let s=e.messageData[1];if(s>0)this.synth.noteOn(t.channel,e.messageData[0],s),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:s});else{this.synth.noteOff(t.channel,e.messageData[0]);let E=this.playingNotes.findIndex(a=>a.midiNote===e.messageData[0]&&a.channel===t.channel);E!==-1&&this.playingNotes.splice(E,1)}break;case R.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let o=this.playingNotes.findIndex(E=>E.midiNote===e.messageData[0]&&E.channel===t.channel);o!==-1&&this.playingNotes.splice(o,1);break;case R.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case R.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case R.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.programChange(t.channel,e.messageData[0]);break;case R.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case R.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case R.systemExclusive:this.synth.systemExclusive(e.messageData,n);break;case R.setTempo:e.messageData.currentIndex=0;let r=6e7/oe(e.messageData,3);this.oneTickToSeconds=60/(r*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),Y("invalid tempo! falling back to 120 BPM"),r=120);break;case R.timeSignature:case R.endOfTrack:case R.midiChannelPrefix:case R.songPosition:case R.activeSensing:case R.keySignature:case R.sequenceNumber:case R.sequenceSpecific:case R.text:case R.lyric:case R.copyright:case R.trackName:case R.marker:case R.cuePoint:case R.instrumentName:case R.programName:break;case R.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case R.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:Y(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(R).find(E=>R[E]===t.status)}`,I.warn,I.unrecognized,I.warn,I.value);break}t.status>=0&&t.status<128&&this.post(UA.metaEvent,[e,A])}function Hs(){for(let e=0;e<16;e++)this.synth.createWorkletChannel(!0)}function Ys(){if(!this.isActive)return;let e=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];this.playedTime+=this.oneTickToSeconds*(n.ticks-t.ticks);let s=this.loop&&(this.loopCount>0||this.loopCount===-1);if(this.midiData.loop.end<=t.ticks&&s){this.loopCount!==1/0&&(this.loopCount--,this.post(UA.loopCountChange,this.loopCount)),this.setTimeTicks(this.midiData.loop.start);return}else if(e>=this.duration){if(s){this.loopCount!==1/0&&(this.loopCount--,this.post(UA.loopCountChange,this.loopCount)),this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function Js(){let e=0,A=1/0;return this.tracks.forEach((t,n)=>{this.eventIndex[n]>=t.length||t[this.eventIndex[n]].ticks0;){let n=this.tempoChanges.find(o=>o.ticksnew Uint8Array(t)),this.lyricsTicks=[...A.lyricsTicks],this.midiPorts=[...A.midiPorts],this.trackNames=[...A.trackNames],this.midiPortChannelOffsets=[...A.midiPortChannelOffsets],this.usedChannelsOnTrack=A.usedChannelsOnTrack.map(t=>new Set(t)),this.rawMidiName=A.rawMidiName?new Uint8Array(A.rawMidiName):void 0,this.loop={...A.loop},this.keyRange={...A.keyRange},this.RMIDInfo={...A.RMIDInfo}}};var Wt=class extends at{isEmbedded=!1;constructor(A){super(),this._copyFromSequence(A),this.isEmbedded=A.embeddedSoundFont!==void 0}},Qa={duration:99999,firstNoteOn:0,loop:{start:0,end:123456},lastVoiceEventTick:123456,lyrics:[],copyright:"",midiPorts:[],midiPortChannelOffsets:[],tracksAmount:0,tempoChanges:[{ticks:0,tempo:120}],fileName:"NOT_LOADED.mid",midiName:"Loading...",rawMidiName:new Uint8Array([76,111,97,100,105,110,103,46,46,46]),usedChannelsOnTrack:[],timeDivision:0,keyRange:{min:0,max:127},isEmbedded:!1,RMIDInfo:{},bankOffset:0,midiNameUsesFileName:!1,format:0};function N(e,A){let t=0;for(let n=0;n>>0}function Xe(e,A,t){for(let n=0;n>n*8&255}function H(e,A){e[e.currentIndex++]=A&255,e[e.currentIndex++]=A>>8}function AA(e,A){Xe(e,A,4)}function Ne(e,A){let t=A<<8|e;return t>32767?t-65536:t}function Ks(e){return e>127?e-256:e}function eA(e,A,t=void 0,n=!0){if(t){let s=e.slice(e.currentIndex,e.currentIndex+A);return e.currentIndex+=A,new TextDecoder(t.replace(/[^\x20-\x7E]/g,"")).decode(s.buffer)}else{let s=!1,o="";for(let r=0;r127)&&E!==10){if(n){s=!0;continue}else if(E===0){s=!0;continue}}o+=String.fromCharCode(E)}}return o}}function It(e,A=0){let t=e.length;A>0&&(t=A);let n=new b(t);return TA(n,e,A),n}function fe(e){return It(e,e.length+1)}function TA(e,A,t=0){t>0&&A.length>t&&(A=A.slice(0,t));for(let n=0;nA.length)for(let n=0;nt.header!=="LIST"?!1:(t.chunkData.currentIndex=0,eA(t.chunkData,4)===A))}function SA(e){let A=0;for(;e;){let t=e[e.currentIndex++];if(A=A<<7|t&127,t>>7!==1)break}return A}function _t(e){let A=[e&127];for(e>>=7;e>0;)A.unshift(e&127|128),e>>=7;return A}var i={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},X=[];X[i.startAddrsOffset]={min:0,max:32768,def:0};X[i.endAddrOffset]={min:-32768,max:32768,def:0};X[i.startloopAddrsOffset]={min:-32768,max:32768,def:0};X[i.endloopAddrsOffset]={min:-32768,max:32768,def:0};X[i.startAddrsCoarseOffset]={min:0,max:32768,def:0};X[i.modLfoToPitch]={min:-12e3,max:12e3,def:0};X[i.vibLfoToPitch]={min:-12e3,max:12e3,def:0};X[i.modEnvToPitch]={min:-12e3,max:12e3,def:0};X[i.initialFilterFc]={min:1500,max:13500,def:13500};X[i.initialFilterQ]={min:0,max:960,def:0};X[i.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};X[i.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};X[i.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};X[i.modLfoToVolume]={min:-960,max:960,def:0};X[i.chorusEffectsSend]={min:0,max:1e3,def:0};X[i.reverbEffectsSend]={min:0,max:1e3,def:0};X[i.pan]={min:-500,max:500,def:0};X[i.delayModLFO]={min:-12e3,max:5e3,def:-12e3};X[i.freqModLFO]={min:-16e3,max:4500,def:0};X[i.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};X[i.freqVibLFO]={min:-16e3,max:4500,def:0};X[i.delayModEnv]={min:-32768,max:5e3,def:-32768};X[i.attackModEnv]={min:-32768,max:8e3,def:-32768};X[i.holdModEnv]={min:-12e3,max:5e3,def:-12e3};X[i.decayModEnv]={min:-12e3,max:8e3,def:-12e3};X[i.sustainModEnv]={min:0,max:1e3,def:0};X[i.releaseModEnv]={min:-7200,max:8e3,def:-12e3};X[i.keyNumToModEnvHold]={min:-1200,max:1200,def:0};X[i.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};X[i.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};X[i.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};X[i.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};X[i.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};X[i.sustainVolEnv]={min:0,max:1440,def:0};X[i.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};X[i.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};X[i.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};X[i.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};X[i.keyNum]={min:-1,max:127,def:-1};X[i.velocity]={min:-1,max:127,def:-1};X[i.initialAttenuation]={min:-250,max:1440,def:0};X[i.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};X[i.coarseTune]={min:-120,max:120,def:0};X[i.fineTune]={min:-12700,max:12700,def:0};X[i.scaleTuning]={min:0,max:1200,def:100};X[i.exclusiveClass]={min:0,max:99999,def:0};X[i.overridingRootKey]={min:-1,max:127,def:-1};X[i.sampleModes]={min:0,max:3,def:0};var U=class{generatorType=i.INVALID;generatorValue=0;constructor(A=i.INVALID,t=0,n=!0){if(this.generatorType=A,t===void 0)throw new Error("No value provided.");if(this.generatorValue=Math.round(t),n){let s=X[A];s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}}};function Os(e,A,t){let n=X[e]||{min:0,max:32768,def:0},s=A.find(C=>C.generatorType===e),o=0;s&&(o=s.generatorValue);let r=t.find(C=>C.generatorType===e),E=n.def;r&&(E=r.generatorValue);let a=E+o;return e===i.initialAttenuation?a:Math.max(n.min,Math.min(n.max,a))}var j={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},GA={linear:0,concave:1,convex:2,switch:3},_=class e{currentValue=0;sourceEnum;secondarySourceEnum;modulatorDestination;transformAmount;transformType;constructor(A,t,n,s,o){this.sourceEnum=A,this.modulatorDestination=n,this.secondarySourceEnum=t,this.transformAmount=s,this.transformType=o,this.modulatorDestination>58&&(this.modulatorDestination=i.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3,this.isEffectModulator=(this.sourceEnum===219||this.sourceEnum===221)&&this.secondarySourceEnum===0&&(this.modulatorDestination===i.reverbEffectsSend||this.modulatorDestination===i.chorusEffectsSend)}static copy(A){return new e(A.sourceEnum,A.secondarySourceEnum,A.modulatorDestination,A.transformAmount,A.transformType)}static isIdentical(A,t,n=!1){return A.sourceEnum===t.sourceEnum&&A.modulatorDestination===t.modulatorDestination&&A.secondarySourceEnum===t.secondarySourceEnum&&A.transformType===t.transformType&&(!n||A.transformAmount===t.transformAmount)}static debugString(A){function t(o,r){return Object.keys(o).find(E=>o[E]===r)}let n=t(GA,A.sourceCurveType);n+=A.sourcePolarity===0?" unipolar ":" bipolar ",n+=A.sourceDirection===0?"forwards ":"backwards ",A.sourceUsesCC?n+=t(y,A.sourceIndex):n+=t(j,A.sourceIndex);let s=t(GA,A.secSrcCurveType);return s+=A.secSrcPolarity===0?" unipolar ":" bipolar ",s+=A.secSrcCurveType===0?"forwards ":"backwards ",A.secSrcUsesCC?s+=t(y,A.secSrcIndex):s+=t(j,A.secSrcIndex),`Modulator: Source: ${n} Secondary source: ${s} Destination: ${t(i,A.modulatorDestination)} Trasform amount: ${A.transformAmount} Transform type: ${A.transformType} `}sumTransform(A){return new e(this.sourceEnum,this.secondarySourceEnum,this.modulatorDestination,this.transformAmount+A.transformAmount,this.transformType)}},Yn=960,Jn=GA.concave;function re(e,A,t,n,s){return e<<10|A<<9|t<<8|n<<7|s}var Ei=[new _(re(Jn,0,1,0,j.noteOnVelocity),0,i.initialAttenuation,Yn,0),new _(129,0,i.vibLfoToPitch,50,0),new _(re(Jn,0,1,1,y.mainVolume),0,i.initialAttenuation,Yn,0),new _(13,0,i.vibLfoToPitch,50,0),new _(526,16,i.fineTune,12700,0),new _(650,0,i.pan,500,0),new _(re(Jn,0,1,1,y.expressionController),0,i.initialAttenuation,Yn,0),new _(219,0,i.reverbEffectsSend,200,0),new _(221,0,i.chorusEffectsSend,200,0)],Bi=[new _(re(GA.linear,0,0,0,j.polyPressure),0,i.vibLfoToPitch,50,0),new _(re(GA.linear,0,0,1,y.tremoloDepth),0,i.modLfoToVolume,24,0),new _(re(GA.convex,1,0,1,y.attackTime),0,i.attackVolEnv,6e3,0),new _(re(GA.linear,1,0,1,y.releaseTime),0,i.releaseVolEnv,3600,0),new _(re(GA.linear,1,0,1,y.brightness),0,i.initialFilterFc,6e3,0),new _(re(GA.linear,1,0,1,y.filterResonance),0,i.initialFilterQ,250,0)],qs=Ei.concat(Bi);var xA=128,zt=147,be=new Int16Array(zt).fill(0),MA=(e,A)=>be[e]=A<<7;MA(y.mainVolume,100);MA(y.balance,64);MA(y.expressionController,127);MA(y.pan,64);MA(y.portamentoOnOff,127);MA(y.filterResonance,64);MA(y.releaseTime,64);MA(y.attackTime,64);MA(y.brightness,64);MA(y.decayTime,64);MA(y.vibratoRate,64);MA(y.vibratoDepth,64);MA(y.vibratoDelay,64);MA(y.generalPurposeController6,64);MA(y.generalPurposeController8,64);MA(y.RPNLsb,127);MA(y.RPNMsb,127);MA(y.NRPNLsb,127);MA(y.NRPNMsb,127);var jt=1;be[y.portamentoControl]=jt;MA(xA+j.pitchWheel,64);MA(xA+j.pitchWheelRange,2);var cA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Kn=Object.keys(cA).length,On=new Float32Array(Kn);On[cA.modulationMultiplier]=1;var YA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},Ps={velocityOverride:128};var Vs="spessasynth-worklet-system";var $t="gs";function gt(e){return e.messageData[0]===67&&e.messageData[2]===76&&e.messageData[5]===126&&e.messageData[6]===0}function An(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[3]===18&&e.messageData[4]===64&&(e.messageData[5]&16)!==0&&e.messageData[6]===21}function en(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[6]===127}function tn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===1}function nn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===3}var on=64,Zs=121;function Xs(e){return e==="gm2"?Zs:0}function jA(e){return e===120||e===126||e===127}function sn(e){return jA(e)||e===on||e===Zs}function Ct(e,A,t,n,s,o){let r=e,E=0;if(n)RA(t)?sn(A)||(r=A):t==="gm2"&&(r=A);else{let a=!0;switch(t){case"gm":p(`%cIgnoring the Bank Select (${A}), as the synth is in GM mode.`,I.info),a=!1;break;case"xg":a=sn(A),jA(A)?E=2:o%16!==9&&(E=1);break;case"gm2":A===120?E=2:o%16!==9&&(E=1)}s&&(A=128),A===128&&!s&&(A=e),a&&(r=A)}return{newBank:r,drumsStatus:E}}function Et(e,A,t,n){return n?t?jA(e)?e:128:sn(e)||A===0&&e!==0?e:sn(A)?0:A:t?128:e}function RA(e){return e==="gm2"||e==="xg"}function qn(e){return new VA(e,R.systemExclusive,new b([65,16,66,18,64,0,127,0,65,247]))}function Bt(e,A,t,n){return new VA(n,R.controllerChange|e%16,new b([A,t]))}function hi(e,A){let t=16|[1,2,3,4,5,6,7,8,0,9,10,11,12,13,14,15][e%16],n=[65,16,66,18,64,t,21,1],o=128-(64+t+21+1)%128;return new VA(A,R.systemExclusive,new b([...n,o,247]))}function Ws(e=[],A=[],t=[],n=[]){let s=this;yA("%cApplying changes to the MIDI file...",I.info),p("Desired program changes:",e),p("Desired CC changes:",A),p("Desired channels to clear:",t),p("Desired channels to transpose:",n);let o=new Set;e.forEach(M=>{o.add(M.channel)});let r="gs",E=!1,a=Array(s.tracks.length).fill(0),C=s.tracks.length;function c(){let M=0,L=1/0;return s.tracks.forEach((G,g)=>{a[g]>=G.length||G[a[g]].ticks{m(L,M)});let u=B,S=Array(u).fill(!0),w=Array(u).fill(0),k=Array(u).fill(0);for(n.forEach(M=>{let L=Math.trunc(M.keyShift),G=M.keyShift-L;w[M.channel]=L,k[M.channel]=G});C>0;){let M=c(),L=s.tracks[M];if(a[M]>=L.length){C--;continue}let G=a[M]++,g=L[G],x=()=>{L.splice(G,1),a[M]--},O=(BA,sA=0)=>{L.splice(G+sA,0,BA),a[M]++},gA=d[h[M]]||0;if(g.messageStatusByte===R.midiPort){m(M,g.messageData[0]);continue}if(g.messageStatusByte<=R.sequenceSpecific&&g.messageStatusByte>=R.sequenceNumber)continue;let tA=g.messageStatusByte&240,T=g.messageStatusByte&15,$=T+gA;if(t.indexOf($)!==-1){x();continue}switch(tA){case R.noteOn:if(S[$]){S[$]=!1,A.filter(EA=>EA.channel===$).forEach(EA=>{let v=Bt(T,EA.controllerNumber,EA.controllerValue,g.ticks);O(v)});let oA=k[$];if(oA!==0){let EA=oA*64+64,v=Bt(T,y.RPNMsb,0,g.ticks),J=Bt(T,y.RPNLsb,1,g.ticks),W=Bt($,y.dataEntryMsb,EA,g.ticks),q=Bt(T,y.lsbForControl6DataEntry,0,g.ticks);O(q),O(W),O(J),O(v)}if(o.has($)){let EA=e.find(rA=>rA.channel===$),v=Math.max(0,Math.min(EA.bank,127)),J=EA.program;p(`%cSetting %c${EA.channel}%c to %c${v}:${J}%c. Track num: %c${M}`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized);let W=new VA(g.ticks,R.programChange|T,new b([J]));O(W);let q=(rA,KA)=>{let Ie=Bt(T,rA?y.lsbForControl0BankSelect:y.bankSelect,KA,g.ticks);O(Ie)};RA(r)?EA.isDrum?(p(`%cAdding XG Drum change on track %c${M}`,I.recognized,I.value),q(!1,jA(v)?v:127),q(!0,0)):v===on?(q(!1,on),q(!0,0)):(q(!1,0),q(!0,v)):(q(!1,v),EA.isDrum&&T!==9&&(p(`%cAdding GS Drum change on track %c${M}`,I.recognized,I.value),O(hi(T,g.ticks))))}}g.messageData[0]+=w[$];break;case R.noteOff:g.messageData[0]+=w[$];break;case R.programChange:if(o.has($)){x();continue}break;case R.controllerChange:let BA=g.messageData[0];if(A.find(oA=>oA.channel===$&&BA===oA.controllerNumber)!==void 0){x();continue}if((BA===y.bankSelect||BA===y.lsbForControl0BankSelect)&&o.has($)){x();continue}break;case R.systemExclusive:if(gt(g))p("%cXG system on detected",I.info),r="xg",E=!0;else if(g.messageData[0]===67&&g.messageData[2]===76&&g.messageData[3]===8&&g.messageData[5]===3)o.has(g.messageData[4]+gA)&&x();else if(en(g)){E=!0,p("%cGS on detected!",I.recognized);break}else(tn(g)||nn(g))&&(p("%cGM/2 on detected, removing!",I.info),x(),E=!1)}}if(!E&&e.length>0){let M=0;s.tracks[0][0].messageStatusByte===R.trackName&&M++,s.tracks[0].splice(M,0,qn(0)),p("%cGS on not detected. Adding it.",I.info)}this.flush(),V()}function _s(e){let A=[],t=[],n=[],s=[];e.channelSnapshots.forEach((o,r)=>{if(o.isMuted){t.push(r);return}let E=o.channelTransposeKeyShift+o.customControllers[cA.channelTransposeFine]/100;E!==0&&A.push({channel:r,keyShift:E}),o.lockPreset&&n.push({channel:r,program:o.program,bank:o.bank,isDrum:o.drumChannel}),o.lockedControllers.forEach((a,C)=>{if(!a||C>127||C===y.bankSelect)return;let c=o.midiControllers[C]>>7;s.push({channel:r,controllerNumber:C,controllerValue:c})})}),this.modifyMIDI(n,s,t,A)}var fA={name:"INAM",album:"IPRD",album2:"IALB",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"},Le="utf-8",ci="Created using SpessaSynth";function zs(e,A,t=0,n="Shift_JIS",s={},o=!0){let r=this;if(se("%cWriting the RMIDI File...",I.info),p(`%cConfiguration: Bank offset: %c${t}%c, encoding: %c${n}`,I.info,I.value,I.info,I.value),p("metadata",s),p("Initial bank offset",r.bankOffset),o){let w=function(){let G=0,g=1/0;return r.tracks.forEach((x,O)=>{u[O]>=x.length||x[u[O]].ticksg>G?g:G),L=[];for(let G=0;G0;){let G=w(),g=r.tracks[G];if(u[G]>=g.length){S--;continue}let x=g[u[G]];u[G]++;let O=r.midiPortChannelOffsets[k[G]];if(x.messageStatusByte===R.midiPort){k[G]=x.messageData[0];continue}let gA=x.messageStatusByte&240;if(gA!==R.controllerChange&&gA!==R.programChange&&gA!==R.systemExclusive)continue;if(gA===R.systemExclusive){if(!An(x)){gt(x)?B="xg":en(x)?B="gs":tn(x)?(B="gm",m.push({tNum:G,e:x})):nn(x)&&(B="gm2");continue}let oA=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][x.messageData[5]&15]+O;L[oA].drums=!!(x.messageData[7]>0&&x.messageData[5]>>4);continue}let tA=(x.messageStatusByte&15)+O,T=L[tA];if(gA===R.programChange){let oA=RA(B),EA=x.messageData[0];T.drums?A.presets.findIndex(q=>q.program===EA&&q.isDrumPreset(oA,!0))===-1&&(x.messageData[0]=A.presets.find(q=>q.isDrumPreset(oA))?.program||0,p(`%cNo drum preset %c${EA}%c. Channel %c${tA}%c. Changing program to ${x.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)):A.presets.findIndex(q=>q.program===EA&&!q.isDrumPreset(oA))===-1&&(x.messageData[0]=A.presets.find(q=>!q.isDrumPreset(oA))?.program||0,p(`%cNo preset %c${EA}%c. Channel %c${tA}%c. Changing program to ${x.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)),T.program=x.messageData[0];let v=Math.max(0,T.lastBank?.messageData[1]-r.bankOffset),J=T?.lastBankLSB?.messageData[1]-r.bankOffset||0;if(T.lastBank===void 0)continue;let W=Et(v,J,T.drums,oA);if(A.presets.findIndex(q=>q.bank===W&&q.program===x.messageData[0])===-1){let q=A.presets.find(rA=>rA.program===x.messageData[0])?.bank+t||t;T.lastBank.messageData[1]=q,T?.lastBankLSB?.messageData&&(T.lastBankLSB.messageData[1]=q),p(`%cNo preset %c${W}:${x.messageData[0]}%c. Channel %c${tA}%c. Changing bank to ${q}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)}else{let q=W;RA(B)&&W===128&&(W=127);let rA=(W===128?128:q)+t;T.lastBank.messageData[1]=rA,T?.lastBankLSB?.messageData&&!T.drums&&(T.lastBankLSB.messageData[1]=T.lastBankLSB.messageData[1]-r.bankOffset+t),p(`%cPreset %c${W}:${x.messageData[0]}%c exists. Channel %c${tA}%c. Changing bank to ${rA}.`,I.info,I.recognized,I.info,I.recognized,I.info)}continue}let $=x.messageData[0]===y.lsbForControl0BankSelect;if(x.messageData[0]!==y.bankSelect&&!$)continue;T.hasBankSelect=!0;let BA=x.messageData[1],sA=Ct(T?.lastBank?.messageData[1]||0,BA,B,$,T.drums,tA);sA.drumsStatus===2?T.drums=!0:sA.drumsStatus===1&&(T.drums=!1),$?T.lastBankLSB=x:T.lastBank=x}if(L.forEach((G,g)=>{if(G.hasBankSelect===!0)return;let x=g%16,O=R.programChange|x,gA=Math.floor(g/16)*16,tA=r.midiPortChannelOffsets.indexOf(gA),T=r.tracks.find((oA,EA)=>r.midiPorts[EA]===tA&&r.usedChannelsOnTrack[EA].has(x));if(T===void 0)return;let $=T.findIndex(oA=>oA.messageStatusByte===O);if($===-1){let oA=T.findIndex(J=>J.messageStatusByte>128&&J.messageStatusByte<240&&(J.messageStatusByte&15)===x);if(oA===-1)return;let EA=T[oA].ticks,v=A.getPreset(0,0).program;T.splice(oA,0,new VA(EA,R.programChange|x,new b([v]))),$=oA}p(`%cAdding bank select for %c${g}`,I.info,I.recognized);let BA=T[$].ticks,sA=A.getPreset(0,G.program,RA(B))?.bank+t||t;T.splice($,0,new VA(BA,R.controllerChange|x,new b([y.bankSelect,sA])))}),B!=="gs"&&!RA(B)){for(let g of m)r.tracks[g.tNum].splice(r.tracks[g.tNum].indexOf(g.e),1);let G=0;r.tracks[0][0].messageStatusByte===R.trackName&&G++,r.tracks[0].splice(G,0,qn(0))}}let E=new b(r.writeMIDI().buffer),a=[It("INFO")],C=new TextEncoder;if(a.push(z(fA.software,C.encode("SpessaSynth"),!0)),s.name!==void 0?(a.push(z(fA.name,C.encode(s.name),!0)),n=Le):a.push(z(fA.name,r.rawMidiName,!0)),s.creationDate!==void 0)n=Le,a.push(z(fA.creationDate,C.encode(s.creationDate),!0));else{let B=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});a.push(z(fA.creationDate,fe(B),!0))}if(s.comment!==void 0&&(n=Le,a.push(z(fA.comment,C.encode(s.comment)))),s.engineer!==void 0&&a.push(z(fA.engineer,C.encode(s.engineer),!0)),s.album!==void 0&&(n=Le,a.push(z(fA.album,C.encode(s.album),!0)),a.push(z(fA.album2,C.encode(s.album),!0))),s.artist!==void 0&&(n=Le,a.push(z(fA.artist,C.encode(s.artist),!0))),s.genre!==void 0&&(n=Le,a.push(z(fA.genre,C.encode(s.genre),!0))),s.picture!==void 0&&a.push(z(fA.picture,new Uint8Array(s.picture))),s.copyright!==void 0)n=Le,a.push(z(fA.copyright,C.encode(s.copyright),!0));else{let B=r.copyright.length>0?r.copyright:ci;a.push(z(fA.copyright,fe(B)))}let c=new b(2);Xe(c,t,2),a.push(z(fA.bankOffset,c)),s.midiEncoding!==void 0&&(a.push(z(fA.midiEncoding,C.encode(s.midiEncoding))),n=Le),a.push(z(fA.encoding,fe(n)));let h=FA(a),d=FA([It("RMID"),z("data",E),z("LIST",h),e]);return p("%cFinished!",I.info),V(),z("RIFF",d)}function js(){let e=this;if(!e.tracks)throw new Error("MIDI has no tracks!");let A=[];for(let s of e.tracks){let o=[],r=0,E;for(let a of s){let C=a.ticks-r,c;a.messageStatusByte<=R.sequenceSpecific?c=[255,a.messageStatusByte,..._t(a.messageData.length),...a.messageData]:a.messageStatusByte===R.systemExclusive?c=[240,..._t(a.messageData.length),...a.messageData]:(c=[],E!==a.messageStatusByte&&(E=a.messageStatusByte,c.push(a.messageStatusByte)),c.push(...a.messageData)),o.push(..._t(C)),o.push(...c),r+=C}A.push(new Uint8Array(o))}function t(s,o){for(let r=0;rd>h?d:h),n=[];for(let h=0;h{E[m]>=B.length||B[E[m]].ticks{o(h)});a>0;){let h=C(),d=A.tracks[h];if(E[h]>=d.length){a--;continue}let B=d[E[h]];if(E[h]++,B.messageStatusByte===R.midiPort){c[h]=B.messageData[0];continue}let m=B.messageStatusByte&240;if(m!==R.noteOn&&m!==R.controllerChange&&m!==R.programChange&&m!==R.systemExclusive)continue;let u=(B.messageStatusByte&15)+A.midiPortChannelOffsets[c[h]]||0,S=n[u];switch(m){case R.programChange:S.program=B.messageData[0],o(S);break;case R.controllerChange:let w=B.messageData[0]===y.lsbForControl0BankSelect;if(B.messageData[0]!==y.bankSelect&&!w||s==="gs"&&S.drums)continue;let k=B.messageData[1],M=Math.max(0,k-A.bankOffset);switch(w?S.bankLSB=M:S.bank=M,Ct(S.bank,M,s,w,S.drums,u).drumsStatus){case 0:break;case 1:S.drums=!1,o(S);break;case 2:S.drums=!0,o(S);break}break;case R.noteOn:if(B.messageData[1]===0)continue;r[S.string].add(`${B.messageData[0]}-${B.messageData[1]}`);break;case R.systemExclusive:if(!An(B)){gt(B)&&(s="xg",p("%cXG on detected!",I.recognized));continue}let G=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][B.messageData[5]&15]+A.midiPortChannelOffsets[c[h]],g=!!(B.messageData[7]>0&&B.messageData[5]>>4);S=n[G],S.drums=g,o(S);break}}for(let h of Object.keys(r))r[h].size===0&&(p(`%cDetected change but no keys for %c${h}`,I.info,I.value),delete r[h]);return V(),r}var ge=class e extends at{embeddedSoundFont=void 0;tracks=[];isDLSRMIDI=!1;static copyFrom(A){let t=new e;return t._copyFromSequence(A),t.isDLSRMIDI=A.isDLSRMIDI,t.embeddedSoundFont=A.embeddedSoundFont?A.embeddedSoundFont.slice(0):void 0,t.tracks=A.tracks.map(n=>[...n]),t}_parseInternal(){se("%cInterpreting MIDI events...",I.info);let A=!1;this.keyRange={max:0,min:127};let t=[],n=!1;typeof this.RMIDInfo.ICOP<"u"&&(n=!0);let s=!1;typeof this.RMIDInfo.INAM<"u"&&(s=!0);let o=null,r=null;for(let c=0;c=128&&u.messageStatusByte<240){B=!0;for(let w=0;wthis.lastVoiceEventTick&&(this.lastVoiceEventTick=u.ticks),u.messageStatusByte&240){case R.controllerChange:switch(u.messageData[0]){case 2:case 116:o=u.ticks;break;case 4:case 117:r===null?r=u.ticks:r=0;break;case 0:this.isDLSRMIDI&&u.messageData[1]!==0&&u.messageData[1]!==127&&(p("%cDLS RMIDI with offset 1 detected!",I.recognized),this.bankOffset=1)}break;case R.noteOn:d.add(u.messageStatusByte&15);let w=u.messageData[0];this.keyRange.min=Math.min(this.keyRange.min,w),this.keyRange.max=Math.max(this.keyRange.max,w);break}}u.messageData.currentIndex=0;let S=eA(u.messageData,u.messageData.length);switch(u.messageData.currentIndex=0,u.messageStatusByte){case R.setTempo:u.messageData.currentIndex=0,this.tempoChanges.push({ticks:u.ticks,tempo:6e7/oe(u.messageData,3)}),u.messageData.currentIndex=0;break;case R.marker:switch(S.trim().toLowerCase()){default:break;case"start":case"loopstart":o=u.ticks;break;case"loopend":r=u.ticks}u.messageData.currentIndex=0;break;case R.copyright:n||(u.messageData.currentIndex=0,t.push(eA(u.messageData,u.messageData.length,void 0,!1)),u.messageData.currentIndex=0);break;case R.lyric:if(S.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,p("%cKaraoke MIDI detected!",I.recognized)),this.isKaraokeFile)u.messageStatusByte=R.text;else{this.lyrics.push(u.messageData),this.lyricsTicks.push(u.ticks);break}case R.text:let k=S.trim();k.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,p("%cKaraoke MIDI detected!",I.recognized)):this.isKaraokeFile&&(k.startsWith("@T")||k.startsWith("@A")?A?t.push(k.substring(2).trim()):(this.midiName=k.substring(2).trim(),A=!0,s=!0,this.rawMidiName=It(this.midiName)):k[0]!=="@"&&(this.lyrics.push(Gs(u.messageData)),this.lyricsTicks.push(u.ticks)));break;case R.trackName:break}}this.usedChannelsOnTrack.push(d),this.trackNames[c]="";let m=h.find(u=>u.messageStatusByte===R.trackName);if(m){m.messageData.currentIndex=0;let u=eA(m.messageData,m.messageData.length);this.trackNames[c]=u,B||t.push(u)}}this.tempoChanges.reverse(),p("%cCorrecting loops, ports and detecting notes...",I.info);let E=[];for(let c of this.tracks){let h=c.find(d=>(d.messageStatusByte&240)===R.noteOn);h&&E.push(h.ticks)}this.firstNoteOn=Math.min(...E),p(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,I.info,I.recognized,I.info),o!==null&&r===null?(o=this.firstNoteOn,r=this.lastVoiceEventTick):(o===null&&(o=this.firstNoteOn),(r===null||r===0)&&(r=this.lastVoiceEventTick)),this.loop={start:o,end:r},p(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,I.info,I.recognized,I.info,I.recognized);let a=0;this.midiPorts=[],this.midiPortChannelOffsets=[];for(let c=0;cc&&(C=c);if(C===1/0&&(C=0),this.midiPorts=this.midiPorts.map(c=>c===-1?C:c),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?p("%cNo additional MIDI Ports detected.",I.info):(this.isMultiPort=!0,p("%cMIDI Ports detected!",I.recognized)),!s)if(this.tracks.length>1){if(this.tracks[0].find(c=>c.messageStatusByte>=R.noteOn&&c.messageStatusByteh.messageStatusByte===R.trackName);c&&(this.rawMidiName=c.messageData,c.messageData.currentIndex=0,this.midiName=eA(c.messageData,c.messageData.length,void 0,!1))}}else{let c=this.tracks[0].find(h=>h.messageStatusByte===R.trackName);c&&(this.rawMidiName=c.messageData,c.messageData.currentIndex=0,this.midiName=eA(c.messageData,c.messageData.length,void 0,!1))}if(n||(this.copyright=t.map(c=>c.trim().replace(/(\r?\n)+/g,` `)).filter(c=>c.length>0).join(` `)||""),this.midiName=this.midiName.trim(),this.midiNameUsesFileName=!1,this.midiName.length===0){p("%cNo name detected. Using the alt name!",I.info),this.midiName=Rs(this.fileName),this.midiNameUsesFileName=!0,this.rawMidiName=new Uint8Array(this.midiName.length);for(let c=0;cc[0].ticks===0)||this.tracks[0].unshift(new VA(0,R.trackName,new b(this.rawMidiName.buffer))),this.duration=this.MIDIticksToSeconds(this.lastVoiceEventTick),p("%cSuccess!",I.recognized),V()}flush(){for(let A of this.tracks)A.sort((t,n)=>t.ticks-n.ticks);this._parseInternal()}};ge.prototype.writeMIDI=js;ge.prototype.modifyMIDI=Ws;ge.prototype.applySnapshotToMIDI=_s;ge.prototype.writeRMIDI=zs;ge.prototype.getUsedProgramsAndKeys=$s;var Pn;(()=>{var e=Uint8Array,A=Uint16Array,t=Int32Array,n=new e([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),s=new e([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),o=new e([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),r=function(v,J){for(var W=new A(31),q=0;q<31;++q)W[q]=J+=1<>1|(k&21845)<<1,m=(m&52428)>>2|(m&13107)<<2,m=(m&61680)>>4|(m&3855)<<4,B[k]=((m&65280)>>8|(m&255)<<8)>>1;var m,k,u=function(v,J,W){for(var q=v.length,rA=0,KA=new A(J);rA>le]=$e}else for(ce=new A(q),rA=0;rA>15-v[rA]);return ce},S=new e(288);for(k=0;k<144;++k)S[k]=8;var k;for(k=144;k<256;++k)S[k]=9;var k;for(k=256;k<280;++k)S[k]=7;var k;for(k=280;k<288;++k)S[k]=8;var k,w=new e(32);for(k=0;k<32;++k)w[k]=5;var k,M=u(S,9,1),L=u(w,5,1),G=function(v){for(var J=v[0],W=1;WJ&&(J=v[W]);return J},g=function(v,J,W){var q=J/8|0;return(v[q]|v[q+1]<<8)>>(J&7)&W},x=function(v,J){var W=J/8|0;return(v[W]|v[W+1]<<8|v[W+2]<<16)>>(J&7)},O=function(v){return(v+7)/8|0},gA=function(v,J,W){return(J==null||J<0)&&(J=0),(W==null||W>v.length)&&(W=v.length),new e(v.subarray(J,W))},tA=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],T=function(v,J,W){var q=new Error(J||tA[v]);if(q.code=v,Error.captureStackTrace&&Error.captureStackTrace(q,T),!W)throw q;return q},$=function(v,J,W,q){var rA=v.length,KA=q?q.length:0;if(!rA||J.f&&!J.l)return W||new e(0);var Ie=!W,ce=Ie||J.i!=2,le=J.i;Ie&&(W=new e(rA*3));var $e=function(Kt){var Me=W.length;if(Kt>Me){var yt=new e(Math.max(Me*2,Kt));yt.set(W),W=yt}},pe=J.f||0,aA=J.p||0,QA=J.b||0,Qe=J.l,XA=J.d,Re=J.m,Ge=J.n,dt=rA*8;do{if(!Qe){pe=g(v,aA,1);var At=g(v,aA+1,3);if(aA+=3,At)if(At==1)Qe=M,XA=L,Re=9,Ge=5;else if(At==2){var ut=g(v,aA,31)+257,kn=g(v,aA+10,15)+4,wn=ut+g(v,aA+5,31)+1;aA+=14;for(var et=new e(wn),xe=new e(19),WA=0;WA>4;if(OA<16)et[WA++]=OA;else{var ye=0,mt=0;for(OA==16?(mt=3+g(v,aA,3),aA+=2,ye=et[WA-1]):OA==17?(mt=3+g(v,aA,7),aA+=3):OA==18&&(mt=11+g(v,aA,127),aA+=7);mt--;)et[WA++]=ye}}var Rn=et.subarray(0,ut),Se=et.subarray(ut);Re=G(Rn),Ge=G(Se),Qe=u(Rn,Re,1),XA=u(Se,Ge,1)}else T(1);else{var OA=O(aA)+4,Ht=v[OA-4]|v[OA-3]<<8,Yt=OA+Ht;if(Yt>rA){le&&T(0);break}ce&&$e(QA+Ht),W.set(v.subarray(OA,Yt),QA),J.b=QA+=Ht,J.p=aA=Yt*8,J.f=pe;continue}if(aA>dt){le&&T(0);break}}ce&&$e(QA+131072);for(var ds=(1<>4;if(aA+=ye&15,aA>dt){le&&T(0);break}if(ye||T(2),qe<256)W[QA++]=qe;else if(qe==256){Jt=aA,Qe=null;break}else{var Gn=qe-254;if(qe>264){var WA=qe-257,De=n[WA];Gn=g(v,aA,(1<>4;nt||T(3),aA+=nt&15;var Se=h[Pe];if(Pe>3){var De=s[Pe];Se+=x(v,aA)&(1<dt){le&&T(0);break}ce&&$e(QA+131072);var pt=QA+Gn;if(QAVn[u]===a);else{let u=SA(E);a=eA(E,u),C=a}let m=SA(E);if(m===0){let u=SA(E),S=E.slice(E.currentIndex,E.currentIndex+u);E.currentIndex+=u,SA(S)<4?this.metadata[C]=eA(S,u-1):this.metadata[C]=S.slice(S.currentIndex)}else Y(`International content: ${m}`),E.currentIndex+=SA(E)}let c=r.currentIndex,h=SA(r),d=r.slice(r.currentIndex,c+h);if(r.currentIndex=c+h,h>0)for(this.packedContent=!0;d.currentIndexZn[S]===u)}}else for(this.resourceFormat="folder";this.nodeData.currentIndex{let C=(c,h)=>{a.metadata[c]!==void 0&&typeof a.metadata[c]=="string"&&(e.RMIDInfo[h]=a.metadata[c])};if(C("nodeName",fA.name),C("title",fA.name),C("copyrightNotice",fA.copyright),C("comment",fA.comment),a.isFile)switch(a.resourceFormat){default:return;case"DLS1":case"DLS2":case"DLS22":case"mobileDLS":p("%cFound embedded DLS!",I.recognized),e.embeddedSoundFont=a.nodeData.buffer;break;case"StandardMIDIFile":case"StandardMIDIFileType1":p("%cFound embedded MIDI!",I.recognized),r=a.nodeData;break}else for(let c of a.innerNodes)E(c)};return E(o),V(),r}var an=class extends ge{constructor(A,t=""){super(),yA("%cParsing MIDI File...",I.info),this.fileName=t;let n=new b(A),s,o=eA(n,4);if(n.currentIndex-=4,o==="RIFF"){n.currentIndex+=8;let E=eA(n,4,void 0,!1);if(E!=="RMID")throw V(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${E}"`);let a=IA(n);if(a.header!=="data")throw V(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${E}"`);for(s=a.chunkData;n.currentIndex<=n.length;){let C=n.currentIndex,c=IA(n,!0);if(c.header==="RIFF"){let h=eA(c.chunkData,4).toLowerCase();h==="sfbk"||h==="sfpk"||h==="dls "?(p("%cFound embedded soundfont!",I.recognized),this.embeddedSoundFont=n.slice(C,C+c.size).buffer):Y(`Unknown RIFF chunk: "${h}"`),h==="dls "&&(this.isDLSRMIDI=!0)}else if(c.header==="LIST"&&eA(c.chunkData,4)==="INFO"){for(p("%cFound RMIDI INFO chunk!",I.recognized),this.RMIDInfo={};c.chunkData.currentIndex<=c.size;){let d=IA(c.chunkData,!0);this.RMIDInfo[d.header]=d.chunkData}this.RMIDInfo.ICOP&&(this.copyright=eA(this.RMIDInfo.ICOP,this.RMIDInfo.ICOP.length,void 0,!1).replaceAll(` `," ")),this.RMIDInfo.INAM&&(this.rawMidiName=this.RMIDInfo[fA.name],this.midiName=eA(this.rawMidiName,this.rawMidiName.length,void 0,!1).replaceAll(` `," ")),this.RMIDInfo.IALB&&!this.RMIDInfo.IPRD&&(this.RMIDInfo.IPRD=this.RMIDInfo.IALB),this.RMIDInfo.IPRD&&!this.RMIDInfo.IALB&&(this.RMIDInfo.IALB=this.RMIDInfo.IPRD),this.bankOffset=1,this.RMIDInfo[fA.bankOffset]&&(this.bankOffset=N(this.RMIDInfo[fA.bankOffset],2))}}this.isDLSRMIDI&&(this.bankOffset=0),this.embeddedSoundFont===void 0&&(this.bankOffset=0)}else o==="XMF_"?s=Ao(this,n):s=n;let r=this._readMIDIChunk(s);if(r.type!=="MThd")throw V(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${r.type}"`);if(r.size!==6)throw V(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${r.size}`);this.format=oe(r.data,2),this.tracksAmount=oe(r.data,2),this.timeDivision=oe(r.data,2);for(let E=0;E0&&(h+=this.tracks[E-1][this.tracks[E-1].length-1].ticks);C.data.currentIndex>4],c=B;break}let S=new b(u);S.set(C.data.slice(C.data.currentIndex,C.data.currentIndex+u),0);let w=new VA(h,B,S);a.push(w),C.data.currentIndex+=u}this.tracks.push(a),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,I.info,I.value,I.info,I.value)}p("%cAll tracks parsed correctly!",I.recognized),this._parseInternal(),V(),p(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}%c, total seconds time: %c${this.duration}`,I.info,I.recognized,I.info,I.recognized)}_readMIDIChunk(A){let t={};t.type=eA(A,4),t.size=oe(A,4),t.data=new b(t.size);let n=A.slice(A.currentIndex,A.currentIndex+t.size);return t.data.set(n,0),A.currentIndex+=t.size,t}};function eo(e,A){this.midiData.usedChannelsOnTrack[e].size!==0&&(this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(n,t)}),this.duration=this.midiData.duration,this.firstNoteTime=this.midiData.MIDIticksToSeconds(this.midiData.firstNoteOn),p(`%cTotal song time: ${Hn(Math.ceil(this.duration)).time}`,I.recognized),this.post(UA.songChange,[this.songIndex,A]),this.duration<=1&&(Y(`%cVery short song: (${Hn(Math.round(this.duration)).time}). Disabling loop!`,I.warn),this.loop=!1),A)this.play(!0);else{let t=this.skipToFirstNoteOn?this.midiData.firstNoteOn-1:0;this.setTimeTicks(t),this.pause()}}function no(e,A=!0){if(this.songs=e.reduce((n,s)=>{if(s.duration)return n.push(ge.copyFrom(s)),n;try{n.push(new an(s.binary,s.altName||""))}catch(o){return console.error(o),this.post(UA.midiError,o),n}return n},[]),this.songs.length<1)return;this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.shuffleSongIndexes();let t=this.songs.map(n=>new Wt(n));this.post(UA.songListChange,t),this.loadCurrentSong(A)}function so(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadCurrentSong()}function oo(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadCurrentSong()}function ro(e=!0){e&&p("%cResetting all controllers!",I.info),this.callEvent("allcontrollerreset",void 0),this.setSystem($t);for(let A=0;A>7});if(this.workletProcessorChannels[A].lockedControllers[xA+j.pitchWheel]===!1){let o=this.workletProcessorChannels[A].midiControllers[xA+j.pitchWheel],r=o>>7,E=o&127;this.callEvent("pitchwheel",{channel:A,MSB:r,LSB:E})}}this.tunings=[],this.tunings=[];for(let A=0;127>A;A++)this.tunings.push([]);this.setMIDIVolume(1)}function io(){this.channelOctaveTuning.fill(0);for(let A=0;A>7):this.midiControllers[A]=t}this.channelVibrato={rate:0,depth:0,delay:0},this.holdPedal=!1,this.randomPan=!1;let e=this.customControllers[cA.channelTransposeFine];this.customControllers.set(On),this.setCustomController(cA.channelTransposeFine,e),this.resetParameters()}var Wn=new Set([y.bankSelect,y.lsbForControl0BankSelect,y.mainVolume,y.lsbForControl7MainVolume,y.pan,y.lsbForControl10Pan,y.reverbDepth,y.tremoloDepth,y.chorusDepth,y.detuneDepth,y.phaserDepth,y.soundVariation,y.filterResonance,y.releaseTime,y.attackTime,y.brightness,y.decayTime,y.vibratoRate,y.vibratoDepth,y.vibratoDelay,y.soundController10]);function ao(){this.channelOctaveTuning.fill(0),this.pitchWheel(64,0),this.channelVibrato={rate:0,depth:0,delay:0};for(let e=0;e<128;e++){let A=be[e];!Wn.has(e)&&A!==this.midiControllers[e]&&(e===y.portamentoControl?this.midiControllers[e]=jt:this.controllerChange(e,A>>7))}}function Io(){this.dataEntryState=YA.Idle,p("%cResetting Registered and Non-Registered Parameters!",I.info)}var We=be.slice(0,128);function go(e,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let t=this.synth.workletProcessorChannels.length,n=Array(t).fill(8192),s=[];for(let a=0;aa===y.dataDecrement||a===y.dataIncrement||a===y.dataEntryMsb||a===y.dataDecrement||a===y.lsbForControl6DataEntry||a===y.RPNLsb||a===y.RPNMsb||a===y.NRPNLsb||a===y.NRPNMsb||a===y.bankSelect||a===y.lsbForControl0BankSelect||a===y.resetAllControllers,r=[];for(let a=0;a=A)break}else if(this.playedTime>=e)break;let c=Zt(C.messageStatusByte),h=c.channel+(this.midiPortChannelOffsets[this.midiPorts[a]]||0);switch(c.status){case R.noteOn:r[h]===void 0&&(r[h]=Array.from(We)),r[h][y.portamentoControl]=C.messageData[0];break;case R.noteOff:break;case R.pitchBend:n[h]=C.messageData[1]<<7|C.messageData[0];break;case R.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[a].size===0)break;let B=s[h];B.program=C.messageData[0],B.actualBank=B.bank;break;case R.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[a].size===0)break;let m=C.messageData[0];if(o(m)){let u=C.messageData[1];if(m===y.bankSelect){s[h].bank=u;break}else m===y.resetAllControllers&&E(h);this.sendMIDIMessages?this.sendMIDICC(h,m,u):this.synth.controllerChange(h,m,u)}else r[h]===void 0&&(r[h]=Array.from(We)),r[h][m]=C.messageData[1];break;default:this._processEvent(C,a);break}this.eventIndex[a]++,a=this._findFirstEventIndex();let d=this.tracks[a][this.eventIndex[a]];if(d===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(d.ticks-C.ticks)}if(this.sendMIDIMessages){for(let a=0;a>7,n[a]&127),r[a]!==void 0&&r[a].forEach((C,c)=>{C!==We[c]&&!o(c)&&this.sendMIDICC(a,c,C)}),s[a].program>=0&&s[a].actualBank>=0){let C=s[a].actualBank;this.sendMIDICC(a,y.bankSelect,C),this.sendMIDIProgramChange(a,s[a].program)}}else for(let a=0;a>7,n[a]&127),r[a]!==void 0&&r[a].forEach((C,c)=>{C!==We[c]&&!o(c)&&this.synth.controllerChange(a,c,C)}),s[a].program>=0&&s[a].actualBank>=0){let C=s[a].actualBank;this.synth.controllerChange(a,y.bankSelect,C),this.synth.programChange(a,s[a].program)}return!0}function Co(e=!1){if(this.midiData!==void 0){if(e){this.pausedTime=void 0,this.currentTime=0;return}if(this.currentTime>=this.duration){this.pausedTime=void 0,this.currentTime=0;return}this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),this.sendMIDIMessages||this.playingNotes.forEach(A=>{this.synth.noteOn(A.channel,A.midiNote,A.velocity,!1,!0)}),this.setProcessHandler()}}function Eo(e){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(UA.timeChange,currentTime-this.midiData.MIDIticksToSeconds(e));let A=this._playTo(0,e);this._recalculateStartTime(this.playedTime),A&&this.play()}function Bo(e){this.absoluteStartTime=currentTime-e/this._playbackRate}var lA={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25,keyModifierManager:26,setEffectsGain:27,destroyWorklet:28},Ue={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3,midiSystem:4},ie=-1,JA={channelPropertyChange:0,eventCall:1,masterParameterChange:2,sequencerSpecific:3,synthesizerSnapshot:4,isFullyInitialized:5,soundfontError:6};function ho(e,A){switch(e){default:break;case zA.loadNewSongList:this.loadNewSongList(A[0],A[1]);break;case zA.pause:this.pause();break;case zA.play:this.play(A);break;case zA.stop:this.stop();break;case zA.setTime:this.currentTime=A;break;case zA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case zA.setPlaybackRate:this.playbackRate=A;break;case zA.setLoop:let[t,n]=A;this.loop=t,n===ie?this.loopCount=1/0:this.loopCount=n;break;case zA.changeSong:switch(A[0]){case it.forwards:this.nextSong();break;case it.backwards:this.previousSong();break;case it.shuffleOff:this.shuffleMode=!1,this.songIndex=this.shuffledSongIndexes[this.songIndex];break;case it.shuffleOn:this.shuffleMode=!0,this.shuffleSongIndexes(),this.songIndex=0,this.loadCurrentSong();break;case it.index:this.songIndex=A[1],this.loadCurrentSong();break}break;case zA.getMIDI:this.post(UA.getMIDI,this.midiData);break;case zA.setSkipToFirstNote:this.skipToFirstNoteOn=A;break;case zA.setPreservePlaybackState:this.preservePlaybackState=A}}function co(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:JA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function lo(e){this.post(UA.midiEvent,e)}function Qo(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([R.controllerChange|e,A,t])}function uo(e,A){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([R.programChange|e,A])}function fo(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([R.pitchBend|e,t,A])}function mo(){if(this.sendMIDIMessages){this.sendMIDIMessage([R.reset]);for(let e=0;e<16;e++)this.sendMIDIMessage([R.controllerChange|e,y.allSoundOff,0]),this.sendMIDIMessage([R.controllerChange|e,y.resetAllControllers,0])}}var kA=class{songs=[];songIndex=0;shuffledSongIndexes=[];synth;isActive=!1;sendMIDIMessages=!1;loopCount=1/0;eventIndex=[];playedTime=0;pausedTime=void 0;absoluteStartTime=currentTime;playingNotes=[];loop=!0;shuffleMode=!1;midiData=void 0;midiPorts=[];midiPortChannelOffset=0;midiPortChannelOffsets={};skipToFirstNoteOn=!0;preservePlaybackState=!1;constructor(A){this.synth=A}_playbackRate=1;set playbackRate(A){let t=this.currentTime;this._playbackRate=A,this.currentTime=t}get currentTime(){return this.pausedTime!==void 0?this.pausedTime:(currentTime-this.absoluteStartTime)*this._playbackRate}set currentTime(A){if(A>this.duration||A<0){this.skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this.skipToFirstNoteOn&&An);for(this.shuffledSongIndexes=[];A.length>0;){let t=A[Math.floor(Math.random()*A.length)];this.shuffledSongIndexes.push(t),A.splice(A.indexOf(t),1)}}};kA.prototype.sendMIDIMessage=lo;kA.prototype.sendMIDIReset=mo;kA.prototype.sendMIDICC=Qo;kA.prototype.sendMIDIProgramChange=uo;kA.prototype.sendMIDIPitchWheel=fo;kA.prototype.assignMIDIPort=eo;kA.prototype.post=co;kA.prototype.processMessage=ho;kA.prototype._processEvent=vs;kA.prototype._addNewMidiPort=Hs;kA.prototype.processTick=Ys;kA.prototype._findFirstEventIndex=Js;kA.prototype.loadNewSequence=to;kA.prototype.loadNewSongList=no;kA.prototype.nextSong=so;kA.prototype.previousSong=oo;kA.prototype.play=Co;kA.prototype._playTo=go;kA.prototype.setTimeTicks=Eo;kA.prototype._recalculateStartTime=Bo;function Qi(e,A){let t=0;return e.drumChannel&&(t+=5),A.isInRelease&&(t-=5),t+=A.velocity/25,t-=A.volumeEnvelope.state,A.isInRelease&&(t-=5),t-=A.volumeEnvelope.currentAttenuationDb/50,t}function po(e){let A=[];for(let n of this.workletProcessorChannels)for(let s of n.voices)if(!s.finished){let o=Qi(n,s);A.push({channel:n,voice:s,priority:o})}A.sort((n,s)=>n.priority-s.priority);let t=A.slice(0,e);for(let{channel:n,voice:s}of t){let o=n.voices.indexOf(s);o>-1&&n.voices.splice(o,1)}}var me=me!==void 0?me:{},yo=!1,So;me.isInitialized=new Promise(e=>So=e);var di=function(e){var A,t,n,s,o,r,E,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",C="",c=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");do s=a.indexOf(e.charAt(c++)),o=a.indexOf(e.charAt(c++)),r=a.indexOf(e.charAt(c++)),E=a.indexOf(e.charAt(c++)),A=s<<2|o>>4,t=(15&o)<<4|r>>2,n=(3&r)<<6|E,C+=String.fromCharCode(A),r!==64&&(C+=String.fromCharCode(t)),E!==64&&(C+=String.fromCharCode(n));while(c1&&(g.thisProgram=process.argv[1].replace(/\\/g,"/")),g.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(l){if(!(l instanceof Dt))throw l}),process.on("unhandledRejection",function(l,Q){process.exit(1)}),g.quit=function(l){process.exit(l)},g.inspect=function(){return"[Emscripten Module object]"}):T?(typeof read<"u"&&(g.read=function(Q){return read(Q)}),g.readBinary=function(Q){var f;return typeof readbuffer=="function"?new Uint8Array(readbuffer(Q)):(XA(typeof(f=read(Q,"binary"))=="object"),f)},typeof scriptArgs<"u"?g.arguments=scriptArgs:typeof arguments<"u"&&(g.arguments=arguments),typeof quit=="function"&&(g.quit=function(l){quit(l)})):(O||gA)&&(O?document.currentScript&&($=document.currentScript.src):$=self.location.href,$=$.indexOf("blob:")!==0?$.split("/").slice(0,-1).join("/")+"/":"",g.read=function(Q){var f=new XMLHttpRequest;return f.open("GET",Q,!1),f.send(null),f.responseText},gA&&(g.readBinary=function(Q){var f=new XMLHttpRequest;return f.open("GET",Q,!1),f.responseType="arraybuffer",f.send(null),new Uint8Array(f.response)}),g.readAsync=function(Q,f,D){var K=new XMLHttpRequest;K.open("GET",Q,!0),K.responseType="arraybuffer",K.onload=function(){if(K.status==200||K.status==0&&K.response){f(K.response);return}D()},K.onerror=D,K.send(null)},g.setWindowTitle=function(l){document.title=l});var sA=g.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),oA=g.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||sA);for(e in x)x.hasOwnProperty(e)&&(g[e]=x[e]);function EA(l){var Q=B;return B=B+l+15&-16,Q}function v(l){var Q=a[M>>2],f=Q+l+15&-16;return a[M>>2]=f,f>=NA&&!pt()?(a[M>>2]=Q,0):Q}function J(l,Q){return Q||(Q=16),l=Math.ceil(l/Q)*Q}function W(l){switch(l){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(l[l.length-1]==="*")return 4;if(l[0]!=="i")return 0;var Q=parseInt(l.substr(1));return XA(Q%8==0),Q/8}}function q(l){q.shown||(q.shown={}),q.shown[l]||(q.shown[l]=1,oA(l))}x=void 0;var rA={"f64-rem":function(l,Q){return l%Q},debugger:function(){}},KA=[];function Ie(l,Q){for(var f=0,D=f;D>>0)+4294967296*+(Q>>>0):+(l>>>0)+4294967296*+(0|Q)}function aA(l,Q,f){return f&&f.length?g["dynCall_"+l].apply(null,[Q].concat(f)):g["dynCall_"+l].call(null,Q)}var QA=0,Qe=0;function XA(l,Q){l||ke("Assertion failed: "+Q)}function Re(l){var Q=g["_"+l];return XA(Q,"Cannot call unknown function "+l+", make sure it is exported"),Q}var Ge={stackSave:function(){Ln()},stackRestore:function(){bn()},arrayToC:function(l){var Q,f,D=Pt(l.length);return Q=l,f=D,s.set(Q,f),D},stringToC:function(l){var Q=0;if(l!=null&&l!==0){var f=(l.length<<2)+1;Q=Pt(f),ft(l,Q,f)}return Q}},dt={string:Ge.stringToC,array:Ge.arrayToC};function At(l,Q,f,D,K){var iA=Re(l),CA=[],Z=0;if(D)for(var LA=0;LA>0]=Q;break;case"i16":r[l>>1]=Q;break;case"i32":a[l>>2]=Q;break;case"i64":tempI64=[Q>>>0,+ii(tempDouble=Q)>=1?tempDouble>0?(0|Ii(+ys(tempDouble/4294967296),4294967295))>>>0:~~+ai((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],a[l>>2]=tempI64[0],a[l+4>>2]=tempI64[1];break;case"float":c[l>>2]=Q;break;case"double":h[l>>3]=Q;break;default:ke("invalid type for setValue: "+f)}}function kn(l,Q,f){switch((Q=Q||"i8").charAt(Q.length-1)==="*"&&(Q="i32"),Q){case"i1":case"i8":return s[l>>0];case"i16":return r[l>>1];case"i32":case"i64":return a[l>>2];case"float":return c[l>>2];case"double":return h[l>>3];default:ke("invalid type for getValue: "+Q)}return null}function wn(l,Q,f,D){typeof l=="number"?(iA=!0,CA=l):(iA=!1,CA=l.length);var K=typeof Q=="string"?Q:null;if(Z=f==4?D:[typeof qt=="function"?qt:EA,Pt,EA,v][f===void 0?2:f](Math.max(CA,K?1:Q.length)),iA){for(D=Z,XA((3&Z)==0),LA=Z+(-4&CA);D>2]=0;for(LA=Z+CA;D>0]=0;return Z}if(K==="i8")return l.subarray||l.slice?o.set(l,Z):o.set(new Uint8Array(l),Z),Z;for(var iA,CA,Z,LA,mA,pA,dA,nA=0;nA>0],(D!=0||Q)&&(CA++,!Q||CA!=Q););Q||(Q=CA);var Z="";if(iA<128){for(;Q>0;)K=String.fromCharCode.apply(String,o.subarray(l,l+Math.min(Q,1024))),Z=Z?Z+K:K,l+=1024,Q-=1024;return Z}return f=l,function(mA,pA){for(var dA=pA;mA[dA];)++dA;if(dA-pA>16&&mA.subarray&&vt)return vt.decode(mA.subarray(pA,dA));for(var nA,PA,Ae,ee,te,Ze,ne="";;){if(!(nA=mA[pA++]))return ne;if(!(128&nA)){ne+=String.fromCharCode(nA);continue}if(PA=63&mA[pA++],(224&nA)==192){ne+=String.fromCharCode((31&nA)<<6|PA);continue}if(Ae=63&mA[pA++],(240&nA)==224?nA=(15&nA)<<12|PA<<6|Ae:(ee=63&mA[pA++],(248&nA)==240?nA=(7&nA)<<18|PA<<12|Ae<<6|ee:(te=63&mA[pA++],nA=(252&nA)==248?(3&nA)<<24|PA<<18|Ae<<12|ee<<6|te:(1&nA)<<30|PA<<24|Ae<<18|ee<<12|te<<6|(Ze=63&mA[pA++]))),nA<65536)ne+=String.fromCharCode(nA);else{var kt=nA-65536;ne+=String.fromCharCode(55296|kt>>10,56320|1023&kt)}}}(o,f)}function WA(l){for(var Q="";;){var f=s[l++>>0];if(!f)return Q;Q+=String.fromCharCode(f)}}function Fn(l,Q){return function(D,K,iA){for(var CA=0;CA>0]=D.charCodeAt(CA);iA||(s[K>>0]=0)}(l,Q,!1)}var vt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function tt(l,Q,f,D){if(!(D>0))return 0;for(var K=f,iA=f+D-1,CA=0;CA=55296&&Z<=57343&&(Z=65536+((1023&Z)<<10)|1023&l.charCodeAt(++CA)),Z<=127){if(f>=iA)break;Q[f++]=Z}else if(Z<=2047){if(f+1>=iA)break;Q[f++]=192|Z>>6,Q[f++]=128|63&Z}else if(Z<=65535){if(f+2>=iA)break;Q[f++]=224|Z>>12,Q[f++]=128|Z>>6&63,Q[f++]=128|63&Z}else if(Z<=2097151){if(f+3>=iA)break;Q[f++]=240|Z>>18,Q[f++]=128|Z>>12&63,Q[f++]=128|Z>>6&63,Q[f++]=128|63&Z}else if(Z<=67108863){if(f+4>=iA)break;Q[f++]=248|Z>>24,Q[f++]=128|Z>>18&63,Q[f++]=128|Z>>12&63,Q[f++]=128|Z>>6&63,Q[f++]=128|63&Z}else{if(f+5>=iA)break;Q[f++]=252|Z>>30,Q[f++]=128|Z>>24&63,Q[f++]=128|Z>>18&63,Q[f++]=128|Z>>12&63,Q[f++]=128|Z>>6&63,Q[f++]=128|63&Z}}return Q[f]=0,f-K}function ft(l,Q,f){return tt(l,o,Q,f)}function OA(l){for(var Q=0,f=0;f=55296&&D<=57343&&(D=65536+((1023&D)<<10)|1023&l.charCodeAt(++f)),D<=127?++Q:D<=2047?Q+=2:D<=65535?Q+=3:D<=2097151?Q+=4:D<=67108863?Q+=5:Q+=6}return Q}var ye=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function mt(l){for(var Q=l,f=Q>>1;r[f];)++f;if((Q=f<<1)-l>32&&ye)return ye.decode(o.subarray(l,Q));for(var D=0,K="";;){var iA=r[l+2*D>>1];if(iA==0)return K;++D,K+=String.fromCharCode(iA)}}function Rn(l,Q,f){if(f===void 0&&(f=2147483647),f<2)return 0;for(var D=Q,K=(f-=2)<2*l.length?f/2:l.length,iA=0;iA>1]=CA,Q+=2}return r[Q>>1]=0,Q-D}function Se(l){return 2*l.length}function Ht(l){for(var Q=0,f="";;){var D=a[l+4*Q>>2];if(D==0)return f;if(++Q,D>=65536){var K=D-65536;f+=String.fromCharCode(55296|K>>10,56320|1023&K)}else f+=String.fromCharCode(D)}}function Yt(l,Q,f){if(f===void 0&&(f=2147483647),f<4)return 0;for(var D=Q,K=D+f-4,iA=0;iA=55296&&CA<=57343&&(CA=65536+((1023&CA)<<10)|1023&l.charCodeAt(++iA)),a[Q>>2]=CA,(Q+=4)+4>K)break}return a[Q>>2]=0,Q-D}function ds(l){for(var Q=0,f=0;f=55296&&D<=57343&&++f,Q+=4}return Q}function us(l){var Q=OA(l)+1,f=qt(Q);return f&&tt(l,s,f,Q),f}function Jt(l){var Q=OA(l)+1,f=Pt(Q);return tt(l,s,f,Q),f}function qe(l){return l}function Gn(){var l,Q=function(){var D=Error();if(!D.stack){try{throw Error(0)}catch(K){D=K}if(!D.stack)return"(no stack trace available)"}return D.stack.toString()}();return g.extraStackTrace&&(Q+=` `+g.extraStackTrace()),(l=Q).replace(/__Z[\w\d_]+/g,function(f){var D,K=D=f;return f===K?f:f+" ["+K+"]"})}function De(l,Q){return l%Q>0&&(l+=Q-l%Q),l}function nt(l){g.buffer=n=l}function Pe(){g.HEAP8=s=new Int8Array(n),g.HEAP16=r=new Int16Array(n),g.HEAP32=a=new Int32Array(n),g.HEAPU8=o=new Uint8Array(n),g.HEAPU16=E=new Uint16Array(n),g.HEAPU32=C=new Uint32Array(n),g.HEAPF32=c=new Float32Array(n),g.HEAPF64=h=new Float64Array(n)}function pt(){var l=g.usingWasm?65536:16777216,Q=2147483648-l;if(a[M>>2]>Q)return!1;var f=NA;for(NA=Math.max(NA,16777216);NA>2];)NA=NA<=536870912?De(2*NA,l):Math.min(De((3*NA+2147483648)/4,l),Q);var D=g.reallocBuffer(NA);return D&&D.byteLength==NA?(nt(D),Pe(),!0):(NA=f,!1)}d=B=u=S=w=k=M=0,m=!1,g.reallocBuffer||(g.reallocBuffer=function(l){try{if(ArrayBuffer.transfer)Q=ArrayBuffer.transfer(n,l);else{var Q,f=s;Q=new ArrayBuffer(l),new Int8Array(Q).set(f)}}catch{return!1}return!!gi(Q)&&Q});try{(L=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{L=function(Q){return Q.byteLength}}var st=g.TOTAL_STACK||5242880,NA=g.TOTAL_MEMORY||16777216;function Kt(){return NA}function Me(l){for(;l.length>0;){var Q=l.shift();if(typeof Q=="function"){Q();continue}var f=Q.func;typeof f=="number"?Q.arg===void 0?g.dynCall_v(f):g.dynCall_vi(f,Q.arg):f(Q.arg===void 0?null:Q.arg)}}NA=0?l:Q<=32?2*Math.abs(1<=D&&(Q<=32||l>D)&&(l=-2*D+l),l}var ii=Math.abs,ai=Math.ceil,ys=Math.floor,Ii=Math.min,Ve=0,Nn=null,St=null;function qi(l){return l}g.preloadedImages={},g.preloadedAudios={};var Ss="data:application/octet-stream;base64,";function Ot(l){return String.prototype.startsWith?l.startsWith(Ss):l.indexOf(Ss)===0}(function(){var Q="main.wast",f="main.wasm",D="main.temp.asm.js";Ot(Q)||(Q=BA(Q)),Ot(f)||(f=BA(f)),Ot(D)||(D=BA(D));var K={global:null,env:null,asm2wasm:rA,parent:g},iA=null;function CA(dA){return dA}function Z(){try{if(g.wasmBinary)return new Uint8Array(g.wasmBinary);if(g.readBinary)return g.readBinary(f);throw"both async and sync fetching of the wasm failed"}catch(dA){ke(dA)}}g.asmPreload=g.asm;var LA=g.reallocBuffer,mA=function(dA){dA=De(dA,g.usingWasm?65536:16777216);var nA=g.buffer.byteLength;if(g.usingWasm)try{var PA=g.wasmMemory.grow((dA-nA)/65536);return PA!==-1?g.buffer=g.wasmMemory.buffer:null}catch{return null}};g.reallocBuffer=function(dA){return pA==="asmjs"?LA(dA):mA(dA)};var pA="";g.asm=function(dA,nA,PA){var Ae;if(!(nA=Ae=nA).table){var ee,te=g.wasmTableSize;te===void 0&&(te=1024);var Ze=g.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?Ze!==void 0?nA.table=new WebAssembly.Table({initial:te,maximum:Ze,element:"anyfunc"}):nA.table=new WebAssembly.Table({initial:te,element:"anyfunc"}):nA.table=Array(te),g.wasmTable=nA.table}return nA.memoryBase||(nA.memoryBase=g.STATIC_BASE),nA.tableBase||(nA.tableBase=0),ee=function(kt,ot,Tn){if(typeof WebAssembly!="object")return oA("no native wasm support detected"),!1;if(!(g.wasmMemory instanceof WebAssembly.Memory))return oA("no native wasm Memory in use"),!1;function Vt(de,ue){if((iA=de.exports).memory){var wt,vn,ws;wt=iA.memory,vn=g.buffer,wt.byteLength0?f:OA(l)+1,K=Array(D),iA=tt(l,K,0,K.length);return Q&&(K.length=iA),K}function Xi(l){for(var Q=[],f=0;f255&&(D&=255),Q.push(String.fromCharCode(D))}return Q.join("")}B+=16,M=EA(4),w=(u=S=J(B))+st,k=J(w),a[M>>2]=k,m=!0,g.wasmTableSize=4,g.wasmMaxTableSize=4,g.asmGlobalArg={},g.asmLibraryArg={abort:ke,assert:XA,enlargeMemory:pt,getTotalMemory:Kt,abortOnCannotGrowMemory:function(){ke("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+NA+", (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(Q,f,D){var K=Ln();try{return g.dynCall_iii(Q,f,D)}catch(iA){if(bn(K),typeof iA!="number"&&iA!=="longjmp")throw iA;g.setThrew(1,0)}},___assert_fail:function(Q,f,D,K){ke("Assertion failed: "+xe(Q)+", at: "+[f?xe(f):"unknown filename",D,K?xe(K):"unknown function"])},___setErrNo:function(Q){return g.___errno_location&&(a[g.___errno_location()>>2]=Q),Q},_abort:function(){g.abort()},_emscripten_memcpy_big:function(Q,f,D){return o.set(o.subarray(f,f+D),Q),Q},_llvm_floor_f64:ys,DYNAMICTOP_PTR:M,tempDoublePtr:_A,ABORT:QA,STACKTOP:S,STACK_MAX:w};var Ds=g.asm(g.asmGlobalArg,g.asmLibraryArg,n);g.asm=Ds,g.___errno_location=function(){return g.asm.___errno_location.apply(null,arguments)};var gi=g._emscripten_replace_memory=function(){return g.asm._emscripten_replace_memory.apply(null,arguments)};g._free=function(){return g.asm._free.apply(null,arguments)};var qt=g._malloc=function(){return g.asm._malloc.apply(null,arguments)};g._memcpy=function(){return g.asm._memcpy.apply(null,arguments)},g._memset=function(){return g.asm._memset.apply(null,arguments)},g._sbrk=function(){return g.asm._sbrk.apply(null,arguments)},g._stb_vorbis_js_channels=function(){return g.asm._stb_vorbis_js_channels.apply(null,arguments)},g._stb_vorbis_js_close=function(){return g.asm._stb_vorbis_js_close.apply(null,arguments)},g._stb_vorbis_js_decode=function(){return g.asm._stb_vorbis_js_decode.apply(null,arguments)},g._stb_vorbis_js_open=function(){return g.asm._stb_vorbis_js_open.apply(null,arguments)},g._stb_vorbis_js_sample_rate=function(){return g.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},g.establishStackSpace=function(){return g.asm.establishStackSpace.apply(null,arguments)},g.getTempRet0=function(){return g.asm.getTempRet0.apply(null,arguments)},g.runPostSets=function(){return g.asm.runPostSets.apply(null,arguments)},g.setTempRet0=function(){return g.asm.setTempRet0.apply(null,arguments)},g.setThrew=function(){return g.asm.setThrew.apply(null,arguments)};var Pt=g.stackAlloc=function(){return g.asm.stackAlloc.apply(null,arguments)},bn=g.stackRestore=function(){return g.asm.stackRestore.apply(null,arguments)},Ln=g.stackSave=function(){return g.asm.stackSave.apply(null,arguments)};function Dt(l){this.name="ExitStatus",this.message="Program terminated with exit("+l+")",this.status=l}function Un(l){l=l||g.arguments,!(Ve>0)&&(function(){if(g.preRun)for(typeof g.preRun=="function"&&(g.preRun=[g.preRun]);g.preRun.length;)oi(g.preRun.shift());Me(yt)}(),!(Ve>0)&&(g.calledRun||(g.setStatus?(g.setStatus("Running..."),setTimeout(function(){setTimeout(function(){g.setStatus("")},1),Q()},1)):Q())));function Q(){!g.calledRun&&(g.calledRun=!0,QA||(Mn||(Mn=!0,Me(xn)),Me(fs),g.onRuntimeInitialized&&g.onRuntimeInitialized(),function(){if(g.postRun)for(typeof g.postRun=="function"&&(g.postRun=[g.postRun]);g.postRun.length;)ri(g.postRun.shift());Me(ps)}()))}}function Wi(l,Q){(!Q||!g.noExitRuntime||l!==0)&&(g.noExitRuntime||(QA=!0,Qe=l,S=G,Me(ms),si=!0,g.onExit&&g.onExit(l)),g.quit(l,new Dt(l)))}function ke(l){throw g.onAbort&&g.onAbort(l),l!==void 0?(sA(l),oA(l),l=JSON.stringify(l)):l="",QA=!0,Qe=1,"abort("+l+"). Build with -s ASSERTIONS=1 for more info."}if(g.dynCall_iii=function(){return g.asm.dynCall_iii.apply(null,arguments)},g.asm=Ds,g.ccall=At,g.cwrap=function(Q,f,D,K){var iA=(D=D||[]).every(function(CA){return CA==="number"});return f!=="string"&&iA&&!K?Re(Q):function(){return At(Q,f,D,arguments,K)}},Dt.prototype=Error(),Dt.prototype.constructor=Dt,St=function l(){g.calledRun||Un(),g.calledRun||(St=l)},g.run=Un,g.abort=ke,g.preInit)for(typeof g.preInit=="function"&&(g.preInit=[g.preInit]);g.preInit.length>0;)g.preInit.pop()();g.noExitRuntime=!0,Un(),g.onRuntimeInitialized=()=>{yo=!0,So()},me.decode=function(l){return function(f){if(!yo)throw Error("SF3 decoder has not been initialized yet. Did you await synth.isReady?");var D={};function K(ot){return new Int32Array(g.HEAPU8.buffer,ot,1)[0]}function iA(ot,Tn){var Vt=new ArrayBuffer(Tn*Float32Array.BYTES_PER_ELEMENT),rt=new Float32Array(Vt);return rt.set(new Float32Array(g.HEAPU8.buffer,ot,Tn)),rt}D.open=g.cwrap("stb_vorbis_js_open","number",[]),D.close=g.cwrap("stb_vorbis_js_close","void",["number"]),D.channels=g.cwrap("stb_vorbis_js_channels","number",["number"]),D.sampleRate=g.cwrap("stb_vorbis_js_sample_rate","number",["number"]),D.decode=g.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var CA,Z,LA,mA,pA=D.open(),dA=(CA=f,Z=f.byteLength,LA=g._malloc(Z),(mA=new Uint8Array(g.HEAPU8.buffer,LA,Z)).set(new Uint8Array(CA,0,Z)),mA),nA=g._malloc(4),PA=g._malloc(4),Ae=D.decode(pA,dA.byteOffset,dA.byteLength,nA,PA);if(g._free(dA.byteOffset),Ae<0)throw D.close(pA),g._free(nA),Error("stbvorbis decode failed: "+Ae);for(var ee=D.channels(pA),te=Array(ee),Ze=new Int32Array(g.HEAPU32.buffer,K(nA),ee),ne=0;neDo?440*Math.pow(2,(e-6900)/1200):jn[~~e-In]}var As=-1660,ui=1600,$n=new Float32Array((ui-As)*100+1);for(let e=0;e<$n.length;e++){let A=(As*100+e)/100;$n[e]=Math.pow(10,-A/20)}function ae(e){return $n[Math.floor((e-As)*100)]}var ko=.01,$A=100,es=90,fi=15e-6,Ee=class e{currentSampleTime=0;sampleRate;currentAttenuationDb=$A;state=0;releaseStartDb=$A;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTargetGain=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;constructor(A,t){this.sampleRate=A,this.canEndOnSilentSustain=t/10>=es}static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=ae(A.volumeEnvelope.currentAttenuationDb),e.recalculate(A)}static recalculate(A){let t=A.volumeEnvelope,n=C=>Math.max(0,Math.floor(Ce(C)*t.sampleRate));t.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[i.initialAttenuation],1440))/10,t.attenuationTargetGain=ae(t.attenuationTarget),t.sustainDbRelative=Math.min($A,A.modulatedGenerators[i.sustainVolEnv]/10);let s=Math.min($A,t.sustainDbRelative);t.attackDuration=n(A.modulatedGenerators[i.attackVolEnv]);let o=A.modulatedGenerators[i.decayVolEnv],r=(60-A.targetKey)*A.modulatedGenerators[i.keyNumToVolEnvDecay],E=s/$A;t.decayDuration=n(o+r)*E,t.releaseDuration=n(A.modulatedGenerators[i.releaseVolEnv]),t.delayEnd=n(A.modulatedGenerators[i.delayVolEnv]),t.attackEnd=t.attackDuration+t.delayEnd;let a=(60-A.targetKey)*A.modulatedGenerators[i.keyNumToVolEnvHold];if(t.holdEnd=n(A.modulatedGenerators[i.holdVolEnv]+a)+t.attackEnd,t.decayEnd=t.decayDuration+t.holdEnd,t.state===0&&t.attackEnd===0&&(t.state=2),A.isInRelease){let C=Math.max(0,Math.min($A,t.sustainDbRelative)),c=C/$A;switch(t.decayDuration=n(o+r)*c,t.state){case 0:t.releaseStartDb=$A;break;case 1:let d=1-(t.attackEnd-t.releaseStartTimeSamples)/t.attackDuration;t.releaseStartDb=20*Math.log10(d)*-1;break;case 2:t.releaseStartDb=0;break;case 3:t.releaseStartDb=(1-(t.decayEnd-t.releaseStartTimeSamples)/t.decayDuration)*C;break;case 4:t.releaseStartDb=C;break}t.releaseStartDb=Math.max(0,Math.min(t.releaseStartDb,$A)),t.releaseStartDb>=es&&(A.finished=!0),t.currentReleaseGain=ae(t.releaseStartDb);let h=($A-t.releaseStartDb)/$A;t.releaseDuration*=h}}static apply(A,t,n,s){let o=A.volumeEnvelope,r=n/10,E=s;if(A.isInRelease){let C=o.currentSampleTime-o.releaseStartTimeSamples;if(C>=o.releaseDuration){for(let h=0;h=t.length)return;o.state++;case 1:for(;o.currentSampleTime=t.length)return}o.state++;case 2:for(;o.currentSampleTime=t.length)return;o.state++;case 3:for(;o.currentSampleTime=t.length)return;o.state++;case 4:for(o.canEndOnSilentSustain&&o.sustainDbRelative>=es&&(A.finished=!0);;)if(o.attenuation+=(o.attenuationTargetGain-o.attenuation)*E,t[a]*=o.attenuation*ae(o.sustainDbRelative+r),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++a>=t.length)return}}};function wo(e){let A=e.messageData,t=e.channelNumber,n;if(t>=0&&(n=this.workletProcessorChannels[t],n===void 0)){Y(`Trying to access channel ${t} which does not exist... ignoring!`);return}switch(e.messageType){case lA.noteOn:n.noteOn(...A);break;case lA.noteOff:n.noteOff(A);break;case lA.pitchWheel:n.pitchWheel(...A);break;case lA.ccChange:n.controllerChange(...A);break;case lA.customcCcChange:n.setCustomController(A[0],A[1]),n.updateChannelTuning();break;case lA.killNote:n.killNote(A);break;case lA.programChange:this.programChange(t,A[0],A[1]);break;case lA.channelPressure:n.channelPressure(A);break;case lA.polyPressure:n.polyPressure(...A);break;case lA.ccReset:t===ie?this.resetAllControllers():n.resetControllers();break;case lA.systemExclusive:this.systemExclusive(A[0],A[1]);break;case lA.setChannelVibrato:if(t===ie)for(let r=0;r>1&1)===1&&this.workletProcessorChannels[15+A].setOctaveTuning(a);for(let C=0;C<7;C++)(e[5]>>C&1)===1&&this.workletProcessorChannels[7+C+A].setOctaveTuning(a);for(let C=0;C<7;C++)(e[6]>>C&1)===1&&this.workletProcessorChannels[C+A].setOctaveTuning(a);p(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${a.join(" ")}`,I.info,I.value);break;default:Y(`%cUnrecognized MIDI Tuning standard message: %c${HA(e)}`,I.warn,I.unrecognized);break}break;default:Y(`%cUnrecognized MIDI Realtime/non realtime message: %c${HA(e)}`,I.warn,I.unrecognized)}break;case 65:let n=function(){Y(`%cUnrecognized Roland %cGS %cSysEx: %c${HA(e)}`,I.warn,I.recognized,I.warn,I.unrecognized)};if(e[2]===66&&e[3]===18){let s=e[7];if(e[6]===127){s===0?(p("%cGS Reset received!",I.info),this.resetAllControllers(!1),this.setSystem("gs")):s===127&&(p("%cGS system off, switching to GM2",I.info),this.resetAllControllers(!1),this.setSystem("gm2"));return}else if(e[4]===64){if((e[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A,r=this.workletProcessorChannels[o];switch(e[6]){default:n();break;case 21:let E=s>0&&e[5]>>4;r.setDrums(E),p(`%cChannel %c${o}%c ${E?"is now a drum channel":"now isn't a drum channel"}%c via: %c${HA(e)}`,I.info,I.value,I.recognized,I.info,I.value);return;case 22:let a=s-64;r.transposeChannel(a),p(`%cChannel %c${o}%c pitch shift. Semitones %c${a}%c, with %c${HA(e)}`,I.info,I.recognized,I.info,I.value,I.info,I.value);return;case 28:let C=s;C===0?(r.randomPan=!0,p(`%cRandom pan is set to %cON%c for %c${o}`,I.info,I.recognized,I.info,I.value)):(r.randomPan=!1,r.controllerChange(y.pan,C));break;case 33:r.controllerChange(y.chorusDepth,s);break;case 34:r.controllerChange(y.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 c=e.length-9,h=new Int8Array(12);for(let B=0;B=this.workletProcessorChannels.length)return;let o=this.workletProcessorChannels[s],r=e[6];switch(e[5]){case 1:o.controllerChange(y.bankSelect,r);break;case 2:o.controllerChange(y.lsbForControl0BankSelect,r);break;case 3:o.programChange(r);break;case 8:if(o.drumChannel)return;let E=r-64;o.channelTransposeKeyShift=E;break;case 11:o.controllerChange(y.mainVolume,r);break;case 14:let a=r;a===0?(o.randomPan=!0,p(`%cRandom pan is set to %cON%c for %c${s}`,I.info,I.recognized,I.info,I.value)):o.controllerChange(y.pan,a);break;case 19:o.controllerChange(y.reverbDepth,r);break;case 18:o.controllerChange(y.chorusDepth,r);break;default:Y(`%cUnrecognized Yamaha XG Part Setup: %c${e[5].toString(16).toUpperCase()}`,I.warn,I.unrecognized)}}else if(e[3]===6&&e[4]===0){let s=new Uint8Array(e.slice(5,e.length-1));this.callEvent("synthdisplay",{displayData:s,displayType:ts.XGText})}else RA(this.system)&&Y(`%cUnrecognized Yamaha XG SysEx: %c${HA(e)}`,I.warn,I.unrecognized);else RA(this.system)&&Y(`%cUnrecognized Yamaha SysEx: %c${HA(e)}`,I.warn,I.unrecognized);break}}function Go(e){this.midiVolume=Math.pow(e,Math.E),this.setMasterPan(this.pan)}function xo(e){this.masterGain=e*ns,this.setMasterPan(this.pan)}function Mo(e){this.pan=e,e=e/2+.5,this.panLeft=1-e,this.panRight=e}var Gt={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};function No(){let e=4;for(let n of this.instruments)e+=n.instrumentZones.reduce((s,o)=>(o.generators=o.generators.filter(r=>r.generatorType!==i.sampleID&&r.generatorType!==i.keyRange&&r.generatorType!==i.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift(new U(i.velRange,o.velRange.max<<8|Math.max(o.velRange.min,0),!1)),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift(new U(i.keyRange,o.keyRange.max<<8|Math.max(o.keyRange.min,0),!1)),o.isGlobal||o.generators.push(new U(i.sampleID,this.samples.indexOf(o.sample),!1)),o.generators.length*4+s),0);let A=new b(e),t=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.generatorZoneStartIndex=t;for(let o of s.generators)H(A,o.generatorType),H(A,o.generatorValue),t++}return AA(A,0),uA(new hA("igen",A.length,A))}function bo(e,A,t,n,s){let o=this.samples.map((C,c)=>{t&&C.compressSample(n,s);let h=C.getRawData();return p(`%cEncoded sample %c${c}. ${C.sampleName}%c of %c${this.samples.length}%c. Compressed: %c${C.isCompressed}%c.`,I.info,I.recognized,I.info,I.recognized,I.info,C.isCompressed?I.recognized:I.unrecognized,I.info),h}),r=this.samples.reduce((C,c,h)=>C+o[h].length+46,0),E=new b(r);this.samples.forEach((C,c)=>{let h=o[c],d,B,m=h.length;C.isCompressed?(d=E.currentIndex,B=d+h.length):(d=E.currentIndex/2,B=d+h.length/2,m+=46),e.push(d),E.set(h,E.currentIndex),E.currentIndex+=m,A.push(B)});let a=uA(new hA("smpl",E.length,E),new b([115,100,116,97]));return uA(new hA("LIST",a.length,a))}function Lo(e,A){let n=new b(46*(this.samples.length+1));return this.samples.forEach((s,o)=>{TA(n,s.sampleName,20);let r=e[o];AA(n,r);let E=A[o];AA(n,E);let a=s.sampleLoopStartIndex+r,C=s.sampleLoopEndIndex+r;s.isCompressed&&(a-=r,C-=r),AA(n,a),AA(n,C),AA(n,s.sampleRate),n[n.currentIndex++]=s.samplePitch,n[n.currentIndex++]=s.samplePitchCorrection,H(n,s.sampleLink),H(n,s.sampleType)}),TA(n,"EOS",46),uA(new hA("shdr",n.length,n))}function Uo(){let e=10;for(let n of this.instruments)e+=n.instrumentZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new b(e),t=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.modulatorZoneStartIndex=t;for(let o of s.modulators)H(A,o.sourceEnum),H(A,o.modulatorDestination),H(A,o.transformAmount),H(A,o.secondarySourceEnum),H(A,o.transformType),t++}return Xe(A,0,10),uA(new hA("imod",A.length,A))}function To(){let e=this.instruments.reduce((o,r)=>r.instrumentZones.length*4+o,4),A=new b(e),t=0,n=0,s=0;for(let o of this.instruments){o.instrumentZoneIndex=t;for(let r of o.instrumentZones)r.zoneID=t,H(A,n),H(A,s),n+=r.generators.length,s+=r.modulators.length,t++}return H(A,n),H(A,s),uA(new hA("ibag",A.length,A))}function vo(){let e=this.instruments.length*22+22,A=new b(e),t=0,n=0;for(let s of this.instruments)TA(A,s.instrumentName,20),H(A,t),t+=s.instrumentZones.length,s.instrumentID=n,n++;return TA(A,"EOI",20),H(A,t),uA(new hA("inst",A.length,A))}function Ho(){let e=4;for(let n of this.presets)e+=n.presetZones.reduce((s,o)=>(o.generators=o.generators.filter(r=>r.generatorType!==i.instrument&&r.generatorType!==i.keyRange&&r.generatorType!==i.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift(new U(i.velRange,o.velRange.max<<8|Math.max(o.velRange.min,0),!1)),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift(new U(i.keyRange,o.keyRange.max<<8|Math.max(o.keyRange.min,0),!1)),o.isGlobal||o.generators.push(new U(i.instrument,this.instruments.indexOf(o.instrument),!1)),o.generators.length*4+s),0);let A=new b(e),t=0;for(let n of this.presets)for(let s of n.presetZones){s.generatorZoneStartIndex=t;for(let o of s.generators)H(A,o.generatorType),H(A,o.generatorValue);t+=s.generators.length}return H(A,0),H(A,0),uA(new hA("pgen",A.length,A))}function Yo(){let e=10;for(let n of this.presets)e+=n.presetZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new b(e),t=0;for(let n of this.presets)for(let s of n.presetZones){s.modulatorZoneStartIndex=t;for(let o of s.modulators)H(A,o.sourceEnum),H(A,o.modulatorDestination),H(A,o.transformAmount),H(A,o.secondarySourceEnum),H(A,o.transformType),t++}return Xe(A,0,10),uA(new hA("pmod",A.length,A))}function Jo(){let e=this.presets.reduce((o,r)=>r.presetZones.length*4+o,4),A=new b(e),t=0,n=0,s=0;for(let o of this.presets){o.presetZoneStartIndex=t;for(let r of o.presetZones)r.zoneID=t,H(A,n),H(A,s),n+=r.generators.length,s+=r.modulators.length,t++}return H(A,n),H(A,s),uA(new hA("pbag",A.length,A))}function Ko(){let e=this.presets.length*38+38,A=new b(e),t=0;for(let n of this.presets)TA(A,n.presetName,20),H(A,n.program),H(A,n.bank),H(A,t),AA(A,n.library),AA(A,n.genre),AA(A,n.morphology),t+=n.presetZones.length;return TA(A,"EOP",20),H(A,0),H(A,0),H(A,t),AA(A,0),AA(A,0),AA(A,0),uA(new hA("phdr",A.length,A))}var pi={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Oo(e=pi){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");yA("%cSaving soundfont...",I.info),p(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,I.info,I.recognized,I.info,I.recognized),p("%cWriting INFO...",I.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.compress&&(this.soundFontInfo.ifil="3.0");for(let[L,G]of Object.entries(this.soundFontInfo))if(L==="ifil"||L==="iver"){let g=parseInt(G.split(".")[0]),x=parseInt(G.split(".")[1]),O=new b(4);H(O,g),H(O,x),A.push(uA(new hA(L,4,O)))}else if(L==="DMOD")A.push(uA(new hA(L,G.length,G)));else{let g=new b(G.length);TA(g,G),A.push(uA(new hA(L,G.length,g)))}let t=FA([new b([73,78,70,79]),...A]),n=uA(new hA("LIST",t.length,t));p("%cWriting SDTA...",I.info);let s=[],o=[],r=bo.call(this,s,o,e?.compress,e?.compressionQuality??.5,e.compressionFunction);p("%cWriting PDTA...",I.info),p("%cWriting SHDR...",I.info);let E=Lo.call(this,s,o);p("%cWriting IGEN...",I.info);let a=No.call(this);p("%cWriting IMOD...",I.info);let C=Uo.call(this);p("%cWriting IBAG...",I.info);let c=To.call(this);p("%cWriting INST...",I.info);let h=vo.call(this),d=Ho.call(this);p("%cWriting PMOD...",I.info);let B=Yo.call(this);p("%cWriting PBAG...",I.info);let m=Jo.call(this);p("%cWriting PHDR...",I.info);let u=Ko.call(this),S=FA([new b([112,100,116,97]),u,m,B,d,h,c,C,a,E]),w=uA(new hA("LIST",S.length,S));p("%cWriting the output file...",I.info);let k=FA([new b([115,102,98,107]),n,r,w]),M=uA(new hA("RIFF",k.length,k));return p(`%cSaved succesfully! Final file size: %c${M.length}`,I.info,I.recognized),V(),M}var xt=class{velRange={min:-1,max:127};keyRange={min:-1,max:127};isGlobal=!1;generators=[];modulators=[];get hasKeyRange(){return this.keyRange.min!==-1}get hasVelRange(){return this.velRange.min!==-1}getGeneratorValue(A,t){return this.generators.find(n=>n.generatorType===A)?.generatorValue??t}};var qA=class extends xt{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},Te=class extends xt{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var yi=new Set([i.velRange,i.keyRange,i.instrument,i.exclusiveClass,i.endOper,i.sampleModes,i.startloopAddrsOffset,i.startloopAddrsCoarseOffset,i.endloopAddrsOffset,i.endloopAddrsCoarseOffset,i.startAddrsOffset,i.startAddrsCoarseOffset,i.endAddrOffset,i.endAddrsCoarseOffset,i.initialAttenuation,i.fineTune,i.coarseTune,i.keyNumToVolEnvHold,i.keyNumToVolEnvDecay,i.keyNumToModEnvHold,i.keyNumToModEnvDecay]);function qo(e,A=!0){function t(h,d){h.push(...d.filter(B=>!h.find(m=>m.generatorType===B.generatorType)))}function n(h,d){return{min:Math.max(h.min,d.min),max:Math.min(h.max,d.max)}}function s(h,d){h.push(...d.filter(B=>!h.find(m=>_.isIdentical(B,m))))}let o=[],r=[],E=[],a={min:0,max:127},C={min:0,max:127},c=e.presetZones.find(h=>h.isGlobal);c&&(r.push(...c.generators),E.push(...c.modulators),a=c.keyRange,C=c.velRange);for(let h of e.presetZones){if(h.isGlobal)continue;let d=h.keyRange;h.hasKeyRange||(d=a);let B=h.velRange;h.hasVelRange||(B=C);let m=h.generators.map(g=>new U(g.generatorType,g.generatorValue));t(m,r);let u=[...h.modulators];s(u,E);let S=h.instrument.instrumentZones,w=[],k=[],M={min:0,max:127},L={min:0,max:127},G=S.find(g=>g.isGlobal);G&&(w.push(...G.generators),k.push(...G.modulators),M=G.keyRange,L=G.velRange);for(let g of S){if(g.isGlobal)continue;let x=g.keyRange;g.hasKeyRange||(x=M);let O=g.velRange;if(g.hasVelRange||(O=L),x=n(x,d),O=n(O,B),x.maxnew U(sA.generatorType,sA.generatorValue));t(gA,w);let tA=[...g.modulators];s(tA,k);let T=[...tA];for(let sA of u){let oA=T.findIndex(EA=>_.isIdentical(sA,EA));oA!==-1?T[oA]=T[oA].sumTransform(sA):T.push(sA)}let $=gA.map(sA=>new U(sA.generatorType,sA.generatorValue));for(let sA of m){if(sA.generatorType===i.velRange||sA.generatorType===i.keyRange||sA.generatorType===i.instrument||sA.generatorType===i.endOper||sA.generatorType===i.sampleModes)continue;let oA=gA.findIndex(EA=>EA.generatorType===sA.generatorType);if(oA!==-1){let EA=$[oA].generatorValue+sA.generatorValue;$[oA]=new U(sA.generatorType,EA)}else{let EA=X[sA.generatorType].def+sA.generatorValue;$.push(new U(sA.generatorType,EA))}}$=$.filter(sA=>sA.generatorType!==i.sampleID&&sA.generatorType!==i.keyRange&&sA.generatorType!==i.velRange&&sA.generatorType!==i.endOper&&sA.generatorType!==i.instrument&&sA.generatorValue!==X[sA.generatorType].def);let BA=new qA;BA.keyRange=x,BA.velRange=O,BA.keyRange.min===0&&BA.keyRange.max===127&&(BA.keyRange.min=-1),BA.velRange.min===0&&BA.velRange.max===127&&(BA.velRange.min=-1),BA.isGlobal=!1,BA.sample=g.sample,BA.generators=$,BA.modulators=T,o.push(BA)}}if(A){let h=new qA;h.isGlobal=!0;for(let m=0;m<58;m++){if(yi.has(m))continue;let u={},S=X[m]?.def||0;u[S]=0;for(let w of o){let k=w.generators.find(G=>G.generatorType===m);if(k){let G=k.generatorValue;u[G]===void 0?u[G]=1:u[G]++}else u[S]++;let M;switch(m){default:continue;case i.decayVolEnv:M=i.keyNumToVolEnvDecay;break;case i.holdVolEnv:M=i.keyNumToVolEnvHold;break;case i.decayModEnv:M=i.keyNumToModEnvDecay;break;case i.holdModEnv:M=i.keyNumToModEnvHold}if(w.generators.find(G=>G.generatorType===M)!==void 0){u={};break}}if(Object.keys(u).length>0){let w=Object.entries(u).reduce((M,L)=>M[1]{let L=M.generators.findIndex(G=>G.generatorType===m);L!==-1?M.generators[L].generatorValue===k&&M.generators.splice(L,1):k!==S&&M.generators.push(new U(m,S))})}}let B=o.find(m=>!m.isGlobal).modulators.map(m=>_.copy(m));for(let m of B){let u=!0;for(let S of o){if(S.isGlobal||!u)continue;S.modulators.find(k=>_.isIdentical(k,m))||(u=!1)}if(u===!0){h.modulators.push(_.copy(m));for(let S of o){let w=S.modulators.find(k=>_.isIdentical(k,m));w.transformAmount===m.transformAmount&&S.modulators.splice(S.modulators.indexOf(w),1)}}}o.splice(0,0,h)}return o}var Po=20;function gn(e,A,t,n,s,o,r){let E=r===0?0:1,a=new b(Po+E*16);AA(a,Po),H(a,A),H(a,t);let C=n*.4,c=Math.floor(C*-65536);AA(a,c),AA(a,2);let h=o-s,d=0;switch(r){default:case 0:E=0;break;case 1:d=0,E=1;break;case 3:d=1,E=1}return AA(a,E),E===1&&(AA(a,16),AA(a,d),AA(a,s),AA(a,h)),z("wsmp",a)}var P={none:0,modLfo:1,velocity:2,keyNum:3,volEnv:4,modEnv:5,pitchWheel:6,polyPressure:7,channelPressure:8,vibratoLfo:9,modulationWheel:129,volume:135,pan:138,expression:139,chorus:221,reverb:219,pitchWheelRange:256,fineTune:257,coarseTune:258},Cn=new _(219,0,i.reverbEffectsSend,1e3,0),En=new _(221,0,i.chorusEffectsSend,1e3,0),Bn=new _(129,0,i.vibLfoToPitch,0,0),hn=new _(13,0,i.vibLfoToPitch,0,0);var F={none:0,gain:1,reserved:2,pitch:3,pan:4,keyNum:5,chorusSend:128,reverbSend:129,modLfoFreq:260,modLfoDelay:261,vibLfoFreq:276,vibLfoDelay:277,volEnvAttack:518,volEnvDecay:519,volEnvRelease:521,volEnvSustain:522,volEnvDelay:523,volEnvHold:524,modEnvAttack:778,modEnvDecay:779,modEnvRelease:781,modEnvSustain:782,modEnvDelay:783,modEnvHold:784,filterCutoff:1280,filterQ:1281};var Mt=class{source;control;destination;scale;transform;constructor(A,t,n,s,o){this.source=A,this.control=t,this.destination=n,this.scale=s,this.transform=o}writeArticulator(){let A=new b(12);return H(A,this.source),H(A,this.control),H(A,this.destination),H(A,this.transform),AA(A,this.scale<<16),A}};function Vo(e,A){if(e)switch(A){default:return;case y.modulationWheel:return P.modulationWheel;case y.mainVolume:return P.volume;case y.pan:return P.pan;case y.expressionController:return P.expression;case y.chorusDepth:return P.chorus;case y.reverbDepth:return P.reverb}else switch(A){default:return;case j.noteOnKeyNum:return P.keyNum;case j.noteOnVelocity:return P.velocity;case j.noController:return P.none;case j.polyPressure:return P.polyPressure;case j.channelPressure:return P.channelPressure;case j.pitchWheel:return P.pitchWheel;case j.pitchWheelRange:return P.pitchWheelRange}}function Zo(e,A){switch(e){default:return;case i.initialAttenuation:return{dest:F.gain,amount:-A};case i.fineTune:return F.pitch;case i.pan:return F.pan;case i.keyNum:return F.keyNum;case i.reverbEffectsSend:return F.reverbSend;case i.chorusEffectsSend:return F.chorusSend;case i.freqModLFO:return F.modLfoFreq;case i.delayModLFO:return F.modLfoDelay;case i.delayVibLFO:return F.vibLfoDelay;case i.freqVibLFO:return F.vibLfoFreq;case i.delayVolEnv:return F.volEnvDelay;case i.attackVolEnv:return F.volEnvAttack;case i.holdVolEnv:return F.volEnvHold;case i.decayVolEnv:return F.volEnvDecay;case i.sustainVolEnv:return{dest:F.volEnvSustain,amount:1e3-A};case i.releaseVolEnv:return F.volEnvRelease;case i.delayModEnv:return F.modEnvDelay;case i.attackModEnv:return F.modEnvAttack;case i.holdModEnv:return F.modEnvHold;case i.decayModEnv:return F.modEnvDecay;case i.sustainModEnv:return{dest:F.modEnvSustain,amount:1e3-A};case i.releaseModEnv:return F.modEnvRelease;case i.initialFilterFc:return F.filterCutoff;case i.initialFilterQ:return F.filterQ}}function Xo(e,A){switch(e){default:return;case i.modEnvToFilterFc:return{source:P.modEnv,dest:F.filterCutoff,amt:A,isBipolar:!1};case i.modEnvToPitch:return{source:P.modEnv,dest:F.pitch,amt:A,isBipolar:!1};case i.modLfoToFilterFc:return{source:P.modLfo,dest:F.filterCutoff,amt:A,isBipolar:!0};case i.modLfoToVolume:return{source:P.modLfo,dest:F.gain,amt:A,isBipolar:!0};case i.modLfoToPitch:return{source:P.modLfo,dest:F.pitch,amt:A,isBipolar:!0};case i.vibLfoToPitch:return{source:P.vibratoLfo,dest:F.pitch,amt:A,isBipolar:!0};case i.keyNumToVolEnvHold:return{source:P.keyNum,dest:F.volEnvHold,amt:A,isBipolar:!0};case i.keyNumToVolEnvDecay:return{source:P.keyNum,dest:F.volEnvDecay,amt:A,isBipolar:!0};case i.keyNumToModEnvHold:return{source:P.keyNum,dest:F.modEnvHold,amt:A,isBipolar:!0};case i.keyNumToModEnvDecay:return{source:P.keyNum,dest:F.modEnvDecay,amt:A,isBipolar:!0};case i.scaleTuning:return{source:P.keyNum,dest:F.pitch,amt:A*128,isBipolar:!1}}}function Wo(e){let A=Zo(e.generatorType,e.generatorValue),t=A,n=0,s=e.generatorValue;A?.amount!==void 0&&(s=A.amount,t=A.dest);let o=Xo(e.generatorType,e.generatorValue);if(o!==void 0)s=o.amt,t=o.dest,n=o.source;else if(t===void 0){Y(`Invalid generator type: ${e.generatorType}`);return}return new Mt(n,0,t,s,0)}function _o(e){if(e.transformType!==0){Y("Other transform types are not supported.");return}let A=Vo(e.sourceUsesCC,e.sourceIndex),t=e.sourceCurveType,n=e.sourcePolarity,s=e.sourceDirection;if(A===void 0){Y(`Invalid source: ${e.sourceIndex}, CC: ${e.sourceUsesCC}`);return}e.modulatorDestination===i.initialAttenuation&&(s=s===1?0:1);let o=Vo(e.secSrcUsesCC,e.secSrcIndex),r=e.secSrcCurveType,E=e.secSrcPolarity,a=e.secSrcDirection;if(o===void 0){Y(`Invalid secondary source: ${e.secSrcIndex}, CC: ${e.secSrcUsesCC}`);return}let C=Zo(e.modulatorDestination,e.transformAmount),c=C,h=e.transformAmount;C?.dest!==void 0&&(c=C.dest,h=C.amount);let d=Xo(e.modulatorDestination,e.transformAmount);if(d!==void 0)h=d.amt,o=A,r=t,E=n,a=s,t=GA.linear,n=d.isBipolar?1:0,s=0,A=d.source,c=d.dest;else if(c===void 0){Y(`Invalid destination: ${e.modulatorDestination}`);return}let B=0;return B|=r<<4,B|=E<<8,B|=a<<9,B|=t,B|=n<<14,B|=s<<15,new Mt(A,o,c,h,B)}var Si=new Set([i.sampleModes,i.initialAttenuation,i.keyRange,i.velRange,i.sampleID,i.fineTune,i.coarseTune,i.startAddrsOffset,i.startAddrsCoarseOffset,i.endAddrOffset,i.endAddrsCoarseOffset,i.startloopAddrsOffset,i.startloopAddrsCoarseOffset,i.endloopAddrsOffset,i.endloopAddrsCoarseOffset,i.overridingRootKey,i.exclusiveClass]);function cn(e){for(let o=0;om.generatorType===E);if(a===void 0)continue;let C=r.generatorValue*-128,c=60/128*C,h=a.generatorValue-c,d=e.generators.indexOf(r),B=e.generators.indexOf(a);e.generators[B]=new U(E,h,!1),e.generators[d]=new U(r.generatorType,C,!1)}let A=e.generators.reduce((o,r)=>{if(Si.has(r.generatorType))return o;let E=Wo(r);return E!==void 0?(o.push(E),p("%cSucceeded converting to DLS Articulator!",I.recognized)):Y("Failed converting to DLS Articulator!"),o},[]),t=e.modulators.reduce((o,r)=>{if(_.isIdentical(r,En,!0)||_.isIdentical(r,Cn,!0)||_.isIdentical(r,Bn,!0)||_.isIdentical(r,hn,!0))return o;let E=_o(r);return E!==void 0?(o.push(E),p("%cSucceeded converting to DLS Articulator!",I.recognized)):Y("Failed converting to DLS Articulator!"),o},[]);A.push(...t);let n=new b(8);AA(n,8),AA(n,A.length);let s=A.map(o=>o.writeArticulator());return z("art2",FA([n,...s]))}function zo(e,A){let t=new b(12);H(t,Math.max(e.keyRange.min,0)),H(t,e.keyRange.max),H(t,Math.max(e.velRange.min,0)),H(t,e.velRange.max),H(t,0);let n=e.getGeneratorValue(i.exclusiveClass,0);H(t,n),H(t,0);let s=z("rgnh",t),o=e.getGeneratorValue(i.overridingRootKey,e.sample.samplePitch);e.getGeneratorValue(i.scaleTuning,A.getGeneratorValue(i.scaleTuning,100))===0&&e.keyRange.max-e.keyRange.min===0&&(o=e.keyRange.min);let E=gn(e.sample,o,e.getGeneratorValue(i.fineTune,0)+e.getGeneratorValue(i.coarseTune,0)*100+e.sample.samplePitchCorrection,e.getGeneratorValue(i.initialAttenuation,0),e.sample.sampleLoopStartIndex+e.getGeneratorValue(i.startloopAddrsOffset,0)+e.getGeneratorValue(i.startloopAddrsCoarseOffset,0)*32768,e.sample.sampleLoopEndIndex+e.getGeneratorValue(i.endloopAddrsOffset,0)+e.getGeneratorValue(i.endloopAddrsCoarseOffset,0)*32768,e.getGeneratorValue(i.sampleModes,0)),a=new b(12);H(a,0),H(a,0),AA(a,1),AA(a,this.samples.indexOf(e.sample));let C=z("wlnk",a),c=new b(0);if(e.modulators.length+e.generators.length>0){let h=cn(e);c=z("lar2",h,!1,!0)}return z("rgn2",FA([s,E,C,c]),!1,!0)}function jo(e){yA(`%cWriting %c${e.presetName}%c...`,I.info,I.recognized,I.info);let A=qo(e),t=A.reduce((d,B)=>B.isGlobal?d:d+1,0),n=new b(12);AA(n,t);let s=(e.bank&127)<<8;e.bank===128&&(s|=1<<31),AA(n,s),AA(n,e.program&127);let o=z("insh",n),r=new b(0),E=A.find(d=>d.isGlobal===!0);if(E){let d=cn(E);r=z("lar2",d,!1,!0)}let a=FA(A.reduce((d,B)=>(B.isGlobal||d.push(zo.apply(this,[B,E])),d),[])),C=z("lrgn",a,!1,!0),c=z("INAM",fe(e.presetName)),h=z("INFO",c,!1,!0);return V(),z("ins ",FA([o,C,r,h]),!1,!0)}function $o(){let e=FA(this.presets.map(A=>jo.apply(this,[A])));return z("lins",e,!1,!0)}function Ar(e){let A=new b(18);H(A,1),H(A,1),AA(A,e.sampleRate),AA(A,e.sampleRate*2),H(A,2),H(A,16);let t=z("fmt ",A),n=1;e.sampleLoopStartIndex+Math.abs(e.getAudioData().length-e.sampleLoopEndIndex)<2&&(n=0);let s=gn(e,e.samplePitch,e.samplePitchCorrection,0,e.sampleLoopStartIndex,e.sampleLoopEndIndex,n),o=e.getAudioData(),r;if(e.isCompressed){let C=new Int16Array(o.length);for(let c=0;c{let s=Ar(n);return A.push(e),e+=s.length,s});return{data:z("wvpl",FA(t),!1,!0),indexes:A}}function tr(){yA("%cSaving DLS...",I.info);let e=new b(4);AA(e,this.presets.length);let A=z("colh",e);yA("%cWriting instruments...",I.info);let t=$o.apply(this);p("%cSuccess!",I.recognized),V(),yA("%cWriting WAVE samples...",I.info);let n=er.apply(this),s=n.data,o=n.indexes;p("%cSucceeded!",I.recognized),V();let r=new b(8+4*o.length);AA(r,8),AA(r,o.length);for(let h of o)AA(r,h);let E=z("ptbl",r);this.soundFontInfo.ICMT=(this.soundFontInfo.ICMT||"Soundfont")+` Converted from SF2 to DLS using SpessaSynth`,this.soundFontInfo.ISFT="SpessaSynth";let a=[];for(let[h,d]of Object.entries(this.soundFontInfo))h!=="ICMT"&&h!=="INAM"&&h!=="ICRD"&&h!=="IENG"&&h!=="ICOP"&&h!=="ISFT"&&h!=="ISBJ"||a.push(z(h,fe(d),!0));let C=z("INFO",FA(a),!1,!0),c=new b(A.length+t.length+E.length+s.length+C.length+4);return TA(c,"DLS "),c.set(FA([A,t,E,s,C]),4),p("%cSaved succesfully!",I.recognized),V(),z("RIFF",c)}var Di=48e3,ve=class{sampleName;sampleRate;samplePitch;samplePitchCorrection;sampleLink;sampleType;sampleLoopStartIndex;sampleLoopEndIndex;isCompressed;compressedData=void 0;useCount=0;sampleData=void 0;constructor(A,t,n,s,o,r,E,a){this.sampleName=A,this.sampleRate=t,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=r,this.sampleLoopStartIndex=E,this.sampleLoopEndIndex=a,this.isCompressed=(r&16)>0}getRawData(){let A=new Uint8Array(this.sampleData.length*2);for(let t=0;t>8&255}return A}resampleData(A){let t=this.getAudioData(),n=A/this.sampleRate,s=new Float32Array(Math.floor(t.length*n));for(let o=0;o96e3)&&(this.resampleData(Di),n=this.getAudioData()),this.compressedData=t([n],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{Y(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=239}}getAudioData(){return this.sampleData}};var He=class{instrumentName="";instrumentZones=[];_useCount=0;get useCount(){return this._useCount}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;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 Ye=class{parentSoundBank;presetName="";program=0;bank=0;presetZones=[];foundSamplesAndGenerators=[];library=0;genre=0;morphology=0;constructor(A){this.parentSoundBank=A;for(let t=0;t<128;t++)this.foundSamplesAndGenerators[t]=[]}isDrumPreset(A,t=!1){let n=A&&this.parentSoundBank.isXGBank;return this.bank===128||n&&jA(this.bank)&&(this.bank!==126||t)}deletePreset(){this.presetZones.forEach(A=>A.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,t){for(let n=A;n{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,t){this.getSamplesAndGenerators(A,t).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}getSamplesAndGenerators(A,t){let n=this.foundSamplesAndGenerators[A][t];if(n)return n;if(this.presetZones.length<1)return[];function s(B,m){return m>=B.min&&m<=B.max}function o(B,m){B.push(...m.filter(u=>!B.find(S=>S.generatorType===u.generatorType)))}function r(B,m){B.push(...m.filter(u=>!B.find(S=>_.isIdentical(u,S))))}let E=[],a=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],C=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[],c=this.presetZones[0].isGlobal?this.presetZones[0].keyRange:{min:0,max:127},h=this.presetZones[0].isGlobal?this.presetZones[0].velRange:{min:0,max:127};return this.presetZones.filter(B=>s(B.hasKeyRange?B.keyRange:c,A)&&s(B.hasVelRange?B.velRange:h,t)&&!B.isGlobal).forEach(B=>{if(B.instrument.instrumentZones.length<1)return;let m=B.generators,u=B.modulators,S=B.instrument.instrumentZones[0],w=S.isGlobal?[...S.generators]:[],k=S.isGlobal?[...S.modulators]:[],M=S.isGlobal?S.keyRange:{min:0,max:127},L=S.isGlobal?S.velRange:{min:0,max:127};B.instrument.instrumentZones.filter(g=>s(g.hasKeyRange?g.keyRange:M,A)&&s(g.hasVelRange?g.velRange:L,t)&&!g.isGlobal).forEach(g=>{let x=[...g.generators],O=[...g.modulators];o(m,a),o(x,w),r(u,C),r(O,k),r(O,this.parentSoundBank.defaultModulators);let gA=[...O];for(let tA=0;tA_.isIdentical(T,BA));$!==-1?gA[$]=gA[$].sumTransform(T):gA.push(T)}E.push({instrumentGenerators:x,presetGenerators:m,modulators:gA,sample:g.sample,sampleID:g.generators.find(tA=>tA.generatorType===i.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=E,E}};var Je=class e{soundFontInfo={};presets=[];samples=[];instruments=[];defaultModulators=qs.map(A=>_.copy(A));isXGBank=!1;constructor(A=void 0){A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}static mergeSoundBanks(...A){let t=A.shift(),n=t.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(r=>r.bank===o.bank&&r.program===o.program)===void 0&&n.push(o)});return new e({presets:n,info:t.soundFontInfo})}static getDummySoundfontFile(){let A=new e,t=new ve("Saw",44100,65,20,0,0,0,127);t.sampleData=new Float32Array(128);for(let C=0;C<128;C++)t.sampleData[C]=C/128*2-1;A.samples.push(t);let n=new qA;n.isGlobal=!0,n.generators.push(new U(i.initialAttenuation,375)),n.generators.push(new U(i.releaseVolEnv,-1e3)),n.generators.push(new U(i.sampleModes,1));let s=new qA;s.sample=t;let o=new qA;o.sample=t,o.generators.push(new U(i.fineTune,-9));let r=new He;r.instrumentName="Saw Wave",r.instrumentZones.push(n),r.instrumentZones.push(s),r.instrumentZones.push(o),A.instruments.push(r);let E=new Te;E.instrument=r;let a=new Ye(A);return a.presetName="Saw Wave",a.presetZones.push(E),A.presets.push(a),A.soundFontInfo.ifil="2.1",A.soundFontInfo.isng="EMU8000",A.soundFontInfo.INAM="Dummy",A._parseInternal(),A.write().buffer}_parseInternal(){this.isXGBank=!1;let A=new Set([0,1,2,3,4,5,6,7,8,9,16,17,24,25,27,28,29,30,31,32,33,40,41,48,56,57,58,64,65,66,126,127]);for(let t of this.presets)if(jA(t.bank)&&(this.isXGBank=!0,!A.has(t.program))){this.isXGBank=!1,p(`%cThis bank is not valid XG. Preset %c${t.bank}:${t.program}%c is not a valid XG drum. XG mode will use presets on bank 128.`,I.info,I.value,I.info);break}}trimSoundBank(A){let t=this;function n(o,r){let E=0;for(let a=0;a=c.min&&B.key<=c.max&&B.velocity>=h.min&&B.velocity<=h.max){d=!0;break}d||(p(`%c${C.sample.sampleName} %cremoved from %c${o.instrumentName}%c. Use count: %c${C.useCount-1}`,I.recognized,I.info,I.recognized,I.info,I.recognized),o.safeDeleteZone(a)&&(E++,a--,p(`%c${C.sample.sampleName} %cdeleted`,I.recognized,I.info)),C.sample.useCount<1&&t.deleteSample(C.sample))}return E}se("%cTrimming soundfont...",I.info);let s=A.getUsedProgramsAndKeys(t);yA("%cModifying soundfont...",I.info),p("Detected keys for midi:",s);for(let o=0;o{let d=h.split("-");return{key:parseInt(d[0]),velocity:parseInt(d[1])}});yA(`%cTrimming %c${r.presetName}`,I.info,I.recognized),p(`Keys for ${r.presetName}:`,C);let c=0;for(let h=0;h=B.min&&S.key<=B.max&&S.velocity>=m.min&&S.velocity<=m.max){u=!0;let w=n(d.instrument,C);p(`%cTrimmed off %c${w}%c zones from %c${d.instrument.instrumentName}`,I.info,I.recognized,I.info,I.recognized);break}u||(c++,r.deleteZone(h),d.instrument.useCount<1&&t.deleteInstrument(d.instrument),h--)}p(`%cTrimmed off %c${c}%c zones from %c${r.presetName}`,I.info,I.recognized,I.info,I.recognized),V()}}t.removeUnusedElements(),t.soundFontInfo.ICMT=`NOTE: This soundfont was trimmed by SpessaSynth to only contain presets used in "${A.midiName}" `+t.soundFontInfo.ICMT,p("%cSoundfont modified!",I.recognized),V(),V()}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(t=>{t.isGlobal||t.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}getPresetNoFallback(A,t,n=!1){let s=A===128||n&&jA(A),o;if(s?o=this.presets.find(r=>r.bank===A&&r.isDrumPreset(n)&&r.program===t):o=this.presets.find(r=>r.bank===A&&r.program===t),o)return o;if(s&&n){let r=this.presets.find(E=>E.isDrumPreset(n)&&E.program===t);if(r)return r}}getPreset(A,t,n=!1){let s=A===128||n&&jA(A),o;return s?o=this.presets.find(r=>r.bank===A&&r.isDrumPreset(n)&&r.program===t):o=this.presets.find(r=>r.bank===A&&r.program===t),o||(s?(o=this.presets.find(r=>r.isDrumPreset(n)&&r.program===t),o||(o=this.presets.find(r=>r.isDrumPreset(n)))):o=this.presets.find(r=>r.program===t&&!r.isDrumPreset(n)),o&&Y(`%cPreset ${A}.${t} not found. Replaced with %c${o.presetName} (${o.bank}.${o.program})`,I.warn,I.recognized),o||(Y(`Preset ${t} not found. Defaulting to`,this.presets[0].presetName),o=this.presets[0]),o)}getPresetByName(A){let t=this.presets.find(n=>n.presetName===A);return t||(Y("Preset not found. Defaulting to:",this.presets[0].presetName),t=this.presets[0]),t}parsingError(A){throw new Error(`SF parsing error: ${A} The file may be corrupted.`)}destroySoundBank(){delete this.presets,delete this.instruments,delete this.samples}};Je.prototype.write=Oo;Je.prototype.writeDLS=tr;function nr(e){yA("%cLoading instruments...",I.info);for(let A=0;A>8&127,o=t&127;s>0?this.bank=s:this.bank=o,t>>31&&(this.bank=128),this.DLSInstrument=new He,this.DLSInstrument.addUseCount();let E=new Te;E.instrument=this.DLSInstrument,this.presetZones=[E]}};function sr(e){this.verifyHeader(e,"LIST"),this.verifyText(eA(e.chunkData,4),"ins ");let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(IA(e.chunkData));let t=A.find(B=>B.header==="insh");if(!t)throw V(),new Error("No instrument header!");let n=N(t.chunkData,4),s=N(t.chunkData,4),o=N(t.chunkData,4),r=new ln(this,s,o),E="unnamedPreset",a=ZA(A,"INFO");if(a){let B=IA(a.chunkData);for(;B.header!=="INAM";)B=IA(a.chunkData);E=eA(B.chunkData,B.chunkData.length).trim()}r.presetName=E,r.DLSInstrument.instrumentName=E,yA(`%cParsing %c"${E}"%c...`,I.info,I.recognized,I.info);let C=ZA(A,"lrgn");if(!C)throw V(),new Error("No region list!");let c=new qA;c.isGlobal=!0;let h=ZA(A,"lart"),d=ZA(A,"lar2");(d!==void 0||h!==void 0)&&this.readLart(h,d,c),c.generators=c.generators.filter(B=>B.generatorValue!==X[B.generatorType].def),c.modulators.find(B=>B.modulatorDestination===i.reverbEffectsSend)===void 0&&c.modulators.push(_.copy(Cn)),c.modulators.find(B=>B.modulatorDestination===i.chorusEffectsSend)===void 0&&c.modulators.push(_.copy(En)),r.DLSInstrument.instrumentZones.push(c);for(let B=0;B>10&15;k===GA.linear&&w!==GA.linear&&(k=w);let M=n>>14&1,L=n>>15&1;r===i.initialAttenuation&&s<0&&(L=1),d=re(k,M,L,E.isCC,E.enum)}r===i.initialAttenuation&&(c=Math.max(960,Math.min(0,c)));let B=n>>4&15,m=n>>8&1,u=n>>9&1,S=re(B,m,u,h.isCC,h.enum);if(a){let w=S;S=d,d=w}return new _(d,S,r,c,0)}function ss(e,A){let t=e.chunkData,n=[],s=[];N(t,4);let o=N(t,4);for(let r=0;r>16;if(E===0&&a===0&&c===0){let B;switch(C){case F.pan:B=new U(i.pan,d);break;case F.gain:B=new U(i.initialAttenuation,-d*10/.4);break;case F.filterCutoff:B=new U(i.initialFilterFc,d);break;case F.filterQ:B=new U(i.initialFilterQ,d);break;case F.modLfoFreq:B=new U(i.freqModLFO,d);break;case F.modLfoDelay:B=new U(i.delayModLFO,d);break;case F.vibLfoFreq:B=new U(i.freqVibLFO,d);break;case F.vibLfoDelay:B=new U(i.delayVibLFO,d);break;case F.volEnvDelay:B=new U(i.delayVolEnv,d);break;case F.volEnvAttack:B=new U(i.attackVolEnv,d);break;case F.volEnvHold:B=new U(i.holdVolEnv,d,!1);break;case F.volEnvDecay:B=new U(i.decayVolEnv,d,!1);break;case F.volEnvRelease:B=new U(i.releaseVolEnv,d);break;case F.volEnvSustain:let m=1e3-d;B=new U(i.sustainVolEnv,m);break;case F.modEnvDelay:B=new U(i.delayModEnv,d);break;case F.modEnvAttack:B=new U(i.attackModEnv,d);break;case F.modEnvHold:B=new U(i.holdModEnv,d,!1);break;case F.modEnvDecay:B=new U(i.decayModEnv,d,!1);break;case F.modEnvRelease:B=new U(i.releaseModEnv,d);break;case F.modEnvSustain:let u=1e3-d;B=new U(i.sustainModEnv,u);break;case F.reverbSend:B=new U(i.reverbEffectsSend,d);break;case F.chorusSend:B=new U(i.chorusEffectsSend,d);break;case F.pitch:let S=Math.floor(d/100),w=Math.floor(d-S*100);B=new U(i.fineTune,w),n.push(new U(i.coarseTune,S));break}B&&n.push(B)}else{let B=!0;if(a===P.none)if(E===P.modLfo&&C===F.pitch)n.push(new U(i.modLfoToPitch,d));else if(E===P.modLfo&&C===F.gain)n.push(new U(i.modLfoToVolume,d));else if(E===P.modLfo&&C===F.filterCutoff)n.push(new U(i.modLfoToFilterFc,d));else if(E===P.vibratoLfo&&C===F.pitch)n.push(new U(i.vibLfoToPitch,d));else if(E===P.modEnv&&C===F.pitch)n.push(new U(i.modEnvToPitch,d));else if(E===P.modEnv&&C===F.filterCutoff)n.push(new U(i.modEnvToFilterFc,d));else if(E===P.keyNum&&C===F.pitch)n.push(new U(i.scaleTuning,d/128));else if(E===P.keyNum&&C===F.volEnvHold){n.push(new U(i.keyNumToVolEnvHold,d/-128));let m=Math.round(60/128*d);n.forEach(u=>{u.generatorType===i.holdVolEnv&&(u.generatorValue+=m)})}else if(E===P.keyNum&&C===F.volEnvDecay){n.push(new U(i.keyNumToVolEnvDecay,d/-128));let m=Math.round(60/128*d);n.forEach(u=>{u.generatorType===i.decayVolEnv&&(u.generatorValue+=m)})}else if(E===P.keyNum&&C===F.modEnvHold){n.push(new U(i.keyNumToModEnvHold,d/-128));let m=Math.round(60/128*d);n.forEach(u=>{u.generatorType===i.holdModEnv&&(u.generatorValue+=m)})}else if(E===P.keyNum&&C===F.modEnvDecay){n.push(new U(i.keyNumToModEnvDecay,d/-128));let m=Math.round(60/128*d);n.forEach(u=>{u.generatorType===i.decayModEnv&&(u.generatorValue+=m)})}else B=!1;else B=!1;if(B===!1){let m=rr(E,a,C,c,d);m?(s.push(m),p("%cSucceeded converting to SF2 Modulator!",I.recognized)):Y("Failed converting to SF2 Modulator!")}}}return A&&s.push(_.copy(Bn),_.copy(hn)),{modulators:s,generators:n}}function ir(e,A,t){if(e)for(;e.chunkData.currentIndexe.chunkData.currentIndex;)A.push(IA(e.chunkData));let t=A.find(O=>O.header==="rgnh"),n=N(t.chunkData,2),s=N(t.chunkData,2),o=N(t.chunkData,2),r=N(t.chunkData,2);o===0&&r===0&&(r=127,o=0),n===0&&s===0&&(s=127,n=0);let E=new Qn({min:n,max:s},{min:o,max:r});N(t.chunkData,2);let a=N(t.chunkData,2);a!==0&&E.generators.push(new U(i.exclusiveClass,a));let C=ZA(A,"lart"),c=ZA(A,"lar2");this.readLart(C,c,E),E.isGlobal=!1;let h=A.find(O=>O.header==="wsmp");N(h.chunkData,4);let d=N(h.chunkData,2),B=Ne(h.chunkData[h.chunkData.currentIndex++],h.chunkData[h.chunkData.currentIndex++]),u=(N(h.chunkData,4)|0)/-655360;N(h.chunkData,4);let S=N(h.chunkData,4),w,k={start:0,end:0};if(S===0)w=0;else{N(h.chunkData,4),N(h.chunkData,4)===0?w=1:w=3,k.start=N(h.chunkData,4);let gA=N(h.chunkData,4);k.end=k.start+gA}let M=A.find(O=>O.header==="wlnk");if(M===void 0)return;N(M.chunkData,2),N(M.chunkData,2),N(M.chunkData,4);let L=N(M.chunkData,4),G=this.samples[L];if(G===void 0)throw new Error("Invalid sample ID!");let x=(u||G.sampleDbAttenuation)*10/.4;return E.setWavesample(x,w,k,d,G,L,B),E}var dn=class extends ve{sampleDbAttenuation;sampleData;constructor(A,t,n,s,o,r,E,a){super(A,t,n,s,0,1,o,r),this.sampleData=E,this.sampleDbAttenuation=a}getAudioData(){return this.sampleData}getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data?? This shouldn't happen!!");return this.compressedData}return super.getRawData()}};var Ir={PCM:1,ALAW:6};function Fi(e,A){let t=Math.pow(2,A*8-1),n=Math.pow(2,A*8),s,o=!1;A===1?(s=255,o=!0):s=t;let r=e.size/A,E=new Float32Array(r);for(let a=0;a=t&&(C-=n),E[a]=C/s)}return E}function Ri(e,A){let t=e.size/A,n=new Float32Array(t);for(let s=0;s>4,a=r&15;E>0&&(a+=16),a=(a<<4)+8,E>1&&(a=a<127?a:-a;n[s]=C/32678}return n}function gr(e){yA("%cLoading Wave samples...",I.recognized);let A=0;for(;e.chunkData.currentIndexG.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");let o=N(s.chunkData,2),r=N(s.chunkData,2);if(r!==1)throw new Error(`Only mono samples are supported. Fmt reports ${r} channels`);let E=N(s.chunkData,4);N(s.chunkData,4),N(s.chunkData,2);let C=N(s.chunkData,2)/8,c=!1,h=n.find(G=>G.header==="data");h||this.parsingError("No data chunk in the WAVE chunk!");let d;switch(o){default:c=!0,d=new Float32Array(h.size/C);break;case Ir.PCM:d=Fi(h,C);break;case Ir.ALAW:d=Ri(h,C);break}let B=ZA(n,"INFO"),m=`Unnamed ${A}`;if(B){let G=IA(B.chunkData);for(;G.header!=="INAM"&&B.chunkData.currentIndexG.header==="wsmp");if(L){N(L.chunkData,4),u=N(L.chunkData,2),S=Ne(L.chunkData[L.chunkData.currentIndex++],L.chunkData[L.chunkData.currentIndex++]);let G=Math.trunc(S/100);if(u+=G,S-=G*100,M=(N(L.chunkData,4)|0)/-655360,N(L.chunkData,4),N(L.chunkData,4)===1){N(L.chunkData,8),w=N(L.chunkData,4);let O=N(L.chunkData,4);k=w+O}}else Y("No wsmp chunk in wave... using sane defaults.");c&&console.error(`Failed to load '${m}': Unsupported format: (${o})`),this.samples.push(new dn(m,E,u,S,w,k,d,M)),A++,p(`%cLoaded sample %c${m}`,I.info,I.recognized)}V()}var we=class extends Je{constructor(A){super(),this.dataArray=new b(A),se("%cParsing DLS...",I.info),this.dataArray||(V(),this.parsingError("No data provided!"));let t=IA(this.dataArray,!1);this.verifyHeader(t,"riff"),this.verifyText(eA(this.dataArray,4).toLowerCase(),"dls ");let n=[];for(;this.dataArray.currentIndexa.header==="colh");o||(V(),this.parsingError("No colh chunk!")),this.instrumentAmount=N(o.chunkData,4),p(`%cInstruments amount: %c${this.instrumentAmount}`,I.info,I.recognized);let r=ZA(n,"wvpl");r||(V(),this.parsingError("No wvpl chunk!")),this.readDLSSamples(r);let E=ZA(n,"lins");E||(V(),this.parsingError("No lins chunk!")),this.readDLSInstrumentList(E),this.presets.sort((a,C)=>a.program-C.program+(a.bank-C.bank)),this._parseInternal(),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.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),V()}verifyHeader(A,...t){for(let n of t)if(A.header.toLowerCase()===n.toLowerCase())return;V(),this.parsingError(`Invalid DLS chunk header! Expected "${t.toString()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(V(),this.parsingError(`FourCC error: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`))}parsingError(A){throw new Error(`DLS parse error: ${A} The file may be corrupted.`)}destroySoundBank(){super.destroySoundBank(),delete this.dataArray}};we.prototype.readDLSInstrumentList=nr;we.prototype.readDLSInstrument=sr;we.prototype.readRegion=ar;we.prototype.readLart=ir;we.prototype.readDLSSamples=gr;var os=class extends ve{constructor(A,t,n,s,o,r,E,a,C,c,h,d,B){super(A,r,E,a,C,c,s-t/2,o-t/2),this.sampleName=A,this.sampleStartIndex=t,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=d,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=h,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=B}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let t=A.currentIndex;return A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t)}else{this.isDataRaw||super.getRawData();let t=A.currentIndex;return A.slice(t+this.sampleStartIndex,t+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,t=A.currentIndex,n=A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t);this.sampleData=new Float32Array(0);try{let s=me.decode(n.buffer);this.sampleData=s.data[0],this.sampleData===void 0&&Y(`Error decoding sample ${this.sampleName}: Vorbis decode returned undefined.`)}catch(s){Y(`Error decoding sample ${this.sampleName}: ${s}`),this.sampleData=new Float32Array(this.sampleLoopEndIndex+1)}}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?(Y(`Invalid sample ${this.sampleName}! Invalid length: ${this.sampleLength}`),new Float32Array(1)):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return Y("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),t=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(t+this.sampleStartIndex,t+this.sampleEndIndex).buffer);for(let s=0;se.chunkData.currentIndex;){let o=Gi(s,e.chunkData,A,t);n.push(o),s++}return n.length>1&&n.pop(),n}function Gi(e,A,t,n){let s=eA(A,20),o=N(A,4)*2,r=N(A,4)*2,E=N(A,4),a=N(A,4),C=N(A,4),c=A[A.currentIndex++];c===255&&(c=60);let h=Ks(A[A.currentIndex++]),d=N(A,2),B=N(A,2);return new os(s,o,r,E,a,C,c,h,d,B,t,e,n)}var rs=class extends U{constructor(A){super();let t=A.currentIndex;this.generatorType=A[t+1]<<8|A[t],this.generatorValue=Ne(A[t+2],A[t+3]),A.currentIndex+=4}};function is(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new rs(e.chunkData));return A.length>1&&A.pop(),A}var as=class extends qA{constructor(A){super(),this.generatorZoneStartIndex=N(A,2),this.modulatorZoneStartIndex=N(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;tn.generatorType===i.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===i.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===i.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function Er(e,A,t,n){let s=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new as(e.chunkData);if(s.length>0){let r=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,E=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(r,E),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(t),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Is=class extends Te{constructor(A){super(),this.generatorZoneStartIndex=N(A,2),this.modulatorZoneStartIndex=N(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;tn.generatorType===i.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===i.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===i.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function Br(e,A,t,n){let s=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Is(e.chunkData);if(s.length>0){let r=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,E=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(r,E),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(t),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var gs=class extends Ye{constructor(A,t){super(t),this.presetName=eA(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=N(A.chunkData,2),this.bank=N(A.chunkData,2),this.presetZoneStartIndex=N(A.chunkData,2),this.library=N(A.chunkData,4),this.genre=N(A.chunkData,4),this.morphology=N(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,t){this.presetZonesAmount=A;for(let n=this.presetZoneStartIndex;ne.chunkData.currentIndex;){let s=new gs(e,t);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var Cs=class extends He{constructor(A){super(),this.instrumentName=eA(A.chunkData,20).trim(),this.instrumentZoneIndex=N(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,t){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;ne.chunkData.currentIndex;){let n=new Cs(e);if(t.length>0){let s=n.instrumentZoneIndex-t[t.length-1].instrumentZoneIndex;t[t.length-1].getInstrumentZones(s,A)}t.push(n)}return t.length>1&&t.pop(),t}var Es=class extends _{constructor(A){let t=N(A,2),n=N(A,2),s=Ne(A[A.currentIndex++],A[A.currentIndex++]),o=N(A,2),r=N(A,2);super(t,o,n,s,r)}};function un(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new Es(e.chunkData));return A}var fn=class extends Je{constructor(A,t=!0){super(),t&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new b(A),se("%cParsing SoundFont...",I.info),this.dataArray||(V(),this.parsingError("No data provided!"));let n=IA(this.dataArray,!1);this.verifyHeader(n,"riff");let s=eA(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw V(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",r=IA(this.dataArray);for(this.verifyHeader(r,"list"),eA(r.chunkData,4);r.chunkData.length>r.chunkData.currentIndex;){let tA=IA(r.chunkData),T;switch(tA.header.toLowerCase()){case"ifil":case"iver":T=`${N(tA.chunkData,2)}.${N(tA.chunkData,2)}`,this.soundFontInfo[tA.header]=T;break;case"icmt":T=eA(tA.chunkData,tA.chunkData.length,void 0,!1),this.soundFontInfo[tA.header]=T;break;case"dmod":let $=un(tA);$.pop(),T=`Modulators: ${$.length}`;let BA=this.defaultModulators;this.defaultModulators=$,this.defaultModulators.push(...BA.filter(sA=>!this.defaultModulators.find(oA=>_.isIdentical(sA,oA)))),this.soundFontInfo[tA.header]=tA.chunkData;break;default:T=eA(tA.chunkData,tA.chunkData.length),this.soundFontInfo[tA.header]=T}p(`%c"${tA.header}": %c"${T}"`,I.info,I.recognized)}let E=IA(this.dataArray,!1);this.verifyHeader(E,"list"),this.verifyText(eA(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",I.warn);let a=IA(this.dataArray,!1);this.verifyHeader(a,"smpl");let C;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",I.info);try{C=me.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+E.size-12)).data[0]}catch(tA){throw V(),new Error(`SF2Pack Ogg Vorbis decode error: ${tA}`)}p(`%cDecoded the smpl chunk! Length: %c${C.length}`,I.info,I.value)}else C=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${E.size-12}`,I.info,I.value),this.dataArray.currentIndex+=E.size-12,p("%cLoading preset data chunk...",I.warn);let c=IA(this.dataArray);this.verifyHeader(c,"list"),eA(c.chunkData,4);let h=IA(c.chunkData);this.verifyHeader(h,"phdr");let d=IA(c.chunkData);this.verifyHeader(d,"pbag");let B=IA(c.chunkData);this.verifyHeader(B,"pmod");let m=IA(c.chunkData);this.verifyHeader(m,"pgen");let u=IA(c.chunkData);this.verifyHeader(u,"inst");let S=IA(c.chunkData);this.verifyHeader(S,"ibag");let w=IA(c.chunkData);this.verifyHeader(w,"imod");let k=IA(c.chunkData);this.verifyHeader(k,"igen");let M=IA(c.chunkData);this.verifyHeader(M,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...Cr(M,C,!o));let L=is(k),G=un(w),g=Er(S,L,G,this.samples);this.instruments=cr(u,g);let x=is(m),O=un(B),gA=Br(d,x,O,this.instruments);this.presets.push(...hr(h,gA,this)),this.presets.sort((tA,T)=>tA.program-T.program+(tA.bank-T.bank)),this._parseInternal(),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.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),V(),o&&delete this.dataArray}verifyHeader(A,t){A.header.toLowerCase()!==t.toLowerCase()&&(V(),this.parsingError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(V(),this.parsingError(`Invalid FourCC: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"\``))}destroySoundBank(){super.destroySoundBank(),delete this.dataArray}};function Nt(e){let A=e.slice(8,12),t=new b(A);return eA(t,4,void 0,!1).toLowerCase()==="dls "?new we(e):new fn(e,!1)}var mn=class{constructor(A,t){this.ready=t,this.reloadManager(A)}generatePresetList(){let A={};for(let t=this.soundfontList.length-1;t>=0;t--){let n=this.soundfontList[t],s=new Set;for(let o of n.soundfont.presets){let r=`${o.bank+n.bankOffset}-${o.program}`;s.has(r)||(s.add(r),A[r]=o.presetName)}}this.presetList=[];for(let[t,n]of Object.entries(A)){let s=t.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}}handleMessage(A,t){switch(A){case Gt.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case Gt.reloadSoundFont:this.reloadManager(t);break;case Gt.deleteSoundFont:this.deleteSoundFont(t);break;case Gt.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let t=Nt(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:t}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){Y("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(n=>n.id===A);if(t===-1){Y(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[t].soundfont.presets,delete this.soundfontList[t].soundfont.instruments,delete this.soundfontList[t].soundfont.samples,this.soundfontList.splice(t,1),this.generatePresetList()}addNewSoundFont(A,t,n){if(this.soundfontList.find(s=>s.id===t)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:t,soundfont:Nt(A),bankOffset:n}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((t,n)=>A.indexOf(t.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,t,n=!1){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let o of this.soundfontList){let r=o.soundfont.getPresetNoFallback(A-o.bankOffset,t,n);if(r!==void 0)return r}if(A===128||n&&jA(A)){for(let o of this.soundfontList){let r=o.soundfont.presets.find(a=>a.isDrumPreset(n)&&a.program===t);if(r)return r;let E=o.soundfont.presets.find(a=>a.isDrumPreset(n));if(E)return E}return this.soundfontList[0].soundfont.presets[0]}else{for(let o of this.soundfontList){let r=o.soundfont.presets.find(E=>E.program===t&&!E.isDrumPreset(n));if(r)return r}return this.soundfontList[0].soundfont.presets[0]}}destroyManager(){this.soundfontList.forEach(A=>{A.soundfont.destroySoundBank()}),delete this.soundfontList}};var lt={linear:0,nearestNeighbor:1,fourthOrder:2},ct=class{static getSampleLinear(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let E=0;E=n.loopEnd;)s-=r;let a=~~s,C=a+1;for(;C>=n.loopEnd;)C-=r;let c=s-a,h=o[C],d=o[a];t[E]=d+(h-d)*c,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r=n.end){A.finished=!0;return}let C=s-E,c=o[a],h=o[E];t[r]=h+(c-h)*C,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}static getSampleNearest(A,t){let n=A.sample,s=n.cursor,o=n.loopEnd-n.loopStart,r=n.sampleData;if(A.sample.isLooping)for(let E=0;E=n.loopEnd;)s-=o;let a=~~s+1;for(;a>=n.loopEnd;)a-=o;t[E]=r[a],s+=n.playbackStep*A.currentTuningCalculated}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let E=0;E=n.end){A.finished=!0;return}t[E]=r[a],s+=n.playbackStep*A.currentTuningCalculated}}n.cursor=s}static getSampleCubic(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let E=0;E=n.loopEnd;)s-=r;let a=~~s,C=a+1,c=C+1,h=c+1,d=s-a;C>=n.loopEnd&&(C-=r),c>=n.loopEnd&&(c-=r),h>=n.loopEnd&&(h-=r);let B=o[a],m=o[C],u=o[c],S=o[h],w=.5*(u-B),k=B-2.5*m+2*u-.5*S,M=.5*(S-B)+1.5*(m-u);t[E]=((M*d+k)*d+w)*d+m,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r=n.end||C>=n.end||c>=n.end){A.finished=!0;return}let d=o[E],B=o[a],m=o[C],u=o[c],S=.5*(m-d),w=d-2.5*B+2*m-.5*u,k=.5*(u-d)+1.5*(B-m);t[r]=((k*h+w)*h+S)*h+B,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}};var Bs={addMapping:0,deleteMapping:1,clearMappings:2},pn=class{_keyMappings=[];handleMessage(A,t){switch(A){default:return;case Bs.addMapping:this.addMapping(...t);break;case Bs.clearMappings:this.clearMappings();break;case Bs.deleteMapping:this.deleteMapping(...t)}}addMapping(A,t,n){this._keyMappings[A]===void 0&&(this._keyMappings[A]=[]),this._keyMappings[A][t]=n}deleteMapping(A,t){this._keyMappings[A]?.[t]!==void 0&&(this._keyMappings[A][t]=void 0)}clearMappings(){this._keyMappings=[]}setMappings(A){this._keyMappings=A}getMappings(){return this._keyMappings}getVelocity(A,t){let n=this._keyMappings[A]?.[t];return n?n.velocity:-1}hasOverridePatch(A,t){let n=this._keyMappings[A]?.[t]?.patch?.bank;return n!==void 0&&n>=0}getPatch(A,t){let n=this._keyMappings[A]?.[t];if(n)return n.patch;throw new Error("No modifier.")}};var lr=.1,Ke=class e{static cachedCoefficients=[];a0=0;a1=0;a2=0;a3=0;a4=0;x1=0;x2=0;y1=0;y2=0;resonanceCb=0;currentInitialFc=13500;lastTargetCutoff=1/0;initialized=!1;static apply(A,t,n,s){let o=A.modulatedGenerators[i.initialFilterFc],r=A.filter;r.initialized?r.currentInitialFc+=(o-r.currentInitialFc)*s:(r.initialized=!0,r.currentInitialFc=o);let E=r.currentInitialFc+n,a=A.modulatedGenerators[i.initialFilterQ];if(r.currentInitialFc>13499&&E>13499&&a===0){r.currentInitialFc=13500;return}(Math.abs(r.lastTargetCutoff-E)>1||r.resonanceCb!==a)&&(r.lastTargetCutoff=E,r.resonanceCb=a,e.calculateCoefficients(r,E));for(let C=0;C.5?1:0,n?t*2-1:t;case GA.concave:return n?(t=t*2-1,t<0?-Fe[~~(t*-bA)]:Fe[~~(t*bA)]):Fe[~~(t*bA)];case GA.convex:return n?(t=t*2-1,t<0?-_e[~~(t*-bA)]:_e[~~(t*bA)]):_e[~~(t*bA)]}}var cs=1,ls=new Float32Array(1e3);for(let e=0;e_.copy(o)))}exclusiveRelease(){this.release(ur),this.modulatedGenerators[i.releaseVolEnv]=xi,this.modulatedGenerators[i.releaseModEnv]=Mi,Ee.recalculate(this),Be.recalculate(this)}release(A=dr){this.releaseStartTime=currentTime,this.releaseStartTime-this.startTimebt.copy(B,n));let d=E.preset;return a&&(d=this.soundfontManager.getPreset(C,c,RA(this.system))),r=d.getSamplesAndGenerators(A,t).reduce((B,m)=>{if(m.sample.getAudioData()===void 0)return Y(`Discarding invalid sample: ${m.sample.sampleName}`),B;let u=new Int16Array(60);for(let g=0;g<60;g++)u[g]=Os(g,m.presetGenerators,m.instrumentGenerators);u[i.initialAttenuation]=Math.floor(u[i.initialAttenuation]*.4);let S=m.sample.samplePitch;u[i.overridingRootKey]>-1&&(S=u[i.overridingRootKey]);let w=A;u[i.keyNum]>-1&&(w=u[i.keyNum]);let k=m.sample.sampleLoopStartIndex,M=m.sample.sampleLoopEndIndex,L=u[i.sampleModes],G=new yn(m.sample.sampleData,m.sample.sampleRate/sampleRate*Math.pow(2,m.sample.samplePitchCorrection/1200),0,S,k,M,Math.floor(m.sample.sampleData.length)-1,L);return u[i.velocity]>-1&&(t=u[i.velocity]),o&&Ts([{Sample:m.sample.sampleName,Generators:u,Modulators:m.modulators.map(g=>_.debugString(g)),Velocity:t,TargetKey:w,MidiNote:A,WorkletSample:G}]),B.push(new bt(sampleRate,G,A,t,e,n,w,s,u,m.modulators.map(g=>_.copy(g)))),B},[]),this.setCachedVoice(C,c,A,t,r.map(B=>bt.copy(B,n))),r}var mr=.05,Ni=4600,bi=2e3,fr=Math.PI/2,Sn=-500,pr=500,Qs=pr-Sn,yr=new Float32Array(Qs+1),Sr=new Float32Array(Qs+1);for(let e=Sn;e<=pr;e++){let A=(e-Sn)/Qs,t=e-Sn;yr[t]=Math.cos(fr*A),Sr[t]=Math.sin(fr*A)}function Dr(e,A,t,n,s,o,r,E){if(isNaN(A[0]))return;let a;e.overridePan?a=e.overridePan:(e.currentPan+=(e.modulatedGenerators[i.pan]-e.currentPan)*this.synth.panSmoothingFactor,a=e.currentPan);let C=this.synth.currentGain,c=~~(a+500),h=yr[c]*C*this.synth.panLeft,d=Sr[c]*C*this.synth.panRight;if(!this.synth.oneOutputMode){let B=e.modulatedGenerators[i.reverbEffectsSend];if(B>0){let u=this.synth.reverbGain*C*(B/Ni);for(let S=0;S0){let u=this.synth.chorusGain*m/bi,S=h*u,w=d*u;for(let k=0;k0)for(let B=0;B0)for(let B=0;Bt.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function Fr(e,A=!1){this.clearSoundFont(!1,A);try{A?this.overrideSoundfont=Nt(e):this.soundfontManager.reloadManager(e)}catch(t){this.post({messageType:JA.soundfontError,messageData:t});return}this.getDefaultPresets(),this.workletProcessorChannels.forEach(t=>t.programChange(t.preset.program)),this.postReady(),this.sendPresetList(),p("%cSpessaSynth is ready!",I.recognized)}function Rr(e=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.getDefaultPresets(),this.cachedVoices=[];for(let t=0;t{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,n=e.find(s=>s.bank===t&&s.program===A.program);n!==void 0?n.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.processorInitialized.then(()=>{this.callEvent("presetlistchange",e)})}function xr(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(t,A,RA(this.system));if(n)return n}return this.soundfontManager.getPreset(e,A,RA(this.system))}function Mr(e,A=!1){this.transposition=0;for(let t=0;tLt.getChannelSnapshot(A,s)),t.keyMappings=A.keyModifierManager.getMappings(),t.mainVolume=A.midiVolume,t.pan=A.pan,t.system=A.system,t.interpolation=A.interpolationType,t.transposition=A.transposition,t.effectsConfig={},t}static applySnapshot(A,t){for(A.setSystem(t.system),A.setMasterGain(t.mainVolume),A.setMasterPan(t.pan),A.transposeAllChannels(t.transposition),A.interpolationType=t.interpolation,A.keyModifierManager.setMappings(t.keyMappings);A.workletProcessorChannels.length{Lt.applyChannelSnapshot(A,s,n)}),p("%cFinished restoring controllers!",I.info)}};function br(){this.post({messageType:JA.synthesizerSnapshot,messageData:Qt.createSynthesizerSnapshot(this)})}function Lr(e){Qt.applySnapshot(this,e),p("%cFinished applying snapshot!",I.info)}function Dn(e,A,t){if(t=e.releaseStartTime&&(e.isInRelease=!0,Ee.startRelease(e),Be.startRelease(e),e.sample.loopingMode===3&&(e.sample.isLooping=!1)),e.modulatedGenerators[i.initialAttenuation]>2500)return e.isInRelease&&(e.finished=!0),e.finished;let a=e.targetKey,C=e.modulatedGenerators[i.fineTune]+this.channelOctaveTuning[e.midiNote]+this.channelTuningCents,c=e.modulatedGenerators[i.coarseTune],h=this.synth.tunings[this.preset.program]?.[e.realKey];if(h!==void 0&&h?.midiNote>=0&&(a=h.midiNote,C+=h.centTuning),e.portamentoFromKey>-1){let g=Math.min((E-e.startTime)/e.portamentoDuration,1),x=a-e.portamentoFromKey;c-=x*(1-g)}C+=(a-e.sample.rootKey)*e.modulatedGenerators[i.scaleTuning];let d=e.modulatedGenerators[i.vibLfoToPitch];if(d!==0){let g=e.startTime+Ce(e.modulatedGenerators[i.delayVibLFO]),x=Rt(e.modulatedGenerators[i.freqVibLFO]),O=Dn(g,x,E);C+=O*(d*this.customControllers[cA.modulationMultiplier])}let B=0,m=e.modulatedGenerators[i.modLfoToPitch],u=e.modulatedGenerators[i.modLfoToVolume],S=e.modulatedGenerators[i.modLfoToFilterFc],w=0;if(m!==0||S!==0||u!==0){let g=e.startTime+Ce(e.modulatedGenerators[i.delayModLFO]),x=Rt(e.modulatedGenerators[i.freqModLFO]),O=Dn(g,x,E);C+=O*(m*this.customControllers[cA.modulationMultiplier]),w=-O*u,B+=O*S}if(this.channelVibrato.depth>0){let g=Dn(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,E);g&&(C+=g*this.channelVibrato.depth)}let k=e.modulatedGenerators[i.modEnvToPitch],M=e.modulatedGenerators[i.modEnvToFilterFc];if(M!==0||k!==0){let g=Be.getValue(e,E);B+=g*M,C+=g*k}let L=~~(C+c*100);L!==e.currentTuningCents&&(e.currentTuningCents=L,e.currentTuningCalculated=Math.pow(2,L/1200));let G=new Float32Array(A.length);switch(this.synth.interpolationType){case lt.fourthOrder:ct.getSampleCubic(e,G);break;case lt.linear:default:ct.getSampleLinear(e,G);break;case lt.nearestNeighbor:ct.getSampleNearest(e,G);break}return Ke.apply(e,G,B,this.synth.filterSmoothingFactor),Ee.apply(e,G,w,this.synth.volumeEnvelopeSmoothingFactor),this.panVoice(e,G,A,t,n,s,o,r),e.finished}function Tr(e,A=-12e3){this.voices.forEach(t=>{t.realKey===e&&(t.modulatedGenerators[i.releaseVolEnv]=A,t.release())})}function vr(e,A=!0){e=Math.round(e),this.setCustomController(cA.channelTuning,e),A&&p(`%cFine tuning for %c${this.channelNumber}%c is now set to %c${e}%c cents.`,I.info,I.recognized,I.info,I.value,I.info)}function Hr(e){e=Math.round(e),p(`%cChannel ${this.channelNumber} modulation depth. Cents: %c${e}`,I.info,I.value),this.setCustomController(cA.modulationMultiplier,e/50)}function Yr(e){switch(this.dataEntryState){default:break;case YA.RPCoarse:case YA.RPFine:switch(this.midiControllers[y.RPNMsb]|this.midiControllers[y.RPNLsb]>>7){default:break;case 0:if(e===0)break;this.midiControllers[xA+j.pitchWheelRange]|=e;let t=(this.midiControllers[xA+j.pitchWheelRange]>>7)+e/128;p(`%cChannel ${this.channelNumber} bend range. Semitones: %c${t}`,I.info,I.value);break;case 1:let s=this.customControllers[cA.channelTuning]<<7|e;this.setTuning(s*.01220703125);break;case 5:let r=this.customControllers[cA.modulationMultiplier]*50+e/128*100;this.setModulationDepth(r);break;case 16383:this.resetParameters();break}}}var Li=1e3/200;function Jr(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=e[A.sourceIndex];else{let C=A.sourceIndex+xA;switch(A.sourceIndex){case j.noController:n=16383;break;case j.noteOnKeyNum:n=t.midiNote<<7;break;case j.noteOnVelocity:n=t.velocity<<7;break;case j.polyPressure:n=t.pressure<<7;break;default:n=e[C];break}}let s=je[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let C=A.secSrcIndex+xA;switch(A.secSrcIndex){case j.noController:o=16383;break;case j.noteOnKeyNum:o=t.midiNote<<7;break;case j.noteOnVelocity:o=t.velocity<<7;break;case j.polyPressure:o=t.pressure<<7;break;default:o=e[C]}}let r=je[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],E=A.transformAmount;A.isEffectModulator&&E<=1e3&&(E*=Li,E=Math.min(E,1e3));let a=s*r*E;return A.transformType===2&&(a=Math.abs(a)),A.currentValue=a,a}function he(e,A,t=-1,n=0){let s=e.modulators,o=e.generators,r=e.modulatedGenerators;if(t===-1){r.set(o),s.forEach(C=>{let c=X[C.modulatorDestination],h=r[C.modulatorDestination]+Jr(A,C,e);r[C.modulatorDestination]=Math.max(c.min,Math.min(h,c.max))}),Ee.recalculate(e),Be.recalculate(e);return}let E=new Set([i.initialAttenuation,i.delayVolEnv,i.attackVolEnv,i.holdVolEnv,i.decayVolEnv,i.sustainVolEnv,i.releaseVolEnv,i.keyNumToVolEnvHold,i.keyNumToVolEnvDecay]),a=new Set;s.forEach(C=>{if(C.sourceUsesCC===t&&C.sourceIndex===n||C.secSrcUsesCC===t&&C.secSrcIndex===n){let c=C.modulatorDestination;a.has(c)||(r[c]=o[c],Jr(A,C,e),s.forEach(h=>{if(h.modulatorDestination===c){let d=X[C.modulatorDestination],B=r[C.modulatorDestination]+h.currentValue;r[C.modulatorDestination]=Math.max(d.min,Math.min(B,d.max))}}),a.add(c))}}),[...a].some(C=>E.has(C))&&Ee.recalculate(e),Be.recalculate(e)}var je=[];for(let e=0;e<4;e++){je[e]=[[new Float32Array(bA),new Float32Array(bA)],[new Float32Array(bA),new Float32Array(bA)]];for(let A=0;A127){if(!t)return;switch(e){default:return;case Ps.velocityOverride:this.velocityOverride=A}}if(e>=y.lsbForControl1ModulationWheel&&e<=y.lsbForControl13EffectControl2&&e!==y.lsbForControl6DataEntry){let n=e-32;if(this.lockedControllers[n])return;this.midiControllers[n]=this.midiControllers[n]&16256|A&127,this.voices.forEach(s=>he(s,this.midiControllers,1,n))}if(!this.lockedControllers[e]){switch(this.midiControllers[e]=A<<7,e){case y.allNotesOff:this.stopAllNotes();break;case y.allSoundOff:this.stopAllNotes(!0);break;case y.bankSelect:this.setBankSelect(A);break;case y.lsbForControl0BankSelect:this.setBankSelect(A,!0);break;case y.RPNLsb:this.dataEntryState=YA.RPFine;break;case y.RPNMsb:this.dataEntryState=YA.RPCoarse;break;case y.NRPNMsb:this.dataEntryState=YA.NRPCoarse;break;case y.NRPNLsb:this.dataEntryState=YA.NRPFine;break;case y.dataEntryMsb:this.dataEntryCoarse(A);break;case y.lsbForControl6DataEntry:this.dataEntryFine(A);break;case y.resetAllControllers:this.resetControllersRP15Compliant();break;case y.sustainPedal:A>=64?this.holdPedal=!0:(this.holdPedal=!1,this.sustainedVoices.forEach(n=>{n.release()}),this.sustainedVoices=[]);break;default:this.voices.forEach(n=>he(n,this.midiControllers,1,e));break}this.synth.callEvent("controllerchange",{channel:this.channelNumber,controllerNumber:e,controllerValue:A})}}function Or(e=!1){e?(this.voices.length=0,this.sustainedVoices.length=0,this.sendChannelProperty()):(this.voices.forEach(A=>{A.isInRelease||A.release()}),this.sustainedVoices.forEach(A=>{A.release()}))}function qr(e){e&&this.stopAllNotes(!0),this.isMuted=e,this.sendChannelProperty(),this.synth.callEvent("mutechannel",{channel:this.channelNumber,isMuted:e})}function Pr(e,A=!1){this.drumChannel||(e+=this.synth.transposition);let t=Math.trunc(e),n=this.channelTransposeKeyShift+this.customControllers[cA.channelTransposeFine]/100;this.drumChannel&&!A||e===n||(t!==this.channelTransposeKeyShift&&this.controllerChange(y.allNotesOff,127),this.channelTransposeKeyShift=t,this.setCustomController(cA.channelTransposeFine,(e-t)*100),this.sendChannelProperty())}var Ut={pitchBendRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},Oe={partParameter:1,vibratoRate:8,vibratoDepth:9,vibratoDelay:10,EGAttackTime:100,EGReleaseTime:102,TVFFilterCutoff:32,drumReverb:29};function Vr(e){let A=()=>{this.channelVibrato.delay===0&&this.channelVibrato.rate===0&&this.channelVibrato.depth===0&&(this.channelVibrato.depth=50,this.channelVibrato.rate=8,this.channelVibrato.delay=.6)},t=(n,s,o)=>{o.length>0&&(o=" "+o),p(`%c${n} for %c${this.channelNumber}%c is now set to %c${s}%c${o}.`,I.info,I.recognized,I.info,I.value,I.info)};switch(this.dataEntryState){default:case YA.Idle:break;case YA.NRPFine:if(this.lockGSNRPNParams)return;let n=this.midiControllers[y.NRPNMsb]>>7,s=this.midiControllers[y.NRPNLsb]>>7;switch(n){default:if(e===64)return;Y(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${s.toString(16).toUpperCase()} 0x${s.toString(16).toUpperCase()})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Oe.partParameter:switch(s){default:if(e===64)return;Y(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${n.toString(16)} 0x${s.toString(16)})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Oe.vibratoRate:if(e===64)return;A(),this.channelVibrato.rate=e/64*8,t("Vibrato rate",`${e} = ${this.channelVibrato.rate}`,"Hz");break;case Oe.vibratoDepth:if(e===64)return;A(),this.channelVibrato.depth=e/2,t("Vibrato depth",`${e} = ${this.channelVibrato.depth}`,"cents of detune");break;case Oe.vibratoDelay:if(e===64)return;A(),this.channelVibrato.delay=e/64/3,t("Vibrato delay",`${e} = ${this.channelVibrato.delay}`,"seconds");break;case Oe.TVFFilterCutoff:this.controllerChange(y.brightness,e),t("Filter cutoff",e.toString(),"");break;case Oe.EGAttackTime:this.controllerChange(y.attackTime,e),t("EG attack time",e.toString(),"");break;case Oe.EGReleaseTime:this.controllerChange(y.releaseTime,e),t("EG release time",e.toString(),"");break}break;case Oe.drumReverb:let r=e;this.controllerChange(y.reverbDepth,r),t("GS Drum reverb",r.toString(),"percent");break}break;case YA.RPCoarse:case YA.RPFine:let o=this.midiControllers[y.RPNMsb]|this.midiControllers[y.RPNLsb]>>7;switch(o){default:Y(`%cUnrecognized RPN for %c${this.channelNumber}%c: %c(0x${o.toString(16)})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Ut.pitchBendRange:this.midiControllers[xA+j.pitchWheelRange]=e<<7,t("Pitch bend range",e.toString(),"semitones");break;case Ut.coarseTuning:let r=e-64;this.setCustomController(cA.channelTuningSemitones,r),t("Coarse tuning",r.toString(),"semitones");break;case Ut.fineTuning:this.setTuning(e-64,!1);break;case Ut.modulationDepth:this.setModulationDepth(e*100);break;case Ut.resetParameters:this.resetParameters();break}}}var Tt={0:0,1:.006,2:.023,4:.05,8:.11,16:.25,32:.5,64:2.06,80:4.2,96:8.4,112:19.5,116:26.7,120:40,124:80,127:480};function Ui(e){if(Tt[e]!==void 0)return Tt[e];let A=null,t=null;for(let n of Object.keys(Tt))n=parseInt(n),nA)&&(A=n),n>e&&(t===null||n200&&A<40||this.synth.highPerformanceMode&&A<10||this.isMuted)return;let o=e+this.channelTransposeKeyShift,r=o;if(o>127||o<0)return;let E=this.preset.program;this.synth.tunings[E]?.[o]?.midiNote>=0&&(r=this.synth.tunings[E]?.[o].midiNote),this.velocityOverride>0&&(A=this.velocityOverride);let a=this.synth.keyModifierManager.getVelocity(this.channelNumber,o);a>-1&&(A=a);let C=-1,c=0,h=this.midiControllers[y.portamentoTime]>>7,d=this.midiControllers[y.portamentoControl],B=d>>7;if(!this.drumChannel&&B!==r&&this.midiControllers[y.portamentoOnOff]>=8192&&h>0){if(d!==1){let w=Math.abs(r-B);c=Zr(h,w),C=B}this.controllerChange(y.portamentoControl,r)}let m=this.synth.getWorkletVoices(this.channelNumber,r,A,s,o,t),u=0;this.randomPan&&(u=Math.round(Math.random()*1e3-500));let S=this.voices;m.forEach(w=>{w.portamentoFromKey=C,w.portamentoDuration=c,w.overridePan=u;let k=w.exclusiveClass;k!==0&&S.forEach(gA=>{gA.exclusiveClass===k&&gA.exclusiveRelease()}),he(w,this.midiControllers);let M=w.modulatedGenerators[i.startAddrsOffset]+w.modulatedGenerators[i.startAddrsCoarseOffset]*32768,L=w.modulatedGenerators[i.endAddrOffset]+w.modulatedGenerators[i.endAddrsCoarseOffset]*32768,G=w.modulatedGenerators[i.startloopAddrsOffset]+w.modulatedGenerators[i.startloopAddrsCoarseOffset]*32768,g=w.modulatedGenerators[i.endloopAddrsOffset]+w.modulatedGenerators[i.endloopAddrsCoarseOffset]*32768,x=w.sample,O=gA=>Math.max(0,Math.min(x.sampleData.length-1,gA));if(x.cursor=O(x.cursor+M),x.end=O(x.end+L),x.loopStart=O(x.loopStart+G),x.loopEnd=O(x.loopEnd+g),x.loopEndthis.synth.voiceCap&&this.synth.voiceKilling(m.length),S.push(...m),n&&(this.sendChannelProperty(),this.synth.callEvent("noteon",{midiNote:e,channel:this.channelNumber,velocity:A}))}function Wr(e){if(e>127||e<0){Y("Received a noteOn for note",e,"Ignoring.");return}let A=e+this.channelTransposeKeyShift;if(this.synth.highPerformanceMode&&!this.drumChannel){this.killNote(A,-6950),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber});return}this.voices.forEach(n=>{n.realKey!==A||n.isInRelease===!0||(this.holdPedal?this.sustainedVoices.push(n):n.release())}),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber})}function _r(e,A){this.voices.forEach(t=>{t.midiNote===e&&(t.pressure=A,he(t,this.midiControllers,0,j.polyPressure))}),this.synth.callEvent("polypressure",{channel:this.channelNumber,midiNote:e,pressure:A})}function zr(e){this.midiControllers[xA+j.channelPressure]=e<<7,this.voices.forEach(A=>he(A,this.midiControllers,0,j.channelPressure)),this.synth.callEvent("channelpressure",{channel:this.channelNumber,pressure:e})}function jr(e,A){if(this.lockedControllers[xA+j.pitchWheel])return;let t=A|e<<7;this.synth.callEvent("pitchwheel",{channel:this.channelNumber,MSB:e,LSB:A}),this.midiControllers[xA+j.pitchWheel]=t,this.voices.forEach(n=>he(n,this.midiControllers,0,j.pitchWheel)),this.sendChannelProperty()}function $r(e){if(e.length!==12)throw new Error("Tuning is not the length of 12.");this.channelOctaveTuning=new Int8Array(128);for(let A=0;A<128;A++)this.channelOctaveTuning[A]=e[A%12]}function Ai(e,A=!1){if(this.lockPreset)return;let t=this.getBankSelect(),n,s,o=this.isXGChannel;if(this.synth.overrideSoundfont){let r=t===128?128:t-this.synth.soundfontBankOffset,E=this.synth.overrideSoundfont.getPresetNoFallback(r,e,o);if(E)n=E.bank===128?128:E.bank+this.synth.soundfontBankOffset,s=E,this.presetUsesOverride=!0;else{s=this.synth.soundfontManager.getPreset(t,e,o);let a=this.synth.soundfontManager.soundfontList.find(C=>C.soundfont===s.parentSoundBank).bankOffset;n=s.bank-a,this.presetUsesOverride=!1}}else{s=this.synth.soundfontManager.getPreset(t,e,o);let r=this.synth.soundfontManager.soundfontList.find(E=>E.soundfont===s.parentSoundBank).bankOffset;n=s.bank-r,this.presetUsesOverride=!1}this.setPreset(s),this.sentBank=n,this.synth.callEvent("programchange",{channel:this.channelNumber,program:s.program,bank:n,userCalled:A}),this.sendChannelProperty()}var DA=class{midiControllers=new Int16Array(zt);lockedControllers=Array(zt).fill(!1);customControllers=new Float32Array(Kn);channelTransposeKeyShift=0;channelOctaveTuning=new Int8Array(128);channelTuningCents=0;holdPedal=!1;drumChannel=!1;velocityOverride=0;randomPan=!1;dataEntryState=YA.Idle;bank=0;sentBank=0;bankLSB=0;preset=void 0;lockPreset=!1;lockedSystem="gs";presetUsesOverride=!1;lockGSNRPNParams=!1;channelVibrato={delay:0,depth:0,rate:0};isMuted=!1;voices=[];sustainedVoices=[];channelNumber;synth;constructor(A,t,n){this.synth=A,this.preset=t,this.channelNumber=n}get isXGChannel(){return RA(this.synth.system)||this.lockPreset&&RA(this.lockedSystem)}setCustomController(A,t){this.customControllers[A]=t,this.updateChannelTuning()}updateChannelTuning(){this.channelTuningCents=this.customControllers[cA.channelTuning]+this.customControllers[cA.channelTransposeFine]+this.customControllers[cA.masterTuning]+this.customControllers[cA.channelTuningSemitones]*100}renderAudio(A,t,n,s,o,r){this.voices=this.voices.filter(E=>!this.renderVoice(E,A,t,n,s,o,r))}setPresetLock(A){this.lockPreset=A,A&&(this.lockedSystem=this.synth.system)}setBankSelect(A,t=!1){if(!this.lockPreset)if(t)this.bankLSB=A;else switch(this.bank=A,Ct(this.getBankSelect(),A,this.synth.system,!1,this.drumChannel,this.channelNumber).drumsStatus){default:case 0:break;case 1:this.channelNumber%16===9&&(this.bank=127);break;case 2:this.setDrums(!0);break}}getBankSelect(){return Et(this.bank,this.bankLSB,this.drumChannel,this.isXGChannel)}setPreset(A){this.lockPreset||(delete this.preset,this.preset=A)}setDrums(A){this.lockPreset||this.drumChannel!==A&&(A?(this.channelTransposeKeyShift=0,this.drumChannel=!0):this.drumChannel=!1,this.presetUsesOverride=!1,this.synth.callEvent("drumchange",{channel:this.channelNumber,isDrumChannel:this.drumChannel}),this.programChange(this.preset.program),this.sendChannelProperty())}setVibrato(A,t,n){this.lockGSNRPNParams||(this.channelVibrato.rate=t,this.channelVibrato.delay=n,this.channelVibrato.depth=A)}disableAndLockGSNRPN(){this.lockGSNRPNParams=!0,this.channelVibrato.rate=0,this.channelVibrato.delay=0,this.channelVibrato.depth=0}sendChannelProperty(){if(!this.synth.enableEventSystem)return;let A={voicesAmount:this.voices.length,pitchBend:this.midiControllers[xA+j.pitchWheel],pitchBendRangeSemitones:this.midiControllers[xA+j.pitchWheelRange]/128,isMuted:this.isMuted,isDrum:this.drumChannel,transposition:this.channelTransposeKeyShift+this.customControllers[cA.channelTransposeFine]/100,bank:this.sentBank,program:this.preset.program};this.synth.post({messageType:JA.channelPropertyChange,messageData:[this.channelNumber,A]})}};DA.prototype.renderVoice=Ur;DA.prototype.panVoice=Dr;DA.prototype.killNote=Tr;DA.prototype.stopAllNotes=Or;DA.prototype.muteChannel=qr;DA.prototype.noteOn=Xr;DA.prototype.noteOff=Wr;DA.prototype.polyPressure=_r;DA.prototype.channelPressure=zr;DA.prototype.pitchWheel=jr;DA.prototype.programChange=Ai;DA.prototype.setTuning=vr;DA.prototype.setOctaveTuning=$r;DA.prototype.setModulationDepth=Hr;DA.prototype.transposeChannel=Pr;DA.prototype.controllerChange=Kr;DA.prototype.resetControllers=io;DA.prototype.resetControllersRP15Compliant=ao;DA.prototype.resetParameters=Io;DA.prototype.dataEntryFine=Yr;DA.prototype.dataEntryCoarse=Vr;function ei(e=!1){let A=new DA(this,this.defaultPreset,this.workletProcessorChannels.length);this.workletProcessorChannels.push(A),A.resetControllers(),A.sendChannelProperty(),e&&this.callEvent("newchannel",void 0),A.channelNumber%16===9&&this.workletProcessorChannels[this.workletProcessorChannels.length-1].setDrums(!0)}function ti(e,A){e===void 0&&(e={});for(let t in A)A.hasOwnProperty(t)&&!(t in e)&&(e[t]=A[t]);return e}var ni={skipToFirstNoteOn:!0,autoPlay:!0,preservePlaybackState:!1};var dr=.03,ur=.07,ns=1,wA=class extends AudioWorkletProcessor{cachedVoices=[];alive=!0;deviceID=ie;interpolationType=lt.fourthOrder;sequencer=new kA(this);transposition=0;tunings=[];soundfontBankOffset=0;masterGain=ns;midiVolume=1;reverbGain=1;chorusGain=1;voiceCap=350;pan=0;panLeft=.5;panRight=.5;highPerformanceMode=!1;keyModifierManager=new pn;overrideSoundfont=void 0;workletProcessorChannels=[];system=$t;totalVoicesAmount=0;defaultPreset;defaultPresetUsesOverride=!1;drumPreset;defaultDrumsUsesOverride=!1;processorInitialized=me.isInitialized;constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem;for(let t=0;t<127;t++)this.tunings.push([]);try{this.soundfontManager=new mn(A.processorOptions.soundfont,this.postReady.bind(this))}catch(t){throw this.post({messageType:JA.soundfontError,messageData:t}),t}this.sendPresetList(),this.getDefaultPresets();for(let t=0;tthis.handleMessage(t.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),p("%cRendering enabled! Starting render.",I.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.voiceCap=1/0,this.processorInitialized.then(()=>{let t=ti(A.processorOptions.startRenderingData.sequencerOptions,ni);this.sequencer.skipToFirstNoteOn=t.skipToFirstNoteOn,this.sequencer.preservePlaybackState=t.preservePlaybackState,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI])}))),this.postReady()}get currentGain(){return this.masterGain*this.midiVolume}getDefaultPresets(){let A=this.system;this.system="xg",this.defaultPreset=this.getPreset(0,0),this.defaultPresetUsesOverride=this.overrideSoundfont?.presets?.indexOf(this.defaultPreset)>=0,this.system=A,this.drumPreset=this.getPreset(128,0),this.defaultDrumsUsesOverride=this.overrideSoundfont?.presets?.indexOf(this.drumPreset)>=0}setSystem(A){this.system=A,this.post({messageType:JA.masterParameterChange,messageData:[Ue.midiSystem,this.system]})}getCachedVoice(A,t,n,s){return this.cachedVoices?.[A]?.[t]?.[n]?.[s]}setCachedVoice(A,t,n,s,o){this.cachedVoices||(this.cachedVoices=[]),this.cachedVoices[A]||(this.cachedVoices[A]=[]),this.cachedVoices[A][t]||(this.cachedVoices[A][t]=[]),this.cachedVoices[A][t][n]||(this.cachedVoices[A][t][n]=[]),this.cachedVoices[A][t][n][s]=o}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.processorInitialized.then(()=>{this.port.postMessage({messageType:JA.isFullyInitialized,messageData:void 0}),p("%cSpessaSynth is ready!",I.recognized)})}debugMessage(){p({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){return this.alive?(this.sequencer.processTick(),this.totalVoicesAmount=0,this.workletProcessorChannels.forEach((n,s)=>{if(n.voices.length<1||n.isMuted)return;let o=n.voices.length,r,E,a,C,c,h,d;if(this.oneOutputMode){let B=t[0];r=s%16*2,E=B[r],a=B[r+1]}else r=s%this._outputsAmount+2,E=t[r][0],a=t[r][1],C=t[0][0],c=t[0][1],h=t[1][0],d=t[1][1];n.renderAudio(E,a,C,c,h,d),this.totalVoicesAmount+=n.voices.length,n.voices.length!==o&&n.sendChannelProperty()}),!0):!1}destroyWorkletProcessor(){this.alive=!1,this.workletProcessorChannels.forEach(A=>{delete A.midiControllers,delete A.voices,delete A.sustainedVoices,delete A.lockedControllers,delete A.preset,delete A.customControllers}),delete this.cachedVoices,delete this.workletProcessorChannels,delete this.sequencer.midiData,delete this.sequencer,this.soundfontManager.destroyManager(),delete this.soundfontManager}controllerChange(A,t,n,s=!1){this.workletProcessorChannels[A].controllerChange(t,n,s)}noteOn(A,t,n,s=!1,o=!0){this.workletProcessorChannels[A].noteOn(t,n,s,o)}noteOff(A,t){this.workletProcessorChannels[A].noteOff(t)}polyPressure(A,t,n){this.workletProcessorChannels[A].polyPressure(t,n)}channelPressure(A,t){this.workletProcessorChannels[A].channelPressure(t)}pitchWheel(A,t,n){this.workletProcessorChannels[A].pitchWheel(t,n)}programChange(A,t,n=!1){this.workletProcessorChannels[A].programChange(t,n)}};wA.prototype.voiceKilling=po;wA.prototype.getWorkletVoices=Qr;wA.prototype.handleMessage=wo;wA.prototype.callEvent=Fo;wA.prototype.systemExclusive=Ro;wA.prototype.stopAllChannels=kr;wA.prototype.createWorkletChannel=ei;wA.prototype.resetAllControllers=ro;wA.prototype.setMasterGain=xo;wA.prototype.setMasterPan=Mo;wA.prototype.setMIDIVolume=Go;wA.prototype.transposeAllChannels=Mr;wA.prototype.setMasterTuning=Nr;wA.prototype.getPreset=xr;wA.prototype.reloadSoundFont=Fr;wA.prototype.clearSoundFont=Rr;wA.prototype.setEmbeddedSoundFont=wr;wA.prototype.sendPresetList=Gr;wA.prototype.sendSynthesizerSnapshot=br;wA.prototype.applySynthesizerSnapshot=Lr;registerProcessor(Vs,wA);p("%cProcessor succesfully registered!",I.recognized);