diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index 5db2a915..ee3a879f 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -1,4 +1,4 @@ -var Bn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>(typeof require<"u"?require:A)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Y=class extends Uint8Array{currentIndex;constructor(A){super(A),this.currentIndex=0}};function ke(t){let A=t.reduce((s,o)=>s+o.length,0),e=new Y(A),n=0;for(let s of t)e.set(s,n),n+=s.length;return e}function mt(t){t=Math.floor(t);let A=Math.floor(t/60),e=Math.round(t-A*60);return{minutes:A,seconds:e,time:`${A.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}}function hn(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function uA(t){let A="";for(let e=0;e=128&&A<=224&&(n=e,s=A),{status:s,channel:n}}var m={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,reverbDepth:91,tremoloDepth:92,chorusDepth:93,detuneDepth:94,phaserDepth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},cn={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var eA={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},ge={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},UA=-1,pA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var ln=!1,un=!0,qe=!1,dn=!0;function fn(t,A,e,n){ln=t,un=A,qe=e,dn=n}function p(...t){ln&&console.info(...t)}function T(...t){un&&console.warn(...t)}function mn(...t){dn&&console.table(...t)}function te(...t){qe&&console.group(...t)}function yA(...t){qe&&console.groupCollapsed(...t)}function Z(){qe&&console.groupEnd()}var Ce={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var g={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},U=[];U[g.startAddrsOffset]={min:0,max:32768,def:0};U[g.endAddrOffset]={min:-32768,max:32768,def:0};U[g.startloopAddrsOffset]={min:-32768,max:32768,def:0};U[g.endloopAddrsOffset]={min:-32768,max:32768,def:0};U[g.startAddrsCoarseOffset]={min:0,max:32768,def:0};U[g.modLfoToPitch]={min:-12e3,max:12e3,def:0};U[g.vibLfoToPitch]={min:-12e3,max:12e3,def:0};U[g.modEnvToPitch]={min:-12e3,max:12e3,def:0};U[g.initialFilterFc]={min:1500,max:13500,def:13500};U[g.initialFilterQ]={min:0,max:960,def:0};U[g.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};U[g.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};U[g.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[g.modLfoToVolume]={min:-960,max:960,def:0};U[g.chorusEffectsSend]={min:0,max:1e3,def:0};U[g.reverbEffectsSend]={min:0,max:1e3,def:0};U[g.pan]={min:-500,max:500,def:0};U[g.delayModLFO]={min:-12e3,max:5e3,def:-12e3};U[g.freqModLFO]={min:-16e3,max:4500,def:0};U[g.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};U[g.freqVibLFO]={min:-16e3,max:4500,def:0};U[g.delayModEnv]={min:-32768,max:5e3,def:-32768};U[g.attackModEnv]={min:-32768,max:8e3,def:-32768};U[g.holdModEnv]={min:-12e3,max:5e3,def:-12e3};U[g.decayModEnv]={min:-12e3,max:8e3,def:-12e3};U[g.sustainModEnv]={min:0,max:1e3,def:0};U[g.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};U[g.keyNumToModEnvHold]={min:-1200,max:1200,def:0};U[g.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};U[g.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};U[g.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};U[g.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};U[g.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};U[g.sustainVolEnv]={min:0,max:1440,def:0};U[g.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};U[g.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};U[g.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};U[g.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[g.keyNum]={min:-1,max:127,def:-1};U[g.velocity]={min:-1,max:127,def:-1};U[g.initialAttenuation]={min:-250,max:1440,def:0};U[g.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[g.coarseTune]={min:-120,max:120,def:0};U[g.fineTune]={min:-12700,max:12700,def:0};U[g.scaleTuning]={min:0,max:1200,def:100};U[g.exclusiveClass]={min:0,max:99999,def:0};U[g.overridingRootKey]={min:-1,max:127,def:-1};var L=class{generatorType=g.INVALID;generatorValue=0;constructor(A=g.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let n=U[A];this.generatorValue=Math.round(e),n!==void 0&&(this.generatorValue=Math.max(n.min,Math.min(n.max,this.generatorValue)))}};function pn(t,A,e){let n=U[t]||{min:0,max:32768,def:0},s=A.find(B=>B.generatorType===t),o=0;s&&(o=s.generatorValue);let I=e.find(B=>B.generatorType===t),C=n.def;I&&(C=I.generatorValue);let Q=C+o;return t===g.initialAttenuation?Q:Math.max(n.min,Math.min(n.max,Q))}var K={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},cA={linear:0,concave:1,convex:2,switch:3},j=class t{currentValue=0;constructor(A){this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform,this.modulatorDestination>58&&(this.modulatorDestination=g.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(A){return new t({srcEnum:A.sourceEnum,secSrcEnum:A.secondarySourceEnum,transform:A.transformType,amt:A.transformAmount,dest:A.modulatorDestination})}static isIdentical(A,e){return A.sourceEnum===e.sourceEnum&&A.modulatorDestination===e.modulatorDestination&&A.secondarySourceEnum===e.secondarySourceEnum&&A.transformType===e.transformType}sumTransform(A){return new t({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(s,o){return Object.keys(s).find(I=>s[I]===o)}let e=A(cA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(m,this.sourceIndex):e+=A(K,this.sourceIndex);let n=A(cA,this.secSrcCurveType);return n+=this.secSrcPolarity===0?" unipolar ":" bipolar ",n+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?n+=A(m,this.secSrcIndex):n+=A(K,this.secSrcIndex),`Modulator: +var Bn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>(typeof require<"u"?require:A)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Y=class extends Uint8Array{currentIndex;constructor(A){super(A),this.currentIndex=0}};function ke(t){let A=t.reduce((s,o)=>s+o.length,0),e=new Y(A),n=0;for(let s of t)e.set(s,n),n+=s.length;return e}function mt(t){t=Math.floor(t);let A=Math.floor(t/60),e=Math.round(t-A*60);return{minutes:A,seconds:e,time:`${A.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}}function hn(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function uA(t){let A="";for(let e=0;e=128&&A<=224&&(n=e,s=A),{status:s,channel:n}}var m={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,reverbDepth:91,tremoloDepth:92,chorusDepth:93,detuneDepth:94,phaserDepth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},cn={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var eA={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},ge={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},TA=-1,pA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var ln=!1,un=!0,qe=!1,dn=!0;function fn(t,A,e,n){ln=t,un=A,qe=e,dn=n}function p(...t){ln&&console.info(...t)}function T(...t){un&&console.warn(...t)}function mn(...t){dn&&console.table(...t)}function te(...t){qe&&console.group(...t)}function yA(...t){qe&&console.groupCollapsed(...t)}function Z(){qe&&console.groupEnd()}var Ce={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var g={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},U=[];U[g.startAddrsOffset]={min:0,max:32768,def:0};U[g.endAddrOffset]={min:-32768,max:32768,def:0};U[g.startloopAddrsOffset]={min:-32768,max:32768,def:0};U[g.endloopAddrsOffset]={min:-32768,max:32768,def:0};U[g.startAddrsCoarseOffset]={min:0,max:32768,def:0};U[g.modLfoToPitch]={min:-12e3,max:12e3,def:0};U[g.vibLfoToPitch]={min:-12e3,max:12e3,def:0};U[g.modEnvToPitch]={min:-12e3,max:12e3,def:0};U[g.initialFilterFc]={min:1500,max:13500,def:13500};U[g.initialFilterQ]={min:0,max:960,def:0};U[g.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};U[g.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};U[g.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[g.modLfoToVolume]={min:-960,max:960,def:0};U[g.chorusEffectsSend]={min:0,max:1e3,def:0};U[g.reverbEffectsSend]={min:0,max:1e3,def:0};U[g.pan]={min:-500,max:500,def:0};U[g.delayModLFO]={min:-12e3,max:5e3,def:-12e3};U[g.freqModLFO]={min:-16e3,max:4500,def:0};U[g.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};U[g.freqVibLFO]={min:-16e3,max:4500,def:0};U[g.delayModEnv]={min:-32768,max:5e3,def:-32768};U[g.attackModEnv]={min:-32768,max:8e3,def:-32768};U[g.holdModEnv]={min:-12e3,max:5e3,def:-12e3};U[g.decayModEnv]={min:-12e3,max:8e3,def:-12e3};U[g.sustainModEnv]={min:0,max:1e3,def:0};U[g.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};U[g.keyNumToModEnvHold]={min:-1200,max:1200,def:0};U[g.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};U[g.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};U[g.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};U[g.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};U[g.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};U[g.sustainVolEnv]={min:0,max:1440,def:0};U[g.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};U[g.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};U[g.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};U[g.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[g.keyNum]={min:-1,max:127,def:-1};U[g.velocity]={min:-1,max:127,def:-1};U[g.initialAttenuation]={min:-250,max:1440,def:0};U[g.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};U[g.coarseTune]={min:-120,max:120,def:0};U[g.fineTune]={min:-12700,max:12700,def:0};U[g.scaleTuning]={min:0,max:1200,def:100};U[g.exclusiveClass]={min:0,max:99999,def:0};U[g.overridingRootKey]={min:-1,max:127,def:-1};var L=class{generatorType=g.INVALID;generatorValue=0;constructor(A=g.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let n=U[A];this.generatorValue=Math.round(e),n!==void 0&&(this.generatorValue=Math.max(n.min,Math.min(n.max,this.generatorValue)))}};function pn(t,A,e){let n=U[t]||{min:0,max:32768,def:0},s=A.find(B=>B.generatorType===t),o=0;s&&(o=s.generatorValue);let I=e.find(B=>B.generatorType===t),C=n.def;I&&(C=I.generatorValue);let Q=C+o;return t===g.initialAttenuation?Q:Math.max(n.min,Math.min(n.max,Q))}var K={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},cA={linear:0,concave:1,convex:2,switch:3},j=class t{currentValue=0;constructor(A){this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform,this.modulatorDestination>58&&(this.modulatorDestination=g.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(A){return new t({srcEnum:A.sourceEnum,secSrcEnum:A.secondarySourceEnum,transform:A.transformType,amt:A.transformAmount,dest:A.modulatorDestination})}static isIdentical(A,e){return A.sourceEnum===e.sourceEnum&&A.modulatorDestination===e.modulatorDestination&&A.secondarySourceEnum===e.secondarySourceEnum&&A.transformType===e.transformType}sumTransform(A){return new t({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(s,o){return Object.keys(s).find(I=>s[I]===o)}let e=A(cA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(m,this.sourceIndex):e+=A(K,this.sourceIndex);let n=A(cA,this.secSrcCurveType);return n+=this.secSrcPolarity===0?" unipolar ":" bipolar ",n+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?n+=A(m,this.secSrcIndex):n+=A(K,this.secSrcIndex),`Modulator: Source: ${e} Secondary source: ${n} Destination: ${A(g,this.modulatorDestination)} @@ -6,13 +6,13 @@ var Bn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>( Transform type: ${this.transformType} -`}},pt=960,yt=cA.concave;function TA(t,A,e,n,s){return t<<10|A<<9|e<<8|n<<7|s}var Pe=[new j({srcEnum:TA(yt,0,1,0,K.noteOnVelocity),dest:g.initialAttenuation,amt:pt,secSrcEnum:0,transform:0}),new j({srcEnum:129,dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new j({srcEnum:TA(yt,0,1,1,m.mainVolume),dest:g.initialAttenuation,amt:pt,secSrcEnum:0,transform:0}),new j({srcEnum:13,dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new j({srcEnum:526,dest:g.fineTune,amt:12700,secSrcEnum:16,transform:0}),new j({srcEnum:650,dest:g.pan,amt:500,secSrcEnum:0,transform:0}),new j({srcEnum:TA(yt,0,1,1,m.expressionController),dest:g.initialAttenuation,amt:pt,secSrcEnum:0,transform:0}),new j({srcEnum:219,dest:g.reverbEffectsSend,amt:750,secSrcEnum:0,transform:0}),new j({srcEnum:221,dest:g.chorusEffectsSend,amt:750,secSrcEnum:0,transform:0}),new j({srcEnum:TA(cA.linear,0,0,0,K.polyPressure),dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new j({srcEnum:TA(cA.linear,0,0,1,m.tremoloDepth),dest:g.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new j({srcEnum:TA(cA.linear,1,0,1,m.releaseTime),dest:g.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new j({srcEnum:TA(cA.linear,1,0,1,m.brightness),dest:g.initialFilterFc,amt:6e3,secSrcEnum:0,transform:0}),new j({srcEnum:TA(cA.linear,1,0,1,m.timbreHarmonicContent),dest:g.initialFilterQ,amt:250,secSrcEnum:0,transform:0})];var EA=128,Ke=147,St=new Int16Array(Ke).fill(0),dA=(t,A)=>St[t]=A<<7;dA(m.mainVolume,100);dA(m.balance,64);dA(m.expressionController,127);dA(m.pan,64);dA(m.timbreHarmonicContent,64);dA(m.releaseTime,64);dA(m.attackTime,64);dA(m.brightness,64);dA(m.soundController6,64);dA(m.soundController7,64);dA(m.soundController8,64);dA(m.soundController9,64);dA(m.generalPurposeController6,64);dA(m.generalPurposeController8,64);dA(EA+K.pitchWheel,64);dA(EA+K.pitchWheelRange,2);var gA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Dt=Object.keys(gA).length,kt=new Float32Array(Dt);kt[gA.modulationMultiplier]=1;var fA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6};function yn(t=!1){let A={midiControllers:new Int16Array(Ke),lockedControllers:Array(Ke).fill(!1),customControllers:new Float32Array(Dt),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:fA.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},velocityOverride:0,lockGSNRPNParams:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let e=0;e<128;e++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),t&&this.callEvent("newchannel",void 0)}var wt={velocityOverride:128};var Sn="spessasynth-worklet-system",Dn=350,SA=9,Ve=16,Oe="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(t,A){let e=0;for(let n=8*(A-1);n>=0;n-=8)e|=t[t.currentIndex++]<>>0}function kn(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=we(t.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=n,e.status){case F.noteOn:let s=t.messageData[1];if(s>0)this.synth.noteOn(e.channel,t.messageData[0],s),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:s});else{this.synth.noteOff(e.channel,t.messageData[0]);let I=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);I!==-1&&this.playingNotes.splice(I,1)}break;case F.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(I=>I.midiNote===t.messageData[0]&&I.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case F.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case F.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case F.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case F.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case F.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case F.systemExclusive:this.synth.systemExclusive(t.messageData,n);break;case F.setTempo:this.oneTickToSeconds=60/(No(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),T("invalid tempo! falling back to 120 BPM"));break;case F.timeSignature:case F.endOfTrack:case F.midiChannelPrefix:case F.songPosition:case F.activeSensing:case F.keySignature:case F.sequenceNumber:case F.sequenceSpecific:break;case F.text:case F.lyric:case F.copyright:case F.trackName:case F.marker:case F.cuePoint:case F.instrumentName:case F.programName:this.post(wA.textEvent,[t.messageData,e.status]);break;case F.midiPort:this.assignMIDIPort(A,t.messageData[0]);break;case F.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:T(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(F).find(I=>F[I]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function wn(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function No(t){return t.messageData.currentIndex=0,6e7/zA(t.messageData,3)}function Fn(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(n.ticks-e.ticks),this.midiData.loop.end<=e.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function Rn(){let t=0,A=1/0;return this.tracks.forEach((e,n)=>{this.eventIndex[n]>=e.length||e[this.eventIndex[n]].ticks>>0}function Ee(t,A,e){for(let n=0;n>n*8&255}function J(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function lA(t,A){Ee(t,A,4)}function jA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function Gn(t){return t>127?t-256:t}function V(t,A,e=void 0,n=!0){if(e){let s=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(s.buffer)}else{let s=!1,o="";for(let I=0;I127){if(n){s=!0;continue}else if(C===0){s=!0;continue}}o+=String.fromCharCode(C)}}return o}}function FA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let n=0;nA.length)for(let n=0;ne.header!=="LIST"?!1:(e.chunkData.currentIndex=0,V(e.chunkData,4)===A))}function Xe(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var We={name:"INAM",album:"IPRD",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"};var _e=class{constructor(){this.timeDivision=0,this.duration=0,this.tempoChanges=[{ticks:0,tempo:120}],this.copyright="",this.tracksAmount=0,this.lyrics=[],this.firstNoteOn=0,this.keyRange={min:0,max:127},this.lastVoiceEventTick=0,this.midiPorts=[0],this.midiPortChannelOffsets=[0],this.usedChannelsOnTrack=[],this.loop={start:0,end:0},this.midiName="",this.fileName="",this.rawMidiName=void 0,this.embeddedSoundFont=void 0,this.format=0,this.RMIDInfo={},this.bankOffset=0,this.tracks=[]}};function Be(t,A){let e=0;for(;t>0;){let n=A.tempoChanges.find(o=>o.ticksSt[t]=A<<7;dA(m.mainVolume,100);dA(m.balance,64);dA(m.expressionController,127);dA(m.pan,64);dA(m.timbreHarmonicContent,64);dA(m.releaseTime,64);dA(m.attackTime,64);dA(m.brightness,64);dA(m.soundController6,64);dA(m.soundController7,64);dA(m.soundController8,64);dA(m.soundController9,64);dA(m.generalPurposeController6,64);dA(m.generalPurposeController8,64);dA(EA+K.pitchWheel,64);dA(EA+K.pitchWheelRange,2);var gA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Dt=Object.keys(gA).length,kt=new Float32Array(Dt);kt[gA.modulationMultiplier]=1;var fA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6};function yn(t=!1){let A={midiControllers:new Int16Array(Ke),lockedControllers:Array(Ke).fill(!1),customControllers:new Float32Array(Dt),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:fA.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},velocityOverride:0,lockGSNRPNParams:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let e=0;e<128;e++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),t&&this.callEvent("newchannel",void 0)}var wt={velocityOverride:128};var Sn="spessasynth-worklet-system",Dn=350,SA=9,Ve=16,Oe="gs";var LA={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(t,A){let e=0;for(let n=8*(A-1);n>=0;n-=8)e|=t[t.currentIndex++]<>>0}function kn(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=we(t.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=n,e.status){case F.noteOn:let s=t.messageData[1];if(s>0)this.synth.noteOn(e.channel,t.messageData[0],s),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:s});else{this.synth.noteOff(e.channel,t.messageData[0]);let I=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);I!==-1&&this.playingNotes.splice(I,1)}break;case F.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(I=>I.midiNote===t.messageData[0]&&I.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case F.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case F.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case F.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case F.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case F.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case F.systemExclusive:this.synth.systemExclusive(t.messageData,n);break;case F.setTempo:this.oneTickToSeconds=60/(No(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),T("invalid tempo! falling back to 120 BPM"));break;case F.timeSignature:case F.endOfTrack:case F.midiChannelPrefix:case F.songPosition:case F.activeSensing:case F.keySignature:case F.sequenceNumber:case F.sequenceSpecific:break;case F.text:case F.lyric:case F.copyright:case F.trackName:case F.marker:case F.cuePoint:case F.instrumentName:case F.programName:this.post(wA.textEvent,[t.messageData,e.status]);break;case F.midiPort:this.assignMIDIPort(A,t.messageData[0]);break;case F.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:T(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(F).find(I=>F[I]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function wn(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function No(t){return t.messageData.currentIndex=0,6e7/zA(t.messageData,3)}function Fn(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(n.ticks-e.ticks),this.midiData.loop.end<=e.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function Rn(){let t=0,A=1/0;return this.tracks.forEach((e,n)=>{this.eventIndex[n]>=e.length||e[this.eventIndex[n]].ticks>>0}function Ee(t,A,e){for(let n=0;n>n*8&255}function J(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function lA(t,A){Ee(t,A,4)}function jA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function Gn(t){return t>127?t-256:t}function V(t,A,e=void 0,n=!0){if(e){let s=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(s.buffer)}else{let s=!1,o="";for(let I=0;I127){if(n){s=!0;continue}else if(C===0){s=!0;continue}}o+=String.fromCharCode(C)}}return o}}function FA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let n=0;nA.length)for(let n=0;ne.header!=="LIST"?!1:(e.chunkData.currentIndex=0,V(e.chunkData,4)===A))}function Xe(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var We={name:"INAM",album:"IPRD",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"};var _e=class{constructor(){this.timeDivision=0,this.duration=0,this.tempoChanges=[{ticks:0,tempo:120}],this.copyright="",this.tracksAmount=0,this.lyrics=[],this.firstNoteOn=0,this.keyRange={min:0,max:127},this.lastVoiceEventTick=0,this.midiPorts=[0],this.midiPortChannelOffsets=[0],this.usedChannelsOnTrack=[],this.loop={start:0,end:0},this.midiName="",this.fileName="",this.rawMidiName=void 0,this.embeddedSoundFont=void 0,this.format=0,this.RMIDInfo={},this.bankOffset=0,this.tracks=[]}};function Be(t,A){let e=0;for(;t>0;){let n=A.tempoChanges.find(o=>o.ticks0&&(b+=this.tracks[y-1][this.tracks[y-1].length-1].ticks);w.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=b),_=cn[i>>4],(i&240)===F.noteOn){G.add(sA);let rA=w.data[w.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,rA),this.keyRange.max=Math.max(this.keyRange.max,rA)}x=i;break}let v=new Y(_),z=w.data.slice(w.data.currentIndex,w.data.currentIndex+_);w.data.currentIndex+=_,v.set(z,0);let oA=new Ie(b,i,v);switch(k.push(oA),sA){case-2:switch(i){case F.setTempo:this.tempoChanges.push({ticks:b,tempo:6e7/zA(z,3)});break;case F.marker:switch(V(v,v.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=b;break;case"loopend":c=b}v.currentIndex=0;break;case F.midiPort:let CA=v[0];this.midiPorts[y]=CA,this.midiPortChannelOffsets[CA]===void 0&&(this.midiPortChannelOffsets[CA]=l,l+=16);break;case F.copyright:o||(this.copyright+=V(v,v.length,void 0,!1)+` `);break;case F.lyric:this.lyrics.push(v)}break;case-3:if(v.slice(0,7).every((rA,CA)=>bo[CA]===rA)){let rA=v.slice(7,z.length-3),CA=V(rA,rA.length)+` -`;this.copyright+=CA,p(`%cDecoded Roland SC message! %c${CA}`,r.recognized,r.value)}break;default:if((i&240)===F.controllerChange)switch(v[0]){case 2:case 116:d=b;break;case 4:case 117:c===null?c=b:c=0;break;case 0:C&&v[1]!==0&&v[1]!==127&&(p("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(k),this.usedChannelsOnTrack.push(G),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,r.info,r.value,r.info,r.value)}p("%cAll tracks parsed correctly!",r.recognized),yA("%cCorrecting loops, ports and detecting notes...",r.info);let u=[];for(let y of this.tracks){let k=y.find(w=>(w.messageStatusByte&240)===F.noteOn);k&&u.push(k.ticks)}this.firstNoteOn=Math.min(...u),p(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&c===null?(d=this.firstNoteOn,c=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(c===null||c===0)&&(c=this.lastVoiceEventTick)),this.loop={start:d,end:c},p(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let D=0;for(let y of this.midiPorts)if(y!==-1){D=y;break}if(this.midiPorts=this.midiPorts.map(y=>y===-1?D:y),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?p("%cNo additional MIDI Ports detected.",r.info):p("%cMIDI Ports detected!",r.recognized),!I)if(this.tracks.length>1){if(this.tracks[0].find(y=>y.messageStatusByte>=F.noteOn&&y.messageStatusBytek.messageStatusByte===F.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=V(y.messageData,y.messageData.length,void 0,!1))}}else{let y=this.tracks[0].find(k=>k.messageStatusByte===F.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=V(y.messageData,y.messageData.length,void 0,!1))}if(this.fileName=e,this.midiName=this.midiName.trim(),this.midiName.length===0){p("%cNo name detected. Using the alt name!",r.info),this.midiName=hn(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let y=0;yl>c?l:c),n=[];for(let c=0;c{I[D]>=u.length||u[I[D]].ticks0;){let c=Q(),l=t.tracks[c];if(I[c]>=l.length){C--;continue}let u=l[I[c]];if(I[c]++,u.messageStatusByte===F.midiPort){B[c]=u.messageData[0];continue}let D=u.messageStatusByte&240;if(D!==F.noteOn&&D!==F.controllerChange&&D!==F.programChange&&D!==F.systemExclusive)continue;let y=(u.messageStatusByte&15)+t.midiPortChannelOffsets[B[c]]||0,k=n[y];switch(D){case F.programChange:k.program=u.messageData[0],s(k);break;case F.controllerChange:if(u.messageData[0]!==m.bankSelect||d==="gs"&&k.drums)continue;let w=u.messageData[1],G=Math.max(0,w-t.bankOffset);if(d==="xg"){let $=w===120||w===126||w===127;$!==k.drums?(k.drums=$,k.bank=k.drums?128:G,s(k)):k.bank=k.drums?128:G;continue}n[y].bank=G;break;case F.noteOn:if(u.messageData[1]===0)continue;s(k),o[k.string].add(`${u.messageData[0]}-${u.messageData[1]}`);break;case F.systemExclusive:if(u.messageData[0]!==65||u.messageData[2]!==66||u.messageData[3]!==18||u.messageData[4]!==64||!(u.messageData[5]&16)||u.messageData[6]!==21){u.messageData[0]===67&&u.messageData[2]===76&&u.messageData[5]===126&&u.messageData[6]===0&&(d="xg");continue}let x=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+t.midiPortChannelOffsets[B[c]],b=!!(u.messageData[7]>0&&u.messageData[5]>>4);k=n[x],k.drums=b,k.bank=b?128:0,s(k);break}}for(let c of Object.keys(o))o[c].size===0&&(p(`%cDetected change but no keys for %c${c}`,r.info,r.value),delete o[c]);return Z(),o}function Mn(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(n,e)}),this.duration=this.midiData.duration,this.firstNoteTime=Be(this.midiData.firstNoteOn,this.midiData),p(`%cTotal song time: ${mt(Math.ceil(this.duration)).time}`,r.recognized),this.post(wA.songChange,[new Ze(this.midiData),this.songIndex,A]),this.duration<=1&&(T(`%cVery short song: (${mt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),A)this.play(!0);else{let e=this._skipToFirstNoteOn?this.midiData.firstNoteOn-1:0;this.setTimeTicks(e),this.pause()}}function bn(t,A=!0){this.songs=t.reduce((e,n)=>{if(n.duration)return e.push(n),e;try{e.push(new ze(n.binary,n.altName||""))}catch(s){return this.post(wA.midiError,s.message),e}return e},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex],A))}function Ln(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Un(){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[m.mainVolume]=100;PA[m.expressionController]=127;PA[m.pan]=64;PA[m.releaseTime]=64;PA[m.brightness]=64;PA[m.reverbDepth]=0;function Tn(t,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let e=this.synth.workletProcessorChannels.length,n=Array(e).fill(8192),s=[];for(let C=0;CC===m.dataDecrement||C===m.dataIncrement||C===m.dataEntryMsb||C===m.dataDecrement||C===m.lsbForControl6DataEntry||C===m.RPNLsb||C===m.RPNMsb||C===m.NRPNLsb||C===m.NRPNMsb||C===m.bankSelect||C===m.lsbForControl0BankSelect||C===m.resetAllControllers,I=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let B=we(Q.messageStatusByte),d=B.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(B.status){case F.noteOn:case F.noteOff:case F.keySignature:break;case F.pitchBend:n[d]=Q.messageData[1]<<7|Q.messageData[0];break;case F.programChange:let l=s[d];l.program=Q.messageData[0],l.actualBank=l.bank;break;case F.controllerChange:let u=Q.messageData[0];if(o(u)){let D=Q.messageData[1];if(u===m.bankSelect){s[d].bank=D;break}this.sendMIDIMessages?this.sendMIDICC(d,u,D):this.synth.controllerChange(d,u,D)}else I[d]===void 0&&(I[d]=Array.from(PA)),I[d][u]=Q.messageData[1];break;default:this._processEvent(Q,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let c=this.tracks[C][this.eventIndex[C]];if(c===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(c.ticks-Q.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7,n[C]&127),I[C]!==void 0&&I[C].forEach((Q,B)=>{Q!==PA[B]&&!o(B)&&this.sendMIDICC(C,B,Q)}),s[C].program>=0&&s[C].actualBank>=0){let Q=s[C].actualBank;this.sendMIDICC(C,m.bankSelect,Q),this.sendMIDIProgramChange(C,s[C].program)}}else for(let C=0;C>7,n[C]&127),I[C]!==void 0&&I[C].forEach((Q,B)=>{Q!==PA[B]&&!o(B)&&this.synth.controllerChange(C,B,Q)}),s[C].program>=0&&s[C].actualBank>=0){let Q=s[C].actualBank;this.synth.controllerChange(C,m.bankSelect,Q),this.synth.programChange(C,s[C].program)}return!0}function Hn(t=!1){if(this.midiData!==void 0){if(t){this.currentTime=0;return}if(this.currentTime>=this.duration){this.currentTime=0;return}this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),this.sendMIDIMessages||this.playingNotes.forEach(A=>{this.synth.noteOn(A.channel,A.midiNote,A.velocity,!1,!0)}),this.setProcessHandler()}}function Yn(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(wA.timeChange,currentTime-Be(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Jn(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function vn(t,A){switch(t){default:break;case bA.loadNewSongList:this.loadNewSongList(A[0],A[1]);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 qn(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:pA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Pn(t){this.post(wA.midiEvent,t)}function Kn(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|t,A,e])}function Vn(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|t,A])}function On(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|t,e,A])}function Zn(){if(this.sendMIDIMessages){this.sendMIDIMessage([F.reset]);for(let t=0;tthis.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&AXn?440*Math.pow(2,(t-6900)/1200):Rt[~~t-je]}var xt=-1660,Lo=1600,Gt=new Float32Array((Lo-xt)*100+1);for(let t=0;t.5?1:0,n?e*2-1:e;case cA.concave:return n?(e=e*2-1,e<0?-ZA[~~(e*-BA)]:ZA[~~(e*BA)]):ZA[~~(e*BA)];case cA.convex:return n?(e=e*2-1,e<0?-ne[~~(e*-BA)]:ne[~~(e*BA)]):ne[~~(e*BA)]}}var Mt=1,Nt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)n-=o;let C=~~n,Q=C+1;for(;Q>=e.loopEnd;)Q-=o;let B=n-C,d=s[Q],c=s[C];A[I]=c+(d-c)*B,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end){t.finished=!0;return}let Q=n-I,B=s[C],d=s[I];A[o]=d+(B-d)*Q,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function _n(t,A){let e=t.sample,n=e.cursor,s=e.loopEnd-e.loopStart,o=e.sampleData;if(t.sample.isLooping)for(let I=0;I=e.loopEnd;)n-=s;let C=~~n+1;for(;C>=e.loopEnd;)C-=s;A[I]=o[C],n+=e.playbackStep*t.currentTuningCalculated}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let I=0;I=e.end){t.finished=!0;return}A[I]=o[C],n+=e.playbackStep*t.currentTuningCalculated}}e.cursor=n}function zn(t,A){let e=t.sample,n=e.cursor,s=e.sampleData;if(e.isLooping){let o=e.loopEnd-e.loopStart;for(let I=0;I=e.loopEnd;)n-=o;let C=~~n,Q=C+1,B=Q+1,d=B+1,c=n-C;Q>=e.loopEnd&&(Q-=o),B>=e.loopEnd&&(B-=o),d>=e.loopEnd&&(d-=o);let l=s[C],u=s[Q],D=s[B],y=s[d],k=.5*(D-l),w=l-2.5*u+2*D-.5*y,G=.5*(y-l)+1.5*(u-D);A[I]=((G*c+w)*c+k)*c+u,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end||Q>=e.end||B>=e.end){t.finished=!0;return}let c=s[I],l=s[C],u=s[Q],D=s[B],y=.5*(u-c),k=c-2.5*l+2*u-.5*D,w=.5*(D-c)+1.5*(l-u);A[o]=((w*d+k)*d+y)*d+l,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function jn(t,A,e,n,s,o,I,C,Q){if(!isNaN(e[0])){if(I>0){let B=o[0],d=o[1];I=Math.min(I,1e3);let c=I/4600;for(let l=0;l0){let B=C[0],d=C[1];Q=Math.min(Q,1e3);let c=Q/1300,l=t*c,u=A*c;for(let D=0;D0)for(let B=0;B0)for(let B=0;B13499&&A.filter.reasonanceCb===0)return;let o=A.filter;(o.cutoffCents!==n||o.reasonanceCb!==A.modulatedGenerators[g.initialFilterQ])&&(o.cutoffCents=n,o.reasonanceCb=A.modulatedGenerators[g.initialFilterQ],t.calculateCoefficients(o));for(let I=0;I=bt}static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=KA(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static recalculate(A){let e=A.volumeEnvelope,n=B=>Math.max(0,Math.floor(HA(B)*e.sampleRate));e.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[g.initialAttenuation],1440))/10,e.sustainDbRelative=Math.min(JA,A.modulatedGenerators[g.sustainVolEnv]/10);let s=Math.min(JA,e.sustainDbRelative);e.attackDuration=n(A.modulatedGenerators[g.attackVolEnv]);let o=A.modulatedGenerators[g.decayVolEnv],I=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvDecay],C=s/JA;e.decayDuration=n(o+I)*C,e.releaseDuration=n(A.modulatedGenerators[g.releaseVolEnv]),e.delayEnd=n(A.modulatedGenerators[g.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let Q=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvHold];if(e.holdEnd=n(A.modulatedGenerators[g.holdVolEnv]+Q)+e.attackEnd,e.decayEnd=e.decayDuration+e.holdEnd,e.state===0&&e.attackEnd===0&&(e.state=2),A.isInRelease){let B=Math.max(0,Math.min(JA,e.sustainDbRelative)),d=B/JA;switch(e.decayDuration=n(o+I)*d,e.state){case 0:e.releaseStartDb=JA;break;case 1:let c=1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration;e.releaseStartDb=20*Math.log10(c)*-1;break;case 2:e.releaseStartDb=0;break;case 3:e.releaseStartDb=(1-(e.decayEnd-e.releaseStartTimeSamples)/e.decayDuration)*B;break;case 4:e.releaseStartDb=B;break}e.releaseStartDb=Math.max(0,Math.min(e.releaseStartDb,JA)),e.releaseStartDb>=bt&&(A.finished=!0),e.currentReleaseGain=KA(e.releaseStartDb)}}static apply(A,e,n,s){let o=A.volumeEnvelope,I=n/10,C=s;if(A.isInRelease){let B=o.currentSampleTime-o.releaseStartTimeSamples;if(B>=o.releaseDuration){for(let c=0;c=e.length)return;o.state++;case 1:for(;o.currentSampleTime=e.length)return}o.state++;case 2:for(;o.currentSampleTime=e.length)return;o.state++;case 3:for(;o.currentSampleTime=e.length)return;o.state++;case 4:for(o.canEndOnSilentSustain&&o.sustainDbRelative>=bt&&(A.finished=!0);;)if(o.attenuation+=(o.attenuationTarget-o.attenuation)*C,e[Q]*=KA(o.sustainDbRelative+I+o.attenuation),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++Q>=e.length)return}}};var As=Math.PI/2,es=.05;function ts(t,A,e,n,s,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,LA.startRelease(A),YA.startRelease(A),A.sample.loopingMode===3&&(A.sample.isLooping=!1)),A.modulatedGenerators[g.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let I=A.targetKey,C=A.modulatedGenerators[g.fineTune]+t.customControllers[gA.channelTuning]+t.customControllers[gA.channelTransposeFine]+t.customControllers[gA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],Q=A.modulatedGenerators[g.coarseTune]+t.customControllers[gA.channelTuningSemitones],B=this.tunings[t.preset.program]?.[A.realKey];B?.midiNote>=0&&(I=B.midiNote,C+=B.centTuning),C+=(I-A.sample.rootKey)*A.modulatedGenerators[g.scaleTuning];let d=A.modulatedGenerators[g.vibLfoToPitch];if(d!==0){let oA=A.startTime+HA(A.modulatedGenerators[g.delayVibLFO]),rA=Fe(A.modulatedGenerators[g.freqVibLFO]),CA=$e(oA,rA,currentTime);C+=CA*(d*t.customControllers[gA.modulationMultiplier])}let c=A.modulatedGenerators[g.initialFilterFc],l=c,u=A.modulatedGenerators[g.modLfoToPitch],D=A.modulatedGenerators[g.modLfoToVolume],y=A.modulatedGenerators[g.modLfoToFilterFc],k=0;if(u+y+D!==0){let oA=A.startTime+HA(A.modulatedGenerators[g.delayModLFO]),rA=Fe(A.modulatedGenerators[g.freqModLFO]),CA=$e(oA,rA,currentTime);C+=CA*(u*t.customControllers[gA.modulationMultiplier]),k=-CA*D,l+=CA*y}if(t.channelVibrato.depth>0){let oA=$e(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);oA&&(C+=oA*t.channelVibrato.depth)}let w=A.modulatedGenerators[g.modEnvToPitch],G=A.modulatedGenerators[g.modEnvToFilterFc],x=YA.getValue(A,currentTime);l+=x*G,C+=x*w;let b=~~(C+Q*100);b!==A.currentTuningCents&&(A.currentTuningCents=b,A.currentTuningCalculated=Math.pow(2,b/1200));let $=(Math.max(-500,Math.min(500,A.modulatedGenerators[g.pan]))+500)/1e3,i=new Float32Array(e.length);switch(this.interpolationType){case he.linear:default:Wn(A,i);break;case he.nearestNeighbor:_n(A,i);break;case he.fourthOrder:zn(A,i)}Qe.apply(A,i,l,c>13499),LA.apply(A,i,k,this.volumeEnvelopeSmoothingFactor),A.currentPan+=($-A.currentPan)*this.panSmoothingFactor;let sA=Math.cos(As*A.currentPan)*this.panLeft,_=Math.sin(As*A.currentPan)*this.panRight,v=this.oneOutputMode?0:A.modulatedGenerators[g.reverbEffectsSend],z=this.oneOutputMode?0:A.modulatedGenerators[g.chorusEffectsSend];jn(sA,_,i,e,n,s,v,o,z)}function To(t,A){let e=0;return t.drumChannel&&(e+=5),A.isInRelease&&(e-=5),e+=A.velocity/25,e-=A.volumeEnvelope.state,A.isInRelease&&(e-=5),e-=A.volumeEnvelope.currentAttenuationDb/50,e}function ns(t){let A=[];for(let n of this.workletProcessorChannels)for(let s of n.voices)if(!s.finished){let o=To(n,s);A.push({channel:n,voice:s,priority:o})}A.sort((n,s)=>n.priority-s.priority);let e=A.slice(0,t);for(let{channel:n,voice:s}of e){let o=n.voices.indexOf(s);o>-1&&n.voices.splice(o,1)}}function ss(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimers=t);var Ho=function(t){var A,e,n,s,o,I,C,Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",B="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do s=Q.indexOf(t.charAt(d++)),o=Q.indexOf(t.charAt(d++)),I=Q.indexOf(t.charAt(d++)),C=Q.indexOf(t.charAt(d++)),A=s<<2|o>>4,e=(15&o)<<4|I>>2,n=(3&I)<<6|C,B+=String.fromCharCode(A),I!==64&&(B+=String.fromCharCode(e)),C!==64&&(B+=String.fromCharCode(n));while(d1&&(i.thisProgram=process.argv[1].replace(/\\/g,"/")),i.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(a){if(!(a instanceof ye))throw a}),process.on("unhandledRejection",function(a,E){process.exit(1)}),i.quit=function(a){process.exit(a)},i.inspect=function(){return"[Emscripten Module object]"}):oA?(typeof read<"u"&&(i.read=function(E){return read(E)}),i.readBinary=function(E){var h;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(h=read(E,"binary"))=="object"),h)},typeof scriptArgs<"u"?i.arguments=scriptArgs:typeof arguments<"u"&&(i.arguments=arguments),typeof quit=="function"&&(i.quit=function(a){quit(a)})):(_||v)&&(_?document.currentScript&&(rA=document.currentScript.src):rA=self.location.href,rA=rA.indexOf("blob:")!==0?rA.split("/").slice(0,-1).join("/")+"/":"",i.read=function(E){var h=new XMLHttpRequest;return h.open("GET",E,!1),h.send(null),h.responseText},v&&(i.readBinary=function(E){var h=new XMLHttpRequest;return h.open("GET",E,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),i.readAsync=function(E,h,f){var R=new XMLHttpRequest;R.open("GET",E,!0),R.responseType="arraybuffer",R.onload=function(){if(R.status==200||R.status==0&&R.response){h(R.response);return}f()},R.onerror=f,R.send(null)},i.setWindowTitle=function(a){document.title=a});var Me=i.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),RA=i.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Me);for(t in sA)sA.hasOwnProperty(t)&&(i[t]=sA[t]);function Ne(a){var E=u;return u=u+a+15&-16,E}function Ot(a){var E=Q[x>>2],h=E+a+15&-16;return Q[x>>2]=h,h>=hA&&!tn()?(Q[x>>2]=E,0):E}function Zt(a,E){return E||(E=16),a=Math.ceil(a/E)*E}function fo(a){switch(a){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(a[a.length-1]==="*")return 4;if(a[0]!=="i")return 0;var E=parseInt(a.substr(1));return _A(E%8==0),E/8}}function fe(a){fe.shown||(fe.shown={}),fe.shown[a]||(fe.shown[a]=1,RA(a))}sA=void 0;var mo={"f64-rem":function(a,E){return a%E},debugger:function(){}},it=[];function Ko(a,E){for(var h=0,f=h;f>>0)+4294967296*+(E>>>0):+(a>>>0)+4294967296*+(0|E)}function It(a,E,h){return h&&h.length?i["dynCall_"+a].apply(null,[E].concat(h)):i["dynCall_"+a].call(null,E)}var be=0,Xt=0;function _A(a,E){a||OA("Assertion failed: "+E)}function Wt(a){var E=i["_"+a];return _A(E,"Cannot call unknown function "+a+", make sure it is exported"),E}var _t={stackSave:function(){lt()},stackRestore:function(){ct()},arrayToC:function(a){var E,h,f=Je(a.length);return E=a,h=f,s.set(E,h),f},stringToC:function(a){var E=0;if(a!=null&&a!==0){var h=(a.length<<2)+1;E=Je(h),$t(a,E,h)}return E}},po={string:_t.stringToC,array:_t.arrayToC};function zt(a,E,h,f,R){var P=Wt(a),X=[],N=0;if(f)for(var QA=0;QA>0]=E;break;case"i16":I[a>>1]=E;break;case"i32":Q[a>>2]=E;break;case"i64":tempI64=[E>>>0,+Fo(tempDouble=E)>=1?tempDouble>0?(0|Go(+an(tempDouble/4294967296),4294967295))>>>0:~~+Ro((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],Q[a>>2]=tempI64[0],Q[a+4>>2]=tempI64[1];break;case"float":d[a>>2]=E;break;case"double":c[a>>3]=E;break;default:OA("invalid type for setValue: "+h)}}function Xo(a,E,h){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return s[a>>0];case"i16":return I[a>>1];case"i32":case"i64":return Q[a>>2];case"float":return d[a>>2];case"double":return c[a>>3];default:OA("invalid type for getValue: "+E)}return null}function Wo(a,E,h,f){typeof a=="number"?(P=!0,X=a):(P=!1,X=a.length);var R=typeof E=="string"?E:null;if(N=h==4?f:[typeof Ye=="function"?Ye:Ne,Je,Ne,Ot][h===void 0?2:h](Math.max(X,R?1:E.length)),P){for(f=N,_A((3&N)==0),QA=N+(-4&X);f>2]=0;for(QA=N+X;f>0]=0;return N}if(R==="i8")return a.subarray||a.slice?o.set(a,N):o.set(new Uint8Array(a),N),N;for(var P,X,N,QA,iA,aA,tA,q=0;q>0],(f!=0||E)&&(X++,!E||X!=E););E||(E=X);var N="";if(P<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(a,a+Math.min(E,1024))),N=N?N+R:R,a+=1024,E-=1024;return N}return h=a,function(iA,aA){for(var tA=aA;iA[tA];)++tA;if(tA-aA>16&&iA.subarray&&jt)return jt.decode(iA.subarray(aA,tA));for(var q,mA,GA,xA,MA,ee,NA="";;){if(!(q=iA[aA++]))return NA;if(!(128&q)){NA+=String.fromCharCode(q);continue}if(mA=63&iA[aA++],(224&q)==192){NA+=String.fromCharCode((31&q)<<6|mA);continue}if(GA=63&iA[aA++],(240&q)==224?q=(15&q)<<12|mA<<6|GA:(xA=63&iA[aA++],(248&q)==240?q=(7&q)<<18|mA<<12|GA<<6|xA:(MA=63&iA[aA++],q=(252&q)==248?(3&q)<<24|mA<<18|GA<<12|xA<<6|MA:(1&q)<<30|mA<<24|GA<<18|xA<<12|MA<<6|(ee=63&iA[aA++]))),q<65536)NA+=String.fromCharCode(q);else{var Se=q-65536;NA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(o,h)}function zo(a){for(var E="";;){var h=s[a++>>0];if(!h)return E;E+=String.fromCharCode(h)}}function jo(a,E){return function(f,R,P){for(var X=0;X>0]=f.charCodeAt(X);P||(s[R>>0]=0)}(a,E,!1)}var jt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ue(a,E,h,f){if(!(f>0))return 0;for(var R=h,P=h+f-1,X=0;X=55296&&N<=57343&&(N=65536+((1023&N)<<10)|1023&a.charCodeAt(++X)),N<=127){if(h>=P)break;E[h++]=N}else if(N<=2047){if(h+1>=P)break;E[h++]=192|N>>6,E[h++]=128|63&N}else if(N<=65535){if(h+2>=P)break;E[h++]=224|N>>12,E[h++]=128|N>>6&63,E[h++]=128|63&N}else if(N<=2097151){if(h+3>=P)break;E[h++]=240|N>>18,E[h++]=128|N>>12&63,E[h++]=128|N>>6&63,E[h++]=128|63&N}else if(N<=67108863){if(h+4>=P)break;E[h++]=248|N>>24,E[h++]=128|N>>18&63,E[h++]=128|N>>12&63,E[h++]=128|N>>6&63,E[h++]=128|63&N}else{if(h+5>=P)break;E[h++]=252|N>>30,E[h++]=128|N>>24&63,E[h++]=128|N>>18&63,E[h++]=128|N>>12&63,E[h++]=128|N>>6&63,E[h++]=128|63&N}}return E[h]=0,h-R}function $t(a,E,h){return Ue(a,o,E,h)}function Te(a){for(var E=0,h=0;h=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&a.charCodeAt(++h)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var An=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function $o(a){for(var E=a,h=E>>1;I[h];)++h;if((E=h<<1)-a>32&&An)return An.decode(o.subarray(a,E));for(var f=0,R="";;){var P=I[a+2*f>>1];if(P==0)return R;++f,R+=String.fromCharCode(P)}}function Ar(a,E,h){if(h===void 0&&(h=2147483647),h<2)return 0;for(var f=E,R=(h-=2)<2*a.length?h/2:a.length,P=0;P>1]=X,E+=2}return I[E>>1]=0,E-f}function er(a){return 2*a.length}function tr(a){for(var E=0,h="";;){var f=Q[a+4*E>>2];if(f==0)return h;if(++E,f>=65536){var R=f-65536;h+=String.fromCharCode(55296|R>>10,56320|1023&R)}else h+=String.fromCharCode(f)}}function nr(a,E,h){if(h===void 0&&(h=2147483647),h<4)return 0;for(var f=E,R=f+h-4,P=0;P=55296&&X<=57343&&(X=65536+((1023&X)<<10)|1023&a.charCodeAt(++P)),Q[E>>2]=X,(E+=4)+4>R)break}return Q[E>>2]=0,E-f}function sr(a){for(var E=0,h=0;h=55296&&f<=57343&&++h,E+=4}return E}function or(a){var E=Te(a)+1,h=Ye(E);return h&&Ue(a,s,h,E),h}function rr(a){var E=Te(a)+1,h=Je(E);return Ue(a,s,h,E),h}function ir(a){return a}function ar(){var a,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(R){f=R}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return i.extraStackTrace&&(E+=` -`+i.extraStackTrace()),(a=E).replace(/__Z[\w\d_]+/g,function(h){var f,R=f=h;return h===R?h:h+" ["+R+"]"})}function gt(a,E){return a%E>0&&(a+=E-a%E),a}function en(a){i.buffer=n=a}function Ct(){i.HEAP8=s=new Int8Array(n),i.HEAP16=I=new Int16Array(n),i.HEAP32=Q=new Int32Array(n),i.HEAPU8=o=new Uint8Array(n),i.HEAPU16=C=new Uint16Array(n),i.HEAPU32=B=new Uint32Array(n),i.HEAPF32=d=new Float32Array(n),i.HEAPF64=c=new Float64Array(n)}function tn(){var a=i.usingWasm?65536:16777216,E=2147483648-a;if(Q[x>>2]>E)return!1;var h=hA;for(hA=Math.max(hA,16777216);hA>2];)hA=hA<=536870912?gt(2*hA,a):Math.min(gt((3*hA+2147483648)/4,a),E);var f=i.reallocBuffer(hA);return f&&f.byteLength==hA?(en(f),Ct(),!0):(hA=h,!1)}l=u=y=k=w=G=x=0,D=!1,i.reallocBuffer||(i.reallocBuffer=function(a){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(n,a);else{var E,h=s;E=new ArrayBuffer(a),new Int8Array(E).set(h)}}catch{return!1}return!!xo(E)&&E});try{(b=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{b=function(E){return E.byteLength}}var Et=i.TOTAL_STACK||5242880,hA=i.TOTAL_MEMORY||16777216;function So(){return hA}function me(a){for(;a.length>0;){var E=a.shift();if(typeof E=="function"){E();continue}var h=E.func;typeof h=="number"?E.arg===void 0?i.dynCall_v(h):i.dynCall_vi(h,E.arg):h(E.arg===void 0?null:E.arg)}}hA=0?a:E<=32?2*Math.abs(1<=f&&(E<=32||a>f)&&(a=-2*f+a),a}var Fo=Math.abs,Ro=Math.ceil,an=Math.floor,Go=Math.min,Ae=0,Qt=null,pe=null;function Qr(a){return a}i.preloadedImages={},i.preloadedAudios={};var In="data:application/octet-stream;base64,";function He(a){return String.prototype.startsWith?a.startsWith(In):a.indexOf(In)===0}(function(){var E="main.wast",h="main.wasm",f="main.temp.asm.js";He(E)||(E=CA(E)),He(h)||(h=CA(h)),He(f)||(f=CA(f));var R={global:null,env:null,asm2wasm:mo,parent:i},P=null;function X(tA){return tA}function N(){try{if(i.wasmBinary)return new Uint8Array(i.wasmBinary);if(i.readBinary)return i.readBinary(h);throw"both async and sync fetching of the wasm failed"}catch(tA){OA(tA)}}i.asmPreload=i.asm;var QA=i.reallocBuffer,iA=function(tA){tA=gt(tA,i.usingWasm?65536:16777216);var q=i.buffer.byteLength;if(i.usingWasm)try{var mA=i.wasmMemory.grow((tA-q)/65536);return mA!==-1?i.buffer=i.wasmMemory.buffer:null}catch{return null}};i.reallocBuffer=function(tA){return aA==="asmjs"?QA(tA):iA(tA)};var aA="";i.asm=function(tA,q,mA){var GA;if(!(q=GA=q).table){var xA,MA=i.wasmTableSize;MA===void 0&&(MA=1024);var ee=i.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?ee!==void 0?q.table=new WebAssembly.Table({initial:MA,maximum:ee,element:"anyfunc"}):q.table=new WebAssembly.Table({initial:MA,element:"anyfunc"}):q.table=Array(MA),i.wasmTable=q.table}return q.memoryBase||(q.memoryBase=i.STATIC_BASE),q.tableBase||(q.tableBase=0),xA=function(Se,ie,dt){if(typeof WebAssembly!="object")return RA("no native wasm support detected"),!1;if(!(i.wasmMemory instanceof WebAssembly.Memory))return RA("no native wasm Memory in use"),!1;function ve(vA,qA){if((P=vA.exports).memory){var De,ft,En;De=P.memory,ft=i.buffer,De.byteLength0?h:Te(a)+1,R=Array(f),P=Ue(a,R,0,R.length);return E&&(R.length=P),R}function dr(a){for(var E=[],h=0;h255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}u+=16,x=Ne(4),w=(y=k=Zt(u))+Et,G=Zt(w),Q[x>>2]=G,D=!0,i.wasmTableSize=4,i.wasmMaxTableSize=4,i.asmGlobalArg={},i.asmLibraryArg={abort:OA,assert:_A,enlargeMemory:tn,getTotalMemory:So,abortOnCannotGrowMemory:function(){OA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+hA+", (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,h,f){var R=lt();try{return i.dynCall_iii(E,h,f)}catch(P){if(ct(R),typeof P!="number"&&P!=="longjmp")throw P;i.setThrew(1,0)}},___assert_fail:function(E,h,f,R){OA("Assertion failed: "+Le(E)+", at: "+[h?Le(h):"unknown filename",f,R?Le(R):"unknown function"])},___setErrNo:function(E){return i.___errno_location&&(Q[i.___errno_location()>>2]=E),E},_abort:function(){i.abort()},_emscripten_memcpy_big:function(E,h,f){return o.set(o.subarray(h,h+f),E),E},_llvm_floor_f64:an,DYNAMICTOP_PTR:x,tempDoublePtr:kA,ABORT:be,STACKTOP:k,STACK_MAX:w};var gn=i.asm(i.asmGlobalArg,i.asmLibraryArg,n);i.asm=gn,i.___errno_location=function(){return i.asm.___errno_location.apply(null,arguments)};var xo=i._emscripten_replace_memory=function(){return i.asm._emscripten_replace_memory.apply(null,arguments)};i._free=function(){return i.asm._free.apply(null,arguments)};var Ye=i._malloc=function(){return i.asm._malloc.apply(null,arguments)};i._memcpy=function(){return i.asm._memcpy.apply(null,arguments)},i._memset=function(){return i.asm._memset.apply(null,arguments)},i._sbrk=function(){return i.asm._sbrk.apply(null,arguments)},i._stb_vorbis_js_channels=function(){return i.asm._stb_vorbis_js_channels.apply(null,arguments)},i._stb_vorbis_js_close=function(){return i.asm._stb_vorbis_js_close.apply(null,arguments)},i._stb_vorbis_js_decode=function(){return i.asm._stb_vorbis_js_decode.apply(null,arguments)},i._stb_vorbis_js_open=function(){return i.asm._stb_vorbis_js_open.apply(null,arguments)},i._stb_vorbis_js_sample_rate=function(){return i.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},i.establishStackSpace=function(){return i.asm.establishStackSpace.apply(null,arguments)},i.getTempRet0=function(){return i.asm.getTempRet0.apply(null,arguments)},i.runPostSets=function(){return i.asm.runPostSets.apply(null,arguments)},i.setTempRet0=function(){return i.asm.setTempRet0.apply(null,arguments)},i.setThrew=function(){return i.asm.setThrew.apply(null,arguments)};var Je=i.stackAlloc=function(){return i.asm.stackAlloc.apply(null,arguments)},ct=i.stackRestore=function(){return i.asm.stackRestore.apply(null,arguments)},lt=i.stackSave=function(){return i.asm.stackSave.apply(null,arguments)};function ye(a){this.name="ExitStatus",this.message="Program terminated with exit("+a+")",this.status=a}function ut(a){a=a||i.arguments,!(Ae>0)&&(function(){if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)ko(i.preRun.shift());me(nn)}(),!(Ae>0)&&(i.calledRun||(i.setStatus?(i.setStatus("Running..."),setTimeout(function(){setTimeout(function(){i.setStatus("")},1),E()},1)):E())));function E(){!i.calledRun&&(i.calledRun=!0,be||(ht||(ht=!0,me(Bt)),me(sn),i.onRuntimeInitialized&&i.onRuntimeInitialized(),function(){if(i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;)wo(i.postRun.shift());me(rn)}()))}}function fr(a,E){(!E||!i.noExitRuntime||a!==0)&&(i.noExitRuntime||(be=!0,Xt=a,k=$,me(on),Do=!0,i.onExit&&i.onExit(a)),i.quit(a,new ye(a)))}function OA(a){throw i.onAbort&&i.onAbort(a),a!==void 0?(Me(a),RA(a),a=JSON.stringify(a)):a="",be=!0,Xt=1,"abort("+a+"). Build with -s ASSERTIONS=1 for more info."}if(i.dynCall_iii=function(){return i.asm.dynCall_iii.apply(null,arguments)},i.asm=gn,i.ccall=zt,i.cwrap=function(E,h,f,R){var P=(f=f||[]).every(function(X){return X==="number"});return h!=="string"&&P&&!R?Wt(E):function(){return zt(E,h,f,arguments,R)}},ye.prototype=Error(),ye.prototype.constructor=ye,pe=function a(){i.calledRun||ut(),i.calledRun||(pe=a)},i.run=ut,i.abort=OA,i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();i.noExitRuntime=!0,ut(),i.onRuntimeInitialized=()=>{os=!0,rs()},VA.decode=function(a){return function(h){if(!os)throw Error("Not initialized");var f={};function R(ie){return new Int32Array(i.HEAPU8.buffer,ie,1)[0]}function P(ie,dt){var ve=new ArrayBuffer(dt*Float32Array.BYTES_PER_ELEMENT),ae=new Float32Array(ve);return ae.set(new Float32Array(i.HEAPU8.buffer,ie,dt)),ae}f.open=i.cwrap("stb_vorbis_js_open","number",[]),f.close=i.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=i.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=i.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=i.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var X,N,QA,iA,aA=f.open(),tA=(X=h,N=h.byteLength,QA=i._malloc(N),(iA=new Uint8Array(i.HEAPU8.buffer,QA,N)).set(new Uint8Array(X,0,N)),iA),q=i._malloc(4),mA=i._malloc(4),GA=f.decode(aA,tA.byteOffset,tA.byteLength,q,mA);if(i._free(tA.byteOffset),GA<0)throw f.close(aA),i._free(q),Error("stbvorbis decode failed: "+GA);for(var xA=f.channels(aA),MA=Array(xA),ee=new Int32Array(i.HEAPU32.buffer,R(q),xA),NA=0;NA=0&&(n=this.workletProcessorChannels[e]),t.messageType){case eA.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case eA.noteOff:this.noteOff(e,A);break;case eA.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case eA.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case eA.customcCcChange:n.customControllers[A[0]]=A[1];break;case eA.killNote:this.killNote(e,A);break;case eA.programChange:this.programChange(e,A[0],A[1]);break;case eA.channelPressure:this.channelPressure(e,A);break;case eA.polyPressure:this.polyPressure(e,A[0],A[1]);break;case eA.ccReset:e===UA?this.resetAllControllers():this.resetControllers(e);break;case eA.systemExclusive:this.systemExclusive(A);break;case eA.setChannelVibrato:if(e===UA)for(let I=0;I{let e=(A.midiControllers[EA+K.pitchWheelRange]>>7)+(A.midiControllers[EA+K.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[EA+K.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:pA.channelProperties,messageData:t})}function Yo(t,A,e){let n=t,s=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:n,centTuning:s*.0061}}function gs(t,A=0){let e=t[0];if(!(this.deviceID!==UA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:T(`%cUnrecognized SysEx: %c${uA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let s;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),p(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),p(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let Q=(t[5]<<7|t[6])-8192;s=Math.floor(Q/81.92),this.setMasterTuning(s),p(`%cMaster Fine Tuning. Cents: %c${s}`,r.info,r.value);break;case 4:s=(t[5]-64)*100,this.setMasterTuning(s),p(`%cMaster Coarse Tuning. Cents: %c${s}`,r.info,r.value);break;default:T(`%cUnrecognized MIDI Device Control Real-time message: %c${uA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(p("%cGM system on",r.info),this.system="gm"):t[3]===3?(p("%cGM2 system on",r.info),this.system="gm2"):(p("%cGM system off, defaulting to GS",r.info),this.system="gs");break;case 8:switch(t[3]){case 2:case 7:let o=4;t[3]===7&&o++;let I=t[o++],C=t[o++];for(let B=0;B>1&1)===1&&this.setOctaveTuning(15+A,Q);for(let B=0;B<7;B++)(t[5]>>B&1)===1&&this.setOctaveTuning(7+B+A,Q);for(let B=0;B<7;B++)(t[6]>>B&1)===1&&this.setOctaveTuning(B+A,Q);p(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${Q.join(" ")}`,r.info,r.value);break;default:T(`%cUnrecognized MIDI Tuning standard message: %c${uA(t)}`,r.warn,r.unrecognized);break}break;default:T(`%cUnrecognized MIDI Realtime/non realtime message: %c${uA(t)}`,r.warn,r.unrecognized)}break;case 65:let n=function(){T(`%cUnrecognized Roland %cGS %cSysEx: %c${uA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let s=t[7];if(t[6]===127){s===0?(p("%cGS Reset received!",r.info),this.resetAllControllers(!1),this.system="gs"):s===127&&(p("%cGS system off, switching to GM2",r.info),this.resetAllControllers(!1),this.system="gm2");return}else if(t[4]===64){if((t[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A;switch(t[6]){default:n();break;case 21:let I=s>0&&t[5]>>4;this.setDrums(o,I),p(`%cChannel %c${o}%c ${I?"is now a drum channel":"now isn't a drum channel"}%c via: %c${uA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=s-64;this.transposeChannel(o,C),p(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${uA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let Q=s;Q===0&&(Q=Math.floor(Math.random()*128)),this.controllerChange(o,m.pan,Q);break;case 33:this.controllerChange(o,m.chorusDepth,s);break;case 34:this.controllerChange(o,m.reverbDepth,s);break;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let B=t.length-9,d=new Int8Array(12);for(let l=0;l=this.workletProcessorChannels.length)return;let o=t[6];switch(t[5]){case 1:this.controllerChange(s,m.bankSelect,o);break;case 2:this.controllerChange(s,m.lsbForControl0BankSelect,o);break;case 3:this.programChange(s,o);break;case 8:let I=this.workletProcessorChannels[s];if(I.drumChannel)return;let C=o-64;I.channelTransposeKeyShift=C;break;case 11:this.controllerChange(s,m.mainVolume,o);break;case 14:let Q=o;Q===0&&(Q=Math.floor(Math.random()*127)),this.controllerChange(s,m.pan,Q);break;case 19:this.controllerChange(s,m.reverbDepth,o);break;case 18:this.controllerChange(s,m.chorusDepth,o);break;default:T(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&T(`%cUnrecognized Yamaha XG SysEx: %c${uA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&T(`%cUnrecognized Yamaha SysEx: %c${uA(t)}`,r.warn,r.unrecognized);break}}function Cs(t,A,e){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=t[A.sourceIndex];else{let Q=A.sourceIndex+EA;switch(A.sourceIndex){case K.noController:n=16383;break;case K.noteOnKeyNum:n=e.midiNote<<7;break;case K.noteOnVelocity:n=e.velocity<<7;break;case K.polyPressure:n=e.pressure<<7;break;default:n=t[Q];break}}let s=oe[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let Q=A.secSrcIndex+EA;switch(A.secSrcIndex){case K.noController:o=16383;break;case K.noteOnKeyNum:o=e.midiNote<<7;break;case K.noteOnVelocity:o=e.velocity<<7;break;case K.polyPressure:o=e.pressure<<7;break;default:o=t[Q]}}let I=oe[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=s*I*A.transformAmount;return A.transformType===2&&(C=Math.abs(C)),A.currentValue=C,C}function XA(t,A,e=-1,n=0){let s=t.modulators,o=t.generators,I=t.modulatedGenerators;if(YA.recalculate(t),e===-1){I.set(o),s.forEach(B=>{let d=U[B.modulatorDestination],c=I[B.modulatorDestination]+Cs(A,B,t);I[B.modulatorDestination]=Math.max(d.min,Math.min(c,d.max))}),LA.recalculate(t);return}let C=new Set([g.initialAttenuation,g.delayVolEnv,g.attackVolEnv,g.holdVolEnv,g.decayVolEnv,g.sustainVolEnv,g.releaseVolEnv,g.keyNumToVolEnvHold,g.keyNumToVolEnvDecay]),Q=new Set;s.forEach(B=>{if(B.sourceUsesCC===e&&B.sourceIndex===n||B.secSrcUsesCC===e&&B.secSrcIndex===n){let d=B.modulatorDestination;Q.has(d)||(I[d]=o[d],Cs(A,B,t),s.forEach(c=>{if(c.modulatorDestination===d){let l=U[B.modulatorDestination],u=I[B.modulatorDestination]+c.currentValue;I[B.modulatorDestination]=Math.max(l.min,Math.min(u,l.max))}}),Q.add(d))}}),[...Q].some(B=>C.has(B))&&LA.recalculate(t)}var oe=[];for(let t=0;t<4;t++){oe[t]=[[new Float32Array(BA),new Float32Array(BA)],[new Float32Array(BA),new Float32Array(BA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||I.isMuted)return;let C=A+I.channelTransposeKeyShift,Q=C;if(A>127||A<0)return;let B=I.preset.program;this.tunings[B]?.[A]?.midiNote>=0&&(Q=this.tunings[B]?.[A].midiNote),I.velocityOverride>0&&(e=I.velocityOverride);let d=this.getWorkletVoices(t,Q,e,I,o,C,n),c=I.voices;d.forEach(l=>{let u=l.generators[g.exclusiveClass];u!==0&&c.forEach(b=>{b.generators[g.exclusiveClass]===u&&(this.releaseVoice(b),b.modulatedGenerators[g.releaseVolEnv]=-7e3,b.modulatedGenerators[g.releaseModEnv]=-7e3,LA.recalculate(b),YA.recalculate(b))}),XA(l,I.midiControllers);let D=l.modulatedGenerators[g.startAddrsOffset]+l.modulatedGenerators[g.startAddrsCoarseOffset]*32768,y=l.modulatedGenerators[g.endAddrOffset]+l.modulatedGenerators[g.endAddrsCoarseOffset]*32768,k=l.modulatedGenerators[g.startloopAddrsOffset]+l.modulatedGenerators[g.startloopAddrsCoarseOffset]*32768,w=l.modulatedGenerators[g.endloopAddrsOffset]+l.modulatedGenerators[g.endloopAddrsCoarseOffset]*32768,G=l.sample,x=b=>Math.max(0,Math.min(G.sampleData.length-1,b));if(G.cursor=x(G.cursor+D),G.end=x(G.end+y),G.loopStart=x(G.loopStart+k),G.loopEnd=x(G.loopEnd+w),G.loopEndthis.voiceCap&&this.voiceKilling(d.length),c.push(...d),s&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Bs(t,A){if(A>127||A<0){T("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift;if(this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(s=>{s.realKey!==e||s.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(s):this.releaseVoice(s))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function hs(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.realKey===A&&(e.modulatedGenerators[g.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function Qs(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(n=>{n.isInRelease||this.releaseVoice(n)}),this.workletProcessorChannels[t].sustainedVoices.forEach(n=>{this.releaseVoice(n)}))}function cs(t=!1){p("%cStop all received!",r.info);for(let A=0;AXA(s,this.workletProcessorChannels[t].midiControllers,0,K.pitchWheel)),this.sendChannelProperties()}function Ss(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[EA+K.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(n=>XA(n,e.midiControllers,0,K.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function Ds(t,A,e){this.workletProcessorChannels[t].voices.forEach(n=>{n.midiNote===A&&(n.pressure=e,XA(n,this.workletProcessorChannels[t].midiControllers,0,K.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function ks(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function ws(t,A,e,n=!1){let s=this.workletProcessorChannels[t];if(s===void 0){T(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>127){if(!n)return;switch(A){default:return;case wt.velocityOverride:s.velocityOverride=e}}if(A>=m.lsbForControl1ModulationWheel&&A<=m.lsbForControl13EffectControl2&&A!==m.lsbForControl6DataEntry){let o=A-32;if(s.lockedControllers[o])return;s.midiControllers[o]=s.midiControllers[o]&16256|e&127,s.voices.forEach(I=>XA(I,s.midiControllers,1,o))}switch(A){case m.allNotesOff:this.stopAll(t);break;case m.allSoundOff:this.stopAll(t,!0);break;case m.bankSelect:let o=e;if(!n){switch(this.system){case"gm":p(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==SA&&this.setDrums(t,!1);break;case"gm2":o===120&&(s.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}s.drumChannel&&(o=128),o===128&&!s.drumChannel&&(o=s.midiControllers[m.bankSelect])}s.midiControllers[m.bankSelect]=o;break;case m.lsbForControl0BankSelect:this.system==="xg"?s.drumChannel||e!==127&&(s.midiControllers[m.bankSelect]=e):this.system==="gm2"&&(s.midiControllers[m.bankSelect]=e);break;case m.RPNLsb:s.RPValue=s.RPValue<<7|e,s.dataEntryState=fA.RPFine;break;case m.RPNMsb:s.RPValue=e,s.dataEntryState=fA.RPCoarse;break;case m.NRPNMsb:s.NRPCoarse=e,s.dataEntryState=fA.NRPCoarse;break;case m.NRPNLsb:s.NRPFine=e,s.dataEntryState=fA.NRPFine;break;case m.dataEntryMsb:this.dataEntryCoarse(t,e);break;case m.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case m.resetAllControllers:this.resetControllers(t);break;case m.sustainPedal:e>=64?s.holdPedal=!0:(s.holdPedal=!1,s.sustainedVoices.forEach(I=>{this.releaseVoice(I)}),s.sustainedVoices=[]);break;default:if(s.lockedControllers[A])return;s.midiControllers[A]=e<<7,s.voices.forEach(I=>XA(I,s.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function Fs(t){this.midiVolume=t,this.setMasterPan(this.pan)}function Rs(t){this.masterGain=t*Ut,this.setMasterPan(this.pan)}function Gs(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function xs(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function Ms(t){this.workletProcessorChannels[t].lockGSNRPNParams=!0,this.workletProcessorChannels[t].channelVibrato.rate=0,this.workletProcessorChannels[t].channelVibrato.delay=0,this.workletProcessorChannels[t].channelVibrato.depth=0}function Ns(t,A,e,n){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=n,this.workletProcessorChannels[t].channelVibrato.depth=A)}function bs(t,A){let e=this.workletProcessorChannels[t],n=()=>{e.channelVibrato.delay===0&&e.channelVibrato.rate===0&&e.channelVibrato.depth===0&&(e.channelVibrato.depth=50,e.channelVibrato.rate=8,e.channelVibrato.delay=.6)};switch(e.dataEntryState){default:case fA.Idle:break;case fA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;T(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16).toUpperCase()} 0x${e.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 1:switch(e.NRPFine){default:if(A===64)return;T(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16)} 0x${e.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(A===64)return;n(),e.channelVibrato.rate=A/64*8,p(`%cVibrato rate for %c${t}%c is now set to %c${A} = ${e.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(A===64)return;n(),e.channelVibrato.depth=A/2,p(`%cVibrato depth for %c${t}%c is now set to %c${A} = ${e.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(A===64)return;n(),e.channelVibrato.delay=A/64/3,p(`%cVibrato delay for %c${t}%c is now set to %c${A} = ${e.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let I=A;this.controllerChange(t,m.brightness,A),p(`%cFilter cutoff for %c${t}%c is now set to %c${I}`,r.info,r.recognized,r.info,r.value)}break;case 24:let s=A-64;e.keyCentTuning[e.NRPFine]=s*100,p(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${s}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,m.reverbDepth,o),p(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:T(`%cUnrecognized RPN for %c${t}%c: %c(0x${e.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:e.midiControllers[EA+K.pitchWheelRange]=A<<7,p(`%cChannel ${t} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(t,A-64);break;case 1:this.setChannelTuning(t,A-64,!1);break;case 5:this.setModulationDepth(t,A*100);break;case 16383:this.resetParameters(t);break}}}function Ls(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[EA+K.pitchWheelRange]|=A;let n=(e.midiControllers[EA+K.pitchWheelRange]>>7)+A/127;p(`%cChannel ${t} bend range. Semitones: %c${n}`,r.info,r.value);break;case 1:let o=e.customControllers[gA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[gA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function Us(t=!0){t&&p("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A{this.workletProcessorChannels[A].lockedControllers[s]&&this.callEvent("controllerchange",{channel:A,controllerNumber:s,controllerValue:this.workletProcessorChannels[A].midiControllers[s]>>7})};if(n(m.mainVolume),n(m.pan),n(m.expressionController),n(m.modulationWheel),n(m.chorusDepth),n(m.reverbDepth),n(m.brightness),this.workletProcessorChannels[A].lockedControllers[EA+K.pitchWheel]){let s=this.workletProcessorChannels[A].midiControllers[EA+K.pitchWheel],o=s>>7,I=s&127;this.callEvent("pitchwheel",{channel:A,MSB:o,LSB:I})}}this.tunings=[],this.tunings=[];for(let A=0;127>A;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Oe}function Ts(t){let A=this.workletProcessorChannels[t],n=A.lockedControllers.reduce((o,I,C)=>(I&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(St),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,n.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let s=A.customControllers[gA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[gA.channelTransposeFine]=s,this.resetParameters(t)}function Hs(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=fA.Idle}function Ys(){let t=4;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==g.sampleID&&I.generatorType!==g.keyRange&&I.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+s),0);let A=new Y(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.generatorZoneStartIndex=e;for(let o of s.generators)J(A,o.generatorType),J(A,o.generatorValue),e++}return lA(A,0),nA(new AA("igen",A.length,A))}function Js(t,A,e,n,s){let o=this.samples.map((B,d)=>{e&&B.compressSample(n,s);let c=B.getRawData();return p(`%cEncoded sample %c${d}. ${B.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),c}),I=this.samples.reduce((B,d,c)=>B+o[c].length+46,0),C=new Y(I);this.samples.forEach((B,d)=>{let c=o[d],l,u,D=c.length;B.isCompressed?(l=C.currentIndex,u=l+c.length):(l=C.currentIndex/2,u=l+c.length/2,D+=46),t.push(l),C.set(c,C.currentIndex),C.currentIndex+=D,A.push(u)});let Q=nA(new AA("smpl",C.length,C),new Y([115,100,116,97]));return nA(new AA("LIST",Q.length,Q))}function vs(t,A){let n=new Y(46*(this.samples.length+1));return this.samples.forEach((s,o)=>{FA(n,s.sampleName,20);let I=t[o];lA(n,I);let C=A[o];lA(n,C);let Q=s.sampleLoopStartIndex+I,B=s.sampleLoopEndIndex+I;s.isCompressed&&(Q-=I,B-=I),lA(n,Q),lA(n,B),lA(n,s.sampleRate),n[n.currentIndex++]=s.samplePitch,n[n.currentIndex++]=s.samplePitchCorrection,J(n,s.sampleLink),J(n,s.sampleType)}),FA(n,"EOS",46),nA(new AA("shdr",n.length,n))}function qs(){let t=10;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new Y(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)J(A,o.sourceEnum),J(A,o.modulatorDestination),J(A,o.transformAmount),J(A,o.secondarySourceEnum),J(A,o.transformType),e++}return Ee(A,0,10),nA(new AA("imod",A.length,A))}function Ps(){let t=this.instruments.reduce((o,I)=>I.instrumentZones.length*4+o,4),A=new Y(t),e=0,n=0,s=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let I of o.instrumentZones)I.zoneID=e,J(A,n),J(A,s),n+=I.generators.length,s+=I.modulators.length,e++}return J(A,n),J(A,s),nA(new AA("ibag",A.length,A))}function Ks(){let t=this.instruments.length*22+22,A=new Y(t),e=0,n=0;for(let s of this.instruments)FA(A,s.instrumentName,20),J(A,e),e+=s.instrumentZones.length,s.instrumentID=n,n++;return FA(A,"EOI",20),J(A,e),nA(new AA("inst",A.length,A))}function Vs(){let t=4;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==g.instrument&&I.generatorType!==g.keyRange&&I.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+s),0);let A=new Y(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.generatorZoneStartIndex=e;for(let o of s.generators)J(A,o.generatorType),J(A,o.generatorValue);e+=s.generators.length}return J(A,0),J(A,0),nA(new AA("pgen",A.length,A))}function Os(){let t=10;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new Y(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)J(A,o.sourceEnum),J(A,o.modulatorDestination),J(A,o.transformAmount),J(A,o.secondarySourceEnum),J(A,o.transformType),e++}return Ee(A,0,10),nA(new AA("pmod",A.length,A))}function Zs(){let t=this.presets.reduce((o,I)=>I.presetZones.length*4+o,4),A=new Y(t),e=0,n=0,s=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let I of o.presetZones)I.zoneID=e,J(A,n),J(A,s),n+=I.generators.length,s+=I.modulators.length,e++}return J(A,n),J(A,s),nA(new AA("pbag",A.length,A))}function Xs(){let t=this.presets.length*38+38,A=new Y(t),e=0;for(let n of this.presets)FA(A,n.presetName,20),J(A,n.program),J(A,n.bank),J(A,e),lA(A,n.library),lA(A,n.genre),lA(A,n.morphology),e+=n.presetZones.length;return FA(A,"EOP",20),J(A,0),J(A,0),J(A,e),lA(A,0),lA(A,0),lA(A,0),nA(new AA("phdr",A.length,A))}var Jo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Ws(t=Jo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");yA("%cSaving soundfont...",r.info),p(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),p("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[b,$]of Object.entries(this.soundFontInfo))if(b==="ifil"||b==="iver"){let i=parseInt($.split(".")[0]),sA=parseInt($.split(".")[1]),_=new Y(4);J(_,i),J(_,sA),A.push(nA(new AA(b,4,_)))}else if(b==="DMOD")A.push(nA(new AA(b,$.length,$)));else{let i=new Y($.length);FA(i,$),A.push(nA(new AA(b,$.length,i)))}let e=ke([new Y([73,78,70,79]),...A]),n=nA(new AA("LIST",e.length,e));p("%cWriting SDTA...",r.info);let s=[],o=[],I=Js.call(this,s,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);p("%cWriting PDTA...",r.info),p("%cWriting SHDR...",r.info);let C=vs.call(this,s,o);p("%cWriting IGEN...",r.info);let Q=Ys.call(this);p("%cWriting IMOD...",r.info);let B=qs.call(this);p("%cWriting IBAG...",r.info);let d=Ps.call(this);p("%cWriting INST...",r.info);let c=Ks.call(this),l=Vs.call(this);p("%cWriting PMOD...",r.info);let u=Os.call(this);p("%cWriting PBAG...",r.info);let D=Zs.call(this);p("%cWriting PHDR...",r.info);let y=Xs.call(this),k=ke([new Y([112,100,116,97]),y,D,u,l,c,d,B,Q,C]),w=nA(new AA("LIST",k.length,k));p("%cWriting the output file...",r.info);let G=ke([new Y([115,102,98,107]),n,I,w]),x=nA(new AA("RIFF",G.length,G));return p(`%cSaved succesfully! Final file size: %c${x.length}`,r.info,r.recognized),Z(),x}var re=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Pe.map(e=>j.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}static mergeSoundfonts(...A){let e=A.shift(),n=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(I=>I.bank===o.bank&&I.program===o.program)===void 0&&n.push(o)});return new t({presets:n,info:e.soundFontInfo})}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPresetNoFallback(A,e,n=!1){let s=this.presets.find(o=>o.bank===A&&o.program===e);if(s)return s;if(n!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}getPreset(A,e){let n=this.presets.find(s=>s.bank===A&&s.program===e);return n||(A===128?(n=this.presets.find(s=>s.bank===128&&s.program===e),n||(n=this.presets.find(s=>s.bank===128))):n=this.presets.find(s=>s.program===e&&s.bank!==128),n&&T(`%cPreset ${A}.${e} not found. Replaced with %c${n.presetName} (${n.bank}.${n.program})`,r.warn,r.recognized)),n||(T(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),n=this.presets[0]),n}getPresetByName(A){let e=this.presets.find(n=>n.presetName===A);return e||(T("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}};re.prototype.write=Ws;function _s(t){yA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let n=A;n{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}getSamplesAndGenerators(A,e){let n=this.foundSamplesAndGenerators[A][e];if(n)return n;if(this.presetZones.length<1)return[];function s(c,l,u){return u>=c&&u<=l}function o(c,l){c.push(...l.filter(u=>!c.find(D=>D.generatorType===u.generatorType)))}function I(c,l){c.push(...l.filter(u=>!c.find(D=>j.isIdentical(u,D))))}let C=[],Q=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],B=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(c=>s(c.keyRange.min,c.keyRange.max,A)&&s(c.velRange.min,c.velRange.max,e)&&!c.isGlobal).forEach(c=>{if(c.instrument.instrumentZones.length<1)return;let l=c.generators,u=c.modulators,D=c.instrument.instrumentZones[0].isGlobal?[...c.instrument.instrumentZones[0].generators]:[],y=c.instrument.instrumentZones[0].isGlobal?[...c.instrument.instrumentZones[0].modulators]:[];c.instrument.instrumentZones.filter(w=>s(w.keyRange.min,w.keyRange.max,A)&&s(w.velRange.min,w.velRange.max,e)&&!w.isGlobal).forEach(w=>{let G=[...w.generators],x=[...w.modulators];o(l,Q),o(G,D),I(u,B),I(x,y),I(x,this.defaultModulators);let b=[...x];for(let $=0;$j.isIdentical(i,_));sA!==-1?b[sA]=b[sA].sumTransform(i):b.push(i)}C.push({instrumentGenerators:G,presetGenerators:l,modulators:b,sample:w.sample,sampleID:w.generators.find($=>$.generatorType===g.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=C,C}};var Re=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var $A=class extends Re{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},le=class extends Re{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var ue=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}get useCount(){return this._useCount}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var At=class extends ce{constructor(A,e){super(Pe),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new ue,this.DLSInstrument.addUseCount();let s=new le;s.instrument=this.DLSInstrument,this.presetZones=[s]}};function zs(t){this.verifyHeader(t,"LIST"),this.verifyText(V(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(u=>u.header==="insh");if(!e)throw Z(),new Error("No instrument header!");let n=S(e.chunkData,4),s=S(e.chunkData,4),o=S(e.chunkData,4),I=new At(s,o),C="unnamedPreset",Q=DA(A,"INFO");if(Q){let u=O(Q.chunkData);for(;u.header!=="INAM";)u=O(Q.chunkData);C=V(u.chunkData,u.chunkData.length).trim()}I.presetName=C,I.DLSInstrument.instrumentName=C,te(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let B=DA(A,"lrgn");if(!B)throw Z(),new Error("No region list!");let d=new $A;d.isGlobal=!0;let c=DA(A,"lart"),l=DA(A,"lar2");this.readLart(c,l,d),I.DLSInstrument.instrumentZones.push(d);for(let u=0;u>10&15;w===cA.linear&&k!==cA.linear&&(w=k);let G=n>>14&1,x=n>>15&1;I===g.initialAttenuation&&(x=!x),c=TA(w,G,x,C.isCC,C.enum)}let l=n>>4&15,u=n>>8&1,D=n>>9&1,y=TA(l,u,D,d.isCC,d.enum);if(Q){let k=y;y=c,c=k}return new j({srcEnum:c,secSrcEnum:y,dest:I,transform:0,amt:s})}function Tt(t,A){let e=t.chunkData,n=[],s=[];S(e,4);let o=S(e,4);for(let I=0;I>16;if(C===0&&Q===0&&d===0){let u;switch(B){case M.pan:u=new L(g.pan,l);break;case M.gain:u=new L(g.initialAttenuation,-l*10/.4);break;case M.filterCutoff:u=new L(g.initialFilterFc,l);break;case M.filterQ:u=new L(g.initialFilterQ,l);break;case M.modLfoFreq:u=new L(g.freqModLFO,l);break;case M.modLfoDelay:u=new L(g.delayModLFO,l);break;case M.vibLfoFreq:u=new L(g.freqVibLFO,l);break;case M.vibLfoDelay:u=new L(g.delayVibLFO,l);break;case M.volEnvDelay:u=new L(g.delayVolEnv,l);break;case M.volEnvAttack:u=new L(g.attackVolEnv,l);break;case M.volEnvHold:u=new L(g.holdVolEnv,l);break;case M.volEnvDecay:u=new L(g.decayVolEnv,l);break;case M.volEnvRelease:u=new L(g.releaseVolEnv,l);break;case M.volEnvSustain:let D=(1e3-l)/10;u=new L(g.sustainVolEnv,D*10);break;case M.modEnvDelay:u=new L(g.delayModEnv,l);break;case M.modEnvAttack:u=new L(g.attackModEnv,l);break;case M.modEnvHold:u=new L(g.holdModEnv,l);break;case M.modEnvDecay:u=new L(g.decayModEnv,l);break;case M.modEnvRelease:u=new L(g.releaseModEnv,l);break;case M.modEnvSustain:let y=1e3-l;u=new L(g.sustainModEnv,y);break;case M.reverbSend:u=new L(g.reverbEffectsSend,l);break;case M.chorusSend:u=new L(g.chorusEffectsSend,l);break;case M.pitch:let k=Math.floor(l/100),w=Math.floor(l-k*100);u=new L(g.fineTune,w),n.push(new L(g.coarseTune,k));break}u&&n.push(u)}else{let u=!0;if(Q===W.none)if(C===W.modLfo&&B===M.pitch)n.push(new L(g.modLfoToPitch,l));else if(C===W.modLfo&&B===M.gain)n.push(new L(g.modLfoToVolume,l));else if(C===W.modLfo&&B===M.filterCutoff)n.push(new L(g.modLfoToFilterFc,l));else if(C===W.vibratoLfo&&B===M.pitch)n.push(new L(g.vibLfoToPitch,l));else if(C===W.modEnv&&B===M.pitch)n.push(new L(g.modEnvToPitch,l));else if(C===W.modEnv&&B===M.filterCutoff)n.push(new L(g.modEnvToFilterFc,l));else if(C===W.keyNum&&B===M.volEnvHold){n.push(new L(g.keyNumToVolEnvHold,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.holdVolEnv&&(y.generatorValue+=D)})}else if(C===W.keyNum&&B===M.volEnvDecay){n.push(new L(g.keyNumToVolEnvDecay,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.decayVolEnv&&(y.generatorValue+=D)})}else if(C===W.keyNum&&B===M.modEnvHold){n.push(new L(g.keyNumToModEnvHold,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.holdModEnv&&(y.generatorValue+=D)})}else if(C===W.keyNum&&B===M.modEnvDecay){n.push(new L(g.keyNumToModEnvDecay,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.decayModEnv&&(y.generatorValue+=D)})}else u=!1;else u=!1;if(u===!1){let D=$s(C,Q,B,d,l);D?(s.push(D),p("%cSucceeded converting to SF2 Modulator!",r.recognized)):T("Failed converting to SF2 Modulator!")}}}return s.find(I=>I.modulatorDestination===g.reverbEffectsSend)===void 0&&s.push(new j({srcEnum:219,dest:g.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),s.find(I=>I.modulatorDestination===g.chorusEffectsSend)===void 0&&s.push(new j({srcEnum:221,dest:g.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&s.push(new j({srcEnum:129,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new j({srcEnum:13,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:s,generators:n}}function Ao(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(_=>_.header==="rgnh"),n=S(e.chunkData,2),s=S(e.chunkData,2),o=S(e.chunkData,2),I=S(e.chunkData,2),C=new et({min:n,max:s},{min:o,max:I});S(e.chunkData,2);let Q=S(e.chunkData,2);Q!==0&&C.generators.push(new L(g.exclusiveClass,Q));let B=DA(A,"lart"),d=DA(A,"lar2");this.readLart(B,d,C),C.isGlobal=!1;let c=A.find(_=>_.header==="wsmp");S(c.chunkData,4);let l=S(c.chunkData,2),u=jA(c.chunkData[c.chunkData.currentIndex++],c.chunkData[c.chunkData.currentIndex++]),y=(S(c.chunkData,4)|0)/-655360;S(c.chunkData,4);let k=S(c.chunkData,4),w,G={start:0,end:0};if(k===0)w=0;else{S(c.chunkData,4),S(c.chunkData,4)===0?w=1:w=3,G.start=S(c.chunkData,4);let v=S(c.chunkData,4);G.end=G.start+v}let x=A.find(_=>_.header==="wlnk");if(x===void 0)return;S(x.chunkData,2),S(x.chunkData,2),S(x.chunkData,4);let b=S(x.chunkData,4),$=this.samples[b];if($===void 0)throw new Error("Invalid sample ID!");let sA=(y||$.sampleDbAttenuation)*10/.4;return C.setWavesample(sA,w,G,l,$,b,u),C}var de=class{constructor(A,e,n,s,o,I,C,Q){this.sampleName=A,this.sampleRate=e,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=I,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=Q,this.isCompressed=(I&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,e){if(!this.isCompressed)try{this.compressedData=e([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{T(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}};var tt=class extends de{sampleDbAttenuation;sampleData;constructor(A,e,n,s,o,I,C,Q){super(A,e,n,s,0,1,o,I-1),this.sampleData=C,this.sampleDbAttenuation=Q}getAudioData(){return this.sampleData}getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let e=0;e>8&255}return A}};function to(t){yA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexv.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");if(S(s.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(S(s.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=S(s.chunkData,4);S(s.chunkData,4),S(s.chunkData,2);let Q=S(s.chunkData,2),B=Q/8,d=Math.pow(2,B*8-1),c=Math.pow(2,B*8),l,u=!1;Q===8?(l=255,u=!0):l=d;let D=n.find(v=>v.header==="data");if(!D)throw new Error("No data chunk in the wave chunk!");let y=D.size/B,k=new Float32Array(y);for(let v=0;v=d&&(z-=c),k[v]=z/l)}let w=60,G=0,x=0,b=k.length-1,$=0,i=n.find(v=>v.header==="wsmp");if(i){if(S(i.chunkData,4),w=S(i.chunkData,2),G=jA(i.chunkData[i.chunkData.currentIndex++],i.chunkData[i.chunkData.currentIndex++]),$=(S(i.chunkData,4)|0)/-655360,S(i.chunkData,4),S(i.chunkData,4)===1){S(i.chunkData,8),x=S(i.chunkData,4);let oA=S(i.chunkData,4);b=x+oA}}else T("No wsmp chunk in wave... using sane defaults.");let sA=DA(n,"INFO"),_=`Unnamed ${A}`;if(sA){let v=O(sA.chunkData);for(;v.header!=="INAM"&&sA.chunkData.currentIndex(w.messageStatusByte&240)===F.noteOn);k&&u.push(k.ticks)}this.firstNoteOn=Math.min(...u),p(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&c===null?(d=this.firstNoteOn,c=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(c===null||c===0)&&(c=this.lastVoiceEventTick)),this.loop={start:d,end:c},p(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let D=0;for(let y of this.midiPorts)if(y!==-1){D=y;break}if(this.midiPorts=this.midiPorts.map(y=>y===-1?D:y),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?p("%cNo additional MIDI Ports detected.",r.info):p("%cMIDI Ports detected!",r.recognized),!I)if(this.tracks.length>1){if(this.tracks[0].find(y=>y.messageStatusByte>=F.noteOn&&y.messageStatusBytek.messageStatusByte===F.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=V(y.messageData,y.messageData.length,void 0,!1))}}else{let y=this.tracks[0].find(k=>k.messageStatusByte===F.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=V(y.messageData,y.messageData.length,void 0,!1))}if(this.fileName=e,this.midiName=this.midiName.trim(),this.midiName.length===0){p("%cNo name detected. Using the alt name!",r.info),this.midiName=hn(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let y=0;yl>c?l:c),n=[];for(let c=0;c{I[D]>=u.length||u[I[D]].ticks0;){let c=Q(),l=t.tracks[c];if(I[c]>=l.length){C--;continue}let u=l[I[c]];if(I[c]++,u.messageStatusByte===F.midiPort){B[c]=u.messageData[0];continue}let D=u.messageStatusByte&240;if(D!==F.noteOn&&D!==F.controllerChange&&D!==F.programChange&&D!==F.systemExclusive)continue;let y=(u.messageStatusByte&15)+t.midiPortChannelOffsets[B[c]]||0,k=n[y];switch(D){case F.programChange:k.program=u.messageData[0],s(k);break;case F.controllerChange:if(u.messageData[0]!==m.bankSelect||d==="gs"&&k.drums)continue;let w=u.messageData[1],G=Math.max(0,w-t.bankOffset);if(d==="xg"){let $=w===120||w===126||w===127;$!==k.drums?(k.drums=$,k.bank=k.drums?128:G,s(k)):k.bank=k.drums?128:G;continue}n[y].bank=G;break;case F.noteOn:if(u.messageData[1]===0)continue;s(k),o[k.string].add(`${u.messageData[0]}-${u.messageData[1]}`);break;case F.systemExclusive:if(u.messageData[0]!==65||u.messageData[2]!==66||u.messageData[3]!==18||u.messageData[4]!==64||!(u.messageData[5]&16)||u.messageData[6]!==21){u.messageData[0]===67&&u.messageData[2]===76&&u.messageData[5]===126&&u.messageData[6]===0&&(d="xg");continue}let x=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+t.midiPortChannelOffsets[B[c]],b=!!(u.messageData[7]>0&&u.messageData[5]>>4);k=n[x],k.drums=b,k.bank=b?128:0,s(k);break}}for(let c of Object.keys(o))o[c].size===0&&(p(`%cDetected change but no keys for %c${c}`,r.info,r.value),delete o[c]);return Z(),o}function Mn(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(n,e)}),this.duration=this.midiData.duration,this.firstNoteTime=Be(this.midiData.firstNoteOn,this.midiData),p(`%cTotal song time: ${mt(Math.ceil(this.duration)).time}`,r.recognized),this.post(wA.songChange,[new Ze(this.midiData),this.songIndex,A]),this.duration<=1&&(T(`%cVery short song: (${mt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),A)this.play(!0);else{let e=this._skipToFirstNoteOn?this.midiData.firstNoteOn-1:0;this.setTimeTicks(e),this.pause()}}function bn(t,A=!0){this.songs=t.reduce((e,n)=>{if(n.duration)return e.push(n),e;try{e.push(new ze(n.binary,n.altName||""))}catch(s){return this.post(wA.midiError,s.message),e}return e},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex],A))}function Ln(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Un(){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[m.mainVolume]=100;PA[m.expressionController]=127;PA[m.pan]=64;PA[m.releaseTime]=64;PA[m.brightness]=64;PA[m.reverbDepth]=0;function Tn(t,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let e=this.synth.workletProcessorChannels.length,n=Array(e).fill(8192),s=[];for(let C=0;CC===m.dataDecrement||C===m.dataIncrement||C===m.dataEntryMsb||C===m.dataDecrement||C===m.lsbForControl6DataEntry||C===m.RPNLsb||C===m.RPNMsb||C===m.NRPNLsb||C===m.NRPNMsb||C===m.bankSelect||C===m.lsbForControl0BankSelect||C===m.resetAllControllers,I=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let B=we(Q.messageStatusByte),d=B.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(B.status){case F.noteOn:case F.noteOff:case F.keySignature:break;case F.pitchBend:n[d]=Q.messageData[1]<<7|Q.messageData[0];break;case F.programChange:let l=s[d];l.program=Q.messageData[0],l.actualBank=l.bank;break;case F.controllerChange:let u=Q.messageData[0];if(o(u)){let D=Q.messageData[1];if(u===m.bankSelect){s[d].bank=D;break}this.sendMIDIMessages?this.sendMIDICC(d,u,D):this.synth.controllerChange(d,u,D)}else I[d]===void 0&&(I[d]=Array.from(PA)),I[d][u]=Q.messageData[1];break;default:this._processEvent(Q,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let c=this.tracks[C][this.eventIndex[C]];if(c===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(c.ticks-Q.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7,n[C]&127),I[C]!==void 0&&I[C].forEach((Q,B)=>{Q!==PA[B]&&!o(B)&&this.sendMIDICC(C,B,Q)}),s[C].program>=0&&s[C].actualBank>=0){let Q=s[C].actualBank;this.sendMIDICC(C,m.bankSelect,Q),this.sendMIDIProgramChange(C,s[C].program)}}else for(let C=0;C>7,n[C]&127),I[C]!==void 0&&I[C].forEach((Q,B)=>{Q!==PA[B]&&!o(B)&&this.synth.controllerChange(C,B,Q)}),s[C].program>=0&&s[C].actualBank>=0){let Q=s[C].actualBank;this.synth.controllerChange(C,m.bankSelect,Q),this.synth.programChange(C,s[C].program)}return!0}function Hn(t=!1){if(this.midiData!==void 0){if(t){this.currentTime=0;return}if(this.currentTime>=this.duration){this.currentTime=0;return}this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),this.sendMIDIMessages||this.playingNotes.forEach(A=>{this.synth.noteOn(A.channel,A.midiNote,A.velocity,!1,!0)}),this.setProcessHandler()}}function Yn(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(wA.timeChange,currentTime-Be(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Jn(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function vn(t,A){switch(t){default:break;case LA.loadNewSongList:this.loadNewSongList(A[0],A[1]);break;case LA.pause:this.pause();break;case LA.play:this.play(A);break;case LA.stop:this.stop();break;case LA.setTime:this.currentTime=A;break;case LA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case LA.setPlaybackRate:this.playbackRate=A;break;case LA.setLoop:this.loop=A;break;case LA.changeSong:A?this.nextSong():this.previousSong();break;case LA.getMIDI:this.post(wA.getMIDI,this.midiData);break;case LA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function qn(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:pA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Pn(t){this.post(wA.midiEvent,t)}function Kn(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|t,A,e])}function Vn(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|t,A])}function On(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|t,e,A])}function Zn(){if(this.sendMIDIMessages){this.sendMIDIMessage([F.reset]);for(let t=0;tthis.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&AXn?440*Math.pow(2,(t-6900)/1200):Rt[~~t-je]}var xt=-1660,Lo=1600,Gt=new Float32Array((Lo-xt)*100+1);for(let t=0;t.5?1:0,n?e*2-1:e;case cA.concave:return n?(e=e*2-1,e<0?-ZA[~~(e*-BA)]:ZA[~~(e*BA)]):ZA[~~(e*BA)];case cA.convex:return n?(e=e*2-1,e<0?-ne[~~(e*-BA)]:ne[~~(e*BA)]):ne[~~(e*BA)]}}var Mt=1,Nt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)n-=o;let C=~~n,Q=C+1;for(;Q>=e.loopEnd;)Q-=o;let B=n-C,d=s[Q],c=s[C];A[I]=c+(d-c)*B,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end){t.finished=!0;return}let Q=n-I,B=s[C],d=s[I];A[o]=d+(B-d)*Q,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function _n(t,A){let e=t.sample,n=e.cursor,s=e.loopEnd-e.loopStart,o=e.sampleData;if(t.sample.isLooping)for(let I=0;I=e.loopEnd;)n-=s;let C=~~n+1;for(;C>=e.loopEnd;)C-=s;A[I]=o[C],n+=e.playbackStep*t.currentTuningCalculated}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let I=0;I=e.end){t.finished=!0;return}A[I]=o[C],n+=e.playbackStep*t.currentTuningCalculated}}e.cursor=n}function zn(t,A){let e=t.sample,n=e.cursor,s=e.sampleData;if(e.isLooping){let o=e.loopEnd-e.loopStart;for(let I=0;I=e.loopEnd;)n-=o;let C=~~n,Q=C+1,B=Q+1,d=B+1,c=n-C;Q>=e.loopEnd&&(Q-=o),B>=e.loopEnd&&(B-=o),d>=e.loopEnd&&(d-=o);let l=s[C],u=s[Q],D=s[B],y=s[d],k=.5*(D-l),w=l-2.5*u+2*D-.5*y,G=.5*(y-l)+1.5*(u-D);A[I]=((G*c+w)*c+k)*c+u,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end||Q>=e.end||B>=e.end){t.finished=!0;return}let c=s[I],l=s[C],u=s[Q],D=s[B],y=.5*(u-c),k=c-2.5*l+2*u-.5*D,w=.5*(D-c)+1.5*(l-u);A[o]=((w*d+k)*d+y)*d+l,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function jn(t,A,e,n,s,o,I,C,Q){if(!isNaN(e[0])){if(I>0){let B=o[0],d=o[1];I=Math.min(I,1e3);let c=I/4600;for(let l=0;l0){let B=C[0],d=C[1];Q=Math.min(Q,1e3);let c=Q/1300,l=t*c,u=A*c;for(let D=0;D0)for(let B=0;B0)for(let B=0;B13499&&A.filter.reasonanceCb===0)return;let o=A.filter;(o.cutoffCents!==n||o.reasonanceCb!==A.modulatedGenerators[g.initialFilterQ])&&(o.cutoffCents=n,o.reasonanceCb=A.modulatedGenerators[g.initialFilterQ],t.calculateCoefficients(o));for(let I=0;I=bt}static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=KA(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static recalculate(A){let e=A.volumeEnvelope,n=B=>Math.max(0,Math.floor(YA(B)*e.sampleRate));e.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[g.initialAttenuation],1440))/10,e.sustainDbRelative=Math.min(RA,A.modulatedGenerators[g.sustainVolEnv]/10);let s=Math.min(RA,e.sustainDbRelative);e.attackDuration=n(A.modulatedGenerators[g.attackVolEnv]);let o=A.modulatedGenerators[g.decayVolEnv],I=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvDecay],C=s/RA;e.decayDuration=n(o+I)*C,e.releaseDuration=n(A.modulatedGenerators[g.releaseVolEnv]),e.delayEnd=n(A.modulatedGenerators[g.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let Q=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvHold];if(e.holdEnd=n(A.modulatedGenerators[g.holdVolEnv]+Q)+e.attackEnd,e.decayEnd=e.decayDuration+e.holdEnd,e.state===0&&e.attackEnd===0&&(e.state=2),A.isInRelease){let B=Math.max(0,Math.min(RA,e.sustainDbRelative)),d=B/RA;switch(e.decayDuration=n(o+I)*d,e.state){case 0:e.releaseStartDb=RA;break;case 1:let l=1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration;e.releaseStartDb=20*Math.log10(l)*-1;break;case 2:e.releaseStartDb=0;break;case 3:e.releaseStartDb=(1-(e.decayEnd-e.releaseStartTimeSamples)/e.decayDuration)*B;break;case 4:e.releaseStartDb=B;break}e.releaseStartDb=Math.max(0,Math.min(e.releaseStartDb,RA)),e.releaseStartDb>=bt&&(A.finished=!0),e.currentReleaseGain=KA(e.releaseStartDb);let c=(RA-e.releaseStartDb)/RA;e.releaseDuration*=c}}static apply(A,e,n,s){let o=A.volumeEnvelope,I=n/10,C=s;if(A.isInRelease){let B=o.currentSampleTime-o.releaseStartTimeSamples;if(B>=o.releaseDuration){for(let c=0;c=e.length)return;o.state++;case 1:for(;o.currentSampleTime=e.length)return}o.state++;case 2:for(;o.currentSampleTime=e.length)return;o.state++;case 3:for(;o.currentSampleTime=e.length)return;o.state++;case 4:for(o.canEndOnSilentSustain&&o.sustainDbRelative>=bt&&(A.finished=!0);;)if(o.attenuation+=(o.attenuationTarget-o.attenuation)*C,e[Q]*=KA(o.sustainDbRelative+I+o.attenuation),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++Q>=e.length)return}}};var As=Math.PI/2,es=.05;function ts(t,A,e,n,s,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,UA.startRelease(A),JA.startRelease(A),A.sample.loopingMode===3&&(A.sample.isLooping=!1)),A.modulatedGenerators[g.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let I=A.targetKey,C=A.modulatedGenerators[g.fineTune]+t.customControllers[gA.channelTuning]+t.customControllers[gA.channelTransposeFine]+t.customControllers[gA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],Q=A.modulatedGenerators[g.coarseTune]+t.customControllers[gA.channelTuningSemitones],B=this.tunings[t.preset.program]?.[A.realKey];B?.midiNote>=0&&(I=B.midiNote,C+=B.centTuning),C+=(I-A.sample.rootKey)*A.modulatedGenerators[g.scaleTuning];let d=A.modulatedGenerators[g.vibLfoToPitch];if(d!==0){let oA=A.startTime+YA(A.modulatedGenerators[g.delayVibLFO]),rA=Fe(A.modulatedGenerators[g.freqVibLFO]),CA=$e(oA,rA,currentTime);C+=CA*(d*t.customControllers[gA.modulationMultiplier])}let c=A.modulatedGenerators[g.initialFilterFc],l=c,u=A.modulatedGenerators[g.modLfoToPitch],D=A.modulatedGenerators[g.modLfoToVolume],y=A.modulatedGenerators[g.modLfoToFilterFc],k=0;if(u+y+D!==0){let oA=A.startTime+YA(A.modulatedGenerators[g.delayModLFO]),rA=Fe(A.modulatedGenerators[g.freqModLFO]),CA=$e(oA,rA,currentTime);C+=CA*(u*t.customControllers[gA.modulationMultiplier]),k=-CA*D,l+=CA*y}if(t.channelVibrato.depth>0){let oA=$e(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);oA&&(C+=oA*t.channelVibrato.depth)}let w=A.modulatedGenerators[g.modEnvToPitch],G=A.modulatedGenerators[g.modEnvToFilterFc],x=JA.getValue(A,currentTime);l+=x*G,C+=x*w;let b=~~(C+Q*100);b!==A.currentTuningCents&&(A.currentTuningCents=b,A.currentTuningCalculated=Math.pow(2,b/1200));let $=(Math.max(-500,Math.min(500,A.modulatedGenerators[g.pan]))+500)/1e3,i=new Float32Array(e.length);switch(this.interpolationType){case he.linear:default:Wn(A,i);break;case he.nearestNeighbor:_n(A,i);break;case he.fourthOrder:zn(A,i)}Qe.apply(A,i,l,c>13499),UA.apply(A,i,k,this.volumeEnvelopeSmoothingFactor),A.currentPan+=($-A.currentPan)*this.panSmoothingFactor;let sA=Math.cos(As*A.currentPan)*this.panLeft,_=Math.sin(As*A.currentPan)*this.panRight,v=this.oneOutputMode?0:A.modulatedGenerators[g.reverbEffectsSend],z=this.oneOutputMode?0:A.modulatedGenerators[g.chorusEffectsSend];jn(sA,_,i,e,n,s,v,o,z)}function To(t,A){let e=0;return t.drumChannel&&(e+=5),A.isInRelease&&(e-=5),e+=A.velocity/25,e-=A.volumeEnvelope.state,A.isInRelease&&(e-=5),e-=A.volumeEnvelope.currentAttenuationDb/50,e}function ns(t){let A=[];for(let n of this.workletProcessorChannels)for(let s of n.voices)if(!s.finished){let o=To(n,s);A.push({channel:n,voice:s,priority:o})}A.sort((n,s)=>n.priority-s.priority);let e=A.slice(0,t);for(let{channel:n,voice:s}of e){let o=n.voices.indexOf(s);o>-1&&n.voices.splice(o,1)}}function ss(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimers=t);var Ho=function(t){var A,e,n,s,o,I,C,Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",B="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do s=Q.indexOf(t.charAt(d++)),o=Q.indexOf(t.charAt(d++)),I=Q.indexOf(t.charAt(d++)),C=Q.indexOf(t.charAt(d++)),A=s<<2|o>>4,e=(15&o)<<4|I>>2,n=(3&I)<<6|C,B+=String.fromCharCode(A),I!==64&&(B+=String.fromCharCode(e)),C!==64&&(B+=String.fromCharCode(n));while(d1&&(i.thisProgram=process.argv[1].replace(/\\/g,"/")),i.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(a){if(!(a instanceof ye))throw a}),process.on("unhandledRejection",function(a,E){process.exit(1)}),i.quit=function(a){process.exit(a)},i.inspect=function(){return"[Emscripten Module object]"}):oA?(typeof read<"u"&&(i.read=function(E){return read(E)}),i.readBinary=function(E){var h;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(h=read(E,"binary"))=="object"),h)},typeof scriptArgs<"u"?i.arguments=scriptArgs:typeof arguments<"u"&&(i.arguments=arguments),typeof quit=="function"&&(i.quit=function(a){quit(a)})):(_||v)&&(_?document.currentScript&&(rA=document.currentScript.src):rA=self.location.href,rA=rA.indexOf("blob:")!==0?rA.split("/").slice(0,-1).join("/")+"/":"",i.read=function(E){var h=new XMLHttpRequest;return h.open("GET",E,!1),h.send(null),h.responseText},v&&(i.readBinary=function(E){var h=new XMLHttpRequest;return h.open("GET",E,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),i.readAsync=function(E,h,f){var R=new XMLHttpRequest;R.open("GET",E,!0),R.responseType="arraybuffer",R.onload=function(){if(R.status==200||R.status==0&&R.response){h(R.response);return}f()},R.onerror=f,R.send(null)},i.setWindowTitle=function(a){document.title=a});var Me=i.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),GA=i.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Me);for(t in sA)sA.hasOwnProperty(t)&&(i[t]=sA[t]);function Ne(a){var E=u;return u=u+a+15&-16,E}function Ot(a){var E=Q[x>>2],h=E+a+15&-16;return Q[x>>2]=h,h>=hA&&!tn()?(Q[x>>2]=E,0):E}function Zt(a,E){return E||(E=16),a=Math.ceil(a/E)*E}function fo(a){switch(a){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(a[a.length-1]==="*")return 4;if(a[0]!=="i")return 0;var E=parseInt(a.substr(1));return _A(E%8==0),E/8}}function fe(a){fe.shown||(fe.shown={}),fe.shown[a]||(fe.shown[a]=1,GA(a))}sA=void 0;var mo={"f64-rem":function(a,E){return a%E},debugger:function(){}},it=[];function Ko(a,E){for(var h=0,f=h;f>>0)+4294967296*+(E>>>0):+(a>>>0)+4294967296*+(0|E)}function It(a,E,h){return h&&h.length?i["dynCall_"+a].apply(null,[E].concat(h)):i["dynCall_"+a].call(null,E)}var be=0,Xt=0;function _A(a,E){a||OA("Assertion failed: "+E)}function Wt(a){var E=i["_"+a];return _A(E,"Cannot call unknown function "+a+", make sure it is exported"),E}var _t={stackSave:function(){lt()},stackRestore:function(){ct()},arrayToC:function(a){var E,h,f=Je(a.length);return E=a,h=f,s.set(E,h),f},stringToC:function(a){var E=0;if(a!=null&&a!==0){var h=(a.length<<2)+1;E=Je(h),$t(a,E,h)}return E}},po={string:_t.stringToC,array:_t.arrayToC};function zt(a,E,h,f,R){var P=Wt(a),X=[],N=0;if(f)for(var QA=0;QA>0]=E;break;case"i16":I[a>>1]=E;break;case"i32":Q[a>>2]=E;break;case"i64":tempI64=[E>>>0,+Fo(tempDouble=E)>=1?tempDouble>0?(0|Go(+an(tempDouble/4294967296),4294967295))>>>0:~~+Ro((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],Q[a>>2]=tempI64[0],Q[a+4>>2]=tempI64[1];break;case"float":d[a>>2]=E;break;case"double":c[a>>3]=E;break;default:OA("invalid type for setValue: "+h)}}function Xo(a,E,h){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return s[a>>0];case"i16":return I[a>>1];case"i32":case"i64":return Q[a>>2];case"float":return d[a>>2];case"double":return c[a>>3];default:OA("invalid type for getValue: "+E)}return null}function Wo(a,E,h,f){typeof a=="number"?(P=!0,X=a):(P=!1,X=a.length);var R=typeof E=="string"?E:null;if(N=h==4?f:[typeof Ye=="function"?Ye:Ne,Je,Ne,Ot][h===void 0?2:h](Math.max(X,R?1:E.length)),P){for(f=N,_A((3&N)==0),QA=N+(-4&X);f>2]=0;for(QA=N+X;f>0]=0;return N}if(R==="i8")return a.subarray||a.slice?o.set(a,N):o.set(new Uint8Array(a),N),N;for(var P,X,N,QA,iA,aA,tA,q=0;q>0],(f!=0||E)&&(X++,!E||X!=E););E||(E=X);var N="";if(P<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(a,a+Math.min(E,1024))),N=N?N+R:R,a+=1024,E-=1024;return N}return h=a,function(iA,aA){for(var tA=aA;iA[tA];)++tA;if(tA-aA>16&&iA.subarray&&jt)return jt.decode(iA.subarray(aA,tA));for(var q,mA,xA,MA,NA,ee,bA="";;){if(!(q=iA[aA++]))return bA;if(!(128&q)){bA+=String.fromCharCode(q);continue}if(mA=63&iA[aA++],(224&q)==192){bA+=String.fromCharCode((31&q)<<6|mA);continue}if(xA=63&iA[aA++],(240&q)==224?q=(15&q)<<12|mA<<6|xA:(MA=63&iA[aA++],(248&q)==240?q=(7&q)<<18|mA<<12|xA<<6|MA:(NA=63&iA[aA++],q=(252&q)==248?(3&q)<<24|mA<<18|xA<<12|MA<<6|NA:(1&q)<<30|mA<<24|xA<<18|MA<<12|NA<<6|(ee=63&iA[aA++]))),q<65536)bA+=String.fromCharCode(q);else{var Se=q-65536;bA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(o,h)}function zo(a){for(var E="";;){var h=s[a++>>0];if(!h)return E;E+=String.fromCharCode(h)}}function jo(a,E){return function(f,R,P){for(var X=0;X>0]=f.charCodeAt(X);P||(s[R>>0]=0)}(a,E,!1)}var jt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ue(a,E,h,f){if(!(f>0))return 0;for(var R=h,P=h+f-1,X=0;X=55296&&N<=57343&&(N=65536+((1023&N)<<10)|1023&a.charCodeAt(++X)),N<=127){if(h>=P)break;E[h++]=N}else if(N<=2047){if(h+1>=P)break;E[h++]=192|N>>6,E[h++]=128|63&N}else if(N<=65535){if(h+2>=P)break;E[h++]=224|N>>12,E[h++]=128|N>>6&63,E[h++]=128|63&N}else if(N<=2097151){if(h+3>=P)break;E[h++]=240|N>>18,E[h++]=128|N>>12&63,E[h++]=128|N>>6&63,E[h++]=128|63&N}else if(N<=67108863){if(h+4>=P)break;E[h++]=248|N>>24,E[h++]=128|N>>18&63,E[h++]=128|N>>12&63,E[h++]=128|N>>6&63,E[h++]=128|63&N}else{if(h+5>=P)break;E[h++]=252|N>>30,E[h++]=128|N>>24&63,E[h++]=128|N>>18&63,E[h++]=128|N>>12&63,E[h++]=128|N>>6&63,E[h++]=128|63&N}}return E[h]=0,h-R}function $t(a,E,h){return Ue(a,o,E,h)}function Te(a){for(var E=0,h=0;h=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&a.charCodeAt(++h)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var An=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function $o(a){for(var E=a,h=E>>1;I[h];)++h;if((E=h<<1)-a>32&&An)return An.decode(o.subarray(a,E));for(var f=0,R="";;){var P=I[a+2*f>>1];if(P==0)return R;++f,R+=String.fromCharCode(P)}}function Ar(a,E,h){if(h===void 0&&(h=2147483647),h<2)return 0;for(var f=E,R=(h-=2)<2*a.length?h/2:a.length,P=0;P>1]=X,E+=2}return I[E>>1]=0,E-f}function er(a){return 2*a.length}function tr(a){for(var E=0,h="";;){var f=Q[a+4*E>>2];if(f==0)return h;if(++E,f>=65536){var R=f-65536;h+=String.fromCharCode(55296|R>>10,56320|1023&R)}else h+=String.fromCharCode(f)}}function nr(a,E,h){if(h===void 0&&(h=2147483647),h<4)return 0;for(var f=E,R=f+h-4,P=0;P=55296&&X<=57343&&(X=65536+((1023&X)<<10)|1023&a.charCodeAt(++P)),Q[E>>2]=X,(E+=4)+4>R)break}return Q[E>>2]=0,E-f}function sr(a){for(var E=0,h=0;h=55296&&f<=57343&&++h,E+=4}return E}function or(a){var E=Te(a)+1,h=Ye(E);return h&&Ue(a,s,h,E),h}function rr(a){var E=Te(a)+1,h=Je(E);return Ue(a,s,h,E),h}function ir(a){return a}function ar(){var a,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(R){f=R}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return i.extraStackTrace&&(E+=` +`+i.extraStackTrace()),(a=E).replace(/__Z[\w\d_]+/g,function(h){var f,R=f=h;return h===R?h:h+" ["+R+"]"})}function gt(a,E){return a%E>0&&(a+=E-a%E),a}function en(a){i.buffer=n=a}function Ct(){i.HEAP8=s=new Int8Array(n),i.HEAP16=I=new Int16Array(n),i.HEAP32=Q=new Int32Array(n),i.HEAPU8=o=new Uint8Array(n),i.HEAPU16=C=new Uint16Array(n),i.HEAPU32=B=new Uint32Array(n),i.HEAPF32=d=new Float32Array(n),i.HEAPF64=c=new Float64Array(n)}function tn(){var a=i.usingWasm?65536:16777216,E=2147483648-a;if(Q[x>>2]>E)return!1;var h=hA;for(hA=Math.max(hA,16777216);hA>2];)hA=hA<=536870912?gt(2*hA,a):Math.min(gt((3*hA+2147483648)/4,a),E);var f=i.reallocBuffer(hA);return f&&f.byteLength==hA?(en(f),Ct(),!0):(hA=h,!1)}l=u=y=k=w=G=x=0,D=!1,i.reallocBuffer||(i.reallocBuffer=function(a){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(n,a);else{var E,h=s;E=new ArrayBuffer(a),new Int8Array(E).set(h)}}catch{return!1}return!!xo(E)&&E});try{(b=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{b=function(E){return E.byteLength}}var Et=i.TOTAL_STACK||5242880,hA=i.TOTAL_MEMORY||16777216;function So(){return hA}function me(a){for(;a.length>0;){var E=a.shift();if(typeof E=="function"){E();continue}var h=E.func;typeof h=="number"?E.arg===void 0?i.dynCall_v(h):i.dynCall_vi(h,E.arg):h(E.arg===void 0?null:E.arg)}}hA=0?a:E<=32?2*Math.abs(1<=f&&(E<=32||a>f)&&(a=-2*f+a),a}var Fo=Math.abs,Ro=Math.ceil,an=Math.floor,Go=Math.min,Ae=0,Qt=null,pe=null;function Qr(a){return a}i.preloadedImages={},i.preloadedAudios={};var In="data:application/octet-stream;base64,";function He(a){return String.prototype.startsWith?a.startsWith(In):a.indexOf(In)===0}(function(){var E="main.wast",h="main.wasm",f="main.temp.asm.js";He(E)||(E=CA(E)),He(h)||(h=CA(h)),He(f)||(f=CA(f));var R={global:null,env:null,asm2wasm:mo,parent:i},P=null;function X(tA){return tA}function N(){try{if(i.wasmBinary)return new Uint8Array(i.wasmBinary);if(i.readBinary)return i.readBinary(h);throw"both async and sync fetching of the wasm failed"}catch(tA){OA(tA)}}i.asmPreload=i.asm;var QA=i.reallocBuffer,iA=function(tA){tA=gt(tA,i.usingWasm?65536:16777216);var q=i.buffer.byteLength;if(i.usingWasm)try{var mA=i.wasmMemory.grow((tA-q)/65536);return mA!==-1?i.buffer=i.wasmMemory.buffer:null}catch{return null}};i.reallocBuffer=function(tA){return aA==="asmjs"?QA(tA):iA(tA)};var aA="";i.asm=function(tA,q,mA){var xA;if(!(q=xA=q).table){var MA,NA=i.wasmTableSize;NA===void 0&&(NA=1024);var ee=i.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?ee!==void 0?q.table=new WebAssembly.Table({initial:NA,maximum:ee,element:"anyfunc"}):q.table=new WebAssembly.Table({initial:NA,element:"anyfunc"}):q.table=Array(NA),i.wasmTable=q.table}return q.memoryBase||(q.memoryBase=i.STATIC_BASE),q.tableBase||(q.tableBase=0),MA=function(Se,ie,dt){if(typeof WebAssembly!="object")return GA("no native wasm support detected"),!1;if(!(i.wasmMemory instanceof WebAssembly.Memory))return GA("no native wasm Memory in use"),!1;function ve(vA,qA){if((P=vA.exports).memory){var De,ft,En;De=P.memory,ft=i.buffer,De.byteLength0?h:Te(a)+1,R=Array(f),P=Ue(a,R,0,R.length);return E&&(R.length=P),R}function dr(a){for(var E=[],h=0;h255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}u+=16,x=Ne(4),w=(y=k=Zt(u))+Et,G=Zt(w),Q[x>>2]=G,D=!0,i.wasmTableSize=4,i.wasmMaxTableSize=4,i.asmGlobalArg={},i.asmLibraryArg={abort:OA,assert:_A,enlargeMemory:tn,getTotalMemory:So,abortOnCannotGrowMemory:function(){OA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+hA+", (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,h,f){var R=lt();try{return i.dynCall_iii(E,h,f)}catch(P){if(ct(R),typeof P!="number"&&P!=="longjmp")throw P;i.setThrew(1,0)}},___assert_fail:function(E,h,f,R){OA("Assertion failed: "+Le(E)+", at: "+[h?Le(h):"unknown filename",f,R?Le(R):"unknown function"])},___setErrNo:function(E){return i.___errno_location&&(Q[i.___errno_location()>>2]=E),E},_abort:function(){i.abort()},_emscripten_memcpy_big:function(E,h,f){return o.set(o.subarray(h,h+f),E),E},_llvm_floor_f64:an,DYNAMICTOP_PTR:x,tempDoublePtr:kA,ABORT:be,STACKTOP:k,STACK_MAX:w};var gn=i.asm(i.asmGlobalArg,i.asmLibraryArg,n);i.asm=gn,i.___errno_location=function(){return i.asm.___errno_location.apply(null,arguments)};var xo=i._emscripten_replace_memory=function(){return i.asm._emscripten_replace_memory.apply(null,arguments)};i._free=function(){return i.asm._free.apply(null,arguments)};var Ye=i._malloc=function(){return i.asm._malloc.apply(null,arguments)};i._memcpy=function(){return i.asm._memcpy.apply(null,arguments)},i._memset=function(){return i.asm._memset.apply(null,arguments)},i._sbrk=function(){return i.asm._sbrk.apply(null,arguments)},i._stb_vorbis_js_channels=function(){return i.asm._stb_vorbis_js_channels.apply(null,arguments)},i._stb_vorbis_js_close=function(){return i.asm._stb_vorbis_js_close.apply(null,arguments)},i._stb_vorbis_js_decode=function(){return i.asm._stb_vorbis_js_decode.apply(null,arguments)},i._stb_vorbis_js_open=function(){return i.asm._stb_vorbis_js_open.apply(null,arguments)},i._stb_vorbis_js_sample_rate=function(){return i.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},i.establishStackSpace=function(){return i.asm.establishStackSpace.apply(null,arguments)},i.getTempRet0=function(){return i.asm.getTempRet0.apply(null,arguments)},i.runPostSets=function(){return i.asm.runPostSets.apply(null,arguments)},i.setTempRet0=function(){return i.asm.setTempRet0.apply(null,arguments)},i.setThrew=function(){return i.asm.setThrew.apply(null,arguments)};var Je=i.stackAlloc=function(){return i.asm.stackAlloc.apply(null,arguments)},ct=i.stackRestore=function(){return i.asm.stackRestore.apply(null,arguments)},lt=i.stackSave=function(){return i.asm.stackSave.apply(null,arguments)};function ye(a){this.name="ExitStatus",this.message="Program terminated with exit("+a+")",this.status=a}function ut(a){a=a||i.arguments,!(Ae>0)&&(function(){if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)ko(i.preRun.shift());me(nn)}(),!(Ae>0)&&(i.calledRun||(i.setStatus?(i.setStatus("Running..."),setTimeout(function(){setTimeout(function(){i.setStatus("")},1),E()},1)):E())));function E(){!i.calledRun&&(i.calledRun=!0,be||(ht||(ht=!0,me(Bt)),me(sn),i.onRuntimeInitialized&&i.onRuntimeInitialized(),function(){if(i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;)wo(i.postRun.shift());me(rn)}()))}}function fr(a,E){(!E||!i.noExitRuntime||a!==0)&&(i.noExitRuntime||(be=!0,Xt=a,k=$,me(on),Do=!0,i.onExit&&i.onExit(a)),i.quit(a,new ye(a)))}function OA(a){throw i.onAbort&&i.onAbort(a),a!==void 0?(Me(a),GA(a),a=JSON.stringify(a)):a="",be=!0,Xt=1,"abort("+a+"). Build with -s ASSERTIONS=1 for more info."}if(i.dynCall_iii=function(){return i.asm.dynCall_iii.apply(null,arguments)},i.asm=gn,i.ccall=zt,i.cwrap=function(E,h,f,R){var P=(f=f||[]).every(function(X){return X==="number"});return h!=="string"&&P&&!R?Wt(E):function(){return zt(E,h,f,arguments,R)}},ye.prototype=Error(),ye.prototype.constructor=ye,pe=function a(){i.calledRun||ut(),i.calledRun||(pe=a)},i.run=ut,i.abort=OA,i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();i.noExitRuntime=!0,ut(),i.onRuntimeInitialized=()=>{os=!0,rs()},VA.decode=function(a){return function(h){if(!os)throw Error("Not initialized");var f={};function R(ie){return new Int32Array(i.HEAPU8.buffer,ie,1)[0]}function P(ie,dt){var ve=new ArrayBuffer(dt*Float32Array.BYTES_PER_ELEMENT),ae=new Float32Array(ve);return ae.set(new Float32Array(i.HEAPU8.buffer,ie,dt)),ae}f.open=i.cwrap("stb_vorbis_js_open","number",[]),f.close=i.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=i.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=i.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=i.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var X,N,QA,iA,aA=f.open(),tA=(X=h,N=h.byteLength,QA=i._malloc(N),(iA=new Uint8Array(i.HEAPU8.buffer,QA,N)).set(new Uint8Array(X,0,N)),iA),q=i._malloc(4),mA=i._malloc(4),xA=f.decode(aA,tA.byteOffset,tA.byteLength,q,mA);if(i._free(tA.byteOffset),xA<0)throw f.close(aA),i._free(q),Error("stbvorbis decode failed: "+xA);for(var MA=f.channels(aA),NA=Array(MA),ee=new Int32Array(i.HEAPU32.buffer,R(q),MA),bA=0;bA=0&&(n=this.workletProcessorChannels[e]),t.messageType){case eA.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case eA.noteOff:this.noteOff(e,A);break;case eA.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case eA.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case eA.customcCcChange:n.customControllers[A[0]]=A[1];break;case eA.killNote:this.killNote(e,A);break;case eA.programChange:this.programChange(e,A[0],A[1]);break;case eA.channelPressure:this.channelPressure(e,A);break;case eA.polyPressure:this.polyPressure(e,A[0],A[1]);break;case eA.ccReset:e===TA?this.resetAllControllers():this.resetControllers(e);break;case eA.systemExclusive:this.systemExclusive(A);break;case eA.setChannelVibrato:if(e===TA)for(let I=0;I{let e=(A.midiControllers[EA+K.pitchWheelRange]>>7)+(A.midiControllers[EA+K.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[EA+K.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:pA.channelProperties,messageData:t})}function Yo(t,A,e){let n=t,s=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:n,centTuning:s*.0061}}function gs(t,A=0){let e=t[0];if(!(this.deviceID!==TA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:T(`%cUnrecognized SysEx: %c${uA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let s;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),p(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),p(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let Q=(t[5]<<7|t[6])-8192;s=Math.floor(Q/81.92),this.setMasterTuning(s),p(`%cMaster Fine Tuning. Cents: %c${s}`,r.info,r.value);break;case 4:s=(t[5]-64)*100,this.setMasterTuning(s),p(`%cMaster Coarse Tuning. Cents: %c${s}`,r.info,r.value);break;default:T(`%cUnrecognized MIDI Device Control Real-time message: %c${uA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(p("%cGM system on",r.info),this.system="gm"):t[3]===3?(p("%cGM2 system on",r.info),this.system="gm2"):(p("%cGM system off, defaulting to GS",r.info),this.system="gs");break;case 8:switch(t[3]){case 2:case 7:let o=4;t[3]===7&&o++;let I=t[o++],C=t[o++];for(let B=0;B>1&1)===1&&this.setOctaveTuning(15+A,Q);for(let B=0;B<7;B++)(t[5]>>B&1)===1&&this.setOctaveTuning(7+B+A,Q);for(let B=0;B<7;B++)(t[6]>>B&1)===1&&this.setOctaveTuning(B+A,Q);p(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${Q.join(" ")}`,r.info,r.value);break;default:T(`%cUnrecognized MIDI Tuning standard message: %c${uA(t)}`,r.warn,r.unrecognized);break}break;default:T(`%cUnrecognized MIDI Realtime/non realtime message: %c${uA(t)}`,r.warn,r.unrecognized)}break;case 65:let n=function(){T(`%cUnrecognized Roland %cGS %cSysEx: %c${uA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let s=t[7];if(t[6]===127){s===0?(p("%cGS Reset received!",r.info),this.resetAllControllers(!1),this.system="gs"):s===127&&(p("%cGS system off, switching to GM2",r.info),this.resetAllControllers(!1),this.system="gm2");return}else if(t[4]===64){if((t[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A;switch(t[6]){default:n();break;case 21:let I=s>0&&t[5]>>4;this.setDrums(o,I),p(`%cChannel %c${o}%c ${I?"is now a drum channel":"now isn't a drum channel"}%c via: %c${uA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=s-64;this.transposeChannel(o,C),p(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${uA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let Q=s;Q===0&&(Q=Math.floor(Math.random()*128)),this.controllerChange(o,m.pan,Q);break;case 33:this.controllerChange(o,m.chorusDepth,s);break;case 34:this.controllerChange(o,m.reverbDepth,s);break;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let B=t.length-9,d=new Int8Array(12);for(let l=0;l=this.workletProcessorChannels.length)return;let o=t[6];switch(t[5]){case 1:this.controllerChange(s,m.bankSelect,o);break;case 2:this.controllerChange(s,m.lsbForControl0BankSelect,o);break;case 3:this.programChange(s,o);break;case 8:let I=this.workletProcessorChannels[s];if(I.drumChannel)return;let C=o-64;I.channelTransposeKeyShift=C;break;case 11:this.controllerChange(s,m.mainVolume,o);break;case 14:let Q=o;Q===0&&(Q=Math.floor(Math.random()*127)),this.controllerChange(s,m.pan,Q);break;case 19:this.controllerChange(s,m.reverbDepth,o);break;case 18:this.controllerChange(s,m.chorusDepth,o);break;default:T(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&T(`%cUnrecognized Yamaha XG SysEx: %c${uA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&T(`%cUnrecognized Yamaha SysEx: %c${uA(t)}`,r.warn,r.unrecognized);break}}function Cs(t,A,e){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=t[A.sourceIndex];else{let Q=A.sourceIndex+EA;switch(A.sourceIndex){case K.noController:n=16383;break;case K.noteOnKeyNum:n=e.midiNote<<7;break;case K.noteOnVelocity:n=e.velocity<<7;break;case K.polyPressure:n=e.pressure<<7;break;default:n=t[Q];break}}let s=oe[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let Q=A.secSrcIndex+EA;switch(A.secSrcIndex){case K.noController:o=16383;break;case K.noteOnKeyNum:o=e.midiNote<<7;break;case K.noteOnVelocity:o=e.velocity<<7;break;case K.polyPressure:o=e.pressure<<7;break;default:o=t[Q]}}let I=oe[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=s*I*A.transformAmount;return A.transformType===2&&(C=Math.abs(C)),A.currentValue=C,C}function XA(t,A,e=-1,n=0){let s=t.modulators,o=t.generators,I=t.modulatedGenerators;if(JA.recalculate(t),e===-1){I.set(o),s.forEach(B=>{let d=U[B.modulatorDestination],c=I[B.modulatorDestination]+Cs(A,B,t);I[B.modulatorDestination]=Math.max(d.min,Math.min(c,d.max))}),UA.recalculate(t);return}let C=new Set([g.initialAttenuation,g.delayVolEnv,g.attackVolEnv,g.holdVolEnv,g.decayVolEnv,g.sustainVolEnv,g.releaseVolEnv,g.keyNumToVolEnvHold,g.keyNumToVolEnvDecay]),Q=new Set;s.forEach(B=>{if(B.sourceUsesCC===e&&B.sourceIndex===n||B.secSrcUsesCC===e&&B.secSrcIndex===n){let d=B.modulatorDestination;Q.has(d)||(I[d]=o[d],Cs(A,B,t),s.forEach(c=>{if(c.modulatorDestination===d){let l=U[B.modulatorDestination],u=I[B.modulatorDestination]+c.currentValue;I[B.modulatorDestination]=Math.max(l.min,Math.min(u,l.max))}}),Q.add(d))}}),[...Q].some(B=>C.has(B))&&UA.recalculate(t)}var oe=[];for(let t=0;t<4;t++){oe[t]=[[new Float32Array(BA),new Float32Array(BA)],[new Float32Array(BA),new Float32Array(BA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||I.isMuted)return;let C=A+I.channelTransposeKeyShift,Q=C;if(A>127||A<0)return;let B=I.preset.program;this.tunings[B]?.[A]?.midiNote>=0&&(Q=this.tunings[B]?.[A].midiNote),I.velocityOverride>0&&(e=I.velocityOverride);let d=this.getWorkletVoices(t,Q,e,I,o,C,n),c=I.voices;d.forEach(l=>{let u=l.generators[g.exclusiveClass];u!==0&&c.forEach(b=>{b.generators[g.exclusiveClass]===u&&(this.releaseVoice(b),b.modulatedGenerators[g.releaseVolEnv]=-7e3,b.modulatedGenerators[g.releaseModEnv]=-7e3,UA.recalculate(b),JA.recalculate(b))}),XA(l,I.midiControllers);let D=l.modulatedGenerators[g.startAddrsOffset]+l.modulatedGenerators[g.startAddrsCoarseOffset]*32768,y=l.modulatedGenerators[g.endAddrOffset]+l.modulatedGenerators[g.endAddrsCoarseOffset]*32768,k=l.modulatedGenerators[g.startloopAddrsOffset]+l.modulatedGenerators[g.startloopAddrsCoarseOffset]*32768,w=l.modulatedGenerators[g.endloopAddrsOffset]+l.modulatedGenerators[g.endloopAddrsCoarseOffset]*32768,G=l.sample,x=b=>Math.max(0,Math.min(G.sampleData.length-1,b));if(G.cursor=x(G.cursor+D),G.end=x(G.end+y),G.loopStart=x(G.loopStart+k),G.loopEnd=x(G.loopEnd+w),G.loopEndthis.voiceCap&&this.voiceKilling(d.length),c.push(...d),s&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Bs(t,A){if(A>127||A<0){T("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift;if(this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(s=>{s.realKey!==e||s.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(s):this.releaseVoice(s))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function hs(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.realKey===A&&(e.modulatedGenerators[g.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function Qs(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(n=>{n.isInRelease||this.releaseVoice(n)}),this.workletProcessorChannels[t].sustainedVoices.forEach(n=>{this.releaseVoice(n)}))}function cs(t=!1){p("%cStop all received!",r.info);for(let A=0;AXA(s,this.workletProcessorChannels[t].midiControllers,0,K.pitchWheel)),this.sendChannelProperties()}function Ss(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[EA+K.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(n=>XA(n,e.midiControllers,0,K.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function Ds(t,A,e){this.workletProcessorChannels[t].voices.forEach(n=>{n.midiNote===A&&(n.pressure=e,XA(n,this.workletProcessorChannels[t].midiControllers,0,K.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function ks(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function ws(t,A,e,n=!1){let s=this.workletProcessorChannels[t];if(s===void 0){T(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>127){if(!n)return;switch(A){default:return;case wt.velocityOverride:s.velocityOverride=e}}if(A>=m.lsbForControl1ModulationWheel&&A<=m.lsbForControl13EffectControl2&&A!==m.lsbForControl6DataEntry){let o=A-32;if(s.lockedControllers[o])return;s.midiControllers[o]=s.midiControllers[o]&16256|e&127,s.voices.forEach(I=>XA(I,s.midiControllers,1,o))}switch(A){case m.allNotesOff:this.stopAll(t);break;case m.allSoundOff:this.stopAll(t,!0);break;case m.bankSelect:let o=e;if(!n){switch(this.system){case"gm":p(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==SA&&this.setDrums(t,!1);break;case"gm2":o===120&&(s.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}s.drumChannel&&(o=128),o===128&&!s.drumChannel&&(o=s.midiControllers[m.bankSelect])}s.midiControllers[m.bankSelect]=o;break;case m.lsbForControl0BankSelect:this.system==="xg"?s.drumChannel||e!==127&&(s.midiControllers[m.bankSelect]=e):this.system==="gm2"&&(s.midiControllers[m.bankSelect]=e);break;case m.RPNLsb:s.RPValue=s.RPValue<<7|e,s.dataEntryState=fA.RPFine;break;case m.RPNMsb:s.RPValue=e,s.dataEntryState=fA.RPCoarse;break;case m.NRPNMsb:s.NRPCoarse=e,s.dataEntryState=fA.NRPCoarse;break;case m.NRPNLsb:s.NRPFine=e,s.dataEntryState=fA.NRPFine;break;case m.dataEntryMsb:this.dataEntryCoarse(t,e);break;case m.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case m.resetAllControllers:this.resetControllers(t);break;case m.sustainPedal:e>=64?s.holdPedal=!0:(s.holdPedal=!1,s.sustainedVoices.forEach(I=>{this.releaseVoice(I)}),s.sustainedVoices=[]);break;default:if(s.lockedControllers[A])return;s.midiControllers[A]=e<<7,s.voices.forEach(I=>XA(I,s.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function Fs(t){this.midiVolume=t,this.setMasterPan(this.pan)}function Rs(t){this.masterGain=t*Ut,this.setMasterPan(this.pan)}function Gs(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function xs(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function Ms(t){this.workletProcessorChannels[t].lockGSNRPNParams=!0,this.workletProcessorChannels[t].channelVibrato.rate=0,this.workletProcessorChannels[t].channelVibrato.delay=0,this.workletProcessorChannels[t].channelVibrato.depth=0}function Ns(t,A,e,n){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=n,this.workletProcessorChannels[t].channelVibrato.depth=A)}function bs(t,A){let e=this.workletProcessorChannels[t],n=()=>{e.channelVibrato.delay===0&&e.channelVibrato.rate===0&&e.channelVibrato.depth===0&&(e.channelVibrato.depth=50,e.channelVibrato.rate=8,e.channelVibrato.delay=.6)};switch(e.dataEntryState){default:case fA.Idle:break;case fA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;T(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16).toUpperCase()} 0x${e.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 1:switch(e.NRPFine){default:if(A===64)return;T(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16)} 0x${e.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(A===64)return;n(),e.channelVibrato.rate=A/64*8,p(`%cVibrato rate for %c${t}%c is now set to %c${A} = ${e.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(A===64)return;n(),e.channelVibrato.depth=A/2,p(`%cVibrato depth for %c${t}%c is now set to %c${A} = ${e.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(A===64)return;n(),e.channelVibrato.delay=A/64/3,p(`%cVibrato delay for %c${t}%c is now set to %c${A} = ${e.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let I=A;this.controllerChange(t,m.brightness,A),p(`%cFilter cutoff for %c${t}%c is now set to %c${I}`,r.info,r.recognized,r.info,r.value)}break;case 24:let s=A-64;e.keyCentTuning[e.NRPFine]=s*100,p(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${s}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,m.reverbDepth,o),p(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:T(`%cUnrecognized RPN for %c${t}%c: %c(0x${e.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:e.midiControllers[EA+K.pitchWheelRange]=A<<7,p(`%cChannel ${t} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(t,A-64);break;case 1:this.setChannelTuning(t,A-64,!1);break;case 5:this.setModulationDepth(t,A*100);break;case 16383:this.resetParameters(t);break}}}function Ls(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[EA+K.pitchWheelRange]|=A;let n=(e.midiControllers[EA+K.pitchWheelRange]>>7)+A/127;p(`%cChannel ${t} bend range. Semitones: %c${n}`,r.info,r.value);break;case 1:let o=e.customControllers[gA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[gA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function Us(t=!0){t&&p("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A{this.workletProcessorChannels[A].lockedControllers[s]&&this.callEvent("controllerchange",{channel:A,controllerNumber:s,controllerValue:this.workletProcessorChannels[A].midiControllers[s]>>7})};if(n(m.mainVolume),n(m.pan),n(m.expressionController),n(m.modulationWheel),n(m.chorusDepth),n(m.reverbDepth),n(m.brightness),this.workletProcessorChannels[A].lockedControllers[EA+K.pitchWheel]){let s=this.workletProcessorChannels[A].midiControllers[EA+K.pitchWheel],o=s>>7,I=s&127;this.callEvent("pitchwheel",{channel:A,MSB:o,LSB:I})}}this.tunings=[],this.tunings=[];for(let A=0;127>A;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Oe}function Ts(t){let A=this.workletProcessorChannels[t],n=A.lockedControllers.reduce((o,I,C)=>(I&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(St),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,n.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let s=A.customControllers[gA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[gA.channelTransposeFine]=s,this.resetParameters(t)}function Hs(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=fA.Idle}function Ys(){let t=4;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==g.sampleID&&I.generatorType!==g.keyRange&&I.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+s),0);let A=new Y(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.generatorZoneStartIndex=e;for(let o of s.generators)J(A,o.generatorType),J(A,o.generatorValue),e++}return lA(A,0),nA(new AA("igen",A.length,A))}function Js(t,A,e,n,s){let o=this.samples.map((B,d)=>{e&&B.compressSample(n,s);let c=B.getRawData();return p(`%cEncoded sample %c${d}. ${B.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),c}),I=this.samples.reduce((B,d,c)=>B+o[c].length+46,0),C=new Y(I);this.samples.forEach((B,d)=>{let c=o[d],l,u,D=c.length;B.isCompressed?(l=C.currentIndex,u=l+c.length):(l=C.currentIndex/2,u=l+c.length/2,D+=46),t.push(l),C.set(c,C.currentIndex),C.currentIndex+=D,A.push(u)});let Q=nA(new AA("smpl",C.length,C),new Y([115,100,116,97]));return nA(new AA("LIST",Q.length,Q))}function vs(t,A){let n=new Y(46*(this.samples.length+1));return this.samples.forEach((s,o)=>{FA(n,s.sampleName,20);let I=t[o];lA(n,I);let C=A[o];lA(n,C);let Q=s.sampleLoopStartIndex+I,B=s.sampleLoopEndIndex+I;s.isCompressed&&(Q-=I,B-=I),lA(n,Q),lA(n,B),lA(n,s.sampleRate),n[n.currentIndex++]=s.samplePitch,n[n.currentIndex++]=s.samplePitchCorrection,J(n,s.sampleLink),J(n,s.sampleType)}),FA(n,"EOS",46),nA(new AA("shdr",n.length,n))}function qs(){let t=10;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new Y(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)J(A,o.sourceEnum),J(A,o.modulatorDestination),J(A,o.transformAmount),J(A,o.secondarySourceEnum),J(A,o.transformType),e++}return Ee(A,0,10),nA(new AA("imod",A.length,A))}function Ps(){let t=this.instruments.reduce((o,I)=>I.instrumentZones.length*4+o,4),A=new Y(t),e=0,n=0,s=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let I of o.instrumentZones)I.zoneID=e,J(A,n),J(A,s),n+=I.generators.length,s+=I.modulators.length,e++}return J(A,n),J(A,s),nA(new AA("ibag",A.length,A))}function Ks(){let t=this.instruments.length*22+22,A=new Y(t),e=0,n=0;for(let s of this.instruments)FA(A,s.instrumentName,20),J(A,e),e+=s.instrumentZones.length,s.instrumentID=n,n++;return FA(A,"EOI",20),J(A,e),nA(new AA("inst",A.length,A))}function Vs(){let t=4;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==g.instrument&&I.generatorType!==g.keyRange&&I.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+s),0);let A=new Y(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.generatorZoneStartIndex=e;for(let o of s.generators)J(A,o.generatorType),J(A,o.generatorValue);e+=s.generators.length}return J(A,0),J(A,0),nA(new AA("pgen",A.length,A))}function Os(){let t=10;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new Y(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)J(A,o.sourceEnum),J(A,o.modulatorDestination),J(A,o.transformAmount),J(A,o.secondarySourceEnum),J(A,o.transformType),e++}return Ee(A,0,10),nA(new AA("pmod",A.length,A))}function Zs(){let t=this.presets.reduce((o,I)=>I.presetZones.length*4+o,4),A=new Y(t),e=0,n=0,s=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let I of o.presetZones)I.zoneID=e,J(A,n),J(A,s),n+=I.generators.length,s+=I.modulators.length,e++}return J(A,n),J(A,s),nA(new AA("pbag",A.length,A))}function Xs(){let t=this.presets.length*38+38,A=new Y(t),e=0;for(let n of this.presets)FA(A,n.presetName,20),J(A,n.program),J(A,n.bank),J(A,e),lA(A,n.library),lA(A,n.genre),lA(A,n.morphology),e+=n.presetZones.length;return FA(A,"EOP",20),J(A,0),J(A,0),J(A,e),lA(A,0),lA(A,0),lA(A,0),nA(new AA("phdr",A.length,A))}var Jo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Ws(t=Jo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");yA("%cSaving soundfont...",r.info),p(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),p("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[b,$]of Object.entries(this.soundFontInfo))if(b==="ifil"||b==="iver"){let i=parseInt($.split(".")[0]),sA=parseInt($.split(".")[1]),_=new Y(4);J(_,i),J(_,sA),A.push(nA(new AA(b,4,_)))}else if(b==="DMOD")A.push(nA(new AA(b,$.length,$)));else{let i=new Y($.length);FA(i,$),A.push(nA(new AA(b,$.length,i)))}let e=ke([new Y([73,78,70,79]),...A]),n=nA(new AA("LIST",e.length,e));p("%cWriting SDTA...",r.info);let s=[],o=[],I=Js.call(this,s,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);p("%cWriting PDTA...",r.info),p("%cWriting SHDR...",r.info);let C=vs.call(this,s,o);p("%cWriting IGEN...",r.info);let Q=Ys.call(this);p("%cWriting IMOD...",r.info);let B=qs.call(this);p("%cWriting IBAG...",r.info);let d=Ps.call(this);p("%cWriting INST...",r.info);let c=Ks.call(this),l=Vs.call(this);p("%cWriting PMOD...",r.info);let u=Os.call(this);p("%cWriting PBAG...",r.info);let D=Zs.call(this);p("%cWriting PHDR...",r.info);let y=Xs.call(this),k=ke([new Y([112,100,116,97]),y,D,u,l,c,d,B,Q,C]),w=nA(new AA("LIST",k.length,k));p("%cWriting the output file...",r.info);let G=ke([new Y([115,102,98,107]),n,I,w]),x=nA(new AA("RIFF",G.length,G));return p(`%cSaved succesfully! Final file size: %c${x.length}`,r.info,r.recognized),Z(),x}var re=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Pe.map(e=>j.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}static mergeSoundfonts(...A){let e=A.shift(),n=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(I=>I.bank===o.bank&&I.program===o.program)===void 0&&n.push(o)});return new t({presets:n,info:e.soundFontInfo})}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPresetNoFallback(A,e,n=!1){let s=this.presets.find(o=>o.bank===A&&o.program===e);if(s)return s;if(n!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}getPreset(A,e){let n=this.presets.find(s=>s.bank===A&&s.program===e);return n||(A===128?(n=this.presets.find(s=>s.bank===128&&s.program===e),n||(n=this.presets.find(s=>s.bank===128))):n=this.presets.find(s=>s.program===e&&s.bank!==128),n&&T(`%cPreset ${A}.${e} not found. Replaced with %c${n.presetName} (${n.bank}.${n.program})`,r.warn,r.recognized)),n||(T(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),n=this.presets[0]),n}getPresetByName(A){let e=this.presets.find(n=>n.presetName===A);return e||(T("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}};re.prototype.write=Ws;function _s(t){yA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let n=A;n{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}getSamplesAndGenerators(A,e){let n=this.foundSamplesAndGenerators[A][e];if(n)return n;if(this.presetZones.length<1)return[];function s(c,l,u){return u>=c&&u<=l}function o(c,l){c.push(...l.filter(u=>!c.find(D=>D.generatorType===u.generatorType)))}function I(c,l){c.push(...l.filter(u=>!c.find(D=>j.isIdentical(u,D))))}let C=[],Q=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],B=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(c=>s(c.keyRange.min,c.keyRange.max,A)&&s(c.velRange.min,c.velRange.max,e)&&!c.isGlobal).forEach(c=>{if(c.instrument.instrumentZones.length<1)return;let l=c.generators,u=c.modulators,D=c.instrument.instrumentZones[0].isGlobal?[...c.instrument.instrumentZones[0].generators]:[],y=c.instrument.instrumentZones[0].isGlobal?[...c.instrument.instrumentZones[0].modulators]:[];c.instrument.instrumentZones.filter(w=>s(w.keyRange.min,w.keyRange.max,A)&&s(w.velRange.min,w.velRange.max,e)&&!w.isGlobal).forEach(w=>{let G=[...w.generators],x=[...w.modulators];o(l,Q),o(G,D),I(u,B),I(x,y),I(x,this.defaultModulators);let b=[...x];for(let $=0;$j.isIdentical(i,_));sA!==-1?b[sA]=b[sA].sumTransform(i):b.push(i)}C.push({instrumentGenerators:G,presetGenerators:l,modulators:b,sample:w.sample,sampleID:w.generators.find($=>$.generatorType===g.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=C,C}};var Re=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var $A=class extends Re{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},le=class extends Re{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var ue=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}get useCount(){return this._useCount}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var At=class extends ce{constructor(A,e){super(Pe),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new ue,this.DLSInstrument.addUseCount();let s=new le;s.instrument=this.DLSInstrument,this.presetZones=[s]}};function zs(t){this.verifyHeader(t,"LIST"),this.verifyText(V(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(u=>u.header==="insh");if(!e)throw Z(),new Error("No instrument header!");let n=S(e.chunkData,4),s=S(e.chunkData,4),o=S(e.chunkData,4),I=new At(s,o),C="unnamedPreset",Q=DA(A,"INFO");if(Q){let u=O(Q.chunkData);for(;u.header!=="INAM";)u=O(Q.chunkData);C=V(u.chunkData,u.chunkData.length).trim()}I.presetName=C,I.DLSInstrument.instrumentName=C,te(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let B=DA(A,"lrgn");if(!B)throw Z(),new Error("No region list!");let d=new $A;d.isGlobal=!0;let c=DA(A,"lart"),l=DA(A,"lar2");this.readLart(c,l,d),I.DLSInstrument.instrumentZones.push(d);for(let u=0;u>10&15;w===cA.linear&&k!==cA.linear&&(w=k);let G=n>>14&1,x=n>>15&1;I===g.initialAttenuation&&(x=!x),c=HA(w,G,x,C.isCC,C.enum)}let l=n>>4&15,u=n>>8&1,D=n>>9&1,y=HA(l,u,D,d.isCC,d.enum);if(Q){let k=y;y=c,c=k}return new j({srcEnum:c,secSrcEnum:y,dest:I,transform:0,amt:s})}function Tt(t,A){let e=t.chunkData,n=[],s=[];S(e,4);let o=S(e,4);for(let I=0;I>16;if(C===0&&Q===0&&d===0){let u;switch(B){case M.pan:u=new L(g.pan,l);break;case M.gain:u=new L(g.initialAttenuation,-l*10/.4);break;case M.filterCutoff:u=new L(g.initialFilterFc,l);break;case M.filterQ:u=new L(g.initialFilterQ,l);break;case M.modLfoFreq:u=new L(g.freqModLFO,l);break;case M.modLfoDelay:u=new L(g.delayModLFO,l);break;case M.vibLfoFreq:u=new L(g.freqVibLFO,l);break;case M.vibLfoDelay:u=new L(g.delayVibLFO,l);break;case M.volEnvDelay:u=new L(g.delayVolEnv,l);break;case M.volEnvAttack:u=new L(g.attackVolEnv,l);break;case M.volEnvHold:u=new L(g.holdVolEnv,l);break;case M.volEnvDecay:u=new L(g.decayVolEnv,l);break;case M.volEnvRelease:u=new L(g.releaseVolEnv,l);break;case M.volEnvSustain:let D=(1e3-l)/10;u=new L(g.sustainVolEnv,D*10);break;case M.modEnvDelay:u=new L(g.delayModEnv,l);break;case M.modEnvAttack:u=new L(g.attackModEnv,l);break;case M.modEnvHold:u=new L(g.holdModEnv,l);break;case M.modEnvDecay:u=new L(g.decayModEnv,l);break;case M.modEnvRelease:u=new L(g.releaseModEnv,l);break;case M.modEnvSustain:let y=1e3-l;u=new L(g.sustainModEnv,y);break;case M.reverbSend:u=new L(g.reverbEffectsSend,l);break;case M.chorusSend:u=new L(g.chorusEffectsSend,l);break;case M.pitch:let k=Math.floor(l/100),w=Math.floor(l-k*100);u=new L(g.fineTune,w),n.push(new L(g.coarseTune,k));break}u&&n.push(u)}else{let u=!0;if(Q===W.none)if(C===W.modLfo&&B===M.pitch)n.push(new L(g.modLfoToPitch,l));else if(C===W.modLfo&&B===M.gain)n.push(new L(g.modLfoToVolume,l));else if(C===W.modLfo&&B===M.filterCutoff)n.push(new L(g.modLfoToFilterFc,l));else if(C===W.vibratoLfo&&B===M.pitch)n.push(new L(g.vibLfoToPitch,l));else if(C===W.modEnv&&B===M.pitch)n.push(new L(g.modEnvToPitch,l));else if(C===W.modEnv&&B===M.filterCutoff)n.push(new L(g.modEnvToFilterFc,l));else if(C===W.keyNum&&B===M.volEnvHold){n.push(new L(g.keyNumToVolEnvHold,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.holdVolEnv&&(y.generatorValue+=D)})}else if(C===W.keyNum&&B===M.volEnvDecay){n.push(new L(g.keyNumToVolEnvDecay,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.decayVolEnv&&(y.generatorValue+=D)})}else if(C===W.keyNum&&B===M.modEnvHold){n.push(new L(g.keyNumToModEnvHold,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.holdModEnv&&(y.generatorValue+=D)})}else if(C===W.keyNum&&B===M.modEnvDecay){n.push(new L(g.keyNumToModEnvDecay,l/-128));let D=Math.round(60/128*l);n.forEach(y=>{y.generatorType===g.decayModEnv&&(y.generatorValue+=D)})}else u=!1;else u=!1;if(u===!1){let D=$s(C,Q,B,d,l);D?(s.push(D),p("%cSucceeded converting to SF2 Modulator!",r.recognized)):T("Failed converting to SF2 Modulator!")}}}return s.find(I=>I.modulatorDestination===g.reverbEffectsSend)===void 0&&s.push(new j({srcEnum:219,dest:g.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),s.find(I=>I.modulatorDestination===g.chorusEffectsSend)===void 0&&s.push(new j({srcEnum:221,dest:g.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&s.push(new j({srcEnum:129,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new j({srcEnum:13,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:s,generators:n}}function Ao(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(_=>_.header==="rgnh"),n=S(e.chunkData,2),s=S(e.chunkData,2),o=S(e.chunkData,2),I=S(e.chunkData,2),C=new et({min:n,max:s},{min:o,max:I});S(e.chunkData,2);let Q=S(e.chunkData,2);Q!==0&&C.generators.push(new L(g.exclusiveClass,Q));let B=DA(A,"lart"),d=DA(A,"lar2");this.readLart(B,d,C),C.isGlobal=!1;let c=A.find(_=>_.header==="wsmp");S(c.chunkData,4);let l=S(c.chunkData,2),u=jA(c.chunkData[c.chunkData.currentIndex++],c.chunkData[c.chunkData.currentIndex++]),y=(S(c.chunkData,4)|0)/-655360;S(c.chunkData,4);let k=S(c.chunkData,4),w,G={start:0,end:0};if(k===0)w=0;else{S(c.chunkData,4),S(c.chunkData,4)===0?w=1:w=3,G.start=S(c.chunkData,4);let v=S(c.chunkData,4);G.end=G.start+v}let x=A.find(_=>_.header==="wlnk");if(x===void 0)return;S(x.chunkData,2),S(x.chunkData,2),S(x.chunkData,4);let b=S(x.chunkData,4),$=this.samples[b];if($===void 0)throw new Error("Invalid sample ID!");let sA=(y||$.sampleDbAttenuation)*10/.4;return C.setWavesample(sA,w,G,l,$,b,u),C}var de=class{constructor(A,e,n,s,o,I,C,Q){this.sampleName=A,this.sampleRate=e,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=I,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=Q,this.isCompressed=(I&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,e){if(!this.isCompressed)try{this.compressedData=e([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{T(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}};var tt=class extends de{sampleDbAttenuation;sampleData;constructor(A,e,n,s,o,I,C,Q){super(A,e,n,s,0,1,o,I-1),this.sampleData=C,this.sampleDbAttenuation=Q}getAudioData(){return this.sampleData}getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let e=0;e>8&255}return A}};function to(t){yA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexv.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");if(S(s.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(S(s.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=S(s.chunkData,4);S(s.chunkData,4),S(s.chunkData,2);let Q=S(s.chunkData,2),B=Q/8,d=Math.pow(2,B*8-1),c=Math.pow(2,B*8),l,u=!1;Q===8?(l=255,u=!0):l=d;let D=n.find(v=>v.header==="data");if(!D)throw new Error("No data chunk in the wave chunk!");let y=D.size/B,k=new Float32Array(y);for(let v=0;v=d&&(z-=c),k[v]=z/l)}let w=60,G=0,x=0,b=k.length-1,$=0,i=n.find(v=>v.header==="wsmp");if(i){if(S(i.chunkData,4),w=S(i.chunkData,2),G=jA(i.chunkData[i.chunkData.currentIndex++],i.chunkData[i.chunkData.currentIndex++]),$=(S(i.chunkData,4)|0)/-655360,S(i.chunkData,4),S(i.chunkData,4)===1){S(i.chunkData,8),x=S(i.chunkData,4);let oA=S(i.chunkData,4);b=x+oA}}else T("No wsmp chunk in wave... using sane defaults.");let sA=DA(n,"INFO"),_=`Unnamed ${A}`;if(sA){let v=O(sA.chunkData);for(;v.header!=="INAM"&&sA.chunkData.currentIndexQ.header==="colh");if(!o)throw Z(),new Error("No colh chunk!");this.instrumentAmount=S(o.chunkData,4),p(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let I=DA(n,"wvpl");this.readDLSSamples(I);let C=DA(n,"lins");if(!C)throw Z(),new Error("No lins chunk!");this.readDLSInstrumentList(C),this.presets.sort((Q,B)=>Q.program-B.program+(Q.bank-B.bank)),p(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),Z()}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=_s;WA.prototype.readDLSInstrument=zs;WA.prototype.readRegion=eo;WA.prototype.readLart=Ao;WA.prototype.readDLSSamples=to;var Ht=class extends de{constructor(A,e,n,s,o,I,C,Q,B,d,c,l,u){super(A,I,C,Q,B,d,s-e/2,o-e/2),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=c,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=u}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let e=A.currentIndex;return A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e)}else{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");let e=A.currentIndex;return A.slice(e+this.sampleStartIndex,e+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,e=A.currentIndex,n=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let s=VA.decode(n.buffer);this.sampleData=s.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return T("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let s=0;st.chunkData.currentIndex;){let o=Po(s,t.chunkData,A,e);n.push(o),s++}return n.length>1&&n.pop(),n}function Po(t,A,e,n){let s=V(A,20),o=S(A,4)*2,I=S(A,4)*2,C=S(A,4),Q=S(A,4),B=S(A,4),d=A[A.currentIndex++];d===255&&(d=60);let c=Gn(A[A.currentIndex++]),l=S(A,2),u=S(A,2);return new Ht(s,o,I,C,Q,B,d,c,l,u,e,t,n)}var Yt=class extends L{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=jA(A[e+2],A[e+3]),A.currentIndex+=4}};function Jt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Yt(t.chunkData));return A.length>1&&A.pop(),A}var vt=class extends ue{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=S(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;nt.chunkData.currentIndex;){let n=new vt(t);if(e.length>0){let s=n.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(s,A)}e.push(n)}return e.length>1&&e.pop(),e}var qt=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=S(A,2),this.modulatorZoneStartIndex=S(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;en.generatorType===g.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function oo(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new qt(t.chunkData);if(s.length>0){let I=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(I,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Pt=class extends le{constructor(A){super(),this.generatorZoneStartIndex=S(A,2),this.modulatorZoneStartIndex=S(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;en.generatorType===g.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ro(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Pt(t.chunkData);if(s.length>0){let I=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(I,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Kt=class extends ce{constructor(A,e){super(e),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=S(A.chunkData,2),this.bank=S(A.chunkData,2),this.presetZoneStartIndex=S(A.chunkData,2),this.library=S(A.chunkData,4),this.genre=S(A.chunkData,4),this.morphology=S(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let n=this.presetZoneStartIndex;nt.chunkData.currentIndex;){let s=new Kt(t,e);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var Vt=class extends j{constructor(A){super({srcEnum:S(A,2),dest:S(A,2),amt:jA(A[A.currentIndex++],A[A.currentIndex++]),secSrcEnum:S(A,2),transform:S(A,2)})}};function nt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Vt(t.chunkData));return A}var st=class extends re{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new Y(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw Z(),new TypeError("No data!");let n=O(this.dataArray,!1);this.verifyHeader(n,"riff");let s=V(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw Z(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",I=O(this.dataArray);for(this.verifyHeader(I,"list"),V(I.chunkData,4);I.chunkData.length>I.chunkData.currentIndex;){let z=O(I.chunkData),oA;switch(z.header.toLowerCase()){case"ifil":case"iver":oA=`${S(z.chunkData,2)}.${S(z.chunkData,2)}`,this.soundFontInfo[z.header]=oA;break;case"icmt":oA=V(z.chunkData,z.chunkData.length,void 0,!1),this.soundFontInfo[z.header]=oA;break;case"dmod":let rA=nt(z);rA.pop(),oA=`Modulators: ${rA.length}`;let CA=this.defaultModulators;this.defaultModulators=rA,this.defaultModulators.push(...CA.filter(Me=>!this.defaultModulators.find(RA=>j.isIdentical(Me,RA)))),this.soundFontInfo[z.header]=z.chunkData;break;default:oA=V(z.chunkData,z.chunkData.length),this.soundFontInfo[z.header]=oA}p(`%c"${z.header}": %c"${oA}"`,r.info,r.recognized)}let C=O(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(V(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",r.warn);let Q=O(this.dataArray,!1);this.verifyHeader(Q,"smpl");let B;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{B=VA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(z){throw Z(),new Error(`SF2Pack Ogg Vorbis decode error: ${z}`)}p(`%cDecoded the smpl chunk! Length: %c${B.length}`,r.info,r.value)}else B=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,p("%cLoading preset data chunk...",r.warn);let d=O(this.dataArray);this.verifyHeader(d,"list"),V(d.chunkData,4);let c=O(d.chunkData);this.verifyHeader(c,"phdr");let l=O(d.chunkData);this.verifyHeader(l,"pbag");let u=O(d.chunkData);this.verifyHeader(u,"pmod");let D=O(d.chunkData);this.verifyHeader(D,"pgen");let y=O(d.chunkData);this.verifyHeader(y,"inst");let k=O(d.chunkData);this.verifyHeader(k,"ibag");let w=O(d.chunkData);this.verifyHeader(w,"imod");let G=O(d.chunkData);this.verifyHeader(G,"igen");let x=O(d.chunkData);this.verifyHeader(x,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...no(x,B,!o));let b=Jt(G),$=nt(w),i=oo(k,b,$,this.samples);this.instruments=so(y,i);let sA=Jt(D),_=nt(u),v=ro(l,sA,_,this.instruments);this.presets.push(...io(c,v,this.defaultModulators)),this.presets.sort((z,oA)=>z.program-oA.program+(z.bank-oA.bank)),p(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,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,e){if(A.header.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Ge(t){let A=t.slice(8,12),e=new Y(A);return V(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new st(t,!1)}function ao(t,A,e=!1){let n=this.workletProcessorChannels[t];if(n===void 0){T(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(n.lockPreset)return;let s=n.drumChannel?128:n.midiControllers[m.bankSelect],o,I;if(this.overrideSoundfont){let C=s===128?128:s-this.soundfontBankOffset,Q=this.overrideSoundfont.getPresetNoFallback(C,A);Q?(o=s,I=Q,n.presetUsesOverride=!0):(I=this.soundfontManager.getPreset(s,A),o=I.bank,n.presetUsesOverride=!1)}else I=this.soundfontManager.getPreset(s,A),o=I.bank,n.presetUsesOverride=!1;this.setPreset(t,I),this.callEvent("programchange",{channel:t,program:I.program,bank:o,userCalled:e})}function Io(t,A){if(this.overrideSoundfont){let e=t===128?128:t-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(e,A);if(n)return n}return this.soundfontManager.getPreset(t,A)}function go(t,A){if(!this.workletProcessorChannels[t].lockPreset){delete this.workletProcessorChannels[t].preset,this.workletProcessorChannels[t].preset=A,this.workletProcessorChannels[t].cachedVoices=[];for(let e=0;e<128;e++)this.workletProcessorChannels[t].cachedVoices.push([])}}function Co(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(128,e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(e.midiControllers[m.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function Eo(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,n=t.find(s=>s.bank===e&&s.program===A.program);n!==void 0?n.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function Bo(t=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let e=0;e{this.programChange(n,e.preset.program)}),this.post({messageType:pA.ready,messageData:void 0}),this.sendPresetList(),p("%cSpessaSynth is ready!",r.recognized)}function Qo(t,A){this.soundfontBankOffset=A,this.reloadSoundFont(t,!0),this.overrideSoundfont.samples.forEach(e=>e.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function co(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:e.preset.bank,lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,velocityOverride:e.velocityOverride,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:pA.synthesizerSnapshot,messageData:A})}function lo(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation;this.workletProcessorChannels.length{let n=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),n.midiControllers=A.midiControllers,n.lockedControllers=A.lockedControllers,n.customControllers=A.customControllers,n.channelVibrato=A.channelVibrato,n.lockGSNRPNParams=A.lockVibrato,n.channelTransposeKeyShift=A.channelTransposeKeyShift,n.channelOctaveTuning=A.channelOctaveTuning,n.velocityOverride=A.velocityOverride,n.lockPreset=!1,n.midiControllers[m.bankSelect]=A.bank,this.programChange(e,A.program),n.lockPreset=A.lockPreset}),p("%cFinished restoring controllers!",r.info)}var ot=class{constructor(A,e){this.ready=e,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(e=>{e.soundfont.setSampleIDOffset(A),A+=e.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let e=this.soundfontList.length-1;e>=0;e--){let n=this.soundfontList[e],s=new Set;for(let o of n.soundfont.presets){let I=`${o.bank+n.bankOffset}-${o.program}`;s.has(I)||(s.add(I),A[I]=o.presetName)}}this.presetList=[];for(let[e,n]of Object.entries(A)){let s=e.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}}handleMessage(A,e){switch(A){case Ce.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ce.reloadSoundFont:this.reloadManager(e);break;case Ce.deleteSoundFont:this.deleteSoundFont(e);break;case Ce.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ge(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){T("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(n=>n.id===A);if(e===-1){T(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[e].soundfont.presets,delete this.soundfontList[e].soundfont.instruments,delete this.soundfontList[e].soundfont.samples,this.soundfontList.splice(e,1),this.generatePresetList()}addNewSoundFont(A,e,n){if(this.soundfontList.find(s=>s.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Ge(A),bankOffset:n}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,n)=>A.indexOf(e.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let n of this.soundfontList){let s=n.soundfont.getPresetNoFallback(A-n.bankOffset,e);if(s!==void 0)return s}if(A!==128){for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.program===e);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}else{for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.bank===128);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}}};var rt=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,e,n,s,o,I,C,Q){this.sampleData=A,this.playbackStep=e,this.cursor=n,this.rootKey=s,this.loopStart=o,this.loopEnd=I,this.end=C,this.loopingMode=Q,this.isLooping=this.loopingMode===1||this.loopingMode===3}},xe=class t{sample;filter=new Qe;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new YA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;realKey;constructor(A,e,n,s,o,I,C,Q,B,d){this.sample=e,this.generators=B,this.modulatedGenerators=new Int16Array(B),this.modulators=d,this.velocity=s,this.midiNote=n,this.channelNumber=o,this.startTime=I,this.targetKey=C,this.realKey=Q,this.volumeEnvelope=new LA(A,B[g.sustainVolEnv])}static copy(A,e){let n=A.sample,s=new rt(n.sampleData,n.playbackStep,n.cursor,n.rootKey,n.loopStart,n.loopEnd,n.end,n.loopingMode);return new t(A.volumeEnvelope.sampleRate,s,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.realKey,A.generators,A.modulators.map(o=>j.copy(o)))}};function uo(t,A,e,n,s,o,I=!1){let C,Q=n.cachedVoices[A][e];return Q!==void 0?Q.map(B=>xe.copy(B,s)):(C=n.preset.getSamplesAndGenerators(A,e).reduce((d,c)=>{if(c.sample.sampleData===void 0)return T(`Discarding invalid sample: ${c.sample.sampleName}`),d;let l=new Int16Array(60);for(let x=0;x<60;x++)l[x]=pn(x,c.presetGenerators,c.instrumentGenerators);l[g.initialAttenuation]=Math.floor(l[g.initialAttenuation]*.4);let u=c.sample.samplePitch;l[g.overridingRootKey]>-1&&(u=l[g.overridingRootKey]);let D=A;l[g.keyNum]>-1&&(D=l[g.keyNum]);let y=c.sample.sampleLoopStartIndex,k=c.sample.sampleLoopEndIndex,w=l[g.sampleModes],G=new rt(c.sample.getAudioData(),c.sample.sampleRate/sampleRate*Math.pow(2,c.sample.samplePitchCorrection/1200),0,u,y,k,Math.floor(c.sample.sampleData.length)-1,w);return l[g.velocity]>-1&&(e=l[g.velocity]),I&&mn([{Sample:c.sample.sampleName,Generators:l,Modulators:c.modulators.map(x=>x.debugString()),Velocity:e,TargetKey:D,MidiNote:A,WorkletSample:G}]),d.push(new xe(sampleRate,G,A,e,t,s,D,o,l,c.modulators.map(x=>j.copy(x)))),d},[]),n.cachedVoices[A][e]=C.map(d=>xe.copy(d,s)),C)}var Lt=.03,Ut=1,H=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=UA,this.interpolationType=he.fourthOrder,this.processTickCallback=void 0,this.sequencer=new IA(this),this.transposition=0,this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Ut,this.midiVolume=1,this.voiceCap=Dn,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new ot(A.processorOptions.soundfont,this.postReady.bind(this))}catch(e){throw this.post({messageType:pA.soundfontError,messageData:e}),e}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let e=0;ethis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),p("%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(),p("%cSpessaSynth is ready!",r.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:pA.ready,messageData:void 0})}debugMessage(){p({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let n=0;return this.workletProcessorChannels.forEach((s,o)=>{if(s.voices.length<1||s.isMuted)return;let I,C,Q,B,d;if(this.oneOutputMode){let l=e[0];I=o%16*2,C=l[I],Q=l[I+1]}else I=o%this._outputsAmount+2,C=e[I][0],Q=e[I][1],B=e[0],d=e[1];let c=s.voices;s.voices=[],c.forEach(l=>{this.renderVoice(s,l,C,Q,B,d),l.finished||s.voices.push(l)}),n+=s.voices.length}),n!==this.totalVoicesAmount&&(this.totalVoicesAmount=n,this.sendChannelProperties()),!0}};H.prototype.renderVoice=ts;H.prototype.releaseVoice=ss;H.prototype.voiceKilling=ns;H.prototype.getWorkletVoices=uo;H.prototype.handleMessage=is;H.prototype.sendChannelProperties=Is;H.prototype.callEvent=as;H.prototype.systemExclusive=gs;H.prototype.noteOn=Es;H.prototype.noteOff=Bs;H.prototype.polyPressure=Ds;H.prototype.killNote=hs;H.prototype.stopAll=Qs;H.prototype.stopAllChannels=cs;H.prototype.muteChannel=xs;H.prototype.setVibrato=Ns;H.prototype.disableAndLockGSNRPN=Ms;H.prototype.dataEntryCoarse=bs;H.prototype.dataEntryFine=Ls;H.prototype.createWorkletChannel=yn;H.prototype.controllerChange=ws;H.prototype.channelPressure=Ss;H.prototype.resetAllControllers=Us;H.prototype.resetControllers=Ts;H.prototype.resetParameters=Hs;H.prototype.setMasterGain=Rs;H.prototype.setMasterPan=Gs;H.prototype.setMIDIVolume=Fs;H.prototype.transposeAllChannels=ls;H.prototype.transposeChannel=us;H.prototype.setChannelTuning=ds;H.prototype.setChannelTuningSemitones=fs;H.prototype.setMasterTuning=ms;H.prototype.setModulationDepth=ps;H.prototype.pitchWheel=ys;H.prototype.setOctaveTuning=ks;H.prototype.programChange=ao;H.prototype.getPreset=Io;H.prototype.setPreset=go;H.prototype.setDrums=Co;H.prototype.reloadSoundFont=ho;H.prototype.clearSoundFont=Bo;H.prototype.setEmbeddedSoundFont=Qo;H.prototype.sendPresetList=Eo;H.prototype.sendSynthesizerSnapshot=co;H.prototype.applySynthesizerSnapshot=lo;registerProcessor(Sn,H);p("%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,e){if(A.header.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=_s;WA.prototype.readDLSInstrument=zs;WA.prototype.readRegion=eo;WA.prototype.readLart=Ao;WA.prototype.readDLSSamples=to;var Ht=class extends de{constructor(A,e,n,s,o,I,C,Q,B,d,c,l,u){super(A,I,C,Q,B,d,s-e/2,o-e/2),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=c,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=u}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let e=A.currentIndex;return A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e)}else{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");let e=A.currentIndex;return A.slice(e+this.sampleStartIndex,e+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,e=A.currentIndex,n=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let s=VA.decode(n.buffer);this.sampleData=s.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return T("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let s=0;st.chunkData.currentIndex;){let o=Po(s,t.chunkData,A,e);n.push(o),s++}return n.length>1&&n.pop(),n}function Po(t,A,e,n){let s=V(A,20),o=S(A,4)*2,I=S(A,4)*2,C=S(A,4),Q=S(A,4),B=S(A,4),d=A[A.currentIndex++];d===255&&(d=60);let c=Gn(A[A.currentIndex++]),l=S(A,2),u=S(A,2);return new Ht(s,o,I,C,Q,B,d,c,l,u,e,t,n)}var Yt=class extends L{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=jA(A[e+2],A[e+3]),A.currentIndex+=4}};function Jt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Yt(t.chunkData));return A.length>1&&A.pop(),A}var vt=class extends ue{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=S(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;nt.chunkData.currentIndex;){let n=new vt(t);if(e.length>0){let s=n.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(s,A)}e.push(n)}return e.length>1&&e.pop(),e}var qt=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=S(A,2),this.modulatorZoneStartIndex=S(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;en.generatorType===g.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function oo(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new qt(t.chunkData);if(s.length>0){let I=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(I,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Pt=class extends le{constructor(A){super(),this.generatorZoneStartIndex=S(A,2),this.modulatorZoneStartIndex=S(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;en.generatorType===g.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ro(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Pt(t.chunkData);if(s.length>0){let I=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(I,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Kt=class extends ce{constructor(A,e){super(e),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=S(A.chunkData,2),this.bank=S(A.chunkData,2),this.presetZoneStartIndex=S(A.chunkData,2),this.library=S(A.chunkData,4),this.genre=S(A.chunkData,4),this.morphology=S(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let n=this.presetZoneStartIndex;nt.chunkData.currentIndex;){let s=new Kt(t,e);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var Vt=class extends j{constructor(A){super({srcEnum:S(A,2),dest:S(A,2),amt:jA(A[A.currentIndex++],A[A.currentIndex++]),secSrcEnum:S(A,2),transform:S(A,2)})}};function nt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Vt(t.chunkData));return A}var st=class extends re{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new Y(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw Z(),new TypeError("No data!");let n=O(this.dataArray,!1);this.verifyHeader(n,"riff");let s=V(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw Z(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",I=O(this.dataArray);for(this.verifyHeader(I,"list"),V(I.chunkData,4);I.chunkData.length>I.chunkData.currentIndex;){let z=O(I.chunkData),oA;switch(z.header.toLowerCase()){case"ifil":case"iver":oA=`${S(z.chunkData,2)}.${S(z.chunkData,2)}`,this.soundFontInfo[z.header]=oA;break;case"icmt":oA=V(z.chunkData,z.chunkData.length,void 0,!1),this.soundFontInfo[z.header]=oA;break;case"dmod":let rA=nt(z);rA.pop(),oA=`Modulators: ${rA.length}`;let CA=this.defaultModulators;this.defaultModulators=rA,this.defaultModulators.push(...CA.filter(Me=>!this.defaultModulators.find(GA=>j.isIdentical(Me,GA)))),this.soundFontInfo[z.header]=z.chunkData;break;default:oA=V(z.chunkData,z.chunkData.length),this.soundFontInfo[z.header]=oA}p(`%c"${z.header}": %c"${oA}"`,r.info,r.recognized)}let C=O(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(V(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",r.warn);let Q=O(this.dataArray,!1);this.verifyHeader(Q,"smpl");let B;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{B=VA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(z){throw Z(),new Error(`SF2Pack Ogg Vorbis decode error: ${z}`)}p(`%cDecoded the smpl chunk! Length: %c${B.length}`,r.info,r.value)}else B=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,p("%cLoading preset data chunk...",r.warn);let d=O(this.dataArray);this.verifyHeader(d,"list"),V(d.chunkData,4);let c=O(d.chunkData);this.verifyHeader(c,"phdr");let l=O(d.chunkData);this.verifyHeader(l,"pbag");let u=O(d.chunkData);this.verifyHeader(u,"pmod");let D=O(d.chunkData);this.verifyHeader(D,"pgen");let y=O(d.chunkData);this.verifyHeader(y,"inst");let k=O(d.chunkData);this.verifyHeader(k,"ibag");let w=O(d.chunkData);this.verifyHeader(w,"imod");let G=O(d.chunkData);this.verifyHeader(G,"igen");let x=O(d.chunkData);this.verifyHeader(x,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...no(x,B,!o));let b=Jt(G),$=nt(w),i=oo(k,b,$,this.samples);this.instruments=so(y,i);let sA=Jt(D),_=nt(u),v=ro(l,sA,_,this.instruments);this.presets.push(...io(c,v,this.defaultModulators)),this.presets.sort((z,oA)=>z.program-oA.program+(z.bank-oA.bank)),p(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,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,e){if(A.header.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Ge(t){let A=t.slice(8,12),e=new Y(A);return V(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new st(t,!1)}function ao(t,A,e=!1){let n=this.workletProcessorChannels[t];if(n===void 0){T(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(n.lockPreset)return;let s=n.drumChannel?128:n.midiControllers[m.bankSelect],o,I;if(this.overrideSoundfont){let C=s===128?128:s-this.soundfontBankOffset,Q=this.overrideSoundfont.getPresetNoFallback(C,A);Q?(o=s,I=Q,n.presetUsesOverride=!0):(I=this.soundfontManager.getPreset(s,A),o=I.bank,n.presetUsesOverride=!1)}else I=this.soundfontManager.getPreset(s,A),o=I.bank,n.presetUsesOverride=!1;this.setPreset(t,I),this.callEvent("programchange",{channel:t,program:I.program,bank:o,userCalled:e})}function Io(t,A){if(this.overrideSoundfont){let e=t===128?128:t-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(e,A);if(n)return n}return this.soundfontManager.getPreset(t,A)}function go(t,A){if(!this.workletProcessorChannels[t].lockPreset){delete this.workletProcessorChannels[t].preset,this.workletProcessorChannels[t].preset=A,this.workletProcessorChannels[t].cachedVoices=[];for(let e=0;e<128;e++)this.workletProcessorChannels[t].cachedVoices.push([])}}function Co(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(128,e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(e.midiControllers[m.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function Eo(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,n=t.find(s=>s.bank===e&&s.program===A.program);n!==void 0?n.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function Bo(t=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let e=0;e{this.programChange(n,e.preset.program)}),this.post({messageType:pA.ready,messageData:void 0}),this.sendPresetList(),p("%cSpessaSynth is ready!",r.recognized)}function Qo(t,A){this.soundfontBankOffset=A,this.reloadSoundFont(t,!0),this.overrideSoundfont.samples.forEach(e=>e.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function co(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:e.preset.bank,lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,velocityOverride:e.velocityOverride,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:pA.synthesizerSnapshot,messageData:A})}function lo(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation;this.workletProcessorChannels.length{let n=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),n.midiControllers=A.midiControllers,n.lockedControllers=A.lockedControllers,n.customControllers=A.customControllers,n.channelVibrato=A.channelVibrato,n.lockGSNRPNParams=A.lockVibrato,n.channelTransposeKeyShift=A.channelTransposeKeyShift,n.channelOctaveTuning=A.channelOctaveTuning,n.velocityOverride=A.velocityOverride,n.lockPreset=!1,n.midiControllers[m.bankSelect]=A.bank,this.programChange(e,A.program),n.lockPreset=A.lockPreset}),p("%cFinished restoring controllers!",r.info)}var ot=class{constructor(A,e){this.ready=e,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(e=>{e.soundfont.setSampleIDOffset(A),A+=e.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let e=this.soundfontList.length-1;e>=0;e--){let n=this.soundfontList[e],s=new Set;for(let o of n.soundfont.presets){let I=`${o.bank+n.bankOffset}-${o.program}`;s.has(I)||(s.add(I),A[I]=o.presetName)}}this.presetList=[];for(let[e,n]of Object.entries(A)){let s=e.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}}handleMessage(A,e){switch(A){case Ce.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ce.reloadSoundFont:this.reloadManager(e);break;case Ce.deleteSoundFont:this.deleteSoundFont(e);break;case Ce.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ge(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){T("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(n=>n.id===A);if(e===-1){T(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[e].soundfont.presets,delete this.soundfontList[e].soundfont.instruments,delete this.soundfontList[e].soundfont.samples,this.soundfontList.splice(e,1),this.generatePresetList()}addNewSoundFont(A,e,n){if(this.soundfontList.find(s=>s.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Ge(A),bankOffset:n}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,n)=>A.indexOf(e.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let n of this.soundfontList){let s=n.soundfont.getPresetNoFallback(A-n.bankOffset,e);if(s!==void 0)return s}if(A!==128){for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.program===e);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}else{for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.bank===128);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}}};var rt=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,e,n,s,o,I,C,Q){this.sampleData=A,this.playbackStep=e,this.cursor=n,this.rootKey=s,this.loopStart=o,this.loopEnd=I,this.end=C,this.loopingMode=Q,this.isLooping=this.loopingMode===1||this.loopingMode===3}},xe=class t{sample;filter=new Qe;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new JA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;realKey;constructor(A,e,n,s,o,I,C,Q,B,d){this.sample=e,this.generators=B,this.modulatedGenerators=new Int16Array(B),this.modulators=d,this.velocity=s,this.midiNote=n,this.channelNumber=o,this.startTime=I,this.targetKey=C,this.realKey=Q,this.volumeEnvelope=new UA(A,B[g.sustainVolEnv])}static copy(A,e){let n=A.sample,s=new rt(n.sampleData,n.playbackStep,n.cursor,n.rootKey,n.loopStart,n.loopEnd,n.end,n.loopingMode);return new t(A.volumeEnvelope.sampleRate,s,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.realKey,A.generators,A.modulators.map(o=>j.copy(o)))}};function uo(t,A,e,n,s,o,I=!1){let C,Q=n.cachedVoices[A][e];return Q!==void 0?Q.map(B=>xe.copy(B,s)):(C=n.preset.getSamplesAndGenerators(A,e).reduce((d,c)=>{if(c.sample.sampleData===void 0)return T(`Discarding invalid sample: ${c.sample.sampleName}`),d;let l=new Int16Array(60);for(let x=0;x<60;x++)l[x]=pn(x,c.presetGenerators,c.instrumentGenerators);l[g.initialAttenuation]=Math.floor(l[g.initialAttenuation]*.4);let u=c.sample.samplePitch;l[g.overridingRootKey]>-1&&(u=l[g.overridingRootKey]);let D=A;l[g.keyNum]>-1&&(D=l[g.keyNum]);let y=c.sample.sampleLoopStartIndex,k=c.sample.sampleLoopEndIndex,w=l[g.sampleModes],G=new rt(c.sample.getAudioData(),c.sample.sampleRate/sampleRate*Math.pow(2,c.sample.samplePitchCorrection/1200),0,u,y,k,Math.floor(c.sample.sampleData.length)-1,w);return l[g.velocity]>-1&&(e=l[g.velocity]),I&&mn([{Sample:c.sample.sampleName,Generators:l,Modulators:c.modulators.map(x=>x.debugString()),Velocity:e,TargetKey:D,MidiNote:A,WorkletSample:G}]),d.push(new xe(sampleRate,G,A,e,t,s,D,o,l,c.modulators.map(x=>j.copy(x)))),d},[]),n.cachedVoices[A][e]=C.map(d=>xe.copy(d,s)),C)}var Lt=.03,Ut=1,H=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=TA,this.interpolationType=he.fourthOrder,this.processTickCallback=void 0,this.sequencer=new IA(this),this.transposition=0,this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Ut,this.midiVolume=1,this.voiceCap=Dn,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new ot(A.processorOptions.soundfont,this.postReady.bind(this))}catch(e){throw this.post({messageType:pA.soundfontError,messageData:e}),e}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let e=0;ethis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),p("%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(),p("%cSpessaSynth is ready!",r.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:pA.ready,messageData:void 0})}debugMessage(){p({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let n=0;return this.workletProcessorChannels.forEach((s,o)=>{if(s.voices.length<1||s.isMuted)return;let I,C,Q,B,d;if(this.oneOutputMode){let l=e[0];I=o%16*2,C=l[I],Q=l[I+1]}else I=o%this._outputsAmount+2,C=e[I][0],Q=e[I][1],B=e[0],d=e[1];let c=s.voices;s.voices=[],c.forEach(l=>{this.renderVoice(s,l,C,Q,B,d),l.finished||s.voices.push(l)}),n+=s.voices.length}),n!==this.totalVoicesAmount&&(this.totalVoicesAmount=n,this.sendChannelProperties()),!0}};H.prototype.renderVoice=ts;H.prototype.releaseVoice=ss;H.prototype.voiceKilling=ns;H.prototype.getWorkletVoices=uo;H.prototype.handleMessage=is;H.prototype.sendChannelProperties=Is;H.prototype.callEvent=as;H.prototype.systemExclusive=gs;H.prototype.noteOn=Es;H.prototype.noteOff=Bs;H.prototype.polyPressure=Ds;H.prototype.killNote=hs;H.prototype.stopAll=Qs;H.prototype.stopAllChannels=cs;H.prototype.muteChannel=xs;H.prototype.setVibrato=Ns;H.prototype.disableAndLockGSNRPN=Ms;H.prototype.dataEntryCoarse=bs;H.prototype.dataEntryFine=Ls;H.prototype.createWorkletChannel=yn;H.prototype.controllerChange=ws;H.prototype.channelPressure=Ss;H.prototype.resetAllControllers=Us;H.prototype.resetControllers=Ts;H.prototype.resetParameters=Hs;H.prototype.setMasterGain=Rs;H.prototype.setMasterPan=Gs;H.prototype.setMIDIVolume=Fs;H.prototype.transposeAllChannels=ls;H.prototype.transposeChannel=us;H.prototype.setChannelTuning=ds;H.prototype.setChannelTuningSemitones=fs;H.prototype.setMasterTuning=ms;H.prototype.setModulationDepth=ps;H.prototype.pitchWheel=ys;H.prototype.setOctaveTuning=ks;H.prototype.programChange=ao;H.prototype.getPreset=Io;H.prototype.setPreset=go;H.prototype.setDrums=Co;H.prototype.reloadSoundFont=ho;H.prototype.clearSoundFont=Bo;H.prototype.setEmbeddedSoundFont=Qo;H.prototype.sendPresetList=Eo;H.prototype.sendSynthesizerSnapshot=co;H.prototype.applySynthesizerSnapshot=lo;registerProcessor(Sn,H);p("%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 e3d7d7be..2f236650 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 @@ -234,6 +234,13 @@ export class WorkletVolumeEnvelope voice.finished = true; } env.currentReleaseGain = decibelAttenuationToGain(env.releaseStartDb); + + // release: sfspec page 35: the time is for change from attenuation to -100dB + // therefore we need to calculate the real time + // (changing from release start to -100dB instead of from peak to -100dB) + const releaseFraction = (DB_SILENCE - env.releaseStartDb) / DB_SILENCE; + env.releaseDuration *= releaseFraction; + } } diff --git a/src/website/js/renderer/channel_analysers.js b/src/website/js/renderer/channel_analysers.js index f0a7f6be..8b3ca039 100644 --- a/src/website/js/renderer/channel_analysers.js +++ b/src/website/js/renderer/channel_analysers.js @@ -73,7 +73,7 @@ export function connectChannelAnalysers(synth) // connect for drum change synth.eventHandler.addEvent("drumchange", "renderer-drum-change", () => { - this.updateFftSize(); + setTimeout(this.updateFftSize.bind(this), 100); }); } diff --git a/src/website/minified/demo_main.min.js b/src/website/minified/demo_main.min.js index 15c08a25..f1524fc9 100644 --- a/src/website/minified/demo_main.min.js +++ b/src/website/minified/demo_main.min.js @@ -7,7 +7,7 @@ var EC=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(r,l)=>( `}},NB=960,GB=Gr.concave;function Nr(o,r,l,g,f){return o<<10|r<<9|l<<8|g<<7|f}var pC=[new oe({srcEnum:Nr(GB,0,1,0,Ft.noteOnVelocity),dest:v1.initialAttenuation,amt:NB,secSrcEnum:0,transform:0}),new oe({srcEnum:129,dest:v1.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new oe({srcEnum:Nr(GB,0,1,1,B3.mainVolume),dest:v1.initialAttenuation,amt:NB,secSrcEnum:0,transform:0}),new oe({srcEnum:13,dest:v1.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new oe({srcEnum:526,dest:v1.fineTune,amt:12700,secSrcEnum:16,transform:0}),new oe({srcEnum:650,dest:v1.pan,amt:500,secSrcEnum:0,transform:0}),new oe({srcEnum:Nr(GB,0,1,1,B3.expressionController),dest:v1.initialAttenuation,amt:NB,secSrcEnum:0,transform:0}),new oe({srcEnum:219,dest:v1.reverbEffectsSend,amt:750,secSrcEnum:0,transform:0}),new oe({srcEnum:221,dest:v1.chorusEffectsSend,amt:750,secSrcEnum:0,transform:0}),new oe({srcEnum:Nr(Gr.linear,0,0,0,Ft.polyPressure),dest:v1.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new oe({srcEnum:Nr(Gr.linear,0,0,1,B3.tremoloDepth),dest:v1.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new oe({srcEnum:Nr(Gr.linear,1,0,1,B3.releaseTime),dest:v1.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new oe({srcEnum:Nr(Gr.linear,1,0,1,B3.brightness),dest:v1.initialFilterFc,amt:6e3,secSrcEnum:0,transform:0}),new oe({srcEnum:Nr(Gr.linear,1,0,1,B3.timbreHarmonicContent),dest:v1.initialFilterQ,amt:250,secSrcEnum:0,transform:0})];var C$=128,ry=147,Ub=new Int16Array(ry).fill(0),ni=(o,r)=>Ub[o]=r<<7;ni(B3.mainVolume,100);ni(B3.balance,64);ni(B3.expressionController,127);ni(B3.pan,64);ni(B3.timbreHarmonicContent,64);ni(B3.releaseTime,64);ni(B3.attackTime,64);ni(B3.brightness,64);ni(B3.soundController6,64);ni(B3.soundController7,64);ni(B3.soundController8,64);ni(B3.soundController9,64);ni(B3.generalPurposeController6,64);ni(B3.generalPurposeController8,64);ni(C$+Ft.pitchWheel,64);ni(C$+Ft.pitchWheelRange,2);var QC={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},ny=Object.keys(QC).length,Pb=new Float32Array(ny);Pb[QC.modulationMultiplier]=1;var sy={velocityOverride:128};var Ob="spessasynth-worklet-system",UB=350,Di=9,qb=16;var ch=class{constructor(r,l,g=!0,f=void 0,v=iy){Y5("%cInitializing SpessaSynth synthesizer...",D1.info),this.context=r.context;let n0=f?.oneOutput===!0;this.eventHandler=new mC,this._voiceCap=UB,this._outputsAmount=qb,this.channelsAmount=this._outputsAmount,this.resolveWhenReady=void 0,this.isReady=new Promise(c0=>this.resolveWhenReady=c0),this.channelProperties=[];for(let c0=0;c0this.handleMessage(c0.data),this.soundfontManager=new BC(this),this._snapshotCallback=void 0,this.sequencerCallbackFunction=void 0,v.reverbEnabled&&!n0&&(this.reverbProcessor=ty(this.context,v.reverbImpulseResponse),this.reverbProcessor.connect(r),this.worklet.connect(this.reverbProcessor,0)),v.chorusEnabled&&!n0&&(this.chorusProcessor=new CC(r,v.chorusConfig),this.worklet.connect(this.chorusProcessor.input,1)),n0)this.worklet.connect(r,0);else for(let c0=2;c0{this.channelsAmount++})}get voiceCap(){return this._voiceCap}set voiceCap(r){this._setMasterParam(Qm.voicesCap,r),this._voiceCap=r}get highPerformanceMode(){return this._highPerformanceMode}set highPerformanceMode(r){this._highPerformanceMode=r}get currentTime(){return this.context.currentTime}get voicesAmount(){return this._voicesAmount}setLogLevel(r,l,g,f){this.post({channelNumber:Ci,messageType:c8.setLogLevel,messageData:[r,l,g,f]})}_setMasterParam(r,l){this.post({channelNumber:Ci,messageType:c8.setMasterParameter,messageData:[r,l]})}setInterpolationType(r){this._setMasterParam(Qm.interpolationType,r)}handleMessage(r){let l=r.messageData;switch(r.messageType){case m$.channelProperties:this.channelProperties=l,this._voicesAmount=this.channelProperties.reduce((g,f)=>g+f.voicesAmount,0);break;case m$.eventCall:this.eventHandler.callEvent(l.eventName,l.eventData);break;case m$.sequencerSpecific:this.sequencerCallbackFunction&&this.sequencerCallbackFunction(l.messageType,l.messageData);break;case m$.synthesizerSnapshot:this._snapshotCallback&&this._snapshotCallback(l);break;case m$.ready:this.resolveWhenReady();break;case m$.soundfontError:x4(new Error(l)),this.eventHandler.callEvent("soundfonterror",l);break}}async getSynthesizerSnapshot(){return new Promise(r=>{this._snapshotCallback=l=>{this._snapshotCallback=void 0,r(l)},this.post({messageType:c8.requestSynthesizerSnapshot,messageData:void 0,channelNumber:Ci})})}addNewChannel(r=!0){this.channelProperties.push({voicesAmount:0,pitchBend:0,pitchBendRangeSemitones:0,isMuted:!1,isDrum:!1}),r&&this.post({channelNumber:0,messageType:c8.addNewChannel,messageData:null})}setVibrato(r,l){this.post({channelNumber:r,messageType:c8.setChannelVibrato,messageData:l})}connectIndividualOutputs(r){if(r.length!==this._outputsAmount)throw new Error(`input nodes amount differs from the system's outputs amount! - Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l127||l<0)throw new Error(`Invalid controller number: ${l}`);g=Math.floor(g),l=Math.floor(l),this.post({channelNumber:r,messageType:c8.ccChange,messageData:[l,g,f]})}resetControllers(){this.post({channelNumber:Ci,messageType:c8.ccReset,messageData:void 0})}channelPressure(r,l){this.post({channelNumber:r,messageType:c8.channelPressure,messageData:l})}polyPressure(r,l,g){this.post({channelNumber:r,messageType:c8.polyPressure,messageData:[l,g]})}post(r){this.worklet.port.postMessage(r)}pitchWheel(r,l,g){this.post({channelNumber:r,messageType:c8.pitchWheel,messageData:[l,g]})}transpose(r){this.transposeChannel(Ci,r,!1)}transposeChannel(r,l,g=!1){this.post({channelNumber:r,messageType:c8.transpose,messageData:[l,g]})}setMainVolume(r){this._setMasterParam(Qm.mainVolume,r)}setMasterPan(r){this._setMasterParam(Qm.masterPan,r)}setPitchBendRange(r,l){this.controllerChange(r,B3.RPNMsb,0),this.controllerChange(r,B3.dataEntryMsb,l),this.controllerChange(r,B3.RPNMsb,127),this.controllerChange(r,B3.RPNLsb,127),this.controllerChange(r,B3.dataEntryMsb,0)}programChange(r,l,g=!1){this.post({channelNumber:r,messageType:c8.programChange,messageData:[l,g]})}velocityOverride(r,l){this.post({channelNumber:r,messageType:c8.ccChange,messageData:[sy.velocityOverride,l,!0]})}lockController(r,l,g){this.post({channelNumber:r,messageType:c8.lockController,messageData:[l,g]})}muteChannel(r,l){this.post({channelNumber:r,messageType:c8.muteChannel,messageData:l})}async reloadSoundFont(r){x4("reloadSoundFont is deprecated. Please use the soundfontManager property instead."),await this.soundfontManager.reloadManager(r)}systemExclusive(r){this.post({channelNumber:Ci,messageType:c8.systemExclusive,messageData:Array.from(r)})}setDrums(r,l){this.post({channelNumber:r,messageType:c8.setDrums,messageData:l})}sendMessage(r){let l=ey(r[0]);switch(l.status){case K3.noteOn:let g=r[2];g>0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case K3.noteOff:this.noteOff(l.channel,r[1]);break;case K3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case K3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case K3.programChange:this.programChange(l.channel,r[1]);break;case K3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case K3.channelPressure:this.channelPressure(l.channel,r[1]);break;case K3.systemExclusive:this.systemExclusive(new V3(r.slice(1)));break;case K3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,f)=>{let v;if(bn)v=127;else{let E0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let m0=f.clientX-E0.left,c0=E0.width;v=Math.floor((c0-m0)/c0*127)}else{let m0=f.clientY-E0.top,c0=E0.height;v=Math.floor(m0/c0*127)}}this.synth.noteOn(this.channel,g,v,this.enableDebugging)},l=g=>{let f=g.touches?Array.from(g.touches):[g],v=new Set;f.forEach(n0=>{let E0=document.elementFromPoint(n0.clientX,n0.clientY),m0=parseInt(E0.id.replace("note",""));v.add(m0),!(isNaN(m0)||m0<0||this.pressedKeys.has(m0))&&(this.pressedKeys.add(m0),r(m0,n0))}),this.pressedKeys.forEach(n0=>{v.has(n0)||o(n0)})};bn||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var Ay=20,wm=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,B3.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,B3.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let f=0;f<128;f++)this.releaseNote(f,g.channel)})}get shown(){return this._shown}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(v=l(r-1)),r<127&&(n0=l(r+1)),n0&&v?g.classList.add("between_sharps"):v?g.classList.add("left_sharp"):n0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let f=900/(r.max-r.min+5),v=document.styleSheets[0].cssRules,n0;for(let E0 of v)if(E0.selectorText==="#keyboard .key"){n0=E0;break}if(n0.style.setProperty("--pressed-transform-skew",`${8e-4/(f/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let E0=getComputedStyle(this.keyboard),m0=parseFloat(E0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),c0=this.keyboard.getBoundingClientRect().height,u1=f/m0,F=c0*u1-c0,q0=(this._keyRange.min+this._keyRange.max)/2,L0=(r.min+r.max)/2;this._keyRange=r;let R1=this.keys.find(Y2=>Y2.classList.contains("sharp_key")).getBoundingClientRect().width,t2=(q0-L0)*R1,y1=parseFloat(E0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${F}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${u1}) translateX(${t2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${y1/u1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${f}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${f}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let f=this.keys[r-this._keyRange.min];if(f===void 0)return;f.classList.add("pressed");let v=f.classList.contains("sharp_key"),n0=g/127,E0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),m0;if(!v&&this.mode==="light"?m0=`rgba(${E0.slice(0,3).map(u1=>255-(255-u1)*n0).join(", ")}, ${E0[3]})`:m0=`rgba(${E0.slice(0,3).map(u1=>u1*n0).join(", ")}, ${E0[3]})`,f.style.background=m0,this.mode==="dark"){let c0=Ay*n0;f.style.boxShadow=`${m0} 0px 0px ${c0}px ${c0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let f=this.keyColors[r-this._keyRange.min];if(!f)return;let v=f.findLastIndex(n0=>n0===this.channelColors[l]);v!==-1&&(f.splice(v,1),g.style.background=f[f.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${Ay}px ${f[f.length-1]}`),f.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};wm.prototype._handlePointers=oy;function B$(o,r){let l=o.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var Yb="#000";function ay(o,r,l){o.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let f=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*f,l){r.fillRect(g.xPos,g.yPos-g.height*f,g.width,g.height*(f*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*f,g.yPos,g.width*(f*2+1),g.height),r.globalAlpha=1}),o.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=Yb,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var PB=!1;function $y(o=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(PB){o&&requestAnimationFrame(this.render.bind(this));return}else PB=!0;else PB=!1;if(o&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let v=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||ay(v,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let f=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${yC}px system-ui`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,yC*2+5),this.drawingContext.fillText(this.version,this.canvas.width,5),this.drawingContext.fillText(Math.round(f).toString()+" FPS",this.canvas.width,yC+5),this.onRender&&this.onRender(),o&&requestAnimationFrame(this.render.bind(this))}function ly(o=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,f=r/(g+1),v=f-Q$*2,n0=this.noteFallingTimeMs/1e3,E0=this.noteAfterTriggerTimeMs/1e3,m0=this.seq.currentHighResolutionTime,c0=m0-E0,u1=n0+E0,F=c0+u1,q0=gy/u1,L0=[];this.synth.channelProperties.forEach(t2=>{if(this.showVisualPitch){let y1=t2.pitchBend-8192+this.visualPitchBendOffset;L0.push(t2.pitchBendRangeSemitones*(y1/8192*f))}else L0.push(0)});let R1=[];return this.noteTimes.forEach((t2,y1)=>{if(t2.renderStartIndex>=t2.notes.length||!this.renderChannels[y1])return;let Y2=t2.renderStartIndex,T2=t2.notes,V2=T2[Y2],i3=-1;for(;V2.start<=F&&(Y2++,!(this.notesOnScreen>hy));){let r3=V2.start+V2.length;if(r3>c0&&V2.length>0){let A0=V2.length/u1*l-Q$*2;if(this.notesOnScreen<1e3||A0>q0){i3===-1&&(i3=Y2-1);let y5=(V2.start-c0)/u1*l,T3;if(this._notesFall?T3=l-A0-y5+Q$:T3=y5+Q$,V2.midiNotethis.keyRange.max){if(Y2>=T2.length)break;V2=T2[Y2];continue}let $3=V2.midiNote-this.keyRange.min,w6=f*$3+Q$,s6,o9,V4,r4;if(this.sideways?(s6=T3,o9=w6,r4=v,V4=A0):(o9=T3,s6=w6,V4=v,r4=A0),this.notesOnScreen++,o)this.drawingContext.fillStyle=this.plainColors[y1],this.drawingContext.fillRect(s6+p$+Q$,o9+p$,V4-p$*2,r4-p$*2);else{let V6;if(V2.start>m0||r3=T2.length)break;V2=T2[Y2]}i3>-1&&(t2.renderStartIndex=i3)}),R1.sort((t2,y1)=>y1.height-t2.height),R1}function uy(){let o=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let f=g%4,v=Math.floor(g/4),n0=!1;for(let F=g;F0){n0=!0;break}if(!n0){let F=this.canvas.width/4,q0=this.canvas.height/4,L0=F*f,R1=q0*v+q0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(L0,R1),this.drawingContext.lineTo(L0+F,R1),this.drawingContext.stroke();return}let E0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(E0);let m0=o*f,c0=r*v+r/2,u1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let F=E0.length/4,q0=o/F,L0=Math.floor(F/2),R1=E0.length-L0;for(let T2=R1;T2>=1;T2--)if(E0[T2-1]<0&&E0[T2]>=0){R1=T2;break}let t2=m0,y1=R1-L0,Y2=R1+L0;for(let T2=y1;T2{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function Iy(){for(let o=0;o4096?this.delayNode.delayTime.value=f/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function Ey(o){o.connectIndividualOutputs(this.channelAnalysers),o.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{this.updateFftSize()})}function my(){for(let o of this.channelAnalysers)o.disconnect();Y5("%cAnalysers disconnected!",D1.recognized)}function Cy(o){this.seq=o,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),f=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${f}), rgba(0, 0, 0, ${f})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function By(){this.noteTimes&&this.noteTimes.forEach(o=>o.renderStartIndex=0)}function OB(o,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=o[o.currentIndex++]<>>0}function km(o,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=o&255,o>>=8;return l}var gh=.02;function py(o){function r(c0){return c0.messageData=new V3(c0.messageData.buffer),c0.messageData.currentIndex=0,6e7/OB(c0.messageData,3)}let l=[],f=o.tracks.flat();f.sort((c0,u1)=>c0.ticks-u1.ticks);for(let c0=0;c0<16;c0++)l.push({renderStartIndex:0,notes:[]});let v=0,n0=60/(120*o.timeDivision),E0=0,m0=0;for(;E0>4,F=c0.messageStatusByte&15;if(u1===8){let q0=l[F].notes.findLast(L0=>L0.midiNote===c0.messageData[0]&&L0.length===-1);if(q0){let L0=v-q0.start;q0.length=L0L0.midiNote===c0.messageData[0]&&L0.length===-1);if(q0){let L0=v-q0.start;q0.length=L0=f.length)break;v+=n0*(f[E0].ticks-c0.ticks)}m0>0&&l.forEach((c0,u1)=>c0.notes.filter(F=>F.length===-1).forEach(F=>{let q0=v-F.start;F.length=q0r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}computeColors(){this.channelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,B$(r,g=>g*kC)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,B$(r,g=>g*kC*wC)),l.addColorStop(1,B$(r,g=>g*wC)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,B$(r,g=>g*kC)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,B$(r,g=>g*kC*wC)),l.addColorStop(1,B$(r,g=>g*wC)),l})}};_i.prototype.render=$y;_i.prototype.computeNotePositions=ly;_i.prototype.createChannelAnalysers=dy;_i.prototype.updateFftSize=Iy;_i.prototype.connectChannelAnalysers=Ey;_i.prototype.disconnectChannelAnalysers=my;_i.prototype.connectSequencer=Cy;_i.prototype.calculateNoteTimes=py;_i.prototype.resetIndexes=By;_i.prototype.renderWaveforms=uy;function o3(o,r){let l=0;for(let g=0;g>>0}function l7(o,r,l){for(let g=0;g>g*8&255}function Q9(o,r){o[o.currentIndex++]=r&255,o[o.currentIndex++]=r>>8}function c7(o,r){l7(o,r,4)}function LA(o,r){let l=r<<8|o;return l>32767?l-65536:l}function Qy(o){return o>127?o-256:o}function Ee(o,r,l=void 0,g=!0){if(l){let f=o.slice(o.currentIndex,o.currentIndex+r);return o.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(f.buffer)}else{let f=!1,v="";for(let n0=0;n0127){if(g){f=!0;continue}else if(E0===0){f=!0;continue}}v+=String.fromCharCode(E0)}}return v}}function RA(o,r=0){let l=o.length;r>0&&(l=r);let g=new V3(l);return g7(g,o,r),g}function g7(o,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,Ee(l.chunkData,4)===r))}function vC(o){let r=[o&127];for(o>>=7;o>0;)r.unshift(o&127|128),o>>=7;return r}function SC(o){let r=[];for(let f of o.tracks){let v=[],n0=0,E0;for(let m0 of f){let c0=m0.ticks-n0,u1;m0.messageStatusByte<=K3.keySignature||m0.messageStatusByte===K3.sequenceSpecific?u1=[255,m0.messageStatusByte,...vC(m0.messageData.length),...m0.messageData]:m0.messageStatusByte===K3.systemExclusive?u1=[240,...vC(m0.messageData.length),...m0.messageData]:(u1=[],E0!==m0.messageStatusByte&&(E0=m0.messageStatusByte,u1.push(m0.messageStatusByte)),u1.push(...m0.messageData)),v.push(...vC(c0)),v.push(...u1),n0+=c0}r.push(new Uint8Array(v))}function l(f,v){for(let n0=0;n0{o.tracks.forEach((R1,t2)=>{if(o.midiPorts[t2]===L0)for(let y1=R1.length-1;y1>=0;y1--)R1[y1].messageStatusByte>=128&&R1[y1].messageStatusByte<240&&(R1[y1].messageStatusByte&15)===q0&&R1.splice(y1,1)})};g.forEach(q0=>{let L0=q0%16,R1=q0-L0,t2=o.midiPortChannelOffsets.findIndex(y1=>y1===R1);v(L0,t2),Y5(`%cRemoving channel %c${q0}%c!`,D1.info,D1.recognized,D1.info)});let n0=!1,E0="gs",m0=[],c0=[];o.tracks.forEach((q0,L0)=>{q0.forEach(R1=>{let t2=R1.messageStatusByte&240;t2===K3.controllerChange?m0.push({track:L0,message:R1,channel:R1.messageStatusByte&15}):t2===K3.programChange?c0.push({track:L0,message:R1,channel:R1.messageStatusByte&15}):R1.messageStatusByte===K3.systemExclusive&&(R1.messageData[0]===67&&R1.messageData[2]===76&&R1.messageData[5]===126&&R1.messageData[6]===0?(Y5("%cXG system on detected",D1.info),E0="xg",n0=!0):R1.messageData[0]===67&&R1.messageData[2]===76&&R1.messageData[3]===8&&R1.messageData[5]===3&&c0.push({track:L0,message:R1,channel:R1.messageData[4]}))})});let u1=(q0,L0,R1)=>o.tracks.reduce((t2,y1,Y2)=>{if(o.usedChannelsOnTrack[Y2].has(q0)&&o.midiPorts[Y2]===L0){let T2;R1?T2=y1.findIndex(V2=>(V2.messageStatusByte&240)===K3.noteOn):T2=y1.findIndex(V2=>V2.messageStatusByte>128&&V2.messageStatusByte<240&&(V2.messageStatusByte&15)===q0&&!(V2.messageStatusByte&K3.controllerChange===240&&(V2.messageData[0]===B3.resetAllControllers||V2.messageData[0]===B3.allNotesOff||V2.messageData[0]===B3.allSoundOff))),T2!==-1&&t2.push({index:T2,track:Y2})}return t2},[]),F=(q0,L0,R1)=>{let t2=m0.filter(y1=>y1.channel===q0&&y1.message.messageData[0]===R1&&o.midiPorts[y1.track]===L0);for(let y1=0;y1{let L0=q0.channel,R1=L0%16,t2=L0-R1,y1=o.midiPortChannelOffsets.findIndex(A0=>A0===t2),Y2=q0.controllerValue,T2=q0.controllerNumber;F(R1,y1,T2),Y5(`%cNo controller %c${T2}%c on channel %c${L0}%c found. Adding it!`,D1.info,D1.unrecognized,D1.info,D1.value,D1.info);let V2=u1(R1,y1,!0);if(V2.length===0){x4("Program change but no notes... ignoring!");return}let i3=V2.reduce((A0,y5)=>o.tracks[y5.track][y5.index].ticks{let L0=q0.channel%16,R1=q0.channel-L0,t2=o.midiPortChannelOffsets.findIndex($3=>$3===R1),y1=q0.isDrum?0:q0.bank,Y2=q0.program,T2=c0.filter($3=>o.midiPorts[$3.track]===t2&&$3.channel===L0);if(F(L0,t2,B3.bankSelect),F(L0,t2,B3.lsbForControl0BankSelect),(q0.isDrum||y1>0)&&!n0&&(o.tracks.forEach($3=>{for(let w6=0;w6<$3.length;w6++){let s6=$3[w6];if(s6.messageStatusByte===K3.systemExclusive)if(s6.messageData[0]===65&&s6.messageData[2]===66&&s6.messageData[6]===127){n0=!0,Y5("%cGS on detected!",D1.recognized);break}else s6.messageData[0]===126&&s6.messageData[2]===9&&(Y5("%cGM/2 on detected, removing!",D1.info),$3.splice(w6,1),w6--)}}),!n0)){let $3=0;o.tracks[0][0].messageStatusByte===K3.trackName&&$3++,o.tracks[0].splice($3,0,qB(0)),Y5("%cGS on not detected. Adding it.",D1.info),n0=!0}for(let $3 of T2)o.tracks[$3.track].splice(o.tracks[$3.track].indexOf($3.message),1);let V2=u1(L0,t2,R1>0);if(V2.length===0){x4("Program change but no notes... ignoring!");return}let i3=V2.reduce(($3,w6)=>o.tracks[w6.track][w6.index].ticks{if(o.midiPorts[T2]!==R1||!o.usedChannelsOnTrack[T2].has(L0))return;let V2=K3.noteOn|L0,i3=K3.noteOff|L0,r3=K3.polyPressure|L0;Y2.forEach(A0=>{A0.messageStatusByte!==V2&&A0.messageStatusByte!==i3&&A0.messageStatusByte!==r3||(A0.messageData[0]=Math.max(0,Math.min(127,A0.messageData[0]+t2)))})}),y1!==0){let Y2=o.tracks.find((s6,o9)=>o.usedChannelsOnTrack[o9].has(q0.channel));if(Y2===void 0){x4(`Channel ${q0.channel} unused but transpose requested???`);continue}let T2=K3.noteOn|q0.channel%16,V2=Y2.findIndex(s6=>s6.messageStatusByte===T2);if(V2===-1){x4(`No notes on channel ${q0.channel} but transpose requested???`);continue}let i3=Y2[V2].ticks,r3=y1*64+64,A0=K3.controllerChange|q0.channel%16,y5=new mi(i3,A0,new V3([B3.RPNMsb,0])),T3=new mi(i3,A0,new V3([B3.RPNLsb,1])),$3=new mi(i3,A0,new V3([B3.dataEntryMsb,r3])),w6=new mi(i3,A0,new V3([B3.lsbForControl6DataEntry,0]));Y2.splice(V2,0,w6),Y2.splice(V2,0,$3),Y2.splice(V2,0,T3),Y2.splice(V2,0,y5)}}i4()}function hh(o,r){let l=[],g=[],f=[],v=[];r.channelSnapshots.forEach((n0,E0)=>{if(n0.isMuted){g.push(E0);return}let m0=n0.channelTransposeKeyShift+n0.customControllers[QC.channelTransposeFine]/100;m0!==0&&l.push({channel:E0,keyShift:m0}),n0.lockPreset&&f.push({channel:E0,program:n0.program,bank:n0.bank,isDrum:n0.drumChannel}),n0.lockedControllers.forEach((c0,u1)=>{if(!c0||u1>127||u1===B3.bankSelect)return;let F=n0.midiControllers[u1]>>7;v.push({channel:E0,controllerNumber:u1,controllerValue:F})})}),Wb(o,f,v,g,l)}var Mt={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"},FA="utf-8",jb="Created using SpessaSynth";function wy(o,r,l,g=0,f="Shift_JIS",v={},n0=!0){if(gr("%cWriting the RMIDI File...",D1.info),Y5(`%cConfiguration: Bank offset: %c${g}%c, encoding: %c${f}`,D1.info,D1.value,D1.info,D1.value),Y5("metadata",v),Y5("Initial bank offset",r.bankOffset),n0){let Y2=function(){let r3=0,A0=1/0;return r.tracks.forEach((y5,T3)=>{t2[T3]>=y5.length||y5[t2[T3]].ticksA0>r3?A0:r3),i3=[];for(let r3=0;r30;){let r3=Y2(),A0=r.tracks[r3];if(t2[r3]>=A0.length){y1--;continue}let y5=A0[t2[r3]];t2[r3]++;let T3=r.midiPortChannelOffsets[T2[r3]];if(y5.messageStatusByte===K3.midiPort){T2[r3]=y5.messageData[0];continue}let $3=y5.messageStatusByte&240;if($3!==K3.controllerChange&&$3!==K3.programChange&&$3!==K3.systemExclusive)continue;if($3===K3.systemExclusive){if(y5.messageData[0]!==65||y5.messageData[2]!==66||y5.messageData[3]!==18||y5.messageData[4]!==64||!(y5.messageData[5]&16)||y5.messageData[6]!==21){y5.messageData[0]===67&&y5.messageData[2]===76&&y5.messageData[5]===126&&y5.messageData[6]===0?L0="xg":y5.messageData[0]===65&&y5.messageData[2]===66&&y5.messageData[6]===127?L0="gs":y5.messageData[0]===126&&y5.messageData[2]===9&&(L0="gm",R1.push({tNum:r3,e:y5}));continue}let o9=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][y5.messageData[5]&15]+T3;i3[o9].drums=!!(y5.messageData[7]>0&&y5.messageData[5]>>4);continue}let w6=(y5.messageStatusByte&15)+T3,s6=i3[w6];if($3===K3.programChange){s6.drums?l.presets.findIndex(r4=>r4.program===y5.messageData[0]&&r4.bank===128)===-1&&(y5.messageData[0]=l.presets.find(r4=>r4.bank===128)?.program||0):l.presets.findIndex(r4=>r4.program===y5.messageData[0]&&r4.bank!==128)===-1&&(y5.messageData[0]=l.presets.find(r4=>r4.bank!==128)?.program||0),s6.program=y5.messageData[0];let o9=Math.max(0,s6.lastBank?.messageData[1]-r.bankOffset),V4=s6.drums?128:o9;if(s6.lastBank===void 0)continue;if(L0==="xg"&&s6.drums&&(i3[w6].lastBank.messageData[1]=127),l.presets.findIndex(r4=>r4.bank===V4&&r4.program===y5.messageData[0])===-1){let r4=l.presets.find(V6=>V6.program===y5.messageData[0])?.bank+g||g;s6.lastBank.messageData[1]=r4,Y5(`%cNo preset %c${V4}:${y5.messageData[0]}%c. Changing bank to ${r4}.`,D1.info,D1.recognized,D1.info)}else{let V6=(V4===128?L0==="xg"?127:0:o9)+g;s6.lastBank.messageData[1]=V6,Y5(`%cPreset %c${V4}:${y5.messageData[0]}%c exists. Changing bank to ${V6}.`,D1.info,D1.recognized,D1.info)}continue}y5.messageData[0]===B3.bankSelect&&(s6.hasBankSelect=!0,L0==="xg"&&(s6.drums=y5.messageData[1]===120||y5.messageData[1]===126||y5.messageData[1]===127),s6.lastBank=y5)}if(i3.forEach((r3,A0)=>{if(r3.hasBankSelect===!0)return;let y5=A0%16,T3=K3.programChange|y5,$3=Math.floor(A0/16)*16,w6=r.midiPortChannelOffsets.indexOf($3),s6=r.tracks.find((V6,We)=>r.midiPorts[We]===w6&&r.usedChannelsOnTrack[We].has(y5));if(s6===void 0)return;let o9=s6.findIndex(V6=>V6.messageStatusByte===T3);if(o9===-1){let V6=s6.findIndex(Vi=>Vi.messageStatusByte>128&&Vi.messageStatusByte<240&&(Vi.messageStatusByte&15)===y5);if(V6===-1)return;let We=s6[V6].ticks,Or=l.getPreset(0,0).program;s6.splice(V6,0,new mi(We,K3.programChange|y5,new V3([Or]))),o9=V6}Y5(`%cAdding bank select for %c${A0}`,D1.info,D1.recognized);let V4=s6[o9].ticks,r4=l.getPreset(0,r3.program)?.bank+g||g;s6.splice(o9,0,new mi(V4,K3.controllerChange|y5,new V3([B3.bankSelect,r4])))}),L0!=="gs"&&L0!=="xg"){for(let A0 of R1)r.tracks[A0.tNum].splice(r.tracks[A0.tNum].indexOf(A0.e),1);let r3=0;r.tracks[0][0].messageStatusByte===K3.trackName&&r3++,r.tracks[0].splice(r3,0,qB(0))}}let E0=new V3(SC(r).buffer),m0=[RA("INFO")],c0=new TextEncoder;if(m0.push(Ze(Mt.software,c0.encode("SpessaSynth"),!0)),v.name!==void 0?(m0.push(Ze(Mt.name,c0.encode(v.name),!0)),f=FA):m0.push(Ze(Mt.name,r.rawMidiName,!0)),v.creationDate!==void 0)f=FA,m0.push(Ze(Mt.creationDate,c0.encode(v.creationDate),!0));else{let L0=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});m0.push(Ze(Mt.creationDate,RA(L0),!0))}if(v.comment!==void 0&&(f=FA,m0.push(Ze(Mt.comment,c0.encode(v.comment)))),v.engineer!==void 0&&m0.push(Ze(Mt.engineer,c0.encode(v.engineer),!0)),v.album!==void 0&&(f=FA,m0.push(Ze(Mt.album,c0.encode(v.album),!0))),v.artist!==void 0&&(f=FA,m0.push(Ze(Mt.artist,c0.encode(v.artist),!0))),v.genre!==void 0&&(f=FA,m0.push(Ze(Mt.genre,c0.encode(v.genre),!0))),v.picture!==void 0&&m0.push(Ze(Mt.picture,new Uint8Array(v.picture))),v.copyright!==void 0)f=FA,m0.push(Ze(Mt.copyright,c0.encode(v.copyright),!0));else{let L0=r.copyright.length>0?r.copyright:jb;m0.push(Ze(Mt.copyright,RA(L0)))}let u1=new V3(2);l7(u1,g,2),m0.push(Ze(Mt.bankOffset,u1)),v.midiEncoding!==void 0&&(m0.push(Ze(Mt.midiEncoding,c0.encode(v.midiEncoding))),f=FA),m0.push(Ze(Mt.encoding,RA(f)));let F=Sn(m0),q0=Sn([RA("RMID"),Ze("data",E0),Ze("LIST",F),o]);return Y5("%cFinished!",D1.info),i4(),Ze("RIFF",q0)}function vm(o,r){let l=0;for(;o>0;){let g=r.tempoChanges.find(v=>v.ticks=128){this.MIDIout.send(g);return}break;case MA.songChange:let f=l[0];this.songIndex=l[1],this.midiData=f,this.hasDummyData=!1,this.absoluteStartTime=0,this.duration=this.midiData.duration,Object.entries(this.onSongChange).forEach(E0=>E0[1](f)),l[2]===!0&&this.unpause();break;case MA.textEvent:let v=l;this.onTextEvent&&this.onTextEvent(v[0],v[1]);break;case MA.timeChange:let n0=this.synth.currentTime-l;Object.entries(this.onTimeChange).forEach(E0=>E0[1](n0)),this.unpause(),this._recalculateStartTime(n0);break;case MA.pause:this.pausedTime=this.currentTime,this.isFinished=l,this.isFinished&&Object.entries(this.onSongEnded).forEach(E0=>E0[1]());break;case MA.midiError:if(this.onError)this.onError(l);else throw new Error(l);return;case MA.getMIDI:this._getMIDIResolve&&this._getMIDIResolve(l)}}_recalculateStartTime(r){this.absoluteStartTime=this.synth.currentTime-r/this._playbackRate,this.highResTimeOffset=(this.synth.currentTime-performance.now()/1e3)*this._playbackRate}async getMIDI(){return new Promise(r=>{this._getMIDIResolve=r,this._sendMessage(Li.getMIDI,void 0)})}loadNewSongList(r,l=!0){this.pause(),this.midiData=ky,this.hasDummyData=!0,this.duration=99999,this._sendMessage(Li.loadNewSongList,[r,l]),this.songIndex=0,this.songsAmount=r.length,this.songsAmount>1&&(this.loop=!1),l===!1&&(this.pausedTime=this.currentTime)}connectMidiOutput(r){this.resetMIDIOut(),this.MIDIout=r,this._sendMessage(Li.changeMIDIMessageSending,r!==void 0),this.currentTime-=.1}pause(){if(this.paused){x4("Already paused");return}this.pausedTime=this.currentTime,this._sendMessage(Li.pause)}unpause(){this.pausedTime=void 0,this.isFinished=!1}play(r=!1){this.isFinished&&(r=!0),this._recalculateStartTime(this.pausedTime||0),this.unpause(),this._sendMessage(Li.play,r)}stop(){this._sendMessage(Li.stop)}};var Sm=["Shift_JIS","windows-1250","utf-8","utf-16","utf-16le","utf-16be","latin1","ISO-8859-1","ISO-8859-2","ISO-8859-3","ISO-8859-4","ISO-8859-5","ISO-8859-6","ISO-8859-7","ISO-8859-8","ISO-8859-9","ISO-8859-10","ISO-8859-11","ISO-8859-13","ISO-8859-14","ISO-8859-15","ISO-8859-16","windows-1251","windows-1252","windows-1253","windows-1254","windows-1255","windows-1256","windows-1257","windows-1258","EUC-JP","ISO-2022-JP","EUC-KR","Big5","GB18030"];function vy(o){return` + Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l127||l<0)throw new Error(`Invalid controller number: ${l}`);g=Math.floor(g),l=Math.floor(l),this.post({channelNumber:r,messageType:c8.ccChange,messageData:[l,g,f]})}resetControllers(){this.post({channelNumber:Ci,messageType:c8.ccReset,messageData:void 0})}channelPressure(r,l){this.post({channelNumber:r,messageType:c8.channelPressure,messageData:l})}polyPressure(r,l,g){this.post({channelNumber:r,messageType:c8.polyPressure,messageData:[l,g]})}post(r){this.worklet.port.postMessage(r)}pitchWheel(r,l,g){this.post({channelNumber:r,messageType:c8.pitchWheel,messageData:[l,g]})}transpose(r){this.transposeChannel(Ci,r,!1)}transposeChannel(r,l,g=!1){this.post({channelNumber:r,messageType:c8.transpose,messageData:[l,g]})}setMainVolume(r){this._setMasterParam(Qm.mainVolume,r)}setMasterPan(r){this._setMasterParam(Qm.masterPan,r)}setPitchBendRange(r,l){this.controllerChange(r,B3.RPNMsb,0),this.controllerChange(r,B3.dataEntryMsb,l),this.controllerChange(r,B3.RPNMsb,127),this.controllerChange(r,B3.RPNLsb,127),this.controllerChange(r,B3.dataEntryMsb,0)}programChange(r,l,g=!1){this.post({channelNumber:r,messageType:c8.programChange,messageData:[l,g]})}velocityOverride(r,l){this.post({channelNumber:r,messageType:c8.ccChange,messageData:[sy.velocityOverride,l,!0]})}lockController(r,l,g){this.post({channelNumber:r,messageType:c8.lockController,messageData:[l,g]})}muteChannel(r,l){this.post({channelNumber:r,messageType:c8.muteChannel,messageData:l})}async reloadSoundFont(r){x4("reloadSoundFont is deprecated. Please use the soundfontManager property instead."),await this.soundfontManager.reloadManager(r)}systemExclusive(r){this.post({channelNumber:Ci,messageType:c8.systemExclusive,messageData:Array.from(r)})}setDrums(r,l){this.post({channelNumber:r,messageType:c8.setDrums,messageData:l})}sendMessage(r){let l=ey(r[0]);switch(l.status){case K3.noteOn:let g=r[2];g>0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case K3.noteOff:this.noteOff(l.channel,r[1]);break;case K3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case K3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case K3.programChange:this.programChange(l.channel,r[1]);break;case K3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case K3.channelPressure:this.channelPressure(l.channel,r[1]);break;case K3.systemExclusive:this.systemExclusive(new V3(r.slice(1)));break;case K3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,f)=>{let v;if(bn)v=127;else{let E0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let m0=f.clientX-E0.left,c0=E0.width;v=Math.floor((c0-m0)/c0*127)}else{let m0=f.clientY-E0.top,c0=E0.height;v=Math.floor(m0/c0*127)}}this.synth.noteOn(this.channel,g,v,this.enableDebugging)},l=g=>{let f=g.touches?Array.from(g.touches):[g],v=new Set;f.forEach(n0=>{let E0=document.elementFromPoint(n0.clientX,n0.clientY),m0=parseInt(E0.id.replace("note",""));v.add(m0),!(isNaN(m0)||m0<0||this.pressedKeys.has(m0))&&(this.pressedKeys.add(m0),r(m0,n0))}),this.pressedKeys.forEach(n0=>{v.has(n0)||o(n0)})};bn||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var Ay=20,wm=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,B3.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,B3.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let f=0;f<128;f++)this.releaseNote(f,g.channel)})}get shown(){return this._shown}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(v=l(r-1)),r<127&&(n0=l(r+1)),n0&&v?g.classList.add("between_sharps"):v?g.classList.add("left_sharp"):n0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let f=900/(r.max-r.min+5),v=document.styleSheets[0].cssRules,n0;for(let E0 of v)if(E0.selectorText==="#keyboard .key"){n0=E0;break}if(n0.style.setProperty("--pressed-transform-skew",`${8e-4/(f/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let E0=getComputedStyle(this.keyboard),m0=parseFloat(E0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),c0=this.keyboard.getBoundingClientRect().height,u1=f/m0,F=c0*u1-c0,q0=(this._keyRange.min+this._keyRange.max)/2,L0=(r.min+r.max)/2;this._keyRange=r;let R1=this.keys.find(Y2=>Y2.classList.contains("sharp_key")).getBoundingClientRect().width,t2=(q0-L0)*R1,y1=parseFloat(E0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${F}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${u1}) translateX(${t2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${y1/u1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${f}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${f}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let f=this.keys[r-this._keyRange.min];if(f===void 0)return;f.classList.add("pressed");let v=f.classList.contains("sharp_key"),n0=g/127,E0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),m0;if(!v&&this.mode==="light"?m0=`rgba(${E0.slice(0,3).map(u1=>255-(255-u1)*n0).join(", ")}, ${E0[3]})`:m0=`rgba(${E0.slice(0,3).map(u1=>u1*n0).join(", ")}, ${E0[3]})`,f.style.background=m0,this.mode==="dark"){let c0=Ay*n0;f.style.boxShadow=`${m0} 0px 0px ${c0}px ${c0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let f=this.keyColors[r-this._keyRange.min];if(!f)return;let v=f.findLastIndex(n0=>n0===this.channelColors[l]);v!==-1&&(f.splice(v,1),g.style.background=f[f.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${Ay}px ${f[f.length-1]}`),f.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};wm.prototype._handlePointers=oy;function B$(o,r){let l=o.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var Yb="#000";function ay(o,r,l){o.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let f=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*f,l){r.fillRect(g.xPos,g.yPos-g.height*f,g.width,g.height*(f*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*f,g.yPos,g.width*(f*2+1),g.height),r.globalAlpha=1}),o.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=Yb,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var PB=!1;function $y(o=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(PB){o&&requestAnimationFrame(this.render.bind(this));return}else PB=!0;else PB=!1;if(o&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let v=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||ay(v,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let f=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${yC}px system-ui`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,yC*2+5),this.drawingContext.fillText(this.version,this.canvas.width,5),this.drawingContext.fillText(Math.round(f).toString()+" FPS",this.canvas.width,yC+5),this.onRender&&this.onRender(),o&&requestAnimationFrame(this.render.bind(this))}function ly(o=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,f=r/(g+1),v=f-Q$*2,n0=this.noteFallingTimeMs/1e3,E0=this.noteAfterTriggerTimeMs/1e3,m0=this.seq.currentHighResolutionTime,c0=m0-E0,u1=n0+E0,F=c0+u1,q0=gy/u1,L0=[];this.synth.channelProperties.forEach(t2=>{if(this.showVisualPitch){let y1=t2.pitchBend-8192+this.visualPitchBendOffset;L0.push(t2.pitchBendRangeSemitones*(y1/8192*f))}else L0.push(0)});let R1=[];return this.noteTimes.forEach((t2,y1)=>{if(t2.renderStartIndex>=t2.notes.length||!this.renderChannels[y1])return;let Y2=t2.renderStartIndex,T2=t2.notes,V2=T2[Y2],i3=-1;for(;V2.start<=F&&(Y2++,!(this.notesOnScreen>hy));){let r3=V2.start+V2.length;if(r3>c0&&V2.length>0){let A0=V2.length/u1*l-Q$*2;if(this.notesOnScreen<1e3||A0>q0){i3===-1&&(i3=Y2-1);let y5=(V2.start-c0)/u1*l,T3;if(this._notesFall?T3=l-A0-y5+Q$:T3=y5+Q$,V2.midiNotethis.keyRange.max){if(Y2>=T2.length)break;V2=T2[Y2];continue}let $3=V2.midiNote-this.keyRange.min,w6=f*$3+Q$,s6,o9,V4,r4;if(this.sideways?(s6=T3,o9=w6,r4=v,V4=A0):(o9=T3,s6=w6,V4=v,r4=A0),this.notesOnScreen++,o)this.drawingContext.fillStyle=this.plainColors[y1],this.drawingContext.fillRect(s6+p$+Q$,o9+p$,V4-p$*2,r4-p$*2);else{let V6;if(V2.start>m0||r3=T2.length)break;V2=T2[Y2]}i3>-1&&(t2.renderStartIndex=i3)}),R1.sort((t2,y1)=>y1.height-t2.height),R1}function uy(){let o=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let f=g%4,v=Math.floor(g/4),n0=!1;for(let F=g;F0){n0=!0;break}if(!n0){let F=this.canvas.width/4,q0=this.canvas.height/4,L0=F*f,R1=q0*v+q0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(L0,R1),this.drawingContext.lineTo(L0+F,R1),this.drawingContext.stroke();return}let E0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(E0);let m0=o*f,c0=r*v+r/2,u1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let F=E0.length/4,q0=o/F,L0=Math.floor(F/2),R1=E0.length-L0;for(let T2=R1;T2>=1;T2--)if(E0[T2-1]<0&&E0[T2]>=0){R1=T2;break}let t2=m0,y1=R1-L0,Y2=R1+L0;for(let T2=y1;T2{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function Iy(){for(let o=0;o4096?this.delayNode.delayTime.value=f/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function Ey(o){o.connectIndividualOutputs(this.channelAnalysers),o.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{setTimeout(this.updateFftSize.bind(this),100)})}function my(){for(let o of this.channelAnalysers)o.disconnect();Y5("%cAnalysers disconnected!",D1.recognized)}function Cy(o){this.seq=o,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),f=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${f}), rgba(0, 0, 0, ${f})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function By(){this.noteTimes&&this.noteTimes.forEach(o=>o.renderStartIndex=0)}function OB(o,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=o[o.currentIndex++]<>>0}function km(o,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=o&255,o>>=8;return l}var gh=.02;function py(o){function r(c0){return c0.messageData=new V3(c0.messageData.buffer),c0.messageData.currentIndex=0,6e7/OB(c0.messageData,3)}let l=[],f=o.tracks.flat();f.sort((c0,u1)=>c0.ticks-u1.ticks);for(let c0=0;c0<16;c0++)l.push({renderStartIndex:0,notes:[]});let v=0,n0=60/(120*o.timeDivision),E0=0,m0=0;for(;E0>4,F=c0.messageStatusByte&15;if(u1===8){let q0=l[F].notes.findLast(L0=>L0.midiNote===c0.messageData[0]&&L0.length===-1);if(q0){let L0=v-q0.start;q0.length=L0L0.midiNote===c0.messageData[0]&&L0.length===-1);if(q0){let L0=v-q0.start;q0.length=L0=f.length)break;v+=n0*(f[E0].ticks-c0.ticks)}m0>0&&l.forEach((c0,u1)=>c0.notes.filter(F=>F.length===-1).forEach(F=>{let q0=v-F.start;F.length=q0r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}computeColors(){this.channelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,B$(r,g=>g*kC)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,B$(r,g=>g*kC*wC)),l.addColorStop(1,B$(r,g=>g*wC)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,B$(r,g=>g*kC)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,B$(r,g=>g*kC*wC)),l.addColorStop(1,B$(r,g=>g*wC)),l})}};_i.prototype.render=$y;_i.prototype.computeNotePositions=ly;_i.prototype.createChannelAnalysers=dy;_i.prototype.updateFftSize=Iy;_i.prototype.connectChannelAnalysers=Ey;_i.prototype.disconnectChannelAnalysers=my;_i.prototype.connectSequencer=Cy;_i.prototype.calculateNoteTimes=py;_i.prototype.resetIndexes=By;_i.prototype.renderWaveforms=uy;function o3(o,r){let l=0;for(let g=0;g>>0}function l7(o,r,l){for(let g=0;g>g*8&255}function Q9(o,r){o[o.currentIndex++]=r&255,o[o.currentIndex++]=r>>8}function c7(o,r){l7(o,r,4)}function LA(o,r){let l=r<<8|o;return l>32767?l-65536:l}function Qy(o){return o>127?o-256:o}function Ee(o,r,l=void 0,g=!0){if(l){let f=o.slice(o.currentIndex,o.currentIndex+r);return o.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(f.buffer)}else{let f=!1,v="";for(let n0=0;n0127){if(g){f=!0;continue}else if(E0===0){f=!0;continue}}v+=String.fromCharCode(E0)}}return v}}function RA(o,r=0){let l=o.length;r>0&&(l=r);let g=new V3(l);return g7(g,o,r),g}function g7(o,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,Ee(l.chunkData,4)===r))}function vC(o){let r=[o&127];for(o>>=7;o>0;)r.unshift(o&127|128),o>>=7;return r}function SC(o){let r=[];for(let f of o.tracks){let v=[],n0=0,E0;for(let m0 of f){let c0=m0.ticks-n0,u1;m0.messageStatusByte<=K3.keySignature||m0.messageStatusByte===K3.sequenceSpecific?u1=[255,m0.messageStatusByte,...vC(m0.messageData.length),...m0.messageData]:m0.messageStatusByte===K3.systemExclusive?u1=[240,...vC(m0.messageData.length),...m0.messageData]:(u1=[],E0!==m0.messageStatusByte&&(E0=m0.messageStatusByte,u1.push(m0.messageStatusByte)),u1.push(...m0.messageData)),v.push(...vC(c0)),v.push(...u1),n0+=c0}r.push(new Uint8Array(v))}function l(f,v){for(let n0=0;n0{o.tracks.forEach((R1,t2)=>{if(o.midiPorts[t2]===L0)for(let y1=R1.length-1;y1>=0;y1--)R1[y1].messageStatusByte>=128&&R1[y1].messageStatusByte<240&&(R1[y1].messageStatusByte&15)===q0&&R1.splice(y1,1)})};g.forEach(q0=>{let L0=q0%16,R1=q0-L0,t2=o.midiPortChannelOffsets.findIndex(y1=>y1===R1);v(L0,t2),Y5(`%cRemoving channel %c${q0}%c!`,D1.info,D1.recognized,D1.info)});let n0=!1,E0="gs",m0=[],c0=[];o.tracks.forEach((q0,L0)=>{q0.forEach(R1=>{let t2=R1.messageStatusByte&240;t2===K3.controllerChange?m0.push({track:L0,message:R1,channel:R1.messageStatusByte&15}):t2===K3.programChange?c0.push({track:L0,message:R1,channel:R1.messageStatusByte&15}):R1.messageStatusByte===K3.systemExclusive&&(R1.messageData[0]===67&&R1.messageData[2]===76&&R1.messageData[5]===126&&R1.messageData[6]===0?(Y5("%cXG system on detected",D1.info),E0="xg",n0=!0):R1.messageData[0]===67&&R1.messageData[2]===76&&R1.messageData[3]===8&&R1.messageData[5]===3&&c0.push({track:L0,message:R1,channel:R1.messageData[4]}))})});let u1=(q0,L0,R1)=>o.tracks.reduce((t2,y1,Y2)=>{if(o.usedChannelsOnTrack[Y2].has(q0)&&o.midiPorts[Y2]===L0){let T2;R1?T2=y1.findIndex(V2=>(V2.messageStatusByte&240)===K3.noteOn):T2=y1.findIndex(V2=>V2.messageStatusByte>128&&V2.messageStatusByte<240&&(V2.messageStatusByte&15)===q0&&!(V2.messageStatusByte&K3.controllerChange===240&&(V2.messageData[0]===B3.resetAllControllers||V2.messageData[0]===B3.allNotesOff||V2.messageData[0]===B3.allSoundOff))),T2!==-1&&t2.push({index:T2,track:Y2})}return t2},[]),F=(q0,L0,R1)=>{let t2=m0.filter(y1=>y1.channel===q0&&y1.message.messageData[0]===R1&&o.midiPorts[y1.track]===L0);for(let y1=0;y1{let L0=q0.channel,R1=L0%16,t2=L0-R1,y1=o.midiPortChannelOffsets.findIndex(A0=>A0===t2),Y2=q0.controllerValue,T2=q0.controllerNumber;F(R1,y1,T2),Y5(`%cNo controller %c${T2}%c on channel %c${L0}%c found. Adding it!`,D1.info,D1.unrecognized,D1.info,D1.value,D1.info);let V2=u1(R1,y1,!0);if(V2.length===0){x4("Program change but no notes... ignoring!");return}let i3=V2.reduce((A0,y5)=>o.tracks[y5.track][y5.index].ticks{let L0=q0.channel%16,R1=q0.channel-L0,t2=o.midiPortChannelOffsets.findIndex($3=>$3===R1),y1=q0.isDrum?0:q0.bank,Y2=q0.program,T2=c0.filter($3=>o.midiPorts[$3.track]===t2&&$3.channel===L0);if(F(L0,t2,B3.bankSelect),F(L0,t2,B3.lsbForControl0BankSelect),(q0.isDrum||y1>0)&&!n0&&(o.tracks.forEach($3=>{for(let w6=0;w6<$3.length;w6++){let s6=$3[w6];if(s6.messageStatusByte===K3.systemExclusive)if(s6.messageData[0]===65&&s6.messageData[2]===66&&s6.messageData[6]===127){n0=!0,Y5("%cGS on detected!",D1.recognized);break}else s6.messageData[0]===126&&s6.messageData[2]===9&&(Y5("%cGM/2 on detected, removing!",D1.info),$3.splice(w6,1),w6--)}}),!n0)){let $3=0;o.tracks[0][0].messageStatusByte===K3.trackName&&$3++,o.tracks[0].splice($3,0,qB(0)),Y5("%cGS on not detected. Adding it.",D1.info),n0=!0}for(let $3 of T2)o.tracks[$3.track].splice(o.tracks[$3.track].indexOf($3.message),1);let V2=u1(L0,t2,R1>0);if(V2.length===0){x4("Program change but no notes... ignoring!");return}let i3=V2.reduce(($3,w6)=>o.tracks[w6.track][w6.index].ticks{if(o.midiPorts[T2]!==R1||!o.usedChannelsOnTrack[T2].has(L0))return;let V2=K3.noteOn|L0,i3=K3.noteOff|L0,r3=K3.polyPressure|L0;Y2.forEach(A0=>{A0.messageStatusByte!==V2&&A0.messageStatusByte!==i3&&A0.messageStatusByte!==r3||(A0.messageData[0]=Math.max(0,Math.min(127,A0.messageData[0]+t2)))})}),y1!==0){let Y2=o.tracks.find((s6,o9)=>o.usedChannelsOnTrack[o9].has(q0.channel));if(Y2===void 0){x4(`Channel ${q0.channel} unused but transpose requested???`);continue}let T2=K3.noteOn|q0.channel%16,V2=Y2.findIndex(s6=>s6.messageStatusByte===T2);if(V2===-1){x4(`No notes on channel ${q0.channel} but transpose requested???`);continue}let i3=Y2[V2].ticks,r3=y1*64+64,A0=K3.controllerChange|q0.channel%16,y5=new mi(i3,A0,new V3([B3.RPNMsb,0])),T3=new mi(i3,A0,new V3([B3.RPNLsb,1])),$3=new mi(i3,A0,new V3([B3.dataEntryMsb,r3])),w6=new mi(i3,A0,new V3([B3.lsbForControl6DataEntry,0]));Y2.splice(V2,0,w6),Y2.splice(V2,0,$3),Y2.splice(V2,0,T3),Y2.splice(V2,0,y5)}}i4()}function hh(o,r){let l=[],g=[],f=[],v=[];r.channelSnapshots.forEach((n0,E0)=>{if(n0.isMuted){g.push(E0);return}let m0=n0.channelTransposeKeyShift+n0.customControllers[QC.channelTransposeFine]/100;m0!==0&&l.push({channel:E0,keyShift:m0}),n0.lockPreset&&f.push({channel:E0,program:n0.program,bank:n0.bank,isDrum:n0.drumChannel}),n0.lockedControllers.forEach((c0,u1)=>{if(!c0||u1>127||u1===B3.bankSelect)return;let F=n0.midiControllers[u1]>>7;v.push({channel:E0,controllerNumber:u1,controllerValue:F})})}),Wb(o,f,v,g,l)}var Mt={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"},FA="utf-8",jb="Created using SpessaSynth";function wy(o,r,l,g=0,f="Shift_JIS",v={},n0=!0){if(gr("%cWriting the RMIDI File...",D1.info),Y5(`%cConfiguration: Bank offset: %c${g}%c, encoding: %c${f}`,D1.info,D1.value,D1.info,D1.value),Y5("metadata",v),Y5("Initial bank offset",r.bankOffset),n0){let Y2=function(){let r3=0,A0=1/0;return r.tracks.forEach((y5,T3)=>{t2[T3]>=y5.length||y5[t2[T3]].ticksA0>r3?A0:r3),i3=[];for(let r3=0;r30;){let r3=Y2(),A0=r.tracks[r3];if(t2[r3]>=A0.length){y1--;continue}let y5=A0[t2[r3]];t2[r3]++;let T3=r.midiPortChannelOffsets[T2[r3]];if(y5.messageStatusByte===K3.midiPort){T2[r3]=y5.messageData[0];continue}let $3=y5.messageStatusByte&240;if($3!==K3.controllerChange&&$3!==K3.programChange&&$3!==K3.systemExclusive)continue;if($3===K3.systemExclusive){if(y5.messageData[0]!==65||y5.messageData[2]!==66||y5.messageData[3]!==18||y5.messageData[4]!==64||!(y5.messageData[5]&16)||y5.messageData[6]!==21){y5.messageData[0]===67&&y5.messageData[2]===76&&y5.messageData[5]===126&&y5.messageData[6]===0?L0="xg":y5.messageData[0]===65&&y5.messageData[2]===66&&y5.messageData[6]===127?L0="gs":y5.messageData[0]===126&&y5.messageData[2]===9&&(L0="gm",R1.push({tNum:r3,e:y5}));continue}let o9=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][y5.messageData[5]&15]+T3;i3[o9].drums=!!(y5.messageData[7]>0&&y5.messageData[5]>>4);continue}let w6=(y5.messageStatusByte&15)+T3,s6=i3[w6];if($3===K3.programChange){s6.drums?l.presets.findIndex(r4=>r4.program===y5.messageData[0]&&r4.bank===128)===-1&&(y5.messageData[0]=l.presets.find(r4=>r4.bank===128)?.program||0):l.presets.findIndex(r4=>r4.program===y5.messageData[0]&&r4.bank!==128)===-1&&(y5.messageData[0]=l.presets.find(r4=>r4.bank!==128)?.program||0),s6.program=y5.messageData[0];let o9=Math.max(0,s6.lastBank?.messageData[1]-r.bankOffset),V4=s6.drums?128:o9;if(s6.lastBank===void 0)continue;if(L0==="xg"&&s6.drums&&(i3[w6].lastBank.messageData[1]=127),l.presets.findIndex(r4=>r4.bank===V4&&r4.program===y5.messageData[0])===-1){let r4=l.presets.find(V6=>V6.program===y5.messageData[0])?.bank+g||g;s6.lastBank.messageData[1]=r4,Y5(`%cNo preset %c${V4}:${y5.messageData[0]}%c. Changing bank to ${r4}.`,D1.info,D1.recognized,D1.info)}else{let V6=(V4===128?L0==="xg"?127:0:o9)+g;s6.lastBank.messageData[1]=V6,Y5(`%cPreset %c${V4}:${y5.messageData[0]}%c exists. Changing bank to ${V6}.`,D1.info,D1.recognized,D1.info)}continue}y5.messageData[0]===B3.bankSelect&&(s6.hasBankSelect=!0,L0==="xg"&&(s6.drums=y5.messageData[1]===120||y5.messageData[1]===126||y5.messageData[1]===127),s6.lastBank=y5)}if(i3.forEach((r3,A0)=>{if(r3.hasBankSelect===!0)return;let y5=A0%16,T3=K3.programChange|y5,$3=Math.floor(A0/16)*16,w6=r.midiPortChannelOffsets.indexOf($3),s6=r.tracks.find((V6,We)=>r.midiPorts[We]===w6&&r.usedChannelsOnTrack[We].has(y5));if(s6===void 0)return;let o9=s6.findIndex(V6=>V6.messageStatusByte===T3);if(o9===-1){let V6=s6.findIndex(Vi=>Vi.messageStatusByte>128&&Vi.messageStatusByte<240&&(Vi.messageStatusByte&15)===y5);if(V6===-1)return;let We=s6[V6].ticks,Or=l.getPreset(0,0).program;s6.splice(V6,0,new mi(We,K3.programChange|y5,new V3([Or]))),o9=V6}Y5(`%cAdding bank select for %c${A0}`,D1.info,D1.recognized);let V4=s6[o9].ticks,r4=l.getPreset(0,r3.program)?.bank+g||g;s6.splice(o9,0,new mi(V4,K3.controllerChange|y5,new V3([B3.bankSelect,r4])))}),L0!=="gs"&&L0!=="xg"){for(let A0 of R1)r.tracks[A0.tNum].splice(r.tracks[A0.tNum].indexOf(A0.e),1);let r3=0;r.tracks[0][0].messageStatusByte===K3.trackName&&r3++,r.tracks[0].splice(r3,0,qB(0))}}let E0=new V3(SC(r).buffer),m0=[RA("INFO")],c0=new TextEncoder;if(m0.push(Ze(Mt.software,c0.encode("SpessaSynth"),!0)),v.name!==void 0?(m0.push(Ze(Mt.name,c0.encode(v.name),!0)),f=FA):m0.push(Ze(Mt.name,r.rawMidiName,!0)),v.creationDate!==void 0)f=FA,m0.push(Ze(Mt.creationDate,c0.encode(v.creationDate),!0));else{let L0=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});m0.push(Ze(Mt.creationDate,RA(L0),!0))}if(v.comment!==void 0&&(f=FA,m0.push(Ze(Mt.comment,c0.encode(v.comment)))),v.engineer!==void 0&&m0.push(Ze(Mt.engineer,c0.encode(v.engineer),!0)),v.album!==void 0&&(f=FA,m0.push(Ze(Mt.album,c0.encode(v.album),!0))),v.artist!==void 0&&(f=FA,m0.push(Ze(Mt.artist,c0.encode(v.artist),!0))),v.genre!==void 0&&(f=FA,m0.push(Ze(Mt.genre,c0.encode(v.genre),!0))),v.picture!==void 0&&m0.push(Ze(Mt.picture,new Uint8Array(v.picture))),v.copyright!==void 0)f=FA,m0.push(Ze(Mt.copyright,c0.encode(v.copyright),!0));else{let L0=r.copyright.length>0?r.copyright:jb;m0.push(Ze(Mt.copyright,RA(L0)))}let u1=new V3(2);l7(u1,g,2),m0.push(Ze(Mt.bankOffset,u1)),v.midiEncoding!==void 0&&(m0.push(Ze(Mt.midiEncoding,c0.encode(v.midiEncoding))),f=FA),m0.push(Ze(Mt.encoding,RA(f)));let F=Sn(m0),q0=Sn([RA("RMID"),Ze("data",E0),Ze("LIST",F),o]);return Y5("%cFinished!",D1.info),i4(),Ze("RIFF",q0)}function vm(o,r){let l=0;for(;o>0;){let g=r.tempoChanges.find(v=>v.ticks=128){this.MIDIout.send(g);return}break;case MA.songChange:let f=l[0];this.songIndex=l[1],this.midiData=f,this.hasDummyData=!1,this.absoluteStartTime=0,this.duration=this.midiData.duration,Object.entries(this.onSongChange).forEach(E0=>E0[1](f)),l[2]===!0&&this.unpause();break;case MA.textEvent:let v=l;this.onTextEvent&&this.onTextEvent(v[0],v[1]);break;case MA.timeChange:let n0=this.synth.currentTime-l;Object.entries(this.onTimeChange).forEach(E0=>E0[1](n0)),this.unpause(),this._recalculateStartTime(n0);break;case MA.pause:this.pausedTime=this.currentTime,this.isFinished=l,this.isFinished&&Object.entries(this.onSongEnded).forEach(E0=>E0[1]());break;case MA.midiError:if(this.onError)this.onError(l);else throw new Error(l);return;case MA.getMIDI:this._getMIDIResolve&&this._getMIDIResolve(l)}}_recalculateStartTime(r){this.absoluteStartTime=this.synth.currentTime-r/this._playbackRate,this.highResTimeOffset=(this.synth.currentTime-performance.now()/1e3)*this._playbackRate}async getMIDI(){return new Promise(r=>{this._getMIDIResolve=r,this._sendMessage(Li.getMIDI,void 0)})}loadNewSongList(r,l=!0){this.pause(),this.midiData=ky,this.hasDummyData=!0,this.duration=99999,this._sendMessage(Li.loadNewSongList,[r,l]),this.songIndex=0,this.songsAmount=r.length,this.songsAmount>1&&(this.loop=!1),l===!1&&(this.pausedTime=this.currentTime)}connectMidiOutput(r){this.resetMIDIOut(),this.MIDIout=r,this._sendMessage(Li.changeMIDIMessageSending,r!==void 0),this.currentTime-=.1}pause(){if(this.paused){x4("Already paused");return}this.pausedTime=this.currentTime,this._sendMessage(Li.pause)}unpause(){this.pausedTime=void 0,this.isFinished=!1}play(r=!1){this.isFinished&&(r=!0),this._recalculateStartTime(this.pausedTime||0),this.unpause(),this._sendMessage(Li.play,r)}stop(){this._sendMessage(Li.stop)}};var Sm=["Shift_JIS","windows-1250","utf-8","utf-16","utf-16le","utf-16be","latin1","ISO-8859-1","ISO-8859-2","ISO-8859-3","ISO-8859-4","ISO-8859-5","ISO-8859-6","ISO-8859-7","ISO-8859-8","ISO-8859-9","ISO-8859-10","ISO-8859-11","ISO-8859-13","ISO-8859-14","ISO-8859-15","ISO-8859-16","windows-1251","windows-1252","windows-1253","windows-1254","windows-1255","windows-1256","windows-1257","windows-1258","EUC-JP","ISO-2022-JP","EUC-KR","Big5","GB18030"];function vy(o){return` `}function y$(o){return` diff --git a/src/website/minified/local_main.min.js b/src/website/minified/local_main.min.js index 66ef5717..fba09fb6 100644 --- a/src/website/minified/local_main.min.js +++ b/src/website/minified/local_main.min.js @@ -7,7 +7,7 @@ var hC=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(r,l)=>( `}},xB=960,RB=Nr.concave;function Tr(o,r,l,g,f){return o<<10|r<<9|l<<8|g<<7|f}var EC=[new se({srcEnum:Tr(RB,0,1,0,Rt.noteOnVelocity),dest:v1.initialAttenuation,amt:xB,secSrcEnum:0,transform:0}),new se({srcEnum:129,dest:v1.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new se({srcEnum:Tr(RB,0,1,1,B3.mainVolume),dest:v1.initialAttenuation,amt:xB,secSrcEnum:0,transform:0}),new se({srcEnum:13,dest:v1.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new se({srcEnum:526,dest:v1.fineTune,amt:12700,secSrcEnum:16,transform:0}),new se({srcEnum:650,dest:v1.pan,amt:500,secSrcEnum:0,transform:0}),new se({srcEnum:Tr(RB,0,1,1,B3.expressionController),dest:v1.initialAttenuation,amt:xB,secSrcEnum:0,transform:0}),new se({srcEnum:219,dest:v1.reverbEffectsSend,amt:750,secSrcEnum:0,transform:0}),new se({srcEnum:221,dest:v1.chorusEffectsSend,amt:750,secSrcEnum:0,transform:0}),new se({srcEnum:Tr(Nr.linear,0,0,0,Rt.polyPressure),dest:v1.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new se({srcEnum:Tr(Nr.linear,0,0,1,B3.tremoloDepth),dest:v1.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new se({srcEnum:Tr(Nr.linear,1,0,1,B3.releaseTime),dest:v1.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new se({srcEnum:Tr(Nr.linear,1,0,1,B3.brightness),dest:v1.initialFilterFc,amt:6e3,secSrcEnum:0,transform:0}),new se({srcEnum:Tr(Nr.linear,1,0,1,B3.timbreHarmonicContent),dest:v1.initialFilterQ,amt:250,secSrcEnum:0,transform:0})];var m$=128,XQ=147,Fb=new Int16Array(XQ).fill(0),ni=(o,r)=>Fb[o]=r<<7;ni(B3.mainVolume,100);ni(B3.balance,64);ni(B3.expressionController,127);ni(B3.pan,64);ni(B3.timbreHarmonicContent,64);ni(B3.releaseTime,64);ni(B3.attackTime,64);ni(B3.brightness,64);ni(B3.soundController6,64);ni(B3.soundController7,64);ni(B3.soundController8,64);ni(B3.soundController9,64);ni(B3.generalPurposeController6,64);ni(B3.generalPurposeController8,64);ni(m$+Rt.pitchWheel,64);ni(m$+Rt.pitchWheelRange,2);var mC={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},ey=Object.keys(mC).length,Mb=new Float32Array(ey);Mb[mC.modulationMultiplier]=1;var ty={velocityOverride:128};var Tb="spessasynth-worklet-system",LB=350,Di=9,Nb=16;var ah=class{constructor(r,l,g=!0,f=void 0,D=jQ){W5("%cInitializing SpessaSynth synthesizer...",D1.info),this.context=r.context;let o0=f?.oneOutput===!0;this.eventHandler=new uC,this._voiceCap=LB,this._outputsAmount=Nb,this.channelsAmount=this._outputsAmount,this.resolveWhenReady=void 0,this.isReady=new Promise(l0=>this.resolveWhenReady=l0),this.channelProperties=[];for(let l0=0;l0this.handleMessage(l0.data),this.soundfontManager=new IC(this),this._snapshotCallback=void 0,this.sequencerCallbackFunction=void 0,D.reverbEnabled&&!o0&&(this.reverbProcessor=KQ(this.context,D.reverbImpulseResponse),this.reverbProcessor.connect(r),this.worklet.connect(this.reverbProcessor,0)),D.chorusEnabled&&!o0&&(this.chorusProcessor=new fC(r,D.chorusConfig),this.worklet.connect(this.chorusProcessor.input,1)),o0)this.worklet.connect(r,0);else for(let l0=2;l0{this.channelsAmount++})}get voiceCap(){return this._voiceCap}set voiceCap(r){this._setMasterParam(Cm.voicesCap,r),this._voiceCap=r}get highPerformanceMode(){return this._highPerformanceMode}set highPerformanceMode(r){this._highPerformanceMode=r}get currentTime(){return this.context.currentTime}get voicesAmount(){return this._voicesAmount}setLogLevel(r,l,g,f){this.post({channelNumber:Ci,messageType:c8.setLogLevel,messageData:[r,l,g,f]})}_setMasterParam(r,l){this.post({channelNumber:Ci,messageType:c8.setMasterParameter,messageData:[r,l]})}setInterpolationType(r){this._setMasterParam(Cm.interpolationType,r)}handleMessage(r){let l=r.messageData;switch(r.messageType){case E$.channelProperties:this.channelProperties=l,this._voicesAmount=this.channelProperties.reduce((g,f)=>g+f.voicesAmount,0);break;case E$.eventCall:this.eventHandler.callEvent(l.eventName,l.eventData);break;case E$.sequencerSpecific:this.sequencerCallbackFunction&&this.sequencerCallbackFunction(l.messageType,l.messageData);break;case E$.synthesizerSnapshot:this._snapshotCallback&&this._snapshotCallback(l);break;case E$.ready:this.resolveWhenReady();break;case E$.soundfontError:Ie(new Error(l)),this.eventHandler.callEvent("soundfonterror",l);break}}async getSynthesizerSnapshot(){return new Promise(r=>{this._snapshotCallback=l=>{this._snapshotCallback=void 0,r(l)},this.post({messageType:c8.requestSynthesizerSnapshot,messageData:void 0,channelNumber:Ci})})}addNewChannel(r=!0){this.channelProperties.push({voicesAmount:0,pitchBend:0,pitchBendRangeSemitones:0,isMuted:!1,isDrum:!1}),r&&this.post({channelNumber:0,messageType:c8.addNewChannel,messageData:null})}setVibrato(r,l){this.post({channelNumber:r,messageType:c8.setChannelVibrato,messageData:l})}connectIndividualOutputs(r){if(r.length!==this._outputsAmount)throw new Error(`input nodes amount differs from the system's outputs amount! - Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l127||l<0)throw new Error(`Invalid controller number: ${l}`);g=Math.floor(g),l=Math.floor(l),this.post({channelNumber:r,messageType:c8.ccChange,messageData:[l,g,f]})}resetControllers(){this.post({channelNumber:Ci,messageType:c8.ccReset,messageData:void 0})}channelPressure(r,l){this.post({channelNumber:r,messageType:c8.channelPressure,messageData:l})}polyPressure(r,l,g){this.post({channelNumber:r,messageType:c8.polyPressure,messageData:[l,g]})}post(r){this.worklet.port.postMessage(r)}pitchWheel(r,l,g){this.post({channelNumber:r,messageType:c8.pitchWheel,messageData:[l,g]})}transpose(r){this.transposeChannel(Ci,r,!1)}transposeChannel(r,l,g=!1){this.post({channelNumber:r,messageType:c8.transpose,messageData:[l,g]})}setMainVolume(r){this._setMasterParam(Cm.mainVolume,r)}setMasterPan(r){this._setMasterParam(Cm.masterPan,r)}setPitchBendRange(r,l){this.controllerChange(r,B3.RPNMsb,0),this.controllerChange(r,B3.dataEntryMsb,l),this.controllerChange(r,B3.RPNMsb,127),this.controllerChange(r,B3.RPNLsb,127),this.controllerChange(r,B3.dataEntryMsb,0)}programChange(r,l,g=!1){this.post({channelNumber:r,messageType:c8.programChange,messageData:[l,g]})}velocityOverride(r,l){this.post({channelNumber:r,messageType:c8.ccChange,messageData:[ty.velocityOverride,l,!0]})}lockController(r,l,g){this.post({channelNumber:r,messageType:c8.lockController,messageData:[l,g]})}muteChannel(r,l){this.post({channelNumber:r,messageType:c8.muteChannel,messageData:l})}async reloadSoundFont(r){Ie("reloadSoundFont is deprecated. Please use the soundfontManager property instead."),await this.soundfontManager.reloadManager(r)}systemExclusive(r){this.post({channelNumber:Ci,messageType:c8.systemExclusive,messageData:Array.from(r)})}setDrums(r,l){this.post({channelNumber:r,messageType:c8.setDrums,messageData:l})}sendMessage(r){let l=VQ(r[0]);switch(l.status){case K3.noteOn:let g=r[2];g>0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case K3.noteOff:this.noteOff(l.channel,r[1]);break;case K3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case K3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case K3.programChange:this.programChange(l.channel,r[1]);break;case K3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case K3.channelPressure:this.channelPressure(l.channel,r[1]);break;case K3.systemExclusive:this.systemExclusive(new V3(r.slice(1)));break;case K3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,f)=>{let D;if(xA)D=127;else{let E0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let m0=f.clientX-E0.left,l0=E0.width;D=Math.floor((l0-m0)/l0*127)}else{let m0=f.clientY-E0.top,l0=E0.height;D=Math.floor(m0/l0*127)}}this.synth.noteOn(this.channel,g,D,this.enableDebugging)},l=g=>{let f=g.touches?Array.from(g.touches):[g],D=new Set;f.forEach(o0=>{let E0=document.elementFromPoint(o0.clientX,o0.clientY),m0=parseInt(E0.id.replace("note",""));D.add(m0),!(isNaN(m0)||m0<0||this.pressedKeys.has(m0))&&(this.pressedKeys.add(m0),r(m0,o0))}),this.pressedKeys.forEach(o0=>{D.has(o0)||o(o0)})};xA||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var ry=20,pm=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,B3.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,B3.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let f=0;f<128;f++)this.releaseNote(f,g.channel)})}get shown(){return this._shown}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(D=l(r-1)),r<127&&(o0=l(r+1)),o0&&D?g.classList.add("between_sharps"):D?g.classList.add("left_sharp"):o0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let f=900/(r.max-r.min+5),D=document.styleSheets[0].cssRules,o0;for(let E0 of D)if(E0.selectorText==="#keyboard .key"){o0=E0;break}if(o0.style.setProperty("--pressed-transform-skew",`${8e-4/(f/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let E0=getComputedStyle(this.keyboard),m0=parseFloat(E0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),l0=this.keyboard.getBoundingClientRect().height,u1=f/m0,F=l0*u1-l0,q0=(this._keyRange.min+this._keyRange.max)/2,R0=(r.min+r.max)/2;this._keyRange=r;let L1=this.keys.find(Y2=>Y2.classList.contains("sharp_key")).getBoundingClientRect().width,t2=(q0-R0)*L1,y1=parseFloat(E0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${F}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${u1}) translateX(${t2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${y1/u1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${f}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${f}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let f=this.keys[r-this._keyRange.min];if(f===void 0)return;f.classList.add("pressed");let D=f.classList.contains("sharp_key"),o0=g/127,E0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),m0;if(!D&&this.mode==="light"?m0=`rgba(${E0.slice(0,3).map(u1=>255-(255-u1)*o0).join(", ")}, ${E0[3]})`:m0=`rgba(${E0.slice(0,3).map(u1=>u1*o0).join(", ")}, ${E0[3]})`,f.style.background=m0,this.mode==="dark"){let l0=ry*o0;f.style.boxShadow=`${m0} 0px 0px ${l0}px ${l0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let f=this.keyColors[r-this._keyRange.min];if(!f)return;let D=f.findLastIndex(o0=>o0===this.channelColors[l]);D!==-1&&(f.splice(D,1),g.style.background=f[f.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${ry}px ${f[f.length-1]}`),f.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};pm.prototype._handlePointers=iy;function C$(o,r){let l=o.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var Ub="#000";function ny(o,r,l){o.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let f=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*f,l){r.fillRect(g.xPos,g.yPos-g.height*f,g.width,g.height*(f*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*f,g.yPos,g.width*(f*2+1),g.height),r.globalAlpha=1}),o.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=Ub,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var FB=!1;function sy(o=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(FB){o&&requestAnimationFrame(this.render.bind(this));return}else FB=!0;else FB=!1;if(o&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let D=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||ny(D,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let f=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${CC}px system-ui`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,CC*2+5),this.drawingContext.fillText(this.version,this.canvas.width,5),this.drawingContext.fillText(Math.round(f).toString()+" FPS",this.canvas.width,CC+5),this.onRender&&this.onRender(),o&&requestAnimationFrame(this.render.bind(this))}function oy(o=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,f=r/(g+1),D=f-p$*2,o0=this.noteFallingTimeMs/1e3,E0=this.noteAfterTriggerTimeMs/1e3,m0=this.seq.currentHighResolutionTime,l0=m0-E0,u1=o0+E0,F=l0+u1,q0=ay/u1,R0=[];this.synth.channelProperties.forEach(t2=>{if(this.showVisualPitch){let y1=t2.pitchBend-8192+this.visualPitchBendOffset;R0.push(t2.pitchBendRangeSemitones*(y1/8192*f))}else R0.push(0)});let L1=[];return this.noteTimes.forEach((t2,y1)=>{if(t2.renderStartIndex>=t2.notes.length||!this.renderChannels[y1])return;let Y2=t2.renderStartIndex,T2=t2.notes,V2=T2[Y2],i3=-1;for(;V2.start<=F&&(Y2++,!(this.notesOnScreen>$y));){let r3=V2.start+V2.length;if(r3>l0&&V2.length>0){let A0=V2.length/u1*l-p$*2;if(this.notesOnScreen<1e3||A0>q0){i3===-1&&(i3=Y2-1);let y5=(V2.start-l0)/u1*l,T3;if(this._notesFall?T3=l-A0-y5+p$:T3=y5+p$,V2.midiNotethis.keyRange.max){if(Y2>=T2.length)break;V2=T2[Y2];continue}let $3=V2.midiNote-this.keyRange.min,w6=f*$3+p$,s6,o9,J4,r4;if(this.sideways?(s6=T3,o9=w6,r4=D,J4=A0):(o9=T3,s6=w6,J4=D,r4=A0),this.notesOnScreen++,o)this.drawingContext.fillStyle=this.plainColors[y1],this.drawingContext.fillRect(s6+B$+p$,o9+B$,J4-B$*2,r4-B$*2);else{let V6;if(V2.start>m0||r3=T2.length)break;V2=T2[Y2]}i3>-1&&(t2.renderStartIndex=i3)}),L1.sort((t2,y1)=>y1.height-t2.height),L1}function ly(){let o=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let f=g%4,D=Math.floor(g/4),o0=!1;for(let F=g;F0){o0=!0;break}if(!o0){let F=this.canvas.width/4,q0=this.canvas.height/4,R0=F*f,L1=q0*D+q0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(R0,L1),this.drawingContext.lineTo(R0+F,L1),this.drawingContext.stroke();return}let E0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(E0);let m0=o*f,l0=r*D+r/2,u1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let F=E0.length/4,q0=o/F,R0=Math.floor(F/2),L1=E0.length-R0;for(let T2=L1;T2>=1;T2--)if(E0[T2-1]<0&&E0[T2]>=0){L1=T2;break}let t2=m0,y1=L1-R0,Y2=L1+R0;for(let T2=y1;T2{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function hy(){for(let o=0;o4096?this.delayNode.delayTime.value=f/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function uy(o){o.connectIndividualOutputs(this.channelAnalysers),o.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{this.updateFftSize()})}function fy(){for(let o of this.channelAnalysers)o.disconnect();W5("%cAnalysers disconnected!",D1.recognized)}function dy(o){this.seq=o,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),f=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${f}), rgba(0, 0, 0, ${f})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function Iy(){this.noteTimes&&this.noteTimes.forEach(o=>o.renderStartIndex=0)}function MB(o,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=o[o.currentIndex++]<>>0}function Qm(o,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=o&255,o>>=8;return l}var $h=.02;function Ey(o){function r(l0){return l0.messageData=new V3(l0.messageData.buffer),l0.messageData.currentIndex=0,6e7/MB(l0.messageData,3)}let l=[],f=o.tracks.flat();f.sort((l0,u1)=>l0.ticks-u1.ticks);for(let l0=0;l0<16;l0++)l.push({renderStartIndex:0,notes:[]});let D=0,o0=60/(120*o.timeDivision),E0=0,m0=0;for(;E0>4,F=l0.messageStatusByte&15;if(u1===8){let q0=l[F].notes.findLast(R0=>R0.midiNote===l0.messageData[0]&&R0.length===-1);if(q0){let R0=D-q0.start;q0.length=R0<$h&&F===Di?$h:R0}m0--}else if(u1===9)if(l0.messageData[1]===0){let q0=l[F].notes.findLast(R0=>R0.midiNote===l0.messageData[0]&&R0.length===-1);if(q0){let R0=D-q0.start;q0.length=R0<$h&&F===Di?$h:R0}m0--}else l[l0.messageStatusByte&15].notes.push({midiNote:l0.messageData[0],start:D,length:-1,velocity:l0.messageData[1]/127}),m0++;else l0.messageStatusByte===81&&(o0=60/(r(l0)*o.timeDivision));if(++E0>=f.length)break;D+=o0*(f[E0].ticks-l0.ticks)}m0>0&&l.forEach((l0,u1)=>l0.notes.filter(F=>F.length===-1).forEach(F=>{let q0=D-F.start;F.length=q0<$h&&u1===Di?$h:q0})),this.noteTimes=l,W5("%cFinished loading note times and ready to render the sequence!",D1.info)}var Pb=1024,Ob=4096,qb=2,Hb=2,BC=.6,pC=.5,B$=1,p$=1,CC=12,Ay=.6,ay=2,$y=81572,_i=class{onRender;constructor(r,l,g,f,D=""){this.noteFallingTimeMs=1e3,this.noteAfterTriggerTimeMs=0,this._keyRange={min:0,max:127},this.version="v"+D,this.visualPitchBendOffset=0,this.lineThickness=Hb,this._normalAnalyserFft=Pb,this._drumAnalyserFft=Ob,this.waveMultiplier=qb,this._notesFall=!0,this.sideways=!1,this._renderBool=!0,this.renderAnalysers=!0,this.renderNotes=!0,this.drawActiveNotes=!0,this.showVisualPitch=!0,this._stabilizeWaveforms=!0,this.renderChannels=Array(16).fill(!0),this.canvas=g,this.drawingContext=this.canvas.getContext("2d"),this.plainColors=r,this.computeColors(),this.synth=l,this.delayNode=f,this.notesOnScreen=0,this.channelAnalysers=[],this.createChannelAnalysers(l),this.connectChannelAnalysers(l)}get stabilizeWaveforms(){return this._stabilizeWaveforms}set stabilizeWaveforms(r){this._stabilizeWaveforms=r,this.updateFftSize()}get direction(){return this._notesFall?"down":"up"}set direction(r){this._notesFall=r==="down"}get normalAnalyserFft(){return this._normalAnalyserFft}set normalAnalyserFft(r){this._normalAnalyserFft=r,this.updateFftSize()}get drumAnalyserFft(){return this._drumAnalyserFft}set drumAnalyserFft(r){this._drumAnalyserFft=r,this.updateFftSize()}get renderBool(){return this._renderBool}set renderBool(r){this._renderBool=r,r===!0?this.connectChannelAnalysers(this.synth):this.disconnectChannelAnalysers()}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}computeColors(){this.channelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,C$(r,g=>g*pC)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,C$(r,g=>g*pC*BC)),l.addColorStop(1,C$(r,g=>g*BC)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,C$(r,g=>g*pC)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,C$(r,g=>g*pC*BC)),l.addColorStop(1,C$(r,g=>g*BC)),l})}};_i.prototype.render=sy;_i.prototype.computeNotePositions=oy;_i.prototype.createChannelAnalysers=gy;_i.prototype.updateFftSize=hy;_i.prototype.connectChannelAnalysers=uy;_i.prototype.disconnectChannelAnalysers=fy;_i.prototype.connectSequencer=dy;_i.prototype.calculateNoteTimes=Ey;_i.prototype.resetIndexes=Iy;_i.prototype.renderWaveforms=ly;function o3(o,r){let l=0;for(let g=0;g>>0}function $7(o,r,l){for(let g=0;g>g*8&255}function Q9(o,r){o[o.currentIndex++]=r&255,o[o.currentIndex++]=r>>8}function l7(o,r){$7(o,r,4)}function RA(o,r){let l=r<<8|o;return l>32767?l-65536:l}function my(o){return o>127?o-256:o}function Ee(o,r,l=void 0,g=!0){if(l){let f=o.slice(o.currentIndex,o.currentIndex+r);return o.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(f.buffer)}else{let f=!1,D="";for(let o0=0;o0127){if(g){f=!0;continue}else if(E0===0){f=!0;continue}}D+=String.fromCharCode(E0)}}return D}}function LA(o,r=0){let l=o.length;r>0&&(l=r);let g=new V3(l);return c7(g,o,r),g}function c7(o,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,Ee(l.chunkData,4)===r))}function QC(o){let r=[o&127];for(o>>=7;o>0;)r.unshift(o&127|128),o>>=7;return r}function yC(o){let r=[];for(let f of o.tracks){let D=[],o0=0,E0;for(let m0 of f){let l0=m0.ticks-o0,u1;m0.messageStatusByte<=K3.keySignature||m0.messageStatusByte===K3.sequenceSpecific?u1=[255,m0.messageStatusByte,...QC(m0.messageData.length),...m0.messageData]:m0.messageStatusByte===K3.systemExclusive?u1=[240,...QC(m0.messageData.length),...m0.messageData]:(u1=[],E0!==m0.messageStatusByte&&(E0=m0.messageStatusByte,u1.push(m0.messageStatusByte)),u1.push(...m0.messageData)),D.push(...QC(l0)),D.push(...u1),o0+=l0}r.push(new Uint8Array(D))}function l(f,D){for(let o0=0;o0{o.tracks.forEach((L1,t2)=>{if(o.midiPorts[t2]===R0)for(let y1=L1.length-1;y1>=0;y1--)L1[y1].messageStatusByte>=128&&L1[y1].messageStatusByte<240&&(L1[y1].messageStatusByte&15)===q0&&L1.splice(y1,1)})};g.forEach(q0=>{let R0=q0%16,L1=q0-R0,t2=o.midiPortChannelOffsets.findIndex(y1=>y1===L1);D(R0,t2),W5(`%cRemoving channel %c${q0}%c!`,D1.info,D1.recognized,D1.info)});let o0=!1,E0="gs",m0=[],l0=[];o.tracks.forEach((q0,R0)=>{q0.forEach(L1=>{let t2=L1.messageStatusByte&240;t2===K3.controllerChange?m0.push({track:R0,message:L1,channel:L1.messageStatusByte&15}):t2===K3.programChange?l0.push({track:R0,message:L1,channel:L1.messageStatusByte&15}):L1.messageStatusByte===K3.systemExclusive&&(L1.messageData[0]===67&&L1.messageData[2]===76&&L1.messageData[5]===126&&L1.messageData[6]===0?(W5("%cXG system on detected",D1.info),E0="xg",o0=!0):L1.messageData[0]===67&&L1.messageData[2]===76&&L1.messageData[3]===8&&L1.messageData[5]===3&&l0.push({track:R0,message:L1,channel:L1.messageData[4]}))})});let u1=(q0,R0,L1)=>o.tracks.reduce((t2,y1,Y2)=>{if(o.usedChannelsOnTrack[Y2].has(q0)&&o.midiPorts[Y2]===R0){let T2;L1?T2=y1.findIndex(V2=>(V2.messageStatusByte&240)===K3.noteOn):T2=y1.findIndex(V2=>V2.messageStatusByte>128&&V2.messageStatusByte<240&&(V2.messageStatusByte&15)===q0&&!(V2.messageStatusByte&K3.controllerChange===240&&(V2.messageData[0]===B3.resetAllControllers||V2.messageData[0]===B3.allNotesOff||V2.messageData[0]===B3.allSoundOff))),T2!==-1&&t2.push({index:T2,track:Y2})}return t2},[]),F=(q0,R0,L1)=>{let t2=m0.filter(y1=>y1.channel===q0&&y1.message.messageData[0]===L1&&o.midiPorts[y1.track]===R0);for(let y1=0;y1{let R0=q0.channel,L1=R0%16,t2=R0-L1,y1=o.midiPortChannelOffsets.findIndex(A0=>A0===t2),Y2=q0.controllerValue,T2=q0.controllerNumber;F(L1,y1,T2),W5(`%cNo controller %c${T2}%c on channel %c${R0}%c found. Adding it!`,D1.info,D1.unrecognized,D1.info,D1.value,D1.info);let V2=u1(L1,y1,!0);if(V2.length===0){Ie("Program change but no notes... ignoring!");return}let i3=V2.reduce((A0,y5)=>o.tracks[y5.track][y5.index].ticks{let R0=q0.channel%16,L1=q0.channel-R0,t2=o.midiPortChannelOffsets.findIndex($3=>$3===L1),y1=q0.isDrum?0:q0.bank,Y2=q0.program,T2=l0.filter($3=>o.midiPorts[$3.track]===t2&&$3.channel===R0);if(F(R0,t2,B3.bankSelect),F(R0,t2,B3.lsbForControl0BankSelect),(q0.isDrum||y1>0)&&!o0&&(o.tracks.forEach($3=>{for(let w6=0;w6<$3.length;w6++){let s6=$3[w6];if(s6.messageStatusByte===K3.systemExclusive)if(s6.messageData[0]===65&&s6.messageData[2]===66&&s6.messageData[6]===127){o0=!0,W5("%cGS on detected!",D1.recognized);break}else s6.messageData[0]===126&&s6.messageData[2]===9&&(W5("%cGM/2 on detected, removing!",D1.info),$3.splice(w6,1),w6--)}}),!o0)){let $3=0;o.tracks[0][0].messageStatusByte===K3.trackName&&$3++,o.tracks[0].splice($3,0,TB(0)),W5("%cGS on not detected. Adding it.",D1.info),o0=!0}for(let $3 of T2)o.tracks[$3.track].splice(o.tracks[$3.track].indexOf($3.message),1);let V2=u1(R0,t2,L1>0);if(V2.length===0){Ie("Program change but no notes... ignoring!");return}let i3=V2.reduce(($3,w6)=>o.tracks[w6.track][w6.index].ticks{if(o.midiPorts[T2]!==L1||!o.usedChannelsOnTrack[T2].has(R0))return;let V2=K3.noteOn|R0,i3=K3.noteOff|R0,r3=K3.polyPressure|R0;Y2.forEach(A0=>{A0.messageStatusByte!==V2&&A0.messageStatusByte!==i3&&A0.messageStatusByte!==r3||(A0.messageData[0]=Math.max(0,Math.min(127,A0.messageData[0]+t2)))})}),y1!==0){let Y2=o.tracks.find((s6,o9)=>o.usedChannelsOnTrack[o9].has(q0.channel));if(Y2===void 0){Ie(`Channel ${q0.channel} unused but transpose requested???`);continue}let T2=K3.noteOn|q0.channel%16,V2=Y2.findIndex(s6=>s6.messageStatusByte===T2);if(V2===-1){Ie(`No notes on channel ${q0.channel} but transpose requested???`);continue}let i3=Y2[V2].ticks,r3=y1*64+64,A0=K3.controllerChange|q0.channel%16,y5=new mi(i3,A0,new V3([B3.RPNMsb,0])),T3=new mi(i3,A0,new V3([B3.RPNLsb,1])),$3=new mi(i3,A0,new V3([B3.dataEntryMsb,r3])),w6=new mi(i3,A0,new V3([B3.lsbForControl6DataEntry,0]));Y2.splice(V2,0,w6),Y2.splice(V2,0,$3),Y2.splice(V2,0,T3),Y2.splice(V2,0,y5)}}i4()}function lh(o,r){let l=[],g=[],f=[],D=[];r.channelSnapshots.forEach((o0,E0)=>{if(o0.isMuted){g.push(E0);return}let m0=o0.channelTransposeKeyShift+o0.customControllers[mC.channelTransposeFine]/100;m0!==0&&l.push({channel:E0,keyShift:m0}),o0.lockPreset&&f.push({channel:E0,program:o0.program,bank:o0.bank,isDrum:o0.drumChannel}),o0.lockedControllers.forEach((l0,u1)=>{if(!l0||u1>127||u1===B3.bankSelect)return;let F=o0.midiControllers[u1]>>7;D.push({channel:E0,controllerNumber:u1,controllerValue:F})})}),Jb(o,f,D,g,l)}var Lt={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"},FA="utf-8",Vb="Created using SpessaSynth";function By(o,r,l,g=0,f="Shift_JIS",D={},o0=!0){if(cr("%cWriting the RMIDI File...",D1.info),W5(`%cConfiguration: Bank offset: %c${g}%c, encoding: %c${f}`,D1.info,D1.value,D1.info,D1.value),W5("metadata",D),W5("Initial bank offset",r.bankOffset),o0){let Y2=function(){let r3=0,A0=1/0;return r.tracks.forEach((y5,T3)=>{t2[T3]>=y5.length||y5[t2[T3]].ticksA0>r3?A0:r3),i3=[];for(let r3=0;r30;){let r3=Y2(),A0=r.tracks[r3];if(t2[r3]>=A0.length){y1--;continue}let y5=A0[t2[r3]];t2[r3]++;let T3=r.midiPortChannelOffsets[T2[r3]];if(y5.messageStatusByte===K3.midiPort){T2[r3]=y5.messageData[0];continue}let $3=y5.messageStatusByte&240;if($3!==K3.controllerChange&&$3!==K3.programChange&&$3!==K3.systemExclusive)continue;if($3===K3.systemExclusive){if(y5.messageData[0]!==65||y5.messageData[2]!==66||y5.messageData[3]!==18||y5.messageData[4]!==64||!(y5.messageData[5]&16)||y5.messageData[6]!==21){y5.messageData[0]===67&&y5.messageData[2]===76&&y5.messageData[5]===126&&y5.messageData[6]===0?R0="xg":y5.messageData[0]===65&&y5.messageData[2]===66&&y5.messageData[6]===127?R0="gs":y5.messageData[0]===126&&y5.messageData[2]===9&&(R0="gm",L1.push({tNum:r3,e:y5}));continue}let o9=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][y5.messageData[5]&15]+T3;i3[o9].drums=!!(y5.messageData[7]>0&&y5.messageData[5]>>4);continue}let w6=(y5.messageStatusByte&15)+T3,s6=i3[w6];if($3===K3.programChange){s6.drums?l.presets.findIndex(r4=>r4.program===y5.messageData[0]&&r4.bank===128)===-1&&(y5.messageData[0]=l.presets.find(r4=>r4.bank===128)?.program||0):l.presets.findIndex(r4=>r4.program===y5.messageData[0]&&r4.bank!==128)===-1&&(y5.messageData[0]=l.presets.find(r4=>r4.bank!==128)?.program||0),s6.program=y5.messageData[0];let o9=Math.max(0,s6.lastBank?.messageData[1]-r.bankOffset),J4=s6.drums?128:o9;if(s6.lastBank===void 0)continue;if(R0==="xg"&&s6.drums&&(i3[w6].lastBank.messageData[1]=127),l.presets.findIndex(r4=>r4.bank===J4&&r4.program===y5.messageData[0])===-1){let r4=l.presets.find(V6=>V6.program===y5.messageData[0])?.bank+g||g;s6.lastBank.messageData[1]=r4,W5(`%cNo preset %c${J4}:${y5.messageData[0]}%c. Changing bank to ${r4}.`,D1.info,D1.recognized,D1.info)}else{let V6=(J4===128?R0==="xg"?127:0:o9)+g;s6.lastBank.messageData[1]=V6,W5(`%cPreset %c${J4}:${y5.messageData[0]}%c exists. Changing bank to ${V6}.`,D1.info,D1.recognized,D1.info)}continue}y5.messageData[0]===B3.bankSelect&&(s6.hasBankSelect=!0,R0==="xg"&&(s6.drums=y5.messageData[1]===120||y5.messageData[1]===126||y5.messageData[1]===127),s6.lastBank=y5)}if(i3.forEach((r3,A0)=>{if(r3.hasBankSelect===!0)return;let y5=A0%16,T3=K3.programChange|y5,$3=Math.floor(A0/16)*16,w6=r.midiPortChannelOffsets.indexOf($3),s6=r.tracks.find((V6,We)=>r.midiPorts[We]===w6&&r.usedChannelsOnTrack[We].has(y5));if(s6===void 0)return;let o9=s6.findIndex(V6=>V6.messageStatusByte===T3);if(o9===-1){let V6=s6.findIndex(Ji=>Ji.messageStatusByte>128&&Ji.messageStatusByte<240&&(Ji.messageStatusByte&15)===y5);if(V6===-1)return;let We=s6[V6].ticks,qr=l.getPreset(0,0).program;s6.splice(V6,0,new mi(We,K3.programChange|y5,new V3([qr]))),o9=V6}W5(`%cAdding bank select for %c${A0}`,D1.info,D1.recognized);let J4=s6[o9].ticks,r4=l.getPreset(0,r3.program)?.bank+g||g;s6.splice(o9,0,new mi(J4,K3.controllerChange|y5,new V3([B3.bankSelect,r4])))}),R0!=="gs"&&R0!=="xg"){for(let A0 of L1)r.tracks[A0.tNum].splice(r.tracks[A0.tNum].indexOf(A0.e),1);let r3=0;r.tracks[0][0].messageStatusByte===K3.trackName&&r3++,r.tracks[0].splice(r3,0,TB(0))}}let E0=new V3(yC(r).buffer),m0=[LA("INFO")],l0=new TextEncoder;if(m0.push(Ze(Lt.software,l0.encode("SpessaSynth"),!0)),D.name!==void 0?(m0.push(Ze(Lt.name,l0.encode(D.name),!0)),f=FA):m0.push(Ze(Lt.name,r.rawMidiName,!0)),D.creationDate!==void 0)f=FA,m0.push(Ze(Lt.creationDate,l0.encode(D.creationDate),!0));else{let R0=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});m0.push(Ze(Lt.creationDate,LA(R0),!0))}if(D.comment!==void 0&&(f=FA,m0.push(Ze(Lt.comment,l0.encode(D.comment)))),D.engineer!==void 0&&m0.push(Ze(Lt.engineer,l0.encode(D.engineer),!0)),D.album!==void 0&&(f=FA,m0.push(Ze(Lt.album,l0.encode(D.album),!0))),D.artist!==void 0&&(f=FA,m0.push(Ze(Lt.artist,l0.encode(D.artist),!0))),D.genre!==void 0&&(f=FA,m0.push(Ze(Lt.genre,l0.encode(D.genre),!0))),D.picture!==void 0&&m0.push(Ze(Lt.picture,new Uint8Array(D.picture))),D.copyright!==void 0)f=FA,m0.push(Ze(Lt.copyright,l0.encode(D.copyright),!0));else{let R0=r.copyright.length>0?r.copyright:Vb;m0.push(Ze(Lt.copyright,LA(R0)))}let u1=new V3(2);$7(u1,g,2),m0.push(Ze(Lt.bankOffset,u1)),D.midiEncoding!==void 0&&(m0.push(Ze(Lt.midiEncoding,l0.encode(D.midiEncoding))),f=FA),m0.push(Ze(Lt.encoding,LA(f)));let F=bn(m0),q0=bn([LA("RMID"),Ze("data",E0),Ze("LIST",F),o]);return W5("%cFinished!",D1.info),i4(),Ze("RIFF",q0)}function ym(o,r){let l=0;for(;o>0;){let g=r.tempoChanges.find(D=>D.ticks=128){this.MIDIout.send(g);return}break;case MA.songChange:let f=l[0];this.songIndex=l[1],this.midiData=f,this.hasDummyData=!1,this.absoluteStartTime=0,this.duration=this.midiData.duration,Object.entries(this.onSongChange).forEach(E0=>E0[1](f)),l[2]===!0&&this.unpause();break;case MA.textEvent:let D=l;this.onTextEvent&&this.onTextEvent(D[0],D[1]);break;case MA.timeChange:let o0=this.synth.currentTime-l;Object.entries(this.onTimeChange).forEach(E0=>E0[1](o0)),this.unpause(),this._recalculateStartTime(o0);break;case MA.pause:this.pausedTime=this.currentTime,this.isFinished=l,this.isFinished&&Object.entries(this.onSongEnded).forEach(E0=>E0[1]());break;case MA.midiError:if(this.onError)this.onError(l);else throw new Error(l);return;case MA.getMIDI:this._getMIDIResolve&&this._getMIDIResolve(l)}}_recalculateStartTime(r){this.absoluteStartTime=this.synth.currentTime-r/this._playbackRate,this.highResTimeOffset=(this.synth.currentTime-performance.now()/1e3)*this._playbackRate}async getMIDI(){return new Promise(r=>{this._getMIDIResolve=r,this._sendMessage(Ri.getMIDI,void 0)})}loadNewSongList(r,l=!0){this.pause(),this.midiData=py,this.hasDummyData=!0,this.duration=99999,this._sendMessage(Ri.loadNewSongList,[r,l]),this.songIndex=0,this.songsAmount=r.length,this.songsAmount>1&&(this.loop=!1),l===!1&&(this.pausedTime=this.currentTime)}connectMidiOutput(r){this.resetMIDIOut(),this.MIDIout=r,this._sendMessage(Ri.changeMIDIMessageSending,r!==void 0),this.currentTime-=.1}pause(){if(this.paused){Ie("Already paused");return}this.pausedTime=this.currentTime,this._sendMessage(Ri.pause)}unpause(){this.pausedTime=void 0,this.isFinished=!1}play(r=!1){this.isFinished&&(r=!0),this._recalculateStartTime(this.pausedTime||0),this.unpause(),this._sendMessage(Ri.play,r)}stop(){this._sendMessage(Ri.stop)}};var wm=["Shift_JIS","windows-1250","utf-8","utf-16","utf-16le","utf-16be","latin1","ISO-8859-1","ISO-8859-2","ISO-8859-3","ISO-8859-4","ISO-8859-5","ISO-8859-6","ISO-8859-7","ISO-8859-8","ISO-8859-9","ISO-8859-10","ISO-8859-11","ISO-8859-13","ISO-8859-14","ISO-8859-15","ISO-8859-16","windows-1251","windows-1252","windows-1253","windows-1254","windows-1255","windows-1256","windows-1257","windows-1258","EUC-JP","ISO-2022-JP","EUC-KR","Big5","GB18030"];function Qy(o){return` + Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l127||l<0)throw new Error(`Invalid controller number: ${l}`);g=Math.floor(g),l=Math.floor(l),this.post({channelNumber:r,messageType:c8.ccChange,messageData:[l,g,f]})}resetControllers(){this.post({channelNumber:Ci,messageType:c8.ccReset,messageData:void 0})}channelPressure(r,l){this.post({channelNumber:r,messageType:c8.channelPressure,messageData:l})}polyPressure(r,l,g){this.post({channelNumber:r,messageType:c8.polyPressure,messageData:[l,g]})}post(r){this.worklet.port.postMessage(r)}pitchWheel(r,l,g){this.post({channelNumber:r,messageType:c8.pitchWheel,messageData:[l,g]})}transpose(r){this.transposeChannel(Ci,r,!1)}transposeChannel(r,l,g=!1){this.post({channelNumber:r,messageType:c8.transpose,messageData:[l,g]})}setMainVolume(r){this._setMasterParam(Cm.mainVolume,r)}setMasterPan(r){this._setMasterParam(Cm.masterPan,r)}setPitchBendRange(r,l){this.controllerChange(r,B3.RPNMsb,0),this.controllerChange(r,B3.dataEntryMsb,l),this.controllerChange(r,B3.RPNMsb,127),this.controllerChange(r,B3.RPNLsb,127),this.controllerChange(r,B3.dataEntryMsb,0)}programChange(r,l,g=!1){this.post({channelNumber:r,messageType:c8.programChange,messageData:[l,g]})}velocityOverride(r,l){this.post({channelNumber:r,messageType:c8.ccChange,messageData:[ty.velocityOverride,l,!0]})}lockController(r,l,g){this.post({channelNumber:r,messageType:c8.lockController,messageData:[l,g]})}muteChannel(r,l){this.post({channelNumber:r,messageType:c8.muteChannel,messageData:l})}async reloadSoundFont(r){Ie("reloadSoundFont is deprecated. Please use the soundfontManager property instead."),await this.soundfontManager.reloadManager(r)}systemExclusive(r){this.post({channelNumber:Ci,messageType:c8.systemExclusive,messageData:Array.from(r)})}setDrums(r,l){this.post({channelNumber:r,messageType:c8.setDrums,messageData:l})}sendMessage(r){let l=VQ(r[0]);switch(l.status){case K3.noteOn:let g=r[2];g>0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case K3.noteOff:this.noteOff(l.channel,r[1]);break;case K3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case K3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case K3.programChange:this.programChange(l.channel,r[1]);break;case K3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case K3.channelPressure:this.channelPressure(l.channel,r[1]);break;case K3.systemExclusive:this.systemExclusive(new V3(r.slice(1)));break;case K3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,f)=>{let D;if(xA)D=127;else{let E0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let m0=f.clientX-E0.left,l0=E0.width;D=Math.floor((l0-m0)/l0*127)}else{let m0=f.clientY-E0.top,l0=E0.height;D=Math.floor(m0/l0*127)}}this.synth.noteOn(this.channel,g,D,this.enableDebugging)},l=g=>{let f=g.touches?Array.from(g.touches):[g],D=new Set;f.forEach(o0=>{let E0=document.elementFromPoint(o0.clientX,o0.clientY),m0=parseInt(E0.id.replace("note",""));D.add(m0),!(isNaN(m0)||m0<0||this.pressedKeys.has(m0))&&(this.pressedKeys.add(m0),r(m0,o0))}),this.pressedKeys.forEach(o0=>{D.has(o0)||o(o0)})};xA||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var ry=20,pm=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,B3.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,B3.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let f=0;f<128;f++)this.releaseNote(f,g.channel)})}get shown(){return this._shown}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(D=l(r-1)),r<127&&(o0=l(r+1)),o0&&D?g.classList.add("between_sharps"):D?g.classList.add("left_sharp"):o0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let f=900/(r.max-r.min+5),D=document.styleSheets[0].cssRules,o0;for(let E0 of D)if(E0.selectorText==="#keyboard .key"){o0=E0;break}if(o0.style.setProperty("--pressed-transform-skew",`${8e-4/(f/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let E0=getComputedStyle(this.keyboard),m0=parseFloat(E0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),l0=this.keyboard.getBoundingClientRect().height,u1=f/m0,F=l0*u1-l0,q0=(this._keyRange.min+this._keyRange.max)/2,R0=(r.min+r.max)/2;this._keyRange=r;let L1=this.keys.find(Y2=>Y2.classList.contains("sharp_key")).getBoundingClientRect().width,t2=(q0-R0)*L1,y1=parseFloat(E0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${F}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${u1}) translateX(${t2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${y1/u1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${f}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${f}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let f=this.keys[r-this._keyRange.min];if(f===void 0)return;f.classList.add("pressed");let D=f.classList.contains("sharp_key"),o0=g/127,E0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),m0;if(!D&&this.mode==="light"?m0=`rgba(${E0.slice(0,3).map(u1=>255-(255-u1)*o0).join(", ")}, ${E0[3]})`:m0=`rgba(${E0.slice(0,3).map(u1=>u1*o0).join(", ")}, ${E0[3]})`,f.style.background=m0,this.mode==="dark"){let l0=ry*o0;f.style.boxShadow=`${m0} 0px 0px ${l0}px ${l0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let f=this.keyColors[r-this._keyRange.min];if(!f)return;let D=f.findLastIndex(o0=>o0===this.channelColors[l]);D!==-1&&(f.splice(D,1),g.style.background=f[f.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${ry}px ${f[f.length-1]}`),f.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};pm.prototype._handlePointers=iy;function C$(o,r){let l=o.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var Ub="#000";function ny(o,r,l){o.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let f=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*f,l){r.fillRect(g.xPos,g.yPos-g.height*f,g.width,g.height*(f*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*f,g.yPos,g.width*(f*2+1),g.height),r.globalAlpha=1}),o.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=Ub,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var FB=!1;function sy(o=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(FB){o&&requestAnimationFrame(this.render.bind(this));return}else FB=!0;else FB=!1;if(o&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let D=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||ny(D,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let f=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${CC}px system-ui`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,CC*2+5),this.drawingContext.fillText(this.version,this.canvas.width,5),this.drawingContext.fillText(Math.round(f).toString()+" FPS",this.canvas.width,CC+5),this.onRender&&this.onRender(),o&&requestAnimationFrame(this.render.bind(this))}function oy(o=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,f=r/(g+1),D=f-p$*2,o0=this.noteFallingTimeMs/1e3,E0=this.noteAfterTriggerTimeMs/1e3,m0=this.seq.currentHighResolutionTime,l0=m0-E0,u1=o0+E0,F=l0+u1,q0=ay/u1,R0=[];this.synth.channelProperties.forEach(t2=>{if(this.showVisualPitch){let y1=t2.pitchBend-8192+this.visualPitchBendOffset;R0.push(t2.pitchBendRangeSemitones*(y1/8192*f))}else R0.push(0)});let L1=[];return this.noteTimes.forEach((t2,y1)=>{if(t2.renderStartIndex>=t2.notes.length||!this.renderChannels[y1])return;let Y2=t2.renderStartIndex,T2=t2.notes,V2=T2[Y2],i3=-1;for(;V2.start<=F&&(Y2++,!(this.notesOnScreen>$y));){let r3=V2.start+V2.length;if(r3>l0&&V2.length>0){let A0=V2.length/u1*l-p$*2;if(this.notesOnScreen<1e3||A0>q0){i3===-1&&(i3=Y2-1);let y5=(V2.start-l0)/u1*l,T3;if(this._notesFall?T3=l-A0-y5+p$:T3=y5+p$,V2.midiNotethis.keyRange.max){if(Y2>=T2.length)break;V2=T2[Y2];continue}let $3=V2.midiNote-this.keyRange.min,w6=f*$3+p$,s6,o9,J4,r4;if(this.sideways?(s6=T3,o9=w6,r4=D,J4=A0):(o9=T3,s6=w6,J4=D,r4=A0),this.notesOnScreen++,o)this.drawingContext.fillStyle=this.plainColors[y1],this.drawingContext.fillRect(s6+B$+p$,o9+B$,J4-B$*2,r4-B$*2);else{let V6;if(V2.start>m0||r3=T2.length)break;V2=T2[Y2]}i3>-1&&(t2.renderStartIndex=i3)}),L1.sort((t2,y1)=>y1.height-t2.height),L1}function ly(){let o=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let f=g%4,D=Math.floor(g/4),o0=!1;for(let F=g;F0){o0=!0;break}if(!o0){let F=this.canvas.width/4,q0=this.canvas.height/4,R0=F*f,L1=q0*D+q0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(R0,L1),this.drawingContext.lineTo(R0+F,L1),this.drawingContext.stroke();return}let E0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(E0);let m0=o*f,l0=r*D+r/2,u1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let F=E0.length/4,q0=o/F,R0=Math.floor(F/2),L1=E0.length-R0;for(let T2=L1;T2>=1;T2--)if(E0[T2-1]<0&&E0[T2]>=0){L1=T2;break}let t2=m0,y1=L1-R0,Y2=L1+R0;for(let T2=y1;T2{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function hy(){for(let o=0;o4096?this.delayNode.delayTime.value=f/this.synth.context.sampleRate/2:this.delayNode.delayTime.value=0)}}function uy(o){o.connectIndividualOutputs(this.channelAnalysers),o.eventHandler.addEvent("drumchange","renderer-drum-change",()=>{setTimeout(this.updateFftSize.bind(this),100)})}function fy(){for(let o of this.channelAnalysers)o.disconnect();W5("%cAnalysers disconnected!",D1.recognized)}function dy(o){this.seq=o,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),f=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${f}), rgba(0, 0, 0, ${f})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function Iy(){this.noteTimes&&this.noteTimes.forEach(o=>o.renderStartIndex=0)}function MB(o,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=o[o.currentIndex++]<>>0}function Qm(o,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=o&255,o>>=8;return l}var $h=.02;function Ey(o){function r(l0){return l0.messageData=new V3(l0.messageData.buffer),l0.messageData.currentIndex=0,6e7/MB(l0.messageData,3)}let l=[],f=o.tracks.flat();f.sort((l0,u1)=>l0.ticks-u1.ticks);for(let l0=0;l0<16;l0++)l.push({renderStartIndex:0,notes:[]});let D=0,o0=60/(120*o.timeDivision),E0=0,m0=0;for(;E0>4,F=l0.messageStatusByte&15;if(u1===8){let q0=l[F].notes.findLast(R0=>R0.midiNote===l0.messageData[0]&&R0.length===-1);if(q0){let R0=D-q0.start;q0.length=R0<$h&&F===Di?$h:R0}m0--}else if(u1===9)if(l0.messageData[1]===0){let q0=l[F].notes.findLast(R0=>R0.midiNote===l0.messageData[0]&&R0.length===-1);if(q0){let R0=D-q0.start;q0.length=R0<$h&&F===Di?$h:R0}m0--}else l[l0.messageStatusByte&15].notes.push({midiNote:l0.messageData[0],start:D,length:-1,velocity:l0.messageData[1]/127}),m0++;else l0.messageStatusByte===81&&(o0=60/(r(l0)*o.timeDivision));if(++E0>=f.length)break;D+=o0*(f[E0].ticks-l0.ticks)}m0>0&&l.forEach((l0,u1)=>l0.notes.filter(F=>F.length===-1).forEach(F=>{let q0=D-F.start;F.length=q0<$h&&u1===Di?$h:q0})),this.noteTimes=l,W5("%cFinished loading note times and ready to render the sequence!",D1.info)}var Pb=1024,Ob=4096,qb=2,Hb=2,BC=.6,pC=.5,B$=1,p$=1,CC=12,Ay=.6,ay=2,$y=81572,_i=class{onRender;constructor(r,l,g,f,D=""){this.noteFallingTimeMs=1e3,this.noteAfterTriggerTimeMs=0,this._keyRange={min:0,max:127},this.version="v"+D,this.visualPitchBendOffset=0,this.lineThickness=Hb,this._normalAnalyserFft=Pb,this._drumAnalyserFft=Ob,this.waveMultiplier=qb,this._notesFall=!0,this.sideways=!1,this._renderBool=!0,this.renderAnalysers=!0,this.renderNotes=!0,this.drawActiveNotes=!0,this.showVisualPitch=!0,this._stabilizeWaveforms=!0,this.renderChannels=Array(16).fill(!0),this.canvas=g,this.drawingContext=this.canvas.getContext("2d"),this.plainColors=r,this.computeColors(),this.synth=l,this.delayNode=f,this.notesOnScreen=0,this.channelAnalysers=[],this.createChannelAnalysers(l),this.connectChannelAnalysers(l)}get stabilizeWaveforms(){return this._stabilizeWaveforms}set stabilizeWaveforms(r){this._stabilizeWaveforms=r,this.updateFftSize()}get direction(){return this._notesFall?"down":"up"}set direction(r){this._notesFall=r==="down"}get normalAnalyserFft(){return this._normalAnalyserFft}set normalAnalyserFft(r){this._normalAnalyserFft=r,this.updateFftSize()}get drumAnalyserFft(){return this._drumAnalyserFft}set drumAnalyserFft(r){this._drumAnalyserFft=r,this.updateFftSize()}get renderBool(){return this._renderBool}set renderBool(r){this._renderBool=r,r===!0?this.connectChannelAnalysers(this.synth):this.disconnectChannelAnalysers()}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}computeColors(){this.channelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,C$(r,g=>g*pC)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,C$(r,g=>g*pC*BC)),l.addColorStop(1,C$(r,g=>g*BC)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,C$(r,g=>g*pC)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,C$(r,g=>g*pC*BC)),l.addColorStop(1,C$(r,g=>g*BC)),l})}};_i.prototype.render=sy;_i.prototype.computeNotePositions=oy;_i.prototype.createChannelAnalysers=gy;_i.prototype.updateFftSize=hy;_i.prototype.connectChannelAnalysers=uy;_i.prototype.disconnectChannelAnalysers=fy;_i.prototype.connectSequencer=dy;_i.prototype.calculateNoteTimes=Ey;_i.prototype.resetIndexes=Iy;_i.prototype.renderWaveforms=ly;function o3(o,r){let l=0;for(let g=0;g>>0}function $7(o,r,l){for(let g=0;g>g*8&255}function Q9(o,r){o[o.currentIndex++]=r&255,o[o.currentIndex++]=r>>8}function l7(o,r){$7(o,r,4)}function RA(o,r){let l=r<<8|o;return l>32767?l-65536:l}function my(o){return o>127?o-256:o}function Ee(o,r,l=void 0,g=!0){if(l){let f=o.slice(o.currentIndex,o.currentIndex+r);return o.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(f.buffer)}else{let f=!1,D="";for(let o0=0;o0127){if(g){f=!0;continue}else if(E0===0){f=!0;continue}}D+=String.fromCharCode(E0)}}return D}}function LA(o,r=0){let l=o.length;r>0&&(l=r);let g=new V3(l);return c7(g,o,r),g}function c7(o,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,Ee(l.chunkData,4)===r))}function QC(o){let r=[o&127];for(o>>=7;o>0;)r.unshift(o&127|128),o>>=7;return r}function yC(o){let r=[];for(let f of o.tracks){let D=[],o0=0,E0;for(let m0 of f){let l0=m0.ticks-o0,u1;m0.messageStatusByte<=K3.keySignature||m0.messageStatusByte===K3.sequenceSpecific?u1=[255,m0.messageStatusByte,...QC(m0.messageData.length),...m0.messageData]:m0.messageStatusByte===K3.systemExclusive?u1=[240,...QC(m0.messageData.length),...m0.messageData]:(u1=[],E0!==m0.messageStatusByte&&(E0=m0.messageStatusByte,u1.push(m0.messageStatusByte)),u1.push(...m0.messageData)),D.push(...QC(l0)),D.push(...u1),o0+=l0}r.push(new Uint8Array(D))}function l(f,D){for(let o0=0;o0{o.tracks.forEach((L1,t2)=>{if(o.midiPorts[t2]===R0)for(let y1=L1.length-1;y1>=0;y1--)L1[y1].messageStatusByte>=128&&L1[y1].messageStatusByte<240&&(L1[y1].messageStatusByte&15)===q0&&L1.splice(y1,1)})};g.forEach(q0=>{let R0=q0%16,L1=q0-R0,t2=o.midiPortChannelOffsets.findIndex(y1=>y1===L1);D(R0,t2),W5(`%cRemoving channel %c${q0}%c!`,D1.info,D1.recognized,D1.info)});let o0=!1,E0="gs",m0=[],l0=[];o.tracks.forEach((q0,R0)=>{q0.forEach(L1=>{let t2=L1.messageStatusByte&240;t2===K3.controllerChange?m0.push({track:R0,message:L1,channel:L1.messageStatusByte&15}):t2===K3.programChange?l0.push({track:R0,message:L1,channel:L1.messageStatusByte&15}):L1.messageStatusByte===K3.systemExclusive&&(L1.messageData[0]===67&&L1.messageData[2]===76&&L1.messageData[5]===126&&L1.messageData[6]===0?(W5("%cXG system on detected",D1.info),E0="xg",o0=!0):L1.messageData[0]===67&&L1.messageData[2]===76&&L1.messageData[3]===8&&L1.messageData[5]===3&&l0.push({track:R0,message:L1,channel:L1.messageData[4]}))})});let u1=(q0,R0,L1)=>o.tracks.reduce((t2,y1,Y2)=>{if(o.usedChannelsOnTrack[Y2].has(q0)&&o.midiPorts[Y2]===R0){let T2;L1?T2=y1.findIndex(V2=>(V2.messageStatusByte&240)===K3.noteOn):T2=y1.findIndex(V2=>V2.messageStatusByte>128&&V2.messageStatusByte<240&&(V2.messageStatusByte&15)===q0&&!(V2.messageStatusByte&K3.controllerChange===240&&(V2.messageData[0]===B3.resetAllControllers||V2.messageData[0]===B3.allNotesOff||V2.messageData[0]===B3.allSoundOff))),T2!==-1&&t2.push({index:T2,track:Y2})}return t2},[]),F=(q0,R0,L1)=>{let t2=m0.filter(y1=>y1.channel===q0&&y1.message.messageData[0]===L1&&o.midiPorts[y1.track]===R0);for(let y1=0;y1{let R0=q0.channel,L1=R0%16,t2=R0-L1,y1=o.midiPortChannelOffsets.findIndex(A0=>A0===t2),Y2=q0.controllerValue,T2=q0.controllerNumber;F(L1,y1,T2),W5(`%cNo controller %c${T2}%c on channel %c${R0}%c found. Adding it!`,D1.info,D1.unrecognized,D1.info,D1.value,D1.info);let V2=u1(L1,y1,!0);if(V2.length===0){Ie("Program change but no notes... ignoring!");return}let i3=V2.reduce((A0,y5)=>o.tracks[y5.track][y5.index].ticks{let R0=q0.channel%16,L1=q0.channel-R0,t2=o.midiPortChannelOffsets.findIndex($3=>$3===L1),y1=q0.isDrum?0:q0.bank,Y2=q0.program,T2=l0.filter($3=>o.midiPorts[$3.track]===t2&&$3.channel===R0);if(F(R0,t2,B3.bankSelect),F(R0,t2,B3.lsbForControl0BankSelect),(q0.isDrum||y1>0)&&!o0&&(o.tracks.forEach($3=>{for(let w6=0;w6<$3.length;w6++){let s6=$3[w6];if(s6.messageStatusByte===K3.systemExclusive)if(s6.messageData[0]===65&&s6.messageData[2]===66&&s6.messageData[6]===127){o0=!0,W5("%cGS on detected!",D1.recognized);break}else s6.messageData[0]===126&&s6.messageData[2]===9&&(W5("%cGM/2 on detected, removing!",D1.info),$3.splice(w6,1),w6--)}}),!o0)){let $3=0;o.tracks[0][0].messageStatusByte===K3.trackName&&$3++,o.tracks[0].splice($3,0,TB(0)),W5("%cGS on not detected. Adding it.",D1.info),o0=!0}for(let $3 of T2)o.tracks[$3.track].splice(o.tracks[$3.track].indexOf($3.message),1);let V2=u1(R0,t2,L1>0);if(V2.length===0){Ie("Program change but no notes... ignoring!");return}let i3=V2.reduce(($3,w6)=>o.tracks[w6.track][w6.index].ticks{if(o.midiPorts[T2]!==L1||!o.usedChannelsOnTrack[T2].has(R0))return;let V2=K3.noteOn|R0,i3=K3.noteOff|R0,r3=K3.polyPressure|R0;Y2.forEach(A0=>{A0.messageStatusByte!==V2&&A0.messageStatusByte!==i3&&A0.messageStatusByte!==r3||(A0.messageData[0]=Math.max(0,Math.min(127,A0.messageData[0]+t2)))})}),y1!==0){let Y2=o.tracks.find((s6,o9)=>o.usedChannelsOnTrack[o9].has(q0.channel));if(Y2===void 0){Ie(`Channel ${q0.channel} unused but transpose requested???`);continue}let T2=K3.noteOn|q0.channel%16,V2=Y2.findIndex(s6=>s6.messageStatusByte===T2);if(V2===-1){Ie(`No notes on channel ${q0.channel} but transpose requested???`);continue}let i3=Y2[V2].ticks,r3=y1*64+64,A0=K3.controllerChange|q0.channel%16,y5=new mi(i3,A0,new V3([B3.RPNMsb,0])),T3=new mi(i3,A0,new V3([B3.RPNLsb,1])),$3=new mi(i3,A0,new V3([B3.dataEntryMsb,r3])),w6=new mi(i3,A0,new V3([B3.lsbForControl6DataEntry,0]));Y2.splice(V2,0,w6),Y2.splice(V2,0,$3),Y2.splice(V2,0,T3),Y2.splice(V2,0,y5)}}i4()}function lh(o,r){let l=[],g=[],f=[],D=[];r.channelSnapshots.forEach((o0,E0)=>{if(o0.isMuted){g.push(E0);return}let m0=o0.channelTransposeKeyShift+o0.customControllers[mC.channelTransposeFine]/100;m0!==0&&l.push({channel:E0,keyShift:m0}),o0.lockPreset&&f.push({channel:E0,program:o0.program,bank:o0.bank,isDrum:o0.drumChannel}),o0.lockedControllers.forEach((l0,u1)=>{if(!l0||u1>127||u1===B3.bankSelect)return;let F=o0.midiControllers[u1]>>7;D.push({channel:E0,controllerNumber:u1,controllerValue:F})})}),Jb(o,f,D,g,l)}var Lt={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"},FA="utf-8",Vb="Created using SpessaSynth";function By(o,r,l,g=0,f="Shift_JIS",D={},o0=!0){if(cr("%cWriting the RMIDI File...",D1.info),W5(`%cConfiguration: Bank offset: %c${g}%c, encoding: %c${f}`,D1.info,D1.value,D1.info,D1.value),W5("metadata",D),W5("Initial bank offset",r.bankOffset),o0){let Y2=function(){let r3=0,A0=1/0;return r.tracks.forEach((y5,T3)=>{t2[T3]>=y5.length||y5[t2[T3]].ticksA0>r3?A0:r3),i3=[];for(let r3=0;r30;){let r3=Y2(),A0=r.tracks[r3];if(t2[r3]>=A0.length){y1--;continue}let y5=A0[t2[r3]];t2[r3]++;let T3=r.midiPortChannelOffsets[T2[r3]];if(y5.messageStatusByte===K3.midiPort){T2[r3]=y5.messageData[0];continue}let $3=y5.messageStatusByte&240;if($3!==K3.controllerChange&&$3!==K3.programChange&&$3!==K3.systemExclusive)continue;if($3===K3.systemExclusive){if(y5.messageData[0]!==65||y5.messageData[2]!==66||y5.messageData[3]!==18||y5.messageData[4]!==64||!(y5.messageData[5]&16)||y5.messageData[6]!==21){y5.messageData[0]===67&&y5.messageData[2]===76&&y5.messageData[5]===126&&y5.messageData[6]===0?R0="xg":y5.messageData[0]===65&&y5.messageData[2]===66&&y5.messageData[6]===127?R0="gs":y5.messageData[0]===126&&y5.messageData[2]===9&&(R0="gm",L1.push({tNum:r3,e:y5}));continue}let o9=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][y5.messageData[5]&15]+T3;i3[o9].drums=!!(y5.messageData[7]>0&&y5.messageData[5]>>4);continue}let w6=(y5.messageStatusByte&15)+T3,s6=i3[w6];if($3===K3.programChange){s6.drums?l.presets.findIndex(r4=>r4.program===y5.messageData[0]&&r4.bank===128)===-1&&(y5.messageData[0]=l.presets.find(r4=>r4.bank===128)?.program||0):l.presets.findIndex(r4=>r4.program===y5.messageData[0]&&r4.bank!==128)===-1&&(y5.messageData[0]=l.presets.find(r4=>r4.bank!==128)?.program||0),s6.program=y5.messageData[0];let o9=Math.max(0,s6.lastBank?.messageData[1]-r.bankOffset),J4=s6.drums?128:o9;if(s6.lastBank===void 0)continue;if(R0==="xg"&&s6.drums&&(i3[w6].lastBank.messageData[1]=127),l.presets.findIndex(r4=>r4.bank===J4&&r4.program===y5.messageData[0])===-1){let r4=l.presets.find(V6=>V6.program===y5.messageData[0])?.bank+g||g;s6.lastBank.messageData[1]=r4,W5(`%cNo preset %c${J4}:${y5.messageData[0]}%c. Changing bank to ${r4}.`,D1.info,D1.recognized,D1.info)}else{let V6=(J4===128?R0==="xg"?127:0:o9)+g;s6.lastBank.messageData[1]=V6,W5(`%cPreset %c${J4}:${y5.messageData[0]}%c exists. Changing bank to ${V6}.`,D1.info,D1.recognized,D1.info)}continue}y5.messageData[0]===B3.bankSelect&&(s6.hasBankSelect=!0,R0==="xg"&&(s6.drums=y5.messageData[1]===120||y5.messageData[1]===126||y5.messageData[1]===127),s6.lastBank=y5)}if(i3.forEach((r3,A0)=>{if(r3.hasBankSelect===!0)return;let y5=A0%16,T3=K3.programChange|y5,$3=Math.floor(A0/16)*16,w6=r.midiPortChannelOffsets.indexOf($3),s6=r.tracks.find((V6,We)=>r.midiPorts[We]===w6&&r.usedChannelsOnTrack[We].has(y5));if(s6===void 0)return;let o9=s6.findIndex(V6=>V6.messageStatusByte===T3);if(o9===-1){let V6=s6.findIndex(Ji=>Ji.messageStatusByte>128&&Ji.messageStatusByte<240&&(Ji.messageStatusByte&15)===y5);if(V6===-1)return;let We=s6[V6].ticks,qr=l.getPreset(0,0).program;s6.splice(V6,0,new mi(We,K3.programChange|y5,new V3([qr]))),o9=V6}W5(`%cAdding bank select for %c${A0}`,D1.info,D1.recognized);let J4=s6[o9].ticks,r4=l.getPreset(0,r3.program)?.bank+g||g;s6.splice(o9,0,new mi(J4,K3.controllerChange|y5,new V3([B3.bankSelect,r4])))}),R0!=="gs"&&R0!=="xg"){for(let A0 of L1)r.tracks[A0.tNum].splice(r.tracks[A0.tNum].indexOf(A0.e),1);let r3=0;r.tracks[0][0].messageStatusByte===K3.trackName&&r3++,r.tracks[0].splice(r3,0,TB(0))}}let E0=new V3(yC(r).buffer),m0=[LA("INFO")],l0=new TextEncoder;if(m0.push(Ze(Lt.software,l0.encode("SpessaSynth"),!0)),D.name!==void 0?(m0.push(Ze(Lt.name,l0.encode(D.name),!0)),f=FA):m0.push(Ze(Lt.name,r.rawMidiName,!0)),D.creationDate!==void 0)f=FA,m0.push(Ze(Lt.creationDate,l0.encode(D.creationDate),!0));else{let R0=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});m0.push(Ze(Lt.creationDate,LA(R0),!0))}if(D.comment!==void 0&&(f=FA,m0.push(Ze(Lt.comment,l0.encode(D.comment)))),D.engineer!==void 0&&m0.push(Ze(Lt.engineer,l0.encode(D.engineer),!0)),D.album!==void 0&&(f=FA,m0.push(Ze(Lt.album,l0.encode(D.album),!0))),D.artist!==void 0&&(f=FA,m0.push(Ze(Lt.artist,l0.encode(D.artist),!0))),D.genre!==void 0&&(f=FA,m0.push(Ze(Lt.genre,l0.encode(D.genre),!0))),D.picture!==void 0&&m0.push(Ze(Lt.picture,new Uint8Array(D.picture))),D.copyright!==void 0)f=FA,m0.push(Ze(Lt.copyright,l0.encode(D.copyright),!0));else{let R0=r.copyright.length>0?r.copyright:Vb;m0.push(Ze(Lt.copyright,LA(R0)))}let u1=new V3(2);$7(u1,g,2),m0.push(Ze(Lt.bankOffset,u1)),D.midiEncoding!==void 0&&(m0.push(Ze(Lt.midiEncoding,l0.encode(D.midiEncoding))),f=FA),m0.push(Ze(Lt.encoding,LA(f)));let F=bn(m0),q0=bn([LA("RMID"),Ze("data",E0),Ze("LIST",F),o]);return W5("%cFinished!",D1.info),i4(),Ze("RIFF",q0)}function ym(o,r){let l=0;for(;o>0;){let g=r.tempoChanges.find(D=>D.ticks=128){this.MIDIout.send(g);return}break;case MA.songChange:let f=l[0];this.songIndex=l[1],this.midiData=f,this.hasDummyData=!1,this.absoluteStartTime=0,this.duration=this.midiData.duration,Object.entries(this.onSongChange).forEach(E0=>E0[1](f)),l[2]===!0&&this.unpause();break;case MA.textEvent:let D=l;this.onTextEvent&&this.onTextEvent(D[0],D[1]);break;case MA.timeChange:let o0=this.synth.currentTime-l;Object.entries(this.onTimeChange).forEach(E0=>E0[1](o0)),this.unpause(),this._recalculateStartTime(o0);break;case MA.pause:this.pausedTime=this.currentTime,this.isFinished=l,this.isFinished&&Object.entries(this.onSongEnded).forEach(E0=>E0[1]());break;case MA.midiError:if(this.onError)this.onError(l);else throw new Error(l);return;case MA.getMIDI:this._getMIDIResolve&&this._getMIDIResolve(l)}}_recalculateStartTime(r){this.absoluteStartTime=this.synth.currentTime-r/this._playbackRate,this.highResTimeOffset=(this.synth.currentTime-performance.now()/1e3)*this._playbackRate}async getMIDI(){return new Promise(r=>{this._getMIDIResolve=r,this._sendMessage(Ri.getMIDI,void 0)})}loadNewSongList(r,l=!0){this.pause(),this.midiData=py,this.hasDummyData=!0,this.duration=99999,this._sendMessage(Ri.loadNewSongList,[r,l]),this.songIndex=0,this.songsAmount=r.length,this.songsAmount>1&&(this.loop=!1),l===!1&&(this.pausedTime=this.currentTime)}connectMidiOutput(r){this.resetMIDIOut(),this.MIDIout=r,this._sendMessage(Ri.changeMIDIMessageSending,r!==void 0),this.currentTime-=.1}pause(){if(this.paused){Ie("Already paused");return}this.pausedTime=this.currentTime,this._sendMessage(Ri.pause)}unpause(){this.pausedTime=void 0,this.isFinished=!1}play(r=!1){this.isFinished&&(r=!0),this._recalculateStartTime(this.pausedTime||0),this.unpause(),this._sendMessage(Ri.play,r)}stop(){this._sendMessage(Ri.stop)}};var wm=["Shift_JIS","windows-1250","utf-8","utf-16","utf-16le","utf-16be","latin1","ISO-8859-1","ISO-8859-2","ISO-8859-3","ISO-8859-4","ISO-8859-5","ISO-8859-6","ISO-8859-7","ISO-8859-8","ISO-8859-9","ISO-8859-10","ISO-8859-11","ISO-8859-13","ISO-8859-14","ISO-8859-15","ISO-8859-16","windows-1251","windows-1252","windows-1253","windows-1254","windows-1255","windows-1256","windows-1257","windows-1258","EUC-JP","ISO-2022-JP","EUC-KR","Big5","GB18030"];function Qy(o){return` `}function Q$(o){return`