spessasynth_lib 3.14.0 → 3.14.1

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.14.0",
3
+ "version": "3.14.1",
4
4
  "description": "No compromise MIDI and SoundFont2 Synthesizer library",
5
5
  "browser": "index.js",
6
6
  "types": "@types/index.d.ts",
@@ -133,6 +133,11 @@ export class Preset {
133
133
  return memorized;
134
134
  }
135
135
 
136
+ if(this.presetZones.length < 1)
137
+ {
138
+ return [];
139
+ }
140
+
136
141
  function isInRange(min, max, number) {
137
142
  return number >= min && number <= max;
138
143
  }
@@ -191,6 +196,10 @@ export class Preset {
191
196
 
192
197
  presetZonesInRange.forEach(zone =>
193
198
  {
199
+ if(zone.instrument.instrumentZones.length < 1)
200
+ {
201
+ return;
202
+ }
194
203
  let presetGenerators = zone.generators;
195
204
  let presetModulators = zone.modulators;
196
205
  /**
@@ -7,7 +7,7 @@ var Ht=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>(
7
7
  Transform type: ${this.transformType}
8
8
 
9
9
 
10
- `}};function OA(e,A,t,s,o){return e<<10|A<<9|t<<8|s<<7|o}var At=960,et=lA.concave,As=[new aA({srcEnum:OA(et,0,1,0,P.noteOnVelocity),dest:B.initialAttenuation,amt:At,secSrcEnum:0,transform:0}),new aA({srcEnum:129,dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(et,0,1,1,p.mainVolume),dest:B.initialAttenuation,amt:At,secSrcEnum:0,transform:0}),new aA({srcEnum:13,dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new aA({srcEnum:526,dest:B.fineTune,amt:12700,secSrcEnum:16,transform:0}),new aA({srcEnum:650,dest:B.pan,amt:1e3,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(et,0,1,1,p.expressionController),dest:B.initialAttenuation,amt:At,secSrcEnum:0,transform:0}),new aA({srcEnum:219,dest:B.reverbEffectsSend,amt:200,secSrcEnum:0,transform:0}),new aA({srcEnum:221,dest:B.chorusEffectsSend,amt:200,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(lA.linear,0,0,0,P.polyPressure),dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(lA.linear,0,0,1,p.effects2Depth),dest:B.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(lA.linear,1,0,1,p.releaseTime),dest:B.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(lA.linear,1,0,1,p.brightness),dest:B.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0})];function tt(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new aA(e.chunkData));return A}var st=class{constructor(A,t){this.generatorZoneStartIndex=K(A,2),this.modulatorZoneStartIndex=K(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.zoneID=t,this.keyRange={min:0,max:127},this.velRange={min:0,max:127},this.isGlobal=!0,this.useCount=0,this.generators=[],this.modulators=[]}deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;t<this.generatorZoneStartIndex+this.generatorZoneSize;t++)this.generators.push(A[t])}getModulators(A){for(let t=this.modulatorZoneStartIndex;t<this.modulatorZoneStartIndex+this.modulatorZoneSize;t++)this.modulators.push(A[t])}getSample(A){let t=this.generators.find(s=>s.generatorType===B.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===B.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===B.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function es(e,A,t,s){let o=[],r=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let C=new st(e.chunkData,r);if(o.length>0){let a=C.modulatorZoneStartIndex-o[o.length-1].modulatorZoneStartIndex,Q=C.generatorZoneStartIndex-o[o.length-1].generatorZoneStartIndex;o[o.length-1].setZoneSize(a,Q),o[o.length-1].getGenerators(A),o[o.length-1].getModulators(t),o[o.length-1].getSample(s),o[o.length-1].getKeyRange(),o[o.length-1].getVelRange()}o.push(C),r++}return o.length>1&&o.pop(),o}var ot=class{constructor(A,t){this.generatorZoneStartIndex=K(A,2),this.modulatorZoneStartIndex=K(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.zoneID=t,this.keyRange={min:0,max:127},this.velRange={min:0,max:127},this.isGlobal=!0,this.generators=[],this.modulators=[]}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}deleteZone(){this.isGlobal||this.instrument.removeUseCount()}getGenerators(A){for(let t=this.generatorZoneStartIndex;t<this.generatorZoneStartIndex+this.generatorZoneSize;t++)this.generators.push(A[t])}getModulators(A){for(let t=this.modulatorZoneStartIndex;t<this.modulatorZoneStartIndex+this.modulatorZoneSize;t++)this.modulators.push(A[t])}getInstrument(A){let t=this.generators.find(s=>s.generatorType===B.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===B.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===B.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ts(e,A,t,s){let o=[],r=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let C=new ot(e.chunkData,r);if(o.length>0){let a=C.modulatorZoneStartIndex-o[o.length-1].modulatorZoneStartIndex,Q=C.generatorZoneStartIndex-o[o.length-1].generatorZoneStartIndex;o[o.length-1].setZoneSize(a,Q),o[o.length-1].getGenerators(A),o[o.length-1].getModulators(t),o[o.length-1].getInstrument(s),o[o.length-1].getKeyRange(),o[o.length-1].getVelRange()}o.push(C),r++}return o.length>1&&o.pop(),o}var nt=class{constructor(A){this.presetName=X(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=K(A.chunkData,2),this.bank=K(A.chunkData,2),this.presetZoneStartIndex=K(A.chunkData,2),this.presetZonesAmount=0,this.presetZones=[],this.foundSamplesAndGenerators=[];for(let t=0;t<128;t++)this.foundSamplesAndGenerators[t]=[];this.library=K(A.chunkData,4),this.genre=K(A.chunkData,4),this.morphology=K(A.chunkData,4)}getPresetZones(A,t){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;s<this.presetZonesAmount+this.presetZoneStartIndex;s++)this.presetZones.push(t[s])}deletePreset(){this.presetZones.forEach(A=>A.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,t){for(let s=A;s<t+1;s++)for(let o=0;o<128;o++)this.getSamplesAndGenerators(s,o).forEach(r=>{r.sample.isSampleLoaded||r.sample.getAudioData()})}preloadSpecific(A,t){this.getSamplesAndGenerators(A,t).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,t){let s=this.foundSamplesAndGenerators[A][t];if(s)return s;function o(m,d,u){return u>=m&&u<=d}function r(m,d){return m.modulatorSource===d.modulatorSource&&m.modulatorDestination===d.modulatorDestination&&m.modulationSecondarySrc===d.modulationSecondarySrc&&m.transformType===d.transformType}function C(m,d){m.push(...d.filter(u=>!m.find(F=>F.generatorType===u.generatorType)))}function a(m,d){m.push(...d.filter(u=>!m.find(F=>r(u,F))))}let Q=[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],c=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(m=>o(m.keyRange.min,m.keyRange.max,A)&&o(m.velRange.min,m.velRange.max,t)&&!m.isGlobal).forEach(m=>{let d=m.generators,u=m.modulators,F=m.instrument.instrumentZones[0].isGlobal?[...m.instrument.instrumentZones[0].generators]:[],k=m.instrument.instrumentZones[0].isGlobal?[...m.instrument.instrumentZones[0].modulators]:[];m.instrument.instrumentZones.filter(Y=>o(Y.keyRange.min,Y.keyRange.max,A)&&o(Y.velRange.min,Y.velRange.max,t)&&!Y.isGlobal).forEach(Y=>{let b=[...Y.generators],_=[...Y.modulators];C(d,h),C(b,F),a(u,c),a(_,k),a(_,As);let J=[..._];for(let I=0;I<u.length;I++){let V=u[I],q=J.findIndex(iA=>r(V,iA));q!==-1?J[q]=J[q].sumTransform(V):J.push(V)}Q.push({instrumentGenerators:b,presetGenerators:d,modulators:J,sample:Y.sample,sampleID:Y.generators.find(I=>I.generatorType===B.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=Q,Q}};function ss(e,A){let t=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let s=new nt(e);if(t.length>0){let o=s.presetZoneStartIndex-t[t.length-1].presetZoneStartIndex;t[t.length-1].getPresetZones(o,A)}t.push(s)}return t.length>1&&t.pop(),t}function os(){let e=4;for(let s of this.instruments)e+=s.instrumentZones.reduce((o,r)=>(r.generators=r.generators.filter(C=>C.generatorType!==B.sampleID&&C.generatorType!==B.keyRange&&C.generatorType!==B.velRange),(r.velRange.max!==127||r.velRange.min!==0)&&r.generators.unshift({generatorType:B.velRange,generatorValue:r.velRange.max<<8|r.velRange.min}),(r.keyRange.max!==127||r.keyRange.min!==0)&&r.generators.unshift({generatorType:B.keyRange,generatorValue:r.keyRange.max<<8|r.keyRange.min}),r.isGlobal||r.generators.push({generatorType:B.sampleID,generatorValue:this.samples.indexOf(r.sample)}),r.generators.length*4+o),0);let A=new U(e),t=0;for(let s of this.instruments)for(let o of s.instrumentZones){o.generatorZoneStartIndex=t;for(let r of o.generators)x(A,r.generatorType),x(A,r.generatorValue),t++}return gA(A,0),W(new O("igen",A.length,A))}function ns(e,A,t,s,o){let r=this.samples.map((h,c)=>{t&&h.compressSample(s,o);let f=h.getRawData();return y(`%cEncoded sample %c${c}. ${h.sampleName}%c of %c${this.samples.length}`,i.info,i.recognized,i.info,i.recognized),f}),C=this.samples.reduce((h,c,f)=>h+r[f].length+46,0),a=new U(C);this.samples.forEach((h,c)=>{let f=r[c],m,d,u=f.length;h.isCompressed?(m=a.currentIndex,d=m+f.length):(m=a.currentIndex/2,d=m+f.length/2,u+=46),e.push(m),a.set(f,a.currentIndex),a.currentIndex+=u,A.push(d)});let Q=W(new O("smpl",a.length,a),new U([115,100,116,97]));return W(new O("LIST",Q.length,Q))}function Is(e,A){let s=new U(46*(this.samples.length+1));return this.samples.forEach((o,r)=>{uA(s,o.sampleName,20);let C=e[r];gA(s,C);let a=A[r];gA(s,a);let Q=o.sampleLoopStartIndex/2+C,h=o.sampleLoopEndIndex/2+C;o.isCompressed&&(Q-=C,h-=C),gA(s,Q),gA(s,h),gA(s,o.sampleRate),s[s.currentIndex++]=o.samplePitch,s[s.currentIndex++]=o.samplePitchCorrection,x(s,o.sampleLink),x(s,o.sampleType)}),uA(s,"EOS",46),W(new O("shdr",s.length,s))}function rs(){let e=10;for(let s of this.instruments)e+=s.instrumentZones.reduce((o,r)=>r.modulators.length*10+o,0);let A=new U(e),t=0;for(let s of this.instruments)for(let o of s.instrumentZones){o.modulatorZoneStartIndex=t;for(let r of o.modulators)x(A,r.modulatorSource),x(A,r.modulatorDestination),x(A,r.transformAmount),x(A,r.modulationSecondarySrc),x(A,r.transformType),t++}return zA(A,0,10),W(new O("imod",A.length,A))}function gs(){let e=this.instruments.reduce((r,C)=>C.instrumentZones.length*4+r,4),A=new U(e),t=0,s=0,o=0;for(let r of this.instruments){r.instrumentZoneIndex=t;for(let C of r.instrumentZones)C.zoneID=t,x(A,s),x(A,o),s+=C.generators.length,o+=C.modulators.length,t++}return x(A,s),x(A,o),W(new O("ibag",A.length,A))}function is(){let e=this.instruments.length*22+22,A=new U(e),t=0,s=0;for(let o of this.instruments)uA(A,o.instrumentName,20),x(A,t),t+=o.instrumentZones.length,o.instrumentID=s,s++;return uA(A,"EOI",20),x(A,t),W(new O("inst",A.length,A))}function as(){let e=4;for(let s of this.presets)e+=s.presetZones.reduce((o,r)=>(r.generators=r.generators.filter(C=>C.generatorType!==B.instrument&&C.generatorType!==B.keyRange&&C.generatorType!==B.velRange),(r.velRange.max!==127||r.velRange.min!==0)&&r.generators.unshift({generatorType:B.velRange,generatorValue:r.velRange.max<<8|r.velRange.min}),(r.keyRange.max!==127||r.keyRange.min!==0)&&r.generators.unshift({generatorType:B.keyRange,generatorValue:r.keyRange.max<<8|r.keyRange.min}),r.isGlobal||r.generators.push({generatorType:B.instrument,generatorValue:this.instruments.indexOf(r.instrument)}),r.generators.length*4+o),0);let A=new U(e),t=0;for(let s of this.presets)for(let o of s.presetZones){o.generatorZoneStartIndex=t;for(let r of o.generators)x(A,r.generatorType),x(A,r.generatorValue);t+=o.generators.length}return x(A,0),x(A,0),W(new O("pgen",A.length,A))}function Cs(){let e=10;for(let s of this.presets)e+=s.presetZones.reduce((o,r)=>r.modulators.length*10+o,0);let A=new U(e),t=0;for(let s of this.presets)for(let o of s.presetZones){o.modulatorZoneStartIndex=t;for(let r of o.modulators)x(A,r.modulatorSource),x(A,r.modulatorDestination),x(A,r.transformAmount),x(A,r.modulationSecondarySrc),x(A,r.transformType),t++}return zA(A,0,10),W(new O("pmod",A.length,A))}function Es(){let e=this.presets.reduce((r,C)=>C.presetZones.length*4+r,4),A=new U(e),t=0,s=0,o=0;for(let r of this.presets){r.presetZoneStartIndex=t;for(let C of r.presetZones)C.zoneID=t,x(A,s),x(A,o),s+=C.generators.length,o+=C.modulators.length,t++}return x(A,s),x(A,o),W(new O("pbag",A.length,A))}function Bs(){let e=this.presets.length*38+38,A=new U(e),t=0;for(let s of this.presets)uA(A,s.presetName,20),x(A,s.program),x(A,s.bank),x(A,t),gA(A,s.library),gA(A,s.genre),gA(A,s.morphology),t+=s.presetZones.length;return uA(A,"EOP",20),x(A,0),x(A,0),x(A,t),gA(A,0),gA(A,0),gA(A,0),W(new O("phdr",A.length,A))}var sn={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Qs(e=sn){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");HA("%cSaving soundfont...",i.info),y(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,i.info,i.recognized,i.info,i.recognized),y("%cWriting INFO...",i.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.compress&&(this.soundFontInfo.ifil="3.0");for(let[_,J]of Object.entries(this.soundFontInfo))if(_==="ifil"||_==="iver"){let I=parseInt(J.split(".")[0]),V=parseInt(J.split(".")[1]),q=new U(4);x(q,I),x(q,V),A.push(W(new O(_,4,q)))}else{let I=new U(J.length);uA(I,J),A.push(W(new O(_,J.length,I)))}let t=Ie([new U([73,78,70,79]),...A]),s=W(new O("LIST",t.length,t));y("%cWriting SDTA...",i.info);let o=[],r=[],C=ns.call(this,o,r,e?.compress,e?.compressionQuality||.5,e.compressionFunction);y("%cWriting PDTA...",i.info),y("%cWriting SHDR...",i.info);let a=Is.call(this,o,r);y("%cWriting IGEN...",i.info);let Q=os.call(this);y("%cWriting IMOD...",i.info);let h=rs.call(this);y("%cWriting IBAG...",i.info);let c=gs.call(this);y("%cWriting INST...",i.info);let f=is.call(this),m=as.call(this);y("%cWriting PMOD...",i.info);let d=Cs.call(this);y("%cWriting PBAG...",i.info);let u=Es.call(this);y("%cWriting PHDR...",i.info);let F=Bs.call(this),k=Ie([new U([112,100,116,97]),F,u,d,m,f,c,h,Q,a]),T=W(new O("LIST",k.length,k));y("%cWriting the output file...",i.info);let Y=Ie([new U([115,102,98,107]),s,C,T]),b=W(new O("RIFF",Y.length,Y));return y(`%cSaved succesfully! Final file size: %c${b.length}`,i.info,i.recognized),eA(),b}var qA=class e{constructor(A){if(A.presets){this.presets=A.presets,this.soundFontInfo=A.info;return}if(this.dataArray=new U(A),Xe("%cParsing SoundFont...",i.info),!this.dataArray)throw eA(),new TypeError("No data!");let t=tA(this.dataArray,!1);this.verifyHeader(t,"riff"),this.verifyText(X(this.dataArray,4),"sfbk");let s=tA(this.dataArray);for(this.verifyHeader(s,"list"),X(s.chunkData,4),this.soundFontInfo={};s.chunkData.length>s.chunkData.currentIndex;){let I=tA(s.chunkData),V;switch(I.header.toLowerCase()){case"ifil":case"iver":V=`${K(I.chunkData,2)}.${K(I.chunkData,2)}`;break;case"icmt":V=X(I.chunkData,I.chunkData.length,void 0,!1);break;default:V=X(I.chunkData,I.chunkData.length)}y(`%c"${I.header}": %c"${V}"`,i.info,i.recognized),this.soundFontInfo[I.header]=V}let o=tA(this.dataArray,!1);this.verifyHeader(o,"list"),this.verifyText(X(this.dataArray,4),"sdta"),y("%cVerifying smpl chunk...",i.warn);let r=tA(this.dataArray,!1);this.verifyHeader(r,"smpl"),this.sampleDataStartIndex=this.dataArray.currentIndex,y(`%cSkipping sample chunk, length: %c${o.size-12}`,i.info,i.value),this.dataArray.currentIndex+=o.size-12,y("%cLoading preset data chunk...",i.warn);let C=tA(this.dataArray);this.verifyHeader(C,"list"),X(C.chunkData,4);let a=tA(C.chunkData);this.verifyHeader(a,"phdr");let Q=tA(C.chunkData);this.verifyHeader(Q,"pbag");let h=tA(C.chunkData);this.verifyHeader(h,"pmod");let c=tA(C.chunkData);this.verifyHeader(c,"pgen");let f=tA(C.chunkData);this.verifyHeader(f,"inst");let m=tA(C.chunkData);this.verifyHeader(m,"ibag");let d=tA(C.chunkData);this.verifyHeader(d,"imod");let u=tA(C.chunkData);this.verifyHeader(u,"igen");let F=tA(C.chunkData);this.verifyHeader(F,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples=zt(F,this.dataArray);let k=je(u),T=tt(d),Y=es(m,k,T,this.samples);this.instruments=$t(f,Y);let b=je(c),_=tt(h),J=ts(Q,b,_,this.instruments);this.presets=ss(a,J),this.presets.sort((I,V)=>I.program-V.program+(I.bank-V.bank)),y(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets,
10
+ `}};function OA(e,A,t,s,o){return e<<10|A<<9|t<<8|s<<7|o}var At=960,et=lA.concave,As=[new aA({srcEnum:OA(et,0,1,0,P.noteOnVelocity),dest:B.initialAttenuation,amt:At,secSrcEnum:0,transform:0}),new aA({srcEnum:129,dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(et,0,1,1,p.mainVolume),dest:B.initialAttenuation,amt:At,secSrcEnum:0,transform:0}),new aA({srcEnum:13,dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new aA({srcEnum:526,dest:B.fineTune,amt:12700,secSrcEnum:16,transform:0}),new aA({srcEnum:650,dest:B.pan,amt:1e3,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(et,0,1,1,p.expressionController),dest:B.initialAttenuation,amt:At,secSrcEnum:0,transform:0}),new aA({srcEnum:219,dest:B.reverbEffectsSend,amt:200,secSrcEnum:0,transform:0}),new aA({srcEnum:221,dest:B.chorusEffectsSend,amt:200,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(lA.linear,0,0,0,P.polyPressure),dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(lA.linear,0,0,1,p.effects2Depth),dest:B.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(lA.linear,1,0,1,p.releaseTime),dest:B.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new aA({srcEnum:OA(lA.linear,1,0,1,p.brightness),dest:B.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0})];function tt(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new aA(e.chunkData));return A}var st=class{constructor(A,t){this.generatorZoneStartIndex=K(A,2),this.modulatorZoneStartIndex=K(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.zoneID=t,this.keyRange={min:0,max:127},this.velRange={min:0,max:127},this.isGlobal=!0,this.useCount=0,this.generators=[],this.modulators=[]}deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;t<this.generatorZoneStartIndex+this.generatorZoneSize;t++)this.generators.push(A[t])}getModulators(A){for(let t=this.modulatorZoneStartIndex;t<this.modulatorZoneStartIndex+this.modulatorZoneSize;t++)this.modulators.push(A[t])}getSample(A){let t=this.generators.find(s=>s.generatorType===B.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===B.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===B.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function es(e,A,t,s){let o=[],r=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let C=new st(e.chunkData,r);if(o.length>0){let a=C.modulatorZoneStartIndex-o[o.length-1].modulatorZoneStartIndex,Q=C.generatorZoneStartIndex-o[o.length-1].generatorZoneStartIndex;o[o.length-1].setZoneSize(a,Q),o[o.length-1].getGenerators(A),o[o.length-1].getModulators(t),o[o.length-1].getSample(s),o[o.length-1].getKeyRange(),o[o.length-1].getVelRange()}o.push(C),r++}return o.length>1&&o.pop(),o}var ot=class{constructor(A,t){this.generatorZoneStartIndex=K(A,2),this.modulatorZoneStartIndex=K(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.zoneID=t,this.keyRange={min:0,max:127},this.velRange={min:0,max:127},this.isGlobal=!0,this.generators=[],this.modulators=[]}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}deleteZone(){this.isGlobal||this.instrument.removeUseCount()}getGenerators(A){for(let t=this.generatorZoneStartIndex;t<this.generatorZoneStartIndex+this.generatorZoneSize;t++)this.generators.push(A[t])}getModulators(A){for(let t=this.modulatorZoneStartIndex;t<this.modulatorZoneStartIndex+this.modulatorZoneSize;t++)this.modulators.push(A[t])}getInstrument(A){let t=this.generators.find(s=>s.generatorType===B.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===B.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===B.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ts(e,A,t,s){let o=[],r=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let C=new ot(e.chunkData,r);if(o.length>0){let a=C.modulatorZoneStartIndex-o[o.length-1].modulatorZoneStartIndex,Q=C.generatorZoneStartIndex-o[o.length-1].generatorZoneStartIndex;o[o.length-1].setZoneSize(a,Q),o[o.length-1].getGenerators(A),o[o.length-1].getModulators(t),o[o.length-1].getInstrument(s),o[o.length-1].getKeyRange(),o[o.length-1].getVelRange()}o.push(C),r++}return o.length>1&&o.pop(),o}var nt=class{constructor(A){this.presetName=X(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=K(A.chunkData,2),this.bank=K(A.chunkData,2),this.presetZoneStartIndex=K(A.chunkData,2),this.presetZonesAmount=0,this.presetZones=[],this.foundSamplesAndGenerators=[];for(let t=0;t<128;t++)this.foundSamplesAndGenerators[t]=[];this.library=K(A.chunkData,4),this.genre=K(A.chunkData,4),this.morphology=K(A.chunkData,4)}getPresetZones(A,t){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;s<this.presetZonesAmount+this.presetZoneStartIndex;s++)this.presetZones.push(t[s])}deletePreset(){this.presetZones.forEach(A=>A.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,t){for(let s=A;s<t+1;s++)for(let o=0;o<128;o++)this.getSamplesAndGenerators(s,o).forEach(r=>{r.sample.isSampleLoaded||r.sample.getAudioData()})}preloadSpecific(A,t){this.getSamplesAndGenerators(A,t).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,t){let s=this.foundSamplesAndGenerators[A][t];if(s)return s;if(this.presetZones.length<1)return[];function o(m,d,u){return u>=m&&u<=d}function r(m,d){return m.modulatorSource===d.modulatorSource&&m.modulatorDestination===d.modulatorDestination&&m.modulationSecondarySrc===d.modulationSecondarySrc&&m.transformType===d.transformType}function C(m,d){m.push(...d.filter(u=>!m.find(F=>F.generatorType===u.generatorType)))}function a(m,d){m.push(...d.filter(u=>!m.find(F=>r(u,F))))}let Q=[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],c=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(m=>o(m.keyRange.min,m.keyRange.max,A)&&o(m.velRange.min,m.velRange.max,t)&&!m.isGlobal).forEach(m=>{if(m.instrument.instrumentZones.length<1)return;let d=m.generators,u=m.modulators,F=m.instrument.instrumentZones[0].isGlobal?[...m.instrument.instrumentZones[0].generators]:[],k=m.instrument.instrumentZones[0].isGlobal?[...m.instrument.instrumentZones[0].modulators]:[];m.instrument.instrumentZones.filter(Y=>o(Y.keyRange.min,Y.keyRange.max,A)&&o(Y.velRange.min,Y.velRange.max,t)&&!Y.isGlobal).forEach(Y=>{let b=[...Y.generators],_=[...Y.modulators];C(d,h),C(b,F),a(u,c),a(_,k),a(_,As);let J=[..._];for(let I=0;I<u.length;I++){let V=u[I],q=J.findIndex(iA=>r(V,iA));q!==-1?J[q]=J[q].sumTransform(V):J.push(V)}Q.push({instrumentGenerators:b,presetGenerators:d,modulators:J,sample:Y.sample,sampleID:Y.generators.find(I=>I.generatorType===B.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=Q,Q}};function ss(e,A){let t=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let s=new nt(e);if(t.length>0){let o=s.presetZoneStartIndex-t[t.length-1].presetZoneStartIndex;t[t.length-1].getPresetZones(o,A)}t.push(s)}return t.length>1&&t.pop(),t}function os(){let e=4;for(let s of this.instruments)e+=s.instrumentZones.reduce((o,r)=>(r.generators=r.generators.filter(C=>C.generatorType!==B.sampleID&&C.generatorType!==B.keyRange&&C.generatorType!==B.velRange),(r.velRange.max!==127||r.velRange.min!==0)&&r.generators.unshift({generatorType:B.velRange,generatorValue:r.velRange.max<<8|r.velRange.min}),(r.keyRange.max!==127||r.keyRange.min!==0)&&r.generators.unshift({generatorType:B.keyRange,generatorValue:r.keyRange.max<<8|r.keyRange.min}),r.isGlobal||r.generators.push({generatorType:B.sampleID,generatorValue:this.samples.indexOf(r.sample)}),r.generators.length*4+o),0);let A=new U(e),t=0;for(let s of this.instruments)for(let o of s.instrumentZones){o.generatorZoneStartIndex=t;for(let r of o.generators)x(A,r.generatorType),x(A,r.generatorValue),t++}return gA(A,0),W(new O("igen",A.length,A))}function ns(e,A,t,s,o){let r=this.samples.map((h,c)=>{t&&h.compressSample(s,o);let f=h.getRawData();return y(`%cEncoded sample %c${c}. ${h.sampleName}%c of %c${this.samples.length}`,i.info,i.recognized,i.info,i.recognized),f}),C=this.samples.reduce((h,c,f)=>h+r[f].length+46,0),a=new U(C);this.samples.forEach((h,c)=>{let f=r[c],m,d,u=f.length;h.isCompressed?(m=a.currentIndex,d=m+f.length):(m=a.currentIndex/2,d=m+f.length/2,u+=46),e.push(m),a.set(f,a.currentIndex),a.currentIndex+=u,A.push(d)});let Q=W(new O("smpl",a.length,a),new U([115,100,116,97]));return W(new O("LIST",Q.length,Q))}function Is(e,A){let s=new U(46*(this.samples.length+1));return this.samples.forEach((o,r)=>{uA(s,o.sampleName,20);let C=e[r];gA(s,C);let a=A[r];gA(s,a);let Q=o.sampleLoopStartIndex/2+C,h=o.sampleLoopEndIndex/2+C;o.isCompressed&&(Q-=C,h-=C),gA(s,Q),gA(s,h),gA(s,o.sampleRate),s[s.currentIndex++]=o.samplePitch,s[s.currentIndex++]=o.samplePitchCorrection,x(s,o.sampleLink),x(s,o.sampleType)}),uA(s,"EOS",46),W(new O("shdr",s.length,s))}function rs(){let e=10;for(let s of this.instruments)e+=s.instrumentZones.reduce((o,r)=>r.modulators.length*10+o,0);let A=new U(e),t=0;for(let s of this.instruments)for(let o of s.instrumentZones){o.modulatorZoneStartIndex=t;for(let r of o.modulators)x(A,r.modulatorSource),x(A,r.modulatorDestination),x(A,r.transformAmount),x(A,r.modulationSecondarySrc),x(A,r.transformType),t++}return zA(A,0,10),W(new O("imod",A.length,A))}function gs(){let e=this.instruments.reduce((r,C)=>C.instrumentZones.length*4+r,4),A=new U(e),t=0,s=0,o=0;for(let r of this.instruments){r.instrumentZoneIndex=t;for(let C of r.instrumentZones)C.zoneID=t,x(A,s),x(A,o),s+=C.generators.length,o+=C.modulators.length,t++}return x(A,s),x(A,o),W(new O("ibag",A.length,A))}function is(){let e=this.instruments.length*22+22,A=new U(e),t=0,s=0;for(let o of this.instruments)uA(A,o.instrumentName,20),x(A,t),t+=o.instrumentZones.length,o.instrumentID=s,s++;return uA(A,"EOI",20),x(A,t),W(new O("inst",A.length,A))}function as(){let e=4;for(let s of this.presets)e+=s.presetZones.reduce((o,r)=>(r.generators=r.generators.filter(C=>C.generatorType!==B.instrument&&C.generatorType!==B.keyRange&&C.generatorType!==B.velRange),(r.velRange.max!==127||r.velRange.min!==0)&&r.generators.unshift({generatorType:B.velRange,generatorValue:r.velRange.max<<8|r.velRange.min}),(r.keyRange.max!==127||r.keyRange.min!==0)&&r.generators.unshift({generatorType:B.keyRange,generatorValue:r.keyRange.max<<8|r.keyRange.min}),r.isGlobal||r.generators.push({generatorType:B.instrument,generatorValue:this.instruments.indexOf(r.instrument)}),r.generators.length*4+o),0);let A=new U(e),t=0;for(let s of this.presets)for(let o of s.presetZones){o.generatorZoneStartIndex=t;for(let r of o.generators)x(A,r.generatorType),x(A,r.generatorValue);t+=o.generators.length}return x(A,0),x(A,0),W(new O("pgen",A.length,A))}function Cs(){let e=10;for(let s of this.presets)e+=s.presetZones.reduce((o,r)=>r.modulators.length*10+o,0);let A=new U(e),t=0;for(let s of this.presets)for(let o of s.presetZones){o.modulatorZoneStartIndex=t;for(let r of o.modulators)x(A,r.modulatorSource),x(A,r.modulatorDestination),x(A,r.transformAmount),x(A,r.modulationSecondarySrc),x(A,r.transformType),t++}return zA(A,0,10),W(new O("pmod",A.length,A))}function Es(){let e=this.presets.reduce((r,C)=>C.presetZones.length*4+r,4),A=new U(e),t=0,s=0,o=0;for(let r of this.presets){r.presetZoneStartIndex=t;for(let C of r.presetZones)C.zoneID=t,x(A,s),x(A,o),s+=C.generators.length,o+=C.modulators.length,t++}return x(A,s),x(A,o),W(new O("pbag",A.length,A))}function Bs(){let e=this.presets.length*38+38,A=new U(e),t=0;for(let s of this.presets)uA(A,s.presetName,20),x(A,s.program),x(A,s.bank),x(A,t),gA(A,s.library),gA(A,s.genre),gA(A,s.morphology),t+=s.presetZones.length;return uA(A,"EOP",20),x(A,0),x(A,0),x(A,t),gA(A,0),gA(A,0),gA(A,0),W(new O("phdr",A.length,A))}var sn={compress:!1,compressionQuality:.5,compressionFunction:void 0};function Qs(e=sn){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");HA("%cSaving soundfont...",i.info),y(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,i.info,i.recognized,i.info,i.recognized),y("%cWriting INFO...",i.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.compress&&(this.soundFontInfo.ifil="3.0");for(let[_,J]of Object.entries(this.soundFontInfo))if(_==="ifil"||_==="iver"){let I=parseInt(J.split(".")[0]),V=parseInt(J.split(".")[1]),q=new U(4);x(q,I),x(q,V),A.push(W(new O(_,4,q)))}else{let I=new U(J.length);uA(I,J),A.push(W(new O(_,J.length,I)))}let t=Ie([new U([73,78,70,79]),...A]),s=W(new O("LIST",t.length,t));y("%cWriting SDTA...",i.info);let o=[],r=[],C=ns.call(this,o,r,e?.compress,e?.compressionQuality||.5,e.compressionFunction);y("%cWriting PDTA...",i.info),y("%cWriting SHDR...",i.info);let a=Is.call(this,o,r);y("%cWriting IGEN...",i.info);let Q=os.call(this);y("%cWriting IMOD...",i.info);let h=rs.call(this);y("%cWriting IBAG...",i.info);let c=gs.call(this);y("%cWriting INST...",i.info);let f=is.call(this),m=as.call(this);y("%cWriting PMOD...",i.info);let d=Cs.call(this);y("%cWriting PBAG...",i.info);let u=Es.call(this);y("%cWriting PHDR...",i.info);let F=Bs.call(this),k=Ie([new U([112,100,116,97]),F,u,d,m,f,c,h,Q,a]),T=W(new O("LIST",k.length,k));y("%cWriting the output file...",i.info);let Y=Ie([new U([115,102,98,107]),s,C,T]),b=W(new O("RIFF",Y.length,Y));return y(`%cSaved succesfully! Final file size: %c${b.length}`,i.info,i.recognized),eA(),b}var qA=class e{constructor(A){if(A.presets){this.presets=A.presets,this.soundFontInfo=A.info;return}if(this.dataArray=new U(A),Xe("%cParsing SoundFont...",i.info),!this.dataArray)throw eA(),new TypeError("No data!");let t=tA(this.dataArray,!1);this.verifyHeader(t,"riff"),this.verifyText(X(this.dataArray,4),"sfbk");let s=tA(this.dataArray);for(this.verifyHeader(s,"list"),X(s.chunkData,4),this.soundFontInfo={};s.chunkData.length>s.chunkData.currentIndex;){let I=tA(s.chunkData),V;switch(I.header.toLowerCase()){case"ifil":case"iver":V=`${K(I.chunkData,2)}.${K(I.chunkData,2)}`;break;case"icmt":V=X(I.chunkData,I.chunkData.length,void 0,!1);break;default:V=X(I.chunkData,I.chunkData.length)}y(`%c"${I.header}": %c"${V}"`,i.info,i.recognized),this.soundFontInfo[I.header]=V}let o=tA(this.dataArray,!1);this.verifyHeader(o,"list"),this.verifyText(X(this.dataArray,4),"sdta"),y("%cVerifying smpl chunk...",i.warn);let r=tA(this.dataArray,!1);this.verifyHeader(r,"smpl"),this.sampleDataStartIndex=this.dataArray.currentIndex,y(`%cSkipping sample chunk, length: %c${o.size-12}`,i.info,i.value),this.dataArray.currentIndex+=o.size-12,y("%cLoading preset data chunk...",i.warn);let C=tA(this.dataArray);this.verifyHeader(C,"list"),X(C.chunkData,4);let a=tA(C.chunkData);this.verifyHeader(a,"phdr");let Q=tA(C.chunkData);this.verifyHeader(Q,"pbag");let h=tA(C.chunkData);this.verifyHeader(h,"pmod");let c=tA(C.chunkData);this.verifyHeader(c,"pgen");let f=tA(C.chunkData);this.verifyHeader(f,"inst");let m=tA(C.chunkData);this.verifyHeader(m,"ibag");let d=tA(C.chunkData);this.verifyHeader(d,"imod");let u=tA(C.chunkData);this.verifyHeader(u,"igen");let F=tA(C.chunkData);this.verifyHeader(F,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples=zt(F,this.dataArray);let k=je(u),T=tt(d),Y=es(m,k,T,this.samples);this.instruments=$t(f,Y);let b=je(c),_=tt(h),J=ts(Q,b,_,this.instruments);this.presets=ss(a,J),this.presets.sort((I,V)=>I.program-V.program+(I.bank-V.bank)),y(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets,
11
11
  %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,i.info,i.recognized,i.info,i.recognized,i.info,i.recognized,i.info,i.recognized,i.info),eA()}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(t=>{t.isGlobal||t.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw eA(),new SyntaxError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw eA(),new SyntaxError(`Invalid soundFont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}getPreset(A,t){let s=this.presets.find(o=>o.bank===A&&o.program===t);return s||(s=this.presets.find(o=>o.program===t&&o.bank!==128),A===128&&(s=this.presets.find(o=>o.bank===128&&o.program===t),s||(s=this.presets.find(o=>o.bank===128))),s&&H(`%cPreset ${A}.${t} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,i.warn,i.recognized)),s||(H(`Preset ${t} not found. Defaulting to`,this.presets[0].presetName),s=this.presets[0]),s}getPresetByName(A){let t=this.presets.find(s=>s.presetName===A);return t||(H("Preset not found. Defaulting to:",this.presets[0].presetName),t=this.presets[0]),t}static mergeSoundfonts(...A){let t=A.shift(),s=t.presets;for(;A.length;)A.shift().presets.forEach(r=>{s.find(C=>C.bank===r.bank&&C.program===r.program)===void 0&&s.push(r)});return new e({presets:s,info:t.soundFontInfo})}};qA.prototype.write=Qs;var wA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},dA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function KA(e,A){let t=0;for(let s=8*(A-1);s>=0;s-=8)t|=e[e.currentIndex++]<<s;return t>>>0}function hs(e,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=re(e.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=s,t.status){case S.noteOn:let o=e.messageData[1];if(o>0)this.synth.noteOn(t.channel,e.messageData[0],o),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:o,startTime:this.currentTime});else{this.synth.noteOff(t.channel,e.messageData[0]);let C=this.playingNotes.findIndex(a=>a.midiNote===e.messageData[0]&&a.channel===t.channel);C!==-1&&this.playingNotes.splice(C,1)}break;case S.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let r=this.playingNotes.findIndex(C=>C.midiNote===e.messageData[0]&&C.channel===t.channel);r!==-1&&this.playingNotes.splice(r,1);break;case S.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case S.controllerChange:this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case S.programChange:this.synth.programChange(t.channel,e.messageData[0]);break;case S.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case S.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case S.systemExclusive:this.synth.systemExclusive(e.messageData,s);break;case S.setTempo:this.oneTickToSeconds=60/(on(e)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),H("invalid tempo! falling back to 120 BPM"));break;case S.timeSignature:case S.endOfTrack:case S.midiChannelPrefix:case S.songPosition:case S.activeSensing:case S.keySignature:break;case S.text:case S.lyric:case S.copyright:case S.trackName:case S.marker:case S.cuePoint:case S.instrumentName:this.post(dA.textEvent,[e.messageData,t.status]);break;case S.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case S.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:H(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(S).find(C=>S[C]===t.status)}`,i.warn,i.unrecognized,i.warn,i.value);break}}function cs(){for(let e=0;e<16;e++)this.synth.createWorkletChannel(!0),e===kA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function on(e){return e.messageData.currentIndex=0,6e7/KA(e.messageData,3)}function ls(){let e=this.currentTime;for(;this.playedTime<e;){let A=this._findFirstEventIndex(),t=this.tracks[A][this.eventIndex[A]];if(this._processEvent(t,A),this.eventIndex[A]++,A=this._findFirstEventIndex(),this.tracks[A].length<=this.eventIndex[A]){if(this.loop){this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}let s=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(s.ticks-t.ticks),this.midiData.loop.end<=t.ticks&&this.loop){this.setTimeTicks(this.midiData.loop.start);return}else if(e>=this.duration){if(this.loop){this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function fs(){let e=0,A=1/0;return this.tracks.forEach((t,s)=>{this.eventIndex[s]>=t.length||t[this.eventIndex[s]].ticks<A&&(e=s,A=t[this.eventIndex[s]].ticks)}),e}var MA=new Int16Array(127);MA[p.mainVolume]=100;MA[p.expressionController]=127;MA[p.pan]=64;MA[p.releaseTime]=64;MA[p.brightness]=64;MA[p.effects1Depth]=40;function us(e,A=void 0){if(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIMessages){this.sendMIDIMessage([S.reset]);for(let a=0;a<me;a++)this.sendMIDIMessage([S.controllerChange|a,p.resetAllControllers,0])}this._resetTimers();let t=this.synth.workletProcessorChannels.length,s=Array(t).fill(8192),o=[];for(let a=0;a<t;a++)o.push({program:-1,bank:0,actualBank:0});let r=a=>a===p.dataDecrement||a===p.dataIncrement||a===p.dataEntryMsb||a===p.dataDecrement||a===p.lsbForControl6DataEntry||a===p.RPNLsb||a===p.RPNMsb||a===p.NRPNLsb||a===p.NRPNMsb||a===p.bankSelect||a===p.lsbForControl0BankSelect||a===p.resetAllControllers,C=[];for(let a=0;a<t;a++)C.push(Array.from(MA));for(;;){let a=this._findFirstEventIndex(),Q=this.tracks[a][this.eventIndex[a]];if(A!==void 0){if(Q.ticks>=A)break}else if(this.playedTime>=e)break;let h=re(Q.messageStatusByte),c=h.channel+(this.midiPortChannelOffsets[this.midiPorts[a]]||0);switch(h.status){case S.noteOn:case S.noteOff:case S.keySignature:break;case S.pitchBend:s[c]=Q.messageData[1]<<7|Q.messageData[0];break;case S.programChange:let m=o[c];m.program=Q.messageData[0],m.actualBank=m.bank;break;case S.controllerChange:let d=Q.messageData[0];if(r(d))if(this.sendMIDIMessages)this.sendMIDIMessage([S.controllerChange|c%16,d,Q.messageData[1]]);else{let u=Q.messageData[1];if(d===p.bankSelect){o[c].bank=u;break}this.synth.controllerChange(c,d,u)}else C[c]===void 0&&(C[c]=Array.from(MA)),C[c][d]=Q.messageData[1];break;default:this._processEvent(Q,a);break}this.eventIndex[a]++,a=this._findFirstEventIndex();let f=this.tracks[a][this.eventIndex[a]];if(f===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(f.ticks-Q.ticks)}if(this.sendMIDIMessages){for(let a=0;a<t;a++)if(this.sendMIDIMessage([S.pitchBend|a%16,s[a]&127,s[a]>>7]),C[a].forEach((Q,h)=>{Q!==MA[h]&&!r(h)&&this.sendMIDIMessage([S.controllerChange|a%16,h,Q])}),o[a].program>=0&&o[a].actualBank>=0){let Q=o[a].actualBank;this.sendMIDIMessage([S.controllerChange|a%16,p.bankSelect,Q]),this.sendMIDIMessage([S.programChange|a%16,o[a].program])}}else for(let a=0;a<t;a++)if(s[a]!==void 0&&this.synth.pitchWheel(a,s[a]>>7,s[a]&127),C[a]!==void 0&&C[a].forEach((Q,h)=>{Q!==MA[h]&&!r(h)&&this.synth.controllerChange(a,h,Q)}),o[a].program>=0&&o[a].actualBank>=0){let Q=o[a].actualBank;this.synth.controllerChange(a,p.bankSelect,Q),this.synth.programChange(a,o[a].program)}return!0}function ds(e=!1){if(this.midiData!==void 0){if(e){this.currentTime=0;return}if(this.currentTime>=this.duration){this.currentTime=0;return}if(this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),!this.sendMIDIMessages){let A=this.currentTime;this.playingNotes.forEach(t=>{let s=t.startTime-A;this.synth.noteOn(t.channel,t.midiNote,t.velocity,!1,!0,currentTime+s)})}this.setProcessHandler()}}function Se(e,A,t){if(A<=0)return 0;let s=e.find(r=>r.ticks<A),o=A-s.ticks;return Se(e,A-o,t)+o*60/(s.tempo*t)}function ms(e){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(dA.timeChange,currentTime-Se(this.midiData.tempoChanges,e,this.midiData.timeDivision));let A=this._playTo(0,e);this._recalculateStartTime(this.playedTime),A&&this.play()}function ps(e){this.absoluteStartTime=currentTime-e/this._playbackRate}var De=class{constructor(A){this.timeDivision=A.timeDivision,this.duration=A.duration,this.tempoChanges=A.tempoChanges,this.copyright=A.copyright,this.tracksAmount=A.tracksAmount,this.lyrics=A.lyrics,this.firstNoteOn=A.firstNoteOn,this.keyRange=A.keyRange,this.lastVoiceEventTick=A.lastVoiceEventTick,this.midiPorts=A.midiPorts,this.midiPortChannelOffsets=A.midiPortChannelOffsets,this.usedChannelsOnTrack=A.usedChannelsOnTrack,this.loop=A.loop,this.midiName=A.midiName,this.fileName=A.fileName,this.rawMidiName=A.rawMidiName,this.isEmbedded=A.embeddedSoundFont!==void 0,this.RMIDInfo=A.RMIDInfo,this.bankOffset=A.bankOffset}},li={duration:99999,firstNoteOn:0,loop:{start:0,end:123456},lastVoiceEventTick:123456,lyrics:[],copyright:"",midiPorts:[],midiPortChannelOffsets:[],tracksAmount:0,tempoChanges:[{ticks:0,tempo:120}],fileName:"NOT_LOADED.mid",midiName:"Loading...",rawMidiName:new Uint8Array([76,111,97,100,105,110,103,46,46,46]),usedChannelsOnTrack:[],timeDivision:0,keyRange:{min:0,max:127},isEmbedded:!1,RMIDInfo:void 0,bankOffset:0};function ke(e){let A=0;for(;e;){let t=e[e.currentIndex++];if(A=A<<7|t&127,t>>7!==1)break}return A}function ys(e=!1){let A={midiControllers:new Int16Array(It),lockedControllers:Array(It).fill(!1),customControllers:new Float32Array(Ss),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:EA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),channelVibrato:{delay:0,depth:0,rate:0},lockVibrato:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let t=0;t<128;t++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),e&&this.callEvent("newchannel",void 0)}var sA=128,It=147,UA=new Int16Array(It).fill(0);UA[p.mainVolume]=12800;UA[p.expressionController]=16256;UA[p.pan]=8192;UA[p.releaseTime]=8192;UA[p.brightness]=8192;UA[p.effects1Depth]=5120;UA[sA+P.pitchWheel]=8192;UA[sA+P.pitchWheelRange]=256;var EA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},$={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Ss=Object.keys($).length,rt=new Float32Array(Ss);rt[$.modulationMultiplier]=1;var we={name:"INAM",album:"IPRD",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",bankOffset:"DBNK"};var Fe=class{constructor(A,t=""){HA("%cParsing MIDI File...",i.info);let s=new U(A),o;this.embeddedSoundFont=void 0,this.RMIDInfo=void 0,this.bankOffset=0,this.copyright="";let r=!1;this.midiName="",this.rawMidiName=new Uint8Array(0);let C=!1,a=X(s,4);if(s.currentIndex-=4,a==="RIFF"){s.currentIndex+=8;let u=X(s,4,void 0,!1);if(u!=="RMID")throw eA(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${u}"`);let F=tA(s);if(F.header!=="data")throw eA(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${u}"`);for(o=F.chunkData;s.currentIndex<=s.length;){let k=s.currentIndex,T=tA(s,!0);if(T.header==="RIFF")X(T.chunkData,4)==="sfbk"&&(y("%cFound embedded soundfont!",i.recognized),this.embeddedSoundFont=s.slice(k,k+T.size).buffer);else if(T.header==="LIST"&&X(T.chunkData,4)==="INFO"){for(y("%cFound RMIDI INFO chunk!",i.recognized),this.RMIDInfo={};T.chunkData.currentIndex<=T.size;){let b=tA(T.chunkData,!0);this.RMIDInfo[b.header]=b.chunkData}this.RMIDInfo.ICOP&&(r=!0,this.copyright=X(this.RMIDInfo.ICOP,this.RMIDInfo.ICOP.length)),this.RMIDInfo.INAM&&(this.rawMidiName=this.RMIDInfo[we.name],this.midiName=X(this.rawMidiName,this.rawMidiName.length,void 0,!1),C=!0),this.bankOffset=1,this.RMIDInfo[we.bankOffset]&&(this.bankOffset=K(this.RMIDInfo[we.bankOffset],2))}}}else o=s;let Q=this.readMIDIChunk(o);if(Q.type!=="MThd")throw eA(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${Q.type}"`);if(Q.size!==6)throw eA(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${Q.size}`);this.format=KA(Q.data,2),this.tracksAmount=KA(Q.data,2),this.timeDivision=KA(Q.data,2),this.keyRange={min:127,max:0},this.lyrics=[],this.tempoChanges=[{ticks:0,tempo:120}];let h=null,c=null;this.lastVoiceEventTick=0,this.midiPorts=[];let f=0;this.midiPortChannelOffsets=[],this.usedChannelsOnTrack=[],this.tracks=[];for(let u=0;u<this.tracksAmount;u++){let F=[],k=this.readMIDIChunk(o),T=new Set;if(this.midiPorts.push(-1),k.type!=="MTrk")throw eA(),new SyntaxError(`Invalid track header! Expected "MTrk" got "${k.type}"`);let Y,b=0;for(this.format===2&&u>0&&(b+=this.tracks[u-1][this.tracks[u-1].length-1].ticks);k.data.currentIndex<k.size;){b+=ke(k.data);let _=k.data[k.data.currentIndex],J;if(Y!==void 0&&_<128)J=Y;else{if(!Y&&_<128)throw eA(),new SyntaxError(`Unexpected byte with no running byte. (${_})`);J=k.data[k.data.currentIndex++]}let I=Tt(J),V;switch(I){case-1:V=0;break;case-2:J=k.data[k.data.currentIndex++],V=ke(k.data);break;case-3:V=ke(k.data);break;default:if(b>this.lastVoiceEventTick&&(this.lastVoiceEventTick=b),V=Jt[J>>4],(J&240)===S.noteOn){T.add(I);let bA=k.data[k.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,bA),this.keyRange.max=Math.max(this.keyRange.max,bA)}Y=J;break}let q=new U(V),iA=k.data.slice(k.data.currentIndex,k.data.currentIndex+V);k.data.currentIndex+=V,q.set(iA,0);let mA=new _A(b,J,q);switch(F.push(mA),I){case-2:switch(J){case S.setTempo:this.tempoChanges.push({ticks:b,tempo:6e7/KA(iA,3)});break;case S.marker:switch(X(q,q.length).trim().toLowerCase()){default:break;case"start":case"loopstart":h=b;break;case"loopend":c=b}q.currentIndex=0;break;case S.midiPort:let CA=q[0];this.midiPorts[u]=CA,this.midiPortChannelOffsets[CA]===void 0&&(this.midiPortChannelOffsets[CA]=f,f+=16);break;case S.copyright:r||(this.copyright+=X(q,q.length,void 0,!1)+`
12
12
  `);break;case S.lyric:this.lyrics.push(q)}break;case-3:if(rA(q.slice(0,7)).trim()==="41 10 45 12 10 00 00"){let bA=q.slice(7,iA.length-3),CA=X(bA,bA.length)+`
13
13
  `;this.copyright+=CA,y(`%cDecoded Roland SC message! %c${CA}`,i.recognized,i.value)}break;default:if((J&240)===S.controllerChange)switch(q[0]){case 2:case 116:h=b;break;case 4:case 117:c===null?c=b:c=0;break}}}this.tracks.push(F),this.usedChannelsOnTrack.push(T),y(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,i.info,i.value,i.info,i.value)}let m=[];for(let u of this.tracks){let F=u.find(k=>(k.messageStatusByte&240)===S.noteOn);F&&m.push(F.ticks)}this.firstNoteOn=Math.min(...m),y(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}`,i.info,i.recognized),eA(),h!==null&&c===null?(h=this.firstNoteOn,c=this.lastVoiceEventTick):(h===null&&(h=this.firstNoteOn),(c===null||c===0)&&(c=this.lastVoiceEventTick));let d=0;for(let u of this.midiPorts)if(u!==-1){d=u;break}if(this.midiPorts=this.midiPorts.map(u=>u===-1?d:u),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.loop={start:h,end:c},!C)if(this.tracks.length>1){if(this.tracks[0].find(u=>u.messageStatusByte>=S.noteOn&&u.messageStatusByte<S.polyPressure)===void 0){let u=this.tracks[0].find(F=>F.messageStatusByte===S.trackName);u&&(this.rawMidiName=u.messageData,this.midiName=X(u.messageData,u.messageData.length,void 0,!1))}}else{let u=this.tracks[0].find(F=>F.messageStatusByte===S.trackName);u&&(this.rawMidiName=u.messageData,this.midiName=X(u.messageData,u.messageData.length,void 0,!1))}if(this.fileName=t,this.midiName=this.midiName.trim(),this.midiName.length===0){this.midiName=Yt(t),this.rawMidiName=new Uint8Array(this.midiName.length);for(let u=0;u<this.midiName.length;u++)this.rawMidiName[u]=this.midiName.charCodeAt(u)}this.tempoChanges.reverse(),this.duration=this._ticksToSeconds(this.lastVoiceEventTick)}readMIDIChunk(A){let t={};t.type=X(A,4),t.size=KA(A,4),t.data=new U(t.size);let s=A.slice(A.currentIndex,A.currentIndex+t.size);return t.data.set(s,0),A.currentIndex+=t.size,t}_ticksToSeconds(A){if(A<=0)return 0;let t=this.tempoChanges.find(o=>o.ticks<A),s=A-t.ticks;return this._ticksToSeconds(A-s)+s*60/(t.tempo*this.timeDivision)}};function Ds(e,A){HA("%cSearching for all used programs and keys...",i.info);let t=16+e.midiPortChannelOffsets.reduce((f,m)=>m>f?m:f),s=[];for(let f=0;f<t;f++){let m=f%16===kA?128:0;s.push({program:0,bank:m,drums:f%16===kA,string:`${m}:0`})}function o(f){let m=A.getPreset(f.bank,f.program);f.bank=m.bank,f.program=m.program,f.string=f.bank+":"+f.program,r[f.string]||(y(`%cDetected a new preset: %c${f.string}`,i.info,i.recognized),r[f.string]=new Set)}let r={},C=Array(e.tracks.length).fill(0),a=e.tracks.length;function Q(){let f=0,m=1/0;return e.tracks.forEach((d,u)=>{C[u]>=d.length||d[C[u]].ticks<m&&(f=u,m=d[C[u]].ticks)}),f}let h=e.midiPorts.slice(),c="gs";for(;a>0;){let f=Q(),m=e.tracks[f];if(C[f]>=m.length){a--;continue}let d=m[C[f]];if(C[f]++,d.messageStatusByte===S.midiPort){h[f]=d.messageData[0];continue}let u=d.messageStatusByte&240;if(u!==S.noteOn&&u!==S.controllerChange&&u!==S.programChange&&u!==S.systemExclusive)continue;let F=(d.messageStatusByte&15)+e.midiPortChannelOffsets[h[f]]||0,k=s[F];switch(u){case S.programChange:k.program=d.messageData[0],o(k);break;case S.controllerChange:if(d.messageData[0]!==p.bankSelect||c==="gs"&&k.drums)continue;let T=d.messageData[1],Y=Math.max(0,T-e.bankOffset);if(c==="xg"){let J=T===120||T===126||T===127;J!==k.drums?(k.drums=J,k.bank=k.drums?128:Y,o(k)):k.bank=k.drums?128:Y;continue}s[F].bank=Y;break;case S.noteOn:if(d.messageData[1]===0)continue;o(k),r[k.string].add(`${d.messageData[0]}-${d.messageData[1]}`);break;case S.systemExclusive:if(d.messageData[0]!==65||d.messageData[2]!==66||d.messageData[3]!==18||d.messageData[4]!==64||!(d.messageData[5]&16)||d.messageData[6]!==21){d.messageData[0]===67&&d.messageData[2]===76&&d.messageData[5]===126&&d.messageData[6]===0&&(c="xg");continue}let b=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][d.messageData[5]&15]+e.midiPortChannelOffsets[h[f]],_=!!(d.messageData[7]>0&&d.messageData[5]>>4);k=s[b],k.drums=_,k.bank=_?128:0,o(k);break}}for(let f of Object.keys(r))r[f].size===0&&(y(`%cDetected change but no keys for %c${f}`,i.info,i.value),delete r[f]);return eA(),r}function ks(e,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.length<this.midiPortChannelOffset+15&&this._addNewMidiPort(),this.midiPortChannelOffsets[A]=this.midiPortChannelOffset,this.midiPortChannelOffset+=16),this.midiPorts[e]=A}function ws(e){if(this.stop(),!e.tracks)throw"No tracks supplied!";if(this.oneTickToSeconds=60/(120*e.timeDivision),this.midiData=e,this.midiData.embeddedSoundFont!==void 0)y("%cEmbedded soundfont detected! Using it.",i.recognized),this.synth.soundfontBankOffset=this.midiData.bankOffset,this.synth.reloadSoundFont(this.midiData.embeddedSoundFont,!0),this.synth.overrideSoundfont.samples.forEach(A=>A.getAudioData());else{this.synth.overrideSoundfont&&this.synth.clearSoundFont(),HA("%cPreloading samples...",i.info);let A=Ds(this.midiData,this.synth.soundfont);for(let[t,s]of Object.entries(A)){let o=parseInt(t.split(":")[0]),r=parseInt(t.split(":")[1]),C=this.synth.getPreset(o,r);y(`%cPreloading used samples on %c${C.presetName}%c...`,i.info,i.recognized,i.info);for(let a of s){let Q=a.split("-");C.preloadSpecific(parseInt(Q[0]),parseInt(Q[1]))}}eA()}this.tracks=this.midiData.tracks,this.midiPorts=this.midiData.midiPorts,this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this.midiData.midiPorts.forEach((A,t)=>{this.assignMIDIPort(t,A)}),this.duration=this.midiData.duration,this.firstNoteTime=Se(this.midiData.tempoChanges,this.midiData.firstNoteOn,this.midiData.timeDivision),y(`%cTotal song time: ${Ze(Math.ceil(this.duration)).time}`,i.recognized),this.post(dA.songChange,[new De(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(H(`%cVery short song: (${Ze(Math.round(this.duration)).time}). Disabling loop!`,i.warn),this.loop=!1),this.play(!0)}function Fs(e){this.songs=e.reduce((A,t)=>{if(t.duration)return A.push(t),A;try{A.push(new Fe(t.binary,t.altName||""))}catch(s){return this.post(dA.midiError,s.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function Rs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Gs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}function xs(e,A){switch(e){default:break;case wA.loadNewSongList:this.loadNewSongList(A);break;case wA.pause:this.pause();break;case wA.play:this.play(A);break;case wA.stop:this.stop();break;case wA.setTime:this.currentTime=A;break;case wA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case wA.setPlaybackRate:this.playbackRate=A;break;case wA.setLoop:this.loop=A;break;case wA.changeSong:A?this.nextSong():this.previousSong();break;case wA.getMIDI:this.post(dA.getMIDI,this.midiData);break;case wA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Ns(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:cA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function Ms(e){this.post(dA.midiEvent,e)}var oA=class{constructor(A){this.synth=A,this.ignoreEvents=!1,this.sendMIDIMessages=!1,this.eventIndex=[],this.songIndex=0,this.playedTime=0,this.pausedTime=void 0,this.absoluteStartTime=currentTime,this._playbackRate=1,this.playingNotes=[],this.loop=!0,this.midiData=void 0,this.midiPorts=[],this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this._skipToFirstNoteOn=!0}set playbackRate(A){let t=this.currentTime;this._playbackRate=A,this.currentTime=t}get currentTime(){return this.pausedTime?this.pausedTime:(currentTime-this.absoluteStartTime)*this._playbackRate}set currentTime(A){if(A>this.duration||A<0){this._skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this._skipToFirstNoteOn&&A<this.firstNoteTime){this.setTimeTicks(this.midiData.firstNoteOn-1);return}this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(dA.timeChange,currentTime-A);let t=this._playTo(A);this._recalculateStartTime(A),t&&this.play()}pause(A=!1){if(this.paused){H("Already paused");return}this.pausedTime=this.currentTime,this.stop(),this.post(dA.pause,A)}stop(){this.clearProcessHandler();for(let A=0;A<16;A++)this.synth.controllerChange(A,p.sustainPedal,0);if(this.synth.stopAllChannels(),this.sendMIDIMessages)for(let A=0;A<me;A++)this.sendMIDIMessage([S.controllerChange|A,120,0]),this.sendMIDIMessage([S.controllerChange|A,123,0])}_resetTimers(){this.playedTime=0,this.eventIndex=Array(this.tracks.length).fill(0)}get paused(){return this.pausedTime!==void 0}setProcessHandler(){this.synth.processTickCallback=this._processTick.bind(this)}clearProcessHandler(){this.synth.processTickCallback=void 0}};oA.prototype.post=Ns;oA.prototype.sendMIDIMessage=Ms;oA.prototype.assignMIDIPort=ks;oA.prototype.processMessage=xs;oA.prototype._processEvent=hs;oA.prototype._addNewMidiPort=cs;oA.prototype._processTick=ls;oA.prototype._findFirstEventIndex=fs;oA.prototype.loadNewSequence=ws;oA.prototype.loadNewSongList=Fs;oA.prototype.nextSong=Rs;oA.prototype.previousSong=Gs;oA.prototype.play=ds;oA.prototype._playTo=us;oA.prototype.setTimeTicks=ms;oA.prototype._recalculateStartTime=ps;var gt=new Float32Array(30001);for(let e=0;e<gt.length;e++){let A=-15e3+e;gt[e]=Math.pow(2,A/1200)}function BA(e){return gt[e- -15e3]}var Re=-2e4,Us=16500,it=new Float32Array(Us-Re+1);for(let e=0;e<it.length;e++){let A=Re+e;it[e]=440*Math.pow(2,(A-6900)/1200)}function ie(e){return e<Re||e>Us?440*Math.pow(2,(e-6900)/1200):it[~~e-Re]}var Ct=-1660,nn=1600,at=new Float32Array((nn-Ct)*100+1);for(let e=0;e<at.length;e++){let A=(Ct*100+e)/100;at[e]=Math.pow(10,-A/20)}function RA(e){return at[Math.floor((e-Ct)*100)]}function Ge(e,A,t){if(t<e)return 0;let s=(t-e)/(1/A)-.25;return Math.abs(s-~~(s+.5))*4-1}var AA=16384,jA=new Float32Array(AA),$A=new Float32Array(AA);jA[0]=0;jA[AA-1]=1;$A[0]=0;$A[AA-1]=1;for(let e=1;e<AA-1;e++){let A=-.4166666666666667*Math.log(e/(AA-1))/Math.LN10;$A[e]=1-A,jA[AA-1-e]=A}function vA(e,A,t,s){switch(e&&(t=1-t),A){case lA.linear:return s?t*2-1:t;case lA.switch:return t=t>.5?1:0,s?t*2-1:t;case lA.concave:return s?(t=t*2-1,t<0?1-jA[~~(t*-AA)]-1:jA[~~t*AA]):jA[~~(t*AA)];case lA.convex:return s?(t=t*2-1,t<0?1-$A[~~(t*-AA)]-1:$A[~~(t*AA)]):$A[~~(t*AA)]}}var Et=1,Bt=new Float32Array(1e3);for(let e=0;e<Bt.length;e++)Bt[e]=vA(0,lA.convex,e/1e3,0);function bs(e,A){let t=BA(e.modulatedGenerators[B.attackModEnv]),s=BA(e.modulatedGenerators[B.decayModEnv]+(60-e.midiNote)*e.modulatedGenerators[B.keyNumToModEnvDecay]),o=BA(e.modulatedGenerators[B.holdModEnv]+(60-e.midiNote)*e.modulatedGenerators[B.keyNumToModEnvHold]);if(e.isInRelease&&e.releaseStartTime<A){let f=BA(e.modulatedGenerators[B.releaseModEnv]);return e.modulatedGenerators[B.releaseModEnv]<-7199?e.releaseStartModEnv:(1-(A-e.releaseStartTime)/f)*e.releaseStartModEnv}let r=1-e.modulatedGenerators[B.sustainModEnv]/1e3,C=BA(e.modulatedGenerators[B.delayModEnv])+e.startTime,a=t+C,Q=o+a,h=s+Q,c;return A<C?c=0:A<a?c=Bt[~~((1-(a-A)/t)*1e3)]:A<Q?c=Et:A<h?c=(1-(h-A)/s)*(r-Et)+Et:c=r,e.currentModEnvValue=c,c}function Ls(e,A,t){let s=e.sample.cursor,o=e.sample.loopingMode===1||e.sample.loopingMode===3&&!e.isInRelease,r=e.sample.loopEnd-e.sample.loopStart;if(o)for(let C=0;C<t.length;C++){for(;s>=e.sample.loopEnd;)s-=r;let a=~~s,Q=a+1;for(;Q>=e.sample.loopEnd;)Q-=r;let h=s-a,c=A[Q],f=A[a];t[C]=f+(c-f)*h,s+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=A.length&&(e.sample.end=A.length-1);for(let C=0;C<t.length;C++){let a=~~s,Q=a+1;if(Q>=e.sample.end){e.finished=!0;return}let h=s-a,c=A[Q],f=A[a];t[C]=f+(c-f)*h,s+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=s}function Hs(e,A,t,s,o,r,C,a,Q){if(!isNaN(t[0])){if(C>0){let h=r[0],c=r[1];C=Math.min(C,1e3);let f=C/500,m=e*f,d=A*f;for(let u=0;u<t.length;u++)h[u]+=m*t[u],c[u]+=d*t[u]}if(Q>0){let h=a[0],c=a[1];Q=Math.min(Q,1e3);let f=Q/500,m=e*f,d=A*f;for(let u=0;u<t.length;u++)h[u]+=m*t[u],c[u]+=d*t[u]}if(e>0)for(let h=0;h<t.length;h++)s[h]+=e*t[h];if(A>0)for(let h=0;h<t.length;h++)o[h]+=A*t[h]}}var Ts={attenuation:100,currentAttenuationDb:100,state:0,releaseStartDb:100,attackDuration:0,decayDuration:0,releaseDuration:0,sustainDb:0,delayEnd:0,attackEnd:0,holdEnd:0,decayEnd:0,currentReleaseGain:1},Js=.001,Ys=100,In=.005;function ZA(e){let A=e.volumeEnvelope;if(A.attackDuration=BA(e.modulatedGenerators[B.attackVolEnv]),A.decayDuration=BA(e.modulatedGenerators[B.decayVolEnv]+(60-e.midiNote)*e.modulatedGenerators[B.keyNumToVolEnvDecay]),A.releaseDuration=BA(e.modulatedGenerators[B.releaseVolEnv]),A.attenuation=e.modulatedGenerators[B.initialAttenuation]/10,A.sustainDb=e.volumeEnvelope.attenuation+e.modulatedGenerators[B.sustainVolEnv]/10,A.delayEnd=BA(e.modulatedGenerators[B.delayVolEnv])+e.startTime,A.attackEnd=A.attackDuration+A.delayEnd,A.holdEnd=BA(e.modulatedGenerators[B.holdVolEnv]+(60-e.midiNote)*e.modulatedGenerators[B.keyNumToVolEnvHold])+A.attackEnd,A.decayEnd=A.decayDuration+A.holdEnd,e.isInRelease)switch(A.state){case 0:A.releaseStartDb=0;break;case 1:let s=(1-(A.attackEnd-e.releaseStartTime)/A.attackDuration)*RA(A.attenuation);A.releaseStartDb=20*Math.log10(s)*-1;break;case 2:A.releaseStartDb=A.attenuation;break;case 3:A.releaseStartDb=(1-(A.decayEnd-e.releaseStartTime)/A.decayDuration)*(A.sustainDb-A.attenuation)+A.attenuation;break;case 4:A.releaseStartDb=A.sustainDb;break;default:A.releaseStartDb=A.currentAttenuationDb}}function qs(e,A,t,s,o,r){let C=s/10,a=e.volumeEnvelope;if(e.isInRelease){let c=r*10,f=a.releaseStartDb+C,m=t-e.releaseStartTime,d=Ys-f,u=a.currentReleaseGain;for(let F=0;F<A.length;F++){let k=m/a.releaseDuration*d+f;u=RA(k+C),a.currentReleaseGain+=(u-a.currentReleaseGain)*c,A[F]*=a.currentReleaseGain,m+=o}a.currentReleaseGain<=In&&(e.finished=!0);return}let Q=t,h=0;switch(a.state){case 0:for(;Q<a.delayEnd;)if(a.currentAttenuationDb=Ys,A[h]=0,Q+=o,++h>=A.length)return;a.state++;case 1:for(;Q<a.attackEnd;){let f=(1-(a.attackEnd-Q)/a.attackDuration)*RA(a.attenuation+C);if(A[h]*=f,a.currentAttenuationDb=a.attenuation,Q+=o,++h>=A.length)return}a.state++;case 2:for(;Q<a.holdEnd;){let c=a.attenuation+C;if(a.currentAttenuationDb+=(c-a.currentAttenuationDb)*r,A[h]*=RA(a.currentAttenuationDb),Q+=o,++h>=A.length)return}a.state++;case 3:for(;Q<a.decayEnd;){let c=(1-(a.decayEnd-Q)/a.decayDuration)*(a.sustainDb-a.attenuation)+a.attenuation+C;if(a.currentAttenuationDb+=(c-a.currentAttenuationDb)*r,A[h]*=RA(a.currentAttenuationDb),Q+=o,++h>=A.length)return}a.state++;case 4:for(;;){let c=a.sustainDb+C;if(a.currentAttenuationDb+=(c-a.currentAttenuationDb)*r,A[h]*=RA(a.currentAttenuationDb),++h>=A.length)return}}}var Ks={a0:0,a1:0,a2:0,a3:0,a4:0,x1:0,x2:0,y1:0,y2:0,reasonanceCb:0,reasonanceGain:1,cutoffCents:13500,cutoffHz:2e4};function Ps(e,A,t){if(!(t>13499)){(e.filter.cutoffCents!==t||e.filter.reasonanceCb!==e.modulatedGenerators[B.initialFilterQ])&&(e.filter.cutoffCents=t,e.filter.reasonanceCb=e.modulatedGenerators[B.initialFilterQ],rn(e));for(let s=0;s<A.length;s++){let o=A[s],r=e.filter.a0*o+e.filter.a1*e.filter.x1+e.filter.a2*e.filter.x2-e.filter.a3*e.filter.y1-e.filter.a4*e.filter.y2;e.filter.x2=e.filter.x1,e.filter.x1=o,e.filter.y2=e.filter.y1,e.filter.y1=r,A[s]=r}}}function rn(e){e.filter.cutoffHz=ie(e.filter.cutoffCents),e.filter.cutoffHz>.45*sampleRate&&(e.filter.cutoffHz=.45*sampleRate);let A=e.filter.reasonanceCb/10-3.01;e.filter.reasonanceGain=RA(-1*A);let t=1/Math.sqrt(e.filter.reasonanceGain),s=2*Math.PI*e.filter.cutoffHz/sampleRate,o=Math.cos(s),r=Math.sin(s)/(2*e.filter.reasonanceGain),C=(1-o)*t,a=C/2,Q=a,h=1+r,c=-2*o,f=1-r;e.filter.a0=a/h,e.filter.a1=C/h,e.filter.a2=Q/h,e.filter.a3=c/h,e.filter.a4=f/h}var Vs=Math.PI/2,Os=.01;function vs(e,A,t,s,o,r){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.releaseStartModEnv=A.currentModEnvValue,A.isInRelease=!0,ZA(A),A.volumeEnvelope.currentReleaseGain=RA(A.volumeEnvelope.currentAttenuationDb)),A.modulatedGenerators[B.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let C=A.modulatedGenerators[B.fineTune]+e.customControllers[$.channelTuning]+e.customControllers[$.channelTransposeFine]+e.customControllers[$.masterTuning]+e.channelOctaveTuning[A.midiNote%12],a=A.modulatedGenerators[B.coarseTune]+e.customControllers[$.channelTuningSemitones];C+=(A.targetKey-A.sample.rootKey)*A.modulatedGenerators[B.scaleTuning];let Q=A.modulatedGenerators[B.vibLfoToPitch];if(Q!==0){let q=A.startTime+BA(A.modulatedGenerators[B.delayVibLFO]),iA=ie(A.modulatedGenerators[B.freqVibLFO]),mA=Ge(q,iA,currentTime);mA&&(C+=mA*(Q*e.customControllers[$.modulationMultiplier]))}let h=A.modulatedGenerators[B.initialFilterFc],c=A.modulatedGenerators[B.modLfoToPitch],f=A.modulatedGenerators[B.modLfoToVolume],m=A.modulatedGenerators[B.modLfoToFilterFc],d=0;if(c+m+f!==0){let q=A.startTime+BA(A.modulatedGenerators[B.delayModLFO]),iA=ie(A.modulatedGenerators[B.freqModLFO]),mA=Ge(q,iA,currentTime);C+=mA*(c*e.customControllers[$.modulationMultiplier]),d=mA*f,h+=mA*m}if(e.channelVibrato.depth>0){let q=Ge(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);q&&(C+=q*e.channelVibrato.depth)}let u=A.modulatedGenerators[B.modEnvToPitch],F=A.modulatedGenerators[B.modEnvToFilterFc],k=bs(A,currentTime);h+=k*F,C+=k*u;let T=~~(C+a*100);T!==A.currentTuningCents&&(A.currentTuningCents=T,A.currentTuningCalculated=Math.pow(2,T/1200));let Y=(Math.max(-500,Math.min(500,A.modulatedGenerators[B.pan]))+500)/1e3,b=new Float32Array(t.length);Ls(A,this.workletDumpedSamplesList[A.sample.sampleID],b),Ps(A,b,h),qs(A,b,currentTime,d,this.sampleTime,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(Y-A.currentPan)*this.panSmoothingFactor;let _=Math.cos(Vs*A.currentPan)*this.panLeft,J=Math.sin(Vs*A.currentPan)*this.panRight,I=this.oneOutputMode?0:A.modulatedGenerators[B.reverbEffectsSend],V=this.oneOutputMode?0:A.modulatedGenerators[B.chorusEffectsSend];Hs(_,J,b,t,s,o,I,r,V)}function gn(e,A){let t=0;return e.drumChannel&&(t+=5),A.isInRelease&&(t-=5),t+=A.velocity/25,t-=A.volumeEnvelope.state,A.isInRelease&&(t-=5),t-=A.volumeEnvelope.currentAttenuationDb/50,t}function Zs(e){let A=[];for(let s of this.workletProcessorChannels)for(let o of s.voices)if(!o.finished){let r=gn(s,o);A.push({channel:s,voice:o,priority:r})}A.sort((s,o)=>s.priority-o.priority);let t=A.slice(0,e);for(let{channel:s,voice:o}of t){let r=s.voices.indexOf(o);r>-1&&s.voices.splice(r,1)}}function Xs(e){e.releaseStartTime=currentTime,e.releaseStartTime-e.startTime<Qt&&(e.releaseStartTime=e.startTime+Qt)}var Qt=.07,ht=1,R=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=FA,this.processTickCallback=void 0,this.sequencer=new oA(this),this.transposition=0,this.soundfontBankOffset=0,this.masterGain=ht,this.midiVolume=1,this.voiceCap=Zt,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfont=new qA(A.processorOptions.soundfont)}catch(t){throw this.post({messageType:cA.soundfontError,messageData:t}),t}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletDumpedSamplesList=[],this.workletProcessorChannels=[];for(let t=0;t<A.processorOptions.midiChannels;t++)this.createWorkletChannel(!1);this.workletProcessorChannels[kA].preset=this.drumPreset,this.workletProcessorChannels[kA].drumChannel=!0,this.sampleTime=1/sampleRate,this.volumeEnvelopeSmoothingFactor=Js*(sampleRate/44100),this.panSmoothingFactor=Os*(sampleRate/44100),this.system=pe,this.totalVoicesAmount=0,this.port.onmessage=t=>this.handleMessage(t.data),A.processorOptions.startRenderingData&&(A.processorOptions.startRenderingData.snapshot&&(this.applySynthesizerSnapshot(A.processorOptions.startRenderingData.snapshot),this.resetAllControllers()),y("%cRendering enabled! Starting render.",i.info),A.processorOptions.startRenderingData.parsedMIDI&&(this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]),this.sequencer.loop=!1)),JA.isInitialized.then(()=>{this.post({messageType:cA.ready,messageData:void 0}),y("%cSpessaSynth is ready!",i.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){y({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){this.processTickCallback&&this.processTickCallback();let s=0;return this.workletProcessorChannels.forEach((o,r)=>{if(o.voices.length<1||o.isMuted)return;let C,a,Q,h,c;if(this.oneOutputMode){let m=t[0];C=r%16*2,a=m[C],Q=m[C+1]}else C=r%this._outputsAmount+2,a=t[C][0],Q=t[C][1],h=t[0],c=t[1];let f=o.voices;o.voices=[],f.forEach(m=>{this.renderVoice(o,m,a,Q,h,c),m.finished||o.voices.push(m)}),s+=f.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};function Ws(e){let A=e.messageData,t=e.channelNumber,s={};switch(t>=0&&(s=this.workletProcessorChannels[t]),e.messageType){case Z.noteOn:this.noteOn(t,A[0],A[1],A[2]);break;case Z.noteOff:this.noteOff(t,A);break;case Z.pitchWheel:this.pitchWheel(t,A[0],A[1]);break;case Z.ccChange:this.controllerChange(t,A[0],A[1],A[2]);break;case Z.customcCcChange:s.customControllers[A[0]]=A[1];break;case Z.killNote:this.killNote(t,A);break;case Z.programChange:this.programChange(t,A[0],A[1]);break;case Z.channelPressure:this.channelPressure(t,A);break;case Z.polyPressure:this.polyPressure(t,A[0],A[1]);break;case Z.ccReset:t===FA?this.resetAllControllers():this.resetControllers(t);break;case Z.systemExclusive:this.systemExclusive(A);break;case Z.setChannelVibrato:if(t===FA)for(let C=0;C<this.workletProcessorChannels.length;C++)A.rate===-1?this.disableAndLockVibrato(C):this.setVibrato(C,A.depth,A.rate,A.delay);A.rate===-1?this.disableAndLockVibrato(t):this.setVibrato(t,A.depth,A.rate,A.delay);break;case Z.reloadSoundFont:this.reloadSoundFont(A);break;case Z.stopAll:t===FA?this.stopAllChannels(A===1):this.stopAll(t,A===1);break;case Z.killNotes:this.voiceKilling(A);break;case Z.muteChannel:this.muteChannel(t,A);break;case Z.addNewChannel:this.createWorkletChannel(!0);break;case Z.debugMessage:this.debugMessage();break;case Z.setMasterParameter:let o=A[0],r=A[1];switch(o){case ge.masterPan:this.setMasterPan(r);break;case ge.mainVolume:this.setMasterGain(r);break;case ge.voicesCap:this.voiceCap=r;break}break;case Z.setDrums:this.setDrums(t,A);break;case Z.transpose:t===FA?this.transposeAllChannels(A[0],A[1]):this.transposeChannel(t,A[0],A[1]);break;case Z.highPerformanceMode:this.highPerformanceMode=A;break;case Z.lockController:A[0]===FA?s.lockPreset=A[1]:s.lockedControllers[A[0]]=A[1];break;case Z.sequencerSpecific:this.sequencer.processMessage(A.messageType,A.messageData);break;case Z.requestSynthesizerSnapshot:this.sendSynthesizerSnapshot();break;case Z.setLogLevel:Vt(A[0],A[1],A[2],A[3]);break;default:H("Unrecognized event:",A);break}}function _s(e,A){this.enableEventSystem&&this.post({messageType:cA.eventCall,messageData:{eventName:e,eventData:A}})}function zs(e){this.enableEventSystem&&this.port.postMessage(e)}function js(){if(!this.enableEventSystem)return;let e=this.workletProcessorChannels.map(A=>{let t=(A.midiControllers[sA+P.pitchWheelRange]>>7)+(A.midiControllers[sA+P.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[sA+P.pitchWheel],pitchBendRangeSemitones:t,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:cA.channelProperties,messageData:e})}function an(e,A,t){if(e===127&&A===127&&t===127)return null;let s=8.1758,o=e,r=A<<7|t,C=o*100+r/16384*100;return s*Math.pow(2,C/1200)}function $s(e,A=0){let t=e[0];if(!(this.deviceID!==FA&&e[1]!==127&&this.deviceID!==e[1]))switch(t){default:H(`%cUnrecognized SysEx: %c${rA(e)}`,i.warn,i.unrecognized);break;case 126:case 127:switch(e[2]){case 4:let s;switch(e[3]){case 1:let o=e[5]<<7|e[4];this.setMIDIVolume(o/16384),y(`%cMaster Volume. Volume: %c${o}`,i.info,i.value);break;case 2:let C=((e[5]<<7|e[4])-8192)/8192;this.setMasterPan(C),y(`%cMaster Pan. Pan: %c${C}`,i.info,i.value);break;case 3:let a=(e[5]<<7|e[6])-8192;s=Math.floor(a/81.92),this.setMasterTuning(s),y(`%cMaster Fine Tuning. Cents: %c${s}`,i.info,i.value);break;case 4:s=(e[5]-64)*100,this.setMasterTuning(s),y(`%cMaster Coarse Tuning. Cents: %c${s}`,i.info,i.value);break;default:H(`%cUnrecognized MIDI Device Control Real-time message: %c${rA(e)}`,i.warn,i.unrecognized)}break;case 9:e[3]===1?(y("%cGM system on",i.info),this.system="gm"):e[3]===3?(y("%cGM2 system on",i.info),this.system="gm2"):(y("%cGM system off, defaulting to GS",i.info),this.system="gs");break;case 8:switch(e[3]){case 2:let o=e[4],r=e[5],C=[],a=6;for(let c=0;c<r;c++)C.push(e[a]),a++;let Q=[];for(let c=0;c<r;c++)Q.push(an(e[a++],e[a++],e[a++]));console.log(o,r,C,Q);break;case 9:case 8:let h=new Int8Array(12);if(e[3]===8)for(let c=0;c<12;c++)h[c]=e[7+c]-64;else for(let c=0;c<24;c+=2){let f=(e[7+c]<<7|e[8+c])-8192;h[c/2]=Math.floor(f/81.92)}(e[4]&1)===1&&this.setOctaveTuning(14+A,h),(e[4]>>1&1)===1&&this.setOctaveTuning(15+A,h);for(let c=0;c<7;c++)(e[5]>>c&1)===1&&this.setOctaveTuning(7+c+A,h);for(let c=0;c<7;c++)(e[6]>>c&1)===1&&this.setOctaveTuning(c+A,h);y(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${h.join(" ")}`,i.info,i.value);break;default:H(`%cUnrecognized MIDI Tuning standard message: %c${rA(e)}`,i.warn,i.unrecognized);break}break;default:H(`%cUnrecognized MIDI Realtime/non realtime message: %c${rA(e)}`,i.warn,i.unrecognized)}break;case 65:if(e[2]===66&&e[3]===18){let s=e[7];if(e[6]===127){s===0?(y("%cGS system on",i.info),this.system="gs"):s===127&&(y("%cGS system off, switching to GM2",i.info),this.system="gm2");return}else if(e[4]===64){if((e[5]&16)>0){let o=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A;switch(e[6]){default:break;case 21:let r=s>0&&e[5]>>4;this.setDrums(o,r),y(`%cChannel %c${o}%c ${r?"is now a drum channel":"now isn't a drum channel"}%c via: %c${rA(e)}`,i.info,i.value,i.recognized,i.info,i.value);return;case 22:let C=s-64;this.transposeChannel(o,C),y(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${rA(e)}`,i.info,i.recognized,i.info,i.value,i.info,i.value);return;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 a=s-64;y(`%cChannel %c${o}%c tuning. Cents %c${a}%c, with %c${rA(e)}`,i.info,i.recognized,i.info,i.value,i.info,i.value),this.setChannelTuning(o,a)}}else if(e[5]===0&&e[6]===6){y(`%cRoland GS Master Pan set to: %c${s}%c with: %c${rA(e)}`,i.info,i.value,i.info,i.value),this.setMasterPan((s-64)/64);return}else if(e[5]===0&&e[6]===5){let o=s-64;y(`%cRoland GS Master Key-Shift set to: %c${o}%c with: %c${rA(e)}`,i.info,i.value,i.info,i.value),this.setMasterTuning(o*100);return}else if(e[5]===0&&e[6]===4){y(`%cRoland GS Master Volume set to: %c${s}%c with: %c${rA(e)}`,i.info,i.value,i.info,i.value),this.setMIDIVolume(s/127);return}}H(`%cUnrecognized Roland %cGS %cSysEx: %c${rA(e)}`,i.warn,i.recognized,i.warn,i.unrecognized);return}else if(e[2]===22&&e[3]===18&&e[4]===16){this.setMIDIVolume(e[7]/100),y(`%cRoland Master Volume control set to: %c${e[7]}%c via: %c${rA(e)}`,i.info,i.value,i.info,i.value);return}else{H(`%cUnrecognized Roland SysEx: %c${rA(e)}`,i.warn,i.unrecognized);return}case 67:if(e[2]===76)if(e[3]===0&&e[4]===0)switch(e[5]){case 4:let s=e[6];this.setMIDIVolume(s/127),y(`%cXG master volume. Volume: %c${s}`,i.info,i.recognized);break;case 6:let o=e[6]-64;this.transposeAllChannels(o),y(`%cXG master transpose. Volume: %c${o}`,i.info,i.recognized);break;case 126:y("%cXG system on",i.info),this.system="xg";break}else if(e[3]===8){if(this.system!=="xg")return;let s=e[4]+A,o=e[6];switch(e[5]){case 1:this.controllerChange(s,p.bankSelect,o);break;case 2:this.controllerChange(s,p.lsbForControl0BankSelect,o);break;case 3:this.programChange(s,o);break;case 11:this.controllerChange(s,p.mainVolume,o);break;case 14:let r=o;r===0&&(r=Math.floor(Math.random()*127)),this.controllerChange(s,p.pan,r);break;case 19:this.controllerChange(s,p.effects1Depth,o);break;case 18:this.controllerChange(s,p.effects3Depth,o);break;default:H(`%cUnrecognized Yamaha XG Part Setup: %c${e[5].toString(16).toUpperCase()}`,i.warn,i.unrecognized)}}else this.system==="xg"&&H(`%cUnrecognized Yamaha XG SysEx: %c${rA(e)}`,i.warn,i.unrecognized);else this.system==="xg"&&H(`%cUnrecognized Yamaha SysEx: %c${rA(e)}`,i.warn,i.unrecognized);break}}var xe=[];function Ao(){xe=[]}function Cn(e,A,t,s){xe[t]=!1,s({channel:e,sampleID:t,sampleData:A.getAudioData()}),xe[t]=!0}function ae(e){if(e===null||typeof e!="object")return e;if(e instanceof Int16Array)return new Int16Array(e);let A=Array.isArray(e)?[]:{};for(let t in e)e.hasOwnProperty(t)&&(typeof e[t]=="object"&&e[t]!==null?A[t]=ae(e[t]):e[t]instanceof Int16Array?A[t]=new Int16Array(e[t]):A[t]=e[t]);return A}function eo(e,A,t,s,o,r,C,a,Q,h=!1){let c,f=a[A][t];return f!==void 0?(c=f.map(ae),c.forEach(m=>{m.startTime=o})):(c=s.getSamplesAndGenerators(A,t).reduce((m,d)=>{let u=d.sampleID+Q;if(xe[u]!==!0&&Cn(e,d.sample,u,C),d.sample.sampleData===void 0)return H(`Discarding invalid sample: ${d.sample.sampleName}`),m;let F=new Int16Array(60);for(let I=0;I<60;I++)F[I]=jt(I,d.presetGenerators,d.instrumentGenerators);F[B.initialAttenuation]=Math.floor(F[B.initialAttenuation]*.4);let k=d.sample.samplePitch;F[B.overridingRootKey]>-1&&(k=F[B.overridingRootKey]);let T=A;F[B.keyNum]>-1&&(T=F[B.keyNum]);let Y=d.sample.sampleLoopStartIndex/2+(F[B.startloopAddrsOffset]+F[B.startloopAddrsCoarseOffset]*32768),b=d.sample.sampleLoopEndIndex/2+(F[B.endloopAddrsOffset]+F[B.endloopAddrsCoarseOffset]*32768),_=F[B.sampleModes];b-Y<1&&(_=0);let J={sampleID:u,playbackStep:d.sample.sampleRate/r*Math.pow(2,d.sample.samplePitchCorrection/1200),cursor:F[B.startAddrsOffset]+F[B.startAddrsCoarseOffset]*32768,rootKey:k,loopStart:Y,loopEnd:b,end:Math.floor(d.sample.sampleData.length)-1+(F[B.endAddrOffset]+F[B.endAddrsCoarseOffset]*32768),loopingMode:_};return F[B.velocity]>-1&&(t=F[B.velocity]),h&&Ot([{Sample:d.sample.sampleName,Generators:F,Modulators:d.modulators.map(I=>I.debugString()),Velocity:t,TargetKey:T,MidiNote:A,WorkletSample:J}]),m.push({filter:ae(Ks),generators:F,modulators:d.modulators,modulatedGenerators:new Int16Array(60),sample:J,velocity:t,midiNote:A,pressure:0,channelNumber:e,startTime:o,targetKey:T,currentTuningCalculated:1,currentTuningCents:0,releaseStartTime:1/0,finished:!1,isInRelease:!1,currentModEnvValue:0,releaseStartModEnv:1,currentPan:.5,volumeEnvelope:ae(Ts)}),m},[]),a[A][t]=c.map(ae)),c}function to(e,A,t){if(A.transformAmount===0)return 0;let s;if(A.sourceUsesCC)s=e[A.sourceIndex];else{let Q=A.sourceIndex+sA;switch(A.sourceIndex){case P.noController:s=16383;break;case P.noteOnKeyNum:s=t.midiNote<<7;break;case P.noteOnVelocity:s=t.velocity<<7;break;case P.polyPressure:s=t.pressure<<7;break;default:s=e[Q];break}}let o=QA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],r;if(A.secSrcUsesCC)r=e[A.secSrcIndex];else{let Q=A.secSrcIndex+sA;switch(A.secSrcIndex){case P.noController:r=16383;break;case P.noteOnKeyNum:r=t.midiNote<<7;break;case P.noteOnVelocity:r=t.velocity<<7;break;case P.polyPressure:r=t.pressure<<7;break;default:r=e[Q]}}let C=QA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][r],a=o*C*A.transformAmount;return A.transformType===2?Math.abs(a):a}function YA(e,A,t=-1,s=0){let{modulators:o,generators:r,modulatedGenerators:C}=e;if(t===-1){C.set(r),o.forEach(h=>{C[h.modulatorDestination]+=to(A,h,e)}),ZA(e);return}let a=new Set([B.initialAttenuation,B.delayVolEnv,B.attackVolEnv,B.holdVolEnv,B.decayVolEnv,B.sustainVolEnv,B.releaseVolEnv,B.keyNumToVolEnvHold,B.keyNumToVolEnvDecay]),Q=new Set;o.forEach(h=>{if(h.sourceUsesCC===t&&h.sourceIndex===s||h.secSrcUsesCC===t&&h.secSrcIndex===s){let c=h.modulatorDestination;Q.has(c)||(C[c]=r[c],o.forEach(f=>{f.modulatorDestination===c&&(C[c]+=to(A,f,e))}),Q.add(c))}}),[...Q].some(h=>a.has(h))&&ZA(e)}var QA=[];for(let e=0;e<4;e++){QA[e]=[[new Float32Array(AA),new Float32Array(AA)],[new Float32Array(AA),new Float32Array(AA)]];for(let A=0;A<AA;A++)QA[e][0][0][A]=vA(0,e,A/AA,0),isNaN(QA[e][0][0][A])&&(QA[e][0][0][A]=1),QA[e][1][0][A]=vA(0,e,A/AA,1),isNaN(QA[e][1][0][A])&&(QA[e][1][0][A]=1),QA[e][0][1][A]=vA(1,e,A/AA,0),isNaN(QA[e][0][1][A])&&(QA[e][0][1][A]=1),QA[e][1][1][A]=vA(1,e,A/AA,1),isNaN(QA[e][1][1][A])&&(QA[e][1][1][A]=1)}function so(e,A,t,s=!1,o=!0,r=currentTime){if(t===0){this.noteOff(e,A);return}let C=this.workletProcessorChannels[e];if(this.highPerformanceMode&&this.totalVoicesAmount>200&&t<40||this.highPerformanceMode&&t<10||C.isMuted||(A+=C.channelTransposeKeyShift,A>127||A<0))return;let a=eo(e,A,t,C.preset,r,sampleRate,h=>this.sampleDump(h.channel,h.sampleID,h.sampleData),C.cachedVoices,C.presetUsesOverride?this.soundfont.samples.length:0,s),Q=C.voices;a.forEach(h=>{let c=h.generators[B.exclusiveClass];c!==0&&Q.forEach(f=>{f.generators[B.exclusiveClass]===c&&(this.releaseVoice(f),f.modulatedGenerators[B.releaseVolEnv]=-7e3,f.modulatedGenerators[B.releaseModEnv]=-7e3,ZA(f))}),YA(h,C.midiControllers),h.currentPan=(Math.max(-500,Math.min(500,h.modulatedGenerators[B.pan]))+500)/1e3}),this.totalVoicesAmount+=a.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(a.length),Q.push(...a),o&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A-C.channelTransposeKeyShift,channel:e,velocity:t}))}function oo(e,A){if(A>127||A<0){H("Received a noteOn for note",A,"Ignoring.");return}if(A+=this.workletProcessorChannels[e].channelTransposeKeyShift,this.highPerformanceMode&&!this.workletProcessorChannels[e].drumChannel){this.killNote(e,A);return}this.workletProcessorChannels[e].voices.forEach(s=>{s.midiNote!==A||s.isInRelease===!0||(this.workletProcessorChannels[e].holdPedal?this.workletProcessorChannels[e].sustainedVoices.push(s):this.releaseVoice(s))}),this.callEvent("noteoff",{midiNote:A-this.workletProcessorChannels[e].channelTransposeKeyShift,channel:e})}function no(e,A){this.workletProcessorChannels[e].voices.forEach(t=>{t.midiNote===A&&(t.modulatedGenerators[B.releaseVolEnv]=-12e3,this.releaseVoice(t))})}function Io(e,A=!1){let t=this.workletProcessorChannels[e].voices;A?(t.length=0,this.workletProcessorChannels[e].sustainedVoices.length=0,this.sendChannelProperties()):(t.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[e].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function ro(e=!1){y("%cStop all received!",i.info);for(let A=0;A<this.workletProcessorChannels.length;A++)this.stopAll(A,e);this.callEvent("stopall",void 0)}function go(e,A=!1){this.transposition=0;for(let t=0;t<this.workletProcessorChannels.length;t++)this.transposeChannel(t,e,A);this.transposition=e}function io(e,A,t=!1){let s=this.workletProcessorChannels[e];s.drumChannel||(A+=this.transposition);let o=Math.trunc(A),r=s.channelTransposeKeyShift+s.customControllers[$.channelTransposeFine]/100;s.drumChannel&&!t||A===r||(o!==s.channelTransposeKeyShift&&this.stopAll(e,!1),s.channelTransposeKeyShift=o,s.customControllers[$.channelTransposeFine]=(A-o)*100)}function ao(e,A,t=!0){let s=this.workletProcessorChannels[e];A=Math.round(A),s.customControllers[$.channelTuning]=A,t&&y(`%cChannel ${e} fine tuning. Cents: %c${A}`,i.info,i.value)}function Co(e,A){let t=this.workletProcessorChannels[e];A=Math.round(A),t.customControllers[$.channelTuningSemitones]=A,y(`%cChannel ${e} coarse tuning. Semitones: %c${A}`,i.info,i.value)}function Eo(e){e=Math.round(e);for(let A=0;A<this.workletProcessorChannels.length;A++)this.workletProcessorChannels[A].customControllers[$.masterTuning]=e}function Bo(e,A){let t=this.workletProcessorChannels[e];A=Math.round(A),y(`%cChannel ${e} modulation depth. Cents: %c${A}`,i.info,i.value),t.customControllers[$.modulationMultiplier]=A/50}function Qo(e,A,t){if(this.workletProcessorChannels[e].lockedControllers[sA+P.pitchWheel])return;let s=t|A<<7;this.callEvent("pitchwheel",{channel:e,MSB:A,LSB:t}),this.workletProcessorChannels[e].midiControllers[sA+P.pitchWheel]=s,this.workletProcessorChannels[e].voices.forEach(o=>YA(o,this.workletProcessorChannels[e].midiControllers,0,P.pitchWheel)),this.sendChannelProperties()}function ho(e,A){let t=this.workletProcessorChannels[e];t.midiControllers[sA+P.channelPressure]=A<<7,this.workletProcessorChannels[e].voices.forEach(s=>YA(s,t.midiControllers,0,P.channelPressure)),this.callEvent("channelpressure",{channel:e,pressure:A})}function co(e,A,t){this.workletProcessorChannels[e].voices.forEach(s=>{s.midiNote===A&&(s.pressure=t,YA(s,this.workletProcessorChannels[e].midiControllers,0,P.polyPressure))}),this.callEvent("polypressure",{channel:e,midiNote:A,pressure:t})}function lo(e,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[e].channelOctaveTuning=A}function fo(e,A,t,s=!1){let o=this.workletProcessorChannels[e];if(A>=p.lsbForControl1ModulationWheel&&A<=p.lsbForControl13EffectControl2&&A!==p.lsbForControl6DataEntry){let r=A-32;if(o.lockedControllers[r])return;o.midiControllers[r]=o.midiControllers[r]&16256|t&127,o.voices.forEach(C=>YA(C,o.midiControllers,1,r))}switch(A){case p.allNotesOff:this.stopAll(e);break;case p.allSoundOff:this.stopAll(e,!0);break;case p.bankSelect:let r=t;if(!s){switch(this.system){case"gm":y(`%cIgnoring the Bank Select (${t}), as the synth is in GM mode.`,i.info);return;case"xg":r===120||r===126||r===127?this.setDrums(e,!0):this.setDrums(e,!1);break;case"gm2":r===120&&(o.drumChannel=!0,this.callEvent("drumchange",{channel:e,isDrumChannel:!0}))}o.drumChannel&&(r=128),r===128&&!o.drumChannel&&(r=o.midiControllers[p.bankSelect])}o.midiControllers[p.bankSelect]=r;break;case p.lsbForControl0BankSelect:this.system==="xg"?o.drumChannel||t!==127&&(o.midiControllers[p.bankSelect]=t):this.system==="gm2"&&(o.midiControllers[p.bankSelect]=t);break;case p.RPNLsb:o.RPValue=o.RPValue<<7|t,o.dataEntryState=EA.RPFine;break;case p.RPNMsb:o.RPValue=t,o.dataEntryState=EA.RPCoarse;break;case p.NRPNMsb:o.NRPCoarse=t,o.dataEntryState=EA.NRPCoarse;break;case p.NRPNLsb:o.NRPFine=t,o.dataEntryState=EA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(e,t);break;case p.lsbForControl6DataEntry:this.dataEntryFine(e,t);break;case p.resetAllControllers:this.resetControllers(e);break;case p.sustainPedal:t>=64?o.holdPedal=!0:(o.holdPedal=!1,o.sustainedVoices.forEach(C=>{this.releaseVoice(C)}),o.sustainedVoices=[]);break;default:if(o.lockedControllers[A])return;o.midiControllers[A]=t<<7,o.voices.forEach(C=>YA(C,o.midiControllers,1,A)),this.callEvent("controllerchange",{channel:e,controllerNumber:A,controllerValue:t});break}}function uo(e){this.midiVolume=e,this.setMasterPan(this.pan)}function mo(e){this.masterGain=e*ht,this.setMasterPan(this.pan)}function po(e){this.pan=e,e=e/2+.5,this.panLeft=(1-e)*this.currentGain,this.panRight=e*this.currentGain}function yo(e,A){A&&this.stopAll(e,!0),this.workletProcessorChannels[e].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:e,isMuted:A})}function So(e){this.workletProcessorChannels[e].lockVibrato=!0,this.workletProcessorChannels[e].channelVibrato.rate=0,this.workletProcessorChannels[e].channelVibrato.delay=0,this.workletProcessorChannels[e].channelVibrato.depth=0}function Do(e,A,t,s){this.workletProcessorChannels[e].lockVibrato||(this.workletProcessorChannels[e].channelVibrato.rate=t,this.workletProcessorChannels[e].channelVibrato.delay=s,this.workletProcessorChannels[e].channelVibrato.depth=A)}function ko(e,A){let t=this.workletProcessorChannels[e],s=()=>{t.channelVibrato.delay===0&&t.channelVibrato.rate===0&&t.channelVibrato.depth===0&&(t.channelVibrato.depth=50,t.channelVibrato.rate=8,t.channelVibrato.delay=.6)};switch(t.dataEntryState){default:case EA.Idle:break;case EA.NRPFine:if(this.system!=="gs")return;switch(t.NRPCoarse){default:if(A===64)return;H(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16).toUpperCase()} 0x${t.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,i.warn,i.recognized,i.warn,i.unrecognized,i.warn,i.value);break;case 1:switch(t.NRPFine){default:if(A===64)return;H(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16)} 0x${t.NRPFine.toString(16)})%c data value: %c${A}`,i.warn,i.recognized,i.warn,i.unrecognized,i.warn,i.value);break;case 8:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.rate=A/64*8,y(`%cVibrato rate for channel %c${e}%c is now set to %c${t.channelVibrato.rate}%cHz.`,i.info,i.recognized,i.info,i.value,i.info);break;case 9:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.depth=A/2,y(`%cVibrato depth for %c${e}%c is now set to %c${t.channelVibrato.depth}%c cents range of detune.`,i.info,i.recognized,i.info,i.value,i.info);break;case 10:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.delay=A/64/3,y(`%cVibrato delay for %c${e}%c is now set to %c${t.channelVibrato.delay}%c seconds.`,i.info,i.recognized,i.info,i.value,i.info);break;case 32:let r=A;this.controllerChange(e,p.brightness,A),y(`%cFilter cutoff for %c${e}%c is now set to %c${r}`,i.info,i.recognized,i.info,i.value)}break;case 29:if(!t.drumChannel)return;let o=A;this.controllerChange(e,p.effects1Depth,o),y(`%cGS Drum reverb for %c${e}%c: %c${o}`,i.info,i.recognized,i.info,i.value);break}break;case EA.RPCoarse:case EA.RPFine:switch(t.RPValue){default:H(`%cUnrecognized RPN for %c${e}%c: %c(0x${t.RPValue.toString(16)})%c data value: %c${A}`,i.warn,i.recognized,i.warn,i.unrecognized,i.warn,i.value);break;case 0:t.midiControllers[sA+P.pitchWheelRange]=A<<7,y(`%cChannel ${e} bend range. Semitones: %c${A}`,i.info,i.value);break;case 2:this.setChannelTuningSemitones(e,A-64);break;case 1:this.setChannelTuning(e,A-64,!1);break;case 5:this.setModulationDepth(e,A*100);break;case 16383:this.resetParameters(e);break}}}function wo(e,A){let t=this.workletProcessorChannels[e];switch(t.dataEntryState){default:break;case EA.RPCoarse:case EA.RPFine:switch(t.RPValue){default:break;case 0:if(A===0)break;t.midiControllers[sA+P.pitchWheelRange]|=A;let s=(t.midiControllers[sA+P.pitchWheelRange]>>7)+A/127;y(`%cChannel ${e} bend range. Semitones: %c${s}`,i.info,i.value);break;case 1:let r=t.customControllers[$.channelTuning]<<7|A;this.setChannelTuning(e,r*.01220703125);break;case 5:let a=t.customControllers[$.modulationMultiplier]*50+A/128*100;this.setModulationDepth(e,a);break;case 16383:this.resetParameters(e);break}}}function Fo(){y("%cResetting all controllers!",i.info),this.callEvent("allcontrollerreset",void 0);for(let e=0;e<this.workletProcessorChannels.length;e++){this.resetControllers(e);let A=this.workletProcessorChannels[e];A.lockPreset?this.callEvent("drumchange",{channel:e,isDrumChannel:A.drumChannel}):(A.presetUsesOverride=!0,A.midiControllers[p.bankSelect]=0,e%16===kA?(this.setPreset(e,this.drumPreset),A.drumChannel=!0,this.callEvent("drumchange",{channel:e,isDrumChannel:!0})):(A.drumChannel=!1,this.setPreset(e,this.defaultPreset),this.callEvent("drumchange",{channel:e,isDrumChannel:!1}))),this.callEvent("programchange",{channel:e,program:A.preset.program,bank:A.preset.bank,userCalled:!1});let t=s=>{this.workletProcessorChannels[e].lockedControllers[s]&&this.callEvent("controllerchange",{channel:e,controllerNumber:s,controllerValue:this.workletProcessorChannels[e].midiControllers[s]>>7})};if(t(p.mainVolume),t(p.pan),t(p.expressionController),t(p.modulationWheel),t(p.effects3Depth),t(p.effects1Depth),this.workletProcessorChannels[e].lockedControllers[sA+P.pitchWheel]){let s=this.workletProcessorChannels[e].midiControllers[sA+P.pitchWheel],o=s>>7,r=s&127;this.callEvent("pitchwheel",{channel:e,MSB:o,LSB:r})}}this.setMIDIVolume(1),this.system=pe}function Ro(e){let A=this.workletProcessorChannels[e],s=A.lockedControllers.reduce((r,C,a)=>(C&&r.push(a),r),[]).map(r=>({ccNum:r,ccVal:A.midiControllers[r]}));A.channelOctaveTuning.fill(0),A.midiControllers.set(UA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(r=>{A.midiControllers[r.ccNum]=r.ccVal});let o=A.customControllers[$.channelTransposeFine];A.customControllers.set(rt),A.customControllers[$.channelTransposeFine]=o,this.resetParameters(e)}function Go(e){let A=this.workletProcessorChannels[e];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=EA.Idle}function xo(e,A,t=!1){let s=this.workletProcessorChannels[e];if(s.lockPreset)return;let o=s.drumChannel?128:s.midiControllers[p.bankSelect],r,C;if(this.overrideSoundfont){let a=o===128?128:Math.max(0,o-this.soundfontBankOffset),Q=this.overrideSoundfont.presets.find(h=>h.program===A&&h.bank===a);Q?(r=o,C=Q,s.presetUsesOverride=!0):(C=this.soundfont.getPreset(o,A),r=C.bank,s.presetUsesOverride=!1)}else C=this.soundfont.getPreset(o,A),r=C.bank,s.presetUsesOverride=!1;this.setPreset(e,C),this.callEvent("programchange",{channel:e,program:C.program,bank:r,userCalled:t})}function No(e,A){if(this.overrideSoundfont){let t=e===128?128:Math.max(0,e-this.soundfontBankOffset),s=this.overrideSoundfont.presets.find(o=>o.program===A&&o.bank===t);if(s)return s}return this.soundfont.getPreset(e,A)}function Mo(e,A){if(!this.workletProcessorChannels[e].lockPreset){delete this.workletProcessorChannels[e].preset,this.workletProcessorChannels[e].preset=A,this.workletProcessorChannels[e].cachedVoices=[];for(let t=0;t<128;t++)this.workletProcessorChannels[e].cachedVoices.push([])}}function Uo(e,A){let t=this.workletProcessorChannels[e];t.lockPreset||t.drumChannel!==A&&(A?(t.channelTransposeKeyShift=0,t.drumChannel=!0,this.setPreset(e,this.getPreset(128,t.preset.program))):(t.drumChannel=!1,this.setPreset(e,this.getPreset(t.midiControllers[p.bankSelect],t.preset.program))),t.presetUsesOverride=!1,this.callEvent("drumchange",{channel:e,isDrumChannel:t.drumChannel}),this.sendChannelProperties())}function bo(){let e=this.soundfont.presets.map(A=>({presetName:A.presetName,bank:A.bank,program:A.program}));this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,s=e.find(o=>o.bank===t&&o.program===A.program);s!==void 0?s.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.callEvent("presetlistchange",e)}function Lo(e=!0,A=!0){this.stopAllChannels(!0),Ao(),A&&delete this.overrideSoundfont,delete this.workletDumpedSamplesList,this.workletDumpedSamplesList=[],this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let t=0;t<this.workletProcessorChannels.length;t++){let s=this.workletProcessorChannels[t];s.cachedVoices=[];for(let o=0;o<128;o++)s.cachedVoices.push([]);s.lockPreset=!1,this.programChange(t,s.preset.program)}e&&this.sendPresetList()}function Ho(e,A=!1){this.clearSoundFont(!1,A),A||delete this.soundfont;try{A?this.overrideSoundfont=new qA(e):this.soundfont=new qA(e)}catch(t){this.post({messageType:cA.soundfontError,messageData:t});return}this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels.forEach((t,s)=>{this.programChange(s,t.preset.program)}),this.post({messageType:cA.ready,messageData:void 0}),this.sendPresetList(),y("%cSpessaSynth is ready!",i.recognized)}function Yo(e,A,t){this.workletDumpedSamplesList[A]=t,this.workletProcessorChannels[e].voices.forEach(s=>{if(s.sample.sampleID===A){if(s.sample.end=t.length-1+s.generators[B.endAddrOffset]+s.generators[B.endAddrsCoarseOffset]*32768,s.sample.cursor=s.sample.playbackStep*sampleRate*(currentTime-s.startTime),s.sample.loopingMode===0){if(s.sample.cursor>=s.sample.end){s.finished=!0;return}}else s.sample.cursor>s.sample.loopEnd&&(s.sample.cursor=s.sample.cursor%(s.sample.loopEnd-s.sample.loopStart)+s.sample.loopStart-1);s.startTime=currentTime}})}function To(){let A={channelSnapshots:this.workletProcessorChannels.map(t=>({program:t.preset.program,bank:t.preset.bank,lockPreset:t.lockPreset,patchName:t.preset.presetName,midiControllers:t.midiControllers,lockedControllers:t.lockedControllers,customControllers:t.customControllers,channelVibrato:t.channelVibrato,lockVibrato:t.lockVibrato,channelTransposeKeyShift:t.channelTransposeKeyShift,channelOctaveTuning:t.channelOctaveTuning,isMuted:t.isMuted,drumChannel:t.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system};this.post({messageType:cA.synthesizerSnapshot,messageData:A})}function Jo(e){for(this.system=e.system,this.setMasterGain(e.mainVolume),this.setMasterPan(e.pan),this.transposeAllChannels(e.transposition);this.workletProcessorChannels.length<e.channelSnapshots.length;)this.createWorkletChannel();e.channelSnapshots.forEach((A,t)=>{let s=this.workletProcessorChannels[t];this.muteChannel(t,A.isMuted),this.setDrums(t,A.drumChannel),s.midiControllers=A.midiControllers,s.lockedControllers=A.lockedControllers,s.customControllers=A.customControllers,s.channelVibrato=A.channelVibrato,s.lockVibrato=A.lockVibrato,s.channelTransposeKeyShift=A.channelTransposeKeyShift,s.channelOctaveTuning=A.channelOctaveTuning,s.lockPreset=!1,s.midiControllers[p.bankSelect]=A.bank,this.programChange(t,A.program),s.lockPreset=A.lockPreset}),y("%cFinished restoring controllers!",i.info)}R.prototype.renderVoice=vs;R.prototype.releaseVoice=Xs;R.prototype.voiceKilling=Zs;R.prototype.handleMessage=Ws;R.prototype.post=zs;R.prototype.sendChannelProperties=js;R.prototype.callEvent=_s;R.prototype.systemExclusive=$s;R.prototype.noteOn=so;R.prototype.noteOff=oo;R.prototype.polyPressure=co;R.prototype.killNote=no;R.prototype.stopAll=Io;R.prototype.stopAllChannels=ro;R.prototype.muteChannel=yo;R.prototype.setVibrato=Do;R.prototype.disableAndLockVibrato=So;R.prototype.dataEntryCoarse=ko;R.prototype.dataEntryFine=wo;R.prototype.createWorkletChannel=ys;R.prototype.controllerChange=fo;R.prototype.channelPressure=ho;R.prototype.resetAllControllers=Fo;R.prototype.resetControllers=Ro;R.prototype.resetParameters=Go;R.prototype.setMasterGain=mo;R.prototype.setMasterPan=po;R.prototype.setMIDIVolume=uo;R.prototype.transposeAllChannels=go;R.prototype.transposeChannel=io;R.prototype.setChannelTuning=ao;R.prototype.setChannelTuningSemitones=Co;R.prototype.setMasterTuning=Eo;R.prototype.setModulationDepth=Bo;R.prototype.pitchWheel=Qo;R.prototype.setOctaveTuning=lo;R.prototype.programChange=xo;R.prototype.getPreset=No;R.prototype.setPreset=Mo;R.prototype.setDrums=Uo;R.prototype.reloadSoundFont=Ho;R.prototype.clearSoundFont=Lo;R.prototype.sampleDump=Yo;R.prototype.sendPresetList=bo;R.prototype.sendSynthesizerSnapshot=To;R.prototype.applySynthesizerSnapshot=Jo;registerProcessor(vt,R);y("%cProcessor succesfully registered!",i.recognized);
@@ -18,9 +18,11 @@ export function getOscillatorData(voice, sampleData, outputBuffer)
18
18
 
19
19
  if(loop)
20
20
  {
21
- for (let i = 0; i < outputBuffer.length; i++) {
21
+ for (let i = 0; i < outputBuffer.length; i++)
22
+ {
22
23
  // check for loop
23
- while(cur >= voice.sample.loopEnd) {
24
+ while(cur >= voice.sample.loopEnd)
25
+ {
24
26
  cur -= loopLength;
25
27
  }
26
28
 
@@ -28,10 +30,16 @@ export function getOscillatorData(voice, sampleData, outputBuffer)
28
30
  const floor = ~~cur;
29
31
  let ceil = floor + 1;
30
32
 
31
- while(ceil >= voice.sample.loopEnd) {
33
+ while(ceil >= voice.sample.loopEnd)
34
+ {
32
35
  ceil -= loopLength;
33
36
  }
34
37
 
38
+ // nearest neighbor (uncomment to use)
39
+ // outputBuffer[i] = sampleData[ceil];
40
+ // cur += voice.sample.playbackStep * voice.currentTuningCalculated;
41
+ // continue;
42
+
35
43
  const fraction = cur - floor;
36
44
 
37
45
  // grab the samples and interpolate
@@ -69,8 +77,9 @@ export function getOscillatorData(voice, sampleData, outputBuffer)
69
77
  return;
70
78
  }
71
79
 
72
- // cur += voice.sample.playbackStep * voice.currentTuningCalculated;
80
+ // nearest neighbor (uncomment to use)
73
81
  // outputBuffer[i] = sampleData[ceil];
82
+ // cur += voice.sample.playbackStep * voice.currentTuningCalculated;
74
83
  // continue;
75
84
 
76
85
  const fraction = cur - floor;