From 3e66754da64d7cbe9b5d46b73c18600a391139c4 Mon Sep 17 00:00:00 2001 From: spessasus Date: Sun, 10 Nov 2024 23:02:29 +0100 Subject: [PATCH] send reset all controllers and take it into account in sequencer --- .../sequencer/worklet_sequencer/play.js | 14 ++++++------- .../synthetizer/worklet_processor.min.js | 20 +++++++++---------- .../worklet_methods/reset_controllers.js | 15 +++++++++++++- 3 files changed, 30 insertions(+), 19 deletions(-) diff --git a/src/spessasynth_lib/sequencer/worklet_sequencer/play.js b/src/spessasynth_lib/sequencer/worklet_sequencer/play.js index 6efa6b3..7798e35 100644 --- a/src/spessasynth_lib/sequencer/worklet_sequencer/play.js +++ b/src/spessasynth_lib/sequencer/worklet_sequencer/play.js @@ -1,17 +1,11 @@ import { getEvent, messageTypes, midiControllers } from "../../midi_parser/midi_message.js"; import { WorkletSequencerReturnMessageType } from "./sequencer_message.js"; import { MIDIticksToSeconds } from "../../midi_parser/basic_midi.js"; +import { resetArray } from "../../synthetizer/worklet_system/worklet_utilities/controller_tables.js"; // an array with preset default values -const defaultControllerArray = new Int16Array(127); -// default values -defaultControllerArray[midiControllers.mainVolume] = 100; -defaultControllerArray[midiControllers.expressionController] = 127; -defaultControllerArray[midiControllers.pan] = 64; -defaultControllerArray[midiControllers.releaseTime] = 64; -defaultControllerArray[midiControllers.brightness] = 64; -defaultControllerArray[midiControllers.reverbDepth] = 0; +const defaultControllerArray = resetArray.slice(0, 128); /** * plays from start to the target time, excluding note messages (to get the synth to the correct state) @@ -130,6 +124,10 @@ export function _playTo(time, ticks = undefined) programs[channel].bank = ccV; break; } + else if (controllerNumber === midiControllers.resetAllControllers) + { + savedControllers[channel] = Array.from(defaultControllerArray); + } if (this.sendMIDIMessages) { this.sendMIDICC(channel, controllerNumber, ccV); diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index 68e4e84..cf8b888 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -1,4 +1,4 @@ -var cs=(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 J=class extends Uint8Array{currentIndex;constructor(A){super(A),this.currentIndex=0}};function Fe(t){let A=t.reduce((n,o)=>n+o.length,0),e=new J(A),s=0;for(let n of t)e.set(n,s),s+=n.length;return e}function Dt(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 ls(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 y={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,reverbDepth:91,tremoloDepth:92,chorusDepth:93,detuneDepth:94,phaserDepth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},ds={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var j={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,keyModifierManager:26},Ee={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},HA=-1,uA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var fs=!1,ms=!0,Ke=!1,ps=!0;function ys(t,A,e,s){fs=t,ms=A,Ke=e,ps=s}function m(...t){fs&&console.info(...t)}function H(...t){ms&&console.warn(...t)}function Ss(...t){ps&&console.table(...t)}function ne(...t){Ke&&console.group(...t)}function yA(...t){Ke&&console.groupCollapsed(...t)}function O(){Ke&&console.groupEnd()}var Be={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var a={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},T=[];T[a.startAddrsOffset]={min:0,max:32768,def:0};T[a.endAddrOffset]={min:-32768,max:32768,def:0};T[a.startloopAddrsOffset]={min:-32768,max:32768,def:0};T[a.endloopAddrsOffset]={min:-32768,max:32768,def:0};T[a.startAddrsCoarseOffset]={min:0,max:32768,def:0};T[a.modLfoToPitch]={min:-12e3,max:12e3,def:0};T[a.vibLfoToPitch]={min:-12e3,max:12e3,def:0};T[a.modEnvToPitch]={min:-12e3,max:12e3,def:0};T[a.initialFilterFc]={min:1500,max:13500,def:13500};T[a.initialFilterQ]={min:0,max:960,def:0};T[a.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};T[a.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};T[a.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[a.modLfoToVolume]={min:-960,max:960,def:0};T[a.chorusEffectsSend]={min:0,max:1e3,def:0};T[a.reverbEffectsSend]={min:0,max:1e3,def:0};T[a.pan]={min:-500,max:500,def:0};T[a.delayModLFO]={min:-12e3,max:5e3,def:-12e3};T[a.freqModLFO]={min:-16e3,max:4500,def:0};T[a.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};T[a.freqVibLFO]={min:-16e3,max:4500,def:0};T[a.delayModEnv]={min:-32768,max:5e3,def:-32768};T[a.attackModEnv]={min:-32768,max:8e3,def:-32768};T[a.holdModEnv]={min:-12e3,max:5e3,def:-12e3};T[a.decayModEnv]={min:-12e3,max:8e3,def:-12e3};T[a.sustainModEnv]={min:0,max:1e3,def:0};T[a.releaseModEnv]={min:-7200,max:8e3,def:-12e3};T[a.keyNumToModEnvHold]={min:-1200,max:1200,def:0};T[a.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};T[a.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};T[a.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};T[a.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};T[a.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};T[a.sustainVolEnv]={min:0,max:1440,def:0};T[a.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};T[a.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};T[a.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};T[a.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[a.keyNum]={min:-1,max:127,def:-1};T[a.velocity]={min:-1,max:127,def:-1};T[a.initialAttenuation]={min:-250,max:1440,def:0};T[a.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[a.coarseTune]={min:-120,max:120,def:0};T[a.fineTune]={min:-12700,max:12700,def:0};T[a.scaleTuning]={min:0,max:1200,def:100};T[a.exclusiveClass]={min:0,max:99999,def:0};T[a.overridingRootKey]={min:-1,max:127,def:-1};var U=class{generatorType=a.INVALID;generatorValue=0;constructor(A=a.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let s=T[A];this.generatorValue=Math.round(e),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}};function Ds(t,A,e){let s=T[t]||{min:0,max:32768,def:0},n=A.find(h=>h.generatorType===t),o=0;n&&(o=n.generatorValue);let i=e.find(h=>h.generatorType===t),g=s.def;i&&(g=i.generatorValue);let B=g+o;return t===a.initialAttenuation?B:Math.max(s.min,Math.min(s.max,B))}var K={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},hA={linear:0,concave:1,convex:2,switch:3},_=class t{currentValue=0;constructor(A){this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform,this.modulatorDestination>58&&(this.modulatorDestination=a.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3,this.isEffectModulator=(this.sourceEnum===219||this.sourceEnum===221)&&this.secondarySourceEnum===0&&(this.modulatorDestination===a.reverbEffectsSend||this.modulatorDestination===a.chorusEffectsSend)}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(hA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(y,this.sourceIndex):e+=A(K,this.sourceIndex);let s=A(hA,this.secSrcCurveType);return s+=this.secSrcPolarity===0?" unipolar ":" bipolar ",s+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?s+=A(y,this.secSrcIndex):s+=A(K,this.secSrcIndex),`Modulator: +var cs=(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 J=class extends Uint8Array{currentIndex;constructor(A){super(A),this.currentIndex=0}};function Fe(t){let A=t.reduce((n,o)=>n+o.length,0),e=new J(A),s=0;for(let n of t)e.set(n,s),s+=n.length;return e}function kt(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 ls(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 S={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,reverbDepth:91,tremoloDepth:92,chorusDepth:93,detuneDepth:94,phaserDepth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},ds={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var j={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,keyModifierManager:26},Ce={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},HA=-1,uA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var fs=!1,ms=!0,Ve=!1,ps=!0;function ys(t,A,e,s){fs=t,ms=A,Ve=e,ps=s}function m(...t){fs&&console.info(...t)}function H(...t){ms&&console.warn(...t)}function Ss(...t){ps&&console.table(...t)}function se(...t){Ve&&console.group(...t)}function yA(...t){Ve&&console.groupCollapsed(...t)}function V(){Ve&&console.groupEnd()}var Ee={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var a={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},T=[];T[a.startAddrsOffset]={min:0,max:32768,def:0};T[a.endAddrOffset]={min:-32768,max:32768,def:0};T[a.startloopAddrsOffset]={min:-32768,max:32768,def:0};T[a.endloopAddrsOffset]={min:-32768,max:32768,def:0};T[a.startAddrsCoarseOffset]={min:0,max:32768,def:0};T[a.modLfoToPitch]={min:-12e3,max:12e3,def:0};T[a.vibLfoToPitch]={min:-12e3,max:12e3,def:0};T[a.modEnvToPitch]={min:-12e3,max:12e3,def:0};T[a.initialFilterFc]={min:1500,max:13500,def:13500};T[a.initialFilterQ]={min:0,max:960,def:0};T[a.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};T[a.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};T[a.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[a.modLfoToVolume]={min:-960,max:960,def:0};T[a.chorusEffectsSend]={min:0,max:1e3,def:0};T[a.reverbEffectsSend]={min:0,max:1e3,def:0};T[a.pan]={min:-500,max:500,def:0};T[a.delayModLFO]={min:-12e3,max:5e3,def:-12e3};T[a.freqModLFO]={min:-16e3,max:4500,def:0};T[a.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};T[a.freqVibLFO]={min:-16e3,max:4500,def:0};T[a.delayModEnv]={min:-32768,max:5e3,def:-32768};T[a.attackModEnv]={min:-32768,max:8e3,def:-32768};T[a.holdModEnv]={min:-12e3,max:5e3,def:-12e3};T[a.decayModEnv]={min:-12e3,max:8e3,def:-12e3};T[a.sustainModEnv]={min:0,max:1e3,def:0};T[a.releaseModEnv]={min:-7200,max:8e3,def:-12e3};T[a.keyNumToModEnvHold]={min:-1200,max:1200,def:0};T[a.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};T[a.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};T[a.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};T[a.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};T[a.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};T[a.sustainVolEnv]={min:0,max:1440,def:0};T[a.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};T[a.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};T[a.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};T[a.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[a.keyNum]={min:-1,max:127,def:-1};T[a.velocity]={min:-1,max:127,def:-1};T[a.initialAttenuation]={min:-250,max:1440,def:0};T[a.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};T[a.coarseTune]={min:-120,max:120,def:0};T[a.fineTune]={min:-12700,max:12700,def:0};T[a.scaleTuning]={min:0,max:1200,def:100};T[a.exclusiveClass]={min:0,max:99999,def:0};T[a.overridingRootKey]={min:-1,max:127,def:-1};var U=class{generatorType=a.INVALID;generatorValue=0;constructor(A=a.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let s=T[A];this.generatorValue=Math.round(e),s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}};function Ds(t,A,e){let s=T[t]||{min:0,max:32768,def:0},n=A.find(h=>h.generatorType===t),o=0;n&&(o=n.generatorValue);let i=e.find(h=>h.generatorType===t),g=s.def;i&&(g=i.generatorValue);let B=g+o;return t===a.initialAttenuation?B:Math.max(s.min,Math.min(s.max,B))}var K={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},hA={linear:0,concave:1,convex:2,switch:3},_=class t{currentValue=0;constructor(A){this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform,this.modulatorDestination>58&&(this.modulatorDestination=a.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3,this.isEffectModulator=(this.sourceEnum===219||this.sourceEnum===221)&&this.secondarySourceEnum===0&&(this.modulatorDestination===a.reverbEffectsSend||this.modulatorDestination===a.chorusEffectsSend)}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(hA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(S,this.sourceIndex):e+=A(K,this.sourceIndex);let s=A(hA,this.secSrcCurveType);return s+=this.secSrcPolarity===0?" unipolar ":" bipolar ",s+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?s+=A(S,this.secSrcIndex):s+=A(K,this.secSrcIndex),`Modulator: Source: ${e} Secondary source: ${s} Destination: ${A(a,this.modulatorDestination)} @@ -6,13 +6,13 @@ var cs=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>( Transform type: ${this.transformType} -`}},kt=960,wt=hA.concave;function YA(t,A,e,s,n){return t<<10|A<<9|e<<8|s<<7|n}var Oe=[new _({srcEnum:YA(wt,0,1,0,K.noteOnVelocity),dest:a.initialAttenuation,amt:kt,secSrcEnum:0,transform:0}),new _({srcEnum:129,dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new _({srcEnum:YA(wt,0,1,1,y.mainVolume),dest:a.initialAttenuation,amt:kt,secSrcEnum:0,transform:0}),new _({srcEnum:13,dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new _({srcEnum:526,dest:a.fineTune,amt:12700,secSrcEnum:16,transform:0}),new _({srcEnum:650,dest:a.pan,amt:500,secSrcEnum:0,transform:0}),new _({srcEnum:YA(wt,0,1,1,y.expressionController),dest:a.initialAttenuation,amt:kt,secSrcEnum:0,transform:0}),new _({srcEnum:219,dest:a.reverbEffectsSend,amt:200,secSrcEnum:0,transform:0}),new _({srcEnum:221,dest:a.chorusEffectsSend,amt:200,secSrcEnum:0,transform:0}),new _({srcEnum:YA(hA.linear,0,0,0,K.polyPressure),dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new _({srcEnum:YA(hA.linear,0,0,1,y.tremoloDepth),dest:a.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new _({srcEnum:YA(hA.linear,1,0,1,y.releaseTime),dest:a.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new _({srcEnum:YA(hA.linear,1,0,1,y.brightness),dest:a.initialFilterFc,amt:6e3,secSrcEnum:0,transform:0}),new _({srcEnum:YA(hA.linear,1,0,1,y.timbreHarmonicContent),dest:a.initialFilterQ,amt:250,secSrcEnum:0,transform:0})];var gA=128,Ve=147,Ft=new Int16Array(Ve).fill(0),dA=(t,A)=>Ft[t]=A<<7;dA(y.mainVolume,100);dA(y.balance,64);dA(y.expressionController,127);dA(y.pan,64);dA(y.timbreHarmonicContent,64);dA(y.releaseTime,64);dA(y.attackTime,64);dA(y.brightness,64);dA(y.soundController6,64);dA(y.soundController7,64);dA(y.soundController8,64);dA(y.soundController9,64);dA(y.generalPurposeController6,64);dA(y.generalPurposeController8,64);dA(gA+K.pitchWheel,64);dA(gA+K.pitchWheelRange,2);var aA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Rt=Object.keys(aA).length,Gt=new Float32Array(Rt);Gt[aA.modulationMultiplier]=1;var fA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6};function ks(t=!1){let A={midiControllers:new Int16Array(Ve),lockedControllers:Array(Ve).fill(!1),customControllers:new Float32Array(Rt),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:fA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},velocityOverride:0,lockGSNRPNParams:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let e=0;e<128;e++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),t&&this.callEvent("newchannel",void 0)}function jA(t,A){t.lockPreset||(t.bank=A)}function KA(t){return t.drumChannel?128:t.bank}var xt={velocityOverride:128};var Ze={addMapping:0,deleteMapping:1,clearMappings:2},Xe=class{_keyMappings=[];handleMessage(A,e){switch(A){default:return;case Ze.addMapping:this.addMapping(...e);break;case Ze.clearMappings:this.clearMappings();break;case Ze.deleteMapping:this.deleteMapping(...e)}}addMapping(A,e,s){this._keyMappings[A]===void 0&&(this._keyMappings[A]=[]),this._keyMappings[A][e]=s}deleteMapping(A,e){this._keyMappings[A]?.[e]!==void 0&&(this._keyMappings[A][e]=void 0)}clearMappings(){this._keyMappings=[]}setMappings(A){this._keyMappings=A}getMappings(){return this._keyMappings}getVelocity(A,e){let s=this._keyMappings[A]?.[e];return s?s.velocity:-1}hasOverridePatch(A,e){let s=this._keyMappings[A]?.[e]?.patch?.bank;return s!==void 0&&s>=0}getPatch(A,e){let s=this._keyMappings[A]?.[e];if(s)return s.patch;throw new Error("No modifier.")}};var ws="spessasynth-worklet-system",Fs=350,SA=9,We=16,_e="gs";var wA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10,setPreservePlaybackState:11},FA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function $A(t,A){let e=0;for(let s=8*(A-1);s>=0;s-=8)e|=t[t.currentIndex++]<>>0}function Rs(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=Re(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(g=>g.midiNote===t.messageData[0]&&g.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/(Ho(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),H("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:H(`%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 Gs(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Ho(t){return t.messageData.currentIndex=0,6e7/$A(t.messageData,3)}function xs(){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 Ms(){let t=0,A=1/0;return this.tracks.forEach((e,s)=>{this.eventIndex[s]>=e.length||e[this.eventIndex[s]].ticks>>0}function he(t,A,e){for(let s=0;s>s*8&255}function v(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function QA(t,A){he(t,A,4)}function Ae(t,A){let e=A<<8|t;return e>32767?e-65536:e}function Ns(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(g===0){n=!0;continue}}o+=String.fromCharCode(g)}}return o}}function RA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let s=0;sA.length)for(let s=0;se.header!=="LIST"?!1:(e.chunkData.currentIndex=0,V(e.chunkData,4)===A))}function je(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var $e={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 At=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 Qe(t,A){let e=0;for(;t>0;){let s=A.tempoChanges.find(o=>o.ticks0&&(N+=this.tracks[S-1][this.tracks[S-1].length-1].ticks);k.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=N),z=ds[C>>4],(C&240)===F.noteOn){L.add(iA);let IA=k.data[k.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,IA),this.keyRange.max=Math.max(this.keyRange.max,IA)}R=C;break}let AA=new J(z),eA=k.data.slice(k.data.currentIndex,k.data.currentIndex+z);k.data.currentIndex+=z,AA.set(eA,0);let cA=new Ce(N,C,AA);switch(w.push(cA),iA){case-2:switch(C){case F.setTempo:this.tempoChanges.push({ticks:N,tempo:6e7/$A(eA,3)});break;case F.marker:switch(V(AA,AA.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=N;break;case"loopend":u=N}AA.currentIndex=0;break;case F.midiPort:let mA=AA[0];this.midiPorts[S]=mA,this.midiPortChannelOffsets[mA]===void 0&&(this.midiPortChannelOffsets[mA]=l,l+=16);break;case F.copyright:o||(this.copyright+=V(AA,AA.length,void 0,!1)+` -`);break;case F.lyric:this.lyrics.push(AA)}break;case-3:if(AA.slice(0,7).every((IA,mA)=>Yo[mA]===IA)){let IA=AA.slice(7,eA.length-3),mA=V(IA,IA.length)+` -`;this.copyright+=mA,m(`%cDecoded Roland SC message! %c${mA}`,r.recognized,r.value)}break;default:if((C&240)===F.controllerChange)switch(AA[0]){case 2:case 116:d=N;break;case 4:case 117:u===null?u=N:u=0;break;case 0:g&&AA[1]!==0&&AA[1]!==127&&(m("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(w),this.usedChannelsOnTrack.push(L),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),yA("%cCorrecting loops, ports and detecting notes...",r.info);let c=[];for(let S of this.tracks){let w=S.find(k=>(k.messageStatusByte&240)===F.noteOn);w&&c.push(w.ticks)}this.firstNoteOn=Math.min(...c),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&u===null?(d=this.firstNoteOn,u=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(u===null||u===0)&&(u=this.lastVoiceEventTick)),this.loop={start:d,end:u},m(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let p=0;for(let S of this.midiPorts)if(S!==-1){p=S;break}if(this.midiPorts=this.midiPorts.map(S=>S===-1?p:S),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?m("%cNo additional MIDI Ports detected.",r.info):m("%cMIDI Ports detected!",r.recognized),!i)if(this.tracks.length>1){if(this.tracks[0].find(S=>S.messageStatusByte>=F.noteOn&&S.messageStatusBytew.messageStatusByte===F.trackName);S&&(this.rawMidiName=S.messageData,this.midiName=V(S.messageData,S.messageData.length,void 0,!1))}}else{let S=this.tracks[0].find(w=>w.messageStatusByte===F.trackName);S&&(this.rawMidiName=S.messageData,this.midiName=V(S.messageData,S.messageData.length,void 0,!1))}if(this.fileName=e,this.midiName=this.midiName.trim(),this.midiName.length===0){m("%cNo name detected. Using the alt name!",r.info),this.midiName=ls(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let S=0;Sl>u?l:u),s=[];for(let u=0;u{i[p]>=c.length||c[i[p]].ticks0;){let u=B(),l=t.tracks[u];if(i[u]>=l.length){g--;continue}let c=l[i[u]];if(i[u]++,c.messageStatusByte===F.midiPort){h[u]=c.messageData[0];continue}let p=c.messageStatusByte&240;if(p!==F.noteOn&&p!==F.controllerChange&&p!==F.programChange&&p!==F.systemExclusive)continue;let S=(c.messageStatusByte&15)+t.midiPortChannelOffsets[h[u]]||0,w=s[S];switch(p){case F.programChange:w.program=c.messageData[0],n(w);break;case F.controllerChange:if(c.messageData[0]!==y.bankSelect||d==="gs"&&w.drums)continue;let k=c.messageData[1],L=Math.max(0,k-t.bankOffset);if(d==="xg"){let G=k===120||k===126||k===127;G!==w.drums?(w.drums=G,w.bank=w.drums?128:L,n(w)):w.bank=w.drums?128:L;continue}s[S].bank=L;break;case F.noteOn:if(c.messageData[1]===0)continue;n(w),o[w.string].add(`${c.messageData[0]}-${c.messageData[1]}`);break;case F.systemExclusive:if(c.messageData[0]!==65||c.messageData[2]!==66||c.messageData[3]!==18||c.messageData[4]!==64||!(c.messageData[5]&16)||c.messageData[6]!==21){c.messageData[0]===67&&c.messageData[2]===76&&c.messageData[5]===126&&c.messageData[6]===0&&(d="xg");continue}let R=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][c.messageData[5]&15]+t.midiPortChannelOffsets[h[u]],N=!!(c.messageData[7]>0&&c.messageData[5]>>4);w=s[R],w.drums=N,w.bank=N?128:0,n(w);break}}for(let u of Object.keys(o))o[u].size===0&&(m(`%cDetected change but no keys for %c${u}`,r.info,r.value),delete o[u]);return O(),o}function Ls(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(s,e)}),this.duration=this.midiData.duration,this.firstNoteTime=Qe(this.midiData.firstNoteOn,this.midiData),m(`%cTotal song time: ${Dt(Math.ceil(this.duration)).time}`,r.recognized),this.post(FA.songChange,[new ze(this.midiData),this.songIndex,A]),this.duration<=1&&(H(`%cVery short song: (${Dt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),A)this.play(!0);else{let e=this._skipToFirstNoteOn?this.midiData.firstNoteOn-1:0;this.setTimeTicks(e),this.pause()}}function Ts(t,A=!0){this.songs=t.reduce((e,s)=>{if(s.duration)return e.push(s),e;try{e.push(new et(s.binary,s.altName||""))}catch(n){return this.post(FA.midiError,n.message),e}return e},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex],A))}function Hs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Ys(){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 OA=new Int16Array(127);OA[y.mainVolume]=100;OA[y.expressionController]=127;OA[y.pan]=64;OA[y.releaseTime]=64;OA[y.brightness]=64;OA[y.reverbDepth]=0;function Js(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 g=0;gg===y.dataDecrement||g===y.dataIncrement||g===y.dataEntryMsb||g===y.dataDecrement||g===y.lsbForControl6DataEntry||g===y.RPNLsb||g===y.RPNMsb||g===y.NRPNLsb||g===y.NRPNMsb||g===y.bankSelect||g===y.lsbForControl0BankSelect||g===y.resetAllControllers,i=[];for(let g=0;g=A)break}else if(this.playedTime>=t)break;let h=Re(B.messageStatusByte),d=h.channel+(this.midiPortChannelOffsets[this.midiPorts[g]]||0);switch(h.status){case F.noteOn:case F.noteOff:case F.keySignature:break;case F.pitchBend:s[d]=B.messageData[1]<<7|B.messageData[0];break;case F.programChange:let l=n[d];l.program=B.messageData[0],l.actualBank=l.bank;break;case F.controllerChange:let c=B.messageData[0];if(o(c)){let p=B.messageData[1];if(c===y.bankSelect){n[d].bank=p;break}this.sendMIDIMessages?this.sendMIDICC(d,c,p):this.synth.controllerChange(d,c,p)}else i[d]===void 0&&(i[d]=Array.from(OA)),i[d][c]=B.messageData[1];break;default:this._processEvent(B,g);break}this.eventIndex[g]++,g=this._findFirstEventIndex();let u=this.tracks[g][this.eventIndex[g]];if(u===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(u.ticks-B.ticks)}if(this.sendMIDIMessages){for(let g=0;g>7,s[g]&127),i[g]!==void 0&&i[g].forEach((B,h)=>{B!==OA[h]&&!o(h)&&this.sendMIDICC(g,h,B)}),n[g].program>=0&&n[g].actualBank>=0){let B=n[g].actualBank;this.sendMIDICC(g,y.bankSelect,B),this.sendMIDIProgramChange(g,n[g].program)}}else for(let g=0;g>7,s[g]&127),i[g]!==void 0&&i[g].forEach((B,h)=>{B!==OA[h]&&!o(h)&&this.synth.controllerChange(g,h,B)}),n[g].program>=0&&n[g].actualBank>=0){let B=n[g].actualBank;this.synth.controllerChange(g,y.bankSelect,B),this.synth.programChange(g,n[g].program)}return!0}function vs(t=!1){if(this.midiData!==void 0){if(t){this.pausedTime=void 0,this.currentTime=0;return}if(this.currentTime>=this.duration){this.pausedTime=void 0,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 qs(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(FA.timeChange,currentTime-Qe(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Ps(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function Ks(t,A){switch(t){default:break;case wA.loadNewSongList:this.loadNewSongList(A[0],A[1]);break;case wA.pause:this.pause();break;case wA.play:this.play(A);break;case wA.stop:this.stop();break;case wA.setTime:this.currentTime=A;break;case wA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case wA.setPlaybackRate:this.playbackRate=A;break;case wA.setLoop:this.loop=A;break;case wA.changeSong:A?this.nextSong():this.previousSong();break;case wA.getMIDI:this.post(FA.getMIDI,this.midiData);break;case wA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break;case wA.setPreservePlaybackState:this.preservePlaybackState=A}}function Os(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:uA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Vs(t){this.post(FA.midiEvent,t)}function Zs(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|t,A,e])}function Xs(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|t,A])}function Ws(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|t,e,A])}function _s(){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&&Azs?440*Math.pow(2,(t-6900)/1200):Nt[~~t-tt]}var Lt=-1660,Jo=1600,bt=new Float32Array((Jo-Lt)*100+1);for(let t=0;t.5?1:0,s?e*2-1:e;case hA.concave:return s?(e=e*2-1,e<0?-XA[~~(e*-CA)]:XA[~~(e*CA)]):XA[~~(e*CA)];case hA.convex:return s?(e=e*2-1,e<0?-oe[~~(e*-CA)]:oe[~~(e*CA)]):oe[~~(e*CA)]}}var Ut=1,Tt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)s-=o;let g=~~s,B=g+1;for(;B>=e.loopEnd;)B-=o;let h=s-g,d=n[B],u=n[g];A[i]=u+(d-u)*h,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 B=s-i,h=n[g],d=n[i];A[o]=d+(h-d)*B,s+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=s}function $s(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 g=~~s+1;for(;g>=e.loopEnd;)g-=n;A[i]=o[g],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[g],s+=e.playbackStep*t.currentTuningCalculated}}e.cursor=s}function An(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 g=~~s,B=g+1,h=B+1,d=h+1,u=s-g;B>=e.loopEnd&&(B-=o),h>=e.loopEnd&&(h-=o),d>=e.loopEnd&&(d-=o);let l=n[g],c=n[B],p=n[h],S=n[d],w=.5*(p-l),k=l-2.5*c+2*p-.5*S,L=.5*(S-l)+1.5*(c-p);A[i]=((L*u+k)*u+w)*u+c,s+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end||B>=e.end||h>=e.end){t.finished=!0;return}let u=n[i],l=n[g],c=n[B],p=n[h],S=.5*(c-u),w=u-2.5*l+2*c-.5*p,k=.5*(p-u)+1.5*(l-c);A[o]=((k*d+w)*d+S)*d+l,s+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=s}var en=.001,GA=100,Ht=90,vo=15e-6,TA=class t{currentSampleTime=0;sampleRate;currentAttenuationDb=GA;state=0;releaseStartDb=GA;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;constructor(A,e){this.sampleRate=A,this.canEndOnSilentSustain=e/10>=Ht}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=h=>Math.max(0,Math.floor(JA(h)*e.sampleRate));e.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[a.initialAttenuation],1440))/10,e.sustainDbRelative=Math.min(GA,A.modulatedGenerators[a.sustainVolEnv]/10);let n=Math.min(GA,e.sustainDbRelative);e.attackDuration=s(A.modulatedGenerators[a.attackVolEnv]);let o=A.modulatedGenerators[a.decayVolEnv],i=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvDecay],g=n/GA;e.decayDuration=s(o+i)*g,e.releaseDuration=s(A.modulatedGenerators[a.releaseVolEnv]),e.delayEnd=s(A.modulatedGenerators[a.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let B=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvHold];if(e.holdEnd=s(A.modulatedGenerators[a.holdVolEnv]+B)+e.attackEnd,e.decayEnd=e.decayDuration+e.holdEnd,e.state===0&&e.attackEnd===0&&(e.state=2),A.isInRelease){let h=Math.max(0,Math.min(GA,e.sustainDbRelative)),d=h/GA;switch(e.decayDuration=s(o+i)*d,e.state){case 0:e.releaseStartDb=GA;break;case 1:let l=1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration;e.releaseStartDb=20*Math.log10(l)*-1;break;case 2:e.releaseStartDb=0;break;case 3:e.releaseStartDb=(1-(e.decayEnd-e.releaseStartTimeSamples)/e.decayDuration)*h;break;case 4:e.releaseStartDb=h;break}e.releaseStartDb=Math.max(0,Math.min(e.releaseStartDb,GA)),e.releaseStartDb>=Ht&&(A.finished=!0),e.currentReleaseGain=vA(e.releaseStartDb);let u=(GA-e.releaseStartDb)/GA;e.releaseDuration*=u}}static apply(A,e,s,n){let o=A.volumeEnvelope,i=s/10,g=n;if(A.isInRelease){let h=o.currentSampleTime-o.releaseStartTimeSamples;if(h>=o.releaseDuration){for(let u=0;u=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>=Ht&&(A.finished=!0);;)if(o.attenuation+=(o.attenuationTarget-o.attenuation)*g,e[B]*=vA(o.sustainDbRelative+i+o.attenuation),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++B>=e.length)return}}};var le=class t{a0=0;a1=0;a2=0;a3=0;a4=0;x1=0;x2=0;y1=0;y2=0;reasonanceCb=0;reasonanceGain=1;cutoffCents=13501;cutoffHz=20001;static apply(A,e,s,n){if(n&&s>13499&&A.filter.reasonanceCb===0)return;let o=A.filter;(o.cutoffCents!==s||o.reasonanceCb!==A.modulatedGenerators[a.initialFilterQ])&&(o.cutoffCents=s,o.reasonanceCb=A.modulatedGenerators[a.initialFilterQ],t.calculateCoefficients(o));for(let i=0;i=A.releaseStartTime&&(A.isInRelease=!0,TA.startRelease(A),UA.startRelease(A),A.sample.loopingMode===3&&(A.sample.isLooping=!1)),A.modulatedGenerators[a.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let i=A.targetKey,g=A.modulatedGenerators[a.fineTune]+t.customControllers[aA.channelTuning]+t.customControllers[aA.channelTransposeFine]+t.customControllers[aA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],B=A.modulatedGenerators[a.coarseTune]+t.customControllers[aA.channelTuningSemitones],h=this.tunings[t.preset.program]?.[A.realKey];h?.midiNote>=0&&(i=h.midiNote,g+=h.centTuning),g+=(i-A.sample.rootKey)*A.modulatedGenerators[a.scaleTuning];let d=A.modulatedGenerators[a.vibLfoToPitch];if(d!==0){let C=A.startTime+JA(A.modulatedGenerators[a.delayVibLFO]),iA=Ge(A.modulatedGenerators[a.freqVibLFO]),z=st(C,iA,currentTime);g+=z*(d*t.customControllers[aA.modulationMultiplier])}let u=A.modulatedGenerators[a.initialFilterFc],l=u,c=A.modulatedGenerators[a.modLfoToPitch],p=A.modulatedGenerators[a.modLfoToVolume],S=A.modulatedGenerators[a.modLfoToFilterFc],w=0;if(c+S+p!==0){let C=A.startTime+JA(A.modulatedGenerators[a.delayModLFO]),iA=Ge(A.modulatedGenerators[a.freqModLFO]),z=st(C,iA,currentTime);g+=z*(c*t.customControllers[aA.modulationMultiplier]),w=-z*p,l+=z*S}if(t.channelVibrato.depth>0){let C=st(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);C&&(g+=C*t.channelVibrato.depth)}let k=A.modulatedGenerators[a.modEnvToPitch],L=A.modulatedGenerators[a.modEnvToFilterFc],R=UA.getValue(A,currentTime);l+=R*L,g+=R*k;let N=~~(g+B*100);N!==A.currentTuningCents&&(A.currentTuningCents=N,A.currentTuningCalculated=Math.pow(2,N/1200));let G=new Float32Array(e.length);switch(this.interpolationType){case ce.linear:default:js(A,G);break;case ce.nearestNeighbor:$s(A,G);break;case ce.fourthOrder:An(A,G)}le.apply(A,G,l,u>13499),TA.apply(A,G,w,this.volumeEnvelopeSmoothingFactor),this.panVoice(A,G,e,s,n,o)}function qo(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 nn(t){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=qo(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 on(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimean=t);var Po=function(t){var A,e,s,n,o,i,g,B="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=B.indexOf(t.charAt(d++)),o=B.indexOf(t.charAt(d++)),i=B.indexOf(t.charAt(d++)),g=B.indexOf(t.charAt(d++)),A=n<<2|o>>4,e=(15&o)<<4|i>>2,s=(3&i)<<6|g,h+=String.fromCharCode(A),i!==64&&(h+=String.fromCharCode(e)),g!==64&&(h+=String.fromCharCode(s));while(d1&&(C.thisProgram=process.argv[1].replace(/\\/g,"/")),C.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(I){if(!(I instanceof De))throw I}),process.on("unhandledRejection",function(I,E){process.exit(1)}),C.quit=function(I){process.exit(I)},C.inspect=function(){return"[Emscripten Module object]"}):cA?(typeof read<"u"&&(C.read=function(E){return read(E)}),C.readBinary=function(E){var Q;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(zA(typeof(Q=read(E,"binary"))=="object"),Q)},typeof scriptArgs<"u"?C.arguments=scriptArgs:typeof arguments<"u"&&(C.arguments=arguments),typeof quit=="function"&&(C.quit=function(I){quit(I)})):(z||AA)&&(z?document.currentScript&&(IA=document.currentScript.src):IA=self.location.href,IA=IA.indexOf("blob:")!==0?IA.split("/").slice(0,-1).join("/")+"/":"",C.read=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.send(null),Q.responseText},AA&&(C.readBinary=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.responseType="arraybuffer",Q.send(null),new Uint8Array(Q.response)}),C.readAsync=function(E,Q,f){var x=new XMLHttpRequest;x.open("GET",E,!0),x.responseType="arraybuffer",x.onload=function(){if(x.status==200||x.status==0&&x.response){Q(x.response);return}f()},x.onerror=f,x.send(null)},C.setWindowTitle=function(I){document.title=I});var be=C.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),xA=C.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||be);for(t in iA)iA.hasOwnProperty(t)&&(C[t]=iA[t]);function Le(I){var E=c;return c=c+I+15&-16,E}function _t(I){var E=B[R>>2],Q=E+I+15&-16;return B[R>>2]=Q,Q>=EA&&!rs()?(B[R>>2]=E,0):E}function zt(I,E){return E||(E=16),I=Math.ceil(I/E)*E}function Do(I){switch(I){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(I[I.length-1]==="*")return 4;if(I[0]!=="i")return 0;var E=parseInt(I.substr(1));return zA(E%8==0),E/8}}function pe(I){pe.shown||(pe.shown={}),pe.shown[I]||(pe.shown[I]=1,xA(I))}iA=void 0;var ko={"f64-rem":function(I,E){return I%E},debugger:function(){}},Ct=[];function Ar(I,E){for(var Q=0,f=Q;f>>0)+4294967296*+(E>>>0):+(I>>>0)+4294967296*+(0|E)}function Bt(I,E,Q){return Q&&Q.length?C["dynCall_"+I].apply(null,[E].concat(Q)):C["dynCall_"+I].call(null,E)}var Ue=0,jt=0;function zA(I,E){I||ZA("Assertion failed: "+E)}function $t(I){var E=C["_"+I];return zA(E,"Cannot call unknown function "+I+", make sure it is exported"),E}var As={stackSave:function(){mt()},stackRestore:function(){ft()},arrayToC:function(I){var E,Q,f=qe(I.length);return E=I,Q=f,n.set(E,Q),f},stringToC:function(I){var E=0;if(I!=null&&I!==0){var Q=(I.length<<2)+1;E=qe(Q),ss(I,E,Q)}return E}},wo={string:As.stringToC,array:As.arrayToC};function es(I,E,Q,f,x){var P=$t(I),X=[],b=0;if(f)for(var BA=0;BA>0]=E;break;case"i16":i[I>>1]=E;break;case"i32":B[I>>2]=E;break;case"i64":tempI64=[E>>>0,+No(tempDouble=E)>=1?tempDouble>0?(0|Lo(+Cs(tempDouble/4294967296),4294967295))>>>0:~~+bo((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],B[I>>2]=tempI64[0],B[I+4>>2]=tempI64[1];break;case"float":d[I>>2]=E;break;case"double":u[I>>3]=E;break;default:ZA("invalid type for setValue: "+Q)}}function nr(I,E,Q){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return n[I>>0];case"i16":return i[I>>1];case"i32":case"i64":return B[I>>2];case"float":return d[I>>2];case"double":return u[I>>3];default:ZA("invalid type for getValue: "+E)}return null}function or(I,E,Q,f){typeof I=="number"?(P=!0,X=I):(P=!1,X=I.length);var x=typeof E=="string"?E:null;if(b=Q==4?f:[typeof ve=="function"?ve:Le,qe,Le,_t][Q===void 0?2:Q](Math.max(X,x?1:E.length)),P){for(f=b,zA((3&b)==0),BA=b+(-4&X);f>2]=0;for(BA=b+X;f>0]=0;return b}if(x==="i8")return I.subarray||I.slice?o.set(I,b):o.set(new Uint8Array(I),b),b;for(var P,X,b,BA,nA,oA,tA,q=0;q>0],(f!=0||E)&&(X++,!E||X!=E););E||(E=X);var b="";if(P<128){for(;E>0;)x=String.fromCharCode.apply(String,o.subarray(I,I+Math.min(E,1024))),b=b?b+x:x,I+=1024,E-=1024;return b}return Q=I,function(nA,oA){for(var tA=oA;nA[tA];)++tA;if(tA-oA>16&&nA.subarray&&ts)return ts.decode(nA.subarray(oA,tA));for(var q,pA,MA,NA,bA,se,LA="";;){if(!(q=nA[oA++]))return LA;if(!(128&q)){LA+=String.fromCharCode(q);continue}if(pA=63&nA[oA++],(224&q)==192){LA+=String.fromCharCode((31&q)<<6|pA);continue}if(MA=63&nA[oA++],(240&q)==224?q=(15&q)<<12|pA<<6|MA:(NA=63&nA[oA++],(248&q)==240?q=(7&q)<<18|pA<<12|MA<<6|NA:(bA=63&nA[oA++],q=(252&q)==248?(3&q)<<24|pA<<18|MA<<12|NA<<6|bA:(1&q)<<30|pA<<24|MA<<18|NA<<12|bA<<6|(se=63&nA[oA++]))),q<65536)LA+=String.fromCharCode(q);else{var ke=q-65536;LA+=String.fromCharCode(55296|ke>>10,56320|1023&ke)}}}(o,Q)}function ir(I){for(var E="";;){var Q=n[I++>>0];if(!Q)return E;E+=String.fromCharCode(Q)}}function ar(I,E){return function(f,x,P){for(var X=0;X>0]=f.charCodeAt(X);P||(n[x>>0]=0)}(I,E,!1)}var ts=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function He(I,E,Q,f){if(!(f>0))return 0;for(var x=Q,P=Q+f-1,X=0;X=55296&&b<=57343&&(b=65536+((1023&b)<<10)|1023&I.charCodeAt(++X)),b<=127){if(Q>=P)break;E[Q++]=b}else if(b<=2047){if(Q+1>=P)break;E[Q++]=192|b>>6,E[Q++]=128|63&b}else if(b<=65535){if(Q+2>=P)break;E[Q++]=224|b>>12,E[Q++]=128|b>>6&63,E[Q++]=128|63&b}else if(b<=2097151){if(Q+3>=P)break;E[Q++]=240|b>>18,E[Q++]=128|b>>12&63,E[Q++]=128|b>>6&63,E[Q++]=128|63&b}else if(b<=67108863){if(Q+4>=P)break;E[Q++]=248|b>>24,E[Q++]=128|b>>18&63,E[Q++]=128|b>>12&63,E[Q++]=128|b>>6&63,E[Q++]=128|63&b}else{if(Q+5>=P)break;E[Q++]=252|b>>30,E[Q++]=128|b>>24&63,E[Q++]=128|b>>18&63,E[Q++]=128|b>>12&63,E[Q++]=128|b>>6&63,E[Q++]=128|63&b}}return E[Q]=0,Q-x}function ss(I,E,Q){return He(I,o,E,Q)}function Ye(I){for(var E=0,Q=0;Q=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&I.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 ns=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function Ir(I){for(var E=I,Q=E>>1;i[Q];)++Q;if((E=Q<<1)-I>32&&ns)return ns.decode(o.subarray(I,E));for(var f=0,x="";;){var P=i[I+2*f>>1];if(P==0)return x;++f,x+=String.fromCharCode(P)}}function gr(I,E,Q){if(Q===void 0&&(Q=2147483647),Q<2)return 0;for(var f=E,x=(Q-=2)<2*I.length?Q/2:I.length,P=0;P>1]=X,E+=2}return i[E>>1]=0,E-f}function Cr(I){return 2*I.length}function Er(I){for(var E=0,Q="";;){var f=B[I+4*E>>2];if(f==0)return Q;if(++E,f>=65536){var x=f-65536;Q+=String.fromCharCode(55296|x>>10,56320|1023&x)}else Q+=String.fromCharCode(f)}}function Br(I,E,Q){if(Q===void 0&&(Q=2147483647),Q<4)return 0;for(var f=E,x=f+Q-4,P=0;P=55296&&X<=57343&&(X=65536+((1023&X)<<10)|1023&I.charCodeAt(++P)),B[E>>2]=X,(E+=4)+4>x)break}return B[E>>2]=0,E-f}function hr(I){for(var E=0,Q=0;Q=55296&&f<=57343&&++Q,E+=4}return E}function Qr(I){var E=Ye(I)+1,Q=ve(E);return Q&&He(I,n,Q,E),Q}function cr(I){var E=Ye(I)+1,Q=qe(E);return He(I,n,Q,E),Q}function lr(I){return I}function ur(){var I,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(x){f=x}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return C.extraStackTrace&&(E+=` -`+C.extraStackTrace()),(I=E).replace(/__Z[\w\d_]+/g,function(Q){var f,x=f=Q;return Q===x?Q:Q+" ["+x+"]"})}function ht(I,E){return I%E>0&&(I+=E-I%E),I}function os(I){C.buffer=s=I}function Qt(){C.HEAP8=n=new Int8Array(s),C.HEAP16=i=new Int16Array(s),C.HEAP32=B=new Int32Array(s),C.HEAPU8=o=new Uint8Array(s),C.HEAPU16=g=new Uint16Array(s),C.HEAPU32=h=new Uint32Array(s),C.HEAPF32=d=new Float32Array(s),C.HEAPF64=u=new Float64Array(s)}function rs(){var I=C.usingWasm?65536:16777216,E=2147483648-I;if(B[R>>2]>E)return!1;var Q=EA;for(EA=Math.max(EA,16777216);EA>2];)EA=EA<=536870912?ht(2*EA,I):Math.min(ht((3*EA+2147483648)/4,I),E);var f=C.reallocBuffer(EA);return f&&f.byteLength==EA?(os(f),Qt(),!0):(EA=Q,!1)}l=c=S=w=k=L=R=0,p=!1,C.reallocBuffer||(C.reallocBuffer=function(I){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(s,I);else{var E,Q=n;E=new ArrayBuffer(I),new Int8Array(E).set(Q)}}catch{return!1}return!!Uo(E)&&E});try{(N=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{N=function(E){return E.byteLength}}var ct=C.TOTAL_STACK||5242880,EA=C.TOTAL_MEMORY||16777216;function Ro(){return EA}function ye(I){for(;I.length>0;){var E=I.shift();if(typeof E=="function"){E();continue}var Q=E.func;typeof Q=="number"?E.arg===void 0?C.dynCall_v(Q):C.dynCall_vi(Q,E.arg):Q(E.arg===void 0?null:E.arg)}}EA=0?I:E<=32?2*Math.abs(1<=f&&(E<=32||I>f)&&(I=-2*f+I),I}var No=Math.abs,bo=Math.ceil,Cs=Math.floor,Lo=Math.min,te=0,dt=null,Se=null;function Dr(I){return I}C.preloadedImages={},C.preloadedAudios={};var Es="data:application/octet-stream;base64,";function Je(I){return String.prototype.startsWith?I.startsWith(Es):I.indexOf(Es)===0}(function(){var E="main.wast",Q="main.wasm",f="main.temp.asm.js";Je(E)||(E=mA(E)),Je(Q)||(Q=mA(Q)),Je(f)||(f=mA(f));var x={global:null,env:null,asm2wasm:ko,parent:C},P=null;function X(tA){return tA}function b(){try{if(C.wasmBinary)return new Uint8Array(C.wasmBinary);if(C.readBinary)return C.readBinary(Q);throw"both async and sync fetching of the wasm failed"}catch(tA){ZA(tA)}}C.asmPreload=C.asm;var BA=C.reallocBuffer,nA=function(tA){tA=ht(tA,C.usingWasm?65536:16777216);var q=C.buffer.byteLength;if(C.usingWasm)try{var pA=C.wasmMemory.grow((tA-q)/65536);return pA!==-1?C.buffer=C.wasmMemory.buffer:null}catch{return null}};C.reallocBuffer=function(tA){return oA==="asmjs"?BA(tA):nA(tA)};var oA="";C.asm=function(tA,q,pA){var MA;if(!(q=MA=q).table){var NA,bA=C.wasmTableSize;bA===void 0&&(bA=1024);var se=C.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?se!==void 0?q.table=new WebAssembly.Table({initial:bA,maximum:se,element:"anyfunc"}):q.table=new WebAssembly.Table({initial:bA,element:"anyfunc"}):q.table=Array(bA),C.wasmTable=q.table}return q.memoryBase||(q.memoryBase=C.STATIC_BASE),q.tableBase||(q.tableBase=0),NA=function(ke,Ie,yt){if(typeof WebAssembly!="object")return xA("no native wasm support detected"),!1;if(!(C.wasmMemory instanceof WebAssembly.Memory))return xA("no native wasm Memory in use"),!1;function Pe(qA,PA){if((P=qA.exports).memory){var we,St,Qs;we=P.memory,St=C.buffer,we.byteLength0?Q:Ye(I)+1,x=Array(f),P=He(I,x,0,x.length);return E&&(x.length=P),x}function Rr(I){for(var E=[],Q=0;Q255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}c+=16,R=Le(4),k=(S=w=zt(c))+ct,L=zt(k),B[R>>2]=L,p=!0,C.wasmTableSize=4,C.wasmMaxTableSize=4,C.asmGlobalArg={},C.asmLibraryArg={abort:ZA,assert:zA,enlargeMemory:rs,getTotalMemory:Ro,abortOnCannotGrowMemory:function(){ZA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+EA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(E,Q,f){var x=mt();try{return C.dynCall_iii(E,Q,f)}catch(P){if(ft(x),typeof P!="number"&&P!=="longjmp")throw P;C.setThrew(1,0)}},___assert_fail:function(E,Q,f,x){ZA("Assertion failed: "+Te(E)+", at: "+[Q?Te(Q):"unknown filename",f,x?Te(x):"unknown function"])},___setErrNo:function(E){return C.___errno_location&&(B[C.___errno_location()>>2]=E),E},_abort:function(){C.abort()},_emscripten_memcpy_big:function(E,Q,f){return o.set(o.subarray(Q,Q+f),E),E},_llvm_floor_f64:Cs,DYNAMICTOP_PTR:R,tempDoublePtr:kA,ABORT:Ue,STACKTOP:w,STACK_MAX:k};var Bs=C.asm(C.asmGlobalArg,C.asmLibraryArg,s);C.asm=Bs,C.___errno_location=function(){return C.asm.___errno_location.apply(null,arguments)};var Uo=C._emscripten_replace_memory=function(){return C.asm._emscripten_replace_memory.apply(null,arguments)};C._free=function(){return C.asm._free.apply(null,arguments)};var ve=C._malloc=function(){return C.asm._malloc.apply(null,arguments)};C._memcpy=function(){return C.asm._memcpy.apply(null,arguments)},C._memset=function(){return C.asm._memset.apply(null,arguments)},C._sbrk=function(){return C.asm._sbrk.apply(null,arguments)},C._stb_vorbis_js_channels=function(){return C.asm._stb_vorbis_js_channels.apply(null,arguments)},C._stb_vorbis_js_close=function(){return C.asm._stb_vorbis_js_close.apply(null,arguments)},C._stb_vorbis_js_decode=function(){return C.asm._stb_vorbis_js_decode.apply(null,arguments)},C._stb_vorbis_js_open=function(){return C.asm._stb_vorbis_js_open.apply(null,arguments)},C._stb_vorbis_js_sample_rate=function(){return C.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},C.establishStackSpace=function(){return C.asm.establishStackSpace.apply(null,arguments)},C.getTempRet0=function(){return C.asm.getTempRet0.apply(null,arguments)},C.runPostSets=function(){return C.asm.runPostSets.apply(null,arguments)},C.setTempRet0=function(){return C.asm.setTempRet0.apply(null,arguments)},C.setThrew=function(){return C.asm.setThrew.apply(null,arguments)};var qe=C.stackAlloc=function(){return C.asm.stackAlloc.apply(null,arguments)},ft=C.stackRestore=function(){return C.asm.stackRestore.apply(null,arguments)},mt=C.stackSave=function(){return C.asm.stackSave.apply(null,arguments)};function De(I){this.name="ExitStatus",this.message="Program terminated with exit("+I+")",this.status=I}function pt(I){I=I||C.arguments,!(te>0)&&(function(){if(C.preRun)for(typeof C.preRun=="function"&&(C.preRun=[C.preRun]);C.preRun.length;)xo(C.preRun.shift());ye(is)}(),!(te>0)&&(C.calledRun||(C.setStatus?(C.setStatus("Running..."),setTimeout(function(){setTimeout(function(){C.setStatus("")},1),E()},1)):E())));function E(){!C.calledRun&&(C.calledRun=!0,Ue||(ut||(ut=!0,ye(lt)),ye(as),C.onRuntimeInitialized&&C.onRuntimeInitialized(),function(){if(C.postRun)for(typeof C.postRun=="function"&&(C.postRun=[C.postRun]);C.postRun.length;)Mo(C.postRun.shift());ye(gs)}()))}}function Gr(I,E){(!E||!C.noExitRuntime||I!==0)&&(C.noExitRuntime||(Ue=!0,jt=I,w=G,ye(Is),Go=!0,C.onExit&&C.onExit(I)),C.quit(I,new De(I)))}function ZA(I){throw C.onAbort&&C.onAbort(I),I!==void 0?(be(I),xA(I),I=JSON.stringify(I)):I="",Ue=!0,jt=1,"abort("+I+"). Build with -s ASSERTIONS=1 for more info."}if(C.dynCall_iii=function(){return C.asm.dynCall_iii.apply(null,arguments)},C.asm=Bs,C.ccall=es,C.cwrap=function(E,Q,f,x){var P=(f=f||[]).every(function(X){return X==="number"});return Q!=="string"&&P&&!x?$t(E):function(){return es(E,Q,f,arguments,x)}},De.prototype=Error(),De.prototype.constructor=De,Se=function I(){C.calledRun||pt(),C.calledRun||(Se=I)},C.run=pt,C.abort=ZA,C.preInit)for(typeof C.preInit=="function"&&(C.preInit=[C.preInit]);C.preInit.length>0;)C.preInit.pop()();C.noExitRuntime=!0,pt(),C.onRuntimeInitialized=()=>{rn=!0,an()},VA.decode=function(I){return function(Q){if(!rn)throw Error("Not initialized");var f={};function x(Ie){return new Int32Array(C.HEAPU8.buffer,Ie,1)[0]}function P(Ie,yt){var Pe=new ArrayBuffer(yt*Float32Array.BYTES_PER_ELEMENT),ge=new Float32Array(Pe);return ge.set(new Float32Array(C.HEAPU8.buffer,Ie,yt)),ge}f.open=C.cwrap("stb_vorbis_js_open","number",[]),f.close=C.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=C.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=C.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=C.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var X,b,BA,nA,oA=f.open(),tA=(X=Q,b=Q.byteLength,BA=C._malloc(b),(nA=new Uint8Array(C.HEAPU8.buffer,BA,b)).set(new Uint8Array(X,0,b)),nA),q=C._malloc(4),pA=C._malloc(4),MA=f.decode(oA,tA.byteOffset,tA.byteLength,q,pA);if(C._free(tA.byteOffset),MA<0)throw f.close(oA),C._free(q),Error("stbvorbis decode failed: "+MA);for(var NA=f.channels(oA),bA=Array(NA),se=new Int32Array(C.HEAPU32.buffer,x(q),NA),LA=0;LA=0&&(s=this.workletProcessorChannels[e]),t.messageType){case j.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case j.noteOff:this.noteOff(e,A);break;case j.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case j.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case j.customcCcChange:s.customControllers[A[0]]=A[1];break;case j.killNote:this.killNote(e,A);break;case j.programChange:this.programChange(e,A[0],A[1]);break;case j.channelPressure:this.channelPressure(e,A);break;case j.polyPressure:this.polyPressure(e,A[0],A[1]);break;case j.ccReset:e===HA?this.resetAllControllers():this.resetControllers(e);break;case j.systemExclusive:this.systemExclusive(A);break;case j.setChannelVibrato:if(e===HA)for(let i=0;i{let e=(A.midiControllers[gA+K.pitchWheelRange]>>7)+(A.midiControllers[gA+K.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[gA+K.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:uA.channelProperties,messageData:t})}function Ko(t,A,e){let s=t,n=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function En(t,A=0){let e=t[0];if(!(this.deviceID!==HA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:H(`%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 g=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(g),m(`%cMaster Pan. Pan: %c${g}`,r.info,r.value);break;case 3:let B=(t[5]<<7|t[6])-8192;n=Math.floor(B/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:H(`%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++],g=t[o++];for(let h=0;h>1&1)===1&&this.setOctaveTuning(15+A,B);for(let h=0;h<7;h++)(t[5]>>h&1)===1&&this.setOctaveTuning(7+h+A,B);for(let h=0;h<7;h++)(t[6]>>h&1)===1&&this.setOctaveTuning(h+A,B);m(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${B.join(" ")}`,r.info,r.value);break;default:H(`%cUnrecognized MIDI Tuning standard message: %c${lA(t)}`,r.warn,r.unrecognized);break}break;default:H(`%cUnrecognized MIDI Realtime/non realtime message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 65:let s=function(){H(`%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 g=n-64;this.transposeChannel(o,g),m(`%cChannel %c${o}%c pitch shift. Semitones %c${g}%c, with %c${lA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let B=n;B===0&&(B=Math.floor(Math.random()*128)),this.controllerChange(o,y.pan,B);break;case 33:this.controllerChange(o,y.chorusDepth,n);break;case 34:this.controllerChange(o,y.reverbDepth,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 h=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,y.bankSelect,o);break;case 2:this.controllerChange(n,y.lsbForControl0BankSelect,o);break;case 3:this.programChange(n,o);break;case 8:let i=this.workletProcessorChannels[n];if(i.drumChannel)return;let g=o-64;i.channelTransposeKeyShift=g;break;case 11:this.controllerChange(n,y.mainVolume,o);break;case 14:let B=o;B===0&&(B=Math.floor(Math.random()*127)),this.controllerChange(n,y.pan,B);break;case 19:this.controllerChange(n,y.reverbDepth,o);break;case 18:this.controllerChange(n,y.chorusDepth,o);break;default:H(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&H(`%cUnrecognized Yamaha XG SysEx: %c${lA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&H(`%cUnrecognized Yamaha SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break}}var Oo=1e3/200;function Bn(t,A,e){if(A.transformAmount===0)return A.currentValue=0,0;let s;if(A.sourceUsesCC)s=t[A.sourceIndex];else{let h=A.sourceIndex+gA;switch(A.sourceIndex){case K.noController:s=16383;break;case K.noteOnKeyNum:s=e.midiNote<<7;break;case K.noteOnVelocity:s=e.velocity<<7;break;case K.polyPressure:s=e.pressure<<7;break;default:s=t[h];break}}let n=ie[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let h=A.secSrcIndex+gA;switch(A.secSrcIndex){case K.noController:o=16383;break;case K.noteOnKeyNum:o=e.midiNote<<7;break;case K.noteOnVelocity:o=e.velocity<<7;break;case K.polyPressure:o=e.pressure<<7;break;default:o=t[h]}}let i=ie[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=A.transformAmount;A.isEffectModulator&&g<=1e3&&(g*=Oo,g=Math.min(g,1e3));let B=n*i*g;return A.transformType===2&&(B=Math.abs(B)),A.currentValue=B,B}function WA(t,A,e=-1,s=0){let n=t.modulators,o=t.generators,i=t.modulatedGenerators;if(e===-1){i.set(o),n.forEach(h=>{let d=T[h.modulatorDestination],u=i[h.modulatorDestination]+Bn(A,h,t);i[h.modulatorDestination]=Math.max(d.min,Math.min(u,d.max))}),TA.recalculate(t),UA.recalculate(t);return}let g=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),B=new Set;n.forEach(h=>{if(h.sourceUsesCC===e&&h.sourceIndex===s||h.secSrcUsesCC===e&&h.secSrcIndex===s){let d=h.modulatorDestination;B.has(d)||(i[d]=o[d],Bn(A,h,t),n.forEach(u=>{if(u.modulatorDestination===d){let l=T[h.modulatorDestination],c=i[h.modulatorDestination]+u.currentValue;i[h.modulatorDestination]=Math.max(l.min,Math.min(c,l.max))}}),B.add(d))}}),[...B].some(h=>g.has(h))&&TA.recalculate(t),UA.recalculate(t)}var ie=[];for(let t=0;t<4;t++){ie[t]=[[new Float32Array(CA),new Float32Array(CA)],[new Float32Array(CA),new Float32Array(CA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||i.isMuted)return;let g=A+i.channelTransposeKeyShift,B=g;if(A>127||A<0)return;let h=i.preset.program;this.tunings[h]?.[A]?.midiNote>=0&&(B=this.tunings[h]?.[A].midiNote),i.velocityOverride>0&&(e=i.velocityOverride);let d=this.keyModifierManager.getVelocity(t,A);d>-1&&(e=d);let u=this.getWorkletVoices(t,B,e,i,o,g,s),l=i.voices;u.forEach(c=>{let p=c.generators[a.exclusiveClass];p!==0&&l.forEach(G=>{G.generators[a.exclusiveClass]===p&&(this.releaseVoice(G),G.modulatedGenerators[a.releaseVolEnv]=-7e3,G.modulatedGenerators[a.releaseModEnv]=-7e3,TA.recalculate(G),UA.recalculate(G))}),WA(c,i.midiControllers);let S=c.modulatedGenerators[a.startAddrsOffset]+c.modulatedGenerators[a.startAddrsCoarseOffset]*32768,w=c.modulatedGenerators[a.endAddrOffset]+c.modulatedGenerators[a.endAddrsCoarseOffset]*32768,k=c.modulatedGenerators[a.startloopAddrsOffset]+c.modulatedGenerators[a.startloopAddrsCoarseOffset]*32768,L=c.modulatedGenerators[a.endloopAddrsOffset]+c.modulatedGenerators[a.endloopAddrsCoarseOffset]*32768,R=c.sample,N=G=>Math.max(0,Math.min(R.sampleData.length-1,G));if(R.cursor=N(R.cursor+S),R.end=N(R.end+w),R.loopStart=N(R.loopStart+k),R.loopEnd=N(R.loopEnd+L),R.loopEndthis.voiceCap&&this.voiceKilling(u.length),l.push(...u),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Qn(t,A){if(A>127||A<0){H("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift;if(this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(n=>{n.realKey!==e||n.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(n):this.releaseVoice(n))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function cn(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.realKey===A&&(e.modulatedGenerators[a.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function ln(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 un(t=!1){m("%cStop all received!",r.info);for(let A=0;AWA(n,this.workletProcessorChannels[t].midiControllers,0,K.pitchWheel)),this.sendChannelProperties()}function kn(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[gA+K.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(s=>WA(s,e.midiControllers,0,K.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function wn(t,A,e){this.workletProcessorChannels[t].voices.forEach(s=>{s.midiNote===A&&(s.pressure=e,WA(s,this.workletProcessorChannels[t].midiControllers,0,K.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function Fn(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function Rn(t,A,e,s=!1){let n=this.workletProcessorChannels[t];if(n===void 0){H(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>127){if(!s)return;switch(A){default:return;case xt.velocityOverride:n.velocityOverride=e}}if(A>=y.lsbForControl1ModulationWheel&&A<=y.lsbForControl13EffectControl2&&A!==y.lsbForControl6DataEntry){let o=A-32;if(n.lockedControllers[o])return;n.midiControllers[o]=n.midiControllers[o]&16256|e&127,n.voices.forEach(i=>WA(i,n.midiControllers,1,o))}switch(A){case y.allNotesOff:this.stopAll(t);break;case y.allSoundOff:this.stopAll(t,!0);break;case y.bankSelect:let o=e;if(!s){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==SA&&this.setDrums(t,!1);break;case"gm2":o===120&&this.setDrums(t,!0)}n.drumChannel&&(o=128),o===128&&!n.drumChannel&&(o=KA(n))}jA(n,o);break;case y.lsbForControl0BankSelect:this.system==="xg"?n.drumChannel||e!==127&&jA(n,e):this.system==="gm2"&&jA(n,e);break;case y.RPNLsb:n.RPValue=n.RPValue<<7|e,n.dataEntryState=fA.RPFine;break;case y.RPNMsb:n.RPValue=e,n.dataEntryState=fA.RPCoarse;break;case y.NRPNMsb:n.NRPCoarse=e,n.dataEntryState=fA.NRPCoarse;break;case y.NRPNLsb:n.NRPFine=e,n.dataEntryState=fA.NRPFine;break;case y.dataEntryMsb:this.dataEntryCoarse(t,e);break;case y.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case y.resetAllControllers:this.resetControllers(t);break;case y.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=>WA(i,n.midiControllers,1,A));break}this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e})}function Gn(t){this.midiVolume=t,this.setMasterPan(this.pan)}function xn(t){this.masterGain=t*Jt,this.setMasterPan(this.pan)}function Mn(t){this.pan=t,t=t/2+.5,this.panLeft=1-t,this.panRight=t}function Nn(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function bn(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 Ln(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 Un(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 fA.Idle:break;case fA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;H(`%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;H(`%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,y.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,y.reverbDepth,o),m(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:H(`%cUnrecognized RPN for %c${t}%c: %c(0x${e.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:e.midiControllers[gA+K.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 Tn(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[gA+K.pitchWheelRange]|=A;let s=(e.midiControllers[gA+K.pitchWheelRange]>>7)+A/127;m(`%cChannel ${t} bend range. Semitones: %c${s}`,r.info,r.value);break;case 1:let o=e.customControllers[aA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let g=e.customControllers[aA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,g);break;case 16383:this.resetParameters(t);break}}}function Hn(t=!0){t&&m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A>7});if(this.workletProcessorChannels[A].lockedControllers[gA+K.pitchWheel]===!1){let s=this.workletProcessorChannels[A].midiControllers[gA+K.pitchWheel],n=s>>7,o=s&127;this.callEvent("pitchwheel",{channel:A,MSB:n,LSB:o})}}this.tunings=[],this.tunings=[];for(let A=0;127>A;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=_e}function Yn(t){let A=this.workletProcessorChannels[t],s=A.lockedControllers.reduce((o,i,g)=>(i&&o.push(g),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(Ft),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let n=A.customControllers[aA.channelTransposeFine];A.customControllers.set(Gt),A.customControllers[aA.channelTransposeFine]=n,this.resetParameters(t)}function Jn(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=fA.Idle}function vn(){let t=4;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>(o.generators=o.generators.filter(i=>i.generatorType!==a.sampleID&&i.generatorType!==a.keyRange&&i.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+n),0);let A=new J(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=e;for(let o of n.generators)v(A,o.generatorType),v(A,o.generatorValue),e++}return QA(A,0),sA(new $("igen",A.length,A))}function qn(t,A,e,s,n){let o=this.samples.map((h,d)=>{e&&h.compressSample(s,n);let u=h.getRawData();return m(`%cEncoded sample %c${d}. ${h.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),u}),i=this.samples.reduce((h,d,u)=>h+o[u].length+46,0),g=new J(i);this.samples.forEach((h,d)=>{let u=o[d],l,c,p=u.length;h.isCompressed?(l=g.currentIndex,c=l+u.length):(l=g.currentIndex/2,c=l+u.length/2,p+=46),t.push(l),g.set(u,g.currentIndex),g.currentIndex+=p,A.push(c)});let B=sA(new $("smpl",g.length,g),new J([115,100,116,97]));return sA(new $("LIST",B.length,B))}function Pn(t,A){let s=new J(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{RA(s,n.sampleName,20);let i=t[o];QA(s,i);let g=A[o];QA(s,g);let B=n.sampleLoopStartIndex+i,h=n.sampleLoopEndIndex+i;n.isCompressed&&(B-=i,h-=i),QA(s,B),QA(s,h),QA(s,n.sampleRate),s[s.currentIndex++]=n.samplePitch,s[s.currentIndex++]=n.samplePitchCorrection,v(s,n.sampleLink),v(s,n.sampleType)}),RA(s,"EOS",46),sA(new $("shdr",s.length,s))}function Kn(){let t=10;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new J(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)v(A,o.sourceEnum),v(A,o.modulatorDestination),v(A,o.transformAmount),v(A,o.secondarySourceEnum),v(A,o.transformType),e++}return he(A,0,10),sA(new $("imod",A.length,A))}function On(){let t=this.instruments.reduce((o,i)=>i.instrumentZones.length*4+o,4),A=new J(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,v(A,s),v(A,n),s+=i.generators.length,n+=i.modulators.length,e++}return v(A,s),v(A,n),sA(new $("ibag",A.length,A))}function Vn(){let t=this.instruments.length*22+22,A=new J(t),e=0,s=0;for(let n of this.instruments)RA(A,n.instrumentName,20),v(A,e),e+=n.instrumentZones.length,n.instrumentID=s,s++;return RA(A,"EOI",20),v(A,e),sA(new $("inst",A.length,A))}function Zn(){let t=4;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>(o.generators=o.generators.filter(i=>i.generatorType!==a.instrument&&i.generatorType!==a.keyRange&&i.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+n),0);let A=new J(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=e;for(let o of n.generators)v(A,o.generatorType),v(A,o.generatorValue);e+=n.generators.length}return v(A,0),v(A,0),sA(new $("pgen",A.length,A))}function Xn(){let t=10;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new J(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)v(A,o.sourceEnum),v(A,o.modulatorDestination),v(A,o.transformAmount),v(A,o.secondarySourceEnum),v(A,o.transformType),e++}return he(A,0,10),sA(new $("pmod",A.length,A))}function Wn(){let t=this.presets.reduce((o,i)=>i.presetZones.length*4+o,4),A=new J(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,v(A,s),v(A,n),s+=i.generators.length,n+=i.modulators.length,e++}return v(A,s),v(A,n),sA(new $("pbag",A.length,A))}function _n(){let t=this.presets.length*38+38,A=new J(t),e=0;for(let s of this.presets)RA(A,s.presetName,20),v(A,s.program),v(A,s.bank),v(A,e),QA(A,s.library),QA(A,s.genre),QA(A,s.morphology),e+=s.presetZones.length;return RA(A,"EOP",20),v(A,0),v(A,0),v(A,e),QA(A,0),QA(A,0),QA(A,0),sA(new $("phdr",A.length,A))}var Vo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function zn(t=Vo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");yA("%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[N,G]of Object.entries(this.soundFontInfo))if(N==="ifil"||N==="iver"){let C=parseInt(G.split(".")[0]),iA=parseInt(G.split(".")[1]),z=new J(4);v(z,C),v(z,iA),A.push(sA(new $(N,4,z)))}else if(N==="DMOD")A.push(sA(new $(N,G.length,G)));else{let C=new J(G.length);RA(C,G),A.push(sA(new $(N,G.length,C)))}let e=Fe([new J([73,78,70,79]),...A]),s=sA(new $("LIST",e.length,e));m("%cWriting SDTA...",r.info);let n=[],o=[],i=qn.call(this,n,o,t?.compress,t?.compressionQuality??.5,t.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let g=Pn.call(this,n,o);m("%cWriting IGEN...",r.info);let B=vn.call(this);m("%cWriting IMOD...",r.info);let h=Kn.call(this);m("%cWriting IBAG...",r.info);let d=On.call(this);m("%cWriting INST...",r.info);let u=Vn.call(this),l=Zn.call(this);m("%cWriting PMOD...",r.info);let c=Xn.call(this);m("%cWriting PBAG...",r.info);let p=Wn.call(this);m("%cWriting PHDR...",r.info);let S=_n.call(this),w=Fe([new J([112,100,116,97]),S,p,c,l,u,d,h,B,g]),k=sA(new $("LIST",w.length,w));m("%cWriting the output file...",r.info);let L=Fe([new J([115,102,98,107]),s,i,k]),R=sA(new $("RIFF",L.length,L));return m(`%cSaved succesfully! Final file size: %c${R.length}`,r.info,r.recognized),O(),R}var ae=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Oe.map(e=>_.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}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})}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPresetNoFallback(A,e,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)}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&&H(`%cPreset ${A}.${e} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,r.warn,r.recognized)),s||(H(`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||(H("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}parsingError(A){throw new Error(`SF parsing error: ${A} The file may be corrupted.`)}};ae.prototype.write=zn;function jn(t){yA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let 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(u,l,c){return c>=u&&c<=l}function o(u,l){u.push(...l.filter(c=>!u.find(p=>p.generatorType===c.generatorType)))}function i(u,l){u.push(...l.filter(c=>!u.find(p=>_.isIdentical(c,p))))}let g=[],B=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(u=>n(u.keyRange.min,u.keyRange.max,A)&&n(u.velRange.min,u.velRange.max,e)&&!u.isGlobal).forEach(u=>{if(u.instrument.instrumentZones.length<1)return;let l=u.generators,c=u.modulators,p=u.instrument.instrumentZones[0].isGlobal?[...u.instrument.instrumentZones[0].generators]:[],S=u.instrument.instrumentZones[0].isGlobal?[...u.instrument.instrumentZones[0].modulators]:[];u.instrument.instrumentZones.filter(k=>n(k.keyRange.min,k.keyRange.max,A)&&n(k.velRange.min,k.velRange.max,e)&&!k.isGlobal).forEach(k=>{let L=[...k.generators],R=[...k.modulators];o(l,B),o(L,p),i(c,h),i(R,S),i(R,this.defaultModulators);let N=[...R];for(let G=0;G_.isIdentical(C,z));iA!==-1?N[iA]=N[iA].sumTransform(C):N.push(C)}g.push({instrumentGenerators:L,presetGenerators:l,modulators:N,sample:k.sample,sampleID:k.generators.find(G=>G.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=g,g}};var xe=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var ee=class extends xe{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},de=class extends xe{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var fe=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}get useCount(){return this._useCount}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var nt=class extends ue{constructor(A,e){super(Oe),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new fe,this.DLSInstrument.addUseCount();let n=new de;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function $n(t){this.verifyHeader(t,"LIST"),this.verifyText(V(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(Z(t.chunkData));let e=A.find(c=>c.header==="insh");if(!e)throw O(),new Error("No instrument header!");let s=D(e.chunkData,4),n=D(e.chunkData,4),o=D(e.chunkData,4),i=new nt(n,o),g="unnamedPreset",B=DA(A,"INFO");if(B){let c=Z(B.chunkData);for(;c.header!=="INAM";)c=Z(B.chunkData);g=V(c.chunkData,c.chunkData.length).trim()}i.presetName=g,i.DLSInstrument.instrumentName=g,ne(`%cParsing %c"${g}"%c...`,r.info,r.recognized,r.info);let h=DA(A,"lrgn");if(!h)throw O(),new Error("No region list!");let d=new ee;d.isGlobal=!0;let u=DA(A,"lart"),l=DA(A,"lar2");this.readLart(u,l,d),i.DLSInstrument.instrumentZones.push(d);for(let c=0;c>10&15;L===hA.linear&&k!==hA.linear&&(L=k);let R=s>>14&1,N=s>>15&1;i===a.initialAttenuation&&n>0&&(N=!N),l=YA(L,R,N,g.isCC,g.enum)}let c=s>>4&15,p=s>>8&1,S=s>>9&1,w=YA(c,p,S,u.isCC,u.enum);if(B){let k=w;w=l,l=k}return new _({srcEnum:l,secSrcEnum:w,dest:i,transform:0,amt:d})}function vt(t,A){let e=t.chunkData,s=[],n=[];D(e,4);let o=D(e,4);for(let i=0;i>16;if(g===0&&B===0&&d===0){let c;switch(h){case M.pan:c=new U(a.pan,l);break;case M.gain:c=new U(a.initialAttenuation,-l*10/.4);break;case M.filterCutoff:c=new U(a.initialFilterFc,l);break;case M.filterQ:c=new U(a.initialFilterQ,l);break;case M.modLfoFreq:c=new U(a.freqModLFO,l);break;case M.modLfoDelay:c=new U(a.delayModLFO,l);break;case M.vibLfoFreq:c=new U(a.freqVibLFO,l);break;case M.vibLfoDelay:c=new U(a.delayVibLFO,l);break;case M.volEnvDelay:c=new U(a.delayVolEnv,l);break;case M.volEnvAttack:c=new U(a.attackVolEnv,l);break;case M.volEnvHold:c=new U(a.holdVolEnv,l);break;case M.volEnvDecay:c=new U(a.decayVolEnv,l);break;case M.volEnvRelease:c=new U(a.releaseVolEnv,l);break;case M.volEnvSustain:let p=(1e3-l)/10;c=new U(a.sustainVolEnv,p*10);break;case M.modEnvDelay:c=new U(a.delayModEnv,l);break;case M.modEnvAttack:c=new U(a.attackModEnv,l);break;case M.modEnvHold:c=new U(a.holdModEnv,l);break;case M.modEnvDecay:c=new U(a.decayModEnv,l);break;case M.modEnvRelease:c=new U(a.releaseModEnv,l);break;case M.modEnvSustain:let S=1e3-l;c=new U(a.sustainModEnv,S);break;case M.reverbSend:c=new U(a.reverbEffectsSend,l);break;case M.chorusSend:c=new U(a.chorusEffectsSend,l);break;case M.pitch:let w=Math.floor(l/100),k=Math.floor(l-w*100);c=new U(a.fineTune,k),s.push(new U(a.coarseTune,w));break}c&&s.push(c)}else{let c=!0;if(B===W.none)if(g===W.modLfo&&h===M.pitch)s.push(new U(a.modLfoToPitch,l));else if(g===W.modLfo&&h===M.gain)s.push(new U(a.modLfoToVolume,l));else if(g===W.modLfo&&h===M.filterCutoff)s.push(new U(a.modLfoToFilterFc,l));else if(g===W.vibratoLfo&&h===M.pitch)s.push(new U(a.vibLfoToPitch,l));else if(g===W.modEnv&&h===M.pitch)s.push(new U(a.modEnvToPitch,l));else if(g===W.modEnv&&h===M.filterCutoff)s.push(new U(a.modEnvToFilterFc,l));else if(g===W.keyNum&&h===M.volEnvHold){s.push(new U(a.keyNumToVolEnvHold,l/-128));let p=Math.round(60/128*l);s.forEach(S=>{S.generatorType===a.holdVolEnv&&(S.generatorValue+=p)})}else if(g===W.keyNum&&h===M.volEnvDecay){s.push(new U(a.keyNumToVolEnvDecay,l/-128));let p=Math.round(60/128*l);s.forEach(S=>{S.generatorType===a.decayVolEnv&&(S.generatorValue+=p)})}else if(g===W.keyNum&&h===M.modEnvHold){s.push(new U(a.keyNumToModEnvHold,l/-128));let p=Math.round(60/128*l);s.forEach(S=>{S.generatorType===a.holdModEnv&&(S.generatorValue+=p)})}else if(g===W.keyNum&&h===M.modEnvDecay){s.push(new U(a.keyNumToModEnvDecay,l/-128));let p=Math.round(60/128*l);s.forEach(S=>{S.generatorType===a.decayModEnv&&(S.generatorValue+=p)})}else c=!1;else c=!1;if(c===!1){let p=eo(g,B,h,d,l);p?(n.push(p),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):H("Failed converting to SF2 Modulator!")}}}return n.find(i=>i.modulatorDestination===a.reverbEffectsSend)===void 0&&n.push(new _({srcEnum:219,dest:a.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(i=>i.modulatorDestination===a.chorusEffectsSend)===void 0&&n.push(new _({srcEnum:221,dest:a.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&n.push(new _({srcEnum:129,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new _({srcEnum:13,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:n,generators:s}}function to(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(Z(t.chunkData));let e=A.find(AA=>AA.header==="rgnh"),s=D(e.chunkData,2),n=D(e.chunkData,2),o=D(e.chunkData,2),i=D(e.chunkData,2),g=new ot({min:s,max:n},{min:o,max:i});D(e.chunkData,2);let B=D(e.chunkData,2);B!==0&&g.generators.push(new U(a.exclusiveClass,B));let h=DA(A,"lart"),d=DA(A,"lar2");this.readLart(h,d,g),g.isGlobal=!1;let u=A.find(AA=>AA.header==="wsmp");D(u.chunkData,4);let l=D(u.chunkData,2),c=Ae(u.chunkData[u.chunkData.currentIndex++],u.chunkData[u.chunkData.currentIndex++]),p=Math.trunc(c/100);l+=p,c-=p*100;let w=(D(u.chunkData,4)|0)/-655360;D(u.chunkData,4);let k=D(u.chunkData,4),L,R={start:0,end:0};if(k===0)L=0;else{D(u.chunkData,4),D(u.chunkData,4)===0?L=1:L=3,R.start=D(u.chunkData,4);let eA=D(u.chunkData,4);R.end=R.start+eA}let N=A.find(AA=>AA.header==="wlnk");if(N===void 0)return;D(N.chunkData,2),D(N.chunkData,2),D(N.chunkData,4);let G=D(N.chunkData,4),C=this.samples[G];if(C===void 0)throw new Error("Invalid sample ID!");let z=(w||C.sampleDbAttenuation)*10/.4;return g.setWavesample(z,L,R,l,C,G,c),g}var me=class{constructor(A,e,s,n,o,i,g,B){this.sampleName=A,this.sampleRate=e,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=i,this.sampleLoopStartIndex=g,this.sampleLoopEndIndex=B,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{H(`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 rt=class extends me{sampleDbAttenuation;sampleData;constructor(A,e,s,n,o,i,g,B){super(A,e,s,n,0,1,o,i-1),this.sampleData=g,this.sampleDbAttenuation=B}getAudioData(){return this.sampleData}getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data?? This shouldn't happen!!");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let e=0;e>8&255}return A}};var no={PCM:1,ALAW:6};function Wo(t,A){let e=Math.pow(2,A*8-1),s=Math.pow(2,A*8),n,o=!1;A===1?(n=255,o=!0):n=e;let i=t.size/A,g=new Float32Array(i);for(let B=0;B=e&&(h-=s),g[B]=h/n)}return g}function _o(t,A){let e=t.size/A,s=new Float32Array(e);for(let n=0;n>4,B=i&15;g>0&&(B+=16),B=(B<<4)+8,g>1&&(B=B<127?B:-B;s[n]=h/32678}return s}function oo(t){yA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexG.header==="fmt ");if(!n)throw new Error("No fmt chunk in the wave file!");let o=D(n.chunkData,2),i=D(n.chunkData,2);if(i!==1)throw new Error(`Only mono samples are supported. Fmt reports ${i} channels`);let g=D(n.chunkData,4);D(n.chunkData,4),D(n.chunkData,2);let h=D(n.chunkData,2)/8,d=!1,u=s.find(G=>G.header==="data");u||this.parsingError("No data chunk in the WAVE chunk!");let l;switch(o){default:d=!0,l=new Float32Array(u.size/h);break;case no.PCM:l=Wo(u,h);break;case no.ALAW:l=_o(u,h);break}let c=60,p=0,S=0,w=l.length-1,k=0,L=s.find(G=>G.header==="wsmp");if(L){D(L.chunkData,4),c=D(L.chunkData,2),p=Ae(L.chunkData[L.chunkData.currentIndex++],L.chunkData[L.chunkData.currentIndex++]);let G=Math.trunc(p/100);if(c+=G,p-=G*100,k=(D(L.chunkData,4)|0)/-655360,D(L.chunkData,4),D(L.chunkData,4)===1){D(L.chunkData,8),S=D(L.chunkData,4);let z=D(L.chunkData,4);w=S+z}}else H("No wsmp chunk in wave... using sane defaults.");let R=DA(s,"INFO"),N=`Unnamed ${A}`;if(R){let G=Z(R.chunkData);for(;G.header!=="INAM"&&R.chunkData.currentIndexBe[t]=A<<7;dA(S.mainVolume,100);dA(S.balance,64);dA(S.expressionController,127);dA(S.pan,64);dA(S.timbreHarmonicContent,64);dA(S.releaseTime,64);dA(S.attackTime,64);dA(S.brightness,64);dA(S.soundController6,64);dA(S.soundController7,64);dA(S.soundController8,64);dA(S.soundController9,64);dA(S.generalPurposeController6,64);dA(S.generalPurposeController8,64);dA(gA+K.pitchWheel,64);dA(gA+K.pitchWheelRange,2);var aA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Rt=Object.keys(aA).length,Gt=new Float32Array(Rt);Gt[aA.modulationMultiplier]=1;var fA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6};function ks(t=!1){let A={midiControllers:new Int16Array(Ze),lockedControllers:Array(Ze).fill(!1),customControllers:new Float32Array(Rt),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:fA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},velocityOverride:0,lockGSNRPNParams:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let e=0;e<128;e++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),t&&this.callEvent("newchannel",void 0)}function zA(t,A){t.lockPreset||(t.bank=A)}function KA(t){return t.drumChannel?128:t.bank}var xt={velocityOverride:128};var Xe={addMapping:0,deleteMapping:1,clearMappings:2},We=class{_keyMappings=[];handleMessage(A,e){switch(A){default:return;case Xe.addMapping:this.addMapping(...e);break;case Xe.clearMappings:this.clearMappings();break;case Xe.deleteMapping:this.deleteMapping(...e)}}addMapping(A,e,s){this._keyMappings[A]===void 0&&(this._keyMappings[A]=[]),this._keyMappings[A][e]=s}deleteMapping(A,e){this._keyMappings[A]?.[e]!==void 0&&(this._keyMappings[A][e]=void 0)}clearMappings(){this._keyMappings=[]}setMappings(A){this._keyMappings=A}getMappings(){return this._keyMappings}getVelocity(A,e){let s=this._keyMappings[A]?.[e];return s?s.velocity:-1}hasOverridePatch(A,e){let s=this._keyMappings[A]?.[e]?.patch?.bank;return s!==void 0&&s>=0}getPatch(A,e){let s=this._keyMappings[A]?.[e];if(s)return s.patch;throw new Error("No modifier.")}};var ws="spessasynth-worklet-system",Fs=350,SA=9,_e=16,ze="gs";var wA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10,setPreservePlaybackState:11},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 Rs(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=Re(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(g=>g.midiNote===t.messageData[0]&&g.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/(Ho(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),H("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:H(`%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 Gs(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===SA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Ho(t){return t.messageData.currentIndex=0,6e7/jA(t.messageData,3)}function xs(){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 Ms(){let t=0,A=1/0;return this.tracks.forEach((e,s)=>{this.eventIndex[s]>=e.length||e[this.eventIndex[s]].ticks>>0}function he(t,A,e){for(let s=0;s>s*8&255}function v(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function QA(t,A){he(t,A,4)}function $A(t,A){let e=A<<8|t;return e>32767?e-65536:e}function Ns(t){return t>127?t-256:t}function O(t,A,e=void 0,s=!0){if(e){let n=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(n.buffer)}else{let n=!1,o="";for(let i=0;i127){if(s){n=!0;continue}else if(g===0){n=!0;continue}}o+=String.fromCharCode(g)}}return o}}function RA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let s=0;sA.length)for(let s=0;se.header!=="LIST"?!1:(e.chunkData.currentIndex=0,O(e.chunkData,4)===A))}function $e(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var At={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 et=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 Qe(t,A){let e=0;for(;t>0;){let s=A.tempoChanges.find(o=>o.ticks0&&(N+=this.tracks[y-1][this.tracks[y-1].length-1].ticks);k.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=N),z=ds[C>>4],(C&240)===F.noteOn){L.add(iA);let IA=k.data[k.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,IA),this.keyRange.max=Math.max(this.keyRange.max,IA)}R=C;break}let AA=new J(z),eA=k.data.slice(k.data.currentIndex,k.data.currentIndex+z);k.data.currentIndex+=z,AA.set(eA,0);let cA=new ge(N,C,AA);switch(w.push(cA),iA){case-2:switch(C){case F.setTempo:this.tempoChanges.push({ticks:N,tempo:6e7/jA(eA,3)});break;case F.marker:switch(O(AA,AA.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=N;break;case"loopend":u=N}AA.currentIndex=0;break;case F.midiPort:let mA=AA[0];this.midiPorts[y]=mA,this.midiPortChannelOffsets[mA]===void 0&&(this.midiPortChannelOffsets[mA]=l,l+=16);break;case F.copyright:o||(this.copyright+=O(AA,AA.length,void 0,!1)+` +`);break;case F.lyric:this.lyrics.push(AA)}break;case-3:if(AA.slice(0,7).every((IA,mA)=>Yo[mA]===IA)){let IA=AA.slice(7,eA.length-3),mA=O(IA,IA.length)+` +`;this.copyright+=mA,m(`%cDecoded Roland SC message! %c${mA}`,r.recognized,r.value)}break;default:if((C&240)===F.controllerChange)switch(AA[0]){case 2:case 116:d=N;break;case 4:case 117:u===null?u=N:u=0;break;case 0:g&&AA[1]!==0&&AA[1]!==127&&(m("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(w),this.usedChannelsOnTrack.push(L),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),yA("%cCorrecting loops, ports and detecting notes...",r.info);let c=[];for(let y of this.tracks){let w=y.find(k=>(k.messageStatusByte&240)===F.noteOn);w&&c.push(w.ticks)}this.firstNoteOn=Math.min(...c),m(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&u===null?(d=this.firstNoteOn,u=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(u===null||u===0)&&(u=this.lastVoiceEventTick)),this.loop={start:d,end:u},m(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let p=0;for(let y of this.midiPorts)if(y!==-1){p=y;break}if(this.midiPorts=this.midiPorts.map(y=>y===-1?p: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=O(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=O(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=ls(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let y=0;yl>u?l:u),s=[];for(let u=0;u{i[p]>=c.length||c[i[p]].ticks0;){let u=B(),l=t.tracks[u];if(i[u]>=l.length){g--;continue}let c=l[i[u]];if(i[u]++,c.messageStatusByte===F.midiPort){h[u]=c.messageData[0];continue}let p=c.messageStatusByte&240;if(p!==F.noteOn&&p!==F.controllerChange&&p!==F.programChange&&p!==F.systemExclusive)continue;let y=(c.messageStatusByte&15)+t.midiPortChannelOffsets[h[u]]||0,w=s[y];switch(p){case F.programChange:w.program=c.messageData[0],n(w);break;case F.controllerChange:if(c.messageData[0]!==S.bankSelect||d==="gs"&&w.drums)continue;let k=c.messageData[1],L=Math.max(0,k-t.bankOffset);if(d==="xg"){let G=k===120||k===126||k===127;G!==w.drums?(w.drums=G,w.bank=w.drums?128:L,n(w)):w.bank=w.drums?128:L;continue}s[y].bank=L;break;case F.noteOn:if(c.messageData[1]===0)continue;n(w),o[w.string].add(`${c.messageData[0]}-${c.messageData[1]}`);break;case F.systemExclusive:if(c.messageData[0]!==65||c.messageData[2]!==66||c.messageData[3]!==18||c.messageData[4]!==64||!(c.messageData[5]&16)||c.messageData[6]!==21){c.messageData[0]===67&&c.messageData[2]===76&&c.messageData[5]===126&&c.messageData[6]===0&&(d="xg");continue}let R=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][c.messageData[5]&15]+t.midiPortChannelOffsets[h[u]],N=!!(c.messageData[7]>0&&c.messageData[5]>>4);w=s[R],w.drums=N,w.bank=N?128:0,n(w);break}}for(let u of Object.keys(o))o[u].size===0&&(m(`%cDetected change but no keys for %c${u}`,r.info,r.value),delete o[u]);return V(),o}function Ls(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(s,e)}),this.duration=this.midiData.duration,this.firstNoteTime=Qe(this.midiData.firstNoteOn,this.midiData),m(`%cTotal song time: ${kt(Math.ceil(this.duration)).time}`,r.recognized),this.post(FA.songChange,[new je(this.midiData),this.songIndex,A]),this.duration<=1&&(H(`%cVery short song: (${kt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),A)this.play(!0);else{let e=this._skipToFirstNoteOn?this.midiData.firstNoteOn-1:0;this.setTimeTicks(e),this.pause()}}function Ts(t,A=!0){this.songs=t.reduce((e,s)=>{if(s.duration)return e.push(s),e;try{e.push(new tt(s.binary,s.altName||""))}catch(n){return this.post(FA.midiError,n.message),e}return e},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex],A))}function Hs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Ys(){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 Ge=Be.slice(0,128);function Js(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 g=0;gg===S.dataDecrement||g===S.dataIncrement||g===S.dataEntryMsb||g===S.dataDecrement||g===S.lsbForControl6DataEntry||g===S.RPNLsb||g===S.RPNMsb||g===S.NRPNLsb||g===S.NRPNMsb||g===S.bankSelect||g===S.lsbForControl0BankSelect||g===S.resetAllControllers,i=[];for(let g=0;g=A)break}else if(this.playedTime>=t)break;let h=Re(B.messageStatusByte),d=h.channel+(this.midiPortChannelOffsets[this.midiPorts[g]]||0);switch(h.status){case F.noteOn:case F.noteOff:case F.keySignature:break;case F.pitchBend:s[d]=B.messageData[1]<<7|B.messageData[0];break;case F.programChange:let l=n[d];l.program=B.messageData[0],l.actualBank=l.bank;break;case F.controllerChange:let c=B.messageData[0];if(o(c)){let p=B.messageData[1];if(c===S.bankSelect){n[d].bank=p;break}else c===S.resetAllControllers&&(i[d]=Array.from(Ge));this.sendMIDIMessages?this.sendMIDICC(d,c,p):this.synth.controllerChange(d,c,p)}else i[d]===void 0&&(i[d]=Array.from(Ge)),i[d][c]=B.messageData[1];break;default:this._processEvent(B,g);break}this.eventIndex[g]++,g=this._findFirstEventIndex();let u=this.tracks[g][this.eventIndex[g]];if(u===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(u.ticks-B.ticks)}if(this.sendMIDIMessages){for(let g=0;g>7,s[g]&127),i[g]!==void 0&&i[g].forEach((B,h)=>{B!==Ge[h]&&!o(h)&&this.sendMIDICC(g,h,B)}),n[g].program>=0&&n[g].actualBank>=0){let B=n[g].actualBank;this.sendMIDICC(g,S.bankSelect,B),this.sendMIDIProgramChange(g,n[g].program)}}else for(let g=0;g>7,s[g]&127),i[g]!==void 0&&i[g].forEach((B,h)=>{B!==Ge[h]&&!o(h)&&this.synth.controllerChange(g,h,B)}),n[g].program>=0&&n[g].actualBank>=0){let B=n[g].actualBank;this.synth.controllerChange(g,S.bankSelect,B),this.synth.programChange(g,n[g].program)}return!0}function vs(t=!1){if(this.midiData!==void 0){if(t){this.pausedTime=void 0,this.currentTime=0;return}if(this.currentTime>=this.duration){this.pausedTime=void 0,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 qs(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(FA.timeChange,currentTime-Qe(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Ps(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function Ks(t,A){switch(t){default:break;case wA.loadNewSongList:this.loadNewSongList(A[0],A[1]);break;case wA.pause:this.pause();break;case wA.play:this.play(A);break;case wA.stop:this.stop();break;case wA.setTime:this.currentTime=A;break;case wA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case wA.setPlaybackRate:this.playbackRate=A;break;case wA.setLoop:this.loop=A;break;case wA.changeSong:A?this.nextSong():this.previousSong();break;case wA.getMIDI:this.post(FA.getMIDI,this.midiData);break;case wA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break;case wA.setPreservePlaybackState:this.preservePlaybackState=A}}function Vs(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:uA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Os(t){this.post(FA.midiEvent,t)}function Zs(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|t,A,e])}function Xs(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|t,A])}function Ws(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|t,e,A])}function _s(){if(this.sendMIDIMessages){this.sendMIDIMessage([F.reset]);for(let t=0;t<_e;t++)this.sendMIDIMessage([F.controllerChange|t,S.allSoundOff,0]),this.sendMIDIMessage([F.controllerChange|t,S.resetAllControllers,0])}}var rA=class{constructor(A){this.synth=A,this.ignoreEvents=!1,this.sendMIDIMessages=!1,this.loopCount=1/0,this.currentLoopCount=this.loopCount,this.eventIndex=[],this.songIndex=0,this.playedTime=0,this.pausedTime=void 0,this.absoluteStartTime=currentTime,this._playbackRate=1,this.playingNotes=[],this.loop=!0,this.midiData=void 0,this.midiPorts=[],this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this._skipToFirstNoteOn=!0,this.preservePlaybackState=!1}set playbackRate(A){let e=this.currentTime;this._playbackRate=A,this.currentTime=e}get currentTime(){return this.pausedTime!==void 0?this.pausedTime:(currentTime-this.absoluteStartTime)*this._playbackRate}set currentTime(A){if(A>this.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&Azs?440*Math.pow(2,(t-6900)/1200):Nt[~~t-st]}var Lt=-1660,Jo=1600,bt=new Float32Array((Jo-Lt)*100+1);for(let t=0;t.5?1:0,s?e*2-1:e;case hA.concave:return s?(e=e*2-1,e<0?-ZA[~~(e*-CA)]:ZA[~~(e*CA)]):ZA[~~(e*CA)];case hA.convex:return s?(e=e*2-1,e<0?-ne[~~(e*-CA)]:ne[~~(e*CA)]):ne[~~(e*CA)]}}var Ut=1,Tt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)s-=o;let g=~~s,B=g+1;for(;B>=e.loopEnd;)B-=o;let h=s-g,d=n[B],u=n[g];A[i]=u+(d-u)*h,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 B=s-i,h=n[g],d=n[i];A[o]=d+(h-d)*B,s+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=s}function $s(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 g=~~s+1;for(;g>=e.loopEnd;)g-=n;A[i]=o[g],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[g],s+=e.playbackStep*t.currentTuningCalculated}}e.cursor=s}function An(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 g=~~s,B=g+1,h=B+1,d=h+1,u=s-g;B>=e.loopEnd&&(B-=o),h>=e.loopEnd&&(h-=o),d>=e.loopEnd&&(d-=o);let l=n[g],c=n[B],p=n[h],y=n[d],w=.5*(p-l),k=l-2.5*c+2*p-.5*y,L=.5*(y-l)+1.5*(c-p);A[i]=((L*u+k)*u+w)*u+c,s+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end||B>=e.end||h>=e.end){t.finished=!0;return}let u=n[i],l=n[g],c=n[B],p=n[h],y=.5*(c-u),w=u-2.5*l+2*c-.5*p,k=.5*(p-u)+1.5*(l-c);A[o]=((k*d+w)*d+y)*d+l,s+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=s}var en=.001,GA=100,Ht=90,vo=15e-6,TA=class t{currentSampleTime=0;sampleRate;currentAttenuationDb=GA;state=0;releaseStartDb=GA;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;constructor(A,e){this.sampleRate=A,this.canEndOnSilentSustain=e/10>=Ht}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=h=>Math.max(0,Math.floor(JA(h)*e.sampleRate));e.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[a.initialAttenuation],1440))/10,e.sustainDbRelative=Math.min(GA,A.modulatedGenerators[a.sustainVolEnv]/10);let n=Math.min(GA,e.sustainDbRelative);e.attackDuration=s(A.modulatedGenerators[a.attackVolEnv]);let o=A.modulatedGenerators[a.decayVolEnv],i=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvDecay],g=n/GA;e.decayDuration=s(o+i)*g,e.releaseDuration=s(A.modulatedGenerators[a.releaseVolEnv]),e.delayEnd=s(A.modulatedGenerators[a.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let B=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvHold];if(e.holdEnd=s(A.modulatedGenerators[a.holdVolEnv]+B)+e.attackEnd,e.decayEnd=e.decayDuration+e.holdEnd,e.state===0&&e.attackEnd===0&&(e.state=2),A.isInRelease){let h=Math.max(0,Math.min(GA,e.sustainDbRelative)),d=h/GA;switch(e.decayDuration=s(o+i)*d,e.state){case 0:e.releaseStartDb=GA;break;case 1:let l=1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration;e.releaseStartDb=20*Math.log10(l)*-1;break;case 2:e.releaseStartDb=0;break;case 3:e.releaseStartDb=(1-(e.decayEnd-e.releaseStartTimeSamples)/e.decayDuration)*h;break;case 4:e.releaseStartDb=h;break}e.releaseStartDb=Math.max(0,Math.min(e.releaseStartDb,GA)),e.releaseStartDb>=Ht&&(A.finished=!0),e.currentReleaseGain=vA(e.releaseStartDb);let u=(GA-e.releaseStartDb)/GA;e.releaseDuration*=u}}static apply(A,e,s,n){let o=A.volumeEnvelope,i=s/10,g=n;if(A.isInRelease){let h=o.currentSampleTime-o.releaseStartTimeSamples;if(h>=o.releaseDuration){for(let u=0;u=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>=Ht&&(A.finished=!0);;)if(o.attenuation+=(o.attenuationTarget-o.attenuation)*g,e[B]*=vA(o.sustainDbRelative+i+o.attenuation),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++B>=e.length)return}}};var le=class t{a0=0;a1=0;a2=0;a3=0;a4=0;x1=0;x2=0;y1=0;y2=0;reasonanceCb=0;reasonanceGain=1;cutoffCents=13501;cutoffHz=20001;static apply(A,e,s,n){if(n&&s>13499&&A.filter.reasonanceCb===0)return;let o=A.filter;(o.cutoffCents!==s||o.reasonanceCb!==A.modulatedGenerators[a.initialFilterQ])&&(o.cutoffCents=s,o.reasonanceCb=A.modulatedGenerators[a.initialFilterQ],t.calculateCoefficients(o));for(let i=0;i=A.releaseStartTime&&(A.isInRelease=!0,TA.startRelease(A),UA.startRelease(A),A.sample.loopingMode===3&&(A.sample.isLooping=!1)),A.modulatedGenerators[a.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let i=A.targetKey,g=A.modulatedGenerators[a.fineTune]+t.customControllers[aA.channelTuning]+t.customControllers[aA.channelTransposeFine]+t.customControllers[aA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],B=A.modulatedGenerators[a.coarseTune]+t.customControllers[aA.channelTuningSemitones],h=this.tunings[t.preset.program]?.[A.realKey];h?.midiNote>=0&&(i=h.midiNote,g+=h.centTuning),g+=(i-A.sample.rootKey)*A.modulatedGenerators[a.scaleTuning];let d=A.modulatedGenerators[a.vibLfoToPitch];if(d!==0){let C=A.startTime+JA(A.modulatedGenerators[a.delayVibLFO]),iA=xe(A.modulatedGenerators[a.freqVibLFO]),z=nt(C,iA,currentTime);g+=z*(d*t.customControllers[aA.modulationMultiplier])}let u=A.modulatedGenerators[a.initialFilterFc],l=u,c=A.modulatedGenerators[a.modLfoToPitch],p=A.modulatedGenerators[a.modLfoToVolume],y=A.modulatedGenerators[a.modLfoToFilterFc],w=0;if(c+y+p!==0){let C=A.startTime+JA(A.modulatedGenerators[a.delayModLFO]),iA=xe(A.modulatedGenerators[a.freqModLFO]),z=nt(C,iA,currentTime);g+=z*(c*t.customControllers[aA.modulationMultiplier]),w=-z*p,l+=z*y}if(t.channelVibrato.depth>0){let C=nt(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);C&&(g+=C*t.channelVibrato.depth)}let k=A.modulatedGenerators[a.modEnvToPitch],L=A.modulatedGenerators[a.modEnvToFilterFc],R=UA.getValue(A,currentTime);l+=R*L,g+=R*k;let N=~~(g+B*100);N!==A.currentTuningCents&&(A.currentTuningCents=N,A.currentTuningCalculated=Math.pow(2,N/1200));let G=new Float32Array(e.length);switch(this.interpolationType){case ce.linear:default:js(A,G);break;case ce.nearestNeighbor:$s(A,G);break;case ce.fourthOrder:An(A,G)}le.apply(A,G,l,u>13499),TA.apply(A,G,w,this.volumeEnvelopeSmoothingFactor),this.panVoice(A,G,e,s,n,o)}function qo(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 nn(t){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=qo(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 on(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimean=t);var Po=function(t){var A,e,s,n,o,i,g,B="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=B.indexOf(t.charAt(d++)),o=B.indexOf(t.charAt(d++)),i=B.indexOf(t.charAt(d++)),g=B.indexOf(t.charAt(d++)),A=n<<2|o>>4,e=(15&o)<<4|i>>2,s=(3&i)<<6|g,h+=String.fromCharCode(A),i!==64&&(h+=String.fromCharCode(e)),g!==64&&(h+=String.fromCharCode(s));while(d1&&(C.thisProgram=process.argv[1].replace(/\\/g,"/")),C.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(I){if(!(I instanceof De))throw I}),process.on("unhandledRejection",function(I,E){process.exit(1)}),C.quit=function(I){process.exit(I)},C.inspect=function(){return"[Emscripten Module object]"}):cA?(typeof read<"u"&&(C.read=function(E){return read(E)}),C.readBinary=function(E){var Q;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(Q=read(E,"binary"))=="object"),Q)},typeof scriptArgs<"u"?C.arguments=scriptArgs:typeof arguments<"u"&&(C.arguments=arguments),typeof quit=="function"&&(C.quit=function(I){quit(I)})):(z||AA)&&(z?document.currentScript&&(IA=document.currentScript.src):IA=self.location.href,IA=IA.indexOf("blob:")!==0?IA.split("/").slice(0,-1).join("/")+"/":"",C.read=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.send(null),Q.responseText},AA&&(C.readBinary=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.responseType="arraybuffer",Q.send(null),new Uint8Array(Q.response)}),C.readAsync=function(E,Q,f){var x=new XMLHttpRequest;x.open("GET",E,!0),x.responseType="arraybuffer",x.onload=function(){if(x.status==200||x.status==0&&x.response){Q(x.response);return}f()},x.onerror=f,x.send(null)},C.setWindowTitle=function(I){document.title=I});var Le=C.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),xA=C.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Le);for(t in iA)iA.hasOwnProperty(t)&&(C[t]=iA[t]);function Ue(I){var E=c;return c=c+I+15&-16,E}function _t(I){var E=B[R>>2],Q=E+I+15&-16;return B[R>>2]=Q,Q>=EA&&!rs()?(B[R>>2]=E,0):E}function zt(I,E){return E||(E=16),I=Math.ceil(I/E)*E}function Do(I){switch(I){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(I[I.length-1]==="*")return 4;if(I[0]!=="i")return 0;var E=parseInt(I.substr(1));return _A(E%8==0),E/8}}function pe(I){pe.shown||(pe.shown={}),pe.shown[I]||(pe.shown[I]=1,xA(I))}iA=void 0;var ko={"f64-rem":function(I,E){return I%E},debugger:function(){}},Et=[];function Ar(I,E){for(var Q=0,f=Q;f>>0)+4294967296*+(E>>>0):+(I>>>0)+4294967296*+(0|E)}function ht(I,E,Q){return Q&&Q.length?C["dynCall_"+I].apply(null,[E].concat(Q)):C["dynCall_"+I].call(null,E)}var Te=0,jt=0;function _A(I,E){I||OA("Assertion failed: "+E)}function $t(I){var E=C["_"+I];return _A(E,"Cannot call unknown function "+I+", make sure it is exported"),E}var As={stackSave:function(){pt()},stackRestore:function(){mt()},arrayToC:function(I){var E,Q,f=Pe(I.length);return E=I,Q=f,n.set(E,Q),f},stringToC:function(I){var E=0;if(I!=null&&I!==0){var Q=(I.length<<2)+1;E=Pe(Q),ss(I,E,Q)}return E}},wo={string:As.stringToC,array:As.arrayToC};function es(I,E,Q,f,x){var P=$t(I),X=[],b=0;if(f)for(var BA=0;BA>0]=E;break;case"i16":i[I>>1]=E;break;case"i32":B[I>>2]=E;break;case"i64":tempI64=[E>>>0,+No(tempDouble=E)>=1?tempDouble>0?(0|Lo(+Cs(tempDouble/4294967296),4294967295))>>>0:~~+bo((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],B[I>>2]=tempI64[0],B[I+4>>2]=tempI64[1];break;case"float":d[I>>2]=E;break;case"double":u[I>>3]=E;break;default:OA("invalid type for setValue: "+Q)}}function nr(I,E,Q){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return n[I>>0];case"i16":return i[I>>1];case"i32":case"i64":return B[I>>2];case"float":return d[I>>2];case"double":return u[I>>3];default:OA("invalid type for getValue: "+E)}return null}function or(I,E,Q,f){typeof I=="number"?(P=!0,X=I):(P=!1,X=I.length);var x=typeof E=="string"?E:null;if(b=Q==4?f:[typeof qe=="function"?qe:Ue,Pe,Ue,_t][Q===void 0?2:Q](Math.max(X,x?1:E.length)),P){for(f=b,_A((3&b)==0),BA=b+(-4&X);f>2]=0;for(BA=b+X;f>0]=0;return b}if(x==="i8")return I.subarray||I.slice?o.set(I,b):o.set(new Uint8Array(I),b),b;for(var P,X,b,BA,nA,oA,tA,q=0;q>0],(f!=0||E)&&(X++,!E||X!=E););E||(E=X);var b="";if(P<128){for(;E>0;)x=String.fromCharCode.apply(String,o.subarray(I,I+Math.min(E,1024))),b=b?b+x:x,I+=1024,E-=1024;return b}return Q=I,function(nA,oA){for(var tA=oA;nA[tA];)++tA;if(tA-oA>16&&nA.subarray&&ts)return ts.decode(nA.subarray(oA,tA));for(var q,pA,MA,NA,bA,te,LA="";;){if(!(q=nA[oA++]))return LA;if(!(128&q)){LA+=String.fromCharCode(q);continue}if(pA=63&nA[oA++],(224&q)==192){LA+=String.fromCharCode((31&q)<<6|pA);continue}if(MA=63&nA[oA++],(240&q)==224?q=(15&q)<<12|pA<<6|MA:(NA=63&nA[oA++],(248&q)==240?q=(7&q)<<18|pA<<12|MA<<6|NA:(bA=63&nA[oA++],q=(252&q)==248?(3&q)<<24|pA<<18|MA<<12|NA<<6|bA:(1&q)<<30|pA<<24|MA<<18|NA<<12|bA<<6|(te=63&nA[oA++]))),q<65536)LA+=String.fromCharCode(q);else{var ke=q-65536;LA+=String.fromCharCode(55296|ke>>10,56320|1023&ke)}}}(o,Q)}function ir(I){for(var E="";;){var Q=n[I++>>0];if(!Q)return E;E+=String.fromCharCode(Q)}}function ar(I,E){return function(f,x,P){for(var X=0;X>0]=f.charCodeAt(X);P||(n[x>>0]=0)}(I,E,!1)}var ts=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ye(I,E,Q,f){if(!(f>0))return 0;for(var x=Q,P=Q+f-1,X=0;X=55296&&b<=57343&&(b=65536+((1023&b)<<10)|1023&I.charCodeAt(++X)),b<=127){if(Q>=P)break;E[Q++]=b}else if(b<=2047){if(Q+1>=P)break;E[Q++]=192|b>>6,E[Q++]=128|63&b}else if(b<=65535){if(Q+2>=P)break;E[Q++]=224|b>>12,E[Q++]=128|b>>6&63,E[Q++]=128|63&b}else if(b<=2097151){if(Q+3>=P)break;E[Q++]=240|b>>18,E[Q++]=128|b>>12&63,E[Q++]=128|b>>6&63,E[Q++]=128|63&b}else if(b<=67108863){if(Q+4>=P)break;E[Q++]=248|b>>24,E[Q++]=128|b>>18&63,E[Q++]=128|b>>12&63,E[Q++]=128|b>>6&63,E[Q++]=128|63&b}else{if(Q+5>=P)break;E[Q++]=252|b>>30,E[Q++]=128|b>>24&63,E[Q++]=128|b>>18&63,E[Q++]=128|b>>12&63,E[Q++]=128|b>>6&63,E[Q++]=128|63&b}}return E[Q]=0,Q-x}function ss(I,E,Q){return Ye(I,o,E,Q)}function Je(I){for(var E=0,Q=0;Q=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&I.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 ns=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function Ir(I){for(var E=I,Q=E>>1;i[Q];)++Q;if((E=Q<<1)-I>32&&ns)return ns.decode(o.subarray(I,E));for(var f=0,x="";;){var P=i[I+2*f>>1];if(P==0)return x;++f,x+=String.fromCharCode(P)}}function gr(I,E,Q){if(Q===void 0&&(Q=2147483647),Q<2)return 0;for(var f=E,x=(Q-=2)<2*I.length?Q/2:I.length,P=0;P>1]=X,E+=2}return i[E>>1]=0,E-f}function Cr(I){return 2*I.length}function Er(I){for(var E=0,Q="";;){var f=B[I+4*E>>2];if(f==0)return Q;if(++E,f>=65536){var x=f-65536;Q+=String.fromCharCode(55296|x>>10,56320|1023&x)}else Q+=String.fromCharCode(f)}}function Br(I,E,Q){if(Q===void 0&&(Q=2147483647),Q<4)return 0;for(var f=E,x=f+Q-4,P=0;P=55296&&X<=57343&&(X=65536+((1023&X)<<10)|1023&I.charCodeAt(++P)),B[E>>2]=X,(E+=4)+4>x)break}return B[E>>2]=0,E-f}function hr(I){for(var E=0,Q=0;Q=55296&&f<=57343&&++Q,E+=4}return E}function Qr(I){var E=Je(I)+1,Q=qe(E);return Q&&Ye(I,n,Q,E),Q}function cr(I){var E=Je(I)+1,Q=Pe(E);return Ye(I,n,Q,E),Q}function lr(I){return I}function ur(){var I,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(x){f=x}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return C.extraStackTrace&&(E+=` +`+C.extraStackTrace()),(I=E).replace(/__Z[\w\d_]+/g,function(Q){var f,x=f=Q;return Q===x?Q:Q+" ["+x+"]"})}function Qt(I,E){return I%E>0&&(I+=E-I%E),I}function os(I){C.buffer=s=I}function ct(){C.HEAP8=n=new Int8Array(s),C.HEAP16=i=new Int16Array(s),C.HEAP32=B=new Int32Array(s),C.HEAPU8=o=new Uint8Array(s),C.HEAPU16=g=new Uint16Array(s),C.HEAPU32=h=new Uint32Array(s),C.HEAPF32=d=new Float32Array(s),C.HEAPF64=u=new Float64Array(s)}function rs(){var I=C.usingWasm?65536:16777216,E=2147483648-I;if(B[R>>2]>E)return!1;var Q=EA;for(EA=Math.max(EA,16777216);EA>2];)EA=EA<=536870912?Qt(2*EA,I):Math.min(Qt((3*EA+2147483648)/4,I),E);var f=C.reallocBuffer(EA);return f&&f.byteLength==EA?(os(f),ct(),!0):(EA=Q,!1)}l=c=y=w=k=L=R=0,p=!1,C.reallocBuffer||(C.reallocBuffer=function(I){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(s,I);else{var E,Q=n;E=new ArrayBuffer(I),new Int8Array(E).set(Q)}}catch{return!1}return!!Uo(E)&&E});try{(N=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{N=function(E){return E.byteLength}}var lt=C.TOTAL_STACK||5242880,EA=C.TOTAL_MEMORY||16777216;function Ro(){return EA}function ye(I){for(;I.length>0;){var E=I.shift();if(typeof E=="function"){E();continue}var Q=E.func;typeof Q=="number"?E.arg===void 0?C.dynCall_v(Q):C.dynCall_vi(Q,E.arg):Q(E.arg===void 0?null:E.arg)}}EA=0?I:E<=32?2*Math.abs(1<=f&&(E<=32||I>f)&&(I=-2*f+I),I}var No=Math.abs,bo=Math.ceil,Cs=Math.floor,Lo=Math.min,ee=0,ft=null,Se=null;function Dr(I){return I}C.preloadedImages={},C.preloadedAudios={};var Es="data:application/octet-stream;base64,";function ve(I){return String.prototype.startsWith?I.startsWith(Es):I.indexOf(Es)===0}(function(){var E="main.wast",Q="main.wasm",f="main.temp.asm.js";ve(E)||(E=mA(E)),ve(Q)||(Q=mA(Q)),ve(f)||(f=mA(f));var x={global:null,env:null,asm2wasm:ko,parent:C},P=null;function X(tA){return tA}function b(){try{if(C.wasmBinary)return new Uint8Array(C.wasmBinary);if(C.readBinary)return C.readBinary(Q);throw"both async and sync fetching of the wasm failed"}catch(tA){OA(tA)}}C.asmPreload=C.asm;var BA=C.reallocBuffer,nA=function(tA){tA=Qt(tA,C.usingWasm?65536:16777216);var q=C.buffer.byteLength;if(C.usingWasm)try{var pA=C.wasmMemory.grow((tA-q)/65536);return pA!==-1?C.buffer=C.wasmMemory.buffer:null}catch{return null}};C.reallocBuffer=function(tA){return oA==="asmjs"?BA(tA):nA(tA)};var oA="";C.asm=function(tA,q,pA){var MA;if(!(q=MA=q).table){var NA,bA=C.wasmTableSize;bA===void 0&&(bA=1024);var te=C.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?te!==void 0?q.table=new WebAssembly.Table({initial:bA,maximum:te,element:"anyfunc"}):q.table=new WebAssembly.Table({initial:bA,element:"anyfunc"}):q.table=Array(bA),C.wasmTable=q.table}return q.memoryBase||(q.memoryBase=C.STATIC_BASE),q.tableBase||(q.tableBase=0),NA=function(ke,ae,St){if(typeof WebAssembly!="object")return xA("no native wasm support detected"),!1;if(!(C.wasmMemory instanceof WebAssembly.Memory))return xA("no native wasm Memory in use"),!1;function Ke(qA,PA){if((P=qA.exports).memory){var we,Dt,Qs;we=P.memory,Dt=C.buffer,we.byteLength0?Q:Je(I)+1,x=Array(f),P=Ye(I,x,0,x.length);return E&&(x.length=P),x}function Rr(I){for(var E=[],Q=0;Q255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}c+=16,R=Ue(4),k=(y=w=zt(c))+lt,L=zt(k),B[R>>2]=L,p=!0,C.wasmTableSize=4,C.wasmMaxTableSize=4,C.asmGlobalArg={},C.asmLibraryArg={abort:OA,assert:_A,enlargeMemory:rs,getTotalMemory:Ro,abortOnCannotGrowMemory:function(){OA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+EA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(E,Q,f){var x=pt();try{return C.dynCall_iii(E,Q,f)}catch(P){if(mt(x),typeof P!="number"&&P!=="longjmp")throw P;C.setThrew(1,0)}},___assert_fail:function(E,Q,f,x){OA("Assertion failed: "+He(E)+", at: "+[Q?He(Q):"unknown filename",f,x?He(x):"unknown function"])},___setErrNo:function(E){return C.___errno_location&&(B[C.___errno_location()>>2]=E),E},_abort:function(){C.abort()},_emscripten_memcpy_big:function(E,Q,f){return o.set(o.subarray(Q,Q+f),E),E},_llvm_floor_f64:Cs,DYNAMICTOP_PTR:R,tempDoublePtr:kA,ABORT:Te,STACKTOP:w,STACK_MAX:k};var Bs=C.asm(C.asmGlobalArg,C.asmLibraryArg,s);C.asm=Bs,C.___errno_location=function(){return C.asm.___errno_location.apply(null,arguments)};var Uo=C._emscripten_replace_memory=function(){return C.asm._emscripten_replace_memory.apply(null,arguments)};C._free=function(){return C.asm._free.apply(null,arguments)};var qe=C._malloc=function(){return C.asm._malloc.apply(null,arguments)};C._memcpy=function(){return C.asm._memcpy.apply(null,arguments)},C._memset=function(){return C.asm._memset.apply(null,arguments)},C._sbrk=function(){return C.asm._sbrk.apply(null,arguments)},C._stb_vorbis_js_channels=function(){return C.asm._stb_vorbis_js_channels.apply(null,arguments)},C._stb_vorbis_js_close=function(){return C.asm._stb_vorbis_js_close.apply(null,arguments)},C._stb_vorbis_js_decode=function(){return C.asm._stb_vorbis_js_decode.apply(null,arguments)},C._stb_vorbis_js_open=function(){return C.asm._stb_vorbis_js_open.apply(null,arguments)},C._stb_vorbis_js_sample_rate=function(){return C.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},C.establishStackSpace=function(){return C.asm.establishStackSpace.apply(null,arguments)},C.getTempRet0=function(){return C.asm.getTempRet0.apply(null,arguments)},C.runPostSets=function(){return C.asm.runPostSets.apply(null,arguments)},C.setTempRet0=function(){return C.asm.setTempRet0.apply(null,arguments)},C.setThrew=function(){return C.asm.setThrew.apply(null,arguments)};var Pe=C.stackAlloc=function(){return C.asm.stackAlloc.apply(null,arguments)},mt=C.stackRestore=function(){return C.asm.stackRestore.apply(null,arguments)},pt=C.stackSave=function(){return C.asm.stackSave.apply(null,arguments)};function De(I){this.name="ExitStatus",this.message="Program terminated with exit("+I+")",this.status=I}function yt(I){I=I||C.arguments,!(ee>0)&&(function(){if(C.preRun)for(typeof C.preRun=="function"&&(C.preRun=[C.preRun]);C.preRun.length;)xo(C.preRun.shift());ye(is)}(),!(ee>0)&&(C.calledRun||(C.setStatus?(C.setStatus("Running..."),setTimeout(function(){setTimeout(function(){C.setStatus("")},1),E()},1)):E())));function E(){!C.calledRun&&(C.calledRun=!0,Te||(dt||(dt=!0,ye(ut)),ye(as),C.onRuntimeInitialized&&C.onRuntimeInitialized(),function(){if(C.postRun)for(typeof C.postRun=="function"&&(C.postRun=[C.postRun]);C.postRun.length;)Mo(C.postRun.shift());ye(gs)}()))}}function Gr(I,E){(!E||!C.noExitRuntime||I!==0)&&(C.noExitRuntime||(Te=!0,jt=I,w=G,ye(Is),Go=!0,C.onExit&&C.onExit(I)),C.quit(I,new De(I)))}function OA(I){throw C.onAbort&&C.onAbort(I),I!==void 0?(Le(I),xA(I),I=JSON.stringify(I)):I="",Te=!0,jt=1,"abort("+I+"). Build with -s ASSERTIONS=1 for more info."}if(C.dynCall_iii=function(){return C.asm.dynCall_iii.apply(null,arguments)},C.asm=Bs,C.ccall=es,C.cwrap=function(E,Q,f,x){var P=(f=f||[]).every(function(X){return X==="number"});return Q!=="string"&&P&&!x?$t(E):function(){return es(E,Q,f,arguments,x)}},De.prototype=Error(),De.prototype.constructor=De,Se=function I(){C.calledRun||yt(),C.calledRun||(Se=I)},C.run=yt,C.abort=OA,C.preInit)for(typeof C.preInit=="function"&&(C.preInit=[C.preInit]);C.preInit.length>0;)C.preInit.pop()();C.noExitRuntime=!0,yt(),C.onRuntimeInitialized=()=>{rn=!0,an()},VA.decode=function(I){return function(Q){if(!rn)throw Error("Not initialized");var f={};function x(ae){return new Int32Array(C.HEAPU8.buffer,ae,1)[0]}function P(ae,St){var Ke=new ArrayBuffer(St*Float32Array.BYTES_PER_ELEMENT),Ie=new Float32Array(Ke);return Ie.set(new Float32Array(C.HEAPU8.buffer,ae,St)),Ie}f.open=C.cwrap("stb_vorbis_js_open","number",[]),f.close=C.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=C.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=C.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=C.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var X,b,BA,nA,oA=f.open(),tA=(X=Q,b=Q.byteLength,BA=C._malloc(b),(nA=new Uint8Array(C.HEAPU8.buffer,BA,b)).set(new Uint8Array(X,0,b)),nA),q=C._malloc(4),pA=C._malloc(4),MA=f.decode(oA,tA.byteOffset,tA.byteLength,q,pA);if(C._free(tA.byteOffset),MA<0)throw f.close(oA),C._free(q),Error("stbvorbis decode failed: "+MA);for(var NA=f.channels(oA),bA=Array(NA),te=new Int32Array(C.HEAPU32.buffer,x(q),NA),LA=0;LA=0&&(s=this.workletProcessorChannels[e]),t.messageType){case j.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case j.noteOff:this.noteOff(e,A);break;case j.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case j.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case j.customcCcChange:s.customControllers[A[0]]=A[1];break;case j.killNote:this.killNote(e,A);break;case j.programChange:this.programChange(e,A[0],A[1]);break;case j.channelPressure:this.channelPressure(e,A);break;case j.polyPressure:this.polyPressure(e,A[0],A[1]);break;case j.ccReset:e===HA?this.resetAllControllers():this.resetControllers(e);break;case j.systemExclusive:this.systemExclusive(A);break;case j.setChannelVibrato:if(e===HA)for(let i=0;i{let e=(A.midiControllers[gA+K.pitchWheelRange]>>7)+(A.midiControllers[gA+K.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[gA+K.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:uA.channelProperties,messageData:t})}function Ko(t,A,e){let s=t,n=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function En(t,A=0){let e=t[0];if(!(this.deviceID!==HA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:H(`%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 g=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(g),m(`%cMaster Pan. Pan: %c${g}`,r.info,r.value);break;case 3:let B=(t[5]<<7|t[6])-8192;n=Math.floor(B/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:H(`%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++],g=t[o++];for(let h=0;h>1&1)===1&&this.setOctaveTuning(15+A,B);for(let h=0;h<7;h++)(t[5]>>h&1)===1&&this.setOctaveTuning(7+h+A,B);for(let h=0;h<7;h++)(t[6]>>h&1)===1&&this.setOctaveTuning(h+A,B);m(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${B.join(" ")}`,r.info,r.value);break;default:H(`%cUnrecognized MIDI Tuning standard message: %c${lA(t)}`,r.warn,r.unrecognized);break}break;default:H(`%cUnrecognized MIDI Realtime/non realtime message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 65:let s=function(){H(`%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 g=n-64;this.transposeChannel(o,g),m(`%cChannel %c${o}%c pitch shift. Semitones %c${g}%c, with %c${lA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let B=n;B===0&&(B=Math.floor(Math.random()*128)),this.controllerChange(o,S.pan,B);break;case 33:this.controllerChange(o,S.chorusDepth,n);break;case 34:this.controllerChange(o,S.reverbDepth,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 h=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,S.bankSelect,o);break;case 2:this.controllerChange(n,S.lsbForControl0BankSelect,o);break;case 3:this.programChange(n,o);break;case 8:let i=this.workletProcessorChannels[n];if(i.drumChannel)return;let g=o-64;i.channelTransposeKeyShift=g;break;case 11:this.controllerChange(n,S.mainVolume,o);break;case 14:let B=o;B===0&&(B=Math.floor(Math.random()*127)),this.controllerChange(n,S.pan,B);break;case 19:this.controllerChange(n,S.reverbDepth,o);break;case 18:this.controllerChange(n,S.chorusDepth,o);break;default:H(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&H(`%cUnrecognized Yamaha XG SysEx: %c${lA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&H(`%cUnrecognized Yamaha SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break}}var Vo=1e3/200;function Bn(t,A,e){if(A.transformAmount===0)return A.currentValue=0,0;let s;if(A.sourceUsesCC)s=t[A.sourceIndex];else{let h=A.sourceIndex+gA;switch(A.sourceIndex){case K.noController:s=16383;break;case K.noteOnKeyNum:s=e.midiNote<<7;break;case K.noteOnVelocity:s=e.velocity<<7;break;case K.polyPressure:s=e.pressure<<7;break;default:s=t[h];break}}let n=re[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let h=A.secSrcIndex+gA;switch(A.secSrcIndex){case K.noController:o=16383;break;case K.noteOnKeyNum:o=e.midiNote<<7;break;case K.noteOnVelocity:o=e.velocity<<7;break;case K.polyPressure:o=e.pressure<<7;break;default:o=t[h]}}let i=re[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=A.transformAmount;A.isEffectModulator&&g<=1e3&&(g*=Vo,g=Math.min(g,1e3));let B=n*i*g;return A.transformType===2&&(B=Math.abs(B)),A.currentValue=B,B}function XA(t,A,e=-1,s=0){let n=t.modulators,o=t.generators,i=t.modulatedGenerators;if(e===-1){i.set(o),n.forEach(h=>{let d=T[h.modulatorDestination],u=i[h.modulatorDestination]+Bn(A,h,t);i[h.modulatorDestination]=Math.max(d.min,Math.min(u,d.max))}),TA.recalculate(t),UA.recalculate(t);return}let g=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),B=new Set;n.forEach(h=>{if(h.sourceUsesCC===e&&h.sourceIndex===s||h.secSrcUsesCC===e&&h.secSrcIndex===s){let d=h.modulatorDestination;B.has(d)||(i[d]=o[d],Bn(A,h,t),n.forEach(u=>{if(u.modulatorDestination===d){let l=T[h.modulatorDestination],c=i[h.modulatorDestination]+u.currentValue;i[h.modulatorDestination]=Math.max(l.min,Math.min(c,l.max))}}),B.add(d))}}),[...B].some(h=>g.has(h))&&TA.recalculate(t),UA.recalculate(t)}var re=[];for(let t=0;t<4;t++){re[t]=[[new Float32Array(CA),new Float32Array(CA)],[new Float32Array(CA),new Float32Array(CA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||i.isMuted)return;let g=A+i.channelTransposeKeyShift,B=g;if(A>127||A<0)return;let h=i.preset.program;this.tunings[h]?.[A]?.midiNote>=0&&(B=this.tunings[h]?.[A].midiNote),i.velocityOverride>0&&(e=i.velocityOverride);let d=this.keyModifierManager.getVelocity(t,A);d>-1&&(e=d);let u=this.getWorkletVoices(t,B,e,i,o,g,s),l=i.voices;u.forEach(c=>{let p=c.generators[a.exclusiveClass];p!==0&&l.forEach(G=>{G.generators[a.exclusiveClass]===p&&(this.releaseVoice(G),G.modulatedGenerators[a.releaseVolEnv]=-7e3,G.modulatedGenerators[a.releaseModEnv]=-7e3,TA.recalculate(G),UA.recalculate(G))}),XA(c,i.midiControllers);let y=c.modulatedGenerators[a.startAddrsOffset]+c.modulatedGenerators[a.startAddrsCoarseOffset]*32768,w=c.modulatedGenerators[a.endAddrOffset]+c.modulatedGenerators[a.endAddrsCoarseOffset]*32768,k=c.modulatedGenerators[a.startloopAddrsOffset]+c.modulatedGenerators[a.startloopAddrsCoarseOffset]*32768,L=c.modulatedGenerators[a.endloopAddrsOffset]+c.modulatedGenerators[a.endloopAddrsCoarseOffset]*32768,R=c.sample,N=G=>Math.max(0,Math.min(R.sampleData.length-1,G));if(R.cursor=N(R.cursor+y),R.end=N(R.end+w),R.loopStart=N(R.loopStart+k),R.loopEnd=N(R.loopEnd+L),R.loopEndthis.voiceCap&&this.voiceKilling(u.length),l.push(...u),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Qn(t,A){if(A>127||A<0){H("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift;if(this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(n=>{n.realKey!==e||n.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(n):this.releaseVoice(n))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function cn(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.realKey===A&&(e.modulatedGenerators[a.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function ln(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 un(t=!1){m("%cStop all received!",r.info);for(let A=0;AXA(n,this.workletProcessorChannels[t].midiControllers,0,K.pitchWheel)),this.sendChannelProperties()}function kn(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[gA+K.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(s=>XA(s,e.midiControllers,0,K.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function wn(t,A,e){this.workletProcessorChannels[t].voices.forEach(s=>{s.midiNote===A&&(s.pressure=e,XA(s,this.workletProcessorChannels[t].midiControllers,0,K.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function Fn(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function Rn(t,A,e,s=!1){let n=this.workletProcessorChannels[t];if(n===void 0){H(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>127){if(!s)return;switch(A){default:return;case xt.velocityOverride:n.velocityOverride=e}}if(A>=S.lsbForControl1ModulationWheel&&A<=S.lsbForControl13EffectControl2&&A!==S.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 S.allNotesOff:this.stopAll(t);break;case S.allSoundOff:this.stopAll(t,!0);break;case S.bankSelect:let o=e;if(!s){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==SA&&this.setDrums(t,!1);break;case"gm2":o===120&&this.setDrums(t,!0)}n.drumChannel&&(o=128),o===128&&!n.drumChannel&&(o=KA(n))}zA(n,o);break;case S.lsbForControl0BankSelect:this.system==="xg"?n.drumChannel||e!==127&&zA(n,e):this.system==="gm2"&&zA(n,e);break;case S.RPNLsb:n.RPValue=n.RPValue<<7|e,n.dataEntryState=fA.RPFine;break;case S.RPNMsb:n.RPValue=e,n.dataEntryState=fA.RPCoarse;break;case S.NRPNMsb:n.NRPCoarse=e,n.dataEntryState=fA.NRPCoarse;break;case S.NRPNLsb:n.NRPFine=e,n.dataEntryState=fA.NRPFine;break;case S.dataEntryMsb:this.dataEntryCoarse(t,e);break;case S.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case S.resetAllControllers:this.resetControllers(t);break;case S.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));break}this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e})}function Gn(t){this.midiVolume=t,this.setMasterPan(this.pan)}function xn(t){this.masterGain=t*Jt,this.setMasterPan(this.pan)}function Mn(t){this.pan=t,t=t/2+.5,this.panLeft=1-t,this.panRight=t}function Nn(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function bn(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 Ln(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 Un(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 fA.Idle:break;case fA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;H(`%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;H(`%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,S.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,S.reverbDepth,o),m(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:H(`%cUnrecognized RPN for %c${t}%c: %c(0x${e.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:e.midiControllers[gA+K.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 Tn(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[gA+K.pitchWheelRange]|=A;let s=(e.midiControllers[gA+K.pitchWheelRange]>>7)+A/127;m(`%cChannel ${t} bend range. Semitones: %c${s}`,r.info,r.value);break;case 1:let o=e.customControllers[aA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let g=e.customControllers[aA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,g);break;case 16383:this.resetParameters(t);break}}}function Hn(t=!0){t&&m("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A>7});if(this.workletProcessorChannels[A].lockedControllers[gA+K.pitchWheel]===!1){let s=this.workletProcessorChannels[A].midiControllers[gA+K.pitchWheel],n=s>>7,o=s&127;this.callEvent("pitchwheel",{channel:A,MSB:n,LSB:o})}}this.tunings=[],this.tunings=[];for(let A=0;127>A;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=ze}function Yn(t){let A=this.workletProcessorChannels[t],s=A.lockedControllers.reduce((o,i,g)=>(i&&o.push(g),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0);for(let o=0;o>7}),A.midiControllers[o]=i}A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let n=A.customControllers[aA.channelTransposeFine];A.customControllers.set(Gt),A.customControllers[aA.channelTransposeFine]=n,this.resetParameters(t)}function Jn(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=fA.Idle}function vn(){let t=4;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>(o.generators=o.generators.filter(i=>i.generatorType!==a.sampleID&&i.generatorType!==a.keyRange&&i.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+n),0);let A=new J(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=e;for(let o of n.generators)v(A,o.generatorType),v(A,o.generatorValue),e++}return QA(A,0),sA(new $("igen",A.length,A))}function qn(t,A,e,s,n){let o=this.samples.map((h,d)=>{e&&h.compressSample(s,n);let u=h.getRawData();return m(`%cEncoded sample %c${d}. ${h.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),u}),i=this.samples.reduce((h,d,u)=>h+o[u].length+46,0),g=new J(i);this.samples.forEach((h,d)=>{let u=o[d],l,c,p=u.length;h.isCompressed?(l=g.currentIndex,c=l+u.length):(l=g.currentIndex/2,c=l+u.length/2,p+=46),t.push(l),g.set(u,g.currentIndex),g.currentIndex+=p,A.push(c)});let B=sA(new $("smpl",g.length,g),new J([115,100,116,97]));return sA(new $("LIST",B.length,B))}function Pn(t,A){let s=new J(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{RA(s,n.sampleName,20);let i=t[o];QA(s,i);let g=A[o];QA(s,g);let B=n.sampleLoopStartIndex+i,h=n.sampleLoopEndIndex+i;n.isCompressed&&(B-=i,h-=i),QA(s,B),QA(s,h),QA(s,n.sampleRate),s[s.currentIndex++]=n.samplePitch,s[s.currentIndex++]=n.samplePitchCorrection,v(s,n.sampleLink),v(s,n.sampleType)}),RA(s,"EOS",46),sA(new $("shdr",s.length,s))}function Kn(){let t=10;for(let s of this.instruments)t+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new J(t),e=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)v(A,o.sourceEnum),v(A,o.modulatorDestination),v(A,o.transformAmount),v(A,o.secondarySourceEnum),v(A,o.transformType),e++}return he(A,0,10),sA(new $("imod",A.length,A))}function Vn(){let t=this.instruments.reduce((o,i)=>i.instrumentZones.length*4+o,4),A=new J(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,v(A,s),v(A,n),s+=i.generators.length,n+=i.modulators.length,e++}return v(A,s),v(A,n),sA(new $("ibag",A.length,A))}function On(){let t=this.instruments.length*22+22,A=new J(t),e=0,s=0;for(let n of this.instruments)RA(A,n.instrumentName,20),v(A,e),e+=n.instrumentZones.length,n.instrumentID=s,s++;return RA(A,"EOI",20),v(A,e),sA(new $("inst",A.length,A))}function Zn(){let t=4;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>(o.generators=o.generators.filter(i=>i.generatorType!==a.instrument&&i.generatorType!==a.keyRange&&i.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+n),0);let A=new J(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=e;for(let o of n.generators)v(A,o.generatorType),v(A,o.generatorValue);e+=n.generators.length}return v(A,0),v(A,0),sA(new $("pgen",A.length,A))}function Xn(){let t=10;for(let s of this.presets)t+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new J(t),e=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=e;for(let o of n.modulators)v(A,o.sourceEnum),v(A,o.modulatorDestination),v(A,o.transformAmount),v(A,o.secondarySourceEnum),v(A,o.transformType),e++}return he(A,0,10),sA(new $("pmod",A.length,A))}function Wn(){let t=this.presets.reduce((o,i)=>i.presetZones.length*4+o,4),A=new J(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,v(A,s),v(A,n),s+=i.generators.length,n+=i.modulators.length,e++}return v(A,s),v(A,n),sA(new $("pbag",A.length,A))}function _n(){let t=this.presets.length*38+38,A=new J(t),e=0;for(let s of this.presets)RA(A,s.presetName,20),v(A,s.program),v(A,s.bank),v(A,e),QA(A,s.library),QA(A,s.genre),QA(A,s.morphology),e+=s.presetZones.length;return RA(A,"EOP",20),v(A,0),v(A,0),v(A,e),QA(A,0),QA(A,0),QA(A,0),sA(new $("phdr",A.length,A))}var Oo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function zn(t=Oo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");yA("%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[N,G]of Object.entries(this.soundFontInfo))if(N==="ifil"||N==="iver"){let C=parseInt(G.split(".")[0]),iA=parseInt(G.split(".")[1]),z=new J(4);v(z,C),v(z,iA),A.push(sA(new $(N,4,z)))}else if(N==="DMOD")A.push(sA(new $(N,G.length,G)));else{let C=new J(G.length);RA(C,G),A.push(sA(new $(N,G.length,C)))}let e=Fe([new J([73,78,70,79]),...A]),s=sA(new $("LIST",e.length,e));m("%cWriting SDTA...",r.info);let n=[],o=[],i=qn.call(this,n,o,t?.compress,t?.compressionQuality??.5,t.compressionFunction);m("%cWriting PDTA...",r.info),m("%cWriting SHDR...",r.info);let g=Pn.call(this,n,o);m("%cWriting IGEN...",r.info);let B=vn.call(this);m("%cWriting IMOD...",r.info);let h=Kn.call(this);m("%cWriting IBAG...",r.info);let d=Vn.call(this);m("%cWriting INST...",r.info);let u=On.call(this),l=Zn.call(this);m("%cWriting PMOD...",r.info);let c=Xn.call(this);m("%cWriting PBAG...",r.info);let p=Wn.call(this);m("%cWriting PHDR...",r.info);let y=_n.call(this),w=Fe([new J([112,100,116,97]),y,p,c,l,u,d,h,B,g]),k=sA(new $("LIST",w.length,w));m("%cWriting the output file...",r.info);let L=Fe([new J([115,102,98,107]),s,i,k]),R=sA(new $("RIFF",L.length,L));return m(`%cSaved succesfully! Final file size: %c${R.length}`,r.info,r.recognized),V(),R}var ie=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Oe.map(e=>_.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}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})}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPresetNoFallback(A,e,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)}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&&H(`%cPreset ${A}.${e} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,r.warn,r.recognized)),s||(H(`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||(H("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}parsingError(A){throw new Error(`SF parsing error: ${A} The file may be corrupted.`)}};ie.prototype.write=zn;function jn(t){yA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let 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(u,l,c){return c>=u&&c<=l}function o(u,l){u.push(...l.filter(c=>!u.find(p=>p.generatorType===c.generatorType)))}function i(u,l){u.push(...l.filter(c=>!u.find(p=>_.isIdentical(c,p))))}let g=[],B=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(u=>n(u.keyRange.min,u.keyRange.max,A)&&n(u.velRange.min,u.velRange.max,e)&&!u.isGlobal).forEach(u=>{if(u.instrument.instrumentZones.length<1)return;let l=u.generators,c=u.modulators,p=u.instrument.instrumentZones[0].isGlobal?[...u.instrument.instrumentZones[0].generators]:[],y=u.instrument.instrumentZones[0].isGlobal?[...u.instrument.instrumentZones[0].modulators]:[];u.instrument.instrumentZones.filter(k=>n(k.keyRange.min,k.keyRange.max,A)&&n(k.velRange.min,k.velRange.max,e)&&!k.isGlobal).forEach(k=>{let L=[...k.generators],R=[...k.modulators];o(l,B),o(L,p),i(c,h),i(R,y),i(R,this.defaultModulators);let N=[...R];for(let G=0;G_.isIdentical(C,z));iA!==-1?N[iA]=N[iA].sumTransform(C):N.push(C)}g.push({instrumentGenerators:L,presetGenerators:l,modulators:N,sample:k.sample,sampleID:k.generators.find(G=>G.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=g,g}};var Me=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var Ae=class extends Me{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},de=class extends Me{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var fe=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}get useCount(){return this._useCount}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var ot=class extends ue{constructor(A,e){super(Oe),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new fe,this.DLSInstrument.addUseCount();let n=new de;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function $n(t){this.verifyHeader(t,"LIST"),this.verifyText(O(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(Z(t.chunkData));let e=A.find(c=>c.header==="insh");if(!e)throw V(),new Error("No instrument header!");let s=D(e.chunkData,4),n=D(e.chunkData,4),o=D(e.chunkData,4),i=new ot(n,o),g="unnamedPreset",B=DA(A,"INFO");if(B){let c=Z(B.chunkData);for(;c.header!=="INAM";)c=Z(B.chunkData);g=O(c.chunkData,c.chunkData.length).trim()}i.presetName=g,i.DLSInstrument.instrumentName=g,se(`%cParsing %c"${g}"%c...`,r.info,r.recognized,r.info);let h=DA(A,"lrgn");if(!h)throw V(),new Error("No region list!");let d=new Ae;d.isGlobal=!0;let u=DA(A,"lart"),l=DA(A,"lar2");this.readLart(u,l,d),i.DLSInstrument.instrumentZones.push(d);for(let c=0;c>10&15;L===hA.linear&&k!==hA.linear&&(L=k);let R=s>>14&1,N=s>>15&1;i===a.initialAttenuation&&n>0&&(N=!N),l=YA(L,R,N,g.isCC,g.enum)}let c=s>>4&15,p=s>>8&1,y=s>>9&1,w=YA(c,p,y,u.isCC,u.enum);if(B){let k=w;w=l,l=k}return new _({srcEnum:l,secSrcEnum:w,dest:i,transform:0,amt:d})}function vt(t,A){let e=t.chunkData,s=[],n=[];D(e,4);let o=D(e,4);for(let i=0;i>16;if(g===0&&B===0&&d===0){let c;switch(h){case M.pan:c=new U(a.pan,l);break;case M.gain:c=new U(a.initialAttenuation,-l*10/.4);break;case M.filterCutoff:c=new U(a.initialFilterFc,l);break;case M.filterQ:c=new U(a.initialFilterQ,l);break;case M.modLfoFreq:c=new U(a.freqModLFO,l);break;case M.modLfoDelay:c=new U(a.delayModLFO,l);break;case M.vibLfoFreq:c=new U(a.freqVibLFO,l);break;case M.vibLfoDelay:c=new U(a.delayVibLFO,l);break;case M.volEnvDelay:c=new U(a.delayVolEnv,l);break;case M.volEnvAttack:c=new U(a.attackVolEnv,l);break;case M.volEnvHold:c=new U(a.holdVolEnv,l);break;case M.volEnvDecay:c=new U(a.decayVolEnv,l);break;case M.volEnvRelease:c=new U(a.releaseVolEnv,l);break;case M.volEnvSustain:let p=(1e3-l)/10;c=new U(a.sustainVolEnv,p*10);break;case M.modEnvDelay:c=new U(a.delayModEnv,l);break;case M.modEnvAttack:c=new U(a.attackModEnv,l);break;case M.modEnvHold:c=new U(a.holdModEnv,l);break;case M.modEnvDecay:c=new U(a.decayModEnv,l);break;case M.modEnvRelease:c=new U(a.releaseModEnv,l);break;case M.modEnvSustain:let y=1e3-l;c=new U(a.sustainModEnv,y);break;case M.reverbSend:c=new U(a.reverbEffectsSend,l);break;case M.chorusSend:c=new U(a.chorusEffectsSend,l);break;case M.pitch:let w=Math.floor(l/100),k=Math.floor(l-w*100);c=new U(a.fineTune,k),s.push(new U(a.coarseTune,w));break}c&&s.push(c)}else{let c=!0;if(B===W.none)if(g===W.modLfo&&h===M.pitch)s.push(new U(a.modLfoToPitch,l));else if(g===W.modLfo&&h===M.gain)s.push(new U(a.modLfoToVolume,l));else if(g===W.modLfo&&h===M.filterCutoff)s.push(new U(a.modLfoToFilterFc,l));else if(g===W.vibratoLfo&&h===M.pitch)s.push(new U(a.vibLfoToPitch,l));else if(g===W.modEnv&&h===M.pitch)s.push(new U(a.modEnvToPitch,l));else if(g===W.modEnv&&h===M.filterCutoff)s.push(new U(a.modEnvToFilterFc,l));else if(g===W.keyNum&&h===M.volEnvHold){s.push(new U(a.keyNumToVolEnvHold,l/-128));let p=Math.round(60/128*l);s.forEach(y=>{y.generatorType===a.holdVolEnv&&(y.generatorValue+=p)})}else if(g===W.keyNum&&h===M.volEnvDecay){s.push(new U(a.keyNumToVolEnvDecay,l/-128));let p=Math.round(60/128*l);s.forEach(y=>{y.generatorType===a.decayVolEnv&&(y.generatorValue+=p)})}else if(g===W.keyNum&&h===M.modEnvHold){s.push(new U(a.keyNumToModEnvHold,l/-128));let p=Math.round(60/128*l);s.forEach(y=>{y.generatorType===a.holdModEnv&&(y.generatorValue+=p)})}else if(g===W.keyNum&&h===M.modEnvDecay){s.push(new U(a.keyNumToModEnvDecay,l/-128));let p=Math.round(60/128*l);s.forEach(y=>{y.generatorType===a.decayModEnv&&(y.generatorValue+=p)})}else c=!1;else c=!1;if(c===!1){let p=eo(g,B,h,d,l);p?(n.push(p),m("%cSucceeded converting to SF2 Modulator!",r.recognized)):H("Failed converting to SF2 Modulator!")}}}return n.find(i=>i.modulatorDestination===a.reverbEffectsSend)===void 0&&n.push(new _({srcEnum:219,dest:a.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(i=>i.modulatorDestination===a.chorusEffectsSend)===void 0&&n.push(new _({srcEnum:221,dest:a.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&n.push(new _({srcEnum:129,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new _({srcEnum:13,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:n,generators:s}}function to(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(Z(t.chunkData));let e=A.find(AA=>AA.header==="rgnh"),s=D(e.chunkData,2),n=D(e.chunkData,2),o=D(e.chunkData,2),i=D(e.chunkData,2),g=new rt({min:s,max:n},{min:o,max:i});D(e.chunkData,2);let B=D(e.chunkData,2);B!==0&&g.generators.push(new U(a.exclusiveClass,B));let h=DA(A,"lart"),d=DA(A,"lar2");this.readLart(h,d,g),g.isGlobal=!1;let u=A.find(AA=>AA.header==="wsmp");D(u.chunkData,4);let l=D(u.chunkData,2),c=$A(u.chunkData[u.chunkData.currentIndex++],u.chunkData[u.chunkData.currentIndex++]),p=Math.trunc(c/100);l+=p,c-=p*100;let w=(D(u.chunkData,4)|0)/-655360;D(u.chunkData,4);let k=D(u.chunkData,4),L,R={start:0,end:0};if(k===0)L=0;else{D(u.chunkData,4),D(u.chunkData,4)===0?L=1:L=3,R.start=D(u.chunkData,4);let eA=D(u.chunkData,4);R.end=R.start+eA}let N=A.find(AA=>AA.header==="wlnk");if(N===void 0)return;D(N.chunkData,2),D(N.chunkData,2),D(N.chunkData,4);let G=D(N.chunkData,4),C=this.samples[G];if(C===void 0)throw new Error("Invalid sample ID!");let z=(w||C.sampleDbAttenuation)*10/.4;return g.setWavesample(z,L,R,l,C,G,c),g}var me=class{constructor(A,e,s,n,o,i,g,B){this.sampleName=A,this.sampleRate=e,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=i,this.sampleLoopStartIndex=g,this.sampleLoopEndIndex=B,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{H(`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 it=class extends me{sampleDbAttenuation;sampleData;constructor(A,e,s,n,o,i,g,B){super(A,e,s,n,0,1,o,i-1),this.sampleData=g,this.sampleDbAttenuation=B}getAudioData(){return this.sampleData}getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data?? This shouldn't happen!!");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let e=0;e>8&255}return A}};var no={PCM:1,ALAW:6};function Wo(t,A){let e=Math.pow(2,A*8-1),s=Math.pow(2,A*8),n,o=!1;A===1?(n=255,o=!0):n=e;let i=t.size/A,g=new Float32Array(i);for(let B=0;B=e&&(h-=s),g[B]=h/n)}return g}function _o(t,A){let e=t.size/A,s=new Float32Array(e);for(let n=0;n>4,B=i&15;g>0&&(B+=16),B=(B<<4)+8,g>1&&(B=B<127?B:-B;s[n]=h/32678}return s}function oo(t){yA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexG.header==="fmt ");if(!n)throw new Error("No fmt chunk in the wave file!");let o=D(n.chunkData,2),i=D(n.chunkData,2);if(i!==1)throw new Error(`Only mono samples are supported. Fmt reports ${i} channels`);let g=D(n.chunkData,4);D(n.chunkData,4),D(n.chunkData,2);let h=D(n.chunkData,2)/8,d=!1,u=s.find(G=>G.header==="data");u||this.parsingError("No data chunk in the WAVE chunk!");let l;switch(o){default:d=!0,l=new Float32Array(u.size/h);break;case no.PCM:l=Wo(u,h);break;case no.ALAW:l=_o(u,h);break}let c=60,p=0,y=0,w=l.length-1,k=0,L=s.find(G=>G.header==="wsmp");if(L){D(L.chunkData,4),c=D(L.chunkData,2),p=$A(L.chunkData[L.chunkData.currentIndex++],L.chunkData[L.chunkData.currentIndex++]);let G=Math.trunc(p/100);if(c+=G,p-=G*100,k=(D(L.chunkData,4)|0)/-655360,D(L.chunkData,4),D(L.chunkData,4)===1){D(L.chunkData,8),y=D(L.chunkData,4);let z=D(L.chunkData,4);w=y+z}}else H("No wsmp chunk in wave... using sane defaults.");let R=DA(s,"INFO"),N=`Unnamed ${A}`;if(R){let G=Z(R.chunkData);for(;G.header!=="INAM"&&R.chunkData.currentIndexB.header==="colh");o||(O(),this.parsingError("No colh chunk!")),this.instrumentAmount=D(o.chunkData,4),m(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let i=DA(s,"wvpl");i||(O(),this.parsingError("No wvpl chunk!")),this.readDLSSamples(i);let g=DA(s,"lins");g||(O(),this.parsingError("No lins chunk!")),this.readDLSInstrumentList(g),this.presets.sort((B,h)=>B.program-h.program+(B.bank-h.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),O()}verifyHeader(A,e){A.header.toLowerCase()!==e.toLowerCase()&&(O(),this.parsingError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,e){A.toLowerCase()!==e.toLowerCase()&&(O(),this.parsingError(`FourCC error: Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`))}parsingError(A){throw new Error(`DLS parse error: ${A} The file may be corrupted.`)}};_A.prototype.readDLSInstrumentList=jn;_A.prototype.readDLSInstrument=$n;_A.prototype.readRegion=so;_A.prototype.readLart=to;_A.prototype.readDLSSamples=oo;var qt=class extends me{constructor(A,e,s,n,o,i,g,B,h,d,u,l,c){super(A,i,g,B,h,d,n-e/2,o-e/2),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=s,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=u,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=c}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);try{let n=VA.decode(s.buffer);this.sampleData=n.data[0]}catch(n){throw new Error(`Ogg Vorbis decode error: ${n}`)}}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 H("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=zo(n,t.chunkData,A,e);s.push(o),n++}return s.length>1&&s.pop(),s}function zo(t,A,e,s){let n=V(A,20),o=D(A,4)*2,i=D(A,4)*2,g=D(A,4),B=D(A,4),h=D(A,4),d=A[A.currentIndex++];d===255&&(d=60);let u=Ns(A[A.currentIndex++]),l=D(A,2),c=D(A,2);return new qt(n,o,i,g,B,h,d,u,l,c,e,t,s)}var Pt=class extends U{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=Ae(A[e+2],A[e+3]),A.currentIndex+=4}};function Kt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Pt(t.chunkData));return A.length>1&&A.pop(),A}var Ot=class extends fe{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=D(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let s=this.instrumentZoneIndex;st.chunkData.currentIndex;){let s=new Ot(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 Vt=class extends ee{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===a.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ao(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,g=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(i,g),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 Zt=class extends de{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===a.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function Io(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Zt(t.chunkData);if(n.length>0){let i=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(i,g),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 Xt=class extends ue{constructor(A,e){super(e),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=D(A.chunkData,2),this.bank=D(A.chunkData,2),this.presetZoneStartIndex=D(A.chunkData,2),this.library=D(A.chunkData,4),this.genre=D(A.chunkData,4),this.morphology=D(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;st.chunkData.currentIndex;){let n=new Xt(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 Wt=class extends _{constructor(A){super({srcEnum:D(A,2),dest:D(A,2),amt:Ae(A[A.currentIndex++],A[A.currentIndex++]),secSrcEnum:D(A,2),transform:D(A,2)})}};function it(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Wt(t.chunkData));return A}var at=class extends ae{constructor(A,e=!0){super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new J(A),ne("%cParsing SoundFont...",r.info),this.dataArray||(O(),this.parsingError("No data provided!"));let s=Z(this.dataArray,!1);this.verifyHeader(s,"riff");let n=V(this.dataArray,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw O(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let o=n==="sfpk",i=Z(this.dataArray);for(this.verifyHeader(i,"list"),V(i.chunkData,4);i.chunkData.length>i.chunkData.currentIndex;){let eA=Z(i.chunkData),cA;switch(eA.header.toLowerCase()){case"ifil":case"iver":cA=`${D(eA.chunkData,2)}.${D(eA.chunkData,2)}`,this.soundFontInfo[eA.header]=cA;break;case"icmt":cA=V(eA.chunkData,eA.chunkData.length,void 0,!1),this.soundFontInfo[eA.header]=cA;break;case"dmod":let IA=it(eA);IA.pop(),cA=`Modulators: ${IA.length}`;let mA=this.defaultModulators;this.defaultModulators=IA,this.defaultModulators.push(...mA.filter(be=>!this.defaultModulators.find(xA=>_.isIdentical(be,xA)))),this.soundFontInfo[eA.header]=eA.chunkData;break;default:cA=V(eA.chunkData,eA.chunkData.length),this.soundFontInfo[eA.header]=cA}m(`%c"${eA.header}": %c"${cA}"`,r.info,r.recognized)}let g=Z(this.dataArray,!1);this.verifyHeader(g,"list"),this.verifyText(V(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",r.warn);let B=Z(this.dataArray,!1);this.verifyHeader(B,"smpl");let h;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{h=VA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+g.size-12)).data[0]}catch(eA){throw O(),new Error(`SF2Pack Ogg Vorbis decode error: ${eA}`)}m(`%cDecoded the smpl chunk! Length: %c${h.length}`,r.info,r.value)}else h=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${g.size-12}`,r.info,r.value),this.dataArray.currentIndex+=g.size-12,m("%cLoading preset data chunk...",r.warn);let d=Z(this.dataArray);this.verifyHeader(d,"list"),V(d.chunkData,4);let u=Z(d.chunkData);this.verifyHeader(u,"phdr");let l=Z(d.chunkData);this.verifyHeader(l,"pbag");let c=Z(d.chunkData);this.verifyHeader(c,"pmod");let p=Z(d.chunkData);this.verifyHeader(p,"pgen");let S=Z(d.chunkData);this.verifyHeader(S,"inst");let w=Z(d.chunkData);this.verifyHeader(w,"ibag");let k=Z(d.chunkData);this.verifyHeader(k,"imod");let L=Z(d.chunkData);this.verifyHeader(L,"igen");let R=Z(d.chunkData);this.verifyHeader(R,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...ro(R,h,!o));let N=Kt(L),G=it(k),C=ao(w,N,G,this.samples);this.instruments=io(S,C);let iA=Kt(p),z=it(c),AA=Io(l,iA,z,this.instruments);this.presets.push(...go(u,AA,this.defaultModulators)),this.presets.sort((eA,cA)=>eA.program-cA.program+(eA.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),O(),o&&delete this.dataArray}verifyHeader(A,e){A.header.toLowerCase()!==e.toLowerCase()&&(O(),this.parsingError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,e){A.toLowerCase()!==e.toLowerCase()&&(O(),this.parsingError(`Invalid FourCC: Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"\``))}};function Me(t){let A=t.slice(8,12),e=new J(A);return V(e,4,void 0,!1).toLowerCase()==="dls "?new _A(t):new at(t,!1)}function Co(t,A,e=!1){let s=this.workletProcessorChannels[t];if(s===void 0){H(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=KA(s),o,i;if(this.overrideSoundfont){let g=n===128?128:n-this.soundfontBankOffset,B=this.overrideSoundfont.getPresetNoFallback(g,A);B?(o=n,i=B,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 Eo(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 Bo(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 ho(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(KA(e),e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(KA(e),e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function Qo(){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:uA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",r.recognized)}function uo(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 fo(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:KA(e),lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,velocityOverride:e.velocityOverride,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType,keyMappings:this.keyModifierManager.getMappings()};this.post({messageType:uA.synthesizerSnapshot,messageData:A})}function mo(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation,this.keyModifierManager.setMappings(t.keyMappings);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.velocityOverride=A.velocityOverride,s.lockPreset=!1,jA(s,A.bank),this.programChange(e,A.program),s.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",r.info)}var It=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 Be.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Be.reloadSoundFont:this.reloadManager(e);break;case Be.deleteSoundFont:this.deleteSoundFont(e);break;case Be.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Me(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){H("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(s=>s.id===A);if(e===-1){H(`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:Me(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 gt=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,e,s,n,o,i,g,B){this.sampleData=A,this.playbackStep=e,this.cursor=s,this.rootKey=n,this.loopStart=o,this.loopEnd=i,this.end=g,this.loopingMode=B,this.isLooping=this.loopingMode===1||this.loopingMode===3}},Ne=class t{sample;filter=new le;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new UA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;realKey;constructor(A,e,s,n,o,i,g,B,h,d){this.sample=e,this.generators=h,this.modulatedGenerators=new Int16Array(h),this.modulators=d,this.velocity=n,this.midiNote=s,this.channelNumber=o,this.startTime=i,this.targetKey=g,this.realKey=B,this.volumeEnvelope=new TA(A,h[a.sustainVolEnv])}static copy(A,e){let s=A.sample,n=new gt(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.realKey,A.generators,A.modulators.map(o=>_.copy(o)))}};function po(t,A,e,s,n,o,i=!1){let g,B=s.cachedVoices[A][e],h=this.keyModifierManager.hasOverridePatch(t,A);if(B!==void 0&&!h)return B.map(l=>Ne.copy(l,n));let d=!0,u=s.preset;if(h){d=!1;let l=this.keyModifierManager.getPatch(t,A);u=this.soundfontManager.getPreset(l.bank,l.program)}return g=u.getSamplesAndGenerators(A,e).reduce((l,c)=>{if(c.sample.sampleData===void 0)return H(`Discarding invalid sample: ${c.sample.sampleName}`),l;let p=new Int16Array(60);for(let G=0;G<60;G++)p[G]=Ds(G,c.presetGenerators,c.instrumentGenerators);p[a.initialAttenuation]=Math.floor(p[a.initialAttenuation]*.4);let S=c.sample.samplePitch;p[a.overridingRootKey]>-1&&(S=p[a.overridingRootKey]);let w=A;p[a.keyNum]>-1&&(w=p[a.keyNum]);let k=c.sample.sampleLoopStartIndex,L=c.sample.sampleLoopEndIndex,R=p[a.sampleModes],N=new gt(c.sample.getAudioData(),c.sample.sampleRate/sampleRate*Math.pow(2,c.sample.samplePitchCorrection/1200),0,S,k,L,Math.floor(c.sample.sampleData.length)-1,R);return p[a.velocity]>-1&&(e=p[a.velocity]),i&&Ss([{Sample:c.sample.sampleName,Generators:p,Modulators:c.modulators.map(G=>G.debugString()),Velocity:e,TargetKey:w,MidiNote:A,WorkletSample:N}]),l.push(new Ne(sampleRate,N,A,e,t,n,w,o,p,c.modulators.map(G=>_.copy(G)))),l},[]),d&&(s.cachedVoices[A][e]=g.map(l=>Ne.copy(l,n))),g}var jo=4600,$o=2e3,yo=Math.PI/2;function So(t,A,e,s,n,o){if(isNaN(A[0]))return;let i=(Math.max(-500,Math.min(500,t.modulatedGenerators[a.pan]))+500)/1e3;t.currentPan+=(i-t.currentPan)*this.panSmoothingFactor;let g=this.currentGain,B=Math.cos(yo*t.currentPan)*g*this.panLeft,h=Math.sin(yo*t.currentPan)*g*this.panRight,d=t.modulatedGenerators[a.reverbEffectsSend]/jo*g,u=t.modulatedGenerators[a.chorusEffectsSend]/$o;if(d>0&&!this.oneOutputMode){let l=n[0],c=n[1];for(let p=0;p0&&!this.oneOutputMode){let l=o[0],c=o[1],p=B*u,S=h*u;for(let w=0;w0)for(let l=0;l0)for(let l=0;lthis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),VA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",r.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:uA.ready,messageData:void 0})}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,g,B,h,d;if(this.oneOutputMode){let l=e[0];i=o%16*2,g=l[i],B=l[i+1]}else i=o%this._outputsAmount+2,g=e[i][0],B=e[i][1],h=e[0],d=e[1];let u=n.voices;n.voices=[],u.forEach(l=>{this.renderVoice(n,l,g,B,h,d),l.finished||n.voices.push(l)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};Y.prototype.renderVoice=sn;Y.prototype.releaseVoice=on;Y.prototype.voiceKilling=nn;Y.prototype.getWorkletVoices=po;Y.prototype.handleMessage=In;Y.prototype.sendChannelProperties=Cn;Y.prototype.callEvent=gn;Y.prototype.systemExclusive=En;Y.prototype.noteOn=hn;Y.prototype.noteOff=Qn;Y.prototype.polyPressure=wn;Y.prototype.killNote=cn;Y.prototype.stopAll=ln;Y.prototype.stopAllChannels=un;Y.prototype.muteChannel=Nn;Y.prototype.setVibrato=Ln;Y.prototype.disableAndLockGSNRPN=bn;Y.prototype.dataEntryCoarse=Un;Y.prototype.dataEntryFine=Tn;Y.prototype.createWorkletChannel=ks;Y.prototype.controllerChange=Rn;Y.prototype.channelPressure=kn;Y.prototype.resetAllControllers=Hn;Y.prototype.resetControllers=Yn;Y.prototype.resetParameters=Jn;Y.prototype.setMasterGain=xn;Y.prototype.setMasterPan=Mn;Y.prototype.setMIDIVolume=Gn;Y.prototype.transposeAllChannels=dn;Y.prototype.transposeChannel=fn;Y.prototype.setChannelTuning=mn;Y.prototype.setChannelTuningSemitones=pn;Y.prototype.setMasterTuning=yn;Y.prototype.setModulationDepth=Sn;Y.prototype.pitchWheel=Dn;Y.prototype.setOctaveTuning=Fn;Y.prototype.programChange=Co;Y.prototype.getPreset=Eo;Y.prototype.setPreset=Bo;Y.prototype.setDrums=ho;Y.prototype.reloadSoundFont=lo;Y.prototype.clearSoundFont=co;Y.prototype.setEmbeddedSoundFont=uo;Y.prototype.sendPresetList=Qo;Y.prototype.sendSynthesizerSnapshot=fo;Y.prototype.applySynthesizerSnapshot=mo;Y.prototype.panVoice=So;registerProcessor(ws,Y);m("%cProcessor succesfully registered!",r.recognized); +`+this.soundFontInfo.ISBJ,delete this.soundFontInfo.ISBJ);for(let[B,h]of Object.entries(this.soundFontInfo))m(`%c"${B}": %c"${h}"`,r.info,r.recognized);let o=s.find(B=>B.header==="colh");o||(V(),this.parsingError("No colh chunk!")),this.instrumentAmount=D(o.chunkData,4),m(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let i=DA(s,"wvpl");i||(V(),this.parsingError("No wvpl chunk!")),this.readDLSSamples(i);let g=DA(s,"lins");g||(V(),this.parsingError("No lins chunk!")),this.readDLSInstrumentList(g),this.presets.sort((B,h)=>B.program-h.program+(B.bank-h.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),V()}verifyHeader(A,e){A.header.toLowerCase()!==e.toLowerCase()&&(V(),this.parsingError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,e){A.toLowerCase()!==e.toLowerCase()&&(V(),this.parsingError(`FourCC error: Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`))}parsingError(A){throw new Error(`DLS parse error: ${A} The file may be corrupted.`)}};WA.prototype.readDLSInstrumentList=jn;WA.prototype.readDLSInstrument=$n;WA.prototype.readRegion=so;WA.prototype.readLart=to;WA.prototype.readDLSSamples=oo;var qt=class extends me{constructor(A,e,s,n,o,i,g,B,h,d,u,l,c){super(A,i,g,B,h,d,n-e/2,o-e/2),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=s,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=u,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=c}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);try{let n=VA.decode(s.buffer);this.sampleData=n.data[0]}catch(n){throw new Error(`Ogg Vorbis decode error: ${n}`)}}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 H("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=zo(n,t.chunkData,A,e);s.push(o),n++}return s.length>1&&s.pop(),s}function zo(t,A,e,s){let n=O(A,20),o=D(A,4)*2,i=D(A,4)*2,g=D(A,4),B=D(A,4),h=D(A,4),d=A[A.currentIndex++];d===255&&(d=60);let u=Ns(A[A.currentIndex++]),l=D(A,2),c=D(A,2);return new qt(n,o,i,g,B,h,d,u,l,c,e,t,s)}var Pt=class extends U{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=$A(A[e+2],A[e+3]),A.currentIndex+=4}};function Kt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Pt(t.chunkData));return A.length>1&&A.pop(),A}var Vt=class extends fe{constructor(A){super(),this.instrumentName=O(A.chunkData,20).trim(),this.instrumentZoneIndex=D(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let s=this.instrumentZoneIndex;st.chunkData.currentIndex;){let s=new Vt(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 Ot=class extends Ae{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===a.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ao(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Ot(t.chunkData);if(n.length>0){let i=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(i,g),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 Zt=class extends de{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;es.generatorType===a.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function Io(t,A,e,s){let n=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Zt(t.chunkData);if(n.length>0){let i=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(i,g),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 Xt=class extends ue{constructor(A,e){super(e),this.presetName=O(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=D(A.chunkData,2),this.bank=D(A.chunkData,2),this.presetZoneStartIndex=D(A.chunkData,2),this.library=D(A.chunkData,4),this.genre=D(A.chunkData,4),this.morphology=D(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;st.chunkData.currentIndex;){let n=new Xt(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 Wt=class extends _{constructor(A){super({srcEnum:D(A,2),dest:D(A,2),amt:$A(A[A.currentIndex++],A[A.currentIndex++]),secSrcEnum:D(A,2),transform:D(A,2)})}};function at(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Wt(t.chunkData));return A}var It=class extends ie{constructor(A,e=!0){super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new J(A),se("%cParsing SoundFont...",r.info),this.dataArray||(V(),this.parsingError("No data provided!"));let s=Z(this.dataArray,!1);this.verifyHeader(s,"riff");let n=O(this.dataArray,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw V(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let o=n==="sfpk",i=Z(this.dataArray);for(this.verifyHeader(i,"list"),O(i.chunkData,4);i.chunkData.length>i.chunkData.currentIndex;){let eA=Z(i.chunkData),cA;switch(eA.header.toLowerCase()){case"ifil":case"iver":cA=`${D(eA.chunkData,2)}.${D(eA.chunkData,2)}`,this.soundFontInfo[eA.header]=cA;break;case"icmt":cA=O(eA.chunkData,eA.chunkData.length,void 0,!1),this.soundFontInfo[eA.header]=cA;break;case"dmod":let IA=at(eA);IA.pop(),cA=`Modulators: ${IA.length}`;let mA=this.defaultModulators;this.defaultModulators=IA,this.defaultModulators.push(...mA.filter(Le=>!this.defaultModulators.find(xA=>_.isIdentical(Le,xA)))),this.soundFontInfo[eA.header]=eA.chunkData;break;default:cA=O(eA.chunkData,eA.chunkData.length),this.soundFontInfo[eA.header]=cA}m(`%c"${eA.header}": %c"${cA}"`,r.info,r.recognized)}let g=Z(this.dataArray,!1);this.verifyHeader(g,"list"),this.verifyText(O(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",r.warn);let B=Z(this.dataArray,!1);this.verifyHeader(B,"smpl");let h;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{h=VA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+g.size-12)).data[0]}catch(eA){throw V(),new Error(`SF2Pack Ogg Vorbis decode error: ${eA}`)}m(`%cDecoded the smpl chunk! Length: %c${h.length}`,r.info,r.value)}else h=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${g.size-12}`,r.info,r.value),this.dataArray.currentIndex+=g.size-12,m("%cLoading preset data chunk...",r.warn);let d=Z(this.dataArray);this.verifyHeader(d,"list"),O(d.chunkData,4);let u=Z(d.chunkData);this.verifyHeader(u,"phdr");let l=Z(d.chunkData);this.verifyHeader(l,"pbag");let c=Z(d.chunkData);this.verifyHeader(c,"pmod");let p=Z(d.chunkData);this.verifyHeader(p,"pgen");let y=Z(d.chunkData);this.verifyHeader(y,"inst");let w=Z(d.chunkData);this.verifyHeader(w,"ibag");let k=Z(d.chunkData);this.verifyHeader(k,"imod");let L=Z(d.chunkData);this.verifyHeader(L,"igen");let R=Z(d.chunkData);this.verifyHeader(R,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...ro(R,h,!o));let N=Kt(L),G=at(k),C=ao(w,N,G,this.samples);this.instruments=io(y,C);let iA=Kt(p),z=at(c),AA=Io(l,iA,z,this.instruments);this.presets.push(...go(u,AA,this.defaultModulators)),this.presets.sort((eA,cA)=>eA.program-cA.program+(eA.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),V(),o&&delete this.dataArray}verifyHeader(A,e){A.header.toLowerCase()!==e.toLowerCase()&&(V(),this.parsingError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,e){A.toLowerCase()!==e.toLowerCase()&&(V(),this.parsingError(`Invalid FourCC: Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"\``))}};function Ne(t){let A=t.slice(8,12),e=new J(A);return O(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new It(t,!1)}function Co(t,A,e=!1){let s=this.workletProcessorChannels[t];if(s===void 0){H(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=KA(s),o,i;if(this.overrideSoundfont){let g=n===128?128:n-this.soundfontBankOffset,B=this.overrideSoundfont.getPresetNoFallback(g,A);B?(o=n,i=B,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 Eo(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 Bo(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 ho(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(KA(e),e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(KA(e),e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function Qo(){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:uA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",r.recognized)}function uo(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 fo(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:KA(e),lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,velocityOverride:e.velocityOverride,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType,keyMappings:this.keyModifierManager.getMappings()};this.post({messageType:uA.synthesizerSnapshot,messageData:A})}function mo(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation,this.keyModifierManager.setMappings(t.keyMappings);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.velocityOverride=A.velocityOverride,s.lockPreset=!1,zA(s,A.bank),this.programChange(e,A.program),s.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",r.info)}var gt=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 Ee.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ee.reloadSoundFont:this.reloadManager(e);break;case Ee.deleteSoundFont:this.deleteSoundFont(e);break;case Ee.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ne(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){H("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(s=>s.id===A);if(e===-1){H(`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:Ne(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 Ct=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,e,s,n,o,i,g,B){this.sampleData=A,this.playbackStep=e,this.cursor=s,this.rootKey=n,this.loopStart=o,this.loopEnd=i,this.end=g,this.loopingMode=B,this.isLooping=this.loopingMode===1||this.loopingMode===3}},be=class t{sample;filter=new le;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new UA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;realKey;constructor(A,e,s,n,o,i,g,B,h,d){this.sample=e,this.generators=h,this.modulatedGenerators=new Int16Array(h),this.modulators=d,this.velocity=n,this.midiNote=s,this.channelNumber=o,this.startTime=i,this.targetKey=g,this.realKey=B,this.volumeEnvelope=new TA(A,h[a.sustainVolEnv])}static copy(A,e){let s=A.sample,n=new Ct(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.realKey,A.generators,A.modulators.map(o=>_.copy(o)))}};function po(t,A,e,s,n,o,i=!1){let g,B=s.cachedVoices[A][e],h=this.keyModifierManager.hasOverridePatch(t,A);if(B!==void 0&&!h)return B.map(l=>be.copy(l,n));let d=!0,u=s.preset;if(h){d=!1;let l=this.keyModifierManager.getPatch(t,A);u=this.soundfontManager.getPreset(l.bank,l.program)}return g=u.getSamplesAndGenerators(A,e).reduce((l,c)=>{if(c.sample.sampleData===void 0)return H(`Discarding invalid sample: ${c.sample.sampleName}`),l;let p=new Int16Array(60);for(let G=0;G<60;G++)p[G]=Ds(G,c.presetGenerators,c.instrumentGenerators);p[a.initialAttenuation]=Math.floor(p[a.initialAttenuation]*.4);let y=c.sample.samplePitch;p[a.overridingRootKey]>-1&&(y=p[a.overridingRootKey]);let w=A;p[a.keyNum]>-1&&(w=p[a.keyNum]);let k=c.sample.sampleLoopStartIndex,L=c.sample.sampleLoopEndIndex,R=p[a.sampleModes],N=new Ct(c.sample.getAudioData(),c.sample.sampleRate/sampleRate*Math.pow(2,c.sample.samplePitchCorrection/1200),0,y,k,L,Math.floor(c.sample.sampleData.length)-1,R);return p[a.velocity]>-1&&(e=p[a.velocity]),i&&Ss([{Sample:c.sample.sampleName,Generators:p,Modulators:c.modulators.map(G=>G.debugString()),Velocity:e,TargetKey:w,MidiNote:A,WorkletSample:N}]),l.push(new be(sampleRate,N,A,e,t,n,w,o,p,c.modulators.map(G=>_.copy(G)))),l},[]),d&&(s.cachedVoices[A][e]=g.map(l=>be.copy(l,n))),g}var jo=4600,$o=2e3,yo=Math.PI/2;function So(t,A,e,s,n,o){if(isNaN(A[0]))return;let i=(Math.max(-500,Math.min(500,t.modulatedGenerators[a.pan]))+500)/1e3;t.currentPan+=(i-t.currentPan)*this.panSmoothingFactor;let g=this.currentGain,B=Math.cos(yo*t.currentPan)*g*this.panLeft,h=Math.sin(yo*t.currentPan)*g*this.panRight,d=t.modulatedGenerators[a.reverbEffectsSend]/jo*g,u=t.modulatedGenerators[a.chorusEffectsSend]/$o;if(d>0&&!this.oneOutputMode){let l=n[0],c=n[1];for(let p=0;p0&&!this.oneOutputMode){let l=o[0],c=o[1],p=B*u,y=h*u;for(let w=0;w0)for(let l=0;l0)for(let l=0;lthis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),VA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",r.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:uA.ready,messageData:void 0})}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,g,B,h,d;if(this.oneOutputMode){let l=e[0];i=o%16*2,g=l[i],B=l[i+1]}else i=o%this._outputsAmount+2,g=e[i][0],B=e[i][1],h=e[0],d=e[1];let u=n.voices;n.voices=[],u.forEach(l=>{this.renderVoice(n,l,g,B,h,d),l.finished||n.voices.push(l)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};Y.prototype.renderVoice=sn;Y.prototype.releaseVoice=on;Y.prototype.voiceKilling=nn;Y.prototype.getWorkletVoices=po;Y.prototype.handleMessage=In;Y.prototype.sendChannelProperties=Cn;Y.prototype.callEvent=gn;Y.prototype.systemExclusive=En;Y.prototype.noteOn=hn;Y.prototype.noteOff=Qn;Y.prototype.polyPressure=wn;Y.prototype.killNote=cn;Y.prototype.stopAll=ln;Y.prototype.stopAllChannels=un;Y.prototype.muteChannel=Nn;Y.prototype.setVibrato=Ln;Y.prototype.disableAndLockGSNRPN=bn;Y.prototype.dataEntryCoarse=Un;Y.prototype.dataEntryFine=Tn;Y.prototype.createWorkletChannel=ks;Y.prototype.controllerChange=Rn;Y.prototype.channelPressure=kn;Y.prototype.resetAllControllers=Hn;Y.prototype.resetControllers=Yn;Y.prototype.resetParameters=Jn;Y.prototype.setMasterGain=xn;Y.prototype.setMasterPan=Mn;Y.prototype.setMIDIVolume=Gn;Y.prototype.transposeAllChannels=dn;Y.prototype.transposeChannel=fn;Y.prototype.setChannelTuning=mn;Y.prototype.setChannelTuningSemitones=pn;Y.prototype.setMasterTuning=yn;Y.prototype.setModulationDepth=Sn;Y.prototype.pitchWheel=Dn;Y.prototype.setOctaveTuning=Fn;Y.prototype.programChange=Co;Y.prototype.getPreset=Eo;Y.prototype.setPreset=Bo;Y.prototype.setDrums=ho;Y.prototype.reloadSoundFont=lo;Y.prototype.clearSoundFont=co;Y.prototype.setEmbeddedSoundFont=uo;Y.prototype.sendPresetList=Qo;Y.prototype.sendSynthesizerSnapshot=fo;Y.prototype.applySynthesizerSnapshot=mo;Y.prototype.panVoice=So;registerProcessor(ws,Y);m("%cProcessor succesfully registered!",r.recognized); diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/reset_controllers.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/reset_controllers.js index 566e239..99e53a4 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/reset_controllers.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/reset_controllers.js @@ -143,7 +143,20 @@ export function resetControllers(channel) channelObject.keyCentTuning.fill(0); // reset the array - channelObject.midiControllers.set(resetArray); + for (let i = 0; i < resetArray.length; i++) + { + const resetValue = resetArray[i]; + if (channelObject.midiControllers[i] !== resetValue && i < 127) + { + // call cc change if reset + this.callEvent("controllerchange", { + channel: channel, + controllerNumber: i, + controllerValue: resetValue >> 7 + }); + } + channelObject.midiControllers[i] = resetValue; + } channelObject.channelVibrato = { rate: 0, depth: 0, delay: 0 }; channelObject.holdPedal = false;