From 4d2985f948239715802cbe03d300a8e3ef1b8c4b Mon Sep 17 00:00:00 2001 From: spessasus Date: Mon, 16 Sep 2024 08:26:10 +0200 Subject: [PATCH] Fix clicking at the start of non-0 samples --- package.json | 2 +- src/spessasynth_lib/soundfont/read_sf2/generators.js | 4 ++-- src/spessasynth_lib/synthetizer/worklet_processor.min.js | 4 ++-- .../worklet_system/worklet_utilities/unit_converter.js | 2 +- src/website/minified/demo_main.min.js | 2 +- src/website/minified/local_main.min.js | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index e2284499..762f535a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "SpessaSynth", - "version": "3.20.18", + "version": "3.20.19", "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 7c60ed45..672a11fc 100644 --- a/src/spessasynth_lib/soundfont/read_sf2/generators.js +++ b/src/spessasynth_lib/soundfont/read_sf2/generators.js @@ -113,8 +113,8 @@ generatorLimits[generatorTypes.delayVibLFO] = {min: -12000, max: 5000, def: -120 generatorLimits[generatorTypes.freqVibLFO] = {min: -16000, max: 4500, def: 0}; // mod env -generatorLimits[generatorTypes.delayModEnv] = {min: -12000, max: 5000, def: -12000}; -generatorLimits[generatorTypes.attackModEnv] = {min: -12000, max: 8000, def: -12000}; +generatorLimits[generatorTypes.delayModEnv] = {min: -32768, max: 5000, def: -32768}; // -32768 indicates instant phase, this is done to prevent click at the start of filter modenv +generatorLimits[generatorTypes.attackModEnv] = {min: -32768, max: 8000, def: -32768}; generatorLimits[generatorTypes.holdModEnv] = {min: -12000, max: 5000, def: -12000}; generatorLimits[generatorTypes.decayModEnv] = {min: -12000, max: 8000, def: -12000}; generatorLimits[generatorTypes.sustainModEnv] = {min: 0, max: 1000, def: 0}; diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index 8999c0ec..9d3bcf24 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -1,4 +1,4 @@ -var is=(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 Se(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 lt(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 as(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function hA(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},gs={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var AA={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},re={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},bA=-1,mA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var Cs=!0,Es=!0,Ye=!0,Bs=!0;function hs(t,A,e,s){Cs=t,Es=A,Ye=e,Bs=s}function m(...t){Cs&&console.info(...t)}function b(...t){Es&&console.warn(...t)}function Qs(...t){Bs&&console.table(...t)}function Ae(...t){Ye&&console.group(...t)}function pA(...t){Ye&&console.groupCollapsed(...t)}function Z(){Ye&&console.groupEnd()}var ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var cs="spessasynth-worklet-system",ls=450,SA=9,Je=16,qe="gs";var MA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},kA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function WA(t,A){let e=0;for(let s=8*(A-1);s>=0;s-=8)e|=t[t.currentIndex++]<>>0}function us(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=ye(t.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=s,e.status){case w.noteOn:let n=t.messageData[1];if(n>0)this.synth.noteOn(e.channel,t.messageData[0],n),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:n});else{this.synth.noteOff(e.channel,t.messageData[0]);let C=this.playingNotes.findIndex(g=>g.midiNote===t.messageData[0]&&g.channel===e.channel);C!==-1&&this.playingNotes.splice(C,1)}break;case w.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case w.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case w.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case w.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case w.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case w.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case w.systemExclusive:this.synth.systemExclusive(t.messageData,s);break;case w.setTempo:this.oneTickToSeconds=60/(Do(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),b("invalid tempo! falling back to 120 BPM"));break;case w.timeSignature:case w.endOfTrack:case w.midiChannelPrefix:case w.songPosition:case w.activeSensing:case w.keySignature:break;case w.text:case w.lyric:case w.copyright:case w.trackName:case w.marker:case w.cuePoint:case w.instrumentName:this.post(kA.textEvent,[t.messageData,e.status]);break;case w.midiPort:this.assignMIDIPort(A,t.messageData[0]);break;case w.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:b(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(w).find(C=>w[C]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function ds(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Do(t){return t.messageData.currentIndex=0,6e7/WA(t.messageData,3)}function fs(){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.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop){this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function ms(){let t=0,A=1/0;return this.tracks.forEach((e,s)=>{this.eventIndex[s]>=e.length||e[this.eventIndex[s]].ticksg===p.dataDecrement||g===p.dataIncrement||g===p.dataEntryMsb||g===p.dataDecrement||g===p.lsbForControl6DataEntry||g===p.RPNLsb||g===p.RPNMsb||g===p.NRPNLsb||g===p.NRPNMsb||g===p.bankSelect||g===p.lsbForControl0BankSelect||g===p.resetAllControllers,C=[];for(let g=0;g=A)break}else if(this.playedTime>=t)break;let Q=ye(h.messageStatusByte),d=Q.channel+(this.midiPortChannelOffsets[this.midiPorts[g]]||0);switch(Q.status){case w.noteOn:case w.noteOff:case w.keySignature:break;case w.pitchBend:s[d]=h.messageData[1]<<7|h.messageData[0];break;case w.programChange:let c=n[d];c.program=h.messageData[0],c.actualBank=c.bank;break;case w.controllerChange:let u=h.messageData[0];if(o(u))if(this.sendMIDIMessages)this.sendMIDIMessage([w.controllerChange|d%16,u,h.messageData[1]]);else{let y=h.messageData[1];if(u===p.bankSelect){n[d].bank=y;break}this.synth.controllerChange(d,u,y)}else C[d]===void 0&&(C[d]=Array.from(qA)),C[d][u]=h.messageData[1];break;default:this._processEvent(h,g);break}this.eventIndex[g]++,g=this._findFirstEventIndex();let l=this.tracks[g][this.eventIndex[g]];if(l===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(l.ticks-h.ticks)}if(this.sendMIDIMessages){for(let g=0;g>7]),C[g].forEach((h,Q)=>{h!==qA[Q]&&!o(Q)&&this.sendMIDIMessage([w.controllerChange|g%16,Q,h])}),n[g].program>=0&&n[g].actualBank>=0){let h=n[g].actualBank;this.sendMIDIMessage([w.controllerChange|g%16,p.bankSelect,h]),this.sendMIDIMessage([w.programChange|g%16,n[g].program])}}else for(let g=0;g>7,s[g]&127),C[g]!==void 0&&C[g].forEach((h,Q)=>{h!==qA[Q]&&!o(Q)&&this.synth.controllerChange(g,Q,h)}),n[g].program>=0&&n[g].actualBank>=0){let h=n[g].actualBank;this.synth.controllerChange(g,p.bankSelect,h),this.synth.programChange(g,n[g].program)}return!0}function Ss(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 Ke(t,A,e){if(A<=0)return 0;let s=t.find(o=>o.ticks>>0}function ae(t,A,e){for(let s=0;s>s*8&255}function Y(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function cA(t,A){ae(t,A,4)}function Ie(t,A){let e=A<<8|t;return e>32767?e-65536:e}function ks(t){return t>127?t-256:t}function V(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 C=0;C127){if(s){n=!0;continue}else if(g===0){n=!0;continue}}o+=String.fromCharCode(g)}}return o}}function wA(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,V(e.chunkData,4)===A))}function Pe(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var I={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},T=[];T[I.startAddrsOffset]={min:0,max:32768,def:0};T[I.endAddrOffset]={min:-32768,max:32768,def:0};T[I.startloopAddrsOffset]={min:-32768,max:32768,def:0};T[I.endloopAddrsOffset]={min:-32768,max:32768,def:0};T[I.startAddrsCoarseOffset]={min:0,max:32768,def:0};T[I.modLfoToPitch]={min:-12e3,max:12e3,def:0};T[I.vibLfoToPitch]={min:-12e3,max:12e3,def:0};T[I.modEnvToPitch]={min:-12e3,max:12e3,def:0};T[I.initialFilterFc]={min:1500,max:13500,def:13500};T[I.initialFilterQ]={min:0,max:960,def:0};T[I.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};T[I.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};T[I.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[I.modLfoToVolume]={min:-960,max:960,def:0};T[I.chorusEffectsSend]={min:0,max:1e3,def:0};T[I.reverbEffectsSend]={min:0,max:1e3,def:0};T[I.pan]={min:-500,max:500,def:0};T[I.delayModLFO]={min:-12e3,max:5e3,def:-12e3};T[I.freqModLFO]={min:-16e3,max:4500,def:0};T[I.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};T[I.freqVibLFO]={min:-16e3,max:4500,def:0};T[I.delayModEnv]={min:-12e3,max:5e3,def:-12e3};T[I.attackModEnv]={min:-12e3,max:8e3,def:-12e3};T[I.holdModEnv]={min:-12e3,max:5e3,def:-12e3};T[I.decayModEnv]={min:-12e3,max:8e3,def:-12e3};T[I.sustainModEnv]={min:0,max:1e3,def:0};T[I.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};T[I.keyNumToModEnvHold]={min:-1200,max:1200,def:0};T[I.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};T[I.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};T[I.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};T[I.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};T[I.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};T[I.sustainVolEnv]={min:0,max:1440,def:0};T[I.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};T[I.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};T[I.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};T[I.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[I.keyNum]={min:-1,max:127,def:-1};T[I.velocity]={min:-1,max:127,def:-1};T[I.initialAttenuation]={min:-250,max:1440,def:0};T[I.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[I.coarseTune]={min:-120,max:120,def:0};T[I.fineTune]={min:-99,max:99,def:0};T[I.scaleTuning]={min:0,max:1200,def:100};T[I.exclusiveClass]={min:0,max:99999,def:0};T[I.overridingRootKey]={min:-1,max:127,def:-1};var U=class{constructor(A=I.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let s=T[A];this.generatorValue=Math.round(e),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}generatorType=I.INVALID;generatorValue=0};function ws(t,A,e){let s=T[t]||{min:0,max:32768,def:0},n=A.find(Q=>Q.generatorType===t),o=0;n&&(o=n.generatorValue);let C=e.find(Q=>Q.generatorType===t),g=s.def;C&&(g=C.generatorValue);let h=g+o;return t===I.initialAttenuation?h:Math.max(s.min,Math.min(s.max,h))}var ut=class extends U{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=Ie(A[e+2],A[e+3]),A.currentIndex+=4}};function dt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new ut(t.chunkData));return A.length>1&&A.pop(),A}var P={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},lA={linear:0,concave:1,convex:2,switch:3},ko=[];for(let t=0;t<4;t++)ko.push([[],[]]);var rA=class t{constructor(A){A.srcEnum?(this.modulatorSource=A.srcEnum,this.modulatorDestination=A.dest,this.modulationSecondarySrc=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform):(this.modulatorSource=D(A,2),this.modulatorDestination=D(A,2),this.transformAmount=Ie(A[A.currentIndex++],A[A.currentIndex++]),this.modulationSecondarySrc=D(A,2),this.transformType=D(A,2)),this.modulatorDestination>58&&(this.modulatorDestination=I.INVALID),this.sourcePolarity=this.modulatorSource>>9&1,this.sourceDirection=this.modulatorSource>>8&1,this.sourceUsesCC=this.modulatorSource>>7&1,this.sourceIndex=this.modulatorSource&127,this.sourceCurveType=this.modulatorSource>>10&3,this.secSrcPolarity=this.modulationSecondarySrc>>9&1,this.secSrcDirection=this.modulationSecondarySrc>>8&1,this.secSrcUsesCC=this.modulationSecondarySrc>>7&1,this.secSrcIndex=this.modulationSecondarySrc&127,this.secSrcCurveType=this.modulationSecondarySrc>>10&3}sumTransform(A){return new t({srcEnum:this.modulatorSource,secSrcEnum:this.modulationSecondarySrc,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(n,o){return Object.keys(n).find(C=>n[C]===o)}let e=A(lA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(p,this.sourceIndex):e+=A(P,this.sourceIndex);let s=A(lA,this.secSrcCurveType);return s+=this.secSrcPolarity===0?" unipolar ":" bipolar ",s+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?s+=A(p,this.secSrcIndex):s+=A(P,this.secSrcIndex),`Modulator: +var is=(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 Se(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 lt(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 as(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function hA(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},gs={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var AA={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},re={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},bA=-1,mA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var Cs=!0,Es=!0,Ye=!0,Bs=!0;function hs(t,A,e,s){Cs=t,Es=A,Ye=e,Bs=s}function m(...t){Cs&&console.info(...t)}function b(...t){Es&&console.warn(...t)}function Qs(...t){Bs&&console.table(...t)}function Ae(...t){Ye&&console.group(...t)}function pA(...t){Ye&&console.groupCollapsed(...t)}function Z(){Ye&&console.groupEnd()}var ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var cs="spessasynth-worklet-system",ls=450,SA=9,Je=16,qe="gs";var MA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},kA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function WA(t,A){let e=0;for(let s=8*(A-1);s>=0;s-=8)e|=t[t.currentIndex++]<>>0}function us(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=ye(t.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=s,e.status){case w.noteOn:let n=t.messageData[1];if(n>0)this.synth.noteOn(e.channel,t.messageData[0],n),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:n});else{this.synth.noteOff(e.channel,t.messageData[0]);let C=this.playingNotes.findIndex(g=>g.midiNote===t.messageData[0]&&g.channel===e.channel);C!==-1&&this.playingNotes.splice(C,1)}break;case w.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case w.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case w.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case w.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case w.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case w.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case w.systemExclusive:this.synth.systemExclusive(t.messageData,s);break;case w.setTempo:this.oneTickToSeconds=60/(Do(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),b("invalid tempo! falling back to 120 BPM"));break;case w.timeSignature:case w.endOfTrack:case w.midiChannelPrefix:case w.songPosition:case w.activeSensing:case w.keySignature:break;case w.text:case w.lyric:case w.copyright:case w.trackName:case w.marker:case w.cuePoint:case w.instrumentName:this.post(kA.textEvent,[t.messageData,e.status]);break;case w.midiPort:this.assignMIDIPort(A,t.messageData[0]);break;case w.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:b(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(w).find(C=>w[C]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function ds(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Do(t){return t.messageData.currentIndex=0,6e7/WA(t.messageData,3)}function fs(){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.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop){this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function ms(){let t=0,A=1/0;return this.tracks.forEach((e,s)=>{this.eventIndex[s]>=e.length||e[this.eventIndex[s]].ticksg===p.dataDecrement||g===p.dataIncrement||g===p.dataEntryMsb||g===p.dataDecrement||g===p.lsbForControl6DataEntry||g===p.RPNLsb||g===p.RPNMsb||g===p.NRPNLsb||g===p.NRPNMsb||g===p.bankSelect||g===p.lsbForControl0BankSelect||g===p.resetAllControllers,C=[];for(let g=0;g=A)break}else if(this.playedTime>=t)break;let Q=ye(h.messageStatusByte),d=Q.channel+(this.midiPortChannelOffsets[this.midiPorts[g]]||0);switch(Q.status){case w.noteOn:case w.noteOff:case w.keySignature:break;case w.pitchBend:s[d]=h.messageData[1]<<7|h.messageData[0];break;case w.programChange:let c=n[d];c.program=h.messageData[0],c.actualBank=c.bank;break;case w.controllerChange:let u=h.messageData[0];if(o(u))if(this.sendMIDIMessages)this.sendMIDIMessage([w.controllerChange|d%16,u,h.messageData[1]]);else{let y=h.messageData[1];if(u===p.bankSelect){n[d].bank=y;break}this.synth.controllerChange(d,u,y)}else C[d]===void 0&&(C[d]=Array.from(qA)),C[d][u]=h.messageData[1];break;default:this._processEvent(h,g);break}this.eventIndex[g]++,g=this._findFirstEventIndex();let l=this.tracks[g][this.eventIndex[g]];if(l===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(l.ticks-h.ticks)}if(this.sendMIDIMessages){for(let g=0;g>7]),C[g].forEach((h,Q)=>{h!==qA[Q]&&!o(Q)&&this.sendMIDIMessage([w.controllerChange|g%16,Q,h])}),n[g].program>=0&&n[g].actualBank>=0){let h=n[g].actualBank;this.sendMIDIMessage([w.controllerChange|g%16,p.bankSelect,h]),this.sendMIDIMessage([w.programChange|g%16,n[g].program])}}else for(let g=0;g>7,s[g]&127),C[g]!==void 0&&C[g].forEach((h,Q)=>{h!==qA[Q]&&!o(Q)&&this.synth.controllerChange(g,Q,h)}),n[g].program>=0&&n[g].actualBank>=0){let h=n[g].actualBank;this.synth.controllerChange(g,p.bankSelect,h),this.synth.programChange(g,n[g].program)}return!0}function Ss(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 Ke(t,A,e){if(A<=0)return 0;let s=t.find(o=>o.ticks>>0}function ae(t,A,e){for(let s=0;s>s*8&255}function Y(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function cA(t,A){ae(t,A,4)}function Ie(t,A){let e=A<<8|t;return e>32767?e-65536:e}function ks(t){return t>127?t-256:t}function V(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 C=0;C127){if(s){n=!0;continue}else if(g===0){n=!0;continue}}o+=String.fromCharCode(g)}}return o}}function wA(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,V(e.chunkData,4)===A))}function Pe(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var I={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},T=[];T[I.startAddrsOffset]={min:0,max:32768,def:0};T[I.endAddrOffset]={min:-32768,max:32768,def:0};T[I.startloopAddrsOffset]={min:-32768,max:32768,def:0};T[I.endloopAddrsOffset]={min:-32768,max:32768,def:0};T[I.startAddrsCoarseOffset]={min:0,max:32768,def:0};T[I.modLfoToPitch]={min:-12e3,max:12e3,def:0};T[I.vibLfoToPitch]={min:-12e3,max:12e3,def:0};T[I.modEnvToPitch]={min:-12e3,max:12e3,def:0};T[I.initialFilterFc]={min:1500,max:13500,def:13500};T[I.initialFilterQ]={min:0,max:960,def:0};T[I.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};T[I.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};T[I.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[I.modLfoToVolume]={min:-960,max:960,def:0};T[I.chorusEffectsSend]={min:0,max:1e3,def:0};T[I.reverbEffectsSend]={min:0,max:1e3,def:0};T[I.pan]={min:-500,max:500,def:0};T[I.delayModLFO]={min:-12e3,max:5e3,def:-12e3};T[I.freqModLFO]={min:-16e3,max:4500,def:0};T[I.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};T[I.freqVibLFO]={min:-16e3,max:4500,def:0};T[I.delayModEnv]={min:-32768,max:5e3,def:-32768};T[I.attackModEnv]={min:-32768,max:8e3,def:-32768};T[I.holdModEnv]={min:-12e3,max:5e3,def:-12e3};T[I.decayModEnv]={min:-12e3,max:8e3,def:-12e3};T[I.sustainModEnv]={min:0,max:1e3,def:0};T[I.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};T[I.keyNumToModEnvHold]={min:-1200,max:1200,def:0};T[I.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};T[I.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};T[I.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};T[I.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};T[I.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};T[I.sustainVolEnv]={min:0,max:1440,def:0};T[I.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};T[I.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};T[I.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};T[I.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[I.keyNum]={min:-1,max:127,def:-1};T[I.velocity]={min:-1,max:127,def:-1};T[I.initialAttenuation]={min:-250,max:1440,def:0};T[I.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[I.coarseTune]={min:-120,max:120,def:0};T[I.fineTune]={min:-99,max:99,def:0};T[I.scaleTuning]={min:0,max:1200,def:100};T[I.exclusiveClass]={min:0,max:99999,def:0};T[I.overridingRootKey]={min:-1,max:127,def:-1};var U=class{constructor(A=I.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let s=T[A];this.generatorValue=Math.round(e),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}generatorType=I.INVALID;generatorValue=0};function ws(t,A,e){let s=T[t]||{min:0,max:32768,def:0},n=A.find(Q=>Q.generatorType===t),o=0;n&&(o=n.generatorValue);let C=e.find(Q=>Q.generatorType===t),g=s.def;C&&(g=C.generatorValue);let h=g+o;return t===I.initialAttenuation?h:Math.max(s.min,Math.min(s.max,h))}var ut=class extends U{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=Ie(A[e+2],A[e+3]),A.currentIndex+=4}};function dt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new ut(t.chunkData));return A.length>1&&A.pop(),A}var P={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},lA={linear:0,concave:1,convex:2,switch:3},ko=[];for(let t=0;t<4;t++)ko.push([[],[]]);var rA=class t{constructor(A){A.srcEnum?(this.modulatorSource=A.srcEnum,this.modulatorDestination=A.dest,this.modulationSecondarySrc=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform):(this.modulatorSource=D(A,2),this.modulatorDestination=D(A,2),this.transformAmount=Ie(A[A.currentIndex++],A[A.currentIndex++]),this.modulationSecondarySrc=D(A,2),this.transformType=D(A,2)),this.modulatorDestination>58&&(this.modulatorDestination=I.INVALID),this.sourcePolarity=this.modulatorSource>>9&1,this.sourceDirection=this.modulatorSource>>8&1,this.sourceUsesCC=this.modulatorSource>>7&1,this.sourceIndex=this.modulatorSource&127,this.sourceCurveType=this.modulatorSource>>10&3,this.secSrcPolarity=this.modulationSecondarySrc>>9&1,this.secSrcDirection=this.modulationSecondarySrc>>8&1,this.secSrcUsesCC=this.modulationSecondarySrc>>7&1,this.secSrcIndex=this.modulationSecondarySrc&127,this.secSrcCurveType=this.modulationSecondarySrc>>10&3}sumTransform(A){return new t({srcEnum:this.modulatorSource,secSrcEnum:this.modulationSecondarySrc,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(n,o){return Object.keys(n).find(C=>n[C]===o)}let e=A(lA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(p,this.sourceIndex):e+=A(P,this.sourceIndex);let s=A(lA,this.secSrcCurveType);return s+=this.secSrcPolarity===0?" unipolar ":" bipolar ",s+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?s+=A(p,this.secSrcIndex):s+=A(P,this.secSrcIndex),`Modulator: Source: ${e} Secondary source: ${s} Destination: ${A(I,this.modulatorDestination)} @@ -8,7 +8,7 @@ var is=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>( `}};function KA(t,A,e,s,n){return t<<10|A<<9|e<<8|s<<7|n}var ft=960,mt=lA.concave,Fs=[new rA({srcEnum:KA(mt,0,1,0,P.noteOnVelocity),dest:I.initialAttenuation,amt:ft,secSrcEnum:0,transform:0}),new rA({srcEnum:129,dest:I.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(mt,0,1,1,p.mainVolume),dest:I.initialAttenuation,amt:ft,secSrcEnum:0,transform:0}),new rA({srcEnum:13,dest:I.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new rA({srcEnum:526,dest:I.fineTune,amt:12700,secSrcEnum:16,transform:0}),new rA({srcEnum:650,dest:I.pan,amt:1e3,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(mt,0,1,1,p.expressionController),dest:I.initialAttenuation,amt:ft,secSrcEnum:0,transform:0}),new rA({srcEnum:219,dest:I.reverbEffectsSend,amt:200,secSrcEnum:0,transform:0}),new rA({srcEnum:221,dest:I.chorusEffectsSend,amt:200,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(lA.linear,0,0,0,P.polyPressure),dest:I.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(lA.linear,0,0,1,p.effects2Depth),dest:I.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(lA.linear,1,0,1,p.releaseTime),dest:I.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(lA.linear,1,0,1,p.brightness),dest:I.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0})];function pt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new rA(t.chunkData));return A}function Rs(t=!1){let A={midiControllers:new Int16Array(St),lockedControllers:Array(St).fill(!1),customControllers:new Float32Array(Gs),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:uA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),channelVibrato:{delay:0,depth:0,rate:0},lockVibrato:!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 gA=128,St=147,vA=new Int16Array(St).fill(0);vA[p.mainVolume]=12800;vA[p.expressionController]=16256;vA[p.pan]=8192;vA[p.releaseTime]=8192;vA[p.brightness]=8192;vA[p.effects1Depth]=5120;vA[gA+P.pitchWheel]=8192;vA[gA+P.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},Gs=Object.keys(iA).length,yt=new Float32Array(Gs);yt[iA.modulationMultiplier]=1;var Ve={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 Oe=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=[]}_ticksToSeconds(A){let e=0;for(;A>0;){let s=this.tempoChanges.find(o=>o.ticks0&&(W+=this.tracks[S-1][this.tracks[S-1].length-1].ticks);x.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=W),K=gs[a>>4],(a&240)===w.noteOn){N.add(sA);let IA=x.data[x.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,IA),this.keyRange.max=Math.max(this.keyRange.max,IA)}M=a;break}let z=new H(K),$=x.data.slice(x.data.currentIndex,x.data.currentIndex+K);x.data.currentIndex+=K,z.set($,0);let QA=new oe(W,a,z);switch(k.push(QA),sA){case-2:switch(a){case w.setTempo:this.tempoChanges.push({ticks:W,tempo:6e7/WA($,3)});break;case w.marker:switch(V(z,z.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=W;break;case"loopend":l=W}z.currentIndex=0;break;case w.midiPort:let TA=z[0];this.midiPorts[S]=TA,this.midiPortChannelOffsets[TA]===void 0&&(this.midiPortChannelOffsets[TA]=c,c+=16);break;case w.copyright:o||(this.copyright+=V(z,z.length,void 0,!1)+` `);break;case w.lyric:this.lyrics.push(z)}break;case-3:if(hA(z.slice(0,7)).trim()==="41 10 45 12 10 00 00"){let IA=z.slice(7,$.length-3),TA=V(IA,IA.length)+` -`;this.copyright+=TA,m(`%cDecoded Roland SC message! %c${TA}`,r.recognized,r.value)}break;default:if((a&240)===w.controllerChange)switch(z[0]){case 2:case 116:d=W;break;case 4:case 117:l===null?l=W:l=0;break;case 0:g&&z[1]!==0&&z[1]!==127&&(m("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(k),this.usedChannelsOnTrack.push(N),m(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,r.info,r.value,r.info,r.value)}m("%cAll tracks parsed correctly!",r.recognized),pA("%cCorrecting loops, ports and detecting notes...",r.info);let u=[];for(let S of this.tracks){let k=S.find(x=>(x.messageStatusByte&240)===w.noteOn);k&&u.push(k.ticks)}this.firstNoteOn=Math.min(...u),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&l===null?(d=this.firstNoteOn,l=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(l===null||l===0)&&(l=this.lastVoiceEventTick)),this.loop={start:d,end:l},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 S of this.midiPorts)if(S!==-1){y=S;break}if(this.midiPorts=this.midiPorts.map(S=>S===-1?y:S),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?m("%cNo additional MIDI Ports detected.",r.info):m("%cMIDI Ports detected!",r.recognized),!C)if(this.tracks.length>1){if(this.tracks[0].find(S=>S.messageStatusByte>=w.noteOn&&S.messageStatusBytek.messageStatusByte===w.trackName);S&&(this.rawMidiName=S.messageData,this.midiName=V(S.messageData,S.messageData.length,void 0,!1))}}else{let S=this.tracks[0].find(k=>k.messageStatusByte===w.trackName);S&&(this.rawMidiName=S.messageData,this.midiName=V(S.messageData,S.messageData.length,void 0,!1))}if(this.fileName=e,this.midiName=this.midiName.trim(),this.midiName.length===0){m("%cNo name detected. Using the alt name!",r.info),this.midiName=as(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let S=0;Sc>l?c:l),s=[];for(let l=0;l{C[y]>=u.length||u[C[y]].ticks0;){let l=h(),c=t.tracks[l];if(C[l]>=c.length){g--;continue}let u=c[C[l]];if(C[l]++,u.messageStatusByte===w.midiPort){Q[l]=u.messageData[0];continue}let y=u.messageStatusByte&240;if(y!==w.noteOn&&y!==w.controllerChange&&y!==w.programChange&&y!==w.systemExclusive)continue;let S=(u.messageStatusByte&15)+t.midiPortChannelOffsets[Q[l]]||0,k=s[S];switch(y){case w.programChange:k.program=u.messageData[0],n(k);break;case w.controllerChange:if(u.messageData[0]!==p.bankSelect||d==="gs"&&k.drums)continue;let x=u.messageData[1],N=Math.max(0,x-t.bankOffset);if(d==="xg"){let J=x===120||x===126||x===127;J!==k.drums?(k.drums=J,k.bank=k.drums?128:N,n(k)):k.bank=k.drums?128:N;continue}s[S].bank=N;break;case w.noteOn:if(u.messageData[1]===0)continue;n(k),o[k.string].add(`${u.messageData[0]}-${u.messageData[1]}`);break;case w.systemExclusive:if(u.messageData[0]!==65||u.messageData[2]!==66||u.messageData[3]!==18||u.messageData[4]!==64||!(u.messageData[5]&16)||u.messageData[6]!==21){u.messageData[0]===67&&u.messageData[2]===76&&u.messageData[5]===126&&u.messageData[6]===0&&(d="xg");continue}let M=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+t.midiPortChannelOffsets[Q[l]],W=!!(u.messageData[7]>0&&u.messageData[5]>>4);k=s[M],k.drums=W,k.bank=W?128:0,n(k);break}}for(let l of Object.keys(o))o[l].size===0&&(m(`%cDetected change but no keys for %c${l}`,r.info,r.value),delete o[l]);return Z(),o}function Ms(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=Ke(this.midiData.tempoChanges,this.midiData.firstNoteOn,this.midiData.timeDivision),m(`%cTotal song time: ${lt(Math.ceil(this.duration)).time}`,r.recognized),this.post(kA.songChange,[new ve(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(b(`%cVery short song: (${lt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function bs(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(kA.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 Ls(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Us(){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])}function Ts(t,A){switch(t){default:break;case MA.loadNewSongList:this.loadNewSongList(A);break;case MA.pause:this.pause();break;case MA.play:this.play(A);break;case MA.stop:this.stop();break;case MA.setTime:this.currentTime=A;break;case MA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case MA.setPlaybackRate:this.playbackRate=A;break;case MA.setLoop:this.loop=A;break;case MA.changeSong:A?this.nextSong():this.previousSong();break;case MA.getMIDI:this.post(kA.getMIDI,this.midiData);break;case MA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Hs(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:mA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Ys(t){this.post(kA.midiEvent,t)}var CA=class{constructor(A){this.synth=A,this.ignoreEvents=!1,this.sendMIDIMessages=!1,this.eventIndex=[],this.songIndex=0,this.playedTime=0,this.pausedTime=void 0,this.absoluteStartTime=currentTime,this._playbackRate=1,this.playingNotes=[],this.loop=!0,this.midiData=void 0,this.midiPorts=[],this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this._skipToFirstNoteOn=!0}set playbackRate(A){let e=this.currentTime;this._playbackRate=A,this.currentTime=e}get currentTime(){return this.pausedTime?this.pausedTime:(currentTime-this.absoluteStartTime)*this._playbackRate}set currentTime(A){if(A>this.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&AJs?440*Math.pow(2,(t-6900)/1200):kt[~~t-Xe]}var Ft=-1660,wo=1600,wt=new Float32Array((wo-Ft)*100+1);for(let t=0;t.5?1:0,s?e*2-1:e;case lA.concave:return s?(e=e*2-1,e<0?1-ge[~~(e*-aA)]-1:ge[~~e*aA]):ge[~~(e*aA)];case lA.convex:return s?(e=e*2-1,e<0?1-Ce[~~(e*-aA)]-1:Ce[~~(e*aA)]):Ce[~~(e*aA)]}}var Rt=1,Gt=new Float32Array(1e3);for(let t=0;t=t.sample.loopEnd;)e-=o;let g=~~e,h=g+1;for(;h>=t.sample.loopEnd;)h-=o;let Q=e-g,d=n[h],l=n[g];A[C]=l+(d-l)*Q,e+=t.sample.playbackStep*t.currentTuningCalculated}}else{t.sample.end>=n.length&&(t.sample.end=n.length-1);for(let o=0;o=t.sample.end){t.finished=!0;return}let h=e-C,Q=n[g],d=n[C];A[o]=d+(Q-d)*h,e+=t.sample.playbackStep*t.currentTuningCalculated}}t.sample.cursor=e}function Ks(t,A){let e=t.sample.cursor,s=t.sample.loopingMode===1||t.sample.loopingMode===3&&!t.isInRelease,n=t.sample.loopEnd-t.sample.loopStart,o=t.sample.sampleData;if(s)for(let C=0;C=t.sample.loopEnd;)e-=n;let g=~~e+1;for(;g>=t.sample.loopEnd;)g-=n;A[C]=o[g],e+=t.sample.playbackStep*t.currentTuningCalculated}else{t.sample.end>=o.length&&(t.sample.end=o.length-1);for(let C=0;C=t.sample.end){t.finished=!0;return}A[C]=o[g],e+=t.sample.playbackStep*t.currentTuningCalculated}}t.sample.cursor=e}function vs(t,A,e,s,n,o,C,g,h){if(!isNaN(e[0])){if(C>0){let Q=o[0],d=o[1];C=Math.min(C,1e3);let l=C/800,c=t*l,u=A*l;for(let y=0;y0){let Q=g[0],d=g[1];h=Math.min(h,1e3);let l=h/800,c=t*l,u=A*l;for(let y=0;y0)for(let Q=0;Q0)for(let Q=0;Q13499)){(A.filter.cutoffCents!==s||A.filter.reasonanceCb!==A.modulatedGenerators[I.initialFilterQ])&&(A.filter.cutoffCents=s,A.filter.reasonanceCb=A.modulatedGenerators[I.initialFilterQ],t.calculateCoefficients(A));for(let n=0;n.45*sampleRate&&(A.filter.cutoffHz=.45*sampleRate);let e=A.filter.reasonanceCb/10-3.01;A.filter.reasonanceGain=_A(-1*e);let s=1/Math.sqrt(A.filter.reasonanceGain),n=2*Math.PI*A.filter.cutoffHz/sampleRate,o=Math.cos(n),C=Math.sin(n)/(2*A.filter.reasonanceGain),g=(1-o)*s,h=g/2,Q=h,d=1+C,l=-2*o,c=1-C;A.filter.a0=h/d,A.filter.a1=g/d,A.filter.a2=Q/d,A.filter.a3=l/d,A.filter.a4=c/d}};var Ps=.001,ke=100,xt=70,NA=class t{constructor(A){this.sampleRate=A}currentSampleTime=0;sampleRate;currentAttenuationDb=ke;state=0;releaseStartDb=100;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;sustainDb=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=_A(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static recalculate(A){let e=A.volumeEnvelope,s=h=>Math.floor(LA(h)*e.sampleRate);e.attenuation=Math.max(0,Math.min(A.modulatedGenerators[I.initialAttenuation],1440))/10,e.sustainDb=Math.min(100,A.volumeEnvelope.attenuation+A.modulatedGenerators[I.sustainVolEnv]/10),e.attackDuration=s(A.modulatedGenerators[I.attackVolEnv]);let n=A.modulatedGenerators[I.decayVolEnv],o=(60-A.targetKey)*A.modulatedGenerators[I.keyNumToVolEnvDecay],C=(e.sustainDb-e.attenuation)/100;e.decayDuration=s(n+o)*C,e.releaseDuration=s(A.modulatedGenerators[I.releaseVolEnv]),e.delayEnd=s(A.modulatedGenerators[I.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let g=(60-A.targetKey)*A.modulatedGenerators[I.keyNumToVolEnvHold];if(e.holdEnd=s(A.modulatedGenerators[I.holdVolEnv]+g)+e.attackEnd,e.decayEnd=e.decayDuration+e.holdEnd,e.state===0&&e.attackEnd===0&&(e.currentAttenuationDb=e.attenuation,e.state=2),A.isInRelease){switch(e.state){case 0:e.releaseStartDb=ke;break;case 1:let Q=(1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration)*_A(e.attenuation);e.releaseStartDb=20*Math.log10(Q)*-1;break;case 2:e.releaseStartDb=e.attenuation;break;case 3:e.releaseStartDb=(1-(e.decayEnd-e.releaseStartTimeSamples)/e.decayDuration)*(e.sustainDb-e.attenuation)+e.attenuation;break;case 4:e.releaseStartDb=e.sustainDb;break;default:e.releaseStartDb=e.currentAttenuationDb}e.releaseStartDb=Math.min(e.releaseStartDb,ke),e.releaseStartDb>=xt&&(A.finished=!0)}}static getInterpolatedGain(A,e,s){return A.currentAttenuationDb+=(e-A.currentAttenuationDb)*s,_A(A.currentAttenuationDb)}static apply(A,e,s,n){let o=A.volumeEnvelope,C=s/10;if(A.isInRelease){let h=n*10,Q=o.currentSampleTime-o.releaseStartTimeSamples;if(Q>=o.releaseDuration){for(let c=0;c=xt&&(A.finished=!0);return}let g=0;switch(o.state){case 0:for(;o.currentSampleTime=e.length)return;o.state++;case 1:for(;o.currentSampleTime=e.length)return}o.state++;case 2:for(;o.currentSampleTime=e.length)return;o.state++;case 3:let h=o.sustainDb-o.attenuation;for(;o.currentSampleTime=e.length)return}o.state++;case 4:if(o.sustainDb>xt){for(;g=e.length)return}}};var Vs=Math.PI/2,Os=.01;function Zs(t,A,e,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,NA.startRelease(A),UA.startRelease(A)),A.modulatedGenerators[I.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let C=A.targetKey,g=A.modulatedGenerators[I.fineTune]+t.customControllers[iA.channelTuning]+t.customControllers[iA.channelTransposeFine]+t.customControllers[iA.masterTuning]+t.channelOctaveTuning[A.midiNote%12],h=A.modulatedGenerators[I.coarseTune]+t.customControllers[iA.channelTuningSemitones],Q=this.tunings[t.preset.program]?.[C];Q?.midiNote>=0&&(C=Q.midiNote,g+=Q.centTuning),g+=(C-A.sample.rootKey)*A.modulatedGenerators[I.scaleTuning];let d=A.modulatedGenerators[I.vibLfoToPitch];if(d!==0){let $=A.startTime+LA(A.modulatedGenerators[I.delayVibLFO]),QA=De(A.modulatedGenerators[I.freqVibLFO]),IA=We($,QA,currentTime);g+=IA*(d*t.customControllers[iA.modulationMultiplier])}let l=A.modulatedGenerators[I.initialFilterFc],c=A.modulatedGenerators[I.modLfoToPitch],u=A.modulatedGenerators[I.modLfoToVolume],y=A.modulatedGenerators[I.modLfoToFilterFc],S=0;if(c+y+u!==0){let $=A.startTime+LA(A.modulatedGenerators[I.delayModLFO]),QA=De(A.modulatedGenerators[I.freqModLFO]),IA=We($,QA,currentTime);g+=IA*(c*t.customControllers[iA.modulationMultiplier]),S=-IA*u,l+=IA*y}if(t.channelVibrato.depth>0){let $=We(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);$&&(g+=$*t.channelVibrato.depth)}let k=A.modulatedGenerators[I.modEnvToPitch],x=A.modulatedGenerators[I.modEnvToFilterFc],N=UA.getValue(A,currentTime);l+=N*x,g+=N*k;let M=~~(g+h*100);M!==A.currentTuningCents&&(A.currentTuningCents=M,A.currentTuningCalculated=Math.pow(2,M/1200));let W=(Math.max(-500,Math.min(500,A.modulatedGenerators[I.pan]))+500)/1e3,J=new Float32Array(e.length);this.interpolationType===_e.linear?qs(A,J):Ks(A,J),Ee.apply(A,J,l),NA.apply(A,J,S,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(W-A.currentPan)*this.panSmoothingFactor;let a=Math.cos(Vs*A.currentPan)*this.panLeft,sA=Math.sin(Vs*A.currentPan)*this.panRight,K=this.oneOutputMode?0:A.modulatedGenerators[I.reverbEffectsSend],z=this.oneOutputMode?0:A.modulatedGenerators[I.chorusEffectsSend];vs(a,sA,J,e,s,n,K,o,z)}function Fo(t,A){let e=0;return t.drumChannel&&(e+=5),A.isInRelease&&(e-=5),e+=A.velocity/25,e-=A.volumeEnvelope.state,A.isInRelease&&(e-=5),e-=A.volumeEnvelope.currentAttenuationDb/50,e}function Xs(t){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=Fo(s,n);A.push({channel:s,voice:n,priority:o})}A.sort((s,n)=>s.priority-n.priority);let e=A.slice(0,t);for(let{channel:s,voice:n}of e){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function Ws(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimezs=t);var Ro=function(t){var A,e,s,n,o,C,g,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Q="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=h.indexOf(t.charAt(d++)),o=h.indexOf(t.charAt(d++)),C=h.indexOf(t.charAt(d++)),g=h.indexOf(t.charAt(d++)),A=n<<2|o>>4,e=(15&o)<<4|C>>2,s=(3&C)<<6|g,Q+=String.fromCharCode(A),C!==64&&(Q+=String.fromCharCode(e)),g!==64&&(Q+=String.fromCharCode(s));while(d1&&(a.thisProgram=process.argv[1].replace(/\\/g,"/")),a.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(i){if(!(i instanceof fe))throw i}),process.on("unhandledRejection",function(i,E){process.exit(1)}),a.quit=function(i){process.exit(i)},a.inspect=function(){return"[Emscripten Module object]"}):QA?(typeof read<"u"&&(a.read=function(E){return read(E)}),a.readBinary=function(E){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(XA(typeof(B=read(E,"binary"))=="object"),B)},typeof scriptArgs<"u"?a.arguments=scriptArgs:typeof arguments<"u"&&(a.arguments=arguments),typeof quit=="function"&&(a.quit=function(i){quit(i)})):(K||z)&&(K?document.currentScript&&(IA=document.currentScript.src):IA=self.location.href,IA=IA.indexOf("blob:")!==0?IA.split("/").slice(0,-1).join("/")+"/":"",a.read=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.send(null),B.responseText},z&&(a.readBinary=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.responseType="arraybuffer",B.send(null),new Uint8Array(B.response)}),a.readAsync=function(E,B,f){var F=new XMLHttpRequest;F.open("GET",E,!0),F.responseType="arraybuffer",F.onload=function(){if(F.status==200||F.status==0&&F.response){B(F.response);return}f()},F.onerror=f,F.send(null)},a.setWindowTitle=function(i){document.title=i});var Jt=a.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),HA=a.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Jt);for(t in sA)sA.hasOwnProperty(t)&&(a[t]=sA[t]);function Ge(i){var E=u;return u=u+i+15&-16,E}function qt(i){var E=h[M>>2],B=E+i+15&-16;return h[M>>2]=B,B>=EA&&!zt()?(h[M>>2]=E,0):E}function Kt(i,E){return E||(E=16),i=Math.ceil(i/E)*E}function Co(i){switch(i){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(i[i.length-1]==="*")return 4;if(i[0]!=="i")return 0;var E=parseInt(i.substr(1));return XA(E%8==0),E/8}}function le(i){le.shown||(le.shown={}),le.shown[i]||(le.shown[i]=1,HA(i))}sA=void 0;var Eo={"f64-rem":function(i,E){return i%E},debugger:function(){}},st=[];function Lo(i,E){for(var B=0,f=B;f>>0)+4294967296*+(E>>>0):+(i>>>0)+4294967296*+(0|E)}function ot(i,E,B){return B&&B.length?a["dynCall_"+i].apply(null,[E].concat(B)):a["dynCall_"+i].call(null,E)}var xe=0,vt=0;function XA(i,E){i||VA("Assertion failed: "+E)}function Pt(i){var E=a["_"+i];return XA(E,"Cannot call unknown function "+i+", make sure it is exported"),E}var Vt={stackSave:function(){Bt()},stackRestore:function(){Et()},arrayToC:function(i){var E,B,f=Te(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=Te(B),Xt(i,E,B)}return E}},Bo={string:Vt.stringToC,array:Vt.arrayToC};function Ot(i,E,B,f,F){var v=Pt(i),X=[],G=0;if(f)for(var BA=0;BA>0]=E;break;case"i16":C[i>>1]=E;break;case"i32":h[i>>2]=E;break;case"i64":tempI64=[E>>>0,+fo(tempDouble=E)>=1?tempDouble>0?(0|po(+ts(tempDouble/4294967296),4294967295))>>>0:~~+mo((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],h[i>>2]=tempI64[0],h[i+4>>2]=tempI64[1];break;case"float":d[i>>2]=E;break;case"double":l[i>>3]=E;break;default:VA("invalid type for setValue: "+B)}}function Yo(i,E,B){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return n[i>>0];case"i16":return C[i>>1];case"i32":case"i64":return h[i>>2];case"float":return d[i>>2];case"double":return l[i>>3];default:VA("invalid type for getValue: "+E)}return null}function Jo(i,E,B,f){typeof i=="number"?(v=!0,X=i):(v=!1,X=i.length);var F=typeof E=="string"?E:null;if(G=B==4?f:[typeof Ue=="function"?Ue:Ge,Te,Ge,qt][B===void 0?2:B](Math.max(X,F?1:E.length)),v){for(f=G,XA((3&G)==0),BA=G+(-4&X);f>2]=0;for(BA=G+X;f>0]=0;return G}if(F==="i8")return i.subarray||i.slice?o.set(i,G):o.set(new Uint8Array(i),G),G;for(var v,X,G,BA,nA,oA,eA,q=0;q>0],(f!=0||E)&&(X++,!E||X!=E););E||(E=X);var G="";if(v<128){for(;E>0;)F=String.fromCharCode.apply(String,o.subarray(i,i+Math.min(E,1024))),G=G?G+F:F,i+=1024,E-=1024;return G}return B=i,function(nA,oA){for(var eA=oA;nA[eA];)++eA;if(eA-oA>16&&nA.subarray&&Zt)return Zt.decode(nA.subarray(oA,eA));for(var q,fA,FA,RA,GA,$A,xA="";;){if(!(q=nA[oA++]))return xA;if(!(128&q)){xA+=String.fromCharCode(q);continue}if(fA=63&nA[oA++],(224&q)==192){xA+=String.fromCharCode((31&q)<<6|fA);continue}if(FA=63&nA[oA++],(240&q)==224?q=(15&q)<<12|fA<<6|FA:(RA=63&nA[oA++],(248&q)==240?q=(7&q)<<18|fA<<12|FA<<6|RA:(GA=63&nA[oA++],q=(252&q)==248?(3&q)<<24|fA<<18|FA<<12|RA<<6|GA:(1&q)<<30|fA<<24|FA<<18|RA<<12|GA<<6|($A=63&nA[oA++]))),q<65536)xA+=String.fromCharCode(q);else{var me=q-65536;xA+=String.fromCharCode(55296|me>>10,56320|1023&me)}}}(o,B)}function Ko(i){for(var E="";;){var B=n[i++>>0];if(!B)return E;E+=String.fromCharCode(B)}}function vo(i,E){return function(f,F,v){for(var X=0;X>0]=f.charCodeAt(X);v||(n[F>>0]=0)}(i,E,!1)}var Zt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ne(i,E,B,f){if(!(f>0))return 0;for(var F=B,v=B+f-1,X=0;X=55296&&G<=57343&&(G=65536+((1023&G)<<10)|1023&i.charCodeAt(++X)),G<=127){if(B>=v)break;E[B++]=G}else if(G<=2047){if(B+1>=v)break;E[B++]=192|G>>6,E[B++]=128|63&G}else if(G<=65535){if(B+2>=v)break;E[B++]=224|G>>12,E[B++]=128|G>>6&63,E[B++]=128|63&G}else if(G<=2097151){if(B+3>=v)break;E[B++]=240|G>>18,E[B++]=128|G>>12&63,E[B++]=128|G>>6&63,E[B++]=128|63&G}else if(G<=67108863){if(B+4>=v)break;E[B++]=248|G>>24,E[B++]=128|G>>18&63,E[B++]=128|G>>12&63,E[B++]=128|G>>6&63,E[B++]=128|63&G}else{if(B+5>=v)break;E[B++]=252|G>>30,E[B++]=128|G>>24&63,E[B++]=128|G>>18&63,E[B++]=128|G>>12&63,E[B++]=128|G>>6&63,E[B++]=128|63&G}}return E[B]=0,B-F}function Xt(i,E,B){return Ne(i,o,E,B)}function be(i){for(var E=0,B=0;B=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&i.charCodeAt(++B)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var Wt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function Po(i){for(var E=i,B=E>>1;C[B];)++B;if((E=B<<1)-i>32&&Wt)return Wt.decode(o.subarray(i,E));for(var f=0,F="";;){var v=C[i+2*f>>1];if(v==0)return F;++f,F+=String.fromCharCode(v)}}function Vo(i,E,B){if(B===void 0&&(B=2147483647),B<2)return 0;for(var f=E,F=(B-=2)<2*i.length?B/2:i.length,v=0;v>1]=X,E+=2}return C[E>>1]=0,E-f}function Oo(i){return 2*i.length}function Zo(i){for(var E=0,B="";;){var f=h[i+4*E>>2];if(f==0)return B;if(++E,f>=65536){var F=f-65536;B+=String.fromCharCode(55296|F>>10,56320|1023&F)}else B+=String.fromCharCode(f)}}function Xo(i,E,B){if(B===void 0&&(B=2147483647),B<4)return 0;for(var f=E,F=f+B-4,v=0;v=55296&&X<=57343&&(X=65536+((1023&X)<<10)|1023&i.charCodeAt(++v)),h[E>>2]=X,(E+=4)+4>F)break}return h[E>>2]=0,E-f}function Wo(i){for(var E=0,B=0;B=55296&&f<=57343&&++B,E+=4}return E}function _o(i){var E=be(i)+1,B=Ue(E);return B&&Ne(i,n,B,E),B}function zo(i){var E=be(i)+1,B=Te(E);return Ne(i,n,B,E),B}function jo(i){return i}function $o(){var i,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(F){f=F}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return a.extraStackTrace&&(E+=` +`;this.copyright+=TA,m(`%cDecoded Roland SC message! %c${TA}`,r.recognized,r.value)}break;default:if((a&240)===w.controllerChange)switch(z[0]){case 2:case 116:d=W;break;case 4:case 117:l===null?l=W:l=0;break;case 0:g&&z[1]!==0&&z[1]!==127&&(m("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(k),this.usedChannelsOnTrack.push(N),m(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,r.info,r.value,r.info,r.value)}m("%cAll tracks parsed correctly!",r.recognized),pA("%cCorrecting loops, ports and detecting notes...",r.info);let u=[];for(let S of this.tracks){let k=S.find(x=>(x.messageStatusByte&240)===w.noteOn);k&&u.push(k.ticks)}this.firstNoteOn=Math.min(...u),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&l===null?(d=this.firstNoteOn,l=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(l===null||l===0)&&(l=this.lastVoiceEventTick)),this.loop={start:d,end:l},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 S of this.midiPorts)if(S!==-1){y=S;break}if(this.midiPorts=this.midiPorts.map(S=>S===-1?y:S),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?m("%cNo additional MIDI Ports detected.",r.info):m("%cMIDI Ports detected!",r.recognized),!C)if(this.tracks.length>1){if(this.tracks[0].find(S=>S.messageStatusByte>=w.noteOn&&S.messageStatusBytek.messageStatusByte===w.trackName);S&&(this.rawMidiName=S.messageData,this.midiName=V(S.messageData,S.messageData.length,void 0,!1))}}else{let S=this.tracks[0].find(k=>k.messageStatusByte===w.trackName);S&&(this.rawMidiName=S.messageData,this.midiName=V(S.messageData,S.messageData.length,void 0,!1))}if(this.fileName=e,this.midiName=this.midiName.trim(),this.midiName.length===0){m("%cNo name detected. Using the alt name!",r.info),this.midiName=as(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let S=0;Sc>l?c:l),s=[];for(let l=0;l{C[y]>=u.length||u[C[y]].ticks0;){let l=h(),c=t.tracks[l];if(C[l]>=c.length){g--;continue}let u=c[C[l]];if(C[l]++,u.messageStatusByte===w.midiPort){Q[l]=u.messageData[0];continue}let y=u.messageStatusByte&240;if(y!==w.noteOn&&y!==w.controllerChange&&y!==w.programChange&&y!==w.systemExclusive)continue;let S=(u.messageStatusByte&15)+t.midiPortChannelOffsets[Q[l]]||0,k=s[S];switch(y){case w.programChange:k.program=u.messageData[0],n(k);break;case w.controllerChange:if(u.messageData[0]!==p.bankSelect||d==="gs"&&k.drums)continue;let x=u.messageData[1],N=Math.max(0,x-t.bankOffset);if(d==="xg"){let J=x===120||x===126||x===127;J!==k.drums?(k.drums=J,k.bank=k.drums?128:N,n(k)):k.bank=k.drums?128:N;continue}s[S].bank=N;break;case w.noteOn:if(u.messageData[1]===0)continue;n(k),o[k.string].add(`${u.messageData[0]}-${u.messageData[1]}`);break;case w.systemExclusive:if(u.messageData[0]!==65||u.messageData[2]!==66||u.messageData[3]!==18||u.messageData[4]!==64||!(u.messageData[5]&16)||u.messageData[6]!==21){u.messageData[0]===67&&u.messageData[2]===76&&u.messageData[5]===126&&u.messageData[6]===0&&(d="xg");continue}let M=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+t.midiPortChannelOffsets[Q[l]],W=!!(u.messageData[7]>0&&u.messageData[5]>>4);k=s[M],k.drums=W,k.bank=W?128:0,n(k);break}}for(let l of Object.keys(o))o[l].size===0&&(m(`%cDetected change but no keys for %c${l}`,r.info,r.value),delete o[l]);return Z(),o}function Ms(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=Ke(this.midiData.tempoChanges,this.midiData.firstNoteOn,this.midiData.timeDivision),m(`%cTotal song time: ${lt(Math.ceil(this.duration)).time}`,r.recognized),this.post(kA.songChange,[new ve(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(b(`%cVery short song: (${lt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function bs(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(kA.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 Ls(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Us(){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])}function Ts(t,A){switch(t){default:break;case MA.loadNewSongList:this.loadNewSongList(A);break;case MA.pause:this.pause();break;case MA.play:this.play(A);break;case MA.stop:this.stop();break;case MA.setTime:this.currentTime=A;break;case MA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case MA.setPlaybackRate:this.playbackRate=A;break;case MA.setLoop:this.loop=A;break;case MA.changeSong:A?this.nextSong():this.previousSong();break;case MA.getMIDI:this.post(kA.getMIDI,this.midiData);break;case MA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Hs(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:mA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Ys(t){this.post(kA.midiEvent,t)}var CA=class{constructor(A){this.synth=A,this.ignoreEvents=!1,this.sendMIDIMessages=!1,this.eventIndex=[],this.songIndex=0,this.playedTime=0,this.pausedTime=void 0,this.absoluteStartTime=currentTime,this._playbackRate=1,this.playingNotes=[],this.loop=!0,this.midiData=void 0,this.midiPorts=[],this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this._skipToFirstNoteOn=!0}set playbackRate(A){let e=this.currentTime;this._playbackRate=A,this.currentTime=e}get currentTime(){return this.pausedTime?this.pausedTime:(currentTime-this.absoluteStartTime)*this._playbackRate}set currentTime(A){if(A>this.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&AJs?440*Math.pow(2,(t-6900)/1200):kt[~~t-Xe]}var Ft=-1660,wo=1600,wt=new Float32Array((wo-Ft)*100+1);for(let t=0;t.5?1:0,s?e*2-1:e;case lA.concave:return s?(e=e*2-1,e<0?1-ge[~~(e*-aA)]-1:ge[~~e*aA]):ge[~~(e*aA)];case lA.convex:return s?(e=e*2-1,e<0?1-Ce[~~(e*-aA)]-1:Ce[~~(e*aA)]):Ce[~~(e*aA)]}}var Rt=1,Gt=new Float32Array(1e3);for(let t=0;t=t.sample.loopEnd;)e-=o;let g=~~e,h=g+1;for(;h>=t.sample.loopEnd;)h-=o;let Q=e-g,d=n[h],l=n[g];A[C]=l+(d-l)*Q,e+=t.sample.playbackStep*t.currentTuningCalculated}}else{t.sample.end>=n.length&&(t.sample.end=n.length-1);for(let o=0;o=t.sample.end){t.finished=!0;return}let h=e-C,Q=n[g],d=n[C];A[o]=d+(Q-d)*h,e+=t.sample.playbackStep*t.currentTuningCalculated}}t.sample.cursor=e}function Ks(t,A){let e=t.sample.cursor,s=t.sample.loopingMode===1||t.sample.loopingMode===3&&!t.isInRelease,n=t.sample.loopEnd-t.sample.loopStart,o=t.sample.sampleData;if(s)for(let C=0;C=t.sample.loopEnd;)e-=n;let g=~~e+1;for(;g>=t.sample.loopEnd;)g-=n;A[C]=o[g],e+=t.sample.playbackStep*t.currentTuningCalculated}else{t.sample.end>=o.length&&(t.sample.end=o.length-1);for(let C=0;C=t.sample.end){t.finished=!0;return}A[C]=o[g],e+=t.sample.playbackStep*t.currentTuningCalculated}}t.sample.cursor=e}function vs(t,A,e,s,n,o,C,g,h){if(!isNaN(e[0])){if(C>0){let Q=o[0],d=o[1];C=Math.min(C,1e3);let l=C/800,c=t*l,u=A*l;for(let y=0;y0){let Q=g[0],d=g[1];h=Math.min(h,1e3);let l=h/800,c=t*l,u=A*l;for(let y=0;y0)for(let Q=0;Q0)for(let Q=0;Q13499)){(A.filter.cutoffCents!==s||A.filter.reasonanceCb!==A.modulatedGenerators[I.initialFilterQ])&&(A.filter.cutoffCents=s,A.filter.reasonanceCb=A.modulatedGenerators[I.initialFilterQ],t.calculateCoefficients(A));for(let n=0;n.45*sampleRate&&(A.filter.cutoffHz=.45*sampleRate);let e=A.filter.reasonanceCb/10-3.01;A.filter.reasonanceGain=_A(-1*e);let s=1/Math.sqrt(A.filter.reasonanceGain),n=2*Math.PI*A.filter.cutoffHz/sampleRate,o=Math.cos(n),C=Math.sin(n)/(2*A.filter.reasonanceGain),g=(1-o)*s,h=g/2,Q=h,d=1+C,l=-2*o,c=1-C;A.filter.a0=h/d,A.filter.a1=g/d,A.filter.a2=Q/d,A.filter.a3=l/d,A.filter.a4=c/d}};var Ps=.001,ke=100,xt=70,NA=class t{constructor(A){this.sampleRate=A}currentSampleTime=0;sampleRate;currentAttenuationDb=ke;state=0;releaseStartDb=100;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;sustainDb=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=_A(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static recalculate(A){let e=A.volumeEnvelope,s=h=>Math.floor(LA(h)*e.sampleRate);e.attenuation=Math.max(0,Math.min(A.modulatedGenerators[I.initialAttenuation],1440))/10,e.sustainDb=Math.min(100,A.volumeEnvelope.attenuation+A.modulatedGenerators[I.sustainVolEnv]/10),e.attackDuration=s(A.modulatedGenerators[I.attackVolEnv]);let n=A.modulatedGenerators[I.decayVolEnv],o=(60-A.targetKey)*A.modulatedGenerators[I.keyNumToVolEnvDecay],C=(e.sustainDb-e.attenuation)/100;e.decayDuration=s(n+o)*C,e.releaseDuration=s(A.modulatedGenerators[I.releaseVolEnv]),e.delayEnd=s(A.modulatedGenerators[I.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let g=(60-A.targetKey)*A.modulatedGenerators[I.keyNumToVolEnvHold];if(e.holdEnd=s(A.modulatedGenerators[I.holdVolEnv]+g)+e.attackEnd,e.decayEnd=e.decayDuration+e.holdEnd,e.state===0&&e.attackEnd===0&&(e.currentAttenuationDb=e.attenuation,e.state=2),A.isInRelease){switch(e.state){case 0:e.releaseStartDb=ke;break;case 1:let Q=(1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration)*_A(e.attenuation);e.releaseStartDb=20*Math.log10(Q)*-1;break;case 2:e.releaseStartDb=e.attenuation;break;case 3:e.releaseStartDb=(1-(e.decayEnd-e.releaseStartTimeSamples)/e.decayDuration)*(e.sustainDb-e.attenuation)+e.attenuation;break;case 4:e.releaseStartDb=e.sustainDb;break;default:e.releaseStartDb=e.currentAttenuationDb}e.releaseStartDb=Math.min(e.releaseStartDb,ke),e.releaseStartDb>=xt&&(A.finished=!0)}}static getInterpolatedGain(A,e,s){return A.currentAttenuationDb+=(e-A.currentAttenuationDb)*s,_A(A.currentAttenuationDb)}static apply(A,e,s,n){let o=A.volumeEnvelope,C=s/10;if(A.isInRelease){let h=n*10,Q=o.currentSampleTime-o.releaseStartTimeSamples;if(Q>=o.releaseDuration){for(let c=0;c=xt&&(A.finished=!0);return}let g=0;switch(o.state){case 0:for(;o.currentSampleTime=e.length)return;o.state++;case 1:for(;o.currentSampleTime=e.length)return}o.state++;case 2:for(;o.currentSampleTime=e.length)return;o.state++;case 3:let h=o.sustainDb-o.attenuation;for(;o.currentSampleTime=e.length)return}o.state++;case 4:if(o.sustainDb>xt){for(;g=e.length)return}}};var Vs=Math.PI/2,Os=.01;function Zs(t,A,e,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,NA.startRelease(A),UA.startRelease(A)),A.modulatedGenerators[I.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let C=A.targetKey,g=A.modulatedGenerators[I.fineTune]+t.customControllers[iA.channelTuning]+t.customControllers[iA.channelTransposeFine]+t.customControllers[iA.masterTuning]+t.channelOctaveTuning[A.midiNote%12],h=A.modulatedGenerators[I.coarseTune]+t.customControllers[iA.channelTuningSemitones],Q=this.tunings[t.preset.program]?.[C];Q?.midiNote>=0&&(C=Q.midiNote,g+=Q.centTuning),g+=(C-A.sample.rootKey)*A.modulatedGenerators[I.scaleTuning];let d=A.modulatedGenerators[I.vibLfoToPitch];if(d!==0){let $=A.startTime+LA(A.modulatedGenerators[I.delayVibLFO]),QA=De(A.modulatedGenerators[I.freqVibLFO]),IA=We($,QA,currentTime);g+=IA*(d*t.customControllers[iA.modulationMultiplier])}let l=A.modulatedGenerators[I.initialFilterFc],c=A.modulatedGenerators[I.modLfoToPitch],u=A.modulatedGenerators[I.modLfoToVolume],y=A.modulatedGenerators[I.modLfoToFilterFc],S=0;if(c+y+u!==0){let $=A.startTime+LA(A.modulatedGenerators[I.delayModLFO]),QA=De(A.modulatedGenerators[I.freqModLFO]),IA=We($,QA,currentTime);g+=IA*(c*t.customControllers[iA.modulationMultiplier]),S=-IA*u,l+=IA*y}if(t.channelVibrato.depth>0){let $=We(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);$&&(g+=$*t.channelVibrato.depth)}let k=A.modulatedGenerators[I.modEnvToPitch],x=A.modulatedGenerators[I.modEnvToFilterFc],N=UA.getValue(A,currentTime);l+=N*x,g+=N*k;let M=~~(g+h*100);M!==A.currentTuningCents&&(A.currentTuningCents=M,A.currentTuningCalculated=Math.pow(2,M/1200));let W=(Math.max(-500,Math.min(500,A.modulatedGenerators[I.pan]))+500)/1e3,J=new Float32Array(e.length);this.interpolationType===_e.linear?qs(A,J):Ks(A,J),Ee.apply(A,J,l),NA.apply(A,J,S,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(W-A.currentPan)*this.panSmoothingFactor;let a=Math.cos(Vs*A.currentPan)*this.panLeft,sA=Math.sin(Vs*A.currentPan)*this.panRight,K=this.oneOutputMode?0:A.modulatedGenerators[I.reverbEffectsSend],z=this.oneOutputMode?0:A.modulatedGenerators[I.chorusEffectsSend];vs(a,sA,J,e,s,n,K,o,z)}function Fo(t,A){let e=0;return t.drumChannel&&(e+=5),A.isInRelease&&(e-=5),e+=A.velocity/25,e-=A.volumeEnvelope.state,A.isInRelease&&(e-=5),e-=A.volumeEnvelope.currentAttenuationDb/50,e}function Xs(t){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=Fo(s,n);A.push({channel:s,voice:n,priority:o})}A.sort((s,n)=>s.priority-n.priority);let e=A.slice(0,t);for(let{channel:s,voice:n}of e){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function Ws(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimezs=t);var Ro=function(t){var A,e,s,n,o,C,g,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Q="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=h.indexOf(t.charAt(d++)),o=h.indexOf(t.charAt(d++)),C=h.indexOf(t.charAt(d++)),g=h.indexOf(t.charAt(d++)),A=n<<2|o>>4,e=(15&o)<<4|C>>2,s=(3&C)<<6|g,Q+=String.fromCharCode(A),C!==64&&(Q+=String.fromCharCode(e)),g!==64&&(Q+=String.fromCharCode(s));while(d1&&(a.thisProgram=process.argv[1].replace(/\\/g,"/")),a.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(i){if(!(i instanceof fe))throw i}),process.on("unhandledRejection",function(i,E){process.exit(1)}),a.quit=function(i){process.exit(i)},a.inspect=function(){return"[Emscripten Module object]"}):QA?(typeof read<"u"&&(a.read=function(E){return read(E)}),a.readBinary=function(E){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(XA(typeof(B=read(E,"binary"))=="object"),B)},typeof scriptArgs<"u"?a.arguments=scriptArgs:typeof arguments<"u"&&(a.arguments=arguments),typeof quit=="function"&&(a.quit=function(i){quit(i)})):(K||z)&&(K?document.currentScript&&(IA=document.currentScript.src):IA=self.location.href,IA=IA.indexOf("blob:")!==0?IA.split("/").slice(0,-1).join("/")+"/":"",a.read=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.send(null),B.responseText},z&&(a.readBinary=function(E){var B=new XMLHttpRequest;return B.open("GET",E,!1),B.responseType="arraybuffer",B.send(null),new Uint8Array(B.response)}),a.readAsync=function(E,B,f){var F=new XMLHttpRequest;F.open("GET",E,!0),F.responseType="arraybuffer",F.onload=function(){if(F.status==200||F.status==0&&F.response){B(F.response);return}f()},F.onerror=f,F.send(null)},a.setWindowTitle=function(i){document.title=i});var Jt=a.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),HA=a.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Jt);for(t in sA)sA.hasOwnProperty(t)&&(a[t]=sA[t]);function Ge(i){var E=u;return u=u+i+15&-16,E}function qt(i){var E=h[M>>2],B=E+i+15&-16;return h[M>>2]=B,B>=EA&&!zt()?(h[M>>2]=E,0):E}function Kt(i,E){return E||(E=16),i=Math.ceil(i/E)*E}function Co(i){switch(i){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(i[i.length-1]==="*")return 4;if(i[0]!=="i")return 0;var E=parseInt(i.substr(1));return XA(E%8==0),E/8}}function le(i){le.shown||(le.shown={}),le.shown[i]||(le.shown[i]=1,HA(i))}sA=void 0;var Eo={"f64-rem":function(i,E){return i%E},debugger:function(){}},st=[];function Lo(i,E){for(var B=0,f=B;f>>0)+4294967296*+(E>>>0):+(i>>>0)+4294967296*+(0|E)}function ot(i,E,B){return B&&B.length?a["dynCall_"+i].apply(null,[E].concat(B)):a["dynCall_"+i].call(null,E)}var xe=0,vt=0;function XA(i,E){i||VA("Assertion failed: "+E)}function Pt(i){var E=a["_"+i];return XA(E,"Cannot call unknown function "+i+", make sure it is exported"),E}var Vt={stackSave:function(){Bt()},stackRestore:function(){Et()},arrayToC:function(i){var E,B,f=Te(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=Te(B),Xt(i,E,B)}return E}},Bo={string:Vt.stringToC,array:Vt.arrayToC};function Ot(i,E,B,f,F){var v=Pt(i),X=[],G=0;if(f)for(var BA=0;BA>0]=E;break;case"i16":C[i>>1]=E;break;case"i32":h[i>>2]=E;break;case"i64":tempI64=[E>>>0,+fo(tempDouble=E)>=1?tempDouble>0?(0|po(+ts(tempDouble/4294967296),4294967295))>>>0:~~+mo((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],h[i>>2]=tempI64[0],h[i+4>>2]=tempI64[1];break;case"float":d[i>>2]=E;break;case"double":l[i>>3]=E;break;default:VA("invalid type for setValue: "+B)}}function Yo(i,E,B){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return n[i>>0];case"i16":return C[i>>1];case"i32":case"i64":return h[i>>2];case"float":return d[i>>2];case"double":return l[i>>3];default:VA("invalid type for getValue: "+E)}return null}function Jo(i,E,B,f){typeof i=="number"?(v=!0,X=i):(v=!1,X=i.length);var F=typeof E=="string"?E:null;if(G=B==4?f:[typeof Ue=="function"?Ue:Ge,Te,Ge,qt][B===void 0?2:B](Math.max(X,F?1:E.length)),v){for(f=G,XA((3&G)==0),BA=G+(-4&X);f>2]=0;for(BA=G+X;f>0]=0;return G}if(F==="i8")return i.subarray||i.slice?o.set(i,G):o.set(new Uint8Array(i),G),G;for(var v,X,G,BA,nA,oA,eA,q=0;q>0],(f!=0||E)&&(X++,!E||X!=E););E||(E=X);var G="";if(v<128){for(;E>0;)F=String.fromCharCode.apply(String,o.subarray(i,i+Math.min(E,1024))),G=G?G+F:F,i+=1024,E-=1024;return G}return B=i,function(nA,oA){for(var eA=oA;nA[eA];)++eA;if(eA-oA>16&&nA.subarray&&Zt)return Zt.decode(nA.subarray(oA,eA));for(var q,fA,FA,RA,GA,$A,xA="";;){if(!(q=nA[oA++]))return xA;if(!(128&q)){xA+=String.fromCharCode(q);continue}if(fA=63&nA[oA++],(224&q)==192){xA+=String.fromCharCode((31&q)<<6|fA);continue}if(FA=63&nA[oA++],(240&q)==224?q=(15&q)<<12|fA<<6|FA:(RA=63&nA[oA++],(248&q)==240?q=(7&q)<<18|fA<<12|FA<<6|RA:(GA=63&nA[oA++],q=(252&q)==248?(3&q)<<24|fA<<18|FA<<12|RA<<6|GA:(1&q)<<30|fA<<24|FA<<18|RA<<12|GA<<6|($A=63&nA[oA++]))),q<65536)xA+=String.fromCharCode(q);else{var me=q-65536;xA+=String.fromCharCode(55296|me>>10,56320|1023&me)}}}(o,B)}function Ko(i){for(var E="";;){var B=n[i++>>0];if(!B)return E;E+=String.fromCharCode(B)}}function vo(i,E){return function(f,F,v){for(var X=0;X>0]=f.charCodeAt(X);v||(n[F>>0]=0)}(i,E,!1)}var Zt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ne(i,E,B,f){if(!(f>0))return 0;for(var F=B,v=B+f-1,X=0;X=55296&&G<=57343&&(G=65536+((1023&G)<<10)|1023&i.charCodeAt(++X)),G<=127){if(B>=v)break;E[B++]=G}else if(G<=2047){if(B+1>=v)break;E[B++]=192|G>>6,E[B++]=128|63&G}else if(G<=65535){if(B+2>=v)break;E[B++]=224|G>>12,E[B++]=128|G>>6&63,E[B++]=128|63&G}else if(G<=2097151){if(B+3>=v)break;E[B++]=240|G>>18,E[B++]=128|G>>12&63,E[B++]=128|G>>6&63,E[B++]=128|63&G}else if(G<=67108863){if(B+4>=v)break;E[B++]=248|G>>24,E[B++]=128|G>>18&63,E[B++]=128|G>>12&63,E[B++]=128|G>>6&63,E[B++]=128|63&G}else{if(B+5>=v)break;E[B++]=252|G>>30,E[B++]=128|G>>24&63,E[B++]=128|G>>18&63,E[B++]=128|G>>12&63,E[B++]=128|G>>6&63,E[B++]=128|63&G}}return E[B]=0,B-F}function Xt(i,E,B){return Ne(i,o,E,B)}function be(i){for(var E=0,B=0;B=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&i.charCodeAt(++B)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var Wt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function Po(i){for(var E=i,B=E>>1;C[B];)++B;if((E=B<<1)-i>32&&Wt)return Wt.decode(o.subarray(i,E));for(var f=0,F="";;){var v=C[i+2*f>>1];if(v==0)return F;++f,F+=String.fromCharCode(v)}}function Vo(i,E,B){if(B===void 0&&(B=2147483647),B<2)return 0;for(var f=E,F=(B-=2)<2*i.length?B/2:i.length,v=0;v>1]=X,E+=2}return C[E>>1]=0,E-f}function Oo(i){return 2*i.length}function Zo(i){for(var E=0,B="";;){var f=h[i+4*E>>2];if(f==0)return B;if(++E,f>=65536){var F=f-65536;B+=String.fromCharCode(55296|F>>10,56320|1023&F)}else B+=String.fromCharCode(f)}}function Xo(i,E,B){if(B===void 0&&(B=2147483647),B<4)return 0;for(var f=E,F=f+B-4,v=0;v=55296&&X<=57343&&(X=65536+((1023&X)<<10)|1023&i.charCodeAt(++v)),h[E>>2]=X,(E+=4)+4>F)break}return h[E>>2]=0,E-f}function Wo(i){for(var E=0,B=0;B=55296&&f<=57343&&++B,E+=4}return E}function _o(i){var E=be(i)+1,B=Ue(E);return B&&Ne(i,n,B,E),B}function zo(i){var E=be(i)+1,B=Te(E);return Ne(i,n,B,E),B}function jo(i){return i}function $o(){var i,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(F){f=F}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return a.extraStackTrace&&(E+=` `+a.extraStackTrace()),(i=E).replace(/__Z[\w\d_]+/g,function(B){var f,F=f=B;return B===F?B:B+" ["+F+"]"})}function rt(i,E){return i%E>0&&(i+=E-i%E),i}function _t(i){a.buffer=s=i}function it(){a.HEAP8=n=new Int8Array(s),a.HEAP16=C=new Int16Array(s),a.HEAP32=h=new Int32Array(s),a.HEAPU8=o=new Uint8Array(s),a.HEAPU16=g=new Uint16Array(s),a.HEAPU32=Q=new Uint32Array(s),a.HEAPF32=d=new Float32Array(s),a.HEAPF64=l=new Float64Array(s)}function zt(){var i=a.usingWasm?65536:16777216,E=2147483648-i;if(h[M>>2]>E)return!1;var B=EA;for(EA=Math.max(EA,16777216);EA>2];)EA=EA<=536870912?rt(2*EA,i):Math.min(rt((3*EA+2147483648)/4,i),E);var f=a.reallocBuffer(EA);return f&&f.byteLength==EA?(_t(f),it(),!0):(EA=B,!1)}c=u=S=k=x=N=M=0,y=!1,a.reallocBuffer||(a.reallocBuffer=function(i){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(s,i);else{var E,B=n;E=new ArrayBuffer(i),new Int8Array(E).set(B)}}catch{return!1}return!!So(E)&&E});try{(W=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{W=function(E){return E.byteLength}}var at=a.TOTAL_STACK||5242880,EA=a.TOTAL_MEMORY||16777216;function Qo(){return EA}function ue(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?a.dynCall_v(B):a.dynCall_vi(B,E.arg):B(E.arg===void 0?null:E.arg)}}EA=0?i:E<=32?2*Math.abs(1<=f&&(E<=32||i>f)&&(i=-2*f+i),i}var fo=Math.abs,mo=Math.ceil,ts=Math.floor,po=Math.min,jA=0,Ct=null,de=null;function rr(i){return i}a.preloadedImages={},a.preloadedAudios={};var ss="data:application/octet-stream;base64,";function Le(i){return String.prototype.startsWith?i.startsWith(ss):i.indexOf(ss)===0}(function(){var E="main.wast",B="main.wasm",f="main.temp.asm.js";Le(E)||(E=TA(E)),Le(B)||(B=TA(B)),Le(f)||(f=TA(f));var F={global:null,env:null,asm2wasm:Eo,parent:a},v=null;function X(eA){return eA}function G(){try{if(a.wasmBinary)return new Uint8Array(a.wasmBinary);if(a.readBinary)return a.readBinary(B);throw"both async and sync fetching of the wasm failed"}catch(eA){VA(eA)}}a.asmPreload=a.asm;var BA=a.reallocBuffer,nA=function(eA){eA=rt(eA,a.usingWasm?65536:16777216);var q=a.buffer.byteLength;if(a.usingWasm)try{var fA=a.wasmMemory.grow((eA-q)/65536);return fA!==-1?a.buffer=a.wasmMemory.buffer:null}catch{return null}};a.reallocBuffer=function(eA){return oA==="asmjs"?BA(eA):nA(eA)};var oA="";a.asm=function(eA,q,fA){var FA;if(!(q=FA=q).table){var RA,GA=a.wasmTableSize;GA===void 0&&(GA=1024);var $A=a.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?$A!==void 0?q.table=new WebAssembly.Table({initial:GA,maximum:$A,element:"anyfunc"}):q.table=new WebAssembly.Table({initial:GA,element:"anyfunc"}):q.table=Array(GA),a.wasmTable=q.table}return q.memoryBase||(q.memoryBase=a.STATIC_BASE),q.tableBase||(q.tableBase=0),RA=function(me,se,Qt){if(typeof WebAssembly!="object")return HA("no native wasm support detected"),!1;if(!(a.wasmMemory instanceof WebAssembly.Memory))return HA("no native wasm Memory in use"),!1;function He(YA,JA){if((v=YA.exports).memory){var pe,ct,rs;pe=v.memory,ct=a.buffer,pe.byteLength0?B:be(i)+1,F=Array(f),v=Ne(i,F,0,F.length);return E&&(F.length=v),F}function gr(i){for(var E=[],B=0;B255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}u+=16,M=Ge(4),x=(S=k=Kt(u))+at,N=Kt(x),h[M>>2]=N,y=!0,a.wasmTableSize=4,a.wasmMaxTableSize=4,a.asmGlobalArg={},a.asmLibraryArg={abort:VA,assert:XA,enlargeMemory:zt,getTotalMemory:Qo,abortOnCannotGrowMemory:function(){VA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+EA+", (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 F=Bt();try{return a.dynCall_iii(E,B,f)}catch(v){if(Et(F),typeof v!="number"&&v!=="longjmp")throw v;a.setThrew(1,0)}},___assert_fail:function(E,B,f,F){VA("Assertion failed: "+Me(E)+", at: "+[B?Me(B):"unknown filename",f,F?Me(F):"unknown function"])},___setErrNo:function(E){return a.___errno_location&&(h[a.___errno_location()>>2]=E),E},_abort:function(){a.abort()},_emscripten_memcpy_big:function(E,B,f){return o.set(o.subarray(B,B+f),E),E},_llvm_floor_f64:ts,DYNAMICTOP_PTR:M,tempDoublePtr:DA,ABORT:xe,STACKTOP:k,STACK_MAX:x};var ns=a.asm(a.asmGlobalArg,a.asmLibraryArg,s);a.asm=ns,a.___errno_location=function(){return a.asm.___errno_location.apply(null,arguments)};var So=a._emscripten_replace_memory=function(){return a.asm._emscripten_replace_memory.apply(null,arguments)};a._free=function(){return a.asm._free.apply(null,arguments)};var Ue=a._malloc=function(){return a.asm._malloc.apply(null,arguments)};a._memcpy=function(){return a.asm._memcpy.apply(null,arguments)},a._memset=function(){return a.asm._memset.apply(null,arguments)},a._sbrk=function(){return a.asm._sbrk.apply(null,arguments)},a._stb_vorbis_js_channels=function(){return a.asm._stb_vorbis_js_channels.apply(null,arguments)},a._stb_vorbis_js_close=function(){return a.asm._stb_vorbis_js_close.apply(null,arguments)},a._stb_vorbis_js_decode=function(){return a.asm._stb_vorbis_js_decode.apply(null,arguments)},a._stb_vorbis_js_open=function(){return a.asm._stb_vorbis_js_open.apply(null,arguments)},a._stb_vorbis_js_sample_rate=function(){return a.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},a.establishStackSpace=function(){return a.asm.establishStackSpace.apply(null,arguments)},a.getTempRet0=function(){return a.asm.getTempRet0.apply(null,arguments)},a.runPostSets=function(){return a.asm.runPostSets.apply(null,arguments)},a.setTempRet0=function(){return a.asm.setTempRet0.apply(null,arguments)},a.setThrew=function(){return a.asm.setThrew.apply(null,arguments)};var Te=a.stackAlloc=function(){return a.asm.stackAlloc.apply(null,arguments)},Et=a.stackRestore=function(){return a.asm.stackRestore.apply(null,arguments)},Bt=a.stackSave=function(){return a.asm.stackSave.apply(null,arguments)};function fe(i){this.name="ExitStatus",this.message="Program terminated with exit("+i+")",this.status=i}function ht(i){i=i||a.arguments,!(jA>0)&&(function(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)lo(a.preRun.shift());ue(jt)}(),!(jA>0)&&(a.calledRun||(a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),E()},1)):E())));function E(){!a.calledRun&&(a.calledRun=!0,xe||(gt||(gt=!0,ue(It)),ue($t),a.onRuntimeInitialized&&a.onRuntimeInitialized(),function(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)uo(a.postRun.shift());ue(es)}()))}}function Cr(i,E){(!E||!a.noExitRuntime||i!==0)&&(a.noExitRuntime||(xe=!0,vt=i,k=J,ue(As),co=!0,a.onExit&&a.onExit(i)),a.quit(i,new fe(i)))}function VA(i){throw a.onAbort&&a.onAbort(i),i!==void 0?(Jt(i),HA(i),i=JSON.stringify(i)):i="",xe=!0,vt=1,"abort("+i+"). Build with -s ASSERTIONS=1 for more info."}if(a.dynCall_iii=function(){return a.asm.dynCall_iii.apply(null,arguments)},a.asm=ns,a.ccall=Ot,a.cwrap=function(E,B,f,F){var v=(f=f||[]).every(function(X){return X==="number"});return B!=="string"&&v&&!F?Pt(E):function(){return Ot(E,B,f,arguments,F)}},fe.prototype=Error(),fe.prototype.constructor=fe,de=function i(){a.calledRun||ht(),a.calledRun||(de=i)},a.run=ht,a.abort=VA,a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();a.noExitRuntime=!0,ht(),a.onRuntimeInitialized=()=>{_s=!0,zs()},PA.decode=function(i){return function(B){if(!_s)throw Error("Not initialized");var f={};function F(se){return new Int32Array(a.HEAPU8.buffer,se,1)[0]}function v(se,Qt){var He=new ArrayBuffer(Qt*Float32Array.BYTES_PER_ELEMENT),ne=new Float32Array(He);return ne.set(new Float32Array(a.HEAPU8.buffer,se,Qt)),ne}f.open=a.cwrap("stb_vorbis_js_open","number",[]),f.close=a.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=a.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=a.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=a.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var X,G,BA,nA,oA=f.open(),eA=(X=B,G=B.byteLength,BA=a._malloc(G),(nA=new Uint8Array(a.HEAPU8.buffer,BA,G)).set(new Uint8Array(X,0,G)),nA),q=a._malloc(4),fA=a._malloc(4),FA=f.decode(oA,eA.byteOffset,eA.byteLength,q,fA);if(a._free(eA.byteOffset),FA<0)throw f.close(oA),a._free(q),Error("stbvorbis decode failed: "+FA);for(var RA=f.channels(oA),GA=Array(RA),$A=new Int32Array(a.HEAPU32.buffer,F(q),RA),xA=0;xA=0&&(s=this.workletProcessorChannels[e]),t.messageType){case AA.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case AA.noteOff:this.noteOff(e,A);break;case AA.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case AA.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case AA.customcCcChange:s.customControllers[A[0]]=A[1];break;case AA.killNote:this.killNote(e,A);break;case AA.programChange:this.programChange(e,A[0],A[1]);break;case AA.channelPressure:this.channelPressure(e,A);break;case AA.polyPressure:this.polyPressure(e,A[0],A[1]);break;case AA.ccReset:e===bA?this.resetAllControllers():this.resetControllers(e);break;case AA.systemExclusive:this.systemExclusive(A);break;case AA.setChannelVibrato:if(e===bA)for(let C=0;C{let e=(A.midiControllers[gA+P.pitchWheelRange]>>7)+(A.midiControllers[gA+P.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[gA+P.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:mA.channelProperties,messageData:t})}function Go(t,A,e){let s=t,n=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function en(t,A=0){let e=t[0];if(!(this.deviceID!==bA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:b(`%cUnrecognized SysEx: %c${hA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let s;switch(t[3]){case 1:let n=t[5]<<7|t[4];this.setMIDIVolume(n/16384),m(`%cMaster Volume. Volume: %c${n}`,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 g=(t[5]<<7|t[6])-8192;s=Math.floor(g/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${hA(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 n=4;t[3]===7&&n++;let o=t[n++],C=t[n++];for(let h=0;h>1&1)===1&&this.setOctaveTuning(15+A,g);for(let h=0;h<7;h++)(t[5]>>h&1)===1&&this.setOctaveTuning(7+h+A,g);for(let h=0;h<7;h++)(t[6]>>h&1)===1&&this.setOctaveTuning(h+A,g);m(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${g.join(" ")}`,r.info,r.value);break;default:b(`%cUnrecognized MIDI Tuning standard message: %c${hA(t)}`,r.warn,r.unrecognized);break}break;default:b(`%cUnrecognized MIDI Realtime/non realtime message: %c${hA(t)}`,r.warn,r.unrecognized)}break;case 65:if(t[2]===66&&t[3]===18){let s=t[7];if(t[6]===127){s===0?(m("%cGS system on",r.info),this.system="gs"):s===127&&(m("%cGS system off, switching to GM2",r.info),this.system="gm2");return}else if(t[4]===64){if((t[5]&16)>0){let n=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A;switch(t[6]){default:break;case 21:let o=s>0&&t[5]>>4;this.setDrums(n,o),m(`%cChannel %c${n}%c ${o?"is now a drum channel":"now isn't a drum channel"}%c via: %c${hA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=s-64;this.transposeChannel(n,C),m(`%cChannel %c${n}%c pitch shift. Semitones %c${C}%c, with %c${hA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let g=s-64;m(`%cChannel %c${n}%c tuning. Cents %c${g}%c, with %c${hA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value),this.setChannelTuning(n,g)}}else if(t[5]===0&&t[6]===6){m(`%cRoland GS Master Pan set to: %c${s}%c with: %c${hA(t)}`,r.info,r.value,r.info,r.value),this.setMasterPan((s-64)/64);return}else if(t[5]===0&&t[6]===5){let n=s-64;m(`%cRoland GS Master Key-Shift set to: %c${n}%c with: %c${hA(t)}`,r.info,r.value,r.info,r.value),this.setMasterTuning(n*100);return}else if(t[5]===0&&t[6]===4){m(`%cRoland GS Master Volume set to: %c${s}%c with: %c${hA(t)}`,r.info,r.value,r.info,r.value),this.setMIDIVolume(s/127);return}}b(`%cUnrecognized Roland %cGS %cSysEx: %c${hA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized);return}else if(t[2]===22&&t[3]===18&&t[4]===16){this.setMIDIVolume(t[7]/100),m(`%cRoland Master Volume control set to: %c${t[7]}%c via: %c${hA(t)}`,r.info,r.value,r.info,r.value);return}else{b(`%cUnrecognized Roland SysEx: %c${hA(t)}`,r.warn,r.unrecognized);return}case 67:if(t[2]===76)if(t[3]===0&&t[4]===0)switch(t[5]){case 4:let s=t[6];this.setMIDIVolume(s/127),m(`%cXG master volume. Volume: %c${s}`,r.info,r.recognized);break;case 6:let n=t[6]-64;this.transposeAllChannels(n),m(`%cXG master transpose. Volume: %c${n}`,r.info,r.recognized);break;case 126:m("%cXG system on",r.info),this.system="xg";break}else if(t[3]===8){if(this.system!=="xg")return;let s=t[4]+A;if(s>=this.workletProcessorChannels.length)return;let n=t[6];switch(t[5]){case 1:this.controllerChange(s,p.bankSelect,n);break;case 2:this.controllerChange(s,p.lsbForControl0BankSelect,n);break;case 3:this.programChange(s,n);break;case 8:let o=this.workletProcessorChannels[s];if(o.drumChannel)return;let C=n-64;o.channelTransposeKeyShift=C;break;case 11:this.controllerChange(s,p.mainVolume,n);break;case 14:let g=n;g===0&&(g=Math.floor(Math.random()*127)),this.controllerChange(s,p.pan,g);break;case 19:this.controllerChange(s,p.effects1Depth,n);break;case 18:this.controllerChange(s,p.effects3Depth,n);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${hA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&b(`%cUnrecognized Yamaha SysEx: %c${hA(t)}`,r.warn,r.unrecognized);break}}function tn(t,A,e){if(A.transformAmount===0)return 0;let s;if(A.sourceUsesCC)s=t[A.sourceIndex];else{let h=A.sourceIndex+gA;switch(A.sourceIndex){case P.noController:s=16383;break;case P.noteOnKeyNum:s=e.midiNote<<7;break;case P.noteOnVelocity:s=e.velocity<<7;break;case P.polyPressure:s=e.pressure<<7;break;default:s=t[h];break}}let n=dA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let h=A.secSrcIndex+gA;switch(A.secSrcIndex){case P.noController:o=16383;break;case P.noteOnKeyNum:o=e.midiNote<<7;break;case P.noteOnVelocity:o=e.velocity<<7;break;case P.polyPressure:o=e.pressure<<7;break;default:o=t[h]}}let C=dA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=n*C*A.transformAmount;return A.transformType===2?Math.abs(g):g}function OA(t,A,e=-1,s=0){let{modulators:n,generators:o,modulatedGenerators:C}=t;if(UA.recalculate(t),e===-1){C.set(o),n.forEach(Q=>{C[Q.modulatorDestination]+=tn(A,Q,t)}),NA.recalculate(t);return}let g=new Set([I.initialAttenuation,I.delayVolEnv,I.attackVolEnv,I.holdVolEnv,I.decayVolEnv,I.sustainVolEnv,I.releaseVolEnv,I.keyNumToVolEnvHold,I.keyNumToVolEnvDecay]),h=new Set;n.forEach(Q=>{if(Q.sourceUsesCC===e&&Q.sourceIndex===s||Q.secSrcUsesCC===e&&Q.secSrcIndex===s){let d=Q.modulatorDestination;h.has(d)||(C[d]=o[d],n.forEach(l=>{l.modulatorDestination===d&&(C[d]+=tn(A,l,t))}),h.add(d))}}),[...h].some(Q=>g.has(Q))&&NA.recalculate(t)}var dA=[];for(let t=0;t<4;t++){dA[t]=[[new Float32Array(aA),new Float32Array(aA)],[new Float32Array(aA),new Float32Array(aA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||C.isMuted)return;let g=A+C.channelTransposeKeyShift;if(A>127||A<0)return;let h=C.preset.program;this.tunings[h]?.[A]?.midiNote>=0&&(g=this.tunings[h]?.[A].midiNote);let Q=this.getWorkletVoices(t,g,e,C,o,s),d=C.voices;Q.forEach(l=>{let c=l.generators[I.exclusiveClass];c!==0&&d.forEach(u=>{u.generators[I.exclusiveClass]===c&&(this.releaseVoice(u),u.modulatedGenerators[I.releaseVolEnv]=-7e3,u.modulatedGenerators[I.releaseModEnv]=-7e3,NA.recalculate(u),UA.recalculate(u))}),OA(l,C.midiControllers),l.currentPan=(Math.max(-500,Math.min(500,l.modulatedGenerators[I.pan]))+500)/1e3}),this.totalVoicesAmount+=Q.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(Q.length),d.push(...Q),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function nn(t,A){if(A>127||A<0){b("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift,s=this.workletProcessorChannels[t].preset.program;if(this.tunings[s]?.[A]?.midiNote>=0&&(e=this.tunings[s]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(o=>{o.midiNote!==e||o.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function on(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.midiNote===A&&(e.modulatedGenerators[I.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function rn(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[t].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function an(t=!1){m("%cStop all received!",r.info);for(let A=0;AOA(n,this.workletProcessorChannels[t].midiControllers,0,P.pitchWheel)),this.sendChannelProperties()}function cn(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[gA+P.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(s=>OA(s,e.midiControllers,0,P.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function ln(t,A,e){this.workletProcessorChannels[t].voices.forEach(s=>{s.midiNote===A&&(s.pressure=e,OA(s,this.workletProcessorChannels[t].midiControllers,0,P.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function un(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function dn(t,A,e,s=!1){let n=this.workletProcessorChannels[t];if(n===void 0){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(n.lockedControllers[o])return;n.midiControllers[o]=n.midiControllers[o]&16256|e&127,n.voices.forEach(C=>OA(C,n.midiControllers,1,o))}switch(A){case p.allNotesOff:this.stopAll(t);break;case p.allSoundOff:this.stopAll(t,!0);break;case p.bankSelect:let o=e;if(!s){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==SA&&this.setDrums(t,!1);break;case"gm2":o===120&&(n.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}n.drumChannel&&(o=128),o===128&&!n.drumChannel&&(o=n.midiControllers[p.bankSelect])}n.midiControllers[p.bankSelect]=o;break;case p.lsbForControl0BankSelect:this.system==="xg"?n.drumChannel||e!==127&&(n.midiControllers[p.bankSelect]=e):this.system==="gm2"&&(n.midiControllers[p.bankSelect]=e);break;case p.RPNLsb:n.RPValue=n.RPValue<<7|e,n.dataEntryState=uA.RPFine;break;case p.RPNMsb:n.RPValue=e,n.dataEntryState=uA.RPCoarse;break;case p.NRPNMsb:n.NRPCoarse=e,n.dataEntryState=uA.NRPCoarse;break;case p.NRPNLsb:n.NRPFine=e,n.dataEntryState=uA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(t,e);break;case p.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case p.resetAllControllers:this.resetControllers(t);break;case p.sustainPedal:e>=64?n.holdPedal=!0:(n.holdPedal=!1,n.sustainedVoices.forEach(C=>{this.releaseVoice(C)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=e<<7,n.voices.forEach(C=>OA(C,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function fn(t){this.midiVolume=t,this.setMasterPan(this.pan)}function mn(t){this.masterGain=t*Nt,this.setMasterPan(this.pan)}function pn(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function Sn(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function yn(t){this.workletProcessorChannels[t].lockVibrato=!0,this.workletProcessorChannels[t].channelVibrato.rate=0,this.workletProcessorChannels[t].channelVibrato.delay=0,this.workletProcessorChannels[t].channelVibrato.depth=0}function Dn(t,A,e,s){this.workletProcessorChannels[t].lockVibrato||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=s,this.workletProcessorChannels[t].channelVibrato.depth=A)}function kn(t,A){let e=this.workletProcessorChannels[t],s=()=>{e.channelVibrato.delay===0&&e.channelVibrato.rate===0&&e.channelVibrato.depth===0&&(e.channelVibrato.depth=50,e.channelVibrato.rate=8,e.channelVibrato.delay=.6)};switch(e.dataEntryState){default:case uA.Idle:break;case uA.NRPFine:if(this.system!=="gs")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(e.lockVibrato||A===64)return;s(),e.channelVibrato.rate=A/64*8,m(`%cVibrato rate for channel %c${t}%c is now set to %c${e.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(e.lockVibrato||A===64)return;s(),e.channelVibrato.depth=A/2,m(`%cVibrato depth for %c${t}%c is now set to %c${e.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(e.lockVibrato||A===64)return;s(),e.channelVibrato.delay=A/64/3,m(`%cVibrato delay for %c${t}%c is now set to %c${e.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let o=A;this.controllerChange(t,p.brightness,A),m(`%cFilter cutoff for %c${t}%c is now set to %c${o}`,r.info,r.recognized,r.info,r.value)}break;case 29:if(!e.drumChannel)return;let n=A;this.controllerChange(t,p.effects1Depth,n),m(`%cGS Drum reverb for %c${t}%c: %c${n}`,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[gA+P.pitchWheelRange]=A<<7,m(`%cChannel ${t} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(t,A-64);break;case 1:this.setChannelTuning(t,A-64,!1);break;case 5:this.setModulationDepth(t,A*100);break;case 16383:this.resetParameters(t);break}}}function wn(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[gA+P.pitchWheelRange]|=A;let s=(e.midiControllers[gA+P.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 g=e.customControllers[iA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,g);break;case 16383:this.resetParameters(t);break}}}function Fn(){m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let t=0;t{this.workletProcessorChannels[t].lockedControllers[s]&&this.callEvent("controllerchange",{channel:t,controllerNumber:s,controllerValue:this.workletProcessorChannels[t].midiControllers[s]>>7})};if(e(p.mainVolume),e(p.pan),e(p.expressionController),e(p.modulationWheel),e(p.effects3Depth),e(p.effects1Depth),this.workletProcessorChannels[t].lockedControllers[gA+P.pitchWheel]){let s=this.workletProcessorChannels[t].midiControllers[gA+P.pitchWheel],n=s>>7,o=s&127;this.callEvent("pitchwheel",{channel:t,MSB:n,LSB:o})}}this.tunings=[],this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.setMIDIVolume(1),this.system=qe}function Rn(t){let A=this.workletProcessorChannels[t],s=A.lockedControllers.reduce((o,C,g)=>(C&&o.push(g),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.midiControllers.set(vA),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(yt),A.customControllers[iA.channelTransposeFine]=n,this.resetParameters(t)}function Gn(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=uA.Idle}function xn(){let t=4;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>(o.generators=o.generators.filter(C=>C.generatorType!==I.sampleID&&C.generatorType!==I.keyRange&&C.generatorType!==I.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:I.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:I.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:I.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+n),0);let A=new H(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=e;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue),e++}return cA(A,0),tA(new j("igen",A.length,A))}function Mn(t,A,e,s,n){let o=this.samples.map((Q,d)=>{e&&Q.compressSample(s,n);let l=Q.getRawData();return m(`%cEncoded sample %c${d}. ${Q.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),l}),C=this.samples.reduce((Q,d,l)=>Q+o[l].length+46,0),g=new H(C);this.samples.forEach((Q,d)=>{let l=o[d],c,u,y=l.length;Q.isCompressed?(c=g.currentIndex,u=c+l.length):(c=g.currentIndex/2,u=c+l.length/2,y+=46),t.push(c),g.set(l,g.currentIndex),g.currentIndex+=y,A.push(u)});let h=tA(new j("smpl",g.length,g),new H([115,100,116,97]));return tA(new j("LIST",h.length,h))}function Nn(t,A){let s=new H(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{wA(s,n.sampleName,20);let C=t[o];cA(s,C);let g=A[o];cA(s,g);let h=n.sampleLoopStartIndex/2+C,Q=n.sampleLoopEndIndex/2+C;n.isCompressed&&(h-=C,Q-=C),cA(s,h),cA(s,Q),cA(s,n.sampleRate),s[s.currentIndex++]=n.samplePitch,s[s.currentIndex++]=n.samplePitchCorrection,Y(s,n.sampleLink),Y(s,n.sampleType)}),wA(s,"EOS",46),tA(new j("shdr",s.length,s))}function bn(){let t=10;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)Y(A,o.modulatorSource),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.modulationSecondarySrc),Y(A,o.transformType),e++}return ae(A,0,10),tA(new j("imod",A.length,A))}function Ln(){let t=this.instruments.reduce((o,C)=>C.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 C of o.instrumentZones)C.zoneID=e,Y(A,s),Y(A,n),s+=C.generators.length,n+=C.modulators.length,e++}return Y(A,s),Y(A,n),tA(new j("ibag",A.length,A))}function Un(){let t=this.instruments.length*22+22,A=new H(t),e=0,s=0;for(let n of this.instruments)wA(A,n.instrumentName,20),Y(A,e),e+=n.instrumentZones.length,n.instrumentID=s,s++;return wA(A,"EOI",20),Y(A,e),tA(new j("inst",A.length,A))}function Tn(){let t=4;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>(o.generators=o.generators.filter(C=>C.generatorType!==I.instrument&&C.generatorType!==I.keyRange&&C.generatorType!==I.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:I.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:I.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:I.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),tA(new j("pgen",A.length,A))}function Hn(){let t=10;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)Y(A,o.modulatorSource),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.modulationSecondarySrc),Y(A,o.transformType),e++}return ae(A,0,10),tA(new j("pmod",A.length,A))}function Yn(){let t=this.presets.reduce((o,C)=>C.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 C of o.presetZones)C.zoneID=e,Y(A,s),Y(A,n),s+=C.generators.length,n+=C.modulators.length,e++}return Y(A,s),Y(A,n),tA(new j("pbag",A.length,A))}function Jn(){let t=this.presets.length*38+38,A=new H(t),e=0;for(let s of this.presets)wA(A,s.presetName,20),Y(A,s.program),Y(A,s.bank),Y(A,e),cA(A,s.library),cA(A,s.genre),cA(A,s.morphology),e+=s.presetZones.length;return wA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,e),cA(A,0),cA(A,0),cA(A,0),tA(new j("phdr",A.length,A))}var xo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function qn(t=xo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");pA("%cSaving soundfont...",r.info),m(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),m("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[W,J]of Object.entries(this.soundFontInfo))if(W==="ifil"||W==="iver"){let a=parseInt(J.split(".")[0]),sA=parseInt(J.split(".")[1]),K=new H(4);Y(K,a),Y(K,sA),A.push(tA(new j(W,4,K)))}else{let a=new H(J.length);wA(a,J),A.push(tA(new j(W,J.length,a)))}let e=Se([new H([73,78,70,79]),...A]),s=tA(new j("LIST",e.length,e));m("%cWriting SDTA...",r.info);let n=[],o=[],C=Mn.call(this,n,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let g=Nn.call(this,n,o);m("%cWriting IGEN...",r.info);let h=xn.call(this);m("%cWriting IMOD...",r.info);let Q=bn.call(this);m("%cWriting IBAG...",r.info);let d=Ln.call(this);m("%cWriting INST...",r.info);let l=Un.call(this),c=Tn.call(this);m("%cWriting PMOD...",r.info);let u=Hn.call(this);m("%cWriting PBAG...",r.info);let y=Yn.call(this);m("%cWriting PHDR...",r.info);let S=Jn.call(this),k=Se([new H([112,100,116,97]),S,y,u,c,l,d,Q,h,g]),x=tA(new j("LIST",k.length,k));m("%cWriting the output file...",r.info);let N=Se([new H([115,102,98,107]),s,C,x]),M=tA(new j("RIFF",N.length,N));return m(`%cSaved succesfully! Final file size: %c${M.length}`,r.info,r.recognized),Z(),M}var te=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],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||(s=this.presets.find(n=>n.program===e&&n.bank!==128),A===128&&(s=this.presets.find(n=>n.bank===128&&n.program===e),s||(s=this.presets.find(n=>n.bank===128))),s&&b(`%cPreset ${A}.${e} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,r.warn,r.recognized)),s||(b(`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||(b("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(C=>C.bank===o.bank&&C.program===o.program)===void 0&&s.push(o)});return new t({presets:s,info:e.soundFontInfo})}};te.prototype.write=qn;function Kn(t){pA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let s=A;s{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,e){let s=this.foundSamplesAndGenerators[A][e];if(s)return s;if(this.presetZones.length<1)return[];function n(c,u,y){return y>=c&&y<=u}function o(c,u){return c.modulatorSource===u.modulatorSource&&c.modulatorDestination===u.modulatorDestination&&c.modulationSecondarySrc===u.modulationSecondarySrc&&c.transformType===u.transformType}function C(c,u){c.push(...u.filter(y=>!c.find(S=>S.generatorType===y.generatorType)))}function g(c,u){c.push(...u.filter(y=>!c.find(S=>o(y,S))))}let h=[],Q=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],d=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(c=>n(c.keyRange.min,c.keyRange.max,A)&&n(c.velRange.min,c.velRange.max,e)&&!c.isGlobal).forEach(c=>{if(c.instrument.instrumentZones.length<1)return;let u=c.generators,y=c.modulators,S=c.instrument.instrumentZones[0].isGlobal?[...c.instrument.instrumentZones[0].generators]:[],k=c.instrument.instrumentZones[0].isGlobal?[...c.instrument.instrumentZones[0].modulators]:[];c.instrument.instrumentZones.filter(N=>n(N.keyRange.min,N.keyRange.max,A)&&n(N.velRange.min,N.velRange.max,e)&&!N.isGlobal).forEach(N=>{let M=[...N.generators],W=[...N.modulators];C(u,Q),C(M,S),g(y,d),g(W,k),g(W,Fs);let J=[...W];for(let a=0;ao(sA,z));K!==-1?J[K]=J[K].sumTransform(sA):J.push(sA)}h.push({instrumentGenerators:M,presetGenerators:u,modulators:J,sample:N.sample,sampleID:N.generators.find(a=>a.generatorType===I.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=h,h}};var we=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var zA=class extends we{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},he=class extends we{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var Qe=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 ze=class extends Be{constructor(A,e){super(),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new Qe,this.DLSInstrument.addUseCount();let n=new he;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function vn(t){this.verifyHeader(t,"LIST"),this.verifyText(V(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(u=>u.header==="insh");if(!e)throw Z(),new Error("No instrument header!");let s=D(e.chunkData,4),n=D(e.chunkData,4),o=D(e.chunkData,4),C=new ze(n,o),g="unnamedPreset",h=yA(A,"INFO");if(h){let u=O(h.chunkData);for(;u.header!=="INAM";)u=O(h.chunkData);g=V(u.chunkData,u.chunkData.length).trim()}C.presetName=g,C.DLSInstrument.instrumentName=g,Ae(`%cParsing %c"${g}"%c...`,r.info,r.recognized,r.info);let Q=yA(A,"lrgn");if(!Q)throw Z(),new Error("No region list!");let d=new zA;d.isGlobal=!0;let l=yA(A,"lart"),c=yA(A,"lar2");this.readLart(l,c,d),C.DLSInstrument.instrumentZones.push(d);for(let u=0;u>10&15;x===lA.linear&&k!==lA.linear&&(x=k);let N=s>>14&1,M=s>>15&1;C===I.initialAttenuation&&(M=!M),l=KA(x,N,M,g.isCC,g.enum)}let c=s>>4&15,u=s>>8&1,y=s>>9&1,S=KA(c,u,y,d.isCC,d.enum);if(h){let k=S;S=l,l=k}return new rA({srcEnum:l,secSrcEnum:S,dest:C,transform:0,amt:n})}function bt(t,A){let e=t.chunkData,s=[],n=[];D(e,4);let o=D(e,4);for(let C=0;C>16;if(g===0&&h===0&&d===0){let u;switch(Q){case R.pan:u=new U(I.pan,c);break;case R.gain:u=new U(I.initialAttenuation,-c*10/.4);break;case R.filterCutoff:u=new U(I.initialFilterFc,c);break;case R.filterQ:u=new U(I.initialFilterQ,c);break;case R.modLfoFreq:u=new U(I.freqModLFO,c);break;case R.modLfoDelay:u=new U(I.delayModLFO,c);break;case R.vibLfoFreq:u=new U(I.freqVibLFO,c);break;case R.vibLfoDelay:u=new U(I.delayVibLFO,c);break;case R.volEnvDelay:u=new U(I.delayVolEnv,c);break;case R.volEnvAttack:u=new U(I.attackVolEnv,c);break;case R.volEnvHold:u=new U(I.holdVolEnv,c);break;case R.volEnvDecay:u=new U(I.decayVolEnv,c);break;case R.volEnvRelease:u=new U(I.releaseVolEnv,c);break;case R.volEnvSustain:let y=(1e3-c)/10;u=new U(I.sustainVolEnv,y*10);break;case R.modEnvDelay:u=new U(I.delayModEnv,c);break;case R.modEnvAttack:u=new U(I.attackModEnv,c);break;case R.modEnvHold:u=new U(I.holdModEnv,c);break;case R.modEnvDecay:u=new U(I.decayModEnv,c);break;case R.modEnvRelease:u=new U(I.releaseModEnv,c);break;case R.modEnvSustain:let S=1e3-c;u=new U(I.sustainModEnv,S);break;case R.reverbSend:u=new U(I.reverbEffectsSend,c);break;case R.chorusSend:u=new U(I.chorusEffectsSend,c);break;case R.pitch:let k=Math.floor(c/100),x=Math.floor(c-k*100);u=new U(I.fineTune,x),s.push(new U(I.coarseTune,k));break}u&&s.push(u)}else{let u=!0;if(h===_.none)if(g===_.modLfo&&Q===R.pitch)s.push(new U(I.modLfoToPitch,c));else if(g===_.modLfo&&Q===R.gain)s.push(new U(I.modLfoToVolume,c));else if(g===_.modLfo&&Q===R.filterCutoff)s.push(new U(I.modLfoToFilterFc,c));else if(g===_.vibratoLfo&&Q===R.pitch)s.push(new U(I.vibLfoToPitch,c));else if(g===_.modEnv&&Q===R.pitch)s.push(new U(I.modEnvToPitch,c));else if(g===_.modEnv&&Q===R.filterCutoff)s.push(new U(I.modEnvToFilterFc,c));else if(g===_.keyNum&&Q===R.volEnvHold){s.push(new U(I.keyNumToVolEnvHold,c/-128));let y=Math.round(60/128*c);s.forEach(S=>{S.generatorType===I.holdVolEnv&&(S.generatorValue+=y)})}else if(g===_.keyNum&&Q===R.volEnvDecay){s.push(new U(I.keyNumToVolEnvDecay,c/-128));let y=Math.round(60/128*c);s.forEach(S=>{S.generatorType===I.decayVolEnv&&(S.generatorValue+=y)})}else if(g===_.keyNum&&Q===R.modEnvHold){s.push(new U(I.keyNumToModEnvHold,c/-128));let y=Math.round(60/128*c);s.forEach(S=>{S.generatorType===I.holdModEnv&&(S.generatorValue+=y)})}else if(g===_.keyNum&&Q===R.modEnvDecay){s.push(new U(I.keyNumToModEnvDecay,c/-128));let y=Math.round(60/128*c);s.forEach(S=>{S.generatorType===I.decayModEnv&&(S.generatorValue+=y)})}else u=!1;else u=!1;if(u===!1){let y=Vn(g,h,Q,d,c);y?(n.push(y),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):b("Failed converting to SF2 Modulator!")}}}return n.find(C=>C.modulatorDestination===I.reverbEffectsSend)===void 0&&n.push(new rA({srcEnum:219,dest:I.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(C=>C.modulatorDestination===I.chorusEffectsSend)===void 0&&n.push(new rA({srcEnum:221,dest:I.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&n.push(new rA({srcEnum:129,dest:I.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new rA({srcEnum:13,dest:I.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:n,generators:s}}function On(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(a=>a.header==="rgnh"),s=D(e.chunkData,2),n=D(e.chunkData,2),o=D(e.chunkData,2),C=D(e.chunkData,2),g=new je({min:s,max:n},{min:o,max:C});D(e.chunkData,2);let h=D(e.chunkData,2);h!==0&&g.generators.push(new U(I.exclusiveClass,h));let Q=yA(A,"lart"),d=yA(A,"lar2");this.readLart(Q,d,g),g.isGlobal=!1;let l=A.find(a=>a.header==="wsmp");D(l.chunkData,4);let c=D(l.chunkData,2);D(l.chunkData,2);let S=(D(l.chunkData,4)|0)/-655360*10/.4;D(l.chunkData,4);let k=D(l.chunkData,4),x,N={start:0,end:0};if(k===0)x=0;else{D(l.chunkData,4),D(l.chunkData,4)===0?x=1:x=3,N.start=D(l.chunkData,4);let sA=D(l.chunkData,4);N.end=N.start+sA}let M=A.find(a=>a.header==="wlnk");if(M===void 0)return;D(M.chunkData,2),D(M.chunkData,2),D(M.chunkData,4);let W=D(M.chunkData,4),J=this.samples[W];if(J===void 0)throw new Error("Invalid sample ID!");return g.setWavesample(S,x,N,c,J,W),g}var ce=class{constructor(A,e,s,n,o,C,g,h){this.sampleName=A,this.sampleRate=e,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=C,this.sampleLoopStartIndex=g,this.sampleLoopEndIndex=h,this.isCompressed=(C&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 $e=class extends ce{constructor(A,e,s,n,o,C,g){super(A,e,s,n,0,1,o*2,(C-1)*2),this.sampleData=g}getAudioData(){return this.sampleData}sampleData;getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let e=0;e>8&255}return A}};function Xn(t){pA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexK.header==="fmt ");if(!n)throw new Error("No fmt chunk in the wave file!");if(D(n.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(D(n.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let g=D(n.chunkData,4);D(n.chunkData,4),D(n.chunkData,2);let h=D(n.chunkData,2),Q=h/8,d=Math.pow(2,Q*8-1),l=Math.pow(2,Q*8),c,u=!1;h===8?(c=255,u=!0):c=d;let y=s.find(K=>K.header==="data");if(!y)throw new Error("No data chunk in the wave chunk!");let S=y.size/Q,k=new Float32Array(S);for(let K=0;K=d&&(z-=l),k[K]=z/c)}let x=60,N=0,M=0,W=k.length-1,J=s.find(K=>K.header==="wsmp");if(J){if(D(J.chunkData,4),x=D(J.chunkData,2),N=Ie(J.chunkData[J.chunkData.currentIndex++],J.chunkData[J.chunkData.currentIndex++]),D(J.chunkData,4),D(J.chunkData,4),D(J.chunkData,4)===1){D(J.chunkData,8),M=D(J.chunkData,4);let z=D(J.chunkData,4);W=M+z}}else b("No wsmp chunk in wave... using sane defaults.");let a=yA(s,"INFO"),sA=`Unnamed ${A}`;if(a){let K=O(a.chunkData);for(;K.header!=="INAM"&&a.chunkData.currentIndexh.header==="colh");if(!o)throw Z(),new Error("No colh chunk!");this.instrumentAmount=D(o.chunkData,4),m(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let C=yA(s,"wvpl");this.readDLSSamples(C);let g=yA(s,"lins");if(!g)throw Z(),new Error("No lins chunk!");this.readDLSInstrumentList(g),m(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/unit_converter.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/unit_converter.js index ab2968f3..e327053c 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/unit_converter.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/unit_converter.js @@ -20,7 +20,7 @@ for (let i = 0; i < timecentLookupTable.length; i++) { */ export function timecentsToSeconds(timecents) { - if(timecents <= -12000) return 0; + if(timecents <= -32767) return 0; return timecentLookupTable[timecents - MIN_TIMECENT]; } diff --git a/src/website/minified/demo_main.min.js b/src/website/minified/demo_main.min.js index 9d64dd5d..96afc87c 100644 --- a/src/website/minified/demo_main.min.js +++ b/src/website/minified/demo_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 n6=class extends Uint8Array{constructor(r){super(r),this.currentIndex=0}currentIndex};function bs(A){let r=A.reduce((d,b)=>d+b.length,0),l=new n6(r),g=0;for(let d of A)l.set(d,g),g+=d.length;return l}function f$(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 wB(A){return A.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}var D1={warn:"color: orange;",unrecognized:"color: red;",info:"color: aqua;",recognized:"color: lime",value:"color: yellow; background-color: black;"};var ui=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,midiChannelPrefix:32,midiPort:33,endOfTrack:47,setTempo:81,smpteOffset:84,timeSignature:88,keySignature:89,sequenceSpecific:127};function KQ(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 kB={nodesAmount:4,defaultDelay:.03,delayVariation:.01,stereoDifference:.02,oscillatorFrequency:.3,oscillatorFrequencyVariation:.05,oscillatorGain:.003},um=class{constructor(r,l=kB){let g=r.context;this.input=new ChannelSplitterNode(g,{numberOfOutputs:2});let d=new ChannelMergerNode(g,{numberOfInputs:2}),b=[],h0=[],b0=l.oscillatorFrequency,p0=l.defaultDelay;for(let R0=0;R0{let b=await d.arrayBuffer();l.buffer=await A.decodeAudioData(b)})}return l}var B8={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},Hi=-1,u$={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var BD=!0,pD=!0,vB=!0;function Y5(...A){BD&&console.info(...A)}function _4(...A){pD&&console.warn(...A)}function ar(...A){vB&&console.group(...A)}function ei(...A){vB&&console.groupCollapsed(...A)}function t4(){vB&&console.groupEnd()}var zQ={chorusEnabled:!0,chorusConfig:kB,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:B8.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){_4("1 soundfont left. Aborting!");return}if(this.soundfontList.findIndex(l=>l.id===r)===-1){_4(`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 QD="spessasynth-worklet-system",SB=450,ki=9,yD=16;var ah=class{constructor(r,l,g=!0,d=void 0,b=zQ){Y5("%cInitializing SpessaSynth synthesizer...",D1.info),this.context=r.context;let h0=d?.oneOutput===!0;this.eventHandler=new fm,this._voiceCap=SB,this._outputsAmount=yD,this.channelsAmount=this._outputsAmount,this.resolveWhenReady=void 0,this.isReady=new Promise(R0=>this.resolveWhenReady=R0),this.channelProperties=[];for(let R0=0;R0this.handleMessage(R0.data),this.soundfontManager=new dm(this),this._snapshotCallback=void 0,this.sequencerCallbackFunction=void 0,b.reverbEnabled&&!h0&&(this.reverbProcessor=VQ(this.context,b.reverbImpulseResponse),this.reverbProcessor.connect(r),this.worklet.connect(this.reverbProcessor,0)),b.chorusEnabled&&!h0&&(this.chorusProcessor=new um(r,b.chorusConfig),this.worklet.connect(this.chorusProcessor.input,1)),h0)this.worklet.connect(r,0);else for(let R0=2;R0{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:Hi,messageType:B8.setLogLevel,messageData:[r,l,g,d]})}_setMasterParam(r,l){this.post({channelNumber:Hi,messageType:B8.setMasterParameter,messageData:[r,l]})}setInterpolationType(r){this._setMasterParam(mC.interpolationType,r)}handleMessage(r){let l=r.messageData;switch(r.messageType){case u$.channelProperties:this.channelProperties=l,this._voicesAmount=this.channelProperties.reduce((g,d)=>g+d.voicesAmount,0);break;case u$.eventCall:this.eventHandler.callEvent(l.eventName,l.eventData);break;case u$.sequencerSpecific:this.sequencerCallbackFunction&&this.sequencerCallbackFunction(l.messageType,l.messageData);break;case u$.synthesizerSnapshot:this._snapshotCallback&&this._snapshotCallback(l);break;case u$.ready:this.resolveWhenReady();break;case u$.soundfontError:_4(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:B8.requestSynthesizerSnapshot,messageData:void 0,channelNumber:Hi})})}addNewChannel(r=!0){this.channelProperties.push({voicesAmount:0,pitchBend:0,pitchBendRangeSemitones:0,isMuted:!1,isDrum:!1}),r&&this.post({channelNumber:0,messageType:B8.addNewChannel,messageData:null})}setVibrato(r,l){this.post({channelNumber:r,messageType:B8.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 n6(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(Bn)b=127;else{let b0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=d.clientX-b0.left,R0=b0.width;b=Math.floor((R0-p0)/R0*127)}else{let p0=d.clientY-b0.top,R0=b0.height;b=Math.floor(p0/R0*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(h0=>{let b0=document.elementFromPoint(h0.clientX,h0.clientY),p0=parseInt(b0.id.replace("note",""));b.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,h0))}),this.pressedKeys.forEach(h0=>{b.has(h0)||A(h0)})};Bn||(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 WQ=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&&(h0=l(r+1)),h0&&b?g.classList.add("between_sharps"):b?g.classList.add("left_sharp"):h0&&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,h0;for(let b0 of b)if(b0.selectorText==="#keyboard .key"){h0=b0;break}if(h0.style.setProperty("--pressed-transform-skew",`${8e-4/(d/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let b0=getComputedStyle(this.keyboard),p0=parseFloat(b0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),R0=this.keyboard.getBoundingClientRect().height,E1=d/p0,M=R0*E1-R0,K0=(this._keyRange.min+this._keyRange.max)/2,_0=(r.min+r.max)/2;this._keyRange=r;let k1=this.keys.find(_5=>_5.classList.contains("sharp_key")).getBoundingClientRect().width,h2=(K0-_0)*k1,R1=parseFloat(b0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${M}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${E1}) translateX(${h2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${R1/E1}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"),h0=g/127,b0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!b&&this.mode==="light"?p0=`rgba(${b0.slice(0,3).map(E1=>255-(255-E1)*h0).join(", ")}, ${b0[3]})`:p0=`rgba(${b0.slice(0,3).map(E1=>E1*h0).join(", ")}, ${b0[3]})`,d.style.background=p0,this.mode==="dark"){let R0=WQ*h0;d.style.boxShadow=`${p0} 0px 0px ${R0}px ${R0/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(h0=>h0===this.channelColors[l]);b!==-1&&(d.splice(b,1),g.style.background=d[d.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${WQ}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=ZQ;function d$(A,r){let l=A.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var kD="#000";function jQ(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=kD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var DB=!1;function XQ(A=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(DB){A&&requestAnimationFrame(this.render.bind(this));return}else DB=!0;else DB=!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||jQ(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=`${bB}px Verdana`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,bB+5),this.drawingContext.fillText(Math.round(d).toString()+" FPS",this.canvas.width,5),this.onRender&&this.onRender(),A&&requestAnimationFrame(this.render.bind(this))}function ey(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-E$*2,h0=this.noteFallingTimeMs/1e3,b0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,R0=p0-b0,E1=h0+b0,M=R0+E1,K0=iy/E1,_0=[];this.synth.channelProperties.forEach(h2=>{if(this.showVisualPitch){let R1=h2.pitchBend-8192+this.visualPitchBendOffset;_0.push(h2.pitchBendRangeSemitones*(R1/8192*d))}else _0.push(0)});let k1=[];return this.noteTimes.forEach((h2,R1)=>{if(h2.renderStartIndex>=h2.notes.length||!this.renderChannels[R1])return;let _5=h2.renderStartIndex,v2=h2.notes,J2=v2[_5],n3=-1;for(;J2.start<=M&&(_5++,!(this.notesOnScreen>ry));){let U5=J2.start+J2.length;if(U5>R0&&J2.length>0){let a0=J2.length/E1*l-E$*2;if(this.notesOnScreen<1e3||a0>K0){n3===-1&&(n3=_5-1);let J5=(J2.start-R0)/E1*l,s6;if(this._notesFall?s6=l-a0-J5+E$:s6=J5+E$,J2.midiNotethis.keyRange.max){if(_5>=v2.length)break;J2=v2[_5];continue}let c6=J2.midiNote-this.keyRange.min,O6=d*c6+E$,g6,u4,Ke,J4;if(this.sideways?(g6=s6,u4=O6,J4=b,Ke=a0):(u4=s6,g6=O6,Ke=b,J4=a0),this.notesOnScreen++,A)this.drawingContext.fillStyle=this.plainColors[R1],this.drawingContext.fillRect(g6+I$+E$,u4+I$,Ke-I$*2,J4-I$*2);else{let p9;if(J2.start>p0||U5=v2.length)break;J2=v2[_5]}n3>-1&&(h2.renderStartIndex=n3)}),k1.sort((h2,R1)=>R1.height-h2.height),k1}function ny(){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),h0=!1;for(let M=g;M0){h0=!0;break}if(!h0){let M=this.canvas.width/4,K0=this.canvas.height/4,_0=M*d,k1=K0*b+K0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(_0,k1),this.drawingContext.lineTo(_0+M,k1),this.drawingContext.stroke();return}let b0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(b0);let p0=A*d,R0=r*b+r/2,E1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let M=b0.length/4,K0=A/M,_0=Math.floor(M/2),k1=b0.length-_0;for(let v2=k1;v2>=1;v2--)if(b0[v2-1]<0&&b0[v2]>=0){k1=v2;break}let h2=p0,R1=k1-_0,_5=k1+_0;for(let v2=R1;v2<_5;v2++)this.drawingContext.lineTo(h2,R0+b0[v2]*E1),h2+=K0}else{let M=A/b0.length,K0=p0;for(let _0=0;_0{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function oy(){for(let A=0;A4096?this.delayNode.delayTime.value=d/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function ay(A){A.connectIndividualOutputs(this.channelAnalysers),A.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{this.updateFftSize()})}function $y(){for(let A of this.channelAnalysers)A.disconnect();Y5("%cAnalysers disconnected!",D1.recognized)}function ly(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 cy(){this.noteTimes&&this.noteTimes.forEach(A=>A.renderStartIndex=0)}function _B(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 gy(A){function r(R0){return R0.messageData=new n6(R0.messageData.buffer),R0.messageData.currentIndex=0,6e7/_B(R0.messageData,3)}let l=[],d=A.tracks.flat();d.sort((R0,E1)=>R0.ticks-E1.ticks);for(let R0=0;R0<16;R0++)l.push({renderStartIndex:0,notes:[]});let b=0,h0=60/(120*A.timeDivision),b0=0,p0=0;for(;b0>4,M=R0.messageStatusByte&15;if(E1===8){let K0=l[M].notes.findLast(_0=>_0.midiNote===R0.messageData[0]&&_0.length===-1);if(K0){let _0=b-K0.start;K0.length=_0<$h&&M===ki?$h:_0}p0--}else if(E1===9)if(R0.messageData[1]===0){let K0=l[M].notes.findLast(_0=>_0.midiNote===R0.messageData[0]&&_0.length===-1);if(K0){let _0=b-K0.start;K0.length=_0<$h&&M===ki?$h:_0}p0--}else l[R0.messageStatusByte&15].notes.push({midiNote:R0.messageData[0],start:b,length:-1,velocity:R0.messageData[1]/127}),p0++;else R0.messageStatusByte===81&&(h0=60/(r(R0)*A.timeDivision));if(++b0>=d.length)break;b+=h0*(d[b0].ticks-R0.ticks)}p0>0&&l.forEach((R0,E1)=>R0.notes.filter(M=>M.length===-1).forEach(M=>{let K0=b-M.start;M.length=K0<$h&&E1===ki?$h:K0})),this.noteTimes=l,Y5("%cFinished loading note times and ready to render the sequence!",D1.info)}var vD=1024,SD=4096,DD=2,bD=2,Im=.6,Em=.5,I$=1,E$=1,bB=16,ty=.6,iy=2,ry=81572,vi=class{constructor(r,l,g,d){this.noteFallingTimeMs=1e3,this.noteAfterTriggerTimeMs=0,this._keyRange={min:0,max:127},this.visualPitchBendOffset=0,this.lineThickness=bD,this._normalAnalyserFft=vD,this._drumAnalyserFft=SD,this.waveMultiplier=DD,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,d$(r,g=>g*Em)),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,d$(r,g=>g*Em*Im)),l.addColorStop(1,d$(r,g=>g*Im)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,d$(r,g=>g*Em)),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,d$(r,g=>g*Em*Im)),l.addColorStop(1,d$(r,g=>g*Im)),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}};vi.prototype.render=XQ;vi.prototype.computeNotePositions=ey;vi.prototype.createChannelAnalysers=Ay;vi.prototype.updateFftSize=oy;vi.prototype.connectChannelAnalysers=ay;vi.prototype.disconnectChannelAnalysers=$y;vi.prototype.connectSequencer=ly;vi.prototype.calculateNoteTimes=gy;vi.prototype.resetIndexes=cy;vi.prototype.renderWaveforms=ny;function r3(A,r){let l=0;for(let g=0;g>>0}function C$(A,r,l){for(let g=0;g>g*8&255}function B9(A,r){A[A.currentIndex++]=r&255,A[A.currentIndex++]=r>>8}function $t(A,r){C$(A,r,4)}function lh(A,r){let l=r<<8|A;return l>32767?l-65536:l}function hy(A){return A>127?A-256:A}function ue(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 h0=0;h0127){if(g){d=!0;continue}else if(b0===0){d=!0;continue}}b+=String.fromCharCode(b0)}}return b}}function So(A,r=0){let l=A.length;r>0&&(l=r);let g=new n6(l);return di(g,A,r),g}function di(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,ue(l.chunkData,4)===r))}function Cm(A){let r=[A&127];for(A>>=7;A>0;)r.unshift(A&127|128),A>>=7;return r}function mm(A){let r=[];for(let d of A.tracks){let b=[],h0=0,b0;for(let p0 of d){let R0=p0.ticks-h0,E1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?E1=[255,p0.messageStatusByte,...Cm(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?E1=[240,...Cm(p0.messageData.length),...p0.messageData]:(E1=[],b0!==p0.messageStatusByte&&(b0=p0.messageStatusByte,E1.push(p0.messageStatusByte)),E1.push(...p0.messageData)),b.push(...Cm(R0)),b.push(...E1),h0+=R0}r.push(new Uint8Array(b))}function l(d,b){for(let h0=0;h0A.chunkData.currentIndex;)r.push(new RB(A.chunkData));return r.length>1&&r.pop(),r}var L7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Qn={linear:0,concave:1,convex:2,switch:3},_D=[];for(let A=0;A<4;A++)_D.push([[],[]]);var o7=class A{constructor(r){r.srcEnum?(this.modulatorSource=r.srcEnum,this.modulatorDestination=r.dest,this.modulationSecondarySrc=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.modulatorSource=r3(r,2),this.modulatorDestination=r3(r,2),this.transformAmount=lh(r[r.currentIndex++],r[r.currentIndex++]),this.modulationSecondarySrc=r3(r,2),this.transformType=r3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=b1.INVALID),this.sourcePolarity=this.modulatorSource>>9&1,this.sourceDirection=this.modulatorSource>>8&1,this.sourceUsesCC=this.modulatorSource>>7&1,this.sourceIndex=this.modulatorSource&127,this.sourceCurveType=this.modulatorSource>>10&3,this.secSrcPolarity=this.modulationSecondarySrc>>9&1,this.secSrcDirection=this.modulationSecondarySrc>>8&1,this.secSrcUsesCC=this.modulationSecondarySrc>>7&1,this.secSrcIndex=this.modulationSecondarySrc&127,this.secSrcCurveType=this.modulationSecondarySrc>>10&3}sumTransform(r){return new A({srcEnum:this.modulatorSource,secSrcEnum:this.modulationSecondarySrc,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(d,b){return Object.keys(d).find(h0=>d[h0]===b)}let l=r(Qn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(o6,this.sourceIndex):l+=r(L7,this.sourceIndex);let g=r(Qn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(o6,this.secSrcIndex):g+=r(L7,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 n6(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(Bn)b=127;else{let b0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=d.clientX-b0.left,R0=b0.width;b=Math.floor((R0-p0)/R0*127)}else{let p0=d.clientY-b0.top,R0=b0.height;b=Math.floor(p0/R0*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(h0=>{let b0=document.elementFromPoint(h0.clientX,h0.clientY),p0=parseInt(b0.id.replace("note",""));b.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,h0))}),this.pressedKeys.forEach(h0=>{b.has(h0)||A(h0)})};Bn||(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 WQ=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&&(h0=l(r+1)),h0&&b?g.classList.add("between_sharps"):b?g.classList.add("left_sharp"):h0&&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,h0;for(let b0 of b)if(b0.selectorText==="#keyboard .key"){h0=b0;break}if(h0.style.setProperty("--pressed-transform-skew",`${8e-4/(d/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let b0=getComputedStyle(this.keyboard),p0=parseFloat(b0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),R0=this.keyboard.getBoundingClientRect().height,E1=d/p0,M=R0*E1-R0,K0=(this._keyRange.min+this._keyRange.max)/2,_0=(r.min+r.max)/2;this._keyRange=r;let k1=this.keys.find(_5=>_5.classList.contains("sharp_key")).getBoundingClientRect().width,h2=(K0-_0)*k1,R1=parseFloat(b0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${M}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${E1}) translateX(${h2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${R1/E1}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"),h0=g/127,b0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!b&&this.mode==="light"?p0=`rgba(${b0.slice(0,3).map(E1=>255-(255-E1)*h0).join(", ")}, ${b0[3]})`:p0=`rgba(${b0.slice(0,3).map(E1=>E1*h0).join(", ")}, ${b0[3]})`,d.style.background=p0,this.mode==="dark"){let R0=WQ*h0;d.style.boxShadow=`${p0} 0px 0px ${R0}px ${R0/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(h0=>h0===this.channelColors[l]);b!==-1&&(d.splice(b,1),g.style.background=d[d.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${WQ}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=ZQ;function d$(A,r){let l=A.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var kD="#000";function jQ(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=kD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var DB=!1;function XQ(A=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(DB){A&&requestAnimationFrame(this.render.bind(this));return}else DB=!0;else DB=!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||jQ(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=`${bB}px Verdana`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,bB+5),this.drawingContext.fillText(Math.round(d).toString()+" FPS",this.canvas.width,5),this.onRender&&this.onRender(),A&&requestAnimationFrame(this.render.bind(this))}function ey(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-E$*2,h0=this.noteFallingTimeMs/1e3,b0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,R0=p0-b0,E1=h0+b0,M=R0+E1,K0=iy/E1,_0=[];this.synth.channelProperties.forEach(h2=>{if(this.showVisualPitch){let R1=h2.pitchBend-8192+this.visualPitchBendOffset;_0.push(h2.pitchBendRangeSemitones*(R1/8192*d))}else _0.push(0)});let k1=[];return this.noteTimes.forEach((h2,R1)=>{if(h2.renderStartIndex>=h2.notes.length||!this.renderChannels[R1])return;let _5=h2.renderStartIndex,v2=h2.notes,J2=v2[_5],n3=-1;for(;J2.start<=M&&(_5++,!(this.notesOnScreen>ry));){let U5=J2.start+J2.length;if(U5>R0&&J2.length>0){let a0=J2.length/E1*l-E$*2;if(this.notesOnScreen<1e3||a0>K0){n3===-1&&(n3=_5-1);let J5=(J2.start-R0)/E1*l,s6;if(this._notesFall?s6=l-a0-J5+E$:s6=J5+E$,J2.midiNotethis.keyRange.max){if(_5>=v2.length)break;J2=v2[_5];continue}let c6=J2.midiNote-this.keyRange.min,O6=d*c6+E$,g6,u4,Ke,J4;if(this.sideways?(g6=s6,u4=O6,J4=b,Ke=a0):(u4=s6,g6=O6,Ke=b,J4=a0),this.notesOnScreen++,A)this.drawingContext.fillStyle=this.plainColors[R1],this.drawingContext.fillRect(g6+I$+E$,u4+I$,Ke-I$*2,J4-I$*2);else{let p9;if(J2.start>p0||U5=v2.length)break;J2=v2[_5]}n3>-1&&(h2.renderStartIndex=n3)}),k1.sort((h2,R1)=>R1.height-h2.height),k1}function ny(){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),h0=!1;for(let M=g;M0){h0=!0;break}if(!h0){let M=this.canvas.width/4,K0=this.canvas.height/4,_0=M*d,k1=K0*b+K0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(_0,k1),this.drawingContext.lineTo(_0+M,k1),this.drawingContext.stroke();return}let b0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(b0);let p0=A*d,R0=r*b+r/2,E1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let M=b0.length/4,K0=A/M,_0=Math.floor(M/2),k1=b0.length-_0;for(let v2=k1;v2>=1;v2--)if(b0[v2-1]<0&&b0[v2]>=0){k1=v2;break}let h2=p0,R1=k1-_0,_5=k1+_0;for(let v2=R1;v2<_5;v2++)this.drawingContext.lineTo(h2,R0+b0[v2]*E1),h2+=K0}else{let M=A/b0.length,K0=p0;for(let _0=0;_0{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function oy(){for(let A=0;A4096?this.delayNode.delayTime.value=d/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function ay(A){A.connectIndividualOutputs(this.channelAnalysers),A.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{this.updateFftSize()})}function $y(){for(let A of this.channelAnalysers)A.disconnect();Y5("%cAnalysers disconnected!",D1.recognized)}function ly(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 cy(){this.noteTimes&&this.noteTimes.forEach(A=>A.renderStartIndex=0)}function _B(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 gy(A){function r(R0){return R0.messageData=new n6(R0.messageData.buffer),R0.messageData.currentIndex=0,6e7/_B(R0.messageData,3)}let l=[],d=A.tracks.flat();d.sort((R0,E1)=>R0.ticks-E1.ticks);for(let R0=0;R0<16;R0++)l.push({renderStartIndex:0,notes:[]});let b=0,h0=60/(120*A.timeDivision),b0=0,p0=0;for(;b0>4,M=R0.messageStatusByte&15;if(E1===8){let K0=l[M].notes.findLast(_0=>_0.midiNote===R0.messageData[0]&&_0.length===-1);if(K0){let _0=b-K0.start;K0.length=_0<$h&&M===ki?$h:_0}p0--}else if(E1===9)if(R0.messageData[1]===0){let K0=l[M].notes.findLast(_0=>_0.midiNote===R0.messageData[0]&&_0.length===-1);if(K0){let _0=b-K0.start;K0.length=_0<$h&&M===ki?$h:_0}p0--}else l[R0.messageStatusByte&15].notes.push({midiNote:R0.messageData[0],start:b,length:-1,velocity:R0.messageData[1]/127}),p0++;else R0.messageStatusByte===81&&(h0=60/(r(R0)*A.timeDivision));if(++b0>=d.length)break;b+=h0*(d[b0].ticks-R0.ticks)}p0>0&&l.forEach((R0,E1)=>R0.notes.filter(M=>M.length===-1).forEach(M=>{let K0=b-M.start;M.length=K0<$h&&E1===ki?$h:K0})),this.noteTimes=l,Y5("%cFinished loading note times and ready to render the sequence!",D1.info)}var vD=1024,SD=4096,DD=2,bD=2,Im=.6,Em=.5,I$=1,E$=1,bB=16,ty=.6,iy=2,ry=81572,vi=class{constructor(r,l,g,d){this.noteFallingTimeMs=1e3,this.noteAfterTriggerTimeMs=0,this._keyRange={min:0,max:127},this.visualPitchBendOffset=0,this.lineThickness=bD,this._normalAnalyserFft=vD,this._drumAnalyserFft=SD,this.waveMultiplier=DD,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,d$(r,g=>g*Em)),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,d$(r,g=>g*Em*Im)),l.addColorStop(1,d$(r,g=>g*Im)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,d$(r,g=>g*Em)),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,d$(r,g=>g*Em*Im)),l.addColorStop(1,d$(r,g=>g*Im)),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}};vi.prototype.render=XQ;vi.prototype.computeNotePositions=ey;vi.prototype.createChannelAnalysers=Ay;vi.prototype.updateFftSize=oy;vi.prototype.connectChannelAnalysers=ay;vi.prototype.disconnectChannelAnalysers=$y;vi.prototype.connectSequencer=ly;vi.prototype.calculateNoteTimes=gy;vi.prototype.resetIndexes=cy;vi.prototype.renderWaveforms=ny;function r3(A,r){let l=0;for(let g=0;g>>0}function C$(A,r,l){for(let g=0;g>g*8&255}function B9(A,r){A[A.currentIndex++]=r&255,A[A.currentIndex++]=r>>8}function $t(A,r){C$(A,r,4)}function lh(A,r){let l=r<<8|A;return l>32767?l-65536:l}function hy(A){return A>127?A-256:A}function ue(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 h0=0;h0127){if(g){d=!0;continue}else if(b0===0){d=!0;continue}}b+=String.fromCharCode(b0)}}return b}}function So(A,r=0){let l=A.length;r>0&&(l=r);let g=new n6(l);return di(g,A,r),g}function di(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,ue(l.chunkData,4)===r))}function Cm(A){let r=[A&127];for(A>>=7;A>0;)r.unshift(A&127|128),A>>=7;return r}function mm(A){let r=[];for(let d of A.tracks){let b=[],h0=0,b0;for(let p0 of d){let R0=p0.ticks-h0,E1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?E1=[255,p0.messageStatusByte,...Cm(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?E1=[240,...Cm(p0.messageData.length),...p0.messageData]:(E1=[],b0!==p0.messageStatusByte&&(b0=p0.messageStatusByte,E1.push(p0.messageStatusByte)),E1.push(...p0.messageData)),b.push(...Cm(R0)),b.push(...E1),h0+=R0}r.push(new Uint8Array(b))}function l(d,b){for(let h0=0;h0A.chunkData.currentIndex;)r.push(new RB(A.chunkData));return r.length>1&&r.pop(),r}var L7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Qn={linear:0,concave:1,convex:2,switch:3},_D=[];for(let A=0;A<4;A++)_D.push([[],[]]);var o7=class A{constructor(r){r.srcEnum?(this.modulatorSource=r.srcEnum,this.modulatorDestination=r.dest,this.modulationSecondarySrc=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.modulatorSource=r3(r,2),this.modulatorDestination=r3(r,2),this.transformAmount=lh(r[r.currentIndex++],r[r.currentIndex++]),this.modulationSecondarySrc=r3(r,2),this.transformType=r3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=b1.INVALID),this.sourcePolarity=this.modulatorSource>>9&1,this.sourceDirection=this.modulatorSource>>8&1,this.sourceUsesCC=this.modulatorSource>>7&1,this.sourceIndex=this.modulatorSource&127,this.sourceCurveType=this.modulatorSource>>10&3,this.secSrcPolarity=this.modulationSecondarySrc>>9&1,this.secSrcDirection=this.modulationSecondarySrc>>8&1,this.secSrcUsesCC=this.modulationSecondarySrc>>7&1,this.secSrcIndex=this.modulationSecondarySrc&127,this.secSrcCurveType=this.modulationSecondarySrc>>10&3}sumTransform(r){return new A({srcEnum:this.modulatorSource,secSrcEnum:this.modulationSecondarySrc,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(d,b){return Object.keys(d).find(h0=>d[h0]===b)}let l=r(Qn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(o6,this.sourceIndex):l+=r(L7,this.sourceIndex);let g=r(Qn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(o6,this.secSrcIndex):g+=r(L7,this.secSrcIndex),`Modulator: Source: ${l} Secondary source: ${g} Destination: ${r(b1,this.modulatorDestination)} diff --git a/src/website/minified/local_main.min.js b/src/website/minified/local_main.min.js index a9d712cb..6f77dd95 100644 --- a/src/website/minified/local_main.min.js +++ b/src/website/minified/local_main.min.js @@ -1,5 +1,5 @@ var am=(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 n6=class extends Uint8Array{constructor(r){super(r),this.currentIndex=0}currentIndex};function Ds(o){let r=o.reduce((E,x)=>E+x.length,0),l=new n6(r),g=0;for(let E of o)l.set(E,g),g+=E.length;return l}function h$(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 CB(o){return o.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}var D1={warn:"color: orange;",unrecognized:"color: red;",info:"color: aqua;",recognized:"color: lime",value:"color: yellow; background-color: black;"};var ui=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,midiChannelPrefix:32,midiPort:33,endOfTrack:47,setTempo:81,smpteOffset:84,timeSignature:88,keySignature:89,sequenceSpecific:127};function UQ(o){let r=o&240,l=o&15,g=-1,E=o;return r>=128&&r<=224&&(g=l,E=r),{status:E,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 $m=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 mB={nodesAmount:4,defaultDelay:.03,delayVariation:.01,stereoDifference:.02,oscillatorFrequency:.3,oscillatorFrequencyVariation:.05,oscillatorGain:.003},lm=class{constructor(r,l=mB){let g=r.context;this.input=new ChannelSplitterNode(g,{numberOfOutputs:2});let E=new ChannelMergerNode(g,{numberOfInputs:2}),x=[],u0=[],R0=l.oscillatorFrequency,p0=l.defaultDelay;for(let D0=0;D0{let x=await E.arrayBuffer();l.buffer=await o.decodeAudioData(x)})}return l}var B8={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},dC={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},Pi=-1,f$={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var fD=!0,uD=!0,BB=!0;function j5(...o){fD&&console.info(...o)}function fe(...o){uD&&console.warn(...o)}function or(...o){BB&&console.group(...o)}function ei(...o){BB&&console.groupCollapsed(...o)}function t4(){BB&&console.groupEnd()}var PQ={chorusEnabled:!0,chorusConfig:mB,reverbEnabled:!0,reverbImpulseResponse:void 0};var EC={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var cm=class{constructor(r){this.soundfontList=[{id:"main",bankOffset:0}],this._port=r.worklet.port,this.synth=r}_sendToWorklet(r,l){this._port.postMessage({messageType:B8.soundFontManager,messageData:[r,l]})}async addNewSoundFont(r,l,g=0){if(this.soundfontList.find(E=>E.id===l)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this._sendToWorklet(EC.addNewSoundFont,[r,l,g]),await new Promise(E=>this.synth.resolveWhenReady=E),this.soundfontList.push({id:l,bankOffset:g})}deleteSoundFont(r){if(this.soundfontList.length===0){fe("1 soundfont left. Aborting!");return}if(this.soundfontList.findIndex(l=>l.id===r)===-1){fe(`No soundfont with id of "${r}" found. Aborting!`);return}this._sendToWorklet(EC.deleteSoundFont,r)}rearrangeSoundFonts(r){this._sendToWorklet(EC.rearrangeSoundFonts,r),this.soundfontList.sort((l,g)=>r.indexOf(l.id)-r.indexOf(g.id))}async reloadManager(r){this._sendToWorklet(EC.reloadSoundFont,r),await new Promise(l=>this.synth.resolveWhenReady=l)}};var ID="spessasynth-worklet-system",pB=450,ki=9,dD=16;var sh=class{constructor(r,l,g=!0,E=void 0,x=PQ){j5("%cInitializing SpessaSynth synthesizer...",D1.info),this.context=r.context;let u0=E?.oneOutput===!0;this.eventHandler=new $m,this._voiceCap=pB,this._outputsAmount=dD,this.channelsAmount=this._outputsAmount,this.resolveWhenReady=void 0,this.isReady=new Promise(D0=>this.resolveWhenReady=D0),this.channelProperties=[];for(let D0=0;D0this.handleMessage(D0.data),this.soundfontManager=new cm(this),this._snapshotCallback=void 0,this.sequencerCallbackFunction=void 0,x.reverbEnabled&&!u0&&(this.reverbProcessor=OQ(this.context,x.reverbImpulseResponse),this.reverbProcessor.connect(r),this.worklet.connect(this.reverbProcessor,0)),x.chorusEnabled&&!u0&&(this.chorusProcessor=new lm(r,x.chorusConfig),this.worklet.connect(this.chorusProcessor.input,1)),u0)this.worklet.connect(r,0);else for(let D0=2;D0{this.channelsAmount++})}get voiceCap(){return this._voiceCap}set voiceCap(r){this._setMasterParam(dC.voicesCap,r),this._voiceCap=r}set highPerformanceMode(r){this._highPerformanceMode=r}get highPerformanceMode(){return this._highPerformanceMode}setLogLevel(r,l,g,E){this.post({channelNumber:Pi,messageType:B8.setLogLevel,messageData:[r,l,g,E]})}_setMasterParam(r,l){this.post({channelNumber:Pi,messageType:B8.setMasterParameter,messageData:[r,l]})}setInterpolationType(r){this._setMasterParam(dC.interpolationType,r)}handleMessage(r){let l=r.messageData;switch(r.messageType){case f$.channelProperties:this.channelProperties=l,this._voicesAmount=this.channelProperties.reduce((g,E)=>g+E.voicesAmount,0);break;case f$.eventCall:this.eventHandler.callEvent(l.eventName,l.eventData);break;case f$.sequencerSpecific:this.sequencerCallbackFunction&&this.sequencerCallbackFunction(l.messageType,l.messageData);break;case f$.synthesizerSnapshot:this._snapshotCallback&&this._snapshotCallback(l);break;case f$.ready:this.resolveWhenReady();break;case f$.soundfontError:fe(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:B8.requestSynthesizerSnapshot,messageData:void 0,channelNumber:Pi})})}addNewChannel(r=!0){this.channelProperties.push({voicesAmount:0,pitchBend:0,pitchBendRangeSemitones:0,isMuted:!1,isDrum:!1}),r&&this.post({channelNumber:0,messageType:B8.addNewChannel,messageData:null})}setVibrato(r,l){this.post({channelNumber:r,messageType:B8.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 n6(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,E)=>{let x;if(vo)x=127;else{let R0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=E.clientX-R0.left,D0=R0.width;x=Math.floor((D0-p0)/D0*127)}else{let p0=E.clientY-R0.top,D0=R0.height;x=Math.floor(p0/D0*127)}}this.synth.noteOn(this.channel,g,x,this.enableDebugging)},l=g=>{let E=g.touches?Array.from(g.touches):[g],x=new Set;E.forEach(u0=>{let R0=document.elementFromPoint(u0.clientX,u0.clientY),p0=parseInt(R0.id.replace("note",""));x.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,u0))}),this.pressedKeys.forEach(u0=>{x.has(u0)||o(u0)})};vo||(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 qQ=20,CC=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 E=0;E<128;E++)this.releaseNote(E,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&&(x=l(r-1)),r<127&&(u0=l(r+1)),u0&&x?g.classList.add("between_sharps"):x?g.classList.add("left_sharp"):u0&&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 E=900/(r.max-r.min+5),x=document.styleSheets[0].cssRules,u0;for(let R0 of x)if(R0.selectorText==="#keyboard .key"){u0=R0;break}if(u0.style.setProperty("--pressed-transform-skew",`${8e-4/(E/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let R0=getComputedStyle(this.keyboard),p0=parseFloat(R0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),D0=this.keyboard.getBoundingClientRect().height,E1=E/p0,M=D0*E1-D0,K0=(this._keyRange.min+this._keyRange.max)/2,_0=(r.min+r.max)/2;this._keyRange=r;let k1=this.keys.find(_5=>_5.classList.contains("sharp_key")).getBoundingClientRect().width,h2=(K0-_0)*k1,R1=parseFloat(R0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${M}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${E1}) translateX(${h2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${R1/E1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${E}`),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",`${E}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let E=this.keys[r-this._keyRange.min];if(E===void 0)return;E.classList.add("pressed");let x=E.classList.contains("sharp_key"),u0=g/127,R0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!x&&this.mode==="light"?p0=`rgba(${R0.slice(0,3).map(E1=>255-(255-E1)*u0).join(", ")}, ${R0[3]})`:p0=`rgba(${R0.slice(0,3).map(E1=>E1*u0).join(", ")}, ${R0[3]})`,E.style.background=p0,this.mode==="dark"){let D0=qQ*u0;E.style.boxShadow=`${p0} 0px 0px ${D0}px ${D0/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 E=this.keyColors[r-this._keyRange.min];if(!E)return;let x=E.findLastIndex(u0=>u0===this.channelColors[l]);x!==-1&&(E.splice(x,1),g.style.background=E[E.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${qQ}px ${E[E.length-1]}`),E.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]=[]})}};CC.prototype._handlePointers=HQ;function u$(o,r){let l=o.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var CD="#000";function YQ(o,r,l){o.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let E=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*E,l){r.fillRect(g.xPos,g.yPos-g.height*E,g.width,g.height*(E*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*E,g.yPos,g.width*(E*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=CD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var QB=!1;function JQ(o=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(QB){o&&requestAnimationFrame(this.render.bind(this));return}else QB=!0;else QB=!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 x=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||YQ(x,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let E=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${yB}px Verdana`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,yB+5),this.drawingContext.fillText(Math.round(E).toString()+" FPS",this.canvas.width,5),this.onRender&&this.onRender(),o&&requestAnimationFrame(this.render.bind(this))}function KQ(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,E=r/(g+1),x=E-d$*2,u0=this.noteFallingTimeMs/1e3,R0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,D0=p0-R0,E1=u0+R0,M=D0+E1,K0=zQ/E1,_0=[];this.synth.channelProperties.forEach(h2=>{if(this.showVisualPitch){let R1=h2.pitchBend-8192+this.visualPitchBendOffset;_0.push(h2.pitchBendRangeSemitones*(R1/8192*E))}else _0.push(0)});let k1=[];return this.noteTimes.forEach((h2,R1)=>{if(h2.renderStartIndex>=h2.notes.length||!this.renderChannels[R1])return;let _5=h2.renderStartIndex,v2=h2.notes,J2=v2[_5],n3=-1;for(;J2.start<=M&&(_5++,!(this.notesOnScreen>ZQ));){let U5=J2.start+J2.length;if(U5>D0&&J2.length>0){let a0=J2.length/E1*l-d$*2;if(this.notesOnScreen<1e3||a0>K0){n3===-1&&(n3=_5-1);let Y5=(J2.start-D0)/E1*l,s6;if(this._notesFall?s6=l-a0-Y5+d$:s6=Y5+d$,J2.midiNotethis.keyRange.max){if(_5>=v2.length)break;J2=v2[_5];continue}let c6=J2.midiNote-this.keyRange.min,O6=E*c6+d$,g6,u4,Ke,Y4;if(this.sideways?(g6=s6,u4=O6,Y4=x,Ke=a0):(u4=s6,g6=O6,Ke=x,Y4=a0),this.notesOnScreen++,o)this.drawingContext.fillStyle=this.plainColors[R1],this.drawingContext.fillRect(g6+I$+d$,u4+I$,Ke-I$*2,Y4-I$*2);else{let p9;if(J2.start>p0||U5=v2.length)break;J2=v2[_5]}n3>-1&&(h2.renderStartIndex=n3)}),k1.sort((h2,R1)=>R1.height-h2.height),k1}function WQ(){let o=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let E=g%4,x=Math.floor(g/4),u0=!1;for(let M=g;M0){u0=!0;break}if(!u0){let M=this.canvas.width/4,K0=this.canvas.height/4,_0=M*E,k1=K0*x+K0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(_0,k1),this.drawingContext.lineTo(_0+M,k1),this.drawingContext.stroke();return}let R0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(R0);let p0=o*E,D0=r*x+r/2,E1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let M=R0.length/4,K0=o/M,_0=Math.floor(M/2),k1=R0.length-_0;for(let v2=k1;v2>=1;v2--)if(R0[v2-1]<0&&R0[v2]>=0){k1=v2;break}let h2=p0,R1=k1-_0,_5=k1+_0;for(let v2=R1;v2<_5;v2++)this.drawingContext.lineTo(h2,D0+R0[v2]*E1),h2+=K0}else{let M=o/R0.length,K0=p0;for(let _0=0;_0{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function ey(){for(let o=0;o4096?this.delayNode.delayTime.value=E/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function ty(o){o.connectIndividualOutputs(this.channelAnalysers),o.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{this.updateFftSize()})}function iy(){for(let o of this.channelAnalysers)o.disconnect();j5("%cAnalysers disconnected!",D1.recognized)}function ry(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),E=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${E}), rgba(0, 0, 0, ${E})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function ny(){this.noteTimes&&this.noteTimes.forEach(o=>o.renderStartIndex=0)}function wB(o,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=o[o.currentIndex++]<>>0}function mC(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 Ah=.02;function sy(o){function r(D0){return D0.messageData=new n6(D0.messageData.buffer),D0.messageData.currentIndex=0,6e7/wB(D0.messageData,3)}let l=[],E=o.tracks.flat();E.sort((D0,E1)=>D0.ticks-E1.ticks);for(let D0=0;D0<16;D0++)l.push({renderStartIndex:0,notes:[]});let x=0,u0=60/(120*o.timeDivision),R0=0,p0=0;for(;R0>4,M=D0.messageStatusByte&15;if(E1===8){let K0=l[M].notes.findLast(_0=>_0.midiNote===D0.messageData[0]&&_0.length===-1);if(K0){let _0=x-K0.start;K0.length=_0_0.midiNote===D0.messageData[0]&&_0.length===-1);if(K0){let _0=x-K0.start;K0.length=_0=E.length)break;x+=u0*(E[R0].ticks-D0.ticks)}p0>0&&l.forEach((D0,E1)=>D0.notes.filter(M=>M.length===-1).forEach(M=>{let K0=x-M.start;M.length=K0{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,u$(r,g=>g*hm)),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,u$(r,g=>g*hm*gm)),l.addColorStop(1,u$(r,g=>g*gm)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,u$(r,g=>g*hm)),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,u$(r,g=>g*hm*gm)),l.addColorStop(1,u$(r,g=>g*gm)),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}};vi.prototype.render=JQ;vi.prototype.computeNotePositions=KQ;vi.prototype.createChannelAnalysers=XQ;vi.prototype.updateFftSize=ey;vi.prototype.connectChannelAnalysers=ty;vi.prototype.disconnectChannelAnalysers=iy;vi.prototype.connectSequencer=ry;vi.prototype.calculateNoteTimes=sy;vi.prototype.resetIndexes=ny;vi.prototype.renderWaveforms=WQ;function r3(o,r){let l=0;for(let g=0;g>>0}function E$(o,r,l){for(let g=0;g>g*8&255}function B9(o,r){o[o.currentIndex++]=r&255,o[o.currentIndex++]=r>>8}function at(o,r){E$(o,r,4)}function oh(o,r){let l=r<<8|o;return l>32767?l-65536:l}function Ay(o){return o>127?o-256:o}function ue(o,r,l=void 0,g=!0){if(l){let E=o.slice(o.currentIndex,o.currentIndex+r);return o.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(E.buffer)}else{let E=!1,x="";for(let u0=0;u0127){if(g){E=!0;continue}else if(R0===0){E=!0;continue}}x+=String.fromCharCode(R0)}}return x}}function So(o,r=0){let l=o.length;r>0&&(l=r);let g=new n6(l);return Ii(g,o,r),g}function Ii(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,ue(l.chunkData,4)===r))}function fm(o){let r=[o&127];for(o>>=7;o>0;)r.unshift(o&127|128),o>>=7;return r}function um(o){let r=[];for(let E of o.tracks){let x=[],u0=0,R0;for(let p0 of E){let D0=p0.ticks-u0,E1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?E1=[255,p0.messageStatusByte,...fm(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?E1=[240,...fm(p0.messageData.length),...p0.messageData]:(E1=[],R0!==p0.messageStatusByte&&(R0=p0.messageStatusByte,E1.push(p0.messageStatusByte)),E1.push(...p0.messageData)),x.push(...fm(D0)),x.push(...E1),u0+=D0}r.push(new Uint8Array(x))}function l(E,x){for(let u0=0;u0o.chunkData.currentIndex;)r.push(new kB(o.chunkData));return r.length>1&&r.pop(),r}var R7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Qn={linear:0,concave:1,convex:2,switch:3},yD=[];for(let o=0;o<4;o++)yD.push([[],[]]);var o7=class o{constructor(r){r.srcEnum?(this.modulatorSource=r.srcEnum,this.modulatorDestination=r.dest,this.modulationSecondarySrc=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.modulatorSource=r3(r,2),this.modulatorDestination=r3(r,2),this.transformAmount=oh(r[r.currentIndex++],r[r.currentIndex++]),this.modulationSecondarySrc=r3(r,2),this.transformType=r3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=b1.INVALID),this.sourcePolarity=this.modulatorSource>>9&1,this.sourceDirection=this.modulatorSource>>8&1,this.sourceUsesCC=this.modulatorSource>>7&1,this.sourceIndex=this.modulatorSource&127,this.sourceCurveType=this.modulatorSource>>10&3,this.secSrcPolarity=this.modulationSecondarySrc>>9&1,this.secSrcDirection=this.modulationSecondarySrc>>8&1,this.secSrcUsesCC=this.modulationSecondarySrc>>7&1,this.secSrcIndex=this.modulationSecondarySrc&127,this.secSrcCurveType=this.modulationSecondarySrc>>10&3}sumTransform(r){return new o({srcEnum:this.modulatorSource,secSrcEnum:this.modulationSecondarySrc,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(E,x){return Object.keys(E).find(u0=>E[u0]===x)}let l=r(Qn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(o6,this.sourceIndex):l+=r(R7,this.sourceIndex);let g=r(Qn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(o6,this.secSrcIndex):g+=r(R7,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 n6(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,E)=>{let x;if(vo)x=127;else{let R0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=E.clientX-R0.left,D0=R0.width;x=Math.floor((D0-p0)/D0*127)}else{let p0=E.clientY-R0.top,D0=R0.height;x=Math.floor(p0/D0*127)}}this.synth.noteOn(this.channel,g,x,this.enableDebugging)},l=g=>{let E=g.touches?Array.from(g.touches):[g],x=new Set;E.forEach(u0=>{let R0=document.elementFromPoint(u0.clientX,u0.clientY),p0=parseInt(R0.id.replace("note",""));x.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,u0))}),this.pressedKeys.forEach(u0=>{x.has(u0)||o(u0)})};vo||(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 qQ=20,CC=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 E=0;E<128;E++)this.releaseNote(E,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&&(x=l(r-1)),r<127&&(u0=l(r+1)),u0&&x?g.classList.add("between_sharps"):x?g.classList.add("left_sharp"):u0&&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 E=900/(r.max-r.min+5),x=document.styleSheets[0].cssRules,u0;for(let R0 of x)if(R0.selectorText==="#keyboard .key"){u0=R0;break}if(u0.style.setProperty("--pressed-transform-skew",`${8e-4/(E/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let R0=getComputedStyle(this.keyboard),p0=parseFloat(R0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),D0=this.keyboard.getBoundingClientRect().height,E1=E/p0,M=D0*E1-D0,K0=(this._keyRange.min+this._keyRange.max)/2,_0=(r.min+r.max)/2;this._keyRange=r;let k1=this.keys.find(_5=>_5.classList.contains("sharp_key")).getBoundingClientRect().width,h2=(K0-_0)*k1,R1=parseFloat(R0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${M}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${E1}) translateX(${h2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${R1/E1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${E}`),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",`${E}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let E=this.keys[r-this._keyRange.min];if(E===void 0)return;E.classList.add("pressed");let x=E.classList.contains("sharp_key"),u0=g/127,R0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!x&&this.mode==="light"?p0=`rgba(${R0.slice(0,3).map(E1=>255-(255-E1)*u0).join(", ")}, ${R0[3]})`:p0=`rgba(${R0.slice(0,3).map(E1=>E1*u0).join(", ")}, ${R0[3]})`,E.style.background=p0,this.mode==="dark"){let D0=qQ*u0;E.style.boxShadow=`${p0} 0px 0px ${D0}px ${D0/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 E=this.keyColors[r-this._keyRange.min];if(!E)return;let x=E.findLastIndex(u0=>u0===this.channelColors[l]);x!==-1&&(E.splice(x,1),g.style.background=E[E.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${qQ}px ${E[E.length-1]}`),E.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]=[]})}};CC.prototype._handlePointers=HQ;function u$(o,r){let l=o.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var CD="#000";function YQ(o,r,l){o.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let E=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*E,l){r.fillRect(g.xPos,g.yPos-g.height*E,g.width,g.height*(E*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*E,g.yPos,g.width*(E*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=CD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var QB=!1;function JQ(o=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(QB){o&&requestAnimationFrame(this.render.bind(this));return}else QB=!0;else QB=!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 x=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||YQ(x,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let E=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${yB}px Verdana`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,yB+5),this.drawingContext.fillText(Math.round(E).toString()+" FPS",this.canvas.width,5),this.onRender&&this.onRender(),o&&requestAnimationFrame(this.render.bind(this))}function KQ(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,E=r/(g+1),x=E-d$*2,u0=this.noteFallingTimeMs/1e3,R0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,D0=p0-R0,E1=u0+R0,M=D0+E1,K0=zQ/E1,_0=[];this.synth.channelProperties.forEach(h2=>{if(this.showVisualPitch){let R1=h2.pitchBend-8192+this.visualPitchBendOffset;_0.push(h2.pitchBendRangeSemitones*(R1/8192*E))}else _0.push(0)});let k1=[];return this.noteTimes.forEach((h2,R1)=>{if(h2.renderStartIndex>=h2.notes.length||!this.renderChannels[R1])return;let _5=h2.renderStartIndex,v2=h2.notes,J2=v2[_5],n3=-1;for(;J2.start<=M&&(_5++,!(this.notesOnScreen>ZQ));){let U5=J2.start+J2.length;if(U5>D0&&J2.length>0){let a0=J2.length/E1*l-d$*2;if(this.notesOnScreen<1e3||a0>K0){n3===-1&&(n3=_5-1);let Y5=(J2.start-D0)/E1*l,s6;if(this._notesFall?s6=l-a0-Y5+d$:s6=Y5+d$,J2.midiNotethis.keyRange.max){if(_5>=v2.length)break;J2=v2[_5];continue}let c6=J2.midiNote-this.keyRange.min,O6=E*c6+d$,g6,u4,Ke,Y4;if(this.sideways?(g6=s6,u4=O6,Y4=x,Ke=a0):(u4=s6,g6=O6,Ke=x,Y4=a0),this.notesOnScreen++,o)this.drawingContext.fillStyle=this.plainColors[R1],this.drawingContext.fillRect(g6+I$+d$,u4+I$,Ke-I$*2,Y4-I$*2);else{let p9;if(J2.start>p0||U5=v2.length)break;J2=v2[_5]}n3>-1&&(h2.renderStartIndex=n3)}),k1.sort((h2,R1)=>R1.height-h2.height),k1}function WQ(){let o=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let E=g%4,x=Math.floor(g/4),u0=!1;for(let M=g;M0){u0=!0;break}if(!u0){let M=this.canvas.width/4,K0=this.canvas.height/4,_0=M*E,k1=K0*x+K0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(_0,k1),this.drawingContext.lineTo(_0+M,k1),this.drawingContext.stroke();return}let R0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(R0);let p0=o*E,D0=r*x+r/2,E1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let M=R0.length/4,K0=o/M,_0=Math.floor(M/2),k1=R0.length-_0;for(let v2=k1;v2>=1;v2--)if(R0[v2-1]<0&&R0[v2]>=0){k1=v2;break}let h2=p0,R1=k1-_0,_5=k1+_0;for(let v2=R1;v2<_5;v2++)this.drawingContext.lineTo(h2,D0+R0[v2]*E1),h2+=K0}else{let M=o/R0.length,K0=p0;for(let _0=0;_0{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function ey(){for(let o=0;o4096?this.delayNode.delayTime.value=E/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function ty(o){o.connectIndividualOutputs(this.channelAnalysers),o.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{this.updateFftSize()})}function iy(){for(let o of this.channelAnalysers)o.disconnect();j5("%cAnalysers disconnected!",D1.recognized)}function ry(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),E=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${E}), rgba(0, 0, 0, ${E})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function ny(){this.noteTimes&&this.noteTimes.forEach(o=>o.renderStartIndex=0)}function wB(o,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=o[o.currentIndex++]<>>0}function mC(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 Ah=.02;function sy(o){function r(D0){return D0.messageData=new n6(D0.messageData.buffer),D0.messageData.currentIndex=0,6e7/wB(D0.messageData,3)}let l=[],E=o.tracks.flat();E.sort((D0,E1)=>D0.ticks-E1.ticks);for(let D0=0;D0<16;D0++)l.push({renderStartIndex:0,notes:[]});let x=0,u0=60/(120*o.timeDivision),R0=0,p0=0;for(;R0>4,M=D0.messageStatusByte&15;if(E1===8){let K0=l[M].notes.findLast(_0=>_0.midiNote===D0.messageData[0]&&_0.length===-1);if(K0){let _0=x-K0.start;K0.length=_0_0.midiNote===D0.messageData[0]&&_0.length===-1);if(K0){let _0=x-K0.start;K0.length=_0=E.length)break;x+=u0*(E[R0].ticks-D0.ticks)}p0>0&&l.forEach((D0,E1)=>D0.notes.filter(M=>M.length===-1).forEach(M=>{let K0=x-M.start;M.length=K0{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,u$(r,g=>g*hm)),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,u$(r,g=>g*hm*gm)),l.addColorStop(1,u$(r,g=>g*gm)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,u$(r,g=>g*hm)),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,u$(r,g=>g*hm*gm)),l.addColorStop(1,u$(r,g=>g*gm)),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}};vi.prototype.render=JQ;vi.prototype.computeNotePositions=KQ;vi.prototype.createChannelAnalysers=XQ;vi.prototype.updateFftSize=ey;vi.prototype.connectChannelAnalysers=ty;vi.prototype.disconnectChannelAnalysers=iy;vi.prototype.connectSequencer=ry;vi.prototype.calculateNoteTimes=sy;vi.prototype.resetIndexes=ny;vi.prototype.renderWaveforms=WQ;function r3(o,r){let l=0;for(let g=0;g>>0}function E$(o,r,l){for(let g=0;g>g*8&255}function B9(o,r){o[o.currentIndex++]=r&255,o[o.currentIndex++]=r>>8}function at(o,r){E$(o,r,4)}function oh(o,r){let l=r<<8|o;return l>32767?l-65536:l}function Ay(o){return o>127?o-256:o}function ue(o,r,l=void 0,g=!0){if(l){let E=o.slice(o.currentIndex,o.currentIndex+r);return o.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(E.buffer)}else{let E=!1,x="";for(let u0=0;u0127){if(g){E=!0;continue}else if(R0===0){E=!0;continue}}x+=String.fromCharCode(R0)}}return x}}function So(o,r=0){let l=o.length;r>0&&(l=r);let g=new n6(l);return Ii(g,o,r),g}function Ii(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,ue(l.chunkData,4)===r))}function fm(o){let r=[o&127];for(o>>=7;o>0;)r.unshift(o&127|128),o>>=7;return r}function um(o){let r=[];for(let E of o.tracks){let x=[],u0=0,R0;for(let p0 of E){let D0=p0.ticks-u0,E1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?E1=[255,p0.messageStatusByte,...fm(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?E1=[240,...fm(p0.messageData.length),...p0.messageData]:(E1=[],R0!==p0.messageStatusByte&&(R0=p0.messageStatusByte,E1.push(p0.messageStatusByte)),E1.push(...p0.messageData)),x.push(...fm(D0)),x.push(...E1),u0+=D0}r.push(new Uint8Array(x))}function l(E,x){for(let u0=0;u0o.chunkData.currentIndex;)r.push(new kB(o.chunkData));return r.length>1&&r.pop(),r}var R7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Qn={linear:0,concave:1,convex:2,switch:3},yD=[];for(let o=0;o<4;o++)yD.push([[],[]]);var o7=class o{constructor(r){r.srcEnum?(this.modulatorSource=r.srcEnum,this.modulatorDestination=r.dest,this.modulationSecondarySrc=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.modulatorSource=r3(r,2),this.modulatorDestination=r3(r,2),this.transformAmount=oh(r[r.currentIndex++],r[r.currentIndex++]),this.modulationSecondarySrc=r3(r,2),this.transformType=r3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=b1.INVALID),this.sourcePolarity=this.modulatorSource>>9&1,this.sourceDirection=this.modulatorSource>>8&1,this.sourceUsesCC=this.modulatorSource>>7&1,this.sourceIndex=this.modulatorSource&127,this.sourceCurveType=this.modulatorSource>>10&3,this.secSrcPolarity=this.modulationSecondarySrc>>9&1,this.secSrcDirection=this.modulationSecondarySrc>>8&1,this.secSrcUsesCC=this.modulationSecondarySrc>>7&1,this.secSrcIndex=this.modulationSecondarySrc&127,this.secSrcCurveType=this.modulationSecondarySrc>>10&3}sumTransform(r){return new o({srcEnum:this.modulatorSource,secSrcEnum:this.modulationSecondarySrc,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(E,x){return Object.keys(E).find(u0=>E[u0]===x)}let l=r(Qn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(o6,this.sourceIndex):l+=r(R7,this.sourceIndex);let g=r(Qn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(o6,this.secSrcIndex):g+=r(R7,this.secSrcIndex),`Modulator: Source: ${l} Secondary source: ${g} Destination: ${r(b1,this.modulatorDestination)}