From 0d769f6ea1eb3bf6d9cb8aee64122f363955cdee Mon Sep 17 00:00:00 2001 From: spessasus Date: Sun, 6 Oct 2024 12:25:24 +0200 Subject: [PATCH] add support for loop mode release and fix selector menu --- package.json | 2 +- .../synthetizer/worklet_processor.min.js | 14 ++++++------- .../worklet_utilities/wavetable_oscillator.js | 12 +++++++++++ .../worklet_utilities/worklet_voice.js | 14 +++---------- .../methods/synthui_selector.js | 20 +++++++++++-------- src/website/minified/demo_main.min.js | 2 +- src/website/minified/local_main.min.js | 2 +- 7 files changed, 37 insertions(+), 29 deletions(-) diff --git a/package.json b/package.json index c378a796..223310b2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "SpessaSynth", - "version": "3.20.40", + "version": "3.20.41", "type": "module", "scripts": { "start": "node src/website/server/server.js" diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index e4f0ca13..994308f8 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -1,4 +1,4 @@ -var Is=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>(typeof require<"u"?require:A)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H=class extends Uint8Array{constructor(A){super(A),this.currentIndex=0}currentIndex};function ke(t){let A=t.reduce((n,o)=>n+o.length,0),e=new H(A),s=0;for(let n of t)e.set(n,s),s+=n.length;return e}function ft(t){t=Math.floor(t);let A=Math.floor(t/60),e=Math.round(t-A*60);return{minutes:A,seconds:e,time:`${A.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}}function gs(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function lA(t){let A="";for(let e=0;e=128&&A<=224&&(s=e,n=A),{status:n,channel:s}}var p={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,effects1Depth:91,effects2Depth:92,effects3Depth:93,effects4Depth:94,effects5Depth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},Es={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},ae={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 Bs=!0,hs=!0,qe=!0,Qs=!0;function cs(t,A,e,s){Bs=t,hs=A,qe=e,Qs=s}function m(...t){Bs&&console.info(...t)}function L(...t){hs&&console.warn(...t)}function ls(...t){Qs&&console.table(...t)}function te(...t){qe&&console.group(...t)}function SA(...t){qe&&console.groupCollapsed(...t)}function X(){qe&&console.groupEnd()}var Ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};function k(t,A){let e=0;for(let s=0;s>>0}function ge(t,A,e){for(let s=0;s>s*8&255}function Y(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function cA(t,A){ge(t,A,4)}function zA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function us(t){return t>127?t-256:t}function V(t,A,e=void 0,s=!0){if(e){let n=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(n.buffer)}else{let n=!1,o="";for(let i=0;i127){if(s){n=!0;continue}else if(C===0){n=!0;continue}}o+=String.fromCharCode(C)}}return o}}function wA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let s=0;sA.length)for(let s=0;se.header!=="LIST"?!1:(e.chunkData.currentIndex=0,V(e.chunkData,4)===A))}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},N=[];N[g.startAddrsOffset]={min:0,max:32768,def:0};N[g.endAddrOffset]={min:-32768,max:32768,def:0};N[g.startloopAddrsOffset]={min:-32768,max:32768,def:0};N[g.endloopAddrsOffset]={min:-32768,max:32768,def:0};N[g.startAddrsCoarseOffset]={min:0,max:32768,def:0};N[g.modLfoToPitch]={min:-12e3,max:12e3,def:0};N[g.vibLfoToPitch]={min:-12e3,max:12e3,def:0};N[g.modEnvToPitch]={min:-12e3,max:12e3,def:0};N[g.initialFilterFc]={min:1500,max:13500,def:13500};N[g.initialFilterQ]={min:0,max:960,def:0};N[g.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};N[g.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};N[g.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};N[g.modLfoToVolume]={min:-960,max:960,def:0};N[g.chorusEffectsSend]={min:0,max:1e3,def:0};N[g.reverbEffectsSend]={min:0,max:1e3,def:0};N[g.pan]={min:-500,max:500,def:0};N[g.delayModLFO]={min:-12e3,max:5e3,def:-12e3};N[g.freqModLFO]={min:-16e3,max:4500,def:0};N[g.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};N[g.freqVibLFO]={min:-16e3,max:4500,def:0};N[g.delayModEnv]={min:-32768,max:5e3,def:-32768};N[g.attackModEnv]={min:-32768,max:8e3,def:-32768};N[g.holdModEnv]={min:-12e3,max:5e3,def:-12e3};N[g.decayModEnv]={min:-12e3,max:8e3,def:-12e3};N[g.sustainModEnv]={min:0,max:1e3,def:0};N[g.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};N[g.keyNumToModEnvHold]={min:-1200,max:1200,def:0};N[g.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};N[g.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};N[g.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};N[g.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};N[g.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};N[g.sustainVolEnv]={min:0,max:1440,def:0};N[g.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};N[g.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};N[g.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};N[g.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};N[g.keyNum]={min:-1,max:127,def:-1};N[g.velocity]={min:-1,max:127,def:-1};N[g.initialAttenuation]={min:-250,max:1440,def:0};N[g.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};N[g.coarseTune]={min:-120,max:120,def:0};N[g.fineTune]={min:-12700,max:12700,def:0};N[g.scaleTuning]={min:0,max:1200,def:100};N[g.exclusiveClass]={min:0,max:99999,def:0};N[g.overridingRootKey]={min:-1,max:127,def:-1};var U=class{constructor(A=g.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let s=N[A];this.generatorValue=Math.round(e),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}generatorType=g.INVALID;generatorValue=0};function ds(t,A,e){let s=N[t]||{min:0,max:32768,def:0},n=A.find(B=>B.generatorType===t),o=0;n&&(o=n.generatorValue);let i=e.find(B=>B.generatorType===t),C=s.def;i&&(C=i.generatorValue);let c=C+o;return t===g.initialAttenuation?c:Math.max(s.min,Math.min(s.max,c))}var mt=class extends U{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=zA(A[e+2],A[e+3]),A.currentIndex+=4}};function pt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new mt(t.chunkData));return A.length>1&&A.pop(),A}var P={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},QA={linear:0,concave:1,convex:2,switch:3},xo=[];for(let t=0;t<4;t++)xo.push([[],[]]);var $=class t{constructor(A){A.srcEnum?(this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform):(this.sourceEnum=k(A,2),this.modulatorDestination=k(A,2),this.transformAmount=zA(A[A.currentIndex++],A[A.currentIndex++]),this.secondarySourceEnum=k(A,2),this.transformType=k(A,2)),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}currentValue=0;static copy(A){return new t({srcEnum:A.sourceEnum,secSrcEnum:A.secondarySourceEnum,transform:A.transformType,amt:A.transformAmount,dest:A.modulatorDestination})}static isIdentical(A,e){return A.sourceEnum===e.sourceEnum&&A.modulatorDestination===e.modulatorDestination&&A.secondarySourceEnum===e.secondarySourceEnum&&A.transformType===e.transformType}sumTransform(A){return new t({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(n,o){return Object.keys(n).find(i=>n[i]===o)}let e=A(QA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(p,this.sourceIndex):e+=A(P,this.sourceIndex);let s=A(QA,this.secSrcCurveType);return s+=this.secSrcPolarity===0?" unipolar ":" bipolar ",s+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?s+=A(p,this.secSrcIndex):s+=A(P,this.secSrcIndex),`Modulator: +var Is=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>(typeof require<"u"?require:A)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H=class extends Uint8Array{constructor(A){super(A),this.currentIndex=0}currentIndex};function ke(t){let A=t.reduce((n,o)=>n+o.length,0),e=new H(A),s=0;for(let n of t)e.set(n,s),s+=n.length;return e}function ft(t){t=Math.floor(t);let A=Math.floor(t/60),e=Math.round(t-A*60);return{minutes:A,seconds:e,time:`${A.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}}function gs(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function lA(t){let A="";for(let e=0;e=128&&A<=224&&(s=e,n=A),{status:n,channel:s}}var p={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,effects1Depth:91,effects2Depth:92,effects3Depth:93,effects4Depth:94,effects5Depth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},Es={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},ae={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 Bs=!0,hs=!0,qe=!0,Qs=!0;function cs(t,A,e,s){Bs=t,hs=A,qe=e,Qs=s}function m(...t){Bs&&console.info(...t)}function L(...t){hs&&console.warn(...t)}function ls(...t){Qs&&console.table(...t)}function te(...t){qe&&console.group(...t)}function SA(...t){qe&&console.groupCollapsed(...t)}function X(){qe&&console.groupEnd()}var Ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};function k(t,A){let e=0;for(let s=0;s>>0}function ge(t,A,e){for(let s=0;s>s*8&255}function Y(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function cA(t,A){ge(t,A,4)}function zA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function us(t){return t>127?t-256:t}function V(t,A,e=void 0,s=!0){if(e){let n=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(n.buffer)}else{let n=!1,o="";for(let i=0;i127){if(s){n=!0;continue}else if(C===0){n=!0;continue}}o+=String.fromCharCode(C)}}return o}}function wA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let s=0;sA.length)for(let s=0;se.header!=="LIST"?!1:(e.chunkData.currentIndex=0,V(e.chunkData,4)===A))}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},b=[];b[g.startAddrsOffset]={min:0,max:32768,def:0};b[g.endAddrOffset]={min:-32768,max:32768,def:0};b[g.startloopAddrsOffset]={min:-32768,max:32768,def:0};b[g.endloopAddrsOffset]={min:-32768,max:32768,def:0};b[g.startAddrsCoarseOffset]={min:0,max:32768,def:0};b[g.modLfoToPitch]={min:-12e3,max:12e3,def:0};b[g.vibLfoToPitch]={min:-12e3,max:12e3,def:0};b[g.modEnvToPitch]={min:-12e3,max:12e3,def:0};b[g.initialFilterFc]={min:1500,max:13500,def:13500};b[g.initialFilterQ]={min:0,max:960,def:0};b[g.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};b[g.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};b[g.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};b[g.modLfoToVolume]={min:-960,max:960,def:0};b[g.chorusEffectsSend]={min:0,max:1e3,def:0};b[g.reverbEffectsSend]={min:0,max:1e3,def:0};b[g.pan]={min:-500,max:500,def:0};b[g.delayModLFO]={min:-12e3,max:5e3,def:-12e3};b[g.freqModLFO]={min:-16e3,max:4500,def:0};b[g.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};b[g.freqVibLFO]={min:-16e3,max:4500,def:0};b[g.delayModEnv]={min:-32768,max:5e3,def:-32768};b[g.attackModEnv]={min:-32768,max:8e3,def:-32768};b[g.holdModEnv]={min:-12e3,max:5e3,def:-12e3};b[g.decayModEnv]={min:-12e3,max:8e3,def:-12e3};b[g.sustainModEnv]={min:0,max:1e3,def:0};b[g.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};b[g.keyNumToModEnvHold]={min:-1200,max:1200,def:0};b[g.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};b[g.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};b[g.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};b[g.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};b[g.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};b[g.sustainVolEnv]={min:0,max:1440,def:0};b[g.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};b[g.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};b[g.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};b[g.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};b[g.keyNum]={min:-1,max:127,def:-1};b[g.velocity]={min:-1,max:127,def:-1};b[g.initialAttenuation]={min:-250,max:1440,def:0};b[g.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};b[g.coarseTune]={min:-120,max:120,def:0};b[g.fineTune]={min:-12700,max:12700,def:0};b[g.scaleTuning]={min:0,max:1200,def:100};b[g.exclusiveClass]={min:0,max:99999,def:0};b[g.overridingRootKey]={min:-1,max:127,def:-1};var U=class{constructor(A=g.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let s=b[A];this.generatorValue=Math.round(e),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}generatorType=g.INVALID;generatorValue=0};function ds(t,A,e){let s=b[t]||{min:0,max:32768,def:0},n=A.find(B=>B.generatorType===t),o=0;n&&(o=n.generatorValue);let i=e.find(B=>B.generatorType===t),C=s.def;i&&(C=i.generatorValue);let c=C+o;return t===g.initialAttenuation?c:Math.max(s.min,Math.min(s.max,c))}var mt=class extends U{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=zA(A[e+2],A[e+3]),A.currentIndex+=4}};function pt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new mt(t.chunkData));return A.length>1&&A.pop(),A}var P={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},QA={linear:0,concave:1,convex:2,switch:3},xo=[];for(let t=0;t<4;t++)xo.push([[],[]]);var $=class t{constructor(A){A.srcEnum?(this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform):(this.sourceEnum=k(A,2),this.modulatorDestination=k(A,2),this.transformAmount=zA(A[A.currentIndex++],A[A.currentIndex++]),this.secondarySourceEnum=k(A,2),this.transformType=k(A,2)),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}currentValue=0;static copy(A){return new t({srcEnum:A.sourceEnum,secSrcEnum:A.secondarySourceEnum,transform:A.transformType,amt:A.transformAmount,dest:A.modulatorDestination})}static isIdentical(A,e){return A.sourceEnum===e.sourceEnum&&A.modulatorDestination===e.modulatorDestination&&A.secondarySourceEnum===e.secondarySourceEnum&&A.transformType===e.transformType}sumTransform(A){return new t({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(n,o){return Object.keys(n).find(i=>n[i]===o)}let e=A(QA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(p,this.sourceIndex):e+=A(P,this.sourceIndex);let s=A(QA,this.secSrcCurveType);return s+=this.secSrcPolarity===0?" unipolar ":" bipolar ",s+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?s+=A(p,this.secSrcIndex):s+=A(P,this.secSrcIndex),`Modulator: Source: ${e} Secondary source: ${s} Destination: ${A(g,this.modulatorDestination)} @@ -6,13 +6,13 @@ var Is=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>( Transform type: ${this.transformType} -`}};function TA(t,A,e,s,n){return t<<10|A<<9|e<<8|s<<7|n}var St=960,yt=QA.concave,Pe=[new $({srcEnum:TA(yt,0,1,0,P.noteOnVelocity),dest:g.initialAttenuation,amt:St,secSrcEnum:0,transform:0}),new $({srcEnum:129,dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new $({srcEnum:TA(yt,0,1,1,p.mainVolume),dest:g.initialAttenuation,amt:St,secSrcEnum:0,transform:0}),new $({srcEnum:13,dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new $({srcEnum:526,dest:g.fineTune,amt:12700,secSrcEnum:16,transform:0}),new $({srcEnum:650,dest:g.pan,amt:1e3,secSrcEnum:0,transform:0}),new $({srcEnum:TA(yt,0,1,1,p.expressionController),dest:g.initialAttenuation,amt:St,secSrcEnum:0,transform:0}),new $({srcEnum:219,dest:g.reverbEffectsSend,amt:750,secSrcEnum:0,transform:0}),new $({srcEnum:221,dest:g.chorusEffectsSend,amt:750,secSrcEnum:0,transform:0}),new $({srcEnum:TA(QA.linear,0,0,0,P.polyPressure),dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new $({srcEnum:TA(QA.linear,0,0,1,p.effects2Depth),dest:g.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new $({srcEnum:TA(QA.linear,1,0,1,p.releaseTime),dest:g.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new $({srcEnum:TA(QA.linear,1,0,1,p.brightness),dest:g.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0}),new $({srcEnum:TA(QA.linear,1,0,1,p.timbreHarmonicContent),dest:g.initialFilterQ,amt:250,secSrcEnum:0,transform:0})];function Ke(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new $(t.chunkData));return A}function fs(t=!1){let A={midiControllers:new Int16Array(Dt),lockedControllers:Array(Dt).fill(!1),customControllers:new Float32Array(ms),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:uA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},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 EA=128,Dt=147,PA=new Int16Array(Dt).fill(0);PA[p.mainVolume]=12800;PA[p.expressionController]=16256;PA[p.pan]=8192;PA[p.releaseTime]=8192;PA[p.brightness]=8192;PA[p.timbreHarmonicContent]=8192;PA[EA+P.pitchWheel]=8192;PA[EA+P.pitchWheelRange]=256;var uA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},IA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},ms=Object.keys(IA).length,kt=new Float32Array(ms);kt[IA.modulationMultiplier]=1;var wt={velocityOverride:128};var ps="spessasynth-worklet-system",Ss=350,DA=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},FA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function jA(t,A){let e=0;for(let s=8*(A-1);s>=0;s-=8)e|=t[t.currentIndex++]<>>0}function ys(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=we(t.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=s,e.status){case F.noteOn:let n=t.messageData[1];if(n>0)this.synth.noteOn(e.channel,t.messageData[0],n),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:n});else{this.synth.noteOff(e.channel,t.messageData[0]);let 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,s);break;case F.setTempo:this.oneTickToSeconds=60/(Mo(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),L("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(FA.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:L(`%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 Ds(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===DA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Mo(t){return t.messageData.currentIndex=0,6e7/jA(t.messageData,3)}function ks(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let s=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(s.ticks-e.ticks),this.midiData.loop.end<=e.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function ws(){let t=0,A=1/0;return this.tracks.forEach((e,s)=>{this.eventIndex[s]>=e.length||e[this.eventIndex[s]].ticks>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 Ce(t,A){let e=0;for(;t>0;){let s=A.tempoChanges.find(o=>o.tickst.chunkData.currentIndex;)A.push(new $(t.chunkData));return A}function fs(t=!1){let A={midiControllers:new Int16Array(Dt),lockedControllers:Array(Dt).fill(!1),customControllers:new Float32Array(ms),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:uA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},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 EA=128,Dt=147,PA=new Int16Array(Dt).fill(0);PA[p.mainVolume]=12800;PA[p.expressionController]=16256;PA[p.pan]=8192;PA[p.releaseTime]=8192;PA[p.brightness]=8192;PA[p.timbreHarmonicContent]=8192;PA[EA+P.pitchWheel]=8192;PA[EA+P.pitchWheelRange]=256;var uA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},IA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},ms=Object.keys(IA).length,kt=new Float32Array(ms);kt[IA.modulationMultiplier]=1;var wt={velocityOverride:128};var ps="spessasynth-worklet-system",Ss=350,DA=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},FA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function jA(t,A){let e=0;for(let s=8*(A-1);s>=0;s-=8)e|=t[t.currentIndex++]<>>0}function ys(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=we(t.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=s,e.status){case F.noteOn:let n=t.messageData[1];if(n>0)this.synth.noteOn(e.channel,t.messageData[0],n),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:n});else{this.synth.noteOff(e.channel,t.messageData[0]);let 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,s);break;case F.setTempo:this.oneTickToSeconds=60/(Mo(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),L("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(FA.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:L(`%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 Ds(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===DA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Mo(t){return t.messageData.currentIndex=0,6e7/jA(t.messageData,3)}function ks(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let s=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(s.ticks-e.ticks),this.midiData.loop.end<=e.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function ws(){let t=0,A=1/0;return this.tracks.forEach((e,s)=>{this.eventIndex[s]>=e.length||e[this.eventIndex[s]].ticks>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 Ce(t,A){let e=0;for(;t>0;){let s=A.tempoChanges.find(o=>o.ticks0&&(K+=this.tracks[y-1][this.tracks[y-1].length-1].ticks);S.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=K),j=Es[I>>4],(I&240)===F.noteOn){b.add(nA);let oA=S.data[S.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,oA),this.keyRange.max=Math.max(this.keyRange.max,oA)}R=I;break}let J=new H(j),Z=S.data.slice(S.data.currentIndex,S.data.currentIndex+j);S.data.currentIndex+=j,J.set(Z,0);let CA=new ie(K,I,J);switch(w.push(CA),nA){case-2:switch(I){case F.setTempo:this.tempoChanges.push({ticks:K,tempo:6e7/jA(Z,3)});break;case F.marker:switch(V(J,J.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=K;break;case"loopend":h=K}J.currentIndex=0;break;case F.midiPort:let fA=J[0];this.midiPorts[y]=fA,this.midiPortChannelOffsets[fA]===void 0&&(this.midiPortChannelOffsets[fA]=l,l+=16);break;case F.copyright:o||(this.copyright+=V(J,J.length,void 0,!1)+` +`," "),i=!0),this.RMIDInfo.IALB&&!this.RMIDInfo.IPRD&&(this.RMIDInfo.IPRD=this.RMIDInfo.IALB),this.RMIDInfo.PRD&&!this.RMIDInfo.IALB&&(this.RMIDInfo.IALB=this.RMIDInfo.IPRD),this.bankOffset=1,this.RMIDInfo[We.bankOffset]&&(this.bankOffset=k(this.RMIDInfo[We.bankOffset],2))}}C&&(this.bankOffset=0)}else n=s;let B=this.readMIDIChunk(n);if(B.type!=="MThd")throw X(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${B.type}"`);if(B.size!==6)throw X(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${B.size}`);this.format=jA(B.data,2),this.tracksAmount=jA(B.data,2),this.timeDivision=jA(B.data,2),this.keyRange={min:127,max:0},this.lyrics=[],this.tempoChanges=[{ticks:0,tempo:120}];let d=null,h=null;this.lastVoiceEventTick=0,this.midiPorts=[];let l=0;this.midiPortChannelOffsets=[],this.usedChannelsOnTrack=[],this.tracks=[];for(let y=0;y0&&(K+=this.tracks[y-1][this.tracks[y-1].length-1].ticks);S.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=K),j=Es[I>>4],(I&240)===F.noteOn){N.add(nA);let oA=S.data[S.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,oA),this.keyRange.max=Math.max(this.keyRange.max,oA)}G=I;break}let J=new H(j),Z=S.data.slice(S.data.currentIndex,S.data.currentIndex+j);S.data.currentIndex+=j,J.set(Z,0);let CA=new ie(K,I,J);switch(w.push(CA),nA){case-2:switch(I){case F.setTempo:this.tempoChanges.push({ticks:K,tempo:6e7/jA(Z,3)});break;case F.marker:switch(V(J,J.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=K;break;case"loopend":h=K}J.currentIndex=0;break;case F.midiPort:let fA=J[0];this.midiPorts[y]=fA,this.midiPortChannelOffsets[fA]===void 0&&(this.midiPortChannelOffsets[fA]=l,l+=16);break;case F.copyright:o||(this.copyright+=V(J,J.length,void 0,!1)+` `);break;case F.lyric:this.lyrics.push(J)}break;case-3:if(J.slice(0,7).every((oA,fA)=>No[fA]===oA)){let oA=J.slice(7,Z.length-3),fA=V(oA,oA.length)+` -`;this.copyright+=fA,m(`%cDecoded Roland SC message! %c${fA}`,r.recognized,r.value)}break;default:if((I&240)===F.controllerChange)switch(J[0]){case 2:case 116:d=K;break;case 4:case 117:h===null?h=K:h=0;break;case 0:C&&J[1]!==0&&J[1]!==127&&(m("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(w),this.usedChannelsOnTrack.push(b),m(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,r.info,r.value,r.info,r.value)}m("%cAll tracks parsed correctly!",r.recognized),SA("%cCorrecting loops, ports and detecting notes...",r.info);let u=[];for(let y of this.tracks){let w=y.find(S=>(S.messageStatusByte&240)===F.noteOn);w&&u.push(w.ticks)}this.firstNoteOn=Math.min(...u),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&h===null?(d=this.firstNoteOn,h=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(h===null||h===0)&&(h=this.lastVoiceEventTick)),this.loop={start:d,end:h},m(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let 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?m("%cNo additional MIDI Ports detected.",r.info):m("%cMIDI Ports detected!",r.recognized),!i)if(this.tracks.length>1){if(this.tracks[0].find(y=>y.messageStatusByte>=F.noteOn&&y.messageStatusBytew.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(w=>w.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){m("%cNo name detected. Using the alt name!",r.info),this.midiName=gs(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let y=0;yl>h?l:h),s=[];for(let h=0;h{i[D]>=u.length||u[i[D]].ticks0;){let h=c(),l=t.tracks[h];if(i[h]>=l.length){C--;continue}let u=l[i[h]];if(i[h]++,u.messageStatusByte===F.midiPort){B[h]=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[h]]||0,w=s[y];switch(D){case F.programChange:w.program=u.messageData[0],n(w);break;case F.controllerChange:if(u.messageData[0]!==p.bankSelect||d==="gs"&&w.drums)continue;let S=u.messageData[1],b=Math.max(0,S-t.bankOffset);if(d==="xg"){let W=S===120||S===126||S===127;W!==w.drums?(w.drums=W,w.bank=w.drums?128:b,n(w)):w.bank=w.drums?128:b;continue}s[y].bank=b;break;case F.noteOn:if(u.messageData[1]===0)continue;n(w),o[w.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 R=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+t.midiPortChannelOffsets[B[h]],K=!!(u.messageData[7]>0&&u.messageData[5]>>4);w=s[R],w.drums=K,w.bank=K?128:0,n(w);break}}for(let h of Object.keys(o))o[h].size===0&&(m(`%cDetected change but no keys for %c${h}`,r.info,r.value),delete o[h]);return X(),o}function Rs(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(e,A)}),this.duration=this.midiData.duration,this.firstNoteTime=Ce(this.midiData.firstNoteOn,this.midiData),m(`%cTotal song time: ${ft(Math.ceil(this.duration)).time}`,r.recognized),this.post(FA.songChange,[new Ze(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(L(`%cVery short song: (${ft(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function xs(t){this.songs=t.reduce((A,e)=>{if(e.duration)return A.push(e),A;try{A.push(new ze(e.binary,e.altName||""))}catch(s){return this.post(FA.midiError,s.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function Ms(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Ns(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}var KA=new Int16Array(127);KA[p.mainVolume]=100;KA[p.expressionController]=127;KA[p.pan]=64;KA[p.releaseTime]=64;KA[p.brightness]=64;KA[p.effects1Depth]=0;function bs(t,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let e=this.synth.workletProcessorChannels.length,s=Array(e).fill(8192),n=[];for(let C=0;CC===p.dataDecrement||C===p.dataIncrement||C===p.dataEntryMsb||C===p.dataDecrement||C===p.lsbForControl6DataEntry||C===p.RPNLsb||C===p.RPNMsb||C===p.NRPNLsb||C===p.NRPNMsb||C===p.bankSelect||C===p.lsbForControl0BankSelect||C===p.resetAllControllers,i=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let B=we(c.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:s[d]=c.messageData[1]<<7|c.messageData[0];break;case F.programChange:let l=n[d];l.program=c.messageData[0],l.actualBank=l.bank;break;case F.controllerChange:let u=c.messageData[0];if(o(u)){let D=c.messageData[1];if(u===p.bankSelect){n[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(KA)),i[d][u]=c.messageData[1];break;default:this._processEvent(c,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let h=this.tracks[C][this.eventIndex[C]];if(h===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(h.ticks-c.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7,s[C]&127),i[C]!==void 0&&i[C].forEach((c,B)=>{c!==KA[B]&&!o(B)&&this.sendMIDICC(C,B,c)}),n[C].program>=0&&n[C].actualBank>=0){let c=n[C].actualBank;this.sendMIDICC(C,p.bankSelect,c),this.sendMIDIProgramChange(C,n[C].program)}}else for(let C=0;C>7,s[C]&127),i[C]!==void 0&&i[C].forEach((c,B)=>{c!==KA[B]&&!o(B)&&this.synth.controllerChange(C,B,c)}),n[C].program>=0&&n[C].actualBank>=0){let c=n[C].actualBank;this.synth.controllerChange(C,p.bankSelect,c),this.synth.programChange(C,n[C].program)}return!0}function Ls(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 Us(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(FA.timeChange,currentTime-Ce(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Ts(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function Hs(t,A){switch(t){default:break;case bA.loadNewSongList:this.loadNewSongList(A);break;case bA.pause:this.pause();break;case bA.play:this.play(A);break;case bA.stop:this.stop();break;case bA.setTime:this.currentTime=A;break;case bA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case bA.setPlaybackRate:this.playbackRate=A;break;case bA.setLoop:this.loop=A;break;case bA.changeSong:A?this.nextSong():this.previousSong();break;case bA.getMIDI:this.post(FA.getMIDI,this.midiData);break;case bA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Ys(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:pA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Js(t){this.post(FA.midiEvent,t)}function vs(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|t,A,e])}function qs(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|t,A])}function Ps(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|t,e,A])}function Ks(){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&&AVs?440*Math.pow(2,(t-6900)/1200):Rt[~~t-je]}var xt=-1660,bo=1600,Gt=new Float32Array((bo-xt)*100+1);for(let t=0;t.5?1:0,s?e*2-1:e;case QA.concave:return s?(e=e*2-1,e<0?1-Ee[~~(e*-gA)]-1:Ee[~~e*gA]):Ee[~~(e*gA)];case QA.convex:return s?(e=e*2-1,e<0?1-Be[~~(e*-gA)]-1:Be[~~(e*gA)]):Be[~~(e*gA)]}}var Mt=1,Nt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)s-=o;let C=~~s,c=C+1;for(;c>=e.loopEnd;)c-=o;let B=s-C,d=n[c],h=n[C];A[i]=h+(d-h)*B,s+=e.playbackStep*t.currentTuningCalculated}}else for(let o=0;o=e.end){t.finished=!0;return}let c=s-i,B=n[C],d=n[i];A[o]=d+(B-d)*c,s+=e.playbackStep*t.currentTuningCalculated}t.sample.cursor=s}function Zs(t,A){let e=t.sample,s=e.cursor,n=e.loopEnd-e.loopStart,o=e.sampleData;if(t.sample.isLooping)for(let i=0;i=e.loopEnd;)s-=n;let C=~~s+1;for(;C>=e.loopEnd;)C-=n;A[i]=o[C],s+=e.playbackStep*t.currentTuningCalculated}else for(let i=0;i=e.end){t.finished=!0;return}A[i]=o[C],s+=e.playbackStep*t.currentTuningCalculated}e.cursor=s}function Xs(t,A){let e=t.sample,s=e.cursor,n=e.sampleData;if(e.isLooping){let o=e.loopEnd-e.loopStart;for(let i=0;i=e.loopEnd;)s-=o;let C=~~s,c=C+1,B=c+1,d=B+1,h=s-C;c>=e.loopEnd&&(c-=o),B>=e.loopEnd&&(B-=o),d>=e.loopEnd&&(d-=o);let l=n[C],u=n[c],D=n[B],y=n[d],w=.5*(D-l),S=l-2.5*u+2*D-.5*y,b=.5*(y-l)+1.5*(u-D);A[i]=((b*h+S)*h+w)*h+u,s+=e.playbackStep*t.currentTuningCalculated}}else for(let o=0;o=e.end||c>=e.end||B>=e.end){t.finished=!0;return}let h=n[i],l=n[C],u=n[c],D=n[B],y=.5*(u-h),w=h-2.5*l+2*u-.5*D,S=.5*(D-h)+1.5*(l-u);A[o]=((S*d+w)*d+y)*d+l,s+=e.playbackStep*t.currentTuningCalculated}t.sample.cursor=s}function Ws(t,A,e,s,n,o,i,C,c){if(!isNaN(e[0])){if(i>0){let B=o[0],d=o[1];i=Math.min(i,1e3);let h=i/1300,l=t*h,u=A*h;for(let D=0;D0){let B=C[0],d=C[1];c=Math.min(c,1e3);let h=c/1300,l=t*h,u=A*h;for(let D=0;D0)for(let B=0;B0)for(let B=0;B13499&&A.filter.reasonanceCb===0)return;let n=A.filter;(n.cutoffCents!==s||n.reasonanceCb!==A.modulatedGenerators[g.initialFilterQ])&&(n.cutoffCents=s,n.reasonanceCb=A.modulatedGenerators[g.initialFilterQ],t.calculateCoefficients(A));for(let o=0;o=bt}currentSampleTime=0;sampleRate;currentAttenuationDb=JA;state=0;releaseStartDb=JA;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=VA(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static recalculate(A){let e=A.volumeEnvelope,s=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 n=Math.min(JA,e.sustainDbRelative);e.attackDuration=s(A.modulatedGenerators[g.attackVolEnv]);let o=A.modulatedGenerators[g.decayVolEnv],i=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvDecay],C=n/JA;e.decayDuration=s(o+i)*C,e.releaseDuration=s(A.modulatedGenerators[g.releaseVolEnv]),e.delayEnd=s(A.modulatedGenerators[g.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let c=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvHold];if(e.holdEnd=s(A.modulatedGenerators[g.holdVolEnv]+c)+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=s(o+i)*d,e.state){case 0:e.releaseStartDb=JA;break;case 1:let h=1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration;e.releaseStartDb=20*Math.log10(h)*-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=VA(e.releaseStartDb)}}static apply(A,e,s,n){let o=A.volumeEnvelope,i=s/10,C=n;if(A.isInRelease){let B=o.currentSampleTime-o.releaseStartTimeSamples;if(B>=o.releaseDuration){for(let h=0;h=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[c]*=VA(o.sustainDbRelative+i+o.attenuation),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++c>=e.length)return}}};var zs=Math.PI/2,js=.05;function $s(t,A,e,s,n,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[IA.channelTuning]+t.customControllers[IA.channelTransposeFine]+t.customControllers[IA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],c=A.modulatedGenerators[g.coarseTune]+t.customControllers[IA.channelTuningSemitones],B=this.tunings[t.preset.program]?.[i];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 Z=A.startTime+HA(A.modulatedGenerators[g.delayVibLFO]),CA=Fe(A.modulatedGenerators[g.freqVibLFO]),oA=$e(Z,CA,currentTime);C+=oA*(d*t.customControllers[IA.modulationMultiplier])}let h=A.modulatedGenerators[g.initialFilterFc],l=A.modulatedGenerators[g.modLfoToPitch],u=A.modulatedGenerators[g.modLfoToVolume],D=A.modulatedGenerators[g.modLfoToFilterFc],y=0;if(l+D+u!==0){let Z=A.startTime+HA(A.modulatedGenerators[g.delayModLFO]),CA=Fe(A.modulatedGenerators[g.freqModLFO]),oA=$e(Z,CA,currentTime);C+=oA*(l*t.customControllers[IA.modulationMultiplier]),y=-oA*u,h+=oA*D}if(t.channelVibrato.depth>0){let Z=$e(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);Z&&(C+=Z*t.channelVibrato.depth)}let w=A.modulatedGenerators[g.modEnvToPitch],S=A.modulatedGenerators[g.modEnvToFilterFc],b=YA.getValue(A,currentTime);h+=b*S,C+=b*w;let R=~~(C+c*100);R!==A.currentTuningCents&&(A.currentTuningCents=R,A.currentTuningCalculated=Math.pow(2,R/1200));let K=(Math.max(-500,Math.min(500,A.modulatedGenerators[g.pan]))+500)/1e3,W=new Float32Array(e.length);switch(this.interpolationType){case he.linear:default:Os(A,W);break;case he.nearestNeighbor:Zs(A,W);break;case he.fourthOrder:Xs(A,W)}Qe.apply(A,W,h),LA.apply(A,W,y,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(K-A.currentPan)*this.panSmoothingFactor;let I=Math.cos(zs*A.currentPan)*this.panLeft,nA=Math.sin(zs*A.currentPan)*this.panRight,j=this.oneOutputMode?0:A.modulatedGenerators[g.reverbEffectsSend],J=this.oneOutputMode?0:A.modulatedGenerators[g.chorusEffectsSend];Ws(I,nA,W,e,s,n,j,o,J)}function Uo(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 An(t){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=Uo(s,n);A.push({channel:s,voice:n,priority:o})}A.sort((s,n)=>s.priority-n.priority);let e=A.slice(0,t);for(let{channel:s,voice:n}of e){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function en(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimesn=t);var To=function(t){var A,e,s,n,o,i,C,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",B="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=c.indexOf(t.charAt(d++)),o=c.indexOf(t.charAt(d++)),i=c.indexOf(t.charAt(d++)),C=c.indexOf(t.charAt(d++)),A=n<<2|o>>4,e=(15&o)<<4|i>>2,s=(3&i)<<6|C,B+=String.fromCharCode(A),i!==64&&(B+=String.fromCharCode(e)),C!==64&&(B+=String.fromCharCode(s));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 Se))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]"}):CA?(typeof read<"u"&&(I.read=function(E){return read(E)}),I.readBinary=function(E){var Q;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(Q=read(E,"binary"))=="object"),Q)},typeof scriptArgs<"u"?I.arguments=scriptArgs:typeof arguments<"u"&&(I.arguments=arguments),typeof quit=="function"&&(I.quit=function(a){quit(a)})):(j||J)&&(j?document.currentScript&&(oA=document.currentScript.src):oA=self.location.href,oA=oA.indexOf("blob:")!==0?oA.split("/").slice(0,-1).join("/")+"/":"",I.read=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.send(null),Q.responseText},J&&(I.readBinary=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.responseType="arraybuffer",Q.send(null),new Uint8Array(Q.response)}),I.readAsync=function(E,Q,f){var G=new XMLHttpRequest;G.open("GET",E,!0),G.responseType="arraybuffer",G.onload=function(){if(G.status==200||G.status==0&&G.response){Q(G.response);return}f()},G.onerror=f,G.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 nA)nA.hasOwnProperty(t)&&(I[t]=nA[t]);function Ne(a){var E=u;return u=u+a+15&-16,E}function Pt(a){var E=c[R>>2],Q=E+a+15&-16;return c[R>>2]=Q,Q>=BA&&!$t()?(c[R>>2]=E,0):E}function Kt(a,E){return E||(E=16),a=Math.ceil(a/E)*E}function lo(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))}nA=void 0;var uo={"f64-rem":function(a,E){return a%E},debugger:function(){}},rt=[];function Po(a,E){for(var Q=0,f=Q;f>>0)+4294967296*+(E>>>0):+(a>>>0)+4294967296*+(0|E)}function at(a,E,Q){return Q&&Q.length?I["dynCall_"+a].apply(null,[E].concat(Q)):I["dynCall_"+a].call(null,E)}var be=0,Vt=0;function _A(a,E){a||ZA("Assertion failed: "+E)}function Ot(a){var E=I["_"+a];return _A(E,"Cannot call unknown function "+a+", make sure it is exported"),E}var Zt={stackSave:function(){ct()},stackRestore:function(){Qt()},arrayToC:function(a){var E,Q,f=Je(a.length);return E=a,Q=f,n.set(E,Q),f},stringToC:function(a){var E=0;if(a!=null&&a!==0){var Q=(a.length<<2)+1;E=Je(Q),_t(a,E,Q)}return E}},fo={string:Zt.stringToC,array:Zt.arrayToC};function Xt(a,E,Q,f,G){var q=Ot(a),_=[],M=0;if(f)for(var hA=0;hA>0]=E;break;case"i16":i[a>>1]=E;break;case"i32":c[a>>2]=E;break;case"i64":tempI64=[E>>>0,+ko(tempDouble=E)>=1?tempDouble>0?(0|Fo(+ns(tempDouble/4294967296),4294967295))>>>0:~~+wo((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],c[a>>2]=tempI64[0],c[a+4>>2]=tempI64[1];break;case"float":d[a>>2]=E;break;case"double":h[a>>3]=E;break;default:ZA("invalid type for setValue: "+Q)}}function Zo(a,E,Q){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return n[a>>0];case"i16":return i[a>>1];case"i32":case"i64":return c[a>>2];case"float":return d[a>>2];case"double":return h[a>>3];default:ZA("invalid type for getValue: "+E)}return null}function Xo(a,E,Q,f){typeof a=="number"?(q=!0,_=a):(q=!1,_=a.length);var G=typeof E=="string"?E:null;if(M=Q==4?f:[typeof Ye=="function"?Ye:Ne,Je,Ne,Pt][Q===void 0?2:Q](Math.max(_,G?1:E.length)),q){for(f=M,_A((3&M)==0),hA=M+(-4&_);f>2]=0;for(hA=M+_;f>0]=0;return M}if(G==="i8")return a.subarray||a.slice?o.set(a,M):o.set(new Uint8Array(a),M),M;for(var q,_,M,hA,rA,iA,tA,v=0;v<_;){var mA=a[v];if((rA=G||E[v])===0){v++;continue}rA=="i64"&&(rA="i32"),mo(M+v,mA,rA),tA!==rA&&(iA=lo(rA),tA=rA),v+=iA}return M}function Wo(a){return D?Bt?Ye(a):Pt(a):Ne(a)}function Le(a,E){if(E===0||!a)return"";for(var Q,f,G,q=0,_=0;q|=f=o[a+_>>0],(f!=0||E)&&(_++,!E||_!=E););E||(E=_);var M="";if(q<128){for(;E>0;)G=String.fromCharCode.apply(String,o.subarray(a,a+Math.min(E,1024))),M=M?M+G:G,a+=1024,E-=1024;return M}return Q=a,function(rA,iA){for(var tA=iA;rA[tA];)++tA;if(tA-iA>16&&rA.subarray&&Wt)return Wt.decode(rA.subarray(iA,tA));for(var v,mA,GA,xA,MA,ee,NA="";;){if(!(v=rA[iA++]))return NA;if(!(128&v)){NA+=String.fromCharCode(v);continue}if(mA=63&rA[iA++],(224&v)==192){NA+=String.fromCharCode((31&v)<<6|mA);continue}if(GA=63&rA[iA++],(240&v)==224?v=(15&v)<<12|mA<<6|GA:(xA=63&rA[iA++],(248&v)==240?v=(7&v)<<18|mA<<12|GA<<6|xA:(MA=63&rA[iA++],v=(252&v)==248?(3&v)<<24|mA<<18|GA<<12|xA<<6|MA:(1&v)<<30|mA<<24|GA<<18|xA<<12|MA<<6|(ee=63&rA[iA++]))),v<65536)NA+=String.fromCharCode(v);else{var ye=v-65536;NA+=String.fromCharCode(55296|ye>>10,56320|1023&ye)}}}(o,Q)}function _o(a){for(var E="";;){var Q=n[a++>>0];if(!Q)return E;E+=String.fromCharCode(Q)}}function zo(a,E){return function(f,G,q){for(var _=0;_>0]=f.charCodeAt(_);q||(n[G>>0]=0)}(a,E,!1)}var Wt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ue(a,E,Q,f){if(!(f>0))return 0;for(var G=Q,q=Q+f-1,_=0;_=55296&&M<=57343&&(M=65536+((1023&M)<<10)|1023&a.charCodeAt(++_)),M<=127){if(Q>=q)break;E[Q++]=M}else if(M<=2047){if(Q+1>=q)break;E[Q++]=192|M>>6,E[Q++]=128|63&M}else if(M<=65535){if(Q+2>=q)break;E[Q++]=224|M>>12,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}else if(M<=2097151){if(Q+3>=q)break;E[Q++]=240|M>>18,E[Q++]=128|M>>12&63,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}else if(M<=67108863){if(Q+4>=q)break;E[Q++]=248|M>>24,E[Q++]=128|M>>18&63,E[Q++]=128|M>>12&63,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}else{if(Q+5>=q)break;E[Q++]=252|M>>30,E[Q++]=128|M>>24&63,E[Q++]=128|M>>18&63,E[Q++]=128|M>>12&63,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}}return E[Q]=0,Q-G}function _t(a,E,Q){return Ue(a,o,E,Q)}function Te(a){for(var E=0,Q=0;Q=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&a.charCodeAt(++Q)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var zt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function jo(a){for(var E=a,Q=E>>1;i[Q];)++Q;if((E=Q<<1)-a>32&&zt)return zt.decode(o.subarray(a,E));for(var f=0,G="";;){var q=i[a+2*f>>1];if(q==0)return G;++f,G+=String.fromCharCode(q)}}function $o(a,E,Q){if(Q===void 0&&(Q=2147483647),Q<2)return 0;for(var f=E,G=(Q-=2)<2*a.length?Q/2:a.length,q=0;q>1]=_,E+=2}return i[E>>1]=0,E-f}function Ar(a){return 2*a.length}function er(a){for(var E=0,Q="";;){var f=c[a+4*E>>2];if(f==0)return Q;if(++E,f>=65536){var G=f-65536;Q+=String.fromCharCode(55296|G>>10,56320|1023&G)}else Q+=String.fromCharCode(f)}}function tr(a,E,Q){if(Q===void 0&&(Q=2147483647),Q<4)return 0;for(var f=E,G=f+Q-4,q=0;q=55296&&_<=57343&&(_=65536+((1023&_)<<10)|1023&a.charCodeAt(++q)),c[E>>2]=_,(E+=4)+4>G)break}return c[E>>2]=0,E-f}function sr(a){for(var E=0,Q=0;Q=55296&&f<=57343&&++Q,E+=4}return E}function nr(a){var E=Te(a)+1,Q=Ye(E);return Q&&Ue(a,n,Q,E),Q}function or(a){var E=Te(a)+1,Q=Je(E);return Ue(a,n,Q,E),Q}function rr(a){return a}function ir(){var a,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(G){f=G}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(Q){var f,G=f=Q;return Q===G?Q:Q+" ["+G+"]"})}function It(a,E){return a%E>0&&(a+=E-a%E),a}function jt(a){I.buffer=s=a}function gt(){I.HEAP8=n=new Int8Array(s),I.HEAP16=i=new Int16Array(s),I.HEAP32=c=new Int32Array(s),I.HEAPU8=o=new Uint8Array(s),I.HEAPU16=C=new Uint16Array(s),I.HEAPU32=B=new Uint32Array(s),I.HEAPF32=d=new Float32Array(s),I.HEAPF64=h=new Float64Array(s)}function $t(){var a=I.usingWasm?65536:16777216,E=2147483648-a;if(c[R>>2]>E)return!1;var Q=BA;for(BA=Math.max(BA,16777216);BA>2];)BA=BA<=536870912?It(2*BA,a):Math.min(It((3*BA+2147483648)/4,a),E);var f=I.reallocBuffer(BA);return f&&f.byteLength==BA?(jt(f),gt(),!0):(BA=Q,!1)}l=u=y=w=S=b=R=0,D=!1,I.reallocBuffer||(I.reallocBuffer=function(a){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(s,a);else{var E,Q=n;E=new ArrayBuffer(a),new Int8Array(E).set(Q)}}catch{return!1}return!!Ro(E)&&E});try{(K=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{K=function(E){return E.byteLength}}var Ct=I.TOTAL_STACK||5242880,BA=I.TOTAL_MEMORY||16777216;function po(){return BA}function me(a){for(;a.length>0;){var E=a.shift();if(typeof E=="function"){E();continue}var Q=E.func;typeof Q=="number"?E.arg===void 0?I.dynCall_v(Q):I.dynCall_vi(Q,E.arg):Q(E.arg===void 0?null:E.arg)}}BA=0?a:E<=32?2*Math.abs(1<=f&&(E<=32||a>f)&&(a=-2*f+a),a}var ko=Math.abs,wo=Math.ceil,ns=Math.floor,Fo=Math.min,Ae=0,ht=null,pe=null;function hr(a){return a}I.preloadedImages={},I.preloadedAudios={};var os="data:application/octet-stream;base64,";function He(a){return String.prototype.startsWith?a.startsWith(os):a.indexOf(os)===0}(function(){var E="main.wast",Q="main.wasm",f="main.temp.asm.js";He(E)||(E=fA(E)),He(Q)||(Q=fA(Q)),He(f)||(f=fA(f));var G={global:null,env:null,asm2wasm:uo,parent:I},q=null;function _(tA){return tA}function M(){try{if(I.wasmBinary)return new Uint8Array(I.wasmBinary);if(I.readBinary)return I.readBinary(Q);throw"both async and sync fetching of the wasm failed"}catch(tA){ZA(tA)}}I.asmPreload=I.asm;var hA=I.reallocBuffer,rA=function(tA){tA=It(tA,I.usingWasm?65536:16777216);var v=I.buffer.byteLength;if(I.usingWasm)try{var mA=I.wasmMemory.grow((tA-v)/65536);return mA!==-1?I.buffer=I.wasmMemory.buffer:null}catch{return null}};I.reallocBuffer=function(tA){return iA==="asmjs"?hA(tA):rA(tA)};var iA="";I.asm=function(tA,v,mA){var GA;if(!(v=GA=v).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?v.table=new WebAssembly.Table({initial:MA,maximum:ee,element:"anyfunc"}):v.table=new WebAssembly.Table({initial:MA,element:"anyfunc"}):v.table=Array(MA),I.wasmTable=v.table}return v.memoryBase||(v.memoryBase=I.STATIC_BASE),v.tableBase||(v.tableBase=0),xA=function(ye,oe,ut){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((q=vA.exports).memory){var De,dt,as;De=q.memory,dt=I.buffer,De.byteLength0?Q:Te(a)+1,G=Array(f),q=Ue(a,G,0,G.length);return E&&(G.length=q),G}function ur(a){for(var E=[],Q=0;Q255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}u+=16,R=Ne(4),S=(y=w=Kt(u))+Ct,b=Kt(S),c[R>>2]=b,D=!0,I.wasmTableSize=4,I.wasmMaxTableSize=4,I.asmGlobalArg={},I.asmLibraryArg={abort:ZA,assert:_A,enlargeMemory:$t,getTotalMemory:po,abortOnCannotGrowMemory:function(){ZA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+BA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(E,Q,f){var G=ct();try{return I.dynCall_iii(E,Q,f)}catch(q){if(Qt(G),typeof q!="number"&&q!=="longjmp")throw q;I.setThrew(1,0)}},___assert_fail:function(E,Q,f,G){ZA("Assertion failed: "+Le(E)+", at: "+[Q?Le(Q):"unknown filename",f,G?Le(G):"unknown function"])},___setErrNo:function(E){return I.___errno_location&&(c[I.___errno_location()>>2]=E),E},_abort:function(){I.abort()},_emscripten_memcpy_big:function(E,Q,f){return o.set(o.subarray(Q,Q+f),E),E},_llvm_floor_f64:ns,DYNAMICTOP_PTR:R,tempDoublePtr:kA,ABORT:be,STACKTOP:w,STACK_MAX:S};var rs=I.asm(I.asmGlobalArg,I.asmLibraryArg,s);I.asm=rs,I.___errno_location=function(){return I.asm.___errno_location.apply(null,arguments)};var Ro=I._emscripten_replace_memory=function(){return I.asm._emscripten_replace_memory.apply(null,arguments)};I._free=function(){return I.asm._free.apply(null,arguments)};var Ye=I._malloc=function(){return I.asm._malloc.apply(null,arguments)};I._memcpy=function(){return I.asm._memcpy.apply(null,arguments)},I._memset=function(){return I.asm._memset.apply(null,arguments)},I._sbrk=function(){return I.asm._sbrk.apply(null,arguments)},I._stb_vorbis_js_channels=function(){return I.asm._stb_vorbis_js_channels.apply(null,arguments)},I._stb_vorbis_js_close=function(){return I.asm._stb_vorbis_js_close.apply(null,arguments)},I._stb_vorbis_js_decode=function(){return I.asm._stb_vorbis_js_decode.apply(null,arguments)},I._stb_vorbis_js_open=function(){return I.asm._stb_vorbis_js_open.apply(null,arguments)},I._stb_vorbis_js_sample_rate=function(){return I.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},I.establishStackSpace=function(){return I.asm.establishStackSpace.apply(null,arguments)},I.getTempRet0=function(){return I.asm.getTempRet0.apply(null,arguments)},I.runPostSets=function(){return I.asm.runPostSets.apply(null,arguments)},I.setTempRet0=function(){return I.asm.setTempRet0.apply(null,arguments)},I.setThrew=function(){return I.asm.setThrew.apply(null,arguments)};var Je=I.stackAlloc=function(){return I.asm.stackAlloc.apply(null,arguments)},Qt=I.stackRestore=function(){return I.asm.stackRestore.apply(null,arguments)},ct=I.stackSave=function(){return I.asm.stackSave.apply(null,arguments)};function Se(a){this.name="ExitStatus",this.message="Program terminated with exit("+a+")",this.status=a}function lt(a){a=a||I.arguments,!(Ae>0)&&(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)yo(I.preRun.shift());me(As)}(),!(Ae>0)&&(I.calledRun||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),E()},1)):E())));function E(){!I.calledRun&&(I.calledRun=!0,be||(Bt||(Bt=!0,me(Et)),me(es),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)Do(I.postRun.shift());me(ss)}()))}}function dr(a,E){(!E||!I.noExitRuntime||a!==0)&&(I.noExitRuntime||(be=!0,Vt=a,w=W,me(ts),So=!0,I.onExit&&I.onExit(a)),I.quit(a,new Se(a)))}function ZA(a){throw I.onAbort&&I.onAbort(a),a!==void 0?(Me(a),RA(a),a=JSON.stringify(a)):a="",be=!0,Vt=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=rs,I.ccall=Xt,I.cwrap=function(E,Q,f,G){var q=(f=f||[]).every(function(_){return _==="number"});return Q!=="string"&&q&&!G?Ot(E):function(){return Xt(E,Q,f,arguments,G)}},Se.prototype=Error(),Se.prototype.constructor=Se,pe=function a(){I.calledRun||lt(),I.calledRun||(pe=a)},I.run=lt,I.abort=ZA,I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();I.noExitRuntime=!0,lt(),I.onRuntimeInitialized=()=>{tn=!0,sn()},OA.decode=function(a){return function(Q){if(!tn)throw Error("Not initialized");var f={};function G(oe){return new Int32Array(I.HEAPU8.buffer,oe,1)[0]}function q(oe,ut){var ve=new ArrayBuffer(ut*Float32Array.BYTES_PER_ELEMENT),re=new Float32Array(ve);return re.set(new Float32Array(I.HEAPU8.buffer,oe,ut)),re}f.open=I.cwrap("stb_vorbis_js_open","number",[]),f.close=I.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=I.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=I.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=I.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var _,M,hA,rA,iA=f.open(),tA=(_=Q,M=Q.byteLength,hA=I._malloc(M),(rA=new Uint8Array(I.HEAPU8.buffer,hA,M)).set(new Uint8Array(_,0,M)),rA),v=I._malloc(4),mA=I._malloc(4),GA=f.decode(iA,tA.byteOffset,tA.byteLength,v,mA);if(I._free(tA.byteOffset),GA<0)throw f.close(iA),I._free(v),Error("stbvorbis decode failed: "+GA);for(var xA=f.channels(iA),MA=Array(xA),ee=new Int32Array(I.HEAPU32.buffer,G(v),xA),NA=0;NA=0&&(s=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:s.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+P.pitchWheelRange]>>7)+(A.midiControllers[EA+P.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[EA+P.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:pA.channelProperties,messageData:t})}function Ho(t,A,e){let s=t,n=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function an(t,A=0){let e=t[0];if(!(this.deviceID!==UA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:L(`%cUnrecognized SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let n;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),m(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),m(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let c=(t[5]<<7|t[6])-8192;n=Math.floor(c/81.92),this.setMasterTuning(n),m(`%cMaster Fine Tuning. Cents: %c${n}`,r.info,r.value);break;case 4:n=(t[5]-64)*100,this.setMasterTuning(n),m(`%cMaster Coarse Tuning. Cents: %c${n}`,r.info,r.value);break;default:L(`%cUnrecognized MIDI Device Control Real-time message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(m("%cGM system on",r.info),this.system="gm"):t[3]===3?(m("%cGM2 system on",r.info),this.system="gm2"):(m("%cGM system off, defaulting to GS",r.info),this.system="gs");break;case 8:switch(t[3]){case 2:case 7:let o=4;t[3]===7&&o++;let i=t[o++],C=t[o++];for(let B=0;B>1&1)===1&&this.setOctaveTuning(15+A,c);for(let B=0;B<7;B++)(t[5]>>B&1)===1&&this.setOctaveTuning(7+B+A,c);for(let B=0;B<7;B++)(t[6]>>B&1)===1&&this.setOctaveTuning(B+A,c);m(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${c.join(" ")}`,r.info,r.value);break;default:L(`%cUnrecognized MIDI Tuning standard message: %c${lA(t)}`,r.warn,r.unrecognized);break}break;default:L(`%cUnrecognized MIDI Realtime/non realtime message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 65:let s=function(){L(`%cUnrecognized Roland %cGS %cSysEx: %c${lA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let n=t[7];if(t[6]===127){n===0?(m("%cGS Reset received!",r.info),this.resetAllControllers(!1),this.system="gs"):n===127&&(m("%cGS system off, switching to GM2",r.info),this.resetAllControllers(!1),this.system="gm2");return}else if(t[4]===64){if((t[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A;switch(t[6]){default:s();break;case 21:let i=n>0&&t[5]>>4;this.setDrums(o,i),m(`%cChannel %c${o}%c ${i?"is now a drum channel":"now isn't a drum channel"}%c via: %c${lA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=n-64;this.transposeChannel(o,C),m(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${lA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let c=n;c===0&&(c=Math.floor(Math.random()*128)),this.controllerChange(o,p.pan,c);break;case 33:this.controllerChange(o,p.effects3Depth,n);break;case 34:this.controllerChange(o,p.effects1Depth,n);break;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let 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(n,p.bankSelect,o);break;case 2:this.controllerChange(n,p.lsbForControl0BankSelect,o);break;case 3:this.programChange(n,o);break;case 8:let i=this.workletProcessorChannels[n];if(i.drumChannel)return;let C=o-64;i.channelTransposeKeyShift=C;break;case 11:this.controllerChange(n,p.mainVolume,o);break;case 14:let c=o;c===0&&(c=Math.floor(Math.random()*127)),this.controllerChange(n,p.pan,c);break;case 19:this.controllerChange(n,p.effects1Depth,o);break;case 18:this.controllerChange(n,p.effects3Depth,o);break;default:L(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&L(`%cUnrecognized Yamaha XG SysEx: %c${lA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&L(`%cUnrecognized Yamaha SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break}}function In(t,A,e){if(A.transformAmount===0)return A.currentValue=0,0;let s;if(A.sourceUsesCC)s=t[A.sourceIndex];else{let c=A.sourceIndex+EA;switch(A.sourceIndex){case P.noController:s=16383;break;case P.noteOnKeyNum:s=e.midiNote<<7;break;case P.noteOnVelocity:s=e.velocity<<7;break;case P.polyPressure:s=e.pressure<<7;break;default:s=t[c];break}}let n=dA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let c=A.secSrcIndex+EA;switch(A.secSrcIndex){case P.noController:o=16383;break;case P.noteOnKeyNum:o=e.midiNote<<7;break;case P.noteOnVelocity:o=e.velocity<<7;break;case P.polyPressure:o=e.pressure<<7;break;default:o=t[c]}}let i=dA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=n*i*A.transformAmount;return A.transformType===2&&(C=Math.abs(C)),A.currentValue=C,C}function XA(t,A,e=-1,s=0){let n=t.modulators,o=t.generators,i=t.modulatedGenerators;if(YA.recalculate(t),e===-1){i.set(o),n.forEach(B=>{let d=N[B.modulatorDestination],h=i[B.modulatorDestination]+In(A,B,t);i[B.modulatorDestination]=Math.max(d.min,Math.min(h,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]),c=new Set;n.forEach(B=>{if(B.sourceUsesCC===e&&B.sourceIndex===s||B.secSrcUsesCC===e&&B.secSrcIndex===s){let d=B.modulatorDestination;c.has(d)||(i[d]=o[d],In(A,B,t),n.forEach(h=>{if(h.modulatorDestination===d){let l=N[B.modulatorDestination],u=i[B.modulatorDestination]+h.currentValue;i[B.modulatorDestination]=Math.max(l.min,Math.min(u,l.max))}}),c.add(d))}}),[...c].some(B=>C.has(B))&&LA.recalculate(t)}var dA=[];for(let t=0;t<4;t++){dA[t]=[[new Float32Array(gA),new Float32Array(gA)],[new Float32Array(gA),new Float32Array(gA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||i.isMuted)return;let C=A+i.channelTransposeKeyShift;if(A>127||A<0)return;let c=i.preset.program;this.tunings[c]?.[A]?.midiNote>=0&&(C=this.tunings[c]?.[A].midiNote),i.velocityOverride>0&&(e=i.velocityOverride);let B=this.getWorkletVoices(t,C,e,i,o,s),d=i.voices;B.forEach(h=>{let l=h.generators[g.exclusiveClass];l!==0&&d.forEach(R=>{R.generators[g.exclusiveClass]===l&&(this.releaseVoice(R),R.modulatedGenerators[g.releaseVolEnv]=-7e3,R.modulatedGenerators[g.releaseModEnv]=-7e3,LA.recalculate(R),YA.recalculate(R))}),XA(h,i.midiControllers);let u=h.modulatedGenerators[g.startAddrsOffset]+h.modulatedGenerators[g.startAddrsCoarseOffset]*32768,D=h.modulatedGenerators[g.endAddrOffset]+h.modulatedGenerators[g.endAddrsCoarseOffset]*32768,y=h.modulatedGenerators[g.startloopAddrsOffset]+h.modulatedGenerators[g.startloopAddrsCoarseOffset]*32768,w=h.modulatedGenerators[g.endloopAddrsOffset]+h.modulatedGenerators[g.endloopAddrsCoarseOffset]*32768,S=h.sample,b=R=>Math.max(0,Math.min(S.sampleData.length-1,R));if(S.cursor=b(S.cursor+u),S.end=b(S.end+D),S.loopStart=b(S.loopStart+y),S.loopEnd=b(S.loopEnd+w),S.loopEndthis.voiceCap&&this.voiceKilling(B.length),d.push(...B),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Cn(t,A){if(A>127||A<0){L("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift,s=this.workletProcessorChannels[t].preset.program;if(this.tunings[s]?.[A]?.midiNote>=0&&(e=this.tunings[s]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(o=>{o.midiNote!==e||o.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function En(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.midiNote===A&&(e.modulatedGenerators[g.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function Bn(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[t].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function hn(t=!1){m("%cStop all received!",r.info);for(let A=0;AXA(n,this.workletProcessorChannels[t].midiControllers,0,P.pitchWheel)),this.sendChannelProperties()}function pn(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[EA+P.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(s=>XA(s,e.midiControllers,0,P.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function Sn(t,A,e){this.workletProcessorChannels[t].voices.forEach(s=>{s.midiNote===A&&(s.pressure=e,XA(s,this.workletProcessorChannels[t].midiControllers,0,P.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function yn(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function Dn(t,A,e,s=!1){let n=this.workletProcessorChannels[t];if(n===void 0){L(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>127){if(!s)return;switch(A){default:return;case wt.velocityOverride:n.velocityOverride=e}}if(A>=p.lsbForControl1ModulationWheel&&A<=p.lsbForControl13EffectControl2&&A!==p.lsbForControl6DataEntry){let o=A-32;if(n.lockedControllers[o])return;n.midiControllers[o]=n.midiControllers[o]&16256|e&127,n.voices.forEach(i=>XA(i,n.midiControllers,1,o))}switch(A){case p.allNotesOff:this.stopAll(t);break;case p.allSoundOff:this.stopAll(t,!0);break;case p.bankSelect:let o=e;if(!s){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==DA&&this.setDrums(t,!1);break;case"gm2":o===120&&(n.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}n.drumChannel&&(o=128),o===128&&!n.drumChannel&&(o=n.midiControllers[p.bankSelect])}n.midiControllers[p.bankSelect]=o;break;case p.lsbForControl0BankSelect:this.system==="xg"?n.drumChannel||e!==127&&(n.midiControllers[p.bankSelect]=e):this.system==="gm2"&&(n.midiControllers[p.bankSelect]=e);break;case p.RPNLsb:n.RPValue=n.RPValue<<7|e,n.dataEntryState=uA.RPFine;break;case p.RPNMsb:n.RPValue=e,n.dataEntryState=uA.RPCoarse;break;case p.NRPNMsb:n.NRPCoarse=e,n.dataEntryState=uA.NRPCoarse;break;case p.NRPNLsb:n.NRPFine=e,n.dataEntryState=uA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(t,e);break;case p.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case p.resetAllControllers:this.resetControllers(t);break;case p.sustainPedal:e>=64?n.holdPedal=!0:(n.holdPedal=!1,n.sustainedVoices.forEach(i=>{this.releaseVoice(i)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=e<<7,n.voices.forEach(i=>XA(i,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function kn(t){this.midiVolume=t,this.setMasterPan(this.pan)}function wn(t){this.masterGain=t*Ut,this.setMasterPan(this.pan)}function Fn(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function Rn(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function Gn(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 xn(t,A,e,s){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=s,this.workletProcessorChannels[t].channelVibrato.depth=A)}function Mn(t,A){let e=this.workletProcessorChannels[t],s=()=>{e.channelVibrato.delay===0&&e.channelVibrato.rate===0&&e.channelVibrato.depth===0&&(e.channelVibrato.depth=50,e.channelVibrato.rate=8,e.channelVibrato.delay=.6)};switch(e.dataEntryState){default:case uA.Idle:break;case uA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;L(`%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;L(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16)} 0x${e.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(A===64)return;s(),e.channelVibrato.rate=A/64*8,m(`%cVibrato rate for %c${t}%c is now set to %c${A} = ${e.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(A===64)return;s(),e.channelVibrato.depth=A/2,m(`%cVibrato depth for %c${t}%c is now set to %c${A} = ${e.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(A===64)return;s(),e.channelVibrato.delay=A/64/3,m(`%cVibrato delay for %c${t}%c is now set to %c${A} = ${e.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let i=A;this.controllerChange(t,p.brightness,A),m(`%cFilter cutoff for %c${t}%c is now set to %c${i}`,r.info,r.recognized,r.info,r.value)}break;case 24:let n=A-64;e.keyCentTuning[e.NRPFine]=n*100,m(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${n}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,p.effects1Depth,o),m(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:L(`%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+P.pitchWheelRange]=A<<7,m(`%cChannel ${t} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(t,A-64);break;case 1:this.setChannelTuning(t,A-64,!1);break;case 5:this.setModulationDepth(t,A*100);break;case 16383:this.resetParameters(t);break}}}function Nn(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[EA+P.pitchWheelRange]|=A;let s=(e.midiControllers[EA+P.pitchWheelRange]>>7)+A/127;m(`%cChannel ${t} bend range. Semitones: %c${s}`,r.info,r.value);break;case 1:let o=e.customControllers[IA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[IA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function bn(t=!0){t&&m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A{this.workletProcessorChannels[A].lockedControllers[n]&&this.callEvent("controllerchange",{channel:A,controllerNumber:n,controllerValue:this.workletProcessorChannels[A].midiControllers[n]>>7})};if(s(p.mainVolume),s(p.pan),s(p.expressionController),s(p.modulationWheel),s(p.effects3Depth),s(p.effects1Depth),s(p.brightness),this.workletProcessorChannels[A].lockedControllers[EA+P.pitchWheel]){let n=this.workletProcessorChannels[A].midiControllers[EA+P.pitchWheel],o=n>>7,i=n&127;this.callEvent("pitchwheel",{channel:A,MSB:o,LSB:i})}}this.tunings=[],this.tunings=[];for(let A=0;A<127;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Oe}function Ln(t){let A=this.workletProcessorChannels[t],s=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(PA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let n=A.customControllers[IA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[IA.channelTransposeFine]=n,this.resetParameters(t)}function Un(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=uA.Idle}function Tn(){let t=4;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,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+n),0);let A=new H(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=e;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue),e++}return cA(A,0),sA(new AA("igen",A.length,A))}function Hn(t,A,e,s,n){let o=this.samples.map((B,d)=>{e&&B.compressSample(s,n);let h=B.getRawData();return m(`%cEncoded sample %c${d}. ${B.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),h}),i=this.samples.reduce((B,d,h)=>B+o[h].length+46,0),C=new H(i);this.samples.forEach((B,d)=>{let h=o[d],l,u,D=h.length;B.isCompressed?(l=C.currentIndex,u=l+h.length):(l=C.currentIndex/2,u=l+h.length/2,D+=46),t.push(l),C.set(h,C.currentIndex),C.currentIndex+=D,A.push(u)});let c=sA(new AA("smpl",C.length,C),new H([115,100,116,97]));return sA(new AA("LIST",c.length,c))}function Yn(t,A){let s=new H(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{wA(s,n.sampleName,20);let i=t[o];cA(s,i);let C=A[o];cA(s,C);let c=n.sampleLoopStartIndex/2+i,B=n.sampleLoopEndIndex/2+i;n.isCompressed&&(c-=i,B-=i),cA(s,c),cA(s,B),cA(s,n.sampleRate),s[s.currentIndex++]=n.samplePitch,s[s.currentIndex++]=n.samplePitchCorrection,Y(s,n.sampleLink),Y(s,n.sampleType)}),wA(s,"EOS",46),sA(new AA("shdr",s.length,s))}function Jn(){let t=10;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),sA(new AA("imod",A.length,A))}function vn(){let t=this.instruments.reduce((o,i)=>i.instrumentZones.length*4+o,4),A=new H(t),e=0,s=0,n=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let i of o.instrumentZones)i.zoneID=e,Y(A,s),Y(A,n),s+=i.generators.length,n+=i.modulators.length,e++}return Y(A,s),Y(A,n),sA(new AA("ibag",A.length,A))}function qn(){let t=this.instruments.length*22+22,A=new H(t),e=0,s=0;for(let n of this.instruments)wA(A,n.instrumentName,20),Y(A,e),e+=n.instrumentZones.length,n.instrumentID=s,s++;return wA(A,"EOI",20),Y(A,e),sA(new AA("inst",A.length,A))}function Pn(){let t=4;for(let s of this.presets)t+=s.presetZones.reduce((n,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+n),0);let A=new H(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=e;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue);e+=n.generators.length}return Y(A,0),Y(A,0),sA(new AA("pgen",A.length,A))}function Kn(){let t=10;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),sA(new AA("pmod",A.length,A))}function Vn(){let t=this.presets.reduce((o,i)=>i.presetZones.length*4+o,4),A=new H(t),e=0,s=0,n=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let i of o.presetZones)i.zoneID=e,Y(A,s),Y(A,n),s+=i.generators.length,n+=i.modulators.length,e++}return Y(A,s),Y(A,n),sA(new AA("pbag",A.length,A))}function On(){let t=this.presets.length*38+38,A=new H(t),e=0;for(let s of this.presets)wA(A,s.presetName,20),Y(A,s.program),Y(A,s.bank),Y(A,e),cA(A,s.library),cA(A,s.genre),cA(A,s.morphology),e+=s.presetZones.length;return wA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,e),cA(A,0),cA(A,0),cA(A,0),sA(new AA("phdr",A.length,A))}var Yo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Zn(t=Yo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");SA("%cSaving soundfont...",r.info),m(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),m("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[K,W]of Object.entries(this.soundFontInfo))if(K==="ifil"||K==="iver"){let I=parseInt(W.split(".")[0]),nA=parseInt(W.split(".")[1]),j=new H(4);Y(j,I),Y(j,nA),A.push(sA(new AA(K,4,j)))}else if(K==="DMOD")A.push(sA(new AA(K,W.length,W)));else{let I=new H(W.length);wA(I,W),A.push(sA(new AA(K,W.length,I)))}let e=ke([new H([73,78,70,79]),...A]),s=sA(new AA("LIST",e.length,e));m("%cWriting SDTA...",r.info);let n=[],o=[],i=Hn.call(this,n,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let C=Yn.call(this,n,o);m("%cWriting IGEN...",r.info);let c=Tn.call(this);m("%cWriting IMOD...",r.info);let B=Jn.call(this);m("%cWriting IBAG...",r.info);let d=vn.call(this);m("%cWriting INST...",r.info);let h=qn.call(this),l=Pn.call(this);m("%cWriting PMOD...",r.info);let u=Kn.call(this);m("%cWriting PBAG...",r.info);let D=Vn.call(this);m("%cWriting PHDR...",r.info);let y=On.call(this),w=ke([new H([112,100,116,97]),y,D,u,l,h,d,B,c,C]),S=sA(new AA("LIST",w.length,w));m("%cWriting the output file...",r.info);let b=ke([new H([115,102,98,107]),s,i,S]),R=sA(new AA("RIFF",b.length,b));return m(`%cSaved succesfully! Final file size: %c${R.length}`,r.info,r.recognized),X(),R}var ne=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Pe.map(e=>$.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}getPresetNoFallback(A,e,s=!1){let n=this.presets.find(o=>o.bank===A&&o.program===e);if(n)return n;if(s!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPreset(A,e){let s=this.presets.find(n=>n.bank===A&&n.program===e);return s||(A===128?(s=this.presets.find(n=>n.bank===128&&n.program===e),s||(s=this.presets.find(n=>n.bank===128))):s=this.presets.find(n=>n.program===e&&n.bank!==128),s&&L(`%cPreset ${A}.${e} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,r.warn,r.recognized)),s||(L(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),s=this.presets[0]),s}getPresetByName(A){let e=this.presets.find(s=>s.presetName===A);return e||(L("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}static mergeSoundfonts(...A){let e=A.shift(),s=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{s.find(i=>i.bank===o.bank&&i.program===o.program)===void 0&&s.push(o)});return new t({presets:s,info:e.soundFontInfo})}};ne.prototype.write=Zn;function Xn(t){SA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let s=A;s{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,e){let s=this.foundSamplesAndGenerators[A][e];if(s)return s;if(this.presetZones.length<1)return[];function n(h,l,u){return u>=h&&u<=l}function o(h,l){h.push(...l.filter(u=>!h.find(D=>D.generatorType===u.generatorType)))}function i(h,l){h.push(...l.filter(u=>!h.find(D=>$.isIdentical(u,D))))}let C=[],c=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],B=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(h=>n(h.keyRange.min,h.keyRange.max,A)&&n(h.velRange.min,h.velRange.max,e)&&!h.isGlobal).forEach(h=>{if(h.instrument.instrumentZones.length<1)return;let l=h.generators,u=h.modulators,D=h.instrument.instrumentZones[0].isGlobal?[...h.instrument.instrumentZones[0].generators]:[],y=h.instrument.instrumentZones[0].isGlobal?[...h.instrument.instrumentZones[0].modulators]:[];h.instrument.instrumentZones.filter(S=>n(S.keyRange.min,S.keyRange.max,A)&&n(S.velRange.min,S.velRange.max,e)&&!S.isGlobal).forEach(S=>{let b=[...S.generators],R=[...S.modulators];o(l,c),o(b,D),i(u,B),i(R,y),i(R,this.defaultModulators);let K=[...R];for(let W=0;W$.isIdentical(I,j));nA!==-1?K[nA]=K[nA].sumTransform(I):K.push(I)}C.push({instrumentGenerators:b,presetGenerators:l,modulators:K,sample:S.sample,sampleID:S.generators.find(W=>W.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}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 n=new le;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function Wn(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 X(),new Error("No instrument header!");let s=k(e.chunkData,4),n=k(e.chunkData,4),o=k(e.chunkData,4),i=new At(n,o),C="unnamedPreset",c=yA(A,"INFO");if(c){let u=O(c.chunkData);for(;u.header!=="INAM";)u=O(c.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=yA(A,"lrgn");if(!B)throw X(),new Error("No region list!");let d=new $A;d.isGlobal=!0;let h=yA(A,"lart"),l=yA(A,"lar2");this.readLart(h,l,d),i.DLSInstrument.instrumentZones.push(d);for(let u=0;u>10&15;S===QA.linear&&w!==QA.linear&&(S=w);let b=s>>14&1,R=s>>15&1;i===g.initialAttenuation&&(R=!R),h=TA(S,b,R,C.isCC,C.enum)}let l=s>>4&15,u=s>>8&1,D=s>>9&1,y=TA(l,u,D,d.isCC,d.enum);if(c){let w=y;y=h,h=w}return new $({srcEnum:h,secSrcEnum:y,dest:i,transform:0,amt:n})}function Tt(t,A){let e=t.chunkData,s=[],n=[];k(e,4);let o=k(e,4);for(let i=0;i>16;if(C===0&&c===0&&d===0){let u;switch(B){case x.pan:u=new U(g.pan,l);break;case x.gain:u=new U(g.initialAttenuation,-l*10/.4);break;case x.filterCutoff:u=new U(g.initialFilterFc,l);break;case x.filterQ:u=new U(g.initialFilterQ,l);break;case x.modLfoFreq:u=new U(g.freqModLFO,l);break;case x.modLfoDelay:u=new U(g.delayModLFO,l);break;case x.vibLfoFreq:u=new U(g.freqVibLFO,l);break;case x.vibLfoDelay:u=new U(g.delayVibLFO,l);break;case x.volEnvDelay:u=new U(g.delayVolEnv,l);break;case x.volEnvAttack:u=new U(g.attackVolEnv,l);break;case x.volEnvHold:u=new U(g.holdVolEnv,l);break;case x.volEnvDecay:u=new U(g.decayVolEnv,l);break;case x.volEnvRelease:u=new U(g.releaseVolEnv,l);break;case x.volEnvSustain:let D=(1e3-l)/10;u=new U(g.sustainVolEnv,D*10);break;case x.modEnvDelay:u=new U(g.delayModEnv,l);break;case x.modEnvAttack:u=new U(g.attackModEnv,l);break;case x.modEnvHold:u=new U(g.holdModEnv,l);break;case x.modEnvDecay:u=new U(g.decayModEnv,l);break;case x.modEnvRelease:u=new U(g.releaseModEnv,l);break;case x.modEnvSustain:let y=1e3-l;u=new U(g.sustainModEnv,y);break;case x.reverbSend:u=new U(g.reverbEffectsSend,l);break;case x.chorusSend:u=new U(g.chorusEffectsSend,l);break;case x.pitch:let w=Math.floor(l/100),S=Math.floor(l-w*100);u=new U(g.fineTune,S),s.push(new U(g.coarseTune,w));break}u&&s.push(u)}else{let u=!0;if(c===z.none)if(C===z.modLfo&&B===x.pitch)s.push(new U(g.modLfoToPitch,l));else if(C===z.modLfo&&B===x.gain)s.push(new U(g.modLfoToVolume,l));else if(C===z.modLfo&&B===x.filterCutoff)s.push(new U(g.modLfoToFilterFc,l));else if(C===z.vibratoLfo&&B===x.pitch)s.push(new U(g.vibLfoToPitch,l));else if(C===z.modEnv&&B===x.pitch)s.push(new U(g.modEnvToPitch,l));else if(C===z.modEnv&&B===x.filterCutoff)s.push(new U(g.modEnvToFilterFc,l));else if(C===z.keyNum&&B===x.volEnvHold){s.push(new U(g.keyNumToVolEnvHold,l/-128));let D=Math.round(60/128*l);s.forEach(y=>{y.generatorType===g.holdVolEnv&&(y.generatorValue+=D)})}else if(C===z.keyNum&&B===x.volEnvDecay){s.push(new U(g.keyNumToVolEnvDecay,l/-128));let D=Math.round(60/128*l);s.forEach(y=>{y.generatorType===g.decayVolEnv&&(y.generatorValue+=D)})}else if(C===z.keyNum&&B===x.modEnvHold){s.push(new U(g.keyNumToModEnvHold,l/-128));let D=Math.round(60/128*l);s.forEach(y=>{y.generatorType===g.holdModEnv&&(y.generatorValue+=D)})}else if(C===z.keyNum&&B===x.modEnvDecay){s.push(new U(g.keyNumToModEnvDecay,l/-128));let D=Math.round(60/128*l);s.forEach(y=>{y.generatorType===g.decayModEnv&&(y.generatorValue+=D)})}else u=!1;else u=!1;if(u===!1){let D=zn(C,c,B,d,l);D?(n.push(D),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):L("Failed converting to SF2 Modulator!")}}}return n.find(i=>i.modulatorDestination===g.reverbEffectsSend)===void 0&&n.push(new $({srcEnum:219,dest:g.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(i=>i.modulatorDestination===g.chorusEffectsSend)===void 0&&n.push(new $({srcEnum:221,dest:g.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&n.push(new $({srcEnum:129,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new $({srcEnum:13,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:n,generators:s}}function jn(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(j=>j.header==="rgnh"),s=k(e.chunkData,2),n=k(e.chunkData,2),o=k(e.chunkData,2),i=k(e.chunkData,2),C=new et({min:s,max:n},{min:o,max:i});k(e.chunkData,2);let c=k(e.chunkData,2);c!==0&&C.generators.push(new U(g.exclusiveClass,c));let B=yA(A,"lart"),d=yA(A,"lar2");this.readLart(B,d,C),C.isGlobal=!1;let h=A.find(j=>j.header==="wsmp");k(h.chunkData,4);let l=k(h.chunkData,2),u=zA(h.chunkData[h.chunkData.currentIndex++],h.chunkData[h.chunkData.currentIndex++]),y=(k(h.chunkData,4)|0)/-655360;k(h.chunkData,4);let w=k(h.chunkData,4),S,b={start:0,end:0};if(w===0)S=0;else{k(h.chunkData,4),k(h.chunkData,4)===0?S=1:S=3,b.start=k(h.chunkData,4);let J=k(h.chunkData,4);b.end=b.start+J}let R=A.find(j=>j.header==="wlnk");if(R===void 0)return;k(R.chunkData,2),k(R.chunkData,2),k(R.chunkData,4);let K=k(R.chunkData,4),W=this.samples[K];if(W===void 0)throw new Error("Invalid sample ID!");let nA=(y||W.sampleDbAttenuation)*10/.4;return C.setWavesample(nA,S,b,l,W,K,u),C}var de=class{constructor(A,e,s,n,o,i,C,c){this.sampleName=A,this.sampleRate=e,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=i,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=c,this.isCompressed=(i&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,e){if(!this.isCompressed)try{this.compressedData=e([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{L(`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{constructor(A,e,s,n,o,i,C,c){super(A,e,s,n,0,1,o*2,(i-1)*2),this.sampleData=C,this.sampleDbAttenuation=c}getAudioData(){return this.sampleData}sampleDbAttenuation;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 Ao(t){SA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexJ.header==="fmt ");if(!n)throw new Error("No fmt chunk in the wave file!");if(k(n.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(k(n.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=k(n.chunkData,4);k(n.chunkData,4),k(n.chunkData,2);let c=k(n.chunkData,2),B=c/8,d=Math.pow(2,B*8-1),h=Math.pow(2,B*8),l,u=!1;c===8?(l=255,u=!0):l=d;let D=s.find(J=>J.header==="data");if(!D)throw new Error("No data chunk in the wave chunk!");let y=D.size/B,w=new Float32Array(y);for(let J=0;J=d&&(Z-=h),w[J]=Z/l)}let S=60,b=0,R=0,K=w.length-1,W=0,I=s.find(J=>J.header==="wsmp");if(I){if(k(I.chunkData,4),S=k(I.chunkData,2),b=zA(I.chunkData[I.chunkData.currentIndex++],I.chunkData[I.chunkData.currentIndex++]),W=(k(I.chunkData,4)|0)/-655360,k(I.chunkData,4),k(I.chunkData,4)===1){k(I.chunkData,8),R=k(I.chunkData,4);let CA=k(I.chunkData,4);K=R+CA}}else L("No wsmp chunk in wave... using sane defaults.");let nA=yA(s,"INFO"),j=`Unnamed ${A}`;if(nA){let J=O(nA.chunkData);for(;J.header!=="INAM"&&nA.chunkData.currentIndex(S.messageStatusByte&240)===F.noteOn);w&&u.push(w.ticks)}this.firstNoteOn=Math.min(...u),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&h===null?(d=this.firstNoteOn,h=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(h===null||h===0)&&(h=this.lastVoiceEventTick)),this.loop={start:d,end:h},m(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let 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?m("%cNo additional MIDI Ports detected.",r.info):m("%cMIDI Ports detected!",r.recognized),!i)if(this.tracks.length>1){if(this.tracks[0].find(y=>y.messageStatusByte>=F.noteOn&&y.messageStatusBytew.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(w=>w.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){m("%cNo name detected. Using the alt name!",r.info),this.midiName=gs(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let y=0;yl>h?l:h),s=[];for(let h=0;h{i[D]>=u.length||u[i[D]].ticks0;){let h=c(),l=t.tracks[h];if(i[h]>=l.length){C--;continue}let u=l[i[h]];if(i[h]++,u.messageStatusByte===F.midiPort){B[h]=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[h]]||0,w=s[y];switch(D){case F.programChange:w.program=u.messageData[0],n(w);break;case F.controllerChange:if(u.messageData[0]!==p.bankSelect||d==="gs"&&w.drums)continue;let S=u.messageData[1],N=Math.max(0,S-t.bankOffset);if(d==="xg"){let W=S===120||S===126||S===127;W!==w.drums?(w.drums=W,w.bank=w.drums?128:N,n(w)):w.bank=w.drums?128:N;continue}s[y].bank=N;break;case F.noteOn:if(u.messageData[1]===0)continue;n(w),o[w.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 G=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+t.midiPortChannelOffsets[B[h]],K=!!(u.messageData[7]>0&&u.messageData[5]>>4);w=s[G],w.drums=K,w.bank=K?128:0,n(w);break}}for(let h of Object.keys(o))o[h].size===0&&(m(`%cDetected change but no keys for %c${h}`,r.info,r.value),delete o[h]);return X(),o}function Rs(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(e,A)}),this.duration=this.midiData.duration,this.firstNoteTime=Ce(this.midiData.firstNoteOn,this.midiData),m(`%cTotal song time: ${ft(Math.ceil(this.duration)).time}`,r.recognized),this.post(FA.songChange,[new Ze(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(L(`%cVery short song: (${ft(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function xs(t){this.songs=t.reduce((A,e)=>{if(e.duration)return A.push(e),A;try{A.push(new ze(e.binary,e.altName||""))}catch(s){return this.post(FA.midiError,s.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function Ms(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Ns(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}var KA=new Int16Array(127);KA[p.mainVolume]=100;KA[p.expressionController]=127;KA[p.pan]=64;KA[p.releaseTime]=64;KA[p.brightness]=64;KA[p.effects1Depth]=0;function bs(t,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let e=this.synth.workletProcessorChannels.length,s=Array(e).fill(8192),n=[];for(let C=0;CC===p.dataDecrement||C===p.dataIncrement||C===p.dataEntryMsb||C===p.dataDecrement||C===p.lsbForControl6DataEntry||C===p.RPNLsb||C===p.RPNMsb||C===p.NRPNLsb||C===p.NRPNMsb||C===p.bankSelect||C===p.lsbForControl0BankSelect||C===p.resetAllControllers,i=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let B=we(c.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:s[d]=c.messageData[1]<<7|c.messageData[0];break;case F.programChange:let l=n[d];l.program=c.messageData[0],l.actualBank=l.bank;break;case F.controllerChange:let u=c.messageData[0];if(o(u)){let D=c.messageData[1];if(u===p.bankSelect){n[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(KA)),i[d][u]=c.messageData[1];break;default:this._processEvent(c,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let h=this.tracks[C][this.eventIndex[C]];if(h===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(h.ticks-c.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7,s[C]&127),i[C]!==void 0&&i[C].forEach((c,B)=>{c!==KA[B]&&!o(B)&&this.sendMIDICC(C,B,c)}),n[C].program>=0&&n[C].actualBank>=0){let c=n[C].actualBank;this.sendMIDICC(C,p.bankSelect,c),this.sendMIDIProgramChange(C,n[C].program)}}else for(let C=0;C>7,s[C]&127),i[C]!==void 0&&i[C].forEach((c,B)=>{c!==KA[B]&&!o(B)&&this.synth.controllerChange(C,B,c)}),n[C].program>=0&&n[C].actualBank>=0){let c=n[C].actualBank;this.synth.controllerChange(C,p.bankSelect,c),this.synth.programChange(C,n[C].program)}return!0}function Ls(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 Us(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(FA.timeChange,currentTime-Ce(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Ts(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function Hs(t,A){switch(t){default:break;case bA.loadNewSongList:this.loadNewSongList(A);break;case bA.pause:this.pause();break;case bA.play:this.play(A);break;case bA.stop:this.stop();break;case bA.setTime:this.currentTime=A;break;case bA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case bA.setPlaybackRate:this.playbackRate=A;break;case bA.setLoop:this.loop=A;break;case bA.changeSong:A?this.nextSong():this.previousSong();break;case bA.getMIDI:this.post(FA.getMIDI,this.midiData);break;case bA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Ys(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:pA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Js(t){this.post(FA.midiEvent,t)}function vs(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|t,A,e])}function qs(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|t,A])}function Ps(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|t,e,A])}function Ks(){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&&AVs?440*Math.pow(2,(t-6900)/1200):Rt[~~t-je]}var xt=-1660,bo=1600,Gt=new Float32Array((bo-xt)*100+1);for(let t=0;t.5?1:0,s?e*2-1:e;case QA.concave:return s?(e=e*2-1,e<0?1-Ee[~~(e*-gA)]-1:Ee[~~e*gA]):Ee[~~(e*gA)];case QA.convex:return s?(e=e*2-1,e<0?1-Be[~~(e*-gA)]-1:Be[~~(e*gA)]):Be[~~(e*gA)]}}var Mt=1,Nt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)s-=o;let C=~~s,c=C+1;for(;c>=e.loopEnd;)c-=o;let B=s-C,d=n[c],h=n[C];A[i]=h+(d-h)*B,s+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end){t.finished=!0;return}let c=s-i,B=n[C],d=n[i];A[o]=d+(B-d)*c,s+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=s}function Zs(t,A){let e=t.sample,s=e.cursor,n=e.loopEnd-e.loopStart,o=e.sampleData;if(t.sample.isLooping)for(let i=0;i=e.loopEnd;)s-=n;let C=~~s+1;for(;C>=e.loopEnd;)C-=n;A[i]=o[C],s+=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],s+=e.playbackStep*t.currentTuningCalculated}}e.cursor=s}function Xs(t,A){let e=t.sample,s=e.cursor,n=e.sampleData;if(e.isLooping){let o=e.loopEnd-e.loopStart;for(let i=0;i=e.loopEnd;)s-=o;let C=~~s,c=C+1,B=c+1,d=B+1,h=s-C;c>=e.loopEnd&&(c-=o),B>=e.loopEnd&&(B-=o),d>=e.loopEnd&&(d-=o);let l=n[C],u=n[c],D=n[B],y=n[d],w=.5*(D-l),S=l-2.5*u+2*D-.5*y,N=.5*(y-l)+1.5*(u-D);A[i]=((N*h+S)*h+w)*h+u,s+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end||c>=e.end||B>=e.end){t.finished=!0;return}let h=n[i],l=n[C],u=n[c],D=n[B],y=.5*(u-h),w=h-2.5*l+2*u-.5*D,S=.5*(D-h)+1.5*(l-u);A[o]=((S*d+w)*d+y)*d+l,s+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=s}function Ws(t,A,e,s,n,o,i,C,c){if(!isNaN(e[0])){if(i>0){let B=o[0],d=o[1];i=Math.min(i,1e3);let h=i/1300,l=t*h,u=A*h;for(let D=0;D0){let B=C[0],d=C[1];c=Math.min(c,1e3);let h=c/1300,l=t*h,u=A*h;for(let D=0;D0)for(let B=0;B0)for(let B=0;B13499&&A.filter.reasonanceCb===0)return;let n=A.filter;(n.cutoffCents!==s||n.reasonanceCb!==A.modulatedGenerators[g.initialFilterQ])&&(n.cutoffCents=s,n.reasonanceCb=A.modulatedGenerators[g.initialFilterQ],t.calculateCoefficients(A));for(let o=0;o=bt}currentSampleTime=0;sampleRate;currentAttenuationDb=JA;state=0;releaseStartDb=JA;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=VA(A.volumeEnvelope.currentAttenuationDb),t.recalculate(A)}static recalculate(A){let e=A.volumeEnvelope,s=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 n=Math.min(JA,e.sustainDbRelative);e.attackDuration=s(A.modulatedGenerators[g.attackVolEnv]);let o=A.modulatedGenerators[g.decayVolEnv],i=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvDecay],C=n/JA;e.decayDuration=s(o+i)*C,e.releaseDuration=s(A.modulatedGenerators[g.releaseVolEnv]),e.delayEnd=s(A.modulatedGenerators[g.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let c=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvHold];if(e.holdEnd=s(A.modulatedGenerators[g.holdVolEnv]+c)+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=s(o+i)*d,e.state){case 0:e.releaseStartDb=JA;break;case 1:let h=1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration;e.releaseStartDb=20*Math.log10(h)*-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=VA(e.releaseStartDb)}}static apply(A,e,s,n){let o=A.volumeEnvelope,i=s/10,C=n;if(A.isInRelease){let B=o.currentSampleTime-o.releaseStartTimeSamples;if(B>=o.releaseDuration){for(let h=0;h=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[c]*=VA(o.sustainDbRelative+i+o.attenuation),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++c>=e.length)return}}};var zs=Math.PI/2,js=.05;function $s(t,A,e,s,n,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[IA.channelTuning]+t.customControllers[IA.channelTransposeFine]+t.customControllers[IA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],c=A.modulatedGenerators[g.coarseTune]+t.customControllers[IA.channelTuningSemitones],B=this.tunings[t.preset.program]?.[i];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 Z=A.startTime+HA(A.modulatedGenerators[g.delayVibLFO]),CA=Fe(A.modulatedGenerators[g.freqVibLFO]),oA=$e(Z,CA,currentTime);C+=oA*(d*t.customControllers[IA.modulationMultiplier])}let h=A.modulatedGenerators[g.initialFilterFc],l=A.modulatedGenerators[g.modLfoToPitch],u=A.modulatedGenerators[g.modLfoToVolume],D=A.modulatedGenerators[g.modLfoToFilterFc],y=0;if(l+D+u!==0){let Z=A.startTime+HA(A.modulatedGenerators[g.delayModLFO]),CA=Fe(A.modulatedGenerators[g.freqModLFO]),oA=$e(Z,CA,currentTime);C+=oA*(l*t.customControllers[IA.modulationMultiplier]),y=-oA*u,h+=oA*D}if(t.channelVibrato.depth>0){let Z=$e(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);Z&&(C+=Z*t.channelVibrato.depth)}let w=A.modulatedGenerators[g.modEnvToPitch],S=A.modulatedGenerators[g.modEnvToFilterFc],N=YA.getValue(A,currentTime);h+=N*S,C+=N*w;let G=~~(C+c*100);G!==A.currentTuningCents&&(A.currentTuningCents=G,A.currentTuningCalculated=Math.pow(2,G/1200));let K=(Math.max(-500,Math.min(500,A.modulatedGenerators[g.pan]))+500)/1e3,W=new Float32Array(e.length);switch(this.interpolationType){case he.linear:default:Os(A,W);break;case he.nearestNeighbor:Zs(A,W);break;case he.fourthOrder:Xs(A,W)}Qe.apply(A,W,h),LA.apply(A,W,y,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(K-A.currentPan)*this.panSmoothingFactor;let I=Math.cos(zs*A.currentPan)*this.panLeft,nA=Math.sin(zs*A.currentPan)*this.panRight,j=this.oneOutputMode?0:A.modulatedGenerators[g.reverbEffectsSend],J=this.oneOutputMode?0:A.modulatedGenerators[g.chorusEffectsSend];Ws(I,nA,W,e,s,n,j,o,J)}function Uo(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 An(t){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=Uo(s,n);A.push({channel:s,voice:n,priority:o})}A.sort((s,n)=>s.priority-n.priority);let e=A.slice(0,t);for(let{channel:s,voice:n}of e){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function en(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimesn=t);var To=function(t){var A,e,s,n,o,i,C,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",B="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=c.indexOf(t.charAt(d++)),o=c.indexOf(t.charAt(d++)),i=c.indexOf(t.charAt(d++)),C=c.indexOf(t.charAt(d++)),A=n<<2|o>>4,e=(15&o)<<4|i>>2,s=(3&i)<<6|C,B+=String.fromCharCode(A),i!==64&&(B+=String.fromCharCode(e)),C!==64&&(B+=String.fromCharCode(s));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 Se))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]"}):CA?(typeof read<"u"&&(I.read=function(E){return read(E)}),I.readBinary=function(E){var Q;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(Q=read(E,"binary"))=="object"),Q)},typeof scriptArgs<"u"?I.arguments=scriptArgs:typeof arguments<"u"&&(I.arguments=arguments),typeof quit=="function"&&(I.quit=function(a){quit(a)})):(j||J)&&(j?document.currentScript&&(oA=document.currentScript.src):oA=self.location.href,oA=oA.indexOf("blob:")!==0?oA.split("/").slice(0,-1).join("/")+"/":"",I.read=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.send(null),Q.responseText},J&&(I.readBinary=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.responseType="arraybuffer",Q.send(null),new Uint8Array(Q.response)}),I.readAsync=function(E,Q,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){Q(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 nA)nA.hasOwnProperty(t)&&(I[t]=nA[t]);function Ne(a){var E=u;return u=u+a+15&-16,E}function Pt(a){var E=c[G>>2],Q=E+a+15&-16;return c[G>>2]=Q,Q>=BA&&!$t()?(c[G>>2]=E,0):E}function Kt(a,E){return E||(E=16),a=Math.ceil(a/E)*E}function lo(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))}nA=void 0;var uo={"f64-rem":function(a,E){return a%E},debugger:function(){}},rt=[];function Po(a,E){for(var Q=0,f=Q;f>>0)+4294967296*+(E>>>0):+(a>>>0)+4294967296*+(0|E)}function at(a,E,Q){return Q&&Q.length?I["dynCall_"+a].apply(null,[E].concat(Q)):I["dynCall_"+a].call(null,E)}var be=0,Vt=0;function _A(a,E){a||ZA("Assertion failed: "+E)}function Ot(a){var E=I["_"+a];return _A(E,"Cannot call unknown function "+a+", make sure it is exported"),E}var Zt={stackSave:function(){ct()},stackRestore:function(){Qt()},arrayToC:function(a){var E,Q,f=Je(a.length);return E=a,Q=f,n.set(E,Q),f},stringToC:function(a){var E=0;if(a!=null&&a!==0){var Q=(a.length<<2)+1;E=Je(Q),_t(a,E,Q)}return E}},fo={string:Zt.stringToC,array:Zt.arrayToC};function Xt(a,E,Q,f,R){var q=Ot(a),_=[],M=0;if(f)for(var hA=0;hA>0]=E;break;case"i16":i[a>>1]=E;break;case"i32":c[a>>2]=E;break;case"i64":tempI64=[E>>>0,+ko(tempDouble=E)>=1?tempDouble>0?(0|Fo(+ns(tempDouble/4294967296),4294967295))>>>0:~~+wo((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],c[a>>2]=tempI64[0],c[a+4>>2]=tempI64[1];break;case"float":d[a>>2]=E;break;case"double":h[a>>3]=E;break;default:ZA("invalid type for setValue: "+Q)}}function Zo(a,E,Q){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return n[a>>0];case"i16":return i[a>>1];case"i32":case"i64":return c[a>>2];case"float":return d[a>>2];case"double":return h[a>>3];default:ZA("invalid type for getValue: "+E)}return null}function Xo(a,E,Q,f){typeof a=="number"?(q=!0,_=a):(q=!1,_=a.length);var R=typeof E=="string"?E:null;if(M=Q==4?f:[typeof Ye=="function"?Ye:Ne,Je,Ne,Pt][Q===void 0?2:Q](Math.max(_,R?1:E.length)),q){for(f=M,_A((3&M)==0),hA=M+(-4&_);f>2]=0;for(hA=M+_;f>0]=0;return M}if(R==="i8")return a.subarray||a.slice?o.set(a,M):o.set(new Uint8Array(a),M),M;for(var q,_,M,hA,rA,iA,tA,v=0;v<_;){var mA=a[v];if((rA=R||E[v])===0){v++;continue}rA=="i64"&&(rA="i32"),mo(M+v,mA,rA),tA!==rA&&(iA=lo(rA),tA=rA),v+=iA}return M}function Wo(a){return D?Bt?Ye(a):Pt(a):Ne(a)}function Le(a,E){if(E===0||!a)return"";for(var Q,f,R,q=0,_=0;q|=f=o[a+_>>0],(f!=0||E)&&(_++,!E||_!=E););E||(E=_);var M="";if(q<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(a,a+Math.min(E,1024))),M=M?M+R:R,a+=1024,E-=1024;return M}return Q=a,function(rA,iA){for(var tA=iA;rA[tA];)++tA;if(tA-iA>16&&rA.subarray&&Wt)return Wt.decode(rA.subarray(iA,tA));for(var v,mA,GA,xA,MA,ee,NA="";;){if(!(v=rA[iA++]))return NA;if(!(128&v)){NA+=String.fromCharCode(v);continue}if(mA=63&rA[iA++],(224&v)==192){NA+=String.fromCharCode((31&v)<<6|mA);continue}if(GA=63&rA[iA++],(240&v)==224?v=(15&v)<<12|mA<<6|GA:(xA=63&rA[iA++],(248&v)==240?v=(7&v)<<18|mA<<12|GA<<6|xA:(MA=63&rA[iA++],v=(252&v)==248?(3&v)<<24|mA<<18|GA<<12|xA<<6|MA:(1&v)<<30|mA<<24|GA<<18|xA<<12|MA<<6|(ee=63&rA[iA++]))),v<65536)NA+=String.fromCharCode(v);else{var ye=v-65536;NA+=String.fromCharCode(55296|ye>>10,56320|1023&ye)}}}(o,Q)}function _o(a){for(var E="";;){var Q=n[a++>>0];if(!Q)return E;E+=String.fromCharCode(Q)}}function zo(a,E){return function(f,R,q){for(var _=0;_>0]=f.charCodeAt(_);q||(n[R>>0]=0)}(a,E,!1)}var Wt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ue(a,E,Q,f){if(!(f>0))return 0;for(var R=Q,q=Q+f-1,_=0;_=55296&&M<=57343&&(M=65536+((1023&M)<<10)|1023&a.charCodeAt(++_)),M<=127){if(Q>=q)break;E[Q++]=M}else if(M<=2047){if(Q+1>=q)break;E[Q++]=192|M>>6,E[Q++]=128|63&M}else if(M<=65535){if(Q+2>=q)break;E[Q++]=224|M>>12,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}else if(M<=2097151){if(Q+3>=q)break;E[Q++]=240|M>>18,E[Q++]=128|M>>12&63,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}else if(M<=67108863){if(Q+4>=q)break;E[Q++]=248|M>>24,E[Q++]=128|M>>18&63,E[Q++]=128|M>>12&63,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}else{if(Q+5>=q)break;E[Q++]=252|M>>30,E[Q++]=128|M>>24&63,E[Q++]=128|M>>18&63,E[Q++]=128|M>>12&63,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}}return E[Q]=0,Q-R}function _t(a,E,Q){return Ue(a,o,E,Q)}function Te(a){for(var E=0,Q=0;Q=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&a.charCodeAt(++Q)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var zt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function jo(a){for(var E=a,Q=E>>1;i[Q];)++Q;if((E=Q<<1)-a>32&&zt)return zt.decode(o.subarray(a,E));for(var f=0,R="";;){var q=i[a+2*f>>1];if(q==0)return R;++f,R+=String.fromCharCode(q)}}function $o(a,E,Q){if(Q===void 0&&(Q=2147483647),Q<2)return 0;for(var f=E,R=(Q-=2)<2*a.length?Q/2:a.length,q=0;q>1]=_,E+=2}return i[E>>1]=0,E-f}function Ar(a){return 2*a.length}function er(a){for(var E=0,Q="";;){var f=c[a+4*E>>2];if(f==0)return Q;if(++E,f>=65536){var R=f-65536;Q+=String.fromCharCode(55296|R>>10,56320|1023&R)}else Q+=String.fromCharCode(f)}}function tr(a,E,Q){if(Q===void 0&&(Q=2147483647),Q<4)return 0;for(var f=E,R=f+Q-4,q=0;q=55296&&_<=57343&&(_=65536+((1023&_)<<10)|1023&a.charCodeAt(++q)),c[E>>2]=_,(E+=4)+4>R)break}return c[E>>2]=0,E-f}function sr(a){for(var E=0,Q=0;Q=55296&&f<=57343&&++Q,E+=4}return E}function nr(a){var E=Te(a)+1,Q=Ye(E);return Q&&Ue(a,n,Q,E),Q}function or(a){var E=Te(a)+1,Q=Je(E);return Ue(a,n,Q,E),Q}function rr(a){return a}function ir(){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(Q){var f,R=f=Q;return Q===R?Q:Q+" ["+R+"]"})}function It(a,E){return a%E>0&&(a+=E-a%E),a}function jt(a){I.buffer=s=a}function gt(){I.HEAP8=n=new Int8Array(s),I.HEAP16=i=new Int16Array(s),I.HEAP32=c=new Int32Array(s),I.HEAPU8=o=new Uint8Array(s),I.HEAPU16=C=new Uint16Array(s),I.HEAPU32=B=new Uint32Array(s),I.HEAPF32=d=new Float32Array(s),I.HEAPF64=h=new Float64Array(s)}function $t(){var a=I.usingWasm?65536:16777216,E=2147483648-a;if(c[G>>2]>E)return!1;var Q=BA;for(BA=Math.max(BA,16777216);BA>2];)BA=BA<=536870912?It(2*BA,a):Math.min(It((3*BA+2147483648)/4,a),E);var f=I.reallocBuffer(BA);return f&&f.byteLength==BA?(jt(f),gt(),!0):(BA=Q,!1)}l=u=y=w=S=N=G=0,D=!1,I.reallocBuffer||(I.reallocBuffer=function(a){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(s,a);else{var E,Q=n;E=new ArrayBuffer(a),new Int8Array(E).set(Q)}}catch{return!1}return!!Ro(E)&&E});try{(K=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{K=function(E){return E.byteLength}}var Ct=I.TOTAL_STACK||5242880,BA=I.TOTAL_MEMORY||16777216;function po(){return BA}function me(a){for(;a.length>0;){var E=a.shift();if(typeof E=="function"){E();continue}var Q=E.func;typeof Q=="number"?E.arg===void 0?I.dynCall_v(Q):I.dynCall_vi(Q,E.arg):Q(E.arg===void 0?null:E.arg)}}BA=0?a:E<=32?2*Math.abs(1<=f&&(E<=32||a>f)&&(a=-2*f+a),a}var ko=Math.abs,wo=Math.ceil,ns=Math.floor,Fo=Math.min,Ae=0,ht=null,pe=null;function hr(a){return a}I.preloadedImages={},I.preloadedAudios={};var os="data:application/octet-stream;base64,";function He(a){return String.prototype.startsWith?a.startsWith(os):a.indexOf(os)===0}(function(){var E="main.wast",Q="main.wasm",f="main.temp.asm.js";He(E)||(E=fA(E)),He(Q)||(Q=fA(Q)),He(f)||(f=fA(f));var R={global:null,env:null,asm2wasm:uo,parent:I},q=null;function _(tA){return tA}function M(){try{if(I.wasmBinary)return new Uint8Array(I.wasmBinary);if(I.readBinary)return I.readBinary(Q);throw"both async and sync fetching of the wasm failed"}catch(tA){ZA(tA)}}I.asmPreload=I.asm;var hA=I.reallocBuffer,rA=function(tA){tA=It(tA,I.usingWasm?65536:16777216);var v=I.buffer.byteLength;if(I.usingWasm)try{var mA=I.wasmMemory.grow((tA-v)/65536);return mA!==-1?I.buffer=I.wasmMemory.buffer:null}catch{return null}};I.reallocBuffer=function(tA){return iA==="asmjs"?hA(tA):rA(tA)};var iA="";I.asm=function(tA,v,mA){var GA;if(!(v=GA=v).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?v.table=new WebAssembly.Table({initial:MA,maximum:ee,element:"anyfunc"}):v.table=new WebAssembly.Table({initial:MA,element:"anyfunc"}):v.table=Array(MA),I.wasmTable=v.table}return v.memoryBase||(v.memoryBase=I.STATIC_BASE),v.tableBase||(v.tableBase=0),xA=function(ye,oe,ut){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((q=vA.exports).memory){var De,dt,as;De=q.memory,dt=I.buffer,De.byteLength0?Q:Te(a)+1,R=Array(f),q=Ue(a,R,0,R.length);return E&&(R.length=q),R}function ur(a){for(var E=[],Q=0;Q255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}u+=16,G=Ne(4),S=(y=w=Kt(u))+Ct,N=Kt(S),c[G>>2]=N,D=!0,I.wasmTableSize=4,I.wasmMaxTableSize=4,I.asmGlobalArg={},I.asmLibraryArg={abort:ZA,assert:_A,enlargeMemory:$t,getTotalMemory:po,abortOnCannotGrowMemory:function(){ZA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+BA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(E,Q,f){var R=ct();try{return I.dynCall_iii(E,Q,f)}catch(q){if(Qt(R),typeof q!="number"&&q!=="longjmp")throw q;I.setThrew(1,0)}},___assert_fail:function(E,Q,f,R){ZA("Assertion failed: "+Le(E)+", at: "+[Q?Le(Q):"unknown filename",f,R?Le(R):"unknown function"])},___setErrNo:function(E){return I.___errno_location&&(c[I.___errno_location()>>2]=E),E},_abort:function(){I.abort()},_emscripten_memcpy_big:function(E,Q,f){return o.set(o.subarray(Q,Q+f),E),E},_llvm_floor_f64:ns,DYNAMICTOP_PTR:G,tempDoublePtr:kA,ABORT:be,STACKTOP:w,STACK_MAX:S};var rs=I.asm(I.asmGlobalArg,I.asmLibraryArg,s);I.asm=rs,I.___errno_location=function(){return I.asm.___errno_location.apply(null,arguments)};var Ro=I._emscripten_replace_memory=function(){return I.asm._emscripten_replace_memory.apply(null,arguments)};I._free=function(){return I.asm._free.apply(null,arguments)};var Ye=I._malloc=function(){return I.asm._malloc.apply(null,arguments)};I._memcpy=function(){return I.asm._memcpy.apply(null,arguments)},I._memset=function(){return I.asm._memset.apply(null,arguments)},I._sbrk=function(){return I.asm._sbrk.apply(null,arguments)},I._stb_vorbis_js_channels=function(){return I.asm._stb_vorbis_js_channels.apply(null,arguments)},I._stb_vorbis_js_close=function(){return I.asm._stb_vorbis_js_close.apply(null,arguments)},I._stb_vorbis_js_decode=function(){return I.asm._stb_vorbis_js_decode.apply(null,arguments)},I._stb_vorbis_js_open=function(){return I.asm._stb_vorbis_js_open.apply(null,arguments)},I._stb_vorbis_js_sample_rate=function(){return I.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},I.establishStackSpace=function(){return I.asm.establishStackSpace.apply(null,arguments)},I.getTempRet0=function(){return I.asm.getTempRet0.apply(null,arguments)},I.runPostSets=function(){return I.asm.runPostSets.apply(null,arguments)},I.setTempRet0=function(){return I.asm.setTempRet0.apply(null,arguments)},I.setThrew=function(){return I.asm.setThrew.apply(null,arguments)};var Je=I.stackAlloc=function(){return I.asm.stackAlloc.apply(null,arguments)},Qt=I.stackRestore=function(){return I.asm.stackRestore.apply(null,arguments)},ct=I.stackSave=function(){return I.asm.stackSave.apply(null,arguments)};function Se(a){this.name="ExitStatus",this.message="Program terminated with exit("+a+")",this.status=a}function lt(a){a=a||I.arguments,!(Ae>0)&&(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)yo(I.preRun.shift());me(As)}(),!(Ae>0)&&(I.calledRun||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),E()},1)):E())));function E(){!I.calledRun&&(I.calledRun=!0,be||(Bt||(Bt=!0,me(Et)),me(es),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)Do(I.postRun.shift());me(ss)}()))}}function dr(a,E){(!E||!I.noExitRuntime||a!==0)&&(I.noExitRuntime||(be=!0,Vt=a,w=W,me(ts),So=!0,I.onExit&&I.onExit(a)),I.quit(a,new Se(a)))}function ZA(a){throw I.onAbort&&I.onAbort(a),a!==void 0?(Me(a),RA(a),a=JSON.stringify(a)):a="",be=!0,Vt=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=rs,I.ccall=Xt,I.cwrap=function(E,Q,f,R){var q=(f=f||[]).every(function(_){return _==="number"});return Q!=="string"&&q&&!R?Ot(E):function(){return Xt(E,Q,f,arguments,R)}},Se.prototype=Error(),Se.prototype.constructor=Se,pe=function a(){I.calledRun||lt(),I.calledRun||(pe=a)},I.run=lt,I.abort=ZA,I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();I.noExitRuntime=!0,lt(),I.onRuntimeInitialized=()=>{tn=!0,sn()},OA.decode=function(a){return function(Q){if(!tn)throw Error("Not initialized");var f={};function R(oe){return new Int32Array(I.HEAPU8.buffer,oe,1)[0]}function q(oe,ut){var ve=new ArrayBuffer(ut*Float32Array.BYTES_PER_ELEMENT),re=new Float32Array(ve);return re.set(new Float32Array(I.HEAPU8.buffer,oe,ut)),re}f.open=I.cwrap("stb_vorbis_js_open","number",[]),f.close=I.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=I.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=I.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=I.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var _,M,hA,rA,iA=f.open(),tA=(_=Q,M=Q.byteLength,hA=I._malloc(M),(rA=new Uint8Array(I.HEAPU8.buffer,hA,M)).set(new Uint8Array(_,0,M)),rA),v=I._malloc(4),mA=I._malloc(4),GA=f.decode(iA,tA.byteOffset,tA.byteLength,v,mA);if(I._free(tA.byteOffset),GA<0)throw f.close(iA),I._free(v),Error("stbvorbis decode failed: "+GA);for(var xA=f.channels(iA),MA=Array(xA),ee=new Int32Array(I.HEAPU32.buffer,R(v),xA),NA=0;NA=0&&(s=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:s.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+P.pitchWheelRange]>>7)+(A.midiControllers[EA+P.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[EA+P.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:pA.channelProperties,messageData:t})}function Ho(t,A,e){let s=t,n=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function an(t,A=0){let e=t[0];if(!(this.deviceID!==UA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:L(`%cUnrecognized SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let n;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),m(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),m(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let c=(t[5]<<7|t[6])-8192;n=Math.floor(c/81.92),this.setMasterTuning(n),m(`%cMaster Fine Tuning. Cents: %c${n}`,r.info,r.value);break;case 4:n=(t[5]-64)*100,this.setMasterTuning(n),m(`%cMaster Coarse Tuning. Cents: %c${n}`,r.info,r.value);break;default:L(`%cUnrecognized MIDI Device Control Real-time message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(m("%cGM system on",r.info),this.system="gm"):t[3]===3?(m("%cGM2 system on",r.info),this.system="gm2"):(m("%cGM system off, defaulting to GS",r.info),this.system="gs");break;case 8:switch(t[3]){case 2:case 7:let o=4;t[3]===7&&o++;let i=t[o++],C=t[o++];for(let B=0;B>1&1)===1&&this.setOctaveTuning(15+A,c);for(let B=0;B<7;B++)(t[5]>>B&1)===1&&this.setOctaveTuning(7+B+A,c);for(let B=0;B<7;B++)(t[6]>>B&1)===1&&this.setOctaveTuning(B+A,c);m(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${c.join(" ")}`,r.info,r.value);break;default:L(`%cUnrecognized MIDI Tuning standard message: %c${lA(t)}`,r.warn,r.unrecognized);break}break;default:L(`%cUnrecognized MIDI Realtime/non realtime message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 65:let s=function(){L(`%cUnrecognized Roland %cGS %cSysEx: %c${lA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let n=t[7];if(t[6]===127){n===0?(m("%cGS Reset received!",r.info),this.resetAllControllers(!1),this.system="gs"):n===127&&(m("%cGS system off, switching to GM2",r.info),this.resetAllControllers(!1),this.system="gm2");return}else if(t[4]===64){if((t[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A;switch(t[6]){default:s();break;case 21:let i=n>0&&t[5]>>4;this.setDrums(o,i),m(`%cChannel %c${o}%c ${i?"is now a drum channel":"now isn't a drum channel"}%c via: %c${lA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=n-64;this.transposeChannel(o,C),m(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${lA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let c=n;c===0&&(c=Math.floor(Math.random()*128)),this.controllerChange(o,p.pan,c);break;case 33:this.controllerChange(o,p.effects3Depth,n);break;case 34:this.controllerChange(o,p.effects1Depth,n);break;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let 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(n,p.bankSelect,o);break;case 2:this.controllerChange(n,p.lsbForControl0BankSelect,o);break;case 3:this.programChange(n,o);break;case 8:let i=this.workletProcessorChannels[n];if(i.drumChannel)return;let C=o-64;i.channelTransposeKeyShift=C;break;case 11:this.controllerChange(n,p.mainVolume,o);break;case 14:let c=o;c===0&&(c=Math.floor(Math.random()*127)),this.controllerChange(n,p.pan,c);break;case 19:this.controllerChange(n,p.effects1Depth,o);break;case 18:this.controllerChange(n,p.effects3Depth,o);break;default:L(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&L(`%cUnrecognized Yamaha XG SysEx: %c${lA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&L(`%cUnrecognized Yamaha SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break}}function In(t,A,e){if(A.transformAmount===0)return A.currentValue=0,0;let s;if(A.sourceUsesCC)s=t[A.sourceIndex];else{let c=A.sourceIndex+EA;switch(A.sourceIndex){case P.noController:s=16383;break;case P.noteOnKeyNum:s=e.midiNote<<7;break;case P.noteOnVelocity:s=e.velocity<<7;break;case P.polyPressure:s=e.pressure<<7;break;default:s=t[c];break}}let n=dA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let c=A.secSrcIndex+EA;switch(A.secSrcIndex){case P.noController:o=16383;break;case P.noteOnKeyNum:o=e.midiNote<<7;break;case P.noteOnVelocity:o=e.velocity<<7;break;case P.polyPressure:o=e.pressure<<7;break;default:o=t[c]}}let i=dA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=n*i*A.transformAmount;return A.transformType===2&&(C=Math.abs(C)),A.currentValue=C,C}function XA(t,A,e=-1,s=0){let n=t.modulators,o=t.generators,i=t.modulatedGenerators;if(YA.recalculate(t),e===-1){i.set(o),n.forEach(B=>{let d=b[B.modulatorDestination],h=i[B.modulatorDestination]+In(A,B,t);i[B.modulatorDestination]=Math.max(d.min,Math.min(h,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]),c=new Set;n.forEach(B=>{if(B.sourceUsesCC===e&&B.sourceIndex===s||B.secSrcUsesCC===e&&B.secSrcIndex===s){let d=B.modulatorDestination;c.has(d)||(i[d]=o[d],In(A,B,t),n.forEach(h=>{if(h.modulatorDestination===d){let l=b[B.modulatorDestination],u=i[B.modulatorDestination]+h.currentValue;i[B.modulatorDestination]=Math.max(l.min,Math.min(u,l.max))}}),c.add(d))}}),[...c].some(B=>C.has(B))&&LA.recalculate(t)}var dA=[];for(let t=0;t<4;t++){dA[t]=[[new Float32Array(gA),new Float32Array(gA)],[new Float32Array(gA),new Float32Array(gA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||i.isMuted)return;let C=A+i.channelTransposeKeyShift;if(A>127||A<0)return;let c=i.preset.program;this.tunings[c]?.[A]?.midiNote>=0&&(C=this.tunings[c]?.[A].midiNote),i.velocityOverride>0&&(e=i.velocityOverride);let B=this.getWorkletVoices(t,C,e,i,o,s),d=i.voices;B.forEach(h=>{let l=h.generators[g.exclusiveClass];l!==0&&d.forEach(G=>{G.generators[g.exclusiveClass]===l&&(this.releaseVoice(G),G.modulatedGenerators[g.releaseVolEnv]=-7e3,G.modulatedGenerators[g.releaseModEnv]=-7e3,LA.recalculate(G),YA.recalculate(G))}),XA(h,i.midiControllers);let u=h.modulatedGenerators[g.startAddrsOffset]+h.modulatedGenerators[g.startAddrsCoarseOffset]*32768,D=h.modulatedGenerators[g.endAddrOffset]+h.modulatedGenerators[g.endAddrsCoarseOffset]*32768,y=h.modulatedGenerators[g.startloopAddrsOffset]+h.modulatedGenerators[g.startloopAddrsCoarseOffset]*32768,w=h.modulatedGenerators[g.endloopAddrsOffset]+h.modulatedGenerators[g.endloopAddrsCoarseOffset]*32768,S=h.sample,N=G=>Math.max(0,Math.min(S.sampleData.length-1,G));if(S.cursor=N(S.cursor+u),S.end=N(S.end+D),S.loopStart=N(S.loopStart+y),S.loopEnd=N(S.loopEnd+w),S.loopEndthis.voiceCap&&this.voiceKilling(B.length),d.push(...B),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Cn(t,A){if(A>127||A<0){L("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift,s=this.workletProcessorChannels[t].preset.program;if(this.tunings[s]?.[A]?.midiNote>=0&&(e=this.tunings[s]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(o=>{o.midiNote!==e||o.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function En(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.midiNote===A&&(e.modulatedGenerators[g.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function Bn(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[t].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function hn(t=!1){m("%cStop all received!",r.info);for(let A=0;AXA(n,this.workletProcessorChannels[t].midiControllers,0,P.pitchWheel)),this.sendChannelProperties()}function pn(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[EA+P.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(s=>XA(s,e.midiControllers,0,P.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function Sn(t,A,e){this.workletProcessorChannels[t].voices.forEach(s=>{s.midiNote===A&&(s.pressure=e,XA(s,this.workletProcessorChannels[t].midiControllers,0,P.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function yn(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function Dn(t,A,e,s=!1){let n=this.workletProcessorChannels[t];if(n===void 0){L(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>127){if(!s)return;switch(A){default:return;case wt.velocityOverride:n.velocityOverride=e}}if(A>=p.lsbForControl1ModulationWheel&&A<=p.lsbForControl13EffectControl2&&A!==p.lsbForControl6DataEntry){let o=A-32;if(n.lockedControllers[o])return;n.midiControllers[o]=n.midiControllers[o]&16256|e&127,n.voices.forEach(i=>XA(i,n.midiControllers,1,o))}switch(A){case p.allNotesOff:this.stopAll(t);break;case p.allSoundOff:this.stopAll(t,!0);break;case p.bankSelect:let o=e;if(!s){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==DA&&this.setDrums(t,!1);break;case"gm2":o===120&&(n.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}n.drumChannel&&(o=128),o===128&&!n.drumChannel&&(o=n.midiControllers[p.bankSelect])}n.midiControllers[p.bankSelect]=o;break;case p.lsbForControl0BankSelect:this.system==="xg"?n.drumChannel||e!==127&&(n.midiControllers[p.bankSelect]=e):this.system==="gm2"&&(n.midiControllers[p.bankSelect]=e);break;case p.RPNLsb:n.RPValue=n.RPValue<<7|e,n.dataEntryState=uA.RPFine;break;case p.RPNMsb:n.RPValue=e,n.dataEntryState=uA.RPCoarse;break;case p.NRPNMsb:n.NRPCoarse=e,n.dataEntryState=uA.NRPCoarse;break;case p.NRPNLsb:n.NRPFine=e,n.dataEntryState=uA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(t,e);break;case p.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case p.resetAllControllers:this.resetControllers(t);break;case p.sustainPedal:e>=64?n.holdPedal=!0:(n.holdPedal=!1,n.sustainedVoices.forEach(i=>{this.releaseVoice(i)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=e<<7,n.voices.forEach(i=>XA(i,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function kn(t){this.midiVolume=t,this.setMasterPan(this.pan)}function wn(t){this.masterGain=t*Ut,this.setMasterPan(this.pan)}function Fn(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function Rn(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function Gn(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 xn(t,A,e,s){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=s,this.workletProcessorChannels[t].channelVibrato.depth=A)}function Mn(t,A){let e=this.workletProcessorChannels[t],s=()=>{e.channelVibrato.delay===0&&e.channelVibrato.rate===0&&e.channelVibrato.depth===0&&(e.channelVibrato.depth=50,e.channelVibrato.rate=8,e.channelVibrato.delay=.6)};switch(e.dataEntryState){default:case uA.Idle:break;case uA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;L(`%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;L(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16)} 0x${e.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(A===64)return;s(),e.channelVibrato.rate=A/64*8,m(`%cVibrato rate for %c${t}%c is now set to %c${A} = ${e.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(A===64)return;s(),e.channelVibrato.depth=A/2,m(`%cVibrato depth for %c${t}%c is now set to %c${A} = ${e.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(A===64)return;s(),e.channelVibrato.delay=A/64/3,m(`%cVibrato delay for %c${t}%c is now set to %c${A} = ${e.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let i=A;this.controllerChange(t,p.brightness,A),m(`%cFilter cutoff for %c${t}%c is now set to %c${i}`,r.info,r.recognized,r.info,r.value)}break;case 24:let n=A-64;e.keyCentTuning[e.NRPFine]=n*100,m(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${n}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,p.effects1Depth,o),m(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:L(`%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+P.pitchWheelRange]=A<<7,m(`%cChannel ${t} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(t,A-64);break;case 1:this.setChannelTuning(t,A-64,!1);break;case 5:this.setModulationDepth(t,A*100);break;case 16383:this.resetParameters(t);break}}}function Nn(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case uA.RPCoarse:case uA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[EA+P.pitchWheelRange]|=A;let s=(e.midiControllers[EA+P.pitchWheelRange]>>7)+A/127;m(`%cChannel ${t} bend range. Semitones: %c${s}`,r.info,r.value);break;case 1:let o=e.customControllers[IA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[IA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function bn(t=!0){t&&m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A{this.workletProcessorChannels[A].lockedControllers[n]&&this.callEvent("controllerchange",{channel:A,controllerNumber:n,controllerValue:this.workletProcessorChannels[A].midiControllers[n]>>7})};if(s(p.mainVolume),s(p.pan),s(p.expressionController),s(p.modulationWheel),s(p.effects3Depth),s(p.effects1Depth),s(p.brightness),this.workletProcessorChannels[A].lockedControllers[EA+P.pitchWheel]){let n=this.workletProcessorChannels[A].midiControllers[EA+P.pitchWheel],o=n>>7,i=n&127;this.callEvent("pitchwheel",{channel:A,MSB:o,LSB:i})}}this.tunings=[],this.tunings=[];for(let A=0;A<127;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Oe}function Ln(t){let A=this.workletProcessorChannels[t],s=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(PA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let n=A.customControllers[IA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[IA.channelTransposeFine]=n,this.resetParameters(t)}function Un(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=uA.Idle}function Tn(){let t=4;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,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+n),0);let A=new H(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=e;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue),e++}return cA(A,0),sA(new AA("igen",A.length,A))}function Hn(t,A,e,s,n){let o=this.samples.map((B,d)=>{e&&B.compressSample(s,n);let h=B.getRawData();return m(`%cEncoded sample %c${d}. ${B.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),h}),i=this.samples.reduce((B,d,h)=>B+o[h].length+46,0),C=new H(i);this.samples.forEach((B,d)=>{let h=o[d],l,u,D=h.length;B.isCompressed?(l=C.currentIndex,u=l+h.length):(l=C.currentIndex/2,u=l+h.length/2,D+=46),t.push(l),C.set(h,C.currentIndex),C.currentIndex+=D,A.push(u)});let c=sA(new AA("smpl",C.length,C),new H([115,100,116,97]));return sA(new AA("LIST",c.length,c))}function Yn(t,A){let s=new H(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{wA(s,n.sampleName,20);let i=t[o];cA(s,i);let C=A[o];cA(s,C);let c=n.sampleLoopStartIndex/2+i,B=n.sampleLoopEndIndex/2+i;n.isCompressed&&(c-=i,B-=i),cA(s,c),cA(s,B),cA(s,n.sampleRate),s[s.currentIndex++]=n.samplePitch,s[s.currentIndex++]=n.samplePitchCorrection,Y(s,n.sampleLink),Y(s,n.sampleType)}),wA(s,"EOS",46),sA(new AA("shdr",s.length,s))}function Jn(){let t=10;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),sA(new AA("imod",A.length,A))}function vn(){let t=this.instruments.reduce((o,i)=>i.instrumentZones.length*4+o,4),A=new H(t),e=0,s=0,n=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let i of o.instrumentZones)i.zoneID=e,Y(A,s),Y(A,n),s+=i.generators.length,n+=i.modulators.length,e++}return Y(A,s),Y(A,n),sA(new AA("ibag",A.length,A))}function qn(){let t=this.instruments.length*22+22,A=new H(t),e=0,s=0;for(let n of this.instruments)wA(A,n.instrumentName,20),Y(A,e),e+=n.instrumentZones.length,n.instrumentID=s,s++;return wA(A,"EOI",20),Y(A,e),sA(new AA("inst",A.length,A))}function Pn(){let t=4;for(let s of this.presets)t+=s.presetZones.reduce((n,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+n),0);let A=new H(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=e;for(let o of n.generators)Y(A,o.generatorType),Y(A,o.generatorValue);e+=n.generators.length}return Y(A,0),Y(A,0),sA(new AA("pgen",A.length,A))}function Kn(){let t=10;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new H(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),sA(new AA("pmod",A.length,A))}function Vn(){let t=this.presets.reduce((o,i)=>i.presetZones.length*4+o,4),A=new H(t),e=0,s=0,n=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let i of o.presetZones)i.zoneID=e,Y(A,s),Y(A,n),s+=i.generators.length,n+=i.modulators.length,e++}return Y(A,s),Y(A,n),sA(new AA("pbag",A.length,A))}function On(){let t=this.presets.length*38+38,A=new H(t),e=0;for(let s of this.presets)wA(A,s.presetName,20),Y(A,s.program),Y(A,s.bank),Y(A,e),cA(A,s.library),cA(A,s.genre),cA(A,s.morphology),e+=s.presetZones.length;return wA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,e),cA(A,0),cA(A,0),cA(A,0),sA(new AA("phdr",A.length,A))}var Yo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Zn(t=Yo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");SA("%cSaving soundfont...",r.info),m(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),m("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[K,W]of Object.entries(this.soundFontInfo))if(K==="ifil"||K==="iver"){let I=parseInt(W.split(".")[0]),nA=parseInt(W.split(".")[1]),j=new H(4);Y(j,I),Y(j,nA),A.push(sA(new AA(K,4,j)))}else if(K==="DMOD")A.push(sA(new AA(K,W.length,W)));else{let I=new H(W.length);wA(I,W),A.push(sA(new AA(K,W.length,I)))}let e=ke([new H([73,78,70,79]),...A]),s=sA(new AA("LIST",e.length,e));m("%cWriting SDTA...",r.info);let n=[],o=[],i=Hn.call(this,n,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let C=Yn.call(this,n,o);m("%cWriting IGEN...",r.info);let c=Tn.call(this);m("%cWriting IMOD...",r.info);let B=Jn.call(this);m("%cWriting IBAG...",r.info);let d=vn.call(this);m("%cWriting INST...",r.info);let h=qn.call(this),l=Pn.call(this);m("%cWriting PMOD...",r.info);let u=Kn.call(this);m("%cWriting PBAG...",r.info);let D=Vn.call(this);m("%cWriting PHDR...",r.info);let y=On.call(this),w=ke([new H([112,100,116,97]),y,D,u,l,h,d,B,c,C]),S=sA(new AA("LIST",w.length,w));m("%cWriting the output file...",r.info);let N=ke([new H([115,102,98,107]),s,i,S]),G=sA(new AA("RIFF",N.length,N));return m(`%cSaved succesfully! Final file size: %c${G.length}`,r.info,r.recognized),X(),G}var ne=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Pe.map(e=>$.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}getPresetNoFallback(A,e,s=!1){let n=this.presets.find(o=>o.bank===A&&o.program===e);if(n)return n;if(s!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPreset(A,e){let s=this.presets.find(n=>n.bank===A&&n.program===e);return s||(A===128?(s=this.presets.find(n=>n.bank===128&&n.program===e),s||(s=this.presets.find(n=>n.bank===128))):s=this.presets.find(n=>n.program===e&&n.bank!==128),s&&L(`%cPreset ${A}.${e} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,r.warn,r.recognized)),s||(L(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),s=this.presets[0]),s}getPresetByName(A){let e=this.presets.find(s=>s.presetName===A);return e||(L("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}static mergeSoundfonts(...A){let e=A.shift(),s=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{s.find(i=>i.bank===o.bank&&i.program===o.program)===void 0&&s.push(o)});return new t({presets:s,info:e.soundFontInfo})}};ne.prototype.write=Zn;function Xn(t){SA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let s=A;s{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,e){let s=this.foundSamplesAndGenerators[A][e];if(s)return s;if(this.presetZones.length<1)return[];function n(h,l,u){return u>=h&&u<=l}function o(h,l){h.push(...l.filter(u=>!h.find(D=>D.generatorType===u.generatorType)))}function i(h,l){h.push(...l.filter(u=>!h.find(D=>$.isIdentical(u,D))))}let C=[],c=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],B=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(h=>n(h.keyRange.min,h.keyRange.max,A)&&n(h.velRange.min,h.velRange.max,e)&&!h.isGlobal).forEach(h=>{if(h.instrument.instrumentZones.length<1)return;let l=h.generators,u=h.modulators,D=h.instrument.instrumentZones[0].isGlobal?[...h.instrument.instrumentZones[0].generators]:[],y=h.instrument.instrumentZones[0].isGlobal?[...h.instrument.instrumentZones[0].modulators]:[];h.instrument.instrumentZones.filter(S=>n(S.keyRange.min,S.keyRange.max,A)&&n(S.velRange.min,S.velRange.max,e)&&!S.isGlobal).forEach(S=>{let N=[...S.generators],G=[...S.modulators];o(l,c),o(N,D),i(u,B),i(G,y),i(G,this.defaultModulators);let K=[...G];for(let W=0;W$.isIdentical(I,j));nA!==-1?K[nA]=K[nA].sumTransform(I):K.push(I)}C.push({instrumentGenerators:N,presetGenerators:l,modulators:K,sample:S.sample,sampleID:S.generators.find(W=>W.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}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 n=new le;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function Wn(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 X(),new Error("No instrument header!");let s=k(e.chunkData,4),n=k(e.chunkData,4),o=k(e.chunkData,4),i=new At(n,o),C="unnamedPreset",c=yA(A,"INFO");if(c){let u=O(c.chunkData);for(;u.header!=="INAM";)u=O(c.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=yA(A,"lrgn");if(!B)throw X(),new Error("No region list!");let d=new $A;d.isGlobal=!0;let h=yA(A,"lart"),l=yA(A,"lar2");this.readLart(h,l,d),i.DLSInstrument.instrumentZones.push(d);for(let u=0;u>10&15;S===QA.linear&&w!==QA.linear&&(S=w);let N=s>>14&1,G=s>>15&1;i===g.initialAttenuation&&(G=!G),h=TA(S,N,G,C.isCC,C.enum)}let l=s>>4&15,u=s>>8&1,D=s>>9&1,y=TA(l,u,D,d.isCC,d.enum);if(c){let w=y;y=h,h=w}return new $({srcEnum:h,secSrcEnum:y,dest:i,transform:0,amt:n})}function Tt(t,A){let e=t.chunkData,s=[],n=[];k(e,4);let o=k(e,4);for(let i=0;i>16;if(C===0&&c===0&&d===0){let u;switch(B){case x.pan:u=new U(g.pan,l);break;case x.gain:u=new U(g.initialAttenuation,-l*10/.4);break;case x.filterCutoff:u=new U(g.initialFilterFc,l);break;case x.filterQ:u=new U(g.initialFilterQ,l);break;case x.modLfoFreq:u=new U(g.freqModLFO,l);break;case x.modLfoDelay:u=new U(g.delayModLFO,l);break;case x.vibLfoFreq:u=new U(g.freqVibLFO,l);break;case x.vibLfoDelay:u=new U(g.delayVibLFO,l);break;case x.volEnvDelay:u=new U(g.delayVolEnv,l);break;case x.volEnvAttack:u=new U(g.attackVolEnv,l);break;case x.volEnvHold:u=new U(g.holdVolEnv,l);break;case x.volEnvDecay:u=new U(g.decayVolEnv,l);break;case x.volEnvRelease:u=new U(g.releaseVolEnv,l);break;case x.volEnvSustain:let D=(1e3-l)/10;u=new U(g.sustainVolEnv,D*10);break;case x.modEnvDelay:u=new U(g.delayModEnv,l);break;case x.modEnvAttack:u=new U(g.attackModEnv,l);break;case x.modEnvHold:u=new U(g.holdModEnv,l);break;case x.modEnvDecay:u=new U(g.decayModEnv,l);break;case x.modEnvRelease:u=new U(g.releaseModEnv,l);break;case x.modEnvSustain:let y=1e3-l;u=new U(g.sustainModEnv,y);break;case x.reverbSend:u=new U(g.reverbEffectsSend,l);break;case x.chorusSend:u=new U(g.chorusEffectsSend,l);break;case x.pitch:let w=Math.floor(l/100),S=Math.floor(l-w*100);u=new U(g.fineTune,S),s.push(new U(g.coarseTune,w));break}u&&s.push(u)}else{let u=!0;if(c===z.none)if(C===z.modLfo&&B===x.pitch)s.push(new U(g.modLfoToPitch,l));else if(C===z.modLfo&&B===x.gain)s.push(new U(g.modLfoToVolume,l));else if(C===z.modLfo&&B===x.filterCutoff)s.push(new U(g.modLfoToFilterFc,l));else if(C===z.vibratoLfo&&B===x.pitch)s.push(new U(g.vibLfoToPitch,l));else if(C===z.modEnv&&B===x.pitch)s.push(new U(g.modEnvToPitch,l));else if(C===z.modEnv&&B===x.filterCutoff)s.push(new U(g.modEnvToFilterFc,l));else if(C===z.keyNum&&B===x.volEnvHold){s.push(new U(g.keyNumToVolEnvHold,l/-128));let D=Math.round(60/128*l);s.forEach(y=>{y.generatorType===g.holdVolEnv&&(y.generatorValue+=D)})}else if(C===z.keyNum&&B===x.volEnvDecay){s.push(new U(g.keyNumToVolEnvDecay,l/-128));let D=Math.round(60/128*l);s.forEach(y=>{y.generatorType===g.decayVolEnv&&(y.generatorValue+=D)})}else if(C===z.keyNum&&B===x.modEnvHold){s.push(new U(g.keyNumToModEnvHold,l/-128));let D=Math.round(60/128*l);s.forEach(y=>{y.generatorType===g.holdModEnv&&(y.generatorValue+=D)})}else if(C===z.keyNum&&B===x.modEnvDecay){s.push(new U(g.keyNumToModEnvDecay,l/-128));let D=Math.round(60/128*l);s.forEach(y=>{y.generatorType===g.decayModEnv&&(y.generatorValue+=D)})}else u=!1;else u=!1;if(u===!1){let D=zn(C,c,B,d,l);D?(n.push(D),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):L("Failed converting to SF2 Modulator!")}}}return n.find(i=>i.modulatorDestination===g.reverbEffectsSend)===void 0&&n.push(new $({srcEnum:219,dest:g.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(i=>i.modulatorDestination===g.chorusEffectsSend)===void 0&&n.push(new $({srcEnum:221,dest:g.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&n.push(new $({srcEnum:129,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new $({srcEnum:13,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:n,generators:s}}function jn(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(j=>j.header==="rgnh"),s=k(e.chunkData,2),n=k(e.chunkData,2),o=k(e.chunkData,2),i=k(e.chunkData,2),C=new et({min:s,max:n},{min:o,max:i});k(e.chunkData,2);let c=k(e.chunkData,2);c!==0&&C.generators.push(new U(g.exclusiveClass,c));let B=yA(A,"lart"),d=yA(A,"lar2");this.readLart(B,d,C),C.isGlobal=!1;let h=A.find(j=>j.header==="wsmp");k(h.chunkData,4);let l=k(h.chunkData,2),u=zA(h.chunkData[h.chunkData.currentIndex++],h.chunkData[h.chunkData.currentIndex++]),y=(k(h.chunkData,4)|0)/-655360;k(h.chunkData,4);let w=k(h.chunkData,4),S,N={start:0,end:0};if(w===0)S=0;else{k(h.chunkData,4),k(h.chunkData,4)===0?S=1:S=3,N.start=k(h.chunkData,4);let J=k(h.chunkData,4);N.end=N.start+J}let G=A.find(j=>j.header==="wlnk");if(G===void 0)return;k(G.chunkData,2),k(G.chunkData,2),k(G.chunkData,4);let K=k(G.chunkData,4),W=this.samples[K];if(W===void 0)throw new Error("Invalid sample ID!");let nA=(y||W.sampleDbAttenuation)*10/.4;return C.setWavesample(nA,S,N,l,W,K,u),C}var de=class{constructor(A,e,s,n,o,i,C,c){this.sampleName=A,this.sampleRate=e,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=i,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=c,this.isCompressed=(i&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,e){if(!this.isCompressed)try{this.compressedData=e([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{L(`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{constructor(A,e,s,n,o,i,C,c){super(A,e,s,n,0,1,o*2,(i-1)*2),this.sampleData=C,this.sampleDbAttenuation=c}getAudioData(){return this.sampleData}sampleDbAttenuation;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 Ao(t){SA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexJ.header==="fmt ");if(!n)throw new Error("No fmt chunk in the wave file!");if(k(n.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(k(n.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=k(n.chunkData,4);k(n.chunkData,4),k(n.chunkData,2);let c=k(n.chunkData,2),B=c/8,d=Math.pow(2,B*8-1),h=Math.pow(2,B*8),l,u=!1;c===8?(l=255,u=!0):l=d;let D=s.find(J=>J.header==="data");if(!D)throw new Error("No data chunk in the wave chunk!");let y=D.size/B,w=new Float32Array(y);for(let J=0;J=d&&(Z-=h),w[J]=Z/l)}let S=60,N=0,G=0,K=w.length-1,W=0,I=s.find(J=>J.header==="wsmp");if(I){if(k(I.chunkData,4),S=k(I.chunkData,2),N=zA(I.chunkData[I.chunkData.currentIndex++],I.chunkData[I.chunkData.currentIndex++]),W=(k(I.chunkData,4)|0)/-655360,k(I.chunkData,4),k(I.chunkData,4)===1){k(I.chunkData,8),G=k(I.chunkData,4);let CA=k(I.chunkData,4);K=G+CA}}else L("No wsmp chunk in wave... using sane defaults.");let nA=yA(s,"INFO"),j=`Unnamed ${A}`;if(nA){let J=O(nA.chunkData);for(;J.header!=="INAM"&&nA.chunkData.currentIndexc.header==="colh");if(!o)throw X(),new Error("No colh chunk!");this.instrumentAmount=k(o.chunkData,4),m(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let i=yA(s,"wvpl");this.readDLSSamples(i);let C=yA(s,"lins");if(!C)throw X(),new Error("No lins chunk!");this.readDLSInstrumentList(C),this.presets.sort((c,B)=>c.program-B.program+(c.bank-B.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X()}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=Xn;WA.prototype.readDLSInstrument=Wn;WA.prototype.readRegion=$n;WA.prototype.readLart=jn;WA.prototype.readDLSSamples=Ao;var Ht=class extends de{constructor(A,e,s,n,o,i,C,c,B,d,h,l,u){super(A,i,C,c,B,d,n-e,o-e),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=s,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=h,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex,this.sampleLoopEndIndex+=this.sampleStartIndex,this.sampleLength=99999999),this.isDataRaw=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,s=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let n=OA.decode(s.buffer);this.sampleData=n.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return L("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,s=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let n=0;nt.chunkData.currentIndex;){let o=qo(n,t.chunkData,A,e);s.push(o),n++}return s.length>1&&s.pop(),s}function qo(t,A,e,s){let n=V(A,20),o=k(A,4)*2,i=k(A,4)*2,C=k(A,4)*2,c=k(A,4)*2,B=k(A,4),d=A[A.currentIndex++];d===255&&(d=60);let h=us(A[A.currentIndex++]),l=k(A,2),u=k(A,2);return new Ht(n,o,i,C,c,B,d,h,l,u,e,t,s)}var Yt=class extends ue{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=k(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let s=this.instrumentZoneIndex;st.chunkData.currentIndex;){let s=new Yt(t);if(e.length>0){let n=s.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(n,A)}e.push(s)}return e.length>1&&e.pop(),e}var Jt=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=k(A,2),this.modulatorZoneStartIndex=k(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===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 so(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Jt(t.chunkData);if(n.length>0){let i=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(i,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(e),n[n.length-1].getSample(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var vt=class extends le{constructor(A){super(),this.generatorZoneStartIndex=k(A,2),this.modulatorZoneStartIndex=k(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===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 no(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new vt(t.chunkData);if(n.length>0){let i=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(i,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(e),n[n.length-1].getInstrument(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var qt=class extends ce{constructor(A,e){super(e),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=k(A.chunkData,2),this.bank=k(A.chunkData,2),this.presetZoneStartIndex=k(A.chunkData,2),this.library=k(A.chunkData,4),this.genre=k(A.chunkData,4),this.morphology=k(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;st.chunkData.currentIndex;){let n=new qt(t,e);if(s.length>0){let o=n.presetZoneStartIndex-s[s.length-1].presetZoneStartIndex;s[s.length-1].getPresetZones(o,A)}s.push(n)}return s.length>1&&s.pop(),s}var st=class extends ne{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new H(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw X(),new TypeError("No data!");let s=O(this.dataArray,!1);this.verifyHeader(s,"riff");let n=V(this.dataArray,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw X(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let o=n==="sfpk",i=O(this.dataArray);for(this.verifyHeader(i,"list"),V(i.chunkData,4);i.chunkData.length>i.chunkData.currentIndex;){let Z=O(i.chunkData),CA;switch(Z.header.toLowerCase()){case"ifil":case"iver":CA=`${k(Z.chunkData,2)}.${k(Z.chunkData,2)}`,this.soundFontInfo[Z.header]=CA;break;case"icmt":CA=V(Z.chunkData,Z.chunkData.length,void 0,!1),this.soundFontInfo[Z.header]=CA;break;case"dmod":let oA=Ke(Z);oA.pop(),CA=`Modulators: ${oA.length}`;let fA=this.defaultModulators;this.defaultModulators=oA,this.defaultModulators.push(...fA.filter(Me=>!this.defaultModulators.find(RA=>$.isIdentical(Me,RA)))),this.soundFontInfo[Z.header]=Z.chunkData;break;default:CA=V(Z.chunkData,Z.chunkData.length),this.soundFontInfo[Z.header]=CA}m(`%c"${Z.header}": %c"${CA}"`,r.info,r.recognized)}let C=O(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(V(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",r.warn);let c=O(this.dataArray,!1);this.verifyHeader(c,"smpl");let B;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{B=OA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(Z){throw X(),new Error(`SF2Pack Ogg Vorbis decode error: ${Z}`)}m(`%cDecoded the smpl chunk! Length: %c${B.length}`,r.info,r.value)}else B=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,m("%cLoading preset data chunk...",r.warn);let d=O(this.dataArray);this.verifyHeader(d,"list"),V(d.chunkData,4);let h=O(d.chunkData);this.verifyHeader(h,"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 w=O(d.chunkData);this.verifyHeader(w,"ibag");let S=O(d.chunkData);this.verifyHeader(S,"imod");let b=O(d.chunkData);this.verifyHeader(b,"igen");let R=O(d.chunkData);this.verifyHeader(R,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...eo(R,B,!o));let K=pt(b),W=Ke(S),I=so(w,K,W,this.samples);this.instruments=to(y,I);let nA=pt(D),j=Ke(u),J=no(l,nA,j,this.instruments);this.presets.push(...oo(h,J,this.defaultModulators)),this.presets.sort((Z,CA)=>Z.program-CA.program+(Z.bank-CA.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X(),o&&delete this.dataArray}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Ge(t){let A=t.slice(8,12),e=new H(A);return V(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new st(t,!1)}function ro(t,A,e=!1){let s=this.workletProcessorChannels[t];if(s===void 0){L(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[p.bankSelect],o,i;if(this.overrideSoundfont){let C=n===128?128:n-this.soundfontBankOffset,c=this.overrideSoundfont.getPresetNoFallback(C,A);c?(o=n,i=c,s.presetUsesOverride=!0):(i=this.soundfontManager.getPreset(n,A),o=i.bank,s.presetUsesOverride=!1)}else i=this.soundfontManager.getPreset(n,A),o=i.bank,s.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,s=this.overrideSoundfont.getPresetNoFallback(e,A);if(s)return s}return this.soundfontManager.getPreset(t,A)}function ao(t,A){if(!this.workletProcessorChannels[t].lockPreset){delete this.workletProcessorChannels[t].preset,this.workletProcessorChannels[t].preset=A,this.workletProcessorChannels[t].cachedVoices=[];for(let e=0;e<128;e++)this.workletProcessorChannels[t].cachedVoices.push([])}}function Io(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(128,e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(e.midiControllers[p.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function go(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,s=t.find(n=>n.bank===e&&n.program===A.program);s!==void 0?s.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function Co(t=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let e=0;e{this.programChange(s,e.preset.program)}),this.post({messageType:pA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",r.recognized)}function Bo(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 ho(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:e.preset.bank,lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:pA.synthesizerSnapshot,messageData:A})}function Qo(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation;this.workletProcessorChannels.length{let s=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),s.midiControllers=A.midiControllers,s.lockedControllers=A.lockedControllers,s.customControllers=A.customControllers,s.channelVibrato=A.channelVibrato,s.lockGSNRPNParams=A.lockVibrato,s.channelTransposeKeyShift=A.channelTransposeKeyShift,s.channelOctaveTuning=A.channelOctaveTuning,s.lockPreset=!1,s.midiControllers[p.bankSelect]=A.bank,this.programChange(e,A.program),s.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",r.info)}var nt=class{constructor(A,e){this.ready=e,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(e=>{e.soundfont.setSampleIDOffset(A),A+=e.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let e=this.soundfontList.length-1;e>=0;e--){let s=this.soundfontList[e],n=new Set;for(let o of s.soundfont.presets){let i=`${o.bank+s.bankOffset}-${o.program}`;n.has(i)||(n.add(i),A[i]=o.presetName)}}this.presetList=[];for(let[e,s]of Object.entries(A)){let n=e.split("-");this.presetList.push({presetName:s,program:parseInt(n[1]),bank:parseInt(n[0])})}}handleMessage(A,e){switch(A){case Ie.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ie.reloadSoundFont:this.reloadManager(e);break;case Ie.deleteSoundFont:this.deleteSoundFont(e);break;case Ie.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ge(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){L("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(s=>s.id===A);if(e===-1){L(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[e].soundfont.presets,delete this.soundfontList[e].soundfont.instruments,delete this.soundfontList[e].soundfont.samples,this.soundfontList.splice(e,1),this.generatePresetList()}addNewSoundFont(A,e,s){if(this.soundfontList.find(n=>n.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Ge(A),bankOffset:s}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,s)=>A.indexOf(e.id)-A.indexOf(s.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let s of this.soundfontList){let n=s.soundfont.getPresetNoFallback(A-s.bankOffset,e);if(n!==void 0)return n}if(A!==128){for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.program===e);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}else{for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.bank===128);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}}};var ot=class{constructor(A,e,s,n,o,i,C,c){this.sampleData=A,this.playbackStep=e,this.cursor=s,this.rootKey=n,this.loopStart=o,this.loopEnd=i,this.end=C,this.loopingMode=c,this.isLooping=this.loopingMode===1||this.loopingMode===3}sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1},xe=class t{constructor(A,e,s,n,o,i,C,c,B){this.sample=e,this.generators=c,this.modulatedGenerators=new Int16Array(c),this.modulators=B,this.velocity=n,this.midiNote=s,this.channelNumber=o,this.startTime=i,this.targetKey=C,this.volumeEnvelope=new LA(A,c[g.sustainVolEnv])}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;static copy(A,e){let s=A.sample,n=new ot(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new t(A.volumeEnvelope.sampleRate,n,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.generators,A.modulators.map(o=>$.copy(o)))}};function co(t,A,e,s,n,o=!1){let i,C=s.cachedVoices[A][e];return C!==void 0?C.map(c=>xe.copy(c,n)):(i=s.preset.getSamplesAndGenerators(A,e).reduce((B,d)=>{if(d.sample.sampleData===void 0)return L(`Discarding invalid sample: ${d.sample.sampleName}`),B;let h=new Int16Array(60);for(let R=0;R<60;R++)h[R]=ds(R,d.presetGenerators,d.instrumentGenerators);h[g.initialAttenuation]=Math.floor(h[g.initialAttenuation]*.4);let l=d.sample.samplePitch;h[g.overridingRootKey]>-1&&(l=h[g.overridingRootKey]);let u=A;h[g.keyNum]>-1&&(u=h[g.keyNum]);let D=d.sample.sampleLoopStartIndex/2,y=d.sample.sampleLoopEndIndex/2,w=h[g.sampleModes],S=d.sample.getAudioData().length;D=Math.min(Math.max(0,D),S),y=Math.min(Math.max(0,y),S),y-D<1&&(w=0);let b=new ot(d.sample.getAudioData(),d.sample.sampleRate/sampleRate*Math.pow(2,d.sample.samplePitchCorrection/1200),0,l,D,y,Math.floor(d.sample.sampleData.length)-1,w);return h[g.velocity]>-1&&(e=h[g.velocity]),o&&ls([{Sample:d.sample.sampleName,Generators:h,Modulators:d.modulators.map(R=>R.debugString()),Velocity:e,TargetKey:u,MidiNote:A,WorkletSample:b}]),B.push(new xe(sampleRate,b,A,e,t,n,u,h,d.modulators.map(R=>$.copy(R)))),B},[]),s.cachedVoices[A][e]=i.map(B=>xe.copy(B,n)),i)}var Lt=.03,Ut=1,T=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 aA(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=Ss,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new nt(A.processorOptions.soundfont,this.postReady.bind(this))}catch(e){throw this.post({messageType:pA.soundfontError,messageData:e}),e}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let e=0;ethis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),OA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",r.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:pA.ready,messageData:void 0})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let s=0;return this.workletProcessorChannels.forEach((n,o)=>{if(n.voices.length<1||n.isMuted)return;let i,C,c,B,d;if(this.oneOutputMode){let l=e[0];i=o%16*2,C=l[i],c=l[i+1]}else i=o%this._outputsAmount+2,C=e[i][0],c=e[i][1],B=e[0],d=e[1];let h=n.voices;n.voices=[],h.forEach(l=>{this.renderVoice(n,l,C,c,B,d),l.finished||n.voices.push(l)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};T.prototype.renderVoice=$s;T.prototype.releaseVoice=en;T.prototype.voiceKilling=An;T.prototype.getWorkletVoices=co;T.prototype.handleMessage=nn;T.prototype.sendChannelProperties=rn;T.prototype.callEvent=on;T.prototype.systemExclusive=an;T.prototype.noteOn=gn;T.prototype.noteOff=Cn;T.prototype.polyPressure=Sn;T.prototype.killNote=En;T.prototype.stopAll=Bn;T.prototype.stopAllChannels=hn;T.prototype.muteChannel=Rn;T.prototype.setVibrato=xn;T.prototype.disableAndLockGSNRPN=Gn;T.prototype.dataEntryCoarse=Mn;T.prototype.dataEntryFine=Nn;T.prototype.createWorkletChannel=fs;T.prototype.controllerChange=Dn;T.prototype.channelPressure=pn;T.prototype.resetAllControllers=bn;T.prototype.resetControllers=Ln;T.prototype.resetParameters=Un;T.prototype.setMasterGain=wn;T.prototype.setMasterPan=Fn;T.prototype.setMIDIVolume=kn;T.prototype.transposeAllChannels=Qn;T.prototype.transposeChannel=cn;T.prototype.setChannelTuning=ln;T.prototype.setChannelTuningSemitones=un;T.prototype.setMasterTuning=dn;T.prototype.setModulationDepth=fn;T.prototype.pitchWheel=mn;T.prototype.setOctaveTuning=yn;T.prototype.programChange=ro;T.prototype.getPreset=io;T.prototype.setPreset=ao;T.prototype.setDrums=Io;T.prototype.reloadSoundFont=Eo;T.prototype.clearSoundFont=Co;T.prototype.setEmbeddedSoundFont=Bo;T.prototype.sendPresetList=go;T.prototype.sendSynthesizerSnapshot=ho;T.prototype.applySynthesizerSnapshot=Qo;registerProcessor(ps,T);m("%cProcessor succesfully registered!",r.recognized); + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X()}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=Xn;WA.prototype.readDLSInstrument=Wn;WA.prototype.readRegion=$n;WA.prototype.readLart=jn;WA.prototype.readDLSSamples=Ao;var Ht=class extends de{constructor(A,e,s,n,o,i,C,c,B,d,h,l,u){super(A,i,C,c,B,d,n-e,o-e),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=s,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=h,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex,this.sampleLoopEndIndex+=this.sampleStartIndex,this.sampleLength=99999999),this.isDataRaw=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,s=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let n=OA.decode(s.buffer);this.sampleData=n.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return L("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,s=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let n=0;nt.chunkData.currentIndex;){let o=qo(n,t.chunkData,A,e);s.push(o),n++}return s.length>1&&s.pop(),s}function qo(t,A,e,s){let n=V(A,20),o=k(A,4)*2,i=k(A,4)*2,C=k(A,4)*2,c=k(A,4)*2,B=k(A,4),d=A[A.currentIndex++];d===255&&(d=60);let h=us(A[A.currentIndex++]),l=k(A,2),u=k(A,2);return new Ht(n,o,i,C,c,B,d,h,l,u,e,t,s)}var Yt=class extends ue{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=k(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let s=this.instrumentZoneIndex;st.chunkData.currentIndex;){let s=new Yt(t);if(e.length>0){let n=s.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(n,A)}e.push(s)}return e.length>1&&e.pop(),e}var Jt=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=k(A,2),this.modulatorZoneStartIndex=k(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===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 so(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Jt(t.chunkData);if(n.length>0){let i=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(i,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(e),n[n.length-1].getSample(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var vt=class extends le{constructor(A){super(),this.generatorZoneStartIndex=k(A,2),this.modulatorZoneStartIndex=k(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===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 no(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new vt(t.chunkData);if(n.length>0){let i=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(i,C),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(e),n[n.length-1].getInstrument(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(o)}return n.length>1&&n.pop(),n}var qt=class extends ce{constructor(A,e){super(e),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=k(A.chunkData,2),this.bank=k(A.chunkData,2),this.presetZoneStartIndex=k(A.chunkData,2),this.library=k(A.chunkData,4),this.genre=k(A.chunkData,4),this.morphology=k(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;st.chunkData.currentIndex;){let n=new qt(t,e);if(s.length>0){let o=n.presetZoneStartIndex-s[s.length-1].presetZoneStartIndex;s[s.length-1].getPresetZones(o,A)}s.push(n)}return s.length>1&&s.pop(),s}var st=class extends ne{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new H(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw X(),new TypeError("No data!");let s=O(this.dataArray,!1);this.verifyHeader(s,"riff");let n=V(this.dataArray,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw X(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let o=n==="sfpk",i=O(this.dataArray);for(this.verifyHeader(i,"list"),V(i.chunkData,4);i.chunkData.length>i.chunkData.currentIndex;){let Z=O(i.chunkData),CA;switch(Z.header.toLowerCase()){case"ifil":case"iver":CA=`${k(Z.chunkData,2)}.${k(Z.chunkData,2)}`,this.soundFontInfo[Z.header]=CA;break;case"icmt":CA=V(Z.chunkData,Z.chunkData.length,void 0,!1),this.soundFontInfo[Z.header]=CA;break;case"dmod":let oA=Ke(Z);oA.pop(),CA=`Modulators: ${oA.length}`;let fA=this.defaultModulators;this.defaultModulators=oA,this.defaultModulators.push(...fA.filter(Me=>!this.defaultModulators.find(RA=>$.isIdentical(Me,RA)))),this.soundFontInfo[Z.header]=Z.chunkData;break;default:CA=V(Z.chunkData,Z.chunkData.length),this.soundFontInfo[Z.header]=CA}m(`%c"${Z.header}": %c"${CA}"`,r.info,r.recognized)}let C=O(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(V(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",r.warn);let c=O(this.dataArray,!1);this.verifyHeader(c,"smpl");let B;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{B=OA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(Z){throw X(),new Error(`SF2Pack Ogg Vorbis decode error: ${Z}`)}m(`%cDecoded the smpl chunk! Length: %c${B.length}`,r.info,r.value)}else B=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,m("%cLoading preset data chunk...",r.warn);let d=O(this.dataArray);this.verifyHeader(d,"list"),V(d.chunkData,4);let h=O(d.chunkData);this.verifyHeader(h,"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 w=O(d.chunkData);this.verifyHeader(w,"ibag");let S=O(d.chunkData);this.verifyHeader(S,"imod");let N=O(d.chunkData);this.verifyHeader(N,"igen");let G=O(d.chunkData);this.verifyHeader(G,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...eo(G,B,!o));let K=pt(N),W=Ke(S),I=so(w,K,W,this.samples);this.instruments=to(y,I);let nA=pt(D),j=Ke(u),J=no(l,nA,j,this.instruments);this.presets.push(...oo(h,J,this.defaultModulators)),this.presets.sort((Z,CA)=>Z.program-CA.program+(Z.bank-CA.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X(),o&&delete this.dataArray}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Ge(t){let A=t.slice(8,12),e=new H(A);return V(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new st(t,!1)}function ro(t,A,e=!1){let s=this.workletProcessorChannels[t];if(s===void 0){L(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[p.bankSelect],o,i;if(this.overrideSoundfont){let C=n===128?128:n-this.soundfontBankOffset,c=this.overrideSoundfont.getPresetNoFallback(C,A);c?(o=n,i=c,s.presetUsesOverride=!0):(i=this.soundfontManager.getPreset(n,A),o=i.bank,s.presetUsesOverride=!1)}else i=this.soundfontManager.getPreset(n,A),o=i.bank,s.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,s=this.overrideSoundfont.getPresetNoFallback(e,A);if(s)return s}return this.soundfontManager.getPreset(t,A)}function ao(t,A){if(!this.workletProcessorChannels[t].lockPreset){delete this.workletProcessorChannels[t].preset,this.workletProcessorChannels[t].preset=A,this.workletProcessorChannels[t].cachedVoices=[];for(let e=0;e<128;e++)this.workletProcessorChannels[t].cachedVoices.push([])}}function Io(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(128,e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(e.midiControllers[p.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function go(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,s=t.find(n=>n.bank===e&&n.program===A.program);s!==void 0?s.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function Co(t=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let e=0;e{this.programChange(s,e.preset.program)}),this.post({messageType:pA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",r.recognized)}function Bo(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 ho(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:e.preset.bank,lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:pA.synthesizerSnapshot,messageData:A})}function Qo(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation;this.workletProcessorChannels.length{let s=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),s.midiControllers=A.midiControllers,s.lockedControllers=A.lockedControllers,s.customControllers=A.customControllers,s.channelVibrato=A.channelVibrato,s.lockGSNRPNParams=A.lockVibrato,s.channelTransposeKeyShift=A.channelTransposeKeyShift,s.channelOctaveTuning=A.channelOctaveTuning,s.lockPreset=!1,s.midiControllers[p.bankSelect]=A.bank,this.programChange(e,A.program),s.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",r.info)}var nt=class{constructor(A,e){this.ready=e,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(e=>{e.soundfont.setSampleIDOffset(A),A+=e.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let e=this.soundfontList.length-1;e>=0;e--){let s=this.soundfontList[e],n=new Set;for(let o of s.soundfont.presets){let i=`${o.bank+s.bankOffset}-${o.program}`;n.has(i)||(n.add(i),A[i]=o.presetName)}}this.presetList=[];for(let[e,s]of Object.entries(A)){let n=e.split("-");this.presetList.push({presetName:s,program:parseInt(n[1]),bank:parseInt(n[0])})}}handleMessage(A,e){switch(A){case Ie.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ie.reloadSoundFont:this.reloadManager(e);break;case Ie.deleteSoundFont:this.deleteSoundFont(e);break;case Ie.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ge(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){L("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(s=>s.id===A);if(e===-1){L(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[e].soundfont.presets,delete this.soundfontList[e].soundfont.instruments,delete this.soundfontList[e].soundfont.samples,this.soundfontList.splice(e,1),this.generatePresetList()}addNewSoundFont(A,e,s){if(this.soundfontList.find(n=>n.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Ge(A),bankOffset:s}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,s)=>A.indexOf(e.id)-A.indexOf(s.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let s of this.soundfontList){let n=s.soundfont.getPresetNoFallback(A-s.bankOffset,e);if(n!==void 0)return n}if(A!==128){for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.program===e);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}else{for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.bank===128);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}}};var ot=class{constructor(A,e,s,n,o,i,C,c){this.sampleData=A,this.playbackStep=e,this.cursor=s,this.rootKey=n,this.loopStart=o,this.loopEnd=i,this.end=C,this.loopingMode=c,this.isLooping=this.loopingMode===1||this.loopingMode===3}sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1},xe=class t{constructor(A,e,s,n,o,i,C,c,B){this.sample=e,this.generators=c,this.modulatedGenerators=new Int16Array(c),this.modulators=B,this.velocity=n,this.midiNote=s,this.channelNumber=o,this.startTime=i,this.targetKey=C,this.volumeEnvelope=new LA(A,c[g.sustainVolEnv])}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;static copy(A,e){let s=A.sample,n=new ot(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new t(A.volumeEnvelope.sampleRate,n,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.generators,A.modulators.map(o=>$.copy(o)))}};function co(t,A,e,s,n,o=!1){let i,C=s.cachedVoices[A][e];return C!==void 0?C.map(c=>xe.copy(c,n)):(i=s.preset.getSamplesAndGenerators(A,e).reduce((B,d)=>{if(d.sample.sampleData===void 0)return L(`Discarding invalid sample: ${d.sample.sampleName}`),B;let h=new Int16Array(60);for(let N=0;N<60;N++)h[N]=ds(N,d.presetGenerators,d.instrumentGenerators);h[g.initialAttenuation]=Math.floor(h[g.initialAttenuation]*.4);let l=d.sample.samplePitch;h[g.overridingRootKey]>-1&&(l=h[g.overridingRootKey]);let u=A;h[g.keyNum]>-1&&(u=h[g.keyNum]);let D=d.sample.sampleLoopStartIndex/2,y=d.sample.sampleLoopEndIndex/2,w=h[g.sampleModes],S=new ot(d.sample.getAudioData(),d.sample.sampleRate/sampleRate*Math.pow(2,d.sample.samplePitchCorrection/1200),0,l,D,y,Math.floor(d.sample.sampleData.length)-1,w);return h[g.velocity]>-1&&(e=h[g.velocity]),o&&ls([{Sample:d.sample.sampleName,Generators:h,Modulators:d.modulators.map(N=>N.debugString()),Velocity:e,TargetKey:u,MidiNote:A,WorkletSample:S}]),B.push(new xe(sampleRate,S,A,e,t,n,u,h,d.modulators.map(N=>$.copy(N)))),B},[]),s.cachedVoices[A][e]=i.map(B=>xe.copy(B,n)),i)}var Lt=.03,Ut=1,T=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 aA(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=Ss,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new nt(A.processorOptions.soundfont,this.postReady.bind(this))}catch(e){throw this.post({messageType:pA.soundfontError,messageData:e}),e}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let e=0;ethis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),OA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",r.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:pA.ready,messageData:void 0})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let s=0;return this.workletProcessorChannels.forEach((n,o)=>{if(n.voices.length<1||n.isMuted)return;let i,C,c,B,d;if(this.oneOutputMode){let l=e[0];i=o%16*2,C=l[i],c=l[i+1]}else i=o%this._outputsAmount+2,C=e[i][0],c=e[i][1],B=e[0],d=e[1];let h=n.voices;n.voices=[],h.forEach(l=>{this.renderVoice(n,l,C,c,B,d),l.finished||n.voices.push(l)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};T.prototype.renderVoice=$s;T.prototype.releaseVoice=en;T.prototype.voiceKilling=An;T.prototype.getWorkletVoices=co;T.prototype.handleMessage=nn;T.prototype.sendChannelProperties=rn;T.prototype.callEvent=on;T.prototype.systemExclusive=an;T.prototype.noteOn=gn;T.prototype.noteOff=Cn;T.prototype.polyPressure=Sn;T.prototype.killNote=En;T.prototype.stopAll=Bn;T.prototype.stopAllChannels=hn;T.prototype.muteChannel=Rn;T.prototype.setVibrato=xn;T.prototype.disableAndLockGSNRPN=Gn;T.prototype.dataEntryCoarse=Mn;T.prototype.dataEntryFine=Nn;T.prototype.createWorkletChannel=fs;T.prototype.controllerChange=Dn;T.prototype.channelPressure=pn;T.prototype.resetAllControllers=bn;T.prototype.resetControllers=Ln;T.prototype.resetParameters=Un;T.prototype.setMasterGain=wn;T.prototype.setMasterPan=Fn;T.prototype.setMIDIVolume=kn;T.prototype.transposeAllChannels=Qn;T.prototype.transposeChannel=cn;T.prototype.setChannelTuning=ln;T.prototype.setChannelTuningSemitones=un;T.prototype.setMasterTuning=dn;T.prototype.setModulationDepth=fn;T.prototype.pitchWheel=mn;T.prototype.setOctaveTuning=yn;T.prototype.programChange=ro;T.prototype.getPreset=io;T.prototype.setPreset=ao;T.prototype.setDrums=Io;T.prototype.reloadSoundFont=Eo;T.prototype.clearSoundFont=Co;T.prototype.setEmbeddedSoundFont=Bo;T.prototype.sendPresetList=go;T.prototype.sendSynthesizerSnapshot=ho;T.prototype.applySynthesizerSnapshot=Qo;registerProcessor(ps,T);m("%cProcessor succesfully registered!",r.recognized); diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/wavetable_oscillator.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/wavetable_oscillator.js index e48e02c6..50a47bcc 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/wavetable_oscillator.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/wavetable_oscillator.js @@ -57,6 +57,10 @@ export function getSampleLinear(voice, outputBuffer) } else { + if(sample.loopingMode === 2 && !voice.isInRelease) + { + return; + } for (let i = 0; i < outputBuffer.length; i++) { @@ -119,6 +123,10 @@ export function getSampleNearest(voice, outputBuffer) } else { + if(sample.loopingMode === 2 && !voice.isInRelease) + { + return; + } for (let i = 0; i < outputBuffer.length; i++) { @@ -198,6 +206,10 @@ export function getSampleCubic(voice, outputBuffer) } else { + if(sample.loopingMode === 2 && !voice.isInRelease) + { + return; + } for (let i = 0; i < outputBuffer.length; i++) { diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_voice.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_voice.js index a10d18a8..06820e1c 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_voice.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/worklet_voice.js @@ -87,8 +87,9 @@ class WorkletSample * Looping mode of the sample: * 0 - no loop * 1 - loop - * 2 - loop then play when released - * @type {0|1|2} + * 2 - UNOFFICIAL: polyphone 2.4 added start on release + * 3 - loop then play when released + * @type {0|1|2|3} */ loopingMode = 0; @@ -372,15 +373,6 @@ export function getWorkletVoices(channel, let loopStart = (sampleAndGenerators.sample.sampleLoopStartIndex / 2); let loopEnd = (sampleAndGenerators.sample.sampleLoopEndIndex / 2); let loopingMode = generators[generatorTypes.sampleModes]; - const sampleLength = sampleAndGenerators.sample.getAudioData().length; - // clamp loop - loopStart = Math.min(Math.max(0, loopStart), sampleLength); - // clamp loop - loopEnd = Math.min(Math.max(0, loopEnd), sampleLength); - if (loopEnd - loopStart < 1) - { - loopingMode = 0; - } /** * create the worklet sample * offsets are calculated at note on time (to allow for modulation of them) diff --git a/src/website/js/synthesizer_ui/methods/synthui_selector.js b/src/website/js/synthesizer_ui/methods/synthui_selector.js index 77d9bac8..8afdeaf0 100644 --- a/src/website/js/synthesizer_ui/methods/synthui_selector.js +++ b/src/website/js/synthesizer_ui/methods/synthui_selector.js @@ -208,13 +208,16 @@ export class Selector if(program !== lastProgram) { lastProgram = program; - // create the header - const headerRow = document.createElement("tr"); - const header = document.createElement("th"); - header.colSpan = "3"; - header.textContent = midiPatchNames[lastProgram]; - headerRow.appendChild(header); - table.appendChild(headerRow); + // create the header (not for drums + if(preset.bank !== 128) + { + const headerRow = document.createElement("tr"); + const header = document.createElement("th"); + header.colSpan = "3"; + header.textContent = midiPatchNames[lastProgram]; + headerRow.appendChild(header); + table.appendChild(headerRow); + } } const programText = `${preset.program.toString().padStart(3, "0")}`; const bankText = `${preset.bank.toString().padStart(3, "0")}`; @@ -270,8 +273,9 @@ export class Selector this.isReloaded = false; return; } - this.mainButton.innerHTML = ""; this.isReloaded = true; + if(this.elements.length > 0) + this.mainButton.textContent = this.getString(`${this.elements[0].bank}:${this.value.split(":")[1]}`); } /** diff --git a/src/website/minified/demo_main.min.js b/src/website/minified/demo_main.min.js index 0dfb76a1..7513ee54 100644 --- a/src/website/minified/demo_main.min.js +++ b/src/website/minified/demo_main.min.js @@ -75,7 +75,7 @@ var EC=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(n,l)=>( `}function KB(o){return` -`}function uh(o,n){let l=document.createElement("div");return l.classList.add("control_buttons"),l.title=o,l.innerHTML=n,l}var e7={synthesizerUIShow:"s",settingsShow:"r",blackMidiMode:"b",midiPanic:"backspace",playPause:" ",toggleLoop:"l",toggleLyrics:"t",seekBackwards:"arrowleft",seekForwards:"arrowright",previousSong:"[",nextSong:"]",cinematicMode:"c",videoMode:"v"};function Fy(){navigator.mediaSession&&(navigator.mediaSession.metadata=new MediaMetadata({title:this.currentSongTitle,artist:"SpessaSynth"}),navigator.mediaSession.setActionHandler("play",()=>{this.seqPlay()}),navigator.mediaSession.setActionHandler("pause",()=>{this.seqPause()}),navigator.mediaSession.setActionHandler("stop",()=>{this.seq.currentTime=0,this.seqPause()}),navigator.mediaSession.setActionHandler("seekbackward",o=>{this.seq.currentTime-=o.seekOffset||10}),navigator.mediaSession.setActionHandler("seekforward",o=>{this.seq.currentTime+=o.seekOffset||10}),navigator.mediaSession.setActionHandler("seekto",o=>{this.seq.currentTime=o.seekTime}),navigator.mediaSession.setActionHandler("previoustrack",()=>{this.switchToPreviousSong()}),navigator.mediaSession.setActionHandler("nexttrack",()=>{this.switchToNextSong()}),navigator.mediaSession.playbackState="playing")}function My(o=!0){if(this.seq?.hasDummyData===!0)this.currentSongTitle=this.locale.getLocaleString("locale.synthInit.genericLoading");else{let n=this.infoDecoder.decode(this.seq.midiData.rawMidiName.buffer).replace(/\0$/,"");this.currentSongTitle=FB(n)}if(this.seq.midiData){let n=this.seq.midiData.lyrics;this.currentLyrics=new Uint8Array(n.reduce((g,u)=>g+u.length,0));let l=0;for(let g of n)this.currentLyrics.set(g,l),l+=g.length;this.currentLyricsString=this.decodeTextFix(this.currentLyrics.buffer)||this.locale.getLocaleString("locale.sequencerController.lyrics.noLyrics"),this.setLyricsText(""),o&&(this.rawOtherTextEvents=[])}if(document.getElementById("title").innerText=this.currentSongTitle,document.title=this.currentSongTitle+" - SpessaSynth",this.musicModeUI.setTitle(this.currentSongTitle),!!navigator.mediaSession)try{navigator.mediaSession.setPositionState({duration:this.seq.duration,playbackRate:this.seq.playbackRate,position:this.seq.currentTime})}catch{}}var Hb=parseFloat(getComputedStyle(document.body).fontSize);function Ty(){this.lyricsElement={};let o=document.createElement("div");o.classList.add("lyrics");let n=document.createElement("div");n.classList.add("lyrics_title_wrapper"),o.append(n),this.lyricsElement.titleWrapper=n;let l=document.createElement("h2");this.locale.bindObjectProperty(l,"textContent","locale.sequencerController.lyrics.title"),l.classList.add("lyrics_title"),n.appendChild(l),this.lyricsElement.title=l;let g=document.createElement("select");Sm.forEach(u1=>{let R=document.createElement("option");R.innerText=u1,R.value=u1,g.appendChild(R)}),g.value=this.encoding,g.onchange=()=>this.changeEncoding(g.value),g.classList.add("lyrics_selector"),this.encodingSelector=g,n.appendChild(g);let u=document.createElement("p");u.classList.add("lyrics_text"),o.appendChild(u);let S=document.createElement("span");S.classList.add("lyrics_text_highlight"),u.appendChild(S);let r0=document.createElement("span");r0.classList.add("lyrics_text_gray"),u.appendChild(r0);let E0=document.createElement("details"),m0=document.createElement("summary");this.locale.bindObjectProperty(m0,"textContent","locale.sequencerController.lyrics.otherText.title"),E0.appendChild(m0);let g0=document.createElement("div");g0.innerText="",E0.appendChild(g0),o.appendChild(E0),this.lyricsElement.text={highlight:S,gray:r0,main:u,other:g0},this.lyricsElement.mainDiv=o,this.lyricsElement.selector=g,this.controls.appendChild(o),this.requiresTextUpdate=!0}function Ny(o){let n=this.lyricsElement.text.highlight,l=this.lyricsElement.text.gray;l.innerText=this.currentLyricsString.replace(o,""),n.innerText=o,this.lyricsElement.text.main.scrollTo(0,n.offsetHeight-Hb*5)}function Gy(){let o="";for(let n of this.rawOtherTextEvents)o+=`
${Object.keys(K3).find(l=>K3[l]===n.type).replace(/([a-z])([A-Z])/g,"$1 $2")}:
${this.decodeTextFix(n.data.buffer)}

`;this.lyricsElement.text.other.innerHTML=o}var Un=32,Uy="#ccc",Py="#555",qb="#333",Yb="#ddd",Jb="Shift_JIS",Ls=class{constructor(n,l,g){this.iconColor=Uy,this.iconDisabledColor=Py,this.controls=n,this.encoding=Jb,this.decoder=new TextDecoder(this.encoding),this.infoDecoder=new TextDecoder(this.encoding),this.hasInfoDecoding=!1,this.text="",this.requiresTextUpdate=!1,this.rawLyrics=[],this.rawOtherTextEvents=[],this.mode="dark",this.locale=l,this.currentSongTitle="",this.currentLyrics=new Uint8Array(0),this.currentLyricsString="",this.musicModeUI=g}toggleDarkMode(){if(this.mode==="dark"?(this.mode="light",this.iconColor=qb,this.iconDisabledColor=Yb):(this.mode="dark",this.iconColor=Uy,this.iconDisabledColor=Py),!this.seq){this.requiresThemeUpdate=!0;return}this.progressBar.classList.toggle("note_progress_light"),this.progressBarBackground.classList.toggle("note_progress_background_light"),this.lyricsElement.mainDiv.classList.toggle("lyrics_light"),this.lyricsElement.titleWrapper.classList.toggle("lyrics_light"),this.lyricsElement.selector.classList.toggle("lyrics_light")}seqPlay(n=!0){n&&this.seq.play(),this.playPause.innerHTML=y$(Un),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),navigator.mediaSession&&(navigator.mediaSession.playbackState="playing")}seqPause(n=!0){n&&this.seq.pause(),this.playPause.innerHTML=yy(Un),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),navigator.mediaSession&&(navigator.mediaSession.playbackState="paused")}switchToNextSong(){this.seq.nextSong(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus()}switchToPreviousSong(){this.seq.previousSong(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus()}decodeTextFix(n,l=!1){let g=0;for(;;)try{return this.decoder.decode(n)}catch{g++,this.changeEncoding(Sm[g]),this.encodingSelector.value=Sm[g]}}connectSequencer(n){this.seq=n,this.createControls(),this.setSliderInterval(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),this.seq.onTextEvent=(l,g)=>{let u=this.decodeTextFix(l.buffer);switch(g){default:return;case K3.text:case K3.copyright:case K3.cuePoint:case K3.trackName:case K3.instrumentName:case K3.programName:case K3.marker:this.rawOtherTextEvents.push({type:g,data:l}),this.requiresTextUpdate=!0;return;case K3.lyric:this.text+=u,this.rawLyrics.push(...l),this.setLyricsText(this.text);break}},this.seq.addOnTimeChangeEvent(()=>{this.text="",this.rawLyrics=[],this.seqPlay(!1)},"sequi-time-change"),this.seq.addOnSongChangeEvent(l=>{if(this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),this.seqPlay(!1),this.seq.songsAmount>1&&(this.seq.loop=!1,this.loopButton.firstElementChild.setAttribute("fill",this.iconDisabledColor)),this.hasInfoDecoding=this.seq.midiData.RMIDInfo?.[Mt.encoding]!==void 0,l.isEmbedded){let g=(E0,m0,g0,u1="")=>this.seq.midiData.RMIDInfo?.[E0]===void 0?m0:u1+g0.decode(this.seq.midiData.RMIDInfo?.[E0]).replace(/\0$/,""),u=new TextDecoder,S=g(Mt.midiEncoding,this.encoding,u),r0=g(Mt.encoding,"utf-8",u);this.infoDecoder=new TextDecoder(r0),this.changeEncoding(S)}},"sequi-song-change"),this.requiresThemeUpdate&&this.mode==="light"&&(this.mode="dark",this.toggleDarkMode())}changeEncoding(n){this.encoding=n,this.decoder=new TextDecoder(n),this.hasInfoDecoding||(this.infoDecoder=new TextDecoder(n)),this.updateOtherTextEvents(),this.text=this.decodeTextFix(new Uint8Array(this.rawLyrics).buffer),this.lyricsElement.selector.value=n,this.updateTitleAndMediaStatus(!1),this.setLyricsText(this.text)}createControls(){this.progressTime=document.createElement("p"),this.progressTime.id="note_time",this.progressTime.onclick=R=>{R.preventDefault();let Z0=n.getBoundingClientRect(),G0=R.clientX-Z0.left,b1=Z0.width;this.seq.currentTime=G0/b1*this.seq.duration,g.innerHTML=y$(Un)},this.createLyrics();let n=document.createElement("div");n.id="note_progress_background",this.progressBarBackground=n,this.progressBar=document.createElement("div"),this.progressBar.id="note_progress",this.progressBar.min="0",this.progressBar.max=this.seq.duration.toString();let l=document.createElement("div"),g=uh("Play/Pause",y$(Un));this.playPause=g,this.locale.bindObjectProperty(g,"title","locale.sequencerController.playPause");let u=()=>{this.seq.paused?this.seqPlay():this.seqPause()};g.onclick=u;let S=uh("Previous song",Sy(Un));this.locale.bindObjectProperty(S,"title","locale.sequencerController.previousSong"),S.onclick=()=>this.switchToPreviousSong();let r0=uh("Next song",vy(Un));this.locale.bindObjectProperty(r0,"title","locale.sequencerController.nextSong"),r0.onclick=()=>this.switchToNextSong();let E0=uh("Loop this",wy(Un));this.locale.bindObjectProperty(E0,"title","locale.sequencerController.loopThis");let m0=()=>{this.seq.loop?this.seq.loop=!1:(this.seq.loop=!0,this.seq.currentTime>=this.seq.duration&&(this.seq.currentTime=0)),E0.firstElementChild.setAttribute("fill",this.seq.loop?this.iconColor:this.iconDisabledColor)};E0.onclick=m0,this.loopButton=E0;let g0=uh("Show lyrics",ky(Un));this.locale.bindObjectProperty(g0,"title","locale.sequencerController.lyrics.show"),g0.firstElementChild.setAttribute("fill",this.iconDisabledColor);let u1=()=>{this.lyricsElement.mainDiv.classList.toggle("lyrics_show"),g0.firstElementChild.setAttribute("fill",this.lyricsElement.mainDiv.classList.contains("lyrics_show")?this.iconColor:this.iconDisabledColor)};g0.onclick=u1,document.addEventListener("keydown",R=>{switch(R.key.toLowerCase()){case e7.playPause:R.preventDefault(),u();break;case e7.toggleLoop:R.preventDefault(),m0();break;case e7.toggleLyrics:R.preventDefault(),u1();break;default:break}}),l.appendChild(S),l.appendChild(E0),l.appendChild(g),l.appendChild(g0),l.appendChild(r0),this.controls.appendChild(n),n.appendChild(this.progressBar),this.controls.appendChild(this.progressTime),this.controls.appendChild(l),document.addEventListener("keydown",R=>{switch(R.key.toLowerCase()){case e7.seekBackwards:R.preventDefault(),this.seq.currentTime-=5,g.innerHTML=y$(Un);break;case e7.seekForwards:R.preventDefault(),this.seq.currentTime+=5,g.innerHTML=y$(Un);break;case e7.previousSong:this.switchToPreviousSong();break;case e7.nextSong:this.switchToNextSong();break;default:if(!isNaN(parseFloat(R.key))){R.preventDefault();let Z0=parseInt(R.key);0<=Z0&&Z0<=9&&(this.seq.currentTime=this.seq.duration*(Z0/10),g.innerHTML=y$(Un))}break}})}_updateInterval(){this.progressBar.style.width=`${this.seq.currentTime/this.seq.duration*100}%`;let n=E$(this.seq.currentTime),l=E$(this.seq.duration);this.progressTime.innerText=`${n.time} / ${l.time}`,this.requiresTextUpdate&&(this.updateOtherTextEvents(),this.requiresTextUpdate=!1)}setSliderInterval(){setInterval(this._updateInterval.bind(this),100)}};Ls.prototype.createNavigatorHandler=Fy;Ls.prototype.updateTitleAndMediaStatus=My;Ls.prototype.createLyrics=Ty;Ls.prototype.setLyricsText=Ny;Ls.prototype.updateOtherTextEvents=Gy;function Oy(){this.controllers.forEach(o=>{o.voiceMeter.hide(),o.pitchWheel.hide(),o.pan.hide(),o.expression.hide(),o.volume.hide(),o.mod.hide(),o.chorus.hide(),o.reverb.hide(),o.brightness.hide(),o.preset.hide()})}function Hy(){this.controllers.forEach(o=>{o.voiceMeter.show(),o.pitchWheel.show(),o.pan.show(),o.expression.show(),o.volume.show(),o.mod.show(),o.chorus.show(),o.reverb.show(),o.brightness.show(),o.preset.show()})}function qy(){this.mainControllerDiv.classList.toggle("synthui_controller_light"),this.mainButtons.forEach(o=>{o.classList.toggle("synthui_button"),o.classList.toggle("synthui_button_light")}),this.mainMeters.forEach(o=>{o.toggleMode(!0)}),this.controllers.forEach(o=>{o.voiceMeter.toggleMode(),o.pitchWheel.toggleMode(),o.pan.toggleMode(),o.expression.toggleMode(),o.volume.toggleMode(),o.mod.toggleMode(),o.chorus.toggleMode(),o.reverb.toggleMode(),o.brightness.toggleMode(),o.preset.toggleMode(),o.drumsToggle.classList.toggle("mute_button_light"),o.muteButton.classList.toggle("mute_button_light")})}var hn=class{constructor(n="none",l,g,u,S=0,r0=100,E0=!1,m0=void 0,g0=void 0,u1=void 0){if(this.meterText="",g.bindObjectProperty(this,"meterText",l+".title"),this.min=S,this.max=r0,this.currentValue=-1,this.isShown=!0,this.isVisualValueSet=!0,this.isLocked=!1,this.lockCallback=g0,this.unlockCallback=u1,this.div=document.createElement("div"),this.div.classList.add("voice_meter"),this.div.classList.add("controller_element"),n!=="none"&&n!==""&&(this.div.style.borderColor=n),g.bindObjectProperty(this.div,"title",l+".description",u),this.bar=document.createElement("div"),this.bar.classList.add("voice_meter_bar"),this.bar.style.background=n,this.div.appendChild(this.bar),this.text=document.createElement("p"),this.text.classList.add("voice_meter_text"),this.div.appendChild(this.text),this.isActive=!1,E0){if(m0===void 0)throw new Error("No editable function given!");this.div.onmousedown=R=>{R.preventDefault(),R.button===0?this.isActive=!0:this.lockMeter()},this.div.onmousemove=R=>{if(!this.isActive)return;let Z0=R.currentTarget.getBoundingClientRect(),G0=Z0.left,b1=Z0.width,l2=R.clientX-G0,y1=Math.max(0,Math.min(1,l2/b1));m0(y1*(r0-S)+S)},this.div.onmouseup=()=>this.isActive=!1,this.div.onmouseleave=R=>{this.div.onmousemove(R),this.isActive=!1},this.text.oncontextmenu=R=>{R.preventDefault()},this.div.onclick=R=>{R.preventDefault(),this.isActive=!0,this.div.onmousemove(R),this.isActive=!1},this.div.classList.add("editable")}}lockMeter(){this.lockCallback!==void 0&&(this.isLocked?(this.text.classList.remove("locked_meter"),this.unlockCallback()):(this.text.classList.add("locked_meter"),this.lockCallback()),this.isLocked=!this.isLocked)}toggleMode(n=!1){n&&(this.bar.classList.toggle("voice_meter_light_color"),this.div.classList.toggle("voice_meter_light_color")),this.text.classList.toggle("voice_meter_text_light")}show(){if(this.isShown=!0,!this.isVisualValueSet){let n=Math.max(0,Math.min((this.currentValue-this.min)/(this.max-this.min),1));this.bar.style.width=`${n*100}%`,this.text.textContent=this.meterText+(Math.round(this.currentValue*100)/100).toString(),this.isVisualValueSet=!0}}hide(){this.isShown=!1}update(n,l=!1){if(!(n===this.currentValue&&l===!1))if(this.currentValue=n,this.isShown){let g=Math.max(0,Math.min((n-this.min)/(this.max-this.min),1));this.bar.style.width=`${g*100}%`,this.text.textContent=this.meterText+(Math.round(n*100)/100).toString(),this.isVisualValueSet=!0}else this.isVisualValueSet=!1}};var Yy=["Acoustic Grand Piano","Bright Acoustic Piano","Electric Grand Piano","Honky-tonk Piano","Electric Piano 1","Electric Piano 2","Harpsichord","Clavi","Celesta","Glockenspiel","Music Box","Vibraphone","Marimba","Xylophone","Tubular Bells","Dulcimer","Drawbar Organ","Percussive Organ","Rock Organ","Church Organ","Reed Organ","Accordion","Harmonica","Tango Accordion","Acoustic Guitar (nylon)","Acoustic Guitar (steel)","Electric Guitar (jazz)","Electric Guitar (clean)","Electric Guitar (muted)","Overdriven Guitar","Distortion Guitar","Guitar Harmonics","Acoustic Bass","Electric Bass (finger)","Electric Bass (pick)","Fretless Bass","Slap Bass 1","Slap Bass 2","Synth Bass 1","Synth Bass 2","Violin","Viola","Cello","Contrabass","Tremolo Strings","Pizzicato Strings","Orchestral Harp","Timpani","String Ensemble 1","String Ensemble 2","Synth Strings 1","Synth Strings 2","Choir Aahs","VoiceGroup Oohs","Synth Choir","Orchestra Hit","Trumpet","Trombone","Tuba","Muted Trumpet","French Horn","Brass Section","Synth Brass 1","Synth Brass 2","Soprano Sax","Alto Sax","Tenor Sax","Baritone Sax","Oboe","English Horn","Bassoon","Clarinet","Piccolo","Flute","Recorder","Pan Flute","Blown Bottle","Shakuhachi","Whistle","Ocarina","Lead 1 (square)","Lead 2 (sawtooth)","Lead 3 (calliope)","Lead 4 (chiff)","Lead 5 (charang)","Lead 6 (voice)","Lead 7 (fifths)","Lead 8 (bass + lead)","Pad 1 (new age)","Pad 2 (warm)","Pad 3 (polysynth)","Pad 4 (choir)","Pad 5 (bowed)","Pad 6 (metallic)","Pad 7 (halo)","Pad 8 (sweep)","FX 1 (rain)","FX 2 (soundtrack)","FX 3 (crystal)","FX 4 (atmosphere)","FX 5 (brightness)","FX 6 (goblins)","FX 7 (echoes)","FX 8 (sci-fi)","Sitar","Banjo","Shamisen","Koto","Kalimba","Bagpipe","Fiddle","Shanai","Tinkle Bell","Agogo","Steel Drums","Woodblock","Taiko Drum","Melodic Tom","Synth Drum","Reverse Cymbal","Guitar Fret Noise","Breath Noise","Seashore","Bird Tweet","Telephone Ring","Attack Helicopter","Applause","Gunshot"];var LC=class{constructor(n,l,g,u,S=void 0,r0=void 0){this.isShown=!0,this.isReloaded=!0,this.elements=n.map(E0=>({name:E0.name,program:E0.program,bank:E0.bank,stringified:`${E0.bank.toString().padStart(3,"0")}:${E0.program.toString().padStart(3,"0")} ${E0.name}`})),this.elements.length>0?this.value=`${this.elements[0].bank}:${this.elements[0].program}`:this.value="",this.mainButton=document.createElement("button"),this.mainButton.classList.add("voice_selector"),this.mainButton.classList.add("controller_element"),l.bindObjectProperty(this.mainButton,"title",g+".description",u),this.locale=l,this.localePath=g,this.localeArgs=u,this.reload(),this.mainButton.onclick=()=>{this.showSelectionMenu()},this.editCallback=S,this.selectionMenu=void 0,this.lockCallback=r0,this.locked=!1,this.isWindowShown=!1}showSelectionMenu(){this.selectionMenu=document.createElement("div"),this.selectionMenu.classList.add("voice_selector_wrapper"),document.getElementsByClassName("spessasynth_main")[0].appendChild(this.selectionMenu);let n=document.createElement("div");n.classList.add("voice_selector_window");let l=document.createElement("h2");this.locale.bindObjectProperty(l,"textContent",this.localePath+".selectionPrompt",this.localeArgs),n.appendChild(l);let g=document.createElement("div");g.classList.add("voice_selector_search_wrapper"),n.appendChild(g);let u=document.createElement("input");u.type="text",this.locale.bindObjectProperty(u,"placeholder",this.localePath+".searchPrompt"),g.appendChild(u),u.onkeydown=E0=>E0.stopPropagation();let S=document.createElement("div");S.innerHTML=this.locked?xC(h7):JB(h7),this.locale.bindObjectProperty(S,"title",oe+"channelController.presetReset.description",this.localeArgs),S.classList.add("voice_reset"),this.mainButton.classList.contains("voice_selector_light")&&S.classList.add("voice_reset_light"),S.onclick=()=>{this.locked=!this.locked,this.lockCallback(this.locked),this.mainButton.classList.toggle("locked_selector"),this.locked?S.innerHTML=xC(h7):S.innerHTML=JB(h7)},g.appendChild(S),this.presetLock=S;let r0=document.createElement("div");r0.classList.add("voice_selector_table_wrapper"),n.appendChild(r0),this.generateTable(r0,this.elements),u.oninput=E0=>{E0.stopPropagation();let m0=u.value,g0=this.elements.filter(u1=>u1.stringified.search(new RegExp(m0,"i"))>=0);g0.length!==this.elements.length&&(r0.replaceChildren(),this.generateTable(r0,g0))},n.onclick=E0=>{E0.stopPropagation()},this.selectionMenu.appendChild(n),this.selectionMenu.onclick=E0=>{E0.stopPropagation(),this.hideSelectionMenu()},this.isWindowShown=!0}generateTable(n,l){let g=document.createElement("table");g.classList.add("voice_selector_table");let u=parseInt(this.value.split(":")[0]),S=parseInt(this.value.split(":")[1]),r0=-20;for(let E0 of l){let m0=document.createElement("tr"),g0=E0.program;if(g0===S&&E0.bank===u&&(m0.classList.add("voice_selector_selected"),setTimeout(()=>{m0.scrollIntoView({behavior:"instant",block:"center",inline:"center"})},20)),m0.onclick=()=>{let l2=`${E0.bank}:${g0}`;if(this.value===l2){this.hideSelectionMenu();return}this.editCallback(l2),this.locked=!0,this.presetLock.innerHTML=xC(h7),this.hideSelectionMenu()},g0!==r0){r0=g0;let l2=document.createElement("tr"),y1=document.createElement("th");y1.colSpan="3",y1.textContent=Yy[r0],l2.appendChild(y1),g.appendChild(l2)}let u1=`${E0.program.toString().padStart(3,"0")}`,R=`${E0.bank.toString().padStart(3,"0")}`,Z0=document.createElement("td");Z0.classList.add("voice_selector_preset_name"),Z0.textContent=E0.name;let G0=document.createElement("td");Z0.classList.add("voice_selector_preset_program"),G0.textContent=u1;let b1=document.createElement("td");Z0.classList.add("voice_selector_preset_program"),b1.textContent=R,m0.appendChild(b1),m0.appendChild(G0),m0.appendChild(Z0),g.appendChild(m0)}n.appendChild(g)}hideSelectionMenu(){document.getElementsByClassName("spessasynth_main")[0].removeChild(this.selectionMenu),this.selectionMenu=void 0,this.isWindowShown=!1}toggleMode(){this.mainButton.classList.toggle("voice_selector_light")}reload(n=this.elements){if(this.elements=n.map(l=>({name:l.name,program:l.program,bank:l.bank,stringified:`${l.bank.toString().padStart(3,"0")}:${l.program.toString().padStart(3,"0")} ${l.name}`})),!this.isShown){this.isReloaded=!1;return}this.mainButton.innerHTML="",this.isReloaded=!0}set(n){if(this.value=n,this.isShown&&(this.isReloaded||this.reload(),this.mainButton.textContent=this.getString(this.value),this.isWindowShown)){let l=this.selectionMenu.getElementsByClassName("voice_selector_selected")[0];l!==void 0&&l.classList.remove("voice_selector_selected");let g=this.selectionMenu.getElementsByClassName("voice_selector_table")[0],u=parseInt(this.value.split(":")[0]),S=parseInt(this.value.split(":")[1]);for(let r0 of g.rows){if(r0.cells.length===1)continue;let E0=parseInt(r0.cells[0].textContent),m0=parseInt(r0.cells[1].textContent);E0===u&&m0===S&&(r0.classList.add("voice_selector_selected"),r0.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}))}}}getString(n){let l=n.split(":"),g=parseInt(l[0]),u=parseInt(l[1]),S=this.elements.find(r0=>r0.bank===g&&r0.program===u);return g===128||this.elements.filter(r0=>r0.program===u&&r0.bank!==128).length<2?`${u}. ${S.name}`:`${g}:${u} ${S.name}`}show(){this.isShown=!0,this.isReloaded||this.reload(),this.mainButton.textContent=this.getString(this.value)}hide(){this.isShown=!1}};var h7=32;function Jy(o){this.soloChannels=new Set;let n=document.createElement("div");n.classList.add("channel_controller");let l=new hn(this.channelColors[o%this.channelColors.length],oe+"channelController.voiceMeter",this.locale,[o+1],0,100);l.bar.classList.add("voice_meter_bar_smooth"),n.appendChild(l.div);let g=new hn(this.channelColors[o%this.channelColors.length],oe+"channelController.pitchBendMeter",this.locale,[o+1],-8192,8191,!0,T2=>{let K2=g.isLocked;K2&&this.synth.lockController(o,C$+Ft.pitchWheel,!1),T2=Math.round(T2)+8192;let i3=T2>>7,n3=T2&127;this.synth.pitchWheel(o,i3,n3),K2&&this.synth.lockController(o,C$+Ft.pitchWheel,!0)},()=>this.synth.lockController(o,C$+Ft.pitchWheel,!0),()=>this.synth.lockController(o,C$+Ft.pitchWheel,!1));g.update(0),n.appendChild(g.div);let u=(T2,K2,i3)=>{i3.isLocked?(this.synth.lockController(o,T2,!1),this.synth.controllerChange(o,T2,K2),this.synth.lockController(o,T2,!0)):this.synth.controllerChange(o,T2,K2)},S=(T2,K2,i3)=>{let n3=new hn(this.channelColors[o%this.channelColors.length],oe+K2,this.locale,[o+1],0,127,!0,A0=>u(T2,Math.round(A0),n3),()=>this.synth.lockController(o,T2,!0),()=>this.synth.lockController(o,T2,!1));return n3.update(i3),n3},r0=S(t6.pan,"channelController.panMeter",64);n.appendChild(r0.div);let E0=S(t6.expressionController,"channelController.expressionMeter",127);n.appendChild(E0.div);let m0=S(t6.mainVolume,"channelController.volumeMeter",100);n.appendChild(m0.div);let g0=S(t6.modulationWheel,"channelController.modulationWheelMeter",0);n.appendChild(g0.div);let u1=S(t6.effects3Depth,"channelController.chorusMeter",0);n.appendChild(u1.div);let R=S(t6.effects1Depth,"channelController.reverbMeter",0);n.appendChild(R.div);let Z0=S(t6.brightness,"channelController.filterMeter",64);n.appendChild(Z0.div);let G0=new hn(this.channelColors[o%this.channelColors.length],oe+"channelController.transposeMeter",this.locale,[o+1],-36,36,!0,T2=>{T2=Math.round(T2),this.synth.transposeChannel(o,T2,!0),G0.update(T2)});G0.update(0),n.appendChild(G0.div);let b1=new LC([],this.locale,oe+"channelController.presetSelector",[o+1],async T2=>{let K2=T2.split(":");this.synth.lockController(o,mi,!1),this.synth.controllerChange(o,t6.bankSelect,parseInt(K2[0]),!0),this.synth.programChange(o,parseInt(K2[1]),!0),b1.mainButton.classList.add("locked_selector"),this.synth.lockController(o,mi,!0)},T2=>this.synth.lockController(o,mi,T2));n.appendChild(b1.mainButton);let l2=document.createElement("div");l2.innerHTML=fh(h7),this.locale.bindObjectProperty(l2,"title",oe+"channelController.soloButton.description",[o+1]),l2.classList.add("controller_element"),l2.classList.add("mute_button"),l2.onclick=()=>{if(this.soloChannels.has(o)?this.soloChannels.delete(o):this.soloChannels.add(o),this.soloChannels.size===0||this.soloChannels.size>=this.synth.channelsAmount){for(let T2=0;T2=this.synth.channelsAmount&&this.soloChannels.clear();return}for(let T2=0;T2{if(y1.hasAttribute("is_muted")){y1.removeAttribute("is_muted");let T2=this.soloChannels.size===0||this.soloChannels.has(o);this.synth.muteChannel(o,!T2),y1.innerHTML=bm(h7)}else this.synth.muteChannel(o,!0),y1.setAttribute("is_muted","true"),y1.innerHTML=Dy(h7)},n.appendChild(y1);let Y2=document.createElement("div");return Y2.innerHTML=o===Di?_C(h7):RC(h7),this.locale.bindObjectProperty(Y2,"title",oe+"channelController.drumToggleButton.description",[o+1]),Y2.classList.add("controller_element"),Y2.classList.add("mute_button"),Y2.onclick=()=>{this.synth.setDrums(o,!this.synth.channelProperties[o].isDrum)},n.appendChild(Y2),{controller:n,voiceMeter:l,pitchWheel:g,pan:r0,expression:E0,volume:m0,mod:g0,chorus:u1,reverb:R,brightness:Z0,preset:b1,drumsToggle:Y2,soloButton:l2,muteButton:y1,transpose:G0}}function Ky(){let o=this.uiDiv.getElementsByClassName("synthui_controller")[0];this.controllers=[];for(let n=0;n{this.synth.setMainVolume(Math.round(g0)/100),this.volumeController.update(g0)}),this.volumeController.bar.classList.add("voice_meter_bar_smooth"),this.volumeController.div.classList.add("main_controller_element"),this.volumeController.update(100),this.panController=new hn("",oe+"mainPanMeter",this.locale,[],-1,1,!0,g0=>{this.synth.setMasterPan(g0),this.panController.update(g0)}),this.panController.bar.classList.add("voice_meter_bar_smooth"),this.panController.div.classList.add("main_controller_element"),this.panController.update(0),this.transposeController=new hn("",oe+"mainTransposeMeter",this.locale,[],-12,12,!0,g0=>{this.synth.transpose(Math.round(g0*2)/2),this.transposeController.update(Math.round(g0*2)/2)}),this.transposeController.bar.classList.add("voice_meter_bar_smooth"),this.transposeController.div.classList.add("main_controller_element"),this.transposeController.update(0);let n=document.createElement("button");this.locale.bindObjectProperty(n,"textContent",oe+"midiPanic.title"),this.locale.bindObjectProperty(n,"title",oe+"midiPanic.description"),n.classList.add("synthui_button"),n.classList.add("main_controller_element"),n.onclick=()=>this.synth.stopAll(!0);let l=document.createElement("button");this.locale.bindObjectProperty(l,"textContent",oe+"systemReset.title"),this.locale.bindObjectProperty(l,"title",oe+"systemReset.description"),l.classList.add("synthui_button"),l.classList.add("main_controller_element"),l.onclick=()=>{this.controllers.forEach((g0,u1)=>{g0.pitchWheel.isLocked&&g0.pitchWheel.lockMeter(),g0.pan.isLocked&&g0.pan.lockMeter(),g0.expression.isLocked&&g0.expression.lockMeter(),g0.volume.isLocked&&g0.volume.lockMeter(),g0.mod.isLocked&&g0.mod.lockMeter(),g0.chorus.isLocked&&g0.chorus.lockMeter(),g0.reverb.isLocked&&g0.reverb.lockMeter(),g0.brightness.isLocked&&g0.brightness.lockMeter(),g0.preset.mainButton.classList.contains("locked_selector")&&(this.synth.lockController(u1,mi,!1),g0.preset.mainButton.classList.remove("locked_selector")),this.synth.transposeChannel(u1,0,!0),g0.transpose.update(0),g0.soloButton.innerHTML=fh(h7),g0.muteButton.innerHTML=bm(h7),this.synth.muteChannel(u1,!1)}),this.synth.resetControllers()};let g=document.createElement("button");this.locale.bindObjectProperty(g,"textContent",oe+"blackMidiMode.title"),this.locale.bindObjectProperty(g,"title",oe+"blackMidiMode.description"),g.classList.add("synthui_button"),g.classList.add("main_controller_element"),g.onclick=()=>{this.synth.highPerformanceMode=!this.synth.highPerformanceMode};let u=document.createElement("button");this.locale.bindObjectProperty(u,"textContent",oe+"disableCustomVibrato.title"),this.locale.bindObjectProperty(u,"title",oe+"disableCustomVibrato.description"),u.classList.add("synthui_button"),u.classList.add("main_controller_element"),u.onclick=()=>{this.synth.disableGSNRPparams(),u.parentNode.removeChild(u)};let S=document.createElement("a");S.href="https://github.com/spessasus/SpessaSynth/wiki/How-To-Use-App#synthesizer-controller",S.target="#",S.classList.add("main_controller_element"),S.classList.add("synthui_button"),this.locale.bindObjectProperty(S,"textContent",oe+"helpButton.title"),this.locale.bindObjectProperty(S,"title",oe+"helpButton.description");let r0=document.createElement("select");r0.classList.add("main_controller_element"),r0.classList.add("synthui_button"),this.locale.bindObjectProperty(r0,"title",oe+"interpolation.description");{let g0=document.createElement("option");g0.value="0",this.locale.bindObjectProperty(g0,"textContent",oe+"interpolation.linear"),r0.appendChild(g0);let u1=document.createElement("option");u1.value="1",this.locale.bindObjectProperty(u1,"textContent",oe+"interpolation.nearestNeighbor"),r0.appendChild(u1);let R=document.createElement("option");R.value="2",R.selected=!0,this.locale.bindObjectProperty(R,"textContent",oe+"interpolation.cubic"),r0.appendChild(R),r0.onchange=()=>{this.synth.setInterpolationType(parseInt(r0.value))}}let E0=document.createElement("div");E0.classList.add("synthui_controller"),this.uiDiv.appendChild(E0);let m0=document.createElement("button");this.locale.bindObjectProperty(m0,"textContent",oe+"toggleButton.title"),this.locale.bindObjectProperty(m0,"title",oe+"toggleButton.description"),m0.classList.add("synthui_button"),m0.onclick=()=>{this.hideOnDocClick=!1,this.toggleVisibility()},o.appendChild(this.volumeController.div),o.appendChild(this.panController.div),o.appendChild(this.transposeController.div),o.appendChild(n),o.appendChild(l),o.appendChild(g),o.appendChild(u),o.appendChild(S),o.appendChild(r0),this.mainMeters=[this.volumeController,this.panController,this.transposeController,this.voiceMeter],this.mainButtons=[n,l,g,u,m0,S,r0],this.uiDiv.appendChild(this.voiceMeter.div),this.uiDiv.appendChild(m0),E0.appendChild(o),this.mainControllerDiv=E0,this.mainControllerDiv.onclick=g0=>g0.stopPropagation(),document.addEventListener("click",()=>{if(!this.hideOnDocClick){this.hideOnDocClick=!0;return}E0.classList.remove("synthui_controller_show"),this.isShown=!1,this.hideControllers()})}function zy(){let o=this.uiDiv.getElementsByClassName("synthui_controller")[0];this.synth.eventHandler.addEvent("programchange","synthui-program-change",n=>{this.controllers[n.channel].preset.set(`${n.bank}:${n.program}`)}),this.synth.eventHandler.addEvent("allcontrollerreset","synthui-all-controller-reset",()=>{for(let n of this.controllers)n.pan.update(64),n.mod.update(0),n.chorus.update(0),n.pitchWheel.update(0),n.expression.update(127),n.volume.update(100),n.reverb.update(0),n.brightness.update(64)}),this.synth.eventHandler.addEvent("controllerchange","synthui-controller-change",n=>{let l=n.controllerNumber,g=n.channel,u=n.controllerValue;switch(l){default:break;case t6.expressionController:this.controllers[g].expression.update(u);break;case t6.mainVolume:this.controllers[g].volume.update(u);break;case t6.pan:this.controllers[g].pan.update(u);break;case t6.modulationWheel:this.controllers[g].mod.update(u);break;case t6.effects3Depth:this.controllers[g].chorus.update(u);break;case t6.effects1Depth:this.controllers[g].reverb.update(u);break;case t6.brightness:this.controllers[g].brightness.update(u)}}),this.synth.eventHandler.addEvent("pitchwheel","synthui-pitch-wheel",n=>{let l=n.MSB<<7|n.LSB;this.controllers[n.channel].pitchWheel.update(l-8192)}),this.synth.eventHandler.addEvent("drumchange","synthui-drum-change",n=>{this.controllers[n.channel].drumsToggle.innerHTML=n.isDrumChannel?_C(32):RC(32),this.controllers[n.channel].preset.reload(n.isDrumChannel?this.percussionList:this.instrumentList)}),this.synth.eventHandler.addEvent("newchannel","synthui-new-channel",()=>{let n=this.createChannelController(this.controllers.length);this.controllers.push(n),o.appendChild(n.controller),this.hideControllers()})}var oe="locale.synthesizerController.",Pn=class{constructor(n,l,g){this.channelColors=n;let u=l;this.uiDiv=document.createElement("div"),this.uiDiv.classList.add("wrapper"),u.appendChild(this.uiDiv),this.uiDiv.style.visibility="visible",this.isShown=!1,this.animationId=-1,this.locale=g,this.hideOnDocClick=!0}connectSynth(n){this.synth=n,this.getInstrumentList(),this.createMainSynthController(),this.createChannelControllers(),document.addEventListener("keydown",l=>{switch(l.key.toLowerCase()){case e7.synthesizerUIShow:l.preventDefault(),this.toggleVisibility();break;case e7.settingsShow:this.isShown=!0,this.toggleVisibility();break;case e7.blackMidiMode:l.preventDefault(),this.synth.highPerformanceMode=!this.synth.highPerformanceMode;break;case e7.midiPanic:l.preventDefault(),this.synth.stopAll(!0);break}}),this.locale.onLocaleChanged.push(()=>{this.voiceMeter.update(this.voiceMeter.currentValue,!0),this.volumeController.update(this.volumeController.currentValue,!0),this.panController.update(this.panController.currentValue,!0),this.panController.update(this.panController.currentValue,!0),this.transposeController.update(this.transposeController.currentValue,!0);for(let l of this.controllers)l.voiceMeter.update(l.voiceMeter.currentValue,!0),l.pitchWheel.update(l.pitchWheel.currentValue,!0),l.pan.update(l.pan.currentValue,!0),l.volume.update(l.volume.currentValue,!0),l.expression.update(l.expression.currentValue,!0),l.mod.update(l.mod.currentValue,!0),l.chorus.update(l.chorus.currentValue,!0),l.reverb.update(l.reverb.currentValue,!0),l.brightness.update(l.brightness.currentValue,!0),l.transpose.update(l.transpose.currentValue,!0)})}toggleVisibility(){this.animationId!==-1&&clearTimeout(this.animationId);let n=document.getElementsByClassName("synthui_controller")[0];this.isShown=!this.isShown,this.isShown?(n.style.display="block",document.getElementsByClassName("top_part")[0].classList.add("synthui_shown"),this.showControllers(),setTimeout(()=>{n.classList.add("synthui_controller_show")},75)):(document.getElementsByClassName("top_part")[0].classList.remove("synthui_shown"),this.hideControllers(),n.classList.remove("synthui_controller_show"),this.animationId=setTimeout(()=>{n.style.display="none"},200))}updateVoicesAmount(){this.voiceMeter.update(this.synth.voicesAmount),this.controllers.forEach((n,l)=>{let g=this.synth.channelProperties[l].voicesAmount;n.voiceMeter.update(g),g<1&&this.synth.voicesAmount>0?n.controller.classList.add("no_voices"):n.controller.classList.remove("no_voices")})}getInstrumentList(){this.synth.eventHandler.addEvent("presetlistchange","synthui-preset-list-change",n=>{let l=n;this.instrumentList=l.filter(g=>g.bank!==128).sort((g,u)=>g.program===u.program?g.bank-u.bank:g.program-u.program).map(g=>({name:g.presetName,bank:g.bank,program:g.program})),this.percussionList=l.filter(g=>g.bank===128).sort((g,u)=>g.program-u.program).map(g=>({name:g.presetName,bank:g.bank,program:g.program})),this.percussionList.length===0?this.percussionList=this.instrumentList:this.instrumentList.length===0&&(this.instrumentList=this.percussionList),this.controllers.forEach((g,u)=>{let S=this.synth.channelProperties[u].isDrum?this.percussionList:this.instrumentList;g.preset.reload(S),g.preset.set(`${S[0].bank}:${S[0].program}`)})})}};Pn.prototype.hideControllers=Oy;Pn.prototype.showControllers=Hy;Pn.prototype.toggleDarkMode=qy;Pn.prototype.createChannelController=Jy;Pn.prototype.createChannelControllers=Ky;Pn.prototype.createMainSynthController=Vy;Pn.prototype.setEventListeners=zy;var _m=null,FC=class{constructor(){}async createMIDIDeviceHandler(){if(this.selectedInput=_m,this.selectedOutput=_m,navigator.requestMIDIAccess)try{let n=await navigator.requestMIDIAccess({sysex:!0,software:!0});return this.inputs=n.inputs,this.outputs=n.outputs,Y5("%cMIDI handler created!",_1.recognized),!0}catch(n){return R4("Could not get MIDI Devices:",n),this.inputs=[],this.outputs=[],!1}else return R4("Web MIDI Api not supported!",_1.unrecognized),this.inputs=[],this.outputs=[],!1}connectMIDIOutputToSeq(n,l){this.selectedOutput=n,l.connectMidiOutput(n),Y5(`%cPlaying MIDI to %c${n.name}`,_1.info,_1.recognized)}disconnectSeqFromMIDI(n){this.selectedOutput=_m,n.connectMidiOutput(void 0),Y5("%cDisconnected from MIDI out.",_1.info)}connectDeviceToSynth(n,l){this.selectedInput=n,n.onmidimessage=g=>{l.sendMessage(g.data)},Y5(`%cListening for messages on %c${n.name}`,_1.info,_1.recognized)}disconnectDeviceFromSynth(n){this.selectedInput=_m,n.onmidimessage=void 0,Y5(`%cDisconnected from %c${n.name}`,_1.info,_1.recognized)}disconnectAllDevicesFromSynth(){this.selectedInput=_m;for(let n of this.inputs)n[1].onmidimessage=void 0}};var MC=class{constructor(n){window.addEventListener("message",l=>{if(typeof l.data!="string")return;let g=l.data.split(",");if(g[0]!=="midi")return;g.shift();let u=g.map(S=>parseInt(S,16));n.sendMessage(u)}),Y5("%cWeb MIDI Link handler created!",_1.recognized)}};var TA="midi range";function Zy(o,n,l){let g=0,u=this.htmlControls.keyboard,S=()=>{let r0=document.createElement("option");r0.value=g.toString(),this.locale.bindObjectProperty(r0,"textContent","locale.settings.keyboardSettings.selectedChannel.channelOption",[g+1]),r0.style.background=n.channelColors[g%n.channelColors.length],r0.style.color="rgb(0, 0, 0)",u.channelSelector.appendChild(r0),g++};for(let r0=0;r0{o.selectChannel(parseInt(u.channelSelector.value))},u.sizeSelector.onchange=()=>{if(this.musicMode.visible){this.musicMode.setVisibility(!1,document.getElementById("keyboard_canvas_wrapper")),setTimeout(()=>{u.sizeSelector.value===TA?(this.autoKeyRange=!0,this?.sequi?.seq&&(o.keyRange=this.sequi.seq.midiData.keyRange,l.keyRange=this.sequi.seq.midiData.keyRange)):(this.autoKeyRange=!1,o.keyRange=this.keyboardSizes[u.sizeSelector.value],l.keyRange=this.keyboardSizes[u.sizeSelector.value]),this._saveSettings()},600);return}u.sizeSelector.value===TA?(this.autoKeyRange=!0,this?.sequi?.seq&&(o.keyRange=this.sequi.seq.midiData.keyRange,l.keyRange=this.sequi.seq.midiData.keyRange)):(this.autoKeyRange=!1,o.keyRange=this.keyboardSizes[u.sizeSelector.value],l.keyRange=this.keyboardSizes[u.sizeSelector.value]),this._saveSettings()},this.addSequencer=r0=>{r0.addOnSongChangeEvent(E0=>{this.autoKeyRange&&(o.keyRange=E0.keyRange,l.keyRange=E0.keyRange),E0.RMIDInfo?.IPIC!==void 0&&this.musicMode.visible===!1&&this.toggleMusicPlayerMode().then()},"settings-keyboard-handler-song-change")},n.synth.eventHandler.addEvent("newchannel","settings-new-channel",()=>{S()}),n.synth.eventHandler.addEvent("programchange","settings-keyboard-program-change",r0=>{r0.userCalled&&(o.selectChannel(r0.channel),u.channelSelector.value=r0.channel)}),n.synth.eventHandler.addEvent("mutechannel","settings-keuboard-mute-channel",r0=>{if(r0.isMuted&&r0.channel===o.channel){let E0=0;for(;n.synth.channelProperties[E0].isMuted;)E0++;E0{if(this.musicMode.visible){this.musicMode.setVisibility(!1,document.getElementById("keyboard_canvas_wrapper")),setTimeout(()=>{o.toggleMode(),this._saveSettings()},600);return}o.toggleMode(),this._saveSettings()},u.showSelector.onclick=()=>{o.shown=!o.shown,this._saveSettings()}}var Wy=` +`}function uh(o,n){let l=document.createElement("div");return l.classList.add("control_buttons"),l.title=o,l.innerHTML=n,l}var e7={synthesizerUIShow:"s",settingsShow:"r",blackMidiMode:"b",midiPanic:"backspace",playPause:" ",toggleLoop:"l",toggleLyrics:"t",seekBackwards:"arrowleft",seekForwards:"arrowright",previousSong:"[",nextSong:"]",cinematicMode:"c",videoMode:"v"};function Fy(){navigator.mediaSession&&(navigator.mediaSession.metadata=new MediaMetadata({title:this.currentSongTitle,artist:"SpessaSynth"}),navigator.mediaSession.setActionHandler("play",()=>{this.seqPlay()}),navigator.mediaSession.setActionHandler("pause",()=>{this.seqPause()}),navigator.mediaSession.setActionHandler("stop",()=>{this.seq.currentTime=0,this.seqPause()}),navigator.mediaSession.setActionHandler("seekbackward",o=>{this.seq.currentTime-=o.seekOffset||10}),navigator.mediaSession.setActionHandler("seekforward",o=>{this.seq.currentTime+=o.seekOffset||10}),navigator.mediaSession.setActionHandler("seekto",o=>{this.seq.currentTime=o.seekTime}),navigator.mediaSession.setActionHandler("previoustrack",()=>{this.switchToPreviousSong()}),navigator.mediaSession.setActionHandler("nexttrack",()=>{this.switchToNextSong()}),navigator.mediaSession.playbackState="playing")}function My(o=!0){if(this.seq?.hasDummyData===!0)this.currentSongTitle=this.locale.getLocaleString("locale.synthInit.genericLoading");else{let n=this.infoDecoder.decode(this.seq.midiData.rawMidiName.buffer).replace(/\0$/,"");this.currentSongTitle=FB(n)}if(this.seq.midiData){let n=this.seq.midiData.lyrics;this.currentLyrics=new Uint8Array(n.reduce((g,u)=>g+u.length,0));let l=0;for(let g of n)this.currentLyrics.set(g,l),l+=g.length;this.currentLyricsString=this.decodeTextFix(this.currentLyrics.buffer)||this.locale.getLocaleString("locale.sequencerController.lyrics.noLyrics"),this.setLyricsText(""),o&&(this.rawOtherTextEvents=[])}if(document.getElementById("title").innerText=this.currentSongTitle,document.title=this.currentSongTitle+" - SpessaSynth",this.musicModeUI.setTitle(this.currentSongTitle),!!navigator.mediaSession)try{navigator.mediaSession.setPositionState({duration:this.seq.duration,playbackRate:this.seq.playbackRate,position:this.seq.currentTime})}catch{}}var Hb=parseFloat(getComputedStyle(document.body).fontSize);function Ty(){this.lyricsElement={};let o=document.createElement("div");o.classList.add("lyrics");let n=document.createElement("div");n.classList.add("lyrics_title_wrapper"),o.append(n),this.lyricsElement.titleWrapper=n;let l=document.createElement("h2");this.locale.bindObjectProperty(l,"textContent","locale.sequencerController.lyrics.title"),l.classList.add("lyrics_title"),n.appendChild(l),this.lyricsElement.title=l;let g=document.createElement("select");Sm.forEach(u1=>{let R=document.createElement("option");R.innerText=u1,R.value=u1,g.appendChild(R)}),g.value=this.encoding,g.onchange=()=>this.changeEncoding(g.value),g.classList.add("lyrics_selector"),this.encodingSelector=g,n.appendChild(g);let u=document.createElement("p");u.classList.add("lyrics_text"),o.appendChild(u);let S=document.createElement("span");S.classList.add("lyrics_text_highlight"),u.appendChild(S);let r0=document.createElement("span");r0.classList.add("lyrics_text_gray"),u.appendChild(r0);let E0=document.createElement("details"),m0=document.createElement("summary");this.locale.bindObjectProperty(m0,"textContent","locale.sequencerController.lyrics.otherText.title"),E0.appendChild(m0);let g0=document.createElement("div");g0.innerText="",E0.appendChild(g0),o.appendChild(E0),this.lyricsElement.text={highlight:S,gray:r0,main:u,other:g0},this.lyricsElement.mainDiv=o,this.lyricsElement.selector=g,this.controls.appendChild(o),this.requiresTextUpdate=!0}function Ny(o){let n=this.lyricsElement.text.highlight,l=this.lyricsElement.text.gray;l.innerText=this.currentLyricsString.replace(o,""),n.innerText=o,this.lyricsElement.text.main.scrollTo(0,n.offsetHeight-Hb*5)}function Gy(){let o="";for(let n of this.rawOtherTextEvents)o+=`
${Object.keys(K3).find(l=>K3[l]===n.type).replace(/([a-z])([A-Z])/g,"$1 $2")}:
${this.decodeTextFix(n.data.buffer)}

`;this.lyricsElement.text.other.innerHTML=o}var Un=32,Uy="#ccc",Py="#555",qb="#333",Yb="#ddd",Jb="Shift_JIS",Ls=class{constructor(n,l,g){this.iconColor=Uy,this.iconDisabledColor=Py,this.controls=n,this.encoding=Jb,this.decoder=new TextDecoder(this.encoding),this.infoDecoder=new TextDecoder(this.encoding),this.hasInfoDecoding=!1,this.text="",this.requiresTextUpdate=!1,this.rawLyrics=[],this.rawOtherTextEvents=[],this.mode="dark",this.locale=l,this.currentSongTitle="",this.currentLyrics=new Uint8Array(0),this.currentLyricsString="",this.musicModeUI=g}toggleDarkMode(){if(this.mode==="dark"?(this.mode="light",this.iconColor=qb,this.iconDisabledColor=Yb):(this.mode="dark",this.iconColor=Uy,this.iconDisabledColor=Py),!this.seq){this.requiresThemeUpdate=!0;return}this.progressBar.classList.toggle("note_progress_light"),this.progressBarBackground.classList.toggle("note_progress_background_light"),this.lyricsElement.mainDiv.classList.toggle("lyrics_light"),this.lyricsElement.titleWrapper.classList.toggle("lyrics_light"),this.lyricsElement.selector.classList.toggle("lyrics_light")}seqPlay(n=!0){n&&this.seq.play(),this.playPause.innerHTML=y$(Un),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),navigator.mediaSession&&(navigator.mediaSession.playbackState="playing")}seqPause(n=!0){n&&this.seq.pause(),this.playPause.innerHTML=yy(Un),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),navigator.mediaSession&&(navigator.mediaSession.playbackState="paused")}switchToNextSong(){this.seq.nextSong(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus()}switchToPreviousSong(){this.seq.previousSong(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus()}decodeTextFix(n,l=!1){let g=0;for(;;)try{return this.decoder.decode(n)}catch{g++,this.changeEncoding(Sm[g]),this.encodingSelector.value=Sm[g]}}connectSequencer(n){this.seq=n,this.createControls(),this.setSliderInterval(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),this.seq.onTextEvent=(l,g)=>{let u=this.decodeTextFix(l.buffer);switch(g){default:return;case K3.text:case K3.copyright:case K3.cuePoint:case K3.trackName:case K3.instrumentName:case K3.programName:case K3.marker:this.rawOtherTextEvents.push({type:g,data:l}),this.requiresTextUpdate=!0;return;case K3.lyric:this.text+=u,this.rawLyrics.push(...l),this.setLyricsText(this.text);break}},this.seq.addOnTimeChangeEvent(()=>{this.text="",this.rawLyrics=[],this.seqPlay(!1)},"sequi-time-change"),this.seq.addOnSongChangeEvent(l=>{if(this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),this.seqPlay(!1),this.seq.songsAmount>1&&(this.seq.loop=!1,this.loopButton.firstElementChild.setAttribute("fill",this.iconDisabledColor)),this.hasInfoDecoding=this.seq.midiData.RMIDInfo?.[Mt.encoding]!==void 0,l.isEmbedded){let g=(E0,m0,g0,u1="")=>this.seq.midiData.RMIDInfo?.[E0]===void 0?m0:u1+g0.decode(this.seq.midiData.RMIDInfo?.[E0]).replace(/\0$/,""),u=new TextDecoder,S=g(Mt.midiEncoding,this.encoding,u),r0=g(Mt.encoding,"utf-8",u);this.infoDecoder=new TextDecoder(r0),this.changeEncoding(S)}},"sequi-song-change"),this.requiresThemeUpdate&&this.mode==="light"&&(this.mode="dark",this.toggleDarkMode())}changeEncoding(n){this.encoding=n,this.decoder=new TextDecoder(n),this.hasInfoDecoding||(this.infoDecoder=new TextDecoder(n)),this.updateOtherTextEvents(),this.text=this.decodeTextFix(new Uint8Array(this.rawLyrics).buffer),this.lyricsElement.selector.value=n,this.updateTitleAndMediaStatus(!1),this.setLyricsText(this.text)}createControls(){this.progressTime=document.createElement("p"),this.progressTime.id="note_time",this.progressTime.onclick=R=>{R.preventDefault();let Z0=n.getBoundingClientRect(),G0=R.clientX-Z0.left,b1=Z0.width;this.seq.currentTime=G0/b1*this.seq.duration,g.innerHTML=y$(Un)},this.createLyrics();let n=document.createElement("div");n.id="note_progress_background",this.progressBarBackground=n,this.progressBar=document.createElement("div"),this.progressBar.id="note_progress",this.progressBar.min="0",this.progressBar.max=this.seq.duration.toString();let l=document.createElement("div"),g=uh("Play/Pause",y$(Un));this.playPause=g,this.locale.bindObjectProperty(g,"title","locale.sequencerController.playPause");let u=()=>{this.seq.paused?this.seqPlay():this.seqPause()};g.onclick=u;let S=uh("Previous song",Sy(Un));this.locale.bindObjectProperty(S,"title","locale.sequencerController.previousSong"),S.onclick=()=>this.switchToPreviousSong();let r0=uh("Next song",vy(Un));this.locale.bindObjectProperty(r0,"title","locale.sequencerController.nextSong"),r0.onclick=()=>this.switchToNextSong();let E0=uh("Loop this",wy(Un));this.locale.bindObjectProperty(E0,"title","locale.sequencerController.loopThis");let m0=()=>{this.seq.loop?this.seq.loop=!1:(this.seq.loop=!0,this.seq.currentTime>=this.seq.duration&&(this.seq.currentTime=0)),E0.firstElementChild.setAttribute("fill",this.seq.loop?this.iconColor:this.iconDisabledColor)};E0.onclick=m0,this.loopButton=E0;let g0=uh("Show lyrics",ky(Un));this.locale.bindObjectProperty(g0,"title","locale.sequencerController.lyrics.show"),g0.firstElementChild.setAttribute("fill",this.iconDisabledColor);let u1=()=>{this.lyricsElement.mainDiv.classList.toggle("lyrics_show"),g0.firstElementChild.setAttribute("fill",this.lyricsElement.mainDiv.classList.contains("lyrics_show")?this.iconColor:this.iconDisabledColor)};g0.onclick=u1,document.addEventListener("keydown",R=>{switch(R.key.toLowerCase()){case e7.playPause:R.preventDefault(),u();break;case e7.toggleLoop:R.preventDefault(),m0();break;case e7.toggleLyrics:R.preventDefault(),u1();break;default:break}}),l.appendChild(S),l.appendChild(E0),l.appendChild(g),l.appendChild(g0),l.appendChild(r0),this.controls.appendChild(n),n.appendChild(this.progressBar),this.controls.appendChild(this.progressTime),this.controls.appendChild(l),document.addEventListener("keydown",R=>{switch(R.key.toLowerCase()){case e7.seekBackwards:R.preventDefault(),this.seq.currentTime-=5,g.innerHTML=y$(Un);break;case e7.seekForwards:R.preventDefault(),this.seq.currentTime+=5,g.innerHTML=y$(Un);break;case e7.previousSong:this.switchToPreviousSong();break;case e7.nextSong:this.switchToNextSong();break;default:if(!isNaN(parseFloat(R.key))){R.preventDefault();let Z0=parseInt(R.key);0<=Z0&&Z0<=9&&(this.seq.currentTime=this.seq.duration*(Z0/10),g.innerHTML=y$(Un))}break}})}_updateInterval(){this.progressBar.style.width=`${this.seq.currentTime/this.seq.duration*100}%`;let n=E$(this.seq.currentTime),l=E$(this.seq.duration);this.progressTime.innerText=`${n.time} / ${l.time}`,this.requiresTextUpdate&&(this.updateOtherTextEvents(),this.requiresTextUpdate=!1)}setSliderInterval(){setInterval(this._updateInterval.bind(this),100)}};Ls.prototype.createNavigatorHandler=Fy;Ls.prototype.updateTitleAndMediaStatus=My;Ls.prototype.createLyrics=Ty;Ls.prototype.setLyricsText=Ny;Ls.prototype.updateOtherTextEvents=Gy;function Oy(){this.controllers.forEach(o=>{o.voiceMeter.hide(),o.pitchWheel.hide(),o.pan.hide(),o.expression.hide(),o.volume.hide(),o.mod.hide(),o.chorus.hide(),o.reverb.hide(),o.brightness.hide(),o.preset.hide()})}function Hy(){this.controllers.forEach(o=>{o.voiceMeter.show(),o.pitchWheel.show(),o.pan.show(),o.expression.show(),o.volume.show(),o.mod.show(),o.chorus.show(),o.reverb.show(),o.brightness.show(),o.preset.show()})}function qy(){this.mainControllerDiv.classList.toggle("synthui_controller_light"),this.mainButtons.forEach(o=>{o.classList.toggle("synthui_button"),o.classList.toggle("synthui_button_light")}),this.mainMeters.forEach(o=>{o.toggleMode(!0)}),this.controllers.forEach(o=>{o.voiceMeter.toggleMode(),o.pitchWheel.toggleMode(),o.pan.toggleMode(),o.expression.toggleMode(),o.volume.toggleMode(),o.mod.toggleMode(),o.chorus.toggleMode(),o.reverb.toggleMode(),o.brightness.toggleMode(),o.preset.toggleMode(),o.drumsToggle.classList.toggle("mute_button_light"),o.muteButton.classList.toggle("mute_button_light")})}var hn=class{constructor(n="none",l,g,u,S=0,r0=100,E0=!1,m0=void 0,g0=void 0,u1=void 0){if(this.meterText="",g.bindObjectProperty(this,"meterText",l+".title"),this.min=S,this.max=r0,this.currentValue=-1,this.isShown=!0,this.isVisualValueSet=!0,this.isLocked=!1,this.lockCallback=g0,this.unlockCallback=u1,this.div=document.createElement("div"),this.div.classList.add("voice_meter"),this.div.classList.add("controller_element"),n!=="none"&&n!==""&&(this.div.style.borderColor=n),g.bindObjectProperty(this.div,"title",l+".description",u),this.bar=document.createElement("div"),this.bar.classList.add("voice_meter_bar"),this.bar.style.background=n,this.div.appendChild(this.bar),this.text=document.createElement("p"),this.text.classList.add("voice_meter_text"),this.div.appendChild(this.text),this.isActive=!1,E0){if(m0===void 0)throw new Error("No editable function given!");this.div.onmousedown=R=>{R.preventDefault(),R.button===0?this.isActive=!0:this.lockMeter()},this.div.onmousemove=R=>{if(!this.isActive)return;let Z0=R.currentTarget.getBoundingClientRect(),G0=Z0.left,b1=Z0.width,l2=R.clientX-G0,y1=Math.max(0,Math.min(1,l2/b1));m0(y1*(r0-S)+S)},this.div.onmouseup=()=>this.isActive=!1,this.div.onmouseleave=R=>{this.div.onmousemove(R),this.isActive=!1},this.text.oncontextmenu=R=>{R.preventDefault()},this.div.onclick=R=>{R.preventDefault(),this.isActive=!0,this.div.onmousemove(R),this.isActive=!1},this.div.classList.add("editable")}}lockMeter(){this.lockCallback!==void 0&&(this.isLocked?(this.text.classList.remove("locked_meter"),this.unlockCallback()):(this.text.classList.add("locked_meter"),this.lockCallback()),this.isLocked=!this.isLocked)}toggleMode(n=!1){n&&(this.bar.classList.toggle("voice_meter_light_color"),this.div.classList.toggle("voice_meter_light_color")),this.text.classList.toggle("voice_meter_text_light")}show(){if(this.isShown=!0,!this.isVisualValueSet){let n=Math.max(0,Math.min((this.currentValue-this.min)/(this.max-this.min),1));this.bar.style.width=`${n*100}%`,this.text.textContent=this.meterText+(Math.round(this.currentValue*100)/100).toString(),this.isVisualValueSet=!0}}hide(){this.isShown=!1}update(n,l=!1){if(!(n===this.currentValue&&l===!1))if(this.currentValue=n,this.isShown){let g=Math.max(0,Math.min((n-this.min)/(this.max-this.min),1));this.bar.style.width=`${g*100}%`,this.text.textContent=this.meterText+(Math.round(n*100)/100).toString(),this.isVisualValueSet=!0}else this.isVisualValueSet=!1}};var Yy=["Acoustic Grand Piano","Bright Acoustic Piano","Electric Grand Piano","Honky-tonk Piano","Electric Piano 1","Electric Piano 2","Harpsichord","Clavi","Celesta","Glockenspiel","Music Box","Vibraphone","Marimba","Xylophone","Tubular Bells","Dulcimer","Drawbar Organ","Percussive Organ","Rock Organ","Church Organ","Reed Organ","Accordion","Harmonica","Tango Accordion","Acoustic Guitar (nylon)","Acoustic Guitar (steel)","Electric Guitar (jazz)","Electric Guitar (clean)","Electric Guitar (muted)","Overdriven Guitar","Distortion Guitar","Guitar Harmonics","Acoustic Bass","Electric Bass (finger)","Electric Bass (pick)","Fretless Bass","Slap Bass 1","Slap Bass 2","Synth Bass 1","Synth Bass 2","Violin","Viola","Cello","Contrabass","Tremolo Strings","Pizzicato Strings","Orchestral Harp","Timpani","String Ensemble 1","String Ensemble 2","Synth Strings 1","Synth Strings 2","Choir Aahs","VoiceGroup Oohs","Synth Choir","Orchestra Hit","Trumpet","Trombone","Tuba","Muted Trumpet","French Horn","Brass Section","Synth Brass 1","Synth Brass 2","Soprano Sax","Alto Sax","Tenor Sax","Baritone Sax","Oboe","English Horn","Bassoon","Clarinet","Piccolo","Flute","Recorder","Pan Flute","Blown Bottle","Shakuhachi","Whistle","Ocarina","Lead 1 (square)","Lead 2 (sawtooth)","Lead 3 (calliope)","Lead 4 (chiff)","Lead 5 (charang)","Lead 6 (voice)","Lead 7 (fifths)","Lead 8 (bass + lead)","Pad 1 (new age)","Pad 2 (warm)","Pad 3 (polysynth)","Pad 4 (choir)","Pad 5 (bowed)","Pad 6 (metallic)","Pad 7 (halo)","Pad 8 (sweep)","FX 1 (rain)","FX 2 (soundtrack)","FX 3 (crystal)","FX 4 (atmosphere)","FX 5 (brightness)","FX 6 (goblins)","FX 7 (echoes)","FX 8 (sci-fi)","Sitar","Banjo","Shamisen","Koto","Kalimba","Bagpipe","Fiddle","Shanai","Tinkle Bell","Agogo","Steel Drums","Woodblock","Taiko Drum","Melodic Tom","Synth Drum","Reverse Cymbal","Guitar Fret Noise","Breath Noise","Seashore","Bird Tweet","Telephone Ring","Attack Helicopter","Applause","Gunshot"];var LC=class{constructor(n,l,g,u,S=void 0,r0=void 0){this.isShown=!0,this.isReloaded=!0,this.elements=n.map(E0=>({name:E0.name,program:E0.program,bank:E0.bank,stringified:`${E0.bank.toString().padStart(3,"0")}:${E0.program.toString().padStart(3,"0")} ${E0.name}`})),this.elements.length>0?this.value=`${this.elements[0].bank}:${this.elements[0].program}`:this.value="",this.mainButton=document.createElement("button"),this.mainButton.classList.add("voice_selector"),this.mainButton.classList.add("controller_element"),l.bindObjectProperty(this.mainButton,"title",g+".description",u),this.locale=l,this.localePath=g,this.localeArgs=u,this.reload(),this.mainButton.onclick=()=>{this.showSelectionMenu()},this.editCallback=S,this.selectionMenu=void 0,this.lockCallback=r0,this.locked=!1,this.isWindowShown=!1}showSelectionMenu(){this.selectionMenu=document.createElement("div"),this.selectionMenu.classList.add("voice_selector_wrapper"),document.getElementsByClassName("spessasynth_main")[0].appendChild(this.selectionMenu);let n=document.createElement("div");n.classList.add("voice_selector_window");let l=document.createElement("h2");this.locale.bindObjectProperty(l,"textContent",this.localePath+".selectionPrompt",this.localeArgs),n.appendChild(l);let g=document.createElement("div");g.classList.add("voice_selector_search_wrapper"),n.appendChild(g);let u=document.createElement("input");u.type="text",this.locale.bindObjectProperty(u,"placeholder",this.localePath+".searchPrompt"),g.appendChild(u),u.onkeydown=E0=>E0.stopPropagation();let S=document.createElement("div");S.innerHTML=this.locked?xC(h7):JB(h7),this.locale.bindObjectProperty(S,"title",oe+"channelController.presetReset.description",this.localeArgs),S.classList.add("voice_reset"),this.mainButton.classList.contains("voice_selector_light")&&S.classList.add("voice_reset_light"),S.onclick=()=>{this.locked=!this.locked,this.lockCallback(this.locked),this.mainButton.classList.toggle("locked_selector"),this.locked?S.innerHTML=xC(h7):S.innerHTML=JB(h7)},g.appendChild(S),this.presetLock=S;let r0=document.createElement("div");r0.classList.add("voice_selector_table_wrapper"),n.appendChild(r0),this.generateTable(r0,this.elements),u.oninput=E0=>{E0.stopPropagation();let m0=u.value,g0=this.elements.filter(u1=>u1.stringified.search(new RegExp(m0,"i"))>=0);g0.length!==this.elements.length&&(r0.replaceChildren(),this.generateTable(r0,g0))},n.onclick=E0=>{E0.stopPropagation()},this.selectionMenu.appendChild(n),this.selectionMenu.onclick=E0=>{E0.stopPropagation(),this.hideSelectionMenu()},this.isWindowShown=!0}generateTable(n,l){let g=document.createElement("table");g.classList.add("voice_selector_table");let u=parseInt(this.value.split(":")[0]),S=parseInt(this.value.split(":")[1]),r0=-20;for(let E0 of l){let m0=document.createElement("tr"),g0=E0.program;if(g0===S&&E0.bank===u&&(m0.classList.add("voice_selector_selected"),setTimeout(()=>{m0.scrollIntoView({behavior:"instant",block:"center",inline:"center"})},20)),m0.onclick=()=>{let l2=`${E0.bank}:${g0}`;if(this.value===l2){this.hideSelectionMenu();return}this.editCallback(l2),this.locked=!0,this.presetLock.innerHTML=xC(h7),this.hideSelectionMenu()},g0!==r0&&(r0=g0,E0.bank!==128)){let l2=document.createElement("tr"),y1=document.createElement("th");y1.colSpan="3",y1.textContent=Yy[r0],l2.appendChild(y1),g.appendChild(l2)}let u1=`${E0.program.toString().padStart(3,"0")}`,R=`${E0.bank.toString().padStart(3,"0")}`,Z0=document.createElement("td");Z0.classList.add("voice_selector_preset_name"),Z0.textContent=E0.name;let G0=document.createElement("td");Z0.classList.add("voice_selector_preset_program"),G0.textContent=u1;let b1=document.createElement("td");Z0.classList.add("voice_selector_preset_program"),b1.textContent=R,m0.appendChild(b1),m0.appendChild(G0),m0.appendChild(Z0),g.appendChild(m0)}n.appendChild(g)}hideSelectionMenu(){document.getElementsByClassName("spessasynth_main")[0].removeChild(this.selectionMenu),this.selectionMenu=void 0,this.isWindowShown=!1}toggleMode(){this.mainButton.classList.toggle("voice_selector_light")}reload(n=this.elements){if(this.elements=n.map(l=>({name:l.name,program:l.program,bank:l.bank,stringified:`${l.bank.toString().padStart(3,"0")}:${l.program.toString().padStart(3,"0")} ${l.name}`})),!this.isShown){this.isReloaded=!1;return}this.isReloaded=!0,this.elements.length>0&&(this.mainButton.textContent=this.getString(`${this.elements[0].bank}:${this.value.split(":")[1]}`))}set(n){if(this.value=n,this.isShown&&(this.isReloaded||this.reload(),this.mainButton.textContent=this.getString(this.value),this.isWindowShown)){let l=this.selectionMenu.getElementsByClassName("voice_selector_selected")[0];l!==void 0&&l.classList.remove("voice_selector_selected");let g=this.selectionMenu.getElementsByClassName("voice_selector_table")[0],u=parseInt(this.value.split(":")[0]),S=parseInt(this.value.split(":")[1]);for(let r0 of g.rows){if(r0.cells.length===1)continue;let E0=parseInt(r0.cells[0].textContent),m0=parseInt(r0.cells[1].textContent);E0===u&&m0===S&&(r0.classList.add("voice_selector_selected"),r0.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}))}}}getString(n){let l=n.split(":"),g=parseInt(l[0]),u=parseInt(l[1]),S=this.elements.find(r0=>r0.bank===g&&r0.program===u);return g===128||this.elements.filter(r0=>r0.program===u&&r0.bank!==128).length<2?`${u}. ${S.name}`:`${g}:${u} ${S.name}`}show(){this.isShown=!0,this.isReloaded||this.reload(),this.mainButton.textContent=this.getString(this.value)}hide(){this.isShown=!1}};var h7=32;function Jy(o){this.soloChannels=new Set;let n=document.createElement("div");n.classList.add("channel_controller");let l=new hn(this.channelColors[o%this.channelColors.length],oe+"channelController.voiceMeter",this.locale,[o+1],0,100);l.bar.classList.add("voice_meter_bar_smooth"),n.appendChild(l.div);let g=new hn(this.channelColors[o%this.channelColors.length],oe+"channelController.pitchBendMeter",this.locale,[o+1],-8192,8191,!0,T2=>{let K2=g.isLocked;K2&&this.synth.lockController(o,C$+Ft.pitchWheel,!1),T2=Math.round(T2)+8192;let i3=T2>>7,n3=T2&127;this.synth.pitchWheel(o,i3,n3),K2&&this.synth.lockController(o,C$+Ft.pitchWheel,!0)},()=>this.synth.lockController(o,C$+Ft.pitchWheel,!0),()=>this.synth.lockController(o,C$+Ft.pitchWheel,!1));g.update(0),n.appendChild(g.div);let u=(T2,K2,i3)=>{i3.isLocked?(this.synth.lockController(o,T2,!1),this.synth.controllerChange(o,T2,K2),this.synth.lockController(o,T2,!0)):this.synth.controllerChange(o,T2,K2)},S=(T2,K2,i3)=>{let n3=new hn(this.channelColors[o%this.channelColors.length],oe+K2,this.locale,[o+1],0,127,!0,A0=>u(T2,Math.round(A0),n3),()=>this.synth.lockController(o,T2,!0),()=>this.synth.lockController(o,T2,!1));return n3.update(i3),n3},r0=S(t6.pan,"channelController.panMeter",64);n.appendChild(r0.div);let E0=S(t6.expressionController,"channelController.expressionMeter",127);n.appendChild(E0.div);let m0=S(t6.mainVolume,"channelController.volumeMeter",100);n.appendChild(m0.div);let g0=S(t6.modulationWheel,"channelController.modulationWheelMeter",0);n.appendChild(g0.div);let u1=S(t6.effects3Depth,"channelController.chorusMeter",0);n.appendChild(u1.div);let R=S(t6.effects1Depth,"channelController.reverbMeter",0);n.appendChild(R.div);let Z0=S(t6.brightness,"channelController.filterMeter",64);n.appendChild(Z0.div);let G0=new hn(this.channelColors[o%this.channelColors.length],oe+"channelController.transposeMeter",this.locale,[o+1],-36,36,!0,T2=>{T2=Math.round(T2),this.synth.transposeChannel(o,T2,!0),G0.update(T2)});G0.update(0),n.appendChild(G0.div);let b1=new LC([],this.locale,oe+"channelController.presetSelector",[o+1],async T2=>{let K2=T2.split(":");this.synth.lockController(o,mi,!1),this.synth.controllerChange(o,t6.bankSelect,parseInt(K2[0]),!0),this.synth.programChange(o,parseInt(K2[1]),!0),b1.mainButton.classList.add("locked_selector"),this.synth.lockController(o,mi,!0)},T2=>this.synth.lockController(o,mi,T2));n.appendChild(b1.mainButton);let l2=document.createElement("div");l2.innerHTML=fh(h7),this.locale.bindObjectProperty(l2,"title",oe+"channelController.soloButton.description",[o+1]),l2.classList.add("controller_element"),l2.classList.add("mute_button"),l2.onclick=()=>{if(this.soloChannels.has(o)?this.soloChannels.delete(o):this.soloChannels.add(o),this.soloChannels.size===0||this.soloChannels.size>=this.synth.channelsAmount){for(let T2=0;T2=this.synth.channelsAmount&&this.soloChannels.clear();return}for(let T2=0;T2{if(y1.hasAttribute("is_muted")){y1.removeAttribute("is_muted");let T2=this.soloChannels.size===0||this.soloChannels.has(o);this.synth.muteChannel(o,!T2),y1.innerHTML=bm(h7)}else this.synth.muteChannel(o,!0),y1.setAttribute("is_muted","true"),y1.innerHTML=Dy(h7)},n.appendChild(y1);let Y2=document.createElement("div");return Y2.innerHTML=o===Di?_C(h7):RC(h7),this.locale.bindObjectProperty(Y2,"title",oe+"channelController.drumToggleButton.description",[o+1]),Y2.classList.add("controller_element"),Y2.classList.add("mute_button"),Y2.onclick=()=>{this.synth.setDrums(o,!this.synth.channelProperties[o].isDrum)},n.appendChild(Y2),{controller:n,voiceMeter:l,pitchWheel:g,pan:r0,expression:E0,volume:m0,mod:g0,chorus:u1,reverb:R,brightness:Z0,preset:b1,drumsToggle:Y2,soloButton:l2,muteButton:y1,transpose:G0}}function Ky(){let o=this.uiDiv.getElementsByClassName("synthui_controller")[0];this.controllers=[];for(let n=0;n{this.synth.setMainVolume(Math.round(g0)/100),this.volumeController.update(g0)}),this.volumeController.bar.classList.add("voice_meter_bar_smooth"),this.volumeController.div.classList.add("main_controller_element"),this.volumeController.update(100),this.panController=new hn("",oe+"mainPanMeter",this.locale,[],-1,1,!0,g0=>{this.synth.setMasterPan(g0),this.panController.update(g0)}),this.panController.bar.classList.add("voice_meter_bar_smooth"),this.panController.div.classList.add("main_controller_element"),this.panController.update(0),this.transposeController=new hn("",oe+"mainTransposeMeter",this.locale,[],-12,12,!0,g0=>{this.synth.transpose(Math.round(g0*2)/2),this.transposeController.update(Math.round(g0*2)/2)}),this.transposeController.bar.classList.add("voice_meter_bar_smooth"),this.transposeController.div.classList.add("main_controller_element"),this.transposeController.update(0);let n=document.createElement("button");this.locale.bindObjectProperty(n,"textContent",oe+"midiPanic.title"),this.locale.bindObjectProperty(n,"title",oe+"midiPanic.description"),n.classList.add("synthui_button"),n.classList.add("main_controller_element"),n.onclick=()=>this.synth.stopAll(!0);let l=document.createElement("button");this.locale.bindObjectProperty(l,"textContent",oe+"systemReset.title"),this.locale.bindObjectProperty(l,"title",oe+"systemReset.description"),l.classList.add("synthui_button"),l.classList.add("main_controller_element"),l.onclick=()=>{this.controllers.forEach((g0,u1)=>{g0.pitchWheel.isLocked&&g0.pitchWheel.lockMeter(),g0.pan.isLocked&&g0.pan.lockMeter(),g0.expression.isLocked&&g0.expression.lockMeter(),g0.volume.isLocked&&g0.volume.lockMeter(),g0.mod.isLocked&&g0.mod.lockMeter(),g0.chorus.isLocked&&g0.chorus.lockMeter(),g0.reverb.isLocked&&g0.reverb.lockMeter(),g0.brightness.isLocked&&g0.brightness.lockMeter(),g0.preset.mainButton.classList.contains("locked_selector")&&(this.synth.lockController(u1,mi,!1),g0.preset.mainButton.classList.remove("locked_selector")),this.synth.transposeChannel(u1,0,!0),g0.transpose.update(0),g0.soloButton.innerHTML=fh(h7),g0.muteButton.innerHTML=bm(h7),this.synth.muteChannel(u1,!1)}),this.synth.resetControllers()};let g=document.createElement("button");this.locale.bindObjectProperty(g,"textContent",oe+"blackMidiMode.title"),this.locale.bindObjectProperty(g,"title",oe+"blackMidiMode.description"),g.classList.add("synthui_button"),g.classList.add("main_controller_element"),g.onclick=()=>{this.synth.highPerformanceMode=!this.synth.highPerformanceMode};let u=document.createElement("button");this.locale.bindObjectProperty(u,"textContent",oe+"disableCustomVibrato.title"),this.locale.bindObjectProperty(u,"title",oe+"disableCustomVibrato.description"),u.classList.add("synthui_button"),u.classList.add("main_controller_element"),u.onclick=()=>{this.synth.disableGSNRPparams(),u.parentNode.removeChild(u)};let S=document.createElement("a");S.href="https://github.com/spessasus/SpessaSynth/wiki/How-To-Use-App#synthesizer-controller",S.target="#",S.classList.add("main_controller_element"),S.classList.add("synthui_button"),this.locale.bindObjectProperty(S,"textContent",oe+"helpButton.title"),this.locale.bindObjectProperty(S,"title",oe+"helpButton.description");let r0=document.createElement("select");r0.classList.add("main_controller_element"),r0.classList.add("synthui_button"),this.locale.bindObjectProperty(r0,"title",oe+"interpolation.description");{let g0=document.createElement("option");g0.value="0",this.locale.bindObjectProperty(g0,"textContent",oe+"interpolation.linear"),r0.appendChild(g0);let u1=document.createElement("option");u1.value="1",this.locale.bindObjectProperty(u1,"textContent",oe+"interpolation.nearestNeighbor"),r0.appendChild(u1);let R=document.createElement("option");R.value="2",R.selected=!0,this.locale.bindObjectProperty(R,"textContent",oe+"interpolation.cubic"),r0.appendChild(R),r0.onchange=()=>{this.synth.setInterpolationType(parseInt(r0.value))}}let E0=document.createElement("div");E0.classList.add("synthui_controller"),this.uiDiv.appendChild(E0);let m0=document.createElement("button");this.locale.bindObjectProperty(m0,"textContent",oe+"toggleButton.title"),this.locale.bindObjectProperty(m0,"title",oe+"toggleButton.description"),m0.classList.add("synthui_button"),m0.onclick=()=>{this.hideOnDocClick=!1,this.toggleVisibility()},o.appendChild(this.volumeController.div),o.appendChild(this.panController.div),o.appendChild(this.transposeController.div),o.appendChild(n),o.appendChild(l),o.appendChild(g),o.appendChild(u),o.appendChild(S),o.appendChild(r0),this.mainMeters=[this.volumeController,this.panController,this.transposeController,this.voiceMeter],this.mainButtons=[n,l,g,u,m0,S,r0],this.uiDiv.appendChild(this.voiceMeter.div),this.uiDiv.appendChild(m0),E0.appendChild(o),this.mainControllerDiv=E0,this.mainControllerDiv.onclick=g0=>g0.stopPropagation(),document.addEventListener("click",()=>{if(!this.hideOnDocClick){this.hideOnDocClick=!0;return}E0.classList.remove("synthui_controller_show"),this.isShown=!1,this.hideControllers()})}function zy(){let o=this.uiDiv.getElementsByClassName("synthui_controller")[0];this.synth.eventHandler.addEvent("programchange","synthui-program-change",n=>{this.controllers[n.channel].preset.set(`${n.bank}:${n.program}`)}),this.synth.eventHandler.addEvent("allcontrollerreset","synthui-all-controller-reset",()=>{for(let n of this.controllers)n.pan.update(64),n.mod.update(0),n.chorus.update(0),n.pitchWheel.update(0),n.expression.update(127),n.volume.update(100),n.reverb.update(0),n.brightness.update(64)}),this.synth.eventHandler.addEvent("controllerchange","synthui-controller-change",n=>{let l=n.controllerNumber,g=n.channel,u=n.controllerValue;switch(l){default:break;case t6.expressionController:this.controllers[g].expression.update(u);break;case t6.mainVolume:this.controllers[g].volume.update(u);break;case t6.pan:this.controllers[g].pan.update(u);break;case t6.modulationWheel:this.controllers[g].mod.update(u);break;case t6.effects3Depth:this.controllers[g].chorus.update(u);break;case t6.effects1Depth:this.controllers[g].reverb.update(u);break;case t6.brightness:this.controllers[g].brightness.update(u)}}),this.synth.eventHandler.addEvent("pitchwheel","synthui-pitch-wheel",n=>{let l=n.MSB<<7|n.LSB;this.controllers[n.channel].pitchWheel.update(l-8192)}),this.synth.eventHandler.addEvent("drumchange","synthui-drum-change",n=>{this.controllers[n.channel].drumsToggle.innerHTML=n.isDrumChannel?_C(32):RC(32),this.controllers[n.channel].preset.reload(n.isDrumChannel?this.percussionList:this.instrumentList)}),this.synth.eventHandler.addEvent("newchannel","synthui-new-channel",()=>{let n=this.createChannelController(this.controllers.length);this.controllers.push(n),o.appendChild(n.controller),this.hideControllers()})}var oe="locale.synthesizerController.",Pn=class{constructor(n,l,g){this.channelColors=n;let u=l;this.uiDiv=document.createElement("div"),this.uiDiv.classList.add("wrapper"),u.appendChild(this.uiDiv),this.uiDiv.style.visibility="visible",this.isShown=!1,this.animationId=-1,this.locale=g,this.hideOnDocClick=!0}connectSynth(n){this.synth=n,this.getInstrumentList(),this.createMainSynthController(),this.createChannelControllers(),document.addEventListener("keydown",l=>{switch(l.key.toLowerCase()){case e7.synthesizerUIShow:l.preventDefault(),this.toggleVisibility();break;case e7.settingsShow:this.isShown=!0,this.toggleVisibility();break;case e7.blackMidiMode:l.preventDefault(),this.synth.highPerformanceMode=!this.synth.highPerformanceMode;break;case e7.midiPanic:l.preventDefault(),this.synth.stopAll(!0);break}}),this.locale.onLocaleChanged.push(()=>{this.voiceMeter.update(this.voiceMeter.currentValue,!0),this.volumeController.update(this.volumeController.currentValue,!0),this.panController.update(this.panController.currentValue,!0),this.panController.update(this.panController.currentValue,!0),this.transposeController.update(this.transposeController.currentValue,!0);for(let l of this.controllers)l.voiceMeter.update(l.voiceMeter.currentValue,!0),l.pitchWheel.update(l.pitchWheel.currentValue,!0),l.pan.update(l.pan.currentValue,!0),l.volume.update(l.volume.currentValue,!0),l.expression.update(l.expression.currentValue,!0),l.mod.update(l.mod.currentValue,!0),l.chorus.update(l.chorus.currentValue,!0),l.reverb.update(l.reverb.currentValue,!0),l.brightness.update(l.brightness.currentValue,!0),l.transpose.update(l.transpose.currentValue,!0)})}toggleVisibility(){this.animationId!==-1&&clearTimeout(this.animationId);let n=document.getElementsByClassName("synthui_controller")[0];this.isShown=!this.isShown,this.isShown?(n.style.display="block",document.getElementsByClassName("top_part")[0].classList.add("synthui_shown"),this.showControllers(),setTimeout(()=>{n.classList.add("synthui_controller_show")},75)):(document.getElementsByClassName("top_part")[0].classList.remove("synthui_shown"),this.hideControllers(),n.classList.remove("synthui_controller_show"),this.animationId=setTimeout(()=>{n.style.display="none"},200))}updateVoicesAmount(){this.voiceMeter.update(this.synth.voicesAmount),this.controllers.forEach((n,l)=>{let g=this.synth.channelProperties[l].voicesAmount;n.voiceMeter.update(g),g<1&&this.synth.voicesAmount>0?n.controller.classList.add("no_voices"):n.controller.classList.remove("no_voices")})}getInstrumentList(){this.synth.eventHandler.addEvent("presetlistchange","synthui-preset-list-change",n=>{let l=n;this.instrumentList=l.filter(g=>g.bank!==128).sort((g,u)=>g.program===u.program?g.bank-u.bank:g.program-u.program).map(g=>({name:g.presetName,bank:g.bank,program:g.program})),this.percussionList=l.filter(g=>g.bank===128).sort((g,u)=>g.program-u.program).map(g=>({name:g.presetName,bank:g.bank,program:g.program})),this.percussionList.length===0?this.percussionList=this.instrumentList:this.instrumentList.length===0&&(this.instrumentList=this.percussionList),this.controllers.forEach((g,u)=>{let S=this.synth.channelProperties[u].isDrum?this.percussionList:this.instrumentList;g.preset.reload(S),g.preset.set(`${S[0].bank}:${S[0].program}`)})})}};Pn.prototype.hideControllers=Oy;Pn.prototype.showControllers=Hy;Pn.prototype.toggleDarkMode=qy;Pn.prototype.createChannelController=Jy;Pn.prototype.createChannelControllers=Ky;Pn.prototype.createMainSynthController=Vy;Pn.prototype.setEventListeners=zy;var _m=null,FC=class{constructor(){}async createMIDIDeviceHandler(){if(this.selectedInput=_m,this.selectedOutput=_m,navigator.requestMIDIAccess)try{let n=await navigator.requestMIDIAccess({sysex:!0,software:!0});return this.inputs=n.inputs,this.outputs=n.outputs,Y5("%cMIDI handler created!",_1.recognized),!0}catch(n){return R4("Could not get MIDI Devices:",n),this.inputs=[],this.outputs=[],!1}else return R4("Web MIDI Api not supported!",_1.unrecognized),this.inputs=[],this.outputs=[],!1}connectMIDIOutputToSeq(n,l){this.selectedOutput=n,l.connectMidiOutput(n),Y5(`%cPlaying MIDI to %c${n.name}`,_1.info,_1.recognized)}disconnectSeqFromMIDI(n){this.selectedOutput=_m,n.connectMidiOutput(void 0),Y5("%cDisconnected from MIDI out.",_1.info)}connectDeviceToSynth(n,l){this.selectedInput=n,n.onmidimessage=g=>{l.sendMessage(g.data)},Y5(`%cListening for messages on %c${n.name}`,_1.info,_1.recognized)}disconnectDeviceFromSynth(n){this.selectedInput=_m,n.onmidimessage=void 0,Y5(`%cDisconnected from %c${n.name}`,_1.info,_1.recognized)}disconnectAllDevicesFromSynth(){this.selectedInput=_m;for(let n of this.inputs)n[1].onmidimessage=void 0}};var MC=class{constructor(n){window.addEventListener("message",l=>{if(typeof l.data!="string")return;let g=l.data.split(",");if(g[0]!=="midi")return;g.shift();let u=g.map(S=>parseInt(S,16));n.sendMessage(u)}),Y5("%cWeb MIDI Link handler created!",_1.recognized)}};var TA="midi range";function Zy(o,n,l){let g=0,u=this.htmlControls.keyboard,S=()=>{let r0=document.createElement("option");r0.value=g.toString(),this.locale.bindObjectProperty(r0,"textContent","locale.settings.keyboardSettings.selectedChannel.channelOption",[g+1]),r0.style.background=n.channelColors[g%n.channelColors.length],r0.style.color="rgb(0, 0, 0)",u.channelSelector.appendChild(r0),g++};for(let r0=0;r0{o.selectChannel(parseInt(u.channelSelector.value))},u.sizeSelector.onchange=()=>{if(this.musicMode.visible){this.musicMode.setVisibility(!1,document.getElementById("keyboard_canvas_wrapper")),setTimeout(()=>{u.sizeSelector.value===TA?(this.autoKeyRange=!0,this?.sequi?.seq&&(o.keyRange=this.sequi.seq.midiData.keyRange,l.keyRange=this.sequi.seq.midiData.keyRange)):(this.autoKeyRange=!1,o.keyRange=this.keyboardSizes[u.sizeSelector.value],l.keyRange=this.keyboardSizes[u.sizeSelector.value]),this._saveSettings()},600);return}u.sizeSelector.value===TA?(this.autoKeyRange=!0,this?.sequi?.seq&&(o.keyRange=this.sequi.seq.midiData.keyRange,l.keyRange=this.sequi.seq.midiData.keyRange)):(this.autoKeyRange=!1,o.keyRange=this.keyboardSizes[u.sizeSelector.value],l.keyRange=this.keyboardSizes[u.sizeSelector.value]),this._saveSettings()},this.addSequencer=r0=>{r0.addOnSongChangeEvent(E0=>{this.autoKeyRange&&(o.keyRange=E0.keyRange,l.keyRange=E0.keyRange),E0.RMIDInfo?.IPIC!==void 0&&this.musicMode.visible===!1&&this.toggleMusicPlayerMode().then()},"settings-keyboard-handler-song-change")},n.synth.eventHandler.addEvent("newchannel","settings-new-channel",()=>{S()}),n.synth.eventHandler.addEvent("programchange","settings-keyboard-program-change",r0=>{r0.userCalled&&(o.selectChannel(r0.channel),u.channelSelector.value=r0.channel)}),n.synth.eventHandler.addEvent("mutechannel","settings-keuboard-mute-channel",r0=>{if(r0.isMuted&&r0.channel===o.channel){let E0=0;for(;n.synth.channelProperties[E0].isMuted;)E0++;E0{if(this.musicMode.visible){this.musicMode.setVisibility(!1,document.getElementById("keyboard_canvas_wrapper")),setTimeout(()=>{o.toggleMode(),this._saveSettings()},600);return}o.toggleMode(),this._saveSettings()},u.showSelector.onclick=()=>{o.shown=!o.shown,this._saveSettings()}}var Wy=`

diff --git a/src/website/minified/local_main.min.js b/src/website/minified/local_main.min.js index d3655567..2cf94edb 100644 --- a/src/website/minified/local_main.min.js +++ b/src/website/minified/local_main.min.js @@ -68,7 +68,7 @@ var hC=(A=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(A,{get:(r,l)=>( `}function UB(A){return` -`}function gh(A,r){let l=document.createElement("div");return l.classList.add("control_buttons"),l.title=A,l.innerHTML=r,l}var X7={synthesizerUIShow:"s",settingsShow:"r",blackMidiMode:"b",midiPanic:"backspace",playPause:" ",toggleLoop:"l",toggleLyrics:"t",seekBackwards:"arrowleft",seekForwards:"arrowright",previousSong:"[",nextSong:"]",cinematicMode:"c",videoMode:"v"};function vy(){navigator.mediaSession&&(navigator.mediaSession.metadata=new MediaMetadata({title:this.currentSongTitle,artist:"SpessaSynth"}),navigator.mediaSession.setActionHandler("play",()=>{this.seqPlay()}),navigator.mediaSession.setActionHandler("pause",()=>{this.seqPause()}),navigator.mediaSession.setActionHandler("stop",()=>{this.seq.currentTime=0,this.seqPause()}),navigator.mediaSession.setActionHandler("seekbackward",A=>{this.seq.currentTime-=A.seekOffset||10}),navigator.mediaSession.setActionHandler("seekforward",A=>{this.seq.currentTime+=A.seekOffset||10}),navigator.mediaSession.setActionHandler("seekto",A=>{this.seq.currentTime=A.seekTime}),navigator.mediaSession.setActionHandler("previoustrack",()=>{this.switchToPreviousSong()}),navigator.mediaSession.setActionHandler("nexttrack",()=>{this.switchToNextSong()}),navigator.mediaSession.playbackState="playing")}function Sy(A=!0){if(this.seq?.hasDummyData===!0)this.currentSongTitle=this.locale.getLocaleString("locale.synthInit.genericLoading");else{let r=this.infoDecoder.decode(this.seq.midiData.rawMidiName.buffer).replace(/\0$/,"");this.currentSongTitle=DB(r)}if(this.seq.midiData){let r=this.seq.midiData.lyrics;this.currentLyrics=new Uint8Array(r.reduce((g,u)=>g+u.length,0));let l=0;for(let g of r)this.currentLyrics.set(g,l),l+=g.length;this.currentLyricsString=this.decodeTextFix(this.currentLyrics.buffer)||this.locale.getLocaleString("locale.sequencerController.lyrics.noLyrics"),this.setLyricsText(""),A&&(this.rawOtherTextEvents=[])}if(document.getElementById("title").innerText=this.currentSongTitle,document.title=this.currentSongTitle+" - SpessaSynth",this.musicModeUI.setTitle(this.currentSongTitle),!!navigator.mediaSession)try{navigator.mediaSession.setPositionState({duration:this.seq.duration,playbackRate:this.seq.playbackRate,position:this.seq.currentTime})}catch{}}var MD=parseFloat(getComputedStyle(document.body).fontSize);function Dy(){this.lyricsElement={};let A=document.createElement("div");A.classList.add("lyrics");let r=document.createElement("div");r.classList.add("lyrics_title_wrapper"),A.append(r),this.lyricsElement.titleWrapper=r;let l=document.createElement("h2");this.locale.bindObjectProperty(l,"textContent","locale.sequencerController.lyrics.title"),l.classList.add("lyrics_title"),r.appendChild(l),this.lyricsElement.title=l;let g=document.createElement("select");wm.forEach(u1=>{let R=document.createElement("option");R.innerText=u1,R.value=u1,g.appendChild(R)}),g.value=this.encoding,g.onchange=()=>this.changeEncoding(g.value),g.classList.add("lyrics_selector"),this.encodingSelector=g,r.appendChild(g);let u=document.createElement("p");u.classList.add("lyrics_text"),A.appendChild(u);let b=document.createElement("span");b.classList.add("lyrics_text_highlight"),u.appendChild(b);let A0=document.createElement("span");A0.classList.add("lyrics_text_gray"),u.appendChild(A0);let E0=document.createElement("details"),m0=document.createElement("summary");this.locale.bindObjectProperty(m0,"textContent","locale.sequencerController.lyrics.otherText.title"),E0.appendChild(m0);let c0=document.createElement("div");c0.innerText="",E0.appendChild(c0),A.appendChild(E0),this.lyricsElement.text={highlight:b,gray:A0,main:u,other:c0},this.lyricsElement.mainDiv=A,this.lyricsElement.selector=g,this.controls.appendChild(A),this.requiresTextUpdate=!0}function by(A){let r=this.lyricsElement.text.highlight,l=this.lyricsElement.text.gray;l.innerText=this.currentLyricsString.replace(A,""),r.innerText=A,this.lyricsElement.text.main.scrollTo(0,r.offsetHeight-MD*5)}function _y(){let A="";for(let r of this.rawOtherTextEvents)A+=`
${Object.keys(K3).find(l=>K3[l]===r.type).replace(/([a-z])([A-Z])/g,"$1 $2")}:
${this.decodeTextFix(r.data.buffer)}

`;this.lyricsElement.text.other.innerHTML=A}var Nr=32,Ry="#ccc",xy="#555",TD="#333",ND="#ddd",GD="Shift_JIS",xs=class{constructor(r,l,g){this.iconColor=Ry,this.iconDisabledColor=xy,this.controls=r,this.encoding=GD,this.decoder=new TextDecoder(this.encoding),this.infoDecoder=new TextDecoder(this.encoding),this.hasInfoDecoding=!1,this.text="",this.requiresTextUpdate=!1,this.rawLyrics=[],this.rawOtherTextEvents=[],this.mode="dark",this.locale=l,this.currentSongTitle="",this.currentLyrics=new Uint8Array(0),this.currentLyricsString="",this.musicModeUI=g}toggleDarkMode(){if(this.mode==="dark"?(this.mode="light",this.iconColor=TD,this.iconDisabledColor=ND):(this.mode="dark",this.iconColor=Ry,this.iconDisabledColor=xy),!this.seq){this.requiresThemeUpdate=!0;return}this.progressBar.classList.toggle("note_progress_light"),this.progressBarBackground.classList.toggle("note_progress_background_light"),this.lyricsElement.mainDiv.classList.toggle("lyrics_light"),this.lyricsElement.titleWrapper.classList.toggle("lyrics_light"),this.lyricsElement.selector.classList.toggle("lyrics_light")}seqPlay(r=!0){r&&this.seq.play(),this.playPause.innerHTML=Q$(Nr),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),navigator.mediaSession&&(navigator.mediaSession.playbackState="playing")}seqPause(r=!0){r&&this.seq.pause(),this.playPause.innerHTML=Iy(Nr),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),navigator.mediaSession&&(navigator.mediaSession.playbackState="paused")}switchToNextSong(){this.seq.nextSong(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus()}switchToPreviousSong(){this.seq.previousSong(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus()}decodeTextFix(r,l=!1){let g=0;for(;;)try{return this.decoder.decode(r)}catch{g++,this.changeEncoding(wm[g]),this.encodingSelector.value=wm[g]}}connectSequencer(r){this.seq=r,this.createControls(),this.setSliderInterval(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),this.seq.onTextEvent=(l,g)=>{let u=this.decodeTextFix(l.buffer);switch(g){default:return;case K3.text:case K3.copyright:case K3.cuePoint:case K3.trackName:case K3.instrumentName:case K3.programName:case K3.marker:this.rawOtherTextEvents.push({type:g,data:l}),this.requiresTextUpdate=!0;return;case K3.lyric:this.text+=u,this.rawLyrics.push(...l),this.setLyricsText(this.text);break}},this.seq.addOnTimeChangeEvent(()=>{this.text="",this.rawLyrics=[],this.seqPlay(!1)},"sequi-time-change"),this.seq.addOnSongChangeEvent(l=>{if(this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),this.seqPlay(!1),this.seq.songsAmount>1&&(this.seq.loop=!1,this.loopButton.firstElementChild.setAttribute("fill",this.iconDisabledColor)),this.hasInfoDecoding=this.seq.midiData.RMIDInfo?.[L7.encoding]!==void 0,l.isEmbedded){let g=(E0,m0,c0,u1="")=>this.seq.midiData.RMIDInfo?.[E0]===void 0?m0:u1+c0.decode(this.seq.midiData.RMIDInfo?.[E0]).replace(/\0$/,""),u=new TextDecoder,b=g(L7.midiEncoding,this.encoding,u),A0=g(L7.encoding,"utf-8",u);this.infoDecoder=new TextDecoder(A0),this.changeEncoding(b)}},"sequi-song-change"),this.requiresThemeUpdate&&this.mode==="light"&&(this.mode="dark",this.toggleDarkMode())}changeEncoding(r){this.encoding=r,this.decoder=new TextDecoder(r),this.hasInfoDecoding||(this.infoDecoder=new TextDecoder(r)),this.updateOtherTextEvents(),this.text=this.decodeTextFix(new Uint8Array(this.rawLyrics).buffer),this.lyricsElement.selector.value=r,this.updateTitleAndMediaStatus(!1),this.setLyricsText(this.text)}createControls(){this.progressTime=document.createElement("p"),this.progressTime.id="note_time",this.progressTime.onclick=R=>{R.preventDefault();let Z0=r.getBoundingClientRect(),G0=R.clientX-Z0.left,D1=Z0.width;this.seq.currentTime=G0/D1*this.seq.duration,g.innerHTML=Q$(Nr)},this.createLyrics();let r=document.createElement("div");r.id="note_progress_background",this.progressBarBackground=r,this.progressBar=document.createElement("div"),this.progressBar.id="note_progress",this.progressBar.min="0",this.progressBar.max=this.seq.duration.toString();let l=document.createElement("div"),g=gh("Play/Pause",Q$(Nr));this.playPause=g,this.locale.bindObjectProperty(g,"title","locale.sequencerController.playPause");let u=()=>{this.seq.paused?this.seqPlay():this.seqPause()};g.onclick=u;let b=gh("Previous song",By(Nr));this.locale.bindObjectProperty(b,"title","locale.sequencerController.previousSong"),b.onclick=()=>this.switchToPreviousSong();let A0=gh("Next song",Cy(Nr));this.locale.bindObjectProperty(A0,"title","locale.sequencerController.nextSong"),A0.onclick=()=>this.switchToNextSong();let E0=gh("Loop this",Ey(Nr));this.locale.bindObjectProperty(E0,"title","locale.sequencerController.loopThis");let m0=()=>{this.seq.loop?this.seq.loop=!1:(this.seq.loop=!0,this.seq.currentTime>=this.seq.duration&&(this.seq.currentTime=0)),E0.firstElementChild.setAttribute("fill",this.seq.loop?this.iconColor:this.iconDisabledColor)};E0.onclick=m0,this.loopButton=E0;let c0=gh("Show lyrics",my(Nr));this.locale.bindObjectProperty(c0,"title","locale.sequencerController.lyrics.show"),c0.firstElementChild.setAttribute("fill",this.iconDisabledColor);let u1=()=>{this.lyricsElement.mainDiv.classList.toggle("lyrics_show"),c0.firstElementChild.setAttribute("fill",this.lyricsElement.mainDiv.classList.contains("lyrics_show")?this.iconColor:this.iconDisabledColor)};c0.onclick=u1,document.addEventListener("keydown",R=>{switch(R.key.toLowerCase()){case X7.playPause:R.preventDefault(),u();break;case X7.toggleLoop:R.preventDefault(),m0();break;case X7.toggleLyrics:R.preventDefault(),u1();break;default:break}}),l.appendChild(b),l.appendChild(E0),l.appendChild(g),l.appendChild(c0),l.appendChild(A0),this.controls.appendChild(r),r.appendChild(this.progressBar),this.controls.appendChild(this.progressTime),this.controls.appendChild(l),document.addEventListener("keydown",R=>{switch(R.key.toLowerCase()){case X7.seekBackwards:R.preventDefault(),this.seq.currentTime-=5,g.innerHTML=Q$(Nr);break;case X7.seekForwards:R.preventDefault(),this.seq.currentTime+=5,g.innerHTML=Q$(Nr);break;case X7.previousSong:this.switchToPreviousSong();break;case X7.nextSong:this.switchToNextSong();break;default:if(!isNaN(parseFloat(R.key))){R.preventDefault();let Z0=parseInt(R.key);0<=Z0&&Z0<=9&&(this.seq.currentTime=this.seq.duration*(Z0/10),g.innerHTML=Q$(Nr))}break}})}_updateInterval(){this.progressBar.style.width=`${this.seq.currentTime/this.seq.duration*100}%`;let r=I$(this.seq.currentTime),l=I$(this.seq.duration);this.progressTime.innerText=`${r.time} / ${l.time}`,this.requiresTextUpdate&&(this.updateOtherTextEvents(),this.requiresTextUpdate=!1)}setSliderInterval(){setInterval(this._updateInterval.bind(this),100)}};xs.prototype.createNavigatorHandler=vy;xs.prototype.updateTitleAndMediaStatus=Sy;xs.prototype.createLyrics=Dy;xs.prototype.setLyricsText=by;xs.prototype.updateOtherTextEvents=_y;function Ly(){this.controllers.forEach(A=>{A.voiceMeter.hide(),A.pitchWheel.hide(),A.pan.hide(),A.expression.hide(),A.volume.hide(),A.mod.hide(),A.chorus.hide(),A.reverb.hide(),A.brightness.hide(),A.preset.hide()})}function Fy(){this.controllers.forEach(A=>{A.voiceMeter.show(),A.pitchWheel.show(),A.pan.show(),A.expression.show(),A.volume.show(),A.mod.show(),A.chorus.show(),A.reverb.show(),A.brightness.show(),A.preset.show()})}function My(){this.mainControllerDiv.classList.toggle("synthui_controller_light"),this.mainButtons.forEach(A=>{A.classList.toggle("synthui_button"),A.classList.toggle("synthui_button_light")}),this.mainMeters.forEach(A=>{A.toggleMode(!0)}),this.controllers.forEach(A=>{A.voiceMeter.toggleMode(),A.pitchWheel.toggleMode(),A.pan.toggleMode(),A.expression.toggleMode(),A.volume.toggleMode(),A.mod.toggleMode(),A.chorus.toggleMode(),A.reverb.toggleMode(),A.brightness.toggleMode(),A.preset.toggleMode(),A.drumsToggle.classList.toggle("mute_button_light"),A.muteButton.classList.toggle("mute_button_light")})}var cr=class{constructor(r="none",l,g,u,b=0,A0=100,E0=!1,m0=void 0,c0=void 0,u1=void 0){if(this.meterText="",g.bindObjectProperty(this,"meterText",l+".title"),this.min=b,this.max=A0,this.currentValue=-1,this.isShown=!0,this.isVisualValueSet=!0,this.isLocked=!1,this.lockCallback=c0,this.unlockCallback=u1,this.div=document.createElement("div"),this.div.classList.add("voice_meter"),this.div.classList.add("controller_element"),r!=="none"&&r!==""&&(this.div.style.borderColor=r),g.bindObjectProperty(this.div,"title",l+".description",u),this.bar=document.createElement("div"),this.bar.classList.add("voice_meter_bar"),this.bar.style.background=r,this.div.appendChild(this.bar),this.text=document.createElement("p"),this.text.classList.add("voice_meter_text"),this.div.appendChild(this.text),this.isActive=!1,E0){if(m0===void 0)throw new Error("No editable function given!");this.div.onmousedown=R=>{R.preventDefault(),R.button===0?this.isActive=!0:this.lockMeter()},this.div.onmousemove=R=>{if(!this.isActive)return;let Z0=R.currentTarget.getBoundingClientRect(),G0=Z0.left,D1=Z0.width,l2=R.clientX-G0,y1=Math.max(0,Math.min(1,l2/D1));m0(y1*(A0-b)+b)},this.div.onmouseup=()=>this.isActive=!1,this.div.onmouseleave=R=>{this.div.onmousemove(R),this.isActive=!1},this.text.oncontextmenu=R=>{R.preventDefault()},this.div.onclick=R=>{R.preventDefault(),this.isActive=!0,this.div.onmousemove(R),this.isActive=!1},this.div.classList.add("editable")}}lockMeter(){this.lockCallback!==void 0&&(this.isLocked?(this.text.classList.remove("locked_meter"),this.unlockCallback()):(this.text.classList.add("locked_meter"),this.lockCallback()),this.isLocked=!this.isLocked)}toggleMode(r=!1){r&&(this.bar.classList.toggle("voice_meter_light_color"),this.div.classList.toggle("voice_meter_light_color")),this.text.classList.toggle("voice_meter_text_light")}show(){if(this.isShown=!0,!this.isVisualValueSet){let r=Math.max(0,Math.min((this.currentValue-this.min)/(this.max-this.min),1));this.bar.style.width=`${r*100}%`,this.text.textContent=this.meterText+(Math.round(this.currentValue*100)/100).toString(),this.isVisualValueSet=!0}}hide(){this.isShown=!1}update(r,l=!1){if(!(r===this.currentValue&&l===!1))if(this.currentValue=r,this.isShown){let g=Math.max(0,Math.min((r-this.min)/(this.max-this.min),1));this.bar.style.width=`${g*100}%`,this.text.textContent=this.meterText+(Math.round(r*100)/100).toString(),this.isVisualValueSet=!0}else this.isVisualValueSet=!1}};var Ty=["Acoustic Grand Piano","Bright Acoustic Piano","Electric Grand Piano","Honky-tonk Piano","Electric Piano 1","Electric Piano 2","Harpsichord","Clavi","Celesta","Glockenspiel","Music Box","Vibraphone","Marimba","Xylophone","Tubular Bells","Dulcimer","Drawbar Organ","Percussive Organ","Rock Organ","Church Organ","Reed Organ","Accordion","Harmonica","Tango Accordion","Acoustic Guitar (nylon)","Acoustic Guitar (steel)","Electric Guitar (jazz)","Electric Guitar (clean)","Electric Guitar (muted)","Overdriven Guitar","Distortion Guitar","Guitar Harmonics","Acoustic Bass","Electric Bass (finger)","Electric Bass (pick)","Fretless Bass","Slap Bass 1","Slap Bass 2","Synth Bass 1","Synth Bass 2","Violin","Viola","Cello","Contrabass","Tremolo Strings","Pizzicato Strings","Orchestral Harp","Timpani","String Ensemble 1","String Ensemble 2","Synth Strings 1","Synth Strings 2","Choir Aahs","VoiceGroup Oohs","Synth Choir","Orchestra Hit","Trumpet","Trombone","Tuba","Muted Trumpet","French Horn","Brass Section","Synth Brass 1","Synth Brass 2","Soprano Sax","Alto Sax","Tenor Sax","Baritone Sax","Oboe","English Horn","Bassoon","Clarinet","Piccolo","Flute","Recorder","Pan Flute","Blown Bottle","Shakuhachi","Whistle","Ocarina","Lead 1 (square)","Lead 2 (sawtooth)","Lead 3 (calliope)","Lead 4 (chiff)","Lead 5 (charang)","Lead 6 (voice)","Lead 7 (fifths)","Lead 8 (bass + lead)","Pad 1 (new age)","Pad 2 (warm)","Pad 3 (polysynth)","Pad 4 (choir)","Pad 5 (bowed)","Pad 6 (metallic)","Pad 7 (halo)","Pad 8 (sweep)","FX 1 (rain)","FX 2 (soundtrack)","FX 3 (crystal)","FX 4 (atmosphere)","FX 5 (brightness)","FX 6 (goblins)","FX 7 (echoes)","FX 8 (sci-fi)","Sitar","Banjo","Shamisen","Koto","Kalimba","Bagpipe","Fiddle","Shanai","Tinkle Bell","Agogo","Steel Drums","Woodblock","Taiko Drum","Melodic Tom","Synth Drum","Reverse Cymbal","Guitar Fret Noise","Breath Noise","Seashore","Bird Tweet","Telephone Ring","Attack Helicopter","Applause","Gunshot"];var DC=class{constructor(r,l,g,u,b=void 0,A0=void 0){this.isShown=!0,this.isReloaded=!0,this.elements=r.map(E0=>({name:E0.name,program:E0.program,bank:E0.bank,stringified:`${E0.bank.toString().padStart(3,"0")}:${E0.program.toString().padStart(3,"0")} ${E0.name}`})),this.elements.length>0?this.value=`${this.elements[0].bank}:${this.elements[0].program}`:this.value="",this.mainButton=document.createElement("button"),this.mainButton.classList.add("voice_selector"),this.mainButton.classList.add("controller_element"),l.bindObjectProperty(this.mainButton,"title",g+".description",u),this.locale=l,this.localePath=g,this.localeArgs=u,this.reload(),this.mainButton.onclick=()=>{this.showSelectionMenu()},this.editCallback=b,this.selectionMenu=void 0,this.lockCallback=A0,this.locked=!1,this.isWindowShown=!1}showSelectionMenu(){this.selectionMenu=document.createElement("div"),this.selectionMenu.classList.add("voice_selector_wrapper"),document.getElementsByClassName("spessasynth_main")[0].appendChild(this.selectionMenu);let r=document.createElement("div");r.classList.add("voice_selector_window");let l=document.createElement("h2");this.locale.bindObjectProperty(l,"textContent",this.localePath+".selectionPrompt",this.localeArgs),r.appendChild(l);let g=document.createElement("div");g.classList.add("voice_selector_search_wrapper"),r.appendChild(g);let u=document.createElement("input");u.type="text",this.locale.bindObjectProperty(u,"placeholder",this.localePath+".searchPrompt"),g.appendChild(u),u.onkeydown=E0=>E0.stopPropagation();let b=document.createElement("div");b.innerHTML=this.locked?SC(gt):UB(gt),this.locale.bindObjectProperty(b,"title",se+"channelController.presetReset.description",this.localeArgs),b.classList.add("voice_reset"),this.mainButton.classList.contains("voice_selector_light")&&b.classList.add("voice_reset_light"),b.onclick=()=>{this.locked=!this.locked,this.lockCallback(this.locked),this.mainButton.classList.toggle("locked_selector"),this.locked?b.innerHTML=SC(gt):b.innerHTML=UB(gt)},g.appendChild(b),this.presetLock=b;let A0=document.createElement("div");A0.classList.add("voice_selector_table_wrapper"),r.appendChild(A0),this.generateTable(A0,this.elements),u.oninput=E0=>{E0.stopPropagation();let m0=u.value,c0=this.elements.filter(u1=>u1.stringified.search(new RegExp(m0,"i"))>=0);c0.length!==this.elements.length&&(A0.replaceChildren(),this.generateTable(A0,c0))},r.onclick=E0=>{E0.stopPropagation()},this.selectionMenu.appendChild(r),this.selectionMenu.onclick=E0=>{E0.stopPropagation(),this.hideSelectionMenu()},this.isWindowShown=!0}generateTable(r,l){let g=document.createElement("table");g.classList.add("voice_selector_table");let u=parseInt(this.value.split(":")[0]),b=parseInt(this.value.split(":")[1]),A0=-20;for(let E0 of l){let m0=document.createElement("tr"),c0=E0.program;if(c0===b&&E0.bank===u&&(m0.classList.add("voice_selector_selected"),setTimeout(()=>{m0.scrollIntoView({behavior:"instant",block:"center",inline:"center"})},20)),m0.onclick=()=>{let l2=`${E0.bank}:${c0}`;if(this.value===l2){this.hideSelectionMenu();return}this.editCallback(l2),this.locked=!0,this.presetLock.innerHTML=SC(gt),this.hideSelectionMenu()},c0!==A0){A0=c0;let l2=document.createElement("tr"),y1=document.createElement("th");y1.colSpan="3",y1.textContent=Ty[A0],l2.appendChild(y1),g.appendChild(l2)}let u1=`${E0.program.toString().padStart(3,"0")}`,R=`${E0.bank.toString().padStart(3,"0")}`,Z0=document.createElement("td");Z0.classList.add("voice_selector_preset_name"),Z0.textContent=E0.name;let G0=document.createElement("td");Z0.classList.add("voice_selector_preset_program"),G0.textContent=u1;let D1=document.createElement("td");Z0.classList.add("voice_selector_preset_program"),D1.textContent=R,m0.appendChild(D1),m0.appendChild(G0),m0.appendChild(Z0),g.appendChild(m0)}r.appendChild(g)}hideSelectionMenu(){document.getElementsByClassName("spessasynth_main")[0].removeChild(this.selectionMenu),this.selectionMenu=void 0,this.isWindowShown=!1}toggleMode(){this.mainButton.classList.toggle("voice_selector_light")}reload(r=this.elements){if(this.elements=r.map(l=>({name:l.name,program:l.program,bank:l.bank,stringified:`${l.bank.toString().padStart(3,"0")}:${l.program.toString().padStart(3,"0")} ${l.name}`})),!this.isShown){this.isReloaded=!1;return}this.mainButton.innerHTML="",this.isReloaded=!0}set(r){if(this.value=r,this.isShown&&(this.isReloaded||this.reload(),this.mainButton.textContent=this.getString(this.value),this.isWindowShown)){let l=this.selectionMenu.getElementsByClassName("voice_selector_selected")[0];l!==void 0&&l.classList.remove("voice_selector_selected");let g=this.selectionMenu.getElementsByClassName("voice_selector_table")[0],u=parseInt(this.value.split(":")[0]),b=parseInt(this.value.split(":")[1]);for(let A0 of g.rows){if(A0.cells.length===1)continue;let E0=parseInt(A0.cells[0].textContent),m0=parseInt(A0.cells[1].textContent);E0===u&&m0===b&&(A0.classList.add("voice_selector_selected"),A0.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}))}}}getString(r){let l=r.split(":"),g=parseInt(l[0]),u=parseInt(l[1]),b=this.elements.find(A0=>A0.bank===g&&A0.program===u);return g===128||this.elements.filter(A0=>A0.program===u&&A0.bank!==128).length<2?`${u}. ${b.name}`:`${g}:${u} ${b.name}`}show(){this.isShown=!0,this.isReloaded||this.reload(),this.mainButton.textContent=this.getString(this.value)}hide(){this.isShown=!1}};var gt=32;function Ny(A){this.soloChannels=new Set;let r=document.createElement("div");r.classList.add("channel_controller");let l=new cr(this.channelColors[A%this.channelColors.length],se+"channelController.voiceMeter",this.locale,[A+1],0,100);l.bar.classList.add("voice_meter_bar_smooth"),r.appendChild(l.div);let g=new cr(this.channelColors[A%this.channelColors.length],se+"channelController.pitchBendMeter",this.locale,[A+1],-8192,8191,!0,T2=>{let K2=g.isLocked;K2&&this.synth.lockController(A,m$+x7.pitchWheel,!1),T2=Math.round(T2)+8192;let i3=T2>>7,r3=T2&127;this.synth.pitchWheel(A,i3,r3),K2&&this.synth.lockController(A,m$+x7.pitchWheel,!0)},()=>this.synth.lockController(A,m$+x7.pitchWheel,!0),()=>this.synth.lockController(A,m$+x7.pitchWheel,!1));g.update(0),r.appendChild(g.div);let u=(T2,K2,i3)=>{i3.isLocked?(this.synth.lockController(A,T2,!1),this.synth.controllerChange(A,T2,K2),this.synth.lockController(A,T2,!0)):this.synth.controllerChange(A,T2,K2)},b=(T2,K2,i3)=>{let r3=new cr(this.channelColors[A%this.channelColors.length],se+K2,this.locale,[A+1],0,127,!0,o0=>u(T2,Math.round(o0),r3),()=>this.synth.lockController(A,T2,!0),()=>this.synth.lockController(A,T2,!1));return r3.update(i3),r3},A0=b(t6.pan,"channelController.panMeter",64);r.appendChild(A0.div);let E0=b(t6.expressionController,"channelController.expressionMeter",127);r.appendChild(E0.div);let m0=b(t6.mainVolume,"channelController.volumeMeter",100);r.appendChild(m0.div);let c0=b(t6.modulationWheel,"channelController.modulationWheelMeter",0);r.appendChild(c0.div);let u1=b(t6.effects3Depth,"channelController.chorusMeter",0);r.appendChild(u1.div);let R=b(t6.effects1Depth,"channelController.reverbMeter",0);r.appendChild(R.div);let Z0=b(t6.brightness,"channelController.filterMeter",64);r.appendChild(Z0.div);let G0=new cr(this.channelColors[A%this.channelColors.length],se+"channelController.transposeMeter",this.locale,[A+1],-36,36,!0,T2=>{T2=Math.round(T2),this.synth.transposeChannel(A,T2,!0),G0.update(T2)});G0.update(0),r.appendChild(G0.div);let D1=new DC([],this.locale,se+"channelController.presetSelector",[A+1],async T2=>{let K2=T2.split(":");this.synth.lockController(A,mi,!1),this.synth.controllerChange(A,t6.bankSelect,parseInt(K2[0]),!0),this.synth.programChange(A,parseInt(K2[1]),!0),D1.mainButton.classList.add("locked_selector"),this.synth.lockController(A,mi,!0)},T2=>this.synth.lockController(A,mi,T2));r.appendChild(D1.mainButton);let l2=document.createElement("div");l2.innerHTML=ch(gt),this.locale.bindObjectProperty(l2,"title",se+"channelController.soloButton.description",[A+1]),l2.classList.add("controller_element"),l2.classList.add("mute_button"),l2.onclick=()=>{if(this.soloChannels.has(A)?this.soloChannels.delete(A):this.soloChannels.add(A),this.soloChannels.size===0||this.soloChannels.size>=this.synth.channelsAmount){for(let T2=0;T2=this.synth.channelsAmount&&this.soloChannels.clear();return}for(let T2=0;T2{if(y1.hasAttribute("is_muted")){y1.removeAttribute("is_muted");let T2=this.soloChannels.size===0||this.soloChannels.has(A);this.synth.muteChannel(A,!T2),y1.innerHTML=km(gt)}else this.synth.muteChannel(A,!0),y1.setAttribute("is_muted","true"),y1.innerHTML=Qy(gt)},r.appendChild(y1);let Y2=document.createElement("div");return Y2.innerHTML=A===bi?kC(gt):vC(gt),this.locale.bindObjectProperty(Y2,"title",se+"channelController.drumToggleButton.description",[A+1]),Y2.classList.add("controller_element"),Y2.classList.add("mute_button"),Y2.onclick=()=>{this.synth.setDrums(A,!this.synth.channelProperties[A].isDrum)},r.appendChild(Y2),{controller:r,voiceMeter:l,pitchWheel:g,pan:A0,expression:E0,volume:m0,mod:c0,chorus:u1,reverb:R,brightness:Z0,preset:D1,drumsToggle:Y2,soloButton:l2,muteButton:y1,transpose:G0}}function Gy(){let A=this.uiDiv.getElementsByClassName("synthui_controller")[0];this.controllers=[];for(let r=0;r{this.synth.setMainVolume(Math.round(c0)/100),this.volumeController.update(c0)}),this.volumeController.bar.classList.add("voice_meter_bar_smooth"),this.volumeController.div.classList.add("main_controller_element"),this.volumeController.update(100),this.panController=new cr("",se+"mainPanMeter",this.locale,[],-1,1,!0,c0=>{this.synth.setMasterPan(c0),this.panController.update(c0)}),this.panController.bar.classList.add("voice_meter_bar_smooth"),this.panController.div.classList.add("main_controller_element"),this.panController.update(0),this.transposeController=new cr("",se+"mainTransposeMeter",this.locale,[],-12,12,!0,c0=>{this.synth.transpose(Math.round(c0*2)/2),this.transposeController.update(Math.round(c0*2)/2)}),this.transposeController.bar.classList.add("voice_meter_bar_smooth"),this.transposeController.div.classList.add("main_controller_element"),this.transposeController.update(0);let r=document.createElement("button");this.locale.bindObjectProperty(r,"textContent",se+"midiPanic.title"),this.locale.bindObjectProperty(r,"title",se+"midiPanic.description"),r.classList.add("synthui_button"),r.classList.add("main_controller_element"),r.onclick=()=>this.synth.stopAll(!0);let l=document.createElement("button");this.locale.bindObjectProperty(l,"textContent",se+"systemReset.title"),this.locale.bindObjectProperty(l,"title",se+"systemReset.description"),l.classList.add("synthui_button"),l.classList.add("main_controller_element"),l.onclick=()=>{this.controllers.forEach((c0,u1)=>{c0.pitchWheel.isLocked&&c0.pitchWheel.lockMeter(),c0.pan.isLocked&&c0.pan.lockMeter(),c0.expression.isLocked&&c0.expression.lockMeter(),c0.volume.isLocked&&c0.volume.lockMeter(),c0.mod.isLocked&&c0.mod.lockMeter(),c0.chorus.isLocked&&c0.chorus.lockMeter(),c0.reverb.isLocked&&c0.reverb.lockMeter(),c0.brightness.isLocked&&c0.brightness.lockMeter(),c0.preset.mainButton.classList.contains("locked_selector")&&(this.synth.lockController(u1,mi,!1),c0.preset.mainButton.classList.remove("locked_selector")),this.synth.transposeChannel(u1,0,!0),c0.transpose.update(0),c0.soloButton.innerHTML=ch(gt),c0.muteButton.innerHTML=km(gt),this.synth.muteChannel(u1,!1)}),this.synth.resetControllers()};let g=document.createElement("button");this.locale.bindObjectProperty(g,"textContent",se+"blackMidiMode.title"),this.locale.bindObjectProperty(g,"title",se+"blackMidiMode.description"),g.classList.add("synthui_button"),g.classList.add("main_controller_element"),g.onclick=()=>{this.synth.highPerformanceMode=!this.synth.highPerformanceMode};let u=document.createElement("button");this.locale.bindObjectProperty(u,"textContent",se+"disableCustomVibrato.title"),this.locale.bindObjectProperty(u,"title",se+"disableCustomVibrato.description"),u.classList.add("synthui_button"),u.classList.add("main_controller_element"),u.onclick=()=>{this.synth.disableGSNRPparams(),u.parentNode.removeChild(u)};let b=document.createElement("a");b.href="https://github.com/spessasus/SpessaSynth/wiki/How-To-Use-App#synthesizer-controller",b.target="#",b.classList.add("main_controller_element"),b.classList.add("synthui_button"),this.locale.bindObjectProperty(b,"textContent",se+"helpButton.title"),this.locale.bindObjectProperty(b,"title",se+"helpButton.description");let A0=document.createElement("select");A0.classList.add("main_controller_element"),A0.classList.add("synthui_button"),this.locale.bindObjectProperty(A0,"title",se+"interpolation.description");{let c0=document.createElement("option");c0.value="0",this.locale.bindObjectProperty(c0,"textContent",se+"interpolation.linear"),A0.appendChild(c0);let u1=document.createElement("option");u1.value="1",this.locale.bindObjectProperty(u1,"textContent",se+"interpolation.nearestNeighbor"),A0.appendChild(u1);let R=document.createElement("option");R.value="2",R.selected=!0,this.locale.bindObjectProperty(R,"textContent",se+"interpolation.cubic"),A0.appendChild(R),A0.onchange=()=>{this.synth.setInterpolationType(parseInt(A0.value))}}let E0=document.createElement("div");E0.classList.add("synthui_controller"),this.uiDiv.appendChild(E0);let m0=document.createElement("button");this.locale.bindObjectProperty(m0,"textContent",se+"toggleButton.title"),this.locale.bindObjectProperty(m0,"title",se+"toggleButton.description"),m0.classList.add("synthui_button"),m0.onclick=()=>{this.hideOnDocClick=!1,this.toggleVisibility()},A.appendChild(this.volumeController.div),A.appendChild(this.panController.div),A.appendChild(this.transposeController.div),A.appendChild(r),A.appendChild(l),A.appendChild(g),A.appendChild(u),A.appendChild(b),A.appendChild(A0),this.mainMeters=[this.volumeController,this.panController,this.transposeController,this.voiceMeter],this.mainButtons=[r,l,g,u,m0,b,A0],this.uiDiv.appendChild(this.voiceMeter.div),this.uiDiv.appendChild(m0),E0.appendChild(A),this.mainControllerDiv=E0,this.mainControllerDiv.onclick=c0=>c0.stopPropagation(),document.addEventListener("click",()=>{if(!this.hideOnDocClick){this.hideOnDocClick=!0;return}E0.classList.remove("synthui_controller_show"),this.isShown=!1,this.hideControllers()})}function Py(){let A=this.uiDiv.getElementsByClassName("synthui_controller")[0];this.synth.eventHandler.addEvent("programchange","synthui-program-change",r=>{this.controllers[r.channel].preset.set(`${r.bank}:${r.program}`)}),this.synth.eventHandler.addEvent("allcontrollerreset","synthui-all-controller-reset",()=>{for(let r of this.controllers)r.pan.update(64),r.mod.update(0),r.chorus.update(0),r.pitchWheel.update(0),r.expression.update(127),r.volume.update(100),r.reverb.update(0),r.brightness.update(64)}),this.synth.eventHandler.addEvent("controllerchange","synthui-controller-change",r=>{let l=r.controllerNumber,g=r.channel,u=r.controllerValue;switch(l){default:break;case t6.expressionController:this.controllers[g].expression.update(u);break;case t6.mainVolume:this.controllers[g].volume.update(u);break;case t6.pan:this.controllers[g].pan.update(u);break;case t6.modulationWheel:this.controllers[g].mod.update(u);break;case t6.effects3Depth:this.controllers[g].chorus.update(u);break;case t6.effects1Depth:this.controllers[g].reverb.update(u);break;case t6.brightness:this.controllers[g].brightness.update(u)}}),this.synth.eventHandler.addEvent("pitchwheel","synthui-pitch-wheel",r=>{let l=r.MSB<<7|r.LSB;this.controllers[r.channel].pitchWheel.update(l-8192)}),this.synth.eventHandler.addEvent("drumchange","synthui-drum-change",r=>{this.controllers[r.channel].drumsToggle.innerHTML=r.isDrumChannel?kC(32):vC(32),this.controllers[r.channel].preset.reload(r.isDrumChannel?this.percussionList:this.instrumentList)}),this.synth.eventHandler.addEvent("newchannel","synthui-new-channel",()=>{let r=this.createChannelController(this.controllers.length);this.controllers.push(r),A.appendChild(r.controller),this.hideControllers()})}var se="locale.synthesizerController.",Gr=class{constructor(r,l,g){this.channelColors=r;let u=l;this.uiDiv=document.createElement("div"),this.uiDiv.classList.add("wrapper"),u.appendChild(this.uiDiv),this.uiDiv.style.visibility="visible",this.isShown=!1,this.animationId=-1,this.locale=g,this.hideOnDocClick=!0}connectSynth(r){this.synth=r,this.getInstrumentList(),this.createMainSynthController(),this.createChannelControllers(),document.addEventListener("keydown",l=>{switch(l.key.toLowerCase()){case X7.synthesizerUIShow:l.preventDefault(),this.toggleVisibility();break;case X7.settingsShow:this.isShown=!0,this.toggleVisibility();break;case X7.blackMidiMode:l.preventDefault(),this.synth.highPerformanceMode=!this.synth.highPerformanceMode;break;case X7.midiPanic:l.preventDefault(),this.synth.stopAll(!0);break}}),this.locale.onLocaleChanged.push(()=>{this.voiceMeter.update(this.voiceMeter.currentValue,!0),this.volumeController.update(this.volumeController.currentValue,!0),this.panController.update(this.panController.currentValue,!0),this.panController.update(this.panController.currentValue,!0),this.transposeController.update(this.transposeController.currentValue,!0);for(let l of this.controllers)l.voiceMeter.update(l.voiceMeter.currentValue,!0),l.pitchWheel.update(l.pitchWheel.currentValue,!0),l.pan.update(l.pan.currentValue,!0),l.volume.update(l.volume.currentValue,!0),l.expression.update(l.expression.currentValue,!0),l.mod.update(l.mod.currentValue,!0),l.chorus.update(l.chorus.currentValue,!0),l.reverb.update(l.reverb.currentValue,!0),l.brightness.update(l.brightness.currentValue,!0),l.transpose.update(l.transpose.currentValue,!0)})}toggleVisibility(){this.animationId!==-1&&clearTimeout(this.animationId);let r=document.getElementsByClassName("synthui_controller")[0];this.isShown=!this.isShown,this.isShown?(r.style.display="block",document.getElementsByClassName("top_part")[0].classList.add("synthui_shown"),this.showControllers(),setTimeout(()=>{r.classList.add("synthui_controller_show")},75)):(document.getElementsByClassName("top_part")[0].classList.remove("synthui_shown"),this.hideControllers(),r.classList.remove("synthui_controller_show"),this.animationId=setTimeout(()=>{r.style.display="none"},200))}updateVoicesAmount(){this.voiceMeter.update(this.synth.voicesAmount),this.controllers.forEach((r,l)=>{let g=this.synth.channelProperties[l].voicesAmount;r.voiceMeter.update(g),g<1&&this.synth.voicesAmount>0?r.controller.classList.add("no_voices"):r.controller.classList.remove("no_voices")})}getInstrumentList(){this.synth.eventHandler.addEvent("presetlistchange","synthui-preset-list-change",r=>{let l=r;this.instrumentList=l.filter(g=>g.bank!==128).sort((g,u)=>g.program===u.program?g.bank-u.bank:g.program-u.program).map(g=>({name:g.presetName,bank:g.bank,program:g.program})),this.percussionList=l.filter(g=>g.bank===128).sort((g,u)=>g.program-u.program).map(g=>({name:g.presetName,bank:g.bank,program:g.program})),this.percussionList.length===0?this.percussionList=this.instrumentList:this.instrumentList.length===0&&(this.instrumentList=this.percussionList),this.controllers.forEach((g,u)=>{let b=this.synth.channelProperties[u].isDrum?this.percussionList:this.instrumentList;g.preset.reload(b),g.preset.set(`${b[0].bank}:${b[0].program}`)})})}};Gr.prototype.hideControllers=Ly;Gr.prototype.showControllers=Fy;Gr.prototype.toggleDarkMode=My;Gr.prototype.createChannelController=Ny;Gr.prototype.createChannelControllers=Gy;Gr.prototype.createMainSynthController=Uy;Gr.prototype.setEventListeners=Py;var vm=null,bC=class{constructor(){}async createMIDIDeviceHandler(){if(this.selectedInput=vm,this.selectedOutput=vm,navigator.requestMIDIAccess)try{let r=await navigator.requestMIDIAccess({sysex:!0,software:!0});return this.inputs=r.inputs,this.outputs=r.outputs,W5("%cMIDI handler created!",_1.recognized),!0}catch(r){return de("Could not get MIDI Devices:",r),this.inputs=[],this.outputs=[],!1}else return de("Web MIDI Api not supported!",_1.unrecognized),this.inputs=[],this.outputs=[],!1}connectMIDIOutputToSeq(r,l){this.selectedOutput=r,l.connectMidiOutput(r),W5(`%cPlaying MIDI to %c${r.name}`,_1.info,_1.recognized)}disconnectSeqFromMIDI(r){this.selectedOutput=vm,r.connectMidiOutput(void 0),W5("%cDisconnected from MIDI out.",_1.info)}connectDeviceToSynth(r,l){this.selectedInput=r,r.onmidimessage=g=>{l.sendMessage(g.data)},W5(`%cListening for messages on %c${r.name}`,_1.info,_1.recognized)}disconnectDeviceFromSynth(r){this.selectedInput=vm,r.onmidimessage=void 0,W5(`%cDisconnected from %c${r.name}`,_1.info,_1.recognized)}disconnectAllDevicesFromSynth(){this.selectedInput=vm;for(let r of this.inputs)r[1].onmidimessage=void 0}};var _C=class{constructor(r){window.addEventListener("message",l=>{if(typeof l.data!="string")return;let g=l.data.split(",");if(g[0]!=="midi")return;g.shift();let u=g.map(b=>parseInt(b,16));r.sendMessage(u)}),W5("%cWeb MIDI Link handler created!",_1.recognized)}};var To="midi range";function Oy(A,r,l){let g=0,u=this.htmlControls.keyboard,b=()=>{let A0=document.createElement("option");A0.value=g.toString(),this.locale.bindObjectProperty(A0,"textContent","locale.settings.keyboardSettings.selectedChannel.channelOption",[g+1]),A0.style.background=r.channelColors[g%r.channelColors.length],A0.style.color="rgb(0, 0, 0)",u.channelSelector.appendChild(A0),g++};for(let A0=0;A0{A.selectChannel(parseInt(u.channelSelector.value))},u.sizeSelector.onchange=()=>{if(this.musicMode.visible){this.musicMode.setVisibility(!1,document.getElementById("keyboard_canvas_wrapper")),setTimeout(()=>{u.sizeSelector.value===To?(this.autoKeyRange=!0,this?.sequi?.seq&&(A.keyRange=this.sequi.seq.midiData.keyRange,l.keyRange=this.sequi.seq.midiData.keyRange)):(this.autoKeyRange=!1,A.keyRange=this.keyboardSizes[u.sizeSelector.value],l.keyRange=this.keyboardSizes[u.sizeSelector.value]),this._saveSettings()},600);return}u.sizeSelector.value===To?(this.autoKeyRange=!0,this?.sequi?.seq&&(A.keyRange=this.sequi.seq.midiData.keyRange,l.keyRange=this.sequi.seq.midiData.keyRange)):(this.autoKeyRange=!1,A.keyRange=this.keyboardSizes[u.sizeSelector.value],l.keyRange=this.keyboardSizes[u.sizeSelector.value]),this._saveSettings()},this.addSequencer=A0=>{A0.addOnSongChangeEvent(E0=>{this.autoKeyRange&&(A.keyRange=E0.keyRange,l.keyRange=E0.keyRange),E0.RMIDInfo?.IPIC!==void 0&&this.musicMode.visible===!1&&this.toggleMusicPlayerMode().then()},"settings-keyboard-handler-song-change")},r.synth.eventHandler.addEvent("newchannel","settings-new-channel",()=>{b()}),r.synth.eventHandler.addEvent("programchange","settings-keyboard-program-change",A0=>{A0.userCalled&&(A.selectChannel(A0.channel),u.channelSelector.value=A0.channel)}),r.synth.eventHandler.addEvent("mutechannel","settings-keuboard-mute-channel",A0=>{if(A0.isMuted&&A0.channel===A.channel){let E0=0;for(;r.synth.channelProperties[E0].isMuted;)E0++;E0{if(this.musicMode.visible){this.musicMode.setVisibility(!1,document.getElementById("keyboard_canvas_wrapper")),setTimeout(()=>{A.toggleMode(),this._saveSettings()},600);return}A.toggleMode(),this._saveSettings()},u.showSelector.onclick=()=>{A.shown=!A.shown,this._saveSettings()}}var Hy=` +`}function gh(A,r){let l=document.createElement("div");return l.classList.add("control_buttons"),l.title=A,l.innerHTML=r,l}var X7={synthesizerUIShow:"s",settingsShow:"r",blackMidiMode:"b",midiPanic:"backspace",playPause:" ",toggleLoop:"l",toggleLyrics:"t",seekBackwards:"arrowleft",seekForwards:"arrowright",previousSong:"[",nextSong:"]",cinematicMode:"c",videoMode:"v"};function vy(){navigator.mediaSession&&(navigator.mediaSession.metadata=new MediaMetadata({title:this.currentSongTitle,artist:"SpessaSynth"}),navigator.mediaSession.setActionHandler("play",()=>{this.seqPlay()}),navigator.mediaSession.setActionHandler("pause",()=>{this.seqPause()}),navigator.mediaSession.setActionHandler("stop",()=>{this.seq.currentTime=0,this.seqPause()}),navigator.mediaSession.setActionHandler("seekbackward",A=>{this.seq.currentTime-=A.seekOffset||10}),navigator.mediaSession.setActionHandler("seekforward",A=>{this.seq.currentTime+=A.seekOffset||10}),navigator.mediaSession.setActionHandler("seekto",A=>{this.seq.currentTime=A.seekTime}),navigator.mediaSession.setActionHandler("previoustrack",()=>{this.switchToPreviousSong()}),navigator.mediaSession.setActionHandler("nexttrack",()=>{this.switchToNextSong()}),navigator.mediaSession.playbackState="playing")}function Sy(A=!0){if(this.seq?.hasDummyData===!0)this.currentSongTitle=this.locale.getLocaleString("locale.synthInit.genericLoading");else{let r=this.infoDecoder.decode(this.seq.midiData.rawMidiName.buffer).replace(/\0$/,"");this.currentSongTitle=DB(r)}if(this.seq.midiData){let r=this.seq.midiData.lyrics;this.currentLyrics=new Uint8Array(r.reduce((g,u)=>g+u.length,0));let l=0;for(let g of r)this.currentLyrics.set(g,l),l+=g.length;this.currentLyricsString=this.decodeTextFix(this.currentLyrics.buffer)||this.locale.getLocaleString("locale.sequencerController.lyrics.noLyrics"),this.setLyricsText(""),A&&(this.rawOtherTextEvents=[])}if(document.getElementById("title").innerText=this.currentSongTitle,document.title=this.currentSongTitle+" - SpessaSynth",this.musicModeUI.setTitle(this.currentSongTitle),!!navigator.mediaSession)try{navigator.mediaSession.setPositionState({duration:this.seq.duration,playbackRate:this.seq.playbackRate,position:this.seq.currentTime})}catch{}}var MD=parseFloat(getComputedStyle(document.body).fontSize);function Dy(){this.lyricsElement={};let A=document.createElement("div");A.classList.add("lyrics");let r=document.createElement("div");r.classList.add("lyrics_title_wrapper"),A.append(r),this.lyricsElement.titleWrapper=r;let l=document.createElement("h2");this.locale.bindObjectProperty(l,"textContent","locale.sequencerController.lyrics.title"),l.classList.add("lyrics_title"),r.appendChild(l),this.lyricsElement.title=l;let g=document.createElement("select");wm.forEach(u1=>{let R=document.createElement("option");R.innerText=u1,R.value=u1,g.appendChild(R)}),g.value=this.encoding,g.onchange=()=>this.changeEncoding(g.value),g.classList.add("lyrics_selector"),this.encodingSelector=g,r.appendChild(g);let u=document.createElement("p");u.classList.add("lyrics_text"),A.appendChild(u);let b=document.createElement("span");b.classList.add("lyrics_text_highlight"),u.appendChild(b);let A0=document.createElement("span");A0.classList.add("lyrics_text_gray"),u.appendChild(A0);let E0=document.createElement("details"),m0=document.createElement("summary");this.locale.bindObjectProperty(m0,"textContent","locale.sequencerController.lyrics.otherText.title"),E0.appendChild(m0);let c0=document.createElement("div");c0.innerText="",E0.appendChild(c0),A.appendChild(E0),this.lyricsElement.text={highlight:b,gray:A0,main:u,other:c0},this.lyricsElement.mainDiv=A,this.lyricsElement.selector=g,this.controls.appendChild(A),this.requiresTextUpdate=!0}function by(A){let r=this.lyricsElement.text.highlight,l=this.lyricsElement.text.gray;l.innerText=this.currentLyricsString.replace(A,""),r.innerText=A,this.lyricsElement.text.main.scrollTo(0,r.offsetHeight-MD*5)}function _y(){let A="";for(let r of this.rawOtherTextEvents)A+=`
${Object.keys(K3).find(l=>K3[l]===r.type).replace(/([a-z])([A-Z])/g,"$1 $2")}:
${this.decodeTextFix(r.data.buffer)}

`;this.lyricsElement.text.other.innerHTML=A}var Nr=32,Ry="#ccc",xy="#555",TD="#333",ND="#ddd",GD="Shift_JIS",xs=class{constructor(r,l,g){this.iconColor=Ry,this.iconDisabledColor=xy,this.controls=r,this.encoding=GD,this.decoder=new TextDecoder(this.encoding),this.infoDecoder=new TextDecoder(this.encoding),this.hasInfoDecoding=!1,this.text="",this.requiresTextUpdate=!1,this.rawLyrics=[],this.rawOtherTextEvents=[],this.mode="dark",this.locale=l,this.currentSongTitle="",this.currentLyrics=new Uint8Array(0),this.currentLyricsString="",this.musicModeUI=g}toggleDarkMode(){if(this.mode==="dark"?(this.mode="light",this.iconColor=TD,this.iconDisabledColor=ND):(this.mode="dark",this.iconColor=Ry,this.iconDisabledColor=xy),!this.seq){this.requiresThemeUpdate=!0;return}this.progressBar.classList.toggle("note_progress_light"),this.progressBarBackground.classList.toggle("note_progress_background_light"),this.lyricsElement.mainDiv.classList.toggle("lyrics_light"),this.lyricsElement.titleWrapper.classList.toggle("lyrics_light"),this.lyricsElement.selector.classList.toggle("lyrics_light")}seqPlay(r=!0){r&&this.seq.play(),this.playPause.innerHTML=Q$(Nr),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),navigator.mediaSession&&(navigator.mediaSession.playbackState="playing")}seqPause(r=!0){r&&this.seq.pause(),this.playPause.innerHTML=Iy(Nr),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),navigator.mediaSession&&(navigator.mediaSession.playbackState="paused")}switchToNextSong(){this.seq.nextSong(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus()}switchToPreviousSong(){this.seq.previousSong(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus()}decodeTextFix(r,l=!1){let g=0;for(;;)try{return this.decoder.decode(r)}catch{g++,this.changeEncoding(wm[g]),this.encodingSelector.value=wm[g]}}connectSequencer(r){this.seq=r,this.createControls(),this.setSliderInterval(),this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),this.seq.onTextEvent=(l,g)=>{let u=this.decodeTextFix(l.buffer);switch(g){default:return;case K3.text:case K3.copyright:case K3.cuePoint:case K3.trackName:case K3.instrumentName:case K3.programName:case K3.marker:this.rawOtherTextEvents.push({type:g,data:l}),this.requiresTextUpdate=!0;return;case K3.lyric:this.text+=u,this.rawLyrics.push(...l),this.setLyricsText(this.text);break}},this.seq.addOnTimeChangeEvent(()=>{this.text="",this.rawLyrics=[],this.seqPlay(!1)},"sequi-time-change"),this.seq.addOnSongChangeEvent(l=>{if(this.createNavigatorHandler(),this.updateTitleAndMediaStatus(),this.seqPlay(!1),this.seq.songsAmount>1&&(this.seq.loop=!1,this.loopButton.firstElementChild.setAttribute("fill",this.iconDisabledColor)),this.hasInfoDecoding=this.seq.midiData.RMIDInfo?.[L7.encoding]!==void 0,l.isEmbedded){let g=(E0,m0,c0,u1="")=>this.seq.midiData.RMIDInfo?.[E0]===void 0?m0:u1+c0.decode(this.seq.midiData.RMIDInfo?.[E0]).replace(/\0$/,""),u=new TextDecoder,b=g(L7.midiEncoding,this.encoding,u),A0=g(L7.encoding,"utf-8",u);this.infoDecoder=new TextDecoder(A0),this.changeEncoding(b)}},"sequi-song-change"),this.requiresThemeUpdate&&this.mode==="light"&&(this.mode="dark",this.toggleDarkMode())}changeEncoding(r){this.encoding=r,this.decoder=new TextDecoder(r),this.hasInfoDecoding||(this.infoDecoder=new TextDecoder(r)),this.updateOtherTextEvents(),this.text=this.decodeTextFix(new Uint8Array(this.rawLyrics).buffer),this.lyricsElement.selector.value=r,this.updateTitleAndMediaStatus(!1),this.setLyricsText(this.text)}createControls(){this.progressTime=document.createElement("p"),this.progressTime.id="note_time",this.progressTime.onclick=R=>{R.preventDefault();let Z0=r.getBoundingClientRect(),G0=R.clientX-Z0.left,D1=Z0.width;this.seq.currentTime=G0/D1*this.seq.duration,g.innerHTML=Q$(Nr)},this.createLyrics();let r=document.createElement("div");r.id="note_progress_background",this.progressBarBackground=r,this.progressBar=document.createElement("div"),this.progressBar.id="note_progress",this.progressBar.min="0",this.progressBar.max=this.seq.duration.toString();let l=document.createElement("div"),g=gh("Play/Pause",Q$(Nr));this.playPause=g,this.locale.bindObjectProperty(g,"title","locale.sequencerController.playPause");let u=()=>{this.seq.paused?this.seqPlay():this.seqPause()};g.onclick=u;let b=gh("Previous song",By(Nr));this.locale.bindObjectProperty(b,"title","locale.sequencerController.previousSong"),b.onclick=()=>this.switchToPreviousSong();let A0=gh("Next song",Cy(Nr));this.locale.bindObjectProperty(A0,"title","locale.sequencerController.nextSong"),A0.onclick=()=>this.switchToNextSong();let E0=gh("Loop this",Ey(Nr));this.locale.bindObjectProperty(E0,"title","locale.sequencerController.loopThis");let m0=()=>{this.seq.loop?this.seq.loop=!1:(this.seq.loop=!0,this.seq.currentTime>=this.seq.duration&&(this.seq.currentTime=0)),E0.firstElementChild.setAttribute("fill",this.seq.loop?this.iconColor:this.iconDisabledColor)};E0.onclick=m0,this.loopButton=E0;let c0=gh("Show lyrics",my(Nr));this.locale.bindObjectProperty(c0,"title","locale.sequencerController.lyrics.show"),c0.firstElementChild.setAttribute("fill",this.iconDisabledColor);let u1=()=>{this.lyricsElement.mainDiv.classList.toggle("lyrics_show"),c0.firstElementChild.setAttribute("fill",this.lyricsElement.mainDiv.classList.contains("lyrics_show")?this.iconColor:this.iconDisabledColor)};c0.onclick=u1,document.addEventListener("keydown",R=>{switch(R.key.toLowerCase()){case X7.playPause:R.preventDefault(),u();break;case X7.toggleLoop:R.preventDefault(),m0();break;case X7.toggleLyrics:R.preventDefault(),u1();break;default:break}}),l.appendChild(b),l.appendChild(E0),l.appendChild(g),l.appendChild(c0),l.appendChild(A0),this.controls.appendChild(r),r.appendChild(this.progressBar),this.controls.appendChild(this.progressTime),this.controls.appendChild(l),document.addEventListener("keydown",R=>{switch(R.key.toLowerCase()){case X7.seekBackwards:R.preventDefault(),this.seq.currentTime-=5,g.innerHTML=Q$(Nr);break;case X7.seekForwards:R.preventDefault(),this.seq.currentTime+=5,g.innerHTML=Q$(Nr);break;case X7.previousSong:this.switchToPreviousSong();break;case X7.nextSong:this.switchToNextSong();break;default:if(!isNaN(parseFloat(R.key))){R.preventDefault();let Z0=parseInt(R.key);0<=Z0&&Z0<=9&&(this.seq.currentTime=this.seq.duration*(Z0/10),g.innerHTML=Q$(Nr))}break}})}_updateInterval(){this.progressBar.style.width=`${this.seq.currentTime/this.seq.duration*100}%`;let r=I$(this.seq.currentTime),l=I$(this.seq.duration);this.progressTime.innerText=`${r.time} / ${l.time}`,this.requiresTextUpdate&&(this.updateOtherTextEvents(),this.requiresTextUpdate=!1)}setSliderInterval(){setInterval(this._updateInterval.bind(this),100)}};xs.prototype.createNavigatorHandler=vy;xs.prototype.updateTitleAndMediaStatus=Sy;xs.prototype.createLyrics=Dy;xs.prototype.setLyricsText=by;xs.prototype.updateOtherTextEvents=_y;function Ly(){this.controllers.forEach(A=>{A.voiceMeter.hide(),A.pitchWheel.hide(),A.pan.hide(),A.expression.hide(),A.volume.hide(),A.mod.hide(),A.chorus.hide(),A.reverb.hide(),A.brightness.hide(),A.preset.hide()})}function Fy(){this.controllers.forEach(A=>{A.voiceMeter.show(),A.pitchWheel.show(),A.pan.show(),A.expression.show(),A.volume.show(),A.mod.show(),A.chorus.show(),A.reverb.show(),A.brightness.show(),A.preset.show()})}function My(){this.mainControllerDiv.classList.toggle("synthui_controller_light"),this.mainButtons.forEach(A=>{A.classList.toggle("synthui_button"),A.classList.toggle("synthui_button_light")}),this.mainMeters.forEach(A=>{A.toggleMode(!0)}),this.controllers.forEach(A=>{A.voiceMeter.toggleMode(),A.pitchWheel.toggleMode(),A.pan.toggleMode(),A.expression.toggleMode(),A.volume.toggleMode(),A.mod.toggleMode(),A.chorus.toggleMode(),A.reverb.toggleMode(),A.brightness.toggleMode(),A.preset.toggleMode(),A.drumsToggle.classList.toggle("mute_button_light"),A.muteButton.classList.toggle("mute_button_light")})}var cr=class{constructor(r="none",l,g,u,b=0,A0=100,E0=!1,m0=void 0,c0=void 0,u1=void 0){if(this.meterText="",g.bindObjectProperty(this,"meterText",l+".title"),this.min=b,this.max=A0,this.currentValue=-1,this.isShown=!0,this.isVisualValueSet=!0,this.isLocked=!1,this.lockCallback=c0,this.unlockCallback=u1,this.div=document.createElement("div"),this.div.classList.add("voice_meter"),this.div.classList.add("controller_element"),r!=="none"&&r!==""&&(this.div.style.borderColor=r),g.bindObjectProperty(this.div,"title",l+".description",u),this.bar=document.createElement("div"),this.bar.classList.add("voice_meter_bar"),this.bar.style.background=r,this.div.appendChild(this.bar),this.text=document.createElement("p"),this.text.classList.add("voice_meter_text"),this.div.appendChild(this.text),this.isActive=!1,E0){if(m0===void 0)throw new Error("No editable function given!");this.div.onmousedown=R=>{R.preventDefault(),R.button===0?this.isActive=!0:this.lockMeter()},this.div.onmousemove=R=>{if(!this.isActive)return;let Z0=R.currentTarget.getBoundingClientRect(),G0=Z0.left,D1=Z0.width,l2=R.clientX-G0,y1=Math.max(0,Math.min(1,l2/D1));m0(y1*(A0-b)+b)},this.div.onmouseup=()=>this.isActive=!1,this.div.onmouseleave=R=>{this.div.onmousemove(R),this.isActive=!1},this.text.oncontextmenu=R=>{R.preventDefault()},this.div.onclick=R=>{R.preventDefault(),this.isActive=!0,this.div.onmousemove(R),this.isActive=!1},this.div.classList.add("editable")}}lockMeter(){this.lockCallback!==void 0&&(this.isLocked?(this.text.classList.remove("locked_meter"),this.unlockCallback()):(this.text.classList.add("locked_meter"),this.lockCallback()),this.isLocked=!this.isLocked)}toggleMode(r=!1){r&&(this.bar.classList.toggle("voice_meter_light_color"),this.div.classList.toggle("voice_meter_light_color")),this.text.classList.toggle("voice_meter_text_light")}show(){if(this.isShown=!0,!this.isVisualValueSet){let r=Math.max(0,Math.min((this.currentValue-this.min)/(this.max-this.min),1));this.bar.style.width=`${r*100}%`,this.text.textContent=this.meterText+(Math.round(this.currentValue*100)/100).toString(),this.isVisualValueSet=!0}}hide(){this.isShown=!1}update(r,l=!1){if(!(r===this.currentValue&&l===!1))if(this.currentValue=r,this.isShown){let g=Math.max(0,Math.min((r-this.min)/(this.max-this.min),1));this.bar.style.width=`${g*100}%`,this.text.textContent=this.meterText+(Math.round(r*100)/100).toString(),this.isVisualValueSet=!0}else this.isVisualValueSet=!1}};var Ty=["Acoustic Grand Piano","Bright Acoustic Piano","Electric Grand Piano","Honky-tonk Piano","Electric Piano 1","Electric Piano 2","Harpsichord","Clavi","Celesta","Glockenspiel","Music Box","Vibraphone","Marimba","Xylophone","Tubular Bells","Dulcimer","Drawbar Organ","Percussive Organ","Rock Organ","Church Organ","Reed Organ","Accordion","Harmonica","Tango Accordion","Acoustic Guitar (nylon)","Acoustic Guitar (steel)","Electric Guitar (jazz)","Electric Guitar (clean)","Electric Guitar (muted)","Overdriven Guitar","Distortion Guitar","Guitar Harmonics","Acoustic Bass","Electric Bass (finger)","Electric Bass (pick)","Fretless Bass","Slap Bass 1","Slap Bass 2","Synth Bass 1","Synth Bass 2","Violin","Viola","Cello","Contrabass","Tremolo Strings","Pizzicato Strings","Orchestral Harp","Timpani","String Ensemble 1","String Ensemble 2","Synth Strings 1","Synth Strings 2","Choir Aahs","VoiceGroup Oohs","Synth Choir","Orchestra Hit","Trumpet","Trombone","Tuba","Muted Trumpet","French Horn","Brass Section","Synth Brass 1","Synth Brass 2","Soprano Sax","Alto Sax","Tenor Sax","Baritone Sax","Oboe","English Horn","Bassoon","Clarinet","Piccolo","Flute","Recorder","Pan Flute","Blown Bottle","Shakuhachi","Whistle","Ocarina","Lead 1 (square)","Lead 2 (sawtooth)","Lead 3 (calliope)","Lead 4 (chiff)","Lead 5 (charang)","Lead 6 (voice)","Lead 7 (fifths)","Lead 8 (bass + lead)","Pad 1 (new age)","Pad 2 (warm)","Pad 3 (polysynth)","Pad 4 (choir)","Pad 5 (bowed)","Pad 6 (metallic)","Pad 7 (halo)","Pad 8 (sweep)","FX 1 (rain)","FX 2 (soundtrack)","FX 3 (crystal)","FX 4 (atmosphere)","FX 5 (brightness)","FX 6 (goblins)","FX 7 (echoes)","FX 8 (sci-fi)","Sitar","Banjo","Shamisen","Koto","Kalimba","Bagpipe","Fiddle","Shanai","Tinkle Bell","Agogo","Steel Drums","Woodblock","Taiko Drum","Melodic Tom","Synth Drum","Reverse Cymbal","Guitar Fret Noise","Breath Noise","Seashore","Bird Tweet","Telephone Ring","Attack Helicopter","Applause","Gunshot"];var DC=class{constructor(r,l,g,u,b=void 0,A0=void 0){this.isShown=!0,this.isReloaded=!0,this.elements=r.map(E0=>({name:E0.name,program:E0.program,bank:E0.bank,stringified:`${E0.bank.toString().padStart(3,"0")}:${E0.program.toString().padStart(3,"0")} ${E0.name}`})),this.elements.length>0?this.value=`${this.elements[0].bank}:${this.elements[0].program}`:this.value="",this.mainButton=document.createElement("button"),this.mainButton.classList.add("voice_selector"),this.mainButton.classList.add("controller_element"),l.bindObjectProperty(this.mainButton,"title",g+".description",u),this.locale=l,this.localePath=g,this.localeArgs=u,this.reload(),this.mainButton.onclick=()=>{this.showSelectionMenu()},this.editCallback=b,this.selectionMenu=void 0,this.lockCallback=A0,this.locked=!1,this.isWindowShown=!1}showSelectionMenu(){this.selectionMenu=document.createElement("div"),this.selectionMenu.classList.add("voice_selector_wrapper"),document.getElementsByClassName("spessasynth_main")[0].appendChild(this.selectionMenu);let r=document.createElement("div");r.classList.add("voice_selector_window");let l=document.createElement("h2");this.locale.bindObjectProperty(l,"textContent",this.localePath+".selectionPrompt",this.localeArgs),r.appendChild(l);let g=document.createElement("div");g.classList.add("voice_selector_search_wrapper"),r.appendChild(g);let u=document.createElement("input");u.type="text",this.locale.bindObjectProperty(u,"placeholder",this.localePath+".searchPrompt"),g.appendChild(u),u.onkeydown=E0=>E0.stopPropagation();let b=document.createElement("div");b.innerHTML=this.locked?SC(gt):UB(gt),this.locale.bindObjectProperty(b,"title",se+"channelController.presetReset.description",this.localeArgs),b.classList.add("voice_reset"),this.mainButton.classList.contains("voice_selector_light")&&b.classList.add("voice_reset_light"),b.onclick=()=>{this.locked=!this.locked,this.lockCallback(this.locked),this.mainButton.classList.toggle("locked_selector"),this.locked?b.innerHTML=SC(gt):b.innerHTML=UB(gt)},g.appendChild(b),this.presetLock=b;let A0=document.createElement("div");A0.classList.add("voice_selector_table_wrapper"),r.appendChild(A0),this.generateTable(A0,this.elements),u.oninput=E0=>{E0.stopPropagation();let m0=u.value,c0=this.elements.filter(u1=>u1.stringified.search(new RegExp(m0,"i"))>=0);c0.length!==this.elements.length&&(A0.replaceChildren(),this.generateTable(A0,c0))},r.onclick=E0=>{E0.stopPropagation()},this.selectionMenu.appendChild(r),this.selectionMenu.onclick=E0=>{E0.stopPropagation(),this.hideSelectionMenu()},this.isWindowShown=!0}generateTable(r,l){let g=document.createElement("table");g.classList.add("voice_selector_table");let u=parseInt(this.value.split(":")[0]),b=parseInt(this.value.split(":")[1]),A0=-20;for(let E0 of l){let m0=document.createElement("tr"),c0=E0.program;if(c0===b&&E0.bank===u&&(m0.classList.add("voice_selector_selected"),setTimeout(()=>{m0.scrollIntoView({behavior:"instant",block:"center",inline:"center"})},20)),m0.onclick=()=>{let l2=`${E0.bank}:${c0}`;if(this.value===l2){this.hideSelectionMenu();return}this.editCallback(l2),this.locked=!0,this.presetLock.innerHTML=SC(gt),this.hideSelectionMenu()},c0!==A0&&(A0=c0,E0.bank!==128)){let l2=document.createElement("tr"),y1=document.createElement("th");y1.colSpan="3",y1.textContent=Ty[A0],l2.appendChild(y1),g.appendChild(l2)}let u1=`${E0.program.toString().padStart(3,"0")}`,R=`${E0.bank.toString().padStart(3,"0")}`,Z0=document.createElement("td");Z0.classList.add("voice_selector_preset_name"),Z0.textContent=E0.name;let G0=document.createElement("td");Z0.classList.add("voice_selector_preset_program"),G0.textContent=u1;let D1=document.createElement("td");Z0.classList.add("voice_selector_preset_program"),D1.textContent=R,m0.appendChild(D1),m0.appendChild(G0),m0.appendChild(Z0),g.appendChild(m0)}r.appendChild(g)}hideSelectionMenu(){document.getElementsByClassName("spessasynth_main")[0].removeChild(this.selectionMenu),this.selectionMenu=void 0,this.isWindowShown=!1}toggleMode(){this.mainButton.classList.toggle("voice_selector_light")}reload(r=this.elements){if(this.elements=r.map(l=>({name:l.name,program:l.program,bank:l.bank,stringified:`${l.bank.toString().padStart(3,"0")}:${l.program.toString().padStart(3,"0")} ${l.name}`})),!this.isShown){this.isReloaded=!1;return}this.isReloaded=!0,this.elements.length>0&&(this.mainButton.textContent=this.getString(`${this.elements[0].bank}:${this.value.split(":")[1]}`))}set(r){if(this.value=r,this.isShown&&(this.isReloaded||this.reload(),this.mainButton.textContent=this.getString(this.value),this.isWindowShown)){let l=this.selectionMenu.getElementsByClassName("voice_selector_selected")[0];l!==void 0&&l.classList.remove("voice_selector_selected");let g=this.selectionMenu.getElementsByClassName("voice_selector_table")[0],u=parseInt(this.value.split(":")[0]),b=parseInt(this.value.split(":")[1]);for(let A0 of g.rows){if(A0.cells.length===1)continue;let E0=parseInt(A0.cells[0].textContent),m0=parseInt(A0.cells[1].textContent);E0===u&&m0===b&&(A0.classList.add("voice_selector_selected"),A0.scrollIntoView({behavior:"smooth",block:"center",inline:"center"}))}}}getString(r){let l=r.split(":"),g=parseInt(l[0]),u=parseInt(l[1]),b=this.elements.find(A0=>A0.bank===g&&A0.program===u);return g===128||this.elements.filter(A0=>A0.program===u&&A0.bank!==128).length<2?`${u}. ${b.name}`:`${g}:${u} ${b.name}`}show(){this.isShown=!0,this.isReloaded||this.reload(),this.mainButton.textContent=this.getString(this.value)}hide(){this.isShown=!1}};var gt=32;function Ny(A){this.soloChannels=new Set;let r=document.createElement("div");r.classList.add("channel_controller");let l=new cr(this.channelColors[A%this.channelColors.length],se+"channelController.voiceMeter",this.locale,[A+1],0,100);l.bar.classList.add("voice_meter_bar_smooth"),r.appendChild(l.div);let g=new cr(this.channelColors[A%this.channelColors.length],se+"channelController.pitchBendMeter",this.locale,[A+1],-8192,8191,!0,T2=>{let K2=g.isLocked;K2&&this.synth.lockController(A,m$+x7.pitchWheel,!1),T2=Math.round(T2)+8192;let i3=T2>>7,r3=T2&127;this.synth.pitchWheel(A,i3,r3),K2&&this.synth.lockController(A,m$+x7.pitchWheel,!0)},()=>this.synth.lockController(A,m$+x7.pitchWheel,!0),()=>this.synth.lockController(A,m$+x7.pitchWheel,!1));g.update(0),r.appendChild(g.div);let u=(T2,K2,i3)=>{i3.isLocked?(this.synth.lockController(A,T2,!1),this.synth.controllerChange(A,T2,K2),this.synth.lockController(A,T2,!0)):this.synth.controllerChange(A,T2,K2)},b=(T2,K2,i3)=>{let r3=new cr(this.channelColors[A%this.channelColors.length],se+K2,this.locale,[A+1],0,127,!0,o0=>u(T2,Math.round(o0),r3),()=>this.synth.lockController(A,T2,!0),()=>this.synth.lockController(A,T2,!1));return r3.update(i3),r3},A0=b(t6.pan,"channelController.panMeter",64);r.appendChild(A0.div);let E0=b(t6.expressionController,"channelController.expressionMeter",127);r.appendChild(E0.div);let m0=b(t6.mainVolume,"channelController.volumeMeter",100);r.appendChild(m0.div);let c0=b(t6.modulationWheel,"channelController.modulationWheelMeter",0);r.appendChild(c0.div);let u1=b(t6.effects3Depth,"channelController.chorusMeter",0);r.appendChild(u1.div);let R=b(t6.effects1Depth,"channelController.reverbMeter",0);r.appendChild(R.div);let Z0=b(t6.brightness,"channelController.filterMeter",64);r.appendChild(Z0.div);let G0=new cr(this.channelColors[A%this.channelColors.length],se+"channelController.transposeMeter",this.locale,[A+1],-36,36,!0,T2=>{T2=Math.round(T2),this.synth.transposeChannel(A,T2,!0),G0.update(T2)});G0.update(0),r.appendChild(G0.div);let D1=new DC([],this.locale,se+"channelController.presetSelector",[A+1],async T2=>{let K2=T2.split(":");this.synth.lockController(A,mi,!1),this.synth.controllerChange(A,t6.bankSelect,parseInt(K2[0]),!0),this.synth.programChange(A,parseInt(K2[1]),!0),D1.mainButton.classList.add("locked_selector"),this.synth.lockController(A,mi,!0)},T2=>this.synth.lockController(A,mi,T2));r.appendChild(D1.mainButton);let l2=document.createElement("div");l2.innerHTML=ch(gt),this.locale.bindObjectProperty(l2,"title",se+"channelController.soloButton.description",[A+1]),l2.classList.add("controller_element"),l2.classList.add("mute_button"),l2.onclick=()=>{if(this.soloChannels.has(A)?this.soloChannels.delete(A):this.soloChannels.add(A),this.soloChannels.size===0||this.soloChannels.size>=this.synth.channelsAmount){for(let T2=0;T2=this.synth.channelsAmount&&this.soloChannels.clear();return}for(let T2=0;T2{if(y1.hasAttribute("is_muted")){y1.removeAttribute("is_muted");let T2=this.soloChannels.size===0||this.soloChannels.has(A);this.synth.muteChannel(A,!T2),y1.innerHTML=km(gt)}else this.synth.muteChannel(A,!0),y1.setAttribute("is_muted","true"),y1.innerHTML=Qy(gt)},r.appendChild(y1);let Y2=document.createElement("div");return Y2.innerHTML=A===bi?kC(gt):vC(gt),this.locale.bindObjectProperty(Y2,"title",se+"channelController.drumToggleButton.description",[A+1]),Y2.classList.add("controller_element"),Y2.classList.add("mute_button"),Y2.onclick=()=>{this.synth.setDrums(A,!this.synth.channelProperties[A].isDrum)},r.appendChild(Y2),{controller:r,voiceMeter:l,pitchWheel:g,pan:A0,expression:E0,volume:m0,mod:c0,chorus:u1,reverb:R,brightness:Z0,preset:D1,drumsToggle:Y2,soloButton:l2,muteButton:y1,transpose:G0}}function Gy(){let A=this.uiDiv.getElementsByClassName("synthui_controller")[0];this.controllers=[];for(let r=0;r{this.synth.setMainVolume(Math.round(c0)/100),this.volumeController.update(c0)}),this.volumeController.bar.classList.add("voice_meter_bar_smooth"),this.volumeController.div.classList.add("main_controller_element"),this.volumeController.update(100),this.panController=new cr("",se+"mainPanMeter",this.locale,[],-1,1,!0,c0=>{this.synth.setMasterPan(c0),this.panController.update(c0)}),this.panController.bar.classList.add("voice_meter_bar_smooth"),this.panController.div.classList.add("main_controller_element"),this.panController.update(0),this.transposeController=new cr("",se+"mainTransposeMeter",this.locale,[],-12,12,!0,c0=>{this.synth.transpose(Math.round(c0*2)/2),this.transposeController.update(Math.round(c0*2)/2)}),this.transposeController.bar.classList.add("voice_meter_bar_smooth"),this.transposeController.div.classList.add("main_controller_element"),this.transposeController.update(0);let r=document.createElement("button");this.locale.bindObjectProperty(r,"textContent",se+"midiPanic.title"),this.locale.bindObjectProperty(r,"title",se+"midiPanic.description"),r.classList.add("synthui_button"),r.classList.add("main_controller_element"),r.onclick=()=>this.synth.stopAll(!0);let l=document.createElement("button");this.locale.bindObjectProperty(l,"textContent",se+"systemReset.title"),this.locale.bindObjectProperty(l,"title",se+"systemReset.description"),l.classList.add("synthui_button"),l.classList.add("main_controller_element"),l.onclick=()=>{this.controllers.forEach((c0,u1)=>{c0.pitchWheel.isLocked&&c0.pitchWheel.lockMeter(),c0.pan.isLocked&&c0.pan.lockMeter(),c0.expression.isLocked&&c0.expression.lockMeter(),c0.volume.isLocked&&c0.volume.lockMeter(),c0.mod.isLocked&&c0.mod.lockMeter(),c0.chorus.isLocked&&c0.chorus.lockMeter(),c0.reverb.isLocked&&c0.reverb.lockMeter(),c0.brightness.isLocked&&c0.brightness.lockMeter(),c0.preset.mainButton.classList.contains("locked_selector")&&(this.synth.lockController(u1,mi,!1),c0.preset.mainButton.classList.remove("locked_selector")),this.synth.transposeChannel(u1,0,!0),c0.transpose.update(0),c0.soloButton.innerHTML=ch(gt),c0.muteButton.innerHTML=km(gt),this.synth.muteChannel(u1,!1)}),this.synth.resetControllers()};let g=document.createElement("button");this.locale.bindObjectProperty(g,"textContent",se+"blackMidiMode.title"),this.locale.bindObjectProperty(g,"title",se+"blackMidiMode.description"),g.classList.add("synthui_button"),g.classList.add("main_controller_element"),g.onclick=()=>{this.synth.highPerformanceMode=!this.synth.highPerformanceMode};let u=document.createElement("button");this.locale.bindObjectProperty(u,"textContent",se+"disableCustomVibrato.title"),this.locale.bindObjectProperty(u,"title",se+"disableCustomVibrato.description"),u.classList.add("synthui_button"),u.classList.add("main_controller_element"),u.onclick=()=>{this.synth.disableGSNRPparams(),u.parentNode.removeChild(u)};let b=document.createElement("a");b.href="https://github.com/spessasus/SpessaSynth/wiki/How-To-Use-App#synthesizer-controller",b.target="#",b.classList.add("main_controller_element"),b.classList.add("synthui_button"),this.locale.bindObjectProperty(b,"textContent",se+"helpButton.title"),this.locale.bindObjectProperty(b,"title",se+"helpButton.description");let A0=document.createElement("select");A0.classList.add("main_controller_element"),A0.classList.add("synthui_button"),this.locale.bindObjectProperty(A0,"title",se+"interpolation.description");{let c0=document.createElement("option");c0.value="0",this.locale.bindObjectProperty(c0,"textContent",se+"interpolation.linear"),A0.appendChild(c0);let u1=document.createElement("option");u1.value="1",this.locale.bindObjectProperty(u1,"textContent",se+"interpolation.nearestNeighbor"),A0.appendChild(u1);let R=document.createElement("option");R.value="2",R.selected=!0,this.locale.bindObjectProperty(R,"textContent",se+"interpolation.cubic"),A0.appendChild(R),A0.onchange=()=>{this.synth.setInterpolationType(parseInt(A0.value))}}let E0=document.createElement("div");E0.classList.add("synthui_controller"),this.uiDiv.appendChild(E0);let m0=document.createElement("button");this.locale.bindObjectProperty(m0,"textContent",se+"toggleButton.title"),this.locale.bindObjectProperty(m0,"title",se+"toggleButton.description"),m0.classList.add("synthui_button"),m0.onclick=()=>{this.hideOnDocClick=!1,this.toggleVisibility()},A.appendChild(this.volumeController.div),A.appendChild(this.panController.div),A.appendChild(this.transposeController.div),A.appendChild(r),A.appendChild(l),A.appendChild(g),A.appendChild(u),A.appendChild(b),A.appendChild(A0),this.mainMeters=[this.volumeController,this.panController,this.transposeController,this.voiceMeter],this.mainButtons=[r,l,g,u,m0,b,A0],this.uiDiv.appendChild(this.voiceMeter.div),this.uiDiv.appendChild(m0),E0.appendChild(A),this.mainControllerDiv=E0,this.mainControllerDiv.onclick=c0=>c0.stopPropagation(),document.addEventListener("click",()=>{if(!this.hideOnDocClick){this.hideOnDocClick=!0;return}E0.classList.remove("synthui_controller_show"),this.isShown=!1,this.hideControllers()})}function Py(){let A=this.uiDiv.getElementsByClassName("synthui_controller")[0];this.synth.eventHandler.addEvent("programchange","synthui-program-change",r=>{this.controllers[r.channel].preset.set(`${r.bank}:${r.program}`)}),this.synth.eventHandler.addEvent("allcontrollerreset","synthui-all-controller-reset",()=>{for(let r of this.controllers)r.pan.update(64),r.mod.update(0),r.chorus.update(0),r.pitchWheel.update(0),r.expression.update(127),r.volume.update(100),r.reverb.update(0),r.brightness.update(64)}),this.synth.eventHandler.addEvent("controllerchange","synthui-controller-change",r=>{let l=r.controllerNumber,g=r.channel,u=r.controllerValue;switch(l){default:break;case t6.expressionController:this.controllers[g].expression.update(u);break;case t6.mainVolume:this.controllers[g].volume.update(u);break;case t6.pan:this.controllers[g].pan.update(u);break;case t6.modulationWheel:this.controllers[g].mod.update(u);break;case t6.effects3Depth:this.controllers[g].chorus.update(u);break;case t6.effects1Depth:this.controllers[g].reverb.update(u);break;case t6.brightness:this.controllers[g].brightness.update(u)}}),this.synth.eventHandler.addEvent("pitchwheel","synthui-pitch-wheel",r=>{let l=r.MSB<<7|r.LSB;this.controllers[r.channel].pitchWheel.update(l-8192)}),this.synth.eventHandler.addEvent("drumchange","synthui-drum-change",r=>{this.controllers[r.channel].drumsToggle.innerHTML=r.isDrumChannel?kC(32):vC(32),this.controllers[r.channel].preset.reload(r.isDrumChannel?this.percussionList:this.instrumentList)}),this.synth.eventHandler.addEvent("newchannel","synthui-new-channel",()=>{let r=this.createChannelController(this.controllers.length);this.controllers.push(r),A.appendChild(r.controller),this.hideControllers()})}var se="locale.synthesizerController.",Gr=class{constructor(r,l,g){this.channelColors=r;let u=l;this.uiDiv=document.createElement("div"),this.uiDiv.classList.add("wrapper"),u.appendChild(this.uiDiv),this.uiDiv.style.visibility="visible",this.isShown=!1,this.animationId=-1,this.locale=g,this.hideOnDocClick=!0}connectSynth(r){this.synth=r,this.getInstrumentList(),this.createMainSynthController(),this.createChannelControllers(),document.addEventListener("keydown",l=>{switch(l.key.toLowerCase()){case X7.synthesizerUIShow:l.preventDefault(),this.toggleVisibility();break;case X7.settingsShow:this.isShown=!0,this.toggleVisibility();break;case X7.blackMidiMode:l.preventDefault(),this.synth.highPerformanceMode=!this.synth.highPerformanceMode;break;case X7.midiPanic:l.preventDefault(),this.synth.stopAll(!0);break}}),this.locale.onLocaleChanged.push(()=>{this.voiceMeter.update(this.voiceMeter.currentValue,!0),this.volumeController.update(this.volumeController.currentValue,!0),this.panController.update(this.panController.currentValue,!0),this.panController.update(this.panController.currentValue,!0),this.transposeController.update(this.transposeController.currentValue,!0);for(let l of this.controllers)l.voiceMeter.update(l.voiceMeter.currentValue,!0),l.pitchWheel.update(l.pitchWheel.currentValue,!0),l.pan.update(l.pan.currentValue,!0),l.volume.update(l.volume.currentValue,!0),l.expression.update(l.expression.currentValue,!0),l.mod.update(l.mod.currentValue,!0),l.chorus.update(l.chorus.currentValue,!0),l.reverb.update(l.reverb.currentValue,!0),l.brightness.update(l.brightness.currentValue,!0),l.transpose.update(l.transpose.currentValue,!0)})}toggleVisibility(){this.animationId!==-1&&clearTimeout(this.animationId);let r=document.getElementsByClassName("synthui_controller")[0];this.isShown=!this.isShown,this.isShown?(r.style.display="block",document.getElementsByClassName("top_part")[0].classList.add("synthui_shown"),this.showControllers(),setTimeout(()=>{r.classList.add("synthui_controller_show")},75)):(document.getElementsByClassName("top_part")[0].classList.remove("synthui_shown"),this.hideControllers(),r.classList.remove("synthui_controller_show"),this.animationId=setTimeout(()=>{r.style.display="none"},200))}updateVoicesAmount(){this.voiceMeter.update(this.synth.voicesAmount),this.controllers.forEach((r,l)=>{let g=this.synth.channelProperties[l].voicesAmount;r.voiceMeter.update(g),g<1&&this.synth.voicesAmount>0?r.controller.classList.add("no_voices"):r.controller.classList.remove("no_voices")})}getInstrumentList(){this.synth.eventHandler.addEvent("presetlistchange","synthui-preset-list-change",r=>{let l=r;this.instrumentList=l.filter(g=>g.bank!==128).sort((g,u)=>g.program===u.program?g.bank-u.bank:g.program-u.program).map(g=>({name:g.presetName,bank:g.bank,program:g.program})),this.percussionList=l.filter(g=>g.bank===128).sort((g,u)=>g.program-u.program).map(g=>({name:g.presetName,bank:g.bank,program:g.program})),this.percussionList.length===0?this.percussionList=this.instrumentList:this.instrumentList.length===0&&(this.instrumentList=this.percussionList),this.controllers.forEach((g,u)=>{let b=this.synth.channelProperties[u].isDrum?this.percussionList:this.instrumentList;g.preset.reload(b),g.preset.set(`${b[0].bank}:${b[0].program}`)})})}};Gr.prototype.hideControllers=Ly;Gr.prototype.showControllers=Fy;Gr.prototype.toggleDarkMode=My;Gr.prototype.createChannelController=Ny;Gr.prototype.createChannelControllers=Gy;Gr.prototype.createMainSynthController=Uy;Gr.prototype.setEventListeners=Py;var vm=null,bC=class{constructor(){}async createMIDIDeviceHandler(){if(this.selectedInput=vm,this.selectedOutput=vm,navigator.requestMIDIAccess)try{let r=await navigator.requestMIDIAccess({sysex:!0,software:!0});return this.inputs=r.inputs,this.outputs=r.outputs,W5("%cMIDI handler created!",_1.recognized),!0}catch(r){return de("Could not get MIDI Devices:",r),this.inputs=[],this.outputs=[],!1}else return de("Web MIDI Api not supported!",_1.unrecognized),this.inputs=[],this.outputs=[],!1}connectMIDIOutputToSeq(r,l){this.selectedOutput=r,l.connectMidiOutput(r),W5(`%cPlaying MIDI to %c${r.name}`,_1.info,_1.recognized)}disconnectSeqFromMIDI(r){this.selectedOutput=vm,r.connectMidiOutput(void 0),W5("%cDisconnected from MIDI out.",_1.info)}connectDeviceToSynth(r,l){this.selectedInput=r,r.onmidimessage=g=>{l.sendMessage(g.data)},W5(`%cListening for messages on %c${r.name}`,_1.info,_1.recognized)}disconnectDeviceFromSynth(r){this.selectedInput=vm,r.onmidimessage=void 0,W5(`%cDisconnected from %c${r.name}`,_1.info,_1.recognized)}disconnectAllDevicesFromSynth(){this.selectedInput=vm;for(let r of this.inputs)r[1].onmidimessage=void 0}};var _C=class{constructor(r){window.addEventListener("message",l=>{if(typeof l.data!="string")return;let g=l.data.split(",");if(g[0]!=="midi")return;g.shift();let u=g.map(b=>parseInt(b,16));r.sendMessage(u)}),W5("%cWeb MIDI Link handler created!",_1.recognized)}};var To="midi range";function Oy(A,r,l){let g=0,u=this.htmlControls.keyboard,b=()=>{let A0=document.createElement("option");A0.value=g.toString(),this.locale.bindObjectProperty(A0,"textContent","locale.settings.keyboardSettings.selectedChannel.channelOption",[g+1]),A0.style.background=r.channelColors[g%r.channelColors.length],A0.style.color="rgb(0, 0, 0)",u.channelSelector.appendChild(A0),g++};for(let A0=0;A0{A.selectChannel(parseInt(u.channelSelector.value))},u.sizeSelector.onchange=()=>{if(this.musicMode.visible){this.musicMode.setVisibility(!1,document.getElementById("keyboard_canvas_wrapper")),setTimeout(()=>{u.sizeSelector.value===To?(this.autoKeyRange=!0,this?.sequi?.seq&&(A.keyRange=this.sequi.seq.midiData.keyRange,l.keyRange=this.sequi.seq.midiData.keyRange)):(this.autoKeyRange=!1,A.keyRange=this.keyboardSizes[u.sizeSelector.value],l.keyRange=this.keyboardSizes[u.sizeSelector.value]),this._saveSettings()},600);return}u.sizeSelector.value===To?(this.autoKeyRange=!0,this?.sequi?.seq&&(A.keyRange=this.sequi.seq.midiData.keyRange,l.keyRange=this.sequi.seq.midiData.keyRange)):(this.autoKeyRange=!1,A.keyRange=this.keyboardSizes[u.sizeSelector.value],l.keyRange=this.keyboardSizes[u.sizeSelector.value]),this._saveSettings()},this.addSequencer=A0=>{A0.addOnSongChangeEvent(E0=>{this.autoKeyRange&&(A.keyRange=E0.keyRange,l.keyRange=E0.keyRange),E0.RMIDInfo?.IPIC!==void 0&&this.musicMode.visible===!1&&this.toggleMusicPlayerMode().then()},"settings-keyboard-handler-song-change")},r.synth.eventHandler.addEvent("newchannel","settings-new-channel",()=>{b()}),r.synth.eventHandler.addEvent("programchange","settings-keyboard-program-change",A0=>{A0.userCalled&&(A.selectChannel(A0.channel),u.channelSelector.value=A0.channel)}),r.synth.eventHandler.addEvent("mutechannel","settings-keuboard-mute-channel",A0=>{if(A0.isMuted&&A0.channel===A.channel){let E0=0;for(;r.synth.channelProperties[E0].isMuted;)E0++;E0{if(this.musicMode.visible){this.musicMode.setVisibility(!1,document.getElementById("keyboard_canvas_wrapper")),setTimeout(()=>{A.toggleMode(),this._saveSettings()},600);return}A.toggleMode(),this._saveSettings()},u.showSelector.onclick=()=>{A.shown=!A.shown,this._saveSettings()}}var Hy=`