From 9366f3d6add5603687fdfa2cfbb6140c2f3467bc Mon Sep 17 00:00:00 2001 From: spessasus Date: Mon, 7 Oct 2024 18:54:57 +0200 Subject: [PATCH] Fix filter optimization causing click Resolves #53 --- README.md | 2 +- package.json | 2 +- src/spessasynth_lib/README.md | 138 +++++++----------- .../synthetizer/worklet_processor.min.js | 18 +-- .../worklet_methods/voice_control.js | 11 +- .../worklet_utilities/lowpass_filter.js | 13 +- 6 files changed, 79 insertions(+), 105 deletions(-) diff --git a/README.md b/README.md index 65e3372e..8a0acc01 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ This repository contains both the library and a complete musical web application - Suitable for both **real-time** and **offline** synthesis - **Excellent SoundFont support:** - **Full Generator Support** - - **Modulator Support:** *First (to my knowledge) JavaScript SoundFont synth with that feature!* + - **Full Modulator Support:** *First (to my knowledge) JavaScript SoundFont synth with that feature!* - **SoundFont3 Support:** Play compressed SoundFonts! - **Experimental SF2Pack Support:** Play soundfonts compressed with BASSMIDI! (*Note: only works with vorbis compression*) - **Can load very large SoundFonts:** up to 4GB! *Note: Only Firefox handles this well; Chromium has a hard-coded memory limit* diff --git a/package.json b/package.json index 22b0fe98..ab269247 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "SpessaSynth", - "version": "3.20.44", + "version": "3.21.0", "type": "module", "scripts": { "start": "node src/website/server/server.js" diff --git a/src/spessasynth_lib/README.md b/src/spessasynth_lib/README.md index cfed7f21..0b61d472 100644 --- a/src/spessasynth_lib/README.md +++ b/src/spessasynth_lib/README.md @@ -33,55 +33,37 @@ document.getElementById("button").onclick = async () => ## Current Features ### Easy Integration - - **Modular design:** Easy integration into other projects (load what you need) -- **[Detailed documentation:](https://github.com/spessasus/SpessaSynth/wiki/Home)** - With [examples!](https://github.com/spessasus/SpessaSynth/wiki/Usage-As-Library#examples) -- **Easy to Use:** basic setup is - just [two lines of code!](https://github.com/spessasus/SpessaSynth/wiki/Usage-As-Library#minimal-setup) +- **[Detailed documentation:](https://github.com/spessasus/SpessaSynth/wiki/Home)** With [examples!](https://github.com/spessasus/SpessaSynth/wiki/Usage-As-Library#examples) +- **Easy to Use:** basic setup is just [two lines of code!](https://github.com/spessasus/SpessaSynth/wiki/Usage-As-Library#minimal-setup) - **No dependencies:** _batteries included!_ ### Powerful SoundFont Synthesizer - - Suitable for both **real-time** and **offline** synthesis - **Excellent SoundFont support:** - - **Generator Support** - - **Modulator Support:** *First (to my knowledge) JavaScript SoundFont synth with that feature!* - - **SoundFont3 Support:** Play compressed SoundFonts! - - **Experimental SF2Pack Support:** Play soundfonts compressed with BASSMIDI! (*Note: only works with vorbis - compression*) - - **Can load very large SoundFonts:** up to 4GB! *Note: Only Firefox handles this well; Chromium has a hard-coded - memory limit* + - **Full Generator Support** + - **Full Modulator Support:** *First (to my knowledge) JavaScript SoundFont synth with that feature!* + - **SoundFont3 Support:** Play compressed SoundFonts! + - **Experimental SF2Pack Support:** Play soundfonts compressed with BASSMIDI! (*Note: only works with vorbis compression*) + - **Can load very large SoundFonts:** up to 4GB! *Note: Only Firefox handles this well; Chromium has a hard-coded memory limit* - **Soundfont manager:** Stack multiple soundfonts! - **DLS Level 1 and 2 Support:** *internally converted to sf2* -- **Reverb and chorus support: - ** [customizable!](https://github.com/spessasus/SpessaSynth/wiki/Synthetizer-Class#effects-configuration-object) -- **Export audio files** - using [OfflineAudioContext](https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext) -- - * - -*[Custom modulators for additional controllers](https://github.com/spessasus/SpessaSynth/wiki/Modulator-Class#default-modulators): -** Why not? - -- **Written using AudioWorklets:** - - Runs in a **separate thread** for maximum performance - - Supported by all modern browsers +- **Reverb and chorus support:** [customizable!](https://github.com/spessasus/SpessaSynth/wiki/Synthetizer-Class#effects-configuration-object) +- **Export audio files** using [OfflineAudioContext](https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext) +- **[Custom modulators for additional controllers](https://github.com/spessasus/SpessaSynth/wiki/Modulator-Class#default-modulators):** Why not? +- **Written using AudioWorklets:** + - Runs in a **separate thread** for maximum performance + - Supported by all modern browsers - **Unlimited channel count:** Your CPU is the limit! - **Excellent MIDI Standards Support:** - - **MIDI Controller Support:** Default supported - controllers [here](https://github.com/spessasus/SpessaSynth/wiki/MIDI-Implementation#supported-controllers) - - **MIDI Tuning Standard Support: - ** [more info here](https://github.com/spessasus/SpessaSynth/wiki/MIDI-Implementation#midi-tuning-standard) - - [Full **RPN** and limited **NRPN - ** support](https://github.com/spessasus/SpessaSynth/wiki/MIDI-Implementation#supported-registered-parameters) - - Supports some [**Roland GS** and **Yamaha XG - ** system exclusives](https://github.com/spessasus/SpessaSynth/wiki/MIDI-Implementation#supported-system-exclusives) + - **MIDI Controller Support:** Default supported controllers [here](https://github.com/spessasus/SpessaSynth/wiki/MIDI-Implementation#supported-controllers) + - **MIDI Tuning Standard Support:** [more info here](https://github.com/spessasus/SpessaSynth/wiki/MIDI-Implementation#midi-tuning-standard) + - [Full **RPN** and limited **NRPN** support](https://github.com/spessasus/SpessaSynth/wiki/MIDI-Implementation#supported-registered-parameters) + - Supports some [**Roland GS** and **Yamaha XG** system exclusives](https://github.com/spessasus/SpessaSynth/wiki/MIDI-Implementation#supported-system-exclusives) - **High-performance mode:** Play Rush E! _note: may kill your browser ;)_ ### Built-in Powerful and Fast Sequencer - - **Supports MIDI formats 0, 1, and 2:** _note: format 2 support is experimental as it's very, very rare_ - **[Multi-Port MIDI](https://github.com/spessasus/SpessaSynth/wiki/About-Multi-Port) support:** More than 16 channels! - **Smart preloading:** Only preloads the samples used in the MIDI file for smooth playback (down to key and velocity!) @@ -91,68 +73,54 @@ document.getElementById("button").onclick = async () => - **Loop points support:** Ensures seamless loops ### Read and Write SoundFont and MIDI Files with Ease - #### Read and write MIDI files - -- **Smart name detection:** Handles incorrectly formatted and non-standard track names -- **Raw name available:** Decode in any encoding! *(Kanji? No problem!)* -- **Port detection during load time:** Manage ports and channels easily! -- **Used channels on track:** Quickly determine which channels are used -- **Key range detection:** Detect the key range of the MIDI -- **Easy MIDI editing:** - Use [helper functions](https://github.com/spessasus/SpessaSynth/wiki/Writing-MIDI-Files#modifymidi) to modify the song - to your needs! -- **Loop detection:** Automatically detects loops in MIDIs (e.g., from _Touhou Project_) -- **First note detection:** Skip unnecessary silence at the start by jumping to the first note! -- **[Write MIDI files from scratch](https://github.com/spessasus/SpessaSynth/wiki/Creating-MIDI-Files)** -- **Easy saving:** Save with - just [one function!](https://github.com/spessasus/SpessaSynth/wiki/Writing-MIDI-Files#writemidifile) + - **Smart name detection:** Handles incorrectly formatted and non-standard track names + - **Raw name available:** Decode in any encoding! *(Kanji? No problem!)* + - **Port detection during load time:** Manage ports and channels easily! + - **Used channels on track:** Quickly determine which channels are used + - **Key range detection:** Detect the key range of the MIDI + - **Easy MIDI editing:** Use [helper functions](https://github.com/spessasus/SpessaSynth/wiki/Writing-MIDI-Files#modifymidi) to modify the song to your needs! + - **Loop detection:** Automatically detects loops in MIDIs (e.g., from _Touhou Project_) + - **First note detection:** Skip unnecessary silence at the start by jumping to the first note! + - **[Write MIDI files from scratch](https://github.com/spessasus/SpessaSynth/wiki/Creating-MIDI-Files)** + - **Easy saving:** Save with just [one function!](https://github.com/spessasus/SpessaSynth/wiki/Writing-MIDI-Files#writemidifile) #### Read and write [RMID files with embedded SF2 soundfonts](https://github.com/spessasus/sf2-rmidi-specification#readme) - -- **[Level 4](https://github.com/spessasus/sf2-rmidi-specification#level-4) compliance:** Reads and writes *everything!* -- **Compression and trimming support:** Reduce a MIDI file with a 1GB soundfont to **as small as 5MB**! -- **DLS Version support:** The original legacy format with bank offset detection! -- **Automatic bank shifting and validation:** Every soundfont *just works!* -- **Metadata support:** Add title, artist, album name and cover and more! And of course read them too! *(In any - encoding!)* -- **Compatible with [Falcosoft Midi Player 6!](https://falcosoft.hu/softwares.html#midiplayer)** -- **Easy saving: - ** [As simple as saving a MIDI file!](https://github.com/spessasus/SpessaSynth/wiki/Writing-MIDI-Files#writermidi) + - **[Level 4](https://github.com/spessasus/sf2-rmidi-specification#level-4) compliance:** Reads and writes *everything!* + - **Compression and trimming support:** Reduce a MIDI file with a 1GB soundfont to **as small as 5MB**! + - **DLS Version support:** The original legacy format with bank offset detection! + - **Automatic bank shifting and validation:** Every soundfont *just works!* + - **Metadata support:** Add title, artist, album name and cover and more! And of course read them too! *(In any encoding!)* + - **Compatible with [Falcosoft Midi Player 6!](https://falcosoft.hu/softwares.html#midiplayer)** + - **Easy saving:** [As simple as saving a MIDI file!](https://github.com/spessasus/SpessaSynth/wiki/Writing-MIDI-Files#writermidi) #### Read and write SoundFont2 files - -- **Easy info access:** Just - an [object of strings!](https://github.com/spessasus/SpessaSynth/wiki/SoundFont2-Class#soundfontinfo) -- **Smart trimming:** Trim the SoundFont to only include samples used in the MIDI *(down to key and velocity!)* -- **sf3 conversion:** Compress SoundFont2 files to SoundFont3 with variable quality! -- **Easy saving:** Also just [one function!](https://github.com/spessasus/SpessaSynth/wiki/SoundFont2-Class#write) + - **Easy info access:** Just an [object of strings!](https://github.com/spessasus/SpessaSynth/wiki/SoundFont2-Class#soundfontinfo) + - **Smart trimming:** Trim the SoundFont to only include samples used in the MIDI *(down to key and velocity!)* + - **sf3 conversion:** Compress SoundFont2 files to SoundFont3 with variable quality! + - **Easy saving:** Also just [one function!](https://github.com/spessasus/SpessaSynth/wiki/SoundFont2-Class#write) #### Read and write SoundFont3 files - -- Same features as SoundFont2 but with now with **Ogg Vorbis compression!** -- **Variable compression quality:** You choose between file size and quality! -- **Compression preserving:** Avoid decompressing and recompressing uncompressed samples for minimal quality loss! + - Same features as SoundFont2 but with now with **Ogg Vorbis compression!** + - **Variable compression quality:** You choose between file size and quality! + - **Compression preserving:** Avoid decompressing and recompressing uncompressed samples for minimal quality loss! #### Read and play DLS Level 1 or 2 files - -- Read DLS (DownLoadable Sounds) files as SF2 files! -- **Works like a normal soundfont:** *Saving it as sf2 is - still [just one function!](https://github.com/spessasus/SpessaSynth/wiki/SoundFont2-Class#write)* -- Converts articulators to both **modulators** and **generators**! -- Works with both unsigned 8-bit samples and signed 16-bit samples! -- **Covers special generator cases:** *such as modLfoToPitch*! -- **Correct volume:** *looking at you, Viena and gm.sf2!* -- Support built right into the synthesizer! + - Read DLS (DownLoadable Sounds) files as SF2 files! + - **Works like a normal soundfont:** *Saving it as sf2 is still [just one function!](https://github.com/spessasus/SpessaSynth/wiki/SoundFont2-Class#write)* + - Converts articulators to both **modulators** and **generators**! + - Works with both unsigned 8-bit samples and signed 16-bit samples! + - **Covers special generator cases:** *such as modLfoToPitch*! + - **Correct volume:** *looking at you, Viena and gm.sf2!* + - Support built right into the synthesizer! ### Export MIDI as WAV + - Save the MIDI file as WAV audio! + - **Metadata support:** *Embed metadata such as title, artist, album and more!* + - **Cue points:** *Write MIDI loop points as cue points!* + - **Loop multiple times:** *Render two (or more) loops into the file for seamless transitions!* + - *That's right, saving as WAV is also [just one function!](https://github.com/spessasus/SpessaSynth/wiki/Writing-Wave-Files#audiobuffertowav)* -- Save the MIDI file as WAV audio! -- **Metadata support:** *Embed metadata such as title, artist, album and more!* -- **Cue points:** *Write MIDI loop points as cue points!* -- **Loop multiple times:** *Render two (or more) loops into the file for seamless transitions!* -- *That's right, saving as WAV is - also [just one function!](https://github.com/spessasus/SpessaSynth/wiki/Writing-Wave-Files#audiobuffertowav)* # License diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index 7318e049..7a86a8c5 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -1,4 +1,4 @@ -var Bn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>(typeof require<"u"?require:A)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H=class extends Uint8Array{currentIndex;constructor(A){super(A),this.currentIndex=0}};function ke(t){let A=t.reduce((s,o)=>s+o.length,0),e=new H(A),n=0;for(let s of t)e.set(s,n),n+=s.length;return e}function mt(t){t=Math.floor(t);let A=Math.floor(t/60),e=Math.round(t-A*60);return{minutes:A,seconds:e,time:`${A.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}}function hn(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function lA(t){let A="";for(let e=0;e=128&&A<=224&&(n=e,s=A),{status:s,channel:n}}var m={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,reverbDepth:91,tremoloDepth:92,chorusDepth:93,detuneDepth:94,phaserDepth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},cn={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var eA={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25},ae={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},TA=-1,yA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var ln=!1,un=!0,qe=!1,dn=!0;function fn(t,A,e,n){ln=t,un=A,qe=e,dn=n}function p(...t){ln&&console.info(...t)}function U(...t){un&&console.warn(...t)}function mn(...t){dn&&console.table(...t)}function te(...t){qe&&console.group(...t)}function SA(...t){qe&&console.groupCollapsed(...t)}function X(){qe&&console.groupEnd()}var Ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var g={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},L=[];L[g.startAddrsOffset]={min:0,max:32768,def:0};L[g.endAddrOffset]={min:-32768,max:32768,def:0};L[g.startloopAddrsOffset]={min:-32768,max:32768,def:0};L[g.endloopAddrsOffset]={min:-32768,max:32768,def:0};L[g.startAddrsCoarseOffset]={min:0,max:32768,def:0};L[g.modLfoToPitch]={min:-12e3,max:12e3,def:0};L[g.vibLfoToPitch]={min:-12e3,max:12e3,def:0};L[g.modEnvToPitch]={min:-12e3,max:12e3,def:0};L[g.initialFilterFc]={min:1500,max:13500,def:13500};L[g.initialFilterQ]={min:0,max:960,def:0};L[g.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};L[g.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};L[g.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};L[g.modLfoToVolume]={min:-960,max:960,def:0};L[g.chorusEffectsSend]={min:0,max:1e3,def:0};L[g.reverbEffectsSend]={min:0,max:1e3,def:0};L[g.pan]={min:-500,max:500,def:0};L[g.delayModLFO]={min:-12e3,max:5e3,def:-12e3};L[g.freqModLFO]={min:-16e3,max:4500,def:0};L[g.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};L[g.freqVibLFO]={min:-16e3,max:4500,def:0};L[g.delayModEnv]={min:-32768,max:5e3,def:-32768};L[g.attackModEnv]={min:-32768,max:8e3,def:-32768};L[g.holdModEnv]={min:-12e3,max:5e3,def:-12e3};L[g.decayModEnv]={min:-12e3,max:8e3,def:-12e3};L[g.sustainModEnv]={min:0,max:1e3,def:0};L[g.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};L[g.keyNumToModEnvHold]={min:-1200,max:1200,def:0};L[g.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};L[g.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};L[g.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};L[g.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};L[g.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};L[g.sustainVolEnv]={min:0,max:1440,def:0};L[g.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};L[g.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};L[g.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};L[g.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};L[g.keyNum]={min:-1,max:127,def:-1};L[g.velocity]={min:-1,max:127,def:-1};L[g.initialAttenuation]={min:-250,max:1440,def:0};L[g.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};L[g.coarseTune]={min:-120,max:120,def:0};L[g.fineTune]={min:-12700,max:12700,def:0};L[g.scaleTuning]={min:0,max:1200,def:100};L[g.exclusiveClass]={min:0,max:99999,def:0};L[g.overridingRootKey]={min:-1,max:127,def:-1};var b=class{generatorType=g.INVALID;generatorValue=0;constructor(A=g.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let n=L[A];this.generatorValue=Math.round(e),n!==void 0&&(this.generatorValue=Math.max(n.min,Math.min(n.max,this.generatorValue)))}};function pn(t,A,e){let n=L[t]||{min:0,max:32768,def:0},s=A.find(B=>B.generatorType===t),o=0;s&&(o=s.generatorValue);let i=e.find(B=>B.generatorType===t),C=n.def;i&&(C=i.generatorValue);let c=C+o;return t===g.initialAttenuation?c:Math.max(n.min,Math.min(n.max,c))}var P={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},QA={linear:0,concave:1,convex:2,switch:3},$=class t{currentValue=0;constructor(A){this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform,this.modulatorDestination>58&&(this.modulatorDestination=g.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(A){return new t({srcEnum:A.sourceEnum,secSrcEnum:A.secondarySourceEnum,transform:A.transformType,amt:A.transformAmount,dest:A.modulatorDestination})}static isIdentical(A,e){return A.sourceEnum===e.sourceEnum&&A.modulatorDestination===e.modulatorDestination&&A.secondarySourceEnum===e.secondarySourceEnum&&A.transformType===e.transformType}sumTransform(A){return new t({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(s,o){return Object.keys(s).find(i=>s[i]===o)}let e=A(QA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(m,this.sourceIndex):e+=A(P,this.sourceIndex);let n=A(QA,this.secSrcCurveType);return n+=this.secSrcPolarity===0?" unipolar ":" bipolar ",n+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?n+=A(m,this.secSrcIndex):n+=A(P,this.secSrcIndex),`Modulator: +var Bn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>(typeof require<"u"?require:A)[e]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var H=class extends Uint8Array{currentIndex;constructor(A){super(A),this.currentIndex=0}};function ke(t){let A=t.reduce((s,o)=>s+o.length,0),e=new H(A),n=0;for(let s of t)e.set(s,n),n+=s.length;return e}function mt(t){t=Math.floor(t);let A=Math.floor(t/60),e=Math.round(t-A*60);return{minutes:A,seconds:e,time:`${A.toString().padStart(2,"0")}:${e.toString().padStart(2,"0")}`}}function hn(t){return t.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}function uA(t){let A="";for(let e=0;e=128&&A<=224&&(n=e,s=A),{status:s,channel:n}}var m={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,reverbDepth:91,tremoloDepth:92,chorusDepth:93,detuneDepth:94,phaserDepth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},cn={8:2,9:2,10:2,11:2,12:1,13:1,14:2};var eA={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25},ae={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},TA=-1,yA={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var ln=!1,un=!0,qe=!1,dn=!0;function fn(t,A,e,n){ln=t,un=A,qe=e,dn=n}function p(...t){ln&&console.info(...t)}function U(...t){un&&console.warn(...t)}function mn(...t){dn&&console.table(...t)}function te(...t){qe&&console.group(...t)}function SA(...t){qe&&console.groupCollapsed(...t)}function Z(){qe&&console.groupEnd()}var Ie={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var g={INVALID:-1,startAddrsOffset:0,endAddrOffset:1,startloopAddrsOffset:2,endloopAddrsOffset:3,startAddrsCoarseOffset:4,modLfoToPitch:5,vibLfoToPitch:6,modEnvToPitch:7,initialFilterFc:8,initialFilterQ:9,modLfoToFilterFc:10,modEnvToFilterFc:11,endAddrsCoarseOffset:12,modLfoToVolume:13,unused1:14,chorusEffectsSend:15,reverbEffectsSend:16,pan:17,unused2:18,unused3:19,unused4:20,delayModLFO:21,freqModLFO:22,delayVibLFO:23,freqVibLFO:24,delayModEnv:25,attackModEnv:26,holdModEnv:27,decayModEnv:28,sustainModEnv:29,releaseModEnv:30,keyNumToModEnvHold:31,keyNumToModEnvDecay:32,delayVolEnv:33,attackVolEnv:34,holdVolEnv:35,decayVolEnv:36,sustainVolEnv:37,releaseVolEnv:38,keyNumToVolEnvHold:39,keyNumToVolEnvDecay:40,instrument:41,reserved1:42,keyRange:43,velRange:44,startloopAddrsCoarseOffset:45,keyNum:46,velocity:47,initialAttenuation:48,reserved2:49,endloopAddrsCoarseOffset:50,coarseTune:51,fineTune:52,sampleID:53,sampleModes:54,reserved3:55,scaleTuning:56,exclusiveClass:57,overridingRootKey:58,unused5:59,endOper:60},L=[];L[g.startAddrsOffset]={min:0,max:32768,def:0};L[g.endAddrOffset]={min:-32768,max:32768,def:0};L[g.startloopAddrsOffset]={min:-32768,max:32768,def:0};L[g.endloopAddrsOffset]={min:-32768,max:32768,def:0};L[g.startAddrsCoarseOffset]={min:0,max:32768,def:0};L[g.modLfoToPitch]={min:-12e3,max:12e3,def:0};L[g.vibLfoToPitch]={min:-12e3,max:12e3,def:0};L[g.modEnvToPitch]={min:-12e3,max:12e3,def:0};L[g.initialFilterFc]={min:1500,max:13500,def:13500};L[g.initialFilterQ]={min:0,max:960,def:0};L[g.modLfoToFilterFc]={min:-12e3,max:12e3,def:0};L[g.modEnvToFilterFc]={min:-12e3,max:12e3,def:0};L[g.endAddrsCoarseOffset]={min:-32768,max:32768,def:0};L[g.modLfoToVolume]={min:-960,max:960,def:0};L[g.chorusEffectsSend]={min:0,max:1e3,def:0};L[g.reverbEffectsSend]={min:0,max:1e3,def:0};L[g.pan]={min:-500,max:500,def:0};L[g.delayModLFO]={min:-12e3,max:5e3,def:-12e3};L[g.freqModLFO]={min:-16e3,max:4500,def:0};L[g.delayVibLFO]={min:-12e3,max:5e3,def:-12e3};L[g.freqVibLFO]={min:-16e3,max:4500,def:0};L[g.delayModEnv]={min:-32768,max:5e3,def:-32768};L[g.attackModEnv]={min:-32768,max:8e3,def:-32768};L[g.holdModEnv]={min:-12e3,max:5e3,def:-12e3};L[g.decayModEnv]={min:-12e3,max:8e3,def:-12e3};L[g.sustainModEnv]={min:0,max:1e3,def:0};L[g.releaseModEnv]={min:-12e3,max:8e3,def:-12e3};L[g.keyNumToModEnvHold]={min:-1200,max:1200,def:0};L[g.keyNumToModEnvDecay]={min:-1200,max:1200,def:0};L[g.delayVolEnv]={min:-12e3,max:5e3,def:-12e3};L[g.attackVolEnv]={min:-12e3,max:8e3,def:-12e3};L[g.holdVolEnv]={min:-12e3,max:5e3,def:-12e3};L[g.decayVolEnv]={min:-12e3,max:8e3,def:-12e3};L[g.sustainVolEnv]={min:0,max:1440,def:0};L[g.releaseVolEnv]={min:-7200,max:8e3,def:-12e3};L[g.keyNumToVolEnvHold]={min:-1200,max:1200,def:0};L[g.keyNumToVolEnvDecay]={min:-1200,max:1200,def:0};L[g.startloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};L[g.keyNum]={min:-1,max:127,def:-1};L[g.velocity]={min:-1,max:127,def:-1};L[g.initialAttenuation]={min:-250,max:1440,def:0};L[g.endloopAddrsCoarseOffset]={min:-32768,max:32768,def:0};L[g.coarseTune]={min:-120,max:120,def:0};L[g.fineTune]={min:-12700,max:12700,def:0};L[g.scaleTuning]={min:0,max:1200,def:100};L[g.exclusiveClass]={min:0,max:99999,def:0};L[g.overridingRootKey]={min:-1,max:127,def:-1};var b=class{generatorType=g.INVALID;generatorValue=0;constructor(A=g.INVALID,e=0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");let n=L[A];this.generatorValue=Math.round(e),n!==void 0&&(this.generatorValue=Math.max(n.min,Math.min(n.max,this.generatorValue)))}};function pn(t,A,e){let n=L[t]||{min:0,max:32768,def:0},s=A.find(B=>B.generatorType===t),o=0;s&&(o=s.generatorValue);let a=e.find(B=>B.generatorType===t),C=n.def;a&&(C=a.generatorValue);let Q=C+o;return t===g.initialAttenuation?Q:Math.max(n.min,Math.min(n.max,Q))}var K={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},cA={linear:0,concave:1,convex:2,switch:3},j=class t{currentValue=0;constructor(A){this.sourceEnum=A.srcEnum,this.modulatorDestination=A.dest,this.secondarySourceEnum=A.secSrcEnum,this.transformAmount=A.amt,this.transformType=A.transform,this.modulatorDestination>58&&(this.modulatorDestination=g.INVALID),this.sourcePolarity=this.sourceEnum>>9&1,this.sourceDirection=this.sourceEnum>>8&1,this.sourceUsesCC=this.sourceEnum>>7&1,this.sourceIndex=this.sourceEnum&127,this.sourceCurveType=this.sourceEnum>>10&3,this.secSrcPolarity=this.secondarySourceEnum>>9&1,this.secSrcDirection=this.secondarySourceEnum>>8&1,this.secSrcUsesCC=this.secondarySourceEnum>>7&1,this.secSrcIndex=this.secondarySourceEnum&127,this.secSrcCurveType=this.secondarySourceEnum>>10&3}static copy(A){return new t({srcEnum:A.sourceEnum,secSrcEnum:A.secondarySourceEnum,transform:A.transformType,amt:A.transformAmount,dest:A.modulatorDestination})}static isIdentical(A,e){return A.sourceEnum===e.sourceEnum&&A.modulatorDestination===e.modulatorDestination&&A.secondarySourceEnum===e.secondarySourceEnum&&A.transformType===e.transformType}sumTransform(A){return new t({srcEnum:this.sourceEnum,secSrcEnum:this.secondarySourceEnum,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+A.transformAmount})}debugString(){function A(s,o){return Object.keys(s).find(a=>s[a]===o)}let e=A(cA,this.sourceCurveType);e+=this.sourcePolarity===0?" unipolar ":" bipolar ",e+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?e+=A(m,this.sourceIndex):e+=A(K,this.sourceIndex);let n=A(cA,this.secSrcCurveType);return n+=this.secSrcPolarity===0?" unipolar ":" bipolar ",n+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?n+=A(m,this.secSrcIndex):n+=A(K,this.secSrcIndex),`Modulator: Source: ${e} Secondary source: ${n} Destination: ${A(g,this.modulatorDestination)} @@ -6,13 +6,13 @@ var Bn=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>( Transform type: ${this.transformType} -`}},pt=960,yt=QA.concave;function HA(t,A,e,n,s){return t<<10|A<<9|e<<8|n<<7|s}var Pe=[new $({srcEnum:HA(yt,0,1,0,P.noteOnVelocity),dest:g.initialAttenuation,amt:pt,secSrcEnum:0,transform:0}),new $({srcEnum:129,dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new $({srcEnum:HA(yt,0,1,1,m.mainVolume),dest:g.initialAttenuation,amt:pt,secSrcEnum:0,transform:0}),new $({srcEnum:13,dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new $({srcEnum:526,dest:g.fineTune,amt:12700,secSrcEnum:16,transform:0}),new $({srcEnum:650,dest:g.pan,amt:1e3,secSrcEnum:0,transform:0}),new $({srcEnum:HA(yt,0,1,1,m.expressionController),dest:g.initialAttenuation,amt:pt,secSrcEnum:0,transform:0}),new $({srcEnum:219,dest:g.reverbEffectsSend,amt:750,secSrcEnum:0,transform:0}),new $({srcEnum:221,dest:g.chorusEffectsSend,amt:750,secSrcEnum:0,transform:0}),new $({srcEnum:HA(QA.linear,0,0,0,P.polyPressure),dest:g.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new $({srcEnum:HA(QA.linear,0,0,1,m.tremoloDepth),dest:g.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new $({srcEnum:HA(QA.linear,1,0,1,m.releaseTime),dest:g.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new $({srcEnum:HA(QA.linear,1,0,1,m.brightness),dest:g.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0}),new $({srcEnum:HA(QA.linear,1,0,1,m.timbreHarmonicContent),dest:g.initialFilterQ,amt:250,secSrcEnum:0,transform:0})];var EA=128,Ke=147,St=new Int16Array(Ke).fill(0),uA=(t,A)=>St[t]=A<<7;uA(m.mainVolume,100);uA(m.balance,64);uA(m.expressionController,127);uA(m.pan,64);uA(m.timbreHarmonicContent,64);uA(m.releaseTime,64);uA(m.attackTime,64);uA(m.brightness,64);uA(m.soundController6,64);uA(m.soundController7,64);uA(m.soundController8,64);uA(m.soundController9,64);uA(m.generalPurposeController6,64);uA(m.generalPurposeController8,64);uA(EA+P.pitchWheel,64);uA(EA+P.pitchWheelRange,2);var IA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Dt=Object.keys(IA).length,kt=new Float32Array(Dt);kt[IA.modulationMultiplier]=1;var dA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6};function yn(t=!1){let A={midiControllers:new Int16Array(Ke),lockedControllers:Array(Ke).fill(!1),customControllers:new Float32Array(Dt),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:dA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},velocityOverride:0,lockGSNRPNParams:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let e=0;e<128;e++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),t&&this.callEvent("newchannel",void 0)}var wt={velocityOverride:128};var Sn="spessasynth-worklet-system",Dn=350,DA=9,Ve=16,Oe="gs";var LA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},FA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function zA(t,A){let e=0;for(let n=8*(A-1);n>=0;n-=8)e|=t[t.currentIndex++]<>>0}function kn(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=we(t.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=n,e.status){case F.noteOn:let s=t.messageData[1];if(s>0)this.synth.noteOn(e.channel,t.messageData[0],s),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:s});else{this.synth.noteOff(e.channel,t.messageData[0]);let i=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);i!==-1&&this.playingNotes.splice(i,1)}break;case F.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(i=>i.midiNote===t.messageData[0]&&i.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case F.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case F.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case F.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case F.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case F.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case F.systemExclusive:this.synth.systemExclusive(t.messageData,n);break;case F.setTempo:this.oneTickToSeconds=60/(No(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),U("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:U(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(F).find(i=>F[i]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function wn(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===DA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function No(t){return t.messageData.currentIndex=0,6e7/zA(t.messageData,3)}function Fn(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(n.ticks-e.ticks),this.midiData.loop.end<=e.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function Rn(){let t=0,A=1/0;return this.tracks.forEach((e,n)=>{this.eventIndex[n]>=e.length||e[this.eventIndex[n]].ticks>>0}function ge(t,A,e){for(let n=0;n>n*8&255}function Y(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function cA(t,A){ge(t,A,4)}function jA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function Gn(t){return t>127?t-256:t}function V(t,A,e=void 0,n=!0){if(e){let s=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(s.buffer)}else{let s=!1,o="";for(let i=0;i127){if(n){s=!0;continue}else if(C===0){s=!0;continue}}o+=String.fromCharCode(C)}}return o}}function RA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let n=0;nA.length)for(let n=0;ne.header!=="LIST"?!1:(e.chunkData.currentIndex=0,V(e.chunkData,4)===A))}function Xe(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var We={name:"INAM",album:"IPRD",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"};var _e=class{constructor(){this.timeDivision=0,this.duration=0,this.tempoChanges=[{ticks:0,tempo:120}],this.copyright="",this.tracksAmount=0,this.lyrics=[],this.firstNoteOn=0,this.keyRange={min:0,max:127},this.lastVoiceEventTick=0,this.midiPorts=[0],this.midiPortChannelOffsets=[0],this.usedChannelsOnTrack=[],this.loop={start:0,end:0},this.midiName="",this.fileName="",this.rawMidiName=void 0,this.embeddedSoundFont=void 0,this.format=0,this.RMIDInfo={},this.bankOffset=0,this.tracks=[]}};function Ce(t,A){let e=0;for(;t>0;){let n=A.tempoChanges.find(o=>o.ticksSt[t]=A<<7;dA(m.mainVolume,100);dA(m.balance,64);dA(m.expressionController,127);dA(m.pan,64);dA(m.timbreHarmonicContent,64);dA(m.releaseTime,64);dA(m.attackTime,64);dA(m.brightness,64);dA(m.soundController6,64);dA(m.soundController7,64);dA(m.soundController8,64);dA(m.soundController9,64);dA(m.generalPurposeController6,64);dA(m.generalPurposeController8,64);dA(BA+K.pitchWheel,64);dA(BA+K.pitchWheelRange,2);var gA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Dt=Object.keys(gA).length,kt=new Float32Array(Dt);kt[gA.modulationMultiplier]=1;var fA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6};function yn(t=!1){let A={midiControllers:new Int16Array(Ke),lockedControllers:Array(Ke).fill(!1),customControllers:new Float32Array(Dt),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:fA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),keyCentTuning:new Int16Array(128),channelVibrato:{delay:0,depth:0,rate:0},velocityOverride:0,lockGSNRPNParams:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let e=0;e<128;e++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),t&&this.callEvent("newchannel",void 0)}var wt={velocityOverride:128};var Sn="spessasynth-worklet-system",Dn=350,DA=9,Ve=16,Oe="gs";var LA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},FA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function zA(t,A){let e=0;for(let n=8*(A-1);n>=0;n-=8)e|=t[t.currentIndex++]<>>0}function kn(t,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&t.messageStatusByte>=128){this.sendMIDIMessage([t.messageStatusByte,...t.messageData]);return}let e=we(t.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(e.channel+=n,e.status){case F.noteOn:let s=t.messageData[1];if(s>0)this.synth.noteOn(e.channel,t.messageData[0],s),this.playingNotes.push({midiNote:t.messageData[0],channel:e.channel,velocity:s});else{this.synth.noteOff(e.channel,t.messageData[0]);let a=this.playingNotes.findIndex(C=>C.midiNote===t.messageData[0]&&C.channel===e.channel);a!==-1&&this.playingNotes.splice(a,1)}break;case F.noteOff:this.synth.noteOff(e.channel,t.messageData[0]);let o=this.playingNotes.findIndex(a=>a.midiNote===t.messageData[0]&&a.channel===e.channel);o!==-1&&this.playingNotes.splice(o,1);break;case F.pitchBend:this.synth.pitchWheel(e.channel,t.messageData[1],t.messageData[0]);break;case F.controllerChange:this.synth.controllerChange(e.channel,t.messageData[0],t.messageData[1]);break;case F.programChange:this.synth.programChange(e.channel,t.messageData[0]);break;case F.polyPressure:this.synth.polyPressure(e.channel,t.messageData[0],t.messageData[1]);break;case F.channelPressure:this.synth.channelPressure(e.channel,t.messageData[0]);break;case F.systemExclusive:this.synth.systemExclusive(t.messageData,n);break;case F.setTempo:this.oneTickToSeconds=60/(No(t)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),U("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:U(`%cUnrecognized Event: %c${t.messageStatusByte}%c status byte: %c${Object.keys(F).find(a=>F[a]===e.status)}`,r.warn,r.unrecognized,r.warn,r.value);break}}function wn(){for(let t=0;t<16;t++)this.synth.createWorkletChannel(!0),t===DA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function No(t){return t.messageData.currentIndex=0,6e7/zA(t.messageData,3)}function Fn(){let t=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(n.ticks-e.ticks),this.midiData.loop.end<=e.ticks&&this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}else if(t>=this.duration){if(this.loop&&this.currentLoopCount>0){this.currentLoopCount--,this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function Rn(){let t=0,A=1/0;return this.tracks.forEach((e,n)=>{this.eventIndex[n]>=e.length||e[this.eventIndex[n]].ticks>>0}function ge(t,A,e){for(let n=0;n>n*8&255}function Y(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function lA(t,A){ge(t,A,4)}function jA(t,A){let e=A<<8|t;return e>32767?e-65536:e}function Gn(t){return t>127?t-256:t}function V(t,A,e=void 0,n=!0){if(e){let s=t.slice(t.currentIndex,t.currentIndex+A);return t.currentIndex+=A,new TextDecoder(e.replace(/[^\x20-\x7E]/g,"")).decode(s.buffer)}else{let s=!1,o="";for(let a=0;a127){if(n){s=!0;continue}else if(C===0){s=!0;continue}}o+=String.fromCharCode(C)}}return o}}function RA(t,A,e=0){e>0&&A.length>e&&(A=A.slice(0,e));for(let n=0;nA.length)for(let n=0;ne.header!=="LIST"?!1:(e.chunkData.currentIndex=0,V(e.chunkData,4)===A))}function Xe(t){let A=0;for(;t;){let e=t[t.currentIndex++];if(A=A<<7|e&127,e>>7!==1)break}return A}var We={name:"INAM",album:"IPRD",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"};var _e=class{constructor(){this.timeDivision=0,this.duration=0,this.tempoChanges=[{ticks:0,tempo:120}],this.copyright="",this.tracksAmount=0,this.lyrics=[],this.firstNoteOn=0,this.keyRange={min:0,max:127},this.lastVoiceEventTick=0,this.midiPorts=[0],this.midiPortChannelOffsets=[0],this.usedChannelsOnTrack=[],this.loop={start:0,end:0},this.midiName="",this.fileName="",this.rawMidiName=void 0,this.embeddedSoundFont=void 0,this.format=0,this.RMIDInfo={},this.bankOffset=0,this.tracks=[]}};function Ce(t,A){let e=0;for(;t>0;){let n=A.tempoChanges.find(o=>o.ticks0&&(K+=this.tracks[S-1][this.tracks[S-1].length-1].ticks);y.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=K),j=cn[I>>4],(I&240)===F.noteOn){N.add(sA);let oA=y.data[y.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,oA),this.keyRange.max=Math.max(this.keyRange.max,oA)}G=I;break}let J=new H(j),Z=y.data.slice(y.data.currentIndex,y.data.currentIndex+j);y.data.currentIndex+=j,J.set(Z,0);let CA=new ie(K,I,J);switch(w.push(CA),sA){case-2:switch(I){case F.setTempo:this.tempoChanges.push({ticks:K,tempo:6e7/zA(Z,3)});break;case F.marker:switch(V(J,J.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=K;break;case"loopend":h=K}J.currentIndex=0;break;case F.midiPort:let mA=J[0];this.midiPorts[S]=mA,this.midiPortChannelOffsets[mA]===void 0&&(this.midiPortChannelOffsets[mA]=u,u+=16);break;case F.copyright:o||(this.copyright+=V(J,J.length,void 0,!1)+` -`);break;case F.lyric:this.lyrics.push(J)}break;case-3:if(J.slice(0,7).every((oA,mA)=>bo[mA]===oA)){let oA=J.slice(7,Z.length-3),mA=V(oA,oA.length)+` -`;this.copyright+=mA,p(`%cDecoded Roland SC message! %c${mA}`,r.recognized,r.value)}break;default:if((I&240)===F.controllerChange)switch(J[0]){case 2:case 116:d=K;break;case 4:case 117:h===null?h=K:h=0;break;case 0:C&&J[1]!==0&&J[1]!==127&&(p("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(w),this.usedChannelsOnTrack.push(N),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,r.info,r.value,r.info,r.value)}p("%cAll tracks parsed correctly!",r.recognized),SA("%cCorrecting loops, ports and detecting notes...",r.info);let l=[];for(let S of this.tracks){let w=S.find(y=>(y.messageStatusByte&240)===F.noteOn);w&&l.push(w.ticks)}this.firstNoteOn=Math.min(...l),p(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&h===null?(d=this.firstNoteOn,h=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(h===null||h===0)&&(h=this.lastVoiceEventTick)),this.loop={start:d,end:h},p(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let D=0;for(let S of this.midiPorts)if(S!==-1){D=S;break}if(this.midiPorts=this.midiPorts.map(S=>S===-1?D:S),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?p("%cNo additional MIDI Ports detected.",r.info):p("%cMIDI Ports detected!",r.recognized),!i)if(this.tracks.length>1){if(this.tracks[0].find(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){p("%cNo name detected. Using the alt name!",r.info),this.midiName=hn(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let S=0;Su>h?u:h),n=[];for(let h=0;h{i[D]>=l.length||l[i[D]].ticks0;){let h=c(),u=t.tracks[h];if(i[h]>=u.length){C--;continue}let l=u[i[h]];if(i[h]++,l.messageStatusByte===F.midiPort){B[h]=l.messageData[0];continue}let D=l.messageStatusByte&240;if(D!==F.noteOn&&D!==F.controllerChange&&D!==F.programChange&&D!==F.systemExclusive)continue;let S=(l.messageStatusByte&15)+t.midiPortChannelOffsets[B[h]]||0,w=n[S];switch(D){case F.programChange:w.program=l.messageData[0],s(w);break;case F.controllerChange:if(l.messageData[0]!==m.bankSelect||d==="gs"&&w.drums)continue;let y=l.messageData[1],N=Math.max(0,y-t.bankOffset);if(d==="xg"){let W=y===120||y===126||y===127;W!==w.drums?(w.drums=W,w.bank=w.drums?128:N,s(w)):w.bank=w.drums?128:N;continue}n[S].bank=N;break;case F.noteOn:if(l.messageData[1]===0)continue;s(w),o[w.string].add(`${l.messageData[0]}-${l.messageData[1]}`);break;case F.systemExclusive:if(l.messageData[0]!==65||l.messageData[2]!==66||l.messageData[3]!==18||l.messageData[4]!==64||!(l.messageData[5]&16)||l.messageData[6]!==21){l.messageData[0]===67&&l.messageData[2]===76&&l.messageData[5]===126&&l.messageData[6]===0&&(d="xg");continue}let G=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][l.messageData[5]&15]+t.midiPortChannelOffsets[B[h]],K=!!(l.messageData[7]>0&&l.messageData[5]>>4);w=n[G],w.drums=K,w.bank=K?128:0,s(w);break}}for(let h of Object.keys(o))o[h].size===0&&(p(`%cDetected change but no keys for %c${h}`,r.info,r.value),delete o[h]);return X(),o}function Mn(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(e,A)}),this.duration=this.midiData.duration,this.firstNoteTime=Ce(this.midiData.firstNoteOn,this.midiData),p(`%cTotal song time: ${mt(Math.ceil(this.duration)).time}`,r.recognized),this.post(FA.songChange,[new Ze(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(U(`%cVery short song: (${mt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function bn(t){this.songs=t.reduce((A,e)=>{if(e.duration)return A.push(e),A;try{A.push(new ze(e.binary,e.altName||""))}catch(n){return this.post(FA.midiError,n.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function Ln(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Un(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}var KA=new Int16Array(127);KA[m.mainVolume]=100;KA[m.expressionController]=127;KA[m.pan]=64;KA[m.releaseTime]=64;KA[m.brightness]=64;KA[m.reverbDepth]=0;function Tn(t,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let e=this.synth.workletProcessorChannels.length,n=Array(e).fill(8192),s=[];for(let C=0;CC===m.dataDecrement||C===m.dataIncrement||C===m.dataEntryMsb||C===m.dataDecrement||C===m.lsbForControl6DataEntry||C===m.RPNLsb||C===m.RPNMsb||C===m.NRPNLsb||C===m.NRPNMsb||C===m.bankSelect||C===m.lsbForControl0BankSelect||C===m.resetAllControllers,i=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let B=we(c.messageStatusByte),d=B.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(B.status){case F.noteOn:case F.noteOff:case F.keySignature:break;case F.pitchBend:n[d]=c.messageData[1]<<7|c.messageData[0];break;case F.programChange:let u=s[d];u.program=c.messageData[0],u.actualBank=u.bank;break;case F.controllerChange:let l=c.messageData[0];if(o(l)){let D=c.messageData[1];if(l===m.bankSelect){s[d].bank=D;break}this.sendMIDIMessages?this.sendMIDICC(d,l,D):this.synth.controllerChange(d,l,D)}else i[d]===void 0&&(i[d]=Array.from(KA)),i[d][l]=c.messageData[1];break;default:this._processEvent(c,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let h=this.tracks[C][this.eventIndex[C]];if(h===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(h.ticks-c.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7,n[C]&127),i[C]!==void 0&&i[C].forEach((c,B)=>{c!==KA[B]&&!o(B)&&this.sendMIDICC(C,B,c)}),s[C].program>=0&&s[C].actualBank>=0){let c=s[C].actualBank;this.sendMIDICC(C,m.bankSelect,c),this.sendMIDIProgramChange(C,s[C].program)}}else for(let C=0;C>7,n[C]&127),i[C]!==void 0&&i[C].forEach((c,B)=>{c!==KA[B]&&!o(B)&&this.synth.controllerChange(C,B,c)}),s[C].program>=0&&s[C].actualBank>=0){let c=s[C].actualBank;this.synth.controllerChange(C,m.bankSelect,c),this.synth.programChange(C,s[C].program)}return!0}function Hn(t=!1){if(this.midiData!==void 0){if(t){this.currentTime=0;return}if(this.currentTime>=this.duration){this.currentTime=0;return}this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),this.sendMIDIMessages||this.playingNotes.forEach(A=>{this.synth.noteOn(A.channel,A.midiNote,A.velocity,!1,!0)}),this.setProcessHandler()}}function Yn(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(FA.timeChange,currentTime-Ce(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Jn(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function vn(t,A){switch(t){default:break;case LA.loadNewSongList:this.loadNewSongList(A);break;case LA.pause:this.pause();break;case LA.play:this.play(A);break;case LA.stop:this.stop();break;case LA.setTime:this.currentTime=A;break;case LA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case LA.setPlaybackRate:this.playbackRate=A;break;case LA.setLoop:this.loop=A;break;case LA.changeSong:A?this.nextSong():this.previousSong();break;case LA.getMIDI:this.post(FA.getMIDI,this.midiData);break;case LA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function qn(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:yA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Pn(t){this.post(FA.midiEvent,t)}function Kn(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|t,A,e])}function Vn(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|t,A])}function On(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|t,e,A])}function Zn(){if(this.sendMIDIMessages){this.sendMIDIMessage([F.reset]);for(let t=0;tthis.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&AXn?440*Math.pow(2,(t-6900)/1200):Rt[~~t-je]}var xt=-1660,Lo=1600,Gt=new Float32Array((Lo-xt)*100+1);for(let t=0;t.5?1:0,n?e*2-1:e;case QA.concave:return n?(e=e*2-1,e<0?1-Ee[~~(e*-gA)]-1:Ee[~~e*gA]):Ee[~~(e*gA)];case QA.convex:return n?(e=e*2-1,e<0?1-Be[~~(e*-gA)]-1:Be[~~(e*gA)]):Be[~~(e*gA)]}}var Mt=1,Nt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)n-=o;let C=~~n,c=C+1;for(;c>=e.loopEnd;)c-=o;let B=n-C,d=s[c],h=s[C];A[i]=h+(d-h)*B,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end){t.finished=!0;return}let c=n-i,B=s[C],d=s[i];A[o]=d+(B-d)*c,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function _n(t,A){let e=t.sample,n=e.cursor,s=e.loopEnd-e.loopStart,o=e.sampleData;if(t.sample.isLooping)for(let i=0;i=e.loopEnd;)n-=s;let C=~~n+1;for(;C>=e.loopEnd;)C-=s;A[i]=o[C],n+=e.playbackStep*t.currentTuningCalculated}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let i=0;i=e.end){t.finished=!0;return}A[i]=o[C],n+=e.playbackStep*t.currentTuningCalculated}}e.cursor=n}function zn(t,A){let e=t.sample,n=e.cursor,s=e.sampleData;if(e.isLooping){let o=e.loopEnd-e.loopStart;for(let i=0;i=e.loopEnd;)n-=o;let C=~~n,c=C+1,B=c+1,d=B+1,h=n-C;c>=e.loopEnd&&(c-=o),B>=e.loopEnd&&(B-=o),d>=e.loopEnd&&(d-=o);let u=s[C],l=s[c],D=s[B],S=s[d],w=.5*(D-u),y=u-2.5*l+2*D-.5*S,N=.5*(S-u)+1.5*(l-D);A[i]=((N*h+y)*h+w)*h+l,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end||c>=e.end||B>=e.end){t.finished=!0;return}let h=s[i],u=s[C],l=s[c],D=s[B],S=.5*(l-h),w=h-2.5*u+2*l-.5*D,y=.5*(D-h)+1.5*(u-l);A[o]=((y*d+w)*d+S)*d+u,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function jn(t,A,e,n,s,o,i,C,c){if(!isNaN(e[0])){if(i>0){let B=o[0],d=o[1];i=Math.min(i,1e3);let h=i/1300,u=t*h,l=A*h;for(let D=0;D0){let B=C[0],d=C[1];c=Math.min(c,1e3);let h=c/1300,u=t*h,l=A*h;for(let D=0;D0)for(let B=0;B0)for(let B=0;B13499&&A.filter.reasonanceCb===0)return;let s=A.filter;(s.cutoffCents!==n||s.reasonanceCb!==A.modulatedGenerators[g.initialFilterQ])&&(s.cutoffCents=n,s.reasonanceCb=A.modulatedGenerators[g.initialFilterQ],t.calculateCoefficients(A));for(let o=0;o=bt}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,n=B=>Math.max(0,Math.floor(YA(B)*e.sampleRate));e.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[g.initialAttenuation],1440))/10,e.sustainDbRelative=Math.min(vA,A.modulatedGenerators[g.sustainVolEnv]/10);let s=Math.min(vA,e.sustainDbRelative);e.attackDuration=n(A.modulatedGenerators[g.attackVolEnv]);let o=A.modulatedGenerators[g.decayVolEnv],i=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvDecay],C=s/vA;e.decayDuration=n(o+i)*C,e.releaseDuration=n(A.modulatedGenerators[g.releaseVolEnv]),e.delayEnd=n(A.modulatedGenerators[g.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let c=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvHold];if(e.holdEnd=n(A.modulatedGenerators[g.holdVolEnv]+c)+e.attackEnd,e.decayEnd=e.decayDuration+e.holdEnd,e.state===0&&e.attackEnd===0&&(e.state=2),A.isInRelease){let B=Math.max(0,Math.min(vA,e.sustainDbRelative)),d=B/vA;switch(e.decayDuration=n(o+i)*d,e.state){case 0:e.releaseStartDb=vA;break;case 1:let h=1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration;e.releaseStartDb=20*Math.log10(h)*-1;break;case 2:e.releaseStartDb=0;break;case 3:e.releaseStartDb=(1-(e.decayEnd-e.releaseStartTimeSamples)/e.decayDuration)*B;break;case 4:e.releaseStartDb=B;break}e.releaseStartDb=Math.max(0,Math.min(e.releaseStartDb,vA)),e.releaseStartDb>=bt&&(A.finished=!0),e.currentReleaseGain=VA(e.releaseStartDb)}}static apply(A,e,n,s){let o=A.volumeEnvelope,i=n/10,C=s;if(A.isInRelease){let B=o.currentSampleTime-o.releaseStartTimeSamples;if(B>=o.releaseDuration){for(let h=0;h=e.length)return;o.state++;case 1:for(;o.currentSampleTime=e.length)return}o.state++;case 2:for(;o.currentSampleTime=e.length)return;o.state++;case 3:for(;o.currentSampleTime=e.length)return;o.state++;case 4:for(o.canEndOnSilentSustain&&o.sustainDbRelative>=bt&&(A.finished=!0);;)if(o.attenuation+=(o.attenuationTarget-o.attenuation)*C,e[c]*=VA(o.sustainDbRelative+i+o.attenuation),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++c>=e.length)return}}};var As=Math.PI/2,es=.05;function ts(t,A,e,n,s,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,UA.startRelease(A),JA.startRelease(A),A.sample.loopingMode===3&&(A.sample.isLooping=!1)),A.modulatedGenerators[g.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let i=A.targetKey,C=A.modulatedGenerators[g.fineTune]+t.customControllers[IA.channelTuning]+t.customControllers[IA.channelTransposeFine]+t.customControllers[IA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],c=A.modulatedGenerators[g.coarseTune]+t.customControllers[IA.channelTuningSemitones],B=this.tunings[t.preset.program]?.[i];B?.midiNote>=0&&(i=B.midiNote,C+=B.centTuning),C+=(i-A.sample.rootKey)*A.modulatedGenerators[g.scaleTuning];let d=A.modulatedGenerators[g.vibLfoToPitch];if(d!==0){let Z=A.startTime+YA(A.modulatedGenerators[g.delayVibLFO]),CA=Fe(A.modulatedGenerators[g.freqVibLFO]),oA=$e(Z,CA,currentTime);C+=oA*(d*t.customControllers[IA.modulationMultiplier])}let h=A.modulatedGenerators[g.initialFilterFc],u=A.modulatedGenerators[g.modLfoToPitch],l=A.modulatedGenerators[g.modLfoToVolume],D=A.modulatedGenerators[g.modLfoToFilterFc],S=0;if(u+D+l!==0){let Z=A.startTime+YA(A.modulatedGenerators[g.delayModLFO]),CA=Fe(A.modulatedGenerators[g.freqModLFO]),oA=$e(Z,CA,currentTime);C+=oA*(u*t.customControllers[IA.modulationMultiplier]),S=-oA*l,h+=oA*D}if(t.channelVibrato.depth>0){let Z=$e(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);Z&&(C+=Z*t.channelVibrato.depth)}let w=A.modulatedGenerators[g.modEnvToPitch],y=A.modulatedGenerators[g.modEnvToFilterFc],N=JA.getValue(A,currentTime);h+=N*y,C+=N*w;let G=~~(C+c*100);G!==A.currentTuningCents&&(A.currentTuningCents=G,A.currentTuningCalculated=Math.pow(2,G/1200));let K=(Math.max(-500,Math.min(500,A.modulatedGenerators[g.pan]))+500)/1e3,W=new Float32Array(e.length);switch(this.interpolationType){case he.linear:default:Wn(A,W);break;case he.nearestNeighbor:_n(A,W);break;case he.fourthOrder:zn(A,W)}Qe.apply(A,W,h),UA.apply(A,W,S,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(K-A.currentPan)*this.panSmoothingFactor;let I=Math.cos(As*A.currentPan)*this.panLeft,sA=Math.sin(As*A.currentPan)*this.panRight,j=this.oneOutputMode?0:A.modulatedGenerators[g.reverbEffectsSend],J=this.oneOutputMode?0:A.modulatedGenerators[g.chorusEffectsSend];jn(I,sA,W,e,n,s,j,o,J)}function To(t,A){let e=0;return t.drumChannel&&(e+=5),A.isInRelease&&(e-=5),e+=A.velocity/25,e-=A.volumeEnvelope.state,A.isInRelease&&(e-=5),e-=A.volumeEnvelope.currentAttenuationDb/50,e}function ns(t){let A=[];for(let n of this.workletProcessorChannels)for(let s of n.voices)if(!s.finished){let o=To(n,s);A.push({channel:n,voice:s,priority:o})}A.sort((n,s)=>n.priority-s.priority);let e=A.slice(0,t);for(let{channel:n,voice:s}of e){let o=n.voices.indexOf(s);o>-1&&n.voices.splice(o,1)}}function ss(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimers=t);var Ho=function(t){var A,e,n,s,o,i,C,c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",B="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do s=c.indexOf(t.charAt(d++)),o=c.indexOf(t.charAt(d++)),i=c.indexOf(t.charAt(d++)),C=c.indexOf(t.charAt(d++)),A=s<<2|o>>4,e=(15&o)<<4|i>>2,n=(3&i)<<6|C,B+=String.fromCharCode(A),i!==64&&(B+=String.fromCharCode(e)),C!==64&&(B+=String.fromCharCode(n));while(d1&&(I.thisProgram=process.argv[1].replace(/\\/g,"/")),I.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(a){if(!(a instanceof ye))throw a}),process.on("unhandledRejection",function(a,E){process.exit(1)}),I.quit=function(a){process.exit(a)},I.inspect=function(){return"[Emscripten Module object]"}):CA?(typeof read<"u"&&(I.read=function(E){return read(E)}),I.readBinary=function(E){var Q;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(Q=read(E,"binary"))=="object"),Q)},typeof scriptArgs<"u"?I.arguments=scriptArgs:typeof arguments<"u"&&(I.arguments=arguments),typeof quit=="function"&&(I.quit=function(a){quit(a)})):(j||J)&&(j?document.currentScript&&(oA=document.currentScript.src):oA=self.location.href,oA=oA.indexOf("blob:")!==0?oA.split("/").slice(0,-1).join("/")+"/":"",I.read=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.send(null),Q.responseText},J&&(I.readBinary=function(E){var Q=new XMLHttpRequest;return Q.open("GET",E,!1),Q.responseType="arraybuffer",Q.send(null),new Uint8Array(Q.response)}),I.readAsync=function(E,Q,f){var R=new XMLHttpRequest;R.open("GET",E,!0),R.responseType="arraybuffer",R.onload=function(){if(R.status==200||R.status==0&&R.response){Q(R.response);return}f()},R.onerror=f,R.send(null)},I.setWindowTitle=function(a){document.title=a});var Me=I.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),GA=I.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Me);for(t in sA)sA.hasOwnProperty(t)&&(I[t]=sA[t]);function Ne(a){var E=l;return l=l+a+15&-16,E}function Ot(a){var E=c[G>>2],Q=E+a+15&-16;return c[G>>2]=Q,Q>=BA&&!tn()?(c[G>>2]=E,0):E}function Zt(a,E){return E||(E=16),a=Math.ceil(a/E)*E}function fo(a){switch(a){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(a[a.length-1]==="*")return 4;if(a[0]!=="i")return 0;var E=parseInt(a.substr(1));return _A(E%8==0),E/8}}function fe(a){fe.shown||(fe.shown={}),fe.shown[a]||(fe.shown[a]=1,GA(a))}sA=void 0;var mo={"f64-rem":function(a,E){return a%E},debugger:function(){}},it=[];function Ko(a,E){for(var Q=0,f=Q;f>>0)+4294967296*+(E>>>0):+(a>>>0)+4294967296*+(0|E)}function It(a,E,Q){return Q&&Q.length?I["dynCall_"+a].apply(null,[E].concat(Q)):I["dynCall_"+a].call(null,E)}var be=0,Xt=0;function _A(a,E){a||ZA("Assertion failed: "+E)}function Wt(a){var E=I["_"+a];return _A(E,"Cannot call unknown function "+a+", make sure it is exported"),E}var _t={stackSave:function(){lt()},stackRestore:function(){ct()},arrayToC:function(a){var E,Q,f=Je(a.length);return E=a,Q=f,s.set(E,Q),f},stringToC:function(a){var E=0;if(a!=null&&a!==0){var Q=(a.length<<2)+1;E=Je(Q),$t(a,E,Q)}return E}},po={string:_t.stringToC,array:_t.arrayToC};function zt(a,E,Q,f,R){var q=Wt(a),_=[],M=0;if(f)for(var hA=0;hA>0]=E;break;case"i16":i[a>>1]=E;break;case"i32":c[a>>2]=E;break;case"i64":tempI64=[E>>>0,+Fo(tempDouble=E)>=1?tempDouble>0?(0|Go(+an(tempDouble/4294967296),4294967295))>>>0:~~+Ro((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],c[a>>2]=tempI64[0],c[a+4>>2]=tempI64[1];break;case"float":d[a>>2]=E;break;case"double":h[a>>3]=E;break;default:ZA("invalid type for setValue: "+Q)}}function Xo(a,E,Q){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return s[a>>0];case"i16":return i[a>>1];case"i32":case"i64":return c[a>>2];case"float":return d[a>>2];case"double":return h[a>>3];default:ZA("invalid type for getValue: "+E)}return null}function Wo(a,E,Q,f){typeof a=="number"?(q=!0,_=a):(q=!1,_=a.length);var R=typeof E=="string"?E:null;if(M=Q==4?f:[typeof Ye=="function"?Ye:Ne,Je,Ne,Ot][Q===void 0?2:Q](Math.max(_,R?1:E.length)),q){for(f=M,_A((3&M)==0),hA=M+(-4&_);f>2]=0;for(hA=M+_;f>0]=0;return M}if(R==="i8")return a.subarray||a.slice?o.set(a,M):o.set(new Uint8Array(a),M),M;for(var q,_,M,hA,rA,iA,tA,v=0;v<_;){var pA=a[v];if((rA=R||E[v])===0){v++;continue}rA=="i64"&&(rA="i32"),yo(M+v,pA,rA),tA!==rA&&(iA=fo(rA),tA=rA),v+=iA}return M}function _o(a){return D?ht?Ye(a):Ot(a):Ne(a)}function Le(a,E){if(E===0||!a)return"";for(var Q,f,R,q=0,_=0;q|=f=o[a+_>>0],(f!=0||E)&&(_++,!E||_!=E););E||(E=_);var M="";if(q<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(a,a+Math.min(E,1024))),M=M?M+R:R,a+=1024,E-=1024;return M}return Q=a,function(rA,iA){for(var tA=iA;rA[tA];)++tA;if(tA-iA>16&&rA.subarray&&jt)return jt.decode(rA.subarray(iA,tA));for(var v,pA,xA,MA,NA,ee,bA="";;){if(!(v=rA[iA++]))return bA;if(!(128&v)){bA+=String.fromCharCode(v);continue}if(pA=63&rA[iA++],(224&v)==192){bA+=String.fromCharCode((31&v)<<6|pA);continue}if(xA=63&rA[iA++],(240&v)==224?v=(15&v)<<12|pA<<6|xA:(MA=63&rA[iA++],(248&v)==240?v=(7&v)<<18|pA<<12|xA<<6|MA:(NA=63&rA[iA++],v=(252&v)==248?(3&v)<<24|pA<<18|xA<<12|MA<<6|NA:(1&v)<<30|pA<<24|xA<<18|MA<<12|NA<<6|(ee=63&rA[iA++]))),v<65536)bA+=String.fromCharCode(v);else{var Se=v-65536;bA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(o,Q)}function zo(a){for(var E="";;){var Q=s[a++>>0];if(!Q)return E;E+=String.fromCharCode(Q)}}function jo(a,E){return function(f,R,q){for(var _=0;_>0]=f.charCodeAt(_);q||(s[R>>0]=0)}(a,E,!1)}var jt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ue(a,E,Q,f){if(!(f>0))return 0;for(var R=Q,q=Q+f-1,_=0;_=55296&&M<=57343&&(M=65536+((1023&M)<<10)|1023&a.charCodeAt(++_)),M<=127){if(Q>=q)break;E[Q++]=M}else if(M<=2047){if(Q+1>=q)break;E[Q++]=192|M>>6,E[Q++]=128|63&M}else if(M<=65535){if(Q+2>=q)break;E[Q++]=224|M>>12,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}else if(M<=2097151){if(Q+3>=q)break;E[Q++]=240|M>>18,E[Q++]=128|M>>12&63,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}else if(M<=67108863){if(Q+4>=q)break;E[Q++]=248|M>>24,E[Q++]=128|M>>18&63,E[Q++]=128|M>>12&63,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}else{if(Q+5>=q)break;E[Q++]=252|M>>30,E[Q++]=128|M>>24&63,E[Q++]=128|M>>18&63,E[Q++]=128|M>>12&63,E[Q++]=128|M>>6&63,E[Q++]=128|63&M}}return E[Q]=0,Q-R}function $t(a,E,Q){return Ue(a,o,E,Q)}function Te(a){for(var E=0,Q=0;Q=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&a.charCodeAt(++Q)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var An=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function $o(a){for(var E=a,Q=E>>1;i[Q];)++Q;if((E=Q<<1)-a>32&&An)return An.decode(o.subarray(a,E));for(var f=0,R="";;){var q=i[a+2*f>>1];if(q==0)return R;++f,R+=String.fromCharCode(q)}}function Ar(a,E,Q){if(Q===void 0&&(Q=2147483647),Q<2)return 0;for(var f=E,R=(Q-=2)<2*a.length?Q/2:a.length,q=0;q>1]=_,E+=2}return i[E>>1]=0,E-f}function er(a){return 2*a.length}function tr(a){for(var E=0,Q="";;){var f=c[a+4*E>>2];if(f==0)return Q;if(++E,f>=65536){var R=f-65536;Q+=String.fromCharCode(55296|R>>10,56320|1023&R)}else Q+=String.fromCharCode(f)}}function nr(a,E,Q){if(Q===void 0&&(Q=2147483647),Q<4)return 0;for(var f=E,R=f+Q-4,q=0;q=55296&&_<=57343&&(_=65536+((1023&_)<<10)|1023&a.charCodeAt(++q)),c[E>>2]=_,(E+=4)+4>R)break}return c[E>>2]=0,E-f}function sr(a){for(var E=0,Q=0;Q=55296&&f<=57343&&++Q,E+=4}return E}function or(a){var E=Te(a)+1,Q=Ye(E);return Q&&Ue(a,s,Q,E),Q}function rr(a){var E=Te(a)+1,Q=Je(E);return Ue(a,s,Q,E),Q}function ir(a){return a}function ar(){var a,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(R){f=R}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return I.extraStackTrace&&(E+=` -`+I.extraStackTrace()),(a=E).replace(/__Z[\w\d_]+/g,function(Q){var f,R=f=Q;return Q===R?Q:Q+" ["+R+"]"})}function gt(a,E){return a%E>0&&(a+=E-a%E),a}function en(a){I.buffer=n=a}function Ct(){I.HEAP8=s=new Int8Array(n),I.HEAP16=i=new Int16Array(n),I.HEAP32=c=new Int32Array(n),I.HEAPU8=o=new Uint8Array(n),I.HEAPU16=C=new Uint16Array(n),I.HEAPU32=B=new Uint32Array(n),I.HEAPF32=d=new Float32Array(n),I.HEAPF64=h=new Float64Array(n)}function tn(){var a=I.usingWasm?65536:16777216,E=2147483648-a;if(c[G>>2]>E)return!1;var Q=BA;for(BA=Math.max(BA,16777216);BA>2];)BA=BA<=536870912?gt(2*BA,a):Math.min(gt((3*BA+2147483648)/4,a),E);var f=I.reallocBuffer(BA);return f&&f.byteLength==BA?(en(f),Ct(),!0):(BA=Q,!1)}u=l=S=w=y=N=G=0,D=!1,I.reallocBuffer||(I.reallocBuffer=function(a){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(n,a);else{var E,Q=s;E=new ArrayBuffer(a),new Int8Array(E).set(Q)}}catch{return!1}return!!xo(E)&&E});try{(K=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{K=function(E){return E.byteLength}}var Et=I.TOTAL_STACK||5242880,BA=I.TOTAL_MEMORY||16777216;function So(){return BA}function me(a){for(;a.length>0;){var E=a.shift();if(typeof E=="function"){E();continue}var Q=E.func;typeof Q=="number"?E.arg===void 0?I.dynCall_v(Q):I.dynCall_vi(Q,E.arg):Q(E.arg===void 0?null:E.arg)}}BA=0?a:E<=32?2*Math.abs(1<=f&&(E<=32||a>f)&&(a=-2*f+a),a}var Fo=Math.abs,Ro=Math.ceil,an=Math.floor,Go=Math.min,Ae=0,Qt=null,pe=null;function Qr(a){return a}I.preloadedImages={},I.preloadedAudios={};var In="data:application/octet-stream;base64,";function He(a){return String.prototype.startsWith?a.startsWith(In):a.indexOf(In)===0}(function(){var E="main.wast",Q="main.wasm",f="main.temp.asm.js";He(E)||(E=mA(E)),He(Q)||(Q=mA(Q)),He(f)||(f=mA(f));var R={global:null,env:null,asm2wasm:mo,parent:I},q=null;function _(tA){return tA}function M(){try{if(I.wasmBinary)return new Uint8Array(I.wasmBinary);if(I.readBinary)return I.readBinary(Q);throw"both async and sync fetching of the wasm failed"}catch(tA){ZA(tA)}}I.asmPreload=I.asm;var hA=I.reallocBuffer,rA=function(tA){tA=gt(tA,I.usingWasm?65536:16777216);var v=I.buffer.byteLength;if(I.usingWasm)try{var pA=I.wasmMemory.grow((tA-v)/65536);return pA!==-1?I.buffer=I.wasmMemory.buffer:null}catch{return null}};I.reallocBuffer=function(tA){return iA==="asmjs"?hA(tA):rA(tA)};var iA="";I.asm=function(tA,v,pA){var xA;if(!(v=xA=v).table){var MA,NA=I.wasmTableSize;NA===void 0&&(NA=1024);var ee=I.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?ee!==void 0?v.table=new WebAssembly.Table({initial:NA,maximum:ee,element:"anyfunc"}):v.table=new WebAssembly.Table({initial:NA,element:"anyfunc"}):v.table=Array(NA),I.wasmTable=v.table}return v.memoryBase||(v.memoryBase=I.STATIC_BASE),v.tableBase||(v.tableBase=0),MA=function(Se,oe,dt){if(typeof WebAssembly!="object")return GA("no native wasm support detected"),!1;if(!(I.wasmMemory instanceof WebAssembly.Memory))return GA("no native wasm Memory in use"),!1;function ve(qA,PA){if((q=qA.exports).memory){var De,ft,En;De=q.memory,ft=I.buffer,De.byteLength0?Q:Te(a)+1,R=Array(f),q=Ue(a,R,0,R.length);return E&&(R.length=q),R}function dr(a){for(var E=[],Q=0;Q255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}l+=16,G=Ne(4),y=(S=w=Zt(l))+Et,N=Zt(y),c[G>>2]=N,D=!0,I.wasmTableSize=4,I.wasmMaxTableSize=4,I.asmGlobalArg={},I.asmLibraryArg={abort:ZA,assert:_A,enlargeMemory:tn,getTotalMemory:So,abortOnCannotGrowMemory:function(){ZA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+BA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(E,Q,f){var R=lt();try{return I.dynCall_iii(E,Q,f)}catch(q){if(ct(R),typeof q!="number"&&q!=="longjmp")throw q;I.setThrew(1,0)}},___assert_fail:function(E,Q,f,R){ZA("Assertion failed: "+Le(E)+", at: "+[Q?Le(Q):"unknown filename",f,R?Le(R):"unknown function"])},___setErrNo:function(E){return I.___errno_location&&(c[I.___errno_location()>>2]=E),E},_abort:function(){I.abort()},_emscripten_memcpy_big:function(E,Q,f){return o.set(o.subarray(Q,Q+f),E),E},_llvm_floor_f64:an,DYNAMICTOP_PTR:G,tempDoublePtr:wA,ABORT:be,STACKTOP:w,STACK_MAX:y};var gn=I.asm(I.asmGlobalArg,I.asmLibraryArg,n);I.asm=gn,I.___errno_location=function(){return I.asm.___errno_location.apply(null,arguments)};var xo=I._emscripten_replace_memory=function(){return I.asm._emscripten_replace_memory.apply(null,arguments)};I._free=function(){return I.asm._free.apply(null,arguments)};var Ye=I._malloc=function(){return I.asm._malloc.apply(null,arguments)};I._memcpy=function(){return I.asm._memcpy.apply(null,arguments)},I._memset=function(){return I.asm._memset.apply(null,arguments)},I._sbrk=function(){return I.asm._sbrk.apply(null,arguments)},I._stb_vorbis_js_channels=function(){return I.asm._stb_vorbis_js_channels.apply(null,arguments)},I._stb_vorbis_js_close=function(){return I.asm._stb_vorbis_js_close.apply(null,arguments)},I._stb_vorbis_js_decode=function(){return I.asm._stb_vorbis_js_decode.apply(null,arguments)},I._stb_vorbis_js_open=function(){return I.asm._stb_vorbis_js_open.apply(null,arguments)},I._stb_vorbis_js_sample_rate=function(){return I.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},I.establishStackSpace=function(){return I.asm.establishStackSpace.apply(null,arguments)},I.getTempRet0=function(){return I.asm.getTempRet0.apply(null,arguments)},I.runPostSets=function(){return I.asm.runPostSets.apply(null,arguments)},I.setTempRet0=function(){return I.asm.setTempRet0.apply(null,arguments)},I.setThrew=function(){return I.asm.setThrew.apply(null,arguments)};var Je=I.stackAlloc=function(){return I.asm.stackAlloc.apply(null,arguments)},ct=I.stackRestore=function(){return I.asm.stackRestore.apply(null,arguments)},lt=I.stackSave=function(){return I.asm.stackSave.apply(null,arguments)};function ye(a){this.name="ExitStatus",this.message="Program terminated with exit("+a+")",this.status=a}function ut(a){a=a||I.arguments,!(Ae>0)&&(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)ko(I.preRun.shift());me(nn)}(),!(Ae>0)&&(I.calledRun||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),E()},1)):E())));function E(){!I.calledRun&&(I.calledRun=!0,be||(ht||(ht=!0,me(Bt)),me(sn),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)wo(I.postRun.shift());me(rn)}()))}}function fr(a,E){(!E||!I.noExitRuntime||a!==0)&&(I.noExitRuntime||(be=!0,Xt=a,w=W,me(on),Do=!0,I.onExit&&I.onExit(a)),I.quit(a,new ye(a)))}function ZA(a){throw I.onAbort&&I.onAbort(a),a!==void 0?(Me(a),GA(a),a=JSON.stringify(a)):a="",be=!0,Xt=1,"abort("+a+"). Build with -s ASSERTIONS=1 for more info."}if(I.dynCall_iii=function(){return I.asm.dynCall_iii.apply(null,arguments)},I.asm=gn,I.ccall=zt,I.cwrap=function(E,Q,f,R){var q=(f=f||[]).every(function(_){return _==="number"});return Q!=="string"&&q&&!R?Wt(E):function(){return zt(E,Q,f,arguments,R)}},ye.prototype=Error(),ye.prototype.constructor=ye,pe=function a(){I.calledRun||ut(),I.calledRun||(pe=a)},I.run=ut,I.abort=ZA,I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();I.noExitRuntime=!0,ut(),I.onRuntimeInitialized=()=>{os=!0,rs()},OA.decode=function(a){return function(Q){if(!os)throw Error("Not initialized");var f={};function R(oe){return new Int32Array(I.HEAPU8.buffer,oe,1)[0]}function q(oe,dt){var ve=new ArrayBuffer(dt*Float32Array.BYTES_PER_ELEMENT),re=new Float32Array(ve);return re.set(new Float32Array(I.HEAPU8.buffer,oe,dt)),re}f.open=I.cwrap("stb_vorbis_js_open","number",[]),f.close=I.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=I.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=I.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=I.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var _,M,hA,rA,iA=f.open(),tA=(_=Q,M=Q.byteLength,hA=I._malloc(M),(rA=new Uint8Array(I.HEAPU8.buffer,hA,M)).set(new Uint8Array(_,0,M)),rA),v=I._malloc(4),pA=I._malloc(4),xA=f.decode(iA,tA.byteOffset,tA.byteLength,v,pA);if(I._free(tA.byteOffset),xA<0)throw f.close(iA),I._free(v),Error("stbvorbis decode failed: "+xA);for(var MA=f.channels(iA),NA=Array(MA),ee=new Int32Array(I.HEAPU32.buffer,R(v),MA),bA=0;bA=0&&(n=this.workletProcessorChannels[e]),t.messageType){case eA.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case eA.noteOff:this.noteOff(e,A);break;case eA.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case eA.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case eA.customcCcChange:n.customControllers[A[0]]=A[1];break;case eA.killNote:this.killNote(e,A);break;case eA.programChange:this.programChange(e,A[0],A[1]);break;case eA.channelPressure:this.channelPressure(e,A);break;case eA.polyPressure:this.polyPressure(e,A[0],A[1]);break;case eA.ccReset:e===TA?this.resetAllControllers():this.resetControllers(e);break;case eA.systemExclusive:this.systemExclusive(A);break;case eA.setChannelVibrato:if(e===TA)for(let i=0;i{let e=(A.midiControllers[EA+P.pitchWheelRange]>>7)+(A.midiControllers[EA+P.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[EA+P.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:yA.channelProperties,messageData:t})}function Yo(t,A,e){let n=t,s=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:n,centTuning:s*.0061}}function gs(t,A=0){let e=t[0];if(!(this.deviceID!==TA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:U(`%cUnrecognized SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let s;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),p(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),p(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let c=(t[5]<<7|t[6])-8192;s=Math.floor(c/81.92),this.setMasterTuning(s),p(`%cMaster Fine Tuning. Cents: %c${s}`,r.info,r.value);break;case 4:s=(t[5]-64)*100,this.setMasterTuning(s),p(`%cMaster Coarse Tuning. Cents: %c${s}`,r.info,r.value);break;default:U(`%cUnrecognized MIDI Device Control Real-time message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(p("%cGM system on",r.info),this.system="gm"):t[3]===3?(p("%cGM2 system on",r.info),this.system="gm2"):(p("%cGM system off, defaulting to GS",r.info),this.system="gs");break;case 8:switch(t[3]){case 2:case 7:let o=4;t[3]===7&&o++;let i=t[o++],C=t[o++];for(let B=0;B>1&1)===1&&this.setOctaveTuning(15+A,c);for(let B=0;B<7;B++)(t[5]>>B&1)===1&&this.setOctaveTuning(7+B+A,c);for(let B=0;B<7;B++)(t[6]>>B&1)===1&&this.setOctaveTuning(B+A,c);p(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${c.join(" ")}`,r.info,r.value);break;default:U(`%cUnrecognized MIDI Tuning standard message: %c${lA(t)}`,r.warn,r.unrecognized);break}break;default:U(`%cUnrecognized MIDI Realtime/non realtime message: %c${lA(t)}`,r.warn,r.unrecognized)}break;case 65:let n=function(){U(`%cUnrecognized Roland %cGS %cSysEx: %c${lA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let s=t[7];if(t[6]===127){s===0?(p("%cGS Reset received!",r.info),this.resetAllControllers(!1),this.system="gs"):s===127&&(p("%cGS system off, switching to GM2",r.info),this.resetAllControllers(!1),this.system="gm2");return}else if(t[4]===64){if((t[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A;switch(t[6]){default:n();break;case 21:let i=s>0&&t[5]>>4;this.setDrums(o,i),p(`%cChannel %c${o}%c ${i?"is now a drum channel":"now isn't a drum channel"}%c via: %c${lA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=s-64;this.transposeChannel(o,C),p(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${lA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let c=s;c===0&&(c=Math.floor(Math.random()*128)),this.controllerChange(o,m.pan,c);break;case 33:this.controllerChange(o,m.chorusDepth,s);break;case 34:this.controllerChange(o,m.reverbDepth,s);break;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let B=t.length-9,d=new Int8Array(12);for(let u=0;u=this.workletProcessorChannels.length)return;let o=t[6];switch(t[5]){case 1:this.controllerChange(s,m.bankSelect,o);break;case 2:this.controllerChange(s,m.lsbForControl0BankSelect,o);break;case 3:this.programChange(s,o);break;case 8:let i=this.workletProcessorChannels[s];if(i.drumChannel)return;let C=o-64;i.channelTransposeKeyShift=C;break;case 11:this.controllerChange(s,m.mainVolume,o);break;case 14:let c=o;c===0&&(c=Math.floor(Math.random()*127)),this.controllerChange(s,m.pan,c);break;case 19:this.controllerChange(s,m.reverbDepth,o);break;case 18:this.controllerChange(s,m.chorusDepth,o);break;default:U(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&U(`%cUnrecognized Yamaha XG SysEx: %c${lA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&U(`%cUnrecognized Yamaha SysEx: %c${lA(t)}`,r.warn,r.unrecognized);break}}function Cs(t,A,e){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=t[A.sourceIndex];else{let c=A.sourceIndex+EA;switch(A.sourceIndex){case P.noController:n=16383;break;case P.noteOnKeyNum:n=e.midiNote<<7;break;case P.noteOnVelocity:n=e.velocity<<7;break;case P.polyPressure:n=e.pressure<<7;break;default:n=t[c];break}}let s=fA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let c=A.secSrcIndex+EA;switch(A.secSrcIndex){case P.noController:o=16383;break;case P.noteOnKeyNum:o=e.midiNote<<7;break;case P.noteOnVelocity:o=e.velocity<<7;break;case P.polyPressure:o=e.pressure<<7;break;default:o=t[c]}}let i=fA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=s*i*A.transformAmount;return A.transformType===2&&(C=Math.abs(C)),A.currentValue=C,C}function XA(t,A,e=-1,n=0){let s=t.modulators,o=t.generators,i=t.modulatedGenerators;if(JA.recalculate(t),e===-1){i.set(o),s.forEach(B=>{let d=L[B.modulatorDestination],h=i[B.modulatorDestination]+Cs(A,B,t);i[B.modulatorDestination]=Math.max(d.min,Math.min(h,d.max))}),UA.recalculate(t);return}let C=new Set([g.initialAttenuation,g.delayVolEnv,g.attackVolEnv,g.holdVolEnv,g.decayVolEnv,g.sustainVolEnv,g.releaseVolEnv,g.keyNumToVolEnvHold,g.keyNumToVolEnvDecay]),c=new Set;s.forEach(B=>{if(B.sourceUsesCC===e&&B.sourceIndex===n||B.secSrcUsesCC===e&&B.secSrcIndex===n){let d=B.modulatorDestination;c.has(d)||(i[d]=o[d],Cs(A,B,t),s.forEach(h=>{if(h.modulatorDestination===d){let u=L[B.modulatorDestination],l=i[B.modulatorDestination]+h.currentValue;i[B.modulatorDestination]=Math.max(u.min,Math.min(l,u.max))}}),c.add(d))}}),[...c].some(B=>C.has(B))&&UA.recalculate(t)}var fA=[];for(let t=0;t<4;t++){fA[t]=[[new Float32Array(gA),new Float32Array(gA)],[new Float32Array(gA),new Float32Array(gA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||i.isMuted)return;let C=A+i.channelTransposeKeyShift;if(A>127||A<0)return;let c=i.preset.program;this.tunings[c]?.[A]?.midiNote>=0&&(C=this.tunings[c]?.[A].midiNote),i.velocityOverride>0&&(e=i.velocityOverride);let B=this.getWorkletVoices(t,C,e,i,o,n),d=i.voices;B.forEach(h=>{let u=h.generators[g.exclusiveClass];u!==0&&d.forEach(G=>{G.generators[g.exclusiveClass]===u&&(this.releaseVoice(G),G.modulatedGenerators[g.releaseVolEnv]=-7e3,G.modulatedGenerators[g.releaseModEnv]=-7e3,UA.recalculate(G),JA.recalculate(G))}),XA(h,i.midiControllers);let l=h.modulatedGenerators[g.startAddrsOffset]+h.modulatedGenerators[g.startAddrsCoarseOffset]*32768,D=h.modulatedGenerators[g.endAddrOffset]+h.modulatedGenerators[g.endAddrsCoarseOffset]*32768,S=h.modulatedGenerators[g.startloopAddrsOffset]+h.modulatedGenerators[g.startloopAddrsCoarseOffset]*32768,w=h.modulatedGenerators[g.endloopAddrsOffset]+h.modulatedGenerators[g.endloopAddrsCoarseOffset]*32768,y=h.sample,N=G=>Math.max(0,Math.min(y.sampleData.length-1,G));if(y.cursor=N(y.cursor+l),y.end=N(y.end+D),y.loopStart=N(y.loopStart+S),y.loopEnd=N(y.loopEnd+w),y.loopEndthis.voiceCap&&this.voiceKilling(B.length),d.push(...B),s&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Bs(t,A){if(A>127||A<0){U("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift,n=this.workletProcessorChannels[t].preset.program;if(this.tunings[n]?.[A]?.midiNote>=0&&(e=this.tunings[n]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(o=>{o.midiNote!==e||o.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function hs(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.midiNote===A&&(e.modulatedGenerators[g.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function Qs(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(n=>{n.isInRelease||this.releaseVoice(n)}),this.workletProcessorChannels[t].sustainedVoices.forEach(n=>{this.releaseVoice(n)}))}function cs(t=!1){p("%cStop all received!",r.info);for(let A=0;AXA(s,this.workletProcessorChannels[t].midiControllers,0,P.pitchWheel)),this.sendChannelProperties()}function Ss(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[EA+P.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(n=>XA(n,e.midiControllers,0,P.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function Ds(t,A,e){this.workletProcessorChannels[t].voices.forEach(n=>{n.midiNote===A&&(n.pressure=e,XA(n,this.workletProcessorChannels[t].midiControllers,0,P.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function ks(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function ws(t,A,e,n=!1){let s=this.workletProcessorChannels[t];if(s===void 0){U(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>127){if(!n)return;switch(A){default:return;case wt.velocityOverride:s.velocityOverride=e}}if(A>=m.lsbForControl1ModulationWheel&&A<=m.lsbForControl13EffectControl2&&A!==m.lsbForControl6DataEntry){let o=A-32;if(s.lockedControllers[o])return;s.midiControllers[o]=s.midiControllers[o]&16256|e&127,s.voices.forEach(i=>XA(i,s.midiControllers,1,o))}switch(A){case m.allNotesOff:this.stopAll(t);break;case m.allSoundOff:this.stopAll(t,!0);break;case m.bankSelect:let o=e;if(!n){switch(this.system){case"gm":p(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==DA&&this.setDrums(t,!1);break;case"gm2":o===120&&(s.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}s.drumChannel&&(o=128),o===128&&!s.drumChannel&&(o=s.midiControllers[m.bankSelect])}s.midiControllers[m.bankSelect]=o;break;case m.lsbForControl0BankSelect:this.system==="xg"?s.drumChannel||e!==127&&(s.midiControllers[m.bankSelect]=e):this.system==="gm2"&&(s.midiControllers[m.bankSelect]=e);break;case m.RPNLsb:s.RPValue=s.RPValue<<7|e,s.dataEntryState=dA.RPFine;break;case m.RPNMsb:s.RPValue=e,s.dataEntryState=dA.RPCoarse;break;case m.NRPNMsb:s.NRPCoarse=e,s.dataEntryState=dA.NRPCoarse;break;case m.NRPNLsb:s.NRPFine=e,s.dataEntryState=dA.NRPFine;break;case m.dataEntryMsb:this.dataEntryCoarse(t,e);break;case m.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case m.resetAllControllers:this.resetControllers(t);break;case m.sustainPedal:e>=64?s.holdPedal=!0:(s.holdPedal=!1,s.sustainedVoices.forEach(i=>{this.releaseVoice(i)}),s.sustainedVoices=[]);break;default:if(s.lockedControllers[A])return;s.midiControllers[A]=e<<7,s.voices.forEach(i=>XA(i,s.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function Fs(t){this.midiVolume=t,this.setMasterPan(this.pan)}function Rs(t){this.masterGain=t*Ut,this.setMasterPan(this.pan)}function Gs(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function xs(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function Ms(t){this.workletProcessorChannels[t].lockGSNRPNParams=!0,this.workletProcessorChannels[t].channelVibrato.rate=0,this.workletProcessorChannels[t].channelVibrato.delay=0,this.workletProcessorChannels[t].channelVibrato.depth=0}function Ns(t,A,e,n){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=n,this.workletProcessorChannels[t].channelVibrato.depth=A)}function bs(t,A){let e=this.workletProcessorChannels[t],n=()=>{e.channelVibrato.delay===0&&e.channelVibrato.rate===0&&e.channelVibrato.depth===0&&(e.channelVibrato.depth=50,e.channelVibrato.rate=8,e.channelVibrato.delay=.6)};switch(e.dataEntryState){default:case dA.Idle:break;case dA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;U(`%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;U(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16)} 0x${e.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(A===64)return;n(),e.channelVibrato.rate=A/64*8,p(`%cVibrato rate for %c${t}%c is now set to %c${A} = ${e.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(A===64)return;n(),e.channelVibrato.depth=A/2,p(`%cVibrato depth for %c${t}%c is now set to %c${A} = ${e.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(A===64)return;n(),e.channelVibrato.delay=A/64/3,p(`%cVibrato delay for %c${t}%c is now set to %c${A} = ${e.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let i=A;this.controllerChange(t,m.brightness,A),p(`%cFilter cutoff for %c${t}%c is now set to %c${i}`,r.info,r.recognized,r.info,r.value)}break;case 24:let s=A-64;e.keyCentTuning[e.NRPFine]=s*100,p(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${s}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,m.reverbDepth,o),p(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case dA.RPCoarse:case dA.RPFine:switch(e.RPValue){default:U(`%cUnrecognized RPN for %c${t}%c: %c(0x${e.RPValue.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 0:e.midiControllers[EA+P.pitchWheelRange]=A<<7,p(`%cChannel ${t} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(t,A-64);break;case 1:this.setChannelTuning(t,A-64,!1);break;case 5:this.setModulationDepth(t,A*100);break;case 16383:this.resetParameters(t);break}}}function Ls(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case dA.RPCoarse:case dA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[EA+P.pitchWheelRange]|=A;let n=(e.midiControllers[EA+P.pitchWheelRange]>>7)+A/127;p(`%cChannel ${t} bend range. Semitones: %c${n}`,r.info,r.value);break;case 1:let o=e.customControllers[IA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[IA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function Us(t=!0){t&&p("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A{this.workletProcessorChannels[A].lockedControllers[s]&&this.callEvent("controllerchange",{channel:A,controllerNumber:s,controllerValue:this.workletProcessorChannels[A].midiControllers[s]>>7})};if(n(m.mainVolume),n(m.pan),n(m.expressionController),n(m.modulationWheel),n(m.chorusDepth),n(m.reverbDepth),n(m.brightness),this.workletProcessorChannels[A].lockedControllers[EA+P.pitchWheel]){let s=this.workletProcessorChannels[A].midiControllers[EA+P.pitchWheel],o=s>>7,i=s&127;this.callEvent("pitchwheel",{channel:A,MSB:o,LSB:i})}}this.tunings=[],this.tunings=[];for(let A=0;127>A;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Oe}function Ts(t){let A=this.workletProcessorChannels[t],n=A.lockedControllers.reduce((o,i,C)=>(i&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(St),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,n.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let s=A.customControllers[IA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[IA.channelTransposeFine]=s,this.resetParameters(t)}function Hs(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=dA.Idle}function Ys(){let t=4;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>(o.generators=o.generators.filter(i=>i.generatorType!==g.sampleID&&i.generatorType!==g.keyRange&&i.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+s),0);let A=new H(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.generatorZoneStartIndex=e;for(let o of s.generators)Y(A,o.generatorType),Y(A,o.generatorValue),e++}return cA(A,0),nA(new AA("igen",A.length,A))}function Js(t,A,e,n,s){let o=this.samples.map((B,d)=>{e&&B.compressSample(n,s);let h=B.getRawData();return p(`%cEncoded sample %c${d}. ${B.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),h}),i=this.samples.reduce((B,d,h)=>B+o[h].length+46,0),C=new H(i);this.samples.forEach((B,d)=>{let h=o[d],u,l,D=h.length;B.isCompressed?(u=C.currentIndex,l=u+h.length):(u=C.currentIndex/2,l=u+h.length/2,D+=46),t.push(u),C.set(h,C.currentIndex),C.currentIndex+=D,A.push(l)});let c=nA(new AA("smpl",C.length,C),new H([115,100,116,97]));return nA(new AA("LIST",c.length,c))}function vs(t,A){let n=new H(46*(this.samples.length+1));return this.samples.forEach((s,o)=>{RA(n,s.sampleName,20);let i=t[o];cA(n,i);let C=A[o];cA(n,C);let c=s.sampleLoopStartIndex+i,B=s.sampleLoopEndIndex+i;s.isCompressed&&(c-=i,B-=i),cA(n,c),cA(n,B),cA(n,s.sampleRate),n[n.currentIndex++]=s.samplePitch,n[n.currentIndex++]=s.samplePitchCorrection,Y(n,s.sampleLink),Y(n,s.sampleType)}),RA(n,"EOS",46),nA(new AA("shdr",n.length,n))}function qs(){let t=10;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new H(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),nA(new AA("imod",A.length,A))}function Ps(){let t=this.instruments.reduce((o,i)=>i.instrumentZones.length*4+o,4),A=new H(t),e=0,n=0,s=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let i of o.instrumentZones)i.zoneID=e,Y(A,n),Y(A,s),n+=i.generators.length,s+=i.modulators.length,e++}return Y(A,n),Y(A,s),nA(new AA("ibag",A.length,A))}function Ks(){let t=this.instruments.length*22+22,A=new H(t),e=0,n=0;for(let s of this.instruments)RA(A,s.instrumentName,20),Y(A,e),e+=s.instrumentZones.length,s.instrumentID=n,n++;return RA(A,"EOI",20),Y(A,e),nA(new AA("inst",A.length,A))}function Vs(){let t=4;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>(o.generators=o.generators.filter(i=>i.generatorType!==g.instrument&&i.generatorType!==g.keyRange&&i.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+s),0);let A=new H(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.generatorZoneStartIndex=e;for(let o of s.generators)Y(A,o.generatorType),Y(A,o.generatorValue);e+=s.generators.length}return Y(A,0),Y(A,0),nA(new AA("pgen",A.length,A))}function Os(){let t=10;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new H(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),nA(new AA("pmod",A.length,A))}function Zs(){let t=this.presets.reduce((o,i)=>i.presetZones.length*4+o,4),A=new H(t),e=0,n=0,s=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let i of o.presetZones)i.zoneID=e,Y(A,n),Y(A,s),n+=i.generators.length,s+=i.modulators.length,e++}return Y(A,n),Y(A,s),nA(new AA("pbag",A.length,A))}function Xs(){let t=this.presets.length*38+38,A=new H(t),e=0;for(let n of this.presets)RA(A,n.presetName,20),Y(A,n.program),Y(A,n.bank),Y(A,e),cA(A,n.library),cA(A,n.genre),cA(A,n.morphology),e+=n.presetZones.length;return RA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,e),cA(A,0),cA(A,0),cA(A,0),nA(new AA("phdr",A.length,A))}var Jo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Ws(t=Jo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");SA("%cSaving soundfont...",r.info),p(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),p("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[K,W]of Object.entries(this.soundFontInfo))if(K==="ifil"||K==="iver"){let I=parseInt(W.split(".")[0]),sA=parseInt(W.split(".")[1]),j=new H(4);Y(j,I),Y(j,sA),A.push(nA(new AA(K,4,j)))}else if(K==="DMOD")A.push(nA(new AA(K,W.length,W)));else{let I=new H(W.length);RA(I,W),A.push(nA(new AA(K,W.length,I)))}let e=ke([new H([73,78,70,79]),...A]),n=nA(new AA("LIST",e.length,e));p("%cWriting SDTA...",r.info);let s=[],o=[],i=Js.call(this,s,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);p("%cWriting PDTA...",r.info),p("%cWriting SHDR...",r.info);let C=vs.call(this,s,o);p("%cWriting IGEN...",r.info);let c=Ys.call(this);p("%cWriting IMOD...",r.info);let B=qs.call(this);p("%cWriting IBAG...",r.info);let d=Ps.call(this);p("%cWriting INST...",r.info);let h=Ks.call(this),u=Vs.call(this);p("%cWriting PMOD...",r.info);let l=Os.call(this);p("%cWriting PBAG...",r.info);let D=Zs.call(this);p("%cWriting PHDR...",r.info);let S=Xs.call(this),w=ke([new H([112,100,116,97]),S,D,l,u,h,d,B,c,C]),y=nA(new AA("LIST",w.length,w));p("%cWriting the output file...",r.info);let N=ke([new H([115,102,98,107]),n,i,y]),G=nA(new AA("RIFF",N.length,N));return p(`%cSaved succesfully! Final file size: %c${G.length}`,r.info,r.recognized),X(),G}var se=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Pe.map(e=>$.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}static mergeSoundfonts(...A){let e=A.shift(),n=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(i=>i.bank===o.bank&&i.program===o.program)===void 0&&n.push(o)});return new t({presets:n,info:e.soundFontInfo})}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPresetNoFallback(A,e,n=!1){let s=this.presets.find(o=>o.bank===A&&o.program===e);if(s)return s;if(n!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}getPreset(A,e){let n=this.presets.find(s=>s.bank===A&&s.program===e);return n||(A===128?(n=this.presets.find(s=>s.bank===128&&s.program===e),n||(n=this.presets.find(s=>s.bank===128))):n=this.presets.find(s=>s.program===e&&s.bank!==128),n&&U(`%cPreset ${A}.${e} not found. Replaced with %c${n.presetName} (${n.bank}.${n.program})`,r.warn,r.recognized)),n||(U(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),n=this.presets[0]),n}getPresetByName(A){let e=this.presets.find(n=>n.presetName===A);return e||(U("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}};se.prototype.write=Ws;function _s(t){SA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let n=A;n{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}getSamplesAndGenerators(A,e){let n=this.foundSamplesAndGenerators[A][e];if(n)return n;if(this.presetZones.length<1)return[];function s(h,u,l){return l>=h&&l<=u}function o(h,u){h.push(...u.filter(l=>!h.find(D=>D.generatorType===l.generatorType)))}function i(h,u){h.push(...u.filter(l=>!h.find(D=>$.isIdentical(l,D))))}let C=[],c=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],B=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(h=>s(h.keyRange.min,h.keyRange.max,A)&&s(h.velRange.min,h.velRange.max,e)&&!h.isGlobal).forEach(h=>{if(h.instrument.instrumentZones.length<1)return;let u=h.generators,l=h.modulators,D=h.instrument.instrumentZones[0].isGlobal?[...h.instrument.instrumentZones[0].generators]:[],S=h.instrument.instrumentZones[0].isGlobal?[...h.instrument.instrumentZones[0].modulators]:[];h.instrument.instrumentZones.filter(y=>s(y.keyRange.min,y.keyRange.max,A)&&s(y.velRange.min,y.velRange.max,e)&&!y.isGlobal).forEach(y=>{let N=[...y.generators],G=[...y.modulators];o(u,c),o(N,D),i(l,B),i(G,S),i(G,this.defaultModulators);let K=[...G];for(let W=0;W$.isIdentical(I,j));sA!==-1?K[sA]=K[sA].sumTransform(I):K.push(I)}C.push({instrumentGenerators:N,presetGenerators:u,modulators:K,sample:y.sample,sampleID:y.generators.find(W=>W.generatorType===g.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=C,C}};var Re=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var $A=class extends Re{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},le=class extends Re{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var ue=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}get useCount(){return this._useCount}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var At=class extends ce{constructor(A,e){super(Pe),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new ue,this.DLSInstrument.addUseCount();let s=new le;s.instrument=this.DLSInstrument,this.presetZones=[s]}};function zs(t){this.verifyHeader(t,"LIST"),this.verifyText(V(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(l=>l.header==="insh");if(!e)throw X(),new Error("No instrument header!");let n=k(e.chunkData,4),s=k(e.chunkData,4),o=k(e.chunkData,4),i=new At(s,o),C="unnamedPreset",c=kA(A,"INFO");if(c){let l=O(c.chunkData);for(;l.header!=="INAM";)l=O(c.chunkData);C=V(l.chunkData,l.chunkData.length).trim()}i.presetName=C,i.DLSInstrument.instrumentName=C,te(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let B=kA(A,"lrgn");if(!B)throw X(),new Error("No region list!");let d=new $A;d.isGlobal=!0;let h=kA(A,"lart"),u=kA(A,"lar2");this.readLart(h,u,d),i.DLSInstrument.instrumentZones.push(d);for(let l=0;l>10&15;y===QA.linear&&w!==QA.linear&&(y=w);let N=n>>14&1,G=n>>15&1;i===g.initialAttenuation&&(G=!G),h=HA(y,N,G,C.isCC,C.enum)}let u=n>>4&15,l=n>>8&1,D=n>>9&1,S=HA(u,l,D,d.isCC,d.enum);if(c){let w=S;S=h,h=w}return new $({srcEnum:h,secSrcEnum:S,dest:i,transform:0,amt:s})}function Tt(t,A){let e=t.chunkData,n=[],s=[];k(e,4);let o=k(e,4);for(let i=0;i>16;if(C===0&&c===0&&d===0){let l;switch(B){case x.pan:l=new b(g.pan,u);break;case x.gain:l=new b(g.initialAttenuation,-u*10/.4);break;case x.filterCutoff:l=new b(g.initialFilterFc,u);break;case x.filterQ:l=new b(g.initialFilterQ,u);break;case x.modLfoFreq:l=new b(g.freqModLFO,u);break;case x.modLfoDelay:l=new b(g.delayModLFO,u);break;case x.vibLfoFreq:l=new b(g.freqVibLFO,u);break;case x.vibLfoDelay:l=new b(g.delayVibLFO,u);break;case x.volEnvDelay:l=new b(g.delayVolEnv,u);break;case x.volEnvAttack:l=new b(g.attackVolEnv,u);break;case x.volEnvHold:l=new b(g.holdVolEnv,u);break;case x.volEnvDecay:l=new b(g.decayVolEnv,u);break;case x.volEnvRelease:l=new b(g.releaseVolEnv,u);break;case x.volEnvSustain:let D=(1e3-u)/10;l=new b(g.sustainVolEnv,D*10);break;case x.modEnvDelay:l=new b(g.delayModEnv,u);break;case x.modEnvAttack:l=new b(g.attackModEnv,u);break;case x.modEnvHold:l=new b(g.holdModEnv,u);break;case x.modEnvDecay:l=new b(g.decayModEnv,u);break;case x.modEnvRelease:l=new b(g.releaseModEnv,u);break;case x.modEnvSustain:let S=1e3-u;l=new b(g.sustainModEnv,S);break;case x.reverbSend:l=new b(g.reverbEffectsSend,u);break;case x.chorusSend:l=new b(g.chorusEffectsSend,u);break;case x.pitch:let w=Math.floor(u/100),y=Math.floor(u-w*100);l=new b(g.fineTune,y),n.push(new b(g.coarseTune,w));break}l&&n.push(l)}else{let l=!0;if(c===z.none)if(C===z.modLfo&&B===x.pitch)n.push(new b(g.modLfoToPitch,u));else if(C===z.modLfo&&B===x.gain)n.push(new b(g.modLfoToVolume,u));else if(C===z.modLfo&&B===x.filterCutoff)n.push(new b(g.modLfoToFilterFc,u));else if(C===z.vibratoLfo&&B===x.pitch)n.push(new b(g.vibLfoToPitch,u));else if(C===z.modEnv&&B===x.pitch)n.push(new b(g.modEnvToPitch,u));else if(C===z.modEnv&&B===x.filterCutoff)n.push(new b(g.modEnvToFilterFc,u));else if(C===z.keyNum&&B===x.volEnvHold){n.push(new b(g.keyNumToVolEnvHold,u/-128));let D=Math.round(60/128*u);n.forEach(S=>{S.generatorType===g.holdVolEnv&&(S.generatorValue+=D)})}else if(C===z.keyNum&&B===x.volEnvDecay){n.push(new b(g.keyNumToVolEnvDecay,u/-128));let D=Math.round(60/128*u);n.forEach(S=>{S.generatorType===g.decayVolEnv&&(S.generatorValue+=D)})}else if(C===z.keyNum&&B===x.modEnvHold){n.push(new b(g.keyNumToModEnvHold,u/-128));let D=Math.round(60/128*u);n.forEach(S=>{S.generatorType===g.holdModEnv&&(S.generatorValue+=D)})}else if(C===z.keyNum&&B===x.modEnvDecay){n.push(new b(g.keyNumToModEnvDecay,u/-128));let D=Math.round(60/128*u);n.forEach(S=>{S.generatorType===g.decayModEnv&&(S.generatorValue+=D)})}else l=!1;else l=!1;if(l===!1){let D=$s(C,c,B,d,u);D?(s.push(D),p("%cSucceeded converting to SF2 Modulator!",r.recognized)):U("Failed converting to SF2 Modulator!")}}}return s.find(i=>i.modulatorDestination===g.reverbEffectsSend)===void 0&&s.push(new $({srcEnum:219,dest:g.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),s.find(i=>i.modulatorDestination===g.chorusEffectsSend)===void 0&&s.push(new $({srcEnum:221,dest:g.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&s.push(new $({srcEnum:129,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new $({srcEnum:13,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:s,generators:n}}function Ao(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(j=>j.header==="rgnh"),n=k(e.chunkData,2),s=k(e.chunkData,2),o=k(e.chunkData,2),i=k(e.chunkData,2),C=new et({min:n,max:s},{min:o,max:i});k(e.chunkData,2);let c=k(e.chunkData,2);c!==0&&C.generators.push(new b(g.exclusiveClass,c));let B=kA(A,"lart"),d=kA(A,"lar2");this.readLart(B,d,C),C.isGlobal=!1;let h=A.find(j=>j.header==="wsmp");k(h.chunkData,4);let u=k(h.chunkData,2),l=jA(h.chunkData[h.chunkData.currentIndex++],h.chunkData[h.chunkData.currentIndex++]),S=(k(h.chunkData,4)|0)/-655360;k(h.chunkData,4);let w=k(h.chunkData,4),y,N={start:0,end:0};if(w===0)y=0;else{k(h.chunkData,4),k(h.chunkData,4)===0?y=1:y=3,N.start=k(h.chunkData,4);let J=k(h.chunkData,4);N.end=N.start+J}let G=A.find(j=>j.header==="wlnk");if(G===void 0)return;k(G.chunkData,2),k(G.chunkData,2),k(G.chunkData,4);let K=k(G.chunkData,4),W=this.samples[K];if(W===void 0)throw new Error("Invalid sample ID!");let sA=(S||W.sampleDbAttenuation)*10/.4;return C.setWavesample(sA,y,N,u,W,K,l),C}var de=class{constructor(A,e,n,s,o,i,C,c){this.sampleName=A,this.sampleRate=e,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=i,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=c,this.isCompressed=(i&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,e){if(!this.isCompressed)try{this.compressedData=e([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{U(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}};var tt=class extends de{sampleDbAttenuation;sampleData;constructor(A,e,n,s,o,i,C,c){super(A,e,n,s,0,1,o,i-1),this.sampleData=C,this.sampleDbAttenuation=c}getAudioData(){return this.sampleData}getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let e=0;e>8&255}return A}};function to(t){SA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexJ.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");if(k(s.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(k(s.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=k(s.chunkData,4);k(s.chunkData,4),k(s.chunkData,2);let c=k(s.chunkData,2),B=c/8,d=Math.pow(2,B*8-1),h=Math.pow(2,B*8),u,l=!1;c===8?(u=255,l=!0):u=d;let D=n.find(J=>J.header==="data");if(!D)throw new Error("No data chunk in the wave chunk!");let S=D.size/B,w=new Float32Array(S);for(let J=0;J=d&&(Z-=h),w[J]=Z/u)}let y=60,N=0,G=0,K=w.length-1,W=0,I=n.find(J=>J.header==="wsmp");if(I){if(k(I.chunkData,4),y=k(I.chunkData,2),N=jA(I.chunkData[I.chunkData.currentIndex++],I.chunkData[I.chunkData.currentIndex++]),W=(k(I.chunkData,4)|0)/-655360,k(I.chunkData,4),k(I.chunkData,4)===1){k(I.chunkData,8),G=k(I.chunkData,4);let CA=k(I.chunkData,4);K=G+CA}}else U("No wsmp chunk in wave... using sane defaults.");let sA=kA(n,"INFO"),j=`Unnamed ${A}`;if(sA){let J=O(sA.chunkData);for(;J.header!=="INAM"&&sA.chunkData.currentIndex0&&(P+=this.tracks[S-1][this.tracks[S-1].length-1].ticks);y.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=P),_=cn[i>>4],(i&240)===F.noteOn){N.add(sA);let rA=y.data[y.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,rA),this.keyRange.max=Math.max(this.keyRange.max,rA)}x=i;break}let J=new H(_),z=y.data.slice(y.data.currentIndex,y.data.currentIndex+_);y.data.currentIndex+=_,J.set(z,0);let oA=new ie(P,i,J);switch(w.push(oA),sA){case-2:switch(i){case F.setTempo:this.tempoChanges.push({ticks:P,tempo:6e7/zA(z,3)});break;case F.marker:switch(V(J,J.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=P;break;case"loopend":h=P}J.currentIndex=0;break;case F.midiPort:let EA=J[0];this.midiPorts[S]=EA,this.midiPortChannelOffsets[EA]===void 0&&(this.midiPortChannelOffsets[EA]=l,l+=16);break;case F.copyright:o||(this.copyright+=V(J,J.length,void 0,!1)+` +`);break;case F.lyric:this.lyrics.push(J)}break;case-3:if(J.slice(0,7).every((rA,EA)=>bo[EA]===rA)){let rA=J.slice(7,z.length-3),EA=V(rA,rA.length)+` +`;this.copyright+=EA,p(`%cDecoded Roland SC message! %c${EA}`,r.recognized,r.value)}break;default:if((i&240)===F.controllerChange)switch(J[0]){case 2:case 116:d=P;break;case 4:case 117:h===null?h=P:h=0;break;case 0:C&&J[1]!==0&&J[1]!==127&&(p("%cDLS RMIDI with offset 1 detected!",r.recognized),this.bankOffset=1)}}}this.tracks.push(w),this.usedChannelsOnTrack.push(N),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,r.info,r.value,r.info,r.value)}p("%cAll tracks parsed correctly!",r.recognized),SA("%cCorrecting loops, ports and detecting notes...",r.info);let u=[];for(let S of this.tracks){let w=S.find(y=>(y.messageStatusByte&240)===F.noteOn);w&&u.push(w.ticks)}this.firstNoteOn=Math.min(...u),p(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,r.info,r.recognized,r.info),d!==null&&h===null?(d=this.firstNoteOn,h=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(h===null||h===0)&&(h=this.lastVoiceEventTick)),this.loop={start:d,end:h},p(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,r.info,r.recognized,r.info,r.recognized);let D=0;for(let S of this.midiPorts)if(S!==-1){D=S;break}if(this.midiPorts=this.midiPorts.map(S=>S===-1?D:S),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?p("%cNo additional MIDI Ports detected.",r.info):p("%cMIDI Ports detected!",r.recognized),!a)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){p("%cNo name detected. Using the alt name!",r.info),this.midiName=hn(e),this.rawMidiName=new Uint8Array(this.midiName.length);for(let S=0;Sl>h?l:h),n=[];for(let h=0;h{a[D]>=u.length||u[a[D]].ticks0;){let h=Q(),l=t.tracks[h];if(a[h]>=l.length){C--;continue}let u=l[a[h]];if(a[h]++,u.messageStatusByte===F.midiPort){B[h]=u.messageData[0];continue}let D=u.messageStatusByte&240;if(D!==F.noteOn&&D!==F.controllerChange&&D!==F.programChange&&D!==F.systemExclusive)continue;let S=(u.messageStatusByte&15)+t.midiPortChannelOffsets[B[h]]||0,w=n[S];switch(D){case F.programChange:w.program=u.messageData[0],s(w);break;case F.controllerChange:if(u.messageData[0]!==m.bankSelect||d==="gs"&&w.drums)continue;let y=u.messageData[1],N=Math.max(0,y-t.bankOffset);if(d==="xg"){let $=y===120||y===126||y===127;$!==w.drums?(w.drums=$,w.bank=w.drums?128:N,s(w)):w.bank=w.drums?128:N;continue}n[S].bank=N;break;case F.noteOn:if(u.messageData[1]===0)continue;s(w),o[w.string].add(`${u.messageData[0]}-${u.messageData[1]}`);break;case F.systemExclusive:if(u.messageData[0]!==65||u.messageData[2]!==66||u.messageData[3]!==18||u.messageData[4]!==64||!(u.messageData[5]&16)||u.messageData[6]!==21){u.messageData[0]===67&&u.messageData[2]===76&&u.messageData[5]===126&&u.messageData[6]===0&&(d="xg");continue}let x=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+t.midiPortChannelOffsets[B[h]],P=!!(u.messageData[7]>0&&u.messageData[5]>>4);w=n[x],w.drums=P,w.bank=P?128:0,s(w);break}}for(let h of Object.keys(o))o[h].size===0&&(p(`%cDetected change but no keys for %c${h}`,r.info,r.value),delete o[h]);return Z(),o}function Mn(t,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length{this.assignMIDIPort(e,A)}),this.duration=this.midiData.duration,this.firstNoteTime=Ce(this.midiData.firstNoteOn,this.midiData),p(`%cTotal song time: ${mt(Math.ceil(this.duration)).time}`,r.recognized),this.post(FA.songChange,[new Ze(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(U(`%cVery short song: (${mt(Math.round(this.duration)).time}). Disabling loop!`,r.warn),this.loop=!1),this.play(!0)}function bn(t){this.songs=t.reduce((A,e)=>{if(e.duration)return A.push(e),A;try{A.push(new ze(e.binary,e.altName||""))}catch(n){return this.post(FA.midiError,n.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function Ln(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Un(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}var KA=new Int16Array(127);KA[m.mainVolume]=100;KA[m.expressionController]=127;KA[m.pan]=64;KA[m.releaseTime]=64;KA[m.brightness]=64;KA[m.reverbDepth]=0;function Tn(t,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let e=this.synth.workletProcessorChannels.length,n=Array(e).fill(8192),s=[];for(let C=0;CC===m.dataDecrement||C===m.dataIncrement||C===m.dataEntryMsb||C===m.dataDecrement||C===m.lsbForControl6DataEntry||C===m.RPNLsb||C===m.RPNMsb||C===m.NRPNLsb||C===m.NRPNMsb||C===m.bankSelect||C===m.lsbForControl0BankSelect||C===m.resetAllControllers,a=[];for(let C=0;C=A)break}else if(this.playedTime>=t)break;let B=we(Q.messageStatusByte),d=B.channel+(this.midiPortChannelOffsets[this.midiPorts[C]]||0);switch(B.status){case F.noteOn:case F.noteOff:case F.keySignature:break;case F.pitchBend:n[d]=Q.messageData[1]<<7|Q.messageData[0];break;case F.programChange:let l=s[d];l.program=Q.messageData[0],l.actualBank=l.bank;break;case F.controllerChange:let u=Q.messageData[0];if(o(u)){let D=Q.messageData[1];if(u===m.bankSelect){s[d].bank=D;break}this.sendMIDIMessages?this.sendMIDICC(d,u,D):this.synth.controllerChange(d,u,D)}else a[d]===void 0&&(a[d]=Array.from(KA)),a[d][u]=Q.messageData[1];break;default:this._processEvent(Q,C);break}this.eventIndex[C]++,C=this._findFirstEventIndex();let h=this.tracks[C][this.eventIndex[C]];if(h===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(h.ticks-Q.ticks)}if(this.sendMIDIMessages){for(let C=0;C>7,n[C]&127),a[C]!==void 0&&a[C].forEach((Q,B)=>{Q!==KA[B]&&!o(B)&&this.sendMIDICC(C,B,Q)}),s[C].program>=0&&s[C].actualBank>=0){let Q=s[C].actualBank;this.sendMIDICC(C,m.bankSelect,Q),this.sendMIDIProgramChange(C,s[C].program)}}else for(let C=0;C>7,n[C]&127),a[C]!==void 0&&a[C].forEach((Q,B)=>{Q!==KA[B]&&!o(B)&&this.synth.controllerChange(C,B,Q)}),s[C].program>=0&&s[C].actualBank>=0){let Q=s[C].actualBank;this.synth.controllerChange(C,m.bankSelect,Q),this.synth.programChange(C,s[C].program)}return!0}function Hn(t=!1){if(this.midiData!==void 0){if(t){this.currentTime=0;return}if(this.currentTime>=this.duration){this.currentTime=0;return}this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),this.sendMIDIMessages||this.playingNotes.forEach(A=>{this.synth.noteOn(A.channel,A.midiNote,A.velocity,!1,!0)}),this.setProcessHandler()}}function Yn(t){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(FA.timeChange,currentTime-Ce(t,this.midiData));let A=this._playTo(0,t);this._recalculateStartTime(this.playedTime),A&&this.play()}function Jn(t){this.absoluteStartTime=currentTime-t/this._playbackRate}function vn(t,A){switch(t){default:break;case LA.loadNewSongList:this.loadNewSongList(A);break;case LA.pause:this.pause();break;case LA.play:this.play(A);break;case LA.stop:this.stop();break;case LA.setTime:this.currentTime=A;break;case LA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case LA.setPlaybackRate:this.playbackRate=A;break;case LA.setLoop:this.loop=A;break;case LA.changeSong:A?this.nextSong():this.previousSong();break;case LA.getMIDI:this.post(FA.getMIDI,this.midiData);break;case LA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function qn(t,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:yA.sequencerSpecific,messageData:{messageType:t,messageData:A}})}function Pn(t){this.post(FA.midiEvent,t)}function Kn(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|t,A,e])}function Vn(t,A){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|t,A])}function On(t,A,e){t%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|t,e,A])}function Zn(){if(this.sendMIDIMessages){this.sendMIDIMessage([F.reset]);for(let t=0;tthis.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&AXn?440*Math.pow(2,(t-6900)/1200):Rt[~~t-je]}var xt=-1660,Lo=1600,Gt=new Float32Array((Lo-xt)*100+1);for(let t=0;t.5?1:0,n?e*2-1:e;case cA.concave:return n?(e=e*2-1,e<0?1-Ee[~~(e*-CA)]-1:Ee[~~e*CA]):Ee[~~(e*CA)];case cA.convex:return n?(e=e*2-1,e<0?1-Be[~~(e*-CA)]-1:Be[~~(e*CA)]):Be[~~(e*CA)]}}var Mt=1,Nt=new Float32Array(1e3);for(let t=0;t=e.loopEnd;)n-=o;let C=~~n,Q=C+1;for(;Q>=e.loopEnd;)Q-=o;let B=n-C,d=s[Q],h=s[C];A[a]=h+(d-h)*B,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end){t.finished=!0;return}let Q=n-a,B=s[C],d=s[a];A[o]=d+(B-d)*Q,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function _n(t,A){let e=t.sample,n=e.cursor,s=e.loopEnd-e.loopStart,o=e.sampleData;if(t.sample.isLooping)for(let a=0;a=e.loopEnd;)n-=s;let C=~~n+1;for(;C>=e.loopEnd;)C-=s;A[a]=o[C],n+=e.playbackStep*t.currentTuningCalculated}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let a=0;a=e.end){t.finished=!0;return}A[a]=o[C],n+=e.playbackStep*t.currentTuningCalculated}}e.cursor=n}function zn(t,A){let e=t.sample,n=e.cursor,s=e.sampleData;if(e.isLooping){let o=e.loopEnd-e.loopStart;for(let a=0;a=e.loopEnd;)n-=o;let C=~~n,Q=C+1,B=Q+1,d=B+1,h=n-C;Q>=e.loopEnd&&(Q-=o),B>=e.loopEnd&&(B-=o),d>=e.loopEnd&&(d-=o);let l=s[C],u=s[Q],D=s[B],S=s[d],w=.5*(D-l),y=l-2.5*u+2*D-.5*S,N=.5*(S-l)+1.5*(u-D);A[a]=((N*h+y)*h+w)*h+u,n+=e.playbackStep*t.currentTuningCalculated}}else{if(e.loopingMode===2&&!t.isInRelease)return;for(let o=0;o=e.end||Q>=e.end||B>=e.end){t.finished=!0;return}let h=s[a],l=s[C],u=s[Q],D=s[B],S=.5*(u-h),w=h-2.5*l+2*u-.5*D,y=.5*(D-h)+1.5*(l-u);A[o]=((y*d+w)*d+S)*d+l,n+=e.playbackStep*t.currentTuningCalculated}}t.sample.cursor=n}function jn(t,A,e,n,s,o,a,C,Q){if(!isNaN(e[0])){if(a>0){let B=o[0],d=o[1];a=Math.min(a,1e3);let h=a/1300,l=t*h,u=A*h;for(let D=0;D0){let B=C[0],d=C[1];Q=Math.min(Q,1e3);let h=Q/1300,l=t*h,u=A*h;for(let D=0;D0)for(let B=0;B0)for(let B=0;B13499&&A.filter.reasonanceCb===0)return;let o=A.filter;(o.cutoffCents!==n||o.reasonanceCb!==A.modulatedGenerators[g.initialFilterQ])&&(o.cutoffCents=n,o.reasonanceCb=A.modulatedGenerators[g.initialFilterQ],t.calculateCoefficients(o));for(let a=0;a=bt}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,n=B=>Math.max(0,Math.floor(YA(B)*e.sampleRate));e.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[g.initialAttenuation],1440))/10,e.sustainDbRelative=Math.min(vA,A.modulatedGenerators[g.sustainVolEnv]/10);let s=Math.min(vA,e.sustainDbRelative);e.attackDuration=n(A.modulatedGenerators[g.attackVolEnv]);let o=A.modulatedGenerators[g.decayVolEnv],a=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvDecay],C=s/vA;e.decayDuration=n(o+a)*C,e.releaseDuration=n(A.modulatedGenerators[g.releaseVolEnv]),e.delayEnd=n(A.modulatedGenerators[g.delayVolEnv]),e.attackEnd=e.attackDuration+e.delayEnd;let Q=(60-A.targetKey)*A.modulatedGenerators[g.keyNumToVolEnvHold];if(e.holdEnd=n(A.modulatedGenerators[g.holdVolEnv]+Q)+e.attackEnd,e.decayEnd=e.decayDuration+e.holdEnd,e.state===0&&e.attackEnd===0&&(e.state=2),A.isInRelease){let B=Math.max(0,Math.min(vA,e.sustainDbRelative)),d=B/vA;switch(e.decayDuration=n(o+a)*d,e.state){case 0:e.releaseStartDb=vA;break;case 1:let h=1-(e.attackEnd-e.releaseStartTimeSamples)/e.attackDuration;e.releaseStartDb=20*Math.log10(h)*-1;break;case 2:e.releaseStartDb=0;break;case 3:e.releaseStartDb=(1-(e.decayEnd-e.releaseStartTimeSamples)/e.decayDuration)*B;break;case 4:e.releaseStartDb=B;break}e.releaseStartDb=Math.max(0,Math.min(e.releaseStartDb,vA)),e.releaseStartDb>=bt&&(A.finished=!0),e.currentReleaseGain=VA(e.releaseStartDb)}}static apply(A,e,n,s){let o=A.volumeEnvelope,a=n/10,C=s;if(A.isInRelease){let B=o.currentSampleTime-o.releaseStartTimeSamples;if(B>=o.releaseDuration){for(let h=0;h=e.length)return;o.state++;case 1:for(;o.currentSampleTime=e.length)return}o.state++;case 2:for(;o.currentSampleTime=e.length)return;o.state++;case 3:for(;o.currentSampleTime=e.length)return;o.state++;case 4:for(o.canEndOnSilentSustain&&o.sustainDbRelative>=bt&&(A.finished=!0);;)if(o.attenuation+=(o.attenuationTarget-o.attenuation)*C,e[Q]*=VA(o.sustainDbRelative+a+o.attenuation),o.currentAttenuationDb=o.sustainDbRelative,o.currentSampleTime++,++Q>=e.length)return}}};var As=Math.PI/2,es=.05;function ts(t,A,e,n,s,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,UA.startRelease(A),JA.startRelease(A),A.sample.loopingMode===3&&(A.sample.isLooping=!1)),A.modulatedGenerators[g.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let a=A.targetKey,C=A.modulatedGenerators[g.fineTune]+t.customControllers[gA.channelTuning]+t.customControllers[gA.channelTransposeFine]+t.customControllers[gA.masterTuning]+t.channelOctaveTuning[A.midiNote%12]+t.keyCentTuning[A.midiNote],Q=A.modulatedGenerators[g.coarseTune]+t.customControllers[gA.channelTuningSemitones],B=this.tunings[t.preset.program]?.[a];B?.midiNote>=0&&(a=B.midiNote,C+=B.centTuning),C+=(a-A.sample.rootKey)*A.modulatedGenerators[g.scaleTuning];let d=A.modulatedGenerators[g.vibLfoToPitch];if(d!==0){let oA=A.startTime+YA(A.modulatedGenerators[g.delayVibLFO]),rA=Fe(A.modulatedGenerators[g.freqVibLFO]),EA=$e(oA,rA,currentTime);C+=EA*(d*t.customControllers[gA.modulationMultiplier])}let h=A.modulatedGenerators[g.initialFilterFc],l=h,u=A.modulatedGenerators[g.modLfoToPitch],D=A.modulatedGenerators[g.modLfoToVolume],S=A.modulatedGenerators[g.modLfoToFilterFc],w=0;if(u+S+D!==0){let oA=A.startTime+YA(A.modulatedGenerators[g.delayModLFO]),rA=Fe(A.modulatedGenerators[g.freqModLFO]),EA=$e(oA,rA,currentTime);C+=EA*(u*t.customControllers[gA.modulationMultiplier]),w=-EA*D,l+=EA*S}if(t.channelVibrato.depth>0){let oA=$e(A.startTime+t.channelVibrato.delay,t.channelVibrato.rate,currentTime);oA&&(C+=oA*t.channelVibrato.depth)}let y=A.modulatedGenerators[g.modEnvToPitch],N=A.modulatedGenerators[g.modEnvToFilterFc],x=JA.getValue(A,currentTime);l+=x*N,C+=x*y;let P=~~(C+Q*100);P!==A.currentTuningCents&&(A.currentTuningCents=P,A.currentTuningCalculated=Math.pow(2,P/1200));let $=(Math.max(-500,Math.min(500,A.modulatedGenerators[g.pan]))+500)/1e3,i=new Float32Array(e.length);switch(this.interpolationType){case he.linear:default:Wn(A,i);break;case he.nearestNeighbor:_n(A,i);break;case he.fourthOrder:zn(A,i)}Qe.apply(A,i,l,h>13499),UA.apply(A,i,w,this.volumeEnvelopeSmoothingFactor),A.currentPan+=($-A.currentPan)*this.panSmoothingFactor;let sA=Math.cos(As*A.currentPan)*this.panLeft,_=Math.sin(As*A.currentPan)*this.panRight,J=this.oneOutputMode?0:A.modulatedGenerators[g.reverbEffectsSend],z=this.oneOutputMode?0:A.modulatedGenerators[g.chorusEffectsSend];jn(sA,_,i,e,n,s,J,o,z)}function To(t,A){let e=0;return t.drumChannel&&(e+=5),A.isInRelease&&(e-=5),e+=A.velocity/25,e-=A.volumeEnvelope.state,A.isInRelease&&(e-=5),e-=A.volumeEnvelope.currentAttenuationDb/50,e}function ns(t){let A=[];for(let n of this.workletProcessorChannels)for(let s of n.voices)if(!s.finished){let o=To(n,s);A.push({channel:n,voice:s,priority:o})}A.sort((n,s)=>n.priority-s.priority);let e=A.slice(0,t);for(let{channel:n,voice:s}of e){let o=n.voices.indexOf(s);o>-1&&n.voices.splice(o,1)}}function ss(t){t.releaseStartTime=currentTime,t.releaseStartTime-t.startTimers=t);var Ho=function(t){var A,e,n,s,o,a,C,Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",B="",d=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do s=Q.indexOf(t.charAt(d++)),o=Q.indexOf(t.charAt(d++)),a=Q.indexOf(t.charAt(d++)),C=Q.indexOf(t.charAt(d++)),A=s<<2|o>>4,e=(15&o)<<4|a>>2,n=(3&a)<<6|C,B+=String.fromCharCode(A),a!==64&&(B+=String.fromCharCode(e)),C!==64&&(B+=String.fromCharCode(n));while(d1&&(i.thisProgram=process.argv[1].replace(/\\/g,"/")),i.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(I){if(!(I instanceof ye))throw I}),process.on("unhandledRejection",function(I,E){process.exit(1)}),i.quit=function(I){process.exit(I)},i.inspect=function(){return"[Emscripten Module object]"}):oA?(typeof read<"u"&&(i.read=function(E){return read(E)}),i.readBinary=function(E){var c;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(_A(typeof(c=read(E,"binary"))=="object"),c)},typeof scriptArgs<"u"?i.arguments=scriptArgs:typeof arguments<"u"&&(i.arguments=arguments),typeof quit=="function"&&(i.quit=function(I){quit(I)})):(_||J)&&(_?document.currentScript&&(rA=document.currentScript.src):rA=self.location.href,rA=rA.indexOf("blob:")!==0?rA.split("/").slice(0,-1).join("/")+"/":"",i.read=function(E){var c=new XMLHttpRequest;return c.open("GET",E,!1),c.send(null),c.responseText},J&&(i.readBinary=function(E){var c=new XMLHttpRequest;return c.open("GET",E,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),i.readAsync=function(E,c,f){var R=new XMLHttpRequest;R.open("GET",E,!0),R.responseType="arraybuffer",R.onload=function(){if(R.status==200||R.status==0&&R.response){c(R.response);return}f()},R.onerror=f,R.send(null)},i.setWindowTitle=function(I){document.title=I});var Me=i.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),GA=i.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Me);for(t in sA)sA.hasOwnProperty(t)&&(i[t]=sA[t]);function Ne(I){var E=u;return u=u+I+15&-16,E}function Ot(I){var E=Q[x>>2],c=E+I+15&-16;return Q[x>>2]=c,c>=hA&&!tn()?(Q[x>>2]=E,0):E}function Zt(I,E){return E||(E=16),I=Math.ceil(I/E)*E}function fo(I){switch(I){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(I[I.length-1]==="*")return 4;if(I[0]!=="i")return 0;var E=parseInt(I.substr(1));return _A(E%8==0),E/8}}function fe(I){fe.shown||(fe.shown={}),fe.shown[I]||(fe.shown[I]=1,GA(I))}sA=void 0;var mo={"f64-rem":function(I,E){return I%E},debugger:function(){}},it=[];function Ko(I,E){for(var c=0,f=c;f>>0)+4294967296*+(E>>>0):+(I>>>0)+4294967296*+(0|E)}function It(I,E,c){return c&&c.length?i["dynCall_"+I].apply(null,[E].concat(c)):i["dynCall_"+I].call(null,E)}var be=0,Xt=0;function _A(I,E){I||ZA("Assertion failed: "+E)}function Wt(I){var E=i["_"+I];return _A(E,"Cannot call unknown function "+I+", make sure it is exported"),E}var _t={stackSave:function(){lt()},stackRestore:function(){ct()},arrayToC:function(I){var E,c,f=Je(I.length);return E=I,c=f,s.set(E,c),f},stringToC:function(I){var E=0;if(I!=null&&I!==0){var c=(I.length<<2)+1;E=Je(c),$t(I,E,c)}return E}},po={string:_t.stringToC,array:_t.arrayToC};function zt(I,E,c,f,R){var q=Wt(I),X=[],M=0;if(f)for(var QA=0;QA>0]=E;break;case"i16":a[I>>1]=E;break;case"i32":Q[I>>2]=E;break;case"i64":tempI64=[E>>>0,+Fo(tempDouble=E)>=1?tempDouble>0?(0|Go(+an(tempDouble/4294967296),4294967295))>>>0:~~+Ro((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],Q[I>>2]=tempI64[0],Q[I+4>>2]=tempI64[1];break;case"float":d[I>>2]=E;break;case"double":h[I>>3]=E;break;default:ZA("invalid type for setValue: "+c)}}function Xo(I,E,c){switch((E=E||"i8").charAt(E.length-1)==="*"&&(E="i32"),E){case"i1":case"i8":return s[I>>0];case"i16":return a[I>>1];case"i32":case"i64":return Q[I>>2];case"float":return d[I>>2];case"double":return h[I>>3];default:ZA("invalid type for getValue: "+E)}return null}function Wo(I,E,c,f){typeof I=="number"?(q=!0,X=I):(q=!1,X=I.length);var R=typeof E=="string"?E:null;if(M=c==4?f:[typeof Ye=="function"?Ye:Ne,Je,Ne,Ot][c===void 0?2:c](Math.max(X,R?1:E.length)),q){for(f=M,_A((3&M)==0),QA=M+(-4&X);f>2]=0;for(QA=M+X;f>0]=0;return M}if(R==="i8")return I.subarray||I.slice?o.set(I,M):o.set(new Uint8Array(I),M),M;for(var q,X,M,QA,iA,aA,tA,v=0;v>0],(f!=0||E)&&(X++,!E||X!=E););E||(E=X);var M="";if(q<128){for(;E>0;)R=String.fromCharCode.apply(String,o.subarray(I,I+Math.min(E,1024))),M=M?M+R:R,I+=1024,E-=1024;return M}return c=I,function(iA,aA){for(var tA=aA;iA[tA];)++tA;if(tA-aA>16&&iA.subarray&&jt)return jt.decode(iA.subarray(aA,tA));for(var v,pA,xA,MA,NA,ee,bA="";;){if(!(v=iA[aA++]))return bA;if(!(128&v)){bA+=String.fromCharCode(v);continue}if(pA=63&iA[aA++],(224&v)==192){bA+=String.fromCharCode((31&v)<<6|pA);continue}if(xA=63&iA[aA++],(240&v)==224?v=(15&v)<<12|pA<<6|xA:(MA=63&iA[aA++],(248&v)==240?v=(7&v)<<18|pA<<12|xA<<6|MA:(NA=63&iA[aA++],v=(252&v)==248?(3&v)<<24|pA<<18|xA<<12|MA<<6|NA:(1&v)<<30|pA<<24|xA<<18|MA<<12|NA<<6|(ee=63&iA[aA++]))),v<65536)bA+=String.fromCharCode(v);else{var Se=v-65536;bA+=String.fromCharCode(55296|Se>>10,56320|1023&Se)}}}(o,c)}function zo(I){for(var E="";;){var c=s[I++>>0];if(!c)return E;E+=String.fromCharCode(c)}}function jo(I,E){return function(f,R,q){for(var X=0;X>0]=f.charCodeAt(X);q||(s[R>>0]=0)}(I,E,!1)}var jt=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function Ue(I,E,c,f){if(!(f>0))return 0;for(var R=c,q=c+f-1,X=0;X=55296&&M<=57343&&(M=65536+((1023&M)<<10)|1023&I.charCodeAt(++X)),M<=127){if(c>=q)break;E[c++]=M}else if(M<=2047){if(c+1>=q)break;E[c++]=192|M>>6,E[c++]=128|63&M}else if(M<=65535){if(c+2>=q)break;E[c++]=224|M>>12,E[c++]=128|M>>6&63,E[c++]=128|63&M}else if(M<=2097151){if(c+3>=q)break;E[c++]=240|M>>18,E[c++]=128|M>>12&63,E[c++]=128|M>>6&63,E[c++]=128|63&M}else if(M<=67108863){if(c+4>=q)break;E[c++]=248|M>>24,E[c++]=128|M>>18&63,E[c++]=128|M>>12&63,E[c++]=128|M>>6&63,E[c++]=128|63&M}else{if(c+5>=q)break;E[c++]=252|M>>30,E[c++]=128|M>>24&63,E[c++]=128|M>>18&63,E[c++]=128|M>>12&63,E[c++]=128|M>>6&63,E[c++]=128|63&M}}return E[c]=0,c-R}function $t(I,E,c){return Ue(I,o,E,c)}function Te(I){for(var E=0,c=0;c=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&I.charCodeAt(++c)),f<=127?++E:f<=2047?E+=2:f<=65535?E+=3:f<=2097151?E+=4:f<=67108863?E+=5:E+=6}return E}var An=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function $o(I){for(var E=I,c=E>>1;a[c];)++c;if((E=c<<1)-I>32&&An)return An.decode(o.subarray(I,E));for(var f=0,R="";;){var q=a[I+2*f>>1];if(q==0)return R;++f,R+=String.fromCharCode(q)}}function Ar(I,E,c){if(c===void 0&&(c=2147483647),c<2)return 0;for(var f=E,R=(c-=2)<2*I.length?c/2:I.length,q=0;q>1]=X,E+=2}return a[E>>1]=0,E-f}function er(I){return 2*I.length}function tr(I){for(var E=0,c="";;){var f=Q[I+4*E>>2];if(f==0)return c;if(++E,f>=65536){var R=f-65536;c+=String.fromCharCode(55296|R>>10,56320|1023&R)}else c+=String.fromCharCode(f)}}function nr(I,E,c){if(c===void 0&&(c=2147483647),c<4)return 0;for(var f=E,R=f+c-4,q=0;q=55296&&X<=57343&&(X=65536+((1023&X)<<10)|1023&I.charCodeAt(++q)),Q[E>>2]=X,(E+=4)+4>R)break}return Q[E>>2]=0,E-f}function sr(I){for(var E=0,c=0;c=55296&&f<=57343&&++c,E+=4}return E}function or(I){var E=Te(I)+1,c=Ye(E);return c&&Ue(I,s,c,E),c}function rr(I){var E=Te(I)+1,c=Je(E);return Ue(I,s,c,E),c}function ir(I){return I}function ar(){var I,E=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(R){f=R}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return i.extraStackTrace&&(E+=` +`+i.extraStackTrace()),(I=E).replace(/__Z[\w\d_]+/g,function(c){var f,R=f=c;return c===R?c:c+" ["+R+"]"})}function gt(I,E){return I%E>0&&(I+=E-I%E),I}function en(I){i.buffer=n=I}function Ct(){i.HEAP8=s=new Int8Array(n),i.HEAP16=a=new Int16Array(n),i.HEAP32=Q=new Int32Array(n),i.HEAPU8=o=new Uint8Array(n),i.HEAPU16=C=new Uint16Array(n),i.HEAPU32=B=new Uint32Array(n),i.HEAPF32=d=new Float32Array(n),i.HEAPF64=h=new Float64Array(n)}function tn(){var I=i.usingWasm?65536:16777216,E=2147483648-I;if(Q[x>>2]>E)return!1;var c=hA;for(hA=Math.max(hA,16777216);hA>2];)hA=hA<=536870912?gt(2*hA,I):Math.min(gt((3*hA+2147483648)/4,I),E);var f=i.reallocBuffer(hA);return f&&f.byteLength==hA?(en(f),Ct(),!0):(hA=c,!1)}l=u=S=w=y=N=x=0,D=!1,i.reallocBuffer||(i.reallocBuffer=function(I){try{if(ArrayBuffer.transfer)E=ArrayBuffer.transfer(n,I);else{var E,c=s;E=new ArrayBuffer(I),new Int8Array(E).set(c)}}catch{return!1}return!!xo(E)&&E});try{(P=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{P=function(E){return E.byteLength}}var Et=i.TOTAL_STACK||5242880,hA=i.TOTAL_MEMORY||16777216;function So(){return hA}function me(I){for(;I.length>0;){var E=I.shift();if(typeof E=="function"){E();continue}var c=E.func;typeof c=="number"?E.arg===void 0?i.dynCall_v(c):i.dynCall_vi(c,E.arg):c(E.arg===void 0?null:E.arg)}}hA=0?I:E<=32?2*Math.abs(1<=f&&(E<=32||I>f)&&(I=-2*f+I),I}var Fo=Math.abs,Ro=Math.ceil,an=Math.floor,Go=Math.min,Ae=0,Qt=null,pe=null;function Qr(I){return I}i.preloadedImages={},i.preloadedAudios={};var In="data:application/octet-stream;base64,";function He(I){return String.prototype.startsWith?I.startsWith(In):I.indexOf(In)===0}(function(){var E="main.wast",c="main.wasm",f="main.temp.asm.js";He(E)||(E=EA(E)),He(c)||(c=EA(c)),He(f)||(f=EA(f));var R={global:null,env:null,asm2wasm:mo,parent:i},q=null;function X(tA){return tA}function M(){try{if(i.wasmBinary)return new Uint8Array(i.wasmBinary);if(i.readBinary)return i.readBinary(c);throw"both async and sync fetching of the wasm failed"}catch(tA){ZA(tA)}}i.asmPreload=i.asm;var QA=i.reallocBuffer,iA=function(tA){tA=gt(tA,i.usingWasm?65536:16777216);var v=i.buffer.byteLength;if(i.usingWasm)try{var pA=i.wasmMemory.grow((tA-v)/65536);return pA!==-1?i.buffer=i.wasmMemory.buffer:null}catch{return null}};i.reallocBuffer=function(tA){return aA==="asmjs"?QA(tA):iA(tA)};var aA="";i.asm=function(tA,v,pA){var xA;if(!(v=xA=v).table){var MA,NA=i.wasmTableSize;NA===void 0&&(NA=1024);var ee=i.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?ee!==void 0?v.table=new WebAssembly.Table({initial:NA,maximum:ee,element:"anyfunc"}):v.table=new WebAssembly.Table({initial:NA,element:"anyfunc"}):v.table=Array(NA),i.wasmTable=v.table}return v.memoryBase||(v.memoryBase=i.STATIC_BASE),v.tableBase||(v.tableBase=0),MA=function(Se,oe,dt){if(typeof WebAssembly!="object")return GA("no native wasm support detected"),!1;if(!(i.wasmMemory instanceof WebAssembly.Memory))return GA("no native wasm Memory in use"),!1;function ve(qA,PA){if((q=qA.exports).memory){var De,ft,En;De=q.memory,ft=i.buffer,De.byteLength0?c:Te(I)+1,R=Array(f),q=Ue(I,R,0,R.length);return E&&(R.length=q),R}function dr(I){for(var E=[],c=0;c255&&(f&=255),E.push(String.fromCharCode(f))}return E.join("")}u+=16,x=Ne(4),y=(S=w=Zt(u))+Et,N=Zt(y),Q[x>>2]=N,D=!0,i.wasmTableSize=4,i.wasmMaxTableSize=4,i.asmGlobalArg={},i.asmLibraryArg={abort:ZA,assert:_A,enlargeMemory:tn,getTotalMemory:So,abortOnCannotGrowMemory:function(){ZA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+hA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(E,c,f){var R=lt();try{return i.dynCall_iii(E,c,f)}catch(q){if(ct(R),typeof q!="number"&&q!=="longjmp")throw q;i.setThrew(1,0)}},___assert_fail:function(E,c,f,R){ZA("Assertion failed: "+Le(E)+", at: "+[c?Le(c):"unknown filename",f,R?Le(R):"unknown function"])},___setErrNo:function(E){return i.___errno_location&&(Q[i.___errno_location()>>2]=E),E},_abort:function(){i.abort()},_emscripten_memcpy_big:function(E,c,f){return o.set(o.subarray(c,c+f),E),E},_llvm_floor_f64:an,DYNAMICTOP_PTR:x,tempDoublePtr:wA,ABORT:be,STACKTOP:w,STACK_MAX:y};var gn=i.asm(i.asmGlobalArg,i.asmLibraryArg,n);i.asm=gn,i.___errno_location=function(){return i.asm.___errno_location.apply(null,arguments)};var xo=i._emscripten_replace_memory=function(){return i.asm._emscripten_replace_memory.apply(null,arguments)};i._free=function(){return i.asm._free.apply(null,arguments)};var Ye=i._malloc=function(){return i.asm._malloc.apply(null,arguments)};i._memcpy=function(){return i.asm._memcpy.apply(null,arguments)},i._memset=function(){return i.asm._memset.apply(null,arguments)},i._sbrk=function(){return i.asm._sbrk.apply(null,arguments)},i._stb_vorbis_js_channels=function(){return i.asm._stb_vorbis_js_channels.apply(null,arguments)},i._stb_vorbis_js_close=function(){return i.asm._stb_vorbis_js_close.apply(null,arguments)},i._stb_vorbis_js_decode=function(){return i.asm._stb_vorbis_js_decode.apply(null,arguments)},i._stb_vorbis_js_open=function(){return i.asm._stb_vorbis_js_open.apply(null,arguments)},i._stb_vorbis_js_sample_rate=function(){return i.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},i.establishStackSpace=function(){return i.asm.establishStackSpace.apply(null,arguments)},i.getTempRet0=function(){return i.asm.getTempRet0.apply(null,arguments)},i.runPostSets=function(){return i.asm.runPostSets.apply(null,arguments)},i.setTempRet0=function(){return i.asm.setTempRet0.apply(null,arguments)},i.setThrew=function(){return i.asm.setThrew.apply(null,arguments)};var Je=i.stackAlloc=function(){return i.asm.stackAlloc.apply(null,arguments)},ct=i.stackRestore=function(){return i.asm.stackRestore.apply(null,arguments)},lt=i.stackSave=function(){return i.asm.stackSave.apply(null,arguments)};function ye(I){this.name="ExitStatus",this.message="Program terminated with exit("+I+")",this.status=I}function ut(I){I=I||i.arguments,!(Ae>0)&&(function(){if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)ko(i.preRun.shift());me(nn)}(),!(Ae>0)&&(i.calledRun||(i.setStatus?(i.setStatus("Running..."),setTimeout(function(){setTimeout(function(){i.setStatus("")},1),E()},1)):E())));function E(){!i.calledRun&&(i.calledRun=!0,be||(ht||(ht=!0,me(Bt)),me(sn),i.onRuntimeInitialized&&i.onRuntimeInitialized(),function(){if(i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;)wo(i.postRun.shift());me(rn)}()))}}function fr(I,E){(!E||!i.noExitRuntime||I!==0)&&(i.noExitRuntime||(be=!0,Xt=I,w=$,me(on),Do=!0,i.onExit&&i.onExit(I)),i.quit(I,new ye(I)))}function ZA(I){throw i.onAbort&&i.onAbort(I),I!==void 0?(Me(I),GA(I),I=JSON.stringify(I)):I="",be=!0,Xt=1,"abort("+I+"). Build with -s ASSERTIONS=1 for more info."}if(i.dynCall_iii=function(){return i.asm.dynCall_iii.apply(null,arguments)},i.asm=gn,i.ccall=zt,i.cwrap=function(E,c,f,R){var q=(f=f||[]).every(function(X){return X==="number"});return c!=="string"&&q&&!R?Wt(E):function(){return zt(E,c,f,arguments,R)}},ye.prototype=Error(),ye.prototype.constructor=ye,pe=function I(){i.calledRun||ut(),i.calledRun||(pe=I)},i.run=ut,i.abort=ZA,i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();i.noExitRuntime=!0,ut(),i.onRuntimeInitialized=()=>{os=!0,rs()},OA.decode=function(I){return function(c){if(!os)throw Error("Not initialized");var f={};function R(oe){return new Int32Array(i.HEAPU8.buffer,oe,1)[0]}function q(oe,dt){var ve=new ArrayBuffer(dt*Float32Array.BYTES_PER_ELEMENT),re=new Float32Array(ve);return re.set(new Float32Array(i.HEAPU8.buffer,oe,dt)),re}f.open=i.cwrap("stb_vorbis_js_open","number",[]),f.close=i.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=i.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=i.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=i.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var X,M,QA,iA,aA=f.open(),tA=(X=c,M=c.byteLength,QA=i._malloc(M),(iA=new Uint8Array(i.HEAPU8.buffer,QA,M)).set(new Uint8Array(X,0,M)),iA),v=i._malloc(4),pA=i._malloc(4),xA=f.decode(aA,tA.byteOffset,tA.byteLength,v,pA);if(i._free(tA.byteOffset),xA<0)throw f.close(aA),i._free(v),Error("stbvorbis decode failed: "+xA);for(var MA=f.channels(aA),NA=Array(MA),ee=new Int32Array(i.HEAPU32.buffer,R(v),MA),bA=0;bA=0&&(n=this.workletProcessorChannels[e]),t.messageType){case eA.noteOn:this.noteOn(e,A[0],A[1],A[2]);break;case eA.noteOff:this.noteOff(e,A);break;case eA.pitchWheel:this.pitchWheel(e,A[0],A[1]);break;case eA.ccChange:this.controllerChange(e,A[0],A[1],A[2]);break;case eA.customcCcChange:n.customControllers[A[0]]=A[1];break;case eA.killNote:this.killNote(e,A);break;case eA.programChange:this.programChange(e,A[0],A[1]);break;case eA.channelPressure:this.channelPressure(e,A);break;case eA.polyPressure:this.polyPressure(e,A[0],A[1]);break;case eA.ccReset:e===TA?this.resetAllControllers():this.resetControllers(e);break;case eA.systemExclusive:this.systemExclusive(A);break;case eA.setChannelVibrato:if(e===TA)for(let a=0;a{let e=(A.midiControllers[BA+K.pitchWheelRange]>>7)+(A.midiControllers[BA+K.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[BA+K.pitchWheel],pitchBendRangeSemitones:e,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:yA.channelProperties,messageData:t})}function Yo(t,A,e){let n=t,s=A<<7|e;return t===127&&A===127&&e===127?{midiNote:-1,centTuning:null}:{midiNote:n,centTuning:s*.0061}}function gs(t,A=0){let e=t[0];if(!(this.deviceID!==TA&&t[1]!==127&&this.deviceID!==t[1]))switch(e){default:U(`%cUnrecognized SysEx: %c${uA(t)}`,r.warn,r.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let s;switch(t[3]){case 1:let o=t[5]<<7|t[4];this.setMIDIVolume(o/16384),p(`%cMaster Volume. Volume: %c${o}`,r.info,r.value);break;case 2:let C=((t[5]<<7|t[4])-8192)/8192;this.setMasterPan(C),p(`%cMaster Pan. Pan: %c${C}`,r.info,r.value);break;case 3:let Q=(t[5]<<7|t[6])-8192;s=Math.floor(Q/81.92),this.setMasterTuning(s),p(`%cMaster Fine Tuning. Cents: %c${s}`,r.info,r.value);break;case 4:s=(t[5]-64)*100,this.setMasterTuning(s),p(`%cMaster Coarse Tuning. Cents: %c${s}`,r.info,r.value);break;default:U(`%cUnrecognized MIDI Device Control Real-time message: %c${uA(t)}`,r.warn,r.unrecognized)}break;case 9:t[3]===1?(p("%cGM system on",r.info),this.system="gm"):t[3]===3?(p("%cGM2 system on",r.info),this.system="gm2"):(p("%cGM system off, defaulting to GS",r.info),this.system="gs");break;case 8:switch(t[3]){case 2:case 7:let o=4;t[3]===7&&o++;let a=t[o++],C=t[o++];for(let B=0;B>1&1)===1&&this.setOctaveTuning(15+A,Q);for(let B=0;B<7;B++)(t[5]>>B&1)===1&&this.setOctaveTuning(7+B+A,Q);for(let B=0;B<7;B++)(t[6]>>B&1)===1&&this.setOctaveTuning(B+A,Q);p(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${Q.join(" ")}`,r.info,r.value);break;default:U(`%cUnrecognized MIDI Tuning standard message: %c${uA(t)}`,r.warn,r.unrecognized);break}break;default:U(`%cUnrecognized MIDI Realtime/non realtime message: %c${uA(t)}`,r.warn,r.unrecognized)}break;case 65:let n=function(){U(`%cUnrecognized Roland %cGS %cSysEx: %c${uA(t)}`,r.warn,r.recognized,r.warn,r.unrecognized)};if(t[2]===66&&t[3]===18){let s=t[7];if(t[6]===127){s===0?(p("%cGS Reset received!",r.info),this.resetAllControllers(!1),this.system="gs"):s===127&&(p("%cGS system off, switching to GM2",r.info),this.resetAllControllers(!1),this.system="gm2");return}else if(t[4]===64){if((t[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A;switch(t[6]){default:n();break;case 21:let a=s>0&&t[5]>>4;this.setDrums(o,a),p(`%cChannel %c${o}%c ${a?"is now a drum channel":"now isn't a drum channel"}%c via: %c${uA(t)}`,r.info,r.value,r.recognized,r.info,r.value);return;case 22:let C=s-64;this.transposeChannel(o,C),p(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${uA(t)}`,r.info,r.recognized,r.info,r.value,r.info,r.value);return;case 28:let Q=s;Q===0&&(Q=Math.floor(Math.random()*128)),this.controllerChange(o,m.pan,Q);break;case 33:this.controllerChange(o,m.chorusDepth,s);break;case 34:this.controllerChange(o,m.reverbDepth,s);break;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let B=t.length-9,d=new Int8Array(12);for(let l=0;l=this.workletProcessorChannels.length)return;let o=t[6];switch(t[5]){case 1:this.controllerChange(s,m.bankSelect,o);break;case 2:this.controllerChange(s,m.lsbForControl0BankSelect,o);break;case 3:this.programChange(s,o);break;case 8:let a=this.workletProcessorChannels[s];if(a.drumChannel)return;let C=o-64;a.channelTransposeKeyShift=C;break;case 11:this.controllerChange(s,m.mainVolume,o);break;case 14:let Q=o;Q===0&&(Q=Math.floor(Math.random()*127)),this.controllerChange(s,m.pan,Q);break;case 19:this.controllerChange(s,m.reverbDepth,o);break;case 18:this.controllerChange(s,m.chorusDepth,o);break;default:U(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,r.warn,r.unrecognized)}}else this.system==="xg"&&U(`%cUnrecognized Yamaha XG SysEx: %c${uA(t)}`,r.warn,r.unrecognized);else this.system==="xg"&&U(`%cUnrecognized Yamaha SysEx: %c${uA(t)}`,r.warn,r.unrecognized);break}}function Cs(t,A,e){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=t[A.sourceIndex];else{let Q=A.sourceIndex+BA;switch(A.sourceIndex){case K.noController:n=16383;break;case K.noteOnKeyNum:n=e.midiNote<<7;break;case K.noteOnVelocity:n=e.velocity<<7;break;case K.polyPressure:n=e.pressure<<7;break;default:n=t[Q];break}}let s=mA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=t[A.secSrcIndex];else{let Q=A.secSrcIndex+BA;switch(A.secSrcIndex){case K.noController:o=16383;break;case K.noteOnKeyNum:o=e.midiNote<<7;break;case K.noteOnVelocity:o=e.velocity<<7;break;case K.polyPressure:o=e.pressure<<7;break;default:o=t[Q]}}let a=mA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],C=s*a*A.transformAmount;return A.transformType===2&&(C=Math.abs(C)),A.currentValue=C,C}function XA(t,A,e=-1,n=0){let s=t.modulators,o=t.generators,a=t.modulatedGenerators;if(JA.recalculate(t),e===-1){a.set(o),s.forEach(B=>{let d=L[B.modulatorDestination],h=a[B.modulatorDestination]+Cs(A,B,t);a[B.modulatorDestination]=Math.max(d.min,Math.min(h,d.max))}),UA.recalculate(t);return}let C=new Set([g.initialAttenuation,g.delayVolEnv,g.attackVolEnv,g.holdVolEnv,g.decayVolEnv,g.sustainVolEnv,g.releaseVolEnv,g.keyNumToVolEnvHold,g.keyNumToVolEnvDecay]),Q=new Set;s.forEach(B=>{if(B.sourceUsesCC===e&&B.sourceIndex===n||B.secSrcUsesCC===e&&B.secSrcIndex===n){let d=B.modulatorDestination;Q.has(d)||(a[d]=o[d],Cs(A,B,t),s.forEach(h=>{if(h.modulatorDestination===d){let l=L[B.modulatorDestination],u=a[B.modulatorDestination]+h.currentValue;a[B.modulatorDestination]=Math.max(l.min,Math.min(u,l.max))}}),Q.add(d))}}),[...Q].some(B=>C.has(B))&&UA.recalculate(t)}var mA=[];for(let t=0;t<4;t++){mA[t]=[[new Float32Array(CA),new Float32Array(CA)],[new Float32Array(CA),new Float32Array(CA)]];for(let A=0;A200&&e<40||this.highPerformanceMode&&e<10||a.isMuted)return;let C=A+a.channelTransposeKeyShift;if(A>127||A<0)return;let Q=a.preset.program;this.tunings[Q]?.[A]?.midiNote>=0&&(C=this.tunings[Q]?.[A].midiNote),a.velocityOverride>0&&(e=a.velocityOverride);let B=this.getWorkletVoices(t,C,e,a,o,n),d=a.voices;B.forEach(h=>{let l=h.generators[g.exclusiveClass];l!==0&&d.forEach(x=>{x.generators[g.exclusiveClass]===l&&(this.releaseVoice(x),x.modulatedGenerators[g.releaseVolEnv]=-7e3,x.modulatedGenerators[g.releaseModEnv]=-7e3,UA.recalculate(x),JA.recalculate(x))}),XA(h,a.midiControllers);let u=h.modulatedGenerators[g.startAddrsOffset]+h.modulatedGenerators[g.startAddrsCoarseOffset]*32768,D=h.modulatedGenerators[g.endAddrOffset]+h.modulatedGenerators[g.endAddrsCoarseOffset]*32768,S=h.modulatedGenerators[g.startloopAddrsOffset]+h.modulatedGenerators[g.startloopAddrsCoarseOffset]*32768,w=h.modulatedGenerators[g.endloopAddrsOffset]+h.modulatedGenerators[g.endloopAddrsCoarseOffset]*32768,y=h.sample,N=x=>Math.max(0,Math.min(y.sampleData.length-1,x));if(y.cursor=N(y.cursor+u),y.end=N(y.end+D),y.loopStart=N(y.loopStart+S),y.loopEnd=N(y.loopEnd+w),y.loopEndthis.voiceCap&&this.voiceKilling(B.length),d.push(...B),s&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:t,velocity:e}))}function Bs(t,A){if(A>127||A<0){U("Received a noteOn for note",A,"Ignoring.");return}let e=A+this.workletProcessorChannels[t].channelTransposeKeyShift,n=this.workletProcessorChannels[t].preset.program;if(this.tunings[n]?.[A]?.midiNote>=0&&(e=this.tunings[n]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[t].drumChannel){this.killNote(t,e);return}this.workletProcessorChannels[t].voices.forEach(o=>{o.midiNote!==e||o.isInRelease===!0||(this.workletProcessorChannels[t].holdPedal?this.workletProcessorChannels[t].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:t})}function hs(t,A){this.workletProcessorChannels[t].voices.forEach(e=>{e.midiNote===A&&(e.modulatedGenerators[g.releaseVolEnv]=-12e3,this.releaseVoice(e))})}function Qs(t,A=!1){let e=this.workletProcessorChannels[t].voices;A?(e.length=0,this.workletProcessorChannels[t].sustainedVoices.length=0,this.sendChannelProperties()):(e.forEach(n=>{n.isInRelease||this.releaseVoice(n)}),this.workletProcessorChannels[t].sustainedVoices.forEach(n=>{this.releaseVoice(n)}))}function cs(t=!1){p("%cStop all received!",r.info);for(let A=0;AXA(s,this.workletProcessorChannels[t].midiControllers,0,K.pitchWheel)),this.sendChannelProperties()}function Ss(t,A){let e=this.workletProcessorChannels[t];e.midiControllers[BA+K.channelPressure]=A<<7,this.workletProcessorChannels[t].voices.forEach(n=>XA(n,e.midiControllers,0,K.channelPressure)),this.callEvent("channelpressure",{channel:t,pressure:A})}function Ds(t,A,e){this.workletProcessorChannels[t].voices.forEach(n=>{n.midiNote===A&&(n.pressure=e,XA(n,this.workletProcessorChannels[t].midiControllers,0,K.polyPressure))}),this.callEvent("polypressure",{channel:t,midiNote:A,pressure:e})}function ks(t,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[t].channelOctaveTuning=A}function ws(t,A,e,n=!1){let s=this.workletProcessorChannels[t];if(s===void 0){U(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(A>127){if(!n)return;switch(A){default:return;case wt.velocityOverride:s.velocityOverride=e}}if(A>=m.lsbForControl1ModulationWheel&&A<=m.lsbForControl13EffectControl2&&A!==m.lsbForControl6DataEntry){let o=A-32;if(s.lockedControllers[o])return;s.midiControllers[o]=s.midiControllers[o]&16256|e&127,s.voices.forEach(a=>XA(a,s.midiControllers,1,o))}switch(A){case m.allNotesOff:this.stopAll(t);break;case m.allSoundOff:this.stopAll(t,!0);break;case m.bankSelect:let o=e;if(!n){switch(this.system){case"gm":p(`%cIgnoring the Bank Select (${e}), as the synth is in GM mode.`,r.info);return;case"xg":o===120||o===126||o===127?this.setDrums(t,!0):t%16!==DA&&this.setDrums(t,!1);break;case"gm2":o===120&&(s.drumChannel=!0,this.callEvent("drumchange",{channel:t,isDrumChannel:!0}))}s.drumChannel&&(o=128),o===128&&!s.drumChannel&&(o=s.midiControllers[m.bankSelect])}s.midiControllers[m.bankSelect]=o;break;case m.lsbForControl0BankSelect:this.system==="xg"?s.drumChannel||e!==127&&(s.midiControllers[m.bankSelect]=e):this.system==="gm2"&&(s.midiControllers[m.bankSelect]=e);break;case m.RPNLsb:s.RPValue=s.RPValue<<7|e,s.dataEntryState=fA.RPFine;break;case m.RPNMsb:s.RPValue=e,s.dataEntryState=fA.RPCoarse;break;case m.NRPNMsb:s.NRPCoarse=e,s.dataEntryState=fA.NRPCoarse;break;case m.NRPNLsb:s.NRPFine=e,s.dataEntryState=fA.NRPFine;break;case m.dataEntryMsb:this.dataEntryCoarse(t,e);break;case m.lsbForControl6DataEntry:this.dataEntryFine(t,e);break;case m.resetAllControllers:this.resetControllers(t);break;case m.sustainPedal:e>=64?s.holdPedal=!0:(s.holdPedal=!1,s.sustainedVoices.forEach(a=>{this.releaseVoice(a)}),s.sustainedVoices=[]);break;default:if(s.lockedControllers[A])return;s.midiControllers[A]=e<<7,s.voices.forEach(a=>XA(a,s.midiControllers,1,A)),this.callEvent("controllerchange",{channel:t,controllerNumber:A,controllerValue:e});break}}function Fs(t){this.midiVolume=t,this.setMasterPan(this.pan)}function Rs(t){this.masterGain=t*Ut,this.setMasterPan(this.pan)}function Gs(t){this.pan=t,t=t/2+.5,this.panLeft=(1-t)*this.currentGain,this.panRight=t*this.currentGain}function xs(t,A){A&&this.stopAll(t,!0),this.workletProcessorChannels[t].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:t,isMuted:A})}function Ms(t){this.workletProcessorChannels[t].lockGSNRPNParams=!0,this.workletProcessorChannels[t].channelVibrato.rate=0,this.workletProcessorChannels[t].channelVibrato.delay=0,this.workletProcessorChannels[t].channelVibrato.depth=0}function Ns(t,A,e,n){this.workletProcessorChannels[t].lockGSNRPNParams||(this.workletProcessorChannels[t].channelVibrato.rate=e,this.workletProcessorChannels[t].channelVibrato.delay=n,this.workletProcessorChannels[t].channelVibrato.depth=A)}function bs(t,A){let e=this.workletProcessorChannels[t],n=()=>{e.channelVibrato.delay===0&&e.channelVibrato.rate===0&&e.channelVibrato.depth===0&&(e.channelVibrato.depth=50,e.channelVibrato.rate=8,e.channelVibrato.delay=.6)};switch(e.dataEntryState){default:case fA.Idle:break;case fA.NRPFine:if(this.system!=="gs"||e.lockGSNRPNParams)return;switch(e.NRPCoarse){default:if(A===64)return;U(`%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;U(`%cUnrecognized NRPN for %c${t}%c: %c(0x${e.NRPCoarse.toString(16)} 0x${e.NRPFine.toString(16)})%c data value: %c${A}`,r.warn,r.recognized,r.warn,r.unrecognized,r.warn,r.value);break;case 8:if(A===64)return;n(),e.channelVibrato.rate=A/64*8,p(`%cVibrato rate for %c${t}%c is now set to %c${A} = ${e.channelVibrato.rate}%cHz.`,r.info,r.recognized,r.info,r.value,r.info);break;case 9:if(A===64)return;n(),e.channelVibrato.depth=A/2,p(`%cVibrato depth for %c${t}%c is now set to %c${A} = ${e.channelVibrato.depth}%c cents range of detune.`,r.info,r.recognized,r.info,r.value,r.info);break;case 10:if(A===64)return;n(),e.channelVibrato.delay=A/64/3,p(`%cVibrato delay for %c${t}%c is now set to %c${A} = ${e.channelVibrato.delay}%c seconds.`,r.info,r.recognized,r.info,r.value,r.info);break;case 32:let a=A;this.controllerChange(t,m.brightness,A),p(`%cFilter cutoff for %c${t}%c is now set to %c${a}`,r.info,r.recognized,r.info,r.value)}break;case 24:let s=A-64;e.keyCentTuning[e.NRPFine]=s*100,p(`%cGS drum key tuning. MIDI note: %c${e.NRPFine}%c semitones: %c${s}`,r.info,r.recognized,r.info,r.value);break;case 29:let o=A;this.controllerChange(t,m.reverbDepth,o),p(`%cGS Drum reverb for %c${t}%c: %c${o}`,r.info,r.recognized,r.info,r.value);break}break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:U(`%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[BA+K.pitchWheelRange]=A<<7,p(`%cChannel ${t} bend range. Semitones: %c${A}`,r.info,r.value);break;case 2:this.setChannelTuningSemitones(t,A-64);break;case 1:this.setChannelTuning(t,A-64,!1);break;case 5:this.setModulationDepth(t,A*100);break;case 16383:this.resetParameters(t);break}}}function Ls(t,A){let e=this.workletProcessorChannels[t];switch(e.dataEntryState){default:break;case fA.RPCoarse:case fA.RPFine:switch(e.RPValue){default:break;case 0:if(A===0)break;e.midiControllers[BA+K.pitchWheelRange]|=A;let n=(e.midiControllers[BA+K.pitchWheelRange]>>7)+A/127;p(`%cChannel ${t} bend range. Semitones: %c${n}`,r.info,r.value);break;case 1:let o=e.customControllers[gA.channelTuning]<<7|A;this.setChannelTuning(t,o*.01220703125);break;case 5:let C=e.customControllers[gA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(t,C);break;case 16383:this.resetParameters(t);break}}}function Us(t=!0){t&&p("%cResetting all controllers!",r.info),this.callEvent("allcontrollerreset",void 0);for(let A=0;A{this.workletProcessorChannels[A].lockedControllers[s]&&this.callEvent("controllerchange",{channel:A,controllerNumber:s,controllerValue:this.workletProcessorChannels[A].midiControllers[s]>>7})};if(n(m.mainVolume),n(m.pan),n(m.expressionController),n(m.modulationWheel),n(m.chorusDepth),n(m.reverbDepth),n(m.brightness),this.workletProcessorChannels[A].lockedControllers[BA+K.pitchWheel]){let s=this.workletProcessorChannels[A].midiControllers[BA+K.pitchWheel],o=s>>7,a=s&127;this.callEvent("pitchwheel",{channel:A,MSB:o,LSB:a})}}this.tunings=[],this.tunings=[];for(let A=0;127>A;A++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Oe}function Ts(t){let A=this.workletProcessorChannels[t],n=A.lockedControllers.reduce((o,a,C)=>(a&&o.push(C),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.keyCentTuning.fill(0),A.midiControllers.set(St),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,n.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let s=A.customControllers[gA.channelTransposeFine];A.customControllers.set(kt),A.customControllers[gA.channelTransposeFine]=s,this.resetParameters(t)}function Hs(t){let A=this.workletProcessorChannels[t];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=fA.Idle}function Ys(){let t=4;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>(o.generators=o.generators.filter(a=>a.generatorType!==g.sampleID&&a.generatorType!==g.keyRange&&a.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+s),0);let A=new H(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.generatorZoneStartIndex=e;for(let o of s.generators)Y(A,o.generatorType),Y(A,o.generatorValue),e++}return lA(A,0),nA(new AA("igen",A.length,A))}function Js(t,A,e,n,s){let o=this.samples.map((B,d)=>{e&&B.compressSample(n,s);let h=B.getRawData();return p(`%cEncoded sample %c${d}. ${B.sampleName}%c of %c${this.samples.length}`,r.info,r.recognized,r.info,r.recognized),h}),a=this.samples.reduce((B,d,h)=>B+o[h].length+46,0),C=new H(a);this.samples.forEach((B,d)=>{let h=o[d],l,u,D=h.length;B.isCompressed?(l=C.currentIndex,u=l+h.length):(l=C.currentIndex/2,u=l+h.length/2,D+=46),t.push(l),C.set(h,C.currentIndex),C.currentIndex+=D,A.push(u)});let Q=nA(new AA("smpl",C.length,C),new H([115,100,116,97]));return nA(new AA("LIST",Q.length,Q))}function vs(t,A){let n=new H(46*(this.samples.length+1));return this.samples.forEach((s,o)=>{RA(n,s.sampleName,20);let a=t[o];lA(n,a);let C=A[o];lA(n,C);let Q=s.sampleLoopStartIndex+a,B=s.sampleLoopEndIndex+a;s.isCompressed&&(Q-=a,B-=a),lA(n,Q),lA(n,B),lA(n,s.sampleRate),n[n.currentIndex++]=s.samplePitch,n[n.currentIndex++]=s.samplePitchCorrection,Y(n,s.sampleLink),Y(n,s.sampleType)}),RA(n,"EOS",46),nA(new AA("shdr",n.length,n))}function qs(){let t=10;for(let n of this.instruments)t+=n.instrumentZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new H(t),e=0;for(let n of this.instruments)for(let s of n.instrumentZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),nA(new AA("imod",A.length,A))}function Ps(){let t=this.instruments.reduce((o,a)=>a.instrumentZones.length*4+o,4),A=new H(t),e=0,n=0,s=0;for(let o of this.instruments){o.instrumentZoneIndex=e;for(let a of o.instrumentZones)a.zoneID=e,Y(A,n),Y(A,s),n+=a.generators.length,s+=a.modulators.length,e++}return Y(A,n),Y(A,s),nA(new AA("ibag",A.length,A))}function Ks(){let t=this.instruments.length*22+22,A=new H(t),e=0,n=0;for(let s of this.instruments)RA(A,s.instrumentName,20),Y(A,e),e+=s.instrumentZones.length,s.instrumentID=n,n++;return RA(A,"EOI",20),Y(A,e),nA(new AA("inst",A.length,A))}function Vs(){let t=4;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>(o.generators=o.generators.filter(a=>a.generatorType!==g.instrument&&a.generatorType!==g.keyRange&&a.generatorType!==g.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:g.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:g.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:g.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+s),0);let A=new H(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.generatorZoneStartIndex=e;for(let o of s.generators)Y(A,o.generatorType),Y(A,o.generatorValue);e+=s.generators.length}return Y(A,0),Y(A,0),nA(new AA("pgen",A.length,A))}function Os(){let t=10;for(let n of this.presets)t+=n.presetZones.reduce((s,o)=>o.modulators.length*10+s,0);let A=new H(t),e=0;for(let n of this.presets)for(let s of n.presetZones){s.modulatorZoneStartIndex=e;for(let o of s.modulators)Y(A,o.sourceEnum),Y(A,o.modulatorDestination),Y(A,o.transformAmount),Y(A,o.secondarySourceEnum),Y(A,o.transformType),e++}return ge(A,0,10),nA(new AA("pmod",A.length,A))}function Zs(){let t=this.presets.reduce((o,a)=>a.presetZones.length*4+o,4),A=new H(t),e=0,n=0,s=0;for(let o of this.presets){o.presetZoneStartIndex=e;for(let a of o.presetZones)a.zoneID=e,Y(A,n),Y(A,s),n+=a.generators.length,s+=a.modulators.length,e++}return Y(A,n),Y(A,s),nA(new AA("pbag",A.length,A))}function Xs(){let t=this.presets.length*38+38,A=new H(t),e=0;for(let n of this.presets)RA(A,n.presetName,20),Y(A,n.program),Y(A,n.bank),Y(A,e),lA(A,n.library),lA(A,n.genre),lA(A,n.morphology),e+=n.presetZones.length;return RA(A,"EOP",20),Y(A,0),Y(A,0),Y(A,e),lA(A,0),lA(A,0),lA(A,0),nA(new AA("phdr",A.length,A))}var Jo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Ws(t=Jo){if(t.compress&&typeof t.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");SA("%cSaving soundfont...",r.info),p(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,r.info,r.recognized,r.info,r.recognized),p("%cWriting INFO...",r.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",t?.compress&&(this.soundFontInfo.ifil="3.0");for(let[P,$]of Object.entries(this.soundFontInfo))if(P==="ifil"||P==="iver"){let i=parseInt($.split(".")[0]),sA=parseInt($.split(".")[1]),_=new H(4);Y(_,i),Y(_,sA),A.push(nA(new AA(P,4,_)))}else if(P==="DMOD")A.push(nA(new AA(P,$.length,$)));else{let i=new H($.length);RA(i,$),A.push(nA(new AA(P,$.length,i)))}let e=ke([new H([73,78,70,79]),...A]),n=nA(new AA("LIST",e.length,e));p("%cWriting SDTA...",r.info);let s=[],o=[],a=Js.call(this,s,o,t?.compress,t?.compressionQuality||.5,t.compressionFunction);p("%cWriting PDTA...",r.info),p("%cWriting SHDR...",r.info);let C=vs.call(this,s,o);p("%cWriting IGEN...",r.info);let Q=Ys.call(this);p("%cWriting IMOD...",r.info);let B=qs.call(this);p("%cWriting IBAG...",r.info);let d=Ps.call(this);p("%cWriting INST...",r.info);let h=Ks.call(this),l=Vs.call(this);p("%cWriting PMOD...",r.info);let u=Os.call(this);p("%cWriting PBAG...",r.info);let D=Zs.call(this);p("%cWriting PHDR...",r.info);let S=Xs.call(this),w=ke([new H([112,100,116,97]),S,D,u,l,h,d,B,Q,C]),y=nA(new AA("LIST",w.length,w));p("%cWriting the output file...",r.info);let N=ke([new H([115,102,98,107]),n,a,y]),x=nA(new AA("RIFF",N.length,N));return p(`%cSaved succesfully! Final file size: %c${x.length}`,r.info,r.recognized),Z(),x}var se=class t{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],this.defaultModulators=Pe.map(e=>j.copy(e)),A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}static mergeSoundfonts(...A){let e=A.shift(),n=e.presets;for(;A.length;)A.shift().presets.forEach(o=>{n.find(a=>a.bank===o.bank&&a.program===o.program)===void 0&&n.push(o)});return new t({presets:n,info:e.soundFontInfo})}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(e=>{e.isGlobal||e.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}setSampleIDOffset(A){this.presets.forEach(e=>e.sampleIDOffset=A)}getPresetNoFallback(A,e,n=!1){let s=this.presets.find(o=>o.bank===A&&o.program===e);if(s)return s;if(n!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.program===e)}getPreset(A,e){let n=this.presets.find(s=>s.bank===A&&s.program===e);return n||(A===128?(n=this.presets.find(s=>s.bank===128&&s.program===e),n||(n=this.presets.find(s=>s.bank===128))):n=this.presets.find(s=>s.program===e&&s.bank!==128),n&&U(`%cPreset ${A}.${e} not found. Replaced with %c${n.presetName} (${n.bank}.${n.program})`,r.warn,r.recognized)),n||(U(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),n=this.presets[0]),n}getPresetByName(A){let e=this.presets.find(n=>n.presetName===A);return e||(U("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}};se.prototype.write=Ws;function _s(t){SA("%cLoading instruments...",r.info);for(let A=0;AA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,e){for(let n=A;n{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,e){this.getSamplesAndGenerators(A,e).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}getSamplesAndGenerators(A,e){let n=this.foundSamplesAndGenerators[A][e];if(n)return n;if(this.presetZones.length<1)return[];function s(h,l,u){return u>=h&&u<=l}function o(h,l){h.push(...l.filter(u=>!h.find(D=>D.generatorType===u.generatorType)))}function a(h,l){h.push(...l.filter(u=>!h.find(D=>j.isIdentical(u,D))))}let C=[],Q=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],B=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(h=>s(h.keyRange.min,h.keyRange.max,A)&&s(h.velRange.min,h.velRange.max,e)&&!h.isGlobal).forEach(h=>{if(h.instrument.instrumentZones.length<1)return;let l=h.generators,u=h.modulators,D=h.instrument.instrumentZones[0].isGlobal?[...h.instrument.instrumentZones[0].generators]:[],S=h.instrument.instrumentZones[0].isGlobal?[...h.instrument.instrumentZones[0].modulators]:[];h.instrument.instrumentZones.filter(y=>s(y.keyRange.min,y.keyRange.max,A)&&s(y.velRange.min,y.velRange.max,e)&&!y.isGlobal).forEach(y=>{let N=[...y.generators],x=[...y.modulators];o(l,Q),o(N,D),a(u,B),a(x,S),a(x,this.defaultModulators);let P=[...x];for(let $=0;$j.isIdentical(i,_));sA!==-1?P[sA]=P[sA].sumTransform(i):P.push(i)}C.push({instrumentGenerators:N,presetGenerators:l,modulators:P,sample:y.sample,sampleID:y.generators.find($=>$.generatorType===g.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][e]=C,C}};var Re=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var $A=class extends Re{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},le=class extends Re{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var ue=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}get useCount(){return this._useCount}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var At=class extends ce{constructor(A,e){super(Pe),this.program=e&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new ue,this.DLSInstrument.addUseCount();let s=new le;s.instrument=this.DLSInstrument,this.presetZones=[s]}};function zs(t){this.verifyHeader(t,"LIST"),this.verifyText(V(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(u=>u.header==="insh");if(!e)throw Z(),new Error("No instrument header!");let n=k(e.chunkData,4),s=k(e.chunkData,4),o=k(e.chunkData,4),a=new At(s,o),C="unnamedPreset",Q=kA(A,"INFO");if(Q){let u=O(Q.chunkData);for(;u.header!=="INAM";)u=O(Q.chunkData);C=V(u.chunkData,u.chunkData.length).trim()}a.presetName=C,a.DLSInstrument.instrumentName=C,te(`%cParsing %c"${C}"%c...`,r.info,r.recognized,r.info);let B=kA(A,"lrgn");if(!B)throw Z(),new Error("No region list!");let d=new $A;d.isGlobal=!0;let h=kA(A,"lart"),l=kA(A,"lar2");this.readLart(h,l,d),a.DLSInstrument.instrumentZones.push(d);for(let u=0;u>10&15;y===cA.linear&&w!==cA.linear&&(y=w);let N=n>>14&1,x=n>>15&1;a===g.initialAttenuation&&(x=!x),h=HA(y,N,x,C.isCC,C.enum)}let l=n>>4&15,u=n>>8&1,D=n>>9&1,S=HA(l,u,D,d.isCC,d.enum);if(Q){let w=S;S=h,h=w}return new j({srcEnum:h,secSrcEnum:S,dest:a,transform:0,amt:s})}function Tt(t,A){let e=t.chunkData,n=[],s=[];k(e,4);let o=k(e,4);for(let a=0;a>16;if(C===0&&Q===0&&d===0){let u;switch(B){case G.pan:u=new b(g.pan,l);break;case G.gain:u=new b(g.initialAttenuation,-l*10/.4);break;case G.filterCutoff:u=new b(g.initialFilterFc,l);break;case G.filterQ:u=new b(g.initialFilterQ,l);break;case G.modLfoFreq:u=new b(g.freqModLFO,l);break;case G.modLfoDelay:u=new b(g.delayModLFO,l);break;case G.vibLfoFreq:u=new b(g.freqVibLFO,l);break;case G.vibLfoDelay:u=new b(g.delayVibLFO,l);break;case G.volEnvDelay:u=new b(g.delayVolEnv,l);break;case G.volEnvAttack:u=new b(g.attackVolEnv,l);break;case G.volEnvHold:u=new b(g.holdVolEnv,l);break;case G.volEnvDecay:u=new b(g.decayVolEnv,l);break;case G.volEnvRelease:u=new b(g.releaseVolEnv,l);break;case G.volEnvSustain:let D=(1e3-l)/10;u=new b(g.sustainVolEnv,D*10);break;case G.modEnvDelay:u=new b(g.delayModEnv,l);break;case G.modEnvAttack:u=new b(g.attackModEnv,l);break;case G.modEnvHold:u=new b(g.holdModEnv,l);break;case G.modEnvDecay:u=new b(g.decayModEnv,l);break;case G.modEnvRelease:u=new b(g.releaseModEnv,l);break;case G.modEnvSustain:let S=1e3-l;u=new b(g.sustainModEnv,S);break;case G.reverbSend:u=new b(g.reverbEffectsSend,l);break;case G.chorusSend:u=new b(g.chorusEffectsSend,l);break;case G.pitch:let w=Math.floor(l/100),y=Math.floor(l-w*100);u=new b(g.fineTune,y),n.push(new b(g.coarseTune,w));break}u&&n.push(u)}else{let u=!0;if(Q===W.none)if(C===W.modLfo&&B===G.pitch)n.push(new b(g.modLfoToPitch,l));else if(C===W.modLfo&&B===G.gain)n.push(new b(g.modLfoToVolume,l));else if(C===W.modLfo&&B===G.filterCutoff)n.push(new b(g.modLfoToFilterFc,l));else if(C===W.vibratoLfo&&B===G.pitch)n.push(new b(g.vibLfoToPitch,l));else if(C===W.modEnv&&B===G.pitch)n.push(new b(g.modEnvToPitch,l));else if(C===W.modEnv&&B===G.filterCutoff)n.push(new b(g.modEnvToFilterFc,l));else if(C===W.keyNum&&B===G.volEnvHold){n.push(new b(g.keyNumToVolEnvHold,l/-128));let D=Math.round(60/128*l);n.forEach(S=>{S.generatorType===g.holdVolEnv&&(S.generatorValue+=D)})}else if(C===W.keyNum&&B===G.volEnvDecay){n.push(new b(g.keyNumToVolEnvDecay,l/-128));let D=Math.round(60/128*l);n.forEach(S=>{S.generatorType===g.decayVolEnv&&(S.generatorValue+=D)})}else if(C===W.keyNum&&B===G.modEnvHold){n.push(new b(g.keyNumToModEnvHold,l/-128));let D=Math.round(60/128*l);n.forEach(S=>{S.generatorType===g.holdModEnv&&(S.generatorValue+=D)})}else if(C===W.keyNum&&B===G.modEnvDecay){n.push(new b(g.keyNumToModEnvDecay,l/-128));let D=Math.round(60/128*l);n.forEach(S=>{S.generatorType===g.decayModEnv&&(S.generatorValue+=D)})}else u=!1;else u=!1;if(u===!1){let D=$s(C,Q,B,d,l);D?(s.push(D),p("%cSucceeded converting to SF2 Modulator!",r.recognized)):U("Failed converting to SF2 Modulator!")}}}return s.find(a=>a.modulatorDestination===g.reverbEffectsSend)===void 0&&s.push(new j({srcEnum:219,dest:g.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),s.find(a=>a.modulatorDestination===g.chorusEffectsSend)===void 0&&s.push(new j({srcEnum:221,dest:g.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&s.push(new j({srcEnum:129,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new j({srcEnum:13,dest:g.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:s,generators:n}}function Ao(t,A,e){if(t)for(;t.chunkData.currentIndext.chunkData.currentIndex;)A.push(O(t.chunkData));let e=A.find(_=>_.header==="rgnh"),n=k(e.chunkData,2),s=k(e.chunkData,2),o=k(e.chunkData,2),a=k(e.chunkData,2),C=new et({min:n,max:s},{min:o,max:a});k(e.chunkData,2);let Q=k(e.chunkData,2);Q!==0&&C.generators.push(new b(g.exclusiveClass,Q));let B=kA(A,"lart"),d=kA(A,"lar2");this.readLart(B,d,C),C.isGlobal=!1;let h=A.find(_=>_.header==="wsmp");k(h.chunkData,4);let l=k(h.chunkData,2),u=jA(h.chunkData[h.chunkData.currentIndex++],h.chunkData[h.chunkData.currentIndex++]),S=(k(h.chunkData,4)|0)/-655360;k(h.chunkData,4);let w=k(h.chunkData,4),y,N={start:0,end:0};if(w===0)y=0;else{k(h.chunkData,4),k(h.chunkData,4)===0?y=1:y=3,N.start=k(h.chunkData,4);let J=k(h.chunkData,4);N.end=N.start+J}let x=A.find(_=>_.header==="wlnk");if(x===void 0)return;k(x.chunkData,2),k(x.chunkData,2),k(x.chunkData,4);let P=k(x.chunkData,4),$=this.samples[P];if($===void 0)throw new Error("Invalid sample ID!");let sA=(S||$.sampleDbAttenuation)*10/.4;return C.setWavesample(sA,y,N,l,$,P,u),C}var de=class{constructor(A,e,n,s,o,a,C,Q){this.sampleName=A,this.sampleRate=e,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLink=o,this.sampleType=a,this.sampleLoopStartIndex=C,this.sampleLoopEndIndex=Q,this.isCompressed=(a&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{U(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}};var tt=class extends de{sampleDbAttenuation;sampleData;constructor(A,e,n,s,o,a,C,Q){super(A,e,n,s,0,1,o,a-1),this.sampleData=C,this.sampleDbAttenuation=Q}getAudioData(){return this.sampleData}getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let e=0;e>8&255}return A}};function to(t){SA("%cLoading Wave samples...",r.recognized);let A=0;for(;t.chunkData.currentIndexJ.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");if(k(s.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(k(s.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let C=k(s.chunkData,4);k(s.chunkData,4),k(s.chunkData,2);let Q=k(s.chunkData,2),B=Q/8,d=Math.pow(2,B*8-1),h=Math.pow(2,B*8),l,u=!1;Q===8?(l=255,u=!0):l=d;let D=n.find(J=>J.header==="data");if(!D)throw new Error("No data chunk in the wave chunk!");let S=D.size/B,w=new Float32Array(S);for(let J=0;J=d&&(z-=h),w[J]=z/l)}let y=60,N=0,x=0,P=w.length-1,$=0,i=n.find(J=>J.header==="wsmp");if(i){if(k(i.chunkData,4),y=k(i.chunkData,2),N=jA(i.chunkData[i.chunkData.currentIndex++],i.chunkData[i.chunkData.currentIndex++]),$=(k(i.chunkData,4)|0)/-655360,k(i.chunkData,4),k(i.chunkData,4)===1){k(i.chunkData,8),x=k(i.chunkData,4);let oA=k(i.chunkData,4);P=x+oA}}else U("No wsmp chunk in wave... using sane defaults.");let sA=kA(n,"INFO"),_=`Unnamed ${A}`;if(sA){let J=O(sA.chunkData);for(;J.header!=="INAM"&&sA.chunkData.currentIndexc.header==="colh");if(!o)throw X(),new Error("No colh chunk!");this.instrumentAmount=k(o.chunkData,4),p(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let i=kA(n,"wvpl");this.readDLSSamples(i);let C=kA(n,"lins");if(!C)throw X(),new Error("No lins chunk!");this.readDLSInstrumentList(C),this.presets.sort((c,B)=>c.program-B.program+(c.bank-B.bank)),p(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X()}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=_s;WA.prototype.readDLSInstrument=zs;WA.prototype.readRegion=eo;WA.prototype.readLart=Ao;WA.prototype.readDLSSamples=to;var Ht=class extends de{constructor(A,e,n,s,o,i,C,c,B,d,h,u,l){super(A,i,C,c,B,d,s-e/2,o-e/2),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=u,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=h,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=l}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let e=A.currentIndex;return A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e)}else{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");let e=A.currentIndex;return A.slice(e+this.sampleStartIndex,e+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,e=A.currentIndex,n=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let s=OA.decode(n.buffer);this.sampleData=s.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return U("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let s=0;st.chunkData.currentIndex;){let o=Po(s,t.chunkData,A,e);n.push(o),s++}return n.length>1&&n.pop(),n}function Po(t,A,e,n){let s=V(A,20),o=k(A,4)*2,i=k(A,4)*2,C=k(A,4),c=k(A,4),B=k(A,4),d=A[A.currentIndex++];d===255&&(d=60);let h=Gn(A[A.currentIndex++]),u=k(A,2),l=k(A,2);return new Ht(s,o,i,C,c,B,d,h,u,l,e,t,n)}var Yt=class extends b{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=jA(A[e+2],A[e+3]),A.currentIndex+=4}};function Jt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Yt(t.chunkData));return A.length>1&&A.pop(),A}var vt=class extends ue{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=k(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;nt.chunkData.currentIndex;){let n=new vt(t);if(e.length>0){let s=n.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(s,A)}e.push(n)}return e.length>1&&e.pop(),e}var qt=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=k(A,2),this.modulatorZoneStartIndex=k(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;en.generatorType===g.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function oo(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new qt(t.chunkData);if(s.length>0){let i=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(i,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Pt=class extends le{constructor(A){super(),this.generatorZoneStartIndex=k(A,2),this.modulatorZoneStartIndex=k(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;en.generatorType===g.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ro(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Pt(t.chunkData);if(s.length>0){let i=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(i,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Kt=class extends ce{constructor(A,e){super(e),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=k(A.chunkData,2),this.bank=k(A.chunkData,2),this.presetZoneStartIndex=k(A.chunkData,2),this.library=k(A.chunkData,4),this.genre=k(A.chunkData,4),this.morphology=k(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let n=this.presetZoneStartIndex;nt.chunkData.currentIndex;){let s=new Kt(t,e);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var Vt=class extends ${constructor(A){super({srcEnum:k(A,2),dest:k(A,2),amt:jA(A[A.currentIndex++],A[A.currentIndex++]),secSrcEnum:k(A,2),transform:k(A,2)})}};function nt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Vt(t.chunkData));return A}var st=class extends se{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new H(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw X(),new TypeError("No data!");let n=O(this.dataArray,!1);this.verifyHeader(n,"riff");let s=V(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw X(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",i=O(this.dataArray);for(this.verifyHeader(i,"list"),V(i.chunkData,4);i.chunkData.length>i.chunkData.currentIndex;){let Z=O(i.chunkData),CA;switch(Z.header.toLowerCase()){case"ifil":case"iver":CA=`${k(Z.chunkData,2)}.${k(Z.chunkData,2)}`,this.soundFontInfo[Z.header]=CA;break;case"icmt":CA=V(Z.chunkData,Z.chunkData.length,void 0,!1),this.soundFontInfo[Z.header]=CA;break;case"dmod":let oA=nt(Z);oA.pop(),CA=`Modulators: ${oA.length}`;let mA=this.defaultModulators;this.defaultModulators=oA,this.defaultModulators.push(...mA.filter(Me=>!this.defaultModulators.find(GA=>$.isIdentical(Me,GA)))),this.soundFontInfo[Z.header]=Z.chunkData;break;default:CA=V(Z.chunkData,Z.chunkData.length),this.soundFontInfo[Z.header]=CA}p(`%c"${Z.header}": %c"${CA}"`,r.info,r.recognized)}let C=O(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(V(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",r.warn);let c=O(this.dataArray,!1);this.verifyHeader(c,"smpl");let B;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{B=OA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(Z){throw X(),new Error(`SF2Pack Ogg Vorbis decode error: ${Z}`)}p(`%cDecoded the smpl chunk! Length: %c${B.length}`,r.info,r.value)}else B=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,p("%cLoading preset data chunk...",r.warn);let d=O(this.dataArray);this.verifyHeader(d,"list"),V(d.chunkData,4);let h=O(d.chunkData);this.verifyHeader(h,"phdr");let u=O(d.chunkData);this.verifyHeader(u,"pbag");let l=O(d.chunkData);this.verifyHeader(l,"pmod");let D=O(d.chunkData);this.verifyHeader(D,"pgen");let S=O(d.chunkData);this.verifyHeader(S,"inst");let w=O(d.chunkData);this.verifyHeader(w,"ibag");let y=O(d.chunkData);this.verifyHeader(y,"imod");let N=O(d.chunkData);this.verifyHeader(N,"igen");let G=O(d.chunkData);this.verifyHeader(G,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...no(G,B,!o));let K=Jt(N),W=nt(y),I=oo(w,K,W,this.samples);this.instruments=so(S,I);let sA=Jt(D),j=nt(l),J=ro(u,sA,j,this.instruments);this.presets.push(...io(h,J,this.defaultModulators)),this.presets.sort((Z,CA)=>Z.program-CA.program+(Z.bank-CA.bank)),p(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, - %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),X(),o&&delete this.dataArray}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw X(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Ge(t){let A=t.slice(8,12),e=new H(A);return V(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new st(t,!1)}function ao(t,A,e=!1){let n=this.workletProcessorChannels[t];if(n===void 0){U(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(n.lockPreset)return;let s=n.drumChannel?128:n.midiControllers[m.bankSelect],o,i;if(this.overrideSoundfont){let C=s===128?128:s-this.soundfontBankOffset,c=this.overrideSoundfont.getPresetNoFallback(C,A);c?(o=s,i=c,n.presetUsesOverride=!0):(i=this.soundfontManager.getPreset(s,A),o=i.bank,n.presetUsesOverride=!1)}else i=this.soundfontManager.getPreset(s,A),o=i.bank,n.presetUsesOverride=!1;this.setPreset(t,i),this.callEvent("programchange",{channel:t,program:i.program,bank:o,userCalled:e})}function Io(t,A){if(this.overrideSoundfont){let e=t===128?128:t-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(e,A);if(n)return n}return this.soundfontManager.getPreset(t,A)}function go(t,A){if(!this.workletProcessorChannels[t].lockPreset){delete this.workletProcessorChannels[t].preset,this.workletProcessorChannels[t].preset=A,this.workletProcessorChannels[t].cachedVoices=[];for(let e=0;e<128;e++)this.workletProcessorChannels[t].cachedVoices.push([])}}function Co(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(128,e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(e.midiControllers[m.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function Eo(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,n=t.find(s=>s.bank===e&&s.program===A.program);n!==void 0?n.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function Bo(t=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let e=0;e{this.programChange(n,e.preset.program)}),this.post({messageType:yA.ready,messageData:void 0}),this.sendPresetList(),p("%cSpessaSynth is ready!",r.recognized)}function Qo(t,A){this.soundfontBankOffset=A,this.reloadSoundFont(t,!0),this.overrideSoundfont.samples.forEach(e=>e.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function co(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:e.preset.bank,lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,velocityOverride:e.velocityOverride,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:yA.synthesizerSnapshot,messageData:A})}function lo(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation;this.workletProcessorChannels.length{let n=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),n.midiControllers=A.midiControllers,n.lockedControllers=A.lockedControllers,n.customControllers=A.customControllers,n.channelVibrato=A.channelVibrato,n.lockGSNRPNParams=A.lockVibrato,n.channelTransposeKeyShift=A.channelTransposeKeyShift,n.channelOctaveTuning=A.channelOctaveTuning,n.velocityOverride=A.velocityOverride,n.lockPreset=!1,n.midiControllers[m.bankSelect]=A.bank,this.programChange(e,A.program),n.lockPreset=A.lockPreset}),p("%cFinished restoring controllers!",r.info)}var ot=class{constructor(A,e){this.ready=e,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(e=>{e.soundfont.setSampleIDOffset(A),A+=e.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let e=this.soundfontList.length-1;e>=0;e--){let n=this.soundfontList[e],s=new Set;for(let o of n.soundfont.presets){let i=`${o.bank+n.bankOffset}-${o.program}`;s.has(i)||(s.add(i),A[i]=o.presetName)}}this.presetList=[];for(let[e,n]of Object.entries(A)){let s=e.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}}handleMessage(A,e){switch(A){case Ie.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ie.reloadSoundFont:this.reloadManager(e);break;case Ie.deleteSoundFont:this.deleteSoundFont(e);break;case Ie.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ge(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){U("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(n=>n.id===A);if(e===-1){U(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[e].soundfont.presets,delete this.soundfontList[e].soundfont.instruments,delete this.soundfontList[e].soundfont.samples,this.soundfontList.splice(e,1),this.generatePresetList()}addNewSoundFont(A,e,n){if(this.soundfontList.find(s=>s.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Ge(A),bankOffset:n}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,n)=>A.indexOf(e.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let n of this.soundfontList){let s=n.soundfont.getPresetNoFallback(A-n.bankOffset,e);if(s!==void 0)return s}if(A!==128){for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.program===e);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}else{for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.bank===128);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}}};var rt=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,e,n,s,o,i,C,c){this.sampleData=A,this.playbackStep=e,this.cursor=n,this.rootKey=s,this.loopStart=o,this.loopEnd=i,this.end=C,this.loopingMode=c,this.isLooping=this.loopingMode===1||this.loopingMode===3}},xe=class t{sample;filter=new Qe;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new JA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;constructor(A,e,n,s,o,i,C,c,B){this.sample=e,this.generators=c,this.modulatedGenerators=new Int16Array(c),this.modulators=B,this.velocity=s,this.midiNote=n,this.channelNumber=o,this.startTime=i,this.targetKey=C,this.volumeEnvelope=new UA(A,c[g.sustainVolEnv])}static copy(A,e){let n=A.sample,s=new rt(n.sampleData,n.playbackStep,n.cursor,n.rootKey,n.loopStart,n.loopEnd,n.end,n.loopingMode);return new t(A.volumeEnvelope.sampleRate,s,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.generators,A.modulators.map(o=>$.copy(o)))}};function uo(t,A,e,n,s,o=!1){let i,C=n.cachedVoices[A][e];return C!==void 0?C.map(c=>xe.copy(c,s)):(i=n.preset.getSamplesAndGenerators(A,e).reduce((B,d)=>{if(d.sample.sampleData===void 0)return U(`Discarding invalid sample: ${d.sample.sampleName}`),B;let h=new Int16Array(60);for(let N=0;N<60;N++)h[N]=pn(N,d.presetGenerators,d.instrumentGenerators);h[g.initialAttenuation]=Math.floor(h[g.initialAttenuation]*.4);let u=d.sample.samplePitch;h[g.overridingRootKey]>-1&&(u=h[g.overridingRootKey]);let l=A;h[g.keyNum]>-1&&(l=h[g.keyNum]);let D=d.sample.sampleLoopStartIndex,S=d.sample.sampleLoopEndIndex,w=h[g.sampleModes],y=new rt(d.sample.getAudioData(),d.sample.sampleRate/sampleRate*Math.pow(2,d.sample.samplePitchCorrection/1200),0,u,D,S,Math.floor(d.sample.sampleData.length)-1,w);return h[g.velocity]>-1&&(e=h[g.velocity]),o&&mn([{Sample:d.sample.sampleName,Generators:h,Modulators:d.modulators.map(N=>N.debugString()),Velocity:e,TargetKey:l,MidiNote:A,WorkletSample:y}]),B.push(new xe(sampleRate,y,A,e,t,s,l,h,d.modulators.map(N=>$.copy(N)))),B},[]),n.cachedVoices[A][e]=i.map(B=>xe.copy(B,s)),i)}var Lt=.03,Ut=1,T=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=TA,this.interpolationType=he.fourthOrder,this.processTickCallback=void 0,this.sequencer=new aA(this),this.transposition=0,this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Ut,this.midiVolume=1,this.voiceCap=Dn,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new ot(A.processorOptions.soundfont,this.postReady.bind(this))}catch(e){throw this.post({messageType:yA.soundfontError,messageData:e}),e}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let e=0;ethis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),p("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),OA.isInitialized.then(()=>{this.postReady(),p("%cSpessaSynth is ready!",r.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:yA.ready,messageData:void 0})}debugMessage(){p({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let n=0;return this.workletProcessorChannels.forEach((s,o)=>{if(s.voices.length<1||s.isMuted)return;let i,C,c,B,d;if(this.oneOutputMode){let u=e[0];i=o%16*2,C=u[i],c=u[i+1]}else i=o%this._outputsAmount+2,C=e[i][0],c=e[i][1],B=e[0],d=e[1];let h=s.voices;s.voices=[],h.forEach(u=>{this.renderVoice(s,u,C,c,B,d),u.finished||s.voices.push(u)}),n+=s.voices.length}),n!==this.totalVoicesAmount&&(this.totalVoicesAmount=n,this.sendChannelProperties()),!0}};T.prototype.renderVoice=ts;T.prototype.releaseVoice=ss;T.prototype.voiceKilling=ns;T.prototype.getWorkletVoices=uo;T.prototype.handleMessage=is;T.prototype.sendChannelProperties=Is;T.prototype.callEvent=as;T.prototype.systemExclusive=gs;T.prototype.noteOn=Es;T.prototype.noteOff=Bs;T.prototype.polyPressure=Ds;T.prototype.killNote=hs;T.prototype.stopAll=Qs;T.prototype.stopAllChannels=cs;T.prototype.muteChannel=xs;T.prototype.setVibrato=Ns;T.prototype.disableAndLockGSNRPN=Ms;T.prototype.dataEntryCoarse=bs;T.prototype.dataEntryFine=Ls;T.prototype.createWorkletChannel=yn;T.prototype.controllerChange=ws;T.prototype.channelPressure=Ss;T.prototype.resetAllControllers=Us;T.prototype.resetControllers=Ts;T.prototype.resetParameters=Hs;T.prototype.setMasterGain=Rs;T.prototype.setMasterPan=Gs;T.prototype.setMIDIVolume=Fs;T.prototype.transposeAllChannels=ls;T.prototype.transposeChannel=us;T.prototype.setChannelTuning=ds;T.prototype.setChannelTuningSemitones=fs;T.prototype.setMasterTuning=ms;T.prototype.setModulationDepth=ps;T.prototype.pitchWheel=ys;T.prototype.setOctaveTuning=ks;T.prototype.programChange=ao;T.prototype.getPreset=Io;T.prototype.setPreset=go;T.prototype.setDrums=Co;T.prototype.reloadSoundFont=ho;T.prototype.clearSoundFont=Bo;T.prototype.setEmbeddedSoundFont=Qo;T.prototype.sendPresetList=Eo;T.prototype.sendSynthesizerSnapshot=co;T.prototype.applySynthesizerSnapshot=lo;registerProcessor(Sn,T);p("%cProcessor succesfully registered!",r.recognized); +`+this.soundFontInfo.ISBJ,delete this.soundFontInfo.ISBJ);for(let[Q,B]of Object.entries(this.soundFontInfo))p(`%c"${Q}": %c"${B}"`,r.info,r.recognized);let o=n.find(Q=>Q.header==="colh");if(!o)throw Z(),new Error("No colh chunk!");this.instrumentAmount=k(o.chunkData,4),p(`%cInstruments amount: %c${this.instrumentAmount}`,r.info,r.recognized);let a=kA(n,"wvpl");this.readDLSSamples(a);let C=kA(n,"lins");if(!C)throw Z(),new Error("No lins chunk!");this.readDLSInstrumentList(C),this.presets.sort((Q,B)=>Q.program-B.program+(Q.bank-B.bank)),p(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),Z()}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid DLS soundfont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};WA.prototype.readDLSInstrumentList=_s;WA.prototype.readDLSInstrument=zs;WA.prototype.readRegion=eo;WA.prototype.readLart=Ao;WA.prototype.readDLSSamples=to;var Ht=class extends de{constructor(A,e,n,s,o,a,C,Q,B,d,h,l,u){super(A,a,C,Q,B,d,s-e/2,o-e/2),this.sampleName=A,this.sampleStartIndex=e,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=l,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=h,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=u}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let e=A.currentIndex;return A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e)}else{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");let e=A.currentIndex;return A.slice(e+this.sampleStartIndex,e+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,e=A.currentIndex,n=A.slice(this.sampleStartIndex/2+e,this.sampleEndIndex/2+e);this.sampleData=new Float32Array(0);let s=OA.decode(n.buffer);this.sampleData=s.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return U("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),e=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(e+this.sampleStartIndex,e+this.sampleEndIndex).buffer);for(let s=0;st.chunkData.currentIndex;){let o=Po(s,t.chunkData,A,e);n.push(o),s++}return n.length>1&&n.pop(),n}function Po(t,A,e,n){let s=V(A,20),o=k(A,4)*2,a=k(A,4)*2,C=k(A,4),Q=k(A,4),B=k(A,4),d=A[A.currentIndex++];d===255&&(d=60);let h=Gn(A[A.currentIndex++]),l=k(A,2),u=k(A,2);return new Ht(s,o,a,C,Q,B,d,h,l,u,e,t,n)}var Yt=class extends b{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=jA(A[e+2],A[e+3]),A.currentIndex+=4}};function Jt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Yt(t.chunkData));return A.length>1&&A.pop(),A}var vt=class extends ue{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=k(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,e){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;nt.chunkData.currentIndex;){let n=new vt(t);if(e.length>0){let s=n.instrumentZoneIndex-e[e.length-1].instrumentZoneIndex;e[e.length-1].getInstrumentZones(s,A)}e.push(n)}return e.length>1&&e.pop(),e}var qt=class extends $A{constructor(A){super(),this.generatorZoneStartIndex=k(A,2),this.modulatorZoneStartIndex=k(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;en.generatorType===g.sampleID);e&&(this.sample=A[e.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function oo(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new qt(t.chunkData);if(s.length>0){let a=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(a,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Pt=class extends le{constructor(A){super(),this.generatorZoneStartIndex=k(A,2),this.modulatorZoneStartIndex=k(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,e){this.modulatorZoneSize=A,this.generatorZoneSize=e}getGenerators(A){for(let e=this.generatorZoneStartIndex;en.generatorType===g.instrument);e&&(this.instrument=A[e.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(e=>e.generatorType===g.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(e=>e.generatorType===g.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ro(t,A,e,n){let s=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let o=new Pt(t.chunkData);if(s.length>0){let a=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,C=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(a,C),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(e),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var Kt=class extends ce{constructor(A,e){super(e),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=k(A.chunkData,2),this.bank=k(A.chunkData,2),this.presetZoneStartIndex=k(A.chunkData,2),this.library=k(A.chunkData,4),this.genre=k(A.chunkData,4),this.morphology=k(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,e){this.presetZonesAmount=A;for(let n=this.presetZoneStartIndex;nt.chunkData.currentIndex;){let s=new Kt(t,e);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var Vt=class extends j{constructor(A){super({srcEnum:k(A,2),dest:k(A,2),amt:jA(A[A.currentIndex++],A[A.currentIndex++]),secSrcEnum:k(A,2),transform:k(A,2)})}};function nt(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new Vt(t.chunkData));return A}var st=class extends se{constructor(A,e=!0){if(super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new H(A),te("%cParsing SoundFont...",r.info),!this.dataArray)throw Z(),new TypeError("No data!");let n=O(this.dataArray,!1);this.verifyHeader(n,"riff");let s=V(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw Z(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",a=O(this.dataArray);for(this.verifyHeader(a,"list"),V(a.chunkData,4);a.chunkData.length>a.chunkData.currentIndex;){let z=O(a.chunkData),oA;switch(z.header.toLowerCase()){case"ifil":case"iver":oA=`${k(z.chunkData,2)}.${k(z.chunkData,2)}`,this.soundFontInfo[z.header]=oA;break;case"icmt":oA=V(z.chunkData,z.chunkData.length,void 0,!1),this.soundFontInfo[z.header]=oA;break;case"dmod":let rA=nt(z);rA.pop(),oA=`Modulators: ${rA.length}`;let EA=this.defaultModulators;this.defaultModulators=rA,this.defaultModulators.push(...EA.filter(Me=>!this.defaultModulators.find(GA=>j.isIdentical(Me,GA)))),this.soundFontInfo[z.header]=z.chunkData;break;default:oA=V(z.chunkData,z.chunkData.length),this.soundFontInfo[z.header]=oA}p(`%c"${z.header}": %c"${oA}"`,r.info,r.recognized)}let C=O(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(V(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",r.warn);let Q=O(this.dataArray,!1);this.verifyHeader(Q,"smpl");let B;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",r.info);try{B=OA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(z){throw Z(),new Error(`SF2Pack Ogg Vorbis decode error: ${z}`)}p(`%cDecoded the smpl chunk! Length: %c${B.length}`,r.info,r.value)}else B=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${C.size-12}`,r.info,r.value),this.dataArray.currentIndex+=C.size-12,p("%cLoading preset data chunk...",r.warn);let d=O(this.dataArray);this.verifyHeader(d,"list"),V(d.chunkData,4);let h=O(d.chunkData);this.verifyHeader(h,"phdr");let l=O(d.chunkData);this.verifyHeader(l,"pbag");let u=O(d.chunkData);this.verifyHeader(u,"pmod");let D=O(d.chunkData);this.verifyHeader(D,"pgen");let S=O(d.chunkData);this.verifyHeader(S,"inst");let w=O(d.chunkData);this.verifyHeader(w,"ibag");let y=O(d.chunkData);this.verifyHeader(y,"imod");let N=O(d.chunkData);this.verifyHeader(N,"igen");let x=O(d.chunkData);this.verifyHeader(x,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...no(x,B,!o));let P=Jt(N),$=nt(y),i=oo(w,P,$,this.samples);this.instruments=so(S,i);let sA=Jt(D),_=nt(u),J=ro(l,sA,_,this.instruments);this.presets.push(...io(h,J,this.defaultModulators)),this.presets.sort((z,oA)=>z.program-oA.program+(z.bank-oA.bank)),p(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info,r.recognized,r.info),Z(),o&&delete this.dataArray}verifyHeader(A,e){if(A.header.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){if(A.toLowerCase()!==e.toLowerCase())throw Z(),new SyntaxError(`Invalid soundFont! Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`)}};function Ge(t){let A=t.slice(8,12),e=new H(A);return V(e,4,void 0,!1).toLowerCase()==="dls "?new WA(t):new st(t,!1)}function ao(t,A,e=!1){let n=this.workletProcessorChannels[t];if(n===void 0){U(`Trying to access channel ${t} which does not exist... ignoring!`);return}if(n.lockPreset)return;let s=n.drumChannel?128:n.midiControllers[m.bankSelect],o,a;if(this.overrideSoundfont){let C=s===128?128:s-this.soundfontBankOffset,Q=this.overrideSoundfont.getPresetNoFallback(C,A);Q?(o=s,a=Q,n.presetUsesOverride=!0):(a=this.soundfontManager.getPreset(s,A),o=a.bank,n.presetUsesOverride=!1)}else a=this.soundfontManager.getPreset(s,A),o=a.bank,n.presetUsesOverride=!1;this.setPreset(t,a),this.callEvent("programchange",{channel:t,program:a.program,bank:o,userCalled:e})}function Io(t,A){if(this.overrideSoundfont){let e=t===128?128:t-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(e,A);if(n)return n}return this.soundfontManager.getPreset(t,A)}function go(t,A){if(!this.workletProcessorChannels[t].lockPreset){delete this.workletProcessorChannels[t].preset,this.workletProcessorChannels[t].preset=A,this.workletProcessorChannels[t].cachedVoices=[];for(let e=0;e<128;e++)this.workletProcessorChannels[t].cachedVoices.push([])}}function Co(t,A){let e=this.workletProcessorChannels[t];e.lockPreset||e.drumChannel!==A&&(A?(e.channelTransposeKeyShift=0,e.drumChannel=!0,this.setPreset(t,this.getPreset(128,e.preset.program))):(e.drumChannel=!1,this.setPreset(t,this.getPreset(e.midiControllers[m.bankSelect],e.preset.program))),e.presetUsesOverride=!1,this.callEvent("drumchange",{channel:t,isDrumChannel:e.drumChannel}),this.sendChannelProperties())}function Eo(){let t=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let e=A.bank===128?128:A.bank+this.soundfontBankOffset,n=t.find(s=>s.bank===e&&s.program===A.program);n!==void 0?n.presetName=A.presetName:t.push({presetName:A.presetName,bank:e,program:A.program})}),this.callEvent("presetlistchange",t)}function Bo(t=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let e=0;e{this.programChange(n,e.preset.program)}),this.post({messageType:yA.ready,messageData:void 0}),this.sendPresetList(),p("%cSpessaSynth is ready!",r.recognized)}function Qo(t,A){this.soundfontBankOffset=A,this.reloadSoundFont(t,!0),this.overrideSoundfont.samples.forEach(e=>e.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function co(){let A={channelSnapshots:this.workletProcessorChannels.map(e=>({program:e.preset.program,bank:e.preset.bank,lockPreset:e.lockPreset,patchName:e.preset.presetName,midiControllers:e.midiControllers,lockedControllers:e.lockedControllers,customControllers:e.customControllers,channelVibrato:e.channelVibrato,lockVibrato:e.lockGSNRPNParams,channelTransposeKeyShift:e.channelTransposeKeyShift,channelOctaveTuning:e.channelOctaveTuning,keyCentTuning:e.keyCentTuning,velocityOverride:e.velocityOverride,isMuted:e.isMuted,drumChannel:e.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system,interpolation:this.interpolationType};this.post({messageType:yA.synthesizerSnapshot,messageData:A})}function lo(t){for(this.system=t.system,this.setMasterGain(t.mainVolume),this.setMasterPan(t.pan),this.transposeAllChannels(t.transposition),this.interpolationType=t.interpolation;this.workletProcessorChannels.length{let n=this.workletProcessorChannels[e];this.muteChannel(e,A.isMuted),this.setDrums(e,A.drumChannel),n.midiControllers=A.midiControllers,n.lockedControllers=A.lockedControllers,n.customControllers=A.customControllers,n.channelVibrato=A.channelVibrato,n.lockGSNRPNParams=A.lockVibrato,n.channelTransposeKeyShift=A.channelTransposeKeyShift,n.channelOctaveTuning=A.channelOctaveTuning,n.velocityOverride=A.velocityOverride,n.lockPreset=!1,n.midiControllers[m.bankSelect]=A.bank,this.programChange(e,A.program),n.lockPreset=A.lockPreset}),p("%cFinished restoring controllers!",r.info)}var ot=class{constructor(A,e){this.ready=e,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(e=>{e.soundfont.setSampleIDOffset(A),A+=e.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let e=this.soundfontList.length-1;e>=0;e--){let n=this.soundfontList[e],s=new Set;for(let o of n.soundfont.presets){let a=`${o.bank+n.bankOffset}-${o.program}`;s.has(a)||(s.add(a),A[a]=o.presetName)}}this.presetList=[];for(let[e,n]of Object.entries(A)){let s=e.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}}handleMessage(A,e){switch(A){case Ie.addNewSoundFont:this.addNewSoundFont(e[0],e[1],e[2]);break;case Ie.reloadSoundFont:this.reloadManager(e);break;case Ie.deleteSoundFont:this.deleteSoundFont(e);break;case Ie.rearrangeSoundFonts:this.rearrangeSoundFonts(e)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let e=Ge(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:e}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){U("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(n=>n.id===A);if(e===-1){U(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[e].soundfont.presets,delete this.soundfontList[e].soundfont.instruments,delete this.soundfontList[e].soundfont.samples,this.soundfontList.splice(e,1),this.generatePresetList()}addNewSoundFont(A,e,n){if(this.soundfontList.find(s=>s.id===e)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:e,soundfont:Ge(A),bankOffset:n}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((e,n)=>A.indexOf(e.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,e){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let n of this.soundfontList){let s=n.soundfont.getPresetNoFallback(A-n.bankOffset,e);if(s!==void 0)return s}if(A!==128){for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.program===e);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}else{for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.bank===128);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}}};var rt=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,e,n,s,o,a,C,Q){this.sampleData=A,this.playbackStep=e,this.cursor=n,this.rootKey=s,this.loopStart=o,this.loopEnd=a,this.end=C,this.loopingMode=Q,this.isLooping=this.loopingMode===1||this.loopingMode===3}},xe=class t{sample;filter=new Qe;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new JA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=.5;constructor(A,e,n,s,o,a,C,Q,B){this.sample=e,this.generators=Q,this.modulatedGenerators=new Int16Array(Q),this.modulators=B,this.velocity=s,this.midiNote=n,this.channelNumber=o,this.startTime=a,this.targetKey=C,this.volumeEnvelope=new UA(A,Q[g.sustainVolEnv])}static copy(A,e){let n=A.sample,s=new rt(n.sampleData,n.playbackStep,n.cursor,n.rootKey,n.loopStart,n.loopEnd,n.end,n.loopingMode);return new t(A.volumeEnvelope.sampleRate,s,A.midiNote,A.velocity,A.channelNumber,e,A.targetKey,A.generators,A.modulators.map(o=>j.copy(o)))}};function uo(t,A,e,n,s,o=!1){let a,C=n.cachedVoices[A][e];return C!==void 0?C.map(Q=>xe.copy(Q,s)):(a=n.preset.getSamplesAndGenerators(A,e).reduce((B,d)=>{if(d.sample.sampleData===void 0)return U(`Discarding invalid sample: ${d.sample.sampleName}`),B;let h=new Int16Array(60);for(let N=0;N<60;N++)h[N]=pn(N,d.presetGenerators,d.instrumentGenerators);h[g.initialAttenuation]=Math.floor(h[g.initialAttenuation]*.4);let l=d.sample.samplePitch;h[g.overridingRootKey]>-1&&(l=h[g.overridingRootKey]);let u=A;h[g.keyNum]>-1&&(u=h[g.keyNum]);let D=d.sample.sampleLoopStartIndex,S=d.sample.sampleLoopEndIndex,w=h[g.sampleModes],y=new rt(d.sample.getAudioData(),d.sample.sampleRate/sampleRate*Math.pow(2,d.sample.samplePitchCorrection/1200),0,l,D,S,Math.floor(d.sample.sampleData.length)-1,w);return h[g.velocity]>-1&&(e=h[g.velocity]),o&&mn([{Sample:d.sample.sampleName,Generators:h,Modulators:d.modulators.map(N=>N.debugString()),Velocity:e,TargetKey:u,MidiNote:A,WorkletSample:y}]),B.push(new xe(sampleRate,y,A,e,t,s,u,h,d.modulators.map(N=>j.copy(N)))),B},[]),n.cachedVoices[A][e]=a.map(B=>xe.copy(B,s)),a)}var Lt=.03,Ut=1,T=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=TA,this.interpolationType=he.fourthOrder,this.processTickCallback=void 0,this.sequencer=new IA(this),this.transposition=0,this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Ut,this.midiVolume=1,this.voiceCap=Dn,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new ot(A.processorOptions.soundfont,this.postReady.bind(this))}catch(e){throw this.post({messageType:yA.soundfontError,messageData:e}),e}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let e=0;ethis.handleMessage(e.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),p("%cRendering enabled! Starting render.",r.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),OA.isInitialized.then(()=>{this.postReady(),p("%cSpessaSynth is ready!",r.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:yA.ready,messageData:void 0})}debugMessage(){p({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,e){this.processTickCallback&&this.processTickCallback();let n=0;return this.workletProcessorChannels.forEach((s,o)=>{if(s.voices.length<1||s.isMuted)return;let a,C,Q,B,d;if(this.oneOutputMode){let l=e[0];a=o%16*2,C=l[a],Q=l[a+1]}else a=o%this._outputsAmount+2,C=e[a][0],Q=e[a][1],B=e[0],d=e[1];let h=s.voices;s.voices=[],h.forEach(l=>{this.renderVoice(s,l,C,Q,B,d),l.finished||s.voices.push(l)}),n+=s.voices.length}),n!==this.totalVoicesAmount&&(this.totalVoicesAmount=n,this.sendChannelProperties()),!0}};T.prototype.renderVoice=ts;T.prototype.releaseVoice=ss;T.prototype.voiceKilling=ns;T.prototype.getWorkletVoices=uo;T.prototype.handleMessage=is;T.prototype.sendChannelProperties=Is;T.prototype.callEvent=as;T.prototype.systemExclusive=gs;T.prototype.noteOn=Es;T.prototype.noteOff=Bs;T.prototype.polyPressure=Ds;T.prototype.killNote=hs;T.prototype.stopAll=Qs;T.prototype.stopAllChannels=cs;T.prototype.muteChannel=xs;T.prototype.setVibrato=Ns;T.prototype.disableAndLockGSNRPN=Ms;T.prototype.dataEntryCoarse=bs;T.prototype.dataEntryFine=Ls;T.prototype.createWorkletChannel=yn;T.prototype.controllerChange=ws;T.prototype.channelPressure=Ss;T.prototype.resetAllControllers=Us;T.prototype.resetControllers=Ts;T.prototype.resetParameters=Hs;T.prototype.setMasterGain=Rs;T.prototype.setMasterPan=Gs;T.prototype.setMIDIVolume=Fs;T.prototype.transposeAllChannels=ls;T.prototype.transposeChannel=us;T.prototype.setChannelTuning=ds;T.prototype.setChannelTuningSemitones=fs;T.prototype.setMasterTuning=ms;T.prototype.setModulationDepth=ps;T.prototype.pitchWheel=ys;T.prototype.setOctaveTuning=ks;T.prototype.programChange=ao;T.prototype.getPreset=Io;T.prototype.setPreset=go;T.prototype.setDrums=Co;T.prototype.reloadSoundFont=ho;T.prototype.clearSoundFont=Bo;T.prototype.setEmbeddedSoundFont=Qo;T.prototype.sendPresetList=Eo;T.prototype.sendSynthesizerSnapshot=co;T.prototype.applySynthesizerSnapshot=lo;registerProcessor(Sn,T);p("%cProcessor succesfully registered!",r.recognized); diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/voice_control.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/voice_control.js index 178057cc..3bc9b30f 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/voice_control.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/voice_control.js @@ -103,7 +103,8 @@ export function renderVoice( } // lowpass frequency - let lowpassCents = voice.modulatedGenerators[generatorTypes.initialFilterFc]; + const initialFc = voice.modulatedGenerators[generatorTypes.initialFilterFc]; + let lowpassCents = initialFc; // mod LFO const modPitchDepth = voice.modulatedGenerators[generatorTypes.modLfoToPitch]; @@ -178,8 +179,12 @@ export function renderVoice( getSampleCubic(voice, bufferOut); } - // lowpass filter - WorkletLowpassFilter.apply(voice, bufferOut, lowpassCents); + /* lowpass filter + * note: the check is because of the filter optimization (if cents are maximum then the filter is open) + * filter cannot use this optimization if it's dynamic (see #53) + * and the filter can only be dynamic if the inital filter is not open + */ + WorkletLowpassFilter.apply(voice, bufferOut, lowpassCents, initialFc > 13499); // volenv WorkletVolumeEnvelope.apply(voice, bufferOut, modLfoCentibels, this.volumeEnvelopeSmoothingFactor); diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/lowpass_filter.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/lowpass_filter.js index bb61e676..29ea3f91 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/lowpass_filter.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_utilities/lowpass_filter.js @@ -94,10 +94,12 @@ export class WorkletLowpassFilter * @param voice {WorkletVoice} the voice we're working on * @param outputBuffer {Float32Array} the buffer to apply the filter to * @param cutoffCents {number} cutoff frequency in cents + * @param canBeOpen {boolean} indicates if the filter can be open. + * See the comment in voice_control for details */ - static apply(voice, outputBuffer, cutoffCents) + static apply(voice, outputBuffer, cutoffCents, canBeOpen) { - if (cutoffCents > 13499 && voice.filter.reasonanceCb === 0) + if (canBeOpen && cutoffCents > 13499 && voice.filter.reasonanceCb === 0) { return; // filter is open } @@ -108,7 +110,7 @@ export class WorkletLowpassFilter { filter.cutoffCents = cutoffCents; filter.reasonanceCb = voice.modulatedGenerators[generatorTypes.initialFilterQ]; - WorkletLowpassFilter.calculateCoefficients(voice); + WorkletLowpassFilter.calculateCoefficients(filter); } // filter the input @@ -132,11 +134,10 @@ export class WorkletLowpassFilter } /** - * @param voice {WorkletVoice} + * @param filter {WorkletLowpassFilter} */ - static calculateCoefficients(voice) + static calculateCoefficients(filter) { - const filter = voice.filter; filter.cutoffHz = absCentsToHz(filter.cutoffCents); // fix cutoff on low frequencies (fluid_iir_filter.c line 392)