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 w={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 at(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,gi=!0;function Ls(e,A,t,n){Ns=e,bs=A,Xt=t,gi=n}function p(...e){Ns&&console.info(...e)}function Y(...e){bs&&console.warn(...e)}function se(...e){Xt&&console.group(...e)}function pA(...e){Xt&&console.groupCollapsed(...e)}function P(){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 Rt(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 Us(e,A){if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=at(e.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=n,t.status){case w.noteOn:let s=e.messageData[1];if(s>0)this.synth.noteOn(t.channel,e.messageData[0],s),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:s});else{this.synth.noteOff(t.channel,e.messageData[0]);let C=this.playingNotes.findIndex(i=>i.midiNote===e.messageData[0]&&i.channel===t.channel);C!==-1&&this.playingNotes.splice(C,1)}break;case w.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let o=this.playingNotes.findIndex(C=>C.midiNote===e.messageData[0]&&C.channel===t.channel);o!==-1&&this.playingNotes.splice(o,1);break;case w.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case w.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case w.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.programChange(t.channel,e.messageData[0]);break;case w.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case w.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case w.systemExclusive:this.synth.systemExclusive(e.messageData,n);break;case w.setTempo:e.messageData.currentIndex=0;let r=6e7/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 w.timeSignature:case w.endOfTrack:case w.midiChannelPrefix:case w.songPosition:case w.activeSensing:case w.keySignature:case w.sequenceNumber:case w.sequenceSpecific:case w.text:case w.lyric:case w.copyright:case w.trackName:case w.marker:case w.cuePoint:case w.instrumentName:case w.programName:break;case w.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case w.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:Y(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(w).find(C=>w[C]===t.status)}`,I.warn,I.unrecognized,I.warn,I.value);break}t.status>=0&&t.status<128&&this.post(UA.metaEvent,[e,A])}function Ts(){for(let e=0;e<16;e++)this.synth.createWorkletChannel(!0)}function vs(){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 Hs(){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 It{isEmbedded=!1;constructor(A){super(),this._copyFromSequence(A),this.isEmbedded=A.embeddedSoundFont!==void 0}},la={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 Ys(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)&&C!==10){if(n){s=!0;continue}else if(C===0){s=!0;continue}}o+=String.fromCharCode(C)}}return o}}function gt(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 gt(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 yA(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 a={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},X=[];X[a.startAddrsOffset]={min:0,max:32768,def:0};X[a.endAddrOffset]={min:-32768,max:32768,def:0};X[a.startloopAddrsOffset]={min:-32768,max:32768,def:0};X[a.endloopAddrsOffset]={min:-32768,max:32768,def:0};X[a.startAddrsCoarseOffset]={min:0,max:32768,def:0};X[a.modLfoToPitch]={min:-12e3,max:12e3,def:0};X[a.vibLfoToPitch]={min:-12e3,max:12e3,def:0};X[a.modEnvToPitch]={min:-12e3,max:12e3,def:0};X[a.initialFilterFc]={min:1500,max:13500,def:13500};X[a.initialFilterQ]={min:0,max:960,def:0};X[a.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};X[a.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};X[a.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};X[a.modLfoToVolume]={min:-960,max:960,def:0};X[a.chorusEffectsSend]={min:0,max:1e3,def:0};X[a.reverbEffectsSend]={min:0,max:1e3,def:0};X[a.pan]={min:-500,max:500,def:0};X[a.delayModLFO]={min:-12e3,max:5e3,def:-12e3};X[a.freqModLFO]={min:-16e3,max:4500,def:0};X[a.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};X[a.freqVibLFO]={min:-16e3,max:4500,def:0};X[a.delayModEnv]={min:-32768,max:5e3,def:-32768};X[a.attackModEnv]={min:-32768,max:8e3,def:-32768};X[a.holdModEnv]={min:-12e3,max:5e3,def:-12e3};X[a.decayModEnv]={min:-12e3,max:8e3,def:-12e3};X[a.sustainModEnv]={min:0,max:1e3,def:0};X[a.releaseModEnv]={min:-7200,max:8e3,def:-12e3};X[a.keyNumToModEnvHold]={min:-1200,max:1200,def:0};X[a.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};X[a.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};X[a.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};X[a.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};X[a.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};X[a.sustainVolEnv]={min:0,max:1440,def:0};X[a.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};X[a.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};X[a.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};X[a.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};X[a.keyNum]={min:-1,max:127,def:-1};X[a.velocity]={min:-1,max:127,def:-1};X[a.initialAttenuation]={min:0,max:1440,def:0};X[a.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};X[a.coarseTune]={min:-120,max:120,def:0};X[a.fineTune]={min:-12700,max:12700,def:0};X[a.scaleTuning]={min:0,max:1200,def:100};X[a.exclusiveClass]={min:0,max:99999,def:0};X[a.overridingRootKey]={min:-1,max:127,def:-1};X[a.sampleModes]={min:0,max:3,def:0};var U=class{generatorType=a.INVALID;generatorValue=0;constructor(A=a.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)),A===a.initialAttenuation&&console.log(this.generatorValue))}}};function Js(e,A,t){let n=X[e]||{min:0,max:32768,def:0},s=A.find(g=>g.generatorType===e),o=0;s&&(o=s.generatorValue);let r=t.find(g=>g.generatorType===e),C=n.def;r&&(C=r.generatorValue);let i=C+o;return e===a.initialAttenuation?i:Math.max(n.min,Math.min(n.max,i))}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},z=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=a.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3,this.isEffectModulator=(this.sourceEnum===219||this.sourceEnum===221)&&this.secondarySourceEnum===0&&(this.modulatorDestination===a.reverbEffectsSend||this.modulatorDestination===a.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(C=>o[C]===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(a,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 Ci=[new z(re(Jn,0,1,0,j.noteOnVelocity),0,a.initialAttenuation,Yn,0),new z(129,0,a.vibLfoToPitch,50,0),new z(re(Jn,0,1,1,y.mainVolume),0,a.initialAttenuation,Yn,0),new z(13,0,a.vibLfoToPitch,50,0),new z(526,16,a.fineTune,12700,0),new z(650,0,a.pan,500,0),new z(re(Jn,0,1,1,y.expressionController),0,a.initialAttenuation,Yn,0),new z(219,0,a.reverbEffectsSend,200,0),new z(221,0,a.chorusEffectsSend,200,0)],Ei=[new z(re(GA.linear,0,0,0,j.polyPressure),0,a.vibLfoToPitch,50,0),new z(re(GA.linear,0,0,1,y.tremoloDepth),0,a.modLfoToVolume,24,0),new z(re(GA.convex,1,0,1,y.attackTime),0,a.attackVolEnv,6e3,0),new z(re(GA.linear,1,0,1,y.releaseTime),0,a.releaseVolEnv,3600,0),new z(re(GA.linear,1,0,1,y.brightness),0,a.initialFilterFc,6e3,0),new z(re(GA.linear,1,0,1,y.filterResonance),0,a.initialFilterQ,250,0)],Ks=Ci.concat(Ei);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},Os={velocityOverride:128};var qs="spessasynth-worklet-system";var $t="gs";function Ct(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,Ps=121;function Vs(e){return e==="gm2"?Ps:0}function jA(e){return e===120||e===126||e===127}function sn(e){return jA(e)||e===on||e===Ps}function Et(e,A,t,n,s,o){let r=e,C=0;if(n)FA(t)?sn(A)||(r=A):t==="gm2"&&(r=A);else{let i=!0;switch(t){case"gm":p(`%cIgnoring the Bank Select (${A}), as the synth is in GM mode.`,I.info),i=!1;break;case"xg":i=sn(A),jA(A)?C=2:o%16!==9&&(C=1);break;case"gm2":A===120?C=2:o%16!==9&&(C=1)}s&&(A=128),A===128&&!s&&(A=e),i&&(r=A)}return{newBank:r,drumsStatus:C}}function Bt(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 FA(e){return e==="gm2"||e==="xg"}function qn(e){return new VA(e,w.systemExclusive,new b([65,16,66,18,64,0,127,0,65,247]))}function ht(e,A,t,n){return new VA(n,w.controllerChange|e%16,new b([A,t]))}function Bi(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,w.systemExclusive,new b([...n,o,247]))}function Zs(e=[],A=[],t=[],n=[]){let s=this;pA("%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(x=>{o.add(x.channel)});let r="gs",C=!1,i=Array(s.tracks.length).fill(0),g=s.tracks.length;function c(){let x=0,G=1/0;return s.tracks.forEach((F,E)=>{i[E]>=F.length||F[i[E]].ticks{f(G,x)});let m=B,S=Array(m).fill(!0),M=Array(m).fill(0),D=Array(m).fill(0);for(n.forEach(x=>{let G=Math.trunc(x.keyShift),F=x.keyShift-G;M[x.channel]=G,D[x.channel]=F});g>0;){let x=c(),G=s.tracks[x];if(i[x]>=G.length){g--;continue}let F=i[x]++,E=G[F],L=()=>{G.splice(F,1),i[x]--},Z=(BA,sA=0)=>{G.splice(F+sA,0,BA),i[x]++},EA=d[h[x]]||0;if(E.messageStatusByte===w.midiPort){f(x,E.messageData[0]);continue}if(E.messageStatusByte<=w.sequenceSpecific&&E.messageStatusByte>=w.sequenceNumber)continue;let tA=E.messageStatusByte&240,T=E.messageStatusByte&15,$=T+EA;if(t.indexOf($)!==-1){L();continue}switch(tA){case w.noteOn:if(S[$]){S[$]=!1,A.filter(CA=>CA.channel===$).forEach(CA=>{let v=ht(T,CA.controllerNumber,CA.controllerValue,E.ticks);Z(v)});let oA=D[$];if(oA!==0){let CA=oA*64+64,v=ht(T,y.RPNMsb,0,E.ticks),J=ht(T,y.RPNLsb,1,E.ticks),W=ht($,y.dataEntryMsb,CA,E.ticks),O=ht(T,y.lsbForControl6DataEntry,0,E.ticks);Z(O),Z(W),Z(J),Z(v)}if(o.has($)){let CA=e.find(rA=>rA.channel===$),v=Math.max(0,Math.min(CA.bank,127)),J=CA.program;p(`%cSetting %c${CA.channel}%c to %c${v}:${J}%c. Track num: %c${x}`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized);let W=new VA(E.ticks,w.programChange|T,new b([J]));Z(W);let O=(rA,KA)=>{let Ie=ht(T,rA?y.lsbForControl0BankSelect:y.bankSelect,KA,E.ticks);Z(Ie)};FA(r)?CA.isDrum?(p(`%cAdding XG Drum change on track %c${x}`,I.recognized,I.value),O(!1,jA(v)?v:127),O(!0,0)):v===on?(O(!1,on),O(!0,0)):(O(!1,0),O(!0,v)):(O(!1,v),CA.isDrum&&T!==9&&(p(`%cAdding GS Drum change on track %c${x}`,I.recognized,I.value),Z(Bi(T,E.ticks))))}}E.messageData[0]+=M[$];break;case w.noteOff:E.messageData[0]+=M[$];break;case w.programChange:if(o.has($)){L();continue}break;case w.controllerChange:let BA=E.messageData[0];if(A.find(oA=>oA.channel===$&&BA===oA.controllerNumber)!==void 0){L();continue}if((BA===y.bankSelect||BA===y.lsbForControl0BankSelect)&&o.has($)){L();continue}break;case w.systemExclusive:if(Ct(E))p("%cXG system on detected",I.info),r="xg",C=!0;else if(E.messageData[0]===67&&E.messageData[2]===76&&E.messageData[3]===8&&E.messageData[5]===3)o.has(E.messageData[4]+EA)&&L();else if(en(E)){C=!0,p("%cGS on detected!",I.recognized);break}else(tn(E)||nn(E))&&(p("%cGM/2 on detected, removing!",I.info),L(),C=!1)}}if(!C&&e.length>0){let x=0;s.tracks[0][0].messageStatusByte===w.trackName&&x++,s.tracks[0].splice(x,0,qn(0)),p("%cGS on not detected. Adding it.",I.info)}this.flush(),P()}function Xs(e){let A=[],t=[],n=[],s=[];e.channelSnapshots.forEach((o,r)=>{if(o.isMuted){t.push(r);return}let C=o.channelTransposeKeyShift+o.customControllers[cA.channelTransposeFine]/100;C!==0&&A.push({channel:r,keyShift:C}),o.lockPreset&&n.push({channel:r,program:o.program,bank:o.bank,isDrum:o.drumChannel}),o.lockedControllers.forEach((i,g)=>{if(!i||g>127||g===y.bankSelect)return;let c=o.midiControllers[g]>>7;s.push({channel:r,controllerNumber:g,controllerValue:c})})}),this.modifyMIDI(n,s,t,A)}var uA={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",hi="Created using SpessaSynth";function Ws(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 M=function(){let F=0,E=1/0;return r.tracks.forEach((L,Z)=>{m[Z]>=L.length||L[m[Z]].ticksE>F?E:F),G=[];for(let F=0;F0;){let F=M(),E=r.tracks[F];if(m[F]>=E.length){S--;continue}let L=E[m[F]];m[F]++;let Z=r.midiPortChannelOffsets[D[F]];if(L.messageStatusByte===w.midiPort){D[F]=L.messageData[0];continue}let EA=L.messageStatusByte&240;if(EA!==w.controllerChange&&EA!==w.programChange&&EA!==w.systemExclusive)continue;if(EA===w.systemExclusive){if(!An(L)){Ct(L)?B="xg":en(L)?B="gs":tn(L)?(B="gm",f.push({tNum:F,e:L})):nn(L)&&(B="gm2");continue}let oA=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][L.messageData[5]&15]+Z;G[oA].drums=!!(L.messageData[7]>0&&L.messageData[5]>>4);continue}let tA=(L.messageStatusByte&15)+Z,T=G[tA];if(EA===w.programChange){let oA=FA(B),CA=L.messageData[0];T.drums?A.presets.findIndex(O=>O.program===CA&&O.isDrumPreset(oA,!0))===-1&&(L.messageData[0]=A.presets.find(O=>O.isDrumPreset(oA))?.program||0,p(`%cNo drum preset %c${CA}%c. Channel %c${tA}%c. Changing program to ${L.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)):A.presets.findIndex(O=>O.program===CA&&!O.isDrumPreset(oA))===-1&&(L.messageData[0]=A.presets.find(O=>!O.isDrumPreset(oA))?.program||0,p(`%cNo preset %c${CA}%c. Channel %c${tA}%c. Changing program to ${L.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)),T.program=L.messageData[0];let v=Math.max(0,T.lastBank?.messageData[1]-r.bankOffset),J=T?.lastBankLSB?.messageData[1]-r.bankOffset||0;if(T.lastBank===void 0)continue;let W=Bt(v,J,T.drums,oA);if(A.presets.findIndex(O=>O.bank===W&&O.program===L.messageData[0])===-1){let O=A.presets.find(rA=>rA.program===L.messageData[0])?.bank+t||t;T.lastBank.messageData[1]=O,T?.lastBankLSB?.messageData&&(T.lastBankLSB.messageData[1]=O),p(`%cNo preset %c${W}:${L.messageData[0]}%c. Channel %c${tA}%c. Changing bank to ${O}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)}else{let O=W;FA(B)&&W===128&&(W=127);let rA=(W===128?128:O)+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}:${L.messageData[0]}%c exists. Channel %c${tA}%c. Changing bank to ${rA}.`,I.info,I.recognized,I.info,I.recognized,I.info)}continue}let $=L.messageData[0]===y.lsbForControl0BankSelect;if(L.messageData[0]!==y.bankSelect&&!$)continue;T.hasBankSelect=!0;let BA=L.messageData[1],sA=Et(T?.lastBank?.messageData[1]||0,BA,B,$,T.drums,tA);sA.drumsStatus===2?T.drums=!0:sA.drumsStatus===1&&(T.drums=!1),$?T.lastBankLSB=L:T.lastBank=L}if(G.forEach((F,E)=>{if(F.hasBankSelect===!0)return;let L=E%16,Z=w.programChange|L,EA=Math.floor(E/16)*16,tA=r.midiPortChannelOffsets.indexOf(EA),T=r.tracks.find((oA,CA)=>r.midiPorts[CA]===tA&&r.usedChannelsOnTrack[CA].has(L));if(T===void 0)return;let $=T.findIndex(oA=>oA.messageStatusByte===Z);if($===-1){let oA=T.findIndex(J=>J.messageStatusByte>128&&J.messageStatusByte<240&&(J.messageStatusByte&15)===L);if(oA===-1)return;let CA=T[oA].ticks,v=A.getPreset(0,0).program;T.splice(oA,0,new VA(CA,w.programChange|L,new b([v]))),$=oA}p(`%cAdding bank select for %c${E}`,I.info,I.recognized);let BA=T[$].ticks,sA=A.getPreset(0,F.program,FA(B))?.bank+t||t;T.splice($,0,new VA(BA,w.controllerChange|L,new b([y.bankSelect,sA])))}),B!=="gs"&&!FA(B)){for(let E of f)r.tracks[E.tNum].splice(r.tracks[E.tNum].indexOf(E.e),1);let F=0;r.tracks[0][0].messageStatusByte===w.trackName&&F++,r.tracks[0].splice(F,0,qn(0))}}let C=new b(r.writeMIDI().buffer),i=[gt("INFO")],g=new TextEncoder;if(i.push(_(uA.software,g.encode("SpessaSynth"),!0)),s.name!==void 0?(i.push(_(uA.name,g.encode(s.name),!0)),n=Le):i.push(_(uA.name,r.rawMidiName,!0)),s.creationDate!==void 0)n=Le,i.push(_(uA.creationDate,g.encode(s.creationDate),!0));else{let B=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});i.push(_(uA.creationDate,fe(B),!0))}if(s.comment!==void 0&&(n=Le,i.push(_(uA.comment,g.encode(s.comment)))),s.engineer!==void 0&&i.push(_(uA.engineer,g.encode(s.engineer),!0)),s.album!==void 0&&(n=Le,i.push(_(uA.album,g.encode(s.album),!0)),i.push(_(uA.album2,g.encode(s.album),!0))),s.artist!==void 0&&(n=Le,i.push(_(uA.artist,g.encode(s.artist),!0))),s.genre!==void 0&&(n=Le,i.push(_(uA.genre,g.encode(s.genre),!0))),s.picture!==void 0&&i.push(_(uA.picture,new Uint8Array(s.picture))),s.copyright!==void 0)n=Le,i.push(_(uA.copyright,g.encode(s.copyright),!0));else{let B=r.copyright.length>0?r.copyright:hi;i.push(_(uA.copyright,fe(B)))}let c=new b(2);Xe(c,t,2),i.push(_(uA.bankOffset,c)),s.midiEncoding!==void 0&&(i.push(_(uA.midiEncoding,g.encode(s.midiEncoding))),n=Le),i.push(_(uA.encoding,fe(n)));let h=wA(i),d=wA([gt("RMID"),_("data",C),_("LIST",h),e]);return p("%cFinished!",I.info),P(),_("RIFF",d)}function _s(){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,C;for(let i of s){let g=i.ticks-r,c;i.messageStatusByte<=w.sequenceSpecific?c=[255,i.messageStatusByte,..._t(i.messageData.length),...i.messageData]:i.messageStatusByte===w.systemExclusive?c=[240,..._t(i.messageData.length),...i.messageData]:(c=[],C!==i.messageStatusByte&&(C=i.messageStatusByte,c.push(i.messageStatusByte)),c.push(...i.messageData)),o.push(..._t(g)),o.push(...c),r+=g}A.push(new Uint8Array(o))}function t(s,o){for(let r=0;rd>h?d:h),n=[];for(let h=0;h{C[f]>=B.length||B[C[f]].ticks{o(h)});i>0;){let h=g(),d=A.tracks[h];if(C[h]>=d.length){i--;continue}let B=d[C[h]];if(C[h]++,B.messageStatusByte===w.midiPort){c[h]=B.messageData[0];continue}let f=B.messageStatusByte&240;if(f!==w.noteOn&&f!==w.controllerChange&&f!==w.programChange&&f!==w.systemExclusive)continue;let m=(B.messageStatusByte&15)+A.midiPortChannelOffsets[c[h]]||0,S=n[m];switch(f){case w.programChange:S.program=B.messageData[0],o(S);break;case w.controllerChange:let M=B.messageData[0]===y.lsbForControl0BankSelect;if(B.messageData[0]!==y.bankSelect&&!M||s==="gs"&&S.drums)continue;let D=B.messageData[1],x=Math.max(0,D-A.bankOffset);switch(M?S.bankLSB=x:S.bank=x,Et(S.bank,x,s,M,S.drums,m).drumsStatus){case 0:break;case 1:S.drums=!1,o(S);break;case 2:S.drums=!0,o(S);break}break;case w.noteOn:if(B.messageData[1]===0)continue;r[S.string].add(`${B.messageData[0]}-${B.messageData[1]}`);break;case w.systemExclusive:if(!An(B)){Ct(B)&&(s="xg",p("%cXG on detected!",I.recognized));continue}let F=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][B.messageData[5]&15]+A.midiPortChannelOffsets[c[h]],E=!!(B.messageData[7]>0&&B.messageData[5]>>4);S=n[F],S.drums=E,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 P(),r}var ge=class e extends It{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&&m.messageStatusByte<240){B=!0;for(let M=0;Mthis.lastVoiceEventTick&&(this.lastVoiceEventTick=m.ticks),m.messageStatusByte&240){case w.controllerChange:switch(m.messageData[0]){case 2:case 116:o=m.ticks;break;case 4:case 117:r===null?r=m.ticks:r=0;break;case 0:this.isDLSRMIDI&&m.messageData[1]!==0&&m.messageData[1]!==127&&(p("%cDLS RMIDI with offset 1 detected!",I.recognized),this.bankOffset=1)}break;case w.noteOn:d.add(m.messageStatusByte&15);let M=m.messageData[0];this.keyRange.min=Math.min(this.keyRange.min,M),this.keyRange.max=Math.max(this.keyRange.max,M);break}}m.messageData.currentIndex=0;let S=eA(m.messageData,m.messageData.length);switch(m.messageData.currentIndex=0,m.messageStatusByte){case w.setTempo:m.messageData.currentIndex=0,this.tempoChanges.push({ticks:m.ticks,tempo:6e7/oe(m.messageData,3)}),m.messageData.currentIndex=0;break;case w.marker:switch(S.trim().toLowerCase()){default:break;case"start":case"loopstart":o=m.ticks;break;case"loopend":r=m.ticks}m.messageData.currentIndex=0;break;case w.copyright:n||(m.messageData.currentIndex=0,t.push(eA(m.messageData,m.messageData.length,void 0,!1)),m.messageData.currentIndex=0);break;case w.lyric:if(S.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,p("%cKaraoke MIDI detected!",I.recognized)),this.isKaraokeFile)m.messageStatusByte=w.text;else{this.lyrics.push(m.messageData),this.lyricsTicks.push(m.ticks);break}case w.text:let D=S.trim();D.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,p("%cKaraoke MIDI detected!",I.recognized)):this.isKaraokeFile&&(D.startsWith("@T")||D.startsWith("@A")?A?t.push(D.substring(2).trim()):(this.midiName=D.substring(2).trim(),A=!0,s=!0,this.rawMidiName=gt(this.midiName)):D[0]!=="@"&&(this.lyrics.push(Gs(m.messageData)),this.lyricsTicks.push(m.ticks)));break;case w.trackName:break}}this.usedChannelsOnTrack.push(d),this.trackNames[c]="";let f=h.find(m=>m.messageStatusByte===w.trackName);if(f){f.messageData.currentIndex=0;let m=eA(f.messageData,f.messageData.length);this.trackNames[c]=m,B||t.push(m)}}this.tempoChanges.reverse(),p("%cCorrecting loops, ports and detecting notes...",I.info);let C=[];for(let c of this.tracks){let h=c.find(d=>(d.messageStatusByte&240)===w.noteOn);h&&C.push(h.ticks)}this.firstNoteOn=Math.min(...C),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 i=0;this.midiPorts=[],this.midiPortChannelOffsets=[];for(let c=0;cc&&(g=c);if(g===1/0&&(g=0),this.midiPorts=this.midiPorts.map(c=>c===-1?g: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>=w.noteOn&&c.messageStatusByteh.messageStatusByte===w.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===w.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,w.trackName,new b(this.rawMidiName.buffer))),this.duration=this.MIDIticksToSeconds(this.lastVoiceEventTick),p("%cSuccess!",I.recognized),P()}flush(){for(let A of this.tracks)A.sort((t,n)=>t.ticks-n.ticks);this._parseInternal()}};ge.prototype.writeMIDI=_s;ge.prototype.modifyMIDI=Zs;ge.prototype.applySnapshotToMIDI=Xs;ge.prototype.writeRMIDI=Ws;ge.prototype.getUsedProgramsAndKeys=zs;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),O=0;O<31;++O)W[O]=J+=1<>1|(D&21845)<<1,f=(f&52428)>>2|(f&13107)<<2,f=(f&61680)>>4|(f&3855)<<4,B[D]=((f&65280)>>8|(f&255)<<8)>>1;var f,D,m=function(v,J,W){for(var O=v.length,rA=0,KA=new A(J);rA>le]=$e}else for(ce=new A(O),rA=0;rA>15-v[rA]);return ce},S=new e(288);for(D=0;D<144;++D)S[D]=8;var D;for(D=144;D<256;++D)S[D]=9;var D;for(D=256;D<280;++D)S[D]=7;var D;for(D=280;D<288;++D)S[D]=8;var D,M=new e(32);for(D=0;D<32;++D)M[D]=5;var D,x=m(S,9,1),G=m(M,5,1),F=function(v){for(var J=v[0],W=1;WJ&&(J=v[W]);return J},E=function(v,J,W){var O=J/8|0;return(v[O]|v[O+1]<<8)>>(J&7)&W},L=function(v,J){var W=J/8|0;return(v[W]|v[W+1]<<8|v[W+2]<<16)>>(J&7)},Z=function(v){return(v+7)/8|0},EA=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 O=new Error(J||tA[v]);if(O.code=v,Error.captureStackTrace&&Error.captureStackTrace(O,T),!W)throw O;return O},$=function(v,J,W,O){var rA=v.length,KA=O?O.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(Ot){var Me=W.length;if(Ot>Me){var St=new e(Math.max(Me*2,Ot));St.set(W),W=St}},pe=J.f||0,aA=J.p||0,lA=J.b||0,Qe=J.l,XA=J.d,Re=J.m,Ge=J.n,ut=rA*8;do{if(!Qe){pe=E(v,aA,1);var At=E(v,aA+1,3);if(aA+=3,At)if(At==1)Qe=x,XA=G,Re=9,Ge=5;else if(At==2){var ft=E(v,aA,31)+257,kn=E(v,aA+10,15)+4,wn=ft+E(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,pt=0;for(OA==16?(pt=3+E(v,aA,3),aA+=2,ye=et[WA-1]):OA==17?(pt=3+E(v,aA,7),aA+=3):OA==18&&(pt=11+E(v,aA,127),aA+=7);pt--;)et[WA++]=ye}}var Rn=et.subarray(0,ft),Se=et.subarray(ft);Re=F(Rn),Ge=F(Se),Qe=m(Rn,Re,1),XA=m(Se,Ge,1)}else T(1);else{var OA=Z(aA)+4,Yt=v[OA-4]|v[OA-3]<<8,Jt=OA+Yt;if(Jt>rA){le&&T(0);break}ce&&$e(lA+Yt),W.set(v.subarray(OA,Jt),lA),J.b=lA+=Yt,J.p=aA=Jt*8,J.f=pe;continue}if(aA>ut){le&&T(0);break}}ce&&$e(lA+131072);for(var ds=(1<>4;if(aA+=ye&15,aA>ut){le&&T(0);break}if(ye||T(2),qe<256)W[lA++]=qe;else if(qe==256){Kt=aA,Qe=null;break}else{var Gn=qe-254;if(qe>264){var WA=qe-257,De=n[WA];Gn=E(v,aA,(1<>4;nt||T(3),aA+=nt&15;var Se=h[Pe];if(Pe>3){var De=s[Pe];Se+=L(v,aA)&(1<ut){le&&T(0);break}ce&&$e(lA+131072);var yt=lA+Gn;if(lAVn[m]===i);else{let m=yA(C);i=eA(C,m),g=i}let f=yA(C);if(f===0){let m=yA(C),S=C.slice(C.currentIndex,C.currentIndex+m);C.currentIndex+=m,yA(S)<4?this.metadata[g]=eA(S,m-1):this.metadata[g]=S.slice(S.currentIndex)}else Y(`International content: ${f}`),C.currentIndex+=yA(C)}let c=r.currentIndex,h=yA(r),d=r.slice(r.currentIndex,c+h);if(r.currentIndex=c+h,h>0)for(this.packedContent=!0;d.currentIndexZn[S]===m)}}else for(this.resourceFormat="folder";this.nodeData.currentIndex{let g=(c,h)=>{i.metadata[c]!==void 0&&typeof i.metadata[c]=="string"&&(e.RMIDInfo[h]=i.metadata[c])};if(g("nodeName",uA.name),g("title",uA.name),g("copyrightNotice",uA.copyright),g("comment",uA.comment),i.isFile)switch(i.resourceFormat){default:return;case"DLS1":case"DLS2":case"DLS22":case"mobileDLS":p("%cFound embedded DLS!",I.recognized),e.embeddedSoundFont=i.nodeData.buffer;break;case"StandardMIDIFile":case"StandardMIDIFileType1":p("%cFound embedded MIDI!",I.recognized),r=i.nodeData;break}else for(let c of i.innerNodes)C(c)};return C(o),P(),r}var an=class extends ge{constructor(A,t=""){super(),pA("%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 C=eA(n,4,void 0,!1);if(C!=="RMID")throw P(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${C}"`);let i=IA(n);if(i.header!=="data")throw P(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${C}"`);for(s=i.chunkData;n.currentIndex<=n.length;){let g=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(g,g+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[uA.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[uA.bankOffset]&&(this.bankOffset=N(this.RMIDInfo[uA.bankOffset],2))}}this.isDLSRMIDI&&(this.bankOffset=0),this.embeddedSoundFont===void 0&&(this.bankOffset=0)}else o==="XMF_"?s=js(this,n):s=n;let r=this._readMIDIChunk(s);if(r.type!=="MThd")throw P(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${r.type}"`);if(r.size!==6)throw P(),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 C=0;C0&&(h+=this.tracks[C-1][this.tracks[C-1].length-1].ticks);g.data.currentIndex>4],c=B;break}let S=new b(m);S.set(g.data.slice(g.data.currentIndex,g.data.currentIndex+m),0);let M=new VA(h,B,S);i.push(M),g.data.currentIndex+=m}this.tracks.push(i),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(),P(),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 $s(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 eo(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 to(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadCurrentSong()}function no(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadCurrentSong()}function so(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,C=o&127;this.callEvent("pitchwheel",{channel:A,MSB:r,LSB:C})}}this.tunings=[],this.tunings=[];for(let A=0;127>A;A++)this.tunings.push([]);this.setMIDIVolume(1)}function oo(){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 ro(){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 ao(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 i=0;ii===y.dataDecrement||i===y.dataIncrement||i===y.dataEntryMsb||i===y.dataDecrement||i===y.lsbForControl6DataEntry||i===y.RPNLsb||i===y.RPNMsb||i===y.NRPNLsb||i===y.NRPNMsb||i===y.bankSelect||i===y.lsbForControl0BankSelect||i===y.resetAllControllers,r=[];for(let i=0;i=A)break}else if(this.playedTime>=e)break;let c=at(g.messageStatusByte),h=c.channel+(this.midiPortChannelOffsets[this.midiPorts[i]]||0);switch(c.status){case w.noteOn:r[h]===void 0&&(r[h]=Array.from(We)),r[h][y.portamentoControl]=g.messageData[0];break;case w.noteOff:break;case w.pitchBend:n[h]=g.messageData[1]<<7|g.messageData[0];break;case w.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[i].size===0)break;let B=s[h];B.program=g.messageData[0],B.actualBank=B.bank;break;case w.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[i].size===0)break;let f=g.messageData[0];if(o(f)){let m=g.messageData[1];if(f===y.bankSelect){s[h].bank=m;break}else f===y.resetAllControllers&&C(h);this.sendMIDIMessages?this.sendMIDICC(h,f,m):this.synth.controllerChange(h,f,m)}else r[h]===void 0&&(r[h]=Array.from(We)),r[h][f]=g.messageData[1];break;default:this._processEvent(g,i);break}this.eventIndex[i]++,i=this._findFirstEventIndex();let d=this.tracks[i][this.eventIndex[i]];if(d===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(d.ticks-g.ticks)}if(this.sendMIDIMessages){for(let i=0;i>7,n[i]&127),r[i]!==void 0&&r[i].forEach((g,c)=>{g!==We[c]&&!o(c)&&this.sendMIDICC(i,c,g)}),s[i].program>=0&&s[i].actualBank>=0){let g=s[i].actualBank;this.sendMIDICC(i,y.bankSelect,g),this.sendMIDIProgramChange(i,s[i].program)}}else for(let i=0;i>7,n[i]&127),r[i]!==void 0&&r[i].forEach((g,c)=>{g!==We[c]&&!o(c)&&this.synth.controllerChange(i,c,g)}),s[i].program>=0&&s[i].actualBank>=0){let g=s[i].actualBank;this.synth.controllerChange(i,y.bankSelect,g),this.synth.programChange(i,s[i].program)}return!0}function Io(e=!1){if(this.midiData!==void 0){if(e){this.pausedTime=void 0,this.currentTime=0;return}if(this.currentTime>=this.duration){this.pausedTime=void 0,this.currentTime=0;return}this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),this.sendMIDIMessages||this.playingNotes.forEach(A=>{this.synth.noteOn(A.channel,A.midiNote,A.velocity)}),this.setProcessHandler()}}function go(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 Co(e){this.absoluteStartTime=currentTime-e/this._playbackRate}var RA={midiMessage:0,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,setMasterParameter:17,setDrums:18,transpose:19,highPerformanceMode:20,lockController:21,sequencerSpecific:22,requestSynthesizerSnapshot:23,setLogLevel:24,keyModifierManager:25,setEffectsGain:26,destroyWorklet:27},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 Eo(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 Bo(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:JA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function ho(e){this.post(UA.midiEvent,e)}function co(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.controllerChange|e,A,t])}function lo(e,A){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.programChange|e,A])}function Qo(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.pitchBend|e,t,A])}function uo(){if(this.sendMIDIMessages){this.sendMIDIMessage([w.reset]);for(let e=0;e<16;e++)this.sendMIDIMessage([w.controllerChange|e,y.allSoundOff,0]),this.sendMIDIMessage([w.controllerChange|e,y.resetAllControllers,0])}}var DA=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)}}};DA.prototype.sendMIDIMessage=ho;DA.prototype.sendMIDIReset=uo;DA.prototype.sendMIDICC=co;DA.prototype.sendMIDIProgramChange=lo;DA.prototype.sendMIDIPitchWheel=Qo;DA.prototype.assignMIDIPort=$s;DA.prototype.post=Bo;DA.prototype.processMessage=Eo;DA.prototype._processEvent=Us;DA.prototype._addNewMidiPort=Ts;DA.prototype.processTick=vs;DA.prototype._findFirstEventIndex=Hs;DA.prototype.loadNewSequence=Ao;DA.prototype.loadNewSongList=eo;DA.prototype.nextSong=to;DA.prototype.previousSong=no;DA.prototype.play=Io;DA.prototype._playTo=ao;DA.prototype.setTimeTicks=go;DA.prototype._recalculateStartTime=Co;function li(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 fo(e){let A=[];for(let n of this.workletProcessorChannels)for(let s of n.voices)if(!s.finished){let o=li(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:{},mo=!1,po;me.isInitialized=new Promise(e=>po=e);var Qi=function(e){var A,t,n,s,o,r,C,i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",g="",c=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");do s=i.indexOf(e.charAt(c++)),o=i.indexOf(e.charAt(c++)),r=i.indexOf(e.charAt(c++)),C=i.indexOf(e.charAt(c++)),A=s<<2|o>>4,t=(15&o)<<4|r>>2,n=(3&r)<<6|C,g+=String.fromCharCode(A),r!==64&&(g+=String.fromCharCode(t)),C!==64&&(g+=String.fromCharCode(n));while(c1&&(E.thisProgram=process.argv[1].replace(/\\/g,"/")),E.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(l){if(!(l instanceof kt))throw l}),process.on("unhandledRejection",function(l,Q){process.exit(1)}),E.quit=function(l){process.exit(l)},E.inspect=function(){return"[Emscripten Module object]"}):T?(typeof read<"u"&&(E.read=function(Q){return read(Q)}),E.readBinary=function(Q){var u;return typeof readbuffer=="function"?new Uint8Array(readbuffer(Q)):(XA(typeof(u=read(Q,"binary"))=="object"),u)},typeof scriptArgs<"u"?E.arguments=scriptArgs:typeof arguments<"u"&&(E.arguments=arguments),typeof quit=="function"&&(E.quit=function(l){quit(l)})):(Z||EA)&&(Z?document.currentScript&&($=document.currentScript.src):$=self.location.href,$=$.indexOf("blob:")!==0?$.split("/").slice(0,-1).join("/")+"/":"",E.read=function(Q){var u=new XMLHttpRequest;return u.open("GET",Q,!1),u.send(null),u.responseText},EA&&(E.readBinary=function(Q){var u=new XMLHttpRequest;return u.open("GET",Q,!1),u.responseType="arraybuffer",u.send(null),new Uint8Array(u.response)}),E.readAsync=function(Q,u,k){var K=new XMLHttpRequest;K.open("GET",Q,!0),K.responseType="arraybuffer",K.onload=function(){if(K.status==200||K.status==0&&K.response){u(K.response);return}k()},K.onerror=k,K.send(null)},E.setWindowTitle=function(l){document.title=l});var sA=E.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),oA=E.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||sA);for(e in L)L.hasOwnProperty(e)&&(E[e]=L[e]);function CA(l){var Q=B;return B=B+l+15&-16,Q}function v(l){var Q=i[x>>2],u=Q+l+15&-16;return i[x>>2]=u,u>=NA&&!yt()?(i[x>>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 O(l){O.shown||(O.shown={}),O.shown[l]||(O.shown[l]=1,oA(l))}L=void 0;var rA={"f64-rem":function(l,Q){return l%Q},debugger:function(){}},KA=[];function Ie(l,Q){for(var u=0,k=u;k>>0)+4294967296*+(Q>>>0):+(l>>>0)+4294967296*+(0|Q)}function aA(l,Q,u){return u&&u.length?E["dynCall_"+l].apply(null,[Q].concat(u)):E["dynCall_"+l].call(null,Q)}var lA=0,Qe=0;function XA(l,Q){l||ke("Assertion failed: "+Q)}function Re(l){var Q=E["_"+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,u,k=Vt(l.length);return Q=l,u=k,s.set(Q,u),k},stringToC:function(l){var Q=0;if(l!=null&&l!==0){var u=(l.length<<2)+1;Q=Vt(u),mt(l,Q,u)}return Q}},ut={string:Ge.stringToC,array:Ge.arrayToC};function At(l,Q,u,k,K){var iA=Re(l),gA=[],V=0;if(k)for(var LA=0;LA>0]=Q;break;case"i16":r[l>>1]=Q;break;case"i32":i[l>>2]=Q;break;case"i64":tempI64=[Q>>>0,+oi(tempDouble=Q)>=1?tempDouble>0?(0|ii(+ys(tempDouble/4294967296),4294967295))>>>0:~~+ri((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],i[l>>2]=tempI64[0],i[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: "+u)}}function kn(l,Q,u){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 i[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,u,k){typeof l=="number"?(iA=!0,gA=l):(iA=!1,gA=l.length);var K=typeof Q=="string"?Q:null;if(V=u==4?k:[typeof Pt=="function"?Pt:CA,Vt,CA,v][u===void 0?2:u](Math.max(gA,K?1:Q.length)),iA){for(k=V,XA((3&V)==0),LA=V+(-4&gA);k>2]=0;for(LA=V+gA;k>0]=0;return V}if(K==="i8")return l.subarray||l.slice?o.set(l,V):o.set(new Uint8Array(l),V),V;for(var iA,gA,V,LA,fA,mA,QA,nA=0;nA>0],(k!=0||Q)&&(gA++,!Q||gA!=Q););Q||(Q=gA);var V="";if(iA<128){for(;Q>0;)K=String.fromCharCode.apply(String,o.subarray(l,l+Math.min(Q,1024))),V=V?V+K:K,l+=1024,Q-=1024;return V}return u=l,function(fA,mA){for(var QA=mA;fA[QA];)++QA;if(QA-mA>16&&fA.subarray&&Ht)return Ht.decode(fA.subarray(mA,QA));for(var nA,PA,Ae,ee,te,Ze,ne="";;){if(!(nA=fA[mA++]))return ne;if(!(128&nA)){ne+=String.fromCharCode(nA);continue}if(PA=63&fA[mA++],(224&nA)==192){ne+=String.fromCharCode((31&nA)<<6|PA);continue}if(Ae=63&fA[mA++],(240&nA)==224?nA=(15&nA)<<12|PA<<6|Ae:(ee=63&fA[mA++],(248&nA)==240?nA=(7&nA)<<18|PA<<12|Ae<<6|ee:(te=63&fA[mA++],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&fA[mA++]))),nA<65536)ne+=String.fromCharCode(nA);else{var wt=nA-65536;ne+=String.fromCharCode(55296|wt>>10,56320|1023&wt)}}}(o,u)}function WA(l){for(var Q="";;){var u=s[l++>>0];if(!u)return Q;Q+=String.fromCharCode(u)}}function Fn(l,Q){return function(k,K,iA){for(var gA=0;gA>0]=k.charCodeAt(gA);iA||(s[K>>0]=0)}(l,Q,!1)}var Ht=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function tt(l,Q,u,k){if(!(k>0))return 0;for(var K=u,iA=u+k-1,gA=0;gA=55296&&V<=57343&&(V=65536+((1023&V)<<10)|1023&l.charCodeAt(++gA)),V<=127){if(u>=iA)break;Q[u++]=V}else if(V<=2047){if(u+1>=iA)break;Q[u++]=192|V>>6,Q[u++]=128|63&V}else if(V<=65535){if(u+2>=iA)break;Q[u++]=224|V>>12,Q[u++]=128|V>>6&63,Q[u++]=128|63&V}else if(V<=2097151){if(u+3>=iA)break;Q[u++]=240|V>>18,Q[u++]=128|V>>12&63,Q[u++]=128|V>>6&63,Q[u++]=128|63&V}else if(V<=67108863){if(u+4>=iA)break;Q[u++]=248|V>>24,Q[u++]=128|V>>18&63,Q[u++]=128|V>>12&63,Q[u++]=128|V>>6&63,Q[u++]=128|63&V}else{if(u+5>=iA)break;Q[u++]=252|V>>30,Q[u++]=128|V>>24&63,Q[u++]=128|V>>18&63,Q[u++]=128|V>>12&63,Q[u++]=128|V>>6&63,Q[u++]=128|63&V}}return Q[u]=0,u-K}function mt(l,Q,u){return tt(l,o,Q,u)}function OA(l){for(var Q=0,u=0;u=55296&&k<=57343&&(k=65536+((1023&k)<<10)|1023&l.charCodeAt(++u)),k<=127?++Q:k<=2047?Q+=2:k<=65535?Q+=3:k<=2097151?Q+=4:k<=67108863?Q+=5:Q+=6}return Q}var ye=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function pt(l){for(var Q=l,u=Q>>1;r[u];)++u;if((Q=u<<1)-l>32&&ye)return ye.decode(o.subarray(l,Q));for(var k=0,K="";;){var iA=r[l+2*k>>1];if(iA==0)return K;++k,K+=String.fromCharCode(iA)}}function Rn(l,Q,u){if(u===void 0&&(u=2147483647),u<2)return 0;for(var k=Q,K=(u-=2)<2*l.length?u/2:l.length,iA=0;iA>1]=gA,Q+=2}return r[Q>>1]=0,Q-k}function Se(l){return 2*l.length}function Yt(l){for(var Q=0,u="";;){var k=i[l+4*Q>>2];if(k==0)return u;if(++Q,k>=65536){var K=k-65536;u+=String.fromCharCode(55296|K>>10,56320|1023&K)}else u+=String.fromCharCode(k)}}function Jt(l,Q,u){if(u===void 0&&(u=2147483647),u<4)return 0;for(var k=Q,K=k+u-4,iA=0;iA=55296&&gA<=57343&&(gA=65536+((1023&gA)<<10)|1023&l.charCodeAt(++iA)),i[Q>>2]=gA,(Q+=4)+4>K)break}return i[Q>>2]=0,Q-k}function ds(l){for(var Q=0,u=0;u=55296&&k<=57343&&++u,Q+=4}return Q}function us(l){var Q=OA(l)+1,u=Pt(Q);return u&&tt(l,s,u,Q),u}function Kt(l){var Q=OA(l)+1,u=Vt(Q);return tt(l,s,u,Q),u}function qe(l){return l}function Gn(){var l,Q=function(){var k=Error();if(!k.stack){try{throw Error(0)}catch(K){k=K}if(!k.stack)return"(no stack trace available)"}return k.stack.toString()}();return E.extraStackTrace&&(Q+=` `+E.extraStackTrace()),(l=Q).replace(/__Z[\w\d_]+/g,function(u){var k,K=k=u;return u===K?u:u+" ["+K+"]"})}function De(l,Q){return l%Q>0&&(l+=Q-l%Q),l}function nt(l){E.buffer=n=l}function Pe(){E.HEAP8=s=new Int8Array(n),E.HEAP16=r=new Int16Array(n),E.HEAP32=i=new Int32Array(n),E.HEAPU8=o=new Uint8Array(n),E.HEAPU16=C=new Uint16Array(n),E.HEAPU32=g=new Uint32Array(n),E.HEAPF32=c=new Float32Array(n),E.HEAPF64=h=new Float64Array(n)}function yt(){var l=E.usingWasm?65536:16777216,Q=2147483648-l;if(i[x>>2]>Q)return!1;var u=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 k=E.reallocBuffer(NA);return k&&k.byteLength==NA?(nt(k),Pe(),!0):(NA=u,!1)}d=B=m=S=M=D=x=0,f=!1,E.reallocBuffer||(E.reallocBuffer=function(l){try{if(ArrayBuffer.transfer)Q=ArrayBuffer.transfer(n,l);else{var Q,u=s;Q=new ArrayBuffer(l),new Int8Array(Q).set(u)}}catch{return!1}return!!ai(Q)&&Q});try{(G=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{G=function(Q){return Q.byteLength}}var st=E.TOTAL_STACK||5242880,NA=E.TOTAL_MEMORY||16777216;function Ot(){return NA}function Me(l){for(;l.length>0;){var Q=l.shift();if(typeof Q=="function"){Q();continue}var u=Q.func;typeof u=="number"?Q.arg===void 0?E.dynCall_v(u):E.dynCall_vi(u,Q.arg):u(Q.arg===void 0?null:Q.arg)}}NA=0?l:Q<=32?2*Math.abs(1<=k&&(Q<=32||l>k)&&(l=-2*k+l),l}var oi=Math.abs,ri=Math.ceil,ys=Math.floor,ii=Math.min,Ve=0,Nn=null,Dt=null;function Oi(l){return l}E.preloadedImages={},E.preloadedAudios={};var Ss="data:application/octet-stream;base64,";function qt(l){return String.prototype.startsWith?l.startsWith(Ss):l.indexOf(Ss)===0}(function(){var Q="main.wast",u="main.wasm",k="main.temp.asm.js";qt(Q)||(Q=BA(Q)),qt(u)||(u=BA(u)),qt(k)||(k=BA(k));var K={global:null,env:null,asm2wasm:rA,parent:E},iA=null;function gA(QA){return QA}function V(){try{if(E.wasmBinary)return new Uint8Array(E.wasmBinary);if(E.readBinary)return E.readBinary(u);throw"both async and sync fetching of the wasm failed"}catch(QA){ke(QA)}}E.asmPreload=E.asm;var LA=E.reallocBuffer,fA=function(QA){QA=De(QA,E.usingWasm?65536:16777216);var nA=E.buffer.byteLength;if(E.usingWasm)try{var PA=E.wasmMemory.grow((QA-nA)/65536);return PA!==-1?E.buffer=E.wasmMemory.buffer:null}catch{return null}};E.reallocBuffer=function(QA){return mA==="asmjs"?LA(QA):fA(QA)};var mA="";E.asm=function(QA,nA,PA){var Ae;if(!(nA=Ae=nA).table){var ee,te=E.wasmTableSize;te===void 0&&(te=1024);var Ze=E.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),E.wasmTable=nA.table}return nA.memoryBase||(nA.memoryBase=E.STATIC_BASE),nA.tableBase||(nA.tableBase=0),ee=function(wt,ot,Tn){if(typeof WebAssembly!="object")return oA("no native wasm support detected"),!1;if(!(E.wasmMemory instanceof WebAssembly.Memory))return oA("no native wasm Memory in use"),!1;function Zt(de,ue){if((iA=de.exports).memory){var Ft,vn,ws;Ft=iA.memory,vn=E.buffer,Ft.byteLength0?u:OA(l)+1,K=Array(k),iA=tt(l,K,0,K.length);return Q&&(K.length=iA),K}function Zi(l){for(var Q=[],u=0;u255&&(k&=255),Q.push(String.fromCharCode(k))}return Q.join("")}B+=16,x=CA(4),M=(m=S=J(B))+st,D=J(M),i[x>>2]=D,f=!0,E.wasmTableSize=4,E.wasmMaxTableSize=4,E.asmGlobalArg={},E.asmLibraryArg={abort:ke,assert:XA,enlargeMemory:yt,getTotalMemory:Ot,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,u,k){var K=Ln();try{return E.dynCall_iii(Q,u,k)}catch(iA){if(bn(K),typeof iA!="number"&&iA!=="longjmp")throw iA;E.setThrew(1,0)}},___assert_fail:function(Q,u,k,K){ke("Assertion failed: "+xe(Q)+", at: "+[u?xe(u):"unknown filename",k,K?xe(K):"unknown function"])},___setErrNo:function(Q){return E.___errno_location&&(i[E.___errno_location()>>2]=Q),Q},_abort:function(){E.abort()},_emscripten_memcpy_big:function(Q,u,k){return o.set(o.subarray(u,u+k),Q),Q},_llvm_floor_f64:ys,DYNAMICTOP_PTR:x,tempDoublePtr:_A,ABORT:lA,STACKTOP:S,STACK_MAX:M};var Ds=E.asm(E.asmGlobalArg,E.asmLibraryArg,n);E.asm=Ds,E.___errno_location=function(){return E.asm.___errno_location.apply(null,arguments)};var ai=E._emscripten_replace_memory=function(){return E.asm._emscripten_replace_memory.apply(null,arguments)};E._free=function(){return E.asm._free.apply(null,arguments)};var Pt=E._malloc=function(){return E.asm._malloc.apply(null,arguments)};E._memcpy=function(){return E.asm._memcpy.apply(null,arguments)},E._memset=function(){return E.asm._memset.apply(null,arguments)},E._sbrk=function(){return E.asm._sbrk.apply(null,arguments)},E._stb_vorbis_js_channels=function(){return E.asm._stb_vorbis_js_channels.apply(null,arguments)},E._stb_vorbis_js_close=function(){return E.asm._stb_vorbis_js_close.apply(null,arguments)},E._stb_vorbis_js_decode=function(){return E.asm._stb_vorbis_js_decode.apply(null,arguments)},E._stb_vorbis_js_open=function(){return E.asm._stb_vorbis_js_open.apply(null,arguments)},E._stb_vorbis_js_sample_rate=function(){return E.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},E.establishStackSpace=function(){return E.asm.establishStackSpace.apply(null,arguments)},E.getTempRet0=function(){return E.asm.getTempRet0.apply(null,arguments)},E.runPostSets=function(){return E.asm.runPostSets.apply(null,arguments)},E.setTempRet0=function(){return E.asm.setTempRet0.apply(null,arguments)},E.setThrew=function(){return E.asm.setThrew.apply(null,arguments)};var Vt=E.stackAlloc=function(){return E.asm.stackAlloc.apply(null,arguments)},bn=E.stackRestore=function(){return E.asm.stackRestore.apply(null,arguments)},Ln=E.stackSave=function(){return E.asm.stackSave.apply(null,arguments)};function kt(l){this.name="ExitStatus",this.message="Program terminated with exit("+l+")",this.status=l}function Un(l){l=l||E.arguments,!(Ve>0)&&(function(){if(E.preRun)for(typeof E.preRun=="function"&&(E.preRun=[E.preRun]);E.preRun.length;)ni(E.preRun.shift());Me(St)}(),!(Ve>0)&&(E.calledRun||(E.setStatus?(E.setStatus("Running..."),setTimeout(function(){setTimeout(function(){E.setStatus("")},1),Q()},1)):Q())));function Q(){!E.calledRun&&(E.calledRun=!0,lA||(Mn||(Mn=!0,Me(xn)),Me(fs),E.onRuntimeInitialized&&E.onRuntimeInitialized(),function(){if(E.postRun)for(typeof E.postRun=="function"&&(E.postRun=[E.postRun]);E.postRun.length;)si(E.postRun.shift());Me(ps)}()))}}function Xi(l,Q){(!Q||!E.noExitRuntime||l!==0)&&(E.noExitRuntime||(lA=!0,Qe=l,S=F,Me(ms),ti=!0,E.onExit&&E.onExit(l)),E.quit(l,new kt(l)))}function ke(l){throw E.onAbort&&E.onAbort(l),l!==void 0?(sA(l),oA(l),l=JSON.stringify(l)):l="",lA=!0,Qe=1,"abort("+l+"). Build with -s ASSERTIONS=1 for more info."}if(E.dynCall_iii=function(){return E.asm.dynCall_iii.apply(null,arguments)},E.asm=Ds,E.ccall=At,E.cwrap=function(Q,u,k,K){var iA=(k=k||[]).every(function(gA){return gA==="number"});return u!=="string"&&iA&&!K?Re(Q):function(){return At(Q,u,k,arguments,K)}},kt.prototype=Error(),kt.prototype.constructor=kt,Dt=function l(){E.calledRun||Un(),E.calledRun||(Dt=l)},E.run=Un,E.abort=ke,E.preInit)for(typeof E.preInit=="function"&&(E.preInit=[E.preInit]);E.preInit.length>0;)E.preInit.pop()();E.noExitRuntime=!0,Un(),E.onRuntimeInitialized=()=>{mo=!0,po()},me.decode=function(l){return function(u){if(!mo)throw Error("SF3 decoder has not been initialized yet. Did you await synth.isReady?");var k={};function K(ot){return new Int32Array(E.HEAPU8.buffer,ot,1)[0]}function iA(ot,Tn){var Zt=new ArrayBuffer(Tn*Float32Array.BYTES_PER_ELEMENT),rt=new Float32Array(Zt);return rt.set(new Float32Array(E.HEAPU8.buffer,ot,Tn)),rt}k.open=E.cwrap("stb_vorbis_js_open","number",[]),k.close=E.cwrap("stb_vorbis_js_close","void",["number"]),k.channels=E.cwrap("stb_vorbis_js_channels","number",["number"]),k.sampleRate=E.cwrap("stb_vorbis_js_sample_rate","number",["number"]),k.decode=E.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var gA,V,LA,fA,mA=k.open(),QA=(gA=u,V=u.byteLength,LA=E._malloc(V),(fA=new Uint8Array(E.HEAPU8.buffer,LA,V)).set(new Uint8Array(gA,0,V)),fA),nA=E._malloc(4),PA=E._malloc(4),Ae=k.decode(mA,QA.byteOffset,QA.byteLength,nA,PA);if(E._free(QA.byteOffset),Ae<0)throw k.close(mA),E._free(nA),Error("stbvorbis decode failed: "+Ae);for(var ee=k.channels(mA),te=Array(ee),Ze=new Int32Array(E.HEAPU32.buffer,K(nA),ee),ne=0;neyo?440*Math.pow(2,(e-6900)/1200):jn[~~e-In]}var As=-1660,di=1600,$n=new Float32Array((di-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 So=.01,$A=100,es=90,ui=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=g=>Math.max(0,Math.floor(Ce(g)*t.sampleRate));t.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[a.initialAttenuation],1440))/10,t.attenuationTargetGain=ae(t.attenuationTarget),t.sustainDbRelative=Math.min($A,A.modulatedGenerators[a.sustainVolEnv]/10);let s=Math.min($A,t.sustainDbRelative);t.attackDuration=n(A.modulatedGenerators[a.attackVolEnv]);let o=A.modulatedGenerators[a.decayVolEnv],r=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvDecay],C=s/$A;t.decayDuration=n(o+r)*C,t.releaseDuration=n(A.modulatedGenerators[a.releaseVolEnv]),t.delayEnd=n(A.modulatedGenerators[a.delayVolEnv]),t.attackEnd=t.attackDuration+t.delayEnd;let i=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvHold];if(t.holdEnd=n(A.modulatedGenerators[a.holdVolEnv]+i)+t.attackEnd,t.decayEnd=t.decayDuration+t.holdEnd,t.state===0&&t.attackEnd===0&&(t.state=2),A.isInRelease){let g=Math.max(0,Math.min($A,t.sustainDbRelative)),c=g/$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)*g;break;case 4:t.releaseStartDb=g;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,C=s;if(A.isInRelease){let g=o.currentSampleTime-o.releaseStartTimeSamples;if(g>=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)*C,t[i]*=o.attenuation*ae(o.sustainDbRelative+r),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++i>=t.length)return}}};function Do(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 RA.midiMessage:this.processMessage(...A);break;case RA.customcCcChange:n.setCustomController(A[0],A[1]),n.updateChannelTuning();break;case RA.ccReset:t===ie?this.resetAllControllers():n.resetControllers();break;case RA.setChannelVibrato:if(t===ie)for(let r=0;r>1&1)===1&&this.workletProcessorChannels[15+A].setOctaveTuning(i);for(let g=0;g<7;g++)(e[5]>>g&1)===1&&this.workletProcessorChannels[7+g+A].setOctaveTuning(i);for(let g=0;g<7;g++)(e[6]>>g&1)===1&&this.workletProcessorChannels[g+A].setOctaveTuning(i);p(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${i.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 C=s>0&&e[5]>>4;r.setDrums(C),p(`%cChannel %c${o}%c ${C?"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 i=s-64;r.transposeChannel(i),p(`%cChannel %c${o}%c pitch shift. Semitones %c${i}%c, with %c${HA(e)}`,I.info,I.recognized,I.info,I.value,I.info,I.value);return;case 28:let g=s;g===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,g));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 C=r-64;o.channelTransposeKeyShift=C;break;case 11:o.controllerChange(y.mainVolume,r);break;case 14:let i=r;i===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,i);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 FA(this.system)&&Y(`%cUnrecognized Yamaha XG SysEx: %c${HA(e)}`,I.warn,I.unrecognized);else FA(this.system)&&Y(`%cUnrecognized Yamaha SysEx: %c${HA(e)}`,I.warn,I.unrecognized);break}}function Fo(e){this.midiVolume=Math.pow(e,Math.E),this.setMasterPan(this.pan)}function Ro(e){this.masterGain=e*ns,this.setMasterPan(this.pan)}function Go(e){this.pan=e,e=e/2+.5,this.panLeft=1-e,this.panRight=e}var xt={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};function xo(){let e=4;for(let n of this.instruments)e+=n.instrumentZones.reduce((s,o)=>(o.generators=o.generators.filter(r=>r.generatorType!==a.sampleID&&r.generatorType!==a.keyRange&&r.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift(new U(a.velRange,o.velRange.max<<8|Math.max(o.velRange.min,0),!1)),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift(new U(a.keyRange,o.keyRange.max<<8|Math.max(o.keyRange.min,0),!1)),o.isGlobal||o.generators.push(new U(a.sampleID,this.samples.indexOf(o.sample),!1)),o.generators.length*4+s),0);let A=new 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),dA(new hA("igen",A.length,A))}function Mo(e,A,t,n,s){let o=this.samples.map((g,c)=>{t&&g.compressSample(n,s);let h=g.getRawData();return p(`%cEncoded sample %c${c}. ${g.sampleName}%c of %c${this.samples.length}%c. Compressed: %c${g.isCompressed}%c.`,I.info,I.recognized,I.info,I.recognized,I.info,g.isCompressed?I.recognized:I.unrecognized,I.info),h}),r=this.samples.reduce((g,c,h)=>g+o[h].length+46,0),C=new b(r);this.samples.forEach((g,c)=>{let h=o[c],d,B,f=h.length;g.isCompressed?(d=C.currentIndex,B=d+h.length):(d=C.currentIndex/2,B=d+h.length/2,f+=46),e.push(d),C.set(h,C.currentIndex),C.currentIndex+=f,A.push(B)});let i=dA(new hA("smpl",C.length,C),new b([115,100,116,97]));return dA(new hA("LIST",i.length,i))}function No(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 C=A[o];AA(n,C);let i=s.sampleLoopStartIndex+r,g=s.sampleLoopEndIndex+r;s.isCompressed&&(i-=r,g-=r),AA(n,i),AA(n,g),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),dA(new hA("shdr",n.length,n))}function bo(){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),dA(new hA("imod",A.length,A))}function Lo(){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),dA(new hA("ibag",A.length,A))}function Uo(){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),dA(new hA("inst",A.length,A))}function To(){let e=4;for(let n of this.presets)e+=n.presetZones.reduce((s,o)=>(o.generators=o.generators.filter(r=>r.generatorType!==a.instrument&&r.generatorType!==a.keyRange&&r.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift(new U(a.velRange,o.velRange.max<<8|Math.max(o.velRange.min,0),!1)),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift(new U(a.keyRange,o.keyRange.max<<8|Math.max(o.keyRange.min,0),!1)),o.isGlobal||o.generators.push(new U(a.instrument,this.instruments.indexOf(o.instrument),!1)),o.generators.length*4+s),0);let A=new 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),dA(new hA("pgen",A.length,A))}function vo(){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),dA(new hA("pmod",A.length,A))}function Ho(){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),dA(new hA("pbag",A.length,A))}function Yo(){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),dA(new hA("phdr",A.length,A))}var mi={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Jo(e=mi){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");pA("%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[G,F]of Object.entries(this.soundFontInfo))if(G==="ifil"||G==="iver"){let E=parseInt(F.split(".")[0]),L=parseInt(F.split(".")[1]),Z=new b(4);H(Z,E),H(Z,L),A.push(dA(new hA(G,4,Z)))}else if(G==="DMOD")A.push(dA(new hA(G,F.length,F)));else{let E=new b(F.length);TA(E,F),A.push(dA(new hA(G,F.length,E)))}let t=wA([new b([73,78,70,79]),...A]),n=dA(new hA("LIST",t.length,t));p("%cWriting SDTA...",I.info);let s=[],o=[],r=Mo.call(this,s,o,e?.compress,e?.compressionQuality??.5,e.compressionFunction);p("%cWriting PDTA...",I.info),p("%cWriting SHDR...",I.info);let C=No.call(this,s,o);p("%cWriting IGEN...",I.info);let i=xo.call(this);p("%cWriting IMOD...",I.info);let g=bo.call(this);p("%cWriting IBAG...",I.info);let c=Lo.call(this);p("%cWriting INST...",I.info);let h=Uo.call(this),d=To.call(this);p("%cWriting PMOD...",I.info);let B=vo.call(this);p("%cWriting PBAG...",I.info);let f=Ho.call(this);p("%cWriting PHDR...",I.info);let m=Yo.call(this),S=wA([new b([112,100,116,97]),m,f,B,d,h,c,g,i,C]),M=dA(new hA("LIST",S.length,S));p("%cWriting the output file...",I.info);let D=wA([new b([115,102,98,107]),n,r,M]),x=dA(new hA("RIFF",D.length,D));return p(`%cSaved succesfully! Final file size: %c${x.length}`,I.info,I.recognized),P(),x}var Mt=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 Mt{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},Te=class extends Mt{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var pi=new Set([a.velRange,a.keyRange,a.instrument,a.exclusiveClass,a.endOper,a.sampleModes,a.startloopAddrsOffset,a.startloopAddrsCoarseOffset,a.endloopAddrsOffset,a.endloopAddrsCoarseOffset,a.startAddrsOffset,a.startAddrsCoarseOffset,a.endAddrOffset,a.endAddrsCoarseOffset,a.initialAttenuation,a.fineTune,a.coarseTune,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay,a.keyNumToModEnvHold,a.keyNumToModEnvDecay]);function Ko(e,A=!0){function t(h,d){h.push(...d.filter(B=>!h.find(f=>f.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(f=>z.isIdentical(B,f))))}let o=[],r=[],C=[],i={min:0,max:127},g={min:0,max:127},c=e.presetZones.find(h=>h.isGlobal);c&&(r.push(...c.generators),C.push(...c.modulators),i=c.keyRange,g=c.velRange);for(let h of e.presetZones){if(h.isGlobal)continue;let d=h.keyRange;h.hasKeyRange||(d=i);let B=h.velRange;h.hasVelRange||(B=g);let f=h.generators.map(E=>new U(E.generatorType,E.generatorValue));t(f,r);let m=[...h.modulators];s(m,C);let S=h.instrument.instrumentZones,M=[],D=[],x={min:0,max:127},G={min:0,max:127},F=S.find(E=>E.isGlobal);F&&(M.push(...F.generators),D.push(...F.modulators),x=F.keyRange,G=F.velRange);for(let E of S){if(E.isGlobal)continue;let L=E.keyRange;E.hasKeyRange||(L=x);let Z=E.velRange;if(E.hasVelRange||(Z=G),L=n(L,d),Z=n(Z,B),L.maxnew U(sA.generatorType,sA.generatorValue));t(EA,M);let tA=[...E.modulators];s(tA,D);let T=[...tA];for(let sA of m){let oA=T.findIndex(CA=>z.isIdentical(sA,CA));oA!==-1?T[oA]=T[oA].sumTransform(sA):T.push(sA)}let $=EA.map(sA=>new U(sA.generatorType,sA.generatorValue));for(let sA of f){if(sA.generatorType===a.velRange||sA.generatorType===a.keyRange||sA.generatorType===a.instrument||sA.generatorType===a.endOper||sA.generatorType===a.sampleModes)continue;let oA=EA.findIndex(CA=>CA.generatorType===sA.generatorType);if(oA!==-1){let CA=$[oA].generatorValue+sA.generatorValue;$[oA]=new U(sA.generatorType,CA)}else{let CA=X[sA.generatorType].def+sA.generatorValue;$.push(new U(sA.generatorType,CA))}}$=$.filter(sA=>sA.generatorType!==a.sampleID&&sA.generatorType!==a.keyRange&&sA.generatorType!==a.velRange&&sA.generatorType!==a.endOper&&sA.generatorType!==a.instrument&&sA.generatorValue!==X[sA.generatorType].def);let BA=new qA;BA.keyRange=L,BA.velRange=Z,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=E.sample,BA.generators=$,BA.modulators=T,o.push(BA)}}if(A){let h=new qA;h.isGlobal=!0;for(let f=0;f<58;f++){if(pi.has(f))continue;let m={},S=X[f]?.def||0;m[S]=0;for(let M of o){let D=M.generators.find(F=>F.generatorType===f);if(D){let F=D.generatorValue;m[F]===void 0?m[F]=1:m[F]++}else m[S]++;let x;switch(f){default:continue;case a.decayVolEnv:x=a.keyNumToVolEnvDecay;break;case a.holdVolEnv:x=a.keyNumToVolEnvHold;break;case a.decayModEnv:x=a.keyNumToModEnvDecay;break;case a.holdModEnv:x=a.keyNumToModEnvHold}if(M.generators.find(F=>F.generatorType===x)!==void 0){m={};break}}if(Object.keys(m).length>0){let M=Object.entries(m).reduce((x,G)=>x[1]{let G=x.generators.findIndex(F=>F.generatorType===f);G!==-1?x.generators[G].generatorValue===D&&x.generators.splice(G,1):D!==S&&x.generators.push(new U(f,S))})}}let B=o.find(f=>!f.isGlobal).modulators.map(f=>z.copy(f));for(let f of B){let m=!0;for(let S of o){if(S.isGlobal||!m)continue;S.modulators.find(D=>z.isIdentical(D,f))||(m=!1)}if(m===!0){h.modulators.push(z.copy(f));for(let S of o){let M=S.modulators.find(D=>z.isIdentical(D,f));M.transformAmount===f.transformAmount&&S.modulators.splice(S.modulators.indexOf(M),1)}}}o.splice(0,0,h)}return o}var Oo=20;function gn(e,A,t,n,s,o,r){let C=r===0?0:1,i=new b(Oo+C*16);AA(i,Oo),H(i,A),H(i,t);let g=n*.4,c=Math.floor(g*-65536);AA(i,c),AA(i,2);let h=o-s,d=0;switch(r){default:case 0:C=0;break;case 1:d=0,C=1;break;case 3:d=1,C=1}return AA(i,C),C===1&&(AA(i,16),AA(i,d),AA(i,s),AA(i,h)),_("wsmp",i)}var q={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 z(219,0,a.reverbEffectsSend,1e3,0),En=new z(221,0,a.chorusEffectsSend,1e3,0),Bn=new z(129,0,a.vibLfoToPitch,0,0),hn=new z(13,0,a.vibLfoToPitch,0,0);var R={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 Nt=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 qo(e,A){if(e)switch(A){default:return;case y.modulationWheel:return q.modulationWheel;case y.mainVolume:return q.volume;case y.pan:return q.pan;case y.expressionController:return q.expression;case y.chorusDepth:return q.chorus;case y.reverbDepth:return q.reverb}else switch(A){default:return;case j.noteOnKeyNum:return q.keyNum;case j.noteOnVelocity:return q.velocity;case j.noController:return q.none;case j.polyPressure:return q.polyPressure;case j.channelPressure:return q.channelPressure;case j.pitchWheel:return q.pitchWheel;case j.pitchWheelRange:return q.pitchWheelRange}}function Po(e,A){switch(e){default:return;case a.initialAttenuation:return{dest:R.gain,amount:-A};case a.fineTune:return R.pitch;case a.pan:return R.pan;case a.keyNum:return R.keyNum;case a.reverbEffectsSend:return R.reverbSend;case a.chorusEffectsSend:return R.chorusSend;case a.freqModLFO:return R.modLfoFreq;case a.delayModLFO:return R.modLfoDelay;case a.delayVibLFO:return R.vibLfoDelay;case a.freqVibLFO:return R.vibLfoFreq;case a.delayVolEnv:return R.volEnvDelay;case a.attackVolEnv:return R.volEnvAttack;case a.holdVolEnv:return R.volEnvHold;case a.decayVolEnv:return R.volEnvDecay;case a.sustainVolEnv:return{dest:R.volEnvSustain,amount:1e3-A};case a.releaseVolEnv:return R.volEnvRelease;case a.delayModEnv:return R.modEnvDelay;case a.attackModEnv:return R.modEnvAttack;case a.holdModEnv:return R.modEnvHold;case a.decayModEnv:return R.modEnvDecay;case a.sustainModEnv:return{dest:R.modEnvSustain,amount:1e3-A};case a.releaseModEnv:return R.modEnvRelease;case a.initialFilterFc:return R.filterCutoff;case a.initialFilterQ:return R.filterQ}}function Vo(e,A){switch(e){default:return;case a.modEnvToFilterFc:return{source:q.modEnv,dest:R.filterCutoff,amt:A,isBipolar:!1};case a.modEnvToPitch:return{source:q.modEnv,dest:R.pitch,amt:A,isBipolar:!1};case a.modLfoToFilterFc:return{source:q.modLfo,dest:R.filterCutoff,amt:A,isBipolar:!0};case a.modLfoToVolume:return{source:q.modLfo,dest:R.gain,amt:A,isBipolar:!0};case a.modLfoToPitch:return{source:q.modLfo,dest:R.pitch,amt:A,isBipolar:!0};case a.vibLfoToPitch:return{source:q.vibratoLfo,dest:R.pitch,amt:A,isBipolar:!0};case a.keyNumToVolEnvHold:return{source:q.keyNum,dest:R.volEnvHold,amt:A,isBipolar:!0};case a.keyNumToVolEnvDecay:return{source:q.keyNum,dest:R.volEnvDecay,amt:A,isBipolar:!0};case a.keyNumToModEnvHold:return{source:q.keyNum,dest:R.modEnvHold,amt:A,isBipolar:!0};case a.keyNumToModEnvDecay:return{source:q.keyNum,dest:R.modEnvDecay,amt:A,isBipolar:!0};case a.scaleTuning:return{source:q.keyNum,dest:R.pitch,amt:A*128,isBipolar:!1}}}function Zo(e){let A=Po(e.generatorType,e.generatorValue),t=A,n=0,s=e.generatorValue;A?.amount!==void 0&&(s=A.amount,t=A.dest);let o=Vo(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 Nt(n,0,t,s,0)}function Xo(e){if(e.transformType!==0){Y("Other transform types are not supported.");return}let A=qo(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===a.initialAttenuation&&(s=s===1?0:1);let o=qo(e.secSrcUsesCC,e.secSrcIndex),r=e.secSrcCurveType,C=e.secSrcPolarity,i=e.secSrcDirection;if(o===void 0){Y(`Invalid secondary source: ${e.secSrcIndex}, CC: ${e.secSrcUsesCC}`);return}let g=Po(e.modulatorDestination,e.transformAmount),c=g,h=e.transformAmount;g?.dest!==void 0&&(c=g.dest,h=g.amount);let d=Vo(e.modulatorDestination,e.transformAmount);if(d!==void 0)h=d.amt,o=A,r=t,C=n,i=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|=C<<8,B|=i<<9,B|=t,B|=n<<14,B|=s<<15,new Nt(A,o,c,h,B)}var yi=new Set([a.sampleModes,a.initialAttenuation,a.keyRange,a.velRange,a.sampleID,a.fineTune,a.coarseTune,a.startAddrsOffset,a.startAddrsCoarseOffset,a.endAddrOffset,a.endAddrsCoarseOffset,a.startloopAddrsOffset,a.startloopAddrsCoarseOffset,a.endloopAddrsOffset,a.endloopAddrsCoarseOffset,a.overridingRootKey,a.exclusiveClass]);function cn(e){for(let o=0;of.generatorType===C);if(i===void 0)continue;let g=r.generatorValue*-128,c=60/128*g,h=i.generatorValue-c,d=e.generators.indexOf(r),B=e.generators.indexOf(i);e.generators[B]=new U(C,h,!1),e.generators[d]=new U(r.generatorType,g,!1)}let A=e.generators.reduce((o,r)=>{if(yi.has(r.generatorType))return o;let C=Zo(r);return C!==void 0?(o.push(C),p("%cSucceeded converting to DLS Articulator!",I.recognized)):Y("Failed converting to DLS Articulator!"),o},[]),t=e.modulators.reduce((o,r)=>{if(z.isIdentical(r,En,!0)||z.isIdentical(r,Cn,!0)||z.isIdentical(r,Bn,!0)||z.isIdentical(r,hn,!0))return o;let C=Xo(r);return C!==void 0?(o.push(C),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 _("art2",wA([n,...s]))}function Wo(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(a.exclusiveClass,0);H(t,n),H(t,0);let s=_("rgnh",t),o=e.getGeneratorValue(a.overridingRootKey,e.sample.samplePitch);e.getGeneratorValue(a.scaleTuning,A.getGeneratorValue(a.scaleTuning,100))===0&&e.keyRange.max-e.keyRange.min===0&&(o=e.keyRange.min);let C=gn(e.sample,o,e.getGeneratorValue(a.fineTune,0)+e.getGeneratorValue(a.coarseTune,0)*100+e.sample.samplePitchCorrection,e.getGeneratorValue(a.initialAttenuation,0),e.sample.sampleLoopStartIndex+e.getGeneratorValue(a.startloopAddrsOffset,0)+e.getGeneratorValue(a.startloopAddrsCoarseOffset,0)*32768,e.sample.sampleLoopEndIndex+e.getGeneratorValue(a.endloopAddrsOffset,0)+e.getGeneratorValue(a.endloopAddrsCoarseOffset,0)*32768,e.getGeneratorValue(a.sampleModes,0)),i=new b(12);H(i,0),H(i,0),AA(i,1),AA(i,this.samples.indexOf(e.sample));let g=_("wlnk",i),c=new b(0);if(e.modulators.length+e.generators.length>0){let h=cn(e);c=_("lar2",h,!1,!0)}return _("rgn2",wA([s,C,g,c]),!1,!0)}function _o(e){pA(`%cWriting %c${e.presetName}%c...`,I.info,I.recognized,I.info);let A=Ko(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=_("insh",n),r=new b(0),C=A.find(d=>d.isGlobal===!0);if(C){let d=cn(C);r=_("lar2",d,!1,!0)}let i=wA(A.reduce((d,B)=>(B.isGlobal||d.push(Wo.apply(this,[B,C])),d),[])),g=_("lrgn",i,!1,!0),c=_("INAM",fe(e.presetName)),h=_("INFO",c,!1,!0);return P(),_("ins ",wA([o,g,r,h]),!1,!0)}function zo(){let e=wA(this.presets.map(A=>_o.apply(this,[A])));return _("lins",e,!1,!0)}function jo(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=_("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 g=new Int16Array(o.length);for(let c=0;c{let s=jo(n);return A.push(e),e+=s.length,s});return{data:_("wvpl",wA(t),!1,!0),indexes:A}}function Ar(){pA("%cSaving DLS...",I.info);let e=new b(4);AA(e,this.presets.length);let A=_("colh",e);pA("%cWriting instruments...",I.info);let t=zo.apply(this);p("%cSuccess!",I.recognized),P(),pA("%cWriting WAVE samples...",I.info);let n=$o.apply(this),s=n.data,o=n.indexes;p("%cSucceeded!",I.recognized),P();let r=new b(8+4*o.length);AA(r,8),AA(r,o.length);for(let h of o)AA(r,h);let C=_("ptbl",r);this.soundFontInfo.ICMT=(this.soundFontInfo.ICMT||"Soundfont")+` Converted from SF2 to DLS using SpessaSynth`,this.soundFontInfo.ISFT="SpessaSynth";let i=[];for(let[h,d]of Object.entries(this.soundFontInfo))h!=="ICMT"&&h!=="INAM"&&h!=="ICRD"&&h!=="IENG"&&h!=="ICOP"&&h!=="ISFT"&&h!=="ISBJ"||i.push(_(h,fe(d),!0));let g=_("INFO",wA(i),!1,!0),c=new b(A.length+t.length+C.length+s.length+g.length+4);return TA(c,"DLS "),c.set(wA([A,t,C,s,g]),4),p("%cSaved succesfully!",I.recognized),P(),_("RIFF",c)}var Si=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,C,i){this.sampleName=A,this.sampleRate=t,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=r,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=i,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(Si),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,f){return f>=B.min&&f<=B.max}function o(B,f){B.push(...f.filter(m=>!B.find(S=>S.generatorType===m.generatorType)))}function r(B,f){B.push(...f.filter(m=>!B.find(S=>z.isIdentical(m,S))))}let C=[],i=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],g=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 f=B.generators,m=B.modulators,S=B.instrument.instrumentZones[0],M=S.isGlobal?[...S.generators]:[],D=S.isGlobal?[...S.modulators]:[],x=S.isGlobal?S.keyRange:{min:0,max:127},G=S.isGlobal?S.velRange:{min:0,max:127};B.instrument.instrumentZones.filter(E=>s(E.hasKeyRange?E.keyRange:x,A)&&s(E.hasVelRange?E.velRange:G,t)&&!E.isGlobal).forEach(E=>{let L=[...E.generators],Z=[...E.modulators];o(f,i),o(L,M),r(m,g),r(Z,D),r(Z,this.parentSoundBank.defaultModulators);let EA=[...Z];for(let tA=0;tAz.isIdentical(T,BA));$!==-1?EA[$]=EA[$].sumTransform(T):EA.push(T)}C.push({instrumentGenerators:L,presetGenerators:f,modulators:EA,sample:E.sample,sampleID:E.generators.find(tA=>tA.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=C,C}};var Je=class e{soundFontInfo={};presets=[];samples=[];instruments=[];defaultModulators=Ks.map(A=>z.copy(A));isXGBank=!1;constructor(A=void 0){A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}static mergeSoundBanks(...A){let t=A.shift(),n=t.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(r=>r.bank===o.bank&&r.program===o.program)===void 0&&n.push(o)});return new e({presets:n,info:t.soundFontInfo})}static getDummySoundfontFile(){let A=new e,t=new ve("Saw",44100,65,20,0,0,0,127);t.sampleData=new Float32Array(128);for(let g=0;g<128;g++)t.sampleData[g]=g/128*2-1;A.samples.push(t);let n=new qA;n.isGlobal=!0,n.generators.push(new U(a.initialAttenuation,375)),n.generators.push(new U(a.releaseVolEnv,-1e3)),n.generators.push(new U(a.sampleModes,1));let s=new qA;s.sample=t;let o=new qA;o.sample=t,o.generators.push(new U(a.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 C=new Te;C.instrument=r;let i=new Ye(A);return i.presetName="Saw Wave",i.presetZones.push(C),A.presets.push(i),A.soundFontInfo.ifil="2.1",A.soundFontInfo.isng="EMU8000",A.soundFontInfo.INAM="Dummy",A._parseInternal(),A.write().buffer}_parseInternal(){this.isXGBank=!1;let A=new Set([0,1,2,3,4,5,6,7,8,9,16,17,24,25,27,28,29,30,31,32,33,40,41,48,56,57,58,64,65,66,126,127]);for(let t of this.presets)if(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 C=0;for(let i=0;i=c.min&&B.key<=c.max&&B.velocity>=h.min&&B.velocity<=h.max){d=!0;break}d||(p(`%c${g.sample.sampleName} %cremoved from %c${o.instrumentName}%c. Use count: %c${g.useCount-1}`,I.recognized,I.info,I.recognized,I.info,I.recognized),o.safeDeleteZone(i)&&(C++,i--,p(`%c${g.sample.sampleName} %cdeleted`,I.recognized,I.info)),g.sample.useCount<1&&t.deleteSample(g.sample))}return C}se("%cTrimming soundfont...",I.info);let s=A.getUsedProgramsAndKeys(t);pA("%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])}});pA(`%cTrimming %c${r.presetName}`,I.info,I.recognized),p(`Keys for ${r.presetName}:`,g);let c=0;for(let h=0;h=B.min&&S.key<=B.max&&S.velocity>=f.min&&S.velocity<=f.max){m=!0;let M=n(d.instrument,g);p(`%cTrimmed off %c${M}%c zones from %c${d.instrument.instrumentName}`,I.info,I.recognized,I.info,I.recognized);break}m||(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),P()}}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),P(),P()}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(C=>C.isDrumPreset(n)&&C.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=Jo;Je.prototype.writeDLS=Ar;function er(e){pA("%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 C=new Te;C.instrument=this.DLSInstrument,this.presetZones=[C]}};function tr(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 P(),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),C="unnamedPreset",i=ZA(A,"INFO");if(i){let B=IA(i.chunkData);for(;B.header!=="INAM";)B=IA(i.chunkData);C=eA(B.chunkData,B.chunkData.length).trim()}r.presetName=C,r.DLSInstrument.instrumentName=C,pA(`%cParsing %c"${C}"%c...`,I.info,I.recognized,I.info);let g=ZA(A,"lrgn");if(!g)throw P(),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===a.reverbEffectsSend)===void 0&&c.modulators.push(z.copy(Cn)),c.modulators.find(B=>B.modulatorDestination===a.chorusEffectsSend)===void 0&&c.modulators.push(z.copy(En)),r.DLSInstrument.instrumentZones.push(c);for(let B=0;B>10&15;D===GA.linear&&M!==GA.linear&&(D=M);let x=n>>14&1,G=n>>15&1;r===a.initialAttenuation&&s<0&&(G=1),d=re(D,x,G,C.isCC,C.enum)}r===a.initialAttenuation&&(c=Math.max(960,Math.min(0,c)));let B=n>>4&15,f=n>>8&1,m=n>>9&1,S=re(B,f,m,h.isCC,h.enum);if(i){let M=S;S=d,d=M}return new z(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(C===0&&i===0&&c===0){let B;switch(g){case R.pan:B=new U(a.pan,d);break;case R.gain:B=new U(a.initialAttenuation,-d*10/.4);break;case R.filterCutoff:B=new U(a.initialFilterFc,d);break;case R.filterQ:B=new U(a.initialFilterQ,d);break;case R.modLfoFreq:B=new U(a.freqModLFO,d);break;case R.modLfoDelay:B=new U(a.delayModLFO,d);break;case R.vibLfoFreq:B=new U(a.freqVibLFO,d);break;case R.vibLfoDelay:B=new U(a.delayVibLFO,d);break;case R.volEnvDelay:B=new U(a.delayVolEnv,d);break;case R.volEnvAttack:B=new U(a.attackVolEnv,d);break;case R.volEnvHold:B=new U(a.holdVolEnv,d,!1);break;case R.volEnvDecay:B=new U(a.decayVolEnv,d,!1);break;case R.volEnvRelease:B=new U(a.releaseVolEnv,d);break;case R.volEnvSustain:let f=1e3-d;B=new U(a.sustainVolEnv,f);break;case R.modEnvDelay:B=new U(a.delayModEnv,d);break;case R.modEnvAttack:B=new U(a.attackModEnv,d);break;case R.modEnvHold:B=new U(a.holdModEnv,d,!1);break;case R.modEnvDecay:B=new U(a.decayModEnv,d,!1);break;case R.modEnvRelease:B=new U(a.releaseModEnv,d);break;case R.modEnvSustain:let m=1e3-d;B=new U(a.sustainModEnv,m);break;case R.reverbSend:B=new U(a.reverbEffectsSend,d);break;case R.chorusSend:B=new U(a.chorusEffectsSend,d);break;case R.pitch:let S=Math.floor(d/100),M=Math.floor(d-S*100);B=new U(a.fineTune,M),n.push(new U(a.coarseTune,S));break}B&&n.push(B)}else{let B=!0,f=(m,S,M)=>{let D=m/-128;if(n.push(new U(S,D)),D<=120){let x=Math.round(.46875*m);n.forEach(G=>{G.generatorType===M&&(G.generatorValue+=x)})}};if(i===q.none?C===q.modLfo&&g===R.pitch?n.push(new U(a.modLfoToPitch,d)):C===q.modLfo&&g===R.gain?n.push(new U(a.modLfoToVolume,d)):C===q.modLfo&&g===R.filterCutoff?n.push(new U(a.modLfoToFilterFc,d)):C===q.vibratoLfo&&g===R.pitch?n.push(new U(a.vibLfoToPitch,d)):C===q.modEnv&&g===R.pitch?n.push(new U(a.modEnvToPitch,d)):C===q.modEnv&&g===R.filterCutoff?n.push(new U(a.modEnvToFilterFc,d)):C===q.keyNum&&g===R.pitch?n.push(new U(a.scaleTuning,d/128)):C===q.keyNum&&g===R.volEnvHold?f(d,a.keyNumToVolEnvHold,a.holdVolEnv):C===q.keyNum&&g===R.volEnvDecay?f(d,a.keyNumToVolEnvDecay,a.decayVolEnv):C===q.keyNum&&g===R.modEnvHold?f(d,a.keyNumToModEnvHold,a.holdModEnv):C===q.keyNum&&g===R.modEnvDecay?f(d,a.keyNumToModEnvDecay,a.decayModEnv):B=!1:B=!1,B===!1){let m=sr(C,i,g,c,d);m?(s.push(m),p("%cSucceeded converting to SF2 Modulator!",I.recognized)):Y("Failed converting to SF2 Modulator!")}}}return A&&s.push(z.copy(Bn),z.copy(hn)),{modulators:s,generators:n}}function or(e,A,t){if(e)for(;e.chunkData.currentIndexe.chunkData.currentIndex;)A.push(IA(e.chunkData));let t=A.find(Z=>Z.header==="rgnh"),n=N(t.chunkData,2),s=N(t.chunkData,2),o=N(t.chunkData,2),r=N(t.chunkData,2);o===0&&r===0&&(r=127,o=0);let C=new Qn({min:n,max:s},{min:o,max:r});N(t.chunkData,2);let i=N(t.chunkData,2);i!==0&&C.generators.push(new U(a.exclusiveClass,i));let g=ZA(A,"lart"),c=ZA(A,"lar2");this.readLart(g,c,C),C.isGlobal=!1;let h=A.find(Z=>Z.header==="wsmp");N(h.chunkData,4);let d=N(h.chunkData,2),B=Ne(h.chunkData[h.chunkData.currentIndex++],h.chunkData[h.chunkData.currentIndex++]),m=(N(h.chunkData,4)|0)/-655360;N(h.chunkData,4);let S=N(h.chunkData,4),M,D={start:0,end:0};if(S===0)M=0;else{N(h.chunkData,4),N(h.chunkData,4)===0?M=1:M=3,D.start=N(h.chunkData,4);let EA=N(h.chunkData,4);D.end=D.start+EA}let x=A.find(Z=>Z.header==="wlnk");if(x===void 0)return;N(x.chunkData,2),N(x.chunkData,2),N(x.chunkData,4);let G=N(x.chunkData,4),F=this.samples[G];if(F===void 0)throw new Error("Invalid sample ID!");let L=(m||F.sampleDbAttenuation)*10/.4;return C.setWavesample(L,M,D,d,F,G,B),C}var dn=class extends ve{sampleDbAttenuation;sampleData;constructor(A,t,n,s,o,r,C,i){super(A,t,n,s,0,1,o,r),this.sampleData=C,this.sampleDbAttenuation=i}getAudioData(){return this.sampleData}getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data?? This shouldn't happen!!");return this.compressedData}return super.getRawData()}};var ir={PCM:1,ALAW:6};function wi(e,A){let t=Math.pow(2,A*8-1),n=Math.pow(2,A*8),s,o=!1;A===1?(s=255,o=!0):s=t;let r=e.size/A,C=new Float32Array(r);for(let i=0;i=t&&(g-=n),C[i]=g/s)}return C}function Fi(e,A){let t=e.size/A,n=new Float32Array(t);for(let s=0;s>4,i=r&15;C>0&&(i+=16),i=(i<<4)+8,C>1&&(i=i<127?i:-i;n[s]=g/32678}return n}function ar(e){pA("%cLoading Wave samples...",I.recognized);let A=0;for(;e.chunkData.currentIndexF.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 C=N(s.chunkData,4);N(s.chunkData,4),N(s.chunkData,2);let g=N(s.chunkData,2)/8,c=!1,h=n.find(F=>F.header==="data");h||this.parsingError("No data chunk in the WAVE chunk!");let d;switch(o){default:c=!0,d=new Float32Array(h.size/g);break;case ir.PCM:d=wi(h,g);break;case ir.ALAW:d=Fi(h,g);break}let B=ZA(n,"INFO"),f=`Unnamed ${A}`;if(B){let F=IA(B.chunkData);for(;F.header!=="INAM"&&B.chunkData.currentIndexF.header==="wsmp");if(G){N(G.chunkData,4),m=N(G.chunkData,2),S=Ne(G.chunkData[G.chunkData.currentIndex++],G.chunkData[G.chunkData.currentIndex++]);let F=Math.trunc(S/100);if(m+=F,S-=F*100,x=(N(G.chunkData,4)|0)/-655360,N(G.chunkData,4),N(G.chunkData,4)===1){N(G.chunkData,8),M=N(G.chunkData,4);let Z=N(G.chunkData,4);D=M+Z}}else Y("No wsmp chunk in wave... using sane defaults.");c&&console.error(`Failed to load '${f}': Unsupported format: (${o})`),this.samples.push(new dn(f,C,m,S,M,D,d,x)),A++,p(`%cLoaded sample %c${f}`,I.info,I.recognized)}P()}var we=class extends Je{constructor(A){super(),this.dataArray=new b(A),se("%cParsing DLS...",I.info),this.dataArray||(P(),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.currentIndexi.header==="colh");o||(P(),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||(P(),this.parsingError("No wvpl chunk!")),this.readDLSSamples(r);let C=ZA(n,"lins");C||(P(),this.parsingError("No lins chunk!")),this.readDLSInstrumentList(C),this.presets.sort((i,g)=>i.program-g.program+(i.bank-g.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),P()}verifyHeader(A,...t){for(let n of t)if(A.header.toLowerCase()===n.toLowerCase())return;P(),this.parsingError(`Invalid DLS chunk header! Expected "${t.toString()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(P(),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=er;we.prototype.readDLSInstrument=tr;we.prototype.readRegion=rr;we.prototype.readLart=or;we.prototype.readDLSSamples=ar;var os=class extends ve{constructor(A,t,n,s,o,r,C,i,g,c,h,d,B){super(A,r,C,i,g,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=Ri(s,e.chunkData,A,t);n.push(o),s++}return n.length>1&&n.pop(),n}function Ri(e,A,t,n){let s=eA(A,20),o=N(A,4)*2,r=N(A,4)*2,C=N(A,4),i=N(A,4),g=N(A,4),c=A[A.currentIndex++];c===255&&(c=60);let h=Ys(A[A.currentIndex++]),d=N(A,2),B=N(A,2);return new os(s,o,r,C,i,g,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===a.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function gr(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,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(r,C),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===a.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function Cr(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,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(r,C),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 z{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||(P(),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 P(),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=>z.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 C=IA(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(eA(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",I.warn);let i=IA(this.dataArray,!1);this.verifyHeader(i,"smpl");let g;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",I.info);try{g=me.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(tA){throw P(),new Error(`SF2Pack Ogg Vorbis decode error: ${tA}`)}p(`%cDecoded the smpl chunk! Length: %c${g.length}`,I.info,I.value)}else g=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${C.size-12}`,I.info,I.value),this.dataArray.currentIndex+=C.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 f=IA(c.chunkData);this.verifyHeader(f,"pgen");let m=IA(c.chunkData);this.verifyHeader(m,"inst");let S=IA(c.chunkData);this.verifyHeader(S,"ibag");let M=IA(c.chunkData);this.verifyHeader(M,"imod");let D=IA(c.chunkData);this.verifyHeader(D,"igen");let x=IA(c.chunkData);this.verifyHeader(x,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...Ir(x,g,!o));let G=is(D),F=un(M),E=gr(S,G,F,this.samples);this.instruments=Br(m,E);let L=is(f),Z=un(B),EA=Cr(d,L,Z,this.instruments);this.presets.push(...Er(h,EA,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),P(),o&&delete this.dataArray}verifyHeader(A,t){A.header.toLowerCase()!==t.toLowerCase()&&(P(),this.parsingError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(P(),this.parsingError(`Invalid FourCC: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"\``))}destroySoundBank(){super.destroySoundBank(),delete this.dataArray}};function bt(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 xt.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case xt.reloadSoundFont:this.reloadManager(t);break;case xt.deleteSoundFont:this.deleteSoundFont(t);break;case xt.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let t=bt(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:bt(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(i=>i.isDrumPreset(n)&&i.program===t);if(r)return r;let C=o.soundfont.presets.find(i=>i.isDrumPreset(n));if(C)return C}return this.soundfontList[0].soundfont.presets[0]}else{for(let o of this.soundfontList){let r=o.soundfont.presets.find(C=>C.program===t&&!C.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 Qt={linear:0,nearestNeighbor:1,fourthOrder:2},lt=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 C=0;C=n.loopEnd;)s-=r;let i=~~s,g=i+1;for(;g>=n.loopEnd;)g-=r;let c=s-i,h=o[g],d=o[i];t[C]=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 g=s-C,c=o[i],h=o[C];t[r]=h+(c-h)*g,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 C=0;C=n.loopEnd;)s-=o;let i=~~s+1;for(;i>=n.loopEnd;)i-=o;t[C]=r[i],s+=n.playbackStep*A.currentTuningCalculated}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let C=0;C=n.end){A.finished=!0;return}t[C]=r[i],s+=n.playbackStep*A.currentTuningCalculated}}n.cursor=s}static getSampleCubic(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let C=0;C=n.loopEnd;)s-=r;let i=~~s,g=i+1,c=g+1,h=c+1,d=s-i;g>=n.loopEnd&&(g-=r),c>=n.loopEnd&&(c-=r),h>=n.loopEnd&&(h-=r);let B=o[i],f=o[g],m=o[c],S=o[h],M=.5*(m-B),D=B-2.5*f+2*m-.5*S,x=.5*(S-B)+1.5*(f-m);t[C]=((x*d+D)*d+M)*d+f,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r=n.end||g>=n.end||c>=n.end){A.finished=!0;return}let d=o[C],B=o[i],f=o[g],m=o[c],S=.5*(f-d),M=d-2.5*B+2*f-.5*m,D=.5*(m-d)+1.5*(B-f);t[r]=((D*h+M)*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 hr=.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[a.initialFilterFc],r=A.filter;r.initialized?r.currentInitialFc+=(o-r.currentInitialFc)*s:(r.initialized=!0,r.currentInitialFc=o);let C=r.currentInitialFc+n,i=A.modulatedGenerators[a.initialFilterQ];if(r.currentInitialFc>13499&&C>13499&&i===0){r.currentInitialFc=13500;return}(Math.abs(r.lastTargetCutoff-C)>1||r.resonanceCb!==i)&&(r.lastTargetCutoff=C,r.resonanceCb=i,e.calculateCoefficients(r,C));for(let g=0;g.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;ez.copy(o)))}exclusiveRelease(){this.release(Qr),this.modulatedGenerators[a.releaseVolEnv]=Gi,this.modulatedGenerators[a.releaseModEnv]=xi,Ee.recalculate(this),Be.recalculate(this)}release(A=lr){this.releaseStartTime=currentTime,this.releaseStartTime-this.startTimeLt.copy(d,n));let h=r.preset;return C&&(h=this.soundfontManager.getPreset(i,g,FA(this.system))),o=h.getSamplesAndGenerators(A,t).reduce((d,B)=>{if(B.sample.getAudioData()===void 0)return Y(`Discarding invalid sample: ${B.sample.sampleName}`),d;let f=new Int16Array(60);for(let F=0;F<60;F++)f[F]=Js(F,B.presetGenerators,B.instrumentGenerators);f[a.initialAttenuation]=Math.floor(f[a.initialAttenuation]*.4);let m=B.sample.samplePitch;f[a.overridingRootKey]>-1&&(m=f[a.overridingRootKey]);let S=A;f[a.keyNum]>-1&&(S=f[a.keyNum]);let M=B.sample.sampleLoopStartIndex,D=B.sample.sampleLoopEndIndex,x=f[a.sampleModes],G=new yn(B.sample.sampleData,B.sample.sampleRate/sampleRate*Math.pow(2,B.sample.samplePitchCorrection/1200),0,m,M,D,Math.floor(B.sample.sampleData.length)-1,x);return f[a.velocity]>-1&&(t=f[a.velocity]),d.push(new Lt(sampleRate,G,A,t,e,n,S,s,f,B.modulators.map(F=>z.copy(F)))),d},[]),this.setCachedVoice(i,g,A,t,o.map(d=>Lt.copy(d,n))),o}var ur=.05,Mi=4600,Ni=2e3,dr=Math.PI/2,Sn=-500,fr=500,Qs=fr-Sn,mr=new Float32Array(Qs+1),pr=new Float32Array(Qs+1);for(let e=Sn;e<=fr;e++){let A=(e-Sn)/Qs,t=e-Sn;mr[t]=Math.cos(dr*A),pr[t]=Math.sin(dr*A)}function yr(e,A,t,n,s,o,r,C){if(isNaN(A[0]))return;let i;e.overridePan?i=e.overridePan:(e.currentPan+=(e.modulatedGenerators[a.pan]-e.currentPan)*this.synth.panSmoothingFactor,i=e.currentPan);let g=this.synth.currentGain,c=~~(i+500),h=mr[c]*g*this.synth.panLeft,d=pr[c]*g*this.synth.panRight;if(!this.synth.oneOutputMode){let B=e.modulatedGenerators[a.reverbEffectsSend];if(B>0){let m=this.synth.reverbGain*g*(B/Mi);for(let S=0;S0){let m=this.synth.chorusGain*f/Ni,S=h*m,M=d*m;for(let D=0;D0)for(let B=0;B0)for(let B=0;Bt.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function kr(e,A=!1){this.clearSoundFont(!1,A);try{A?this.overrideSoundfont=bt(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 wr(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 Rr(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(t,A,FA(this.system));if(n)return n}return this.soundfontManager.getPreset(e,A,FA(this.system))}function Gr(e,A=!1){this.transposition=0;for(let t=0;tUt.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{Ut.applyChannelSnapshot(A,s,n)}),p("%cFinished restoring controllers!",I.info)}};function Mr(){this.post({messageType:JA.synthesizerSnapshot,messageData:dt.createSynthesizerSnapshot(this)})}function Nr(e){dt.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[a.initialAttenuation]>2500)return e.isInRelease&&(e.finished=!0),e.finished;let i=e.targetKey,g=e.modulatedGenerators[a.fineTune]+this.channelOctaveTuning[e.midiNote]+this.channelTuningCents,c=e.modulatedGenerators[a.coarseTune],h=this.synth.tunings[this.preset.program]?.[e.realKey];if(h!==void 0&&h?.midiNote>=0&&(i=h.midiNote,g+=h.centTuning),e.portamentoFromKey>-1){let E=Math.min((C-e.startTime)/e.portamentoDuration,1),L=i-e.portamentoFromKey;c-=L*(1-E)}g+=(i-e.sample.rootKey)*e.modulatedGenerators[a.scaleTuning];let d=e.modulatedGenerators[a.vibLfoToPitch];if(d!==0){let E=e.startTime+Ce(e.modulatedGenerators[a.delayVibLFO]),L=Gt(e.modulatedGenerators[a.freqVibLFO]),Z=Dn(E,L,C);g+=Z*(d*this.customControllers[cA.modulationMultiplier])}let B=0,f=e.modulatedGenerators[a.modLfoToPitch],m=e.modulatedGenerators[a.modLfoToVolume],S=e.modulatedGenerators[a.modLfoToFilterFc],M=0;if(f!==0||S!==0||m!==0){let E=e.startTime+Ce(e.modulatedGenerators[a.delayModLFO]),L=Gt(e.modulatedGenerators[a.freqModLFO]),Z=Dn(E,L,C);g+=Z*(f*this.customControllers[cA.modulationMultiplier]),M=-Z*m,B+=Z*S}if(this.channelVibrato.depth>0){let E=Dn(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,C);E&&(g+=E*this.channelVibrato.depth)}let D=e.modulatedGenerators[a.modEnvToPitch],x=e.modulatedGenerators[a.modEnvToFilterFc];if(x!==0||D!==0){let E=Be.getValue(e,C);B+=E*x,g+=E*D}let G=~~(g+c*100);G!==e.currentTuningCents&&(e.currentTuningCents=G,e.currentTuningCalculated=Math.pow(2,G/1200));let F=new Float32Array(A.length);switch(this.synth.interpolationType){case Qt.fourthOrder:lt.getSampleCubic(e,F);break;case Qt.linear:default:lt.getSampleLinear(e,F);break;case Qt.nearestNeighbor:lt.getSampleNearest(e,F);break}return Ke.apply(e,F,B,this.synth.filterSmoothingFactor),Ee.apply(e,F,M,this.synth.volumeEnvelopeSmoothingFactor),this.panVoice(e,F,A,t,n,s,o,r),e.finished}function Lr(e,A=-12e3){this.voices.forEach(t=>{t.realKey===e&&(t.modulatedGenerators[a.releaseVolEnv]=A,t.release())})}function Ur(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 Tr(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 vr(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 bi=1e3/200;function Hr(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=e[A.sourceIndex];else{let g=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[g];break}}let s=je[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let g=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[g]}}let r=je[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=A.transformAmount;A.isEffectModulator&&C<=1e3&&(C*=bi,C=Math.min(C,1e3));let i=s*r*C;return A.transformType===2&&(i=Math.abs(i)),A.currentValue=i,i}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(g=>{let c=X[g.modulatorDestination],h=r[g.modulatorDestination]+Hr(A,g,e);r[g.modulatorDestination]=Math.max(c.min,Math.min(h,c.max))}),Ee.recalculate(e),Be.recalculate(e);return}let C=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),i=new Set;s.forEach(g=>{if(g.sourceUsesCC===t&&g.sourceIndex===n||g.secSrcUsesCC===t&&g.secSrcIndex===n){let c=g.modulatorDestination;i.has(c)||(r[c]=o[c],Hr(A,g,e),s.forEach(h=>{if(h.modulatorDestination===c){let d=X[g.modulatorDestination],B=r[g.modulatorDestination]+h.currentValue;r[g.modulatorDestination]=Math.max(d.min,Math.min(B,d.max))}}),i.add(c))}}),[...i].some(g=>C.has(g))&&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 Os.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 Jr(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 Kr(e){e&&this.stopAllNotes(!0),this.isMuted=e,this.sendChannelProperty(),this.synth.callEvent("mutechannel",{channel:this.channelNumber,isMuted:e})}function Or(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 Tt={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 qr(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 Tt.pitchBendRange:this.midiControllers[xA+j.pitchWheelRange]=e<<7,t("Pitch bend range",e.toString(),"semitones");break;case Tt.coarseTuning:let r=e-64;this.setCustomController(cA.channelTuningSemitones,r),t("Coarse tuning",r.toString(),"semitones");break;case Tt.fineTuning:this.setTuning(e-64,!1);break;case Tt.modulationDepth:this.setModulationDepth(e*100);break;case Tt.resetParameters:this.resetParameters();break}}}var vt={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 Li(e){if(vt[e]!==void 0)return vt[e];let A=null,t=null;for(let n of Object.keys(vt))n=parseInt(n),nA)&&(A=n),n>e&&(t===null||n200&&A<40||this.synth.highPerformanceMode&&A<10||this.isMuted)return;let t=e+this.channelTransposeKeyShift,n=t;if(t>127||t<0)return;let s=this.preset.program;this.synth.tunings[s]?.[t]?.midiNote>=0&&(n=this.synth.tunings[s]?.[t].midiNote),this.velocityOverride>0&&(A=this.velocityOverride);let o=this.synth.keyModifierManager.getVelocity(this.channelNumber,t);o>-1&&(A=o);let r=-1,C=0,i=this.midiControllers[y.portamentoTime]>>7,g=this.midiControllers[y.portamentoControl],c=g>>7;if(!this.drumChannel&&c!==n&&this.midiControllers[y.portamentoOnOff]>=8192&&i>0){if(g!==1){let f=Math.abs(n-c);C=Pr(i,f),r=c}this.controllerChange(y.portamentoControl,n)}let h=this.synth.getWorkletVoices(this.channelNumber,n,A,currentTime,t),d=0;this.randomPan&&(d=Math.round(Math.random()*1e3-500));let B=this.voices;h.forEach(f=>{f.portamentoFromKey=r,f.portamentoDuration=C,f.overridePan=d;let m=f.exclusiveClass;m!==0&&B.forEach(E=>{E.exclusiveClass===m&&E.exclusiveRelease()}),he(f,this.midiControllers);let S=f.modulatedGenerators[a.startAddrsOffset]+f.modulatedGenerators[a.startAddrsCoarseOffset]*32768,M=f.modulatedGenerators[a.endAddrOffset]+f.modulatedGenerators[a.endAddrsCoarseOffset]*32768,D=f.modulatedGenerators[a.startloopAddrsOffset]+f.modulatedGenerators[a.startloopAddrsCoarseOffset]*32768,x=f.modulatedGenerators[a.endloopAddrsOffset]+f.modulatedGenerators[a.endloopAddrsCoarseOffset]*32768,G=f.sample,F=E=>Math.max(0,Math.min(G.sampleData.length-1,E));if(G.cursor=F(G.cursor+S),G.end=F(G.end+M),G.loopStart=F(G.loopStart+D),G.loopEnd=F(G.loopEnd+x),G.loopEndthis.synth.voiceCap&&this.synth.voiceKilling(h.length),B.push(...h),this.sendChannelProperty(),this.synth.callEvent("noteon",{midiNote:e,channel:this.channelNumber,velocity:A})}function Zr(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 Xr(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 Wr(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 _r(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 zr(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 jr(e){if(this.lockPreset)return;let A=this.getBankSelect(),t,n,s=this.isXGChannel;if(this.synth.overrideSoundfont){let o=A===128?128:A-this.synth.soundfontBankOffset,r=this.synth.overrideSoundfont.getPresetNoFallback(o,e,s);if(r)t=r.bank===128?128:r.bank+this.synth.soundfontBankOffset,n=r,this.presetUsesOverride=!0;else{n=this.synth.soundfontManager.getPreset(A,e,s);let C=this.synth.soundfontManager.soundfontList.find(i=>i.soundfont===n.parentSoundBank).bankOffset;t=n.bank-C,this.presetUsesOverride=!1}}else{n=this.synth.soundfontManager.getPreset(A,e,s);let o=this.synth.soundfontManager.soundfontList.find(r=>r.soundfont===n.parentSoundBank).bankOffset;t=n.bank-o,this.presetUsesOverride=!1}this.setPreset(n),this.sentBank=t,this.synth.callEvent("programchange",{channel:this.channelNumber,program:n.program,bank:t}),this.sendChannelProperty()}var SA=class{midiControllers=new Int16Array(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 FA(this.synth.system)||this.lockPreset&&FA(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(C=>!this.renderVoice(C,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,Et(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 Bt(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]})}};SA.prototype.renderVoice=br;SA.prototype.panVoice=yr;SA.prototype.killNote=Lr;SA.prototype.stopAllNotes=Jr;SA.prototype.muteChannel=Kr;SA.prototype.noteOn=Vr;SA.prototype.noteOff=Zr;SA.prototype.polyPressure=Xr;SA.prototype.channelPressure=Wr;SA.prototype.pitchWheel=_r;SA.prototype.programChange=jr;SA.prototype.setTuning=Ur;SA.prototype.setOctaveTuning=zr;SA.prototype.setModulationDepth=Tr;SA.prototype.transposeChannel=Or;SA.prototype.controllerChange=Yr;SA.prototype.resetControllers=oo;SA.prototype.resetControllersRP15Compliant=ro;SA.prototype.resetParameters=io;SA.prototype.dataEntryFine=vr;SA.prototype.dataEntryCoarse=qr;function $r(e=!1){let A=new SA(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 Ai(e,A){e===void 0&&(e={});for(let t in A)A.hasOwnProperty(t)&&!(t in e)&&(e[t]=A[t]);return e}var ei={skipToFirstNoteOn:!0,autoPlay:!0,preservePlaybackState:!1};var lr=.03,Qr=.07,ns=1,kA=class extends AudioWorkletProcessor{cachedVoices=[];alive=!0;deviceID=ie;eventQueue=[];interpolationType=Qt.fourthOrder;sequencer=new DA(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.midiOutputsCount=A.processorOptions.midiChannels;let t=this.midiOutputsCount;this.oneOutputMode=this.midiOutputsCount===1,this.oneOutputMode&&(t=16),this.enableEventSystem=A.processorOptions.enableEventSystem;for(let n=0;n<127;n++)this.tunings.push([]);try{this.soundfontManager=new mn(A.processorOptions.soundfont,this.postReady.bind(this))}catch(n){throw this.post({messageType:JA.soundfontError,messageData:n}),n}this.sendPresetList(),this.getDefaultPresets();for(let n=0;nthis.handleMessage(n.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 n=Ai(A.processorOptions.startRenderingData.sequencerOptions,ei);this.sequencer.skipToFirstNoteOn=n.skipToFirstNoteOn,this.sequencer.preservePlaybackState=n.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,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){if(!this.alive)return!1;this.sequencer.processTick();let n=currentTime;for(;this.eventQueue[0]?.time<=n;)this.eventQueue.shift().callback();return this.totalVoicesAmount=0,this.workletProcessorChannels.forEach((s,o)=>{if(s.voices.length<1||s.isMuted)return;let r=s.voices.length,C,i,g,c,h,d,B;if(this.oneOutputMode){let f=t[0];C=o%16*2,i=f[C],g=f[C+1]}else C=o%this.midiOutputsCount+2,i=t[C][0],g=t[C][1],c=t[0][0],h=t[0][1],d=t[1][0],B=t[1][1];s.renderAudio(i,g,c,h,d,B),this.totalVoicesAmount+=s.voices.length,s.voices.length!==r&&s.sendChannelProperty()}),!0}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){this.workletProcessorChannels[A].noteOn(t,n)}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){this.workletProcessorChannels[A].programChange(t)}processMessage(A,t,n,s){let o=()=>{let C=at(A[0]),i=C.channel+t;switch(C.status){case w.noteOn:let g=A[2];g>0?this.noteOn(i,A[1],g):this.noteOff(i,A[1]);break;case w.noteOff:n?this.workletProcessorChannels[i].killNote(A[1]):this.noteOff(i,A[1]);break;case w.pitchBend:this.pitchWheel(i,A[2],A[1]);break;case w.controllerChange:this.controllerChange(i,A[1],A[2],n);break;case w.programChange:this.programChange(i,A[1]);break;case w.polyPressure:this.polyPressure(i,A[0],A[1]);break;case w.channelPressure:this.channelPressure(i,A[1]);break;case w.systemExclusive:this.systemExclusive(new b(A.slice(1)),t);break;case w.reset:this.stopAllChannels(!0),this.resetAllControllers();break;default:break}},r=s.time;r>currentTime?(this.eventQueue.push({callback:o.bind(this),time:r}),this.eventQueue.sort((C,i)=>C.time-i.time)):o()}};kA.prototype.voiceKilling=fo;kA.prototype.getWorkletVoices=cr;kA.prototype.handleMessage=Do;kA.prototype.callEvent=ko;kA.prototype.systemExclusive=wo;kA.prototype.stopAllChannels=Sr;kA.prototype.createWorkletChannel=$r;kA.prototype.resetAllControllers=so;kA.prototype.setMasterGain=Ro;kA.prototype.setMasterPan=Go;kA.prototype.setMIDIVolume=Fo;kA.prototype.transposeAllChannels=Gr;kA.prototype.setMasterTuning=xr;kA.prototype.getPreset=Rr;kA.prototype.reloadSoundFont=kr;kA.prototype.clearSoundFont=wr;kA.prototype.setEmbeddedSoundFont=Dr;kA.prototype.sendPresetList=Fr;kA.prototype.sendSynthesizerSnapshot=Mr;kA.prototype.applySynthesizerSnapshot=Nr;registerProcessor(qs,kA);p("%cProcessor succesfully registered!",I.recognized);