diff --git a/package.json b/package.json index 2f5e7a3e..0e3e3a12 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "SpessaSynth", - "version": "3.20.32", + "version": "3.20.33", "type": "module", "scripts": { "start": "node src/website/server/server.js" diff --git a/src/spessasynth_lib/soundfont/read_sf2/generators.js b/src/spessasynth_lib/soundfont/read_sf2/generators.js index 672a11fc..3d5a6f7f 100644 --- a/src/spessasynth_lib/soundfont/read_sf2/generators.js +++ b/src/spessasynth_lib/soundfont/read_sf2/generators.js @@ -143,7 +143,7 @@ generatorLimits[generatorTypes.initialAttenuation] = {min: -250, max: 1440, def: generatorLimits[generatorTypes.endloopAddrsCoarseOffset] = {min: -32768, max: 32768, def: 0}; generatorLimits[generatorTypes.coarseTune] = {min: -120, max: 120, def: 0}; -generatorLimits[generatorTypes.fineTune] = {min: -99, max: 99, def: 0}; +generatorLimits[generatorTypes.fineTune] = {min: -12700, max: 12700, def: 0}; // this generator is used as initial pitch, hence this range generatorLimits[generatorTypes.scaleTuning] = {min: 0, max: 1200, def: 100}; generatorLimits[generatorTypes.exclusiveClass] = {min: 0, max: 99999, def: 0}; generatorLimits[generatorTypes.overridingRootKey] = {min: 0-1, max: 127, def: -1}; diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index 2e791daa..32ac673d 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -1,18 +1,18 @@ -var as=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>(typeof require<"u"?require:A)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H=class extends Uint8Array{constructor(A){super(A),this.currentIndex=0}currentIndex};function De(t){let A=t.reduce((n,o)=>n+o.length,0),e=new H(A),s=0;for(let n of t)e.set(n,s),s+=n.length;return e}function ft(t){t=Math.floor(t);let A=Math.floor(t/60),e=Math.round(t-A*60);return{minutes:A,seconds:e,time:`${A.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}}function Is(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function lA(t){let A="";for(let e=0;e=128&&A<=224&&(s=e,n=A),{status:n,channel:s}}var p={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,effects1Depth:91,effects2Depth:92,effects3Depth:93,effects4Depth:94,effects5Depth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},Cs={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var tA={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25},ae={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},TA=-1,pA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var Es=!0,Bs=!0,qe=!0,hs=!0;function Qs(t,A,e,s){Es=t,Bs=A,qe=e,hs=s}function m(...t){Es&&console.info(...t)}function N(...t){Bs&&console.warn(...t)}function cs(...t){hs&&console.table(...t)}function te(...t){qe&&console.group(...t)}function SA(...t){qe&&console.groupCollapsed(...t)}function X(){qe&&console.groupEnd()}var Ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var ls="spessasynth-worklet-system",us=450,yA=9,Pe=16,Ke="gs";var UA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},FA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function zA(t,A){let e=0;for(let s=8*(A-1);s>=0;s-=8)e|=t[t.currentIndex++]<>>0}function ds(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=ke(t.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=s,e.status){case k.noteOn:let n=t.messageData[1];if(n>0)this.synth.noteOn(e.channel,t.messageData[0],n),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:n});else{this.synth.noteOff(e.channel,t.messageData[0]);let g=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);g!==-1&&this.playingNotes.splice(g,1)}break;case k.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(g=>g.midiNote===t.messageData[0]&&g.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case k.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case k.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case k.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case k.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case k.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case k.systemExclusive:this.synth.systemExclusive(t.messageData,s);break;case k.setTempo:this.oneTickToSeconds=60/(Ro(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),N("invalid tempo! falling back to 120 BPM"));break;case k.timeSignature:case k.endOfTrack:case k.midiChannelPrefix:case k.songPosition:case k.activeSensing:case k.keySignature:case k.sequenceNumber:case k.sequenceSpecific:break;case k.text:case k.lyric:case k.copyright:case k.trackName:case k.marker:case k.cuePoint:case k.instrumentName:case k.programName:this.post(FA.textEvent,[t.messageData,e.status]);break;case k.midiPort:this.assignMIDIPort(A,t.messageData[0]);break;case k.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:N(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(k).find(g=>k[g]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function fs(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===yA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Ro(t){return t.messageData.currentIndex=0,6e7/zA(t.messageData,3)}function ms(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let s=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(s.ticks-e.ticks),this.midiData.loop.end<=e.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function ps(){let t=0,A=1/0;return this.tracks.forEach((e,s)=>{this.eventIndex[s]>=e.length||e[this.eventIndex[s]].ticks>>0}function ge(t,A,e){for(let s=0;s>s*8&255}function Y(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function QA(t,A){ge(t,A,4)}function jA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function Ss(t){return t>127?t-256:t}function O(t,A,e=void 0,s=!0){if(e){let n=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(n.buffer)}else{let n=!1,o="";for(let g=0;g127){if(s){n=!0;continue}else if(C===0){n=!0;continue}}o+=String.fromCharCode(C)}}return o}}function RA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let s=0;sA.length)for(let s=0;se.header!=="LIST"?!1:(e.chunkData.currentIndex=0,O(e.chunkData,4)===A))}function Oe(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var a={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},U=[];U[a.startAddrsOffset]={min:0,max:32768,def:0};U[a.endAddrOffset]={min:-32768,max:32768,def:0};U[a.startloopAddrsOffset]={min:-32768,max:32768,def:0};U[a.endloopAddrsOffset]={min:-32768,max:32768,def:0};U[a.startAddrsCoarseOffset]={min:0,max:32768,def:0};U[a.modLfoToPitch]={min:-12e3,max:12e3,def:0};U[a.vibLfoToPitch]={min:-12e3,max:12e3,def:0};U[a.modEnvToPitch]={min:-12e3,max:12e3,def:0};U[a.initialFilterFc]={min:1500,max:13500,def:13500};U[a.initialFilterQ]={min:0,max:960,def:0};U[a.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};U[a.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};U[a.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[a.modLfoToVolume]={min:-960,max:960,def:0};U[a.chorusEffectsSend]={min:0,max:1e3,def:0};U[a.reverbEffectsSend]={min:0,max:1e3,def:0};U[a.pan]={min:-500,max:500,def:0};U[a.delayModLFO]={min:-12e3,max:5e3,def:-12e3};U[a.freqModLFO]={min:-16e3,max:4500,def:0};U[a.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};U[a.freqVibLFO]={min:-16e3,max:4500,def:0};U[a.delayModEnv]={min:-32768,max:5e3,def:-32768};U[a.attackModEnv]={min:-32768,max:8e3,def:-32768};U[a.holdModEnv]={min:-12e3,max:5e3,def:-12e3};U[a.decayModEnv]={min:-12e3,max:8e3,def:-12e3};U[a.sustainModEnv]={min:0,max:1e3,def:0};U[a.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};U[a.keyNumToModEnvHold]={min:-1200,max:1200,def:0};U[a.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};U[a.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};U[a.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};U[a.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};U[a.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};U[a.sustainVolEnv]={min:0,max:1440,def:0};U[a.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};U[a.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};U[a.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};U[a.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[a.keyNum]={min:-1,max:127,def:-1};U[a.velocity]={min:-1,max:127,def:-1};U[a.initialAttenuation]={min:-250,max:1440,def:0};U[a.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[a.coarseTune]={min:-120,max:120,def:0};U[a.fineTune]={min:-99,max:99,def:0};U[a.scaleTuning]={min:0,max:1200,def:100};U[a.exclusiveClass]={min:0,max:99999,def:0};U[a.overridingRootKey]={min:-1,max:127,def:-1};var b=class{constructor(A=a.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let s=U[A];this.generatorValue=Math.round(e),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}generatorType=a.INVALID;generatorValue=0};function ys(t,A,e){let s=U[t]||{min:0,max:32768,def:0},n=A.find(Q=>Q.generatorType===t),o=0;n&&(o=n.generatorValue);let g=e.find(Q=>Q.generatorType===t),C=s.def;g&&(C=g.generatorValue);let c=C+o;return t===a.initialAttenuation?c:Math.max(s.min,Math.min(s.max,c))}var mt=class extends b{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=jA(A[e+2],A[e+3]),A.currentIndex+=4}};function pt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new mt(t.chunkData));return A.length>1&&A.pop(),A}var V={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},cA={linear:0,concave:1,convex:2,switch:3},Go=[];for(let t=0;t<4;t++)Go.push([[],[]]);var eA=class t{constructor(A){A.srcEnum?(this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform):(this.sourceEnum=S(A,2),this.modulatorDestination=S(A,2),this.transformAmount=jA(A[A.currentIndex++],A[A.currentIndex++]),this.secondarySourceEnum=S(A,2),this.transformType=S(A,2)),this.modulatorDestination>58&&(this.modulatorDestination=a.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(A){return new t({srcEnum:A.sourceEnum,secSrcEnum:A.secondarySourceEnum,transform:A.transformType,amt:A.transformAmount,dest:A.modulatorDestination})}static isIdentical(A,e){return A.sourceEnum===e.sourceEnum&&A.modulatorDestination===e.modulatorDestination&&A.secondarySourceEnum===e.secondarySourceEnum&&A.transformType===e.transformType}sumTransform(A){return new t({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(n,o){return Object.keys(n).find(g=>n[g]===o)}let e=A(cA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(p,this.sourceIndex):e+=A(V,this.sourceIndex);let s=A(cA,this.secSrcCurveType);return s+=this.secSrcPolarity===0?" unipolar ":" bipolar ",s+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?s+=A(p,this.secSrcIndex):s+=A(V,this.secSrcIndex),`Modulator: +var In=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>(typeof require<"u"?require:A)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H=class extends Uint8Array{constructor(A){super(A),this.currentIndex=0}currentIndex};function De(t){let A=t.reduce((s,o)=>s+o.length,0),e=new H(A),n=0;for(let s of t)e.set(s,n),n+=s.length;return e}function ft(t){t=Math.floor(t);let A=Math.floor(t/60),e=Math.round(t-A*60);return{minutes:A,seconds:e,time:`${A.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}}function gn(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function lA(t){let A="";for(let e=0;e=128&&A<=224&&(n=e,s=A),{status:s,channel:n}}var p={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,effects1Depth:91,effects2Depth:92,effects3Depth:93,effects4Depth:94,effects5Depth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},En={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var tA={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25},ae={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},TA=-1,pA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var Bn=!0,hn=!0,qe=!0,Qn=!0;function cn(t,A,e,n){Bn=t,hn=A,qe=e,Qn=n}function m(...t){Bn&&console.info(...t)}function b(...t){hn&&console.warn(...t)}function ln(...t){Qn&&console.table(...t)}function te(...t){qe&&console.group(...t)}function SA(...t){qe&&console.groupCollapsed(...t)}function X(){qe&&console.groupEnd()}var Ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var un="spessasynth-worklet-system",dn=450,yA=9,Pe=16,Ke="gs";var UA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},FA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function zA(t,A){let e=0;for(let n=8*(A-1);n>=0;n-=8)e|=t[t.currentIndex++]<>>0}function fn(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=ke(t.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=n,e.status){case k.noteOn:let s=t.messageData[1];if(s>0)this.synth.noteOn(e.channel,t.messageData[0],s),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:s});else{this.synth.noteOff(e.channel,t.messageData[0]);let I=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);I!==-1&&this.playingNotes.splice(I,1)}break;case k.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(I=>I.midiNote===t.messageData[0]&&I.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case k.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case k.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case k.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case k.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case k.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case k.systemExclusive:this.synth.systemExclusive(t.messageData,n);break;case k.setTempo:this.oneTickToSeconds=60/(Ro(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),b("invalid tempo! falling back to 120 BPM"));break;case k.timeSignature:case k.endOfTrack:case k.midiChannelPrefix:case k.songPosition:case k.activeSensing:case k.keySignature:case k.sequenceNumber:case k.sequenceSpecific:break;case k.text:case k.lyric:case k.copyright:case k.trackName:case k.marker:case k.cuePoint:case k.instrumentName:case k.programName:this.post(FA.textEvent,[t.messageData,e.status]);break;case k.midiPort:this.assignMIDIPort(A,t.messageData[0]);break;case k.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:b(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(k).find(I=>k[I]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function mn(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===yA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Ro(t){return t.messageData.currentIndex=0,6e7/zA(t.messageData,3)}function pn(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(n.ticks-e.ticks),this.midiData.loop.end<=e.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function Sn(){let t=0,A=1/0;return this.tracks.forEach((e,n)=>{this.eventIndex[n]>=e.length||e[this.eventIndex[n]].ticks>>0}function ge(t,A,e){for(let n=0;n>n*8&255}function Y(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function QA(t,A){ge(t,A,4)}function jA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function yn(t){return t>127?t-256:t}function O(t,A,e=void 0,n=!0){if(e){let s=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(s.buffer)}else{let s=!1,o="";for(let I=0;I127){if(n){s=!0;continue}else if(C===0){s=!0;continue}}o+=String.fromCharCode(C)}}return o}}function RA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let n=0;nA.length)for(let n=0;ne.header!=="LIST"?!1:(e.chunkData.currentIndex=0,O(e.chunkData,4)===A))}function Oe(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var a={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},N=[];N[a.startAddrsOffset]={min:0,max:32768,def:0};N[a.endAddrOffset]={min:-32768,max:32768,def:0};N[a.startloopAddrsOffset]={min:-32768,max:32768,def:0};N[a.endloopAddrsOffset]={min:-32768,max:32768,def:0};N[a.startAddrsCoarseOffset]={min:0,max:32768,def:0};N[a.modLfoToPitch]={min:-12e3,max:12e3,def:0};N[a.vibLfoToPitch]={min:-12e3,max:12e3,def:0};N[a.modEnvToPitch]={min:-12e3,max:12e3,def:0};N[a.initialFilterFc]={min:1500,max:13500,def:13500};N[a.initialFilterQ]={min:0,max:960,def:0};N[a.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};N[a.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};N[a.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};N[a.modLfoToVolume]={min:-960,max:960,def:0};N[a.chorusEffectsSend]={min:0,max:1e3,def:0};N[a.reverbEffectsSend]={min:0,max:1e3,def:0};N[a.pan]={min:-500,max:500,def:0};N[a.delayModLFO]={min:-12e3,max:5e3,def:-12e3};N[a.freqModLFO]={min:-16e3,max:4500,def:0};N[a.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};N[a.freqVibLFO]={min:-16e3,max:4500,def:0};N[a.delayModEnv]={min:-32768,max:5e3,def:-32768};N[a.attackModEnv]={min:-32768,max:8e3,def:-32768};N[a.holdModEnv]={min:-12e3,max:5e3,def:-12e3};N[a.decayModEnv]={min:-12e3,max:8e3,def:-12e3};N[a.sustainModEnv]={min:0,max:1e3,def:0};N[a.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};N[a.keyNumToModEnvHold]={min:-1200,max:1200,def:0};N[a.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};N[a.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};N[a.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};N[a.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};N[a.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};N[a.sustainVolEnv]={min:0,max:1440,def:0};N[a.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};N[a.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};N[a.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};N[a.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};N[a.keyNum]={min:-1,max:127,def:-1};N[a.velocity]={min:-1,max:127,def:-1};N[a.initialAttenuation]={min:-250,max:1440,def:0};N[a.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};N[a.coarseTune]={min:-120,max:120,def:0};N[a.fineTune]={min:-12700,max:12700,def:0};N[a.scaleTuning]={min:0,max:1200,def:100};N[a.exclusiveClass]={min:0,max:99999,def:0};N[a.overridingRootKey]={min:-1,max:127,def:-1};var L=class{constructor(A=a.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let n=N[A];this.generatorValue=Math.round(e),n!==void 0&&(this.generatorValue=Math.max(n.min,Math.min(n.max,this.generatorValue)))}generatorType=a.INVALID;generatorValue=0};function Dn(t,A,e){let n=N[t]||{min:0,max:32768,def:0},s=A.find(h=>h.generatorType===t),o=0;s&&(o=s.generatorValue);let I=e.find(h=>h.generatorType===t),C=n.def;I&&(C=I.generatorValue);let c=C+o;return t===a.initialAttenuation?c:Math.max(n.min,Math.min(n.max,c))}var mt=class extends L{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=jA(A[e+2],A[e+3]),A.currentIndex+=4}};function pt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new mt(t.chunkData));return A.length>1&&A.pop(),A}var V={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},cA={linear:0,concave:1,convex:2,switch:3},Go=[];for(let t=0;t<4;t++)Go.push([[],[]]);var eA=class t{constructor(A){A.srcEnum?(this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform):(this.sourceEnum=y(A,2),this.modulatorDestination=y(A,2),this.transformAmount=jA(A[A.currentIndex++],A[A.currentIndex++]),this.secondarySourceEnum=y(A,2),this.transformType=y(A,2)),this.modulatorDestination>58&&(this.modulatorDestination=a.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(A){return new t({srcEnum:A.sourceEnum,secSrcEnum:A.secondarySourceEnum,transform:A.transformType,amt:A.transformAmount,dest:A.modulatorDestination})}static isIdentical(A,e){return A.sourceEnum===e.sourceEnum&&A.modulatorDestination===e.modulatorDestination&&A.secondarySourceEnum===e.secondarySourceEnum&&A.transformType===e.transformType}sumTransform(A){return new t({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(s,o){return Object.keys(s).find(I=>s[I]===o)}let e=A(cA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(p,this.sourceIndex):e+=A(V,this.sourceIndex);let n=A(cA,this.secSrcCurveType);return n+=this.secSrcPolarity===0?" unipolar ":" bipolar ",n+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?n+=A(p,this.secSrcIndex):n+=A(V,this.secSrcIndex),`Modulator: Source: ${e} - Secondary source: ${s} + Secondary source: ${n} Destination: ${A(a,this.modulatorDestination)} Trasform amount: ${this.transformAmount} Transform type: ${this.transformType} -`}};function PA(t,A,e,s,n){return t<<10|A<<9|e<<8|s<<7|n}var St=960,yt=cA.concave,Ze=[new eA({srcEnum:PA(yt,0,1,0,V.noteOnVelocity),dest:a.initialAttenuation,amt:St,secSrcEnum:0,transform:0}),new eA({srcEnum:129,dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new eA({srcEnum:PA(yt,0,1,1,p.mainVolume),dest:a.initialAttenuation,amt:St,secSrcEnum:0,transform:0}),new eA({srcEnum:13,dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new eA({srcEnum:526,dest:a.fineTune,amt:12700,secSrcEnum:16,transform:0}),new eA({srcEnum:650,dest:a.pan,amt:1e3,secSrcEnum:0,transform:0}),new eA({srcEnum:PA(yt,0,1,1,p.expressionController),dest:a.initialAttenuation,amt:St,secSrcEnum:0,transform:0}),new eA({srcEnum:219,dest:a.reverbEffectsSend,amt:750,secSrcEnum:0,transform:0}),new eA({srcEnum:221,dest:a.chorusEffectsSend,amt:750,secSrcEnum:0,transform:0}),new eA({srcEnum:PA(cA.linear,0,0,0,V.polyPressure),dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new eA({srcEnum:PA(cA.linear,0,0,1,p.effects2Depth),dest:a.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new eA({srcEnum:PA(cA.linear,1,0,1,p.releaseTime),dest:a.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new eA({srcEnum:PA(cA.linear,1,0,1,p.brightness),dest:a.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0})];function Xe(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new eA(t.chunkData));return A}function Ds(t=!1){let A={midiControllers:new Int16Array(Dt),lockedControllers:Array(Dt).fill(!1),customControllers:new Float32Array(ks),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:uA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},lockGSNRPNParams:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let e=0;e<128;e++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),t&&this.callEvent("newchannel",void 0)}var EA=128,Dt=147,ZA=new Int16Array(Dt).fill(0);ZA[p.mainVolume]=12800;ZA[p.expressionController]=16256;ZA[p.pan]=8192;ZA[p.releaseTime]=8192;ZA[p.brightness]=8192;ZA[EA+V.pitchWheel]=8192;ZA[EA+V.pitchWheelRange]=256;var uA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},IA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},ks=Object.keys(IA).length,kt=new Float32Array(ks);kt[IA.modulationMultiplier]=1;var We={name:"INAM",album:"IPRD",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"};var _e=class{constructor(){this.timeDivision=0,this.duration=0,this.tempoChanges=[{ticks:0,tempo:120}],this.copyright="",this.tracksAmount=0,this.lyrics=[],this.firstNoteOn=0,this.keyRange={min:0,max:127},this.lastVoiceEventTick=0,this.midiPorts=[0],this.midiPortChannelOffsets=[0],this.usedChannelsOnTrack=[],this.loop={start:0,end:0},this.midiName="",this.fileName="",this.rawMidiName=void 0,this.embeddedSoundFont=void 0,this.format=0,this.RMIDInfo={},this.bankOffset=0,this.tracks=[]}};function Ce(t,A){let e=0;for(;t>0;){let s=A.tempoChanges.find(o=>o.tickst.chunkData.currentIndex;)A.push(new eA(t.chunkData));return A}function kn(t=!1){let A={midiControllers:new Int16Array(Dt),lockedControllers:Array(Dt).fill(!1),customControllers:new Float32Array(wn),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:uA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},lockGSNRPNParams:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let e=0;e<128;e++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),t&&this.callEvent("newchannel",void 0)}var EA=128,Dt=147,ZA=new Int16Array(Dt).fill(0);ZA[p.mainVolume]=12800;ZA[p.expressionController]=16256;ZA[p.pan]=8192;ZA[p.releaseTime]=8192;ZA[p.brightness]=8192;ZA[EA+V.pitchWheel]=8192;ZA[EA+V.pitchWheelRange]=256;var uA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},IA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},wn=Object.keys(IA).length,kt=new Float32Array(wn);kt[IA.modulationMultiplier]=1;var We={name:"INAM",album:"IPRD",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"};var _e=class{constructor(){this.timeDivision=0,this.duration=0,this.tempoChanges=[{ticks:0,tempo:120}],this.copyright="",this.tracksAmount=0,this.lyrics=[],this.firstNoteOn=0,this.keyRange={min:0,max:127},this.lastVoiceEventTick=0,this.midiPorts=[0],this.midiPortChannelOffsets=[0],this.usedChannelsOnTrack=[],this.loop={start:0,end:0},this.midiName="",this.fileName="",this.rawMidiName=void 0,this.embeddedSoundFont=void 0,this.format=0,this.RMIDInfo={},this.bankOffset=0,this.tracks=[]}};function Ce(t,A){let e=0;for(;t>0;){let n=A.tempoChanges.find(o=>o.ticks0&&(q+=this.tracks[D-1][this.tracks[D-1].length-1].ticks);F.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=q),P=Cs[I>>4],(I&240)===k.noteOn){v.add(AA);let oA=F.data[F.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,oA),this.keyRange.max=Math.max(this.keyRange.max,oA)}M=I;break}let j=new H(P),z=F.data.slice(F.data.currentIndex,F.data.currentIndex+P);F.data.currentIndex+=P,j.set(z,0);let CA=new ie(q,I,j);switch(w.push(CA),AA){case-2:switch(I){case k.setTempo:this.tempoChanges.push({ticks:q,tempo:6e7/zA(z,3)});break;case k.marker:switch(O(j,j.length).trim().toLowerCase()){default:break;case"start":case"loopstart":u=q;break;case"loopend":h=q}j.currentIndex=0;break;case k.midiPort:let fA=j[0];this.midiPorts[D]=fA,this.midiPortChannelOffsets[fA]===void 0&&(this.midiPortChannelOffsets[fA]=l,l+=16);break;case k.copyright:o||(this.copyright+=O(j,j.length,void 0,!1)+` +`," "),I=!0),this.RMIDInfo.IALB&&!this.RMIDInfo.IPRD&&(this.RMIDInfo.IPRD=this.RMIDInfo.IALB),this.RMIDInfo.PRD&&!this.RMIDInfo.IALB&&(this.RMIDInfo.IALB=this.RMIDInfo.IPRD),this.bankOffset=1,this.RMIDInfo[We.bankOffset]&&(this.bankOffset=y(this.RMIDInfo[We.bankOffset],2))}}C&&(this.bankOffset=0)}else s=n;let h=this.readMIDIChunk(s);if(h.type!=="MThd")throw X(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${h.type}"`);if(h.size!==6)throw X(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${h.size}`);this.format=zA(h.data,2),this.tracksAmount=zA(h.data,2),this.timeDivision=zA(h.data,2),this.keyRange={min:127,max:0},this.lyrics=[],this.tempoChanges=[{ticks:0,tempo:120}];let u=null,Q=null;this.lastVoiceEventTick=0,this.midiPorts=[];let l=0;this.midiPortChannelOffsets=[],this.usedChannelsOnTrack=[],this.tracks=[];for(let D=0;D0&&(q+=this.tracks[D-1][this.tracks[D-1].length-1].ticks);F.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=q),P=En[g>>4],(g&240)===k.noteOn){v.add(AA);let oA=F.data[F.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,oA),this.keyRange.max=Math.max(this.keyRange.max,oA)}M=g;break}let j=new H(P),z=F.data.slice(F.data.currentIndex,F.data.currentIndex+P);F.data.currentIndex+=P,j.set(z,0);let CA=new ie(q,g,j);switch(w.push(CA),AA){case-2:switch(g){case k.setTempo:this.tempoChanges.push({ticks:q,tempo:6e7/zA(z,3)});break;case k.marker:switch(O(j,j.length).trim().toLowerCase()){default:break;case"start":case"loopstart":u=q;break;case"loopend":Q=q}j.currentIndex=0;break;case k.midiPort:let fA=j[0];this.midiPorts[D]=fA,this.midiPortChannelOffsets[fA]===void 0&&(this.midiPortChannelOffsets[fA]=l,l+=16);break;case k.copyright:o||(this.copyright+=O(j,j.length,void 0,!1)+` `);break;case k.lyric:this.lyrics.push(j)}break;case-3:if(j.slice(0,7).every((oA,fA)=>xo[fA]===oA)){let oA=j.slice(7,z.length-3),fA=O(oA,oA.length)+` -`;this.copyright+=fA,m(`%cDecoded Roland SC message! %c${fA}`,r.recognized,r.value)}break;default:if((I&240)===k.controllerChange)switch(j[0]){case 2:case 116:u=q;break;case 4:case 117:h===null?h=q:h=0;break;case 0:C&&j[1]!==0&&j[1]!==127&&(m("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(w),this.usedChannelsOnTrack.push(v),m(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,r.info,r.value,r.info,r.value)}m("%cAll tracks parsed correctly!",r.recognized),SA("%cCorrecting loops, ports and detecting notes...",r.info);let d=[];for(let D of this.tracks){let w=D.find(F=>(F.messageStatusByte&240)===k.noteOn);w&&d.push(w.ticks)}this.firstNoteOn=Math.min(...d),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),u!==null&&h===null?(u=this.firstNoteOn,h=this.lastVoiceEventTick):(u===null&&(u=this.firstNoteOn),(h===null||h===0)&&(h=this.lastVoiceEventTick)),this.loop={start:u,end:h},m(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let y=0;for(let D of this.midiPorts)if(D!==-1){y=D;break}if(this.midiPorts=this.midiPorts.map(D=>D===-1?y:D),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?m("%cNo additional MIDI Ports detected.",r.info):m("%cMIDI Ports detected!",r.recognized),!g)if(this.tracks.length>1){if(this.tracks[0].find(D=>D.messageStatusByte>=k.noteOn&&D.messageStatusBytew.messageStatusByte===k.trackName);D&&(this.rawMidiName=D.messageData,this.midiName=O(D.messageData,D.messageData.length,void 0,!1))}}else{let D=this.tracks[0].find(w=>w.messageStatusByte===k.trackName);D&&(this.rawMidiName=D.messageData,this.midiName=O(D.messageData,D.messageData.length,void 0,!1))}if(this.fileName=e,this.midiName=this.midiName.trim(),this.midiName.length===0){m("%cNo name detected. Using the alt name!",r.info),this.midiName=Is(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let D=0;Dl>h?l:h),s=[];for(let h=0;h{g[y]>=d.length||d[g[y]].ticks0;){let h=c(),l=t.tracks[h];if(g[h]>=l.length){C--;continue}let d=l[g[h]];if(g[h]++,d.messageStatusByte===k.midiPort){Q[h]=d.messageData[0];continue}let y=d.messageStatusByte&240;if(y!==k.noteOn&&y!==k.controllerChange&&y!==k.programChange&&y!==k.systemExclusive)continue;let D=(d.messageStatusByte&15)+t.midiPortChannelOffsets[Q[h]]||0,w=s[D];switch(y){case k.programChange:w.program=d.messageData[0],n(w);break;case k.controllerChange:if(d.messageData[0]!==p.bankSelect||u==="gs"&&w.drums)continue;let F=d.messageData[1],v=Math.max(0,F-t.bankOffset);if(u==="xg"){let T=F===120||F===126||F===127;T!==w.drums?(w.drums=T,w.bank=w.drums?128:v,n(w)):w.bank=w.drums?128:v;continue}s[D].bank=v;break;case k.noteOn:if(d.messageData[1]===0)continue;n(w),o[w.string].add(`${d.messageData[0]}-${d.messageData[1]}`);break;case k.systemExclusive:if(d.messageData[0]!==65||d.messageData[2]!==66||d.messageData[3]!==18||d.messageData[4]!==64||!(d.messageData[5]&16)||d.messageData[6]!==21){d.messageData[0]===67&&d.messageData[2]===76&&d.messageData[5]===126&&d.messageData[6]===0&&(u="xg");continue}let M=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][d.messageData[5]&15]+t.midiPortChannelOffsets[Q[h]],q=!!(d.messageData[7]>0&&d.messageData[5]>>4);w=s[M],w.drums=q,w.bank=q?128:0,n(w);break}}for(let h of Object.keys(o))o[h].size===0&&(m(`%cDetected change but no keys for %c${h}`,r.info,r.value),delete o[h]);return X(),o}function Fs(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(e,A)}),this.duration=this.midiData.duration,this.firstNoteTime=Ce(this.midiData.firstNoteOn,this.midiData),m(`%cTotal song time: ${ft(Math.ceil(this.duration)).time}`,r.recognized),this.post(FA.songChange,[new Ve(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(N(`%cVery short song: (${ft(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function Gs(t){this.songs=t.reduce((A,e)=>{if(e.duration)return A.push(e),A;try{A.push(new ze(e.binary,e.altName||""))}catch(s){return this.post(FA.midiError,s.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function xs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Ms(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}var KA=new Int16Array(127);KA[p.mainVolume]=100;KA[p.expressionController]=127;KA[p.pan]=64;KA[p.releaseTime]=64;KA[p.brightness]=64;KA[p.effects1Depth]=0;function Ns(t,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let e=this.synth.workletProcessorChannels.length,s=Array(e).fill(8192),n=[];for(let C=0;CC===p.dataDecrement||C===p.dataIncrement||C===p.dataEntryMsb||C===p.dataDecrement||C===p.lsbForControl6DataEntry||C===p.RPNLsb||C===p.RPNMsb||C===p.NRPNLsb||C===p.NRPNMsb||C===p.bankSelect||C===p.lsbForControl0BankSelect||C===p.resetAllControllers,g=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let Q=ke(c.messageStatusByte),u=Q.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(Q.status){case k.noteOn:case k.noteOff:case k.keySignature:break;case k.pitchBend:s[u]=c.messageData[1]<<7|c.messageData[0];break;case k.programChange:let l=n[u];l.program=c.messageData[0],l.actualBank=l.bank;break;case k.controllerChange:let d=c.messageData[0];if(o(d)){let y=c.messageData[1];if(d===p.bankSelect){n[u].bank=y;break}this.sendMIDIMessages?this.sendMIDICC(u,d,y):this.synth.controllerChange(u,d,y)}else g[u]===void 0&&(g[u]=Array.from(KA)),g[u][d]=c.messageData[1];break;default:this._processEvent(c,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let h=this.tracks[C][this.eventIndex[C]];if(h===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(h.ticks-c.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7,s[C]&127),g[C]!==void 0&&g[C].forEach((c,Q)=>{c!==KA[Q]&&!o(Q)&&this.sendMIDICC(C,Q,c)}),n[C].program>=0&&n[C].actualBank>=0){let c=n[C].actualBank;this.sendMIDICC(C,p.bankSelect,c),this.sendMIDIProgramChange(C,n[C].program)}}else for(let C=0;C>7,s[C]&127),g[C]!==void 0&&g[C].forEach((c,Q)=>{c!==KA[Q]&&!o(Q)&&this.synth.controllerChange(C,Q,c)}),n[C].program>=0&&n[C].actualBank>=0){let c=n[C].actualBank;this.synth.controllerChange(C,p.bankSelect,c),this.synth.programChange(C,n[C].program)}return!0}function bs(t=!1){if(this.midiData!==void 0){if(t){this.currentTime=0;return}if(this.currentTime>=this.duration){this.currentTime=0;return}this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),this.sendMIDIMessages||this.playingNotes.forEach(A=>{this.synth.noteOn(A.channel,A.midiNote,A.velocity,!1,!0)}),this.setProcessHandler()}}function Ls(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(FA.timeChange,currentTime-Ce(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Us(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function Ts(t,A){switch(t){default:break;case UA.loadNewSongList:this.loadNewSongList(A);break;case UA.pause:this.pause();break;case UA.play:this.play(A);break;case UA.stop:this.stop();break;case UA.setTime:this.currentTime=A;break;case UA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case UA.setPlaybackRate:this.playbackRate=A;break;case UA.setLoop:this.loop=A;break;case UA.changeSong:A?this.nextSong():this.previousSong();break;case UA.getMIDI:this.post(FA.getMIDI,this.midiData);break;case UA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Hs(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:pA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Ys(t){this.post(FA.midiEvent,t)}function Js(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([k.controllerChange|t,A,e])}function vs(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([k.programChange|t,A])}function qs(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([k.pitchBend|t,e,A])}function Ps(){if(this.sendMIDIMessages){this.sendMIDIMessage([k.reset]);for(let t=0;tthis.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&AKs?440*Math.pow(2,(t-6900)/1200):Ft[~~t-je]}var Gt=-1660,Mo=1600,Rt=new Float32Array((Mo-Gt)*100+1);for(let t=0;t.5?1:0,s?e*2-1:e;case cA.concave:return s?(e=e*2-1,e<0?1-Ee[~~(e*-gA)]-1:Ee[~~e*gA]):Ee[~~(e*gA)];case cA.convex:return s?(e=e*2-1,e<0?1-Be[~~(e*-gA)]-1:Be[~~(e*gA)]):Be[~~(e*gA)]}}var xt=1,Mt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)s-=o;let C=~~s,c=C+1;for(;c>=e.loopEnd;)c-=o;let Q=s-C,u=n[c],h=n[C];A[g]=h+(u-h)*Q,s+=e.playbackStep*t.currentTuningCalculated}}else{e.end>=n.length&&(e.end=n.length-1);for(let o=0;o=e.end){t.finished=!0;return}let c=s-g,Q=n[C],u=n[g];A[o]=u+(Q-u)*c,s+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=s}function Os(t,A){let e=t.sample,s=e.cursor,n=e.loopEnd-e.loopStart,o=e.sampleData;if(t.sample.isLooping)for(let g=0;g=e.loopEnd;)s-=n;let C=~~s+1;for(;C>=e.loopEnd;)C-=n;A[g]=o[C],s+=e.playbackStep*t.currentTuningCalculated}else{e.end>=o.length&&(e.end=o.length-1);for(let g=0;g=e.end){t.finished=!0;return}A[g]=o[C],s+=e.playbackStep*t.currentTuningCalculated}}e.cursor=s}function Zs(t,A,e,s,n,o,g,C,c){if(!isNaN(e[0])){if(g>0){let Q=o[0],u=o[1];g=Math.min(g,1e3);let h=g/1300,l=t*h,d=A*h;for(let y=0;y0){let Q=C[0],u=C[1];c=Math.min(c,1e3);let h=c/1300,l=t*h,d=A*h;for(let y=0;y0)for(let Q=0;Q0)for(let Q=0;Q13499&&A.filter.reasonanceCb===0)return;let n=A.filter;(n.cutoffCents!==s||n.reasonanceCb!==A.modulatedGenerators[a.initialFilterQ])&&(n.cutoffCents=s,n.reasonanceCb=A.modulatedGenerators[a.initialFilterQ],t.calculateCoefficients(A));for(let o=0;o.45*sampleRate&&(e.cutoffHz=.45*sampleRate);let s=e.reasonanceCb/10-3.01;e.reasonanceGain=YA(-1*s);let n=1/Math.sqrt(e.reasonanceGain),o=2*Math.PI*e.cutoffHz/sampleRate,g=Math.cos(o),C=Math.sin(o)/(2*e.reasonanceGain),c=(1-g)*n,Q=c/2,u=Q,h=1+C,l=-2*g,d=1-C;e.a0=Q/h,e.a1=c/h,e.a2=u/h,e.a3=l/h,e.a4=d/h}};var Xs=.001,kA=100,Nt=90,No=.005,GA=class t{constructor(A,e){this.sampleRate=A,this.canEndOnSilentSustain=e/10>=Nt}currentSampleTime=0;sampleRate;currentAttenuationDb=kA;state=0;releaseStartDb=kA;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=YA(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static intialize(A){t.recalculate(A,!0),A.volumeEnvelope.attenuation=A.volumeEnvelope.attenuationTarget}static recalculate(A,e=!1){let s=A.volumeEnvelope,n=u=>Math.max(0,Math.floor(HA(u)*s.sampleRate));s.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[a.initialAttenuation],1440))/10,s.sustainDbRelative=Math.min(kA,A.modulatedGenerators[a.sustainVolEnv]/10),e&&(s.attenuation=s.attenuationTarget);let o=Math.min(kA,s.sustainDbRelative+s.attenuation);s.attackDuration=n(A.modulatedGenerators[a.attackVolEnv]);let g=A.modulatedGenerators[a.decayVolEnv],C=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvDecay],c=(o-s.attenuation)/kA;s.decayDuration=n(g+C)*c,s.releaseDuration=n(A.modulatedGenerators[a.releaseVolEnv]),s.delayEnd=n(A.modulatedGenerators[a.delayVolEnv]),s.attackEnd=s.attackDuration+s.delayEnd;let Q=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvHold];if(s.holdEnd=n(A.modulatedGenerators[a.holdVolEnv]+Q)+s.attackEnd,s.decayEnd=s.decayDuration+s.holdEnd,s.state===0&&s.attackEnd===0&&(s.currentAttenuationDb=s.attenuationTarget,s.state=2),A.isInRelease){s.attenuation=Math.min(kA,s.attenuationTarget);let u=Math.max(0,Math.min(kA,s.sustainDbRelative+s.attenuation)),h=(u-s.attenuation)/kA;switch(s.decayDuration=n(g+C)*h,s.state){case 0:s.releaseStartDb=kA;break;case 1:let d=(1-(s.attackEnd-s.releaseStartTimeSamples)/s.attackDuration)*YA(s.attenuation);s.releaseStartDb=20*Math.log10(d)*-1;break;case 2:s.releaseStartDb=s.attenuation;break;case 3:s.releaseStartDb=(1-(s.decayEnd-s.releaseStartTimeSamples)/s.decayDuration)*(u-s.attenuation)+s.attenuation;break;case 4:s.releaseStartDb=u;break;default:s.releaseStartDb=s.currentAttenuationDb}s.releaseStartDb=Math.max(0,Math.min(s.releaseStartDb,kA)),s.releaseStartDb>=Nt&&(A.finished=!0),s.currentReleaseGain=YA(s.releaseStartDb)}}static apply(A,e,s,n){let o=A.volumeEnvelope,g=s/10,C=n;if(A.isInRelease){let Q=n*10,u=o.currentSampleTime-o.releaseStartTimeSamples;if(u>=o.releaseDuration){for(let l=0;l=e.length)return;o.state++;case 1:let Q;for(;o.currentSampleTime=e.length)return;o.state++;case 2:for(;o.currentSampleTime=e.length)return;o.state++;case 3:for(;o.currentSampleTime=e.length)return}o.state++;case 4:for(o.canEndOnSilentSustain&&o.sustainDbRelative>=Nt&&(A.finished=!0);;){o.attenuation+=(o.attenuationTarget-o.attenuation)*C;let u=Math.min(kA,o.sustainDbRelative+o.attenuation);if(e[c]*=YA(u+g),o.currentAttenuationDb=u,o.currentSampleTime++,++c>=e.length)return}}}};var Ws=Math.PI/2,_s=.01;function zs(t,A,e,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,GA.startRelease(A),JA.startRelease(A)),A.modulatedGenerators[a.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let g=A.targetKey,C=A.modulatedGenerators[a.fineTune]+t.customControllers[IA.channelTuning]+t.customControllers[IA.channelTransposeFine]+t.customControllers[IA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],c=A.modulatedGenerators[a.coarseTune]+t.customControllers[IA.channelTuningSemitones],Q=this.tunings[t.preset.program]?.[g];Q?.midiNote>=0&&(g=Q.midiNote,C+=Q.centTuning),C+=(g-A.sample.rootKey)*A.modulatedGenerators[a.scaleTuning];let u=A.modulatedGenerators[a.vibLfoToPitch];if(u!==0){let z=A.startTime+HA(A.modulatedGenerators[a.delayVibLFO]),CA=we(A.modulatedGenerators[a.freqVibLFO]),oA=$e(z,CA,currentTime);C+=oA*(u*t.customControllers[IA.modulationMultiplier])}let h=A.modulatedGenerators[a.initialFilterFc],l=A.modulatedGenerators[a.modLfoToPitch],d=A.modulatedGenerators[a.modLfoToVolume],y=A.modulatedGenerators[a.modLfoToFilterFc],D=0;if(l+y+d!==0){let z=A.startTime+HA(A.modulatedGenerators[a.delayModLFO]),CA=we(A.modulatedGenerators[a.freqModLFO]),oA=$e(z,CA,currentTime);C+=oA*(l*t.customControllers[IA.modulationMultiplier]),D=-oA*d,h+=oA*y}if(t.channelVibrato.depth>0){let z=$e(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);z&&(C+=z*t.channelVibrato.depth)}let w=A.modulatedGenerators[a.modEnvToPitch],F=A.modulatedGenerators[a.modEnvToFilterFc],v=JA.getValue(A,currentTime);h+=v*F,C+=v*w;let M=~~(C+c*100);M!==A.currentTuningCents&&(A.currentTuningCents=M,A.currentTuningCalculated=Math.pow(2,M/1200));let q=(Math.max(-500,Math.min(500,A.modulatedGenerators[a.pan]))+500)/1e3,T=new Float32Array(e.length);switch(this.interpolationType){case Fe.linear:default:Vs(A,T);break;case Fe.nearestNeighbor:Os(A,T);break}he.apply(A,T,h),GA.apply(A,T,D,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(q-A.currentPan)*this.panSmoothingFactor;let I=Math.cos(Ws*A.currentPan)*this.panLeft,AA=Math.sin(Ws*A.currentPan)*this.panRight,P=this.oneOutputMode?0:A.modulatedGenerators[a.reverbEffectsSend],j=this.oneOutputMode?0:A.modulatedGenerators[a.chorusEffectsSend];Zs(I,AA,T,e,s,n,P,o,j)}function bo(t,A){let e=0;return t.drumChannel&&(e+=5),A.isInRelease&&(e-=5),e+=A.velocity/25,e-=A.volumeEnvelope.state,A.isInRelease&&(e-=5),e-=A.volumeEnvelope.currentAttenuationDb/50,e}function js(t){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=bo(s,n);A.push({channel:s,voice:n,priority:o})}A.sort((s,n)=>s.priority-n.priority);let e=A.slice(0,t);for(let{channel:s,voice:n}of e){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function $s(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimeen=t);var Lo=function(t){var A,e,s,n,o,g,C,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Q="",u=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=c.indexOf(t.charAt(u++)),o=c.indexOf(t.charAt(u++)),g=c.indexOf(t.charAt(u++)),C=c.indexOf(t.charAt(u++)),A=n<<2|o>>4,e=(15&o)<<4|g>>2,s=(3&g)<<6|C,Q+=String.fromCharCode(A),g!==64&&(Q+=String.fromCharCode(e)),C!==64&&(Q+=String.fromCharCode(s));while(u1&&(I.thisProgram=process.argv[1].replace(/\\/g,"/")),I.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(i){if(!(i instanceof pe))throw i}),process.on("unhandledRejection",function(i,E){process.exit(1)}),I.quit=function(i){process.exit(i)},I.inspect=function(){return"[Emscripten Module object]"}):CA?(typeof read<"u"&&(I.read=function(E){return read(E)}),I.readBinary=function(E){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(B=read(E,"binary"))=="object"),B)},typeof scriptArgs<"u"?I.arguments=scriptArgs:typeof arguments<"u"&&(I.arguments=arguments),typeof quit=="function"&&(I.quit=function(i){quit(i)})):(P||j)&&(P?document.currentScript&&(oA=document.currentScript.src):oA=self.location.href,oA=oA.indexOf("blob:")!==0?oA.split("/").slice(0,-1).join("/")+"/":"",I.read=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.send(null),B.responseText},j&&(I.readBinary=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.responseType="arraybuffer",B.send(null),new Uint8Array(B.response)}),I.readAsync=function(E,B,f){var R=new XMLHttpRequest;R.open("GET",E,!0),R.responseType="arraybuffer",R.onload=function(){if(R.status==200||R.status==0&&R.response){B(R.response);return}f()},R.onerror=f,R.send(null)},I.setWindowTitle=function(i){document.title=i});var Me=I.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),xA=I.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Me);for(t in AA)AA.hasOwnProperty(t)&&(I[t]=AA[t]);function Ne(i){var E=d;return d=d+i+15&-16,E}function qt(i){var E=c[M>>2],B=E+i+15&-16;return c[M>>2]=B,B>=BA&&!jt()?(c[M>>2]=E,0):E}function Pt(i,E){return E||(E=16),i=Math.ceil(i/E)*E}function Qo(i){switch(i){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(i[i.length-1]==="*")return 4;if(i[0]!=="i")return 0;var E=parseInt(i.substr(1));return _A(E%8==0),E/8}}function de(i){de.shown||(de.shown={}),de.shown[i]||(de.shown[i]=1,xA(i))}AA=void 0;var co={"f64-rem":function(i,E){return i%E},debugger:function(){}},rt=[];function vo(i,E){for(var B=0,f=B;f>>0)+4294967296*+(E>>>0):+(i>>>0)+4294967296*+(0|E)}function at(i,E,B){return B&&B.length?I["dynCall_"+i].apply(null,[E].concat(B)):I["dynCall_"+i].call(null,E)}var be=0,Kt=0;function _A(i,E){i||OA("Assertion failed: "+E)}function Vt(i){var E=I["_"+i];return _A(E,"Cannot call unknown function "+i+", make sure it is exported"),E}var Ot={stackSave:function(){ct()},stackRestore:function(){Qt()},arrayToC:function(i){var E,B,f=Je(i.length);return E=i,B=f,n.set(E,B),f},stringToC:function(i){var E=0;if(i!=null&&i!==0){var B=(i.length<<2)+1;E=Je(B),Wt(i,E,B)}return E}},lo={string:Ot.stringToC,array:Ot.arrayToC};function Zt(i,E,B,f,R){var K=Vt(i),W=[],x=0;if(f)for(var hA=0;hA>0]=E;break;case"i16":g[i>>1]=E;break;case"i32":c[i>>2]=E;break;case"i64":tempI64=[E>>>0,+yo(tempDouble=E)>=1?tempDouble>0?(0|ko(+ss(tempDouble/4294967296),4294967295))>>>0:~~+Do((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],c[i>>2]=tempI64[0],c[i+4>>2]=tempI64[1];break;case"float":u[i>>2]=E;break;case"double":h[i>>3]=E;break;default:OA("invalid type for setValue: "+B)}}function Vo(i,E,B){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return n[i>>0];case"i16":return g[i>>1];case"i32":case"i64":return c[i>>2];case"float":return u[i>>2];case"double":return h[i>>3];default:OA("invalid type for getValue: "+E)}return null}function Oo(i,E,B,f){typeof i=="number"?(K=!0,W=i):(K=!1,W=i.length);var R=typeof E=="string"?E:null;if(x=B==4?f:[typeof Ye=="function"?Ye:Ne,Je,Ne,qt][B===void 0?2:B](Math.max(W,R?1:E.length)),K){for(f=x,_A((3&x)==0),hA=x+(-4&W);f>2]=0;for(hA=x+W;f>0]=0;return x}if(R==="i8")return i.subarray||i.slice?o.set(i,x):o.set(new Uint8Array(i),x),x;for(var K,W,x,hA,rA,iA,sA,J=0;J>0],(f!=0||E)&&(W++,!E||W!=E););E||(E=W);var x="";if(K<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(i,i+Math.min(E,1024))),x=x?x+R:R,i+=1024,E-=1024;return x}return B=i,function(rA,iA){for(var sA=iA;rA[sA];)++sA;if(sA-iA>16&&rA.subarray&&Xt)return Xt.decode(rA.subarray(iA,sA));for(var J,mA,MA,NA,bA,ee,LA="";;){if(!(J=rA[iA++]))return LA;if(!(128&J)){LA+=String.fromCharCode(J);continue}if(mA=63&rA[iA++],(224&J)==192){LA+=String.fromCharCode((31&J)<<6|mA);continue}if(MA=63&rA[iA++],(240&J)==224?J=(15&J)<<12|mA<<6|MA:(NA=63&rA[iA++],(248&J)==240?J=(7&J)<<18|mA<<12|MA<<6|NA:(bA=63&rA[iA++],J=(252&J)==248?(3&J)<<24|mA<<18|MA<<12|NA<<6|bA:(1&J)<<30|mA<<24|MA<<18|NA<<12|bA<<6|(ee=63&rA[iA++]))),J<65536)LA+=String.fromCharCode(J);else{var Se=J-65536;LA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(o,B)}function Xo(i){for(var E="";;){var B=n[i++>>0];if(!B)return E;E+=String.fromCharCode(B)}}function Wo(i,E){return function(f,R,K){for(var W=0;W>0]=f.charCodeAt(W);K||(n[R>>0]=0)}(i,E,!1)}var Xt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ue(i,E,B,f){if(!(f>0))return 0;for(var R=B,K=B+f-1,W=0;W=55296&&x<=57343&&(x=65536+((1023&x)<<10)|1023&i.charCodeAt(++W)),x<=127){if(B>=K)break;E[B++]=x}else if(x<=2047){if(B+1>=K)break;E[B++]=192|x>>6,E[B++]=128|63&x}else if(x<=65535){if(B+2>=K)break;E[B++]=224|x>>12,E[B++]=128|x>>6&63,E[B++]=128|63&x}else if(x<=2097151){if(B+3>=K)break;E[B++]=240|x>>18,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}else if(x<=67108863){if(B+4>=K)break;E[B++]=248|x>>24,E[B++]=128|x>>18&63,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}else{if(B+5>=K)break;E[B++]=252|x>>30,E[B++]=128|x>>24&63,E[B++]=128|x>>18&63,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}}return E[B]=0,B-R}function Wt(i,E,B){return Ue(i,o,E,B)}function Te(i){for(var E=0,B=0;B=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&i.charCodeAt(++B)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var _t=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function _o(i){for(var E=i,B=E>>1;g[B];)++B;if((E=B<<1)-i>32&&_t)return _t.decode(o.subarray(i,E));for(var f=0,R="";;){var K=g[i+2*f>>1];if(K==0)return R;++f,R+=String.fromCharCode(K)}}function zo(i,E,B){if(B===void 0&&(B=2147483647),B<2)return 0;for(var f=E,R=(B-=2)<2*i.length?B/2:i.length,K=0;K>1]=W,E+=2}return g[E>>1]=0,E-f}function jo(i){return 2*i.length}function $o(i){for(var E=0,B="";;){var f=c[i+4*E>>2];if(f==0)return B;if(++E,f>=65536){var R=f-65536;B+=String.fromCharCode(55296|R>>10,56320|1023&R)}else B+=String.fromCharCode(f)}}function Ar(i,E,B){if(B===void 0&&(B=2147483647),B<4)return 0;for(var f=E,R=f+B-4,K=0;K=55296&&W<=57343&&(W=65536+((1023&W)<<10)|1023&i.charCodeAt(++K)),c[E>>2]=W,(E+=4)+4>R)break}return c[E>>2]=0,E-f}function er(i){for(var E=0,B=0;B=55296&&f<=57343&&++B,E+=4}return E}function tr(i){var E=Te(i)+1,B=Ye(E);return B&&Ue(i,n,B,E),B}function sr(i){var E=Te(i)+1,B=Je(E);return Ue(i,n,B,E),B}function nr(i){return i}function or(){var i,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(R){f=R}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return I.extraStackTrace&&(E+=` -`+I.extraStackTrace()),(i=E).replace(/__Z[\w\d_]+/g,function(B){var f,R=f=B;return B===R?B:B+" ["+R+"]"})}function It(i,E){return i%E>0&&(i+=E-i%E),i}function zt(i){I.buffer=s=i}function gt(){I.HEAP8=n=new Int8Array(s),I.HEAP16=g=new Int16Array(s),I.HEAP32=c=new Int32Array(s),I.HEAPU8=o=new Uint8Array(s),I.HEAPU16=C=new Uint16Array(s),I.HEAPU32=Q=new Uint32Array(s),I.HEAPF32=u=new Float32Array(s),I.HEAPF64=h=new Float64Array(s)}function jt(){var i=I.usingWasm?65536:16777216,E=2147483648-i;if(c[M>>2]>E)return!1;var B=BA;for(BA=Math.max(BA,16777216);BA>2];)BA=BA<=536870912?It(2*BA,i):Math.min(It((3*BA+2147483648)/4,i),E);var f=I.reallocBuffer(BA);return f&&f.byteLength==BA?(zt(f),gt(),!0):(BA=B,!1)}l=d=D=w=F=v=M=0,y=!1,I.reallocBuffer||(I.reallocBuffer=function(i){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(s,i);else{var E,B=n;E=new ArrayBuffer(i),new Int8Array(E).set(B)}}catch{return!1}return!!wo(E)&&E});try{(q=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{q=function(E){return E.byteLength}}var Ct=I.TOTAL_STACK||5242880,BA=I.TOTAL_MEMORY||16777216;function fo(){return BA}function fe(i){for(;i.length>0;){var E=i.shift();if(typeof E=="function"){E();continue}var B=E.func;typeof B=="number"?E.arg===void 0?I.dynCall_v(B):I.dynCall_vi(B,E.arg):B(E.arg===void 0?null:E.arg)}}BA=0?i:E<=32?2*Math.abs(1<=f&&(E<=32||i>f)&&(i=-2*f+i),i}var yo=Math.abs,Do=Math.ceil,ss=Math.floor,ko=Math.min,Ae=0,ht=null,me=null;function Er(i){return i}I.preloadedImages={},I.preloadedAudios={};var ns="data:application/octet-stream;base64,";function He(i){return String.prototype.startsWith?i.startsWith(ns):i.indexOf(ns)===0}(function(){var E="main.wast",B="main.wasm",f="main.temp.asm.js";He(E)||(E=fA(E)),He(B)||(B=fA(B)),He(f)||(f=fA(f));var R={global:null,env:null,asm2wasm:co,parent:I},K=null;function W(sA){return sA}function x(){try{if(I.wasmBinary)return new Uint8Array(I.wasmBinary);if(I.readBinary)return I.readBinary(B);throw"both async and sync fetching of the wasm failed"}catch(sA){OA(sA)}}I.asmPreload=I.asm;var hA=I.reallocBuffer,rA=function(sA){sA=It(sA,I.usingWasm?65536:16777216);var J=I.buffer.byteLength;if(I.usingWasm)try{var mA=I.wasmMemory.grow((sA-J)/65536);return mA!==-1?I.buffer=I.wasmMemory.buffer:null}catch{return null}};I.reallocBuffer=function(sA){return iA==="asmjs"?hA(sA):rA(sA)};var iA="";I.asm=function(sA,J,mA){var MA;if(!(J=MA=J).table){var NA,bA=I.wasmTableSize;bA===void 0&&(bA=1024);var ee=I.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?ee!==void 0?J.table=new WebAssembly.Table({initial:bA,maximum:ee,element:"anyfunc"}):J.table=new WebAssembly.Table({initial:bA,element:"anyfunc"}):J.table=Array(bA),I.wasmTable=J.table}return J.memoryBase||(J.memoryBase=I.STATIC_BASE),J.tableBase||(J.tableBase=0),NA=function(Se,oe,ut){if(typeof WebAssembly!="object")return xA("no native wasm support detected"),!1;if(!(I.wasmMemory instanceof WebAssembly.Memory))return xA("no native wasm Memory in use"),!1;function ve(vA,qA){if((K=vA.exports).memory){var ye,dt,is;ye=K.memory,dt=I.buffer,ye.byteLength0?B:Te(i)+1,R=Array(f),K=Ue(i,R,0,R.length);return E&&(R.length=K),R}function cr(i){for(var E=[],B=0;B255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}d+=16,M=Ne(4),F=(D=w=Pt(d))+Ct,v=Pt(F),c[M>>2]=v,y=!0,I.wasmTableSize=4,I.wasmMaxTableSize=4,I.asmGlobalArg={},I.asmLibraryArg={abort:OA,assert:_A,enlargeMemory:jt,getTotalMemory:fo,abortOnCannotGrowMemory:function(){OA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+BA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(E,B,f){var R=ct();try{return I.dynCall_iii(E,B,f)}catch(K){if(Qt(R),typeof K!="number"&&K!=="longjmp")throw K;I.setThrew(1,0)}},___assert_fail:function(E,B,f,R){OA("Assertion failed: "+Le(E)+", at: "+[B?Le(B):"unknown filename",f,R?Le(R):"unknown function"])},___setErrNo:function(E){return I.___errno_location&&(c[I.___errno_location()>>2]=E),E},_abort:function(){I.abort()},_emscripten_memcpy_big:function(E,B,f){return o.set(o.subarray(B,B+f),E),E},_llvm_floor_f64:ss,DYNAMICTOP_PTR:M,tempDoublePtr:wA,ABORT:be,STACKTOP:w,STACK_MAX:F};var os=I.asm(I.asmGlobalArg,I.asmLibraryArg,s);I.asm=os,I.___errno_location=function(){return I.asm.___errno_location.apply(null,arguments)};var wo=I._emscripten_replace_memory=function(){return I.asm._emscripten_replace_memory.apply(null,arguments)};I._free=function(){return I.asm._free.apply(null,arguments)};var Ye=I._malloc=function(){return I.asm._malloc.apply(null,arguments)};I._memcpy=function(){return I.asm._memcpy.apply(null,arguments)},I._memset=function(){return I.asm._memset.apply(null,arguments)},I._sbrk=function(){return I.asm._sbrk.apply(null,arguments)},I._stb_vorbis_js_channels=function(){return I.asm._stb_vorbis_js_channels.apply(null,arguments)},I._stb_vorbis_js_close=function(){return I.asm._stb_vorbis_js_close.apply(null,arguments)},I._stb_vorbis_js_decode=function(){return I.asm._stb_vorbis_js_decode.apply(null,arguments)},I._stb_vorbis_js_open=function(){return I.asm._stb_vorbis_js_open.apply(null,arguments)},I._stb_vorbis_js_sample_rate=function(){return I.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},I.establishStackSpace=function(){return I.asm.establishStackSpace.apply(null,arguments)},I.getTempRet0=function(){return I.asm.getTempRet0.apply(null,arguments)},I.runPostSets=function(){return I.asm.runPostSets.apply(null,arguments)},I.setTempRet0=function(){return I.asm.setTempRet0.apply(null,arguments)},I.setThrew=function(){return I.asm.setThrew.apply(null,arguments)};var Je=I.stackAlloc=function(){return I.asm.stackAlloc.apply(null,arguments)},Qt=I.stackRestore=function(){return I.asm.stackRestore.apply(null,arguments)},ct=I.stackSave=function(){return I.asm.stackSave.apply(null,arguments)};function pe(i){this.name="ExitStatus",this.message="Program terminated with exit("+i+")",this.status=i}function lt(i){i=i||I.arguments,!(Ae>0)&&(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)po(I.preRun.shift());fe($t)}(),!(Ae>0)&&(I.calledRun||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),E()},1)):E())));function E(){!I.calledRun&&(I.calledRun=!0,be||(Bt||(Bt=!0,fe(Et)),fe(As),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)So(I.postRun.shift());fe(ts)}()))}}function lr(i,E){(!E||!I.noExitRuntime||i!==0)&&(I.noExitRuntime||(be=!0,Kt=i,w=T,fe(es),mo=!0,I.onExit&&I.onExit(i)),I.quit(i,new pe(i)))}function OA(i){throw I.onAbort&&I.onAbort(i),i!==void 0?(Me(i),xA(i),i=JSON.stringify(i)):i="",be=!0,Kt=1,"abort("+i+"). Build with -s ASSERTIONS=1 for more info."}if(I.dynCall_iii=function(){return I.asm.dynCall_iii.apply(null,arguments)},I.asm=os,I.ccall=Zt,I.cwrap=function(E,B,f,R){var K=(f=f||[]).every(function(W){return W==="number"});return B!=="string"&&K&&!R?Vt(E):function(){return Zt(E,B,f,arguments,R)}},pe.prototype=Error(),pe.prototype.constructor=pe,me=function i(){I.calledRun||lt(),I.calledRun||(me=i)},I.run=lt,I.abort=OA,I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();I.noExitRuntime=!0,lt(),I.onRuntimeInitialized=()=>{An=!0,en()},VA.decode=function(i){return function(B){if(!An)throw Error("Not initialized");var f={};function R(oe){return new Int32Array(I.HEAPU8.buffer,oe,1)[0]}function K(oe,ut){var ve=new ArrayBuffer(ut*Float32Array.BYTES_PER_ELEMENT),re=new Float32Array(ve);return re.set(new Float32Array(I.HEAPU8.buffer,oe,ut)),re}f.open=I.cwrap("stb_vorbis_js_open","number",[]),f.close=I.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=I.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=I.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=I.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var W,x,hA,rA,iA=f.open(),sA=(W=B,x=B.byteLength,hA=I._malloc(x),(rA=new Uint8Array(I.HEAPU8.buffer,hA,x)).set(new Uint8Array(W,0,x)),rA),J=I._malloc(4),mA=I._malloc(4),MA=f.decode(iA,sA.byteOffset,sA.byteLength,J,mA);if(I._free(sA.byteOffset),MA<0)throw f.close(iA),I._free(J),Error("stbvorbis decode failed: "+MA);for(var NA=f.channels(iA),bA=Array(NA),ee=new Int32Array(I.HEAPU32.buffer,R(J),NA),LA=0;LA=0&&(s=this.workletProcessorChannels[e]),t.messageType){case tA.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case tA.noteOff:this.noteOff(e,A);break;case tA.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case tA.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case tA.customcCcChange:s.customControllers[A[0]]=A[1];break;case tA.killNote:this.killNote(e,A);break;case tA.programChange:this.programChange(e,A[0],A[1]);break;case tA.channelPressure:this.channelPressure(e,A);break;case tA.polyPressure:this.polyPressure(e,A[0],A[1]);break;case tA.ccReset:e===TA?this.resetAllControllers():this.resetControllers(e);break;case tA.systemExclusive:this.systemExclusive(A);break;case tA.setChannelVibrato:if(e===TA)for(let g=0;g{let e=(A.midiControllers[EA+V.pitchWheelRange]>>7)+(A.midiControllers[EA+V.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[EA+V.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:pA.channelProperties,messageData:t})}function Uo(t,A,e){let s=t,n=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function on(t,A=0){let e=t[0];if(!(this.deviceID!==TA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:N(`%cUnrecognized SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let n;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),m(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),m(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let c=(t[5]<<7|t[6])-8192;n=Math.floor(c/81.92),this.setMasterTuning(n),m(`%cMaster Fine Tuning. Cents: %c${n}`,r.info,r.value);break;case 4:n=(t[5]-64)*100,this.setMasterTuning(n),m(`%cMaster Coarse Tuning. Cents: %c${n}`,r.info,r.value);break;default:N(`%cUnrecognized MIDI Device Control Real-time message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(m("%cGM system on",r.info),this.system="gm"):t[3]===3?(m("%cGM2 system on",r.info),this.system="gm2"):(m("%cGM system off, defaulting to GS",r.info),this.system="gs");break;case 8:switch(t[3]){case 2:case 7:let o=4;t[3]===7&&o++;let g=t[o++],C=t[o++];for(let Q=0;Q>1&1)===1&&this.setOctaveTuning(15+A,c);for(let Q=0;Q<7;Q++)(t[5]>>Q&1)===1&&this.setOctaveTuning(7+Q+A,c);for(let Q=0;Q<7;Q++)(t[6]>>Q&1)===1&&this.setOctaveTuning(Q+A,c);m(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${c.join(" ")}`,r.info,r.value);break;default:N(`%cUnrecognized MIDI Tuning standard message: %c${lA(t)}`,r.warn,r.unrecognized);break}break;default:N(`%cUnrecognized MIDI Realtime/non realtime message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 65:let s=function(){N(`%cUnrecognized Roland %cGS %cSysEx: %c${lA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let n=t[7];if(t[6]===127){n===0?(m("%cGS Reset received!",r.info),this.resetAllControllers(!1),this.system="gs"):n===127&&(m("%cGS system off, switching to GM2",r.info),this.resetAllControllers(!1),this.system="gm2");return}else if(t[4]===64){if((t[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A;switch(t[6]){default:s();break;case 21:let g=n>0&&t[5]>>4;this.setDrums(o,g),m(`%cChannel %c${o}%c ${g?"is now a drum channel":"now isn't a drum channel"}%c via: %c${lA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=n-64;this.transposeChannel(o,C),m(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${lA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let c=n;c===0&&(c=Math.floor(Math.random()*128)),this.controllerChange(o,p.pan,c);break;case 33:this.controllerChange(o,p.effects3Depth,n);break;case 34:this.controllerChange(o,p.effects1Depth,n);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 Q=t.length-9,u=new Int8Array(12);for(let l=0;l=this.workletProcessorChannels.length)return;let o=t[6];switch(t[5]){case 1:this.controllerChange(n,p.bankSelect,o);break;case 2:this.controllerChange(n,p.lsbForControl0BankSelect,o);break;case 3:this.programChange(n,o);break;case 8:let g=this.workletProcessorChannels[n];if(g.drumChannel)return;let C=o-64;g.channelTransposeKeyShift=C;break;case 11:this.controllerChange(n,p.mainVolume,o);break;case 14:let c=o;c===0&&(c=Math.floor(Math.random()*127)),this.controllerChange(n,p.pan,c);break;case 19:this.controllerChange(n,p.effects1Depth,o);break;case 18:this.controllerChange(n,p.effects3Depth,o);break;default:N(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&N(`%cUnrecognized Yamaha XG SysEx: %c${lA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&N(`%cUnrecognized Yamaha SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break}}function rn(t,A,e){if(A.transformAmount===0)return 0;let s;if(A.sourceUsesCC)s=t[A.sourceIndex];else{let c=A.sourceIndex+EA;switch(A.sourceIndex){case V.noController:s=16383;break;case V.noteOnKeyNum:s=e.midiNote<<7;break;case V.noteOnVelocity:s=e.velocity<<7;break;case V.polyPressure:s=e.pressure<<7;break;default:s=t[c];break}}let n=dA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let c=A.secSrcIndex+EA;switch(A.secSrcIndex){case V.noController:o=16383;break;case V.noteOnKeyNum:o=e.midiNote<<7;break;case V.noteOnVelocity:o=e.velocity<<7;break;case V.polyPressure:o=e.pressure<<7;break;default:o=t[c]}}let g=dA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=n*g*A.transformAmount;return A.transformType===2?Math.abs(C):C}function XA(t,A,e=-1,s=0){let{modulators:n,generators:o,modulatedGenerators:g}=t;if(JA.recalculate(t),e===-1){g.set(o),n.forEach(Q=>{g[Q.modulatorDestination]+=rn(A,Q,t)}),GA.recalculate(t);return}let C=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),c=new Set;n.forEach(Q=>{if(Q.sourceUsesCC===e&&Q.sourceIndex===s||Q.secSrcUsesCC===e&&Q.secSrcIndex===s){let u=Q.modulatorDestination;c.has(u)||(g[u]=o[u],n.forEach(h=>{h.modulatorDestination===u&&(g[u]+=rn(A,h,t))}),c.add(u))}}),[...c].some(Q=>C.has(Q))&&GA.recalculate(t)}var dA=[];for(let t=0;t<4;t++){dA[t]=[[new Float32Array(gA),new Float32Array(gA)],[new Float32Array(gA),new Float32Array(gA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||g.isMuted)return;let C=A+g.channelTransposeKeyShift;if(A>127||A<0)return;let c=g.preset.program;this.tunings[c]?.[A]?.midiNote>=0&&(C=this.tunings[c]?.[A].midiNote);let Q=this.getWorkletVoices(t,C,e,g,o,s),u=g.voices;Q.forEach(h=>{let l=h.generators[a.exclusiveClass];l!==0&&u.forEach(d=>{d.generators[a.exclusiveClass]===l&&(this.releaseVoice(d),d.modulatedGenerators[a.releaseVolEnv]=-7e3,d.modulatedGenerators[a.releaseModEnv]=-7e3,GA.recalculate(d),JA.recalculate(d))}),XA(h,g.midiControllers),GA.intialize(h),h.currentPan=(Math.max(-500,Math.min(500,h.modulatedGenerators[a.pan]))+500)/1e3}),this.totalVoicesAmount+=Q.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(Q.length),u.push(...Q),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function In(t,A){if(A>127||A<0){N("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift,s=this.workletProcessorChannels[t].preset.program;if(this.tunings[s]?.[A]?.midiNote>=0&&(e=this.tunings[s]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(o=>{o.midiNote!==e||o.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function gn(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.midiNote===A&&(e.modulatedGenerators[a.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function Cn(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[t].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function En(t=!1){m("%cStop all received!",r.info);for(let A=0;AXA(n,this.workletProcessorChannels[t].midiControllers,0,V.pitchWheel)),this.sendChannelProperties()}function fn(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[EA+V.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(s=>XA(s,e.midiControllers,0,V.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function mn(t,A,e){this.workletProcessorChannels[t].voices.forEach(s=>{s.midiNote===A&&(s.pressure=e,XA(s,this.workletProcessorChannels[t].midiControllers,0,V.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function pn(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function Sn(t,A,e,s=!1){let n=this.workletProcessorChannels[t];if(n===void 0){N(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>=p.lsbForControl1ModulationWheel&&A<=p.lsbForControl13EffectControl2&&A!==p.lsbForControl6DataEntry){let o=A-32;if(n.lockedControllers[o])return;n.midiControllers[o]=n.midiControllers[o]&16256|e&127,n.voices.forEach(g=>XA(g,n.midiControllers,1,o))}switch(A){case p.allNotesOff:this.stopAll(t);break;case p.allSoundOff:this.stopAll(t,!0);break;case p.bankSelect:let o=e;if(!s){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==yA&&this.setDrums(t,!1);break;case"gm2":o===120&&(n.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}n.drumChannel&&(o=128),o===128&&!n.drumChannel&&(o=n.midiControllers[p.bankSelect])}n.midiControllers[p.bankSelect]=o;break;case p.lsbForControl0BankSelect:this.system==="xg"?n.drumChannel||e!==127&&(n.midiControllers[p.bankSelect]=e):this.system==="gm2"&&(n.midiControllers[p.bankSelect]=e);break;case p.RPNLsb:n.RPValue=n.RPValue<<7|e,n.dataEntryState=uA.RPFine;break;case p.RPNMsb:n.RPValue=e,n.dataEntryState=uA.RPCoarse;break;case p.NRPNMsb:n.NRPCoarse=e,n.dataEntryState=uA.NRPCoarse;break;case p.NRPNLsb:n.NRPFine=e,n.dataEntryState=uA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(t,e);break;case p.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case p.resetAllControllers:this.resetControllers(t);break;case p.sustainPedal:e>=64?n.holdPedal=!0:(n.holdPedal=!1,n.sustainedVoices.forEach(g=>{this.releaseVoice(g)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=e<<7,n.voices.forEach(g=>XA(g,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function yn(t){this.midiVolume=t,this.setMasterPan(this.pan)}function Dn(t){this.masterGain=t*Lt,this.setMasterPan(this.pan)}function kn(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function wn(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function Fn(t){this.workletProcessorChannels[t].lockGSNRPNParams=!0,this.workletProcessorChannels[t].channelVibrato.rate=0,this.workletProcessorChannels[t].channelVibrato.delay=0,this.workletProcessorChannels[t].channelVibrato.depth=0}function Rn(t,A,e,s){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=s,this.workletProcessorChannels[t].channelVibrato.depth=A)}function Gn(t,A){let e=this.workletProcessorChannels[t],s=()=>{e.channelVibrato.delay===0&&e.channelVibrato.rate===0&&e.channelVibrato.depth===0&&(e.channelVibrato.depth=50,e.channelVibrato.rate=8,e.channelVibrato.delay=.6)};switch(e.dataEntryState){default:case uA.Idle:break;case uA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;N(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16).toUpperCase()} 0x${e.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 1:switch(e.NRPFine){default:if(A===64)return;N(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16)} 0x${e.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(A===64)return;s(),e.channelVibrato.rate=A/64*8,m(`%cVibrato rate for %c${t}%c is now set to %c${A} = ${e.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(A===64)return;s(),e.channelVibrato.depth=A/2,m(`%cVibrato depth for %c${t}%c is now set to %c${A} = ${e.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(A===64)return;s(),e.channelVibrato.delay=A/64/3,m(`%cVibrato delay for %c${t}%c is now set to %c${A} = ${e.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let g=A;this.controllerChange(t,p.brightness,A),m(`%cFilter cutoff for %c${t}%c is now set to %c${g}`,r.info,r.recognized,r.info,r.value)}break;case 24:let n=A-64;e.keyCentTuning[e.NRPFine]=n*100,m(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${n}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,p.effects1Depth,o),m(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:N(`%cUnrecognized RPN for %c${t}%c: %c(0x${e.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:e.midiControllers[EA+V.pitchWheelRange]=A<<7,m(`%cChannel ${t} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(t,A-64);break;case 1:this.setChannelTuning(t,A-64,!1);break;case 5:this.setModulationDepth(t,A*100);break;case 16383:this.resetParameters(t);break}}}function xn(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[EA+V.pitchWheelRange]|=A;let s=(e.midiControllers[EA+V.pitchWheelRange]>>7)+A/127;m(`%cChannel ${t} bend range. Semitones: %c${s}`,r.info,r.value);break;case 1:let o=e.customControllers[IA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[IA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function Mn(t=!0){t&&m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A{this.workletProcessorChannels[A].lockedControllers[n]&&this.callEvent("controllerchange",{channel:A,controllerNumber:n,controllerValue:this.workletProcessorChannels[A].midiControllers[n]>>7})};if(s(p.mainVolume),s(p.pan),s(p.expressionController),s(p.modulationWheel),s(p.effects3Depth),s(p.effects1Depth),s(p.brightness),this.workletProcessorChannels[A].lockedControllers[EA+V.pitchWheel]){let n=this.workletProcessorChannels[A].midiControllers[EA+V.pitchWheel],o=n>>7,g=n&127;this.callEvent("pitchwheel",{channel:A,MSB:o,LSB:g})}}this.tunings=[],this.tunings=[];for(let A=0;A<127;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Ke}function Nn(t){let A=this.workletProcessorChannels[t],s=A.lockedControllers.reduce((o,g,C)=>(g&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(ZA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let n=A.customControllers[IA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[IA.channelTransposeFine]=n,this.resetParameters(t)}function bn(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=uA.Idle}function Ln(){let t=4;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>(o.generators=o.generators.filter(g=>g.generatorType!==a.sampleID&&g.generatorType!==a.keyRange&&g.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+n),0);let A=new H(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=e;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue),e++}return QA(A,0),nA(new $("igen",A.length,A))}function Un(t,A,e,s,n){let o=this.samples.map((Q,u)=>{e&&Q.compressSample(s,n);let h=Q.getRawData();return m(`%cEncoded sample %c${u}. ${Q.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),h}),g=this.samples.reduce((Q,u,h)=>Q+o[h].length+46,0),C=new H(g);this.samples.forEach((Q,u)=>{let h=o[u],l,d,y=h.length;Q.isCompressed?(l=C.currentIndex,d=l+h.length):(l=C.currentIndex/2,d=l+h.length/2,y+=46),t.push(l),C.set(h,C.currentIndex),C.currentIndex+=y,A.push(d)});let c=nA(new $("smpl",C.length,C),new H([115,100,116,97]));return nA(new $("LIST",c.length,c))}function Tn(t,A){let s=new H(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{RA(s,n.sampleName,20);let g=t[o];QA(s,g);let C=A[o];QA(s,C);let c=n.sampleLoopStartIndex/2+g,Q=n.sampleLoopEndIndex/2+g;n.isCompressed&&(c-=g,Q-=g),QA(s,c),QA(s,Q),QA(s,n.sampleRate),s[s.currentIndex++]=n.samplePitch,s[s.currentIndex++]=n.samplePitchCorrection,Y(s,n.sampleLink),Y(s,n.sampleType)}),RA(s,"EOS",46),nA(new $("shdr",s.length,s))}function Hn(){let t=10;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),nA(new $("imod",A.length,A))}function Yn(){let t=this.instruments.reduce((o,g)=>g.instrumentZones.length*4+o,4),A=new H(t),e=0,s=0,n=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let g of o.instrumentZones)g.zoneID=e,Y(A,s),Y(A,n),s+=g.generators.length,n+=g.modulators.length,e++}return Y(A,s),Y(A,n),nA(new $("ibag",A.length,A))}function Jn(){let t=this.instruments.length*22+22,A=new H(t),e=0,s=0;for(let n of this.instruments)RA(A,n.instrumentName,20),Y(A,e),e+=n.instrumentZones.length,n.instrumentID=s,s++;return RA(A,"EOI",20),Y(A,e),nA(new $("inst",A.length,A))}function vn(){let t=4;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>(o.generators=o.generators.filter(g=>g.generatorType!==a.instrument&&g.generatorType!==a.keyRange&&g.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+n),0);let A=new H(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=e;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue);e+=n.generators.length}return Y(A,0),Y(A,0),nA(new $("pgen",A.length,A))}function qn(){let t=10;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),nA(new $("pmod",A.length,A))}function Pn(){let t=this.presets.reduce((o,g)=>g.presetZones.length*4+o,4),A=new H(t),e=0,s=0,n=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let g of o.presetZones)g.zoneID=e,Y(A,s),Y(A,n),s+=g.generators.length,n+=g.modulators.length,e++}return Y(A,s),Y(A,n),nA(new $("pbag",A.length,A))}function Kn(){let t=this.presets.length*38+38,A=new H(t),e=0;for(let s of this.presets)RA(A,s.presetName,20),Y(A,s.program),Y(A,s.bank),Y(A,e),QA(A,s.library),QA(A,s.genre),QA(A,s.morphology),e+=s.presetZones.length;return RA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,e),QA(A,0),QA(A,0),QA(A,0),nA(new $("phdr",A.length,A))}var To={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Vn(t=To){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");SA("%cSaving soundfont...",r.info),m(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),m("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[q,T]of Object.entries(this.soundFontInfo))if(q==="ifil"||q==="iver"){let I=parseInt(T.split(".")[0]),AA=parseInt(T.split(".")[1]),P=new H(4);Y(P,I),Y(P,AA),A.push(nA(new $(q,4,P)))}else if(q==="DMOD")A.push(nA(new $(q,T.length,T)));else{let I=new H(T.length);RA(I,T),A.push(nA(new $(q,T.length,I)))}let e=De([new H([73,78,70,79]),...A]),s=nA(new $("LIST",e.length,e));m("%cWriting SDTA...",r.info);let n=[],o=[],g=Un.call(this,n,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let C=Tn.call(this,n,o);m("%cWriting IGEN...",r.info);let c=Ln.call(this);m("%cWriting IMOD...",r.info);let Q=Hn.call(this);m("%cWriting IBAG...",r.info);let u=Yn.call(this);m("%cWriting INST...",r.info);let h=Jn.call(this),l=vn.call(this);m("%cWriting PMOD...",r.info);let d=qn.call(this);m("%cWriting PBAG...",r.info);let y=Pn.call(this);m("%cWriting PHDR...",r.info);let D=Kn.call(this),w=De([new H([112,100,116,97]),D,y,d,l,h,u,Q,c,C]),F=nA(new $("LIST",w.length,w));m("%cWriting the output file...",r.info);let v=De([new H([115,102,98,107]),s,g,F]),M=nA(new $("RIFF",v.length,v));return m(`%cSaved succesfully! Final file size: %c${M.length}`,r.info,r.recognized),X(),M}var ne=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Ze.map(e=>eA.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}getPresetNoFallback(A,e,s=!1){let n=this.presets.find(o=>o.bank===A&&o.program===e);if(n)return n;if(s!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPreset(A,e){let s=this.presets.find(n=>n.bank===A&&n.program===e);return s||(A===128?(s=this.presets.find(n=>n.bank===128&&n.program===e),s||(s=this.presets.find(n=>n.bank===128))):s=this.presets.find(n=>n.program===e&&n.bank!==128),s&&N(`%cPreset ${A}.${e} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,r.warn,r.recognized)),s||(N(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),s=this.presets[0]),s}getPresetByName(A){let e=this.presets.find(s=>s.presetName===A);return e||(N("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}static mergeSoundfonts(...A){let e=A.shift(),s=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{s.find(g=>g.bank===o.bank&&g.program===o.program)===void 0&&s.push(o)});return new t({presets:s,info:e.soundFontInfo})}};ne.prototype.write=Vn;function On(t){SA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let s=A;s{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,e){let s=this.foundSamplesAndGenerators[A][e];if(s)return s;if(this.presetZones.length<1)return[];function n(h,l,d){return d>=h&&d<=l}function o(h,l){h.push(...l.filter(d=>!h.find(y=>y.generatorType===d.generatorType)))}function g(h,l){h.push(...l.filter(d=>!h.find(y=>eA.isIdentical(d,y))))}let C=[],c=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],Q=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(h=>n(h.keyRange.min,h.keyRange.max,A)&&n(h.velRange.min,h.velRange.max,e)&&!h.isGlobal).forEach(h=>{if(h.instrument.instrumentZones.length<1)return;let l=h.generators,d=h.modulators,y=h.instrument.instrumentZones[0].isGlobal?[...h.instrument.instrumentZones[0].generators]:[],D=h.instrument.instrumentZones[0].isGlobal?[...h.instrument.instrumentZones[0].modulators]:[];h.instrument.instrumentZones.filter(F=>n(F.keyRange.min,F.keyRange.max,A)&&n(F.velRange.min,F.velRange.max,e)&&!F.isGlobal).forEach(F=>{let v=[...F.generators],M=[...F.modulators];o(l,c),o(v,y),g(d,Q),g(M,D),g(M,this.defaultModulators);let q=[...M];for(let T=0;TeA.isIdentical(I,P));AA!==-1?q[AA]=q[AA].sumTransform(I):q.push(I)}C.push({instrumentGenerators:v,presetGenerators:l,modulators:q,sample:F.sample,sampleID:F.generators.find(T=>T.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=C,C}};var Re=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var $A=class extends Re{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},ce=class extends Re{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var le=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var At=class extends Qe{constructor(A,e){super(Ze),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new le,this.DLSInstrument.addUseCount();let n=new ce;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function Zn(t){this.verifyHeader(t,"LIST"),this.verifyText(O(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(Z(t.chunkData));let e=A.find(d=>d.header==="insh");if(!e)throw X(),new Error("No instrument header!");let s=S(e.chunkData,4),n=S(e.chunkData,4),o=S(e.chunkData,4),g=new At(n,o),C="unnamedPreset",c=DA(A,"INFO");if(c){let d=Z(c.chunkData);for(;d.header!=="INAM";)d=Z(c.chunkData);C=O(d.chunkData,d.chunkData.length).trim()}g.presetName=C,g.DLSInstrument.instrumentName=C,te(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let Q=DA(A,"lrgn");if(!Q)throw X(),new Error("No region list!");let u=new $A;u.isGlobal=!0;let h=DA(A,"lart"),l=DA(A,"lar2");this.readLart(h,l,u),g.DLSInstrument.instrumentZones.push(u);for(let d=0;d>10&15;F===cA.linear&&w!==cA.linear&&(F=w);let v=s>>14&1,M=s>>15&1;g===a.initialAttenuation&&(M=!M),h=PA(F,v,M,C.isCC,C.enum)}let l=s>>4&15,d=s>>8&1,y=s>>9&1,D=PA(l,d,y,u.isCC,u.enum);if(c){let w=D;D=h,h=w}return new eA({srcEnum:h,secSrcEnum:D,dest:g,transform:0,amt:n})}function Ut(t,A){let e=t.chunkData,s=[],n=[];S(e,4);let o=S(e,4);for(let g=0;g>16;if(C===0&&c===0&&u===0){let d;switch(Q){case G.pan:d=new b(a.pan,l);break;case G.gain:d=new b(a.initialAttenuation,-l*10/.4);break;case G.filterCutoff:d=new b(a.initialFilterFc,l);break;case G.filterQ:d=new b(a.initialFilterQ,l);break;case G.modLfoFreq:d=new b(a.freqModLFO,l);break;case G.modLfoDelay:d=new b(a.delayModLFO,l);break;case G.vibLfoFreq:d=new b(a.freqVibLFO,l);break;case G.vibLfoDelay:d=new b(a.delayVibLFO,l);break;case G.volEnvDelay:d=new b(a.delayVolEnv,l);break;case G.volEnvAttack:d=new b(a.attackVolEnv,l);break;case G.volEnvHold:d=new b(a.holdVolEnv,l);break;case G.volEnvDecay:d=new b(a.decayVolEnv,l);break;case G.volEnvRelease:d=new b(a.releaseVolEnv,l);break;case G.volEnvSustain:let y=(1e3-l)/10;d=new b(a.sustainVolEnv,y*10);break;case G.modEnvDelay:d=new b(a.delayModEnv,l);break;case G.modEnvAttack:d=new b(a.attackModEnv,l);break;case G.modEnvHold:d=new b(a.holdModEnv,l);break;case G.modEnvDecay:d=new b(a.decayModEnv,l);break;case G.modEnvRelease:d=new b(a.releaseModEnv,l);break;case G.modEnvSustain:let D=1e3-l;d=new b(a.sustainModEnv,D);break;case G.reverbSend:d=new b(a.reverbEffectsSend,l);break;case G.chorusSend:d=new b(a.chorusEffectsSend,l);break;case G.pitch:let w=Math.floor(l/100),F=Math.floor(l-w*100);d=new b(a.fineTune,F),s.push(new b(a.coarseTune,w));break}d&&s.push(d)}else{let d=!0;if(c===_.none)if(C===_.modLfo&&Q===G.pitch)s.push(new b(a.modLfoToPitch,l));else if(C===_.modLfo&&Q===G.gain)s.push(new b(a.modLfoToVolume,l));else if(C===_.modLfo&&Q===G.filterCutoff)s.push(new b(a.modLfoToFilterFc,l));else if(C===_.vibratoLfo&&Q===G.pitch)s.push(new b(a.vibLfoToPitch,l));else if(C===_.modEnv&&Q===G.pitch)s.push(new b(a.modEnvToPitch,l));else if(C===_.modEnv&&Q===G.filterCutoff)s.push(new b(a.modEnvToFilterFc,l));else if(C===_.keyNum&&Q===G.volEnvHold){s.push(new b(a.keyNumToVolEnvHold,l/-128));let y=Math.round(60/128*l);s.forEach(D=>{D.generatorType===a.holdVolEnv&&(D.generatorValue+=y)})}else if(C===_.keyNum&&Q===G.volEnvDecay){s.push(new b(a.keyNumToVolEnvDecay,l/-128));let y=Math.round(60/128*l);s.forEach(D=>{D.generatorType===a.decayVolEnv&&(D.generatorValue+=y)})}else if(C===_.keyNum&&Q===G.modEnvHold){s.push(new b(a.keyNumToModEnvHold,l/-128));let y=Math.round(60/128*l);s.forEach(D=>{D.generatorType===a.holdModEnv&&(D.generatorValue+=y)})}else if(C===_.keyNum&&Q===G.modEnvDecay){s.push(new b(a.keyNumToModEnvDecay,l/-128));let y=Math.round(60/128*l);s.forEach(D=>{D.generatorType===a.decayModEnv&&(D.generatorValue+=y)})}else d=!1;else d=!1;if(d===!1){let y=Wn(C,c,Q,u,l);y?(n.push(y),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):N("Failed converting to SF2 Modulator!")}}}return n.find(g=>g.modulatorDestination===a.reverbEffectsSend)===void 0&&n.push(new eA({srcEnum:219,dest:a.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(g=>g.modulatorDestination===a.chorusEffectsSend)===void 0&&n.push(new eA({srcEnum:221,dest:a.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&n.push(new eA({srcEnum:129,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new eA({srcEnum:13,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:n,generators:s}}function _n(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(Z(t.chunkData));let e=A.find(AA=>AA.header==="rgnh"),s=S(e.chunkData,2),n=S(e.chunkData,2),o=S(e.chunkData,2),g=S(e.chunkData,2),C=new et({min:s,max:n},{min:o,max:g});S(e.chunkData,2);let c=S(e.chunkData,2);c!==0&&C.generators.push(new b(a.exclusiveClass,c));let Q=DA(A,"lart"),u=DA(A,"lar2");this.readLart(Q,u,C),C.isGlobal=!1;let h=A.find(AA=>AA.header==="wsmp");S(h.chunkData,4);let l=S(h.chunkData,2),d=jA(h.chunkData[h.chunkData.currentIndex++],h.chunkData[h.chunkData.currentIndex++]),w=(S(h.chunkData,4)|0)/-655360*10/.4;S(h.chunkData,4);let F=S(h.chunkData,4),v,M={start:0,end:0};if(F===0)v=0;else{S(h.chunkData,4),S(h.chunkData,4)===0?v=1:v=3,M.start=S(h.chunkData,4);let P=S(h.chunkData,4);M.end=M.start+P}let q=A.find(AA=>AA.header==="wlnk");if(q===void 0)return;S(q.chunkData,2),S(q.chunkData,2),S(q.chunkData,4);let T=S(q.chunkData,4),I=this.samples[T];if(I===void 0)throw new Error("Invalid sample ID!");return C.setWavesample(w,v,M,l,I,T,d),C}var ue=class{constructor(A,e,s,n,o,g,C,c){this.sampleName=A,this.sampleRate=e,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=g,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=c,this.isCompressed=(g&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,e){if(!this.isCompressed)try{this.compressedData=e([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{N(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}};var tt=class extends ue{constructor(A,e,s,n,o,g,C){super(A,e,s,n,0,1,o*2,(g-1)*2),this.sampleData=C}getAudioData(){return this.sampleData}sampleData;getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let e=0;e>8&255}return A}};function jn(t){SA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexP.header==="fmt ");if(!n)throw new Error("No fmt chunk in the wave file!");if(S(n.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(S(n.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=S(n.chunkData,4);S(n.chunkData,4),S(n.chunkData,2);let c=S(n.chunkData,2),Q=c/8,u=Math.pow(2,Q*8-1),h=Math.pow(2,Q*8),l,d=!1;c===8?(l=255,d=!0):l=u;let y=s.find(P=>P.header==="data");if(!y)throw new Error("No data chunk in the wave chunk!");let D=y.size/Q,w=new Float32Array(D);for(let P=0;P=u&&(j-=h),w[P]=j/l)}let F=60,v=0,M=0,q=w.length-1,T=s.find(P=>P.header==="wsmp");if(T){if(S(T.chunkData,4),F=S(T.chunkData,2),v=jA(T.chunkData[T.chunkData.currentIndex++],T.chunkData[T.chunkData.currentIndex++]),S(T.chunkData,4),S(T.chunkData,4),S(T.chunkData,4)===1){S(T.chunkData,8),M=S(T.chunkData,4);let j=S(T.chunkData,4);q=M+j}}else N("No wsmp chunk in wave... using sane defaults.");let I=DA(s,"INFO"),AA=`Unnamed ${A}`;if(I){let P=Z(I.chunkData);for(;P.header!=="INAM"&&I.chunkData.currentIndex(F.messageStatusByte&240)===k.noteOn);w&&d.push(w.ticks)}this.firstNoteOn=Math.min(...d),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),u!==null&&Q===null?(u=this.firstNoteOn,Q=this.lastVoiceEventTick):(u===null&&(u=this.firstNoteOn),(Q===null||Q===0)&&(Q=this.lastVoiceEventTick)),this.loop={start:u,end:Q},m(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let S=0;for(let D of this.midiPorts)if(D!==-1){S=D;break}if(this.midiPorts=this.midiPorts.map(D=>D===-1?S:D),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?m("%cNo additional MIDI Ports detected.",r.info):m("%cMIDI Ports detected!",r.recognized),!I)if(this.tracks.length>1){if(this.tracks[0].find(D=>D.messageStatusByte>=k.noteOn&&D.messageStatusBytew.messageStatusByte===k.trackName);D&&(this.rawMidiName=D.messageData,this.midiName=O(D.messageData,D.messageData.length,void 0,!1))}}else{let D=this.tracks[0].find(w=>w.messageStatusByte===k.trackName);D&&(this.rawMidiName=D.messageData,this.midiName=O(D.messageData,D.messageData.length,void 0,!1))}if(this.fileName=e,this.midiName=this.midiName.trim(),this.midiName.length===0){m("%cNo name detected. Using the alt name!",r.info),this.midiName=gn(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let D=0;Dl>Q?l:Q),n=[];for(let Q=0;Q{I[S]>=d.length||d[I[S]].ticks0;){let Q=c(),l=t.tracks[Q];if(I[Q]>=l.length){C--;continue}let d=l[I[Q]];if(I[Q]++,d.messageStatusByte===k.midiPort){h[Q]=d.messageData[0];continue}let S=d.messageStatusByte&240;if(S!==k.noteOn&&S!==k.controllerChange&&S!==k.programChange&&S!==k.systemExclusive)continue;let D=(d.messageStatusByte&15)+t.midiPortChannelOffsets[h[Q]]||0,w=n[D];switch(S){case k.programChange:w.program=d.messageData[0],s(w);break;case k.controllerChange:if(d.messageData[0]!==p.bankSelect||u==="gs"&&w.drums)continue;let F=d.messageData[1],v=Math.max(0,F-t.bankOffset);if(u==="xg"){let T=F===120||F===126||F===127;T!==w.drums?(w.drums=T,w.bank=w.drums?128:v,s(w)):w.bank=w.drums?128:v;continue}n[D].bank=v;break;case k.noteOn:if(d.messageData[1]===0)continue;s(w),o[w.string].add(`${d.messageData[0]}-${d.messageData[1]}`);break;case k.systemExclusive:if(d.messageData[0]!==65||d.messageData[2]!==66||d.messageData[3]!==18||d.messageData[4]!==64||!(d.messageData[5]&16)||d.messageData[6]!==21){d.messageData[0]===67&&d.messageData[2]===76&&d.messageData[5]===126&&d.messageData[6]===0&&(u="xg");continue}let M=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][d.messageData[5]&15]+t.midiPortChannelOffsets[h[Q]],q=!!(d.messageData[7]>0&&d.messageData[5]>>4);w=n[M],w.drums=q,w.bank=q?128:0,s(w);break}}for(let Q of Object.keys(o))o[Q].size===0&&(m(`%cDetected change but no keys for %c${Q}`,r.info,r.value),delete o[Q]);return X(),o}function Rn(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(e,A)}),this.duration=this.midiData.duration,this.firstNoteTime=Ce(this.midiData.firstNoteOn,this.midiData),m(`%cTotal song time: ${ft(Math.ceil(this.duration)).time}`,r.recognized),this.post(FA.songChange,[new Ve(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(b(`%cVery short song: (${ft(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function xn(t){this.songs=t.reduce((A,e)=>{if(e.duration)return A.push(e),A;try{A.push(new ze(e.binary,e.altName||""))}catch(n){return this.post(FA.midiError,n.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function Mn(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Nn(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}var KA=new Int16Array(127);KA[p.mainVolume]=100;KA[p.expressionController]=127;KA[p.pan]=64;KA[p.releaseTime]=64;KA[p.brightness]=64;KA[p.effects1Depth]=0;function bn(t,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let e=this.synth.workletProcessorChannels.length,n=Array(e).fill(8192),s=[];for(let C=0;CC===p.dataDecrement||C===p.dataIncrement||C===p.dataEntryMsb||C===p.dataDecrement||C===p.lsbForControl6DataEntry||C===p.RPNLsb||C===p.RPNMsb||C===p.NRPNLsb||C===p.NRPNMsb||C===p.bankSelect||C===p.lsbForControl0BankSelect||C===p.resetAllControllers,I=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let h=ke(c.messageStatusByte),u=h.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(h.status){case k.noteOn:case k.noteOff:case k.keySignature:break;case k.pitchBend:n[u]=c.messageData[1]<<7|c.messageData[0];break;case k.programChange:let l=s[u];l.program=c.messageData[0],l.actualBank=l.bank;break;case k.controllerChange:let d=c.messageData[0];if(o(d)){let S=c.messageData[1];if(d===p.bankSelect){s[u].bank=S;break}this.sendMIDIMessages?this.sendMIDICC(u,d,S):this.synth.controllerChange(u,d,S)}else I[u]===void 0&&(I[u]=Array.from(KA)),I[u][d]=c.messageData[1];break;default:this._processEvent(c,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let Q=this.tracks[C][this.eventIndex[C]];if(Q===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(Q.ticks-c.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7,n[C]&127),I[C]!==void 0&&I[C].forEach((c,h)=>{c!==KA[h]&&!o(h)&&this.sendMIDICC(C,h,c)}),s[C].program>=0&&s[C].actualBank>=0){let c=s[C].actualBank;this.sendMIDICC(C,p.bankSelect,c),this.sendMIDIProgramChange(C,s[C].program)}}else for(let C=0;C>7,n[C]&127),I[C]!==void 0&&I[C].forEach((c,h)=>{c!==KA[h]&&!o(h)&&this.synth.controllerChange(C,h,c)}),s[C].program>=0&&s[C].actualBank>=0){let c=s[C].actualBank;this.synth.controllerChange(C,p.bankSelect,c),this.synth.programChange(C,s[C].program)}return!0}function Ln(t=!1){if(this.midiData!==void 0){if(t){this.currentTime=0;return}if(this.currentTime>=this.duration){this.currentTime=0;return}this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),this.sendMIDIMessages||this.playingNotes.forEach(A=>{this.synth.noteOn(A.channel,A.midiNote,A.velocity,!1,!0)}),this.setProcessHandler()}}function Un(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(FA.timeChange,currentTime-Ce(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Tn(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function Hn(t,A){switch(t){default:break;case UA.loadNewSongList:this.loadNewSongList(A);break;case UA.pause:this.pause();break;case UA.play:this.play(A);break;case UA.stop:this.stop();break;case UA.setTime:this.currentTime=A;break;case UA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case UA.setPlaybackRate:this.playbackRate=A;break;case UA.setLoop:this.loop=A;break;case UA.changeSong:A?this.nextSong():this.previousSong();break;case UA.getMIDI:this.post(FA.getMIDI,this.midiData);break;case UA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Yn(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:pA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Jn(t){this.post(FA.midiEvent,t)}function vn(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([k.controllerChange|t,A,e])}function qn(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([k.programChange|t,A])}function Pn(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([k.pitchBend|t,e,A])}function Kn(){if(this.sendMIDIMessages){this.sendMIDIMessage([k.reset]);for(let t=0;tthis.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&AVn?440*Math.pow(2,(t-6900)/1200):Ft[~~t-je]}var Gt=-1660,Mo=1600,Rt=new Float32Array((Mo-Gt)*100+1);for(let t=0;t.5?1:0,n?e*2-1:e;case cA.concave:return n?(e=e*2-1,e<0?1-Ee[~~(e*-gA)]-1:Ee[~~e*gA]):Ee[~~(e*gA)];case cA.convex:return n?(e=e*2-1,e<0?1-Be[~~(e*-gA)]-1:Be[~~(e*gA)]):Be[~~(e*gA)]}}var xt=1,Mt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)n-=o;let C=~~n,c=C+1;for(;c>=e.loopEnd;)c-=o;let h=n-C,u=s[c],Q=s[C];A[I]=Q+(u-Q)*h,n+=e.playbackStep*t.currentTuningCalculated}}else{e.end>=s.length&&(e.end=s.length-1);for(let o=0;o=e.end){t.finished=!0;return}let c=n-I,h=s[C],u=s[I];A[o]=u+(h-u)*c,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function Zn(t,A){let e=t.sample,n=e.cursor,s=e.loopEnd-e.loopStart,o=e.sampleData;if(t.sample.isLooping)for(let I=0;I=e.loopEnd;)n-=s;let C=~~n+1;for(;C>=e.loopEnd;)C-=s;A[I]=o[C],n+=e.playbackStep*t.currentTuningCalculated}else{e.end>=o.length&&(e.end=o.length-1);for(let I=0;I=e.end){t.finished=!0;return}A[I]=o[C],n+=e.playbackStep*t.currentTuningCalculated}}e.cursor=n}function Xn(t,A,e,n,s,o,I,C,c){if(!isNaN(e[0])){if(I>0){let h=o[0],u=o[1];I=Math.min(I,1e3);let Q=I/1300,l=t*Q,d=A*Q;for(let S=0;S0){let h=C[0],u=C[1];c=Math.min(c,1e3);let Q=c/1300,l=t*Q,d=A*Q;for(let S=0;S0)for(let h=0;h0)for(let h=0;h13499&&A.filter.reasonanceCb===0)return;let s=A.filter;(s.cutoffCents!==n||s.reasonanceCb!==A.modulatedGenerators[a.initialFilterQ])&&(s.cutoffCents=n,s.reasonanceCb=A.modulatedGenerators[a.initialFilterQ],t.calculateCoefficients(A));for(let o=0;o.45*sampleRate&&(e.cutoffHz=.45*sampleRate);let n=e.reasonanceCb/10-3.01;e.reasonanceGain=YA(-1*n);let s=1/Math.sqrt(e.reasonanceGain),o=2*Math.PI*e.cutoffHz/sampleRate,I=Math.cos(o),C=Math.sin(o)/(2*e.reasonanceGain),c=(1-I)*s,h=c/2,u=h,Q=1+C,l=-2*I,d=1-C;e.a0=h/Q,e.a1=c/Q,e.a2=u/Q,e.a3=l/Q,e.a4=d/Q}};var Wn=.001,kA=100,Nt=90,No=.005,GA=class t{constructor(A,e){this.sampleRate=A,this.canEndOnSilentSustain=e/10>=Nt}currentSampleTime=0;sampleRate;currentAttenuationDb=kA;state=0;releaseStartDb=kA;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=YA(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static intialize(A){t.recalculate(A,!0),A.volumeEnvelope.attenuation=A.volumeEnvelope.attenuationTarget}static recalculate(A,e=!1){let n=A.volumeEnvelope,s=u=>Math.max(0,Math.floor(HA(u)*n.sampleRate));n.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[a.initialAttenuation],1440))/10,n.sustainDbRelative=Math.min(kA,A.modulatedGenerators[a.sustainVolEnv]/10),e&&(n.attenuation=n.attenuationTarget);let o=Math.min(kA,n.sustainDbRelative+n.attenuation);n.attackDuration=s(A.modulatedGenerators[a.attackVolEnv]);let I=A.modulatedGenerators[a.decayVolEnv],C=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvDecay],c=(o-n.attenuation)/kA;n.decayDuration=s(I+C)*c,n.releaseDuration=s(A.modulatedGenerators[a.releaseVolEnv]),n.delayEnd=s(A.modulatedGenerators[a.delayVolEnv]),n.attackEnd=n.attackDuration+n.delayEnd;let h=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvHold];if(n.holdEnd=s(A.modulatedGenerators[a.holdVolEnv]+h)+n.attackEnd,n.decayEnd=n.decayDuration+n.holdEnd,n.state===0&&n.attackEnd===0&&(n.currentAttenuationDb=n.attenuationTarget,n.state=2),A.isInRelease){n.attenuation=Math.min(kA,n.attenuationTarget);let u=Math.max(0,Math.min(kA,n.sustainDbRelative+n.attenuation)),Q=(u-n.attenuation)/kA;switch(n.decayDuration=s(I+C)*Q,n.state){case 0:n.releaseStartDb=kA;break;case 1:let d=(1-(n.attackEnd-n.releaseStartTimeSamples)/n.attackDuration)*YA(n.attenuation);n.releaseStartDb=20*Math.log10(d)*-1;break;case 2:n.releaseStartDb=n.attenuation;break;case 3:n.releaseStartDb=(1-(n.decayEnd-n.releaseStartTimeSamples)/n.decayDuration)*(u-n.attenuation)+n.attenuation;break;case 4:n.releaseStartDb=u;break;default:n.releaseStartDb=n.currentAttenuationDb}n.releaseStartDb=Math.max(0,Math.min(n.releaseStartDb,kA)),n.releaseStartDb>=Nt&&(A.finished=!0),n.currentReleaseGain=YA(n.releaseStartDb)}}static apply(A,e,n,s){let o=A.volumeEnvelope,I=n/10,C=s;if(A.isInRelease){let h=s*10,u=o.currentSampleTime-o.releaseStartTimeSamples;if(u>=o.releaseDuration){for(let l=0;l=e.length)return;o.state++;case 1:let h;for(;o.currentSampleTime=e.length)return;o.state++;case 2:for(;o.currentSampleTime=e.length)return;o.state++;case 3:for(;o.currentSampleTime=e.length)return}o.state++;case 4:for(o.canEndOnSilentSustain&&o.sustainDbRelative>=Nt&&(A.finished=!0);;){o.attenuation+=(o.attenuationTarget-o.attenuation)*C;let u=Math.min(kA,o.sustainDbRelative+o.attenuation);if(e[c]*=YA(u+I),o.currentAttenuationDb=u,o.currentSampleTime++,++c>=e.length)return}}}};var _n=Math.PI/2,zn=.01;function jn(t,A,e,n,s,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,GA.startRelease(A),JA.startRelease(A)),A.modulatedGenerators[a.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let I=A.targetKey,C=A.modulatedGenerators[a.fineTune]+t.customControllers[IA.channelTuning]+t.customControllers[IA.channelTransposeFine]+t.customControllers[IA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],c=A.modulatedGenerators[a.coarseTune]+t.customControllers[IA.channelTuningSemitones],h=this.tunings[t.preset.program]?.[I];h?.midiNote>=0&&(I=h.midiNote,C+=h.centTuning),C+=(I-A.sample.rootKey)*A.modulatedGenerators[a.scaleTuning];let u=A.modulatedGenerators[a.vibLfoToPitch];if(u!==0){let z=A.startTime+HA(A.modulatedGenerators[a.delayVibLFO]),CA=we(A.modulatedGenerators[a.freqVibLFO]),oA=$e(z,CA,currentTime);C+=oA*(u*t.customControllers[IA.modulationMultiplier])}let Q=A.modulatedGenerators[a.initialFilterFc],l=A.modulatedGenerators[a.modLfoToPitch],d=A.modulatedGenerators[a.modLfoToVolume],S=A.modulatedGenerators[a.modLfoToFilterFc],D=0;if(l+S+d!==0){let z=A.startTime+HA(A.modulatedGenerators[a.delayModLFO]),CA=we(A.modulatedGenerators[a.freqModLFO]),oA=$e(z,CA,currentTime);C+=oA*(l*t.customControllers[IA.modulationMultiplier]),D=-oA*d,Q+=oA*S}if(t.channelVibrato.depth>0){let z=$e(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);z&&(C+=z*t.channelVibrato.depth)}let w=A.modulatedGenerators[a.modEnvToPitch],F=A.modulatedGenerators[a.modEnvToFilterFc],v=JA.getValue(A,currentTime);Q+=v*F,C+=v*w;let M=~~(C+c*100);M!==A.currentTuningCents&&(A.currentTuningCents=M,A.currentTuningCalculated=Math.pow(2,M/1200));let q=(Math.max(-500,Math.min(500,A.modulatedGenerators[a.pan]))+500)/1e3,T=new Float32Array(e.length);switch(this.interpolationType){case Fe.linear:default:On(A,T);break;case Fe.nearestNeighbor:Zn(A,T);break}he.apply(A,T,Q),GA.apply(A,T,D,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(q-A.currentPan)*this.panSmoothingFactor;let g=Math.cos(_n*A.currentPan)*this.panLeft,AA=Math.sin(_n*A.currentPan)*this.panRight,P=this.oneOutputMode?0:A.modulatedGenerators[a.reverbEffectsSend],j=this.oneOutputMode?0:A.modulatedGenerators[a.chorusEffectsSend];Xn(g,AA,T,e,n,s,P,o,j)}function bo(t,A){let e=0;return t.drumChannel&&(e+=5),A.isInRelease&&(e-=5),e+=A.velocity/25,e-=A.volumeEnvelope.state,A.isInRelease&&(e-=5),e-=A.volumeEnvelope.currentAttenuationDb/50,e}function $n(t){let A=[];for(let n of this.workletProcessorChannels)for(let s of n.voices)if(!s.finished){let o=bo(n,s);A.push({channel:n,voice:s,priority:o})}A.sort((n,s)=>n.priority-s.priority);let e=A.slice(0,t);for(let{channel:n,voice:s}of e){let o=n.voices.indexOf(s);o>-1&&n.voices.splice(o,1)}}function As(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimets=t);var Lo=function(t){var A,e,n,s,o,I,C,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",u=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do s=c.indexOf(t.charAt(u++)),o=c.indexOf(t.charAt(u++)),I=c.indexOf(t.charAt(u++)),C=c.indexOf(t.charAt(u++)),A=s<<2|o>>4,e=(15&o)<<4|I>>2,n=(3&I)<<6|C,h+=String.fromCharCode(A),I!==64&&(h+=String.fromCharCode(e)),C!==64&&(h+=String.fromCharCode(n));while(u1&&(g.thisProgram=process.argv[1].replace(/\\/g,"/")),g.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(i){if(!(i instanceof pe))throw i}),process.on("unhandledRejection",function(i,E){process.exit(1)}),g.quit=function(i){process.exit(i)},g.inspect=function(){return"[Emscripten Module object]"}):CA?(typeof read<"u"&&(g.read=function(E){return read(E)}),g.readBinary=function(E){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(B=read(E,"binary"))=="object"),B)},typeof scriptArgs<"u"?g.arguments=scriptArgs:typeof arguments<"u"&&(g.arguments=arguments),typeof quit=="function"&&(g.quit=function(i){quit(i)})):(P||j)&&(P?document.currentScript&&(oA=document.currentScript.src):oA=self.location.href,oA=oA.indexOf("blob:")!==0?oA.split("/").slice(0,-1).join("/")+"/":"",g.read=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.send(null),B.responseText},j&&(g.readBinary=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.responseType="arraybuffer",B.send(null),new Uint8Array(B.response)}),g.readAsync=function(E,B,f){var R=new XMLHttpRequest;R.open("GET",E,!0),R.responseType="arraybuffer",R.onload=function(){if(R.status==200||R.status==0&&R.response){B(R.response);return}f()},R.onerror=f,R.send(null)},g.setWindowTitle=function(i){document.title=i});var Me=g.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),xA=g.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Me);for(t in AA)AA.hasOwnProperty(t)&&(g[t]=AA[t]);function Ne(i){var E=d;return d=d+i+15&-16,E}function qt(i){var E=c[M>>2],B=E+i+15&-16;return c[M>>2]=B,B>=BA&&!jt()?(c[M>>2]=E,0):E}function Pt(i,E){return E||(E=16),i=Math.ceil(i/E)*E}function Qo(i){switch(i){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(i[i.length-1]==="*")return 4;if(i[0]!=="i")return 0;var E=parseInt(i.substr(1));return _A(E%8==0),E/8}}function de(i){de.shown||(de.shown={}),de.shown[i]||(de.shown[i]=1,xA(i))}AA=void 0;var co={"f64-rem":function(i,E){return i%E},debugger:function(){}},rt=[];function vo(i,E){for(var B=0,f=B;f>>0)+4294967296*+(E>>>0):+(i>>>0)+4294967296*+(0|E)}function at(i,E,B){return B&&B.length?g["dynCall_"+i].apply(null,[E].concat(B)):g["dynCall_"+i].call(null,E)}var be=0,Kt=0;function _A(i,E){i||OA("Assertion failed: "+E)}function Vt(i){var E=g["_"+i];return _A(E,"Cannot call unknown function "+i+", make sure it is exported"),E}var Ot={stackSave:function(){ct()},stackRestore:function(){Qt()},arrayToC:function(i){var E,B,f=Je(i.length);return E=i,B=f,s.set(E,B),f},stringToC:function(i){var E=0;if(i!=null&&i!==0){var B=(i.length<<2)+1;E=Je(B),Wt(i,E,B)}return E}},lo={string:Ot.stringToC,array:Ot.arrayToC};function Zt(i,E,B,f,R){var K=Vt(i),W=[],x=0;if(f)for(var hA=0;hA>0]=E;break;case"i16":I[i>>1]=E;break;case"i32":c[i>>2]=E;break;case"i64":tempI64=[E>>>0,+yo(tempDouble=E)>=1?tempDouble>0?(0|ko(+nn(tempDouble/4294967296),4294967295))>>>0:~~+Do((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],c[i>>2]=tempI64[0],c[i+4>>2]=tempI64[1];break;case"float":u[i>>2]=E;break;case"double":Q[i>>3]=E;break;default:OA("invalid type for setValue: "+B)}}function Vo(i,E,B){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return s[i>>0];case"i16":return I[i>>1];case"i32":case"i64":return c[i>>2];case"float":return u[i>>2];case"double":return Q[i>>3];default:OA("invalid type for getValue: "+E)}return null}function Oo(i,E,B,f){typeof i=="number"?(K=!0,W=i):(K=!1,W=i.length);var R=typeof E=="string"?E:null;if(x=B==4?f:[typeof Ye=="function"?Ye:Ne,Je,Ne,qt][B===void 0?2:B](Math.max(W,R?1:E.length)),K){for(f=x,_A((3&x)==0),hA=x+(-4&W);f>2]=0;for(hA=x+W;f>0]=0;return x}if(R==="i8")return i.subarray||i.slice?o.set(i,x):o.set(new Uint8Array(i),x),x;for(var K,W,x,hA,rA,iA,nA,J=0;J>0],(f!=0||E)&&(W++,!E||W!=E););E||(E=W);var x="";if(K<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(i,i+Math.min(E,1024))),x=x?x+R:R,i+=1024,E-=1024;return x}return B=i,function(rA,iA){for(var nA=iA;rA[nA];)++nA;if(nA-iA>16&&rA.subarray&&Xt)return Xt.decode(rA.subarray(iA,nA));for(var J,mA,MA,NA,bA,ee,LA="";;){if(!(J=rA[iA++]))return LA;if(!(128&J)){LA+=String.fromCharCode(J);continue}if(mA=63&rA[iA++],(224&J)==192){LA+=String.fromCharCode((31&J)<<6|mA);continue}if(MA=63&rA[iA++],(240&J)==224?J=(15&J)<<12|mA<<6|MA:(NA=63&rA[iA++],(248&J)==240?J=(7&J)<<18|mA<<12|MA<<6|NA:(bA=63&rA[iA++],J=(252&J)==248?(3&J)<<24|mA<<18|MA<<12|NA<<6|bA:(1&J)<<30|mA<<24|MA<<18|NA<<12|bA<<6|(ee=63&rA[iA++]))),J<65536)LA+=String.fromCharCode(J);else{var Se=J-65536;LA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(o,B)}function Xo(i){for(var E="";;){var B=s[i++>>0];if(!B)return E;E+=String.fromCharCode(B)}}function Wo(i,E){return function(f,R,K){for(var W=0;W>0]=f.charCodeAt(W);K||(s[R>>0]=0)}(i,E,!1)}var Xt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ue(i,E,B,f){if(!(f>0))return 0;for(var R=B,K=B+f-1,W=0;W=55296&&x<=57343&&(x=65536+((1023&x)<<10)|1023&i.charCodeAt(++W)),x<=127){if(B>=K)break;E[B++]=x}else if(x<=2047){if(B+1>=K)break;E[B++]=192|x>>6,E[B++]=128|63&x}else if(x<=65535){if(B+2>=K)break;E[B++]=224|x>>12,E[B++]=128|x>>6&63,E[B++]=128|63&x}else if(x<=2097151){if(B+3>=K)break;E[B++]=240|x>>18,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}else if(x<=67108863){if(B+4>=K)break;E[B++]=248|x>>24,E[B++]=128|x>>18&63,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}else{if(B+5>=K)break;E[B++]=252|x>>30,E[B++]=128|x>>24&63,E[B++]=128|x>>18&63,E[B++]=128|x>>12&63,E[B++]=128|x>>6&63,E[B++]=128|63&x}}return E[B]=0,B-R}function Wt(i,E,B){return Ue(i,o,E,B)}function Te(i){for(var E=0,B=0;B=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&i.charCodeAt(++B)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var _t=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function _o(i){for(var E=i,B=E>>1;I[B];)++B;if((E=B<<1)-i>32&&_t)return _t.decode(o.subarray(i,E));for(var f=0,R="";;){var K=I[i+2*f>>1];if(K==0)return R;++f,R+=String.fromCharCode(K)}}function zo(i,E,B){if(B===void 0&&(B=2147483647),B<2)return 0;for(var f=E,R=(B-=2)<2*i.length?B/2:i.length,K=0;K>1]=W,E+=2}return I[E>>1]=0,E-f}function jo(i){return 2*i.length}function $o(i){for(var E=0,B="";;){var f=c[i+4*E>>2];if(f==0)return B;if(++E,f>=65536){var R=f-65536;B+=String.fromCharCode(55296|R>>10,56320|1023&R)}else B+=String.fromCharCode(f)}}function Ar(i,E,B){if(B===void 0&&(B=2147483647),B<4)return 0;for(var f=E,R=f+B-4,K=0;K=55296&&W<=57343&&(W=65536+((1023&W)<<10)|1023&i.charCodeAt(++K)),c[E>>2]=W,(E+=4)+4>R)break}return c[E>>2]=0,E-f}function er(i){for(var E=0,B=0;B=55296&&f<=57343&&++B,E+=4}return E}function tr(i){var E=Te(i)+1,B=Ye(E);return B&&Ue(i,s,B,E),B}function nr(i){var E=Te(i)+1,B=Je(E);return Ue(i,s,B,E),B}function sr(i){return i}function or(){var i,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(R){f=R}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return g.extraStackTrace&&(E+=` +`+g.extraStackTrace()),(i=E).replace(/__Z[\w\d_]+/g,function(B){var f,R=f=B;return B===R?B:B+" ["+R+"]"})}function It(i,E){return i%E>0&&(i+=E-i%E),i}function zt(i){g.buffer=n=i}function gt(){g.HEAP8=s=new Int8Array(n),g.HEAP16=I=new Int16Array(n),g.HEAP32=c=new Int32Array(n),g.HEAPU8=o=new Uint8Array(n),g.HEAPU16=C=new Uint16Array(n),g.HEAPU32=h=new Uint32Array(n),g.HEAPF32=u=new Float32Array(n),g.HEAPF64=Q=new Float64Array(n)}function jt(){var i=g.usingWasm?65536:16777216,E=2147483648-i;if(c[M>>2]>E)return!1;var B=BA;for(BA=Math.max(BA,16777216);BA>2];)BA=BA<=536870912?It(2*BA,i):Math.min(It((3*BA+2147483648)/4,i),E);var f=g.reallocBuffer(BA);return f&&f.byteLength==BA?(zt(f),gt(),!0):(BA=B,!1)}l=d=D=w=F=v=M=0,S=!1,g.reallocBuffer||(g.reallocBuffer=function(i){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(n,i);else{var E,B=s;E=new ArrayBuffer(i),new Int8Array(E).set(B)}}catch{return!1}return!!wo(E)&&E});try{(q=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{q=function(E){return E.byteLength}}var Ct=g.TOTAL_STACK||5242880,BA=g.TOTAL_MEMORY||16777216;function fo(){return BA}function fe(i){for(;i.length>0;){var E=i.shift();if(typeof E=="function"){E();continue}var B=E.func;typeof B=="number"?E.arg===void 0?g.dynCall_v(B):g.dynCall_vi(B,E.arg):B(E.arg===void 0?null:E.arg)}}BA=0?i:E<=32?2*Math.abs(1<=f&&(E<=32||i>f)&&(i=-2*f+i),i}var yo=Math.abs,Do=Math.ceil,nn=Math.floor,ko=Math.min,Ae=0,ht=null,me=null;function Er(i){return i}g.preloadedImages={},g.preloadedAudios={};var sn="data:application/octet-stream;base64,";function He(i){return String.prototype.startsWith?i.startsWith(sn):i.indexOf(sn)===0}(function(){var E="main.wast",B="main.wasm",f="main.temp.asm.js";He(E)||(E=fA(E)),He(B)||(B=fA(B)),He(f)||(f=fA(f));var R={global:null,env:null,asm2wasm:co,parent:g},K=null;function W(nA){return nA}function x(){try{if(g.wasmBinary)return new Uint8Array(g.wasmBinary);if(g.readBinary)return g.readBinary(B);throw"both async and sync fetching of the wasm failed"}catch(nA){OA(nA)}}g.asmPreload=g.asm;var hA=g.reallocBuffer,rA=function(nA){nA=It(nA,g.usingWasm?65536:16777216);var J=g.buffer.byteLength;if(g.usingWasm)try{var mA=g.wasmMemory.grow((nA-J)/65536);return mA!==-1?g.buffer=g.wasmMemory.buffer:null}catch{return null}};g.reallocBuffer=function(nA){return iA==="asmjs"?hA(nA):rA(nA)};var iA="";g.asm=function(nA,J,mA){var MA;if(!(J=MA=J).table){var NA,bA=g.wasmTableSize;bA===void 0&&(bA=1024);var ee=g.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?ee!==void 0?J.table=new WebAssembly.Table({initial:bA,maximum:ee,element:"anyfunc"}):J.table=new WebAssembly.Table({initial:bA,element:"anyfunc"}):J.table=Array(bA),g.wasmTable=J.table}return J.memoryBase||(J.memoryBase=g.STATIC_BASE),J.tableBase||(J.tableBase=0),NA=function(Se,oe,ut){if(typeof WebAssembly!="object")return xA("no native wasm support detected"),!1;if(!(g.wasmMemory instanceof WebAssembly.Memory))return xA("no native wasm Memory in use"),!1;function ve(vA,qA){if((K=vA.exports).memory){var ye,dt,an;ye=K.memory,dt=g.buffer,ye.byteLength0?B:Te(i)+1,R=Array(f),K=Ue(i,R,0,R.length);return E&&(R.length=K),R}function cr(i){for(var E=[],B=0;B255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}d+=16,M=Ne(4),F=(D=w=Pt(d))+Ct,v=Pt(F),c[M>>2]=v,S=!0,g.wasmTableSize=4,g.wasmMaxTableSize=4,g.asmGlobalArg={},g.asmLibraryArg={abort:OA,assert:_A,enlargeMemory:jt,getTotalMemory:fo,abortOnCannotGrowMemory:function(){OA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+BA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(E,B,f){var R=ct();try{return g.dynCall_iii(E,B,f)}catch(K){if(Qt(R),typeof K!="number"&&K!=="longjmp")throw K;g.setThrew(1,0)}},___assert_fail:function(E,B,f,R){OA("Assertion failed: "+Le(E)+", at: "+[B?Le(B):"unknown filename",f,R?Le(R):"unknown function"])},___setErrNo:function(E){return g.___errno_location&&(c[g.___errno_location()>>2]=E),E},_abort:function(){g.abort()},_emscripten_memcpy_big:function(E,B,f){return o.set(o.subarray(B,B+f),E),E},_llvm_floor_f64:nn,DYNAMICTOP_PTR:M,tempDoublePtr:wA,ABORT:be,STACKTOP:w,STACK_MAX:F};var on=g.asm(g.asmGlobalArg,g.asmLibraryArg,n);g.asm=on,g.___errno_location=function(){return g.asm.___errno_location.apply(null,arguments)};var wo=g._emscripten_replace_memory=function(){return g.asm._emscripten_replace_memory.apply(null,arguments)};g._free=function(){return g.asm._free.apply(null,arguments)};var Ye=g._malloc=function(){return g.asm._malloc.apply(null,arguments)};g._memcpy=function(){return g.asm._memcpy.apply(null,arguments)},g._memset=function(){return g.asm._memset.apply(null,arguments)},g._sbrk=function(){return g.asm._sbrk.apply(null,arguments)},g._stb_vorbis_js_channels=function(){return g.asm._stb_vorbis_js_channels.apply(null,arguments)},g._stb_vorbis_js_close=function(){return g.asm._stb_vorbis_js_close.apply(null,arguments)},g._stb_vorbis_js_decode=function(){return g.asm._stb_vorbis_js_decode.apply(null,arguments)},g._stb_vorbis_js_open=function(){return g.asm._stb_vorbis_js_open.apply(null,arguments)},g._stb_vorbis_js_sample_rate=function(){return g.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},g.establishStackSpace=function(){return g.asm.establishStackSpace.apply(null,arguments)},g.getTempRet0=function(){return g.asm.getTempRet0.apply(null,arguments)},g.runPostSets=function(){return g.asm.runPostSets.apply(null,arguments)},g.setTempRet0=function(){return g.asm.setTempRet0.apply(null,arguments)},g.setThrew=function(){return g.asm.setThrew.apply(null,arguments)};var Je=g.stackAlloc=function(){return g.asm.stackAlloc.apply(null,arguments)},Qt=g.stackRestore=function(){return g.asm.stackRestore.apply(null,arguments)},ct=g.stackSave=function(){return g.asm.stackSave.apply(null,arguments)};function pe(i){this.name="ExitStatus",this.message="Program terminated with exit("+i+")",this.status=i}function lt(i){i=i||g.arguments,!(Ae>0)&&(function(){if(g.preRun)for(typeof g.preRun=="function"&&(g.preRun=[g.preRun]);g.preRun.length;)po(g.preRun.shift());fe($t)}(),!(Ae>0)&&(g.calledRun||(g.setStatus?(g.setStatus("Running..."),setTimeout(function(){setTimeout(function(){g.setStatus("")},1),E()},1)):E())));function E(){!g.calledRun&&(g.calledRun=!0,be||(Bt||(Bt=!0,fe(Et)),fe(An),g.onRuntimeInitialized&&g.onRuntimeInitialized(),function(){if(g.postRun)for(typeof g.postRun=="function"&&(g.postRun=[g.postRun]);g.postRun.length;)So(g.postRun.shift());fe(tn)}()))}}function lr(i,E){(!E||!g.noExitRuntime||i!==0)&&(g.noExitRuntime||(be=!0,Kt=i,w=T,fe(en),mo=!0,g.onExit&&g.onExit(i)),g.quit(i,new pe(i)))}function OA(i){throw g.onAbort&&g.onAbort(i),i!==void 0?(Me(i),xA(i),i=JSON.stringify(i)):i="",be=!0,Kt=1,"abort("+i+"). Build with -s ASSERTIONS=1 for more info."}if(g.dynCall_iii=function(){return g.asm.dynCall_iii.apply(null,arguments)},g.asm=on,g.ccall=Zt,g.cwrap=function(E,B,f,R){var K=(f=f||[]).every(function(W){return W==="number"});return B!=="string"&&K&&!R?Vt(E):function(){return Zt(E,B,f,arguments,R)}},pe.prototype=Error(),pe.prototype.constructor=pe,me=function i(){g.calledRun||lt(),g.calledRun||(me=i)},g.run=lt,g.abort=OA,g.preInit)for(typeof g.preInit=="function"&&(g.preInit=[g.preInit]);g.preInit.length>0;)g.preInit.pop()();g.noExitRuntime=!0,lt(),g.onRuntimeInitialized=()=>{es=!0,ts()},VA.decode=function(i){return function(B){if(!es)throw Error("Not initialized");var f={};function R(oe){return new Int32Array(g.HEAPU8.buffer,oe,1)[0]}function K(oe,ut){var ve=new ArrayBuffer(ut*Float32Array.BYTES_PER_ELEMENT),re=new Float32Array(ve);return re.set(new Float32Array(g.HEAPU8.buffer,oe,ut)),re}f.open=g.cwrap("stb_vorbis_js_open","number",[]),f.close=g.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=g.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=g.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=g.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var W,x,hA,rA,iA=f.open(),nA=(W=B,x=B.byteLength,hA=g._malloc(x),(rA=new Uint8Array(g.HEAPU8.buffer,hA,x)).set(new Uint8Array(W,0,x)),rA),J=g._malloc(4),mA=g._malloc(4),MA=f.decode(iA,nA.byteOffset,nA.byteLength,J,mA);if(g._free(nA.byteOffset),MA<0)throw f.close(iA),g._free(J),Error("stbvorbis decode failed: "+MA);for(var NA=f.channels(iA),bA=Array(NA),ee=new Int32Array(g.HEAPU32.buffer,R(J),NA),LA=0;LA=0&&(n=this.workletProcessorChannels[e]),t.messageType){case tA.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case tA.noteOff:this.noteOff(e,A);break;case tA.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case tA.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case tA.customcCcChange:n.customControllers[A[0]]=A[1];break;case tA.killNote:this.killNote(e,A);break;case tA.programChange:this.programChange(e,A[0],A[1]);break;case tA.channelPressure:this.channelPressure(e,A);break;case tA.polyPressure:this.polyPressure(e,A[0],A[1]);break;case tA.ccReset:e===TA?this.resetAllControllers():this.resetControllers(e);break;case tA.systemExclusive:this.systemExclusive(A);break;case tA.setChannelVibrato:if(e===TA)for(let I=0;I{let e=(A.midiControllers[EA+V.pitchWheelRange]>>7)+(A.midiControllers[EA+V.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[EA+V.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:pA.channelProperties,messageData:t})}function Uo(t,A,e){let n=t,s=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:n,centTuning:s*.0061}}function rs(t,A=0){let e=t[0];if(!(this.deviceID!==TA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:b(`%cUnrecognized SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let s;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),m(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),m(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let c=(t[5]<<7|t[6])-8192;s=Math.floor(c/81.92),this.setMasterTuning(s),m(`%cMaster Fine Tuning. Cents: %c${s}`,r.info,r.value);break;case 4:s=(t[5]-64)*100,this.setMasterTuning(s),m(`%cMaster Coarse Tuning. Cents: %c${s}`,r.info,r.value);break;default:b(`%cUnrecognized MIDI Device Control Real-time message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(m("%cGM system on",r.info),this.system="gm"):t[3]===3?(m("%cGM2 system on",r.info),this.system="gm2"):(m("%cGM system off, defaulting to GS",r.info),this.system="gs");break;case 8:switch(t[3]){case 2:case 7:let o=4;t[3]===7&&o++;let I=t[o++],C=t[o++];for(let h=0;h>1&1)===1&&this.setOctaveTuning(15+A,c);for(let h=0;h<7;h++)(t[5]>>h&1)===1&&this.setOctaveTuning(7+h+A,c);for(let h=0;h<7;h++)(t[6]>>h&1)===1&&this.setOctaveTuning(h+A,c);m(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${c.join(" ")}`,r.info,r.value);break;default:b(`%cUnrecognized MIDI Tuning standard message: %c${lA(t)}`,r.warn,r.unrecognized);break}break;default:b(`%cUnrecognized MIDI Realtime/non realtime message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 65:let n=function(){b(`%cUnrecognized Roland %cGS %cSysEx: %c${lA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let s=t[7];if(t[6]===127){s===0?(m("%cGS Reset received!",r.info),this.resetAllControllers(!1),this.system="gs"):s===127&&(m("%cGS system off, switching to GM2",r.info),this.resetAllControllers(!1),this.system="gm2");return}else if(t[4]===64){if((t[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A;switch(t[6]){default:n();break;case 21:let I=s>0&&t[5]>>4;this.setDrums(o,I),m(`%cChannel %c${o}%c ${I?"is now a drum channel":"now isn't a drum channel"}%c via: %c${lA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=s-64;this.transposeChannel(o,C),m(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${lA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let c=s;c===0&&(c=Math.floor(Math.random()*128)),this.controllerChange(o,p.pan,c);break;case 33:this.controllerChange(o,p.effects3Depth,s);break;case 34:this.controllerChange(o,p.effects1Depth,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 h=t.length-9,u=new Int8Array(12);for(let l=0;l=this.workletProcessorChannels.length)return;let o=t[6];switch(t[5]){case 1:this.controllerChange(s,p.bankSelect,o);break;case 2:this.controllerChange(s,p.lsbForControl0BankSelect,o);break;case 3:this.programChange(s,o);break;case 8:let I=this.workletProcessorChannels[s];if(I.drumChannel)return;let C=o-64;I.channelTransposeKeyShift=C;break;case 11:this.controllerChange(s,p.mainVolume,o);break;case 14:let c=o;c===0&&(c=Math.floor(Math.random()*127)),this.controllerChange(s,p.pan,c);break;case 19:this.controllerChange(s,p.effects1Depth,o);break;case 18:this.controllerChange(s,p.effects3Depth,o);break;default:b(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&b(`%cUnrecognized Yamaha XG SysEx: %c${lA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&b(`%cUnrecognized Yamaha SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break}}function is(t,A,e){if(A.transformAmount===0)return 0;let n;if(A.sourceUsesCC)n=t[A.sourceIndex];else{let c=A.sourceIndex+EA;switch(A.sourceIndex){case V.noController:n=16383;break;case V.noteOnKeyNum:n=e.midiNote<<7;break;case V.noteOnVelocity:n=e.velocity<<7;break;case V.polyPressure:n=e.pressure<<7;break;default:n=t[c];break}}let s=dA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let c=A.secSrcIndex+EA;switch(A.secSrcIndex){case V.noController:o=16383;break;case V.noteOnKeyNum:o=e.midiNote<<7;break;case V.noteOnVelocity:o=e.velocity<<7;break;case V.polyPressure:o=e.pressure<<7;break;default:o=t[c]}}let I=dA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=s*I*A.transformAmount;return A.transformType===2?Math.abs(C):C}function XA(t,A,e=-1,n=0){let{modulators:s,generators:o,modulatedGenerators:I}=t;if(JA.recalculate(t),e===-1){I.set(o),s.forEach(h=>{let u=N[h.modulatorDestination];if(I[h.modulatorDestination]===u.min||I[h.modulatorDestination]===u.max)return;let Q=I[h.modulatorDestination]+is(A,h,t);I[h.modulatorDestination]=Math.max(u.min,Math.min(Q,u.max))}),GA.recalculate(t);return}let C=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),c=new Set;s.forEach(h=>{if(h.sourceUsesCC===e&&h.sourceIndex===n||h.secSrcUsesCC===e&&h.secSrcIndex===n){let u=h.modulatorDestination;c.has(u)||(I[u]=o[u],s.forEach(Q=>{if(Q.modulatorDestination===u){let l=N[h.modulatorDestination],d=I[h.modulatorDestination];if(d===l.min||d===l.max)return;let S=d+is(A,Q,t);I[h.modulatorDestination]=Math.max(l.min,Math.min(S,l.max))}}),c.add(u))}}),[...c].some(h=>C.has(h))&&GA.recalculate(t)}var dA=[];for(let t=0;t<4;t++){dA[t]=[[new Float32Array(gA),new Float32Array(gA)],[new Float32Array(gA),new Float32Array(gA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||I.isMuted)return;let C=A+I.channelTransposeKeyShift;if(A>127||A<0)return;let c=I.preset.program;this.tunings[c]?.[A]?.midiNote>=0&&(C=this.tunings[c]?.[A].midiNote);let h=this.getWorkletVoices(t,C,e,I,o,n),u=I.voices;h.forEach(Q=>{let l=Q.generators[a.exclusiveClass];l!==0&&u.forEach(d=>{d.generators[a.exclusiveClass]===l&&(this.releaseVoice(d),d.modulatedGenerators[a.releaseVolEnv]=-7e3,d.modulatedGenerators[a.releaseModEnv]=-7e3,GA.recalculate(d),JA.recalculate(d))}),XA(Q,I.midiControllers),GA.intialize(Q),Q.currentPan=(Math.max(-500,Math.min(500,Q.modulatedGenerators[a.pan]))+500)/1e3}),this.totalVoicesAmount+=h.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(h.length),u.push(...h),s&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Is(t,A){if(A>127||A<0){b("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift,n=this.workletProcessorChannels[t].preset.program;if(this.tunings[n]?.[A]?.midiNote>=0&&(e=this.tunings[n]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(o=>{o.midiNote!==e||o.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function gs(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.midiNote===A&&(e.modulatedGenerators[a.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function Cs(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(n=>{n.isInRelease||this.releaseVoice(n)}),this.workletProcessorChannels[t].sustainedVoices.forEach(n=>{this.releaseVoice(n)}))}function Es(t=!1){m("%cStop all received!",r.info);for(let A=0;AXA(s,this.workletProcessorChannels[t].midiControllers,0,V.pitchWheel)),this.sendChannelProperties()}function fs(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[EA+V.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(n=>XA(n,e.midiControllers,0,V.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function ms(t,A,e){this.workletProcessorChannels[t].voices.forEach(n=>{n.midiNote===A&&(n.pressure=e,XA(n,this.workletProcessorChannels[t].midiControllers,0,V.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function ps(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function Ss(t,A,e,n=!1){let s=this.workletProcessorChannels[t];if(s===void 0){b(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>=p.lsbForControl1ModulationWheel&&A<=p.lsbForControl13EffectControl2&&A!==p.lsbForControl6DataEntry){let o=A-32;if(s.lockedControllers[o])return;s.midiControllers[o]=s.midiControllers[o]&16256|e&127,s.voices.forEach(I=>XA(I,s.midiControllers,1,o))}switch(A){case p.allNotesOff:this.stopAll(t);break;case p.allSoundOff:this.stopAll(t,!0);break;case p.bankSelect:let o=e;if(!n){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==yA&&this.setDrums(t,!1);break;case"gm2":o===120&&(s.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}s.drumChannel&&(o=128),o===128&&!s.drumChannel&&(o=s.midiControllers[p.bankSelect])}s.midiControllers[p.bankSelect]=o;break;case p.lsbForControl0BankSelect:this.system==="xg"?s.drumChannel||e!==127&&(s.midiControllers[p.bankSelect]=e):this.system==="gm2"&&(s.midiControllers[p.bankSelect]=e);break;case p.RPNLsb:s.RPValue=s.RPValue<<7|e,s.dataEntryState=uA.RPFine;break;case p.RPNMsb:s.RPValue=e,s.dataEntryState=uA.RPCoarse;break;case p.NRPNMsb:s.NRPCoarse=e,s.dataEntryState=uA.NRPCoarse;break;case p.NRPNLsb:s.NRPFine=e,s.dataEntryState=uA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(t,e);break;case p.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case p.resetAllControllers:this.resetControllers(t);break;case p.sustainPedal:e>=64?s.holdPedal=!0:(s.holdPedal=!1,s.sustainedVoices.forEach(I=>{this.releaseVoice(I)}),s.sustainedVoices=[]);break;default:if(s.lockedControllers[A])return;s.midiControllers[A]=e<<7,s.voices.forEach(I=>XA(I,s.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function ys(t){this.midiVolume=t,this.setMasterPan(this.pan)}function Ds(t){this.masterGain=t*Lt,this.setMasterPan(this.pan)}function ks(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function ws(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function Fs(t){this.workletProcessorChannels[t].lockGSNRPNParams=!0,this.workletProcessorChannels[t].channelVibrato.rate=0,this.workletProcessorChannels[t].channelVibrato.delay=0,this.workletProcessorChannels[t].channelVibrato.depth=0}function Rs(t,A,e,n){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=n,this.workletProcessorChannels[t].channelVibrato.depth=A)}function Gs(t,A){let e=this.workletProcessorChannels[t],n=()=>{e.channelVibrato.delay===0&&e.channelVibrato.rate===0&&e.channelVibrato.depth===0&&(e.channelVibrato.depth=50,e.channelVibrato.rate=8,e.channelVibrato.delay=.6)};switch(e.dataEntryState){default:case uA.Idle:break;case uA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;b(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16).toUpperCase()} 0x${e.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 1:switch(e.NRPFine){default:if(A===64)return;b(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16)} 0x${e.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(A===64)return;n(),e.channelVibrato.rate=A/64*8,m(`%cVibrato rate for %c${t}%c is now set to %c${A} = ${e.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(A===64)return;n(),e.channelVibrato.depth=A/2,m(`%cVibrato depth for %c${t}%c is now set to %c${A} = ${e.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(A===64)return;n(),e.channelVibrato.delay=A/64/3,m(`%cVibrato delay for %c${t}%c is now set to %c${A} = ${e.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let I=A;this.controllerChange(t,p.brightness,A),m(`%cFilter cutoff for %c${t}%c is now set to %c${I}`,r.info,r.recognized,r.info,r.value)}break;case 24:let s=A-64;e.keyCentTuning[e.NRPFine]=s*100,m(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${s}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,p.effects1Depth,o),m(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:b(`%cUnrecognized RPN for %c${t}%c: %c(0x${e.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:e.midiControllers[EA+V.pitchWheelRange]=A<<7,m(`%cChannel ${t} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(t,A-64);break;case 1:this.setChannelTuning(t,A-64,!1);break;case 5:this.setModulationDepth(t,A*100);break;case 16383:this.resetParameters(t);break}}}function xs(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[EA+V.pitchWheelRange]|=A;let n=(e.midiControllers[EA+V.pitchWheelRange]>>7)+A/127;m(`%cChannel ${t} bend range. Semitones: %c${n}`,r.info,r.value);break;case 1:let o=e.customControllers[IA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[IA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function Ms(t=!0){t&&m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A{this.workletProcessorChannels[A].lockedControllers[s]&&this.callEvent("controllerchange",{channel:A,controllerNumber:s,controllerValue:this.workletProcessorChannels[A].midiControllers[s]>>7})};if(n(p.mainVolume),n(p.pan),n(p.expressionController),n(p.modulationWheel),n(p.effects3Depth),n(p.effects1Depth),n(p.brightness),this.workletProcessorChannels[A].lockedControllers[EA+V.pitchWheel]){let s=this.workletProcessorChannels[A].midiControllers[EA+V.pitchWheel],o=s>>7,I=s&127;this.callEvent("pitchwheel",{channel:A,MSB:o,LSB:I})}}this.tunings=[],this.tunings=[];for(let A=0;A<127;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Ke}function Ns(t){let A=this.workletProcessorChannels[t],n=A.lockedControllers.reduce((o,I,C)=>(I&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(ZA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,n.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let s=A.customControllers[IA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[IA.channelTransposeFine]=s,this.resetParameters(t)}function bs(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=uA.Idle}function Ls(){let t=4;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==a.sampleID&&I.generatorType!==a.keyRange&&I.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+s),0);let A=new H(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.generatorZoneStartIndex=e;for(let o of s.generators)Y(A,o.generatorType),Y(A,o.generatorValue),e++}return QA(A,0),sA(new $("igen",A.length,A))}function Us(t,A,e,n,s){let o=this.samples.map((h,u)=>{e&&h.compressSample(n,s);let Q=h.getRawData();return m(`%cEncoded sample %c${u}. ${h.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),Q}),I=this.samples.reduce((h,u,Q)=>h+o[Q].length+46,0),C=new H(I);this.samples.forEach((h,u)=>{let Q=o[u],l,d,S=Q.length;h.isCompressed?(l=C.currentIndex,d=l+Q.length):(l=C.currentIndex/2,d=l+Q.length/2,S+=46),t.push(l),C.set(Q,C.currentIndex),C.currentIndex+=S,A.push(d)});let c=sA(new $("smpl",C.length,C),new H([115,100,116,97]));return sA(new $("LIST",c.length,c))}function Ts(t,A){let n=new H(46*(this.samples.length+1));return this.samples.forEach((s,o)=>{RA(n,s.sampleName,20);let I=t[o];QA(n,I);let C=A[o];QA(n,C);let c=s.sampleLoopStartIndex/2+I,h=s.sampleLoopEndIndex/2+I;s.isCompressed&&(c-=I,h-=I),QA(n,c),QA(n,h),QA(n,s.sampleRate),n[n.currentIndex++]=s.samplePitch,n[n.currentIndex++]=s.samplePitchCorrection,Y(n,s.sampleLink),Y(n,s.sampleType)}),RA(n,"EOS",46),sA(new $("shdr",n.length,n))}function Hs(){let t=10;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new H(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),sA(new $("imod",A.length,A))}function Ys(){let t=this.instruments.reduce((o,I)=>I.instrumentZones.length*4+o,4),A=new H(t),e=0,n=0,s=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let I of o.instrumentZones)I.zoneID=e,Y(A,n),Y(A,s),n+=I.generators.length,s+=I.modulators.length,e++}return Y(A,n),Y(A,s),sA(new $("ibag",A.length,A))}function Js(){let t=this.instruments.length*22+22,A=new H(t),e=0,n=0;for(let s of this.instruments)RA(A,s.instrumentName,20),Y(A,e),e+=s.instrumentZones.length,s.instrumentID=n,n++;return RA(A,"EOI",20),Y(A,e),sA(new $("inst",A.length,A))}function vs(){let t=4;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==a.instrument&&I.generatorType!==a.keyRange&&I.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+s),0);let A=new H(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.generatorZoneStartIndex=e;for(let o of s.generators)Y(A,o.generatorType),Y(A,o.generatorValue);e+=s.generators.length}return Y(A,0),Y(A,0),sA(new $("pgen",A.length,A))}function qs(){let t=10;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new H(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),sA(new $("pmod",A.length,A))}function Ps(){let t=this.presets.reduce((o,I)=>I.presetZones.length*4+o,4),A=new H(t),e=0,n=0,s=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let I of o.presetZones)I.zoneID=e,Y(A,n),Y(A,s),n+=I.generators.length,s+=I.modulators.length,e++}return Y(A,n),Y(A,s),sA(new $("pbag",A.length,A))}function Ks(){let t=this.presets.length*38+38,A=new H(t),e=0;for(let n of this.presets)RA(A,n.presetName,20),Y(A,n.program),Y(A,n.bank),Y(A,e),QA(A,n.library),QA(A,n.genre),QA(A,n.morphology),e+=n.presetZones.length;return RA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,e),QA(A,0),QA(A,0),QA(A,0),sA(new $("phdr",A.length,A))}var To={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Vs(t=To){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");SA("%cSaving soundfont...",r.info),m(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),m("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[q,T]of Object.entries(this.soundFontInfo))if(q==="ifil"||q==="iver"){let g=parseInt(T.split(".")[0]),AA=parseInt(T.split(".")[1]),P=new H(4);Y(P,g),Y(P,AA),A.push(sA(new $(q,4,P)))}else if(q==="DMOD")A.push(sA(new $(q,T.length,T)));else{let g=new H(T.length);RA(g,T),A.push(sA(new $(q,T.length,g)))}let e=De([new H([73,78,70,79]),...A]),n=sA(new $("LIST",e.length,e));m("%cWriting SDTA...",r.info);let s=[],o=[],I=Us.call(this,s,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let C=Ts.call(this,s,o);m("%cWriting IGEN...",r.info);let c=Ls.call(this);m("%cWriting IMOD...",r.info);let h=Hs.call(this);m("%cWriting IBAG...",r.info);let u=Ys.call(this);m("%cWriting INST...",r.info);let Q=Js.call(this),l=vs.call(this);m("%cWriting PMOD...",r.info);let d=qs.call(this);m("%cWriting PBAG...",r.info);let S=Ps.call(this);m("%cWriting PHDR...",r.info);let D=Ks.call(this),w=De([new H([112,100,116,97]),D,S,d,l,Q,u,h,c,C]),F=sA(new $("LIST",w.length,w));m("%cWriting the output file...",r.info);let v=De([new H([115,102,98,107]),n,I,F]),M=sA(new $("RIFF",v.length,v));return m(`%cSaved succesfully! Final file size: %c${M.length}`,r.info,r.recognized),X(),M}var se=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Ze.map(e=>eA.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}getPresetNoFallback(A,e,n=!1){let s=this.presets.find(o=>o.bank===A&&o.program===e);if(s)return s;if(n!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPreset(A,e){let n=this.presets.find(s=>s.bank===A&&s.program===e);return n||(A===128?(n=this.presets.find(s=>s.bank===128&&s.program===e),n||(n=this.presets.find(s=>s.bank===128))):n=this.presets.find(s=>s.program===e&&s.bank!==128),n&&b(`%cPreset ${A}.${e} not found. Replaced with %c${n.presetName} (${n.bank}.${n.program})`,r.warn,r.recognized)),n||(b(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),n=this.presets[0]),n}getPresetByName(A){let e=this.presets.find(n=>n.presetName===A);return e||(b("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}static mergeSoundfonts(...A){let e=A.shift(),n=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(I=>I.bank===o.bank&&I.program===o.program)===void 0&&n.push(o)});return new t({presets:n,info:e.soundFontInfo})}};se.prototype.write=Vs;function Os(t){SA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let n=A;n{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}getSamplesAndGenerators(A,e){let n=this.foundSamplesAndGenerators[A][e];if(n)return n;if(this.presetZones.length<1)return[];function s(Q,l,d){return d>=Q&&d<=l}function o(Q,l){Q.push(...l.filter(d=>!Q.find(S=>S.generatorType===d.generatorType)))}function I(Q,l){Q.push(...l.filter(d=>!Q.find(S=>eA.isIdentical(d,S))))}let C=[],c=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(Q=>s(Q.keyRange.min,Q.keyRange.max,A)&&s(Q.velRange.min,Q.velRange.max,e)&&!Q.isGlobal).forEach(Q=>{if(Q.instrument.instrumentZones.length<1)return;let l=Q.generators,d=Q.modulators,S=Q.instrument.instrumentZones[0].isGlobal?[...Q.instrument.instrumentZones[0].generators]:[],D=Q.instrument.instrumentZones[0].isGlobal?[...Q.instrument.instrumentZones[0].modulators]:[];Q.instrument.instrumentZones.filter(F=>s(F.keyRange.min,F.keyRange.max,A)&&s(F.velRange.min,F.velRange.max,e)&&!F.isGlobal).forEach(F=>{let v=[...F.generators],M=[...F.modulators];o(l,c),o(v,S),I(d,h),I(M,D),I(M,this.defaultModulators);let q=[...M];for(let T=0;TeA.isIdentical(g,P));AA!==-1?q[AA]=q[AA].sumTransform(g):q.push(g)}C.push({instrumentGenerators:v,presetGenerators:l,modulators:q,sample:F.sample,sampleID:F.generators.find(T=>T.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=C,C}};var Re=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var $A=class extends Re{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},ce=class extends Re{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var le=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var At=class extends Qe{constructor(A,e){super(Ze),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new le,this.DLSInstrument.addUseCount();let s=new ce;s.instrument=this.DLSInstrument,this.presetZones=[s]}};function Zs(t){this.verifyHeader(t,"LIST"),this.verifyText(O(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(Z(t.chunkData));let e=A.find(d=>d.header==="insh");if(!e)throw X(),new Error("No instrument header!");let n=y(e.chunkData,4),s=y(e.chunkData,4),o=y(e.chunkData,4),I=new At(s,o),C="unnamedPreset",c=DA(A,"INFO");if(c){let d=Z(c.chunkData);for(;d.header!=="INAM";)d=Z(c.chunkData);C=O(d.chunkData,d.chunkData.length).trim()}I.presetName=C,I.DLSInstrument.instrumentName=C,te(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let h=DA(A,"lrgn");if(!h)throw X(),new Error("No region list!");let u=new $A;u.isGlobal=!0;let Q=DA(A,"lart"),l=DA(A,"lar2");this.readLart(Q,l,u),I.DLSInstrument.instrumentZones.push(u);for(let d=0;d>10&15;F===cA.linear&&w!==cA.linear&&(F=w);let v=n>>14&1,M=n>>15&1;I===a.initialAttenuation&&(M=!M),Q=PA(F,v,M,C.isCC,C.enum)}let l=n>>4&15,d=n>>8&1,S=n>>9&1,D=PA(l,d,S,u.isCC,u.enum);if(c){let w=D;D=Q,Q=w}return new eA({srcEnum:Q,secSrcEnum:D,dest:I,transform:0,amt:s})}function Ut(t,A){let e=t.chunkData,n=[],s=[];y(e,4);let o=y(e,4);for(let I=0;I>16;if(C===0&&c===0&&u===0){let d;switch(h){case G.pan:d=new L(a.pan,l);break;case G.gain:d=new L(a.initialAttenuation,-l*10/.4);break;case G.filterCutoff:d=new L(a.initialFilterFc,l);break;case G.filterQ:d=new L(a.initialFilterQ,l);break;case G.modLfoFreq:d=new L(a.freqModLFO,l);break;case G.modLfoDelay:d=new L(a.delayModLFO,l);break;case G.vibLfoFreq:d=new L(a.freqVibLFO,l);break;case G.vibLfoDelay:d=new L(a.delayVibLFO,l);break;case G.volEnvDelay:d=new L(a.delayVolEnv,l);break;case G.volEnvAttack:d=new L(a.attackVolEnv,l);break;case G.volEnvHold:d=new L(a.holdVolEnv,l);break;case G.volEnvDecay:d=new L(a.decayVolEnv,l);break;case G.volEnvRelease:d=new L(a.releaseVolEnv,l);break;case G.volEnvSustain:let S=(1e3-l)/10;d=new L(a.sustainVolEnv,S*10);break;case G.modEnvDelay:d=new L(a.delayModEnv,l);break;case G.modEnvAttack:d=new L(a.attackModEnv,l);break;case G.modEnvHold:d=new L(a.holdModEnv,l);break;case G.modEnvDecay:d=new L(a.decayModEnv,l);break;case G.modEnvRelease:d=new L(a.releaseModEnv,l);break;case G.modEnvSustain:let D=1e3-l;d=new L(a.sustainModEnv,D);break;case G.reverbSend:d=new L(a.reverbEffectsSend,l);break;case G.chorusSend:d=new L(a.chorusEffectsSend,l);break;case G.pitch:let w=Math.floor(l/100),F=Math.floor(l-w*100);d=new L(a.fineTune,F),n.push(new L(a.coarseTune,w));break}d&&n.push(d)}else{let d=!0;if(c===_.none)if(C===_.modLfo&&h===G.pitch)n.push(new L(a.modLfoToPitch,l));else if(C===_.modLfo&&h===G.gain)n.push(new L(a.modLfoToVolume,l));else if(C===_.modLfo&&h===G.filterCutoff)n.push(new L(a.modLfoToFilterFc,l));else if(C===_.vibratoLfo&&h===G.pitch)n.push(new L(a.vibLfoToPitch,l));else if(C===_.modEnv&&h===G.pitch)n.push(new L(a.modEnvToPitch,l));else if(C===_.modEnv&&h===G.filterCutoff)n.push(new L(a.modEnvToFilterFc,l));else if(C===_.keyNum&&h===G.volEnvHold){n.push(new L(a.keyNumToVolEnvHold,l/-128));let S=Math.round(60/128*l);n.forEach(D=>{D.generatorType===a.holdVolEnv&&(D.generatorValue+=S)})}else if(C===_.keyNum&&h===G.volEnvDecay){n.push(new L(a.keyNumToVolEnvDecay,l/-128));let S=Math.round(60/128*l);n.forEach(D=>{D.generatorType===a.decayVolEnv&&(D.generatorValue+=S)})}else if(C===_.keyNum&&h===G.modEnvHold){n.push(new L(a.keyNumToModEnvHold,l/-128));let S=Math.round(60/128*l);n.forEach(D=>{D.generatorType===a.holdModEnv&&(D.generatorValue+=S)})}else if(C===_.keyNum&&h===G.modEnvDecay){n.push(new L(a.keyNumToModEnvDecay,l/-128));let S=Math.round(60/128*l);n.forEach(D=>{D.generatorType===a.decayModEnv&&(D.generatorValue+=S)})}else d=!1;else d=!1;if(d===!1){let S=Ws(C,c,h,u,l);S?(s.push(S),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):b("Failed converting to SF2 Modulator!")}}}return s.find(I=>I.modulatorDestination===a.reverbEffectsSend)===void 0&&s.push(new eA({srcEnum:219,dest:a.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),s.find(I=>I.modulatorDestination===a.chorusEffectsSend)===void 0&&s.push(new eA({srcEnum:221,dest:a.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&s.push(new eA({srcEnum:129,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new eA({srcEnum:13,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:s,generators:n}}function _s(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(Z(t.chunkData));let e=A.find(AA=>AA.header==="rgnh"),n=y(e.chunkData,2),s=y(e.chunkData,2),o=y(e.chunkData,2),I=y(e.chunkData,2),C=new et({min:n,max:s},{min:o,max:I});y(e.chunkData,2);let c=y(e.chunkData,2);c!==0&&C.generators.push(new L(a.exclusiveClass,c));let h=DA(A,"lart"),u=DA(A,"lar2");this.readLart(h,u,C),C.isGlobal=!1;let Q=A.find(AA=>AA.header==="wsmp");y(Q.chunkData,4);let l=y(Q.chunkData,2),d=jA(Q.chunkData[Q.chunkData.currentIndex++],Q.chunkData[Q.chunkData.currentIndex++]),w=(y(Q.chunkData,4)|0)/-655360*10/.4;y(Q.chunkData,4);let F=y(Q.chunkData,4),v,M={start:0,end:0};if(F===0)v=0;else{y(Q.chunkData,4),y(Q.chunkData,4)===0?v=1:v=3,M.start=y(Q.chunkData,4);let P=y(Q.chunkData,4);M.end=M.start+P}let q=A.find(AA=>AA.header==="wlnk");if(q===void 0)return;y(q.chunkData,2),y(q.chunkData,2),y(q.chunkData,4);let T=y(q.chunkData,4),g=this.samples[T];if(g===void 0)throw new Error("Invalid sample ID!");return C.setWavesample(w,v,M,l,g,T,d),C}var ue=class{constructor(A,e,n,s,o,I,C,c){this.sampleName=A,this.sampleRate=e,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=I,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=c,this.isCompressed=(I&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,e){if(!this.isCompressed)try{this.compressedData=e([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{b(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}};var tt=class extends ue{constructor(A,e,n,s,o,I,C){super(A,e,n,s,0,1,o*2,(I-1)*2),this.sampleData=C}getAudioData(){return this.sampleData}sampleData;getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let e=0;e>8&255}return A}};function js(t){SA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexP.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");if(y(s.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(y(s.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=y(s.chunkData,4);y(s.chunkData,4),y(s.chunkData,2);let c=y(s.chunkData,2),h=c/8,u=Math.pow(2,h*8-1),Q=Math.pow(2,h*8),l,d=!1;c===8?(l=255,d=!0):l=u;let S=n.find(P=>P.header==="data");if(!S)throw new Error("No data chunk in the wave chunk!");let D=S.size/h,w=new Float32Array(D);for(let P=0;P=u&&(j-=Q),w[P]=j/l)}let F=60,v=0,M=0,q=w.length-1,T=n.find(P=>P.header==="wsmp");if(T){if(y(T.chunkData,4),F=y(T.chunkData,2),v=jA(T.chunkData[T.chunkData.currentIndex++],T.chunkData[T.chunkData.currentIndex++]),y(T.chunkData,4),y(T.chunkData,4),y(T.chunkData,4)===1){y(T.chunkData,8),M=y(T.chunkData,4);let j=y(T.chunkData,4);q=M+j}}else b("No wsmp chunk in wave... using sane defaults.");let g=DA(n,"INFO"),AA=`Unnamed ${A}`;if(g){let P=Z(g.chunkData);for(;P.header!=="INAM"&&g.chunkData.currentIndexc.header==="colh");if(!o)throw X(),new Error("No colh chunk!");this.instrumentAmount=S(o.chunkData,4),m(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let g=DA(s,"wvpl");this.readDLSSamples(g);let C=DA(s,"lins");if(!C)throw X(),new Error("No lins chunk!");this.readDLSInstrumentList(C),this.presets.sort((c,Q)=>c.program-Q.program+(c.bank-Q.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X()}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=On;WA.prototype.readDLSInstrument=Zn;WA.prototype.readRegion=zn;WA.prototype.readLart=_n;WA.prototype.readDLSSamples=jn;var Tt=class extends ue{constructor(A,e,s,n,o,g,C,c,Q,u,h,l,d){super(A,g,C,c,Q,u,n-e,o-e),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=s,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=h,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex,this.sampleLoopEndIndex+=this.sampleStartIndex,this.sampleLength=99999999),this.isDataRaw=d}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let e=A.currentIndex;return A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e)}else{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");let e=A.currentIndex;return A.slice(e+this.sampleStartIndex,e+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,e=A.currentIndex,s=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let n=VA.decode(s.buffer);this.sampleData=n.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return N("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,s=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let n=0;nt.chunkData.currentIndex;){let o=Jo(n,t.chunkData,A,e);s.push(o),n++}return s.length>1&&s.pop(),s}function Jo(t,A,e,s){let n=O(A,20),o=S(A,4)*2,g=S(A,4)*2,C=S(A,4)*2,c=S(A,4)*2,Q=S(A,4),u=A[A.currentIndex++];u===255&&(u=60);let h=Ss(A[A.currentIndex++]),l=S(A,2),d=S(A,2);return new Tt(n,o,g,C,c,Q,u,h,l,d,e,t,s)}var Ht=class extends le{constructor(A){super(),this.instrumentName=O(A.chunkData,20).trim(),this.instrumentZoneIndex=S(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let s=this.instrumentZoneIndex;st.chunkData.currentIndex;){let s=new Ht(t);if(e.length>0){let n=s.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(n,A)}e.push(s)}return e.length>1&&e.pop(),e}var Yt=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=S(A,2),this.modulatorZoneStartIndex=S(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===a.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function eo(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Yt(t.chunkData);if(n.length>0){let g=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(g,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(e),n[n.length-1].getSample(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var Jt=class extends ce{constructor(A){super(),this.generatorZoneStartIndex=S(A,2),this.modulatorZoneStartIndex=S(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===a.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function to(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Jt(t.chunkData);if(n.length>0){let g=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(g,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(e),n[n.length-1].getInstrument(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var vt=class extends Qe{constructor(A,e){super(e),this.presetName=O(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=S(A.chunkData,2),this.bank=S(A.chunkData,2),this.presetZoneStartIndex=S(A.chunkData,2),this.library=S(A.chunkData,4),this.genre=S(A.chunkData,4),this.morphology=S(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;st.chunkData.currentIndex;){let n=new vt(t,e);if(s.length>0){let o=n.presetZoneStartIndex-s[s.length-1].presetZoneStartIndex;s[s.length-1].getPresetZones(o,A)}s.push(n)}return s.length>1&&s.pop(),s}var st=class extends ne{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new H(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw X(),new TypeError("No data!");let s=Z(this.dataArray,!1);this.verifyHeader(s,"riff");let n=O(this.dataArray,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw X(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let o=n==="sfpk",g=Z(this.dataArray);for(this.verifyHeader(g,"list"),O(g.chunkData,4);g.chunkData.length>g.chunkData.currentIndex;){let z=Z(g.chunkData),CA;switch(z.header.toLowerCase()){case"ifil":case"iver":CA=`${S(z.chunkData,2)}.${S(z.chunkData,2)}`,this.soundFontInfo[z.header]=CA;break;case"icmt":CA=O(z.chunkData,z.chunkData.length,void 0,!1),this.soundFontInfo[z.header]=CA;break;case"dmod":let oA=Xe(z);oA.pop(),CA=`Modulators: ${oA.length}`;let fA=this.defaultModulators;this.defaultModulators=oA,this.defaultModulators.push(...fA.filter(Me=>!this.defaultModulators.find(xA=>eA.isIdentical(Me,xA)))),this.soundFontInfo[z.header]=z.chunkData;break;default:CA=O(z.chunkData,z.chunkData.length),this.soundFontInfo[z.header]=CA}m(`%c"${z.header}": %c"${CA}"`,r.info,r.recognized)}let C=Z(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(O(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",r.warn);let c=Z(this.dataArray,!1);this.verifyHeader(c,"smpl");let Q;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{Q=VA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(z){throw X(),new Error(`SF2Pack Ogg Vorbis decode error: ${z}`)}m(`%cDecoded the smpl chunk! Length: %c${Q.length}`,r.info,r.value)}else Q=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,m("%cLoading preset data chunk...",r.warn);let u=Z(this.dataArray);this.verifyHeader(u,"list"),O(u.chunkData,4);let h=Z(u.chunkData);this.verifyHeader(h,"phdr");let l=Z(u.chunkData);this.verifyHeader(l,"pbag");let d=Z(u.chunkData);this.verifyHeader(d,"pmod");let y=Z(u.chunkData);this.verifyHeader(y,"pgen");let D=Z(u.chunkData);this.verifyHeader(D,"inst");let w=Z(u.chunkData);this.verifyHeader(w,"ibag");let F=Z(u.chunkData);this.verifyHeader(F,"imod");let v=Z(u.chunkData);this.verifyHeader(v,"igen");let M=Z(u.chunkData);this.verifyHeader(M,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...$n(M,Q,!o));let q=pt(v),T=Xe(F),I=eo(w,q,T,this.samples);this.instruments=Ao(D,I);let AA=pt(y),P=Xe(d),j=to(l,AA,P,this.instruments);this.presets.push(...so(h,j,this.defaultModulators)),this.presets.sort((z,CA)=>z.program-CA.program+(z.bank-CA.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X(),o&&delete this.dataArray}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Ge(t){let A=t.slice(8,12),e=new H(A);return O(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new st(t,!1)}function no(t,A,e=!1){let s=this.workletProcessorChannels[t];if(s===void 0){N(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[p.bankSelect],o,g;if(this.overrideSoundfont){let C=n===128?128:n-this.soundfontBankOffset,c=this.overrideSoundfont.getPresetNoFallback(C,A);c?(o=n,g=c,s.presetUsesOverride=!0):(g=this.soundfontManager.getPreset(n,A),o=g.bank,s.presetUsesOverride=!1)}else g=this.soundfontManager.getPreset(n,A),o=g.bank,s.presetUsesOverride=!1;this.setPreset(t,g),this.callEvent("programchange",{channel:t,program:g.program,bank:o,userCalled:e})}function oo(t,A){if(this.overrideSoundfont){let e=t===128?128:t-this.soundfontBankOffset,s=this.overrideSoundfont.getPresetNoFallback(e,A);if(s)return s}return this.soundfontManager.getPreset(t,A)}function ro(t,A){if(!this.workletProcessorChannels[t].lockPreset){delete this.workletProcessorChannels[t].preset,this.workletProcessorChannels[t].preset=A,this.workletProcessorChannels[t].cachedVoices=[];for(let e=0;e<128;e++)this.workletProcessorChannels[t].cachedVoices.push([])}}function io(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(128,e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(e.midiControllers[p.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function ao(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,s=t.find(n=>n.bank===e&&n.program===A.program);s!==void 0?s.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function Io(t=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let e=0;e{this.programChange(s,e.preset.program)}),this.post({messageType:pA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",r.recognized)}function Co(t,A){this.soundfontBankOffset=A,this.reloadSoundFont(t,!0),this.overrideSoundfont.samples.forEach(e=>e.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function Eo(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:e.preset.bank,lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:pA.synthesizerSnapshot,messageData:A})}function Bo(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation;this.workletProcessorChannels.length{let s=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),s.midiControllers=A.midiControllers,s.lockedControllers=A.lockedControllers,s.customControllers=A.customControllers,s.channelVibrato=A.channelVibrato,s.lockGSNRPNParams=A.lockVibrato,s.channelTransposeKeyShift=A.channelTransposeKeyShift,s.channelOctaveTuning=A.channelOctaveTuning,s.lockPreset=!1,s.midiControllers[p.bankSelect]=A.bank,this.programChange(e,A.program),s.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",r.info)}var nt=class{constructor(A,e){this.ready=e,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(e=>{e.soundfont.setSampleIDOffset(A),A+=e.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let e=this.soundfontList.length-1;e>=0;e--){let s=this.soundfontList[e],n=new Set;for(let o of s.soundfont.presets){let g=`${o.bank+s.bankOffset}-${o.program}`;n.has(g)||(n.add(g),A[g]=o.presetName)}}this.presetList=[];for(let[e,s]of Object.entries(A)){let n=e.split("-");this.presetList.push({presetName:s,program:parseInt(n[1]),bank:parseInt(n[0])})}}handleMessage(A,e){switch(A){case Ie.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ie.reloadSoundFont:this.reloadManager(e);break;case Ie.deleteSoundFont:this.deleteSoundFont(e);break;case Ie.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ge(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){N("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(s=>s.id===A);if(e===-1){N(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[e].soundfont.presets,delete this.soundfontList[e].soundfont.instruments,delete this.soundfontList[e].soundfont.samples,this.soundfontList.splice(e,1),this.generatePresetList()}addNewSoundFont(A,e,s){if(this.soundfontList.find(n=>n.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Ge(A),bankOffset:s}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,s)=>A.indexOf(e.id)-A.indexOf(s.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let s of this.soundfontList){let n=s.soundfont.getPresetNoFallback(A-s.bankOffset,e);if(n!==void 0)return n}if(A!==128){for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.program===e);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}else{for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.bank===128);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}}};var ot=class{constructor(A,e,s,n,o,g,C,c){this.sampleData=A,this.playbackStep=e,this.cursor=s,this.rootKey=n,this.loopStart=o,this.loopEnd=g,this.end=C,this.loopingMode=c,this.isLooping=this.loopingMode===1||this.loopingMode===3}sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1},xe=class t{constructor(A,e,s,n,o,g,C,c,Q){this.sample=e,this.generators=c,this.modulatedGenerators=new Int16Array(c),this.modulators=Q,this.velocity=n,this.midiNote=s,this.channelNumber=o,this.startTime=g,this.targetKey=C,this.volumeEnvelope=new GA(A,c[a.sustainVolEnv])}sample;filter=new he;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new JA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;static copy(A,e){let s=A.sample,n=new ot(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new t(A.volumeEnvelope.sampleRate,n,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.generators,A.modulators.slice())}};function ho(t,A,e,s,n,o=!1){let g,C=s.cachedVoices[A][e];return C!==void 0?g=C.map(c=>xe.copy(c,n)):(g=s.preset.getSamplesAndGenerators(A,e).reduce((Q,u)=>{if(u.sample.sampleData===void 0)return N(`Discarding invalid sample: ${u.sample.sampleName}`),Q;let h=new Int16Array(60);for(let M=0;M<60;M++)h[M]=ys(M,u.presetGenerators,u.instrumentGenerators);h[a.initialAttenuation]=Math.floor(h[a.initialAttenuation]*.4);let l=u.sample.samplePitch;h[a.overridingRootKey]>-1&&(l=h[a.overridingRootKey]);let d=A;h[a.keyNum]>-1&&(d=h[a.keyNum]);let y=u.sample.sampleLoopStartIndex/2+(h[a.startloopAddrsOffset]+h[a.startloopAddrsCoarseOffset]*32768),D=u.sample.sampleLoopEndIndex/2+(h[a.endloopAddrsOffset]+h[a.endloopAddrsCoarseOffset]*32768),w=h[a.sampleModes],F=u.sample.getAudioData().length;y=Math.min(Math.max(0,y),F),D=Math.min(Math.max(0,D),F),D-y<1&&(w=0);let v=new ot(u.sample.getAudioData(),u.sample.sampleRate/sampleRate*Math.pow(2,u.sample.samplePitchCorrection/1200),h[a.startAddrsOffset]+h[a.startAddrsCoarseOffset]*32768,l,y,D,Math.floor(u.sample.sampleData.length)-1+(h[a.endAddrOffset]+h[a.endAddrsCoarseOffset]*32768),w);return h[a.velocity]>-1&&(e=h[a.velocity]),o&&cs([{Sample:u.sample.sampleName,Generators:h,Modulators:u.modulators.map(M=>M.debugString()),Velocity:e,TargetKey:d,MidiNote:A,WorkletSample:v}]),Q.push(new xe(sampleRate,v,A,e,t,n,d,h,u.modulators)),Q},[]),s.cachedVoices[A][e]=g.map(Q=>xe.copy(Q,n))),g}var bt=.07,Lt=1,L=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=TA,this.interpolationType=Fe.linear,this.processTickCallback=void 0,this.sequencer=new aA(this),this.transposition=0,this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Lt,this.midiVolume=1,this.voiceCap=us,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new nt(A.processorOptions.soundfont,this.postReady.bind(this))}catch(e){throw this.post({messageType:pA.soundfontError,messageData:e}),e}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let e=0;ethis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),VA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",r.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:pA.ready,messageData:void 0})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let s=0;return this.workletProcessorChannels.forEach((n,o)=>{if(n.voices.length<1||n.isMuted)return;let g,C,c,Q,u;if(this.oneOutputMode){let l=e[0];g=o%16*2,C=l[g],c=l[g+1]}else g=o%this._outputsAmount+2,C=e[g][0],c=e[g][1],Q=e[0],u=e[1];let h=n.voices;n.voices=[],h.forEach(l=>{this.renderVoice(n,l,C,c,Q,u),l.finished||n.voices.push(l)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};L.prototype.renderVoice=zs;L.prototype.releaseVoice=$s;L.prototype.voiceKilling=js;L.prototype.getWorkletVoices=ho;L.prototype.handleMessage=tn;L.prototype.sendChannelProperties=nn;L.prototype.callEvent=sn;L.prototype.systemExclusive=on;L.prototype.noteOn=an;L.prototype.noteOff=In;L.prototype.polyPressure=mn;L.prototype.killNote=gn;L.prototype.stopAll=Cn;L.prototype.stopAllChannels=En;L.prototype.muteChannel=wn;L.prototype.setVibrato=Rn;L.prototype.disableAndLockGSNRPN=Fn;L.prototype.dataEntryCoarse=Gn;L.prototype.dataEntryFine=xn;L.prototype.createWorkletChannel=Ds;L.prototype.controllerChange=Sn;L.prototype.channelPressure=fn;L.prototype.resetAllControllers=Mn;L.prototype.resetControllers=Nn;L.prototype.resetParameters=bn;L.prototype.setMasterGain=Dn;L.prototype.setMasterPan=kn;L.prototype.setMIDIVolume=yn;L.prototype.transposeAllChannels=Bn;L.prototype.transposeChannel=hn;L.prototype.setChannelTuning=Qn;L.prototype.setChannelTuningSemitones=cn;L.prototype.setMasterTuning=ln;L.prototype.setModulationDepth=un;L.prototype.pitchWheel=dn;L.prototype.setOctaveTuning=pn;L.prototype.programChange=no;L.prototype.getPreset=oo;L.prototype.setPreset=ro;L.prototype.setDrums=io;L.prototype.reloadSoundFont=go;L.prototype.clearSoundFont=Io;L.prototype.setEmbeddedSoundFont=Co;L.prototype.sendPresetList=ao;L.prototype.sendSynthesizerSnapshot=Eo;L.prototype.applySynthesizerSnapshot=Bo;registerProcessor(ls,L);m("%cProcessor succesfully registered!",r.recognized); +`+this.soundFontInfo.ISBJ,delete this.soundFontInfo.ISBJ);for(let[c,h]of Object.entries(this.soundFontInfo))m(`%c"${c}": %c"${h}"`,r.info,r.recognized);let o=n.find(c=>c.header==="colh");if(!o)throw X(),new Error("No colh chunk!");this.instrumentAmount=y(o.chunkData,4),m(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let I=DA(n,"wvpl");this.readDLSSamples(I);let C=DA(n,"lins");if(!C)throw X(),new Error("No lins chunk!");this.readDLSInstrumentList(C),this.presets.sort((c,h)=>c.program-h.program+(c.bank-h.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X()}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=Os;WA.prototype.readDLSInstrument=Zs;WA.prototype.readRegion=zs;WA.prototype.readLart=_s;WA.prototype.readDLSSamples=js;var Tt=class extends ue{constructor(A,e,n,s,o,I,C,c,h,u,Q,l,d){super(A,I,C,c,h,u,s-e,o-e),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=Q,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex,this.sampleLoopEndIndex+=this.sampleStartIndex,this.sampleLength=99999999),this.isDataRaw=d}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let e=A.currentIndex;return A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e)}else{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");let e=A.currentIndex;return A.slice(e+this.sampleStartIndex,e+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,e=A.currentIndex,n=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let s=VA.decode(n.buffer);this.sampleData=s.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return b("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let s=0;st.chunkData.currentIndex;){let o=Jo(s,t.chunkData,A,e);n.push(o),s++}return n.length>1&&n.pop(),n}function Jo(t,A,e,n){let s=O(A,20),o=y(A,4)*2,I=y(A,4)*2,C=y(A,4)*2,c=y(A,4)*2,h=y(A,4),u=A[A.currentIndex++];u===255&&(u=60);let Q=yn(A[A.currentIndex++]),l=y(A,2),d=y(A,2);return new Tt(s,o,I,C,c,h,u,Q,l,d,e,t,n)}var Ht=class extends le{constructor(A){super(),this.instrumentName=O(A.chunkData,20).trim(),this.instrumentZoneIndex=y(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;nt.chunkData.currentIndex;){let n=new Ht(t);if(e.length>0){let s=n.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(s,A)}e.push(n)}return e.length>1&&e.pop(),e}var Yt=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=y(A,2),this.modulatorZoneStartIndex=y(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;en.generatorType===a.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function eo(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Yt(t.chunkData);if(s.length>0){let I=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(I,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Jt=class extends ce{constructor(A){super(),this.generatorZoneStartIndex=y(A,2),this.modulatorZoneStartIndex=y(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;en.generatorType===a.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function to(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Jt(t.chunkData);if(s.length>0){let I=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(I,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var vt=class extends Qe{constructor(A,e){super(e),this.presetName=O(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=y(A.chunkData,2),this.bank=y(A.chunkData,2),this.presetZoneStartIndex=y(A.chunkData,2),this.library=y(A.chunkData,4),this.genre=y(A.chunkData,4),this.morphology=y(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let n=this.presetZoneStartIndex;nt.chunkData.currentIndex;){let s=new vt(t,e);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var nt=class extends se{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new H(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw X(),new TypeError("No data!");let n=Z(this.dataArray,!1);this.verifyHeader(n,"riff");let s=O(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw X(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",I=Z(this.dataArray);for(this.verifyHeader(I,"list"),O(I.chunkData,4);I.chunkData.length>I.chunkData.currentIndex;){let z=Z(I.chunkData),CA;switch(z.header.toLowerCase()){case"ifil":case"iver":CA=`${y(z.chunkData,2)}.${y(z.chunkData,2)}`,this.soundFontInfo[z.header]=CA;break;case"icmt":CA=O(z.chunkData,z.chunkData.length,void 0,!1),this.soundFontInfo[z.header]=CA;break;case"dmod":let oA=Xe(z);oA.pop(),CA=`Modulators: ${oA.length}`;let fA=this.defaultModulators;this.defaultModulators=oA,this.defaultModulators.push(...fA.filter(Me=>!this.defaultModulators.find(xA=>eA.isIdentical(Me,xA)))),this.soundFontInfo[z.header]=z.chunkData;break;default:CA=O(z.chunkData,z.chunkData.length),this.soundFontInfo[z.header]=CA}m(`%c"${z.header}": %c"${CA}"`,r.info,r.recognized)}let C=Z(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(O(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",r.warn);let c=Z(this.dataArray,!1);this.verifyHeader(c,"smpl");let h;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{h=VA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(z){throw X(),new Error(`SF2Pack Ogg Vorbis decode error: ${z}`)}m(`%cDecoded the smpl chunk! Length: %c${h.length}`,r.info,r.value)}else h=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,m("%cLoading preset data chunk...",r.warn);let u=Z(this.dataArray);this.verifyHeader(u,"list"),O(u.chunkData,4);let Q=Z(u.chunkData);this.verifyHeader(Q,"phdr");let l=Z(u.chunkData);this.verifyHeader(l,"pbag");let d=Z(u.chunkData);this.verifyHeader(d,"pmod");let S=Z(u.chunkData);this.verifyHeader(S,"pgen");let D=Z(u.chunkData);this.verifyHeader(D,"inst");let w=Z(u.chunkData);this.verifyHeader(w,"ibag");let F=Z(u.chunkData);this.verifyHeader(F,"imod");let v=Z(u.chunkData);this.verifyHeader(v,"igen");let M=Z(u.chunkData);this.verifyHeader(M,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...$s(M,h,!o));let q=pt(v),T=Xe(F),g=eo(w,q,T,this.samples);this.instruments=Ao(D,g);let AA=pt(S),P=Xe(d),j=to(l,AA,P,this.instruments);this.presets.push(...no(Q,j,this.defaultModulators)),this.presets.sort((z,CA)=>z.program-CA.program+(z.bank-CA.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X(),o&&delete this.dataArray}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Ge(t){let A=t.slice(8,12),e=new H(A);return O(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new nt(t,!1)}function so(t,A,e=!1){let n=this.workletProcessorChannels[t];if(n===void 0){b(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(n.lockPreset)return;let s=n.drumChannel?128:n.midiControllers[p.bankSelect],o,I;if(this.overrideSoundfont){let C=s===128?128:s-this.soundfontBankOffset,c=this.overrideSoundfont.getPresetNoFallback(C,A);c?(o=s,I=c,n.presetUsesOverride=!0):(I=this.soundfontManager.getPreset(s,A),o=I.bank,n.presetUsesOverride=!1)}else I=this.soundfontManager.getPreset(s,A),o=I.bank,n.presetUsesOverride=!1;this.setPreset(t,I),this.callEvent("programchange",{channel:t,program:I.program,bank:o,userCalled:e})}function oo(t,A){if(this.overrideSoundfont){let e=t===128?128:t-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(e,A);if(n)return n}return this.soundfontManager.getPreset(t,A)}function ro(t,A){if(!this.workletProcessorChannels[t].lockPreset){delete this.workletProcessorChannels[t].preset,this.workletProcessorChannels[t].preset=A,this.workletProcessorChannels[t].cachedVoices=[];for(let e=0;e<128;e++)this.workletProcessorChannels[t].cachedVoices.push([])}}function io(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(128,e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(e.midiControllers[p.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function ao(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,n=t.find(s=>s.bank===e&&s.program===A.program);n!==void 0?n.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function Io(t=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let e=0;e{this.programChange(n,e.preset.program)}),this.post({messageType:pA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",r.recognized)}function Co(t,A){this.soundfontBankOffset=A,this.reloadSoundFont(t,!0),this.overrideSoundfont.samples.forEach(e=>e.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function Eo(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:e.preset.bank,lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:pA.synthesizerSnapshot,messageData:A})}function Bo(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation;this.workletProcessorChannels.length{let n=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),n.midiControllers=A.midiControllers,n.lockedControllers=A.lockedControllers,n.customControllers=A.customControllers,n.channelVibrato=A.channelVibrato,n.lockGSNRPNParams=A.lockVibrato,n.channelTransposeKeyShift=A.channelTransposeKeyShift,n.channelOctaveTuning=A.channelOctaveTuning,n.lockPreset=!1,n.midiControllers[p.bankSelect]=A.bank,this.programChange(e,A.program),n.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",r.info)}var st=class{constructor(A,e){this.ready=e,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(e=>{e.soundfont.setSampleIDOffset(A),A+=e.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let e=this.soundfontList.length-1;e>=0;e--){let n=this.soundfontList[e],s=new Set;for(let o of n.soundfont.presets){let I=`${o.bank+n.bankOffset}-${o.program}`;s.has(I)||(s.add(I),A[I]=o.presetName)}}this.presetList=[];for(let[e,n]of Object.entries(A)){let s=e.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}}handleMessage(A,e){switch(A){case Ie.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ie.reloadSoundFont:this.reloadManager(e);break;case Ie.deleteSoundFont:this.deleteSoundFont(e);break;case Ie.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ge(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){b("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(n=>n.id===A);if(e===-1){b(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[e].soundfont.presets,delete this.soundfontList[e].soundfont.instruments,delete this.soundfontList[e].soundfont.samples,this.soundfontList.splice(e,1),this.generatePresetList()}addNewSoundFont(A,e,n){if(this.soundfontList.find(s=>s.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Ge(A),bankOffset:n}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,n)=>A.indexOf(e.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let n of this.soundfontList){let s=n.soundfont.getPresetNoFallback(A-n.bankOffset,e);if(s!==void 0)return s}if(A!==128){for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.program===e);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}else{for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.bank===128);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}}};var ot=class{constructor(A,e,n,s,o,I,C,c){this.sampleData=A,this.playbackStep=e,this.cursor=n,this.rootKey=s,this.loopStart=o,this.loopEnd=I,this.end=C,this.loopingMode=c,this.isLooping=this.loopingMode===1||this.loopingMode===3}sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1},xe=class t{constructor(A,e,n,s,o,I,C,c,h){this.sample=e,this.generators=c,this.modulatedGenerators=new Int16Array(c),this.modulators=h,this.velocity=s,this.midiNote=n,this.channelNumber=o,this.startTime=I,this.targetKey=C,this.volumeEnvelope=new GA(A,c[a.sustainVolEnv])}sample;filter=new he;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new JA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;static copy(A,e){let n=A.sample,s=new ot(n.sampleData,n.playbackStep,n.cursor,n.rootKey,n.loopStart,n.loopEnd,n.end,n.loopingMode);return new t(A.volumeEnvelope.sampleRate,s,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.generators,A.modulators.slice())}};function ho(t,A,e,n,s,o=!1){let I,C=n.cachedVoices[A][e];return C!==void 0?I=C.map(c=>xe.copy(c,s)):(I=n.preset.getSamplesAndGenerators(A,e).reduce((h,u)=>{if(u.sample.sampleData===void 0)return b(`Discarding invalid sample: ${u.sample.sampleName}`),h;let Q=new Int16Array(60);for(let M=0;M<60;M++)Q[M]=Dn(M,u.presetGenerators,u.instrumentGenerators);Q[a.initialAttenuation]=Math.floor(Q[a.initialAttenuation]*.4);let l=u.sample.samplePitch;Q[a.overridingRootKey]>-1&&(l=Q[a.overridingRootKey]);let d=A;Q[a.keyNum]>-1&&(d=Q[a.keyNum]);let S=u.sample.sampleLoopStartIndex/2+(Q[a.startloopAddrsOffset]+Q[a.startloopAddrsCoarseOffset]*32768),D=u.sample.sampleLoopEndIndex/2+(Q[a.endloopAddrsOffset]+Q[a.endloopAddrsCoarseOffset]*32768),w=Q[a.sampleModes],F=u.sample.getAudioData().length;S=Math.min(Math.max(0,S),F),D=Math.min(Math.max(0,D),F),D-S<1&&(w=0);let v=new ot(u.sample.getAudioData(),u.sample.sampleRate/sampleRate*Math.pow(2,u.sample.samplePitchCorrection/1200),Q[a.startAddrsOffset]+Q[a.startAddrsCoarseOffset]*32768,l,S,D,Math.floor(u.sample.sampleData.length)-1+(Q[a.endAddrOffset]+Q[a.endAddrsCoarseOffset]*32768),w);return Q[a.velocity]>-1&&(e=Q[a.velocity]),o&&ln([{Sample:u.sample.sampleName,Generators:Q,Modulators:u.modulators.map(M=>M.debugString()),Velocity:e,TargetKey:d,MidiNote:A,WorkletSample:v}]),h.push(new xe(sampleRate,v,A,e,t,s,d,Q,u.modulators)),h},[]),n.cachedVoices[A][e]=I.map(h=>xe.copy(h,s))),I}var bt=.07,Lt=1,U=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=TA,this.interpolationType=Fe.linear,this.processTickCallback=void 0,this.sequencer=new aA(this),this.transposition=0,this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Lt,this.midiVolume=1,this.voiceCap=dn,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new st(A.processorOptions.soundfont,this.postReady.bind(this))}catch(e){throw this.post({messageType:pA.soundfontError,messageData:e}),e}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let e=0;ethis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),VA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",r.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:pA.ready,messageData:void 0})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let n=0;return this.workletProcessorChannels.forEach((s,o)=>{if(s.voices.length<1||s.isMuted)return;let I,C,c,h,u;if(this.oneOutputMode){let l=e[0];I=o%16*2,C=l[I],c=l[I+1]}else I=o%this._outputsAmount+2,C=e[I][0],c=e[I][1],h=e[0],u=e[1];let Q=s.voices;s.voices=[],Q.forEach(l=>{this.renderVoice(s,l,C,c,h,u),l.finished||s.voices.push(l)}),n+=s.voices.length}),n!==this.totalVoicesAmount&&(this.totalVoicesAmount=n,this.sendChannelProperties()),!0}};U.prototype.renderVoice=jn;U.prototype.releaseVoice=As;U.prototype.voiceKilling=$n;U.prototype.getWorkletVoices=ho;U.prototype.handleMessage=ns;U.prototype.sendChannelProperties=os;U.prototype.callEvent=ss;U.prototype.systemExclusive=rs;U.prototype.noteOn=as;U.prototype.noteOff=Is;U.prototype.polyPressure=ms;U.prototype.killNote=gs;U.prototype.stopAll=Cs;U.prototype.stopAllChannels=Es;U.prototype.muteChannel=ws;U.prototype.setVibrato=Rs;U.prototype.disableAndLockGSNRPN=Fs;U.prototype.dataEntryCoarse=Gs;U.prototype.dataEntryFine=xs;U.prototype.createWorkletChannel=kn;U.prototype.controllerChange=Ss;U.prototype.channelPressure=fs;U.prototype.resetAllControllers=Ms;U.prototype.resetControllers=Ns;U.prototype.resetParameters=bs;U.prototype.setMasterGain=Ds;U.prototype.setMasterPan=ks;U.prototype.setMIDIVolume=ys;U.prototype.transposeAllChannels=Bs;U.prototype.transposeChannel=hs;U.prototype.setChannelTuning=Qs;U.prototype.setChannelTuningSemitones=cs;U.prototype.setMasterTuning=ls;U.prototype.setModulationDepth=us;U.prototype.pitchWheel=ds;U.prototype.setOctaveTuning=ps;U.prototype.programChange=so;U.prototype.getPreset=oo;U.prototype.setPreset=ro;U.prototype.setDrums=io;U.prototype.reloadSoundFont=go;U.prototype.clearSoundFont=Io;U.prototype.setEmbeddedSoundFont=Co;U.prototype.sendPresetList=ao;U.prototype.sendSynthesizerSnapshot=Eo;U.prototype.applySynthesizerSnapshot=Bo;registerProcessor(un,U);m("%cProcessor succesfully registered!",r.recognized); diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_modulator.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_modulator.js index cccccbd8..cc450d0a 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_modulator.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_modulator.js @@ -1,7 +1,7 @@ import { modulatorSources } from '../../../soundfont/read_sf2/modulators.js' import { getModulatorCurveValue, MOD_PRECOMPUTED_LENGTH } from './modulator_curves.js' import { NON_CC_INDEX_OFFSET } from './worklet_processor_channel.js' -import { generatorTypes } from '../../../soundfont/read_sf2/generators.js' +import { generatorLimits, generatorTypes } from '../../../soundfont/read_sf2/generators.js' import { WorkletVolumeEnvelope } from './volume_envelope.js' import { WorkletModulationEnvelope } from './modulation_envelope.js' @@ -123,7 +123,10 @@ export function computeModulators(voice, controllerTable, sourceUsesCC = -1, sou // All modulators mode: compute all modulators modulatedGenerators.set(generators); modulators.forEach(mod => { - modulatedGenerators[mod.modulatorDestination] += computeWorkletModulator(controllerTable, mod, voice); + const limits = generatorLimits[mod.modulatorDestination]; + if(modulatedGenerators[mod.modulatorDestination] === limits.min || modulatedGenerators[mod.modulatorDestination] === limits.max) return; + const newValue = modulatedGenerators[mod.modulatorDestination] + computeWorkletModulator(controllerTable, mod, voice); + modulatedGenerators[mod.modulatorDestination] = Math.max(limits.min, Math.min(newValue, limits.max)); }); WorkletVolumeEnvelope.recalculate(voice); return; @@ -158,7 +161,11 @@ export function computeModulators(voice, controllerTable, sourceUsesCC = -1, sou modulators.forEach(m => { if (m.modulatorDestination === destination) { - modulatedGenerators[destination] += computeWorkletModulator(controllerTable, m, voice); + const limits = generatorLimits[mod.modulatorDestination]; + const current = modulatedGenerators[mod.modulatorDestination]; + if(current === limits.min || current === limits.max) return; + const newValue = current + computeWorkletModulator(controllerTable, m, voice); + modulatedGenerators[mod.modulatorDestination] = Math.max(limits.min, Math.min(newValue, limits.max)); } }); computedDestinations.add(destination); @@ -183,16 +190,16 @@ const transforms = []; for(let curve = 0; curve < 4; curve++) { transforms[curve] = - [ [ - new Float32Array(MOD_PRECOMPUTED_LENGTH), - new Float32Array(MOD_PRECOMPUTED_LENGTH) - ], - [ - new Float32Array(MOD_PRECOMPUTED_LENGTH), - new Float32Array(MOD_PRECOMPUTED_LENGTH) - ] - ]; + [ + new Float32Array(MOD_PRECOMPUTED_LENGTH), + new Float32Array(MOD_PRECOMPUTED_LENGTH) + ], + [ + new Float32Array(MOD_PRECOMPUTED_LENGTH), + new Float32Array(MOD_PRECOMPUTED_LENGTH) + ] + ]; for (let i = 0; i < MOD_PRECOMPUTED_LENGTH; i++) { // polarity 0 dir 0 diff --git a/src/website/minified/demo_main.min.js b/src/website/minified/demo_main.min.js index c789db5a..46ce5c73 100644 --- a/src/website/minified/demo_main.min.js +++ b/src/website/minified/demo_main.min.js @@ -1,5 +1,5 @@ var EC=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(r,l)=>(typeof require<"u"?require:r)[l]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var Y3=class extends Uint8Array{constructor(r){super(r),this.currentIndex=0}currentIndex};function wn(o){let r=o.reduce((u,b)=>u+b.length,0),l=new Y3(r),g=0;for(let u of o)l.set(u,g),g+=u.length;return l}function I$(o){o=Math.floor(o);let r=Math.floor(o/60),l=Math.round(o-r*60);return{minutes:r,seconds:l,time:`${r.toString().padStart(2,"0")}:${l.toString().padStart(2,"0")}`}}function LB(o){return o.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}var b1={warn:"color: orange;",unrecognized:"color: red;",info:"color: aqua;",recognized:"color: lime",value:"color: yellow; background-color: black;"};var Ii=class{constructor(r,l,g){this.ticks=r,this.messageStatusByte=l,this.messageData=g}};var J3={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 WQ(o){let r=o&240,l=o&15,g=-1,u=o;return r>=128&&r<=224&&(g=l,u=r),{status:u,channel:g}}var A6={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,effects1Depth:91,effects2Depth:92,effects3Depth:93,effects4Depth:94,effects5Depth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127};var mC=class{constructor(){this.events={noteoff:{},noteon:{},pitchwheel:{},controllerchange:{},programchange:{},channelpressure:{},polypressure:{},drumchange:{},stopall:{},newchannel:{},mutechannel:{},presetlistchange:{},allcontrollerreset:{},soundfonterror:{}}}addEvent(r,l,g){this.events[r][l]=g}removeEvent(r,l){delete this.events[r][l]}callEvent(r,l){this.events[r]&&Object.values(this.events[r]).forEach(g=>g(l))}};var FB={nodesAmount:4,defaultDelay:.03,delayVariation:.01,stereoDifference:.02,oscillatorFrequency:.3,oscillatorFrequencyVariation:.05,oscillatorGain:.003},CC=class{constructor(r,l=FB){let g=r.context;this.input=new ChannelSplitterNode(g,{numberOfOutputs:2});let u=new ChannelMergerNode(g,{numberOfInputs:2}),b=[],g0=[],v0=l.oscillatorFrequency,p0=l.defaultDelay;for(let f0=0;f0{let b=await u.arrayBuffer();l.buffer=await o.decodeAudioData(b)})}return l}var Q8={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25},Qm={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},Ei=-1,E$={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var QD=!0,yD=!0,MB=!0;function J5(...o){QD&&console.info(...o)}function R4(...o){yD&&console.warn(...o)}function cr(...o){MB&&console.group(...o)}function ii(...o){MB&&console.groupCollapsed(...o)}function i4(){MB&&console.groupEnd()}var XQ={chorusEnabled:!0,chorusConfig:FB,reverbEnabled:!0,reverbImpulseResponse:void 0};var ym={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var BC=class{constructor(r){this.soundfontList=[{id:"main",bankOffset:0}],this._port=r.worklet.port,this.synth=r}_sendToWorklet(r,l){this._port.postMessage({messageType:Q8.soundFontManager,messageData:[r,l]})}async addNewSoundFont(r,l,g=0){if(this.soundfontList.find(u=>u.id===l)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this._sendToWorklet(ym.addNewSoundFont,[r,l,g]),await new Promise(u=>this.synth.resolveWhenReady=u),this.soundfontList.push({id:l,bankOffset:g})}deleteSoundFont(r){if(this.soundfontList.length===0){R4("1 soundfont left. Aborting!");return}if(this.soundfontList.findIndex(l=>l.id===r)===-1){R4(`No soundfont with id of "${r}" found. Aborting!`);return}this._sendToWorklet(ym.deleteSoundFont,r)}rearrangeSoundFonts(r){this._sendToWorklet(ym.rearrangeSoundFonts,r),this.soundfontList.sort((l,g)=>r.indexOf(l.id)-r.indexOf(g.id))}async reloadManager(r){this._sendToWorklet(ym.reloadSoundFont,r),await new Promise(l=>this.synth.resolveWhenReady=l)}};var wD="spessasynth-worklet-system",TB=450,Si=9,kD=16;var ch=class{constructor(r,l,g=!0,u=void 0,b=XQ){J5("%cInitializing SpessaSynth synthesizer...",b1.info),this.context=r.context;let g0=u?.oneOutput===!0;this.eventHandler=new mC,this._voiceCap=TB,this._outputsAmount=kD,this.channelsAmount=this._outputsAmount,this.resolveWhenReady=void 0,this.isReady=new Promise(f0=>this.resolveWhenReady=f0),this.channelProperties=[];for(let f0=0;f0this.handleMessage(f0.data),this.soundfontManager=new BC(this),this._snapshotCallback=void 0,this.sequencerCallbackFunction=void 0,b.reverbEnabled&&!g0&&(this.reverbProcessor=jQ(this.context,b.reverbImpulseResponse),this.reverbProcessor.connect(r),this.worklet.connect(this.reverbProcessor,0)),b.chorusEnabled&&!g0&&(this.chorusProcessor=new CC(r,b.chorusConfig),this.worklet.connect(this.chorusProcessor.input,1)),g0)this.worklet.connect(r,0);else for(let f0=2;f0{this.channelsAmount++})}get voiceCap(){return this._voiceCap}set voiceCap(r){this._setMasterParam(Qm.voicesCap,r),this._voiceCap=r}set highPerformanceMode(r){this._highPerformanceMode=r}get highPerformanceMode(){return this._highPerformanceMode}setLogLevel(r,l,g,u){this.post({channelNumber:Ei,messageType:Q8.setLogLevel,messageData:[r,l,g,u]})}_setMasterParam(r,l){this.post({channelNumber:Ei,messageType:Q8.setMasterParameter,messageData:[r,l]})}setInterpolationType(r){this._setMasterParam(Qm.interpolationType,r)}handleMessage(r){let l=r.messageData;switch(r.messageType){case E$.channelProperties:this.channelProperties=l,this._voicesAmount=this.channelProperties.reduce((g,u)=>g+u.voicesAmount,0);break;case E$.eventCall:this.eventHandler.callEvent(l.eventName,l.eventData);break;case E$.sequencerSpecific:this.sequencerCallbackFunction&&this.sequencerCallbackFunction(l.messageType,l.messageData);break;case E$.synthesizerSnapshot:this._snapshotCallback&&this._snapshotCallback(l);break;case E$.ready:this.resolveWhenReady();break;case E$.soundfontError:R4(new Error(l)),this.eventHandler.callEvent("soundfonterror",l);break}}async getSynthesizerSnapshot(){return new Promise(r=>{this._snapshotCallback=l=>{this._snapshotCallback=void 0,r(l)},this.post({messageType:Q8.requestSynthesizerSnapshot,messageData:void 0,channelNumber:Ei})})}addNewChannel(r=!0){this.channelProperties.push({voicesAmount:0,pitchBend:0,pitchBendRangeSemitones:0,isMuted:!1,isDrum:!1}),r&&this.post({channelNumber:0,messageType:Q8.addNewChannel,messageData:null})}setVibrato(r,l){this.post({channelNumber:r,messageType:Q8.setChannelVibrato,messageData:l})}connectIndividualOutputs(r){if(r.length!==this._outputsAmount)throw new Error(`input nodes amount differs from the system's outputs amount! - Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case J3.noteOff:this.noteOff(l.channel,r[1]);break;case J3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case J3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case J3.programChange:this.programChange(l.channel,r[1]);break;case J3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case J3.channelPressure:this.channelPressure(l.channel,r[1]);break;case J3.systemExclusive:this.systemExclusive(new Y3(r.slice(1)));break;case J3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}get currentTime(){return this.context.currentTime}get voicesAmount(){return this._voicesAmount}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,u)=>{let b;if(kn)b=127;else{let v0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=u.clientX-v0.left,f0=v0.width;b=Math.floor((f0-p0)/f0*127)}else{let p0=u.clientY-v0.top,f0=v0.height;b=Math.floor(p0/f0*127)}}this.synth.noteOn(this.channel,g,b,this.enableDebugging)},l=g=>{let u=g.touches?Array.from(g.touches):[g],b=new Set;u.forEach(g0=>{let v0=document.elementFromPoint(g0.clientX,g0.clientY),p0=parseInt(v0.id.replace("note",""));b.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,g0))}),this.pressedKeys.forEach(g0=>{b.has(g0)||o(g0)})};kn||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var ty=20,wm=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,A6.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,A6.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let u=0;u<128;u++)this.releaseNote(u,g.channel)})}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get shown(){return this._shown}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(b=l(r-1)),r<127&&(g0=l(r+1)),g0&&b?g.classList.add("between_sharps"):b?g.classList.add("left_sharp"):g0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let u=900/(r.max-r.min+5),b=document.styleSheets[0].cssRules,g0;for(let v0 of b)if(v0.selectorText==="#keyboard .key"){g0=v0;break}if(g0.style.setProperty("--pressed-transform-skew",`${8e-4/(u/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let v0=getComputedStyle(this.keyboard),p0=parseFloat(v0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),f0=this.keyboard.getBoundingClientRect().height,d1=u/p0,L=f0*d1-f0,t1=(this._keyRange.min+this._keyRange.max)/2,H0=(r.min+r.max)/2;this._keyRange=r;let S1=this.keys.find(q2=>q2.classList.contains("sharp_key")).getBoundingClientRect().width,m2=(t1-H0)*S1,_1=parseFloat(v0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${L}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${d1}) translateX(${m2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${_1/d1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${u}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${u}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let u=this.keys[r-this._keyRange.min];if(u===void 0)return;u.classList.add("pressed");let b=u.classList.contains("sharp_key"),g0=g/127,v0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!b&&this.mode==="light"?p0=`rgba(${v0.slice(0,3).map(d1=>255-(255-d1)*g0).join(", ")}, ${v0[3]})`:p0=`rgba(${v0.slice(0,3).map(d1=>d1*g0).join(", ")}, ${v0[3]})`,u.style.background=p0,this.mode==="dark"){let f0=ty*g0;u.style.boxShadow=`${p0} 0px 0px ${f0}px ${f0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let u=this.keyColors[r-this._keyRange.min];if(!u)return;let b=u.findLastIndex(g0=>g0===this.channelColors[l]);b!==-1&&(u.splice(b,1),g.style.background=u[u.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${ty}px ${u[u.length-1]}`),u.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};wm.prototype._handlePointers=ey;function m$(o,r){let l=o.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var SD="#000";function iy(o,r,l){o.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let u=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*u,l){r.fillRect(g.xPos,g.yPos-g.height*u,g.width,g.height*(u*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*u,g.yPos,g.width*(u*2+1),g.height),r.globalAlpha=1}),o.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=SD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var NB=!1;function ry(o=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(NB){o&&requestAnimationFrame(this.render.bind(this));return}else NB=!0;else NB=!1;if(o&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let b=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||iy(b,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let u=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${pC}px system-ui`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,pC*2+5),this.drawingContext.fillText(this.version,this.canvas.width,5),this.drawingContext.fillText(Math.round(u).toString()+" FPS",this.canvas.width,pC+5),this.onRender&&this.onRender(),o&&requestAnimationFrame(this.render.bind(this))}function ny(o=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,u=r/(g+1),b=u-B$*2,g0=this.noteFallingTimeMs/1e3,v0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,f0=p0-v0,d1=g0+v0,L=f0+d1,t1=oy/d1,H0=[];this.synth.channelProperties.forEach(m2=>{if(this.showVisualPitch){let _1=m2.pitchBend-8192+this.visualPitchBendOffset;H0.push(m2.pitchBendRangeSemitones*(_1/8192*u))}else H0.push(0)});let S1=[];return this.noteTimes.forEach((m2,_1)=>{if(m2.renderStartIndex>=m2.notes.length||!this.renderChannels[_1])return;let q2=m2.renderStartIndex,r3=m2.notes,$2=r3[q2],Y5=-1;for(;$2.start<=L&&(q2++,!(this.notesOnScreen>Ay));){let O5=$2.start+$2.length;if(O5>f0&&$2.length>0){let A0=$2.length/d1*l-B$*2;if(this.notesOnScreen<1e3||A0>t1){Y5===-1&&(Y5=q2-1);let i5=($2.start-f0)/d1*l,g3;if(this._notesFall?g3=l-A0-i5+B$:g3=i5+B$,$2.midiNotethis.keyRange.max){if(q2>=r3.length)break;$2=r3[q2];continue}let e6=$2.midiNote-this.keyRange.min,J6=u*e6+B$,$6,o9,K4,r4;if(this.sideways?($6=g3,o9=J6,r4=b,K4=A0):(o9=g3,$6=J6,K4=b,r4=A0),this.notesOnScreen++,o)this.drawingContext.fillStyle=this.plainColors[_1],this.drawingContext.fillRect($6+C$+B$,o9+C$,K4-C$*2,r4-C$*2);else{let K6;if($2.start>p0||O5=r3.length)break;$2=r3[q2]}Y5>-1&&(m2.renderStartIndex=Y5)}),S1.sort((m2,_1)=>_1.height-m2.height),S1}function ay(){let o=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let u=g%4,b=Math.floor(g/4),g0=!1;for(let L=g;L0){g0=!0;break}if(!g0){let L=this.canvas.width/4,t1=this.canvas.height/4,H0=L*u,S1=t1*b+t1/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(H0,S1),this.drawingContext.lineTo(H0+L,S1),this.drawingContext.stroke();return}let v0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(v0);let p0=o*u,f0=r*b+r/2,d1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let L=v0.length/4,t1=o/L,H0=Math.floor(L/2),S1=v0.length-H0;for(let r3=S1;r3>=1;r3--)if(v0[r3-1]<0&&v0[r3]>=0){S1=r3;break}let m2=p0,_1=S1-H0,q2=S1+H0;for(let r3=_1;r3{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function cy(){for(let o=0;o4096?this.delayNode.delayTime.value=u/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function gy(o){o.connectIndividualOutputs(this.channelAnalysers),o.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{this.updateFftSize()})}function hy(){for(let o of this.channelAnalysers)o.disconnect();J5("%cAnalysers disconnected!",b1.recognized)}function fy(o){this.seq=o,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),u=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${u}), rgba(0, 0, 0, ${u})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function uy(){this.noteTimes&&this.noteTimes.forEach(o=>o.renderStartIndex=0)}function GB(o,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=o[o.currentIndex++]<>>0}function km(o,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=o&255,o>>=8;return l}var gh=.02;function dy(o){function r(f0){return f0.messageData=new Y3(f0.messageData.buffer),f0.messageData.currentIndex=0,6e7/GB(f0.messageData,3)}let l=[],u=o.tracks.flat();u.sort((f0,d1)=>f0.ticks-d1.ticks);for(let f0=0;f0<16;f0++)l.push({renderStartIndex:0,notes:[]});let b=0,g0=60/(120*o.timeDivision),v0=0,p0=0;for(;v0>4,L=f0.messageStatusByte&15;if(d1===8){let t1=l[L].notes.findLast(H0=>H0.midiNote===f0.messageData[0]&&H0.length===-1);if(t1){let H0=b-t1.start;t1.length=H0H0.midiNote===f0.messageData[0]&&H0.length===-1);if(t1){let H0=b-t1.start;t1.length=H0=u.length)break;b+=g0*(u[v0].ticks-f0.ticks)}p0>0&&l.forEach((f0,d1)=>f0.notes.filter(L=>L.length===-1).forEach(L=>{let t1=b-L.start;L.length=t1{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,m$(r,g=>g*yC)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,m$(r,g=>g*yC*QC)),l.addColorStop(1,m$(r,g=>g*QC)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,m$(r,g=>g*yC)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,m$(r,g=>g*yC*QC)),l.addColorStop(1,m$(r,g=>g*QC)),l})}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}onRender;get normalAnalyserFft(){return this._normalAnalyserFft}set normalAnalyserFft(r){this._normalAnalyserFft=r,this.updateFftSize()}get drumAnalyserFft(){return this._drumAnalyserFft}set drumAnalyserFft(r){this._drumAnalyserFft=r,this.updateFftSize()}get renderBool(){return this._renderBool}set renderBool(r){this._renderBool=r,r===!0?this.connectChannelAnalysers(this.synth):this.disconnectChannelAnalysers()}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}};Di.prototype.render=ry;Di.prototype.computeNotePositions=ny;Di.prototype.createChannelAnalysers=ly;Di.prototype.updateFftSize=cy;Di.prototype.connectChannelAnalysers=gy;Di.prototype.disconnectChannelAnalysers=hy;Di.prototype.connectSequencer=fy;Di.prototype.calculateNoteTimes=dy;Di.prototype.resetIndexes=uy;Di.prototype.renderWaveforms=ay;function o3(o,r){let l=0;for(let g=0;g>>0}function lt(o,r,l){for(let g=0;g>g*8&255}function Q9(o,r){o[o.currentIndex++]=r&255,o[o.currentIndex++]=r>>8}function ct(o,r){lt(o,r,4)}function RA(o,r){let l=r<<8|o;return l>32767?l-65536:l}function Iy(o){return o>127?o-256:o}function de(o,r,l=void 0,g=!0){if(l){let u=o.slice(o.currentIndex,o.currentIndex+r);return o.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(u.buffer)}else{let u=!1,b="";for(let g0=0;g0127){if(g){u=!0;continue}else if(v0===0){u=!0;continue}}b+=String.fromCharCode(v0)}}return b}}function xA(o,r=0){let l=o.length;r>0&&(l=r);let g=new Y3(l);return gt(g,o,r),g}function gt(o,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,de(l.chunkData,4)===r))}function wC(o){let r=[o&127];for(o>>=7;o>0;)r.unshift(o&127|128),o>>=7;return r}function kC(o){let r=[];for(let u of o.tracks){let b=[],g0=0,v0;for(let p0 of u){let f0=p0.ticks-g0,d1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?d1=[255,p0.messageStatusByte,...wC(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?d1=[240,...wC(p0.messageData.length),...p0.messageData]:(d1=[],v0!==p0.messageStatusByte&&(v0=p0.messageStatusByte,d1.push(p0.messageStatusByte)),d1.push(...p0.messageData)),b.push(...wC(f0)),b.push(...d1),g0+=f0}r.push(new Uint8Array(b))}function l(u,b){for(let g0=0;g0o.chunkData.currentIndex;)r.push(new UB(o.chunkData));return r.length>1&&r.pop(),r}var F7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Sn={linear:0,concave:1,convex:2,switch:3},xD=[];for(let o=0;o<4;o++)xD.push([[],[]]);var ke=class o{constructor(r){r.srcEnum?(this.sourceEnum=r.srcEnum,this.modulatorDestination=r.dest,this.secondarySourceEnum=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.sourceEnum=o3(r,2),this.modulatorDestination=o3(r,2),this.transformAmount=RA(r[r.currentIndex++],r[r.currentIndex++]),this.secondarySourceEnum=o3(r,2),this.transformType=o3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=v1.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(r){return new o({srcEnum:r.sourceEnum,secSrcEnum:r.secondarySourceEnum,transform:r.transformType,amt:r.transformAmount,dest:r.modulatorDestination})}static isIdentical(r,l){return r.sourceEnum===l.sourceEnum&&r.modulatorDestination===l.modulatorDestination&&r.secondarySourceEnum===l.secondarySourceEnum&&r.transformType===l.transformType}sumTransform(r){return new o({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(u,b){return Object.keys(u).find(g0=>u[g0]===b)}let l=r(Sn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(A6,this.sourceIndex):l+=r(F7,this.sourceIndex);let g=r(Sn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(A6,this.secSrcIndex):g+=r(F7,this.secSrcIndex),`Modulator: + Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case J3.noteOff:this.noteOff(l.channel,r[1]);break;case J3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case J3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case J3.programChange:this.programChange(l.channel,r[1]);break;case J3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case J3.channelPressure:this.channelPressure(l.channel,r[1]);break;case J3.systemExclusive:this.systemExclusive(new Y3(r.slice(1)));break;case J3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}get currentTime(){return this.context.currentTime}get voicesAmount(){return this._voicesAmount}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,u)=>{let b;if(kn)b=127;else{let v0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=u.clientX-v0.left,f0=v0.width;b=Math.floor((f0-p0)/f0*127)}else{let p0=u.clientY-v0.top,f0=v0.height;b=Math.floor(p0/f0*127)}}this.synth.noteOn(this.channel,g,b,this.enableDebugging)},l=g=>{let u=g.touches?Array.from(g.touches):[g],b=new Set;u.forEach(g0=>{let v0=document.elementFromPoint(g0.clientX,g0.clientY),p0=parseInt(v0.id.replace("note",""));b.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,g0))}),this.pressedKeys.forEach(g0=>{b.has(g0)||o(g0)})};kn||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var ty=20,wm=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,A6.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,A6.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let u=0;u<128;u++)this.releaseNote(u,g.channel)})}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get shown(){return this._shown}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(b=l(r-1)),r<127&&(g0=l(r+1)),g0&&b?g.classList.add("between_sharps"):b?g.classList.add("left_sharp"):g0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let u=900/(r.max-r.min+5),b=document.styleSheets[0].cssRules,g0;for(let v0 of b)if(v0.selectorText==="#keyboard .key"){g0=v0;break}if(g0.style.setProperty("--pressed-transform-skew",`${8e-4/(u/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let v0=getComputedStyle(this.keyboard),p0=parseFloat(v0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),f0=this.keyboard.getBoundingClientRect().height,d1=u/p0,L=f0*d1-f0,t1=(this._keyRange.min+this._keyRange.max)/2,H0=(r.min+r.max)/2;this._keyRange=r;let S1=this.keys.find(q2=>q2.classList.contains("sharp_key")).getBoundingClientRect().width,m2=(t1-H0)*S1,_1=parseFloat(v0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${L}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${d1}) translateX(${m2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${_1/d1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${u}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${u}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let u=this.keys[r-this._keyRange.min];if(u===void 0)return;u.classList.add("pressed");let b=u.classList.contains("sharp_key"),g0=g/127,v0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!b&&this.mode==="light"?p0=`rgba(${v0.slice(0,3).map(d1=>255-(255-d1)*g0).join(", ")}, ${v0[3]})`:p0=`rgba(${v0.slice(0,3).map(d1=>d1*g0).join(", ")}, ${v0[3]})`,u.style.background=p0,this.mode==="dark"){let f0=ty*g0;u.style.boxShadow=`${p0} 0px 0px ${f0}px ${f0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let u=this.keyColors[r-this._keyRange.min];if(!u)return;let b=u.findLastIndex(g0=>g0===this.channelColors[l]);b!==-1&&(u.splice(b,1),g.style.background=u[u.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${ty}px ${u[u.length-1]}`),u.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};wm.prototype._handlePointers=ey;function m$(o,r){let l=o.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var SD="#000";function iy(o,r,l){o.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let u=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*u,l){r.fillRect(g.xPos,g.yPos-g.height*u,g.width,g.height*(u*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*u,g.yPos,g.width*(u*2+1),g.height),r.globalAlpha=1}),o.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=SD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var NB=!1;function ry(o=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(NB){o&&requestAnimationFrame(this.render.bind(this));return}else NB=!0;else NB=!1;if(o&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let b=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||iy(b,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let u=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${pC}px system-ui`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,pC*2+5),this.drawingContext.fillText(this.version,this.canvas.width,5),this.drawingContext.fillText(Math.round(u).toString()+" FPS",this.canvas.width,pC+5),this.onRender&&this.onRender(),o&&requestAnimationFrame(this.render.bind(this))}function ny(o=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,u=r/(g+1),b=u-B$*2,g0=this.noteFallingTimeMs/1e3,v0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,f0=p0-v0,d1=g0+v0,L=f0+d1,t1=oy/d1,H0=[];this.synth.channelProperties.forEach(m2=>{if(this.showVisualPitch){let _1=m2.pitchBend-8192+this.visualPitchBendOffset;H0.push(m2.pitchBendRangeSemitones*(_1/8192*u))}else H0.push(0)});let S1=[];return this.noteTimes.forEach((m2,_1)=>{if(m2.renderStartIndex>=m2.notes.length||!this.renderChannels[_1])return;let q2=m2.renderStartIndex,r3=m2.notes,$2=r3[q2],Y5=-1;for(;$2.start<=L&&(q2++,!(this.notesOnScreen>Ay));){let O5=$2.start+$2.length;if(O5>f0&&$2.length>0){let A0=$2.length/d1*l-B$*2;if(this.notesOnScreen<1e3||A0>t1){Y5===-1&&(Y5=q2-1);let i5=($2.start-f0)/d1*l,g3;if(this._notesFall?g3=l-A0-i5+B$:g3=i5+B$,$2.midiNotethis.keyRange.max){if(q2>=r3.length)break;$2=r3[q2];continue}let e6=$2.midiNote-this.keyRange.min,J6=u*e6+B$,$6,o9,K4,r4;if(this.sideways?($6=g3,o9=J6,r4=b,K4=A0):(o9=g3,$6=J6,K4=b,r4=A0),this.notesOnScreen++,o)this.drawingContext.fillStyle=this.plainColors[_1],this.drawingContext.fillRect($6+C$+B$,o9+C$,K4-C$*2,r4-C$*2);else{let K6;if($2.start>p0||O5=r3.length)break;$2=r3[q2]}Y5>-1&&(m2.renderStartIndex=Y5)}),S1.sort((m2,_1)=>_1.height-m2.height),S1}function ay(){let o=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let u=g%4,b=Math.floor(g/4),g0=!1;for(let L=g;L0){g0=!0;break}if(!g0){let L=this.canvas.width/4,t1=this.canvas.height/4,H0=L*u,S1=t1*b+t1/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(H0,S1),this.drawingContext.lineTo(H0+L,S1),this.drawingContext.stroke();return}let v0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(v0);let p0=o*u,f0=r*b+r/2,d1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let L=v0.length/4,t1=o/L,H0=Math.floor(L/2),S1=v0.length-H0;for(let r3=S1;r3>=1;r3--)if(v0[r3-1]<0&&v0[r3]>=0){S1=r3;break}let m2=p0,_1=S1-H0,q2=S1+H0;for(let r3=_1;r3{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function cy(){for(let o=0;o4096?this.delayNode.delayTime.value=u/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function gy(o){o.connectIndividualOutputs(this.channelAnalysers),o.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{this.updateFftSize()})}function hy(){for(let o of this.channelAnalysers)o.disconnect();J5("%cAnalysers disconnected!",b1.recognized)}function fy(o){this.seq=o,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),u=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${u}), rgba(0, 0, 0, ${u})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function uy(){this.noteTimes&&this.noteTimes.forEach(o=>o.renderStartIndex=0)}function GB(o,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=o[o.currentIndex++]<>>0}function km(o,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=o&255,o>>=8;return l}var gh=.02;function dy(o){function r(f0){return f0.messageData=new Y3(f0.messageData.buffer),f0.messageData.currentIndex=0,6e7/GB(f0.messageData,3)}let l=[],u=o.tracks.flat();u.sort((f0,d1)=>f0.ticks-d1.ticks);for(let f0=0;f0<16;f0++)l.push({renderStartIndex:0,notes:[]});let b=0,g0=60/(120*o.timeDivision),v0=0,p0=0;for(;v0>4,L=f0.messageStatusByte&15;if(d1===8){let t1=l[L].notes.findLast(H0=>H0.midiNote===f0.messageData[0]&&H0.length===-1);if(t1){let H0=b-t1.start;t1.length=H0H0.midiNote===f0.messageData[0]&&H0.length===-1);if(t1){let H0=b-t1.start;t1.length=H0=u.length)break;b+=g0*(u[v0].ticks-f0.ticks)}p0>0&&l.forEach((f0,d1)=>f0.notes.filter(L=>L.length===-1).forEach(L=>{let t1=b-L.start;L.length=t1{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,m$(r,g=>g*yC)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,m$(r,g=>g*yC*QC)),l.addColorStop(1,m$(r,g=>g*QC)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,m$(r,g=>g*yC)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,m$(r,g=>g*yC*QC)),l.addColorStop(1,m$(r,g=>g*QC)),l})}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}onRender;get normalAnalyserFft(){return this._normalAnalyserFft}set normalAnalyserFft(r){this._normalAnalyserFft=r,this.updateFftSize()}get drumAnalyserFft(){return this._drumAnalyserFft}set drumAnalyserFft(r){this._drumAnalyserFft=r,this.updateFftSize()}get renderBool(){return this._renderBool}set renderBool(r){this._renderBool=r,r===!0?this.connectChannelAnalysers(this.synth):this.disconnectChannelAnalysers()}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}};Di.prototype.render=ry;Di.prototype.computeNotePositions=ny;Di.prototype.createChannelAnalysers=ly;Di.prototype.updateFftSize=cy;Di.prototype.connectChannelAnalysers=gy;Di.prototype.disconnectChannelAnalysers=hy;Di.prototype.connectSequencer=fy;Di.prototype.calculateNoteTimes=dy;Di.prototype.resetIndexes=uy;Di.prototype.renderWaveforms=ay;function o3(o,r){let l=0;for(let g=0;g>>0}function lt(o,r,l){for(let g=0;g>g*8&255}function Q9(o,r){o[o.currentIndex++]=r&255,o[o.currentIndex++]=r>>8}function ct(o,r){lt(o,r,4)}function RA(o,r){let l=r<<8|o;return l>32767?l-65536:l}function Iy(o){return o>127?o-256:o}function de(o,r,l=void 0,g=!0){if(l){let u=o.slice(o.currentIndex,o.currentIndex+r);return o.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(u.buffer)}else{let u=!1,b="";for(let g0=0;g0127){if(g){u=!0;continue}else if(v0===0){u=!0;continue}}b+=String.fromCharCode(v0)}}return b}}function xA(o,r=0){let l=o.length;r>0&&(l=r);let g=new Y3(l);return gt(g,o,r),g}function gt(o,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,de(l.chunkData,4)===r))}function wC(o){let r=[o&127];for(o>>=7;o>0;)r.unshift(o&127|128),o>>=7;return r}function kC(o){let r=[];for(let u of o.tracks){let b=[],g0=0,v0;for(let p0 of u){let f0=p0.ticks-g0,d1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?d1=[255,p0.messageStatusByte,...wC(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?d1=[240,...wC(p0.messageData.length),...p0.messageData]:(d1=[],v0!==p0.messageStatusByte&&(v0=p0.messageStatusByte,d1.push(p0.messageStatusByte)),d1.push(...p0.messageData)),b.push(...wC(f0)),b.push(...d1),g0+=f0}r.push(new Uint8Array(b))}function l(u,b){for(let g0=0;g0o.chunkData.currentIndex;)r.push(new UB(o.chunkData));return r.length>1&&r.pop(),r}var F7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Sn={linear:0,concave:1,convex:2,switch:3},xD=[];for(let o=0;o<4;o++)xD.push([[],[]]);var ke=class o{constructor(r){r.srcEnum?(this.sourceEnum=r.srcEnum,this.modulatorDestination=r.dest,this.secondarySourceEnum=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.sourceEnum=o3(r,2),this.modulatorDestination=o3(r,2),this.transformAmount=RA(r[r.currentIndex++],r[r.currentIndex++]),this.secondarySourceEnum=o3(r,2),this.transformType=o3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=v1.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(r){return new o({srcEnum:r.sourceEnum,secSrcEnum:r.secondarySourceEnum,transform:r.transformType,amt:r.transformAmount,dest:r.modulatorDestination})}static isIdentical(r,l){return r.sourceEnum===l.sourceEnum&&r.modulatorDestination===l.modulatorDestination&&r.secondarySourceEnum===l.secondarySourceEnum&&r.transformType===l.transformType}sumTransform(r){return new o({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(u,b){return Object.keys(u).find(g0=>u[g0]===b)}let l=r(Sn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(A6,this.sourceIndex):l+=r(F7,this.sourceIndex);let g=r(Sn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(A6,this.secSrcIndex):g+=r(F7,this.secSrcIndex),`Modulator: Source: ${l} Secondary source: ${g} Destination: ${r(v1,this.modulatorDestination)} diff --git a/src/website/minified/local_main.min.js b/src/website/minified/local_main.min.js index e9ea3c2f..eb13ab89 100644 --- a/src/website/minified/local_main.min.js +++ b/src/website/minified/local_main.min.js @@ -1,5 +1,5 @@ var hm=(A=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(A,{get:(r,l)=>(typeof require<"u"?require:r)[l]}):A)(function(A){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+A+'" is not supported')});var Y3=class extends Uint8Array{constructor(r){super(r),this.currentIndex=0}currentIndex};function kn(A){let r=A.reduce((d,b)=>d+b.length,0),l=new Y3(r),g=0;for(let d of A)l.set(d,g),g+=d.length;return l}function d$(A){A=Math.floor(A);let r=Math.floor(A/60),l=Math.round(A-r*60);return{minutes:r,seconds:l,time:`${r.toString().padStart(2,"0")}:${l.toString().padStart(2,"0")}`}}function SB(A){return A.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}var b1={warn:"color: orange;",unrecognized:"color: red;",info:"color: aqua;",recognized:"color: lime",value:"color: yellow; background-color: black;"};var Ii=class{constructor(r,l,g){this.ticks=r,this.messageStatusByte=l,this.messageData=g}};var J3={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 qQ(A){let r=A&240,l=A&15,g=-1,d=A;return r>=128&&r<=224&&(g=l,d=r),{status:d,channel:g}}var o6={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,effects1Depth:91,effects2Depth:92,effects3Depth:93,effects4Depth:94,effects5Depth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127};var fm=class{constructor(){this.events={noteoff:{},noteon:{},pitchwheel:{},controllerchange:{},programchange:{},channelpressure:{},polypressure:{},drumchange:{},stopall:{},newchannel:{},mutechannel:{},presetlistchange:{},allcontrollerreset:{},soundfonterror:{}}}addEvent(r,l,g){this.events[r][l]=g}removeEvent(r,l){delete this.events[r][l]}callEvent(r,l){this.events[r]&&Object.values(this.events[r]).forEach(g=>g(l))}};var DB={nodesAmount:4,defaultDelay:.03,delayVariation:.01,stereoDifference:.02,oscillatorFrequency:.3,oscillatorFrequencyVariation:.05,oscillatorGain:.003},um=class{constructor(r,l=DB){let g=r.context;this.input=new ChannelSplitterNode(g,{numberOfOutputs:2});let d=new ChannelMergerNode(g,{numberOfInputs:2}),b=[],f0=[],D0=l.oscillatorFrequency,p0=l.defaultDelay;for(let g0=0;g0{let b=await d.arrayBuffer();l.buffer=await A.decodeAudioData(b)})}return l}var Q8={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25},mC={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},Ei=-1,I$={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var dD=!0,ID=!0,bB=!0;function j5(...A){dD&&console.info(...A)}function ue(...A){ID&&console.warn(...A)}function lr(...A){bB&&console.group(...A)}function ii(...A){bB&&console.groupCollapsed(...A)}function i4(){bB&&console.groupEnd()}var JQ={chorusEnabled:!0,chorusConfig:DB,reverbEnabled:!0,reverbImpulseResponse:void 0};var BC={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var dm=class{constructor(r){this.soundfontList=[{id:"main",bankOffset:0}],this._port=r.worklet.port,this.synth=r}_sendToWorklet(r,l){this._port.postMessage({messageType:Q8.soundFontManager,messageData:[r,l]})}async addNewSoundFont(r,l,g=0){if(this.soundfontList.find(d=>d.id===l)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this._sendToWorklet(BC.addNewSoundFont,[r,l,g]),await new Promise(d=>this.synth.resolveWhenReady=d),this.soundfontList.push({id:l,bankOffset:g})}deleteSoundFont(r){if(this.soundfontList.length===0){ue("1 soundfont left. Aborting!");return}if(this.soundfontList.findIndex(l=>l.id===r)===-1){ue(`No soundfont with id of "${r}" found. Aborting!`);return}this._sendToWorklet(BC.deleteSoundFont,r)}rearrangeSoundFonts(r){this._sendToWorklet(BC.rearrangeSoundFonts,r),this.soundfontList.sort((l,g)=>r.indexOf(l.id)-r.indexOf(g.id))}async reloadManager(r){this._sendToWorklet(BC.reloadSoundFont,r),await new Promise(l=>this.synth.resolveWhenReady=l)}};var ED="spessasynth-worklet-system",_B=450,Si=9,CD=16;var ah=class{constructor(r,l,g=!0,d=void 0,b=JQ){j5("%cInitializing SpessaSynth synthesizer...",b1.info),this.context=r.context;let f0=d?.oneOutput===!0;this.eventHandler=new fm,this._voiceCap=_B,this._outputsAmount=CD,this.channelsAmount=this._outputsAmount,this.resolveWhenReady=void 0,this.isReady=new Promise(g0=>this.resolveWhenReady=g0),this.channelProperties=[];for(let g0=0;g0this.handleMessage(g0.data),this.soundfontManager=new dm(this),this._snapshotCallback=void 0,this.sequencerCallbackFunction=void 0,b.reverbEnabled&&!f0&&(this.reverbProcessor=YQ(this.context,b.reverbImpulseResponse),this.reverbProcessor.connect(r),this.worklet.connect(this.reverbProcessor,0)),b.chorusEnabled&&!f0&&(this.chorusProcessor=new um(r,b.chorusConfig),this.worklet.connect(this.chorusProcessor.input,1)),f0)this.worklet.connect(r,0);else for(let g0=2;g0{this.channelsAmount++})}get voiceCap(){return this._voiceCap}set voiceCap(r){this._setMasterParam(mC.voicesCap,r),this._voiceCap=r}set highPerformanceMode(r){this._highPerformanceMode=r}get highPerformanceMode(){return this._highPerformanceMode}setLogLevel(r,l,g,d){this.post({channelNumber:Ei,messageType:Q8.setLogLevel,messageData:[r,l,g,d]})}_setMasterParam(r,l){this.post({channelNumber:Ei,messageType:Q8.setMasterParameter,messageData:[r,l]})}setInterpolationType(r){this._setMasterParam(mC.interpolationType,r)}handleMessage(r){let l=r.messageData;switch(r.messageType){case I$.channelProperties:this.channelProperties=l,this._voicesAmount=this.channelProperties.reduce((g,d)=>g+d.voicesAmount,0);break;case I$.eventCall:this.eventHandler.callEvent(l.eventName,l.eventData);break;case I$.sequencerSpecific:this.sequencerCallbackFunction&&this.sequencerCallbackFunction(l.messageType,l.messageData);break;case I$.synthesizerSnapshot:this._snapshotCallback&&this._snapshotCallback(l);break;case I$.ready:this.resolveWhenReady();break;case I$.soundfontError:ue(new Error(l)),this.eventHandler.callEvent("soundfonterror",l);break}}async getSynthesizerSnapshot(){return new Promise(r=>{this._snapshotCallback=l=>{this._snapshotCallback=void 0,r(l)},this.post({messageType:Q8.requestSynthesizerSnapshot,messageData:void 0,channelNumber:Ei})})}addNewChannel(r=!0){this.channelProperties.push({voicesAmount:0,pitchBend:0,pitchBendRangeSemitones:0,isMuted:!1,isDrum:!1}),r&&this.post({channelNumber:0,messageType:Q8.addNewChannel,messageData:null})}setVibrato(r,l){this.post({channelNumber:r,messageType:Q8.setChannelVibrato,messageData:l})}connectIndividualOutputs(r){if(r.length!==this._outputsAmount)throw new Error(`input nodes amount differs from the system's outputs amount! - Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case J3.noteOff:this.noteOff(l.channel,r[1]);break;case J3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case J3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case J3.programChange:this.programChange(l.channel,r[1]);break;case J3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case J3.channelPressure:this.channelPressure(l.channel,r[1]);break;case J3.systemExclusive:this.systemExclusive(new Y3(r.slice(1)));break;case J3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}get currentTime(){return this.context.currentTime}get voicesAmount(){return this._voicesAmount}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,d)=>{let b;if(_o)b=127;else{let D0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=d.clientX-D0.left,g0=D0.width;b=Math.floor((g0-p0)/g0*127)}else{let p0=d.clientY-D0.top,g0=D0.height;b=Math.floor(p0/g0*127)}}this.synth.noteOn(this.channel,g,b,this.enableDebugging)},l=g=>{let d=g.touches?Array.from(g.touches):[g],b=new Set;d.forEach(f0=>{let D0=document.elementFromPoint(f0.clientX,f0.clientY),p0=parseInt(D0.id.replace("note",""));b.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,f0))}),this.pressedKeys.forEach(f0=>{b.has(f0)||A(f0)})};_o||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{A(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{A(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var VQ=20,pC=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,o6.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,o6.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let d=0;d<128;d++)this.releaseNote(d,g.channel)})}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get shown(){return this._shown}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(b=l(r-1)),r<127&&(f0=l(r+1)),f0&&b?g.classList.add("between_sharps"):b?g.classList.add("left_sharp"):f0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let d=900/(r.max-r.min+5),b=document.styleSheets[0].cssRules,f0;for(let D0 of b)if(D0.selectorText==="#keyboard .key"){f0=D0;break}if(f0.style.setProperty("--pressed-transform-skew",`${8e-4/(d/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let D0=getComputedStyle(this.keyboard),p0=parseFloat(D0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),g0=this.keyboard.getBoundingClientRect().height,d1=d/p0,F=g0*d1-g0,t1=(this._keyRange.min+this._keyRange.max)/2,H0=(r.min+r.max)/2;this._keyRange=r;let S1=this.keys.find(q2=>q2.classList.contains("sharp_key")).getBoundingClientRect().width,C2=(t1-H0)*S1,_1=parseFloat(D0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${F}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${d1}) translateX(${C2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${_1/d1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${d}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${d}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let d=this.keys[r-this._keyRange.min];if(d===void 0)return;d.classList.add("pressed");let b=d.classList.contains("sharp_key"),f0=g/127,D0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!b&&this.mode==="light"?p0=`rgba(${D0.slice(0,3).map(d1=>255-(255-d1)*f0).join(", ")}, ${D0[3]})`:p0=`rgba(${D0.slice(0,3).map(d1=>d1*f0).join(", ")}, ${D0[3]})`,d.style.background=p0,this.mode==="dark"){let g0=VQ*f0;d.style.boxShadow=`${p0} 0px 0px ${g0}px ${g0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let d=this.keyColors[r-this._keyRange.min];if(!d)return;let b=d.findLastIndex(f0=>f0===this.channelColors[l]);b!==-1&&(d.splice(b,1),g.style.background=d[d.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${VQ}px ${d[d.length-1]}`),d.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};pC.prototype._handlePointers=KQ;function E$(A,r){let l=A.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var BD="#000";function zQ(A,r,l){A.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let d=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*d,l){r.fillRect(g.xPos,g.yPos-g.height*d,g.width,g.height*(d*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*d,g.yPos,g.width*(d*2+1),g.height),r.globalAlpha=1}),A.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=BD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var RB=!1;function ZQ(A=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(RB){A&&requestAnimationFrame(this.render.bind(this));return}else RB=!0;else RB=!1;if(A&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let b=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||zQ(b,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let d=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${Im}px system-ui`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,Im*2+5),this.drawingContext.fillText(this.version,this.canvas.width,5),this.drawingContext.fillText(Math.round(d).toString()+" FPS",this.canvas.width,Im+5),this.onRender&&this.onRender(),A&&requestAnimationFrame(this.render.bind(this))}function WQ(A=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,d=r/(g+1),b=d-m$*2,f0=this.noteFallingTimeMs/1e3,D0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,g0=p0-D0,d1=f0+D0,F=g0+d1,t1=XQ/d1,H0=[];this.synth.channelProperties.forEach(C2=>{if(this.showVisualPitch){let _1=C2.pitchBend-8192+this.visualPitchBendOffset;H0.push(C2.pitchBendRangeSemitones*(_1/8192*d))}else H0.push(0)});let S1=[];return this.noteTimes.forEach((C2,_1)=>{if(C2.renderStartIndex>=C2.notes.length||!this.renderChannels[_1])return;let q2=C2.renderStartIndex,r3=C2.notes,$2=r3[q2],Y5=-1;for(;$2.start<=F&&(q2++,!(this.notesOnScreen>ey));){let P5=$2.start+$2.length;if(P5>g0&&$2.length>0){let o0=$2.length/d1*l-m$*2;if(this.notesOnScreen<1e3||o0>t1){Y5===-1&&(Y5=q2-1);let i5=($2.start-g0)/d1*l,g3;if(this._notesFall?g3=l-o0-i5+m$:g3=i5+m$,$2.midiNotethis.keyRange.max){if(q2>=r3.length)break;$2=r3[q2];continue}let e6=$2.midiNote-this.keyRange.min,J6=d*e6+m$,$6,A9,J4,r4;if(this.sideways?($6=g3,A9=J6,r4=b,J4=o0):(A9=g3,$6=J6,J4=b,r4=o0),this.notesOnScreen++,A)this.drawingContext.fillStyle=this.plainColors[_1],this.drawingContext.fillRect($6+C$+m$,A9+C$,J4-C$*2,r4-C$*2);else{let K6;if($2.start>p0||P5=r3.length)break;$2=r3[q2]}Y5>-1&&(C2.renderStartIndex=Y5)}),S1.sort((C2,_1)=>_1.height-C2.height),S1}function ty(){let A=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let d=g%4,b=Math.floor(g/4),f0=!1;for(let F=g;F0){f0=!0;break}if(!f0){let F=this.canvas.width/4,t1=this.canvas.height/4,H0=F*d,S1=t1*b+t1/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(H0,S1),this.drawingContext.lineTo(H0+F,S1),this.drawingContext.stroke();return}let D0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(D0);let p0=A*d,g0=r*b+r/2,d1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let F=D0.length/4,t1=A/F,H0=Math.floor(F/2),S1=D0.length-H0;for(let r3=S1;r3>=1;r3--)if(D0[r3-1]<0&&D0[r3]>=0){S1=r3;break}let C2=p0,_1=S1-H0,q2=S1+H0;for(let r3=_1;r3{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function ny(){for(let A=0;A4096?this.delayNode.delayTime.value=d/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function sy(A){A.connectIndividualOutputs(this.channelAnalysers),A.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{this.updateFftSize()})}function Ay(){for(let A of this.channelAnalysers)A.disconnect();j5("%cAnalysers disconnected!",b1.recognized)}function oy(A){this.seq=A,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),d=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${d}), rgba(0, 0, 0, ${d})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function ay(){this.noteTimes&&this.noteTimes.forEach(A=>A.renderStartIndex=0)}function xB(A,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=A[A.currentIndex++]<>>0}function QC(A,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=A&255,A>>=8;return l}var $h=.02;function $y(A){function r(g0){return g0.messageData=new Y3(g0.messageData.buffer),g0.messageData.currentIndex=0,6e7/xB(g0.messageData,3)}let l=[],d=A.tracks.flat();d.sort((g0,d1)=>g0.ticks-d1.ticks);for(let g0=0;g0<16;g0++)l.push({renderStartIndex:0,notes:[]});let b=0,f0=60/(120*A.timeDivision),D0=0,p0=0;for(;D0>4,F=g0.messageStatusByte&15;if(d1===8){let t1=l[F].notes.findLast(H0=>H0.midiNote===g0.messageData[0]&&H0.length===-1);if(t1){let H0=b-t1.start;t1.length=H0<$h&&F===Si?$h:H0}p0--}else if(d1===9)if(g0.messageData[1]===0){let t1=l[F].notes.findLast(H0=>H0.midiNote===g0.messageData[0]&&H0.length===-1);if(t1){let H0=b-t1.start;t1.length=H0<$h&&F===Si?$h:H0}p0--}else l[g0.messageStatusByte&15].notes.push({midiNote:g0.messageData[0],start:b,length:-1,velocity:g0.messageData[1]/127}),p0++;else g0.messageStatusByte===81&&(f0=60/(r(g0)*A.timeDivision));if(++D0>=d.length)break;b+=f0*(d[D0].ticks-g0.ticks)}p0>0&&l.forEach((g0,d1)=>g0.notes.filter(F=>F.length===-1).forEach(F=>{let t1=b-F.start;F.length=t1<$h&&d1===Si?$h:t1})),this.noteTimes=l,j5("%cFinished loading note times and ready to render the sequence!",b1.info)}var pD=1024,QD=4096,yD=2,wD=2,Em=.6,Cm=.5,C$=1,m$=1,Im=12,jQ=.6,XQ=2,ey=81572,Di=class{constructor(r,l,g,d,b=""){this.noteFallingTimeMs=1e3,this.noteAfterTriggerTimeMs=0,this._keyRange={min:0,max:127},this.version="v"+b,this.visualPitchBendOffset=0,this.lineThickness=wD,this._normalAnalyserFft=pD,this._drumAnalyserFft=QD,this.waveMultiplier=yD,this._notesFall=!0,this.sideways=!1,this._renderBool=!0,this.renderAnalysers=!0,this.renderNotes=!0,this.drawActiveNotes=!0,this.showVisualPitch=!0,this._stabilizeWaveforms=!0,this.renderChannels=Array(16).fill(!0),this.canvas=g,this.drawingContext=this.canvas.getContext("2d"),this.plainColors=r,this.computeColors(),this.synth=l,this.delayNode=d,this.notesOnScreen=0,this.channelAnalysers=[],this.createChannelAnalysers(l),this.connectChannelAnalysers(l)}get stabilizeWaveforms(){return this._stabilizeWaveforms}set stabilizeWaveforms(r){this._stabilizeWaveforms=r,this.updateFftSize()}set direction(r){this._notesFall=r==="down"}get direction(){return this._notesFall?"down":"up"}computeColors(){this.channelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,E$(r,g=>g*Cm)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,E$(r,g=>g*Cm*Em)),l.addColorStop(1,E$(r,g=>g*Em)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,E$(r,g=>g*Cm)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,E$(r,g=>g*Cm*Em)),l.addColorStop(1,E$(r,g=>g*Em)),l})}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}onRender;get normalAnalyserFft(){return this._normalAnalyserFft}set normalAnalyserFft(r){this._normalAnalyserFft=r,this.updateFftSize()}get drumAnalyserFft(){return this._drumAnalyserFft}set drumAnalyserFft(r){this._drumAnalyserFft=r,this.updateFftSize()}get renderBool(){return this._renderBool}set renderBool(r){this._renderBool=r,r===!0?this.connectChannelAnalysers(this.synth):this.disconnectChannelAnalysers()}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}};Di.prototype.render=ZQ;Di.prototype.computeNotePositions=WQ;Di.prototype.createChannelAnalysers=ry;Di.prototype.updateFftSize=ny;Di.prototype.connectChannelAnalysers=sy;Di.prototype.disconnectChannelAnalysers=Ay;Di.prototype.connectSequencer=oy;Di.prototype.calculateNoteTimes=$y;Di.prototype.resetIndexes=ay;Di.prototype.renderWaveforms=ty;function A3(A,r){let l=0;for(let g=0;g>>0}function $t(A,r,l){for(let g=0;g>g*8&255}function Q9(A,r){A[A.currentIndex++]=r&255,A[A.currentIndex++]=r>>8}function lt(A,r){$t(A,r,4)}function Ro(A,r){let l=r<<8|A;return l>32767?l-65536:l}function ly(A){return A>127?A-256:A}function de(A,r,l=void 0,g=!0){if(l){let d=A.slice(A.currentIndex,A.currentIndex+r);return A.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(d.buffer)}else{let d=!1,b="";for(let f0=0;f0127){if(g){d=!0;continue}else if(D0===0){d=!0;continue}}b+=String.fromCharCode(D0)}}return b}}function xo(A,r=0){let l=A.length;r>0&&(l=r);let g=new Y3(l);return ct(g,A,r),g}function ct(A,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,de(l.chunkData,4)===r))}function mm(A){let r=[A&127];for(A>>=7;A>0;)r.unshift(A&127|128),A>>=7;return r}function Bm(A){let r=[];for(let d of A.tracks){let b=[],f0=0,D0;for(let p0 of d){let g0=p0.ticks-f0,d1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?d1=[255,p0.messageStatusByte,...mm(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?d1=[240,...mm(p0.messageData.length),...p0.messageData]:(d1=[],D0!==p0.messageStatusByte&&(D0=p0.messageStatusByte,d1.push(p0.messageStatusByte)),d1.push(...p0.messageData)),b.push(...mm(g0)),b.push(...d1),f0+=g0}r.push(new Uint8Array(b))}function l(d,b){for(let f0=0;f0A.chunkData.currentIndex;)r.push(new FB(A.chunkData));return r.length>1&&r.pop(),r}var x7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Sn={linear:0,concave:1,convex:2,switch:3},kD=[];for(let A=0;A<4;A++)kD.push([[],[]]);var ke=class A{constructor(r){r.srcEnum?(this.sourceEnum=r.srcEnum,this.modulatorDestination=r.dest,this.secondarySourceEnum=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.sourceEnum=A3(r,2),this.modulatorDestination=A3(r,2),this.transformAmount=Ro(r[r.currentIndex++],r[r.currentIndex++]),this.secondarySourceEnum=A3(r,2),this.transformType=A3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=v1.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(r){return new A({srcEnum:r.sourceEnum,secSrcEnum:r.secondarySourceEnum,transform:r.transformType,amt:r.transformAmount,dest:r.modulatorDestination})}static isIdentical(r,l){return r.sourceEnum===l.sourceEnum&&r.modulatorDestination===l.modulatorDestination&&r.secondarySourceEnum===l.secondarySourceEnum&&r.transformType===l.transformType}sumTransform(r){return new A({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(d,b){return Object.keys(d).find(f0=>d[f0]===b)}let l=r(Sn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(o6,this.sourceIndex):l+=r(x7,this.sourceIndex);let g=r(Sn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(o6,this.secSrcIndex):g+=r(x7,this.secSrcIndex),`Modulator: + Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case J3.noteOff:this.noteOff(l.channel,r[1]);break;case J3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case J3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case J3.programChange:this.programChange(l.channel,r[1]);break;case J3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case J3.channelPressure:this.channelPressure(l.channel,r[1]);break;case J3.systemExclusive:this.systemExclusive(new Y3(r.slice(1)));break;case J3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}get currentTime(){return this.context.currentTime}get voicesAmount(){return this._voicesAmount}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,d)=>{let b;if(_o)b=127;else{let D0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=d.clientX-D0.left,g0=D0.width;b=Math.floor((g0-p0)/g0*127)}else{let p0=d.clientY-D0.top,g0=D0.height;b=Math.floor(p0/g0*127)}}this.synth.noteOn(this.channel,g,b,this.enableDebugging)},l=g=>{let d=g.touches?Array.from(g.touches):[g],b=new Set;d.forEach(f0=>{let D0=document.elementFromPoint(f0.clientX,f0.clientY),p0=parseInt(D0.id.replace("note",""));b.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,f0))}),this.pressedKeys.forEach(f0=>{b.has(f0)||A(f0)})};_o||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{A(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{A(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var VQ=20,pC=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,o6.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,o6.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let d=0;d<128;d++)this.releaseNote(d,g.channel)})}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get shown(){return this._shown}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(b=l(r-1)),r<127&&(f0=l(r+1)),f0&&b?g.classList.add("between_sharps"):b?g.classList.add("left_sharp"):f0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let d=900/(r.max-r.min+5),b=document.styleSheets[0].cssRules,f0;for(let D0 of b)if(D0.selectorText==="#keyboard .key"){f0=D0;break}if(f0.style.setProperty("--pressed-transform-skew",`${8e-4/(d/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let D0=getComputedStyle(this.keyboard),p0=parseFloat(D0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),g0=this.keyboard.getBoundingClientRect().height,d1=d/p0,F=g0*d1-g0,t1=(this._keyRange.min+this._keyRange.max)/2,H0=(r.min+r.max)/2;this._keyRange=r;let S1=this.keys.find(q2=>q2.classList.contains("sharp_key")).getBoundingClientRect().width,C2=(t1-H0)*S1,_1=parseFloat(D0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${F}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${d1}) translateX(${C2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${_1/d1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${d}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${d}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let d=this.keys[r-this._keyRange.min];if(d===void 0)return;d.classList.add("pressed");let b=d.classList.contains("sharp_key"),f0=g/127,D0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!b&&this.mode==="light"?p0=`rgba(${D0.slice(0,3).map(d1=>255-(255-d1)*f0).join(", ")}, ${D0[3]})`:p0=`rgba(${D0.slice(0,3).map(d1=>d1*f0).join(", ")}, ${D0[3]})`,d.style.background=p0,this.mode==="dark"){let g0=VQ*f0;d.style.boxShadow=`${p0} 0px 0px ${g0}px ${g0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let d=this.keyColors[r-this._keyRange.min];if(!d)return;let b=d.findLastIndex(f0=>f0===this.channelColors[l]);b!==-1&&(d.splice(b,1),g.style.background=d[d.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${VQ}px ${d[d.length-1]}`),d.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};pC.prototype._handlePointers=KQ;function E$(A,r){let l=A.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var BD="#000";function zQ(A,r,l){A.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let d=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*d,l){r.fillRect(g.xPos,g.yPos-g.height*d,g.width,g.height*(d*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*d,g.yPos,g.width*(d*2+1),g.height),r.globalAlpha=1}),A.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=BD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var RB=!1;function ZQ(A=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(RB){A&&requestAnimationFrame(this.render.bind(this));return}else RB=!0;else RB=!1;if(A&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let b=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||zQ(b,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let d=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${Im}px system-ui`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,Im*2+5),this.drawingContext.fillText(this.version,this.canvas.width,5),this.drawingContext.fillText(Math.round(d).toString()+" FPS",this.canvas.width,Im+5),this.onRender&&this.onRender(),A&&requestAnimationFrame(this.render.bind(this))}function WQ(A=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,d=r/(g+1),b=d-m$*2,f0=this.noteFallingTimeMs/1e3,D0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,g0=p0-D0,d1=f0+D0,F=g0+d1,t1=XQ/d1,H0=[];this.synth.channelProperties.forEach(C2=>{if(this.showVisualPitch){let _1=C2.pitchBend-8192+this.visualPitchBendOffset;H0.push(C2.pitchBendRangeSemitones*(_1/8192*d))}else H0.push(0)});let S1=[];return this.noteTimes.forEach((C2,_1)=>{if(C2.renderStartIndex>=C2.notes.length||!this.renderChannels[_1])return;let q2=C2.renderStartIndex,r3=C2.notes,$2=r3[q2],Y5=-1;for(;$2.start<=F&&(q2++,!(this.notesOnScreen>ey));){let P5=$2.start+$2.length;if(P5>g0&&$2.length>0){let o0=$2.length/d1*l-m$*2;if(this.notesOnScreen<1e3||o0>t1){Y5===-1&&(Y5=q2-1);let i5=($2.start-g0)/d1*l,g3;if(this._notesFall?g3=l-o0-i5+m$:g3=i5+m$,$2.midiNotethis.keyRange.max){if(q2>=r3.length)break;$2=r3[q2];continue}let e6=$2.midiNote-this.keyRange.min,J6=d*e6+m$,$6,A9,J4,r4;if(this.sideways?($6=g3,A9=J6,r4=b,J4=o0):(A9=g3,$6=J6,J4=b,r4=o0),this.notesOnScreen++,A)this.drawingContext.fillStyle=this.plainColors[_1],this.drawingContext.fillRect($6+C$+m$,A9+C$,J4-C$*2,r4-C$*2);else{let K6;if($2.start>p0||P5=r3.length)break;$2=r3[q2]}Y5>-1&&(C2.renderStartIndex=Y5)}),S1.sort((C2,_1)=>_1.height-C2.height),S1}function ty(){let A=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let d=g%4,b=Math.floor(g/4),f0=!1;for(let F=g;F0){f0=!0;break}if(!f0){let F=this.canvas.width/4,t1=this.canvas.height/4,H0=F*d,S1=t1*b+t1/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(H0,S1),this.drawingContext.lineTo(H0+F,S1),this.drawingContext.stroke();return}let D0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(D0);let p0=A*d,g0=r*b+r/2,d1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let F=D0.length/4,t1=A/F,H0=Math.floor(F/2),S1=D0.length-H0;for(let r3=S1;r3>=1;r3--)if(D0[r3-1]<0&&D0[r3]>=0){S1=r3;break}let C2=p0,_1=S1-H0,q2=S1+H0;for(let r3=_1;r3{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function ny(){for(let A=0;A4096?this.delayNode.delayTime.value=d/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function sy(A){A.connectIndividualOutputs(this.channelAnalysers),A.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{this.updateFftSize()})}function Ay(){for(let A of this.channelAnalysers)A.disconnect();j5("%cAnalysers disconnected!",b1.recognized)}function oy(A){this.seq=A,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),d=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${d}), rgba(0, 0, 0, ${d})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function ay(){this.noteTimes&&this.noteTimes.forEach(A=>A.renderStartIndex=0)}function xB(A,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=A[A.currentIndex++]<>>0}function QC(A,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=A&255,A>>=8;return l}var $h=.02;function $y(A){function r(g0){return g0.messageData=new Y3(g0.messageData.buffer),g0.messageData.currentIndex=0,6e7/xB(g0.messageData,3)}let l=[],d=A.tracks.flat();d.sort((g0,d1)=>g0.ticks-d1.ticks);for(let g0=0;g0<16;g0++)l.push({renderStartIndex:0,notes:[]});let b=0,f0=60/(120*A.timeDivision),D0=0,p0=0;for(;D0>4,F=g0.messageStatusByte&15;if(d1===8){let t1=l[F].notes.findLast(H0=>H0.midiNote===g0.messageData[0]&&H0.length===-1);if(t1){let H0=b-t1.start;t1.length=H0<$h&&F===Si?$h:H0}p0--}else if(d1===9)if(g0.messageData[1]===0){let t1=l[F].notes.findLast(H0=>H0.midiNote===g0.messageData[0]&&H0.length===-1);if(t1){let H0=b-t1.start;t1.length=H0<$h&&F===Si?$h:H0}p0--}else l[g0.messageStatusByte&15].notes.push({midiNote:g0.messageData[0],start:b,length:-1,velocity:g0.messageData[1]/127}),p0++;else g0.messageStatusByte===81&&(f0=60/(r(g0)*A.timeDivision));if(++D0>=d.length)break;b+=f0*(d[D0].ticks-g0.ticks)}p0>0&&l.forEach((g0,d1)=>g0.notes.filter(F=>F.length===-1).forEach(F=>{let t1=b-F.start;F.length=t1<$h&&d1===Si?$h:t1})),this.noteTimes=l,j5("%cFinished loading note times and ready to render the sequence!",b1.info)}var pD=1024,QD=4096,yD=2,wD=2,Em=.6,Cm=.5,C$=1,m$=1,Im=12,jQ=.6,XQ=2,ey=81572,Di=class{constructor(r,l,g,d,b=""){this.noteFallingTimeMs=1e3,this.noteAfterTriggerTimeMs=0,this._keyRange={min:0,max:127},this.version="v"+b,this.visualPitchBendOffset=0,this.lineThickness=wD,this._normalAnalyserFft=pD,this._drumAnalyserFft=QD,this.waveMultiplier=yD,this._notesFall=!0,this.sideways=!1,this._renderBool=!0,this.renderAnalysers=!0,this.renderNotes=!0,this.drawActiveNotes=!0,this.showVisualPitch=!0,this._stabilizeWaveforms=!0,this.renderChannels=Array(16).fill(!0),this.canvas=g,this.drawingContext=this.canvas.getContext("2d"),this.plainColors=r,this.computeColors(),this.synth=l,this.delayNode=d,this.notesOnScreen=0,this.channelAnalysers=[],this.createChannelAnalysers(l),this.connectChannelAnalysers(l)}get stabilizeWaveforms(){return this._stabilizeWaveforms}set stabilizeWaveforms(r){this._stabilizeWaveforms=r,this.updateFftSize()}set direction(r){this._notesFall=r==="down"}get direction(){return this._notesFall?"down":"up"}computeColors(){this.channelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,E$(r,g=>g*Cm)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,E$(r,g=>g*Cm*Em)),l.addColorStop(1,E$(r,g=>g*Em)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,E$(r,g=>g*Cm)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,E$(r,g=>g*Cm*Em)),l.addColorStop(1,E$(r,g=>g*Em)),l})}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}onRender;get normalAnalyserFft(){return this._normalAnalyserFft}set normalAnalyserFft(r){this._normalAnalyserFft=r,this.updateFftSize()}get drumAnalyserFft(){return this._drumAnalyserFft}set drumAnalyserFft(r){this._drumAnalyserFft=r,this.updateFftSize()}get renderBool(){return this._renderBool}set renderBool(r){this._renderBool=r,r===!0?this.connectChannelAnalysers(this.synth):this.disconnectChannelAnalysers()}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}};Di.prototype.render=ZQ;Di.prototype.computeNotePositions=WQ;Di.prototype.createChannelAnalysers=ry;Di.prototype.updateFftSize=ny;Di.prototype.connectChannelAnalysers=sy;Di.prototype.disconnectChannelAnalysers=Ay;Di.prototype.connectSequencer=oy;Di.prototype.calculateNoteTimes=$y;Di.prototype.resetIndexes=ay;Di.prototype.renderWaveforms=ty;function A3(A,r){let l=0;for(let g=0;g>>0}function $t(A,r,l){for(let g=0;g>g*8&255}function Q9(A,r){A[A.currentIndex++]=r&255,A[A.currentIndex++]=r>>8}function lt(A,r){$t(A,r,4)}function Ro(A,r){let l=r<<8|A;return l>32767?l-65536:l}function ly(A){return A>127?A-256:A}function de(A,r,l=void 0,g=!0){if(l){let d=A.slice(A.currentIndex,A.currentIndex+r);return A.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(d.buffer)}else{let d=!1,b="";for(let f0=0;f0127){if(g){d=!0;continue}else if(D0===0){d=!0;continue}}b+=String.fromCharCode(D0)}}return b}}function xo(A,r=0){let l=A.length;r>0&&(l=r);let g=new Y3(l);return ct(g,A,r),g}function ct(A,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,de(l.chunkData,4)===r))}function mm(A){let r=[A&127];for(A>>=7;A>0;)r.unshift(A&127|128),A>>=7;return r}function Bm(A){let r=[];for(let d of A.tracks){let b=[],f0=0,D0;for(let p0 of d){let g0=p0.ticks-f0,d1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?d1=[255,p0.messageStatusByte,...mm(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?d1=[240,...mm(p0.messageData.length),...p0.messageData]:(d1=[],D0!==p0.messageStatusByte&&(D0=p0.messageStatusByte,d1.push(p0.messageStatusByte)),d1.push(...p0.messageData)),b.push(...mm(g0)),b.push(...d1),f0+=g0}r.push(new Uint8Array(b))}function l(d,b){for(let f0=0;f0A.chunkData.currentIndex;)r.push(new FB(A.chunkData));return r.length>1&&r.pop(),r}var x7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Sn={linear:0,concave:1,convex:2,switch:3},kD=[];for(let A=0;A<4;A++)kD.push([[],[]]);var ke=class A{constructor(r){r.srcEnum?(this.sourceEnum=r.srcEnum,this.modulatorDestination=r.dest,this.secondarySourceEnum=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.sourceEnum=A3(r,2),this.modulatorDestination=A3(r,2),this.transformAmount=Ro(r[r.currentIndex++],r[r.currentIndex++]),this.secondarySourceEnum=A3(r,2),this.transformType=A3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=v1.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(r){return new A({srcEnum:r.sourceEnum,secSrcEnum:r.secondarySourceEnum,transform:r.transformType,amt:r.transformAmount,dest:r.modulatorDestination})}static isIdentical(r,l){return r.sourceEnum===l.sourceEnum&&r.modulatorDestination===l.modulatorDestination&&r.secondarySourceEnum===l.secondarySourceEnum&&r.transformType===l.transformType}sumTransform(r){return new A({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(d,b){return Object.keys(d).find(f0=>d[f0]===b)}let l=r(Sn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(o6,this.sourceIndex):l+=r(x7,this.sourceIndex);let g=r(Sn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(o6,this.secSrcIndex):g+=r(x7,this.secSrcIndex),`Modulator: Source: ${l} Secondary source: ${g} Destination: ${r(v1,this.modulatorDestination)}