From 766242db3955afb5ccff926e5d4aece473d7fb46 Mon Sep 17 00:00:00 2001 From: spessasus Date: Wed, 18 Sep 2024 01:46:56 +0200 Subject: [PATCH] Fix volume change in release --- package.json | 2 +- .../synthetizer/worklet_processor.min.js | 14 +++++------ .../worklet_utilities/volume_envelope.js | 23 +++++++++++-------- 3 files changed, 22 insertions(+), 17 deletions(-) diff --git a/package.json b/package.json index f1aa284e..a9554bfe 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "SpessaSynth", - "version": "3.20.21", + "version": "3.20.22", "type": "module", "scripts": { "start": "node src/website/server/server.js" diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index 40431274..6e1bc3fb 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -1,4 +1,4 @@ -var rs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>(typeof require<"u"?require:A)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var H=class extends Uint8Array{constructor(A){super(A),this.currentIndex=0}currentIndex};function ye(e){let A=e.reduce((n,o)=>n+o.length,0),t=new H(A),s=0;for(let n of e)t.set(n,s),s+=n.length;return t}function lt(e){e=Math.floor(e);let A=Math.floor(e/60),t=Math.round(e-A*60);return{minutes:A,seconds:t,time:`${A.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`}}function is(e){return e.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function hA(e){let A="";for(let t=0;t=128&&A<=224&&(s=t,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},Is={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 gs=!0,Cs=!0,Je=!0,Es=!0;function Bs(e,A,t,s){gs=e,Cs=A,Je=t,Es=s}function m(...e){gs&&console.info(...e)}function b(...e){Cs&&console.warn(...e)}function hs(...e){Es&&console.table(...e)}function Ae(...e){Je&&console.group(...e)}function pA(...e){Je&&console.groupCollapsed(...e)}function Z(){Je&&console.groupEnd()}var ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var Qs="spessasynth-worklet-system",cs=450,SA=9,qe=16,Ke="gs";var NA={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 _A(e,A){let t=0;for(let s=8*(A-1);s>=0;s-=8)t|=e[e.currentIndex++]<>>0}function ls(e,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=De(e.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=s,t.status){case w.noteOn:let n=e.messageData[1];if(n>0)this.synth.noteOn(t.channel,e.messageData[0],n),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:n});else{this.synth.noteOff(t.channel,e.messageData[0]);let g=this.playingNotes.findIndex(C=>C.midiNote===e.messageData[0]&&C.channel===t.channel);g!==-1&&this.playingNotes.splice(g,1)}break;case w.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let o=this.playingNotes.findIndex(g=>g.midiNote===e.messageData[0]&&g.channel===t.channel);o!==-1&&this.playingNotes.splice(o,1);break;case w.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case w.controllerChange:this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case w.programChange:this.synth.programChange(t.channel,e.messageData[0]);break;case w.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case w.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case w.systemExclusive:this.synth.systemExclusive(e.messageData,s);break;case w.setTempo:this.oneTickToSeconds=60/(Do(e)*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,[e.messageData,t.status]);break;case w.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case w.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:b(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(w).find(g=>w[g]===t.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function us(){for(let e=0;e<16;e++)this.synth.createWorkletChannel(!0),e===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Do(e){return e.messageData.currentIndex=0,6e7/_A(e.messageData,3)}function fs(){let e=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let s=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(s.ticks-t.ticks),this.midiData.loop.end<=t.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(e>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function ds(){let e=0,A=1/0;return this.tracks.forEach((t,s)=>{this.eventIndex[s]>=t.length||t[this.eventIndex[s]].ticks>>0}function ae(e,A,t){for(let s=0;s>s*8&255}function Y(e,A){e[e.currentIndex++]=A&255,e[e.currentIndex++]=A>>8}function cA(e,A){ae(e,A,4)}function Ie(e,A){let t=A<<8|e;return t>32767?t-65536:t}function ms(e){return e>127?e-256:e}function V(e,A,t=void 0,s=!0){if(t){let n=e.slice(e.currentIndex,e.currentIndex+A);return e.currentIndex+=A,new TextDecoder(t.replace(/[^\x20-\x7E]/g,"")).decode(n.buffer)}else{let n=!1,o="";for(let g=0;g127){if(s){n=!0;continue}else if(C===0){n=!0;continue}}o+=String.fromCharCode(C)}}return o}}function wA(e,A,t=0){t>0&&A.length>t&&(A=A.slice(0,t));for(let s=0;sA.length)for(let s=0;st.header!=="LIST"?!1:(t.chunkData.currentIndex=0,V(t.chunkData,4)===A))}function Pe(e){let A=0;for(;e;){let t=e[e.currentIndex++];if(A=A<<7|t&127,t>>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,t=0){if(this.generatorType=A,t===void 0)throw new Error("No value provided.");let s=T[A];this.generatorValue=Math.round(t),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}generatorType=I.INVALID;generatorValue=0};function ps(e,A,t){let s=T[e]||{min:0,max:32768,def:0},n=A.find(Q=>Q.generatorType===e),o=0;n&&(o=n.generatorValue);let g=t.find(Q=>Q.generatorType===e),C=s.def;g&&(C=g.generatorValue);let h=C+o;return e===I.initialAttenuation?h:Math.max(s.min,Math.min(s.max,h))}var ut=class extends U{constructor(A){super();let t=A.currentIndex;this.generatorType=A[t+1]<<8|A[t],this.generatorValue=Ie(A[t+2],A[t+3]),A.currentIndex+=4}};function ft(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new ut(e.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 e=0;e<4;e++)ko.push([[],[]]);var rA=class e{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 e({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(g=>n[g]===o)}let t=A(lA,this.sourceCurveType);t+=this.sourcePolarity===0?" unipolar ":" bipolar ",t+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?t+=A(p,this.sourceIndex):t+=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 rs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>(typeof require<"u"?require:A)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var H=class extends Uint8Array{constructor(A){super(A),this.currentIndex=0}currentIndex};function De(e){let A=e.reduce((n,o)=>n+o.length,0),t=new H(A),s=0;for(let n of e)t.set(n,s),s+=n.length;return t}function lt(e){e=Math.floor(e);let A=Math.floor(e/60),t=Math.round(e-A*60);return{minutes:A,seconds:t,time:`${A.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`}}function is(e){return e.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function hA(e){let A="";for(let t=0;t=128&&A<=224&&(s=t,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},Is={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},ie={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},LA=-1,mA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var gs=!0,Cs=!0,Je=!0,Es=!0;function Bs(e,A,t,s){gs=e,Cs=A,Je=t,Es=s}function m(...e){gs&&console.info(...e)}function b(...e){Cs&&console.warn(...e)}function hs(...e){Es&&console.table(...e)}function ee(...e){Je&&console.group(...e)}function pA(...e){Je&&console.groupCollapsed(...e)}function Z(){Je&&console.groupEnd()}var ae={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var Qs="spessasynth-worklet-system",cs=450,SA=9,qe=16,Ke="gs";var bA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},wA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function zA(e,A){let t=0;for(let s=8*(A-1);s>=0;s-=8)t|=e[e.currentIndex++]<>>0}function ls(e,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=ke(e.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=s,t.status){case w.noteOn:let n=e.messageData[1];if(n>0)this.synth.noteOn(t.channel,e.messageData[0],n),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:n});else{this.synth.noteOff(t.channel,e.messageData[0]);let g=this.playingNotes.findIndex(C=>C.midiNote===e.messageData[0]&&C.channel===t.channel);g!==-1&&this.playingNotes.splice(g,1)}break;case w.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let o=this.playingNotes.findIndex(g=>g.midiNote===e.messageData[0]&&g.channel===t.channel);o!==-1&&this.playingNotes.splice(o,1);break;case w.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case w.controllerChange:this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case w.programChange:this.synth.programChange(t.channel,e.messageData[0]);break;case w.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case w.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case w.systemExclusive:this.synth.systemExclusive(e.messageData,s);break;case w.setTempo:this.oneTickToSeconds=60/(Do(e)*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(wA.textEvent,[e.messageData,t.status]);break;case w.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case w.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:b(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(w).find(g=>w[g]===t.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function us(){for(let e=0;e<16;e++)this.synth.createWorkletChannel(!0),e===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Do(e){return e.messageData.currentIndex=0,6e7/zA(e.messageData,3)}function fs(){let e=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let s=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(s.ticks-t.ticks),this.midiData.loop.end<=t.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(e>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function ds(){let e=0,A=1/0;return this.tracks.forEach((t,s)=>{this.eventIndex[s]>=t.length||t[this.eventIndex[s]].ticks>>0}function Ie(e,A,t){for(let s=0;s>s*8&255}function Y(e,A){e[e.currentIndex++]=A&255,e[e.currentIndex++]=A>>8}function cA(e,A){Ie(e,A,4)}function ge(e,A){let t=A<<8|e;return t>32767?t-65536:t}function ms(e){return e>127?e-256:e}function V(e,A,t=void 0,s=!0){if(t){let n=e.slice(e.currentIndex,e.currentIndex+A);return e.currentIndex+=A,new TextDecoder(t.replace(/[^\x20-\x7E]/g,"")).decode(n.buffer)}else{let n=!1,o="";for(let g=0;g127){if(s){n=!0;continue}else if(C===0){n=!0;continue}}o+=String.fromCharCode(C)}}return o}}function FA(e,A,t=0){t>0&&A.length>t&&(A=A.slice(0,t));for(let s=0;sA.length)for(let s=0;st.header!=="LIST"?!1:(t.chunkData.currentIndex=0,V(t.chunkData,4)===A))}function Pe(e){let A=0;for(;e;){let t=e[e.currentIndex++];if(A=A<<7|t&127,t>>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,t=0){if(this.generatorType=A,t===void 0)throw new Error("No value provided.");let s=T[A];this.generatorValue=Math.round(t),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}generatorType=I.INVALID;generatorValue=0};function ps(e,A,t){let s=T[e]||{min:0,max:32768,def:0},n=A.find(Q=>Q.generatorType===e),o=0;n&&(o=n.generatorValue);let g=t.find(Q=>Q.generatorType===e),C=s.def;g&&(C=g.generatorValue);let h=C+o;return e===I.initialAttenuation?h:Math.max(s.min,Math.min(s.max,h))}var ut=class extends U{constructor(A){super();let t=A.currentIndex;this.generatorType=A[t+1]<<8|A[t],this.generatorValue=ge(A[t+2],A[t+3]),A.currentIndex+=4}};function ft(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new ut(e.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 e=0;e<4;e++)ko.push([[],[]]);var rA=class e{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=ge(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 e({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(g=>n[g]===o)}let t=A(lA,this.sourceCurveType);t+=this.sourcePolarity===0?" unipolar ":" bipolar ",t+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?t+=A(p,this.sourceIndex):t+=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: ${t} Secondary source: ${s} Destination: ${A(I,this.modulatorDestination)} @@ -6,11 +6,11 @@ var rs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>( Transform type: ${this.transformType} -`}};function qA(e,A,t,s,n){return e<<10|A<<9|t<<8|s<<7|n}var dt=960,mt=lA.concave,Ss=[new rA({srcEnum:qA(mt,0,1,0,P.noteOnVelocity),dest:I.initialAttenuation,amt:dt,secSrcEnum:0,transform:0}),new rA({srcEnum:129,dest:I.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new rA({srcEnum:qA(mt,0,1,1,p.mainVolume),dest:I.initialAttenuation,amt:dt,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:qA(mt,0,1,1,p.expressionController),dest:I.initialAttenuation,amt:dt,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:qA(lA.linear,0,0,0,P.polyPressure),dest:I.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new rA({srcEnum:qA(lA.linear,0,0,1,p.effects2Depth),dest:I.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new rA({srcEnum:qA(lA.linear,1,0,1,p.releaseTime),dest:I.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new rA({srcEnum:qA(lA.linear,1,0,1,p.brightness),dest:I.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0})];function pt(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new rA(e.chunkData));return A}function ys(e=!1){let A={midiControllers:new Int16Array(St),lockedControllers:Array(St).fill(!1),customControllers:new Float32Array(Ds),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:uA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},lockVibrato:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let t=0;t<128;t++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),e&&this.callEvent("newchannel",void 0)}var gA=128,St=147,KA=new Int16Array(St).fill(0);KA[p.mainVolume]=12800;KA[p.expressionController]=16256;KA[p.pan]=8192;KA[p.releaseTime]=8192;KA[p.brightness]=8192;KA[p.effects1Depth]=5120;KA[gA+P.pitchWheel]=8192;KA[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},Ds=Object.keys(iA).length,yt=new Float32Array(Ds);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=[]}};function ge(e,A){let t=0;for(;e>0;){let s=A.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=Is[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/_A($,3)});break;case w.marker:switch(V(z,z.length).trim().toLowerCase()){default:break;case"start":case"loopstart":f=W;break;case"loopend":u=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:f=W;break;case 4:case 117:u===null?u=W:u=0;break;case 0:C&&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 l=[];for(let S of this.tracks){let k=S.find(x=>(x.messageStatusByte&240)===w.noteOn);k&&l.push(k.ticks)}this.firstNoteOn=Math.min(...l),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),f!==null&&u===null?(f=this.firstNoteOn,u=this.lastVoiceEventTick):(f===null&&(f=this.firstNoteOn),(u===null||u===0)&&(u=this.lastVoiceEventTick)),this.loop={start:f,end:u},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),!g)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=t,this.midiName=this.midiName.trim(),this.midiName.length===0){m("%cNo name detected. Using the alt name!",r.info),this.midiName=is(t),this.rawMidiName=new Uint8Array(this.midiName.length);for(let S=0;Sc>u?c:u),s=[];for(let u=0;u{g[y]>=l.length||l[g[y]].ticks0;){let u=h(),c=e.tracks[u];if(g[u]>=c.length){C--;continue}let l=c[g[u]];if(g[u]++,l.messageStatusByte===w.midiPort){Q[u]=l.messageData[0];continue}let y=l.messageStatusByte&240;if(y!==w.noteOn&&y!==w.controllerChange&&y!==w.programChange&&y!==w.systemExclusive)continue;let S=(l.messageStatusByte&15)+e.midiPortChannelOffsets[Q[u]]||0,k=s[S];switch(y){case w.programChange:k.program=l.messageData[0],n(k);break;case w.controllerChange:if(l.messageData[0]!==p.bankSelect||f==="gs"&&k.drums)continue;let x=l.messageData[1],N=Math.max(0,x-e.bankOffset);if(f==="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(l.messageData[1]===0)continue;n(k),o[k.string].add(`${l.messageData[0]}-${l.messageData[1]}`);break;case w.systemExclusive:if(l.messageData[0]!==65||l.messageData[2]!==66||l.messageData[3]!==18||l.messageData[4]!==64||!(l.messageData[5]&16)||l.messageData[6]!==21){l.messageData[0]===67&&l.messageData[2]===76&&l.messageData[5]===126&&l.messageData[6]===0&&(f="xg");continue}let M=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][l.messageData[5]&15]+e.midiPortChannelOffsets[Q[u]],W=!!(l.messageData[7]>0&&l.messageData[5]>>4);k=s[M],k.drums=W,k.bank=W?128:0,n(k);break}}for(let u of Object.keys(o))o[u].size===0&&(m(`%cDetected change but no keys for %c${u}`,r.info,r.value),delete o[u]);return Z(),o}function ws(e,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(t,A)}),this.duration=this.midiData.duration,this.firstNoteTime=ge(this.midiData.firstNoteOn,this.midiData),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 Rs(e){this.songs=e.reduce((A,t)=>{if(t.duration)return A.push(t),A;try{A.push(new Ze(t.binary,t.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 Gs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function xs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}var vA=new Int16Array(127);vA[p.mainVolume]=100;vA[p.expressionController]=127;vA[p.pan]=64;vA[p.releaseTime]=64;vA[p.brightness]=64;vA[p.effects1Depth]=40;function Ms(e,A=void 0){if(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIMessages){this.sendMIDIMessage([w.reset]);for(let C=0;CC===p.dataDecrement||C===p.dataIncrement||C===p.dataEntryMsb||C===p.dataDecrement||C===p.lsbForControl6DataEntry||C===p.RPNLsb||C===p.RPNMsb||C===p.NRPNLsb||C===p.NRPNMsb||C===p.bankSelect||C===p.lsbForControl0BankSelect||C===p.resetAllControllers,g=[];for(let C=0;C=A)break}else if(this.playedTime>=e)break;let Q=De(h.messageStatusByte),f=Q.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(Q.status){case w.noteOn:case w.noteOff:case w.keySignature:break;case w.pitchBend:s[f]=h.messageData[1]<<7|h.messageData[0];break;case w.programChange:let c=n[f];c.program=h.messageData[0],c.actualBank=c.bank;break;case w.controllerChange:let l=h.messageData[0];if(o(l))if(this.sendMIDIMessages)this.sendMIDIMessage([w.controllerChange|f%16,l,h.messageData[1]]);else{let y=h.messageData[1];if(l===p.bankSelect){n[f].bank=y;break}this.synth.controllerChange(f,l,y)}else g[f]===void 0&&(g[f]=Array.from(vA)),g[f][l]=h.messageData[1];break;default:this._processEvent(h,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let u=this.tracks[C][this.eventIndex[C]];if(u===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(u.ticks-h.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7]),g[C].forEach((h,Q)=>{h!==vA[Q]&&!o(Q)&&this.sendMIDIMessage([w.controllerChange|C%16,Q,h])}),n[C].program>=0&&n[C].actualBank>=0){let h=n[C].actualBank;this.sendMIDIMessage([w.controllerChange|C%16,p.bankSelect,h]),this.sendMIDIMessage([w.programChange|C%16,n[C].program])}}else for(let C=0;C>7,s[C]&127),g[C]!==void 0&&g[C].forEach((h,Q)=>{h!==vA[Q]&&!o(Q)&&this.synth.controllerChange(C,Q,h)}),n[C].program>=0&&n[C].actualBank>=0){let h=n[C].actualBank;this.synth.controllerChange(C,p.bankSelect,h),this.synth.programChange(C,n[C].program)}return!0}function Ns(e=!1){if(this.midiData!==void 0){if(e){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 bs(e){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(kA.timeChange,currentTime-ge(e,this.midiData));let A=this._playTo(0,e);this._recalculateStartTime(this.playedTime),A&&this.play()}function Ls(e){this.absoluteStartTime=currentTime-e/this._playbackRate}function Us(e,A){switch(e){default:break;case NA.loadNewSongList:this.loadNewSongList(A);break;case NA.pause:this.pause();break;case NA.play:this.play(A);break;case NA.stop:this.stop();break;case NA.setTime:this.currentTime=A;break;case NA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case NA.setPlaybackRate:this.playbackRate=A;break;case NA.setLoop:this.loop=A;break;case NA.changeSong:A?this.nextSong():this.previousSong();break;case NA.getMIDI:this.post(kA.getMIDI,this.midiData);break;case NA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Ts(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:mA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function Hs(e){this.post(kA.midiEvent,e)}var CA=class{constructor(A){this.synth=A,this.ignoreEvents=!1,this.sendMIDIMessages=!1,this.loopCount=1/0,this.currentLoopCount=this.loopCount,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 t=this.currentTime;this._playbackRate=A,this.currentTime=t}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&&AYs?440*Math.pow(2,(e-6900)/1200):kt[~~e-Xe]}var Ft=-1660,wo=1600,wt=new Float32Array((wo-Ft)*100+1);for(let e=0;e.5?1:0,s?t*2-1:t;case lA.concave:return s?(t=t*2-1,t<0?1-Ce[~~(t*-aA)]-1:Ce[~~t*aA]):Ce[~~(t*aA)];case lA.convex:return s?(t=t*2-1,t<0?1-Ee[~~(t*-aA)]-1:Ee[~~(t*aA)]):Ee[~~(t*aA)]}}var Rt=1,Gt=new Float32Array(1e3);for(let e=0;e=e.sample.loopEnd;)t-=o;let C=~~t,h=C+1;for(;h>=e.sample.loopEnd;)h-=o;let Q=t-C,f=n[h],u=n[C];A[g]=u+(f-u)*Q,t+=e.sample.playbackStep*e.currentTuningCalculated}}else{e.sample.end>=n.length&&(e.sample.end=n.length-1);for(let o=0;o=e.sample.end){e.finished=!0;return}let h=t-g,Q=n[C],f=n[g];A[o]=f+(Q-f)*h,t+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=t}function qs(e,A){let t=e.sample.cursor,s=e.sample.loopingMode===1||e.sample.loopingMode===3&&!e.isInRelease,n=e.sample.loopEnd-e.sample.loopStart,o=e.sample.sampleData;if(s)for(let g=0;g=e.sample.loopEnd;)t-=n;let C=~~t+1;for(;C>=e.sample.loopEnd;)C-=n;A[g]=o[C],t+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=o.length&&(e.sample.end=o.length-1);for(let g=0;g=e.sample.end){e.finished=!0;return}A[g]=o[C],t+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=t}function Ks(e,A,t,s,n,o,g,C,h){if(!isNaN(t[0])){if(g>0){let Q=o[0],f=o[1];g=Math.min(g,1e3);let u=g/800,c=e*u,l=A*u;for(let y=0;y0){let Q=C[0],f=C[1];h=Math.min(h,1e3);let u=h/800,c=e*u,l=A*u;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],e.calculateCoefficients(A));for(let n=0;n.45*sampleRate&&(A.filter.cutoffHz=.45*sampleRate);let t=A.filter.reasonanceCb/10-3.01;A.filter.reasonanceGain=PA(-1*t);let s=1/Math.sqrt(A.filter.reasonanceGain),n=2*Math.PI*A.filter.cutoffHz/sampleRate,o=Math.cos(n),g=Math.sin(n)/(2*A.filter.reasonanceGain),C=(1-o)*s,h=C/2,Q=h,f=1+g,u=-2*o,c=1-g;A.filter.a0=h/f,A.filter.a1=C/f,A.filter.a2=Q/f,A.filter.a3=u/f,A.filter.a4=c/f}};var Ps=.001,we=100,vs=96,FA=class e{constructor(A){this.sampleRate=A}currentSampleTime=0;sampleRate;currentAttenuationDb=we;state=0;releaseStartDb=100;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=PA(A.volumeEnvelope.currentAttenuationDb),e.recalculate(A)}static intialize(A){e.recalculate(A,!0),A.volumeEnvelope.attenuation=A.volumeEnvelope.attenuationTarget}static recalculate(A,t=!1){let s=A.volumeEnvelope,n=f=>Math.floor(LA(f)*s.sampleRate);s.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[I.initialAttenuation],1440))/10,s.sustainDbRelative=Math.min(100,A.modulatedGenerators[I.sustainVolEnv]/10),t&&(s.attenuation=s.attenuationTarget);let o=Math.min(100,s.sustainDbRelative+s.attenuation);s.attackDuration=n(A.modulatedGenerators[I.attackVolEnv]);let g=A.modulatedGenerators[I.decayVolEnv],C=(60-A.targetKey)*A.modulatedGenerators[I.keyNumToVolEnvDecay],h=(o-s.attenuation)/100;s.decayDuration=n(g+C)*h,s.releaseDuration=n(A.modulatedGenerators[I.releaseVolEnv]),s.delayEnd=n(A.modulatedGenerators[I.delayVolEnv]),s.attackEnd=s.attackDuration+s.delayEnd;let Q=(60-A.targetKey)*A.modulatedGenerators[I.keyNumToVolEnvHold];if(s.holdEnd=n(A.modulatedGenerators[I.holdVolEnv]+Q)+s.attackEnd,s.decayEnd=s.decayDuration+s.holdEnd,s.state===0&&s.attackEnd===0&&(s.currentAttenuationDb=s.attenuationTarget,s.state=2),A.isInRelease){let f=Math.min(100,s.sustainDbRelative+s.attenuation);switch(s.state){case 0:s.releaseStartDb=we;break;case 1:let c=(1-(s.attackEnd-s.releaseStartTimeSamples)/s.attackDuration)*PA(s.attenuation);s.releaseStartDb=20*Math.log10(c)*-1;break;case 2:s.releaseStartDb=s.attenuation;break;case 3:s.releaseStartDb=(1-(s.decayEnd-s.releaseStartTimeSamples)/s.decayDuration)*(f-s.attenuation)+s.attenuation;break;case 4:s.releaseStartDb=f;break;default:s.releaseStartDb=s.currentAttenuationDb}s.releaseStartDb=Math.min(s.releaseStartDb,we),s.releaseStartDb>=vs&&(A.finished=!0)}}static apply(A,t,s,n){let o=A.volumeEnvelope,g=s/10,C=n;if(A.isInRelease){let Q=n*10,f=o.currentSampleTime-o.releaseStartTimeSamples;if(f>=o.releaseDuration){for(let l=0;l=vs&&(A.finished=!0);return}let h=0;switch(o.state){case 0:for(;o.currentSampleTime=t.length)return;o.state++;case 1:for(;o.currentSampleTime=t.length)return}o.state++;case 2:for(;o.currentSampleTime=t.length)return;o.state++;case 3:for(;o.currentSampleTime=t.length)return}o.state++;case 4:for(;;){o.attenuation+=(o.attenuationTarget-o.attenuation)*C;let Q=Math.min(100,o.sustainDbRelative+o.attenuation);if(t[h]*=PA(Q+g),o.currentAttenuationDb=Q,o.currentSampleTime++,++h>=t.length)return}}}};var Vs=Math.PI/2,Os=.01;function Zs(e,A,t,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,FA.startRelease(A),UA.startRelease(A)),A.modulatedGenerators[I.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let g=A.targetKey,C=A.modulatedGenerators[I.fineTune]+e.customControllers[iA.channelTuning]+e.customControllers[iA.channelTransposeFine]+e.customControllers[iA.masterTuning]+e.channelOctaveTuning[A.midiNote%12]+e.keyCentTuning[A.midiNote],h=A.modulatedGenerators[I.coarseTune]+e.customControllers[iA.channelTuningSemitones],Q=this.tunings[e.preset.program]?.[g];Q?.midiNote>=0&&(g=Q.midiNote,C+=Q.centTuning),C+=(g-A.sample.rootKey)*A.modulatedGenerators[I.scaleTuning];let f=A.modulatedGenerators[I.vibLfoToPitch];if(f!==0){let $=A.startTime+LA(A.modulatedGenerators[I.delayVibLFO]),QA=ke(A.modulatedGenerators[I.freqVibLFO]),IA=We($,QA,currentTime);C+=IA*(f*e.customControllers[iA.modulationMultiplier])}let u=A.modulatedGenerators[I.initialFilterFc],c=A.modulatedGenerators[I.modLfoToPitch],l=A.modulatedGenerators[I.modLfoToVolume],y=A.modulatedGenerators[I.modLfoToFilterFc],S=0;if(c+y+l!==0){let $=A.startTime+LA(A.modulatedGenerators[I.delayModLFO]),QA=ke(A.modulatedGenerators[I.freqModLFO]),IA=We($,QA,currentTime);C+=IA*(c*e.customControllers[iA.modulationMultiplier]),S=-IA*l,u+=IA*y}if(e.channelVibrato.depth>0){let $=We(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);$&&(C+=$*e.channelVibrato.depth)}let k=A.modulatedGenerators[I.modEnvToPitch],x=A.modulatedGenerators[I.modEnvToFilterFc],N=UA.getValue(A,currentTime);u+=N*x,C+=N*k;let M=~~(C+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(t.length);this.interpolationType===_e.linear?Js(A,J):qs(A,J),Be.apply(A,J,u),FA.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];Ks(a,sA,J,t,s,n,K,o,z)}function Fo(e,A){let t=0;return e.drumChannel&&(t+=5),A.isInRelease&&(t-=5),t+=A.velocity/25,t-=A.volumeEnvelope.state,A.isInRelease&&(t-=5),t-=A.volumeEnvelope.currentAttenuationDb/50,t}function Xs(e){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 t=A.slice(0,e);for(let{channel:s,voice:n}of t){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function Ws(e){e.releaseStartTime=currentTime,e.releaseStartTime-e.startTimezs=e);var Ro=function(e){var A,t,s,n,o,g,C,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Q="",f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=h.indexOf(e.charAt(f++)),o=h.indexOf(e.charAt(f++)),g=h.indexOf(e.charAt(f++)),C=h.indexOf(e.charAt(f++)),A=n<<2|o>>4,t=(15&o)<<4|g>>2,s=(3&g)<<6|C,Q+=String.fromCharCode(A),g!==64&&(Q+=String.fromCharCode(t)),C!==64&&(Q+=String.fromCharCode(s));while(f1&&(a.thisProgram=process.argv[1].replace(/\\/g,"/")),a.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(i){if(!(i instanceof me))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)):(WA(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,d){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}d()},F.onerror=d,F.send(null)},a.setWindowTitle=function(i){document.title=i});var Yt=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)||Yt);for(e in sA)sA.hasOwnProperty(e)&&(a[e]=sA[e]);function xe(i){var E=l;return l=l+i+15&-16,E}function Jt(i){var E=h[M>>2],B=E+i+15&-16;return h[M>>2]=B,B>=EA&&!_t()?(h[M>>2]=E,0):E}function qt(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 WA(E%8==0),E/8}}function ue(i){ue.shown||(ue.shown={}),ue.shown[i]||(ue.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,d=B;d>>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 Me=0,Kt=0;function WA(i,E){i||OA("Assertion failed: "+E)}function vt(i){var E=a["_"+i];return WA(E,"Cannot call unknown function "+i+", make sure it is exported"),E}var Pt={stackSave:function(){Bt()},stackRestore:function(){Et()},arrayToC:function(i){var E,B,d=He(i.length);return E=i,B=d,n.set(E,B),d},stringToC:function(i){var E=0;if(i!=null&&i!==0){var B=(i.length<<2)+1;E=He(B),Zt(i,E,B)}return E}},Bo={string:Pt.stringToC,array:Pt.arrayToC};function Vt(i,E,B,d,F){var v=vt(i),X=[],G=0;if(d)for(var BA=0;BA>0]=E;break;case"i16":g[i>>1]=E;break;case"i32":h[i>>2]=E;break;case"i64":tempI64=[E>>>0,+fo(tempDouble=E)>=1?tempDouble>0?(0|po(+es(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":f[i>>2]=E;break;case"double":u[i>>3]=E;break;default:OA("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 g[i>>1];case"i32":case"i64":return h[i>>2];case"float":return f[i>>2];case"double":return u[i>>3];default:OA("invalid type for getValue: "+E)}return null}function Jo(i,E,B,d){typeof i=="number"?(v=!0,X=i):(v=!1,X=i.length);var F=typeof E=="string"?E:null;if(G=B==4?d:[typeof Te=="function"?Te:xe,He,xe,Jt][B===void 0?2:B](Math.max(X,F?1:E.length)),v){for(d=G,WA((3&G)==0),BA=G+(-4&X);d>2]=0;for(BA=G+X;d>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],(d!=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&&Ot)return Ot.decode(nA.subarray(oA,eA));for(var q,dA,RA,GA,xA,$A,MA="";;){if(!(q=nA[oA++]))return MA;if(!(128&q)){MA+=String.fromCharCode(q);continue}if(dA=63&nA[oA++],(224&q)==192){MA+=String.fromCharCode((31&q)<<6|dA);continue}if(RA=63&nA[oA++],(240&q)==224?q=(15&q)<<12|dA<<6|RA:(GA=63&nA[oA++],(248&q)==240?q=(7&q)<<18|dA<<12|RA<<6|GA:(xA=63&nA[oA++],q=(252&q)==248?(3&q)<<24|dA<<18|RA<<12|GA<<6|xA:(1&q)<<30|dA<<24|RA<<18|GA<<12|xA<<6|($A=63&nA[oA++]))),q<65536)MA+=String.fromCharCode(q);else{var pe=q-65536;MA+=String.fromCharCode(55296|pe>>10,56320|1023&pe)}}}(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(d,F,v){for(var X=0;X>0]=d.charCodeAt(X);v||(n[F>>0]=0)}(i,E,!1)}var Ot=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function be(i,E,B,d){if(!(d>0))return 0;for(var F=B,v=B+d-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 Zt(i,E,B){return be(i,o,E,B)}function Le(i){for(var E=0,B=0;B=55296&&d<=57343&&(d=65536+((1023&d)<<10)|1023&i.charCodeAt(++B)),d<=127?++E:d<=2047?E+=2:d<=65535?E+=3:d<=2097151?E+=4:d<=67108863?E+=5:E+=6}return E}var Xt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function Po(i){for(var E=i,B=E>>1;g[B];)++B;if((E=B<<1)-i>32&&Xt)return Xt.decode(o.subarray(i,E));for(var d=0,F="";;){var v=g[i+2*d>>1];if(v==0)return F;++d,F+=String.fromCharCode(v)}}function Vo(i,E,B){if(B===void 0&&(B=2147483647),B<2)return 0;for(var d=E,F=(B-=2)<2*i.length?B/2:i.length,v=0;v>1]=X,E+=2}return g[E>>1]=0,E-d}function Oo(i){return 2*i.length}function Zo(i){for(var E=0,B="";;){var d=h[i+4*E>>2];if(d==0)return B;if(++E,d>=65536){var F=d-65536;B+=String.fromCharCode(55296|F>>10,56320|1023&F)}else B+=String.fromCharCode(d)}}function Xo(i,E,B){if(B===void 0&&(B=2147483647),B<4)return 0;for(var d=E,F=d+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-d}function Wo(i){for(var E=0,B=0;B=55296&&d<=57343&&++B,E+=4}return E}function _o(i){var E=Le(i)+1,B=Te(E);return B&&be(i,n,B,E),B}function zo(i){var E=Le(i)+1,B=He(E);return be(i,n,B,E),B}function jo(i){return i}function $o(){var i,E=function(){var d=Error();if(!d.stack){try{throw Error(0)}catch(F){d=F}if(!d.stack)return"(no stack trace available)"}return d.stack.toString()}();return a.extraStackTrace&&(E+=` -`+a.extraStackTrace()),(i=E).replace(/__Z[\w\d_]+/g,function(B){var d,F=d=B;return B===F?B:B+" ["+F+"]"})}function rt(i,E){return i%E>0&&(i+=E-i%E),i}function Wt(i){a.buffer=s=i}function it(){a.HEAP8=n=new Int8Array(s),a.HEAP16=g=new Int16Array(s),a.HEAP32=h=new Int32Array(s),a.HEAPU8=o=new Uint8Array(s),a.HEAPU16=C=new Uint16Array(s),a.HEAPU32=Q=new Uint32Array(s),a.HEAPF32=f=new Float32Array(s),a.HEAPF64=u=new Float64Array(s)}function _t(){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 d=a.reallocBuffer(EA);return d&&d.byteLength==EA?(Wt(d),it(),!0):(EA=B,!1)}c=l=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 fe(i){for(;i.length>0;){var E=i.shift();if(typeof E=="function"){E();continue}var B=E.func;typeof B=="number"?E.arg===void 0?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<=d&&(E<=32||i>d)&&(i=-2*d+i),i}var fo=Math.abs,mo=Math.ceil,es=Math.floor,po=Math.min,jA=0,Ct=null,de=null;function rr(i){return i}a.preloadedImages={},a.preloadedAudios={};var ts="data:application/octet-stream;base64,";function Ue(i){return String.prototype.startsWith?i.startsWith(ts):i.indexOf(ts)===0}(function(){var E="main.wast",B="main.wasm",d="main.temp.asm.js";Ue(E)||(E=TA(E)),Ue(B)||(B=TA(B)),Ue(d)||(d=TA(d));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){OA(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 dA=a.wasmMemory.grow((eA-q)/65536);return dA!==-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,dA){var RA;if(!(q=RA=q).table){var GA,xA=a.wasmTableSize;xA===void 0&&(xA=1024);var $A=a.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?$A!==void 0?q.table=new WebAssembly.Table({initial:xA,maximum:$A,element:"anyfunc"}):q.table=new WebAssembly.Table({initial:xA,element:"anyfunc"}):q.table=Array(xA),a.wasmTable=q.table}return q.memoryBase||(q.memoryBase=a.STATIC_BASE),q.tableBase||(q.tableBase=0),GA=function(pe,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 Ye(YA,JA){if((v=YA.exports).memory){var Se,ct,os;Se=v.memory,ct=a.buffer,Se.byteLength0?B:Le(i)+1,F=Array(d),v=be(i,F,0,F.length);return E&&(F.length=v),F}function gr(i){for(var E=[],B=0;B255&&(d&=255),E.push(String.fromCharCode(d))}return E.join("")}l+=16,M=xe(4),x=(S=k=qt(l))+at,N=qt(x),h[M>>2]=N,y=!0,a.wasmTableSize=4,a.wasmMaxTableSize=4,a.asmGlobalArg={},a.asmLibraryArg={abort:OA,assert:WA,enlargeMemory:_t,getTotalMemory:Qo,abortOnCannotGrowMemory:function(){OA("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,d){var F=Bt();try{return a.dynCall_iii(E,B,d)}catch(v){if(Et(F),typeof v!="number"&&v!=="longjmp")throw v;a.setThrew(1,0)}},___assert_fail:function(E,B,d,F){OA("Assertion failed: "+Ne(E)+", at: "+[B?Ne(B):"unknown filename",d,F?Ne(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,d){return o.set(o.subarray(B,B+d),E),E},_llvm_floor_f64:es,DYNAMICTOP_PTR:M,tempDoublePtr:DA,ABORT:Me,STACKTOP:k,STACK_MAX:x};var ss=a.asm(a.asmGlobalArg,a.asmLibraryArg,s);a.asm=ss,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 Te=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 He=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 me(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());fe(zt)}(),!(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,Me||(gt||(gt=!0,fe(It)),fe(jt),a.onRuntimeInitialized&&a.onRuntimeInitialized(),function(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)uo(a.postRun.shift());fe(As)}()))}}function Cr(i,E){(!E||!a.noExitRuntime||i!==0)&&(a.noExitRuntime||(Me=!0,Kt=i,k=J,fe($t),co=!0,a.onExit&&a.onExit(i)),a.quit(i,new me(i)))}function OA(i){throw a.onAbort&&a.onAbort(i),i!==void 0?(Yt(i),HA(i),i=JSON.stringify(i)):i="",Me=!0,Kt=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=ss,a.ccall=Vt,a.cwrap=function(E,B,d,F){var v=(d=d||[]).every(function(X){return X==="number"});return B!=="string"&&v&&!F?vt(E):function(){return Vt(E,B,d,arguments,F)}},me.prototype=Error(),me.prototype.constructor=me,de=function i(){a.calledRun||ht(),a.calledRun||(de=i)},a.run=ht,a.abort=OA,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()},VA.decode=function(i){return function(B){if(!_s)throw Error("Not initialized");var d={};function F(se){return new Int32Array(a.HEAPU8.buffer,se,1)[0]}function v(se,Qt){var Ye=new ArrayBuffer(Qt*Float32Array.BYTES_PER_ELEMENT),ne=new Float32Array(Ye);return ne.set(new Float32Array(a.HEAPU8.buffer,se,Qt)),ne}d.open=a.cwrap("stb_vorbis_js_open","number",[]),d.close=a.cwrap("stb_vorbis_js_close","void",["number"]),d.channels=a.cwrap("stb_vorbis_js_channels","number",["number"]),d.sampleRate=a.cwrap("stb_vorbis_js_sample_rate","number",["number"]),d.decode=a.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var X,G,BA,nA,oA=d.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),dA=a._malloc(4),RA=d.decode(oA,eA.byteOffset,eA.byteLength,q,dA);if(a._free(eA.byteOffset),RA<0)throw d.close(oA),a._free(q),Error("stbvorbis decode failed: "+RA);for(var GA=d.channels(oA),xA=Array(GA),$A=new Int32Array(a.HEAPU32.buffer,F(q),GA),MA=0;MA=0&&(s=this.workletProcessorChannels[t]),e.messageType){case AA.noteOn:this.noteOn(t,A[0],A[1],A[2]);break;case AA.noteOff:this.noteOff(t,A);break;case AA.pitchWheel:this.pitchWheel(t,A[0],A[1]);break;case AA.ccChange:this.controllerChange(t,A[0],A[1],A[2]);break;case AA.customcCcChange:s.customControllers[A[0]]=A[1];break;case AA.killNote:this.killNote(t,A);break;case AA.programChange:this.programChange(t,A[0],A[1]);break;case AA.channelPressure:this.channelPressure(t,A);break;case AA.polyPressure:this.polyPressure(t,A[0],A[1]);break;case AA.ccReset:t===bA?this.resetAllControllers():this.resetControllers(t);break;case AA.systemExclusive:this.systemExclusive(A);break;case AA.setChannelVibrato:if(t===bA)for(let g=0;g{let t=(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:t,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:mA.channelProperties,messageData:e})}function Go(e,A,t){let s=e,n=A<<7|t;return e===127&&A===127&&t===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function en(e,A=0){let t=e[0];if(!(this.deviceID!==bA&&e[1]!==127&&this.deviceID!==e[1]))switch(t){default:b(`%cUnrecognized SysEx: %c${hA(e)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(e[2]){case 4:let s;switch(e[3]){case 1:let n=e[5]<<7|e[4];this.setMIDIVolume(n/16384),m(`%cMaster Volume. Volume: %c${n}`,r.info,r.value);break;case 2:let g=((e[5]<<7|e[4])-8192)/8192;this.setMasterPan(g),m(`%cMaster Pan. Pan: %c${g}`,r.info,r.value);break;case 3:let C=(e[5]<<7|e[6])-8192;s=Math.floor(C/81.92),this.setMasterTuning(s),m(`%cMaster Fine Tuning. Cents: %c${s}`,r.info,r.value);break;case 4:s=(e[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(e)}`,r.warn,r.unrecognized)}break;case 9:e[3]===1?(m("%cGM system on",r.info),this.system="gm"):e[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(e[3]){case 2:case 7:let n=4;e[3]===7&&n++;let o=e[n++],g=e[n++];for(let h=0;h>1&1)===1&&this.setOctaveTuning(15+A,C);for(let h=0;h<7;h++)(e[5]>>h&1)===1&&this.setOctaveTuning(7+h+A,C);for(let h=0;h<7;h++)(e[6]>>h&1)===1&&this.setOctaveTuning(h+A,C);m(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${C.join(" ")}`,r.info,r.value);break;default:b(`%cUnrecognized MIDI Tuning standard message: %c${hA(e)}`,r.warn,r.unrecognized);break}break;default:b(`%cUnrecognized MIDI Realtime/non realtime message: %c${hA(e)}`,r.warn,r.unrecognized)}break;case 65:if(e[2]===66&&e[3]===18){let s=e[7];if(e[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(e[4]===64){if((e[5]&16)>0){let n=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A;switch(e[6]){default:break;case 21:let o=s>0&&e[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(e)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let g=s-64;this.transposeChannel(n,g),m(`%cChannel %c${n}%c pitch shift. Semitones %c${g}%c, with %c${hA(e)}`,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 C=s-64;m(`%cChannel %c${n}%c tuning. Cents %c${C}%c, with %c${hA(e)}`,r.info,r.recognized,r.info,r.value,r.info,r.value),this.setChannelTuning(n,C)}}else if(e[5]===0&&e[6]===6){m(`%cRoland GS Master Pan set to: %c${s}%c with: %c${hA(e)}`,r.info,r.value,r.info,r.value),this.setMasterPan((s-64)/64);return}else if(e[5]===0&&e[6]===5){let n=s-64;m(`%cRoland GS Master Key-Shift set to: %c${n}%c with: %c${hA(e)}`,r.info,r.value,r.info,r.value),this.setMasterTuning(n*100);return}else if(e[5]===0&&e[6]===4){m(`%cRoland GS Master Volume set to: %c${s}%c with: %c${hA(e)}`,r.info,r.value,r.info,r.value),this.setMIDIVolume(s/127);return}}b(`%cUnrecognized Roland %cGS %cSysEx: %c${hA(e)}`,r.warn,r.recognized,r.warn,r.unrecognized);return}else if(e[2]===22&&e[3]===18&&e[4]===16){this.setMIDIVolume(e[7]/100),m(`%cRoland Master Volume control set to: %c${e[7]}%c via: %c${hA(e)}`,r.info,r.value,r.info,r.value);return}else{b(`%cUnrecognized Roland SysEx: %c${hA(e)}`,r.warn,r.unrecognized);return}case 67:if(e[2]===76)if(e[3]===0&&e[4]===0)switch(e[5]){case 4:let s=e[6];this.setMIDIVolume(s/127),m(`%cXG master volume. Volume: %c${s}`,r.info,r.recognized);break;case 6:let n=e[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(e[3]===8){if(this.system!=="xg")return;let s=e[4]+A;if(s>=this.workletProcessorChannels.length)return;let n=e[6];switch(e[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 g=n-64;o.channelTransposeKeyShift=g;break;case 11:this.controllerChange(s,p.mainVolume,n);break;case 14:let C=n;C===0&&(C=Math.floor(Math.random()*127)),this.controllerChange(s,p.pan,C);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${e[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&b(`%cUnrecognized Yamaha XG SysEx: %c${hA(e)}`,r.warn,r.unrecognized);else this.system==="xg"&&b(`%cUnrecognized Yamaha SysEx: %c${hA(e)}`,r.warn,r.unrecognized);break}}function tn(e,A,t){if(A.transformAmount===0)return 0;let s;if(A.sourceUsesCC)s=e[A.sourceIndex];else{let h=A.sourceIndex+gA;switch(A.sourceIndex){case P.noController:s=16383;break;case P.noteOnKeyNum:s=t.midiNote<<7;break;case P.noteOnVelocity:s=t.velocity<<7;break;case P.polyPressure:s=t.pressure<<7;break;default:s=e[h];break}}let n=fA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let h=A.secSrcIndex+gA;switch(A.secSrcIndex){case P.noController:o=16383;break;case P.noteOnKeyNum:o=t.midiNote<<7;break;case P.noteOnVelocity:o=t.velocity<<7;break;case P.polyPressure:o=t.pressure<<7;break;default:o=e[h]}}let g=fA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=n*g*A.transformAmount;return A.transformType===2?Math.abs(C):C}function ZA(e,A,t=-1,s=0){let{modulators:n,generators:o,modulatedGenerators:g}=e;if(UA.recalculate(e),t===-1){g.set(o),n.forEach(Q=>{g[Q.modulatorDestination]+=tn(A,Q,e)}),FA.recalculate(e);return}let C=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===t&&Q.sourceIndex===s||Q.secSrcUsesCC===t&&Q.secSrcIndex===s){let f=Q.modulatorDestination;h.has(f)||(g[f]=o[f],n.forEach(u=>{u.modulatorDestination===f&&(g[f]+=tn(A,u,e))}),h.add(f))}}),[...h].some(Q=>C.has(Q))&&FA.recalculate(e)}var fA=[];for(let e=0;e<4;e++){fA[e]=[[new Float32Array(aA),new Float32Array(aA)],[new Float32Array(aA),new Float32Array(aA)]];for(let A=0;A200&&t<40||this.highPerformanceMode&&t<10||g.isMuted)return;let C=A+g.channelTransposeKeyShift;if(A>127||A<0)return;let h=g.preset.program;this.tunings[h]?.[A]?.midiNote>=0&&(C=this.tunings[h]?.[A].midiNote);let Q=this.getWorkletVoices(e,C,t,g,o,s),f=g.voices;Q.forEach(u=>{let c=u.generators[I.exclusiveClass];c!==0&&f.forEach(l=>{l.generators[I.exclusiveClass]===c&&(this.releaseVoice(l),l.modulatedGenerators[I.releaseVolEnv]=-7e3,l.modulatedGenerators[I.releaseModEnv]=-7e3,FA.recalculate(l),UA.recalculate(l))}),ZA(u,g.midiControllers),FA.intialize(u),u.currentPan=(Math.max(-500,Math.min(500,u.modulatedGenerators[I.pan]))+500)/1e3}),this.totalVoicesAmount+=Q.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(Q.length),f.push(...Q),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:e,velocity:t}))}function nn(e,A){if(A>127||A<0){b("Received a noteOn for note",A,"Ignoring.");return}let t=A+this.workletProcessorChannels[e].channelTransposeKeyShift,s=this.workletProcessorChannels[e].preset.program;if(this.tunings[s]?.[A]?.midiNote>=0&&(t=this.tunings[s]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[e].drumChannel){this.killNote(e,t);return}this.workletProcessorChannels[e].voices.forEach(o=>{o.midiNote!==t||o.isInRelease===!0||(this.workletProcessorChannels[e].holdPedal?this.workletProcessorChannels[e].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:e})}function on(e,A){this.workletProcessorChannels[e].voices.forEach(t=>{t.midiNote===A&&(t.modulatedGenerators[I.releaseVolEnv]=-12e3,this.releaseVoice(t))})}function rn(e,A=!1){let t=this.workletProcessorChannels[e].voices;A?(t.length=0,this.workletProcessorChannels[e].sustainedVoices.length=0,this.sendChannelProperties()):(t.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[e].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function an(e=!1){m("%cStop all received!",r.info);for(let A=0;AZA(n,this.workletProcessorChannels[e].midiControllers,0,P.pitchWheel)),this.sendChannelProperties()}function cn(e,A){let t=this.workletProcessorChannels[e];t.midiControllers[gA+P.channelPressure]=A<<7,this.workletProcessorChannels[e].voices.forEach(s=>ZA(s,t.midiControllers,0,P.channelPressure)),this.callEvent("channelpressure",{channel:e,pressure:A})}function ln(e,A,t){this.workletProcessorChannels[e].voices.forEach(s=>{s.midiNote===A&&(s.pressure=t,ZA(s,this.workletProcessorChannels[e].midiControllers,0,P.polyPressure))}),this.callEvent("polypressure",{channel:e,midiNote:A,pressure:t})}function un(e,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[e].channelOctaveTuning=A}function fn(e,A,t,s=!1){let n=this.workletProcessorChannels[e];if(n===void 0){b(`Trying to access channel ${e} 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|t&127,n.voices.forEach(g=>ZA(g,n.midiControllers,1,o))}switch(A){case p.allNotesOff:this.stopAll(e);break;case p.allSoundOff:this.stopAll(e,!0);break;case p.bankSelect:let o=t;if(!s){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${t}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(e,!0):e%16!==SA&&this.setDrums(e,!1);break;case"gm2":o===120&&(n.drumChannel=!0,this.callEvent("drumchange",{channel:e,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||t!==127&&(n.midiControllers[p.bankSelect]=t):this.system==="gm2"&&(n.midiControllers[p.bankSelect]=t);break;case p.RPNLsb:n.RPValue=n.RPValue<<7|t,n.dataEntryState=uA.RPFine;break;case p.RPNMsb:n.RPValue=t,n.dataEntryState=uA.RPCoarse;break;case p.NRPNMsb:n.NRPCoarse=t,n.dataEntryState=uA.NRPCoarse;break;case p.NRPNLsb:n.NRPFine=t,n.dataEntryState=uA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(e,t);break;case p.lsbForControl6DataEntry:this.dataEntryFine(e,t);break;case p.resetAllControllers:this.resetControllers(e);break;case p.sustainPedal:t>=64?n.holdPedal=!0:(n.holdPedal=!1,n.sustainedVoices.forEach(g=>{this.releaseVoice(g)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=t<<7,n.voices.forEach(g=>ZA(g,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:e,controllerNumber:A,controllerValue:t});break}}function dn(e){this.midiVolume=e,this.setMasterPan(this.pan)}function mn(e){this.masterGain=e*Mt,this.setMasterPan(this.pan)}function pn(e){this.pan=e,e=e/2+.5,this.panLeft=(1-e)*this.currentGain,this.panRight=e*this.currentGain}function Sn(e,A){A&&this.stopAll(e,!0),this.workletProcessorChannels[e].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:e,isMuted:A})}function yn(e){this.workletProcessorChannels[e].lockVibrato=!0,this.workletProcessorChannels[e].channelVibrato.rate=0,this.workletProcessorChannels[e].channelVibrato.delay=0,this.workletProcessorChannels[e].channelVibrato.depth=0}function Dn(e,A,t,s){this.workletProcessorChannels[e].lockVibrato||(this.workletProcessorChannels[e].channelVibrato.rate=t,this.workletProcessorChannels[e].channelVibrato.delay=s,this.workletProcessorChannels[e].channelVibrato.depth=A)}function kn(e,A){let t=this.workletProcessorChannels[e],s=()=>{t.channelVibrato.delay===0&&t.channelVibrato.rate===0&&t.channelVibrato.depth===0&&(t.channelVibrato.depth=50,t.channelVibrato.rate=8,t.channelVibrato.delay=.6)};switch(t.dataEntryState){default:case uA.Idle:break;case uA.NRPFine:if(this.system!=="gs")return;switch(t.NRPCoarse){default:if(A===64)return;b(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16).toUpperCase()} 0x${t.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(t.NRPFine){default:if(A===64)return;b(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16)} 0x${t.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.rate=A/64*8,m(`%cVibrato rate for %c${e}%c is now set to %c${A} = ${t.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.depth=A/2,m(`%cVibrato depth for %c${e}%c is now set to %c${A} = ${t.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.delay=A/64/3,m(`%cVibrato delay for %c${e}%c is now set to %c${A} = ${t.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let g=A;this.controllerChange(e,p.brightness,A),m(`%cFilter cutoff for %c${e}%c is now set to %c${g}`,r.info,r.recognized,r.info,r.value)}break;case 24:if(!t.drumChannel)return;let n=A-64;t.keyCentTuning[t.NRPFine]=n*100,m(`%cGS drum key tuning. MIDI note: %c${t.NRPFine}%c semitones: %c${n}`,r.info,r.recognized,r.info,r.value);break;case 29:if(!t.drumChannel)return;let o=A;this.controllerChange(e,p.effects1Depth,o),m(`%cGS Drum reverb for %c${e}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case uA.RPCoarse:case uA.RPFine:switch(t.RPValue){default:b(`%cUnrecognized RPN for %c${e}%c: %c(0x${t.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:t.midiControllers[gA+P.pitchWheelRange]=A<<7,m(`%cChannel ${e} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(e,A-64);break;case 1:this.setChannelTuning(e,A-64,!1);break;case 5:this.setModulationDepth(e,A*100);break;case 16383:this.resetParameters(e);break}}}function wn(e,A){let t=this.workletProcessorChannels[e];switch(t.dataEntryState){default:break;case uA.RPCoarse:case uA.RPFine:switch(t.RPValue){default:break;case 0:if(A===0)break;t.midiControllers[gA+P.pitchWheelRange]|=A;let s=(t.midiControllers[gA+P.pitchWheelRange]>>7)+A/127;m(`%cChannel ${e} bend range. Semitones: %c${s}`,r.info,r.value);break;case 1:let o=t.customControllers[iA.channelTuning]<<7|A;this.setChannelTuning(e,o*.01220703125);break;case 5:let C=t.customControllers[iA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(e,C);break;case 16383:this.resetParameters(e);break}}}function Fn(){m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let e=0;e{this.workletProcessorChannels[e].lockedControllers[s]&&this.callEvent("controllerchange",{channel:e,controllerNumber:s,controllerValue:this.workletProcessorChannels[e].midiControllers[s]>>7})};if(t(p.mainVolume),t(p.pan),t(p.expressionController),t(p.modulationWheel),t(p.effects3Depth),t(p.effects1Depth),this.workletProcessorChannels[e].lockedControllers[gA+P.pitchWheel]){let s=this.workletProcessorChannels[e].midiControllers[gA+P.pitchWheel],n=s>>7,o=s&127;this.callEvent("pitchwheel",{channel:e,MSB:n,LSB:o})}}this.tunings=[],this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Ke}function Rn(e){let A=this.workletProcessorChannels[e],s=A.lockedControllers.reduce((o,g,C)=>(g&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(KA),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(e)}function Gn(e){let A=this.workletProcessorChannels[e];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=uA.Idle}function xn(){let e=4;for(let s of this.instruments)e+=s.instrumentZones.reduce((n,o)=>(o.generators=o.generators.filter(g=>g.generatorType!==I.sampleID&&g.generatorType!==I.keyRange&&g.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(e),t=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=t;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue),t++}return cA(A,0),tA(new j("igen",A.length,A))}function Mn(e,A,t,s,n){let o=this.samples.map((Q,f)=>{t&&Q.compressSample(s,n);let u=Q.getRawData();return m(`%cEncoded sample %c${f}. ${Q.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),u}),g=this.samples.reduce((Q,f,u)=>Q+o[u].length+46,0),C=new H(g);this.samples.forEach((Q,f)=>{let u=o[f],c,l,y=u.length;Q.isCompressed?(c=C.currentIndex,l=c+u.length):(c=C.currentIndex/2,l=c+u.length/2,y+=46),e.push(c),C.set(u,C.currentIndex),C.currentIndex+=y,A.push(l)});let h=tA(new j("smpl",C.length,C),new H([115,100,116,97]));return tA(new j("LIST",h.length,h))}function Nn(e,A){let s=new H(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{wA(s,n.sampleName,20);let g=e[o];cA(s,g);let C=A[o];cA(s,C);let h=n.sampleLoopStartIndex/2+g,Q=n.sampleLoopEndIndex/2+g;n.isCompressed&&(h-=g,Q-=g),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 e=10;for(let s of this.instruments)e+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(e),t=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=t;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),t++}return ae(A,0,10),tA(new j("imod",A.length,A))}function Ln(){let e=this.instruments.reduce((o,g)=>g.instrumentZones.length*4+o,4),A=new H(e),t=0,s=0,n=0;for(let o of this.instruments){o.instrumentZoneIndex=t;for(let g of o.instrumentZones)g.zoneID=t,Y(A,s),Y(A,n),s+=g.generators.length,n+=g.modulators.length,t++}return Y(A,s),Y(A,n),tA(new j("ibag",A.length,A))}function Un(){let e=this.instruments.length*22+22,A=new H(e),t=0,s=0;for(let n of this.instruments)wA(A,n.instrumentName,20),Y(A,t),t+=n.instrumentZones.length,n.instrumentID=s,s++;return wA(A,"EOI",20),Y(A,t),tA(new j("inst",A.length,A))}function Tn(){let e=4;for(let s of this.presets)e+=s.presetZones.reduce((n,o)=>(o.generators=o.generators.filter(g=>g.generatorType!==I.instrument&&g.generatorType!==I.keyRange&&g.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(e),t=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=t;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue);t+=n.generators.length}return Y(A,0),Y(A,0),tA(new j("pgen",A.length,A))}function Hn(){let e=10;for(let s of this.presets)e+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(e),t=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=t;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),t++}return ae(A,0,10),tA(new j("pmod",A.length,A))}function Yn(){let e=this.presets.reduce((o,g)=>g.presetZones.length*4+o,4),A=new H(e),t=0,s=0,n=0;for(let o of this.presets){o.presetZoneStartIndex=t;for(let g of o.presetZones)g.zoneID=t,Y(A,s),Y(A,n),s+=g.generators.length,n+=g.modulators.length,t++}return Y(A,s),Y(A,n),tA(new j("pbag",A.length,A))}function Jn(){let e=this.presets.length*38+38,A=new H(e),t=0;for(let s of this.presets)wA(A,s.presetName,20),Y(A,s.program),Y(A,s.bank),Y(A,t),cA(A,s.library),cA(A,s.genre),cA(A,s.morphology),t+=s.presetZones.length;return wA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,t),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(e=xo){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");pA("%cSaving soundfont...",r.info),m(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),m("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.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 t=ye([new H([73,78,70,79]),...A]),s=tA(new j("LIST",t.length,t));m("%cWriting SDTA...",r.info);let n=[],o=[],g=Mn.call(this,n,o,e?.compress,e?.compressionQuality||.5,e.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let C=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 f=Ln.call(this);m("%cWriting INST...",r.info);let u=Un.call(this),c=Tn.call(this);m("%cWriting PMOD...",r.info);let l=Hn.call(this);m("%cWriting PBAG...",r.info);let y=Yn.call(this);m("%cWriting PHDR...",r.info);let S=Jn.call(this),k=ye([new H([112,100,116,97]),S,y,l,c,u,f,Q,h,C]),x=tA(new j("LIST",k.length,k));m("%cWriting the output file...",r.info);let N=ye([new H([115,102,98,107]),s,g,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 e{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(t=>{t.isGlobal||t.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}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,t,s=!1){let n=this.presets.find(o=>o.bank===A&&o.program===t);if(n)return n;if(s!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===t)}setSampleIDOffset(A){this.presets.forEach(t=>t.sampleIDOffset=A)}getPreset(A,t){let s=this.presets.find(n=>n.bank===A&&n.program===t);return s||(s=this.presets.find(n=>n.program===t&&n.bank!==128),A===128&&(s=this.presets.find(n=>n.bank===128&&n.program===t),s||(s=this.presets.find(n=>n.bank===128))),s&&b(`%cPreset ${A}.${t} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,r.warn,r.recognized)),s||(b(`Preset ${t} not found. Defaulting to`,this.presets[0].presetName),s=this.presets[0]),s}getPresetByName(A){let t=this.presets.find(s=>s.presetName===A);return t||(b("Preset not found. Defaulting to:",this.presets[0].presetName),t=this.presets[0]),t}static mergeSoundfonts(...A){let t=A.shift(),s=t.presets;for(;A.length;)A.shift().presets.forEach(o=>{s.find(g=>g.bank===o.bank&&g.program===o.program)===void 0&&s.push(o)});return new e({presets:s,info:t.soundFontInfo})}};te.prototype.write=qn;function Kn(e){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,t){for(let s=A;s{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,t){this.getSamplesAndGenerators(A,t).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,t){let s=this.foundSamplesAndGenerators[A][t];if(s)return s;if(this.presetZones.length<1)return[];function n(c,l,y){return y>=c&&y<=l}function o(c,l){return c.modulatorSource===l.modulatorSource&&c.modulatorDestination===l.modulatorDestination&&c.modulationSecondarySrc===l.modulationSecondarySrc&&c.transformType===l.transformType}function g(c,l){c.push(...l.filter(y=>!c.find(S=>S.generatorType===y.generatorType)))}function C(c,l){c.push(...l.filter(y=>!c.find(S=>o(y,S))))}let h=[],Q=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],f=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,t)&&!c.isGlobal).forEach(c=>{if(c.instrument.instrumentZones.length<1)return;let l=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,t)&&!N.isGlobal).forEach(N=>{let M=[...N.generators],W=[...N.modulators];g(l,Q),g(M,S),C(y,f),C(W,k),C(W,Ss);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:l,modulators:J,sample:N.sample,sampleID:N.generators.find(a=>a.generatorType===I.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=h,h}};var Fe=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var zA=class extends Fe{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},Qe=class extends Fe{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var ce=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 he{constructor(A,t){super(),this.program=t&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new ce,this.DLSInstrument.addUseCount();let n=new Qe;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function vn(e){this.verifyHeader(e,"LIST"),this.verifyText(V(e.chunkData,4),"ins ");let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(O(e.chunkData));let t=A.find(l=>l.header==="insh");if(!t)throw Z(),new Error("No instrument header!");let s=D(t.chunkData,4),n=D(t.chunkData,4),o=D(t.chunkData,4),g=new ze(n,o),C="unnamedPreset",h=yA(A,"INFO");if(h){let l=O(h.chunkData);for(;l.header!=="INAM";)l=O(h.chunkData);C=V(l.chunkData,l.chunkData.length).trim()}g.presetName=C,g.DLSInstrument.instrumentName=C,Ae(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let Q=yA(A,"lrgn");if(!Q)throw Z(),new Error("No region list!");let f=new zA;f.isGlobal=!0;let u=yA(A,"lart"),c=yA(A,"lar2");this.readLart(u,c,f),g.DLSInstrument.instrumentZones.push(f);for(let l=0;l>10&15;x===lA.linear&&k!==lA.linear&&(x=k);let N=s>>14&1,M=s>>15&1;g===I.initialAttenuation&&(M=!M),u=qA(x,N,M,C.isCC,C.enum)}let c=s>>4&15,l=s>>8&1,y=s>>9&1,S=qA(c,l,y,f.isCC,f.enum);if(h){let k=S;S=u,u=k}return new rA({srcEnum:u,secSrcEnum:S,dest:g,transform:0,amt:n})}function Nt(e,A){let t=e.chunkData,s=[],n=[];D(t,4);let o=D(t,4);for(let g=0;g>16;if(C===0&&h===0&&f===0){let l;switch(Q){case R.pan:l=new U(I.pan,c);break;case R.gain:l=new U(I.initialAttenuation,-c*10/.4);break;case R.filterCutoff:l=new U(I.initialFilterFc,c);break;case R.filterQ:l=new U(I.initialFilterQ,c);break;case R.modLfoFreq:l=new U(I.freqModLFO,c);break;case R.modLfoDelay:l=new U(I.delayModLFO,c);break;case R.vibLfoFreq:l=new U(I.freqVibLFO,c);break;case R.vibLfoDelay:l=new U(I.delayVibLFO,c);break;case R.volEnvDelay:l=new U(I.delayVolEnv,c);break;case R.volEnvAttack:l=new U(I.attackVolEnv,c);break;case R.volEnvHold:l=new U(I.holdVolEnv,c);break;case R.volEnvDecay:l=new U(I.decayVolEnv,c);break;case R.volEnvRelease:l=new U(I.releaseVolEnv,c);break;case R.volEnvSustain:let y=(1e3-c)/10;l=new U(I.sustainVolEnv,y*10);break;case R.modEnvDelay:l=new U(I.delayModEnv,c);break;case R.modEnvAttack:l=new U(I.attackModEnv,c);break;case R.modEnvHold:l=new U(I.holdModEnv,c);break;case R.modEnvDecay:l=new U(I.decayModEnv,c);break;case R.modEnvRelease:l=new U(I.releaseModEnv,c);break;case R.modEnvSustain:let S=1e3-c;l=new U(I.sustainModEnv,S);break;case R.reverbSend:l=new U(I.reverbEffectsSend,c);break;case R.chorusSend:l=new U(I.chorusEffectsSend,c);break;case R.pitch:let k=Math.floor(c/100),x=Math.floor(c-k*100);l=new U(I.fineTune,x),s.push(new U(I.coarseTune,k));break}l&&s.push(l)}else{let l=!0;if(h===_.none)if(C===_.modLfo&&Q===R.pitch)s.push(new U(I.modLfoToPitch,c));else if(C===_.modLfo&&Q===R.gain)s.push(new U(I.modLfoToVolume,c));else if(C===_.modLfo&&Q===R.filterCutoff)s.push(new U(I.modLfoToFilterFc,c));else if(C===_.vibratoLfo&&Q===R.pitch)s.push(new U(I.vibLfoToPitch,c));else if(C===_.modEnv&&Q===R.pitch)s.push(new U(I.modEnvToPitch,c));else if(C===_.modEnv&&Q===R.filterCutoff)s.push(new U(I.modEnvToFilterFc,c));else if(C===_.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(C===_.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(C===_.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(C===_.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 l=!1;else l=!1;if(l===!1){let y=Vn(C,h,Q,f,c);y?(n.push(y),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):b("Failed converting to SF2 Modulator!")}}}return n.find(g=>g.modulatorDestination===I.reverbEffectsSend)===void 0&&n.push(new rA({srcEnum:219,dest:I.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(g=>g.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(e,A,t){if(e)for(;e.chunkData.currentIndexe.chunkData.currentIndex;)A.push(O(e.chunkData));let t=A.find(a=>a.header==="rgnh"),s=D(t.chunkData,2),n=D(t.chunkData,2),o=D(t.chunkData,2),g=D(t.chunkData,2),C=new je({min:s,max:n},{min:o,max:g});D(t.chunkData,2);let h=D(t.chunkData,2);h!==0&&C.generators.push(new U(I.exclusiveClass,h));let Q=yA(A,"lart"),f=yA(A,"lar2");this.readLart(Q,f,C),C.isGlobal=!1;let u=A.find(a=>a.header==="wsmp");D(u.chunkData,4);let c=D(u.chunkData,2);D(u.chunkData,2);let S=(D(u.chunkData,4)|0)/-655360*10/.4;D(u.chunkData,4);let k=D(u.chunkData,4),x,N={start:0,end:0};if(k===0)x=0;else{D(u.chunkData,4),D(u.chunkData,4)===0?x=1:x=3,N.start=D(u.chunkData,4);let sA=D(u.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 C.setWavesample(S,x,N,c,J,W),C}var le=class{constructor(A,t,s,n,o,g,C,h){this.sampleName=A,this.sampleRate=t,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=g,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=h,this.isCompressed=(g&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,t){if(!this.isCompressed)try{this.compressedData=t([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 le{constructor(A,t,s,n,o,g,C){super(A,t,s,n,0,1,o*2,(g-1)*2),this.sampleData=C}getAudioData(){return this.sampleData}sampleData;getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let t=0;t>8&255}return A}};function Xn(e){pA("%cLoading Wave samples...",r.recognized);let A=0;for(;e.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 C=D(n.chunkData,4);D(n.chunkData,4),D(n.chunkData,2);let h=D(n.chunkData,2),Q=h/8,f=Math.pow(2,Q*8-1),u=Math.pow(2,Q*8),c,l=!1;h===8?(c=255,l=!0):c=f;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=f&&(z-=u),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.currentIndexe.chunkData.currentIndex;)A.push(new rA(e.chunkData));return A}function ys(e=!1){let A={midiControllers:new Int16Array(St),lockedControllers:Array(St).fill(!1),customControllers:new Float32Array(Ds),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:uA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},lockVibrato:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let t=0;t<128;t++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),e&&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},Ds=Object.keys(iA).length,yt=new Float32Array(Ds);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=[]}};function Ce(e,A){let t=0;for(;e>0;){let s=A.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=Is[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 re(W,a,z);switch(k.push(QA),sA){case-2:switch(a){case w.setTempo:this.tempoChanges.push({ticks:W,tempo:6e7/zA($,3)});break;case w.marker:switch(V(z,z.length).trim().toLowerCase()){default:break;case"start":case"loopstart":f=W;break;case"loopend":u=W}z.currentIndex=0;break;case w.midiPort:let HA=z[0];this.midiPorts[S]=HA,this.midiPortChannelOffsets[HA]===void 0&&(this.midiPortChannelOffsets[HA]=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),HA=V(IA,IA.length)+` +`;this.copyright+=HA,m(`%cDecoded Roland SC message! %c${HA}`,r.recognized,r.value)}break;default:if((a&240)===w.controllerChange)switch(z[0]){case 2:case 116:f=W;break;case 4:case 117:u===null?u=W:u=0;break;case 0:C&&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 l=[];for(let S of this.tracks){let k=S.find(x=>(x.messageStatusByte&240)===w.noteOn);k&&l.push(k.ticks)}this.firstNoteOn=Math.min(...l),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),f!==null&&u===null?(f=this.firstNoteOn,u=this.lastVoiceEventTick):(f===null&&(f=this.firstNoteOn),(u===null||u===0)&&(u=this.lastVoiceEventTick)),this.loop={start:f,end:u},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),!g)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=t,this.midiName=this.midiName.trim(),this.midiName.length===0){m("%cNo name detected. Using the alt name!",r.info),this.midiName=is(t),this.rawMidiName=new Uint8Array(this.midiName.length);for(let S=0;Sc>u?c:u),s=[];for(let u=0;u{g[y]>=l.length||l[g[y]].ticks0;){let u=h(),c=e.tracks[u];if(g[u]>=c.length){C--;continue}let l=c[g[u]];if(g[u]++,l.messageStatusByte===w.midiPort){Q[u]=l.messageData[0];continue}let y=l.messageStatusByte&240;if(y!==w.noteOn&&y!==w.controllerChange&&y!==w.programChange&&y!==w.systemExclusive)continue;let S=(l.messageStatusByte&15)+e.midiPortChannelOffsets[Q[u]]||0,k=s[S];switch(y){case w.programChange:k.program=l.messageData[0],n(k);break;case w.controllerChange:if(l.messageData[0]!==p.bankSelect||f==="gs"&&k.drums)continue;let x=l.messageData[1],N=Math.max(0,x-e.bankOffset);if(f==="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(l.messageData[1]===0)continue;n(k),o[k.string].add(`${l.messageData[0]}-${l.messageData[1]}`);break;case w.systemExclusive:if(l.messageData[0]!==65||l.messageData[2]!==66||l.messageData[3]!==18||l.messageData[4]!==64||!(l.messageData[5]&16)||l.messageData[6]!==21){l.messageData[0]===67&&l.messageData[2]===76&&l.messageData[5]===126&&l.messageData[6]===0&&(f="xg");continue}let M=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][l.messageData[5]&15]+e.midiPortChannelOffsets[Q[u]],W=!!(l.messageData[7]>0&&l.messageData[5]>>4);k=s[M],k.drums=W,k.bank=W?128:0,n(k);break}}for(let u of Object.keys(o))o[u].size===0&&(m(`%cDetected change but no keys for %c${u}`,r.info,r.value),delete o[u]);return Z(),o}function ws(e,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(t,A)}),this.duration=this.midiData.duration,this.firstNoteTime=Ce(this.midiData.firstNoteOn,this.midiData),m(`%cTotal song time: ${lt(Math.ceil(this.duration)).time}`,r.recognized),this.post(wA.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 Rs(e){this.songs=e.reduce((A,t)=>{if(t.duration)return A.push(t),A;try{A.push(new Ze(t.binary,t.altName||""))}catch(s){return this.post(wA.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 Gs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function xs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}var PA=new Int16Array(127);PA[p.mainVolume]=100;PA[p.expressionController]=127;PA[p.pan]=64;PA[p.releaseTime]=64;PA[p.brightness]=64;PA[p.effects1Depth]=40;function Ms(e,A=void 0){if(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIMessages){this.sendMIDIMessage([w.reset]);for(let C=0;CC===p.dataDecrement||C===p.dataIncrement||C===p.dataEntryMsb||C===p.dataDecrement||C===p.lsbForControl6DataEntry||C===p.RPNLsb||C===p.RPNMsb||C===p.NRPNLsb||C===p.NRPNMsb||C===p.bankSelect||C===p.lsbForControl0BankSelect||C===p.resetAllControllers,g=[];for(let C=0;C=A)break}else if(this.playedTime>=e)break;let Q=ke(h.messageStatusByte),f=Q.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(Q.status){case w.noteOn:case w.noteOff:case w.keySignature:break;case w.pitchBend:s[f]=h.messageData[1]<<7|h.messageData[0];break;case w.programChange:let c=n[f];c.program=h.messageData[0],c.actualBank=c.bank;break;case w.controllerChange:let l=h.messageData[0];if(o(l))if(this.sendMIDIMessages)this.sendMIDIMessage([w.controllerChange|f%16,l,h.messageData[1]]);else{let y=h.messageData[1];if(l===p.bankSelect){n[f].bank=y;break}this.synth.controllerChange(f,l,y)}else g[f]===void 0&&(g[f]=Array.from(PA)),g[f][l]=h.messageData[1];break;default:this._processEvent(h,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let u=this.tracks[C][this.eventIndex[C]];if(u===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(u.ticks-h.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7]),g[C].forEach((h,Q)=>{h!==PA[Q]&&!o(Q)&&this.sendMIDIMessage([w.controllerChange|C%16,Q,h])}),n[C].program>=0&&n[C].actualBank>=0){let h=n[C].actualBank;this.sendMIDIMessage([w.controllerChange|C%16,p.bankSelect,h]),this.sendMIDIMessage([w.programChange|C%16,n[C].program])}}else for(let C=0;C>7,s[C]&127),g[C]!==void 0&&g[C].forEach((h,Q)=>{h!==PA[Q]&&!o(Q)&&this.synth.controllerChange(C,Q,h)}),n[C].program>=0&&n[C].actualBank>=0){let h=n[C].actualBank;this.synth.controllerChange(C,p.bankSelect,h),this.synth.programChange(C,n[C].program)}return!0}function Ns(e=!1){if(this.midiData!==void 0){if(e){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 bs(e){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(wA.timeChange,currentTime-Ce(e,this.midiData));let A=this._playTo(0,e);this._recalculateStartTime(this.playedTime),A&&this.play()}function Ls(e){this.absoluteStartTime=currentTime-e/this._playbackRate}function Us(e,A){switch(e){default:break;case bA.loadNewSongList:this.loadNewSongList(A);break;case bA.pause:this.pause();break;case bA.play:this.play(A);break;case bA.stop:this.stop();break;case bA.setTime:this.currentTime=A;break;case bA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case bA.setPlaybackRate:this.playbackRate=A;break;case bA.setLoop:this.loop=A;break;case bA.changeSong:A?this.nextSong():this.previousSong();break;case bA.getMIDI:this.post(wA.getMIDI,this.midiData);break;case bA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Ts(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:mA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function Hs(e){this.post(wA.midiEvent,e)}var CA=class{constructor(A){this.synth=A,this.ignoreEvents=!1,this.sendMIDIMessages=!1,this.loopCount=1/0,this.currentLoopCount=this.loopCount,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 t=this.currentTime;this._playbackRate=A,this.currentTime=t}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&&AYs?440*Math.pow(2,(e-6900)/1200):kt[~~e-Xe]}var Ft=-1660,wo=1600,wt=new Float32Array((wo-Ft)*100+1);for(let e=0;e.5?1:0,s?t*2-1:t;case lA.concave:return s?(t=t*2-1,t<0?1-Ee[~~(t*-aA)]-1:Ee[~~t*aA]):Ee[~~(t*aA)];case lA.convex:return s?(t=t*2-1,t<0?1-Be[~~(t*-aA)]-1:Be[~~(t*aA)]):Be[~~(t*aA)]}}var Rt=1,Gt=new Float32Array(1e3);for(let e=0;e=e.sample.loopEnd;)t-=o;let C=~~t,h=C+1;for(;h>=e.sample.loopEnd;)h-=o;let Q=t-C,f=n[h],u=n[C];A[g]=u+(f-u)*Q,t+=e.sample.playbackStep*e.currentTuningCalculated}}else{e.sample.end>=n.length&&(e.sample.end=n.length-1);for(let o=0;o=e.sample.end){e.finished=!0;return}let h=t-g,Q=n[C],f=n[g];A[o]=f+(Q-f)*h,t+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=t}function qs(e,A){let t=e.sample.cursor,s=e.sample.loopingMode===1||e.sample.loopingMode===3&&!e.isInRelease,n=e.sample.loopEnd-e.sample.loopStart,o=e.sample.sampleData;if(s)for(let g=0;g=e.sample.loopEnd;)t-=n;let C=~~t+1;for(;C>=e.sample.loopEnd;)C-=n;A[g]=o[C],t+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=o.length&&(e.sample.end=o.length-1);for(let g=0;g=e.sample.end){e.finished=!0;return}A[g]=o[C],t+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=t}function Ks(e,A,t,s,n,o,g,C,h){if(!isNaN(t[0])){if(g>0){let Q=o[0],f=o[1];g=Math.min(g,1e3);let u=g/800,c=e*u,l=A*u;for(let y=0;y0){let Q=C[0],f=C[1];h=Math.min(h,1e3);let u=h/800,c=e*u,l=A*u;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],e.calculateCoefficients(A));for(let n=0;n.45*sampleRate&&(A.filter.cutoffHz=.45*sampleRate);let t=A.filter.reasonanceCb/10-3.01;A.filter.reasonanceGain=VA(-1*t);let s=1/Math.sqrt(A.filter.reasonanceGain),n=2*Math.PI*A.filter.cutoffHz/sampleRate,o=Math.cos(n),g=Math.sin(n)/(2*A.filter.reasonanceGain),C=(1-o)*s,h=C/2,Q=h,f=1+g,u=-2*o,c=1-g;A.filter.a0=h/f,A.filter.a1=C/f,A.filter.a2=Q/f,A.filter.a3=u/f,A.filter.a4=c/f}};var Ps=.001,DA=100,vs=96,RA=class e{constructor(A){this.sampleRate=A}currentSampleTime=0;sampleRate;currentAttenuationDb=DA;state=0;releaseStartDb=DA;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=VA(A.volumeEnvelope.currentAttenuationDb),e.recalculate(A)}static intialize(A){e.recalculate(A,!0),A.volumeEnvelope.attenuation=A.volumeEnvelope.attenuationTarget}static recalculate(A,t=!1){let s=A.volumeEnvelope,n=f=>Math.max(0,Math.floor(UA(f)*s.sampleRate));s.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[I.initialAttenuation],1440))/10,s.sustainDbRelative=Math.min(DA,A.modulatedGenerators[I.sustainVolEnv]/10),t&&(s.attenuation=s.attenuationTarget);let o=Math.min(DA,s.sustainDbRelative+s.attenuation);s.attackDuration=n(A.modulatedGenerators[I.attackVolEnv]);let g=A.modulatedGenerators[I.decayVolEnv],C=(60-A.targetKey)*A.modulatedGenerators[I.keyNumToVolEnvDecay],h=(o-s.attenuation)/DA;s.decayDuration=n(g+C)*h,s.releaseDuration=n(A.modulatedGenerators[I.releaseVolEnv]),s.delayEnd=n(A.modulatedGenerators[I.delayVolEnv]),s.attackEnd=s.attackDuration+s.delayEnd;let Q=(60-A.targetKey)*A.modulatedGenerators[I.keyNumToVolEnvHold];if(s.holdEnd=n(A.modulatedGenerators[I.holdVolEnv]+Q)+s.attackEnd,s.decayEnd=s.decayDuration+s.holdEnd,s.state===0&&s.attackEnd===0&&(s.currentAttenuationDb=s.attenuationTarget,s.state=2),A.isInRelease){s.attenuation=Math.min(DA,s.attenuationTarget);let f=Math.max(0,Math.min(DA,s.sustainDbRelative+s.attenuation)),u=(f-s.attenuation)/DA;switch(s.decayDuration=n(g+C)*u,s.state){case 0:s.releaseStartDb=DA;break;case 1:let l=(1-(s.attackEnd-s.releaseStartTimeSamples)/s.attackDuration)*VA(s.attenuation);s.releaseStartDb=20*Math.log10(l)*-1;break;case 2:s.releaseStartDb=s.attenuation;break;case 3:s.releaseStartDb=(1-(s.decayEnd-s.releaseStartTimeSamples)/s.decayDuration)*(f-s.attenuation)+s.attenuation;break;case 4:s.releaseStartDb=f;break;default:s.releaseStartDb=s.currentAttenuationDb}s.releaseStartDb=Math.max(0,Math.min(s.releaseStartDb,DA)),s.releaseStartDb>=vs&&(A.finished=!0)}}static apply(A,t,s,n){let o=A.volumeEnvelope,g=s/10,C=n;if(A.isInRelease){let Q=n*10,f=o.currentSampleTime-o.releaseStartTimeSamples;if(f>=o.releaseDuration){for(let l=0;l=vs&&(A.finished=!0);return}let h=0;switch(o.state){case 0:for(;o.currentSampleTime=t.length)return;o.state++;case 1:for(;o.currentSampleTime=t.length)return}o.state++;case 2:for(;o.currentSampleTime=t.length)return;o.state++;case 3:for(;o.currentSampleTime=t.length)return}o.state++;case 4:for(;;){o.attenuation+=(o.attenuationTarget-o.attenuation)*C;let Q=Math.min(DA,o.sustainDbRelative+o.attenuation);if(t[h]*=VA(Q+g),o.currentAttenuationDb=Q,o.currentSampleTime++,++h>=t.length)return}}}};var Vs=Math.PI/2,Os=.01;function Zs(e,A,t,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,RA.startRelease(A),TA.startRelease(A)),A.modulatedGenerators[I.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let g=A.targetKey,C=A.modulatedGenerators[I.fineTune]+e.customControllers[iA.channelTuning]+e.customControllers[iA.channelTransposeFine]+e.customControllers[iA.masterTuning]+e.channelOctaveTuning[A.midiNote%12]+e.keyCentTuning[A.midiNote],h=A.modulatedGenerators[I.coarseTune]+e.customControllers[iA.channelTuningSemitones],Q=this.tunings[e.preset.program]?.[g];Q?.midiNote>=0&&(g=Q.midiNote,C+=Q.centTuning),C+=(g-A.sample.rootKey)*A.modulatedGenerators[I.scaleTuning];let f=A.modulatedGenerators[I.vibLfoToPitch];if(f!==0){let $=A.startTime+UA(A.modulatedGenerators[I.delayVibLFO]),QA=we(A.modulatedGenerators[I.freqVibLFO]),IA=We($,QA,currentTime);C+=IA*(f*e.customControllers[iA.modulationMultiplier])}let u=A.modulatedGenerators[I.initialFilterFc],c=A.modulatedGenerators[I.modLfoToPitch],l=A.modulatedGenerators[I.modLfoToVolume],y=A.modulatedGenerators[I.modLfoToFilterFc],S=0;if(c+y+l!==0){let $=A.startTime+UA(A.modulatedGenerators[I.delayModLFO]),QA=we(A.modulatedGenerators[I.freqModLFO]),IA=We($,QA,currentTime);C+=IA*(c*e.customControllers[iA.modulationMultiplier]),S=-IA*l,u+=IA*y}if(e.channelVibrato.depth>0){let $=We(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);$&&(C+=$*e.channelVibrato.depth)}let k=A.modulatedGenerators[I.modEnvToPitch],x=A.modulatedGenerators[I.modEnvToFilterFc],N=TA.getValue(A,currentTime);u+=N*x,C+=N*k;let M=~~(C+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(t.length);this.interpolationType===_e.linear?Js(A,J):qs(A,J),he.apply(A,J,u),RA.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];Ks(a,sA,J,t,s,n,K,o,z)}function Fo(e,A){let t=0;return e.drumChannel&&(t+=5),A.isInRelease&&(t-=5),t+=A.velocity/25,t-=A.volumeEnvelope.state,A.isInRelease&&(t-=5),t-=A.volumeEnvelope.currentAttenuationDb/50,t}function Xs(e){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 t=A.slice(0,e);for(let{channel:s,voice:n}of t){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function Ws(e){e.releaseStartTime=currentTime,e.releaseStartTime-e.startTimezs=e);var Ro=function(e){var A,t,s,n,o,g,C,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Q="",f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=h.indexOf(e.charAt(f++)),o=h.indexOf(e.charAt(f++)),g=h.indexOf(e.charAt(f++)),C=h.indexOf(e.charAt(f++)),A=n<<2|o>>4,t=(15&o)<<4|g>>2,s=(3&g)<<6|C,Q+=String.fromCharCode(A),g!==64&&(Q+=String.fromCharCode(t)),C!==64&&(Q+=String.fromCharCode(s));while(f1&&(a.thisProgram=process.argv[1].replace(/\\/g,"/")),a.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(i){if(!(i instanceof pe))throw i}),process.on("unhandledRejection",function(i,E){process.exit(1)}),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)):(_A(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,d){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}d()},F.onerror=d,F.send(null)},a.setWindowTitle=function(i){document.title=i});var Yt=a.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),YA=a.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Yt);for(e in sA)sA.hasOwnProperty(e)&&(a[e]=sA[e]);function xe(i){var E=l;return l=l+i+15&-16,E}function Jt(i){var E=h[M>>2],B=E+i+15&-16;return h[M>>2]=B,B>=EA&&!_t()?(h[M>>2]=E,0):E}function qt(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 _A(E%8==0),E/8}}function fe(i){fe.shown||(fe.shown={}),fe.shown[i]||(fe.shown[i]=1,YA(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,d=B;d>>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 Me=0,Kt=0;function _A(i,E){i||ZA("Assertion failed: "+E)}function vt(i){var E=a["_"+i];return _A(E,"Cannot call unknown function "+i+", make sure it is exported"),E}var Pt={stackSave:function(){Bt()},stackRestore:function(){Et()},arrayToC:function(i){var E,B,d=He(i.length);return E=i,B=d,n.set(E,B),d},stringToC:function(i){var E=0;if(i!=null&&i!==0){var B=(i.length<<2)+1;E=He(B),Zt(i,E,B)}return E}},Bo={string:Pt.stringToC,array:Pt.arrayToC};function Vt(i,E,B,d,F){var v=vt(i),X=[],G=0;if(d)for(var BA=0;BA>0]=E;break;case"i16":g[i>>1]=E;break;case"i32":h[i>>2]=E;break;case"i64":tempI64=[E>>>0,+fo(tempDouble=E)>=1?tempDouble>0?(0|po(+es(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":f[i>>2]=E;break;case"double":u[i>>3]=E;break;default:ZA("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 g[i>>1];case"i32":case"i64":return h[i>>2];case"float":return f[i>>2];case"double":return u[i>>3];default:ZA("invalid type for getValue: "+E)}return null}function Jo(i,E,B,d){typeof i=="number"?(v=!0,X=i):(v=!1,X=i.length);var F=typeof E=="string"?E:null;if(G=B==4?d:[typeof Te=="function"?Te:xe,He,xe,Jt][B===void 0?2:B](Math.max(X,F?1:E.length)),v){for(d=G,_A((3&G)==0),BA=G+(-4&X);d>2]=0;for(BA=G+X;d>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],(d!=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&&Ot)return Ot.decode(nA.subarray(oA,eA));for(var q,dA,GA,xA,MA,Ae,NA="";;){if(!(q=nA[oA++]))return NA;if(!(128&q)){NA+=String.fromCharCode(q);continue}if(dA=63&nA[oA++],(224&q)==192){NA+=String.fromCharCode((31&q)<<6|dA);continue}if(GA=63&nA[oA++],(240&q)==224?q=(15&q)<<12|dA<<6|GA:(xA=63&nA[oA++],(248&q)==240?q=(7&q)<<18|dA<<12|GA<<6|xA:(MA=63&nA[oA++],q=(252&q)==248?(3&q)<<24|dA<<18|GA<<12|xA<<6|MA:(1&q)<<30|dA<<24|GA<<18|xA<<12|MA<<6|(Ae=63&nA[oA++]))),q<65536)NA+=String.fromCharCode(q);else{var Se=q-65536;NA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(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(d,F,v){for(var X=0;X>0]=d.charCodeAt(X);v||(n[F>>0]=0)}(i,E,!1)}var Ot=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function be(i,E,B,d){if(!(d>0))return 0;for(var F=B,v=B+d-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 Zt(i,E,B){return be(i,o,E,B)}function Le(i){for(var E=0,B=0;B=55296&&d<=57343&&(d=65536+((1023&d)<<10)|1023&i.charCodeAt(++B)),d<=127?++E:d<=2047?E+=2:d<=65535?E+=3:d<=2097151?E+=4:d<=67108863?E+=5:E+=6}return E}var Xt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function Po(i){for(var E=i,B=E>>1;g[B];)++B;if((E=B<<1)-i>32&&Xt)return Xt.decode(o.subarray(i,E));for(var d=0,F="";;){var v=g[i+2*d>>1];if(v==0)return F;++d,F+=String.fromCharCode(v)}}function Vo(i,E,B){if(B===void 0&&(B=2147483647),B<2)return 0;for(var d=E,F=(B-=2)<2*i.length?B/2:i.length,v=0;v>1]=X,E+=2}return g[E>>1]=0,E-d}function Oo(i){return 2*i.length}function Zo(i){for(var E=0,B="";;){var d=h[i+4*E>>2];if(d==0)return B;if(++E,d>=65536){var F=d-65536;B+=String.fromCharCode(55296|F>>10,56320|1023&F)}else B+=String.fromCharCode(d)}}function Xo(i,E,B){if(B===void 0&&(B=2147483647),B<4)return 0;for(var d=E,F=d+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-d}function Wo(i){for(var E=0,B=0;B=55296&&d<=57343&&++B,E+=4}return E}function _o(i){var E=Le(i)+1,B=Te(E);return B&&be(i,n,B,E),B}function zo(i){var E=Le(i)+1,B=He(E);return be(i,n,B,E),B}function jo(i){return i}function $o(){var i,E=function(){var d=Error();if(!d.stack){try{throw Error(0)}catch(F){d=F}if(!d.stack)return"(no stack trace available)"}return d.stack.toString()}();return a.extraStackTrace&&(E+=` +`+a.extraStackTrace()),(i=E).replace(/__Z[\w\d_]+/g,function(B){var d,F=d=B;return B===F?B:B+" ["+F+"]"})}function rt(i,E){return i%E>0&&(i+=E-i%E),i}function Wt(i){a.buffer=s=i}function it(){a.HEAP8=n=new Int8Array(s),a.HEAP16=g=new Int16Array(s),a.HEAP32=h=new Int32Array(s),a.HEAPU8=o=new Uint8Array(s),a.HEAPU16=C=new Uint16Array(s),a.HEAPU32=Q=new Uint32Array(s),a.HEAPF32=f=new Float32Array(s),a.HEAPF64=u=new Float64Array(s)}function _t(){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 d=a.reallocBuffer(EA);return d&&d.byteLength==EA?(Wt(d),it(),!0):(EA=B,!1)}c=l=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 de(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<=d&&(E<=32||i>d)&&(i=-2*d+i),i}var fo=Math.abs,mo=Math.ceil,es=Math.floor,po=Math.min,$A=0,Ct=null,me=null;function rr(i){return i}a.preloadedImages={},a.preloadedAudios={};var ts="data:application/octet-stream;base64,";function Ue(i){return String.prototype.startsWith?i.startsWith(ts):i.indexOf(ts)===0}(function(){var E="main.wast",B="main.wasm",d="main.temp.asm.js";Ue(E)||(E=HA(E)),Ue(B)||(B=HA(B)),Ue(d)||(d=HA(d));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){ZA(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 dA=a.wasmMemory.grow((eA-q)/65536);return dA!==-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,dA){var GA;if(!(q=GA=q).table){var xA,MA=a.wasmTableSize;MA===void 0&&(MA=1024);var Ae=a.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?Ae!==void 0?q.table=new WebAssembly.Table({initial:MA,maximum:Ae,element:"anyfunc"}):q.table=new WebAssembly.Table({initial:MA,element:"anyfunc"}):q.table=Array(MA),a.wasmTable=q.table}return q.memoryBase||(q.memoryBase=a.STATIC_BASE),q.tableBase||(q.tableBase=0),xA=function(Se,ne,Qt){if(typeof WebAssembly!="object")return YA("no native wasm support detected"),!1;if(!(a.wasmMemory instanceof WebAssembly.Memory))return YA("no native wasm Memory in use"),!1;function Ye(JA,qA){if((v=JA.exports).memory){var ye,ct,os;ye=v.memory,ct=a.buffer,ye.byteLength0?B:Le(i)+1,F=Array(d),v=be(i,F,0,F.length);return E&&(F.length=v),F}function gr(i){for(var E=[],B=0;B255&&(d&=255),E.push(String.fromCharCode(d))}return E.join("")}l+=16,M=xe(4),x=(S=k=qt(l))+at,N=qt(x),h[M>>2]=N,y=!0,a.wasmTableSize=4,a.wasmMaxTableSize=4,a.asmGlobalArg={},a.asmLibraryArg={abort:ZA,assert:_A,enlargeMemory:_t,getTotalMemory:Qo,abortOnCannotGrowMemory:function(){ZA("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,d){var F=Bt();try{return a.dynCall_iii(E,B,d)}catch(v){if(Et(F),typeof v!="number"&&v!=="longjmp")throw v;a.setThrew(1,0)}},___assert_fail:function(E,B,d,F){ZA("Assertion failed: "+Ne(E)+", at: "+[B?Ne(B):"unknown filename",d,F?Ne(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,d){return o.set(o.subarray(B,B+d),E),E},_llvm_floor_f64:es,DYNAMICTOP_PTR:M,tempDoublePtr:kA,ABORT:Me,STACKTOP:k,STACK_MAX:x};var ss=a.asm(a.asmGlobalArg,a.asmLibraryArg,s);a.asm=ss,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 Te=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 He=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 pe(i){this.name="ExitStatus",this.message="Program terminated with exit("+i+")",this.status=i}function ht(i){i=i||a.arguments,!($A>0)&&(function(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)lo(a.preRun.shift());de(zt)}(),!($A>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,Me||(gt||(gt=!0,de(It)),de(jt),a.onRuntimeInitialized&&a.onRuntimeInitialized(),function(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)uo(a.postRun.shift());de(As)}()))}}function Cr(i,E){(!E||!a.noExitRuntime||i!==0)&&(a.noExitRuntime||(Me=!0,Kt=i,k=J,de($t),co=!0,a.onExit&&a.onExit(i)),a.quit(i,new pe(i)))}function ZA(i){throw a.onAbort&&a.onAbort(i),i!==void 0?(Yt(i),YA(i),i=JSON.stringify(i)):i="",Me=!0,Kt=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=ss,a.ccall=Vt,a.cwrap=function(E,B,d,F){var v=(d=d||[]).every(function(X){return X==="number"});return B!=="string"&&v&&!F?vt(E):function(){return Vt(E,B,d,arguments,F)}},pe.prototype=Error(),pe.prototype.constructor=pe,me=function i(){a.calledRun||ht(),a.calledRun||(me=i)},a.run=ht,a.abort=ZA,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()},OA.decode=function(i){return function(B){if(!_s)throw Error("Not initialized");var d={};function F(ne){return new Int32Array(a.HEAPU8.buffer,ne,1)[0]}function v(ne,Qt){var Ye=new ArrayBuffer(Qt*Float32Array.BYTES_PER_ELEMENT),oe=new Float32Array(Ye);return oe.set(new Float32Array(a.HEAPU8.buffer,ne,Qt)),oe}d.open=a.cwrap("stb_vorbis_js_open","number",[]),d.close=a.cwrap("stb_vorbis_js_close","void",["number"]),d.channels=a.cwrap("stb_vorbis_js_channels","number",["number"]),d.sampleRate=a.cwrap("stb_vorbis_js_sample_rate","number",["number"]),d.decode=a.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var X,G,BA,nA,oA=d.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),dA=a._malloc(4),GA=d.decode(oA,eA.byteOffset,eA.byteLength,q,dA);if(a._free(eA.byteOffset),GA<0)throw d.close(oA),a._free(q),Error("stbvorbis decode failed: "+GA);for(var xA=d.channels(oA),MA=Array(xA),Ae=new Int32Array(a.HEAPU32.buffer,F(q),xA),NA=0;NA=0&&(s=this.workletProcessorChannels[t]),e.messageType){case AA.noteOn:this.noteOn(t,A[0],A[1],A[2]);break;case AA.noteOff:this.noteOff(t,A);break;case AA.pitchWheel:this.pitchWheel(t,A[0],A[1]);break;case AA.ccChange:this.controllerChange(t,A[0],A[1],A[2]);break;case AA.customcCcChange:s.customControllers[A[0]]=A[1];break;case AA.killNote:this.killNote(t,A);break;case AA.programChange:this.programChange(t,A[0],A[1]);break;case AA.channelPressure:this.channelPressure(t,A);break;case AA.polyPressure:this.polyPressure(t,A[0],A[1]);break;case AA.ccReset:t===LA?this.resetAllControllers():this.resetControllers(t);break;case AA.systemExclusive:this.systemExclusive(A);break;case AA.setChannelVibrato:if(t===LA)for(let g=0;g{let t=(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:t,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:mA.channelProperties,messageData:e})}function Go(e,A,t){let s=e,n=A<<7|t;return e===127&&A===127&&t===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function en(e,A=0){let t=e[0];if(!(this.deviceID!==LA&&e[1]!==127&&this.deviceID!==e[1]))switch(t){default:b(`%cUnrecognized SysEx: %c${hA(e)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(e[2]){case 4:let s;switch(e[3]){case 1:let n=e[5]<<7|e[4];this.setMIDIVolume(n/16384),m(`%cMaster Volume. Volume: %c${n}`,r.info,r.value);break;case 2:let g=((e[5]<<7|e[4])-8192)/8192;this.setMasterPan(g),m(`%cMaster Pan. Pan: %c${g}`,r.info,r.value);break;case 3:let C=(e[5]<<7|e[6])-8192;s=Math.floor(C/81.92),this.setMasterTuning(s),m(`%cMaster Fine Tuning. Cents: %c${s}`,r.info,r.value);break;case 4:s=(e[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(e)}`,r.warn,r.unrecognized)}break;case 9:e[3]===1?(m("%cGM system on",r.info),this.system="gm"):e[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(e[3]){case 2:case 7:let n=4;e[3]===7&&n++;let o=e[n++],g=e[n++];for(let h=0;h>1&1)===1&&this.setOctaveTuning(15+A,C);for(let h=0;h<7;h++)(e[5]>>h&1)===1&&this.setOctaveTuning(7+h+A,C);for(let h=0;h<7;h++)(e[6]>>h&1)===1&&this.setOctaveTuning(h+A,C);m(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${C.join(" ")}`,r.info,r.value);break;default:b(`%cUnrecognized MIDI Tuning standard message: %c${hA(e)}`,r.warn,r.unrecognized);break}break;default:b(`%cUnrecognized MIDI Realtime/non realtime message: %c${hA(e)}`,r.warn,r.unrecognized)}break;case 65:if(e[2]===66&&e[3]===18){let s=e[7];if(e[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(e[4]===64){if((e[5]&16)>0){let n=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A;switch(e[6]){default:break;case 21:let o=s>0&&e[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(e)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let g=s-64;this.transposeChannel(n,g),m(`%cChannel %c${n}%c pitch shift. Semitones %c${g}%c, with %c${hA(e)}`,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 C=s-64;m(`%cChannel %c${n}%c tuning. Cents %c${C}%c, with %c${hA(e)}`,r.info,r.recognized,r.info,r.value,r.info,r.value),this.setChannelTuning(n,C)}}else if(e[5]===0&&e[6]===6){m(`%cRoland GS Master Pan set to: %c${s}%c with: %c${hA(e)}`,r.info,r.value,r.info,r.value),this.setMasterPan((s-64)/64);return}else if(e[5]===0&&e[6]===5){let n=s-64;m(`%cRoland GS Master Key-Shift set to: %c${n}%c with: %c${hA(e)}`,r.info,r.value,r.info,r.value),this.setMasterTuning(n*100);return}else if(e[5]===0&&e[6]===4){m(`%cRoland GS Master Volume set to: %c${s}%c with: %c${hA(e)}`,r.info,r.value,r.info,r.value),this.setMIDIVolume(s/127);return}}b(`%cUnrecognized Roland %cGS %cSysEx: %c${hA(e)}`,r.warn,r.recognized,r.warn,r.unrecognized);return}else if(e[2]===22&&e[3]===18&&e[4]===16){this.setMIDIVolume(e[7]/100),m(`%cRoland Master Volume control set to: %c${e[7]}%c via: %c${hA(e)}`,r.info,r.value,r.info,r.value);return}else{b(`%cUnrecognized Roland SysEx: %c${hA(e)}`,r.warn,r.unrecognized);return}case 67:if(e[2]===76)if(e[3]===0&&e[4]===0)switch(e[5]){case 4:let s=e[6];this.setMIDIVolume(s/127),m(`%cXG master volume. Volume: %c${s}`,r.info,r.recognized);break;case 6:let n=e[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(e[3]===8){if(this.system!=="xg")return;let s=e[4]+A;if(s>=this.workletProcessorChannels.length)return;let n=e[6];switch(e[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 g=n-64;o.channelTransposeKeyShift=g;break;case 11:this.controllerChange(s,p.mainVolume,n);break;case 14:let C=n;C===0&&(C=Math.floor(Math.random()*127)),this.controllerChange(s,p.pan,C);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${e[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&b(`%cUnrecognized Yamaha XG SysEx: %c${hA(e)}`,r.warn,r.unrecognized);else this.system==="xg"&&b(`%cUnrecognized Yamaha SysEx: %c${hA(e)}`,r.warn,r.unrecognized);break}}function tn(e,A,t){if(A.transformAmount===0)return 0;let s;if(A.sourceUsesCC)s=e[A.sourceIndex];else{let h=A.sourceIndex+gA;switch(A.sourceIndex){case P.noController:s=16383;break;case P.noteOnKeyNum:s=t.midiNote<<7;break;case P.noteOnVelocity:s=t.velocity<<7;break;case P.polyPressure:s=t.pressure<<7;break;default:s=e[h];break}}let n=fA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let h=A.secSrcIndex+gA;switch(A.secSrcIndex){case P.noController:o=16383;break;case P.noteOnKeyNum:o=t.midiNote<<7;break;case P.noteOnVelocity:o=t.velocity<<7;break;case P.polyPressure:o=t.pressure<<7;break;default:o=e[h]}}let g=fA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=n*g*A.transformAmount;return A.transformType===2?Math.abs(C):C}function XA(e,A,t=-1,s=0){let{modulators:n,generators:o,modulatedGenerators:g}=e;if(TA.recalculate(e),t===-1){g.set(o),n.forEach(Q=>{g[Q.modulatorDestination]+=tn(A,Q,e)}),RA.recalculate(e);return}let C=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===t&&Q.sourceIndex===s||Q.secSrcUsesCC===t&&Q.secSrcIndex===s){let f=Q.modulatorDestination;h.has(f)||(g[f]=o[f],n.forEach(u=>{u.modulatorDestination===f&&(g[f]+=tn(A,u,e))}),h.add(f))}}),[...h].some(Q=>C.has(Q))&&RA.recalculate(e)}var fA=[];for(let e=0;e<4;e++){fA[e]=[[new Float32Array(aA),new Float32Array(aA)],[new Float32Array(aA),new Float32Array(aA)]];for(let A=0;A200&&t<40||this.highPerformanceMode&&t<10||g.isMuted)return;let C=A+g.channelTransposeKeyShift;if(A>127||A<0)return;let h=g.preset.program;this.tunings[h]?.[A]?.midiNote>=0&&(C=this.tunings[h]?.[A].midiNote);let Q=this.getWorkletVoices(e,C,t,g,o,s),f=g.voices;Q.forEach(u=>{let c=u.generators[I.exclusiveClass];c!==0&&f.forEach(l=>{l.generators[I.exclusiveClass]===c&&(this.releaseVoice(l),l.modulatedGenerators[I.releaseVolEnv]=-7e3,l.modulatedGenerators[I.releaseModEnv]=-7e3,RA.recalculate(l),TA.recalculate(l))}),XA(u,g.midiControllers),RA.intialize(u),u.currentPan=(Math.max(-500,Math.min(500,u.modulatedGenerators[I.pan]))+500)/1e3}),this.totalVoicesAmount+=Q.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(Q.length),f.push(...Q),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:e,velocity:t}))}function nn(e,A){if(A>127||A<0){b("Received a noteOn for note",A,"Ignoring.");return}let t=A+this.workletProcessorChannels[e].channelTransposeKeyShift,s=this.workletProcessorChannels[e].preset.program;if(this.tunings[s]?.[A]?.midiNote>=0&&(t=this.tunings[s]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[e].drumChannel){this.killNote(e,t);return}this.workletProcessorChannels[e].voices.forEach(o=>{o.midiNote!==t||o.isInRelease===!0||(this.workletProcessorChannels[e].holdPedal?this.workletProcessorChannels[e].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:e})}function on(e,A){this.workletProcessorChannels[e].voices.forEach(t=>{t.midiNote===A&&(t.modulatedGenerators[I.releaseVolEnv]=-12e3,this.releaseVoice(t))})}function rn(e,A=!1){let t=this.workletProcessorChannels[e].voices;A?(t.length=0,this.workletProcessorChannels[e].sustainedVoices.length=0,this.sendChannelProperties()):(t.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[e].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function an(e=!1){m("%cStop all received!",r.info);for(let A=0;AXA(n,this.workletProcessorChannels[e].midiControllers,0,P.pitchWheel)),this.sendChannelProperties()}function cn(e,A){let t=this.workletProcessorChannels[e];t.midiControllers[gA+P.channelPressure]=A<<7,this.workletProcessorChannels[e].voices.forEach(s=>XA(s,t.midiControllers,0,P.channelPressure)),this.callEvent("channelpressure",{channel:e,pressure:A})}function ln(e,A,t){this.workletProcessorChannels[e].voices.forEach(s=>{s.midiNote===A&&(s.pressure=t,XA(s,this.workletProcessorChannels[e].midiControllers,0,P.polyPressure))}),this.callEvent("polypressure",{channel:e,midiNote:A,pressure:t})}function un(e,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[e].channelOctaveTuning=A}function fn(e,A,t,s=!1){let n=this.workletProcessorChannels[e];if(n===void 0){b(`Trying to access channel ${e} 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|t&127,n.voices.forEach(g=>XA(g,n.midiControllers,1,o))}switch(A){case p.allNotesOff:this.stopAll(e);break;case p.allSoundOff:this.stopAll(e,!0);break;case p.bankSelect:let o=t;if(!s){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${t}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(e,!0):e%16!==SA&&this.setDrums(e,!1);break;case"gm2":o===120&&(n.drumChannel=!0,this.callEvent("drumchange",{channel:e,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||t!==127&&(n.midiControllers[p.bankSelect]=t):this.system==="gm2"&&(n.midiControllers[p.bankSelect]=t);break;case p.RPNLsb:n.RPValue=n.RPValue<<7|t,n.dataEntryState=uA.RPFine;break;case p.RPNMsb:n.RPValue=t,n.dataEntryState=uA.RPCoarse;break;case p.NRPNMsb:n.NRPCoarse=t,n.dataEntryState=uA.NRPCoarse;break;case p.NRPNLsb:n.NRPFine=t,n.dataEntryState=uA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(e,t);break;case p.lsbForControl6DataEntry:this.dataEntryFine(e,t);break;case p.resetAllControllers:this.resetControllers(e);break;case p.sustainPedal:t>=64?n.holdPedal=!0:(n.holdPedal=!1,n.sustainedVoices.forEach(g=>{this.releaseVoice(g)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=t<<7,n.voices.forEach(g=>XA(g,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:e,controllerNumber:A,controllerValue:t});break}}function dn(e){this.midiVolume=e,this.setMasterPan(this.pan)}function mn(e){this.masterGain=e*Mt,this.setMasterPan(this.pan)}function pn(e){this.pan=e,e=e/2+.5,this.panLeft=(1-e)*this.currentGain,this.panRight=e*this.currentGain}function Sn(e,A){A&&this.stopAll(e,!0),this.workletProcessorChannels[e].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:e,isMuted:A})}function yn(e){this.workletProcessorChannels[e].lockVibrato=!0,this.workletProcessorChannels[e].channelVibrato.rate=0,this.workletProcessorChannels[e].channelVibrato.delay=0,this.workletProcessorChannels[e].channelVibrato.depth=0}function Dn(e,A,t,s){this.workletProcessorChannels[e].lockVibrato||(this.workletProcessorChannels[e].channelVibrato.rate=t,this.workletProcessorChannels[e].channelVibrato.delay=s,this.workletProcessorChannels[e].channelVibrato.depth=A)}function kn(e,A){let t=this.workletProcessorChannels[e],s=()=>{t.channelVibrato.delay===0&&t.channelVibrato.rate===0&&t.channelVibrato.depth===0&&(t.channelVibrato.depth=50,t.channelVibrato.rate=8,t.channelVibrato.delay=.6)};switch(t.dataEntryState){default:case uA.Idle:break;case uA.NRPFine:if(this.system!=="gs")return;switch(t.NRPCoarse){default:if(A===64)return;b(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16).toUpperCase()} 0x${t.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(t.NRPFine){default:if(A===64)return;b(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16)} 0x${t.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.rate=A/64*8,m(`%cVibrato rate for %c${e}%c is now set to %c${A} = ${t.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.depth=A/2,m(`%cVibrato depth for %c${e}%c is now set to %c${A} = ${t.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.delay=A/64/3,m(`%cVibrato delay for %c${e}%c is now set to %c${A} = ${t.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let g=A;this.controllerChange(e,p.brightness,A),m(`%cFilter cutoff for %c${e}%c is now set to %c${g}`,r.info,r.recognized,r.info,r.value)}break;case 24:if(!t.drumChannel)return;let n=A-64;t.keyCentTuning[t.NRPFine]=n*100,m(`%cGS drum key tuning. MIDI note: %c${t.NRPFine}%c semitones: %c${n}`,r.info,r.recognized,r.info,r.value);break;case 29:if(!t.drumChannel)return;let o=A;this.controllerChange(e,p.effects1Depth,o),m(`%cGS Drum reverb for %c${e}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case uA.RPCoarse:case uA.RPFine:switch(t.RPValue){default:b(`%cUnrecognized RPN for %c${e}%c: %c(0x${t.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:t.midiControllers[gA+P.pitchWheelRange]=A<<7,m(`%cChannel ${e} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(e,A-64);break;case 1:this.setChannelTuning(e,A-64,!1);break;case 5:this.setModulationDepth(e,A*100);break;case 16383:this.resetParameters(e);break}}}function wn(e,A){let t=this.workletProcessorChannels[e];switch(t.dataEntryState){default:break;case uA.RPCoarse:case uA.RPFine:switch(t.RPValue){default:break;case 0:if(A===0)break;t.midiControllers[gA+P.pitchWheelRange]|=A;let s=(t.midiControllers[gA+P.pitchWheelRange]>>7)+A/127;m(`%cChannel ${e} bend range. Semitones: %c${s}`,r.info,r.value);break;case 1:let o=t.customControllers[iA.channelTuning]<<7|A;this.setChannelTuning(e,o*.01220703125);break;case 5:let C=t.customControllers[iA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(e,C);break;case 16383:this.resetParameters(e);break}}}function Fn(){m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let e=0;e{this.workletProcessorChannels[e].lockedControllers[s]&&this.callEvent("controllerchange",{channel:e,controllerNumber:s,controllerValue:this.workletProcessorChannels[e].midiControllers[s]>>7})};if(t(p.mainVolume),t(p.pan),t(p.expressionController),t(p.modulationWheel),t(p.effects3Depth),t(p.effects1Depth),this.workletProcessorChannels[e].lockedControllers[gA+P.pitchWheel]){let s=this.workletProcessorChannels[e].midiControllers[gA+P.pitchWheel],n=s>>7,o=s&127;this.callEvent("pitchwheel",{channel:e,MSB:n,LSB:o})}}this.tunings=[],this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Ke}function Rn(e){let A=this.workletProcessorChannels[e],s=A.lockedControllers.reduce((o,g,C)=>(g&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(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(e)}function Gn(e){let A=this.workletProcessorChannels[e];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=uA.Idle}function xn(){let e=4;for(let s of this.instruments)e+=s.instrumentZones.reduce((n,o)=>(o.generators=o.generators.filter(g=>g.generatorType!==I.sampleID&&g.generatorType!==I.keyRange&&g.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(e),t=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=t;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue),t++}return cA(A,0),tA(new j("igen",A.length,A))}function Mn(e,A,t,s,n){let o=this.samples.map((Q,f)=>{t&&Q.compressSample(s,n);let u=Q.getRawData();return m(`%cEncoded sample %c${f}. ${Q.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),u}),g=this.samples.reduce((Q,f,u)=>Q+o[u].length+46,0),C=new H(g);this.samples.forEach((Q,f)=>{let u=o[f],c,l,y=u.length;Q.isCompressed?(c=C.currentIndex,l=c+u.length):(c=C.currentIndex/2,l=c+u.length/2,y+=46),e.push(c),C.set(u,C.currentIndex),C.currentIndex+=y,A.push(l)});let h=tA(new j("smpl",C.length,C),new H([115,100,116,97]));return tA(new j("LIST",h.length,h))}function Nn(e,A){let s=new H(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{FA(s,n.sampleName,20);let g=e[o];cA(s,g);let C=A[o];cA(s,C);let h=n.sampleLoopStartIndex/2+g,Q=n.sampleLoopEndIndex/2+g;n.isCompressed&&(h-=g,Q-=g),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)}),FA(s,"EOS",46),tA(new j("shdr",s.length,s))}function bn(){let e=10;for(let s of this.instruments)e+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(e),t=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=t;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),t++}return Ie(A,0,10),tA(new j("imod",A.length,A))}function Ln(){let e=this.instruments.reduce((o,g)=>g.instrumentZones.length*4+o,4),A=new H(e),t=0,s=0,n=0;for(let o of this.instruments){o.instrumentZoneIndex=t;for(let g of o.instrumentZones)g.zoneID=t,Y(A,s),Y(A,n),s+=g.generators.length,n+=g.modulators.length,t++}return Y(A,s),Y(A,n),tA(new j("ibag",A.length,A))}function Un(){let e=this.instruments.length*22+22,A=new H(e),t=0,s=0;for(let n of this.instruments)FA(A,n.instrumentName,20),Y(A,t),t+=n.instrumentZones.length,n.instrumentID=s,s++;return FA(A,"EOI",20),Y(A,t),tA(new j("inst",A.length,A))}function Tn(){let e=4;for(let s of this.presets)e+=s.presetZones.reduce((n,o)=>(o.generators=o.generators.filter(g=>g.generatorType!==I.instrument&&g.generatorType!==I.keyRange&&g.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(e),t=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=t;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue);t+=n.generators.length}return Y(A,0),Y(A,0),tA(new j("pgen",A.length,A))}function Hn(){let e=10;for(let s of this.presets)e+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(e),t=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=t;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),t++}return Ie(A,0,10),tA(new j("pmod",A.length,A))}function Yn(){let e=this.presets.reduce((o,g)=>g.presetZones.length*4+o,4),A=new H(e),t=0,s=0,n=0;for(let o of this.presets){o.presetZoneStartIndex=t;for(let g of o.presetZones)g.zoneID=t,Y(A,s),Y(A,n),s+=g.generators.length,n+=g.modulators.length,t++}return Y(A,s),Y(A,n),tA(new j("pbag",A.length,A))}function Jn(){let e=this.presets.length*38+38,A=new H(e),t=0;for(let s of this.presets)FA(A,s.presetName,20),Y(A,s.program),Y(A,s.bank),Y(A,t),cA(A,s.library),cA(A,s.genre),cA(A,s.morphology),t+=s.presetZones.length;return FA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,t),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(e=xo){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");pA("%cSaving soundfont...",r.info),m(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),m("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.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);FA(a,J),A.push(tA(new j(W,J.length,a)))}let t=De([new H([73,78,70,79]),...A]),s=tA(new j("LIST",t.length,t));m("%cWriting SDTA...",r.info);let n=[],o=[],g=Mn.call(this,n,o,e?.compress,e?.compressionQuality||.5,e.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let C=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 f=Ln.call(this);m("%cWriting INST...",r.info);let u=Un.call(this),c=Tn.call(this);m("%cWriting PMOD...",r.info);let l=Hn.call(this);m("%cWriting PBAG...",r.info);let y=Yn.call(this);m("%cWriting PHDR...",r.info);let S=Jn.call(this),k=De([new H([112,100,116,97]),S,y,l,c,u,f,Q,h,C]),x=tA(new j("LIST",k.length,k));m("%cWriting the output file...",r.info);let N=De([new H([115,102,98,107]),s,g,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 se=class e{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(t=>{t.isGlobal||t.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}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,t,s=!1){let n=this.presets.find(o=>o.bank===A&&o.program===t);if(n)return n;if(s!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===t)}setSampleIDOffset(A){this.presets.forEach(t=>t.sampleIDOffset=A)}getPreset(A,t){let s=this.presets.find(n=>n.bank===A&&n.program===t);return s||(s=this.presets.find(n=>n.program===t&&n.bank!==128),A===128&&(s=this.presets.find(n=>n.bank===128&&n.program===t),s||(s=this.presets.find(n=>n.bank===128))),s&&b(`%cPreset ${A}.${t} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,r.warn,r.recognized)),s||(b(`Preset ${t} not found. Defaulting to`,this.presets[0].presetName),s=this.presets[0]),s}getPresetByName(A){let t=this.presets.find(s=>s.presetName===A);return t||(b("Preset not found. Defaulting to:",this.presets[0].presetName),t=this.presets[0]),t}static mergeSoundfonts(...A){let t=A.shift(),s=t.presets;for(;A.length;)A.shift().presets.forEach(o=>{s.find(g=>g.bank===o.bank&&g.program===o.program)===void 0&&s.push(o)});return new e({presets:s,info:t.soundFontInfo})}};se.prototype.write=qn;function Kn(e){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,t){for(let s=A;s{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,t){this.getSamplesAndGenerators(A,t).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,t){let s=this.foundSamplesAndGenerators[A][t];if(s)return s;if(this.presetZones.length<1)return[];function n(c,l,y){return y>=c&&y<=l}function o(c,l){return c.modulatorSource===l.modulatorSource&&c.modulatorDestination===l.modulatorDestination&&c.modulationSecondarySrc===l.modulationSecondarySrc&&c.transformType===l.transformType}function g(c,l){c.push(...l.filter(y=>!c.find(S=>S.generatorType===y.generatorType)))}function C(c,l){c.push(...l.filter(y=>!c.find(S=>o(y,S))))}let h=[],Q=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],f=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,t)&&!c.isGlobal).forEach(c=>{if(c.instrument.instrumentZones.length<1)return;let l=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,t)&&!N.isGlobal).forEach(N=>{let M=[...N.generators],W=[...N.modulators];g(l,Q),g(M,S),C(y,f),C(W,k),C(W,Ss);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:l,modulators:J,sample:N.sample,sampleID:N.generators.find(a=>a.generatorType===I.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=h,h}};var Fe=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var jA=class extends Fe{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},ce=class extends Fe{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var le=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var ze=class extends Qe{constructor(A,t){super(),this.program=t&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new le,this.DLSInstrument.addUseCount();let n=new ce;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function vn(e){this.verifyHeader(e,"LIST"),this.verifyText(V(e.chunkData,4),"ins ");let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(O(e.chunkData));let t=A.find(l=>l.header==="insh");if(!t)throw Z(),new Error("No instrument header!");let s=D(t.chunkData,4),n=D(t.chunkData,4),o=D(t.chunkData,4),g=new ze(n,o),C="unnamedPreset",h=yA(A,"INFO");if(h){let l=O(h.chunkData);for(;l.header!=="INAM";)l=O(h.chunkData);C=V(l.chunkData,l.chunkData.length).trim()}g.presetName=C,g.DLSInstrument.instrumentName=C,ee(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let Q=yA(A,"lrgn");if(!Q)throw Z(),new Error("No region list!");let f=new jA;f.isGlobal=!0;let u=yA(A,"lart"),c=yA(A,"lar2");this.readLart(u,c,f),g.DLSInstrument.instrumentZones.push(f);for(let l=0;l>10&15;x===lA.linear&&k!==lA.linear&&(x=k);let N=s>>14&1,M=s>>15&1;g===I.initialAttenuation&&(M=!M),u=KA(x,N,M,C.isCC,C.enum)}let c=s>>4&15,l=s>>8&1,y=s>>9&1,S=KA(c,l,y,f.isCC,f.enum);if(h){let k=S;S=u,u=k}return new rA({srcEnum:u,secSrcEnum:S,dest:g,transform:0,amt:n})}function Nt(e,A){let t=e.chunkData,s=[],n=[];D(t,4);let o=D(t,4);for(let g=0;g>16;if(C===0&&h===0&&f===0){let l;switch(Q){case R.pan:l=new U(I.pan,c);break;case R.gain:l=new U(I.initialAttenuation,-c*10/.4);break;case R.filterCutoff:l=new U(I.initialFilterFc,c);break;case R.filterQ:l=new U(I.initialFilterQ,c);break;case R.modLfoFreq:l=new U(I.freqModLFO,c);break;case R.modLfoDelay:l=new U(I.delayModLFO,c);break;case R.vibLfoFreq:l=new U(I.freqVibLFO,c);break;case R.vibLfoDelay:l=new U(I.delayVibLFO,c);break;case R.volEnvDelay:l=new U(I.delayVolEnv,c);break;case R.volEnvAttack:l=new U(I.attackVolEnv,c);break;case R.volEnvHold:l=new U(I.holdVolEnv,c);break;case R.volEnvDecay:l=new U(I.decayVolEnv,c);break;case R.volEnvRelease:l=new U(I.releaseVolEnv,c);break;case R.volEnvSustain:let y=(1e3-c)/10;l=new U(I.sustainVolEnv,y*10);break;case R.modEnvDelay:l=new U(I.delayModEnv,c);break;case R.modEnvAttack:l=new U(I.attackModEnv,c);break;case R.modEnvHold:l=new U(I.holdModEnv,c);break;case R.modEnvDecay:l=new U(I.decayModEnv,c);break;case R.modEnvRelease:l=new U(I.releaseModEnv,c);break;case R.modEnvSustain:let S=1e3-c;l=new U(I.sustainModEnv,S);break;case R.reverbSend:l=new U(I.reverbEffectsSend,c);break;case R.chorusSend:l=new U(I.chorusEffectsSend,c);break;case R.pitch:let k=Math.floor(c/100),x=Math.floor(c-k*100);l=new U(I.fineTune,x),s.push(new U(I.coarseTune,k));break}l&&s.push(l)}else{let l=!0;if(h===_.none)if(C===_.modLfo&&Q===R.pitch)s.push(new U(I.modLfoToPitch,c));else if(C===_.modLfo&&Q===R.gain)s.push(new U(I.modLfoToVolume,c));else if(C===_.modLfo&&Q===R.filterCutoff)s.push(new U(I.modLfoToFilterFc,c));else if(C===_.vibratoLfo&&Q===R.pitch)s.push(new U(I.vibLfoToPitch,c));else if(C===_.modEnv&&Q===R.pitch)s.push(new U(I.modEnvToPitch,c));else if(C===_.modEnv&&Q===R.filterCutoff)s.push(new U(I.modEnvToFilterFc,c));else if(C===_.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(C===_.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(C===_.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(C===_.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 l=!1;else l=!1;if(l===!1){let y=Vn(C,h,Q,f,c);y?(n.push(y),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):b("Failed converting to SF2 Modulator!")}}}return n.find(g=>g.modulatorDestination===I.reverbEffectsSend)===void 0&&n.push(new rA({srcEnum:219,dest:I.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(g=>g.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(e,A,t){if(e)for(;e.chunkData.currentIndexe.chunkData.currentIndex;)A.push(O(e.chunkData));let t=A.find(a=>a.header==="rgnh"),s=D(t.chunkData,2),n=D(t.chunkData,2),o=D(t.chunkData,2),g=D(t.chunkData,2),C=new je({min:s,max:n},{min:o,max:g});D(t.chunkData,2);let h=D(t.chunkData,2);h!==0&&C.generators.push(new U(I.exclusiveClass,h));let Q=yA(A,"lart"),f=yA(A,"lar2");this.readLart(Q,f,C),C.isGlobal=!1;let u=A.find(a=>a.header==="wsmp");D(u.chunkData,4);let c=D(u.chunkData,2);D(u.chunkData,2);let S=(D(u.chunkData,4)|0)/-655360*10/.4;D(u.chunkData,4);let k=D(u.chunkData,4),x,N={start:0,end:0};if(k===0)x=0;else{D(u.chunkData,4),D(u.chunkData,4)===0?x=1:x=3,N.start=D(u.chunkData,4);let sA=D(u.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 C.setWavesample(S,x,N,c,J,W),C}var ue=class{constructor(A,t,s,n,o,g,C,h){this.sampleName=A,this.sampleRate=t,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=g,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=h,this.isCompressed=(g&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,t){if(!this.isCompressed)try{this.compressedData=t([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 ue{constructor(A,t,s,n,o,g,C){super(A,t,s,n,0,1,o*2,(g-1)*2),this.sampleData=C}getAudioData(){return this.sampleData}sampleData;getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let t=0;t>8&255}return A}};function Xn(e){pA("%cLoading Wave samples...",r.recognized);let A=0;for(;e.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 C=D(n.chunkData,4);D(n.chunkData,4),D(n.chunkData,2);let h=D(n.chunkData,2),Q=h/8,f=Math.pow(2,Q*8-1),u=Math.pow(2,Q*8),c,l=!1;h===8?(c=255,l=!0):c=f;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=f&&(z-=u),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=ge(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 g=yA(s,"wvpl");this.readDLSSamples(g);let C=yA(s,"lins");if(!C)throw Z(),new Error("No lins chunk!");this.readDLSInstrumentList(C),m(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),Z()}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS soundfont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}};XA.prototype.readDLSInstrumentList=Kn;XA.prototype.readDLSInstrument=vn;XA.prototype.readRegion=Zn;XA.prototype.readLart=On;XA.prototype.readDLSSamples=Xn;var bt=class extends le{constructor(A,t,s,n,o,g,C,h,Q,f,u,c,l){super(A,g,C,h,Q,f,n-t,o-t),this.sampleName=A,this.sampleStartIndex=t,this.sampleEndIndex=s,this.isSampleLoaded=!1,this.sampleID=c,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=u,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex,this.sampleLoopEndIndex+=this.sampleStartIndex,this.sampleLength=99999999),this.isDataRaw=l}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let t=A.currentIndex;return A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t)}else{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");let t=A.currentIndex;return A.slice(t+this.sampleStartIndex,t+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,t=A.currentIndex,s=A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t);this.sampleData=new Float32Array(0);let n=VA.decode(s.buffer);this.sampleData=n.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return b("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),t=this.sampleDataArray.currentIndex,s=new Int16Array(this.sampleDataArray.slice(t+this.sampleStartIndex,t+this.sampleEndIndex).buffer);for(let n=0;ne.chunkData.currentIndex;){let o=bo(n,e.chunkData,A,t);s.push(o),n++}return s.length>1&&s.pop(),s}function bo(e,A,t,s){let n=V(A,20),o=D(A,4)*2,g=D(A,4)*2,C=D(A,4)*2,h=D(A,4)*2,Q=D(A,4),f=A[A.currentIndex++];f===255&&(f=60);let u=ms(A[A.currentIndex++]),c=D(A,2),l=D(A,2);return new bt(n,o,g,C,h,Q,f,u,c,l,t,e,s)}var Lt=class extends ce{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=D(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,t){this.instrumentZonesAmount=A;for(let s=this.instrumentZoneIndex;se.chunkData.currentIndex;){let s=new Lt(e);if(t.length>0){let n=s.instrumentZoneIndex-t[t.length-1].instrumentZoneIndex;t[t.length-1].getInstrumentZones(n,A)}t.push(s)}return t.length>1&&t.pop(),t}var Ut=class extends zA{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;ts.generatorType===I.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===I.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===I.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function zn(e,A,t,s){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Ut(e.chunkData);if(n.length>0){let g=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(g,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(t),n[n.length-1].getSample(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var Tt=class extends Qe{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;ts.generatorType===I.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===I.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===I.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function jn(e,A,t,s){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Tt(e.chunkData);if(n.length>0){let g=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(g,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(t),n[n.length-1].getInstrument(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var Ht=class extends he{constructor(A){super(),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=D(A.chunkData,2),this.bank=D(A.chunkData,2),this.presetZoneStartIndex=D(A.chunkData,2),this.library=D(A.chunkData,4),this.genre=D(A.chunkData,4),this.morphology=D(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,t){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;se.chunkData.currentIndex;){let s=new Ht(e);if(t.length>0){let n=s.presetZoneStartIndex-t[t.length-1].presetZoneStartIndex;t[t.length-1].getPresetZones(n,A)}t.push(s)}return t.length>1&&t.pop(),t}var At=class extends te{constructor(A,t=!0){if(super(),t&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new H(A),Ae("%cParsing SoundFont...",r.info),!this.dataArray)throw Z(),new TypeError("No data!");let s=O(this.dataArray,!1);this.verifyHeader(s,"riff");let n=V(this.dataArray,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw Z(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let o=n==="sfpk",g=O(this.dataArray);for(this.verifyHeader(g,"list"),V(g.chunkData,4);g.chunkData.length>g.chunkData.currentIndex;){let $=O(g.chunkData),QA;switch($.header.toLowerCase()){case"ifil":case"iver":QA=`${D($.chunkData,2)}.${D($.chunkData,2)}`;break;case"icmt":QA=V($.chunkData,$.chunkData.length,void 0,!1);break;default:QA=V($.chunkData,$.chunkData.length)}m(`%c"${$.header}": %c"${QA}"`,r.info,r.recognized),this.soundFontInfo[$.header]=QA}let C=O(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(V(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",r.warn);let h=O(this.dataArray,!1);this.verifyHeader(h,"smpl");let Q;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{Q=VA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch($){throw Z(),new Error(`SF2Pack Ogg Vorbis decode error: ${$}`)}m(`%cDecoded the smpl chunk! Length: %c${Q.length}`,r.info,r.value)}else Q=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,m("%cLoading preset data chunk...",r.warn);let f=O(this.dataArray);this.verifyHeader(f,"list"),V(f.chunkData,4);let u=O(f.chunkData);this.verifyHeader(u,"phdr");let c=O(f.chunkData);this.verifyHeader(c,"pbag");let l=O(f.chunkData);this.verifyHeader(l,"pmod");let y=O(f.chunkData);this.verifyHeader(y,"pgen");let S=O(f.chunkData);this.verifyHeader(S,"inst");let k=O(f.chunkData);this.verifyHeader(k,"ibag");let x=O(f.chunkData);this.verifyHeader(x,"imod");let N=O(f.chunkData);this.verifyHeader(N,"igen");let M=O(f.chunkData);this.verifyHeader(M,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...Wn(M,Q,!o));let W=ft(N),J=pt(x),a=zn(k,W,J,this.samples);this.instruments=_n(S,a);let sA=ft(y),K=pt(l),z=jn(c,sA,K,this.instruments);this.presets.push(...$n(u,z)),this.presets.sort(($,QA)=>$.program-QA.program+($.bank-QA.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),Z(),o&&delete this.dataArray}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw Z(),new SyntaxError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw Z(),new SyntaxError(`Invalid soundFont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Re(e){let A=e.slice(8,12),t=new H(A);return V(t,4,void 0,!1).toLowerCase()==="dls "?new XA(e):new At(e,!1)}function Ao(e,A,t=!1){let s=this.workletProcessorChannels[e];if(s===void 0){b(`Trying to access channel ${e} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[p.bankSelect],o,g;if(this.overrideSoundfont){let C=n===128?128:n-this.soundfontBankOffset,h=this.overrideSoundfont.getPresetNoFallback(C,A);h?(o=n,g=h,s.presetUsesOverride=!0):(g=this.soundfontManager.getPreset(n,A),o=g.bank,s.presetUsesOverride=!1)}else g=this.soundfontManager.getPreset(n,A),o=g.bank,s.presetUsesOverride=!1;this.setPreset(e,g),this.callEvent("programchange",{channel:e,program:g.program,bank:o,userCalled:t})}function eo(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,s=this.overrideSoundfont.getPresetNoFallback(t,A);if(s)return s}return this.soundfontManager.getPreset(e,A)}function to(e,A){if(!this.workletProcessorChannels[e].lockPreset){delete this.workletProcessorChannels[e].preset,this.workletProcessorChannels[e].preset=A,this.workletProcessorChannels[e].cachedVoices=[];for(let t=0;t<128;t++)this.workletProcessorChannels[e].cachedVoices.push([])}}function so(e,A){let t=this.workletProcessorChannels[e];t.lockPreset||t.drumChannel!==A&&(A?(t.channelTransposeKeyShift=0,t.drumChannel=!0,this.setPreset(e,this.getPreset(128,t.preset.program))):(t.drumChannel=!1,this.setPreset(e,this.getPreset(t.midiControllers[p.bankSelect],t.preset.program))),t.presetUsesOverride=!1,this.callEvent("drumchange",{channel:e,isDrumChannel:t.drumChannel}),this.sendChannelProperties())}function no(){let e=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,s=e.find(n=>n.bank===t&&n.program===A.program);s!==void 0?s.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.callEvent("presetlistchange",e)}function oo(e=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let t=0;t{this.programChange(s,t.preset.program)}),this.post({messageType:mA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",r.recognized)}function io(e,A){this.soundfontBankOffset=A,this.reloadSoundFont(e,!0),this.overrideSoundfont.samples.forEach(t=>t.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function ao(){let A={channelSnapshots:this.workletProcessorChannels.map(t=>({program:t.preset.program,bank:t.preset.bank,lockPreset:t.lockPreset,patchName:t.preset.presetName,midiControllers:t.midiControllers,lockedControllers:t.lockedControllers,customControllers:t.customControllers,channelVibrato:t.channelVibrato,lockVibrato:t.lockVibrato,channelTransposeKeyShift:t.channelTransposeKeyShift,channelOctaveTuning:t.channelOctaveTuning,keyCentTuning:t.keyCentTuning,isMuted:t.isMuted,drumChannel:t.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:mA.synthesizerSnapshot,messageData:A})}function Io(e){for(this.system=e.system,this.setMasterGain(e.mainVolume),this.setMasterPan(e.pan),this.transposeAllChannels(e.transposition),this.interpolationType=e.interpolation;this.workletProcessorChannels.length{let s=this.workletProcessorChannels[t];this.muteChannel(t,A.isMuted),this.setDrums(t,A.drumChannel),s.midiControllers=A.midiControllers,s.lockedControllers=A.lockedControllers,s.customControllers=A.customControllers,s.channelVibrato=A.channelVibrato,s.lockVibrato=A.lockVibrato,s.channelTransposeKeyShift=A.channelTransposeKeyShift,s.channelOctaveTuning=A.channelOctaveTuning,s.lockPreset=!1,s.midiControllers[p.bankSelect]=A.bank,this.programChange(t,A.program),s.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",r.info)}var et=class{constructor(A,t){this.ready=t,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(t=>{t.soundfont.setSampleIDOffset(A),A+=t.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let t=this.soundfontList.length-1;t>=0;t--){let s=this.soundfontList[t];for(let n of s.soundfont.presets){let o=`${n.bank+s.bankOffset}-${n.program}`;A[o]=n.presetName}}this.presetList=[];for(let[t,s]of Object.entries(A)){let n=t.split("-");this.presetList.push({presetName:s,program:parseInt(n[1]),bank:parseInt(n[0])})}}handleMessage(A,t){switch(A){case ie.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case ie.reloadSoundFont:this.reloadManager(t);break;case ie.deleteSoundFont:this.deleteSoundFont(t);break;case ie.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let t=Re(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:t}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){b("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(s=>s.id===A);if(t===-1){b(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[t].soundfont.presets,delete this.soundfontList[t].soundfont.instruments,delete this.soundfontList[t].soundfont.samples,this.soundfontList.splice(t,1),this.generatePresetList()}addNewSoundFont(A,t,s){if(this.soundfontList.find(n=>n.id===t)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:t,soundfont:Re(A),bankOffset:s}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((t,s)=>A.indexOf(t.id)-A.indexOf(s.id)),this.generatePresetList()}getPreset(A,t){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let s of this.soundfontList){let n=s.soundfont.getPresetNoFallback(A-s.bankOffset,t);if(n!==void 0)return n}if(A!==128){for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.program===t);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}else{for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.bank===128);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}}};var tt=class{constructor(A,t,s,n,o,g,C,h){this.sampleData=A,this.playbackStep=t,this.cursor=s,this.rootKey=n,this.loopStart=o,this.loopEnd=g,this.end=C,this.loopingMode=h}sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0},Ge=class e{constructor(A,t,s,n,o,g,C,h,Q){this.sample=t,this.generators=h,this.modulatedGenerators=new Int16Array(h),this.modulators=Q,this.velocity=n,this.midiNote=s,this.channelNumber=o,this.startTime=g,this.targetKey=C,this.volumeEnvelope=new FA(A)}sample;filter=new Be;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new UA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;static copy(A,t){let s=A.sample,n=new tt(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new e(A.volumeEnvelope.sampleRate,n,A.midiNote,A.velocity,A.channelNumber,t,A.targetKey,A.generators,A.modulators.slice())}};function go(e,A,t,s,n,o=!1){let g,C=s.cachedVoices[A][t];return C!==void 0?g=C.map(h=>Ge.copy(h,n)):(g=s.preset.getSamplesAndGenerators(A,t).reduce((Q,f)=>{if(f.sample.sampleData===void 0)return b(`Discarding invalid sample: ${f.sample.sampleName}`),Q;let u=new Int16Array(60);for(let M=0;M<60;M++)u[M]=ps(M,f.presetGenerators,f.instrumentGenerators);u[I.initialAttenuation]=Math.floor(u[I.initialAttenuation]*.4);let c=f.sample.samplePitch;u[I.overridingRootKey]>-1&&(c=u[I.overridingRootKey]);let l=A;u[I.keyNum]>-1&&(l=u[I.keyNum]);let y=f.sample.sampleLoopStartIndex/2+(u[I.startloopAddrsOffset]+u[I.startloopAddrsCoarseOffset]*32768),S=f.sample.sampleLoopEndIndex/2+(u[I.endloopAddrsOffset]+u[I.endloopAddrsCoarseOffset]*32768),k=u[I.sampleModes],x=f.sample.getAudioData().length;y=Math.min(Math.max(0,y),x),S=Math.min(Math.max(0,S),x),S-y<1&&(k=0);let N=new tt(f.sample.getAudioData(),f.sample.sampleRate/sampleRate*Math.pow(2,f.sample.samplePitchCorrection/1200),u[I.startAddrsOffset]+u[I.startAddrsCoarseOffset]*32768,c,y,S,Math.floor(f.sample.sampleData.length)-1+(u[I.endAddrOffset]+u[I.endAddrsCoarseOffset]*32768),k);return u[I.velocity]>-1&&(t=u[I.velocity]),o&&hs([{Sample:f.sample.sampleName,Generators:u,Modulators:f.modulators.map(M=>M.debugString()),Velocity:t,TargetKey:l,MidiNote:A,WorkletSample:N}]),Q.push(new Ge(sampleRate,N,A,t,e,n,l,u,f.modulators)),Q},[]),s.cachedVoices[A][t]=g.map(Q=>Ge.copy(Q,n))),g}var xt=.07,Mt=1,L=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=bA,this.interpolationType=_e.linear,this.processTickCallback=void 0,this.sequencer=new CA(this),this.transposition=0,this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Mt,this.midiVolume=1,this.voiceCap=cs,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new et(A.processorOptions.soundfont,this.postReady.bind(this))}catch(t){throw this.post({messageType:mA.soundfontError,messageData:t}),t}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let t=0;tthis.handleMessage(t.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),VA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",r.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:mA.ready,messageData:void 0})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){this.processTickCallback&&this.processTickCallback();let s=0;return this.workletProcessorChannels.forEach((n,o)=>{if(n.voices.length<1||n.isMuted)return;let g,C,h,Q,f;if(this.oneOutputMode){let c=t[0];g=o%16*2,C=c[g],h=c[g+1]}else g=o%this._outputsAmount+2,C=t[g][0],h=t[g][1],Q=t[0],f=t[1];let u=n.voices;n.voices=[],u.forEach(c=>{this.renderVoice(n,c,C,h,Q,f),c.finished||n.voices.push(c)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};L.prototype.renderVoice=Zs;L.prototype.releaseVoice=Ws;L.prototype.voiceKilling=Xs;L.prototype.getWorkletVoices=go;L.prototype.handleMessage=js;L.prototype.sendChannelProperties=An;L.prototype.callEvent=$s;L.prototype.systemExclusive=en;L.prototype.noteOn=sn;L.prototype.noteOff=nn;L.prototype.polyPressure=ln;L.prototype.killNote=on;L.prototype.stopAll=rn;L.prototype.stopAllChannels=an;L.prototype.muteChannel=Sn;L.prototype.setVibrato=Dn;L.prototype.disableAndLockVibrato=yn;L.prototype.dataEntryCoarse=kn;L.prototype.dataEntryFine=wn;L.prototype.createWorkletChannel=ys;L.prototype.controllerChange=fn;L.prototype.channelPressure=cn;L.prototype.resetAllControllers=Fn;L.prototype.resetControllers=Rn;L.prototype.resetParameters=Gn;L.prototype.setMasterGain=mn;L.prototype.setMasterPan=pn;L.prototype.setMIDIVolume=dn;L.prototype.transposeAllChannels=In;L.prototype.transposeChannel=gn;L.prototype.setChannelTuning=Cn;L.prototype.setChannelTuningSemitones=En;L.prototype.setMasterTuning=Bn;L.prototype.setModulationDepth=hn;L.prototype.pitchWheel=Qn;L.prototype.setOctaveTuning=un;L.prototype.programChange=Ao;L.prototype.getPreset=eo;L.prototype.setPreset=to;L.prototype.setDrums=so;L.prototype.reloadSoundFont=ro;L.prototype.clearSoundFont=oo;L.prototype.setEmbeddedSoundFont=io;L.prototype.sendPresetList=no;L.prototype.sendSynthesizerSnapshot=ao;L.prototype.applySynthesizerSnapshot=Io;registerProcessor(Qs,L);m("%cProcessor succesfully registered!",r.recognized); + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),Z()}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS soundfont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=Kn;WA.prototype.readDLSInstrument=vn;WA.prototype.readRegion=Zn;WA.prototype.readLart=On;WA.prototype.readDLSSamples=Xn;var bt=class extends ue{constructor(A,t,s,n,o,g,C,h,Q,f,u,c,l){super(A,g,C,h,Q,f,n-t,o-t),this.sampleName=A,this.sampleStartIndex=t,this.sampleEndIndex=s,this.isSampleLoaded=!1,this.sampleID=c,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=u,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex,this.sampleLoopEndIndex+=this.sampleStartIndex,this.sampleLength=99999999),this.isDataRaw=l}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let t=A.currentIndex;return A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t)}else{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");let t=A.currentIndex;return A.slice(t+this.sampleStartIndex,t+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,t=A.currentIndex,s=A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t);this.sampleData=new Float32Array(0);let n=OA.decode(s.buffer);this.sampleData=n.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return b("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),t=this.sampleDataArray.currentIndex,s=new Int16Array(this.sampleDataArray.slice(t+this.sampleStartIndex,t+this.sampleEndIndex).buffer);for(let n=0;ne.chunkData.currentIndex;){let o=bo(n,e.chunkData,A,t);s.push(o),n++}return s.length>1&&s.pop(),s}function bo(e,A,t,s){let n=V(A,20),o=D(A,4)*2,g=D(A,4)*2,C=D(A,4)*2,h=D(A,4)*2,Q=D(A,4),f=A[A.currentIndex++];f===255&&(f=60);let u=ms(A[A.currentIndex++]),c=D(A,2),l=D(A,2);return new bt(n,o,g,C,h,Q,f,u,c,l,t,e,s)}var Lt=class extends le{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=D(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,t){this.instrumentZonesAmount=A;for(let s=this.instrumentZoneIndex;se.chunkData.currentIndex;){let s=new Lt(e);if(t.length>0){let n=s.instrumentZoneIndex-t[t.length-1].instrumentZoneIndex;t[t.length-1].getInstrumentZones(n,A)}t.push(s)}return t.length>1&&t.pop(),t}var Ut=class extends jA{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;ts.generatorType===I.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===I.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===I.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function zn(e,A,t,s){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Ut(e.chunkData);if(n.length>0){let g=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(g,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(t),n[n.length-1].getSample(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var Tt=class extends ce{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;ts.generatorType===I.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===I.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===I.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function jn(e,A,t,s){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Tt(e.chunkData);if(n.length>0){let g=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(g,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(t),n[n.length-1].getInstrument(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var Ht=class extends Qe{constructor(A){super(),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=D(A.chunkData,2),this.bank=D(A.chunkData,2),this.presetZoneStartIndex=D(A.chunkData,2),this.library=D(A.chunkData,4),this.genre=D(A.chunkData,4),this.morphology=D(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,t){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;se.chunkData.currentIndex;){let s=new Ht(e);if(t.length>0){let n=s.presetZoneStartIndex-t[t.length-1].presetZoneStartIndex;t[t.length-1].getPresetZones(n,A)}t.push(s)}return t.length>1&&t.pop(),t}var At=class extends se{constructor(A,t=!0){if(super(),t&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new H(A),ee("%cParsing SoundFont...",r.info),!this.dataArray)throw Z(),new TypeError("No data!");let s=O(this.dataArray,!1);this.verifyHeader(s,"riff");let n=V(this.dataArray,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw Z(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let o=n==="sfpk",g=O(this.dataArray);for(this.verifyHeader(g,"list"),V(g.chunkData,4);g.chunkData.length>g.chunkData.currentIndex;){let $=O(g.chunkData),QA;switch($.header.toLowerCase()){case"ifil":case"iver":QA=`${D($.chunkData,2)}.${D($.chunkData,2)}`;break;case"icmt":QA=V($.chunkData,$.chunkData.length,void 0,!1);break;default:QA=V($.chunkData,$.chunkData.length)}m(`%c"${$.header}": %c"${QA}"`,r.info,r.recognized),this.soundFontInfo[$.header]=QA}let C=O(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(V(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",r.warn);let h=O(this.dataArray,!1);this.verifyHeader(h,"smpl");let Q;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{Q=OA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch($){throw Z(),new Error(`SF2Pack Ogg Vorbis decode error: ${$}`)}m(`%cDecoded the smpl chunk! Length: %c${Q.length}`,r.info,r.value)}else Q=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,m("%cLoading preset data chunk...",r.warn);let f=O(this.dataArray);this.verifyHeader(f,"list"),V(f.chunkData,4);let u=O(f.chunkData);this.verifyHeader(u,"phdr");let c=O(f.chunkData);this.verifyHeader(c,"pbag");let l=O(f.chunkData);this.verifyHeader(l,"pmod");let y=O(f.chunkData);this.verifyHeader(y,"pgen");let S=O(f.chunkData);this.verifyHeader(S,"inst");let k=O(f.chunkData);this.verifyHeader(k,"ibag");let x=O(f.chunkData);this.verifyHeader(x,"imod");let N=O(f.chunkData);this.verifyHeader(N,"igen");let M=O(f.chunkData);this.verifyHeader(M,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...Wn(M,Q,!o));let W=ft(N),J=pt(x),a=zn(k,W,J,this.samples);this.instruments=_n(S,a);let sA=ft(y),K=pt(l),z=jn(c,sA,K,this.instruments);this.presets.push(...$n(u,z)),this.presets.sort(($,QA)=>$.program-QA.program+($.bank-QA.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),Z(),o&&delete this.dataArray}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw Z(),new SyntaxError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw Z(),new SyntaxError(`Invalid soundFont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Re(e){let A=e.slice(8,12),t=new H(A);return V(t,4,void 0,!1).toLowerCase()==="dls "?new WA(e):new At(e,!1)}function Ao(e,A,t=!1){let s=this.workletProcessorChannels[e];if(s===void 0){b(`Trying to access channel ${e} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[p.bankSelect],o,g;if(this.overrideSoundfont){let C=n===128?128:n-this.soundfontBankOffset,h=this.overrideSoundfont.getPresetNoFallback(C,A);h?(o=n,g=h,s.presetUsesOverride=!0):(g=this.soundfontManager.getPreset(n,A),o=g.bank,s.presetUsesOverride=!1)}else g=this.soundfontManager.getPreset(n,A),o=g.bank,s.presetUsesOverride=!1;this.setPreset(e,g),this.callEvent("programchange",{channel:e,program:g.program,bank:o,userCalled:t})}function eo(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,s=this.overrideSoundfont.getPresetNoFallback(t,A);if(s)return s}return this.soundfontManager.getPreset(e,A)}function to(e,A){if(!this.workletProcessorChannels[e].lockPreset){delete this.workletProcessorChannels[e].preset,this.workletProcessorChannels[e].preset=A,this.workletProcessorChannels[e].cachedVoices=[];for(let t=0;t<128;t++)this.workletProcessorChannels[e].cachedVoices.push([])}}function so(e,A){let t=this.workletProcessorChannels[e];t.lockPreset||t.drumChannel!==A&&(A?(t.channelTransposeKeyShift=0,t.drumChannel=!0,this.setPreset(e,this.getPreset(128,t.preset.program))):(t.drumChannel=!1,this.setPreset(e,this.getPreset(t.midiControllers[p.bankSelect],t.preset.program))),t.presetUsesOverride=!1,this.callEvent("drumchange",{channel:e,isDrumChannel:t.drumChannel}),this.sendChannelProperties())}function no(){let e=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,s=e.find(n=>n.bank===t&&n.program===A.program);s!==void 0?s.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.callEvent("presetlistchange",e)}function oo(e=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let t=0;t{this.programChange(s,t.preset.program)}),this.post({messageType:mA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",r.recognized)}function io(e,A){this.soundfontBankOffset=A,this.reloadSoundFont(e,!0),this.overrideSoundfont.samples.forEach(t=>t.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function ao(){let A={channelSnapshots:this.workletProcessorChannels.map(t=>({program:t.preset.program,bank:t.preset.bank,lockPreset:t.lockPreset,patchName:t.preset.presetName,midiControllers:t.midiControllers,lockedControllers:t.lockedControllers,customControllers:t.customControllers,channelVibrato:t.channelVibrato,lockVibrato:t.lockVibrato,channelTransposeKeyShift:t.channelTransposeKeyShift,channelOctaveTuning:t.channelOctaveTuning,keyCentTuning:t.keyCentTuning,isMuted:t.isMuted,drumChannel:t.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:mA.synthesizerSnapshot,messageData:A})}function Io(e){for(this.system=e.system,this.setMasterGain(e.mainVolume),this.setMasterPan(e.pan),this.transposeAllChannels(e.transposition),this.interpolationType=e.interpolation;this.workletProcessorChannels.length{let s=this.workletProcessorChannels[t];this.muteChannel(t,A.isMuted),this.setDrums(t,A.drumChannel),s.midiControllers=A.midiControllers,s.lockedControllers=A.lockedControllers,s.customControllers=A.customControllers,s.channelVibrato=A.channelVibrato,s.lockVibrato=A.lockVibrato,s.channelTransposeKeyShift=A.channelTransposeKeyShift,s.channelOctaveTuning=A.channelOctaveTuning,s.lockPreset=!1,s.midiControllers[p.bankSelect]=A.bank,this.programChange(t,A.program),s.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",r.info)}var et=class{constructor(A,t){this.ready=t,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(t=>{t.soundfont.setSampleIDOffset(A),A+=t.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let t=this.soundfontList.length-1;t>=0;t--){let s=this.soundfontList[t];for(let n of s.soundfont.presets){let o=`${n.bank+s.bankOffset}-${n.program}`;A[o]=n.presetName}}this.presetList=[];for(let[t,s]of Object.entries(A)){let n=t.split("-");this.presetList.push({presetName:s,program:parseInt(n[1]),bank:parseInt(n[0])})}}handleMessage(A,t){switch(A){case ae.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case ae.reloadSoundFont:this.reloadManager(t);break;case ae.deleteSoundFont:this.deleteSoundFont(t);break;case ae.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let t=Re(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:t}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){b("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(s=>s.id===A);if(t===-1){b(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[t].soundfont.presets,delete this.soundfontList[t].soundfont.instruments,delete this.soundfontList[t].soundfont.samples,this.soundfontList.splice(t,1),this.generatePresetList()}addNewSoundFont(A,t,s){if(this.soundfontList.find(n=>n.id===t)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:t,soundfont:Re(A),bankOffset:s}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((t,s)=>A.indexOf(t.id)-A.indexOf(s.id)),this.generatePresetList()}getPreset(A,t){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let s of this.soundfontList){let n=s.soundfont.getPresetNoFallback(A-s.bankOffset,t);if(n!==void 0)return n}if(A!==128){for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.program===t);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}else{for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.bank===128);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}}};var tt=class{constructor(A,t,s,n,o,g,C,h){this.sampleData=A,this.playbackStep=t,this.cursor=s,this.rootKey=n,this.loopStart=o,this.loopEnd=g,this.end=C,this.loopingMode=h}sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0},Ge=class e{constructor(A,t,s,n,o,g,C,h,Q){this.sample=t,this.generators=h,this.modulatedGenerators=new Int16Array(h),this.modulators=Q,this.velocity=n,this.midiNote=s,this.channelNumber=o,this.startTime=g,this.targetKey=C,this.volumeEnvelope=new RA(A)}sample;filter=new he;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new TA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;static copy(A,t){let s=A.sample,n=new tt(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new e(A.volumeEnvelope.sampleRate,n,A.midiNote,A.velocity,A.channelNumber,t,A.targetKey,A.generators,A.modulators.slice())}};function go(e,A,t,s,n,o=!1){let g,C=s.cachedVoices[A][t];return C!==void 0?g=C.map(h=>Ge.copy(h,n)):(g=s.preset.getSamplesAndGenerators(A,t).reduce((Q,f)=>{if(f.sample.sampleData===void 0)return b(`Discarding invalid sample: ${f.sample.sampleName}`),Q;let u=new Int16Array(60);for(let M=0;M<60;M++)u[M]=ps(M,f.presetGenerators,f.instrumentGenerators);u[I.initialAttenuation]=Math.floor(u[I.initialAttenuation]*.4);let c=f.sample.samplePitch;u[I.overridingRootKey]>-1&&(c=u[I.overridingRootKey]);let l=A;u[I.keyNum]>-1&&(l=u[I.keyNum]);let y=f.sample.sampleLoopStartIndex/2+(u[I.startloopAddrsOffset]+u[I.startloopAddrsCoarseOffset]*32768),S=f.sample.sampleLoopEndIndex/2+(u[I.endloopAddrsOffset]+u[I.endloopAddrsCoarseOffset]*32768),k=u[I.sampleModes],x=f.sample.getAudioData().length;y=Math.min(Math.max(0,y),x),S=Math.min(Math.max(0,S),x),S-y<1&&(k=0);let N=new tt(f.sample.getAudioData(),f.sample.sampleRate/sampleRate*Math.pow(2,f.sample.samplePitchCorrection/1200),u[I.startAddrsOffset]+u[I.startAddrsCoarseOffset]*32768,c,y,S,Math.floor(f.sample.sampleData.length)-1+(u[I.endAddrOffset]+u[I.endAddrsCoarseOffset]*32768),k);return u[I.velocity]>-1&&(t=u[I.velocity]),o&&hs([{Sample:f.sample.sampleName,Generators:u,Modulators:f.modulators.map(M=>M.debugString()),Velocity:t,TargetKey:l,MidiNote:A,WorkletSample:N}]),Q.push(new Ge(sampleRate,N,A,t,e,n,l,u,f.modulators)),Q},[]),s.cachedVoices[A][t]=g.map(Q=>Ge.copy(Q,n))),g}var xt=.07,Mt=1,L=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=LA,this.interpolationType=_e.linear,this.processTickCallback=void 0,this.sequencer=new CA(this),this.transposition=0,this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Mt,this.midiVolume=1,this.voiceCap=cs,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new et(A.processorOptions.soundfont,this.postReady.bind(this))}catch(t){throw this.post({messageType:mA.soundfontError,messageData:t}),t}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let t=0;tthis.handleMessage(t.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),OA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",r.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:mA.ready,messageData:void 0})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){this.processTickCallback&&this.processTickCallback();let s=0;return this.workletProcessorChannels.forEach((n,o)=>{if(n.voices.length<1||n.isMuted)return;let g,C,h,Q,f;if(this.oneOutputMode){let c=t[0];g=o%16*2,C=c[g],h=c[g+1]}else g=o%this._outputsAmount+2,C=t[g][0],h=t[g][1],Q=t[0],f=t[1];let u=n.voices;n.voices=[],u.forEach(c=>{this.renderVoice(n,c,C,h,Q,f),c.finished||n.voices.push(c)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};L.prototype.renderVoice=Zs;L.prototype.releaseVoice=Ws;L.prototype.voiceKilling=Xs;L.prototype.getWorkletVoices=go;L.prototype.handleMessage=js;L.prototype.sendChannelProperties=An;L.prototype.callEvent=$s;L.prototype.systemExclusive=en;L.prototype.noteOn=sn;L.prototype.noteOff=nn;L.prototype.polyPressure=ln;L.prototype.killNote=on;L.prototype.stopAll=rn;L.prototype.stopAllChannels=an;L.prototype.muteChannel=Sn;L.prototype.setVibrato=Dn;L.prototype.disableAndLockVibrato=yn;L.prototype.dataEntryCoarse=kn;L.prototype.dataEntryFine=wn;L.prototype.createWorkletChannel=ys;L.prototype.controllerChange=fn;L.prototype.channelPressure=cn;L.prototype.resetAllControllers=Fn;L.prototype.resetControllers=Rn;L.prototype.resetParameters=Gn;L.prototype.setMasterGain=mn;L.prototype.setMasterPan=pn;L.prototype.setMIDIVolume=dn;L.prototype.transposeAllChannels=In;L.prototype.transposeChannel=gn;L.prototype.setChannelTuning=Cn;L.prototype.setChannelTuningSemitones=En;L.prototype.setMasterTuning=Bn;L.prototype.setModulationDepth=hn;L.prototype.pitchWheel=Qn;L.prototype.setOctaveTuning=un;L.prototype.programChange=Ao;L.prototype.getPreset=eo;L.prototype.setPreset=to;L.prototype.setDrums=so;L.prototype.reloadSoundFont=ro;L.prototype.clearSoundFont=oo;L.prototype.setEmbeddedSoundFont=io;L.prototype.sendPresetList=no;L.prototype.sendSynthesizerSnapshot=ao;L.prototype.applySynthesizerSnapshot=Io;registerProcessor(Qs,L);m("%cProcessor succesfully registered!",r.recognized); diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/volume_envelope.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/volume_envelope.js index 7f559174..39a0414a 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/volume_envelope.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/volume_envelope.js @@ -56,7 +56,7 @@ export class WorkletVolumeEnvelope * The dB attenuation of the envelope when it entered the release stage * @type {number} */ - releaseStartDb = 100; + releaseStartDb = DB_SILENCE; /** * The time in samples relative to the start of the envelope * @type {number} @@ -158,16 +158,16 @@ export class WorkletVolumeEnvelope const env = voice.volumeEnvelope; const timecentsToSamples = tc => { - return Math.floor(timecentsToSeconds(tc) * env.sampleRate); + return Math.max(0, Math.floor(timecentsToSeconds(tc) * env.sampleRate)); } // calculate absolute times (they can change so we have to recalculate every time env.attenuationTarget = Math.max(0, Math.min(voice.modulatedGenerators[generatorTypes.initialAttenuation], 1440)) / 10; // divide by ten to get decibels - env.sustainDbRelative = Math.min(100, voice.modulatedGenerators[generatorTypes.sustainVolEnv] / 10); + env.sustainDbRelative = Math.min(DB_SILENCE, voice.modulatedGenerators[generatorTypes.sustainVolEnv] / 10); if(setupInterpolated) { env.attenuation = env.attenuationTarget; } - const sustainDb = Math.min(100, env.sustainDbRelative + env.attenuation); + const sustainDb = Math.min(DB_SILENCE, env.sustainDbRelative + env.attenuation); // calculate durations env.attackDuration = timecentsToSamples(voice.modulatedGenerators[generatorTypes.attackVolEnv]); @@ -177,7 +177,7 @@ export class WorkletVolumeEnvelope // (changing from attenuation to sustain instead of -100dB) const fullChange = voice.modulatedGenerators[generatorTypes.decayVolEnv]; const keyNumAddition = (60 - voice.targetKey) * voice.modulatedGenerators[generatorTypes.keyNumToVolEnvDecay]; - const fraction = (sustainDb - env.attenuation) / 100; + const fraction = (sustainDb - env.attenuation) / DB_SILENCE; env.decayDuration = timecentsToSamples(fullChange + keyNumAddition) * fraction; env.releaseDuration = timecentsToSamples(voice.modulatedGenerators[generatorTypes.releaseVolEnv]); @@ -204,7 +204,12 @@ export class WorkletVolumeEnvelope // check if voice is in release if(voice.isInRelease) { - const sustainDb = Math.min(100, env.sustainDbRelative + env.attenuation); + // no interpolation this time: force update to actual attenuation and calculate release start from there + env.attenuation = Math.min(DB_SILENCE, env.attenuationTarget); + const sustainDb = Math.max(0, Math.min(DB_SILENCE, env.sustainDbRelative + env.attenuation)); + const fraction = (sustainDb - env.attenuation) / DB_SILENCE; + env.decayDuration = timecentsToSamples(fullChange + keyNumAddition) * fraction; + switch (env.state) { case 0: @@ -239,7 +244,7 @@ export class WorkletVolumeEnvelope default: env.releaseStartDb = env.currentAttenuationDb; } - env.releaseStartDb = Math.min(env.releaseStartDb, DB_SILENCE); + env.releaseStartDb = Math.max(0, Math.min(env.releaseStartDb, DB_SILENCE)); if(env.releaseStartDb >= PERCEIVED_DB_SILENCE) { voice.finished = true; @@ -364,7 +369,7 @@ export class WorkletVolumeEnvelope // attenuation interpolation env.attenuation += (env.attenuationTarget - env.attenuation) * attenuationSmoothing; - const sustainDb = Math.min(100, env.sustainDbRelative + env.attenuation); + const sustainDb = Math.min(DB_SILENCE, env.sustainDbRelative + env.attenuation); env.currentAttenuationDb = (1 - (env.decayEnd - env.currentSampleTime) / env.decayDuration) * (sustainDb - env.attenuation) + env.attenuation; audioBuffer[filledBuffer] *= decibelAttenuationToGain(env.currentAttenuationDb + decibelOffset); @@ -383,7 +388,7 @@ export class WorkletVolumeEnvelope { // attenuation interpolation env.attenuation += (env.attenuationTarget - env.attenuation) * attenuationSmoothing; - const sustainDb = Math.min(100, env.sustainDbRelative + env.attenuation); + const sustainDb = Math.min(DB_SILENCE, env.sustainDbRelative + env.attenuation); audioBuffer[filledBuffer] *= decibelAttenuationToGain(sustainDb + decibelOffset); env.currentAttenuationDb = sustainDb;