spessasynth_lib 3.27.0 → 3.27.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spessasynth_lib",
3
- "version": "3.27.0",
3
+ "version": "3.27.2",
4
4
  "description": "MIDI and SoundFont2/DLS library for the browsers with no compromises",
5
5
  "browser": "index.js",
6
6
  "type": "module",
@@ -16,17 +16,22 @@ import { audioToWav } from "spessasynth_core";
16
16
  * @param channelOffset {number} channel offset and channel offset + 1 get saved
17
17
  * @param metadata {WaveMetadata}
18
18
  * @param loop {{start: number, end: number}} loop start and end points in seconds. Undefined if no loop
19
+ * @param channelCount {number} the channel count, defaults to all the channels
19
20
  * @returns {Blob}
20
21
  */
21
- export function audioBufferToWav(audioBuffer, normalizeAudio = true, channelOffset = 0, metadata = {}, loop = undefined)
22
+ export function audioBufferToWav(audioBuffer, normalizeAudio = true, channelOffset = 0, metadata = {}, loop = undefined, channelCount = audioBuffer.numberOfChannels)
22
23
  {
23
24
  /**
24
25
  * @type {Float32Array[]}
25
26
  */
26
27
  const channels = [];
27
- for (let i = 0; i < audioBuffer.numberOfChannels; i++)
28
+ for (let i = channelOffset; i < audioBuffer.numberOfChannels; i++)
28
29
  {
29
- channels.push(audioBuffer.getChannelData(channelOffset + i));
30
+ channels.push(audioBuffer.getChannelData(i));
31
+ if (channels.length >= channelCount)
32
+ {
33
+ break;
34
+ }
30
35
  }
31
36
  return new Blob(
32
37
  [audioToWav(channels, audioBuffer.sampleRate, normalizeAudio, metadata, loop)],
@@ -10,7 +10,7 @@ var Ws=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(A,e)=>(
10
10
  `}getSourceEnum(){return WA(this.sourceCurveType,this.sourcePolarity,this.sourceDirection,this.sourceUsesCC,this.sourceIndex)}getSecSrcEnum(){return WA(this.secSrcCurveType,this.secSrcPolarity,this.secSrcDirection,this.secSrcUsesCC,this.secSrcIndex)}sumTransform(A){return new t(this.sourceIndex,this.sourceCurveType,this.sourceUsesCC,this.sourcePolarity,this.sourceDirection,this.secSrcIndex,this.secSrcCurveType,this.secSrcUsesCC,this.secSrcPolarity,this.secSrcDirection,this.modulatorDestination,this.transformAmount+A.transformAmount,this.transformType,this.isEffectModulator)}},pA=class extends EA{constructor(A,e,n,s,r){let i=A>>9&1,a=A>>8&1,o=A>>7&1,I=A&127,l=A>>10&3,E=e>>9&1,C=e>>8&1,B=e>>7&1,f=e&127,u=e>>10&3;super(I,l,o,i,a,f,u,B,E,C,n,s,r),this.isEffectModulator=(A===219||A===221)&&e===0&&(this.modulatorDestination===g.reverbEffectsSend||this.modulatorDestination===g.chorusEffectsSend)}},Is=960,cs=kA.concave;function WA(t,A,e,n,s){return t<<10|A<<9|e<<8|n<<7|s}var bi=[new pA(WA(cs,0,1,0,W.noteOnVelocity),0,g.initialAttenuation,Is,0),new pA(129,0,g.vibLfoToPitch,50,0),new pA(WA(cs,0,1,1,p.mainVolume),0,g.initialAttenuation,Is,0),new pA(13,0,g.vibLfoToPitch,50,0),new pA(526,16,g.fineTune,12700,0),new pA(650,0,g.pan,500,0),new pA(WA(cs,0,1,1,p.expressionController),0,g.initialAttenuation,Is,0),new pA(219,0,g.reverbEffectsSend,200,0),new pA(221,0,g.chorusEffectsSend,200,0)],Li=[new pA(WA(kA.linear,0,0,0,W.polyPressure),0,g.vibLfoToPitch,50,0),new pA(WA(kA.linear,0,0,1,p.tremoloDepth),0,g.modLfoToVolume,24,0),new pA(WA(kA.convex,1,0,1,p.attackTime),0,g.attackVolEnv,6e3,0),new pA(WA(kA.linear,1,0,1,p.releaseTime),0,g.releaseVolEnv,3600,0),new pA(WA(kA.linear,1,0,1,p.brightness),0,g.initialFilterFc,6e3,0),new pA(WA(kA.linear,1,0,1,p.filterResonance),0,g.initialFilterQ,250,0)],co=bi.concat(Li);var hA=128,hn=147,Pe=new Int16Array(hn).fill(0),MA=(t,A)=>Pe[t]=A<<7;MA(p.mainVolume,100);MA(p.balance,64);MA(p.expressionController,127);MA(p.pan,64);MA(p.portamentoOnOff,127);MA(p.filterResonance,64);MA(p.releaseTime,64);MA(p.attackTime,64);MA(p.brightness,64);MA(p.decayTime,64);MA(p.vibratoRate,64);MA(p.vibratoDepth,64);MA(p.vibratoDelay,64);MA(p.generalPurposeController6,64);MA(p.generalPurposeController8,64);MA(p.RPNLsb,127);MA(p.RPNMsb,127);MA(p.NRPNLsb,127);MA(p.NRPNMsb,127);var ln=1;Pe[p.portamentoControl]=ln;MA(hA+W.pitchWheel,64);MA(hA+W.pitchWheelRange,2);var nA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4,channelKeyShift:5,sf2NPRNGeneratorLSB:6},Es=Object.keys(nA).length,Cs=new Float32Array(Es);Cs[nA.modulationMultiplier]=1;var UA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},hs={velocityOverride:128};function Eo(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 Co(t,A=0){let e=t[0];if(this.deviceID!==-1&&t[1]!==127&&this.deviceID!==t[1])return;function n(r,i,a,o){y(`%cChannel %c${r}%c ${a}. %c${i} ${o}%c, with %c${YA(t)}`,c.info,c.recognized,c.info,c.value,c.info,c.value)}function s(){H(`%cUnrecognized Roland %cGS %cSysEx: %c${YA(t)}`,c.warn,c.recognized,c.warn,c.unrecognized)}switch(e){default:H(`%cUnrecognized SysEx: %c${YA(t)}`,c.warn,c.unrecognized);break;case 126:case 127:switch(t[2]){case 4:let r;switch(t[3]){case 1:let a=t[5]<<7|t[4];this.setMIDIVolume(a/16384),y(`%cMaster Volume. Volume: %c${a}`,c.info,c.value);break;case 2:let I=((t[5]<<7|t[4])-8192)/8192;this.setMasterParameter(JA.masterPan,I),y(`%cMaster Pan. Pan: %c${I}`,c.info,c.value);break;case 3:let l=(t[5]<<7|t[6])-8192;r=Math.floor(l/81.92),this.setMasterTuning(r),y(`%cMaster Fine Tuning. Cents: %c${r}`,c.info,c.value);break;case 4:r=(t[5]-64)*100,this.setMasterTuning(r),y(`%cMaster Coarse Tuning. Cents: %c${r}`,c.info,c.value);break;default:H(`%cUnrecognized MIDI Device Control Real-time message: %c${YA(t)}`,c.warn,c.unrecognized)}break;case 9:t[3]===1?(y("%cGM1 system on",c.info),this.setSystem("gm")):t[3]===3?(y("%cGM2 system on",c.info),this.setSystem("gm2")):(y("%cGM system off, defaulting to GS",c.info),this.setSystem("gs"));break;case 8:let i=4;switch(t[3]){case 1:let a=t[i++];t.currentIndex=i;let o=j(t,16);if(i+=16,t.length<384){H(`The Bulk Tuning Dump is too short! (${t.length} bytes, at least 384 are expected)`);return}for(let C=0;C<128;C++)this.tunings[a][C]=Eo(t[i++],t[i++],t[i++]);y(`%cBulk Tuning Dump %c${o}%c Program: %c${a}`,c.info,c.value,c.info,c.recognized);break;case 2:case 7:t[3]===7&&i++;let I=t[i++],l=t[i++];for(let C=0;C<l;C++)this.tunings[I][t[i++]]=Eo(t[i++],t[i++],t[i++]);y(`%cSingle Note Tuning. Program: %c${I}%c Keys affected: %c${l}`,c.info,c.recognized,c.info,c.recognized);break;case 9:case 8:let E=new Int8Array(12);if(t[3]===8)for(let C=0;C<12;C++)E[C]=t[7+C]-64;else for(let C=0;C<24;C+=2){let B=(t[7+C]<<7|t[8+C])-8192;E[C/2]=Math.floor(B/81.92)}(t[4]&1)===1&&this.midiAudioChannels[14+A].setOctaveTuning(E),(t[4]>>1&1)===1&&this.midiAudioChannels[15+A].setOctaveTuning(E);for(let C=0;C<7;C++)(t[5]>>C&1)===1&&this.midiAudioChannels[7+C+A].setOctaveTuning(E);for(let C=0;C<7;C++)(t[6]>>C&1)===1&&this.midiAudioChannels[C+A].setOctaveTuning(E);y(`%cMIDI Octave Scale ${t[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${E.join(" ")}`,c.info,c.value);break;default:H(`%cUnrecognized MIDI Tuning standard message: %c${YA(t)}`,c.warn,c.unrecognized);break}break;default:H(`%cUnrecognized MIDI Realtime/non realtime message: %c${YA(t)}`,c.warn,c.unrecognized)}break;case 65:if(t[2]===66&&t[3]===18){let r=t[7];if(t[4]===64||t[4]===0&&t[6]===127){if((t[5]&16)>0){let i=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A,a=this.midiAudioChannels[i];switch(t[6]){default:s();break;case 21:let o=r>0&&t[5]>>4;a.setDrums(o),y(`%cChannel %c${i}%c ${o?"is now a drum channel":"now isn't a drum channel"}%c via: %c${YA(t)}`,c.info,c.value,c.recognized,c.info,c.value);return;case 22:let I=r-64;a.setCustomController(nA.channelKeyShift,I),n(i,I,"key shift","keys");return;case 28:let l=r;l===0?(a.randomPan=!0,y(`%cRandom pan is set to %cON%c for %c${i}`,c.info,c.recognized,c.info,c.value)):(a.randomPan=!1,a.controllerChange(p.pan,l));break;case 33:a.controllerChange(p.chorusDepth,r);break;case 34:a.controllerChange(p.reverbDepth,r);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 E=t.length-9,C=new Int8Array(12);for(let f=0;f<E;f++)C[f]=t[f+7]-64;a.setOctaveTuning(C);let B=r-64;n(i,C.join(" "),"octave scale tuning","cents"),a.setTuning(B);break}return}else if((t[5]&32)>0){let i=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][t[5]&15]+A,a=this.midiAudioChannels[i],o=r-64,I=o/64,l=r/128,E=(C,B,f=!1)=>{switch(t[6]&15){case 0:C===hA+W.pitchWheel?(a.controllerChange(p.RPNMsb,0),a.controllerChange(p.RPNLsb,0),a.controllerChange(p.dataEntryMsb,Math.floor(o))):(a.sysExModulators.setModulator(C,g.fineTune,o*100,f),n(i,o,`${B} pitch control`,"semitones"));break;case 1:a.sysExModulators.setModulator(C,g.initialFilterFc,I*9600,f),n(i,I*9600,`${B} pitch control`,"cents");break;case 2:a.sysExModulators.setModulator(C,g.initialAttenuation,I*960,f),n(i,I*960,`${B} amplitude`,"cB");break;case 4:a.sysExModulators.setModulator(C,g.vibLfoToPitch,l*600,f),n(i,l*600,`${B} LFO1 pitch depth`,"cents");break;case 5:a.sysExModulators.setModulator(C,g.vibLfoToFilterFc,l*2400,f),n(i,l*2400,`${B} LFO1 filter depth`,"cents");break;case 6:a.sysExModulators.setModulator(C,g.vibLfoToVolume,I*960,f),n(i,I*960,`${B} LFO1 amplitude depth`,"cB");break;case 8:a.sysExModulators.setModulator(C,g.modLfoToPitch,l*600,f),n(i,l*600,`${B} LFO2 pitch depth`,"cents");break;case 9:a.sysExModulators.setModulator(C,g.modLfoToFilterFc,l*2400,f),n(i,l*2400,`${B} LFO2 filter depth`,"cents");break;case 10:a.sysExModulators.setModulator(C,g.modLfoToVolume,I*960,f),n(i,I*960,`${B} LFO2 amplitude depth`,"cB");break}};switch(t[6]&240){default:s();break;case 0:E(p.modulationWheel,"mod wheel");break;case 16:E(hA+W.pitchWheel,"pitch bend",!0);break;case 32:E(hA+W.channelPressure,"channel pressure");break;case 48:E(hA+W.polyPressure,"poly pressure");break}return}else if(t[5]===0){switch(t[6]){default:s();break;case 127:r===0?(y("%cGS Reset received!",c.info),this.resetAllControllers(!1),this.setSystem("gs")):r===127&&(y("%cGS system off, switching to GM2",c.info),this.resetAllControllers(!1),this.setSystem("gm2"));break;case 6:y(`%cRoland GS Master Pan set to: %c${r}%c with: %c${YA(t)}`,c.info,c.value,c.info,c.value),this.setMasterParameter(JA.masterPan,(r-64)/64);break;case 4:y(`%cRoland GS Master Volume set to: %c${r}%c with: %c${YA(t)}`,c.info,c.value,c.info,c.value),this.setMIDIVolume(r/127);break;case 5:let i=r-64;y(`%cRoland GS Master Key-Shift set to: %c${i}%c with: %c${YA(t)}`,c.info,c.value,c.info,c.value),this.setMasterTuning(i*100);break}return}else if(t[5]===1)switch(t[6]){default:s();break;case 0:t.currentIndex=7;let i=j(t,16);y(`%cGS Patch name: %c${i}`,c.info,c.value);break;case 51:y(`%cGS Reverb level: %c${r}`,c.info,c.value),this.reverbSend=r/64;break;case 48:case 49:case 50:case 52:case 53:case 55:y(`%cUnsupported GS Reverb Parameter: %c${t[6].toString(16)}`,c.warn,c.unrecognized);break;case 58:y(`%cGS Chorus level: %c${r}`,c.info,c.value),this.chorusSend=r/64;break;case 56:case 57:case 59:case 60:case 61:case 62:case 63:case 64:y(`%cUnsupported GS Chorus Parameter: %c${t[6].toString(16)}`,c.warn,c.unrecognized);break}}else s();return}else if(t[2]===69&&t[3]===18){if(t[4]===16&&t[6]===0)if(t[5]===0){let r=new Uint8Array(t.slice(7,t.length-2));this.callEvent("synthdisplay",{displayData:r,displayType:Jt.SoundCanvasText})}else if(t[5]===1){let r=new Uint8Array(t.slice(7,t.length-3));this.callEvent("synthdisplay",{displayData:r,displayType:Jt.SoundCanvasDotDisplay}),y(`%cRoland SC Display Dot Matrix via: %c${YA(t)}`,c.info,c.value)}else s()}else if(t[2]===22&&t[3]===18&&t[4]===16){this.setMIDIVolume(t[7]/100),y(`%cRoland Master Volume control set to: %c${t[7]}%c via: %c${YA(t)}`,c.info,c.value,c.info,c.value);return}else{H(`%cUnrecognized Roland SysEx: %c${YA(t)}`,c.warn,c.unrecognized);return}break;case 67:if(t[2]===76)if(t[3]===0&&t[4]===0)switch(t[5]){case 4:let r=t[6];this.setMIDIVolume(r/127),y(`%cXG master volume. Volume: %c${r}`,c.info,c.recognized);break;case 6:let i=t[6]-64;this.transposeAllChannels(i),y(`%cXG master transpose. Volume: %c${i}`,c.info,c.recognized);break;case 126:y("%cXG system on",c.info),this.resetAllControllers(!1),this.setSystem("xg");break}else if(t[3]===8){if(!GA(this.system))return;let r=t[4]+A;if(r>=this.midiAudioChannels.length)return;let i=this.midiAudioChannels[r],a=t[6];switch(t[5]){case 1:i.controllerChange(p.bankSelect,a);break;case 2:i.controllerChange(p.lsbForControl0BankSelect,a);break;case 3:i.programChange(a);break;case 8:if(i.drumChannel)return;let o=a-64;i.channelTransposeKeyShift=o;break;case 11:i.controllerChange(p.mainVolume,a);break;case 14:let I=a;I===0?(i.randomPan=!0,y(`%cRandom pan is set to %cON%c for %c${r}`,c.info,c.recognized,c.info,c.value)):i.controllerChange(p.pan,I);break;case 19:i.controllerChange(p.reverbDepth,a);break;case 18:i.controllerChange(p.chorusDepth,a);break;default:H(`%cUnrecognized Yamaha XG Part Setup: %c${t[5].toString(16).toUpperCase()}`,c.warn,c.unrecognized)}}else if(t[3]===6&&t[4]===0){let r=new Uint8Array(t.slice(5,t.length-1));this.callEvent("synthdisplay",{displayData:r,displayType:Jt.XGText})}else GA(this.system)&&H(`%cUnrecognized Yamaha XG SysEx: %c${YA(t)}`,c.warn,c.unrecognized);else GA(this.system)&&H(`%cUnrecognized Yamaha SysEx: %c${YA(t)}`,c.warn,c.unrecognized);break}}function ho(t=!0){t&&y("%cResetting all controllers!",c.info),this.callEvent("allcontrollerreset",void 0),this.setSystem(Ot);for(let A=0;A<this.midiAudioChannels.length;A++){let e=this.midiAudioChannels[A];if(e.resetControllers(),e.lockPreset?this.callEvent("drumchange",{channel:A,isDrumChannel:e.drumChannel}):(e.setBankSelect(go(this.system)),A%16===9?(e.setPreset(this.drumPreset),e.drumChannel=!0,this.callEvent("drumchange",{channel:A,isDrumChannel:!0})):(e.drumChannel=!1,e.setPreset(this.defaultPreset),this.callEvent("drumchange",{channel:A,isDrumChannel:!1}))),!e.preset)continue;let n=e.preset?.bank;this.callEvent("programchange",{channel:A,program:e.preset?.program,bank:n});for(let s=0;s<128;s++)this.midiAudioChannels[A].lockedControllers[s]&&this.callEvent("controllerchange",{channel:A,controllerNumber:s,controllerValue:this.midiAudioChannels[A].midiControllers[s]>>7});if(this.midiAudioChannels[A].lockedControllers[hA+W.pitchWheel]===!1){let s=this.midiAudioChannels[A].midiControllers[hA+W.pitchWheel],r=s>>7,i=s&127;this.callEvent("pitchwheel",{channel:A,MSB:r,LSB:i})}if(this.midiAudioChannels[A].lockedControllers[hA+W.channelPressure]===!1){let s=this.midiAudioChannels[A].midiControllers[hA+W.channelPressure]>>7;this.callEvent("channelpressure",{channel:A,pressure:s})}}this.tunings=[],this.tunings=[];for(let A=0;A<128;A++)this.tunings.push([]);this.setMIDIVolume(1)}function lo(){this.channelOctaveTuning.fill(0);for(let A=0;A<Pe.length;A++){if(this.lockedControllers[A])continue;let e=Pe[A];this.midiControllers[A]!==e&&A<127?A===p.portamentoControl?this.midiControllers[A]=ln:this.controllerChange(A,e>>7):this.midiControllers[A]=e}this.channelVibrato={rate:0,depth:0,delay:0},this.holdPedal=!1,this.randomPan=!1,this.sysExModulators.resetModulators();let t=this.customControllers[nA.channelTransposeFine];this.customControllers.set(Cs),this.setCustomController(nA.channelTransposeFine,t),this.resetParameters()}var ls=new Set([p.bankSelect,p.lsbForControl0BankSelect,p.mainVolume,p.lsbForControl7MainVolume,p.pan,p.lsbForControl10Pan,p.reverbDepth,p.tremoloDepth,p.chorusDepth,p.detuneDepth,p.phaserDepth,p.soundVariation,p.filterResonance,p.releaseTime,p.attackTime,p.brightness,p.decayTime,p.vibratoRate,p.vibratoDepth,p.vibratoDelay,p.soundController10]);function Bo(){this.channelOctaveTuning.fill(0),this.pitchWheel(64,0),this.channelVibrato={rate:0,depth:0,delay:0};for(let t=0;t<128;t++){let A=Pe[t];!ls.has(t)&&A!==this.midiControllers[t]&&(t===p.portamentoControl?this.midiControllers[t]=ln:this.controllerChange(t,A>>7))}this.resetGeneratorOverrides(),this.resetGeneratorOffsets()}function Qo(){this.dataEntryState=UA.Idle,this.midiControllers[p.NRPNLsb]=16256,this.midiControllers[p.NRPNMsb]=16256,this.midiControllers[p.RPNLsb]=16256,this.midiControllers[p.RPNMsb]=16256,this.resetGeneratorOverrides(),this.resetGeneratorOffsets()}var ut=class{soundfontList=[];presetList=[];constructor(A){this.presetListChangeCallback=A}generatePresetList(){let A={};for(let e=this.soundfontList.length-1;e>=0;e--){let n=this.soundfontList[e],s=new Set;for(let r of n.soundfont.presets){let a=`${Math.min(128,r.bank+n.bankOffset)}-${r.program}`;s.has(a)||(s.add(a),A[a]=r.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])})}this.presetListChangeCallback()}getPresetList(){return this.presetList.slice()}reloadManager(A){this.soundfontList=this.soundfontList.filter(e=>e.id===je),this.soundfontList.push({id:"main",bankOffset:0,soundfont:A}),this.generatePresetList()}deleteSoundFont(A){if(this.soundfontList.length===0){H("1 soundfont left. Aborting!");return}let e=this.soundfontList.findIndex(n=>n.id===A);if(e===-1){y(`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){let s=this.soundfontList.find(r=>r.id===e);s.soundfont=A,s.bankOffset=n}else this.soundfontList.push({id:e,soundfont:A,bankOffset:n});this.generatePresetList()}getCurrentSoundFontOrder(){return this.soundfontList.map(A=>A.id)}rearrangeSoundFonts(A){this.soundfontList.sort((e,n)=>A.indexOf(e.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,e,n=!1){if(this.soundfontList.length<1)throw new Error("No soundfonts! Did you forget to add one?");let s=A===128||n&&te(A);for(let r of this.soundfontList){let i=r.soundfont.getPresetNoFallback(A===128?128:A-r.bankOffset,e,n);if(i!==void 0)return{preset:i,bankOffset:r.bankOffset}}if(s){for(let i of this.soundfontList){let a=i.soundfont.presets.find(I=>I.isDrumPreset(n)&&I.program===e);if(a)return{preset:a,bankOffset:i.bankOffset};let o=i.soundfont.presets.find(I=>I.isDrumPreset(n));if(o)return{preset:o,bankOffset:i.bankOffset}}let r=this.soundfontList[0];return{preset:r.soundfont.presets[0],bankOffset:r.bankOffset}}else{for(let i of this.soundfontList){let a=i.soundfont.presets.find(o=>o.program===e&&!o.isDrumPreset(n));if(a)return{preset:a,bankOffset:i.bankOffset}}let r=this.soundfontList[0];return{preset:r.soundfont.presets[0],bankOffset:r.bankOffset}}}destroyManager(){this.soundfontList.forEach(A=>{A.soundfont.destroySoundBank()}),delete this.soundfontList}};var Bn=class{_keyMappings=[];addMapping(A,e,n){this._keyMappings[A]===void 0&&(this._keyMappings[A]=[]),this._keyMappings[A][e]=n}deleteMapping(A,e){this._keyMappings[A]?.[e]!==void 0&&(this._keyMappings[A][e]=void 0)}clearMappings(){this._keyMappings=[]}setMappings(A){this._keyMappings=A}getMappings(){return this._keyMappings}getVelocity(A,e){return this._keyMappings[A]?.[e]?.velocity??-1}getGain(A,e){return this._keyMappings[A]?.[e]?.gain??1}hasOverridePatch(A,e){let n=this._keyMappings[A]?.[e]?.patch?.bank;return n!==void 0&&n>=0}getPatch(A,e){let n=this._keyMappings[A]?.[e];if(n)return n.patch;throw new Error("No modifier.")}};var fo=.1,Je=class t{static cachedCoefficients=[];a0=0;a1=0;a2=0;a3=0;a4=0;x1=0;x2=0;y1=0;y2=0;resonanceCb=0;currentInitialFc=13500;lastTargetCutoff=1/0;initialized=!1;sampleRate;constructor(A){this.sampleRate=A,this.maxCutoff=A*.45}static apply(A,e,n,s){let r=A.modulatedGenerators[g.initialFilterFc],i=A.filter;i.initialized?i.currentInitialFc+=(r-i.currentInitialFc)*s:(i.initialized=!0,i.currentInitialFc=r);let a=i.currentInitialFc+n,o=A.modulatedGenerators[g.initialFilterQ];if(i.currentInitialFc>13499&&a>13499&&o===0){i.currentInitialFc=13500;return}(Math.abs(i.lastTargetCutoff-a)>1||i.resonanceCb!==o)&&(i.lastTargetCutoff=a,i.resonanceCb=o,t.calculateCoefficients(i,a));for(let I=0;I<e.length;I++){let l=e[I],E=i.a0*l+i.a1*i.x1+i.a2*i.x2-i.a3*i.y1-i.a4*i.y2;i.x2=i.x1,i.x1=l,i.y2=i.y1,i.y1=E,e[I]=E}}static calculateCoefficients(A,e){e=~~e;let n=A.resonanceCb,s=t.cachedCoefficients?.[n]?.[e];if(s!==void 0){A.a0=s.a0,A.a1=s.a1,A.a2=s.a2,A.a3=s.a3,A.a4=s.a4;return}let r=Yt(e);r=Math.min(r,A.maxCutoff);let i=n/10,a=Ee(-(i-3.01)),o=1/Math.sqrt(Ee(-i)),I=2*Math.PI*r/A.sampleRate,l=Math.cos(I),E=Math.sin(I)/(2*a),C=(1-l)*o,B=C/2,f=B,u=1+E,S=-2*l,M=1-E,F={};F.a0=B/u,F.a1=C/u,F.a2=f/u,F.a3=S/u,F.a4=M/u,A.a0=F.a0,A.a1=F.a1,A.a2=F.a2,A.a3=F.a3,A.a4=F.a4,t.cachedCoefficients[n]===void 0&&(t.cachedCoefficients[n]=[]),t.cachedCoefficients[n][e]=F}},Bs=new Je(44100);Bs.resonanceCb=0;for(let t=1500;t<13500;t++)Bs.currentInitialFc=t,Je.calculateCoefficients(Bs,t);var NA=16384,xe=new Float32Array(NA+1),At=new Float32Array(NA+1);xe[0]=0;xe[xe.length-1]=1;At[0]=0;At[At.length-1]=1;for(let t=1;t<NA-1;t++){let A=-.4166666666666667*Math.log(t/(xe.length-1))/Math.LN10;At[t]=1-A,xe[xe.length-1-t]=A}function et(t,A,e,n){switch(t&&(e=1-e),A){case kA.linear:return n?e*2-1:e;case kA.switch:return e=e>.5?1:0,n?e*2-1:e;case kA.concave:return n?(e=e*2-1,e<0?-xe[~~(e*-NA)]:xe[~~(e*NA)]):xe[~~(e*NA)];case kA.convex:return n?(e=e*2-1,e<0?-At[~~(e*-NA)]:At[~~(e*NA)]):At[~~(e*NA)]}}var ds=1,Qs=new Float32Array(1e3);for(let t=0;t<Qs.length;t++)Qs[t]=et(0,kA.convex,t/1e3,0);var Qe=class t{attackDuration=0;decayDuration=0;holdDuration=0;releaseDuration=0;sustainLevel=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;releaseStartLevel=0;currentValue=0;static startRelease(A){t.recalculate(A)}static recalculate(A){let e=A.modulationEnvelope;A.isInRelease&&(e.releaseStartLevel=t.getValue(A,A.releaseStartTime,!0)),e.sustainLevel=1-A.modulatedGenerators[g.sustainModEnv]/1e3,e.attackDuration=Be(A.modulatedGenerators[g.attackModEnv]);let n=(60-A.midiNote)*A.modulatedGenerators[g.keyNumToModEnvDecay],s=Be(A.modulatedGenerators[g.decayModEnv]+n);e.decayDuration=s*(1-e.sustainLevel);let r=(60-A.midiNote)*A.modulatedGenerators[g.keyNumToModEnvHold];e.holdDuration=Be(r+A.modulatedGenerators[g.holdModEnv]);let i=Be(A.modulatedGenerators[g.releaseModEnv]);e.releaseDuration=i*e.releaseStartLevel,e.delayEnd=A.startTime+Be(A.modulatedGenerators[g.delayModEnv]),e.attackEnd=e.delayEnd+e.attackDuration,e.holdEnd=e.attackEnd+e.holdDuration,e.decayEnd=e.holdEnd+e.decayDuration}static getValue(A,e,n=!1){let s=A.modulationEnvelope;return A.isInRelease&&!n?s.releaseStartLevel===0?0:Math.max(0,(1-(e-A.releaseStartTime)/s.releaseDuration)*s.releaseStartLevel):(e<s.delayEnd?s.currentValue=0:e<s.attackEnd?s.currentValue=Qs[~~((1-(s.attackEnd-e)/s.attackDuration)*1e3)]:e<s.holdEnd?s.currentValue=ds:e<s.decayEnd?s.currentValue=(1-(s.decayEnd-e)/s.decayDuration)*(s.sustainLevel-ds)+ds:s.currentValue=s.sustainLevel,s.currentValue)}};var De=4,Y=class{generatorType=g.INVALID;generatorValue=0;constructor(A=g.INVALID,e=0,n=!0){if(this.generatorType=A,e===void 0)throw new Error("No value provided.");if(this.generatorValue=Math.round(e),n){let s=V[A];s!==void 0&&(this.generatorValue=Math.max(s.min,Math.min(s.max,this.generatorValue)))}}};function uo(t,A,e){let n=V[t]||{min:0,max:32768,def:0},s=A.find(o=>o.generatorType===t),r=0;s&&(r=s.generatorValue);let i=e.find(o=>o.generatorType===t),a=n.def;return i&&(a=i.generatorValue),a+r}var Ti=-2320,Ui=-1130,dn=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,e,n,s,r,i,a,o){this.sampleData=A,this.playbackStep=e,this.cursor=n,this.rootKey=s,this.loopStart=r,this.loopEnd=i,this.end=a,this.loopingMode=o,this.isLooping=this.loopingMode===1||this.loopingMode===3}},Kt=class t{sample;filter;gain=1;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new Qe;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=0;realKey;portamentoFromKey=-1;portamentoDuration=0;overridePan=0;exclusiveClass=0;constructor(A,e,n,s,r,i,a,o,I){this.sample=e,this.generators=o,this.exclusiveClass=this.generators[g.exclusiveClass],this.modulatedGenerators=new Int16Array(o),this.modulators=I,this.filter=new Je(A),this.velocity=s,this.midiNote=n,this.startTime=r,this.targetKey=i,this.realKey=a,this.volumeEnvelope=new de(A,o[g.sustainVolEnv])}static copy(A,e,n){let s=A.sample,r=new dn(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new t(A.volumeEnvelope.sampleRate,r,A.midiNote,A.velocity,e,A.targetKey,n,new Int16Array(A.generators),A.modulators.map(i=>EA.copy(i)))}exclusiveRelease(A){this.release(A,So),this.modulatedGenerators[g.releaseVolEnv]=Ti,this.modulatedGenerators[g.releaseModEnv]=Ui,de.recalculate(this),Qe.recalculate(this)}release(A,e=yo){this.releaseStartTime=A,this.releaseStartTime-this.startTime<e&&(this.releaseStartTime=this.startTime+e)}};function mo(t,A,e,n,s,r){let i=t.getSamplesAndGenerators(n,s).reduce((a,o)=>{if(o.sample.getAudioData()===void 0)return H(`Discarding invalid sample: ${o.sample.sampleName}`),a;let I=new Int16Array(Pt);for(let S=0;S<60;S++)I[S]=uo(S,o.presetGenerators,o.instrumentGenerators);I[g.initialAttenuation]=Math.floor(I[g.initialAttenuation]*.4);let l=o.sample.samplePitch;I[g.overridingRootKey]>-1&&(l=I[g.overridingRootKey]);let E=n;I[g.keyNum]>-1&&(E=I[g.keyNum]);let C=o.sample.sampleLoopStartIndex,B=o.sample.sampleLoopEndIndex,f=I[g.sampleModes],u=new dn(o.sample.sampleData,o.sample.sampleRate/this.sampleRate*Math.pow(2,o.sample.samplePitchCorrection/1200),0,l,C,B,Math.floor(o.sample.sampleData.length)-1,f);return I[g.velocity]>-1&&(s=I[g.velocity]),a.push(new Kt(this.sampleRate,u,n,s,this.currentSynthTime,E,r,I,o.modulators.map(S=>EA.copy(S)))),a},[]);return this.setCachedVoice(A,e,n,s,i),i.map(a=>Kt.copy(a,this.currentSynthTime,r))}function po(t,A,e,n){let s=this.midiAudioChannels[t],r=this.keyModifierManager.hasOverridePatch(t,A),i=s.getBankSelect(),a=s.preset;if(!a)return H(`No preset for channel ${t}!`),[];let o=a.program;if(r){let l=this.keyModifierManager.getPatch(t,A);i=l.bank,o=l.program}let I=this.getCachedVoice(i,o,A,e);return I!==void 0?I.map(l=>Kt.copy(l,this.currentSynthTime,n)):(r&&(a=this.getPreset(i,o)),this.getVoicesForPreset(a,i,o,A,e,n))}var ko=.05,vi=3070,Hi=2e3,Do=Math.PI/2,Qn=-500,Fo=500,fs=Fo-Qn,wo=new Float32Array(fs+1),Ro=new Float32Array(fs+1);for(let t=Qn;t<=Fo;t++){let A=(t-Qn)/fs,e=t-Qn;wo[e]=Math.cos(Do*A),Ro[e]=Math.sin(Do*A)}function Go(t,A,e,n,s,r,i,a,o){if(isNaN(A[0]))return;let I;t.overridePan?I=t.overridePan:(t.currentPan+=(t.modulatedGenerators[g.pan]-t.currentPan)*this.synth.panSmoothingFactor,I=t.currentPan);let l=this.synth.currentGain*t.gain,E=~~(I+500),C=wo[E]*l*this.synth.panLeft,B=Ro[E]*l*this.synth.panRight;if(this.synth.effectsEnabled){let f=t.modulatedGenerators[g.reverbEffectsSend];if(f>0){let S=this.synth.reverbGain*this.synth.reverbSend*l*(f/vi);for(let M=0;M<A.length;M++){let F=M+o;s[F]+=S*A[M],r[F]+=S*A[M]}}let u=t.modulatedGenerators[g.chorusEffectsSend];if(u>0){let S=this.synth.chorusGain*this.synth.chorusSend*(u/Hi),M=C*S,F=B*S;for(let k=0;k<A.length;k++){let G=k+o;i[G]+=M*A[k],a[G]+=F*A[k]}}}if(C>0)for(let f=0;f<A.length;f++)e[f+o]+=C*A[f];if(B>0)for(let f=0;f<A.length;f++)n[f+o]+=B*A[f]}function Mo(t=!1){y("%cStop all received!",c.info);for(let A=0;A<this.midiAudioChannels.length;A++)this.midiAudioChannels[A].stopAllNotes(t);this.callEvent("stopall",void 0)}function U(t,A){let e=0;for(let n=0;n<A;n++)e|=t[t.currentIndex++]<<n*8;return e>>>0}function ZA(t,A,e){for(let n=0;n<e;n++)t[t.currentIndex++]=A>>n*8&255}function O(t,A){t[t.currentIndex++]=A&255,t[t.currentIndex++]=A>>8}function tA(t,A){ZA(t,A,4)}function Ke(t,A){let e=A<<8|t;return e>32767?e-65536:e}function xo(t){return t>127?t-256:t}var us=class{header;size;chunkData;constructor(A,e,n){this.header=A,this.size=e,this.chunkData=n}};function AA(t,A=!0,e=!1){let n=j(t,4),s=U(t,4);n===""&&(s=0);let r;return A&&(r=t.slice(t.currentIndex,t.currentIndex+s)),(A||e)&&(t.currentIndex+=s),s%2!==0&&t[t.currentIndex]===0&&t.currentIndex++,new us(n,s,r)}function J(t,A,e=!1,n=!1){let s=8,r=t,i=A.length;e&&i++;let a=i;n&&(s+=4,a+=4,r="LIST");let o=s+i;o%2!==0&&o++;let I=new T(o);return mA(I,r),tA(I,a),n&&mA(I,t),I.set(A,s),I}function FA(t,A,e=!1){let n=8,s=t,r=A.reduce((I,l)=>l.length+I,0),i=r;e&&(n+=4,i+=4,s="LIST");let a=n+r;a%2!==0&&a++;let o=new T(a);return mA(o,s),tA(o,i),e&&mA(o,t),A.forEach(I=>{o.set(I,n),n+=I.length}),o}function _A(t,A){return t.find(e=>e.header!=="LIST"?!1:(e.chunkData.currentIndex=0,j(e.chunkData,4)===A))}function No(){let t=De;for(let i of this.instruments)t+=i.globalZone.generators.length*De,t+=i.instrumentZones.reduce((a,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==g.sampleID&&I.generatorType!==g.keyRange&&I.generatorType!==g.velRange),o.hasVelRange&&o.prependGenerator(new Y(g.velRange,o.velRange.max<<8|Math.max(o.velRange.min,0),!1)),o.hasKeyRange&&o.prependGenerator(new Y(g.keyRange,o.keyRange.max<<8|Math.max(o.keyRange.min,0),!1)),o.addGenerators(new Y(g.sampleID,this.samples.indexOf(o.sample),!1)),o.generators.length*De+a),0);let A=new T(t),e=i=>{for(let a of i.generators)O(A,a.generatorType),O(A,a.generatorValue)};for(let i of this.instruments){e(i.globalZone);for(let a of i.instrumentZones)e(a)}tA(A,0);let n=new T(De);tA(n,0);let s=J("igen",A),r=J("igen",n);return{pdta:s,xdta:r,highestIndex:0}}var ms=20;async function bo(t,A,e,n,s,r){let i=0,a=0,o=[];for(let E of this.samples){e&&await E.compressSample(s),n&&E.setAudioData(E.getAudioData());let C=E.getRawData(!0);i++,r?.(E.sampleName,i,this.samples.length),y(`%cEncoded sample %c${i}. ${E.sampleName}%c of %c${this.samples.length}%c. Compressed: %c${E.isCompressed}%c.`,c.info,c.recognized,c.info,c.recognized,c.info,E.isCompressed?c.recognized:c.unrecognized,c.info),a+=C.length+(E.isCompressed?0:92),o.push(C)}a%2!==0&&a++;let I=new T(a+ms);mA(I,"LIST"),ZA(I,a+ms-8,4),mA(I,"sdta"),mA(I,"smpl"),ZA(I,a,4);let l=0;return this.samples.forEach((E,C)=>{let B=o[C];I.set(B,l+ms);let f,u;E.isCompressed?(f=l,u=f+B.length):(f=l/2,u=f+B.length/2,l+=92),l+=B.length,t.push(f),A.push(u)}),I}var Oi=48e3,vA={monoSample:1,rightSample:2,leftSample:4,linkedSample:8,romMonoSample:32769,romRightSample:32770,romLeftSample:32772,romLinkedSample:32776},ke=class{sampleName;sampleRate;samplePitch;samplePitchCorrection;linkedSample;sampleType;sampleLoopStartIndex;sampleLoopEndIndex;isCompressed=!1;compressedData=void 0;linkedInstruments=[];sampleData=void 0;dataOverriden=!0;constructor(A,e,n,s,r,i,a){this.sampleName=A,this.sampleRate=e,this.samplePitch=n,this.samplePitchCorrection=s,this.sampleLoopStartIndex=i,this.sampleLoopEndIndex=a,this.sampleType=r}get isLinked(){return this.sampleType===vA.rightSample||this.sampleType===vA.leftSample||this.sampleType===vA.linkedSample}get useCount(){return this.linkedInstruments.length}getRawData(A){return this.isCompressed&&A&&!this.dataOverriden?this.compressedData:this.encodeS16LE()}resampleData(A){let e=this.getAudioData(),n=A/this.sampleRate,s=new Float32Array(Math.floor(e.length*n));for(let r=0;r<s.length;r++)s[r]=e[Math.floor(r*(1/n))];e=s,this.sampleRate=A,this.sampleLoopStartIndex=Math.floor(this.sampleLoopStartIndex*n),this.sampleLoopEndIndex=Math.floor(this.sampleLoopEndIndex*n),this.sampleData=e}async compressSample(A){if(!this.isCompressed)try{let e=this.getAudioData();(this.sampleRate<8e3||this.sampleRate>96e3)&&(this.resampleData(Oi),e=this.getAudioData());let n=await A(e,this.sampleRate);this.setCompressedData(n)}catch(e){H(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`,e),delete this.compressedData,this.isCompressed=!1}}setSampleType(A){if(this.sampleType=A,this.isLinked||(this.linkedSample&&(this.linkedSample.linkedSample=void 0,this.linkedSample.sampleType=A),this.linkedSample=void 0),(A&32768)>0)throw new Error("ROM samples are not supported.")}deleteSample(){if(this.useCount>0)throw new Error(`Cannot delete sample used by: ${this.linkedInstruments.map(A=>A.instrumentName)}.`);this.unlinkSample()}unlinkSample(){this.setSampleType(vA.monoSample)}setLinkedSample(A,e){if(A.linkedSample)throw new Error(`${A.sampleName} is linked tp ${A.linkedSample.sampleName}. Unlink it first.`);if(this.linkedSample=A,A.linkedSample=this,e===vA.leftSample)this.setSampleType(vA.leftSample),A.setSampleType(vA.rightSample);else if(e===vA.rightSample)this.setSampleType(vA.rightSample),A.setSampleType(vA.leftSample);else if(e===vA.linkedSample)this.setSampleType(vA.linkedSample),A.setSampleType(vA.linkedSample);else throw new Error("Invalid sample type: "+e)}linkTo(A){this.linkedInstruments.push(A)}unlinkFrom(A){let e=this.linkedInstruments.indexOf(A);if(e<0){H(`Cannot unlink ${A.instrumentName} from ${this.sampleName}: not linked.`);return}this.linkedInstruments.splice(e,1)}decodeVorbis(){if(this.sampleData)return this.sampleData;try{let e=ce.decode(this.compressedData).data[0];if(e===void 0)return H(`Error decoding sample ${this.sampleName}: Vorbis decode returned undefined.`),new Float32Array(0);for(let n=0;n<e.length;n++)e[n]=Math.max(-1,Math.min(e[n],.999969482421875));return e}catch(A){return H(`Error decoding sample ${this.sampleName}: ${A}`),new Float32Array(this.sampleLoopEndIndex+1)}}getAudioData(){if(this.sampleData)return this.sampleData;if(this.isCompressed)return this.sampleData=this.decodeVorbis(),this.sampleData;throw new Error("Sample data is undefined for a BasicSample instance.")}encodeS16LE(){let A=this.getAudioData(),e=new Int16Array(A.length),n=A.length;for(let s=0;s<n;s++){let r=A[s]*32768;r>32767?r=32767:r<-32768&&(r=-32768),e[s]=r}return new T(e.buffer)}setAudioData(A){this.isCompressed=!1,delete this.compressedData,this.sampleData=A,this.dataOverriden=!0}setCompressedData(A){this.sampleData=void 0,this.compressedData=A,this.isCompressed=!0,this.dataOverriden=!1}};var fn=16,ps=class extends ke{linkedSampleIndex;s16leData;constructor(A,e,n,s,r,i,a,o,I,l,E,C){let B=(l&fn)>0;l&=~fn,super(A,i,a,o,l,s-e/2,r-e/2),this.dataOverriden=!1,this.isCompressed=B,this.sampleName=A,this.startByteOffset=e,this.endByteOffset=n,this.sampleID=C;let f=E.currentIndex;this.isCompressed?(this.sampleLoopStartIndex+=this.startByteOffset/2,this.sampleLoopEndIndex+=this.startByteOffset/2,this.compressedData=E.slice(this.startByteOffset/2+f,this.endByteOffset/2+f)):E instanceof Float32Array?(this.sampleData=E.slice(this.startByteOffset/2,this.endByteOffset/2),this.dataOverriden=!0):this.s16leData=E.slice(f+this.startByteOffset,f+this.endByteOffset),this.linkedSampleIndex=I}getLinkedSample(A){if(this.linkedSample||!this.isLinked)return;let e=A[this.linkedSampleIndex];e?e.linkedSample?(y(`%cInvalid linked sample for ${this.sampleName}: Already linked to ${e.linkedSample.sampleName}`,c.warn),this.unlinkSample()):this.setLinkedSample(e,this.sampleType):(y(`%cInvalid linked sample for ${this.sampleName}. Setting to mono.`,c.warn),this.unlinkSample())}setAudioData(A){super.setAudioData(A)}getAudioData(){if(this.sampleData)return this.sampleData;if(this.isCompressed)return super.getAudioData();let A=this.endByteOffset-this.startByteOffset;if(A<1)return H(`Invalid sample ${this.sampleName}! Invalid length: ${A}`),new Float32Array(1);let e=new Float32Array(A/2),n=new Int16Array(this.s16leData.buffer);for(let s=0;s<n.length;s++)e[s]=n[s]/32768;return this.sampleData=e,e}getRawData(A){return this.dataOverriden||this.compressedData?super.getRawData(A):this.s16leData}};function ys(t,A,e=!0){let n=[],s=0;for(;t.chunkData.length>t.chunkData.currentIndex;){let r=Yi(s,t.chunkData,A);n.push(r),s++}return n.pop(),e&&n.forEach(r=>r.getLinkedSample(n)),n}function Yi(t,A,e){let n=j(A,20),s=U(A,4)*2,r=U(A,4)*2,i=U(A,4),a=U(A,4),o=U(A,4),I=A[A.currentIndex++];I>127&&(I=60);let l=xo(A[A.currentIndex++]),E=U(A,2),C=U(A,2);return new ps(n,s,r,i,a,o,I,l,E,C,e,t)}function Lo(t,A){let n=46*(this.samples.length+1),s=new T(n),r=new T(n),i=0;this.samples.forEach((I,l)=>{mA(s,I.sampleName.substring(0,20),20),mA(r,I.sampleName.substring(20),20);let E=t[l];tA(s,E),r.currentIndex+=4;let C=A[l];tA(s,C),r.currentIndex+=4;let B=I.sampleLoopStartIndex+E,f=I.sampleLoopEndIndex+E;I.isCompressed&&(B-=E,f-=E),tA(s,B),tA(s,f),tA(s,I.sampleRate),s[s.currentIndex++]=I.samplePitch,s[s.currentIndex++]=I.samplePitchCorrection,r.currentIndex+=14;let u=this.samples.indexOf(I.linkedSample);O(s,Math.max(0,u)&65535),O(r,Math.max(0,u)>>16),i=Math.max(i,u);let S=I.sampleType;I.isCompressed&&(S|=fn),O(s,S),r.currentIndex+=2}),mA(s,"EOS",46),mA(r,"EOS",46);let a=J("shdr",s),o=J("shdr",r);return{pdta:a,xdta:o,highestIndex:i}}function To(){let t=TA;for(let i of this.instruments)t+=i.globalZone.modulators.length*TA,t+=i.instrumentZones.reduce((a,o)=>o.modulators.length*TA+a,0);let A=new T(t),e=i=>{for(let a of i.modulators)O(A,a.getSourceEnum()),O(A,a.modulatorDestination),O(A,a.transformAmount),O(A,a.getSecSrcEnum()),O(A,a.transformType)};for(let i of this.instruments){e(i.globalZone);for(let a of i.instrumentZones)e(a)}ZA(A,0,TA);let n=new T(TA);ZA(n,0,TA);let s=J("imod",A),r=J("imod",n);return{pdta:s,xdta:r,highestIndex:0}}var Uo=4;function vo(){let t=this.instruments.reduce((o,I)=>(I.instrumentZones.length+1)*Uo+o,Uo),A=new T(t),e=new T(t),n=0,s=0,r=o=>{O(A,n&65535),O(A,s&65535),O(e,n>>16),O(e,s>>16),n+=o.generators.length,s+=o.modulators.length};for(let o of this.instruments){r(o.globalZone);for(let I of o.instrumentZones)r(I)}O(A,n&65535),O(A,s&65535),O(e,n>>16),O(e,s>>16);let i=J("ibag",A),a=J("ibag",e);return{pdta:i,xdta:a,highestIndex:Math.max(n,s)}}var Ho=22;function Oo(){let t=this.instruments.length*Ho+Ho,A=new T(t),e=new T(t),n=0;for(let i of this.instruments)mA(A,i.instrumentName.substring(0,20),20),mA(e,i.instrumentName.substring(20),20),O(A,n&65535),O(e,n>>16),n+=i.instrumentZones.length+1;mA(A,"EOI",20),mA(e,"EOI",20),O(A,n&65535),O(e,n>>16);let s=J("inst",A),r=J("inst",e);return{pdta:s,xdta:r,highestIndex:n}}function Yo(){let t=De;for(let i of this.presets)t+=i.globalZone.generators.length*De,t+=i.presetZones.reduce((a,o)=>(o.generators=o.generators.filter(I=>I.generatorType!==g.instrument&&I.generatorType!==g.keyRange&&I.generatorType!==g.velRange),o.hasVelRange&&o.prependGenerator(new Y(g.velRange,o.velRange.max<<8|Math.max(o.velRange.min,0),!1)),o.hasKeyRange&&o.prependGenerator(new Y(g.keyRange,o.keyRange.max<<8|Math.max(o.keyRange.min,0),!1)),o.addGenerators(new Y(g.instrument,this.instruments.indexOf(o.instrument),!1)),o.generators.length*De+a),0);let A=new T(t),e=i=>{for(let a of i.generators)O(A,a.generatorType),O(A,a.generatorValue)};for(let i of this.presets){e(i.globalZone);for(let a of i.presetZones)e(a)}tA(A,0);let n=new T(De);tA(n,0);let s=J("pgen",A),r=J("pgen",n);return{pdta:s,xdta:r,highestIndex:0}}function Po(){let t=TA;for(let i of this.presets)t+=i.globalZone.modulators.length*TA,t+=i.presetZones.reduce((a,o)=>o.modulators.length*TA+a,0);let A=new T(t),e=i=>{for(let a of i.modulators)O(A,a.getSourceEnum()),O(A,a.modulatorDestination),O(A,a.transformAmount),O(A,a.getSecSrcEnum()),O(A,a.transformType)};for(let i of this.presets){e(i.globalZone);for(let a of i.presetZones)e(a)}ZA(A,0,TA);let n=new T(TA);ZA(n,0,TA);let s=J("pmod",A),r=J("pmod",n);return{pdta:s,xdta:r,highestIndex:0}}var Jo=4;function Ko(){let t=this.presets.reduce((o,I)=>(I.presetZones.length+1)*Jo+o,Jo),A=new T(t),e=new T(t),n=0,s=0,r=o=>{O(A,n&65535),O(A,s&65535),O(e,n>>16),O(e,s>>16),n+=o.generators.length,s+=o.modulators.length};for(let o of this.presets){r(o.globalZone);for(let I of o.presetZones)r(I)}O(A,n),O(A,s),O(e,n),O(e,s);let i=J("pbag",A),a=J("pbag",e);return{pdta:i,xdta:a,highestIndex:Math.max(n,s)}}var qo=38;function Vo(){let t=this.presets.length*qo+qo,A=new T(t),e=new T(t),n=0;for(let i of this.presets)mA(A,i.presetName.substring(0,20),20),mA(e,i.presetName.substring(20),20),O(A,i.program),O(A,i.bank),O(A,n&65535),e.currentIndex+=4,O(e,n>>16),tA(A,i.library),tA(A,i.genre),tA(A,i.morphology),e.currentIndex+=12,n+=i.presetZones.length+1;mA(A,"EOP",20),A.currentIndex+=4,O(A,n&65535),A.currentIndex+=12,mA(e,"EOP",20),e.currentIndex+=4,O(e,n>>16),e.currentIndex+=12;let s=J("phdr",A),r=J("phdr",e);return{pdta:s,xdta:r,highestIndex:n}}function mt(t,A){t===void 0&&(t={});for(let e in A)A.hasOwnProperty(e)&&!(e in t)&&(t[e]=A[e]);return t}var Zo={compress:!1,compressionQuality:.5,compressionFunction:void 0,progressFunction:void 0,writeDefaultModulators:!0,writeExtendedLimits:!0,decompress:!1};async function Xo(t=Zo){if(t=mt(t,Zo),t?.compress){if(typeof t?.compressionFunction!="function")throw new Error("No compression function supplied but compression enabled.");if(t?.decompress)throw new Error("Decompressed and compressed at the same time.")}dA("%cSaving soundfont...",c.info),y(`%cCompression: %c${t?.compress||"false"}%c quality: %c${t?.compressionQuality||"none"}`,c.info,c.recognized,c.info,c.recognized),y("%cWriting INFO...",c.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",(t?.compress||this.samples.some(G=>G.isCompressed))&&(this.soundFontInfo.ifil="3.0"),t?.decompress&&(this.soundFontInfo.ifil="2.4"),t?.writeDefaultModulators?(this.soundFontInfo.DMOD=`${this.defaultModulators.length} Modulators`,this.customDefaultModulators=!0):delete this.soundFontInfo.DMOD;for(let[G,N]of Object.entries(this.soundFontInfo))if(G==="ifil"||G==="iver"){let h=parseInt(N.split(".")[0]),eA=parseInt(N.split(".")[1]),P=new T(4);O(P,h),O(P,eA),A.push(J(G,P))}else if(G==="DMOD"){let h=this.defaultModulators;y(`%cWriting %c${h.length}%c default modulators...`,c.info,c.recognized,c.info);let eA=TA+h.length*TA,P=new T(eA);for(let v of h)O(P,v.getSourceEnum()),O(P,v.modulatorDestination),O(P,v.transformAmount),O(P,v.getSecSrcEnum()),O(P,v.transformType);ZA(P,0,TA),A.push(J(G,P))}else A.push(J(G,OA(N,!0,!0)));y("%cWriting SDTA...",c.info);let e=[],n=[],s=await bo.call(this,e,n,t.compress,t.decompress,t?.compressionFunction,t?.progressFunction);y("%cWriting PDTA...",c.info),y("%cWriting SHDR...",c.info);let r=Lo.call(this,e,n);y("%cWriting IGEN...",c.info);let i=No.call(this);y("%cWriting IMOD...",c.info);let a=To.call(this);y("%cWriting IBAG...",c.info);let o=vo.call(this);y("%cWriting INST...",c.info);let I=Oo.call(this);y("%cWriting PGEN...",c.info);let l=Yo.call(this);y("%cWriting PMOD...",c.info);let E=Po.call(this);y("%cWriting PBAG...",c.info);let C=Ko.call(this);y("%cWriting PHDR...",c.info);let f=[Vo.call(this),C,E,l,I,o,a,i,r],u=FA("pdta",f.map(G=>G.pdta),!0),S=Math.max(...f.map(G=>G.highestIndex));if(t.writeExtendedLimits&&(S>65535||this.presets.some(G=>G.presetName.length>20)||this.instruments.some(G=>G.instrumentName.length>20)||this.samples.some(G=>G.sampleName.length>20))){y(`%cWriting the xdta chunk! Max index: %c${S}`,c.info,c.value);let G=FA("xdta",f.map(N=>N.xdta),!0);A.push(G)}let F=FA("INFO",A,!0);y("%cWriting the output file...",c.info);let k=FA("RIFF",[OA("sfbk"),F,s,u]);return y(`%cSaved succesfully! Final file size: %c${k.length}`,c.info,c.recognized),q(),k}var Ne=class{velRange={min:-1,max:127};keyRange={min:-1,max:127};generators=[];modulators=[];get hasKeyRange(){return this.keyRange.min!==-1}get hasVelRange(){return this.velRange.min!==-1}prependGenerator(A){this.generators.unshift(A)}setGenerator(A,e){switch(A){case g.sampleID:throw new Error("Use setSample()");case g.instrument:throw new Error("Use setInstrument()");case g.velRange:case g.keyRange:throw new Error("Set the range manually")}let n=this.generators.find(s=>s.generatorType===A);n?n.generatorValue=e:this.addGenerators(new Y(A,e))}addGenerators(...A){A.forEach(e=>{switch(e.generatorType){default:this.generators.push(e);break;case g.velRange:this.velRange.min=e.generatorValue&127,this.velRange.max=e.generatorValue>>8&127;break;case g.keyRange:this.keyRange.min=e.generatorValue&127,this.keyRange.max=e.generatorValue>>8&127}})}addModulators(...A){this.modulators.push(...A)}getGeneratorValue(A,e){return this.generators.find(n=>n.generatorType===A)?.generatorValue??e}copyFrom(A){this.generators=[...A.generators],this.modulators=A.modulators.map(e=>EA.copy(e)),this.velRange={...A.velRange},this.keyRange={...A.keyRange}}};var be=class extends Ne{};var Le=class extends Ne{parentInstrument;sample;useCount;constructor(A){super(),this.parentInstrument=A,this.useCount=A.useCount}setSample(A){this.sample=A,A.linkTo(this.parentInstrument)}deleteZone(){this.sample.unlinkFrom(this.parentInstrument)}};var Ce=class{instrumentName="";instrumentZones=[];globalZone=new be;linkedPresets=[];get useCount(){return this.linkedPresets.length}createZone(){let A=new Le(this);return this.instrumentZones.push(A),A}linkTo(A){this.linkedPresets.push(A),this.instrumentZones.forEach(e=>e.useCount++)}unlinkFrom(A){let e=this.linkedPresets.indexOf(A);if(e<0){H(`Cannot unlink ${A.presetName} from ${this.instrumentName}: not linked.`);return}this.linkedPresets.splice(e,1),this.instrumentZones.forEach(n=>n.useCount--)}deleteUnusedZones(){this.instrumentZones=this.instrumentZones.filter(A=>{let e=A.useCount>0;return e||A.deleteZone(),e})}deleteInstrument(){if(this.useCount>0)throw new Error(`Cannot delete an instrument that is used by: ${this.linkedPresets.map(A=>A.presetName)}.`);this.instrumentZones.forEach(A=>A.deleteZone())}deleteZone(A,e=!1){let n=this.instrumentZones[A];return n.useCount-=1,n.useCount<1||e?(n.deleteZone(),this.instrumentZones.splice(A,1),!0):!1}};var Pi=new Set([g.velRange,g.keyRange,g.instrument,g.exclusiveClass,g.endOper,g.sampleModes,g.startloopAddrsOffset,g.startloopAddrsCoarseOffset,g.endloopAddrsOffset,g.endloopAddrsCoarseOffset,g.startAddrsOffset,g.startAddrsCoarseOffset,g.endAddrOffset,g.endAddrsCoarseOffset,g.initialAttenuation,g.fineTune,g.coarseTune,g.keyNumToVolEnvHold,g.keyNumToVolEnvDecay,g.keyNumToModEnvHold,g.keyNumToModEnvDecay]);function Wo(t,A=!0){function e(C,B){C.push(...B.filter(f=>!C.find(u=>u.generatorType===f.generatorType)))}function n(C,B){return{min:Math.max(C.min,B.min),max:Math.min(C.max,B.max)}}function s(C,B){C.push(...B.filter(f=>!C.find(u=>EA.isIdentical(f,u))))}let r=new Ce,i=[],a=[],o=t.globalZone;i.push(...o.generators),a.push(...o.modulators);let I=o.keyRange,l=o.velRange;for(let C of t.presetZones){let B=C.keyRange;C.hasKeyRange||(B=I);let f=C.velRange;C.hasVelRange||(f=l);let u=C.generators.map(P=>new Y(P.generatorType,P.generatorValue));e(u,i);let S=[...C.modulators];s(S,a);let M=C.instrument,F=M.instrumentZones,k=[],G=[],N=M.globalZone;k.push(...N.generators),G.push(...N.modulators);let h=N.keyRange,eA=N.velRange;for(let P of F){let v=P.keyRange;P.hasKeyRange||(v=h);let sA=P.velRange;if(P.hasVelRange||(sA=eA),v=n(v,B),sA=n(sA,f),v.max<v.min||sA.max<sA.min)continue;let rA=P.generators.map(X=>new Y(X.generatorType,X.generatorValue));e(rA,k);let $=[...P.modulators];s($,G);let IA=[...$];for(let X of S){let L=IA.findIndex(D=>EA.isIdentical(X,D));L!==-1?IA[L]=IA[L].sumTransform(X):IA.push(X)}let uA=rA.map(X=>new Y(X.generatorType,X.generatorValue));for(let X of u){if(X.generatorType===g.velRange||X.generatorType===g.keyRange||X.generatorType===g.instrument||X.generatorType===g.endOper||X.generatorType===g.sampleModes)continue;let L=rA.findIndex(D=>D.generatorType===X.generatorType);if(L!==-1){let D=uA[L].generatorValue+X.generatorValue;uA[L]=new Y(X.generatorType,D)}else{let D=V[X.generatorType].def+X.generatorValue;uA.push(new Y(X.generatorType,D))}}uA=uA.filter(X=>X.generatorType!==g.sampleID&&X.generatorType!==g.keyRange&&X.generatorType!==g.velRange&&X.generatorType!==g.endOper&&X.generatorType!==g.instrument&&X.generatorValue!==V[X.generatorType].def);let CA=r.createZone();CA.keyRange=v,CA.velRange=sA,CA.keyRange.min===0&&CA.keyRange.max===127&&(CA.keyRange.min=-1),CA.velRange.min===0&&CA.velRange.max===127&&(CA.velRange.min=-1),CA.setSample(P.sample),CA.addGenerators(...uA),CA.addModulators(...IA)}}let E=r.globalZone;if(A){for(let f=0;f<58;f++){if(Pi.has(f))continue;let u={},S=V[f]?.def||0;u[S]=0;for(let M of r.instrumentZones){let F=M.generators.find(N=>N.generatorType===f);if(F){let N=F.generatorValue;u[N]===void 0?u[N]=1:u[N]++}else u[S]++;let k;switch(f){default:continue;case g.decayVolEnv:k=g.keyNumToVolEnvDecay;break;case g.holdVolEnv:k=g.keyNumToVolEnvHold;break;case g.decayModEnv:k=g.keyNumToModEnvDecay;break;case g.holdModEnv:k=g.keyNumToModEnvHold}if(M.generators.find(N=>N.generatorType===k)!==void 0){u={};break}}if(Object.keys(u).length>0){let M=Object.entries(u).reduce((k,G)=>k[1]<G[1]?G:k,[0,0]),F=parseInt(M[0]);F!==S&&E.addGenerators(new Y(f,F)),r.instrumentZones.forEach(k=>{let G=k.generators.findIndex(N=>N.generatorType===f);G!==-1?k.generators[G].generatorValue===F&&k.generators.splice(G,1):F!==S&&k.addGenerators(new Y(f,S))})}}let B=r.instrumentZones[0].modulators.map(f=>EA.copy(f));for(let f of B){let u=!0;for(let S of r.instrumentZones){if(!u)continue;S.modulators.find(F=>EA.isIdentical(F,f))||(u=!1)}if(u===!0){E.addModulators(EA.copy(f));for(let S of r.instrumentZones){let M=S.modulators.find(F=>EA.isIdentical(F,f));M.transformAmount===f.transformAmount&&S.modulators.splice(S.modulators.indexOf(M),1)}}}}return r}var _o=20;function un(t,A,e,n,s,r,i){let a=i===0?0:1,o=new T(_o+a*16);tA(o,_o),O(o,A),O(o,e);let I=n*.4,l=Math.floor(I*-65536);tA(o,l),tA(o,2);let E=r-s,C=0;switch(i){default:case 0:a=0;break;case 1:C=0,a=1;break;case 3:C=1,a=1}return tA(o,a),a===1&&(tA(o,16),tA(o,C),tA(o,s),tA(o,E)),J("wsmp",o)}var Z={none:0,modLfo:1,velocity:2,keyNum:3,volEnv:4,modEnv:5,pitchWheel:6,polyPressure:7,channelPressure:8,vibratoLfo:9,modulationWheel:129,volume:135,pan:138,expression:139,chorus:221,reverb:219,pitchWheelRange:256,fineTune:257,coarseTune:258},mn=new pA(219,0,g.reverbEffectsSend,1e3,0),pn=new pA(221,0,g.chorusEffectsSend,1e3,0),yn=new pA(129,0,g.vibLfoToPitch,0,0),Sn=new pA(13,0,g.vibLfoToPitch,0,0);var x={none:0,gain:1,reserved:2,pitch:3,pan:4,keyNum:5,chorusSend:128,reverbSend:129,modLfoFreq:260,modLfoDelay:261,vibLfoFreq:276,vibLfoDelay:277,volEnvAttack:518,volEnvDecay:519,volEnvRelease:521,volEnvSustain:522,volEnvDelay:523,volEnvHold:524,modEnvAttack:778,modEnvDecay:779,modEnvRelease:781,modEnvSustain:782,modEnvDelay:783,modEnvHold:784,filterCutoff:1280,filterQ:1281};var qt=class{source;control;destination;scale;transform;constructor(A,e,n,s,r){this.source=A,this.control=e,this.destination=n,this.scale=s,this.transform=r}writeArticulator(){let A=new T(12);return O(A,this.source),O(A,this.control),O(A,this.destination),O(A,this.transform),tA(A,this.scale<<16),A}};function zo(t,A){if(t)switch(A){default:return;case p.modulationWheel:return Z.modulationWheel;case p.mainVolume:return Z.volume;case p.pan:return Z.pan;case p.expressionController:return Z.expression;case p.chorusDepth:return Z.chorus;case p.reverbDepth:return Z.reverb}else switch(A){default:return;case W.noteOnKeyNum:return Z.keyNum;case W.noteOnVelocity:return Z.velocity;case W.noController:return Z.none;case W.polyPressure:return Z.polyPressure;case W.channelPressure:return Z.channelPressure;case W.pitchWheel:return Z.pitchWheel;case W.pitchWheelRange:return Z.pitchWheelRange}}function jo(t,A){switch(t){default:return;case g.initialAttenuation:return{dest:x.gain,amount:-A};case g.fineTune:return x.pitch;case g.pan:return x.pan;case g.keyNum:return x.keyNum;case g.reverbEffectsSend:return x.reverbSend;case g.chorusEffectsSend:return x.chorusSend;case g.freqModLFO:return x.modLfoFreq;case g.delayModLFO:return x.modLfoDelay;case g.delayVibLFO:return x.vibLfoDelay;case g.freqVibLFO:return x.vibLfoFreq;case g.delayVolEnv:return x.volEnvDelay;case g.attackVolEnv:return x.volEnvAttack;case g.holdVolEnv:return x.volEnvHold;case g.decayVolEnv:return x.volEnvDecay;case g.sustainVolEnv:return{dest:x.volEnvSustain,amount:1e3-A};case g.releaseVolEnv:return x.volEnvRelease;case g.delayModEnv:return x.modEnvDelay;case g.attackModEnv:return x.modEnvAttack;case g.holdModEnv:return x.modEnvHold;case g.decayModEnv:return x.modEnvDecay;case g.sustainModEnv:return{dest:x.modEnvSustain,amount:1e3-A};case g.releaseModEnv:return x.modEnvRelease;case g.initialFilterFc:return x.filterCutoff;case g.initialFilterQ:return x.filterQ}}function $o(t,A){switch(t){default:return;case g.modEnvToFilterFc:return{source:Z.modEnv,dest:x.filterCutoff,amt:A,isBipolar:!1};case g.modEnvToPitch:return{source:Z.modEnv,dest:x.pitch,amt:A,isBipolar:!1};case g.modLfoToFilterFc:return{source:Z.modLfo,dest:x.filterCutoff,amt:A,isBipolar:!0};case g.modLfoToVolume:return{source:Z.modLfo,dest:x.gain,amt:A,isBipolar:!0};case g.modLfoToPitch:return{source:Z.modLfo,dest:x.pitch,amt:A,isBipolar:!0};case g.vibLfoToPitch:return{source:Z.vibratoLfo,dest:x.pitch,amt:A,isBipolar:!0};case g.keyNumToVolEnvHold:return{source:Z.keyNum,dest:x.volEnvHold,amt:A,isBipolar:!0};case g.keyNumToVolEnvDecay:return{source:Z.keyNum,dest:x.volEnvDecay,amt:A,isBipolar:!0};case g.keyNumToModEnvHold:return{source:Z.keyNum,dest:x.modEnvHold,amt:A,isBipolar:!0};case g.keyNumToModEnvDecay:return{source:Z.keyNum,dest:x.modEnvDecay,amt:A,isBipolar:!0};case g.scaleTuning:return{source:Z.keyNum,dest:x.pitch,amt:A*128,isBipolar:!1}}}function Ar(t){let A=jo(t.generatorType,t.generatorValue),e=A,n=0,s=t.generatorValue;A?.amount!==void 0&&(s=A.amount,e=A.dest);let r=$o(t.generatorType,t.generatorValue);if(r!==void 0)s=r.amt,e=r.dest,n=r.source;else if(e===void 0){H(`Invalid generator type: ${t.generatorType}`);return}return new qt(n,0,e,s,0)}function er(t){if(t.transformType!==0){H("Other transform types are not supported.");return}let A=zo(t.sourceUsesCC,t.sourceIndex),e=t.sourceCurveType,n=t.sourcePolarity,s=t.sourceDirection;if(A===void 0){H(`Invalid source: ${t.sourceIndex}, CC: ${t.sourceUsesCC}`);return}t.modulatorDestination===g.initialAttenuation&&(s=s===1?0:1);let r=zo(t.secSrcUsesCC,t.secSrcIndex),i=t.secSrcCurveType,a=t.secSrcPolarity,o=t.secSrcDirection;if(r===void 0){H(`Invalid secondary source: ${t.secSrcIndex}, CC: ${t.secSrcUsesCC}`);return}let I=jo(t.modulatorDestination,t.transformAmount),l=I,E=t.transformAmount;I?.dest!==void 0&&(l=I.dest,E=I.amount);let C=$o(t.modulatorDestination,t.transformAmount);if(C!==void 0)E=C.amt,r=A,i=e,a=n,o=s,e=kA.linear,n=C.isBipolar?1:0,s=0,A=C.source,l=C.dest;else if(l===void 0){H(`Invalid destination: ${t.modulatorDestination}`);return}let B=0;return B|=i<<4,B|=a<<8,B|=o<<9,B|=e,B|=n<<14,B|=s<<15,new qt(A,r,l,E,B)}var Ji=new Set([g.sampleModes,g.initialAttenuation,g.keyRange,g.velRange,g.sampleID,g.fineTune,g.coarseTune,g.startAddrsOffset,g.startAddrsCoarseOffset,g.endAddrOffset,g.endAddrsCoarseOffset,g.startloopAddrsOffset,g.startloopAddrsCoarseOffset,g.endloopAddrsOffset,g.endloopAddrsCoarseOffset,g.overridingRootKey,g.exclusiveClass]);function Dn(t){for(let r=0;r<t.generators.length;r++){let i=t.generators[r];(i.generatorType===g.delayVolEnv||i.generatorType===g.attackVolEnv||i.generatorType===g.holdVolEnv||i.generatorType===g.decayVolEnv||i.generatorType===g.releaseVolEnv||i.generatorType===g.delayModEnv||i.generatorType===g.attackModEnv||i.generatorType===g.holdModEnv||i.generatorType===g.decayModEnv)&&(t.generators[r]=new Y(i.generatorType,Math.min(i.generatorValue,6386),!1))}for(let r=0;r<t.generators.length;r++){let i=t.generators[r],a;switch(i.generatorType){default:continue;case g.keyNumToVolEnvDecay:a=g.decayVolEnv;break;case g.keyNumToVolEnvHold:a=g.holdVolEnv;break;case g.keyNumToModEnvDecay:a=g.decayModEnv;break;case g.keyNumToModEnvHold:a=g.holdModEnv}let o=t.generators.find(f=>f.generatorType===a);if(o===void 0)continue;let I=i.generatorValue*-128,l=60/128*I,E=o.generatorValue-l,C=t.generators.indexOf(i),B=t.generators.indexOf(o);t.generators[B]=new Y(a,E,!1),t.generators[C]=new Y(i.generatorType,I,!1)}let A=t.generators.reduce((r,i)=>{if(Ji.has(i.generatorType))return r;let a=Ar(i);return a!==void 0?(r.push(a),y("%cSucceeded converting to DLS Articulator!",c.recognized)):H("Failed converting to DLS Articulator!"),r},[]),e=t.modulators.reduce((r,i)=>{if(EA.isIdentical(i,pn,!0)||EA.isIdentical(i,mn,!0)||EA.isIdentical(i,yn,!0)||EA.isIdentical(i,Sn,!0))return r;let a=er(i);return a!==void 0?(r.push(a),y("%cSucceeded converting to DLS Articulator!",c.recognized)):H("Failed converting to DLS Articulator!"),r},[]);A.push(...e);let n=new T(8);tA(n,8),tA(n,A.length);let s=A.map(r=>r.writeArticulator());return FA("art2",[n,...s])}function tr(t,A){let e=new T(12);O(e,Math.max(t.keyRange.min,0)),O(e,t.keyRange.max),O(e,Math.max(t.velRange.min,0)),O(e,t.velRange.max),O(e,0);let n=t.getGeneratorValue(g.exclusiveClass,0);O(e,n),O(e,0);let s=J("rgnh",e),r=t.getGeneratorValue(g.overridingRootKey,t.sample.samplePitch);t.getGeneratorValue(g.scaleTuning,A.getGeneratorValue(g.scaleTuning,100))===0&&t.keyRange.max-t.keyRange.min===0&&(r=t.keyRange.min);let a=un(t.sample,r,t.getGeneratorValue(g.fineTune,0)+t.getGeneratorValue(g.coarseTune,0)*100+t.sample.samplePitchCorrection,t.getGeneratorValue(g.initialAttenuation,0),t.sample.sampleLoopStartIndex+t.getGeneratorValue(g.startloopAddrsOffset,0)+t.getGeneratorValue(g.startloopAddrsCoarseOffset,0)*32768,t.sample.sampleLoopEndIndex+t.getGeneratorValue(g.endloopAddrsOffset,0)+t.getGeneratorValue(g.endloopAddrsCoarseOffset,0)*32768,t.getGeneratorValue(g.sampleModes,0)),o=new T(12);O(o,0),O(o,0),tA(o,1),tA(o,this.samples.indexOf(t.sample));let I=J("wlnk",o),l=new T(0);if(t.modulators.length+t.generators.length>0){let E=Dn(t);l=J("lar2",E,!1,!0)}return FA("rgn2",[s,a,I,l],!0)}function nr(t){dA(`%cWriting %c${t.presetName}%c...`,c.info,c.recognized,c.info);let A=Wo(t),e=A.globalZone,n=A.instrumentZones,s=new T(12);tA(s,n.length);let r=(t.bank&127)<<8;t.bank===128&&(r|=1<<31),tA(s,r),tA(s,t.program&127);let i=J("insh",s),a=Dn(e),o=J("lar2",a,!1,!0),I=FA("lrgn",n.reduce((C,B)=>(C.push(tr.apply(this,[B,e])),C),[]),!0),l=J("INAM",OA(t.presetName,!0)),E=J("INFO",l,!1,!0);return q(),FA("ins ",[i,I,o,E],!0)}function sr(){return FA("lins",this.presets.map(t=>nr.apply(this,[t])),!0)}function or(t){let A=new T(18);O(A,1),O(A,1),tA(A,t.sampleRate),tA(A,t.sampleRate*2),O(A,2),O(A,16);let e=J("fmt ",A),n=1;t.sampleLoopStartIndex+Math.abs(t.getAudioData().length-t.sampleLoopEndIndex)<2&&(n=0);let s=un(t,t.samplePitch,t.samplePitchCorrection,0,t.sampleLoopStartIndex,t.sampleLoopEndIndex,n),r=J("data",t.getRawData(!1)),i=J("INAM",OA(t.sampleName,!0)),a=J("INFO",i,!1,!0);return y(`%cSaved %c${t.sampleName}%c succesfully!`,c.recognized,c.value,c.recognized),FA("wave",[e,s,r,a],!0)}async function rr(t){let A=0,e=[],n=[],s=0;for(let r of this.samples){let i=or(r);await t?.(r.sampleName,s,this.samples.length),e.push(A),A+=i.length,n.push(i),s++}return{data:FA("wvpl",n,!0),indexes:e}}var ir={progressFunction:void 0};async function ar(t=ir){t=mt(t,ir),dA("%cSaving DLS...",c.info);let A=new T(4);tA(A,this.presets.length);let e=J("colh",A);dA("%cWriting instruments...",c.info);let n=sr.apply(this);y("%cSuccess!",c.recognized),q(),dA("%cWriting WAVE samples...",c.info);let s=await rr.call(this,t.progressFunction),r=s.data,i=s.indexes;y("%cSucceeded!",c.recognized),q();let a=new T(8+4*i.length);tA(a,8),tA(a,i.length);for(let E of i)tA(a,E);let o=J("ptbl",a);this.soundFontInfo.ICMT=(this.soundFontInfo.ICMT||"Soundfont")+`
11
11
  Converted from SF2 to DLS using SpessaSynth`,this.soundFontInfo.ISFT="SpessaSynth";let I=[];for(let[E,C]of Object.entries(this.soundFontInfo))E!=="ICMT"&&E!=="INAM"&&E!=="ICRD"&&E!=="IENG"&&E!=="ICOP"&&E!=="ISFT"&&E!=="ISBJ"||I.push(J(E,OA(C,!0)));let l=FA("INFO",I,!0);return y("%cSaved succesfully!",c.recognized),q(),FA("RIFF",[OA("DLS "),e,n,o,r,l])}var tt=class extends Ne{parentPreset;instrument;constructor(A){super(),this.parentPreset=A}deleteZone(){this.instrument.unlinkFrom(this.parentPreset)}setInstrument(A){this.instrument=A,this.instrument.linkTo(this.parentPreset)}};var he=class{parentSoundBank;presetName="";program=0;bank=0;presetZones=[];globalZone=new be;library=0;genre=0;morphology=0;constructor(A){this.parentSoundBank=A}isDrumPreset(A,e=!1){let n=A&&this.parentSoundBank.isXGBank;return this.bank===128||n&&te(this.bank)&&(this.bank!==126||e)}deletePreset(){this.presetZones.forEach(A=>A.deleteZone())}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}createZone(){let A=new tt(this);return this.presetZones.push(A),A}preload(A,e){for(let n=A;n<e+1;n++)for(let s=0;s<128;s++)this.getSamplesAndGenerators(n,s).forEach(r=>{r.sample.getAudioData()})}getSamplesAndGenerators(A,e){if(this.presetZones.length<1)return[];function n(C,B){return B>=C.min&&B<=C.max}function s(C,B){C.push(...B.filter(f=>!C.find(u=>u.generatorType===f.generatorType)))}function r(C,B){C.push(...B.filter(f=>!C.find(u=>EA.isIdentical(f,u))))}let i=[],a=[...this.globalZone.generators],o=[...this.globalZone.modulators],I=this.globalZone.keyRange,l=this.globalZone.velRange;return this.presetZones.filter(C=>n(C.hasKeyRange?C.keyRange:I,A)&&n(C.hasVelRange?C.velRange:l,e)).forEach(C=>{let B=C.instrument;if(B.instrumentZones.length<1)return;let f=C.generators,u=C.modulators,S=[...B.globalZone.generators],M=[...B.globalZone.modulators],F=B.globalZone.keyRange,k=B.globalZone.velRange;B.instrumentZones.filter(N=>n(N.hasKeyRange?N.keyRange:F,A)&&n(N.hasVelRange?N.velRange:k,e)).forEach(N=>{let h=[...N.generators],eA=[...N.modulators];s(f,a),s(h,S),r(u,o),r(eA,M),r(eA,this.parentSoundBank.defaultModulators);let P=[...eA];for(let v=0;v<u.length;v++){let sA=u[v],rA=P.findIndex($=>EA.isIdentical(sA,$));rA!==-1?P[rA]=P[rA].sumTransform(sA):P.push(sA)}i.push({instrumentGenerators:h,presetGenerators:f,modulators:P,sample:N.sample})})}),i}};var Te=class t{static isSF3DecoderReady=ce.isInitialized;soundFontInfo={};presets=[];samples=[];instruments=[];defaultModulators=co.map(A=>EA.copy(A));customDefaultModulators=!1;isXGBank=!1;constructor(A=void 0){if(A?.presets){this.soundFontInfo=A.info,this.addPresets(...A.presets);let e=[];for(let s of A.presets)for(let r of s.presetZones)e.includes(r.instrument)||e.push(r.instrument);this.addInstruments(...e);let n=[];for(let s of e)for(let r of s.instrumentZones)n.includes(r.sample)||n.push(r.sample);this.addSamples(...n)}}static mergeSoundBanks(...A){let e=A.shift(),n=e.presets;for(;A.length;)A.shift().presets.forEach(r=>{n.find(i=>i.bank===r.bank&&i.program===r.program)===void 0&&n.push(r)});return new t({presets:n,info:e.soundFontInfo})}static async getDummySoundfontFile(){let A=new t,e=new ke("Saw",44100,65,20,vA.monoSample,0,127),n=new Float32Array(128);for(let E=0;E<128;E++)n[E]=E/128*2-1;e.setAudioData(n),A.addSamples(e);let s=new be;s.addGenerators(new Y(g.initialAttenuation,375),new Y(g.releaseVolEnv,-1e3),new Y(g.sampleModes,1));let r=new Ce;r.instrumentName="Saw Wave",r.globalZone=s,r.createZone().setSample(e);let a=r.createZone();a.setSample(e),a.addGenerators(new Y(g.fineTune,-9)),A.addInstruments(r);let o=new he(A);return o.presetName="Saw Wave",o.createZone().setInstrument(r),A.addPresets(o),A.soundFontInfo.ifil="2.1",A.soundFontInfo.isng="E-mu 10K2",A.soundFontInfo.INAM="Dummy",A.flush(),(await A.write()).buffer}addPresets(...A){this.presets.push(...A)}addInstruments(...A){this.instruments.push(...A)}addSamples(...A){this.samples.push(...A)}cloneSample(A){let e=this.samples.find(s=>s.sampleName===A.sampleName);if(e)return e;let n=new ke(A.sampleName,A.sampleRate,A.samplePitch,A.samplePitchCorrection,A.sampleType,A.sampleLoopStartIndex,A.sampleLoopEndIndex);if(A.isCompressed?n.setCompressedData(A.compressedData.slice()):n.setAudioData(A.getAudioData()),this.addSamples(n),A.linkedSample){let s=this.cloneSample(A.linkedSample);s.linkedSample||n.setLinkedSample(s,n.sampleType)}return n}cloneInstrument(A){let e=this.instruments.find(s=>s.instrumentName===A.instrumentName);if(e)return e;let n=new Ce;n.instrumentName=A.instrumentName,n.globalZone.copyFrom(A.globalZone);for(let s of A.instrumentZones){let r=n.createZone();r.copyFrom(s),r.setSample(this.cloneSample(s.sample))}return this.addInstruments(n),n}clonePreset(A){let e=this.presets.find(s=>s.presetName===A.presetName);if(e)return e;let n=new he(this);n.presetName=A.presetName,n.bank=A.bank,n.program=A.program,n.library=A.library,n.genre=A.genre,n.morphology=A.morphology,n.globalZone.copyFrom(A.globalZone);for(let s of A.presetZones){let r=n.createZone();r.copyFrom(s),r.setInstrument(this.cloneInstrument(s.instrument))}return this.addPresets(n),n}flush(){this.presets.sort((A,e)=>A.bank!==e.bank?A.bank-e.bank:A.program-e.program),this._parseInternal()}_parseInternal(){this.isXGBank=!1;let A=new Set([0,1,2,3,4,5,6,7,8,9,16,17,24,25,27,28,29,30,31,32,33,40,41,48,56,57,58,64,65,66,126,127]);for(let e of this.presets)if(te(e.bank)&&(this.isXGBank=!0,!A.has(e.program))){this.isXGBank=!1,y(`%cThis bank is not valid XG. Preset %c${e.bank}:${e.program}%c is not a valid XG drum. XG mode will use presets on bank 128.`,c.info,c.value,c.info);break}}trimSoundBank(A){let e=this;function n(r,i){let a=0;for(let o=0;o<r.instrumentZones.length;o++){let I=r.instrumentZones[o],l=I.keyRange,E=I.velRange,C=!1;for(let B of i)if(B.key>=l.min&&B.key<=l.max&&B.velocity>=E.min&&B.velocity<=E.max){C=!0;break}C||(y(`%c${I.sample.sampleName} %cremoved from %c${r.instrumentName}%c.`,c.recognized,c.info,c.recognized,c.info),r.deleteZone(o)&&(a++,o--,y(`%c${I.sample.sampleName} %cdeleted`,c.recognized,c.info)),I.sample.useCount<1&&e.deleteSample(I.sample))}return a}Ie("%cTrimming soundfont...",c.info);let s=A.getUsedProgramsAndKeys(e);dA("%cModifying soundfont...",c.info),y("Detected keys for midi:",s);for(let r=0;r<e.presets.length;r++){let i=e.presets[r],a=i.bank+":"+i.program,o=s[a];if(o===void 0)y(`%cDeleting preset %c${i.presetName}%c and its zones`,c.info,c.recognized,c.info),e.deletePreset(i),r--;else{let I=[...o].map(E=>{let C=E.split("-");return{key:parseInt(C[0]),velocity:parseInt(C[1])}});dA(`%cTrimming %c${i.presetName}`,c.info,c.recognized),y(`Keys for ${i.presetName}:`,I);let l=0;for(let E=0;E<i.presetZones.length;E++){let C=i.presetZones[E],B=C.keyRange,f=C.velRange,u=!1;for(let S of I)if(S.key>=B.min&&S.key<=B.max&&S.velocity>=f.min&&S.velocity<=f.max){u=!0;let M=n(C.instrument,I);y(`%cTrimmed off %c${M}%c zones from %c${C.instrument.instrumentName}`,c.info,c.recognized,c.info,c.recognized);break}u||(l++,i.deleteZone(E),C.instrument.useCount<1&&e.deleteInstrument(C.instrument),E--)}y(`%cTrimmed off %c${l}%c zones from %c${i.presetName}`,c.info,c.recognized,c.info,c.recognized),q()}}e.removeUnusedElements(),e.soundFontInfo.ICMT=`NOTE: This soundfont was trimmed by SpessaSynth to only contain presets used in "${A.midiName}"
12
12
 
13
- `+e.soundFontInfo.ICMT,y("%cSoundfont modified!",c.recognized),q(),q()}removeUnusedElements(){this.instruments=this.instruments.filter(A=>{A.deleteUnusedZones();let e=A.useCount<1;return e&&A.deleteInstrument(),!e}),this.samples=this.samples.filter(A=>{let e=A.useCount<1;return e&&A.deleteSample(),!e})}deleteInstrument(A){A.deleteInstrument(),this.instruments.splice(this.instruments.indexOf(A),1)}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1)}deleteSample(A){A.deleteSample(),this.samples.splice(this.samples.indexOf(A),1)}getPresetNoFallback(A,e,n=!1){let s=A===128||n&&te(A),r;if(s?r=this.presets.find(i=>i.bank===A&&i.isDrumPreset(n)&&i.program===e):r=this.presets.find(i=>i.bank===A&&i.program===e),r)return r;if(s&&n){let i=this.presets.find(a=>a.isDrumPreset(n)&&a.program===e);if(i)return i}}getPreset(A,e,n=!1){let s=A===128||n&&te(A),r;return s?r=this.presets.find(i=>i.bank===A&&i.isDrumPreset(n)&&i.program===e):r=this.presets.find(i=>i.bank===A&&i.program===e),r||(s?(r=this.presets.find(i=>i.isDrumPreset(n)&&i.program===e),r||(r=this.presets.find(i=>i.isDrumPreset(n)))):r=this.presets.find(i=>i.program===e&&!i.isDrumPreset(n)),r&&H(`%cPreset ${A}.${e} not found. Replaced with %c${r.presetName} (${r.bank}.${r.program})`,c.warn,c.recognized),r||(H(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),r=this.presets[0]),r)}getPresetByName(A){let e=this.presets.find(n=>n.presetName===A);return e||(H("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}parsingError(A){throw new Error(`SF parsing error: ${A} The file may be corrupted.`)}destroySoundBank(){delete this.presets,delete this.instruments,delete this.samples,delete this.soundFontInfo}};Te.prototype.write=Xo;Te.prototype.writeDLS=ar;function gr(t){dA("%cLoading instruments...",c.info);for(let A=0;A<this.instrumentAmount;A++)this.readDLSInstrument(AA(t.chunkData));q()}var kn=class extends Le{constructor(A){super(A)}setWavesample(A,e,n,s,r,i,a){e!==0&&this.addGenerators(new Y(g.sampleModes,e)),this.addGenerators(new Y(g.initialAttenuation,A)),a-=r.samplePitchCorrection;let o=Math.trunc(a/100);o!==0&&this.addGenerators(new Y(g.coarseTune,o));let I=a-o*100;if(I!==0&&this.addGenerators(new Y(g.fineTune,I)),e!==0){let l=n.start-r.sampleLoopStartIndex,E=n.end-r.sampleLoopEndIndex;if(l!==0){let C=l%32768;this.addGenerators(new Y(g.startloopAddrsOffset,C));let B=Math.trunc(l/32768);B!==0&&this.addGenerators(new Y(g.startloopAddrsCoarseOffset,B))}if(E!==0){let C=E%32768;this.addGenerators(new Y(g.endloopAddrsOffset,C));let B=Math.trunc(E/32768);B!==0&&this.addGenerators(new Y(g.endloopAddrsCoarseOffset,B))}}s!==r.samplePitch&&this.addGenerators(new Y(g.overridingRootKey,s)),this.setSample(r)}};var Fn=class extends Ce{constructor(){super()}createZone(){let A=new kn(this);return this.instrumentZones.push(A),A}};var wn=class extends he{dlsInstrument=new Fn;constructor(A,e,n){super(A),this.program=n&127;let s=e>>8&127,r=e&127;s>0?this.bank=s:this.bank=r,e>>31&&(this.bank=128),this.createZone().setInstrument(this.dlsInstrument)}};function Ir(t,A){let e=[];for(;t.chunkData.length>t.chunkData.currentIndex;)e.push(AA(t.chunkData));let n=e.find(v=>v.header==="rgnh");if(!n){H("Invalid DLS region: missing 'rgnh' chunk! Discarding...");return}let s=U(n.chunkData,2),r=U(n.chunkData,2),i=U(n.chunkData,2),a=U(n.chunkData,2);i===0&&a===0&&(a=127,i=0);let o=A.createZone();o.keyRange={min:s,max:r},o.velRange={min:i,max:a},U(n.chunkData,2);let I=U(n.chunkData,2);I!==0&&o.addGenerators(new Y(g.exclusiveClass,I));let l=_A(e,"lart"),E=_A(e,"lar2");this.readLart(l,E,o);let C=e.find(v=>v.header==="wsmp");U(C.chunkData,4);let B=U(C.chunkData,2),f=Ke(C.chunkData[C.chunkData.currentIndex++],C.chunkData[C.chunkData.currentIndex++]),S=(U(C.chunkData,4)|0)/-655360;U(C.chunkData,4);let M=U(C.chunkData,4),F,k={start:0,end:0};if(M===0)F=0;else{U(C.chunkData,4),U(C.chunkData,4)===0?F=1:F=3,k.start=U(C.chunkData,4);let sA=U(C.chunkData,4);k.end=k.start+sA}let G=e.find(v=>v.header==="wlnk");if(G===void 0)return;U(G.chunkData,2),U(G.chunkData,2),U(G.chunkData,4);let N=U(G.chunkData,4),h=this.samples[N];if(h===void 0)throw new Error("Invalid sample ID!");let P=(S||h.sampleDbAttenuation)*10/.4;o.setWavesample(P,F,k,B,h,N,f)}function cr(t){this.verifyHeader(t,"LIST"),this.verifyText(j(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(AA(t.chunkData));let e=A.find(B=>B.header==="insh");if(!e)throw q(),new Error("No instrument header!");let n=U(e.chunkData,4),s=U(e.chunkData,4),r=U(e.chunkData,4),i=new wn(this,s,r),a="",o=_A(A,"INFO");if(o){let B=AA(o.chunkData);for(;B.header!=="INAM";)B=AA(o.chunkData);a=j(B.chunkData,B.chunkData.length).trim()}a.length<1&&(a=`unnamed ${s>>8&127}:${r&127}`),i.presetName=a,i.dlsInstrument.instrumentName=a,dA(`%cParsing %c"${a}"%c...`,c.info,c.recognized,c.info);let I=_A(A,"lrgn");if(!I)throw q(),new Error("No region list!");let l=i.dlsInstrument.globalZone,E=_A(A,"lart"),C=_A(A,"lar2");(C!==void 0||E!==void 0)&&this.readLart(E,C,l),l.generators=l.generators.filter(B=>B.generatorValue!==V[B.generatorType].def),l.modulators.find(B=>B.modulatorDestination===g.reverbEffectsSend)===void 0&&l.addModulators(EA.copy(mn)),l.modulators.find(B=>B.modulatorDestination===g.chorusEffectsSend)===void 0&&l.addModulators(EA.copy(pn));for(let B=0;B<n;B++){let f=AA(I.chunkData);this.verifyHeader(f,"LIST");let u=j(f.chunkData,4);u!=="rgn "&&u!=="rgn2"&&(q(),this.parsingError(`Invalid DLS region! Expected "rgn " or "rgn2" got "${u}"`)),Ir.call(this,f,i.dlsInstrument)}this.addPresets(i),this.addInstruments(i.dlsInstrument),q()}function Er(t){let A,e=!1;switch(t){default:case Z.modLfo:case Z.vibratoLfo:case Z.coarseTune:case Z.fineTune:case Z.modEnv:return;case Z.keyNum:A=W.noteOnKeyNum;break;case Z.none:A=W.noController;break;case Z.modulationWheel:A=p.modulationWheel,e=!0;break;case Z.pan:A=p.pan,e=!0;break;case Z.reverb:A=p.reverbDepth,e=!0;break;case Z.chorus:A=p.chorusDepth,e=!0;break;case Z.expression:A=p.expressionController,e=!0;break;case Z.volume:A=p.mainVolume,e=!0;break;case Z.velocity:A=W.noteOnVelocity;break;case Z.polyPressure:A=W.polyPressure;break;case Z.channelPressure:A=W.channelPressure;break;case Z.pitchWheel:A=W.pitchWheel;break;case Z.pitchWheelRange:A=W.pitchWheelRange;break}if(A===void 0)throw new Error(`Unknown DLS Source: ${t}`);return{enum:A,isCC:e}}function Ki(t,A){switch(t){default:case x.none:return;case x.pan:return g.pan;case x.gain:return{gen:g.initialAttenuation,newAmount:A*-1};case x.pitch:return g.fineTune;case x.keyNum:return g.overridingRootKey;case x.volEnvDelay:return g.delayVolEnv;case x.volEnvAttack:return g.attackVolEnv;case x.volEnvHold:return g.holdVolEnv;case x.volEnvDecay:return g.decayVolEnv;case x.volEnvSustain:return{gen:g.sustainVolEnv,newAmount:1e3-A};case x.volEnvRelease:return g.releaseVolEnv;case x.modEnvDelay:return g.delayModEnv;case x.modEnvAttack:return g.attackModEnv;case x.modEnvHold:return g.holdModEnv;case x.modEnvDecay:return g.decayModEnv;case x.modEnvSustain:return{gen:g.sustainModEnv,newAmount:(1e3-A)/10};case x.modEnvRelease:return g.releaseModEnv;case x.filterCutoff:return g.initialFilterFc;case x.filterQ:return g.initialFilterQ;case x.chorusSend:return g.chorusEffectsSend;case x.reverbSend:return g.reverbEffectsSend;case x.modLfoFreq:return g.freqModLFO;case x.modLfoDelay:return g.delayModLFO;case x.vibLfoFreq:return g.freqVibLFO;case x.vibLfoDelay:return g.delayVibLFO}}function qi(t,A){return t===Z.vibratoLfo&&A===x.pitch?g.vibLfoToPitch:t===Z.modLfo&&A===x.pitch?g.modLfoToPitch:t===Z.modLfo&&A===x.filterCutoff?g.modLfoToFilterFc:t===Z.modLfo&&A===x.gain?g.modLfoToVolume:t===Z.modEnv&&A===x.filterCutoff?g.modEnvToFilterFc:t===Z.modEnv&&A===x.pitch?g.modEnvToPitch:void 0}function Cr(t,A,e,n,s){let r=qi(t,e),i,a,o=!1,I=!1,l=s;if(r===void 0){let M=Ki(e,s);if(M===void 0){H(`Invalid destination: ${e}`);return}if(i=M,M.newAmount!==void 0&&(l=M.newAmount,i=M.gen),a=Er(t),a===void 0){H(`Invalid source: ${t}`);return}}else i=r,o=!0,a={enum:W.noController,isCC:!1},I=!0;let E=Er(A);if(E===void 0){H(`Invalid control: ${A}`);return}let C;if(I)C=0;else{let M=n&15,F=n>>10&15;F===kA.linear&&M!==kA.linear&&(F=M);let k=n>>14&1,G=n>>15&1;i===g.initialAttenuation&&s<0&&(G=1),C=WA(F,k,G,a.isCC,a.enum)}i===g.initialAttenuation&&(l=Math.max(960,Math.min(0,l)));let B=n>>4&15,f=n>>8&1,u=n>>9&1,S=WA(B,f,u,E.isCC,E.enum);if(o){let M=S;S=C,C=M}return new pA(C,S,i,l,0)}function Ss(t,A){let e=t.chunkData,n=[],s=[];U(e,4);let r=U(e,4);for(let i=0;i<r;i++){let a=U(e,2),o=U(e,2),I=U(e,2),l=U(e,2),C=(U(e,4)|0)>>16;if(a===0&&o===0&&l===0){let B;switch(I){case x.pan:B=new Y(g.pan,C);break;case x.gain:B=new Y(g.initialAttenuation,-C*10/.4);break;case x.filterCutoff:B=new Y(g.initialFilterFc,C);break;case x.filterQ:B=new Y(g.initialFilterQ,C);break;case x.modLfoFreq:B=new Y(g.freqModLFO,C);break;case x.modLfoDelay:B=new Y(g.delayModLFO,C);break;case x.vibLfoFreq:B=new Y(g.freqVibLFO,C);break;case x.vibLfoDelay:B=new Y(g.delayVibLFO,C);break;case x.volEnvDelay:B=new Y(g.delayVolEnv,C);break;case x.volEnvAttack:B=new Y(g.attackVolEnv,C);break;case x.volEnvHold:B=new Y(g.holdVolEnv,C,!1);break;case x.volEnvDecay:B=new Y(g.decayVolEnv,C,!1);break;case x.volEnvRelease:B=new Y(g.releaseVolEnv,C);break;case x.volEnvSustain:let f=1e3-C;B=new Y(g.sustainVolEnv,f);break;case x.modEnvDelay:B=new Y(g.delayModEnv,C);break;case x.modEnvAttack:B=new Y(g.attackModEnv,C);break;case x.modEnvHold:B=new Y(g.holdModEnv,C,!1);break;case x.modEnvDecay:B=new Y(g.decayModEnv,C,!1);break;case x.modEnvRelease:B=new Y(g.releaseModEnv,C);break;case x.modEnvSustain:let u=1e3-C;B=new Y(g.sustainModEnv,u);break;case x.reverbSend:B=new Y(g.reverbEffectsSend,C);break;case x.chorusSend:B=new Y(g.chorusEffectsSend,C);break;case x.pitch:let S=Math.floor(C/100),M=Math.floor(C-S*100);B=new Y(g.fineTune,M),n.push(new Y(g.coarseTune,S));break}B&&n.push(B)}else{let B=!0,f=(u,S,M)=>{let F=u/-128;if(n.push(new Y(S,F)),F<=120){let k=Math.round(.46875*u);n.forEach(G=>{G.generatorType===M&&(G.generatorValue+=k)})}};if(o===Z.none?a===Z.modLfo&&I===x.pitch?n.push(new Y(g.modLfoToPitch,C)):a===Z.modLfo&&I===x.gain?n.push(new Y(g.modLfoToVolume,C)):a===Z.modLfo&&I===x.filterCutoff?n.push(new Y(g.modLfoToFilterFc,C)):a===Z.vibratoLfo&&I===x.pitch?n.push(new Y(g.vibLfoToPitch,C)):a===Z.modEnv&&I===x.pitch?n.push(new Y(g.modEnvToPitch,C)):a===Z.modEnv&&I===x.filterCutoff?n.push(new Y(g.modEnvToFilterFc,C)):a===Z.keyNum&&I===x.pitch?n.push(new Y(g.scaleTuning,C/128)):a===Z.keyNum&&I===x.volEnvHold?f(C,g.keyNumToVolEnvHold,g.holdVolEnv):a===Z.keyNum&&I===x.volEnvDecay?f(C,g.keyNumToVolEnvDecay,g.decayVolEnv):a===Z.keyNum&&I===x.modEnvHold?f(C,g.keyNumToModEnvHold,g.holdModEnv):a===Z.keyNum&&I===x.modEnvDecay?f(C,g.keyNumToModEnvDecay,g.decayModEnv):B=!1:B=!1,B===!1){let u=Cr(a,o,I,l,C);u?(s.push(u),y("%cSucceeded converting to SF2 Modulator!",c.recognized)):H("Failed converting to SF2 Modulator!")}}}return A&&s.push(EA.copy(yn),EA.copy(Sn)),{modulators:s,generators:n}}function hr(t,A,e){if(t)for(;t.chunkData.currentIndex<t.chunkData.length;){let n=AA(t.chunkData);this.verifyHeader(n,"art1","art2");let s=Ss(n,!0);e.addGenerators(...s.generators),e.addModulators(...s.modulators)}if(A)for(;A.chunkData.currentIndex<A.chunkData.length;){let n=AA(A.chunkData);this.verifyHeader(n,"art2","art1");let s=Ss(n,!1);e.addGenerators(...s.generators),e.addModulators(...s.modulators)}}var Ds={PCM:1,ALAW:6};function Vi(t,A){let e=Math.pow(2,A*8-1),n=Math.pow(2,A*8),s,r=!1;A===1?(s=255,r=!0):s=e;let i=t.length/A,a=new Float32Array(i);if(A===2){let o=new Int16Array(t.buffer);for(let I=0;I<o.length;I++)a[I]=o[I]/32768}else for(let o=0;o<a.length;o++){let I=U(t,A);r?a[o]=I/s-.5:(I>=e&&(I-=n),a[o]=I/s)}return a}function Zi(t,A){let e=t/A,n=new Float32Array(e);for(let s=0;s<n.length;s++){let r=U(t,A),i=r^85;i&=127;let a=i>>4,o=i&15;a>0&&(o+=16),o=(o<<4)+8,a>1&&(o=o<<a-1);let I=r>127?o:-o;n[s]=I/32678}return n}var Rn=class extends ke{sampleDbAttenuation;sampleData;wFormatTag;bytesPerSample;rawData;constructor(A,e,n,s,r,i,a,o,I,l){super(A,e,n,s,vA.monoSample,r,i),this.sampleDbAttenuation=a,this.dataOverriden=!1,this.rawData=o.chunkData,this.wFormatTag=I,this.bytesPerSample=l}getAudioData(){if(!(this.rawData instanceof Uint8Array))return new Float32Array(0);if(!this.sampleData){let A;switch(this.wFormatTag){default:H(`Failed to decode sample. Unknown wFormatTag: ${this.wFormatTag}`),A=new Float32Array(this.rawData.length/this.bytesPerSample);break;case Ds.PCM:A=Vi(this.rawData,this.bytesPerSample);break;case Ds.ALAW:A=Zi(this.rawData,this.bytesPerSample);break}this.setAudioData(A)}return this.sampleData}setAudioData(A){super.setAudioData(A)}getRawData(A){return this.dataOverriden||this.isCompressed?super.getRawData(A):this.wFormatTag===Ds.PCM&&this.bytesPerSample===2?this.rawData:this.encodeS16LE()}};function lr(t){dA("%cLoading Wave samples...",c.recognized);let A=0;for(;t.chunkData.currentIndex<t.chunkData.length;){let e=AA(t.chunkData);this.verifyHeader(e,"LIST"),this.verifyText(j(e.chunkData,4),"wave");let n=[];for(;e.chunkData.currentIndex<e.chunkData.length;)n.push(AA(e.chunkData));let s=n.find(G=>G.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");let r=U(s.chunkData,2),i=U(s.chunkData,2);if(i!==1)throw new Error(`Only mono samples are supported. Fmt reports ${i} channels`);let a=U(s.chunkData,4);U(s.chunkData,4),U(s.chunkData,2);let I=U(s.chunkData,2)/8,l=n.find(G=>G.header==="data");l||this.parsingError("No data chunk in the WAVE chunk!");let E=_A(n,"INFO"),C=`Unnamed ${A}`;if(E){let G=AA(E.chunkData);for(;G.header!=="INAM"&&E.chunkData.currentIndex<E.chunkData.length;)G=AA(E.chunkData);G.header==="INAM"&&(C=j(G.chunkData,G.size).trim())}let B=60,f=0,u=0,M=l.size/I-1,F=0,k=n.find(G=>G.header==="wsmp");if(k){U(k.chunkData,4),B=U(k.chunkData,2),f=Ke(k.chunkData[k.chunkData.currentIndex++],k.chunkData[k.chunkData.currentIndex++]);let G=Math.trunc(f/100);if(B+=G,f-=G*100,F=(U(k.chunkData,4)|0)/-655360,U(k.chunkData,4),U(k.chunkData,4)===1){U(k.chunkData,8),u=U(k.chunkData,4);let eA=U(k.chunkData,4);M=u+eA}}else H("No wsmp chunk in wave... using sane defaults.");this.samples.push(new Rn(C,a,B,f,u,M,F,l,r,I)),A++,y(`%cLoaded sample %c${C}`,c.info,c.recognized)}q()}var qe=class extends Te{constructor(A){super(),this.dataArray=new T(A),Ie("%cParsing DLS...",c.info),this.dataArray||(q(),this.parsingError("No data provided!"));let e=AA(this.dataArray,!1);this.verifyHeader(e,"riff"),this.verifyText(j(this.dataArray,4).toLowerCase(),"dls ");let n=[];for(;this.dataArray.currentIndex<this.dataArray.length;)n.push(AA(this.dataArray));this.soundFontInfo.ifil="2.1",this.soundFontInfo.isng="E-mu 10K2",this.soundFontInfo.INAM="Unnamed DLS",this.soundFontInfo.IENG="Unknown",this.soundFontInfo.IPRD="SpessaSynth DLS",this.soundFontInfo.ICRD=new Date().toDateString();let s=_A(n,"INFO");if(s)for(;s.chunkData.currentIndex<s.chunkData.length;){let o=AA(s.chunkData);this.soundFontInfo[o.header]=j(o.chunkData,o.size)}this.soundFontInfo.ICMT=this.soundFontInfo.ICMT||"(No description)",this.soundFontInfo.ISBJ&&(this.soundFontInfo.ICMT+=`
13
+ `+e.soundFontInfo.ICMT,y("%cSoundfont modified!",c.recognized),q(),q()}removeUnusedElements(){this.instruments=this.instruments.filter(A=>{A.deleteUnusedZones();let e=A.useCount<1;return e&&A.deleteInstrument(),!e}),this.samples=this.samples.filter(A=>{let e=A.useCount<1;return e&&A.deleteSample(),!e})}deleteInstrument(A){A.deleteInstrument(),this.instruments.splice(this.instruments.indexOf(A),1)}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1)}deleteSample(A){A.deleteSample(),this.samples.splice(this.samples.indexOf(A),1)}getPresetNoFallback(A,e,n=!1){let s=A===128||n&&te(A),r;if(s?r=this.presets.find(i=>i.bank===A&&i.isDrumPreset(n)&&i.program===e):r=this.presets.find(i=>i.bank===A&&i.program===e),r)return r;if(s&&n){let i=this.presets.find(a=>a.isDrumPreset(n)&&a.program===e);if(i)return i}}getPreset(A,e,n=!1){let s=A===128||n&&te(A),r;return s?r=this.presets.find(i=>i.bank===A&&i.isDrumPreset(n)&&i.program===e):r=this.presets.find(i=>i.bank===A&&i.program===e),r||(s?(r=this.presets.find(i=>i.isDrumPreset(n)&&i.program===e),r||(r=this.presets.find(i=>i.isDrumPreset(n)))):r=this.presets.find(i=>i.program===e&&!i.isDrumPreset(n)),r&&H(`%cPreset ${A}.${e} not found. Replaced with %c${r.presetName} (${r.bank}.${r.program})`,c.warn,c.recognized),r||(H(`Preset ${e} not found. Defaulting to`,this.presets[0].presetName),r=this.presets[0]),r)}getPresetByName(A){let e=this.presets.find(n=>n.presetName===A);return e||(H("Preset not found. Defaulting to:",this.presets[0].presetName),e=this.presets[0]),e}parsingError(A){throw new Error(`SF parsing error: ${A} The file may be corrupted.`)}destroySoundBank(){delete this.presets,delete this.instruments,delete this.samples,delete this.soundFontInfo}};Te.prototype.write=Xo;Te.prototype.writeDLS=ar;function gr(t){dA("%cLoading instruments...",c.info);for(let A=0;A<this.instrumentAmount;A++)this.readDLSInstrument(AA(t.chunkData));q()}var kn=class extends Le{constructor(A){super(A)}setWavesample(A,e,n,s,r,i,a){e!==0&&this.addGenerators(new Y(g.sampleModes,e)),this.addGenerators(new Y(g.initialAttenuation,A)),a-=r.samplePitchCorrection;let o=Math.trunc(a/100);o!==0&&this.addGenerators(new Y(g.coarseTune,o));let I=a-o*100;if(I!==0&&this.addGenerators(new Y(g.fineTune,I)),e!==0){let l=n.start-r.sampleLoopStartIndex,E=n.end-r.sampleLoopEndIndex;if(l!==0){let C=l%32768;this.addGenerators(new Y(g.startloopAddrsOffset,C));let B=Math.trunc(l/32768);B!==0&&this.addGenerators(new Y(g.startloopAddrsCoarseOffset,B))}if(E!==0){let C=E%32768;this.addGenerators(new Y(g.endloopAddrsOffset,C));let B=Math.trunc(E/32768);B!==0&&this.addGenerators(new Y(g.endloopAddrsCoarseOffset,B))}}s!==r.samplePitch&&this.addGenerators(new Y(g.overridingRootKey,s)),this.setSample(r)}};var Fn=class extends Ce{constructor(){super()}createZone(){let A=new kn(this);return this.instrumentZones.push(A),A}};var wn=class extends he{dlsInstrument=new Fn;constructor(A,e,n){super(A),this.program=n&127;let s=e>>8&127,r=e&127;s>0?this.bank=s:this.bank=r,e>>31&&(this.bank=128),this.createZone().setInstrument(this.dlsInstrument)}};function Ir(t,A){let e=[];for(;t.chunkData.length>t.chunkData.currentIndex;)e.push(AA(t.chunkData));let n=e.find(v=>v.header==="rgnh");if(!n){H("Invalid DLS region: missing 'rgnh' chunk! Discarding...");return}let s=U(n.chunkData,2),r=U(n.chunkData,2),i=U(n.chunkData,2),a=U(n.chunkData,2);i===0&&a===0&&(a=127,i=0);let o=A.createZone();o.keyRange={min:s,max:r},o.velRange={min:i,max:a},U(n.chunkData,2);let I=U(n.chunkData,2);I!==0&&o.addGenerators(new Y(g.exclusiveClass,I));let l=_A(e,"lart"),E=_A(e,"lar2");this.readLart(l,E,o);let C=e.find(v=>v.header==="wsmp");U(C.chunkData,4);let B=U(C.chunkData,2),f=Ke(C.chunkData[C.chunkData.currentIndex++],C.chunkData[C.chunkData.currentIndex++]),S=(U(C.chunkData,4)|0)/-655360;U(C.chunkData,4);let M=U(C.chunkData,4),F,k={start:0,end:0};if(M===0)F=0;else{U(C.chunkData,4),U(C.chunkData,4)===0?F=1:F=3,k.start=U(C.chunkData,4);let sA=U(C.chunkData,4);k.end=k.start+sA}let G=e.find(v=>v.header==="wlnk");if(G===void 0)return;U(G.chunkData,2),U(G.chunkData,2),U(G.chunkData,4);let N=U(G.chunkData,4),h=this.samples[N];if(h===void 0)throw new Error("Invalid sample ID!");let P=(S||h.sampleDbAttenuation)*10/.4;o.setWavesample(P,F,k,B,h,N,f)}function cr(t){this.verifyHeader(t,"LIST"),this.verifyText(j(t.chunkData,4),"ins ");let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(AA(t.chunkData));let e=A.find(B=>B.header==="insh");if(!e)throw q(),new Error("No instrument header!");let n=U(e.chunkData,4),s=U(e.chunkData,4),r=U(e.chunkData,4),i=new wn(this,s,r),a="",o=_A(A,"INFO");if(o){let B=AA(o.chunkData);for(;B.header!=="INAM";)B=AA(o.chunkData);a=j(B.chunkData,B.chunkData.length).trim()}a.length<1&&(a=`unnamed ${s>>8&127}:${r&127}`),i.presetName=a,i.dlsInstrument.instrumentName=a,dA(`%cParsing %c"${a}"%c...`,c.info,c.recognized,c.info);let I=_A(A,"lrgn");if(!I)throw q(),new Error("No region list!");let l=i.dlsInstrument.globalZone,E=_A(A,"lart"),C=_A(A,"lar2");(C!==void 0||E!==void 0)&&this.readLart(E,C,l),l.generators=l.generators.filter(B=>B.generatorValue!==V[B.generatorType].def),l.modulators.find(B=>B.modulatorDestination===g.reverbEffectsSend)===void 0&&l.addModulators(EA.copy(mn)),l.modulators.find(B=>B.modulatorDestination===g.chorusEffectsSend)===void 0&&l.addModulators(EA.copy(pn));for(let B=0;B<n;B++){let f=AA(I.chunkData);this.verifyHeader(f,"LIST");let u=j(f.chunkData,4);u!=="rgn "&&u!=="rgn2"&&(q(),this.parsingError(`Invalid DLS region! Expected "rgn " or "rgn2" got "${u}"`)),Ir.call(this,f,i.dlsInstrument)}this.addPresets(i),this.addInstruments(i.dlsInstrument),q()}function Er(t){let A,e=!1;switch(t){default:case Z.modLfo:case Z.vibratoLfo:case Z.coarseTune:case Z.fineTune:case Z.modEnv:return;case Z.keyNum:A=W.noteOnKeyNum;break;case Z.none:A=W.noController;break;case Z.modulationWheel:A=p.modulationWheel,e=!0;break;case Z.pan:A=p.pan,e=!0;break;case Z.reverb:A=p.reverbDepth,e=!0;break;case Z.chorus:A=p.chorusDepth,e=!0;break;case Z.expression:A=p.expressionController,e=!0;break;case Z.volume:A=p.mainVolume,e=!0;break;case Z.velocity:A=W.noteOnVelocity;break;case Z.polyPressure:A=W.polyPressure;break;case Z.channelPressure:A=W.channelPressure;break;case Z.pitchWheel:A=W.pitchWheel;break;case Z.pitchWheelRange:A=W.pitchWheelRange;break}if(A===void 0)throw new Error(`Unknown DLS Source: ${t}`);return{enum:A,isCC:e}}function Ki(t,A){switch(t){default:case x.none:return;case x.pan:return g.pan;case x.gain:return{gen:g.initialAttenuation,newAmount:A*-1};case x.pitch:return g.fineTune;case x.keyNum:return g.overridingRootKey;case x.volEnvDelay:return g.delayVolEnv;case x.volEnvAttack:return g.attackVolEnv;case x.volEnvHold:return g.holdVolEnv;case x.volEnvDecay:return g.decayVolEnv;case x.volEnvSustain:return{gen:g.sustainVolEnv,newAmount:1e3-A};case x.volEnvRelease:return g.releaseVolEnv;case x.modEnvDelay:return g.delayModEnv;case x.modEnvAttack:return g.attackModEnv;case x.modEnvHold:return g.holdModEnv;case x.modEnvDecay:return g.decayModEnv;case x.modEnvSustain:return{gen:g.sustainModEnv,newAmount:(1e3-A)/10};case x.modEnvRelease:return g.releaseModEnv;case x.filterCutoff:return g.initialFilterFc;case x.filterQ:return g.initialFilterQ;case x.chorusSend:return g.chorusEffectsSend;case x.reverbSend:return g.reverbEffectsSend;case x.modLfoFreq:return g.freqModLFO;case x.modLfoDelay:return g.delayModLFO;case x.vibLfoFreq:return g.freqVibLFO;case x.vibLfoDelay:return g.delayVibLFO}}function qi(t,A){return t===Z.vibratoLfo&&A===x.pitch?g.vibLfoToPitch:t===Z.modLfo&&A===x.pitch?g.modLfoToPitch:t===Z.modLfo&&A===x.filterCutoff?g.modLfoToFilterFc:t===Z.modLfo&&A===x.gain?g.modLfoToVolume:t===Z.modEnv&&A===x.filterCutoff?g.modEnvToFilterFc:t===Z.modEnv&&A===x.pitch?g.modEnvToPitch:void 0}function Cr(t,A,e,n,s){let r=qi(t,e),i,a,o=!1,I=!1,l=s;if(r===void 0){let M=Ki(e,s);if(M===void 0){H(`Invalid destination: ${e}`);return}if(i=M,M.newAmount!==void 0&&(l=M.newAmount,i=M.gen),a=Er(t),a===void 0){H(`Invalid source: ${t}`);return}}else i=r,o=!0,a={enum:W.noController,isCC:!1},I=!0;let E=Er(A);if(E===void 0){H(`Invalid control: ${A}`);return}let C;if(I)C=0;else{let M=n&15,F=n>>10&15;F===kA.linear&&M!==kA.linear&&(F=M);let k=n>>14&1,G=n>>15&1;i===g.initialAttenuation&&s<0&&(G=1),C=WA(F,k,G,a.isCC,a.enum)}i===g.initialAttenuation&&(l=Math.max(960,Math.min(0,l)));let B=n>>4&15,f=n>>8&1,u=n>>9&1,S=WA(B,f,u,E.isCC,E.enum);if(o){let M=S;S=C,C=M}return new pA(C,S,i,l,0)}function Ss(t,A){let e=t.chunkData,n=[],s=[];U(e,4);let r=U(e,4);for(let i=0;i<r;i++){let a=U(e,2),o=U(e,2),I=U(e,2),l=U(e,2),C=(U(e,4)|0)>>16;if(a===0&&o===0&&l===0){let B;switch(I){case x.pan:B=new Y(g.pan,C);break;case x.gain:B=new Y(g.initialAttenuation,-C*10/.4);break;case x.filterCutoff:B=new Y(g.initialFilterFc,C);break;case x.filterQ:B=new Y(g.initialFilterQ,C);break;case x.modLfoFreq:B=new Y(g.freqModLFO,C);break;case x.modLfoDelay:B=new Y(g.delayModLFO,C);break;case x.vibLfoFreq:B=new Y(g.freqVibLFO,C);break;case x.vibLfoDelay:B=new Y(g.delayVibLFO,C);break;case x.volEnvDelay:B=new Y(g.delayVolEnv,C);break;case x.volEnvAttack:B=new Y(g.attackVolEnv,C);break;case x.volEnvHold:B=new Y(g.holdVolEnv,C,!1);break;case x.volEnvDecay:B=new Y(g.decayVolEnv,C,!1);break;case x.volEnvRelease:B=new Y(g.releaseVolEnv,C);break;case x.volEnvSustain:let f=1e3-C;B=new Y(g.sustainVolEnv,f);break;case x.modEnvDelay:B=new Y(g.delayModEnv,C);break;case x.modEnvAttack:B=new Y(g.attackModEnv,C);break;case x.modEnvHold:B=new Y(g.holdModEnv,C,!1);break;case x.modEnvDecay:B=new Y(g.decayModEnv,C,!1);break;case x.modEnvRelease:B=new Y(g.releaseModEnv,C);break;case x.modEnvSustain:let u=1e3-C;B=new Y(g.sustainModEnv,u);break;case x.reverbSend:B=new Y(g.reverbEffectsSend,C);break;case x.chorusSend:B=new Y(g.chorusEffectsSend,C);break;case x.pitch:let S=Math.floor(C/100),M=Math.floor(C-S*100);B=new Y(g.fineTune,M),n.push(new Y(g.coarseTune,S));break}B&&n.push(B)}else{let B=!0,f=(u,S,M)=>{let F=u/-128;if(n.push(new Y(S,F)),F<=120){let k=Math.round(.46875*u);n.forEach(G=>{G.generatorType===M&&(G.generatorValue+=k)})}};if(o===Z.none?a===Z.modLfo&&I===x.pitch?n.push(new Y(g.modLfoToPitch,C)):a===Z.modLfo&&I===x.gain?n.push(new Y(g.modLfoToVolume,C)):a===Z.modLfo&&I===x.filterCutoff?n.push(new Y(g.modLfoToFilterFc,C)):a===Z.vibratoLfo&&I===x.pitch?n.push(new Y(g.vibLfoToPitch,C)):a===Z.modEnv&&I===x.pitch?n.push(new Y(g.modEnvToPitch,C)):a===Z.modEnv&&I===x.filterCutoff?n.push(new Y(g.modEnvToFilterFc,C)):a===Z.keyNum&&I===x.pitch?n.push(new Y(g.scaleTuning,C/128)):a===Z.keyNum&&I===x.volEnvHold?f(C,g.keyNumToVolEnvHold,g.holdVolEnv):a===Z.keyNum&&I===x.volEnvDecay?f(C,g.keyNumToVolEnvDecay,g.decayVolEnv):a===Z.keyNum&&I===x.modEnvHold?f(C,g.keyNumToModEnvHold,g.holdModEnv):a===Z.keyNum&&I===x.modEnvDecay?f(C,g.keyNumToModEnvDecay,g.decayModEnv):B=!1:B=!1,B===!1){let u=Cr(a,o,I,l,C);u?(s.push(u),y("%cSucceeded converting to SF2 Modulator!",c.recognized)):H("Failed converting to SF2 Modulator!")}}}return A&&s.push(EA.copy(yn),EA.copy(Sn)),{modulators:s,generators:n}}function hr(t,A,e){if(t)for(;t.chunkData.currentIndex<t.chunkData.length;){let n=AA(t.chunkData);this.verifyHeader(n,"art1","art2");let s=Ss(n,!0);e.addGenerators(...s.generators),e.addModulators(...s.modulators)}if(A)for(;A.chunkData.currentIndex<A.chunkData.length;){let n=AA(A.chunkData);this.verifyHeader(n,"art2","art1");let s=Ss(n,!1);e.addGenerators(...s.generators),e.addModulators(...s.modulators)}}var Ds={PCM:1,ALAW:6};function Vi(t,A){let e=Math.pow(2,A*8-1),n=Math.pow(2,A*8),s,r=!1;A===1?(s=255,r=!0):s=e;let i=t.length/A,a=new Float32Array(i);if(A===2){let o=new Int16Array(t.buffer);for(let I=0;I<o.length;I++)a[I]=o[I]/32768}else for(let o=0;o<a.length;o++){let I=U(t,A);r?a[o]=I/s-.5:(I>=e&&(I-=n),a[o]=I/s)}return a}function Zi(t,A){let e=t.length/A,n=new Float32Array(e);for(let s=0;s<n.length;s++){let r=U(t,A),i=r^85;i&=127;let a=i>>4,o=i&15;a>0&&(o+=16),o=(o<<4)+8,a>1&&(o=o<<a-1);let I=r>127?o:-o;n[s]=I/32678}return n}var Rn=class extends ke{sampleDbAttenuation;sampleData;wFormatTag;bytesPerSample;rawData;constructor(A,e,n,s,r,i,a,o,I,l){super(A,e,n,s,vA.monoSample,r,i),this.sampleDbAttenuation=a,this.dataOverriden=!1,this.rawData=o.chunkData,this.wFormatTag=I,this.bytesPerSample=l}getAudioData(){if(!(this.rawData instanceof Uint8Array))return new Float32Array(0);if(!this.sampleData){let A;switch(this.wFormatTag){default:H(`Failed to decode sample. Unknown wFormatTag: ${this.wFormatTag}`),A=new Float32Array(this.rawData.length/this.bytesPerSample);break;case Ds.PCM:A=Vi(this.rawData,this.bytesPerSample);break;case Ds.ALAW:A=Zi(this.rawData,this.bytesPerSample);break}this.setAudioData(A)}return this.sampleData}setAudioData(A){super.setAudioData(A)}getRawData(A){return this.dataOverriden||this.isCompressed?super.getRawData(A):this.wFormatTag===Ds.PCM&&this.bytesPerSample===2?this.rawData:this.encodeS16LE()}};function lr(t){dA("%cLoading Wave samples...",c.recognized);let A=0;for(;t.chunkData.currentIndex<t.chunkData.length;){let e=AA(t.chunkData);this.verifyHeader(e,"LIST"),this.verifyText(j(e.chunkData,4),"wave");let n=[];for(;e.chunkData.currentIndex<e.chunkData.length;)n.push(AA(e.chunkData));let s=n.find(G=>G.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");let r=U(s.chunkData,2),i=U(s.chunkData,2);if(i!==1)throw new Error(`Only mono samples are supported. Fmt reports ${i} channels`);let a=U(s.chunkData,4);U(s.chunkData,4),U(s.chunkData,2);let I=U(s.chunkData,2)/8,l=n.find(G=>G.header==="data");l||this.parsingError("No data chunk in the WAVE chunk!");let E=_A(n,"INFO"),C=`Unnamed ${A}`;if(E){let G=AA(E.chunkData);for(;G.header!=="INAM"&&E.chunkData.currentIndex<E.chunkData.length;)G=AA(E.chunkData);G.header==="INAM"&&(C=j(G.chunkData,G.size).trim())}let B=60,f=0,u=0,M=l.size/I-1,F=0,k=n.find(G=>G.header==="wsmp");if(k){U(k.chunkData,4),B=U(k.chunkData,2),f=Ke(k.chunkData[k.chunkData.currentIndex++],k.chunkData[k.chunkData.currentIndex++]);let G=Math.trunc(f/100);if(B+=G,f-=G*100,F=(U(k.chunkData,4)|0)/-655360,U(k.chunkData,4),U(k.chunkData,4)===1){U(k.chunkData,8),u=U(k.chunkData,4);let eA=U(k.chunkData,4);M=u+eA}}else H("No wsmp chunk in wave... using sane defaults.");this.samples.push(new Rn(C,a,B,f,u,M,F,l,r,I)),A++,y(`%cLoaded sample %c${C}`,c.info,c.recognized)}q()}var qe=class extends Te{constructor(A){super(),this.dataArray=new T(A),Ie("%cParsing DLS...",c.info),this.dataArray||(q(),this.parsingError("No data provided!"));let e=AA(this.dataArray,!1);this.verifyHeader(e,"riff"),this.verifyText(j(this.dataArray,4).toLowerCase(),"dls ");let n=[];for(;this.dataArray.currentIndex<this.dataArray.length;)n.push(AA(this.dataArray));this.soundFontInfo.ifil="2.1",this.soundFontInfo.isng="E-mu 10K2",this.soundFontInfo.INAM="Unnamed DLS",this.soundFontInfo.IENG="Unknown",this.soundFontInfo.IPRD="SpessaSynth DLS",this.soundFontInfo.ICRD=new Date().toDateString();let s=_A(n,"INFO");if(s)for(;s.chunkData.currentIndex<s.chunkData.length;){let o=AA(s.chunkData);this.soundFontInfo[o.header]=j(o.chunkData,o.size)}this.soundFontInfo.ICMT=this.soundFontInfo.ICMT||"(No description)",this.soundFontInfo.ISBJ&&(this.soundFontInfo.ICMT+=`
14
14
  `+this.soundFontInfo.ISBJ,delete this.soundFontInfo.ISBJ),this.soundFontInfo.ICMT+=`
15
15
  Converted from DLS to SF2 with SpessaSynth`;for(let[o,I]of Object.entries(this.soundFontInfo))y(`%c"${o}": %c"${I}"`,c.info,c.recognized);let r=n.find(o=>o.header==="colh");r||(q(),this.parsingError("No colh chunk!")),this.instrumentAmount=U(r.chunkData,4),y(`%cInstruments amount: %c${this.instrumentAmount}`,c.info,c.recognized);let i=_A(n,"wvpl");i||(q(),this.parsingError("No wvpl chunk!")),this.readDLSSamples(i);let a=_A(n,"lins");a||(q(),this.parsingError("No lins chunk!")),this.readDLSInstrumentList(a),this.flush(),y(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets,
16
16
  %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,c.info,c.recognized,c.info,c.recognized,c.info,c.recognized,c.info,c.recognized,c.info),q()}verifyHeader(A,...e){for(let n of e)if(A.header.toLowerCase()===n.toLowerCase())return;q(),this.parsingError(`Invalid DLS chunk header! Expected "${e.toString()}" got "${A.header.toLowerCase()}"`)}verifyText(A,e){A.toLowerCase()!==e.toLowerCase()&&(q(),this.parsingError(`FourCC error: Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"`))}parsingError(A){throw new Error(`DLS parse error: ${A} The file may be corrupted.`)}destroySoundBank(){super.destroySoundBank(),delete this.dataArray}};qe.prototype.readDLSInstrumentList=gr;qe.prototype.readDLSInstrument=cr;qe.prototype.readLart=hr;qe.prototype.readDLSSamples=lr;var ks=class extends Y{constructor(A){super();let e=A.currentIndex;this.generatorType=A[e+1]<<8|A[e],this.generatorValue=Ke(A[e+2],A[e+3]),A.currentIndex+=4}};function Fs(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;)A.push(new ks(t.chunkData));return A.pop(),A}var Gn=class extends tt{constructor(A){super(A)}getInstrument(A){let e=this.generators.find(n=>n.generatorType===g.instrument);e&&this.setInstrument(A[e.generatorValue])}};function Br(t,A,e,n,s){let r=t.gen,i=t.mod,a=0,o=0;for(let I of s)for(let l=0;l<I.zonesCount;l++){let E=r[o++],C=r[o],B=A.slice(E,C),f=i[a++],u=i[a],S=e.slice(f,u);if(B.find(M=>M.generatorType===g.instrument)!==void 0){let M=I.createZone();M.addGenerators(...B),M.addModulators(...S),M.getInstrument(n)}else I.globalZone.addGenerators(...B),I.globalZone.addModulators(...S)}}var ws=class extends he{zoneStartIndex;zonesCount=0;constructor(A,e){super(e),this.presetName=j(A.chunkData,20).replace(/\d{3}:\d{3}/,""),this.program=U(A.chunkData,2),this.bank=U(A.chunkData,2),this.zoneStartIndex=U(A.chunkData,2),this.library=U(A.chunkData,4),this.genre=U(A.chunkData,4),this.morphology=U(A.chunkData,4)}createZone(){let A=new Gn(this);return this.presetZones.push(A),A}};function Rs(t,A){let e=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let n=new ws(t,A);if(e.length>0){let s=e[e.length-1];s.zonesCount=n.zoneStartIndex-s.zoneStartIndex}e.push(n)}return e.pop(),e}var Mn=class extends Le{constructor(A){super(A)}getSample(A){let e=this.generators.find(n=>n.generatorType===g.sampleID);e&&this.setSample(A[e.generatorValue])}};function dr(t,A,e,n,s){let r=t.gen,i=t.mod,a=0,o=0;for(let I of s)for(let l=0;l<I.zonesCount;l++){let E=r[o++],C=r[o],B=A.slice(E,C),f=i[a++],u=i[a],S=e.slice(f,u);if(B.find(M=>M.generatorType===g.sampleID)){let M=I.createZone();M.addGenerators(...B),M.addModulators(...S),M.getSample(n)}else I.globalZone.addGenerators(...B),I.globalZone.addModulators(...S)}}var Gs=class extends Ce{zoneStartIndex;zonesCount=0;constructor(A){super(),this.instrumentName=j(A.chunkData,20),this.zoneStartIndex=U(A.chunkData,2)}createZone(){let A=new Mn(this);return this.instrumentZones.push(A),A}};function Ms(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let e=new Gs(t);if(A.length>0){let n=A[A.length-1];n.zonesCount=e.zoneStartIndex-n.zoneStartIndex}A.push(e)}return A.pop(),A}function xn(t){let A=[];for(;t.chunkData.length>t.chunkData.currentIndex;){let e=t.chunkData,n=U(e,2),s=U(e,2),r=Ke(e[e.currentIndex++],e[e.currentIndex++]),i=U(e,2),a=U(e,2);A.push(new pA(n,i,s,r,a))}return A.pop(),A}function Vt(t){let A=[],e=[];for(;t.chunkData.length>t.chunkData.currentIndex;)e.push(U(t.chunkData,2)),A.push(U(t.chunkData,2));return{mod:A,gen:e}}var Nn=class extends Te{instruments=[];presets=[];constructor(A,e=!0){super(),e&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead.");let n=new T(A);Ie("%cParsing SoundFont...",c.info),n||(q(),this.parsingError("No data provided!"));let s=AA(n,!1);this.verifyHeader(s,"riff");let r=j(n,4).toLowerCase();if(r!=="sfbk"&&r!=="sfpk")throw q(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${r}"`);let i=r==="sfpk",a=AA(n);this.verifyHeader(a,"list");let o=j(a.chunkData,4);if(o!=="INFO")throw q(),new SyntaxError(`Invalid soundFont! Expected "INFO" or "${o}"`);let I;for(;a.chunkData.length>a.chunkData.currentIndex;){let D=AA(a.chunkData),b;switch(D.header.toLowerCase()){case"ifil":case"iver":b=`${U(D.chunkData,2)}.${U(D.chunkData,2)}`,this.soundFontInfo[D.header]=b;break;case"icmt":b=j(D.chunkData,D.chunkData.length,void 0,!1),this.soundFontInfo[D.header]=b;break;case"dmod":let _=xn(D);b=`Modulators: ${_.length}`,this.defaultModulators=_,this.customDefaultModulators=!0,this.soundFontInfo[D.header]=b;break;case"list":j(D.chunkData,4)==="xdta"&&(y("%cExtended SF2 found!",c.recognized),I=D);break;default:b=j(D.chunkData,D.chunkData.length),this.soundFontInfo[D.header]=b}y(`%c"${D.header}": %c"${b}"`,c.info,c.recognized)}let l=I!==void 0,E={};l&&(E.phdr=AA(I.chunkData),E.pbag=AA(I.chunkData),E.pmod=AA(I.chunkData),E.pgen=AA(I.chunkData),E.inst=AA(I.chunkData),E.ibag=AA(I.chunkData),E.imod=AA(I.chunkData),E.igen=AA(I.chunkData),E.shdr=AA(I.chunkData));let C=AA(n,!1);this.verifyHeader(C,"list"),this.verifyText(j(n,4),"sdta"),y("%cVerifying smpl chunk...",c.warn);let B=AA(n,!1);this.verifyHeader(B,"smpl");let f;if(i){y("%cSF2Pack detected, attempting to decode the smpl chunk...",c.info);try{f=ce.decode(n.buffer.slice(n.currentIndex,n.currentIndex+C.size-12)).data[0]}catch(D){throw q(),new Error(`SF2Pack Ogg Vorbis decode error: ${D}`)}y(`%cDecoded the smpl chunk! Length: %c${f.length}`,c.info,c.value)}else f=n,this.sampleDataStartIndex=n.currentIndex;y(`%cSkipping sample chunk, length: %c${C.size-12}`,c.info,c.value),n.currentIndex+=C.size-12,y("%cLoading preset data chunk...",c.warn);let u=AA(n);this.verifyHeader(u,"list"),j(u.chunkData,4);let S=AA(u.chunkData);this.verifyHeader(S,"phdr");let M=AA(u.chunkData);this.verifyHeader(M,"pbag");let F=AA(u.chunkData);this.verifyHeader(F,"pmod");let k=AA(u.chunkData);this.verifyHeader(k,"pgen");let G=AA(u.chunkData);this.verifyHeader(G,"inst");let N=AA(u.chunkData);this.verifyHeader(N,"ibag");let h=AA(u.chunkData);this.verifyHeader(h,"imod");let eA=AA(u.chunkData);this.verifyHeader(eA,"igen");let P=AA(u.chunkData);this.verifyHeader(P,"shdr"),n.currentIndex=this.sampleDataStartIndex;let v=ys(P,f,!l);if(l){let D=ys(E.shdr,new Float32Array(1),!1);D.length===v.length&&v.forEach((b,_)=>{b.sampleName+=D[_].sampleName,b.linkedSampleIndex|=D[_].linkedSampleIndex<<16})}v.forEach(D=>D.sampleName=D.sampleName.trim()),this.samples.push(...v);let sA=Fs(eA),rA=xn(h),$=Ms(G);if(l){let D=Ms(E.inst);D.length===$.length&&($.forEach((b,_)=>{b.instrumentName+=D[_].instrumentName,b.zoneStartIndex|=D[_].zoneStartIndex}),$.forEach((b,_)=>{_<$.length-1&&(b.zonesCount=$[_+1].zoneStartIndex-b.zoneStartIndex)}))}$.forEach(D=>D.instrumentName=D.instrumentName.trim()),this.instruments.push(...$);let IA=Vt(N);if(l){let D=Vt(E.ibag);for(let b=0;b<IA.mod.length;b++)IA.mod[b]|=D.mod[b]<<16;for(let b=0;b<IA.gen.length;b++)IA.gen[b]|=D.gen[b]<<16}dr(IA,sA,rA,this.samples,this.instruments);let uA=Fs(k),CA=xn(F),X=Rs(S,this);if(l){let D=Rs(E.phdr,this);D.length===X.length&&(X.forEach((b,_)=>{b.presetName+=D[_].presetName,b.zoneStartIndex|=D[_].zoneStartIndex}),X.forEach((b,_)=>{_<X.length-1&&(b.zonesCount=X[_+1].zoneStartIndex-b.zoneStartIndex)}))}X.forEach(D=>D.presetName===D.presetName.trim()),this.addPresets(...X);let L=Vt(M);if(l){let D=Vt(E.pbag);for(let b=0;b<L.mod.length;b++)L.mod[b]|=D.mod[b]<<16;for(let b=0;b<L.gen.length;b++)L.gen[b]|=D.gen[b]<<16}Br(L,uA,CA,this.instruments,this.presets),this.flush(),y(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets,