spessasynth_lib 3.15.0 → 3.15.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.
@@ -88,7 +88,7 @@ class MIDI{
88
88
  if(currentChunk.header === "RIFF")
89
89
  {
90
90
  const type = readBytesAsString(currentChunk.chunkData, 4);
91
- if(type === "sfbk")
91
+ if(type === "sfbk" || type === "sfpk")
92
92
  {
93
93
  SpessaSynthInfo("%cFound embedded soundfont!", consoleColors.recognized);
94
94
  this.embeddedSoundFont = binaryData.slice(startIndex, startIndex + currentChunk.size).buffer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spessasynth_lib",
3
- "version": "3.15.0",
3
+ "version": "3.15.1",
4
4
  "description": "No compromise MIDI and SoundFont2 Synthesizer library",
5
5
  "browser": "index.js",
6
6
  "types": "@types/index.d.ts",
@@ -8,6 +8,6 @@ var Ht=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>(
8
8
 
9
9
 
10
10
  `}};function OA(e,A,t,s,o){return e<<10|A<<9|t<<8|s<<7|o}var At=960,et=fA.concave,As=[new EA({srcEnum:OA(et,0,1,0,q.noteOnVelocity),dest:B.initialAttenuation,amt:At,secSrcEnum:0,transform:0}),new EA({srcEnum:129,dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(et,0,1,1,y.mainVolume),dest:B.initialAttenuation,amt:At,secSrcEnum:0,transform:0}),new EA({srcEnum:13,dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new EA({srcEnum:526,dest:B.fineTune,amt:12700,secSrcEnum:16,transform:0}),new EA({srcEnum:650,dest:B.pan,amt:1e3,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(et,0,1,1,y.expressionController),dest:B.initialAttenuation,amt:At,secSrcEnum:0,transform:0}),new EA({srcEnum:219,dest:B.reverbEffectsSend,amt:200,secSrcEnum:0,transform:0}),new EA({srcEnum:221,dest:B.chorusEffectsSend,amt:200,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(fA.linear,0,0,0,q.polyPressure),dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(fA.linear,0,0,1,y.effects2Depth),dest:B.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(fA.linear,1,0,1,y.releaseTime),dest:B.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(fA.linear,1,0,1,y.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 EA(e.chunkData));return A}var st=class{constructor(A,t){this.generatorZoneStartIndex=J(A,2),this.modulatorZoneStartIndex=J(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=[],I=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let C=new st(e.chunkData,I);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),I++}return o.length>1&&o.pop(),o}var ot=class{constructor(A,t){this.generatorZoneStartIndex=J(A,2),this.modulatorZoneStartIndex=J(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=[],I=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let C=new ot(e.chunkData,I);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),I++}return o.length>1&&o.pop(),o}var nt=class{constructor(A){this.presetName=W(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=J(A.chunkData,2),this.bank=J(A.chunkData,2),this.presetZoneStartIndex=J(A.chunkData,2),this.presetZonesAmount=0,this.presetZones=[],this.foundSamplesAndGenerators=[];for(let t=0;t<128;t++)this.foundSamplesAndGenerators[t]=[];this.library=J(A.chunkData,4),this.genre=J(A.chunkData,4),this.morphology=J(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(I=>{I.sample.isSampleLoaded||I.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,f,d){return d>=m&&d<=f}function I(m,f){return m.modulatorSource===f.modulatorSource&&m.modulatorDestination===f.modulatorDestination&&m.modulationSecondarySrc===f.modulationSecondarySrc&&m.transformType===f.transformType}function C(m,f){m.push(...f.filter(d=>!m.find(F=>F.generatorType===d.generatorType)))}function a(m,f){m.push(...f.filter(d=>!m.find(F=>I(d,F))))}let Q=[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],u=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 f=m.generators,d=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(L=>o(L.keyRange.min,L.keyRange.max,A)&&o(L.velRange.min,L.velRange.max,t)&&!L.isGlobal).forEach(L=>{let b=[...L.generators],z=[...L.modulators];C(f,h),C(b,F),a(d,u),a(z,k),a(z,As);let Y=[...z];for(let r=0;r<d.length;r++){let V=d[r],P=Y.findIndex(v=>I(V,v));P!==-1?Y[P]=Y[P].sumTransform(V):Y.push(V)}Q.push({instrumentGenerators:b,presetGenerators:f,modulators:Y,sample:L.sample,sampleID:L.generators.find(r=>r.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,I)=>(I.generators=I.generators.filter(C=>C.generatorType!==B.sampleID&&C.generatorType!==B.keyRange&&C.generatorType!==B.velRange),(I.velRange.max!==127||I.velRange.min!==0)&&I.generators.unshift({generatorType:B.velRange,generatorValue:I.velRange.max<<8|I.velRange.min}),(I.keyRange.max!==127||I.keyRange.min!==0)&&I.generators.unshift({generatorType:B.keyRange,generatorValue:I.keyRange.max<<8|I.keyRange.min}),I.isGlobal||I.generators.push({generatorType:B.sampleID,generatorValue:this.samples.indexOf(I.sample)}),I.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 I of o.generators)x(A,I.generatorType),x(A,I.generatorValue),t++}return CA(A,0),_(new O("igen",A.length,A))}function ns(e,A,t,s,o){let I=this.samples.map((h,u)=>{t&&h.compressSample(s,o);let l=h.getRawData();return p(`%cEncoded sample %c${u}. ${h.sampleName}%c of %c${this.samples.length}`,i.info,i.recognized,i.info,i.recognized),l}),C=this.samples.reduce((h,u,l)=>h+I[l].length+46,0),a=new U(C);this.samples.forEach((h,u)=>{let l=I[u],m,f,d=l.length;h.isCompressed?(m=a.currentIndex,f=m+l.length):(m=a.currentIndex/2,f=m+l.length/2,d+=46),e.push(m),a.set(l,a.currentIndex),a.currentIndex+=d,A.push(f)});let Q=_(new O("smpl",a.length,a),new U([115,100,116,97]));return _(new O("LIST",Q.length,Q))}function Is(e,A){let s=new U(46*(this.samples.length+1));return this.samples.forEach((o,I)=>{mA(s,o.sampleName,20);let C=e[I];CA(s,C);let a=A[I];CA(s,a);let Q=o.sampleLoopStartIndex/2+C,h=o.sampleLoopEndIndex/2+C;o.isCompressed&&(Q-=C,h-=C),CA(s,Q),CA(s,h),CA(s,o.sampleRate),s[s.currentIndex++]=o.samplePitch,s[s.currentIndex++]=o.samplePitchCorrection,x(s,o.sampleLink),x(s,o.sampleType)}),mA(s,"EOS",46),_(new O("shdr",s.length,s))}function rs(){let e=10;for(let s of this.instruments)e+=s.instrumentZones.reduce((o,I)=>I.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 I of o.modulators)x(A,I.modulatorSource),x(A,I.modulatorDestination),x(A,I.transformAmount),x(A,I.modulationSecondarySrc),x(A,I.transformType),t++}return zA(A,0,10),_(new O("imod",A.length,A))}function gs(){let e=this.instruments.reduce((I,C)=>C.instrumentZones.length*4+I,4),A=new U(e),t=0,s=0,o=0;for(let I of this.instruments){I.instrumentZoneIndex=t;for(let C of I.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),_(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)mA(A,o.instrumentName,20),x(A,t),t+=o.instrumentZones.length,o.instrumentID=s,s++;return mA(A,"EOI",20),x(A,t),_(new O("inst",A.length,A))}function as(){let e=4;for(let s of this.presets)e+=s.presetZones.reduce((o,I)=>(I.generators=I.generators.filter(C=>C.generatorType!==B.instrument&&C.generatorType!==B.keyRange&&C.generatorType!==B.velRange),(I.velRange.max!==127||I.velRange.min!==0)&&I.generators.unshift({generatorType:B.velRange,generatorValue:I.velRange.max<<8|I.velRange.min}),(I.keyRange.max!==127||I.keyRange.min!==0)&&I.generators.unshift({generatorType:B.keyRange,generatorValue:I.keyRange.max<<8|I.keyRange.min}),I.isGlobal||I.generators.push({generatorType:B.instrument,generatorValue:this.instruments.indexOf(I.instrument)}),I.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 I of o.generators)x(A,I.generatorType),x(A,I.generatorValue);t+=o.generators.length}return x(A,0),x(A,0),_(new O("pgen",A.length,A))}function Cs(){let e=10;for(let s of this.presets)e+=s.presetZones.reduce((o,I)=>I.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 I of o.modulators)x(A,I.modulatorSource),x(A,I.modulatorDestination),x(A,I.transformAmount),x(A,I.modulationSecondarySrc),x(A,I.transformType),t++}return zA(A,0,10),_(new O("pmod",A.length,A))}function Es(){let e=this.presets.reduce((I,C)=>C.presetZones.length*4+I,4),A=new U(e),t=0,s=0,o=0;for(let I of this.presets){I.presetZoneStartIndex=t;for(let C of I.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),_(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)mA(A,s.presetName,20),x(A,s.program),x(A,s.bank),x(A,t),CA(A,s.library),CA(A,s.genre),CA(A,s.morphology),t+=s.presetZones.length;return mA(A,"EOP",20),x(A,0),x(A,0),x(A,t),CA(A,0),CA(A,0),CA(A,0),_(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.");YA("%cSaving soundfont...",i.info),p(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,i.info,i.recognized,i.info,i.recognized),p("%cWriting INFO...",i.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.compress&&(this.soundFontInfo.ifil="3.0");for(let[z,Y]of Object.entries(this.soundFontInfo))if(z==="ifil"||z==="iver"){let r=parseInt(Y.split(".")[0]),V=parseInt(Y.split(".")[1]),P=new U(4);x(P,r),x(P,V),A.push(_(new O(z,4,P)))}else{let r=new U(Y.length);mA(r,Y),A.push(_(new O(z,Y.length,r)))}let t=Ie([new U([73,78,70,79]),...A]),s=_(new O("LIST",t.length,t));p("%cWriting SDTA...",i.info);let o=[],I=[],C=ns.call(this,o,I,e?.compress,e?.compressionQuality||.5,e.compressionFunction);p("%cWriting PDTA...",i.info),p("%cWriting SHDR...",i.info);let a=Is.call(this,o,I);p("%cWriting IGEN...",i.info);let Q=os.call(this);p("%cWriting IMOD...",i.info);let h=rs.call(this);p("%cWriting IBAG...",i.info);let u=gs.call(this);p("%cWriting INST...",i.info);let l=is.call(this),m=as.call(this);p("%cWriting PMOD...",i.info);let f=Cs.call(this);p("%cWriting PBAG...",i.info);let d=Es.call(this);p("%cWriting PHDR...",i.info);let F=Bs.call(this),k=Ie([new U([112,100,116,97]),F,d,f,m,l,u,h,Q,a]),K=_(new O("LIST",k.length,k));p("%cWriting the output file...",i.info);let L=Ie([new U([115,102,98,107]),s,C,K]),b=_(new O("RIFF",L.length,L));return p(`%cSaved succesfully! Final file size: %c${b.length}`,i.info,i.recognized),AA(),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 AA(),new TypeError("No data!");let t=nA(this.dataArray,!1);this.verifyHeader(t,"riff");let s=W(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw AA(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",I=nA(this.dataArray);for(this.verifyHeader(I,"list"),W(I.chunkData,4),this.soundFontInfo={};I.chunkData.length>I.chunkData.currentIndex;){let v=nA(I.chunkData),oA;switch(v.header.toLowerCase()){case"ifil":case"iver":oA=`${J(v.chunkData,2)}.${J(v.chunkData,2)}`;break;case"icmt":oA=W(v.chunkData,v.chunkData.length,void 0,!1);break;default:oA=W(v.chunkData,v.chunkData.length)}p(`%c"${v.header}": %c"${oA}"`,i.info,i.recognized),this.soundFontInfo[v.header]=oA}let C=nA(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(W(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",i.warn);let a=nA(this.dataArray,!1);this.verifyHeader(a,"smpl");let Q;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",i.info);try{Q=UA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(v){throw AA(),new Error(`SF2Pack Ogg Vorbis decode error: ${v}`)}p(`%cDecoded the smpl chunk! Length: %c${Q.length}`,i.info,i.value)}else Q=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${C.size-12}`,i.info,i.value),this.dataArray.currentIndex+=C.size-12,p("%cLoading preset data chunk...",i.warn);let h=nA(this.dataArray);this.verifyHeader(h,"list"),W(h.chunkData,4);let u=nA(h.chunkData);this.verifyHeader(u,"phdr");let l=nA(h.chunkData);this.verifyHeader(l,"pbag");let m=nA(h.chunkData);this.verifyHeader(m,"pmod");let f=nA(h.chunkData);this.verifyHeader(f,"pgen");let d=nA(h.chunkData);this.verifyHeader(d,"inst");let F=nA(h.chunkData);this.verifyHeader(F,"ibag");let k=nA(h.chunkData);this.verifyHeader(k,"imod");let K=nA(h.chunkData);this.verifyHeader(K,"igen");let L=nA(h.chunkData);this.verifyHeader(L,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples=zt(L,Q,!o);let b=je(K),z=tt(k),Y=es(F,b,z,this.samples);this.instruments=$t(d,Y);let r=je(f),V=tt(m),P=ts(l,r,V,this.instruments);this.presets=ss(u,P),this.presets.sort((v,oA)=>v.program-oA.program+(v.bank-oA.bank)),p(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets,
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),AA(),o&&delete this.dataArray}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 AA(),new SyntaxError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw AA(),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&&T(`%cPreset ${A}.${t} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,i.warn,i.recognized)),s||(T(`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||(T("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(I=>{s.find(C=>C.bank===I.bank&&C.program===I.program)===void 0&&s.push(I)});return new e({presets:s,info:t.soundFontInfo})}};qA.prototype.write=Qs;var FA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},pA={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 I=this.playingNotes.findIndex(C=>C.midiNote===e.messageData[0]&&C.channel===t.channel);I!==-1&&this.playingNotes.splice(I,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),T("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(pA.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:T(`%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===wA&&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 bA=new Int16Array(127);bA[y.mainVolume]=100;bA[y.expressionController]=127;bA[y.pan]=64;bA[y.releaseTime]=64;bA[y.brightness]=64;bA[y.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,y.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 I=a=>a===y.dataDecrement||a===y.dataIncrement||a===y.dataEntryMsb||a===y.dataDecrement||a===y.lsbForControl6DataEntry||a===y.RPNLsb||a===y.RPNMsb||a===y.NRPNLsb||a===y.NRPNMsb||a===y.bankSelect||a===y.lsbForControl0BankSelect||a===y.resetAllControllers,C=[];for(let a=0;a<t;a++)C.push(Array.from(bA));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),u=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[u]=Q.messageData[1]<<7|Q.messageData[0];break;case S.programChange:let m=o[u];m.program=Q.messageData[0],m.actualBank=m.bank;break;case S.controllerChange:let f=Q.messageData[0];if(I(f))if(this.sendMIDIMessages)this.sendMIDIMessage([S.controllerChange|u%16,f,Q.messageData[1]]);else{let d=Q.messageData[1];if(f===y.bankSelect){o[u].bank=d;break}this.synth.controllerChange(u,f,d)}else C[u]===void 0&&(C[u]=Array.from(bA)),C[u][f]=Q.messageData[1];break;default:this._processEvent(Q,a);break}this.eventIndex[a]++,a=this._findFirstEventIndex();let l=this.tracks[a][this.eventIndex[a]];if(l===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(l.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!==bA[h]&&!I(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,y.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!==bA[h]&&!I(h)&&this.synth.controllerChange(a,h,Q)}),o[a].program>=0&&o[a].actualBank>=0){let Q=o[a].actualBank;this.synth.controllerChange(a,y.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(I=>I.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(pA.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}},fi={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:BA.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 IA=128,It=147,LA=new Int16Array(It).fill(0);LA[y.mainVolume]=12800;LA[y.expressionController]=16256;LA[y.pan]=8192;LA[y.releaseTime]=8192;LA[y.brightness]=8192;LA[y.effects1Depth]=5120;LA[IA+q.pitchWheel]=8192;LA[IA+q.pitchWheelRange]=256;var BA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},eA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Ss=Object.keys(eA).length,rt=new Float32Array(Ss);rt[eA.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",midiEncoding:"MENC",bankOffset:"DBNK"};var Fe=class{constructor(A,t=""){YA("%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 I=!1;this.midiName="",this.rawMidiName=new Uint8Array(0);let C=!1,a=W(s,4);if(s.currentIndex-=4,a==="RIFF"){s.currentIndex+=8;let d=W(s,4,void 0,!1);if(d!=="RMID")throw AA(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${d}"`);let F=nA(s);if(F.header!=="data")throw AA(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${d}"`);for(o=F.chunkData;s.currentIndex<=s.length;){let k=s.currentIndex,K=nA(s,!0);if(K.header==="RIFF")W(K.chunkData,4)==="sfbk"&&(p("%cFound embedded soundfont!",i.recognized),this.embeddedSoundFont=s.slice(k,k+K.size).buffer);else if(K.header==="LIST"&&W(K.chunkData,4)==="INFO"){for(p("%cFound RMIDI INFO chunk!",i.recognized),this.RMIDInfo={};K.chunkData.currentIndex<=K.size;){let b=nA(K.chunkData,!0);this.RMIDInfo[b.header]=b.chunkData}this.RMIDInfo.ICOP&&(I=!0,this.copyright=W(this.RMIDInfo.ICOP,this.RMIDInfo.ICOP.length)),this.RMIDInfo.INAM&&(this.rawMidiName=this.RMIDInfo[we.name],this.midiName=W(this.rawMidiName,this.rawMidiName.length,void 0,!1),C=!0),this.bankOffset=1,this.RMIDInfo[we.bankOffset]&&(this.bankOffset=J(this.RMIDInfo[we.bankOffset],2))}}}else o=s;let Q=this.readMIDIChunk(o);if(Q.type!=="MThd")throw AA(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${Q.type}"`);if(Q.size!==6)throw AA(),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,u=null;this.lastVoiceEventTick=0,this.midiPorts=[];let l=0;this.midiPortChannelOffsets=[],this.usedChannelsOnTrack=[],this.tracks=[];for(let d=0;d<this.tracksAmount;d++){let F=[],k=this.readMIDIChunk(o),K=new Set;if(this.midiPorts.push(-1),k.type!=="MTrk")throw AA(),new SyntaxError(`Invalid track header! Expected "MTrk" got "${k.type}"`);let L,b=0;for(this.format===2&&d>0&&(b+=this.tracks[d-1][this.tracks[d-1].length-1].ticks);k.data.currentIndex<k.size;){b+=ke(k.data);let z=k.data[k.data.currentIndex],Y;if(L!==void 0&&z<128)Y=L;else{if(!L&&z<128)throw AA(),new SyntaxError(`Unexpected byte with no running byte. (${z})`);Y=k.data[k.data.currentIndex++]}let r=Tt(Y),V;switch(r){case-1:V=0;break;case-2:Y=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[Y>>4],(Y&240)===S.noteOn){K.add(r);let uA=k.data[k.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,uA),this.keyRange.max=Math.max(this.keyRange.max,uA)}L=Y;break}let P=new U(V),v=k.data.slice(k.data.currentIndex,k.data.currentIndex+V);k.data.currentIndex+=V,P.set(v,0);let oA=new _A(b,Y,P);switch(F.push(oA),r){case-2:switch(Y){case S.setTempo:this.tempoChanges.push({ticks:b,tempo:6e7/KA(v,3)});break;case S.marker:switch(W(P,P.length).trim().toLowerCase()){default:break;case"start":case"loopstart":h=b;break;case"loopend":u=b}P.currentIndex=0;break;case S.midiPort:let sA=P[0];this.midiPorts[d]=sA,this.midiPortChannelOffsets[sA]===void 0&&(this.midiPortChannelOffsets[sA]=l,l+=16);break;case S.copyright:I||(this.copyright+=W(P,P.length,void 0,!1)+`
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),AA(),o&&delete this.dataArray}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 AA(),new SyntaxError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw AA(),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&&T(`%cPreset ${A}.${t} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,i.warn,i.recognized)),s||(T(`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||(T("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(I=>{s.find(C=>C.bank===I.bank&&C.program===I.program)===void 0&&s.push(I)});return new e({presets:s,info:t.soundFontInfo})}};qA.prototype.write=Qs;var FA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},pA={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 I=this.playingNotes.findIndex(C=>C.midiNote===e.messageData[0]&&C.channel===t.channel);I!==-1&&this.playingNotes.splice(I,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),T("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(pA.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:T(`%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===wA&&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 bA=new Int16Array(127);bA[y.mainVolume]=100;bA[y.expressionController]=127;bA[y.pan]=64;bA[y.releaseTime]=64;bA[y.brightness]=64;bA[y.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,y.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 I=a=>a===y.dataDecrement||a===y.dataIncrement||a===y.dataEntryMsb||a===y.dataDecrement||a===y.lsbForControl6DataEntry||a===y.RPNLsb||a===y.RPNMsb||a===y.NRPNLsb||a===y.NRPNMsb||a===y.bankSelect||a===y.lsbForControl0BankSelect||a===y.resetAllControllers,C=[];for(let a=0;a<t;a++)C.push(Array.from(bA));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),u=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[u]=Q.messageData[1]<<7|Q.messageData[0];break;case S.programChange:let m=o[u];m.program=Q.messageData[0],m.actualBank=m.bank;break;case S.controllerChange:let f=Q.messageData[0];if(I(f))if(this.sendMIDIMessages)this.sendMIDIMessage([S.controllerChange|u%16,f,Q.messageData[1]]);else{let d=Q.messageData[1];if(f===y.bankSelect){o[u].bank=d;break}this.synth.controllerChange(u,f,d)}else C[u]===void 0&&(C[u]=Array.from(bA)),C[u][f]=Q.messageData[1];break;default:this._processEvent(Q,a);break}this.eventIndex[a]++,a=this._findFirstEventIndex();let l=this.tracks[a][this.eventIndex[a]];if(l===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(l.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!==bA[h]&&!I(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,y.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!==bA[h]&&!I(h)&&this.synth.controllerChange(a,h,Q)}),o[a].program>=0&&o[a].actualBank>=0){let Q=o[a].actualBank;this.synth.controllerChange(a,y.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(I=>I.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(pA.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}},fi={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:BA.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 IA=128,It=147,LA=new Int16Array(It).fill(0);LA[y.mainVolume]=12800;LA[y.expressionController]=16256;LA[y.pan]=8192;LA[y.releaseTime]=8192;LA[y.brightness]=8192;LA[y.effects1Depth]=5120;LA[IA+q.pitchWheel]=8192;LA[IA+q.pitchWheelRange]=256;var BA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},eA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Ss=Object.keys(eA).length,rt=new Float32Array(Ss);rt[eA.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",midiEncoding:"MENC",bankOffset:"DBNK"};var Fe=class{constructor(A,t=""){YA("%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 I=!1;this.midiName="",this.rawMidiName=new Uint8Array(0);let C=!1,a=W(s,4);if(s.currentIndex-=4,a==="RIFF"){s.currentIndex+=8;let d=W(s,4,void 0,!1);if(d!=="RMID")throw AA(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${d}"`);let F=nA(s);if(F.header!=="data")throw AA(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${d}"`);for(o=F.chunkData;s.currentIndex<=s.length;){let k=s.currentIndex,K=nA(s,!0);if(K.header==="RIFF"){let L=W(K.chunkData,4);(L==="sfbk"||L==="sfpk")&&(p("%cFound embedded soundfont!",i.recognized),this.embeddedSoundFont=s.slice(k,k+K.size).buffer)}else if(K.header==="LIST"&&W(K.chunkData,4)==="INFO"){for(p("%cFound RMIDI INFO chunk!",i.recognized),this.RMIDInfo={};K.chunkData.currentIndex<=K.size;){let b=nA(K.chunkData,!0);this.RMIDInfo[b.header]=b.chunkData}this.RMIDInfo.ICOP&&(I=!0,this.copyright=W(this.RMIDInfo.ICOP,this.RMIDInfo.ICOP.length)),this.RMIDInfo.INAM&&(this.rawMidiName=this.RMIDInfo[we.name],this.midiName=W(this.rawMidiName,this.rawMidiName.length,void 0,!1),C=!0),this.bankOffset=1,this.RMIDInfo[we.bankOffset]&&(this.bankOffset=J(this.RMIDInfo[we.bankOffset],2))}}}else o=s;let Q=this.readMIDIChunk(o);if(Q.type!=="MThd")throw AA(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${Q.type}"`);if(Q.size!==6)throw AA(),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,u=null;this.lastVoiceEventTick=0,this.midiPorts=[];let l=0;this.midiPortChannelOffsets=[],this.usedChannelsOnTrack=[],this.tracks=[];for(let d=0;d<this.tracksAmount;d++){let F=[],k=this.readMIDIChunk(o),K=new Set;if(this.midiPorts.push(-1),k.type!=="MTrk")throw AA(),new SyntaxError(`Invalid track header! Expected "MTrk" got "${k.type}"`);let L,b=0;for(this.format===2&&d>0&&(b+=this.tracks[d-1][this.tracks[d-1].length-1].ticks);k.data.currentIndex<k.size;){b+=ke(k.data);let z=k.data[k.data.currentIndex],Y;if(L!==void 0&&z<128)Y=L;else{if(!L&&z<128)throw AA(),new SyntaxError(`Unexpected byte with no running byte. (${z})`);Y=k.data[k.data.currentIndex++]}let r=Tt(Y),V;switch(r){case-1:V=0;break;case-2:Y=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[Y>>4],(Y&240)===S.noteOn){K.add(r);let uA=k.data[k.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,uA),this.keyRange.max=Math.max(this.keyRange.max,uA)}L=Y;break}let P=new U(V),v=k.data.slice(k.data.currentIndex,k.data.currentIndex+V);k.data.currentIndex+=V,P.set(v,0);let oA=new _A(b,Y,P);switch(F.push(oA),r){case-2:switch(Y){case S.setTempo:this.tempoChanges.push({ticks:b,tempo:6e7/KA(v,3)});break;case S.marker:switch(W(P,P.length).trim().toLowerCase()){default:break;case"start":case"loopstart":h=b;break;case"loopend":u=b}P.currentIndex=0;break;case S.midiPort:let sA=P[0];this.midiPorts[d]=sA,this.midiPortChannelOffsets[sA]===void 0&&(this.midiPortChannelOffsets[sA]=l,l+=16);break;case S.copyright:I||(this.copyright+=W(P,P.length,void 0,!1)+`
12
12
  `);break;case S.lyric:this.lyrics.push(P)}break;case-3:if(aA(P.slice(0,7)).trim()==="41 10 45 12 10 00 00"){let uA=P.slice(7,v.length-3),sA=W(uA,uA.length)+`
13
13
  `;this.copyright+=sA,p(`%cDecoded Roland SC message! %c${sA}`,i.recognized,i.value)}break;default:if((Y&240)===S.controllerChange)switch(P[0]){case 2:case 116:h=b;break;case 4:case 117:u===null?u=b:u=0;break}}}this.tracks.push(F),this.usedChannelsOnTrack.push(K),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,i.info,i.value,i.info,i.value)}let m=[];for(let d of this.tracks){let F=d.find(k=>(k.messageStatusByte&240)===S.noteOn);F&&m.push(F.ticks)}this.firstNoteOn=Math.min(...m),p(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}`,i.info,i.recognized),AA(),h!==null&&u===null?(h=this.firstNoteOn,u=this.lastVoiceEventTick):(h===null&&(h=this.firstNoteOn),(u===null||u===0)&&(u=this.lastVoiceEventTick));let f=0;for(let d of this.midiPorts)if(d!==-1){f=d;break}if(this.midiPorts=this.midiPorts.map(d=>d===-1?f:d),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.loop={start:h,end:u},!C)if(this.tracks.length>1){if(this.tracks[0].find(d=>d.messageStatusByte>=S.noteOn&&d.messageStatusByte<S.polyPressure)===void 0){let d=this.tracks[0].find(F=>F.messageStatusByte===S.trackName);d&&(this.rawMidiName=d.messageData,this.midiName=W(d.messageData,d.messageData.length,void 0,!1))}}else{let d=this.tracks[0].find(F=>F.messageStatusByte===S.trackName);d&&(this.rawMidiName=d.messageData,this.midiName=W(d.messageData,d.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 d=0;d<this.midiName.length;d++)this.rawMidiName[d]=this.midiName.charCodeAt(d)}this.tempoChanges.reverse(),this.duration=this._ticksToSeconds(this.lastVoiceEventTick)}readMIDIChunk(A){let t={};t.type=W(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){YA("%cSearching for all used programs and keys...",i.info);let t=16+e.midiPortChannelOffsets.reduce((l,m)=>m>l?m:l),s=[];for(let l=0;l<t;l++){let m=l%16===wA?128:0;s.push({program:0,bank:m,drums:l%16===wA,string:`${m}:0`})}function o(l){let m=A.getPreset(l.bank,l.program);l.bank=m.bank,l.program=m.program,l.string=l.bank+":"+l.program,I[l.string]||(p(`%cDetected a new preset: %c${l.string}`,i.info,i.recognized),I[l.string]=new Set)}let I={},C=Array(e.tracks.length).fill(0),a=e.tracks.length;function Q(){let l=0,m=1/0;return e.tracks.forEach((f,d)=>{C[d]>=f.length||f[C[d]].ticks<m&&(l=d,m=f[C[d]].ticks)}),l}let h=e.midiPorts.slice(),u="gs";for(;a>0;){let l=Q(),m=e.tracks[l];if(C[l]>=m.length){a--;continue}let f=m[C[l]];if(C[l]++,f.messageStatusByte===S.midiPort){h[l]=f.messageData[0];continue}let d=f.messageStatusByte&240;if(d!==S.noteOn&&d!==S.controllerChange&&d!==S.programChange&&d!==S.systemExclusive)continue;let F=(f.messageStatusByte&15)+e.midiPortChannelOffsets[h[l]]||0,k=s[F];switch(d){case S.programChange:k.program=f.messageData[0],o(k);break;case S.controllerChange:if(f.messageData[0]!==y.bankSelect||u==="gs"&&k.drums)continue;let K=f.messageData[1],L=Math.max(0,K-e.bankOffset);if(u==="xg"){let Y=K===120||K===126||K===127;Y!==k.drums?(k.drums=Y,k.bank=k.drums?128:L,o(k)):k.bank=k.drums?128:L;continue}s[F].bank=L;break;case S.noteOn:if(f.messageData[1]===0)continue;o(k),I[k.string].add(`${f.messageData[0]}-${f.messageData[1]}`);break;case S.systemExclusive:if(f.messageData[0]!==65||f.messageData[2]!==66||f.messageData[3]!==18||f.messageData[4]!==64||!(f.messageData[5]&16)||f.messageData[6]!==21){f.messageData[0]===67&&f.messageData[2]===76&&f.messageData[5]===126&&f.messageData[6]===0&&(u="xg");continue}let b=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][f.messageData[5]&15]+e.midiPortChannelOffsets[h[l]],z=!!(f.messageData[7]>0&&f.messageData[5]>>4);k=s[b],k.drums=z,k.bank=z?128:0,o(k);break}}for(let l of Object.keys(I))I[l].size===0&&(p(`%cDetected change but no keys for %c${l}`,i.info,i.value),delete I[l]);return AA(),I}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)p("%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(),YA("%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]),I=parseInt(t.split(":")[1]),C=this.synth.getPreset(o,I);p(`%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]))}}AA()}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),p(`%cTotal song time: ${Ze(Math.ceil(this.duration)).time}`,i.recognized),this.post(pA.songChange,[new De(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(T(`%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(pA.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 FA.loadNewSongList:this.loadNewSongList(A);break;case FA.pause:this.pause();break;case FA.play:this.play(A);break;case FA.stop:this.stop();break;case FA.setTime:this.currentTime=A;break;case FA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case FA.setPlaybackRate:this.playbackRate=A;break;case FA.setLoop:this.loop=A;break;case FA.changeSong:A?this.nextSong():this.previousSong();break;case FA.getMIDI:this.post(pA.getMIDI,this.midiData);break;case FA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Ns(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:lA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function Ms(e){this.post(pA.midiEvent,e)}var rA=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(pA.timeChange,currentTime-A);let t=this._playTo(A);this._recalculateStartTime(A),t&&this.play()}pause(A=!1){if(this.paused){T("Already paused");return}this.pausedTime=this.currentTime,this.stop(),this.post(pA.pause,A)}stop(){this.clearProcessHandler();for(let A=0;A<16;A++)this.synth.controllerChange(A,y.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}};rA.prototype.post=Ns;rA.prototype.sendMIDIMessage=Ms;rA.prototype.assignMIDIPort=ks;rA.prototype.processMessage=xs;rA.prototype._processEvent=hs;rA.prototype._addNewMidiPort=cs;rA.prototype._processTick=ls;rA.prototype._findFirstEventIndex=fs;rA.prototype.loadNewSequence=ws;rA.prototype.loadNewSongList=Fs;rA.prototype.nextSong=Rs;rA.prototype.previousSong=Gs;rA.prototype.play=ds;rA.prototype._playTo=us;rA.prototype.setTimeTicks=ms;rA.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 QA(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 GA(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 tA=16384,jA=new Float32Array(tA),$A=new Float32Array(tA);jA[0]=0;jA[tA-1]=1;$A[0]=0;$A[tA-1]=1;for(let e=1;e<tA-1;e++){let A=-.4166666666666667*Math.log(e/(tA-1))/Math.LN10;$A[e]=1-A,jA[tA-1-e]=A}function vA(e,A,t,s){switch(e&&(t=1-t),A){case fA.linear:return s?t*2-1:t;case fA.switch:return t=t>.5?1:0,s?t*2-1:t;case fA.concave:return s?(t=t*2-1,t<0?1-jA[~~(t*-tA)]-1:jA[~~t*tA]):jA[~~(t*tA)];case fA.convex:return s?(t=t*2-1,t<0?1-$A[~~(t*-tA)]-1:$A[~~(t*tA)]):$A[~~(t*tA)]}}var Et=1,Bt=new Float32Array(1e3);for(let e=0;e<Bt.length;e++)Bt[e]=vA(0,fA.convex,e/1e3,0);function bs(e,A){let t=QA(e.modulatedGenerators[B.attackModEnv]),s=QA(e.modulatedGenerators[B.decayModEnv]+(60-e.midiNote)*e.modulatedGenerators[B.keyNumToModEnvDecay]),o=QA(e.modulatedGenerators[B.holdModEnv]+(60-e.midiNote)*e.modulatedGenerators[B.keyNumToModEnvHold]);if(e.isInRelease&&e.releaseStartTime<A){let l=QA(e.modulatedGenerators[B.releaseModEnv]);return e.modulatedGenerators[B.releaseModEnv]<-7199?e.releaseStartModEnv:(1-(A-e.releaseStartTime)/l)*e.releaseStartModEnv}let I=1-e.modulatedGenerators[B.sustainModEnv]/1e3,C=QA(e.modulatedGenerators[B.delayModEnv])+e.startTime,a=t+C,Q=o+a,h=s+Q,u;return A<C?u=0:A<a?u=Bt[~~((1-(a-A)/t)*1e3)]:A<Q?u=Et:A<h?u=(1-(h-A)/s)*(I-Et)+Et:u=I,e.currentModEnvValue=u,u}function Ls(e,A,t){let s=e.sample.cursor,o=e.sample.loopingMode===1||e.sample.loopingMode===3&&!e.isInRelease,I=e.sample.loopEnd-e.sample.loopStart;if(o)for(let C=0;C<t.length;C++){for(;s>=e.sample.loopEnd;)s-=I;let a=~~s,Q=a+1;for(;Q>=e.sample.loopEnd;)Q-=I;let h=s-a,u=A[Q],l=A[a];t[C]=l+(u-l)*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,u=A[Q],l=A[a];t[C]=l+(u-l)*h,s+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=s}function Hs(e,A,t,s,o,I,C,a,Q){if(!isNaN(t[0])){if(C>0){let h=I[0],u=I[1];C=Math.min(C,1e3);let l=C/500,m=e*l,f=A*l;for(let d=0;d<t.length;d++)h[d]+=m*t[d],u[d]+=f*t[d]}if(Q>0){let h=a[0],u=a[1];Q=Math.min(Q,1e3);let l=Q/500,m=e*l,f=A*l;for(let d=0;d<t.length;d++)h[d]+=m*t[d],u[d]+=f*t[d]}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=QA(e.modulatedGenerators[B.attackVolEnv]),A.decayDuration=QA(e.modulatedGenerators[B.decayVolEnv]+(60-e.midiNote)*e.modulatedGenerators[B.keyNumToVolEnvDecay]),A.releaseDuration=QA(e.modulatedGenerators[B.releaseVolEnv]),A.attenuation=e.modulatedGenerators[B.initialAttenuation]/10,A.sustainDb=e.volumeEnvelope.attenuation+e.modulatedGenerators[B.sustainVolEnv]/10,A.delayEnd=QA(e.modulatedGenerators[B.delayVolEnv])+e.startTime,A.attackEnd=A.attackDuration+A.delayEnd,A.holdEnd=QA(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)*GA(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,I){let C=s/10,a=e.volumeEnvelope;if(e.isInRelease){let u=I*10,l=a.releaseStartDb+C,m=t-e.releaseStartTime,f=Ys-l,d=a.currentReleaseGain;for(let F=0;F<A.length;F++){let k=m/a.releaseDuration*f+l;d=GA(k+C),a.currentReleaseGain+=(d-a.currentReleaseGain)*u,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 l=(1-(a.attackEnd-Q)/a.attackDuration)*GA(a.attenuation+C);if(A[h]*=l,a.currentAttenuationDb=a.attenuation,Q+=o,++h>=A.length)return}a.state++;case 2:for(;Q<a.holdEnd;){let u=a.attenuation+C;if(a.currentAttenuationDb+=(u-a.currentAttenuationDb)*I,A[h]*=GA(a.currentAttenuationDb),Q+=o,++h>=A.length)return}a.state++;case 3:for(;Q<a.decayEnd;){let u=(1-(a.decayEnd-Q)/a.decayDuration)*(a.sustainDb-a.attenuation)+a.attenuation+C;if(a.currentAttenuationDb+=(u-a.currentAttenuationDb)*I,A[h]*=GA(a.currentAttenuationDb),Q+=o,++h>=A.length)return}a.state++;case 4:for(;;){let u=a.sustainDb+C;if(a.currentAttenuationDb+=(u-a.currentAttenuationDb)*I,A[h]*=GA(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],I=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=I,A[s]=I}}}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=GA(-1*A);let t=1/Math.sqrt(e.filter.reasonanceGain),s=2*Math.PI*e.filter.cutoffHz/sampleRate,o=Math.cos(s),I=Math.sin(s)/(2*e.filter.reasonanceGain),C=(1-o)*t,a=C/2,Q=a,h=1+I,u=-2*o,l=1-I;e.filter.a0=a/h,e.filter.a1=C/h,e.filter.a2=Q/h,e.filter.a3=u/h,e.filter.a4=l/h}var Vs=Math.PI/2,Os=.01;function vs(e,A,t,s,o,I){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.releaseStartModEnv=A.currentModEnvValue,A.isInRelease=!0,ZA(A),A.volumeEnvelope.currentReleaseGain=GA(A.volumeEnvelope.currentAttenuationDb)),A.modulatedGenerators[B.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let C=A.targetKey,a=A.modulatedGenerators[B.fineTune]+e.customControllers[eA.channelTuning]+e.customControllers[eA.channelTransposeFine]+e.customControllers[eA.masterTuning]+e.channelOctaveTuning[A.midiNote%12],Q=A.modulatedGenerators[B.coarseTune]+e.customControllers[eA.channelTuningSemitones],h=this.tunings[e.preset.program]?.[C];h?.midiNote>=0&&(C=h.midiNote,a+=h.centTuning),a+=(C-A.sample.rootKey)*A.modulatedGenerators[B.scaleTuning];let u=A.modulatedGenerators[B.vibLfoToPitch];if(u!==0){let oA=A.startTime+QA(A.modulatedGenerators[B.delayVibLFO]),uA=ie(A.modulatedGenerators[B.freqVibLFO]),sA=Ge(oA,uA,currentTime);sA&&(a+=sA*(u*e.customControllers[eA.modulationMultiplier]))}let l=A.modulatedGenerators[B.initialFilterFc],m=A.modulatedGenerators[B.modLfoToPitch],f=A.modulatedGenerators[B.modLfoToVolume],d=A.modulatedGenerators[B.modLfoToFilterFc],F=0;if(m+d+f!==0){let oA=A.startTime+QA(A.modulatedGenerators[B.delayModLFO]),uA=ie(A.modulatedGenerators[B.freqModLFO]),sA=Ge(oA,uA,currentTime);a+=sA*(m*e.customControllers[eA.modulationMultiplier]),F=sA*f,l+=sA*d}if(e.channelVibrato.depth>0){let oA=Ge(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);oA&&(a+=oA*e.channelVibrato.depth)}let k=A.modulatedGenerators[B.modEnvToPitch],K=A.modulatedGenerators[B.modEnvToFilterFc],L=bs(A,currentTime);l+=L*K,a+=L*k;let b=~~(a+Q*100);b!==A.currentTuningCents&&(A.currentTuningCents=b,A.currentTuningCalculated=Math.pow(2,b/1200));let z=(Math.max(-500,Math.min(500,A.modulatedGenerators[B.pan]))+500)/1e3,Y=new Float32Array(t.length);Ls(A,this.workletDumpedSamplesList[A.sample.sampleID],Y),Ps(A,Y,l),qs(A,Y,currentTime,F,this.sampleTime,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(z-A.currentPan)*this.panSmoothingFactor;let r=Math.cos(Vs*A.currentPan)*this.panLeft,V=Math.sin(Vs*A.currentPan)*this.panRight,P=this.oneOutputMode?0:A.modulatedGenerators[B.reverbEffectsSend],v=this.oneOutputMode?0:A.modulatedGenerators[B.chorusEffectsSend];Hs(r,V,Y,t,s,o,P,I,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 I=gn(s,o);A.push({channel:s,voice:o,priority:I})}A.sort((s,o)=>s.priority-o.priority);let t=A.slice(0,e);for(let{channel:s,voice:o}of t){let I=s.voices.indexOf(o);I>-1&&s.voices.splice(I,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=RA,this.processTickCallback=void 0,this.sequencer=new rA(this),this.transposition=0,this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);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:lA.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[wA].preset=this.drumPreset,this.workletProcessorChannels[wA].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()),p("%cRendering enabled! Starting render.",i.info),A.processorOptions.startRenderingData.parsedMIDI&&(this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]),this.sequencer.loop=!1)),UA.isInitialized.then(()=>{this.post({messageType:lA.ready,messageData:void 0}),p("%cSpessaSynth is ready!",i.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){p({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,I)=>{if(o.voices.length<1||o.isMuted)return;let C,a,Q,h,u;if(this.oneOutputMode){let m=t[0];C=I%16*2,a=m[C],Q=m[C+1]}else C=I%this._outputsAmount+2,a=t[C][0],Q=t[C][1],h=t[0],u=t[1];let l=o.voices;o.voices=[],l.forEach(m=>{this.renderVoice(o,m,a,Q,h,u),m.finished||o.voices.push(m)}),s+=l.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 X.noteOn:this.noteOn(t,A[0],A[1],A[2]);break;case X.noteOff:this.noteOff(t,A);break;case X.pitchWheel:this.pitchWheel(t,A[0],A[1]);break;case X.ccChange:this.controllerChange(t,A[0],A[1],A[2]);break;case X.customcCcChange:s.customControllers[A[0]]=A[1];break;case X.killNote:this.killNote(t,A);break;case X.programChange:this.programChange(t,A[0],A[1]);break;case X.channelPressure:this.channelPressure(t,A);break;case X.polyPressure:this.polyPressure(t,A[0],A[1]);break;case X.ccReset:t===RA?this.resetAllControllers():this.resetControllers(t);break;case X.systemExclusive:this.systemExclusive(A);break;case X.setChannelVibrato:if(t===RA)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 X.reloadSoundFont:this.reloadSoundFont(A);break;case X.stopAll:t===RA?this.stopAllChannels(A===1):this.stopAll(t,A===1);break;case X.killNotes:this.voiceKilling(A);break;case X.muteChannel:this.muteChannel(t,A);break;case X.addNewChannel:this.createWorkletChannel(!0);break;case X.debugMessage:this.debugMessage();break;case X.setMasterParameter:let o=A[0],I=A[1];switch(o){case ge.masterPan:this.setMasterPan(I);break;case ge.mainVolume:this.setMasterGain(I);break;case ge.voicesCap:this.voiceCap=I;break}break;case X.setDrums:this.setDrums(t,A);break;case X.transpose:t===RA?this.transposeAllChannels(A[0],A[1]):this.transposeChannel(t,A[0],A[1]);break;case X.highPerformanceMode:this.highPerformanceMode=A;break;case X.lockController:A[0]===RA?s.lockPreset=A[1]:s.lockedControllers[A[0]]=A[1];break;case X.sequencerSpecific:this.sequencer.processMessage(A.messageType,A.messageData);break;case X.requestSynthesizerSnapshot:this.sendSynthesizerSnapshot();break;case X.setLogLevel:Vt(A[0],A[1],A[2],A[3]);break;default:T("Unrecognized event:",A);break}}function _s(e,A){this.enableEventSystem&&this.post({messageType:lA.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[IA+q.pitchWheelRange]>>7)+(A.midiControllers[IA+q.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[IA+q.pitchWheel],pitchBendRangeSemitones:t,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:lA.channelProperties,messageData:e})}function an(e,A,t){let s=e,o=A<<7|t;return e===127&&A===127&&t===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:o*.0061}}function $s(e,A=0){let t=e[0];if(!(this.deviceID!==RA&&e[1]!==127&&this.deviceID!==e[1]))switch(t){default:T(`%cUnrecognized SysEx: %c${aA(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),p(`%cMaster Volume. Volume: %c${o}`,i.info,i.value);break;case 2:let C=((e[5]<<7|e[4])-8192)/8192;this.setMasterPan(C),p(`%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),p(`%cMaster Fine Tuning. Cents: %c${s}`,i.info,i.value);break;case 4:s=(e[5]-64)*100,this.setMasterTuning(s),p(`%cMaster Coarse Tuning. Cents: %c${s}`,i.info,i.value);break;default:T(`%cUnrecognized MIDI Device Control Real-time message: %c${aA(e)}`,i.warn,i.unrecognized)}break;case 9:e[3]===1?(p("%cGM system on",i.info),this.system="gm"):e[3]===3?(p("%cGM2 system on",i.info),this.system="gm2"):(p("%cGM system off, defaulting to GS",i.info),this.system="gs");break;case 8:switch(e[3]){case 2:case 7:let o=4;e[3]===7&&o++;let I=e[o++],C=e[o++];for(let Q=0;Q<C;Q++)this.tunings[I][e[o++]]=an(e[o++],e[o++],e[o++]);p(`%cSingle Note Tuning. Program: %c${I}%c Keys affected: ${C}`,i.info,i.recognized,i.info,i.recognized);break;case 9:case 8:let a=new Int8Array(12);if(e[3]===8)for(let Q=0;Q<12;Q++)a[Q]=e[7+Q]-64;else for(let Q=0;Q<24;Q+=2){let h=(e[7+Q]<<7|e[8+Q])-8192;a[Q/2]=Math.floor(h/81.92)}(e[4]&1)===1&&this.setOctaveTuning(14+A,a),(e[4]>>1&1)===1&&this.setOctaveTuning(15+A,a);for(let Q=0;Q<7;Q++)(e[5]>>Q&1)===1&&this.setOctaveTuning(7+Q+A,a);for(let Q=0;Q<7;Q++)(e[6]>>Q&1)===1&&this.setOctaveTuning(Q+A,a);p(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${a.join(" ")}`,i.info,i.value);break;default:T(`%cUnrecognized MIDI Tuning standard message: %c${aA(e)}`,i.warn,i.unrecognized);break}break;default:T(`%cUnrecognized MIDI Realtime/non realtime message: %c${aA(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?(p("%cGS system on",i.info),this.system="gs"):s===127&&(p("%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 I=s>0&&e[5]>>4;this.setDrums(o,I),p(`%cChannel %c${o}%c ${I?"is now a drum channel":"now isn't a drum channel"}%c via: %c${aA(e)}`,i.info,i.value,i.recognized,i.info,i.value);return;case 22:let C=s-64;this.transposeChannel(o,C),p(`%cChannel %c${o}%c pitch shift. Semitones %c${C}%c, with %c${aA(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;p(`%cChannel %c${o}%c tuning. Cents %c${a}%c, with %c${aA(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){p(`%cRoland GS Master Pan set to: %c${s}%c with: %c${aA(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;p(`%cRoland GS Master Key-Shift set to: %c${o}%c with: %c${aA(e)}`,i.info,i.value,i.info,i.value),this.setMasterTuning(o*100);return}else if(e[5]===0&&e[6]===4){p(`%cRoland GS Master Volume set to: %c${s}%c with: %c${aA(e)}`,i.info,i.value,i.info,i.value),this.setMIDIVolume(s/127);return}}T(`%cUnrecognized Roland %cGS %cSysEx: %c${aA(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),p(`%cRoland Master Volume control set to: %c${e[7]}%c via: %c${aA(e)}`,i.info,i.value,i.info,i.value);return}else{T(`%cUnrecognized Roland SysEx: %c${aA(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),p(`%cXG master volume. Volume: %c${s}`,i.info,i.recognized);break;case 6:let o=e[6]-64;this.transposeAllChannels(o),p(`%cXG master transpose. Volume: %c${o}`,i.info,i.recognized);break;case 126:p("%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,y.bankSelect,o);break;case 2:this.controllerChange(s,y.lsbForControl0BankSelect,o);break;case 3:this.programChange(s,o);break;case 11:this.controllerChange(s,y.mainVolume,o);break;case 14:let I=o;I===0&&(I=Math.floor(Math.random()*127)),this.controllerChange(s,y.pan,I);break;case 19:this.controllerChange(s,y.effects1Depth,o);break;case 18:this.controllerChange(s,y.effects3Depth,o);break;default:T(`%cUnrecognized Yamaha XG Part Setup: %c${e[5].toString(16).toUpperCase()}`,i.warn,i.unrecognized)}}else this.system==="xg"&&T(`%cUnrecognized Yamaha XG SysEx: %c${aA(e)}`,i.warn,i.unrecognized);else this.system==="xg"&&T(`%cUnrecognized Yamaha SysEx: %c${aA(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,I,C,a,Q,h=!1){let u,l=a[A][t];return l!==void 0?(u=l.map(ae),u.forEach(m=>{m.startTime=o})):(u=s.getSamplesAndGenerators(A,t).reduce((m,f)=>{let d=f.sampleID+Q;if(xe[d]!==!0&&Cn(e,f.sample,d,C),f.sample.sampleData===void 0)return T(`Discarding invalid sample: ${f.sample.sampleName}`),m;let F=new Int16Array(60);for(let V=0;V<60;V++)F[V]=jt(V,f.presetGenerators,f.instrumentGenerators);F[B.initialAttenuation]=Math.floor(F[B.initialAttenuation]*.4);let k=f.sample.samplePitch;F[B.overridingRootKey]>-1&&(k=F[B.overridingRootKey]);let K=A;F[B.keyNum]>-1&&(K=F[B.keyNum]);let L=f.sample.sampleLoopStartIndex/2+(F[B.startloopAddrsOffset]+F[B.startloopAddrsCoarseOffset]*32768),b=f.sample.sampleLoopEndIndex/2+(F[B.endloopAddrsOffset]+F[B.endloopAddrsCoarseOffset]*32768),z=F[B.sampleModes],Y=f.sample.getAudioData().length;L=Math.min(Math.max(0,L),Y),b=Math.min(Math.max(0,b),Y),b-L<1&&(z=0);let r={sampleID:d,playbackStep:f.sample.sampleRate/I*Math.pow(2,f.sample.samplePitchCorrection/1200),cursor:F[B.startAddrsOffset]+F[B.startAddrsCoarseOffset]*32768,rootKey:k,loopStart:L,loopEnd:b,end:Math.floor(f.sample.sampleData.length)-1+(F[B.endAddrOffset]+F[B.endAddrsCoarseOffset]*32768),loopingMode:z};return F[B.velocity]>-1&&(t=F[B.velocity]),h&&Ot([{Sample:f.sample.sampleName,Generators:F,Modulators:f.modulators.map(V=>V.debugString()),Velocity:t,TargetKey:K,MidiNote:A,WorkletSample:r}]),m.push({filter:ae(Ks),generators:F,modulators:f.modulators,modulatedGenerators:new Int16Array(60),sample:r,velocity:t,midiNote:A,pressure:0,channelNumber:e,startTime:o,targetKey:K,currentTuningCalculated:1,currentTuningCents:0,releaseStartTime:1/0,finished:!1,isInRelease:!1,currentModEnvValue:0,releaseStartModEnv:1,currentPan:.5,volumeEnvelope:ae(Ts)}),m},[]),a[A][t]=u.map(ae)),u}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+IA;switch(A.sourceIndex){case q.noController:s=16383;break;case q.noteOnKeyNum:s=t.midiNote<<7;break;case q.noteOnVelocity:s=t.velocity<<7;break;case q.polyPressure:s=t.pressure<<7;break;default:s=e[Q];break}}let o=hA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],I;if(A.secSrcUsesCC)I=e[A.secSrcIndex];else{let Q=A.secSrcIndex+IA;switch(A.secSrcIndex){case q.noController:I=16383;break;case q.noteOnKeyNum:I=t.midiNote<<7;break;case q.noteOnVelocity:I=t.velocity<<7;break;case q.polyPressure:I=t.pressure<<7;break;default:I=e[Q]}}let C=hA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][I],a=o*C*A.transformAmount;return A.transformType===2?Math.abs(a):a}function TA(e,A,t=-1,s=0){let{modulators:o,generators:I,modulatedGenerators:C}=e;if(t===-1){C.set(I),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 u=h.modulatorDestination;Q.has(u)||(C[u]=I[u],o.forEach(l=>{l.modulatorDestination===u&&(C[u]+=to(A,l,e))}),Q.add(u))}}),[...Q].some(h=>a.has(h))&&ZA(e)}var hA=[];for(let e=0;e<4;e++){hA[e]=[[new Float32Array(tA),new Float32Array(tA)],[new Float32Array(tA),new Float32Array(tA)]];for(let A=0;A<tA;A++)hA[e][0][0][A]=vA(0,e,A/tA,0),isNaN(hA[e][0][0][A])&&(hA[e][0][0][A]=1),hA[e][1][0][A]=vA(0,e,A/tA,1),isNaN(hA[e][1][0][A])&&(hA[e][1][0][A]=1),hA[e][0][1][A]=vA(1,e,A/tA,0),isNaN(hA[e][0][1][A])&&(hA[e][0][1][A]=1),hA[e][1][1][A]=vA(1,e,A/tA,1),isNaN(hA[e][1][1][A])&&(hA[e][1][1][A]=1)}function so(e,A,t,s=!1,o=!0,I=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)return;let a=A+C.channelTransposeKeyShift;if(A>127||A<0)return;let Q=C.preset.program;this.tunings[Q]?.[A]?.midiNote>=0&&(a=this.tunings[Q]?.[A].midiNote);let h=eo(e,a,t,C.preset,I,sampleRate,l=>this.sampleDump(l.channel,l.sampleID,l.sampleData),C.cachedVoices,C.presetUsesOverride?this.soundfont.samples.length:0,s),u=C.voices;h.forEach(l=>{let m=l.generators[B.exclusiveClass];m!==0&&u.forEach(f=>{f.generators[B.exclusiveClass]===m&&(this.releaseVoice(f),f.modulatedGenerators[B.releaseVolEnv]=-7e3,f.modulatedGenerators[B.releaseModEnv]=-7e3,ZA(f))}),TA(l,C.midiControllers),l.currentPan=(Math.max(-500,Math.min(500,l.modulatedGenerators[B.pan]))+500)/1e3}),this.totalVoicesAmount+=h.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(h.length),u.push(...h),o&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:e,velocity:t}))}function oo(e,A){if(A>127||A<0){T("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){p("%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),I=s.channelTransposeKeyShift+s.customControllers[eA.channelTransposeFine]/100;s.drumChannel&&!t||A===I||(o!==s.channelTransposeKeyShift&&this.stopAll(e,!1),s.channelTransposeKeyShift=o,s.customControllers[eA.channelTransposeFine]=(A-o)*100)}function ao(e,A,t=!0){let s=this.workletProcessorChannels[e];A=Math.round(A),s.customControllers[eA.channelTuning]=A,t&&p(`%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[eA.channelTuningSemitones]=A,p(`%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[eA.masterTuning]=e}function Bo(e,A){let t=this.workletProcessorChannels[e];A=Math.round(A),p(`%cChannel ${e} modulation depth. Cents: %c${A}`,i.info,i.value),t.customControllers[eA.modulationMultiplier]=A/50}function Qo(e,A,t){if(this.workletProcessorChannels[e].lockedControllers[IA+q.pitchWheel])return;let s=t|A<<7;this.callEvent("pitchwheel",{channel:e,MSB:A,LSB:t}),this.workletProcessorChannels[e].midiControllers[IA+q.pitchWheel]=s,this.workletProcessorChannels[e].voices.forEach(o=>TA(o,this.workletProcessorChannels[e].midiControllers,0,q.pitchWheel)),this.sendChannelProperties()}function ho(e,A){let t=this.workletProcessorChannels[e];t.midiControllers[IA+q.channelPressure]=A<<7,this.workletProcessorChannels[e].voices.forEach(s=>TA(s,t.midiControllers,0,q.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,TA(s,this.workletProcessorChannels[e].midiControllers,0,q.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>=y.lsbForControl1ModulationWheel&&A<=y.lsbForControl13EffectControl2&&A!==y.lsbForControl6DataEntry){let I=A-32;if(o.lockedControllers[I])return;o.midiControllers[I]=o.midiControllers[I]&16256|t&127,o.voices.forEach(C=>TA(C,o.midiControllers,1,I))}switch(A){case y.allNotesOff:this.stopAll(e);break;case y.allSoundOff:this.stopAll(e,!0);break;case y.bankSelect:let I=t;if(!s){switch(this.system){case"gm":p(`%cIgnoring the Bank Select (${t}), as the synth is in GM mode.`,i.info);return;case"xg":I===120||I===126||I===127?this.setDrums(e,!0):this.setDrums(e,!1);break;case"gm2":I===120&&(o.drumChannel=!0,this.callEvent("drumchange",{channel:e,isDrumChannel:!0}))}o.drumChannel&&(I=128),I===128&&!o.drumChannel&&(I=o.midiControllers[y.bankSelect])}o.midiControllers[y.bankSelect]=I;break;case y.lsbForControl0BankSelect:this.system==="xg"?o.drumChannel||t!==127&&(o.midiControllers[y.bankSelect]=t):this.system==="gm2"&&(o.midiControllers[y.bankSelect]=t);break;case y.RPNLsb:o.RPValue=o.RPValue<<7|t,o.dataEntryState=BA.RPFine;break;case y.RPNMsb:o.RPValue=t,o.dataEntryState=BA.RPCoarse;break;case y.NRPNMsb:o.NRPCoarse=t,o.dataEntryState=BA.NRPCoarse;break;case y.NRPNLsb:o.NRPFine=t,o.dataEntryState=BA.NRPFine;break;case y.dataEntryMsb:this.dataEntryCoarse(e,t);break;case y.lsbForControl6DataEntry:this.dataEntryFine(e,t);break;case y.resetAllControllers:this.resetControllers(e);break;case y.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=>TA(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 BA.Idle:break;case BA.NRPFine:if(this.system!=="gs")return;switch(t.NRPCoarse){default:if(A===64)return;T(`%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;T(`%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,p(`%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,p(`%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,p(`%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 I=A;this.controllerChange(e,y.brightness,A),p(`%cFilter cutoff for %c${e}%c is now set to %c${I}`,i.info,i.recognized,i.info,i.value)}break;case 29:if(!t.drumChannel)return;let o=A;this.controllerChange(e,y.effects1Depth,o),p(`%cGS Drum reverb for %c${e}%c: %c${o}`,i.info,i.recognized,i.info,i.value);break}break;case BA.RPCoarse:case BA.RPFine:switch(t.RPValue){default:T(`%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[IA+q.pitchWheelRange]=A<<7,p(`%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 BA.RPCoarse:case BA.RPFine:switch(t.RPValue){default:break;case 0:if(A===0)break;t.midiControllers[IA+q.pitchWheelRange]|=A;let s=(t.midiControllers[IA+q.pitchWheelRange]>>7)+A/127;p(`%cChannel ${e} bend range. Semitones: %c${s}`,i.info,i.value);break;case 1:let I=t.customControllers[eA.channelTuning]<<7|A;this.setChannelTuning(e,I*.01220703125);break;case 5:let a=t.customControllers[eA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(e,a);break;case 16383:this.resetParameters(e);break}}}function Fo(){p("%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[y.bankSelect]=0,e%16===wA?(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(y.mainVolume),t(y.pan),t(y.expressionController),t(y.modulationWheel),t(y.effects3Depth),t(y.effects1Depth),this.workletProcessorChannels[e].lockedControllers[IA+q.pitchWheel]){let s=this.workletProcessorChannels[e].midiControllers[IA+q.pitchWheel],o=s>>7,I=s&127;this.callEvent("pitchwheel",{channel:e,MSB:o,LSB:I})}}this.tunings=[],this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.setMIDIVolume(1),this.system=pe}function Ro(e){let A=this.workletProcessorChannels[e],s=A.lockedControllers.reduce((I,C,a)=>(C&&I.push(a),I),[]).map(I=>({ccNum:I,ccVal:A.midiControllers[I]}));A.channelOctaveTuning.fill(0),A.midiControllers.set(LA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(I=>{A.midiControllers[I.ccNum]=I.ccVal});let o=A.customControllers[eA.channelTransposeFine];A.customControllers.set(rt),A.customControllers[eA.channelTransposeFine]=o,this.resetParameters(e)}function Go(e){let A=this.workletProcessorChannels[e];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=BA.Idle}function xo(e,A,t=!1){let s=this.workletProcessorChannels[e];if(s.lockPreset)return;let o=s.drumChannel?128:s.midiControllers[y.bankSelect],I,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?(I=o,C=Q,s.presetUsesOverride=!0):this.soundfontBankOffset===0?C=this.overrideSoundfont.getPreset(0,A):(C=this.soundfont.getPreset(o,A),I=C.bank,s.presetUsesOverride=!1)}else C=this.soundfont.getPreset(o,A),I=C.bank,s.presetUsesOverride=!1;this.setPreset(e,C),this.callEvent("programchange",{channel:e,program:C.program,bank:I,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;if(this.soundfontBankOffset===0)return this.overrideSoundfont.getPreset(0,A)}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[y.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.dataArray,this.soundfont.samples.length=0,this.soundfont.instruments.length=0,this.soundfont.presets.length=0,delete this.soundfont);try{A?this.overrideSoundfont=new qA(e):this.soundfont=new qA(e)}catch(t){this.post({messageType:lA.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:lA.ready,messageData:void 0}),this.sendPresetList(),p("%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:lA.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[y.bankSelect]=A.bank,this.programChange(t,A.program),s.lockPreset=A.lockPreset}),p("%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);p("%cProcessor succesfully registered!",i.recognized);
@@ -6,7 +6,7 @@
6
6
  * @property {string|undefined} genre - the song's genre
7
7
  */
8
8
 
9
- import { combineArrays } from './indexed_array.js'
9
+ import { combineArrays, IndexedByteArray } from './indexed_array.js'
10
10
  import { getStringBytes } from './byte_functions/string.js'
11
11
  import { writeRIFFOddSize } from '../soundfont/read/riff_chunk.js'
12
12
 
@@ -20,17 +20,54 @@ import { writeRIFFOddSize } from '../soundfont/read/riff_chunk.js'
20
20
  */
21
21
  export function audioBufferToWav(audioBuffer, normalizeAudio = true, channelOffset = 0, metadata = {})
22
22
  {
23
- // this code currently doesn't add any metadata
24
23
  const channel1Data = audioBuffer.getChannelData(channelOffset);
25
24
  const channel2Data = audioBuffer.getChannelData(channelOffset + 1);
26
25
  const length = channel1Data.length;
27
26
 
28
27
  const bytesPerSample = 2; // 16-bit PCM
29
28
 
29
+ // prepare INFO chunk
30
+ let infoChunk = new IndexedByteArray(0);
31
+ const infoOn = Object.keys(metadata).length > 0;
32
+ // INFO chunk
33
+ if(infoOn)
34
+ {
35
+ const encoder = new TextEncoder();
36
+ const infoChunks = [
37
+ getStringBytes("INFO"),
38
+ writeRIFFOddSize("ICMT", encoder.encode("Created with SpessaSynth"))
39
+ ];
40
+ if(metadata.artist)
41
+ {
42
+ infoChunks.push(
43
+ writeRIFFOddSize("IART", encoder.encode(metadata.artist))
44
+ );
45
+ }
46
+ if(metadata.album)
47
+ {
48
+ infoChunks.push(
49
+ writeRIFFOddSize("IPRD", encoder.encode(metadata.album))
50
+ );
51
+ }
52
+ if(metadata.genre)
53
+ {
54
+ infoChunks.push(
55
+ writeRIFFOddSize("IGNR", encoder.encode(metadata.genre))
56
+ );
57
+ }
58
+ if(metadata.title)
59
+ {
60
+ infoChunks.push(
61
+ writeRIFFOddSize("INAM", encoder.encode(metadata.title))
62
+ );
63
+ }
64
+ infoChunk = writeRIFFOddSize("LIST", combineArrays(infoChunks));
65
+ }
66
+
30
67
  // Prepare the header
31
68
  const headerSize = 44;
32
69
  const dataSize = length * 2 * bytesPerSample; // 2 channels, 16-bit per channel
33
- const fileSize = headerSize + dataSize - 8; // total file size minus the first 8 bytes
70
+ const fileSize = headerSize + dataSize + infoChunk.length - 8; // total file size minus the first 8 bytes
34
71
  const header = new Uint8Array(headerSize);
35
72
 
36
73
  // 'RIFF'
@@ -65,46 +102,13 @@ export function audioBufferToWav(audioBuffer, normalizeAudio = true, channelOffs
65
102
 
66
103
  let wavData;
67
104
  let offset = headerSize;
68
- let infoChunk = undefined;
69
- // INFO chunk
70
- if(Object.keys(metadata).length > 0)
105
+ if(infoOn)
71
106
  {
72
- const encoder = new TextEncoder();
73
- const infoChunks = [
74
- getStringBytes("INFO"),
75
- writeRIFFOddSize("ICMT", encoder.encode("Created with SpessaSynth"))
76
- ];
77
- if(metadata.artist)
78
- {
79
- infoChunks.push(
80
- writeRIFFOddSize("IART", encoder.encode(metadata.artist))
81
- );
82
- }
83
- if(metadata.album)
84
- {
85
- infoChunks.push(
86
- writeRIFFOddSize("IPRD", encoder.encode(metadata.album))
87
- );
88
- }
89
- if(metadata.genre)
90
- {
91
- infoChunks.push(
92
- writeRIFFOddSize("IGNR", encoder.encode(metadata.genre))
93
- );
94
- }
95
- if(metadata.title)
96
- {
97
- infoChunks.push(
98
- writeRIFFOddSize("INAM", encoder.encode(metadata.title))
99
- );
100
- }
101
- infoChunk = writeRIFFOddSize("LIST", combineArrays(infoChunks));
102
107
  wavData = new Uint8Array(headerSize + dataSize + infoChunk.length);
103
108
  }
104
109
  else
105
110
  {
106
111
  wavData = new Uint8Array(headerSize + dataSize);
107
-
108
112
  }
109
113
  wavData.set(header, 0);
110
114
 
@@ -150,7 +154,7 @@ export function audioBufferToWav(audioBuffer, normalizeAudio = true, channelOffs
150
154
  wavData[offset++] = (sample2 >> 8) & 0xff;
151
155
  }
152
156
 
153
- if(infoChunk)
157
+ if(infoOn)
154
158
  {
155
159
  wavData.set(infoChunk, offset);
156
160
  }