spessasynth_lib 3.24.15 → 3.24.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -16,4 +16,4 @@ Converted from SF2 to DLS using SpessaSynth`,this.soundFontInfo.ISFT="SpessaSynt
|
|
|
16
16
|
`+this.soundFontInfo.ISBJ,delete this.soundFontInfo.ISBJ),this.soundFontInfo.ICMT+=`
|
|
17
17
|
Converted from DLS to SF2 with SpessaSynth`;for(let[E,C]of Object.entries(this.soundFontInfo))m(`%c"${E}": %c"${C}"`,a.info,a.recognized);let o=n.find(E=>E.header==="colh");o||(O(),this.parsingError("No colh chunk!")),this.instrumentAmount=w(o.chunkData,4),m(`%cInstruments amount: %c${this.instrumentAmount}`,a.info,a.recognized);let i=NA(n,"wvpl");i||(O(),this.parsingError("No wvpl chunk!")),this.readDLSSamples(i);let g=NA(n,"lins");g||(O(),this.parsingError("No lins chunk!")),this.readDLSInstrumentList(g),this.presets.sort((E,C)=>E.program-C.program+(E.bank-C.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets,
|
|
18
18
|
%c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,a.info,a.recognized,a.info,a.recognized,a.info,a.recognized,a.info,a.recognized,a.info),O()}verifyHeader(A,...t){for(let n of t)if(A.header.toLowerCase()===n.toLowerCase())return;O(),this.parsingError(`Invalid DLS chunk header! Expected "${t.toString()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(O(),this.parsingError(`FourCC error: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`))}parsingError(A){throw new Error(`DLS parse error: ${A} The file may be corrupted.`)}destroySoundfont(){super.destroySoundfont(),delete this.dataArray}};ee.prototype.readDLSInstrumentList=$s;ee.prototype.readDLSInstrument=Ao;ee.prototype.readRegion=so;ee.prototype.readLart=no;ee.prototype.readDLSSamples=ro;var en=class extends re{constructor(A,t,n,s,o,i,g,E,C,d,B,Q,c){super(A,i,g,E,C,d,s-t/2,o-t/2),this.sampleName=A,this.sampleStartIndex=t,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=Q,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=B,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=c}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let t=A.currentIndex;return A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t)}else{this.isDataRaw||super.getRawData();let t=A.currentIndex;return A.slice(t+this.sampleStartIndex,t+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,t=A.currentIndex,n=A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t);this.sampleData=new Float32Array(0);try{let s=zA.decode(n.buffer);this.sampleData=s.data[0]}catch(s){v(`Error decoding sample ${this.sampleName}: ${s}`),this.sampleData=new Float32Array(this.sampleLoopEndIndex+1)}}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return v("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),t=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(t+this.sampleStartIndex,t+this.sampleEndIndex).buffer);for(let s=0;s<n.length;s++)A[s]=n[s]/32768;return this.sampleData=A,this.isSampleLoaded=!0,A}getUncompressedReadyData(){let A=this.sampleDataArray.slice(this.sampleStartIndex/2,this.sampleEndIndex/2);return this.sampleData=A,this.isSampleLoaded=!0,A}};function io(e,A,t=!0){let n=[],s=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let o=wr(s,e.chunkData,A,t);n.push(o),s++}return n.length>1&&n.pop(),n}function wr(e,A,t,n){let s=X(A,20),o=w(A,4)*2,i=w(A,4)*2,g=w(A,4),E=w(A,4),C=w(A,4),d=A[A.currentIndex++];d===255&&(d=60);let B=_n(A[A.currentIndex++]),Q=w(A,2),c=w(A,2);return new en(s,o,i,g,E,C,d,B,Q,c,t,e,n)}var tn=class extends G{constructor(A){super();let t=A.currentIndex;this.generatorType=A[t+1]<<8|A[t],this.generatorValue=se(A[t+2],A[t+3]),A.currentIndex+=4}};function nn(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new tn(e.chunkData));return A.length>1&&A.pop(),A}var sn=class extends ie{constructor(A){super(),this.instrumentName=X(A.chunkData,20).trim(),this.instrumentZoneIndex=w(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,t){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;n<this.instrumentZonesAmount+this.instrumentZoneIndex;n++)this.instrumentZones.push(t[n])}};function ao(e,A){let t=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let n=new sn(e);if(t.length>0){let s=n.instrumentZoneIndex-t[t.length-1].instrumentZoneIndex;t[t.length-1].getInstrumentZones(s,A)}t.push(n)}return t.length>1&&t.pop(),t}var on=class extends GA{constructor(A){super(),this.generatorZoneStartIndex=w(A,2),this.modulatorZoneStartIndex=w(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}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(n=>n.generatorType===r.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===r.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===r.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function go(e,A,t,n){let s=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new on(e.chunkData);if(s.length>0){let i=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(i,g),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(t),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var rn=class extends oe{constructor(A){super(),this.generatorZoneStartIndex=w(A,2),this.modulatorZoneStartIndex=w(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}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])}getInstrument(A){let t=this.generators.find(n=>n.generatorType===r.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===r.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===r.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function Io(e,A,t,n){let s=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new rn(e.chunkData);if(s.length>0){let i=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(i,g),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(t),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var an=class extends ae{constructor(A,t){super(t),this.presetName=X(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=w(A.chunkData,2),this.bank=w(A.chunkData,2),this.presetZoneStartIndex=w(A.chunkData,2),this.library=w(A.chunkData,4),this.genre=w(A.chunkData,4),this.morphology=w(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,t){this.presetZonesAmount=A;for(let n=this.presetZoneStartIndex;n<this.presetZonesAmount+this.presetZoneStartIndex;n++)this.presetZones.push(t[n])}};function Eo(e,A,t){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let s=new an(e,t);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var gn=class extends K{constructor(A){super({srcEnum:w(A,2),dest:w(A,2),amt:se(A[A.currentIndex++],A[A.currentIndex++]),secSrcEnum:w(A,2),transform:w(A,2)})}};function mt(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new gn(e.chunkData));return A}var pt=class extends ge{constructor(A,t=!0){super(),t&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new M(A),$A("%cParsing SoundFont...",a.info),this.dataArray||(O(),this.parsingError("No data provided!"));let n=_(this.dataArray,!1);this.verifyHeader(n,"riff");let s=X(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw O(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",i=_(this.dataArray);for(this.verifyHeader(i,"list"),X(i.chunkData,4);i.chunkData.length>i.chunkData.currentIndex;){let tA=_(i.chunkData),CA;switch(tA.header.toLowerCase()){case"ifil":case"iver":CA=`${w(tA.chunkData,2)}.${w(tA.chunkData,2)}`,this.soundFontInfo[tA.header]=CA;break;case"icmt":CA=X(tA.chunkData,tA.chunkData.length,void 0,!1),this.soundFontInfo[tA.header]=CA;break;case"dmod":let BA=mt(tA);BA.pop(),CA=`Modulators: ${BA.length}`;let lA=this.defaultModulators;this.defaultModulators=BA,this.defaultModulators.push(...lA.filter($=>!this.defaultModulators.find(uA=>K.isIdentical($,uA)))),this.soundFontInfo[tA.header]=tA.chunkData;break;default:CA=X(tA.chunkData,tA.chunkData.length),this.soundFontInfo[tA.header]=CA}m(`%c"${tA.header}": %c"${CA}"`,a.info,a.recognized)}let g=_(this.dataArray,!1);this.verifyHeader(g,"list"),this.verifyText(X(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",a.warn);let E=_(this.dataArray,!1);this.verifyHeader(E,"smpl");let C;if(o){m("%cSF2Pack detected, attempting to decode the smpl chunk...",a.info);try{C=zA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+g.size-12)).data[0]}catch(tA){throw O(),new Error(`SF2Pack Ogg Vorbis decode error: ${tA}`)}m(`%cDecoded the smpl chunk! Length: %c${C.length}`,a.info,a.value)}else C=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;m(`%cSkipping sample chunk, length: %c${g.size-12}`,a.info,a.value),this.dataArray.currentIndex+=g.size-12,m("%cLoading preset data chunk...",a.warn);let d=_(this.dataArray);this.verifyHeader(d,"list"),X(d.chunkData,4);let B=_(d.chunkData);this.verifyHeader(B,"phdr");let Q=_(d.chunkData);this.verifyHeader(Q,"pbag");let c=_(d.chunkData);this.verifyHeader(c,"pmod");let p=_(d.chunkData);this.verifyHeader(p,"pgen");let f=_(d.chunkData);this.verifyHeader(f,"inst");let y=_(d.chunkData);this.verifyHeader(y,"ibag");let F=_(d.chunkData);this.verifyHeader(F,"imod");let L=_(d.chunkData);this.verifyHeader(L,"igen");let T=_(d.chunkData);this.verifyHeader(T,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...io(T,C,!o));let J=nn(L),b=mt(F),I=go(y,J,b,this.samples);this.instruments=ao(f,I);let j=nn(p),P=mt(c),iA=Io(Q,j,P,this.instruments);this.presets.push(...Eo(B,iA,this.defaultModulators)),this.presets.sort((tA,CA)=>tA.program-CA.program+(tA.bank-CA.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets,
|
|
19
|
-
%c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,a.info,a.recognized,a.info,a.recognized,a.info,a.recognized,a.info,a.recognized,a.info),O(),o&&delete this.dataArray}verifyHeader(A,t){A.header.toLowerCase()!==t.toLowerCase()&&(O(),this.parsingError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(O(),this.parsingError(`Invalid FourCC: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"\``))}destroySoundfont(){super.destroySoundfont(),delete this.dataArray}};function Ye(e){let A=e.slice(8,12),t=new M(A);return X(t,4,void 0,!1).toLowerCase()==="dls "?new ee(e):new pt(e,!1)}var yt=class{constructor(A,t){this.ready=t,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(t=>{t.soundfont.setSampleIDOffset(A),A+=t.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let t=this.soundfontList.length-1;t>=0;t--){let n=this.soundfontList[t],s=new Set;for(let o of n.soundfont.presets){let i=`${o.bank+n.bankOffset}-${o.program}`;s.has(i)||(s.add(i),A[i]=o.presetName)}}this.presetList=[];for(let[t,n]of Object.entries(A)){let s=t.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}}handleMessage(A,t){switch(A){case fe.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case fe.reloadSoundFont:this.reloadManager(t);break;case fe.deleteSoundFont:this.deleteSoundFont(t);break;case fe.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let t=Ye(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:t}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){v("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(n=>n.id===A);if(t===-1){v(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[t].soundfont.presets,delete this.soundfontList[t].soundfont.instruments,delete this.soundfontList[t].soundfont.samples,this.soundfontList.splice(t,1),this.generatePresetList()}addNewSoundFont(A,t,n){if(this.soundfontList.find(s=>s.id===t)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:t,soundfont:Ye(A),bankOffset:n}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((t,n)=>A.indexOf(t.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,t){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let n of this.soundfontList){let s=n.soundfont.getPresetNoFallback(A-n.bankOffset,t);if(s!==void 0)return s}if(A!==128){for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.program===t);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}else{for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.bank===128);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}}destroyManager(){this.soundfontList.forEach(A=>{A.soundfont.destroySoundfont()}),delete this.soundfontList}};var ke={linear:0,nearestNeighbor:1,fourthOrder:2},De=class{static getSampleLinear(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let i=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=i;let E=~~s,C=E+1;for(;C>=n.loopEnd;)C-=i;let d=s-E,B=o[C],Q=o[E];t[g]=Q+(B-Q)*d,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let i=0;i<t.length;i++){let g=~~s,E=g+1;if(E>=n.end){A.finished=!0;return}let C=s-g,d=o[E],B=o[g];t[i]=B+(d-B)*C,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}static getSampleNearest(A,t){let n=A.sample,s=n.cursor,o=n.loopEnd-n.loopStart,i=n.sampleData;if(A.sample.isLooping)for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=o;let E=~~s+1;for(;E>=n.loopEnd;)E-=o;t[g]=i[E],s+=n.playbackStep*A.currentTuningCalculated}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let g=0;g<t.length;g++){let E=~~s+1;if(E>=n.end){A.finished=!0;return}t[g]=i[E],s+=n.playbackStep*A.currentTuningCalculated}}n.cursor=s}static getSampleCubic(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let i=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=i;let E=~~s,C=E+1,d=C+1,B=d+1,Q=s-E;C>=n.loopEnd&&(C-=i),d>=n.loopEnd&&(d-=i),B>=n.loopEnd&&(B-=i);let c=o[E],p=o[C],f=o[d],y=o[B],F=.5*(f-c),L=c-2.5*p+2*f-.5*y,T=.5*(y-c)+1.5*(p-f);t[g]=((T*Q+L)*Q+F)*Q+p,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let i=0;i<t.length;i++){let g=~~s,E=g+1,C=E+1,d=C+1,B=s-g;if(E>=n.end||C>=n.end||d>=n.end){A.finished=!0;return}let Q=o[g],c=o[E],p=o[C],f=o[d],y=.5*(p-Q),F=Q-2.5*c+2*p-.5*f,L=.5*(f-Q)+1.5*(c-p);t[i]=((L*B+F)*B+y)*B+c,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}};var we=class e{static cachedCoefficients=[];a0=0;a1=0;a2=0;a3=0;a4=0;x1=0;x2=0;y1=0;y2=0;reasonanceCb=0;cutoffCents=13501;static apply(A,t,n,s){if(s&&n>13499&&A.filter.reasonanceCb===0)return;let o=A.filter;(o.cutoffCents!==n||o.reasonanceCb!==A.modulatedGenerators[r.initialFilterQ])&&(o.cutoffCents=n,o.reasonanceCb=A.modulatedGenerators[r.initialFilterQ],e.calculateCoefficients(o));for(let i=0;i<t.length;i++){let g=t[i],E=o.a0*g+o.a1*o.x1+o.a2*o.x2-o.a3*o.y1-o.a4*o.y2;o.x2=o.x1,o.x1=g,o.y2=o.y1,o.y1=E,t[i]=E}}static calculateCoefficients(A){let t=~~A.cutoffCents,n=A.reasonanceCb;if(e.cachedCoefficients?.[n]?.[t]===void 0){let o=Te(t);o=Math.min(o,.45*sampleRate);let i=n/10,g=KA(-1*(i-3.01)),E=1/Math.sqrt(KA(-i)),C=2*Math.PI*o/sampleRate,d=Math.cos(C),B=Math.sin(C)/(2*g),Q=(1-d)*E,c=Q/2,p=c,f=1+B,y=-2*d,F=1-B,L={};L.a0=c/f,L.a1=Q/f,L.a2=p/f,L.a3=y/f,L.a4=F/f,e.cachedCoefficients[n]===void 0&&(e.cachedCoefficients[n]=[]),e.cachedCoefficients[n][t]=L}let s=e.cachedCoefficients[n][t];A.a0=s.a0,A.a1=s.a1,A.a2=s.a2,A.a3=s.a3,A.a4=s.a4}};var mA=16384,te=new Float32Array(mA+1),he=new Float32Array(mA+1);te[0]=0;te[te.length-1]=1;he[0]=0;he[he.length-1]=1;for(let e=1;e<mA-1;e++){let A=-.4166666666666667*Math.log(e/(te.length-1))/Math.LN10;he[e]=1-A,te[te.length-1-e]=A}function Be(e,A,t,n){switch(e&&(t=1-t),A){case dA.linear:return n?t*2-1:t;case dA.switch:return t=t>.5?1:0,n?t*2-1:t;case dA.concave:return n?(t=t*2-1,t<0?-te[~~(t*-mA)]:te[~~(t*mA)]):te[~~(t*mA)];case dA.convex:return n?(t=t*2-1,t<0?-he[~~(t*-mA)]:he[~~(t*mA)]):he[~~(t*mA)]}}var In=1,En=new Float32Array(1e3);for(let e=0;e<En.length;e++)En[e]=Be(0,dA.convex,e/1e3,0);var OA=class e{attackDuration=0;decayDuration=0;holdDuration=0;releaseDuration=0;sustainLevel=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;releaseStartLevel=0;currentValue=0;static startRelease(A){e.recalculate(A)}static recalculate(A){let t=A.modulationEnvelope;A.isInRelease&&(t.releaseStartLevel=e.getValue(A,A.releaseStartTime,!0)),t.sustainLevel=1-A.modulatedGenerators[r.sustainModEnv]/1e3,t.attackDuration=ZA(A.modulatedGenerators[r.attackModEnv]);let n=(60-A.midiNote)*A.modulatedGenerators[r.keyNumToModEnvDecay],s=ZA(A.modulatedGenerators[r.decayModEnv]+n);t.decayDuration=s*(1-t.sustainLevel);let o=(60-A.midiNote)*A.modulatedGenerators[r.keyNumToModEnvHold];t.holdDuration=ZA(o+A.modulatedGenerators[r.holdModEnv]);let i=ZA(A.modulatedGenerators[r.releaseModEnv]);t.releaseDuration=i*t.releaseStartLevel,t.delayEnd=A.startTime+ZA(A.modulatedGenerators[r.delayModEnv]),t.attackEnd=t.delayEnd+t.attackDuration,t.holdEnd=t.attackEnd+t.holdDuration,t.decayEnd=t.holdEnd+t.decayDuration}static getValue(A,t,n=!1){let s=A.modulationEnvelope;return A.isInRelease&&!n?s.releaseStartLevel===0?0:Math.max(0,(1-(t-A.releaseStartTime)/s.releaseDuration)*s.releaseStartLevel):(t<s.delayEnd?s.currentValue=0:t<s.attackEnd?s.currentValue=En[~~((1-(s.attackEnd-t)/s.attackDuration)*1e3)]:t<s.holdEnd?s.currentValue=In:t<s.decayEnd?s.currentValue=(1-(s.decayEnd-t)/s.decayDuration)*(s.sustainLevel-In)+In:s.currentValue=s.sustainLevel,s.currentValue)}};var St=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,t,n,s,o,i,g,E){this.sampleData=A,this.playbackStep=t,this.cursor=n,this.rootKey=s,this.loopStart=o,this.loopEnd=i,this.end=g,this.loopingMode=E,this.isLooping=this.loopingMode===1||this.loopingMode===3}},Je=class e{sample;filter=new we;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new OA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=0;realKey;portamentoFromKey=-1;portamentoDuration=0;overridePan=0;constructor(A,t,n,s,o,i,g,E,C,d){this.sample=t,this.generators=C,this.modulatedGenerators=new Int16Array(C),this.modulators=d,this.velocity=s,this.midiNote=n,this.channelNumber=o,this.startTime=i,this.targetKey=g,this.realKey=E,this.volumeEnvelope=new PA(A,C[r.sustainVolEnv])}static copy(A,t){let n=A.sample,s=new St(n.sampleData,n.playbackStep,n.cursor,n.rootKey,n.loopStart,n.loopEnd,n.end,n.loopingMode);return new e(A.volumeEnvelope.sampleRate,s,A.midiNote,A.velocity,A.channelNumber,t,A.targetKey,A.realKey,A.generators,A.modulators.map(o=>K.copy(o)))}release(A=ho){this.releaseStartTime=currentTime,this.releaseStartTime-this.startTime<A&&(this.releaseStartTime=this.startTime+A)}};function Co(e,A,t,n,s,o=!1){let i,g=this.workletProcessorChannels[e],E=g.cachedVoices[A]?.[t],C=this.keyModifierManager.hasOverridePatch(e,A);if(E!==void 0&&!C)return E.map(Q=>Je.copy(Q,n));let d=!0,B=g.preset;if(C){d=!1;let Q=this.keyModifierManager.getPatch(e,A);B=this.soundfontManager.getPreset(Q.bank,Q.program)}return i=B.getSamplesAndGenerators(A,t).reduce((Q,c)=>{if(c.sample.sampleData===void 0)return v(`Discarding invalid sample: ${c.sample.sampleName}`),Q;let p=new Int16Array(60);for(let b=0;b<60;b++)p[b]=Kn(b,c.presetGenerators,c.instrumentGenerators);p[r.initialAttenuation]=Math.floor(p[r.initialAttenuation]*.4);let f=c.sample.samplePitch;p[r.overridingRootKey]>-1&&(f=p[r.overridingRootKey]);let y=A;p[r.keyNum]>-1&&(y=p[r.keyNum]);let F=c.sample.sampleLoopStartIndex,L=c.sample.sampleLoopEndIndex,T=p[r.sampleModes],J=new St(c.sample.getAudioData(),c.sample.sampleRate/sampleRate*Math.pow(2,c.sample.samplePitchCorrection/1200),0,f,F,L,Math.floor(c.sample.sampleData.length)-1,T);return p[r.velocity]>-1&&(t=p[r.velocity]),o&&qn([{Sample:c.sample.sampleName,Generators:p,Modulators:c.modulators.map(b=>b.debugString()),Velocity:t,TargetKey:y,MidiNote:A,WorkletSample:J}]),Q.push(new Je(sampleRate,J,A,t,e,n,y,s,p,c.modulators.map(b=>K.copy(b)))),Q},[]),d&&(g.cachedVoices[A][t]=i.map(Q=>Je.copy(Q,n))),i}var co=.1,Fr=4600,Rr=2e3,Bo=Math.PI/2,Dt=-500,lo=500,Cn=lo-Dt,Qo=new Float32Array(Cn+1),uo=new Float32Array(Cn+1);for(let e=Dt;e<=lo;e++){let A=(e-Dt)/Cn,t=e-Dt;Qo[t]=Math.cos(Bo*A),uo[t]=Math.sin(Bo*A)}function fo(e,A,t,n,s,o,i,g){if(isNaN(A[0]))return;let E;if(e.overridePan)E=e.overridePan;else{let c=Math.max(-500,Math.min(500,e.modulatedGenerators[r.pan]));e.currentPan+=(c-e.currentPan)*this.synth.panSmoothingFactor,E=e.currentPan}let C=this.synth.currentGain,d=~~(E+500),B=Qo[d]*C*this.synth.panLeft,Q=uo[d]*C*this.synth.panRight;if(!this.synth.oneOutputMode){let c=this.synth.reverbGain*e.modulatedGenerators[r.reverbEffectsSend]/Fr*C,p=this.synth.chorusGain*e.modulatedGenerators[r.chorusEffectsSend]/Rr;if(c>0){for(let f=0;f<A.length;f++)s[f]+=c*A[f];o.set(s)}if(p>0){let f=B*p,y=Q*p;for(let F=0;F<A.length;F++)i[F]+=f*A[F],g[F]+=y*A[F]}}if(B>0)for(let c=0;c<A.length;c++)t[c]+=B*A[c];if(Q>0)for(let c=0;c<A.length;c++)n[c]+=Q*A[c]}function mo(e=!1){m("%cStop all received!",a.info);for(let A=0;A<this.workletProcessorChannels.length;A++)this.workletProcessorChannels[A].stopAllNotes(e);this.callEvent("stopall",void 0)}function po(e,A){this.soundfontBankOffset=A,this.reloadSoundFont(e,!0),this.overrideSoundfont.samples.forEach(t=>t.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function yo(e,A=!1){this.clearSoundFont(!1,A);try{A?(this.overrideSoundfont=Ye(e),this.overrideSoundfont.setSampleIDOffset(this.soundfontManager.totalSoundfontOffset)):this.soundfontManager.reloadManager(e)}catch(t){this.post({messageType:RA.soundfontError,messageData:t});return}this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels.forEach(t=>t.programChange(t.preset.program)),this.post({messageType:RA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",a.recognized)}function So(e=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let t=0;t<this.workletProcessorChannels.length;t++){let n=this.workletProcessorChannels[t];n.cachedVoices=[];for(let s=0;s<128;s++)n.cachedVoices.push([]);(!A||A&&n.presetUsesOverride)&&(n.lockPreset=!1),n.programChange(n.preset.program)}e&&this.sendPresetList()}function Do(){let e=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,n=e.find(s=>s.bank===t&&s.program===A.program);n!==void 0?n.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.callEvent("presetlistchange",e)}function ko(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(t,A);if(n)return n}return this.soundfontManager.getPreset(e,A)}function wo(e,A=!1){this.transposition=0;for(let t=0;t<this.workletProcessorChannels.length;t++)this.workletProcessorChannels[t].transposeChannel(e,A);this.transposition=e}function Fo(e){e=Math.round(e);for(let A=0;A<this.workletProcessorChannels.length;A++)this.workletProcessorChannels[A].customControllers[rA.masterTuning]=e}var qe=class e{program;bank;patchName;lockPreset;midiControllers;lockedControllers;customControllers;lockVibrato;channelVibrato;channelTransposeKeyShift;channelOctaveTuning;keyCentTuning;isMuted;velocityOverride;drumChannel;static getChannelSnapshot(A,t){let n=A.workletProcessorChannels[t],s=new e;return s.program=n.preset.program,s.bank=n.getBankSelect(),s.lockPreset=n.lockPreset,s.patchName=n.preset.presetName,s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.channelVibrato=n.channelVibrato,s.lockVibrato=n.lockGSNRPNParams,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.keyCentTuning=n.keyCentTuning,s.isMuted=n.isMuted,s.velocityOverride=n.velocityOverride,s.drumChannel=n.drumChannel,s}static applyChannelSnapshot(A,t,n){let s=A.workletProcessorChannels[t];s.muteChannel(n.isMuted),s.setDrums(n.drumChannel),s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.channelVibrato=n.channelVibrato,s.lockGSNRPNParams=n.lockVibrato,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.velocityOverride=n.velocityOverride,s.lockPreset=!1,s.setBankSelect(n.bank),s.programChange(n.program),s.lockPreset=n.lockPreset}};var Fe=class e{channelSnapshots;keyMappings;mainVolume;pan;interpolation;system;transposition;effectsConfig;static createSynthesizerSnapshot(A){let t=new e;return t.channelSnapshots=A.workletProcessorChannels.map((n,s)=>qe.getChannelSnapshot(A,s)),t.keyMappings=A.keyModifierManager.getMappings(),t.mainVolume=A.midiVolume,t.pan=A.pan,t.system=A.system,t.interpolation=A.interpolationType,t.transposition=A.transposition,t.effectsConfig={},t}static applySnapshot(A,t){for(A.system=t.system,A.setMasterGain(t.mainVolume),A.setMasterPan(t.pan),A.transposeAllChannels(t.transposition),A.interpolationType=t.interpolation,A.keyModifierManager.setMappings(t.keyMappings);A.workletProcessorChannels.length<t.channelSnapshots.length;)A.createWorkletChannel();t.channelSnapshots.forEach((n,s)=>{qe.applyChannelSnapshot(A,s,n)}),m("%cFinished restoring controllers!",a.info)}};function Ro(){this.post({messageType:RA.synthesizerSnapshot,messageData:Fe.createSynthesizerSnapshot(this)})}function Go(e){Fe.applySnapshot(this,e),m("%cFinished applying snapshot!",a.info)}function kt(e,A,t){if(t<e)return 0;let n=(t-e)/(1/A)+.25;return Math.abs(n-~~(n+.5))*4-1}function Mo(e,A,t,n,s,o,i){if(e.isInRelease||currentTime>=e.releaseStartTime&&(e.isInRelease=!0,PA.startRelease(e),OA.startRelease(e),e.sample.loopingMode===3&&(e.sample.isLooping=!1)),e.modulatedGenerators[r.initialAttenuation]>2500)return e.isInRelease&&(e.finished=!0),e.finished;let g=e.targetKey,E=e.modulatedGenerators[r.fineTune]+this.customControllers[rA.channelTuning]+this.customControllers[rA.channelTransposeFine]+this.customControllers[rA.masterTuning]+this.channelOctaveTuning[e.midiNote%12]+this.keyCentTuning[e.midiNote],C=e.modulatedGenerators[r.coarseTune]+this.customControllers[rA.channelTuningSemitones],d=this.synth.tunings[this.preset.program]?.[e.realKey];if(d?.midiNote>=0&&(g=d.midiNote,E+=d.centTuning),e.portamentoFromKey>-1){let j=Math.min((currentTime-e.startTime)/e.portamentoDuration,1),P=g-e.portamentoFromKey;C-=P*(1-j)}E+=(g-e.sample.rootKey)*e.modulatedGenerators[r.scaleTuning];let B=e.modulatedGenerators[r.vibLfoToPitch];if(B!==0){let j=e.startTime+ZA(e.modulatedGenerators[r.delayVibLFO]),P=Te(e.modulatedGenerators[r.freqVibLFO]),iA=kt(j,P,currentTime);E+=iA*(B*this.customControllers[rA.modulationMultiplier])}let Q=e.modulatedGenerators[r.initialFilterFc],c=Q,p=e.modulatedGenerators[r.modLfoToPitch],f=e.modulatedGenerators[r.modLfoToVolume],y=e.modulatedGenerators[r.modLfoToFilterFc],F=0;if(p+y+f!==0){let j=e.startTime+ZA(e.modulatedGenerators[r.delayModLFO]),P=Te(e.modulatedGenerators[r.freqModLFO]),iA=kt(j,P,currentTime);E+=iA*(p*this.customControllers[rA.modulationMultiplier]),F=-iA*f,c+=iA*y}if(this.channelVibrato.depth>0){let j=kt(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,currentTime);j&&(E+=j*this.channelVibrato.depth)}let L=e.modulatedGenerators[r.modEnvToPitch],T=e.modulatedGenerators[r.modEnvToFilterFc],J=OA.getValue(e,currentTime);c+=J*T,E+=J*L;let b=~~(E+C*100);b!==e.currentTuningCents&&(e.currentTuningCents=b,e.currentTuningCalculated=Math.pow(2,b/1200));let I=new Float32Array(A.length);switch(this.synth.interpolationType){case ke.fourthOrder:De.getSampleCubic(e,I);break;case ke.linear:default:De.getSampleLinear(e,I);break;case ke.nearestNeighbor:De.getSampleNearest(e,I);break}return we.apply(e,I,c,Q>13499),PA.apply(e,I,F,this.synth.volumeEnvelopeSmoothingFactor),this.panVoice(e,I,A,t,n,s,o,i),e.finished}function xo(e){this.voices.forEach(A=>{A.realKey===e&&(A.modulatedGenerators[r.releaseVolEnv]=-12e3,A.release())})}function No(e,A=!0){e=Math.round(e),this.customControllers[rA.channelTuning]=e,A&&m(`%cChannel ${this.channelNumber} fine tuning. Cents: %c${e}`,a.info,a.value)}function bo(e){e=Math.round(e),m(`%cChannel ${this.channelNumber} modulation depth. Cents: %c${e}`,a.info,a.value),this.customControllers[rA.modulationMultiplier]=e/50}function Lo(e){switch(this.dataEntryState){default:break;case FA.RPCoarse:case FA.RPFine:switch(this.RPValue){default:break;case 0:if(e===0)break;this.midiControllers[cA+q.pitchWheelRange]|=e;let A=(this.midiControllers[cA+q.pitchWheelRange]>>7)+e/127;m(`%cChannel ${this.channelNumber} bend range. Semitones: %c${A}`,a.info,a.value);break;case 1:let n=this.customControllers[rA.channelTuning]<<7|e;this.setTuning(n*.01220703125);break;case 5:let o=this.customControllers[rA.modulationMultiplier]*50+e/128*100;this.setModulationDepth(o);break;case 16383:this.resetParameters();break}}}function Uo(e){e=Math.round(e),this.customControllers[rA.channelTuningSemitones]=e,m(`%cChannel ${this.channelNumber} coarse tuning. Semitones: %c${e}`,a.info,a.value)}var Gr=1e3/200;function To(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=e[A.sourceIndex];else{let C=A.sourceIndex+cA;switch(A.sourceIndex){case q.noController:n=16383;break;case q.noteOnKeyNum:n=t.midiNote<<7;break;case q.noteOnVelocity:n=t.velocity<<7;break;case q.polyPressure:n=t.pressure<<7;break;default:n=e[C];break}}let s=ce[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let C=A.secSrcIndex+cA;switch(A.secSrcIndex){case q.noController:o=16383;break;case q.noteOnKeyNum:o=t.midiNote<<7;break;case q.noteOnVelocity:o=t.velocity<<7;break;case q.polyPressure:o=t.pressure<<7;break;default:o=e[C]}}let i=ce[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=A.transformAmount;A.isEffectModulator&&g<=1e3&&(g*=Gr,g=Math.min(g,1e3));let E=s*i*g;return A.transformType===2&&(E=Math.abs(E)),A.currentValue=E,E}function WA(e,A,t=-1,n=0){let s=e.modulators,o=e.generators,i=e.modulatedGenerators;if(t===-1){i.set(o),s.forEach(C=>{let d=Y[C.modulatorDestination],B=i[C.modulatorDestination]+To(A,C,e);i[C.modulatorDestination]=Math.max(d.min,Math.min(B,d.max))}),PA.recalculate(e),OA.recalculate(e);return}let g=new Set([r.initialAttenuation,r.delayVolEnv,r.attackVolEnv,r.holdVolEnv,r.decayVolEnv,r.sustainVolEnv,r.releaseVolEnv,r.keyNumToVolEnvHold,r.keyNumToVolEnvDecay]),E=new Set;s.forEach(C=>{if(C.sourceUsesCC===t&&C.sourceIndex===n||C.secSrcUsesCC===t&&C.secSrcIndex===n){let d=C.modulatorDestination;E.has(d)||(i[d]=o[d],To(A,C,e),s.forEach(B=>{if(B.modulatorDestination===d){let Q=Y[C.modulatorDestination],c=i[C.modulatorDestination]+B.currentValue;i[C.modulatorDestination]=Math.max(Q.min,Math.min(c,Q.max))}}),E.add(d))}}),[...E].some(C=>g.has(C))&&PA.recalculate(e),OA.recalculate(e)}var ce=[];for(let e=0;e<4;e++){ce[e]=[[new Float32Array(mA),new Float32Array(mA)],[new Float32Array(mA),new Float32Array(mA)]];for(let A=0;A<mA;A++)ce[e][0][0][A]=Be(0,e,A/mA,0),ce[e][1][0][A]=Be(0,e,A/mA,1),ce[e][0][1][A]=Be(1,e,A/mA,0),ce[e][1][1][A]=Be(1,e,A/mA,1)}function vo(e,A,t=!1){if(e>127){if(!t)return;switch(e){default:return;case Vt.velocityOverride:this.velocityOverride=A}}if(e>=D.lsbForControl1ModulationWheel&&e<=D.lsbForControl13EffectControl2&&e!==D.lsbForControl6DataEntry){let n=e-32;if(this.lockedControllers[n])return;this.midiControllers[n]=this.midiControllers[n]&16256|A&127,this.voices.forEach(s=>WA(s,this.midiControllers,1,n))}switch(e){case D.allNotesOff:this.stopAllNotes();break;case D.allSoundOff:this.stopAllNotes(!0);break;case D.bankSelect:let n=A;if(!t){switch(this.synth.system){case"gm":m(`%cIgnoring the Bank Select (${A}), as the synth is in GM mode.`,a.info);return;case"xg":n===120||n===126||n===127?this.setDrums(!0):this.channelNumber%16!==xA&&this.setDrums(!1);break;case"gm2":n===120&&this.setDrums(!0)}this.drumChannel&&(n=128),n===128&&!this.drumChannel&&(n=this.getBankSelect())}this.setBankSelect(n);break;case D.lsbForControl0BankSelect:this.synth.system==="xg"?this.drumChannel||A!==127&&this.setBankSelect(A):this.synth.system==="gm2"&&this.setBankSelect(A);break;case D.RPNLsb:this.RPValue=this.RPValue<<7|A,this.dataEntryState=FA.RPFine;break;case D.RPNMsb:this.RPValue=A,this.dataEntryState=FA.RPCoarse;break;case D.NRPNMsb:this.NRPCoarse=A,this.dataEntryState=FA.NRPCoarse;break;case D.NRPNLsb:this.NRPFine=A,this.dataEntryState=FA.NRPFine;break;case D.dataEntryMsb:this.dataEntryCoarse(A);break;case D.lsbForControl6DataEntry:this.dataEntryFine(A);break;case D.resetAllControllers:this.resetControllers();break;case D.sustainPedal:A>=64?this.holdPedal=!0:(this.holdPedal=!1,this.sustainedVoices.forEach(s=>{s.release()}),this.sustainedVoices=[]);break;default:if(this.lockedControllers[e])return;this.midiControllers[e]=A<<7,this.voices.forEach(s=>WA(s,this.midiControllers,1,e));break}this.synth.callEvent("controllerchange",{channel:this.channelNumber,controllerNumber:e,controllerValue:A})}function Ho(e=!1){e?(this.voices.length=0,this.sustainedVoices.length=0,this.synth.sendChannelProperties()):(this.voices.forEach(A=>{A.isInRelease||A.release()}),this.sustainedVoices.forEach(A=>{A.release()}))}function Yo(e){e&&this.stopAllNotes(!0),this.isMuted=e,this.synth.sendChannelProperties(),this.synth.callEvent("mutechannel",{channel:this.channelNumber,isMuted:e})}function Jo(e,A=!1){this.drumChannel||(e+=this.synth.transposition);let t=Math.trunc(e),n=this.channelTransposeKeyShift+this.customControllers[rA.channelTransposeFine]/100;this.drumChannel&&!A||e===n||(t!==this.channelTransposeKeyShift&&this.stopAllNotes(!1),this.channelTransposeKeyShift=t,this.customControllers[rA.channelTransposeFine]=(e-t)*100)}function qo(e){let A=()=>{this.channelVibrato.delay===0&&this.channelVibrato.rate===0&&this.channelVibrato.depth===0&&(this.channelVibrato.depth=50,this.channelVibrato.rate=8,this.channelVibrato.delay=.6)};switch(this.dataEntryState){default:case FA.Idle:break;case FA.NRPFine:if(this.synth.system!=="gs"||this.lockGSNRPNParams)return;switch(this.NRPCoarse){default:if(e===64)return;v(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${this.NRPCoarse.toString(16).toUpperCase()} 0x${this.NRPFine.toString(16).toUpperCase()})%c data value: %c${e}`,a.warn,a.recognized,a.warn,a.unrecognized,a.warn,a.value);break;case 1:switch(this.NRPFine){default:if(e===64)return;v(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${this.NRPCoarse.toString(16)} 0x${this.NRPFine.toString(16)})%c data value: %c${e}`,a.warn,a.recognized,a.warn,a.unrecognized,a.warn,a.value);break;case 8:if(e===64)return;A(),this.channelVibrato.rate=e/64*8,m(`%cVibrato rate for %c${this.channelNumber}%c is now set to %c${e} = ${this.channelVibrato.rate}%cHz.`,a.info,a.recognized,a.info,a.value,a.info);break;case 9:if(e===64)return;A(),this.channelVibrato.depth=e/2,m(`%cVibrato depth for %c${this.channelNumber}%c is now set to %c${e} = ${this.channelVibrato.depth}%c cents range of detune.`,a.info,a.recognized,a.info,a.value,a.info);break;case 10:if(e===64)return;A(),this.channelVibrato.delay=e/64/3,m(`%cVibrato delay for %c${this.channelNumber}%c is now set to %c${e} = ${this.channelVibrato.delay}%c seconds.`,a.info,a.recognized,a.info,a.value,a.info);break;case 32:let n=e;this.controllerChange(D.brightness,e),m(`%cFilter cutoff for %c${this.channelNumber}%c is now set to %c${n}`,a.info,a.recognized,a.info,a.value)}break;case 29:let t=e;this.controllerChange(D.reverbDepth,t),m(`%cGS Drum reverb for %c${this.channelNumber}%c: %c${t}`,a.info,a.recognized,a.info,a.value);break}break;case FA.RPCoarse:case FA.RPFine:switch(this.RPValue){default:v(`%cUnrecognized RPN for %c${this.channelNumber}%c: %c(0x${this.RPValue.toString(16)})%c data value: %c${e}`,a.warn,a.recognized,a.warn,a.unrecognized,a.warn,a.value);break;case 0:this.midiControllers[cA+q.pitchWheelRange]=e<<7,m(`%cChannel ${this.channelNumber} bend range. Semitones: %c${e}`,a.info,a.value);break;case 2:this.setTuningSemitones(e-64);break;case 1:this.setTuning(e-64,!1);break;case 5:this.setModulationDepth(e*100);break;case 16383:this.resetParameters();break}}}var Ke={0:0,1:.006,2:.023,4:.05,8:.11,16:.25,32:.5,64:2.06,80:4.2,96:8.4,112:19.5,116:26.7,120:40,124:80,127:480};function Mr(e){if(Ke[e]!==void 0)return Ke[e];let A=null,t=null;for(let n of Object.keys(Ke))n=parseInt(n),n<e&&(A===null||n>A)&&(A=n),n>e&&(t===null||n<t)&&(t=n);if(A!==null&&t!==null){let n=Ke[A],s=Ke[t];return n+(e-A)*(s-n)/(t-A)}return 0}function Ko(e,A){return Mr(e)*(A/30)}var xr=-2320,Nr=-1130;function Po(e,A,t=!1,n=!0,s=currentTime){if(A<1){this.noteOff(e);return}if(A=Math.min(127,A),this.synth.highPerformanceMode&&this.totalVoicesAmount>200&&A<40||this.synth.highPerformanceMode&&A<10||this.isMuted)return;let o=e+this.channelTransposeKeyShift,i=o;if(o>127||o<0)return;let g=this.preset.program;this.synth.tunings[g]?.[o]?.midiNote>=0&&(i=this.synth.tunings[g]?.[o].midiNote),this.velocityOverride>0&&(A=this.velocityOverride);let E=this.synth.keyModifierManager.getVelocity(this.channelNumber,o);E>-1&&(A=E);let C=-1,d=0,B=this.midiControllers[D.portamentoTime]>>7,Q=this.midiControllers[D.portamentoControl]>>7;if(!this.drumChannel&&Q!==i&&this.midiControllers[D.portamentoOnOff]>=8192&&B>0){let y=Math.abs(i-Q);d=Ko(B,y),C=Q,this.controllerChange(D.portamentoControl,i)}let c=this.synth.getWorkletVoices(this.channelNumber,i,A,s,o,t),p=0;this.randomPan&&(p=Math.round(Math.random()*1e3-500));let f=this.voices;c.forEach(y=>{y.portamentoFromKey=C,y.portamentoDuration=d,y.overridePan=p;let F=y.generators[r.exclusiveClass];F!==0&&f.forEach(P=>{P.generators[r.exclusiveClass]===F&&(P.release(Oo),P.modulatedGenerators[r.releaseVolEnv]=xr,P.modulatedGenerators[r.releaseModEnv]=Nr,PA.recalculate(P),OA.recalculate(P))}),WA(y,this.midiControllers);let L=y.modulatedGenerators[r.startAddrsOffset]+y.modulatedGenerators[r.startAddrsCoarseOffset]*32768,T=y.modulatedGenerators[r.endAddrOffset]+y.modulatedGenerators[r.endAddrsCoarseOffset]*32768,J=y.modulatedGenerators[r.startloopAddrsOffset]+y.modulatedGenerators[r.startloopAddrsCoarseOffset]*32768,b=y.modulatedGenerators[r.endloopAddrsOffset]+y.modulatedGenerators[r.endloopAddrsCoarseOffset]*32768,I=y.sample,j=P=>Math.max(0,Math.min(I.sampleData.length-1,P));if(I.cursor=j(I.cursor+L),I.end=j(I.end+T),I.loopStart=j(I.loopStart+J),I.loopEnd=j(I.loopEnd+b),I.loopEnd<I.loopStart){let P=I.loopStart;I.loopStart=I.loopEnd,I.loopEnd=P}I.loopEnd-I.loopStart<1&&(I.loopingMode=0,I.isLooping=!1),y.volumeEnvelope.attenuation=y.volumeEnvelope.attenuationTargetGain,y.currentPan=Math.max(-500,Math.min(500,y.modulatedGenerators[r.pan]))}),this.synth.totalVoicesAmount+=c.length,this.synth.totalVoicesAmount>this.synth.voiceCap&&this.synth.voiceKilling(c.length),f.push(...c),n&&(this.synth.sendChannelProperties(),this.synth.callEvent("noteon",{midiNote:e,channel:this.channelNumber,velocity:A}))}function Vo(e){if(e>127||e<0){v("Received a noteOn for note",e,"Ignoring.");return}let A=e+this.channelTransposeKeyShift;if(this.synth.highPerformanceMode&&!this.drumChannel){this.killNote(A);return}this.voices.forEach(n=>{n.realKey!==A||n.isInRelease===!0||(this.holdPedal?this.sustainedVoices.push(n):n.release())}),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber})}function Zo(e,A){this.voices.forEach(t=>{t.midiNote===e&&(t.pressure=A,WA(t,this.midiControllers,0,q.polyPressure))}),this.synth.callEvent("polypressure",{channel:this.channelNumber,midiNote:e,pressure:A})}function Wo(e){this.midiControllers[cA+q.channelPressure]=e<<7,this.voices.forEach(A=>WA(A,this.midiControllers,0,q.channelPressure)),this.synth.callEvent("channelpressure",{channel:this.channelNumber,pressure:e})}function Xo(e,A){if(this.lockedControllers[cA+q.pitchWheel])return;let t=A|e<<7;this.synth.callEvent("pitchwheel",{channel:this.channelNumber,MSB:e,LSB:A}),this.midiControllers[cA+q.pitchWheel]=t,this.voices.forEach(n=>WA(n,this.midiControllers,0,q.pitchWheel)),this.synth.sendChannelProperties()}function _o(e){if(e.length!==12)throw new Error("Tuning is not the length of 12.");this.channelOctaveTuning=e}function zo(e,A=!1){if(this.lockPreset)return;let t=this.getBankSelect(),n,s;if(this.synth.overrideSoundfont){let o=t===128?128:t-this.synth.soundfontBankOffset,i=this.synth.overrideSoundfont.getPresetNoFallback(o,e);i?(n=t,s=i,this.presetUsesOverride=!0):(s=this.synth.soundfontManager.getPreset(t,e),n=s.bank,this.presetUsesOverride=!1)}else s=this.synth.soundfontManager.getPreset(t,e),n=s.bank,this.presetUsesOverride=!1;this.setPreset(s),this.synth.callEvent("programchange",{channel:this.channelNumber,program:s.program,bank:n,userCalled:A})}var IA=class{midiControllers=new Int16Array(tt);lockedControllers=Array(tt).fill(!1);customControllers=new Float32Array(Pt);channelTransposeKeyShift=0;channelOctaveTuning=new Int8Array(12);keyCentTuning=new Int16Array(128);holdPedal=!1;drumChannel=!1;velocityOverride=0;randomPan=!1;dataEntryState=FA.Idle;NRPCoarse=0;NRPFine=0;RPValue=0;bank=0;preset=void 0;lockPreset=!1;presetUsesOverride=!1;lockGSNRPNParams=!1;channelVibrato={delay:0,depth:0,rate:0};isMuted=!1;voices=[];sustainedVoices=[];cachedVoices=[];channelNumber;synth;constructor(A,t,n){this.synth=A,this.preset=t,this.channelNumber=n;for(let s=0;s<128;s++)this.cachedVoices.push([])}renderAudio(A,t,n,s,o,i){this.voices=this.voices.filter(g=>!this.renderVoice(g,A,t,n,s,o,i))}setBankSelect(A){this.lockPreset||(this.bank=A)}getBankSelect(){return this.drumChannel?128:this.bank}setPreset(A){if(!this.lockPreset){delete this.preset,this.preset=A,this.cachedVoices=[];for(let t=0;t<128;t++)this.cachedVoices.push([])}}setDrums(A){this.lockPreset||this.drumChannel!==A&&(A?(this.channelTransposeKeyShift=0,this.drumChannel=!0,this.setPreset(this.synth.getPreset(this.getBankSelect(),this.preset.program))):(this.drumChannel=!1,this.setPreset(this.synth.getPreset(this.getBankSelect(),this.preset.program))),this.presetUsesOverride=!1,this.synth.callEvent("drumchange",{channel:this.channelNumber,isDrumChannel:this.drumChannel}),this.synth.sendChannelProperties())}setVibrato(A,t,n){this.lockGSNRPNParams||(this.channelVibrato.rate=t,this.channelVibrato.delay=n,this.channelVibrato.depth=A)}disableAndLockGSNRPN(){this.lockGSNRPNParams=!0,this.channelVibrato.rate=0,this.channelVibrato.delay=0,this.channelVibrato.depth=0}};IA.prototype.renderVoice=Mo;IA.prototype.panVoice=fo;IA.prototype.killNote=xo;IA.prototype.stopAllNotes=Ho;IA.prototype.muteChannel=Yo;IA.prototype.noteOn=Po;IA.prototype.noteOff=Vo;IA.prototype.polyPressure=Zo;IA.prototype.channelPressure=Wo;IA.prototype.pitchWheel=Xo;IA.prototype.programChange=zo;IA.prototype.setTuning=No;IA.prototype.setTuningSemitones=Uo;IA.prototype.setOctaveTuning=_o;IA.prototype.setModulationDepth=bo;IA.prototype.transposeChannel=Jo;IA.prototype.controllerChange=vo;IA.prototype.resetControllers=ws;IA.prototype.resetParameters=Fs;IA.prototype.dataEntryFine=Lo;IA.prototype.dataEntryCoarse=qo;function jo(e=!1){let A=new IA(this,this.defaultPreset,this.workletProcessorChannels.length);this.workletProcessorChannels.push(A),A.resetControllers(),this.sendChannelProperties(),e&&this.callEvent("newchannel",void 0),A.channelNumber%16===xA&&this.workletProcessorChannels[this.workletProcessorChannels.length-1].setDrums(!0)}var ho=.03,Oo=.07,$t=1,EA=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.alive=!0,this.deviceID=LA,this.interpolationType=ke.fourthOrder,this.sequencer=new hA(this),this.transposition=0,this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=$t,this.midiVolume=1,this.reverbGain=1,this.chorusGain=1,this.voiceCap=On,this.pan=0,this.panLeft=.5,this.highPerformanceMode=!1,this.keyModifierManager=new At,this.overrideSoundfont=void 0,this.panRight=.5;try{this.soundfontManager=new yt(A.processorOptions.soundfont,this.postReady.bind(this))}catch(t){throw this.post({messageType:RA.soundfontError,messageData:t}),t}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let t=0;t<A.processorOptions.midiChannels;t++)this.createWorkletChannel(!1);this.workletProcessorChannels[xA].preset=this.drumPreset,this.workletProcessorChannels[xA].drumChannel=!0,this.volumeEnvelopeSmoothingFactor=us*(44100/sampleRate),this.panSmoothingFactor=co*(44100/sampleRate),this.system=st,this.totalVoicesAmount=0,this._snapshot=A.processorOptions?.startRenderingData?.snapshot,this.port.onmessage=t=>this.handleMessage(t.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",a.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.voiceCap=1/0,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),zA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",a.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:RA.ready,messageData:void 0})}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){if(!this.alive)return!1;this.sequencer.processTick();let n=0;return this.workletProcessorChannels.forEach((s,o)=>{if(s.voices.length<1||s.isMuted)return;let i,g,E,C,d,B,Q;if(this.oneOutputMode){let c=t[0];i=o%16*2,g=c[i],E=c[i+1]}else i=o%this._outputsAmount+2,g=t[i][0],E=t[i][1],C=t[0][0],d=t[0][1],B=t[1][0],Q=t[1][1];s.renderAudio(g,E,C,d,B,Q),n+=s.voices.length}),n!==this.totalVoicesAmount&&(this.totalVoicesAmount=n,this.sendChannelProperties()),!0}destroyWorkletProcessor(){this.alive=!1,this.workletProcessorChannels.forEach(A=>{delete A.midiControllers,delete A.voices,delete A.sustainedVoices,delete A.cachedVoices,delete A.lockedControllers,delete A.preset,delete A.customControllers}),delete this.workletProcessorChannels,delete this.sequencer.midiData,delete this.sequencer,this.soundfontManager.destroyManager(),delete this.soundfontManager}controllerChange(A,t,n,s=!1){this.workletProcessorChannels[A].controllerChange(t,n,s)}noteOn(A,t,n,s=!1,o=!0){this.workletProcessorChannels[A].noteOn(t,n,s,o)}noteOff(A,t){this.workletProcessorChannels[A].noteOff(t)}polyPressure(A,t,n){this.workletProcessorChannels[A].polyPressure(t,n)}channelPressure(A,t){this.workletProcessorChannels[A].channelPressure(t)}pitchWheel(A,t,n){this.workletProcessorChannels[A].pitchWheel(t,n)}programChange(A,t,n=!1){this.workletProcessorChannels[A].programChange(t,n)}};EA.prototype.voiceKilling=Bs;EA.prototype.getWorkletVoices=Co;EA.prototype.handleMessage=ds;EA.prototype.sendChannelProperties=ms;EA.prototype.callEvent=fs;EA.prototype.systemExclusive=ps;EA.prototype.stopAllChannels=mo;EA.prototype.createWorkletChannel=jo;EA.prototype.resetAllControllers=ks;EA.prototype.setMasterGain=Ss;EA.prototype.setMasterPan=Ds;EA.prototype.setMIDIVolume=ys;EA.prototype.transposeAllChannels=wo;EA.prototype.setMasterTuning=Fo;EA.prototype.getPreset=ko;EA.prototype.reloadSoundFont=yo;EA.prototype.clearSoundFont=So;EA.prototype.setEmbeddedSoundFont=po;EA.prototype.sendPresetList=Do;EA.prototype.sendSynthesizerSnapshot=Ro;EA.prototype.applySynthesizerSnapshot=Go;registerProcessor(Pn,EA);m("%cProcessor succesfully registered!",a.recognized);
|
|
19
|
+
%c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,a.info,a.recognized,a.info,a.recognized,a.info,a.recognized,a.info,a.recognized,a.info),O(),o&&delete this.dataArray}verifyHeader(A,t){A.header.toLowerCase()!==t.toLowerCase()&&(O(),this.parsingError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(O(),this.parsingError(`Invalid FourCC: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"\``))}destroySoundfont(){super.destroySoundfont(),delete this.dataArray}};function Ye(e){let A=e.slice(8,12),t=new M(A);return X(t,4,void 0,!1).toLowerCase()==="dls "?new ee(e):new pt(e,!1)}var yt=class{constructor(A,t){this.ready=t,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(t=>{t.soundfont.setSampleIDOffset(A),A+=t.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let t=this.soundfontList.length-1;t>=0;t--){let n=this.soundfontList[t],s=new Set;for(let o of n.soundfont.presets){let i=`${o.bank+n.bankOffset}-${o.program}`;s.has(i)||(s.add(i),A[i]=o.presetName)}}this.presetList=[];for(let[t,n]of Object.entries(A)){let s=t.split("-");this.presetList.push({presetName:n,program:parseInt(s[1]),bank:parseInt(s[0])})}}handleMessage(A,t){switch(A){case fe.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case fe.reloadSoundFont:this.reloadManager(t);break;case fe.deleteSoundFont:this.deleteSoundFont(t);break;case fe.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let t=Ye(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:t}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){v("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(n=>n.id===A);if(t===-1){v(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[t].soundfont.presets,delete this.soundfontList[t].soundfont.instruments,delete this.soundfontList[t].soundfont.samples,this.soundfontList.splice(t,1),this.generatePresetList()}addNewSoundFont(A,t,n){if(this.soundfontList.find(s=>s.id===t)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:t,soundfont:Ye(A),bankOffset:n}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((t,n)=>A.indexOf(t.id)-A.indexOf(n.id)),this.generatePresetList()}getPreset(A,t){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let n of this.soundfontList){let s=n.soundfont.getPresetNoFallback(A-n.bankOffset,t);if(s!==void 0)return s}if(A!==128){for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.program===t);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}else{for(let n of this.soundfontList){let s=n.soundfont.presets.find(o=>o.bank===128);if(s)return s}return this.soundfontList[0].soundfont.presets[0]}}destroyManager(){this.soundfontList.forEach(A=>{A.soundfont.destroySoundfont()}),delete this.soundfontList}};var ke={linear:0,nearestNeighbor:1,fourthOrder:2},De=class{static getSampleLinear(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let i=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=i;let E=~~s,C=E+1;for(;C>=n.loopEnd;)C-=i;let d=s-E,B=o[C],Q=o[E];t[g]=Q+(B-Q)*d,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let i=0;i<t.length;i++){let g=~~s,E=g+1;if(E>=n.end){A.finished=!0;return}let C=s-g,d=o[E],B=o[g];t[i]=B+(d-B)*C,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}static getSampleNearest(A,t){let n=A.sample,s=n.cursor,o=n.loopEnd-n.loopStart,i=n.sampleData;if(A.sample.isLooping)for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=o;let E=~~s+1;for(;E>=n.loopEnd;)E-=o;t[g]=i[E],s+=n.playbackStep*A.currentTuningCalculated}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let g=0;g<t.length;g++){let E=~~s+1;if(E>=n.end){A.finished=!0;return}t[g]=i[E],s+=n.playbackStep*A.currentTuningCalculated}}n.cursor=s}static getSampleCubic(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let i=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=i;let E=~~s,C=E+1,d=C+1,B=d+1,Q=s-E;C>=n.loopEnd&&(C-=i),d>=n.loopEnd&&(d-=i),B>=n.loopEnd&&(B-=i);let c=o[E],p=o[C],f=o[d],y=o[B],F=.5*(f-c),L=c-2.5*p+2*f-.5*y,T=.5*(y-c)+1.5*(p-f);t[g]=((T*Q+L)*Q+F)*Q+p,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let i=0;i<t.length;i++){let g=~~s,E=g+1,C=E+1,d=C+1,B=s-g;if(E>=n.end||C>=n.end||d>=n.end){A.finished=!0;return}let Q=o[g],c=o[E],p=o[C],f=o[d],y=.5*(p-Q),F=Q-2.5*c+2*p-.5*f,L=.5*(f-Q)+1.5*(c-p);t[i]=((L*B+F)*B+y)*B+c,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}};var we=class e{static cachedCoefficients=[];a0=0;a1=0;a2=0;a3=0;a4=0;x1=0;x2=0;y1=0;y2=0;reasonanceCb=0;cutoffCents=13501;static apply(A,t,n,s){if(s&&n>13499&&A.filter.reasonanceCb===0)return;let o=A.filter;(o.cutoffCents!==n||o.reasonanceCb!==A.modulatedGenerators[r.initialFilterQ])&&(o.cutoffCents=n,o.reasonanceCb=A.modulatedGenerators[r.initialFilterQ],e.calculateCoefficients(o));for(let i=0;i<t.length;i++){let g=t[i],E=o.a0*g+o.a1*o.x1+o.a2*o.x2-o.a3*o.y1-o.a4*o.y2;o.x2=o.x1,o.x1=g,o.y2=o.y1,o.y1=E,t[i]=E}}static calculateCoefficients(A){let t=~~A.cutoffCents,n=A.reasonanceCb;if(e.cachedCoefficients?.[n]?.[t]===void 0){let o=Te(t);o=Math.min(o,.45*sampleRate);let i=n/10,g=KA(-1*(i-3.01)),E=1/Math.sqrt(KA(-i)),C=2*Math.PI*o/sampleRate,d=Math.cos(C),B=Math.sin(C)/(2*g),Q=(1-d)*E,c=Q/2,p=c,f=1+B,y=-2*d,F=1-B,L={};L.a0=c/f,L.a1=Q/f,L.a2=p/f,L.a3=y/f,L.a4=F/f,e.cachedCoefficients[n]===void 0&&(e.cachedCoefficients[n]=[]),e.cachedCoefficients[n][t]=L}let s=e.cachedCoefficients[n][t];A.a0=s.a0,A.a1=s.a1,A.a2=s.a2,A.a3=s.a3,A.a4=s.a4}};var mA=16384,te=new Float32Array(mA+1),he=new Float32Array(mA+1);te[0]=0;te[te.length-1]=1;he[0]=0;he[he.length-1]=1;for(let e=1;e<mA-1;e++){let A=-.4166666666666667*Math.log(e/(te.length-1))/Math.LN10;he[e]=1-A,te[te.length-1-e]=A}function Be(e,A,t,n){switch(e&&(t=1-t),A){case dA.linear:return n?t*2-1:t;case dA.switch:return t=t>.5?1:0,n?t*2-1:t;case dA.concave:return n?(t=t*2-1,t<0?-te[~~(t*-mA)]:te[~~(t*mA)]):te[~~(t*mA)];case dA.convex:return n?(t=t*2-1,t<0?-he[~~(t*-mA)]:he[~~(t*mA)]):he[~~(t*mA)]}}var In=1,En=new Float32Array(1e3);for(let e=0;e<En.length;e++)En[e]=Be(0,dA.convex,e/1e3,0);var OA=class e{attackDuration=0;decayDuration=0;holdDuration=0;releaseDuration=0;sustainLevel=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;releaseStartLevel=0;currentValue=0;static startRelease(A){e.recalculate(A)}static recalculate(A){let t=A.modulationEnvelope;A.isInRelease&&(t.releaseStartLevel=e.getValue(A,A.releaseStartTime,!0)),t.sustainLevel=1-A.modulatedGenerators[r.sustainModEnv]/1e3,t.attackDuration=ZA(A.modulatedGenerators[r.attackModEnv]);let n=(60-A.midiNote)*A.modulatedGenerators[r.keyNumToModEnvDecay],s=ZA(A.modulatedGenerators[r.decayModEnv]+n);t.decayDuration=s*(1-t.sustainLevel);let o=(60-A.midiNote)*A.modulatedGenerators[r.keyNumToModEnvHold];t.holdDuration=ZA(o+A.modulatedGenerators[r.holdModEnv]);let i=ZA(A.modulatedGenerators[r.releaseModEnv]);t.releaseDuration=i*t.releaseStartLevel,t.delayEnd=A.startTime+ZA(A.modulatedGenerators[r.delayModEnv]),t.attackEnd=t.delayEnd+t.attackDuration,t.holdEnd=t.attackEnd+t.holdDuration,t.decayEnd=t.holdEnd+t.decayDuration}static getValue(A,t,n=!1){let s=A.modulationEnvelope;return A.isInRelease&&!n?s.releaseStartLevel===0?0:Math.max(0,(1-(t-A.releaseStartTime)/s.releaseDuration)*s.releaseStartLevel):(t<s.delayEnd?s.currentValue=0:t<s.attackEnd?s.currentValue=En[~~((1-(s.attackEnd-t)/s.attackDuration)*1e3)]:t<s.holdEnd?s.currentValue=In:t<s.decayEnd?s.currentValue=(1-(s.decayEnd-t)/s.decayDuration)*(s.sustainLevel-In)+In:s.currentValue=s.sustainLevel,s.currentValue)}};var St=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(A,t,n,s,o,i,g,E){this.sampleData=A,this.playbackStep=t,this.cursor=n,this.rootKey=s,this.loopStart=o,this.loopEnd=i,this.end=g,this.loopingMode=E,this.isLooping=this.loopingMode===1||this.loopingMode===3}},Je=class e{sample;filter=new we;generators;modulators=[];modulatedGenerators;finished=!1;isInRelease=!1;channelNumber=0;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new OA;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=0;realKey;portamentoFromKey=-1;portamentoDuration=0;overridePan=0;constructor(A,t,n,s,o,i,g,E,C,d){this.sample=t,this.generators=C,this.modulatedGenerators=new Int16Array(C),this.modulators=d,this.velocity=s,this.midiNote=n,this.channelNumber=o,this.startTime=i,this.targetKey=g,this.realKey=E,this.volumeEnvelope=new PA(A,C[r.sustainVolEnv])}static copy(A,t){let n=A.sample,s=new St(n.sampleData,n.playbackStep,n.cursor,n.rootKey,n.loopStart,n.loopEnd,n.end,n.loopingMode);return new e(A.volumeEnvelope.sampleRate,s,A.midiNote,A.velocity,A.channelNumber,t,A.targetKey,A.realKey,A.generators,A.modulators.map(o=>K.copy(o)))}release(A=ho){this.releaseStartTime=currentTime,this.releaseStartTime-this.startTime<A&&(this.releaseStartTime=this.startTime+A)}};function Co(e,A,t,n,s,o=!1){let i,g=this.workletProcessorChannels[e],E=g.cachedVoices[A]?.[t],C=this.keyModifierManager.hasOverridePatch(e,A);if(E!==void 0&&!C)return E.map(Q=>Je.copy(Q,n));let d=!0,B=g.preset;if(C){d=!1;let Q=this.keyModifierManager.getPatch(e,A);B=this.soundfontManager.getPreset(Q.bank,Q.program)}return i=B.getSamplesAndGenerators(A,t).reduce((Q,c)=>{if(c.sample.sampleData===void 0)return v(`Discarding invalid sample: ${c.sample.sampleName}`),Q;let p=new Int16Array(60);for(let b=0;b<60;b++)p[b]=Kn(b,c.presetGenerators,c.instrumentGenerators);p[r.initialAttenuation]=Math.floor(p[r.initialAttenuation]*.4);let f=c.sample.samplePitch;p[r.overridingRootKey]>-1&&(f=p[r.overridingRootKey]);let y=A;p[r.keyNum]>-1&&(y=p[r.keyNum]);let F=c.sample.sampleLoopStartIndex,L=c.sample.sampleLoopEndIndex,T=p[r.sampleModes],J=new St(c.sample.getAudioData(),c.sample.sampleRate/sampleRate*Math.pow(2,c.sample.samplePitchCorrection/1200),0,f,F,L,Math.floor(c.sample.sampleData.length)-1,T);return p[r.velocity]>-1&&(t=p[r.velocity]),o&&qn([{Sample:c.sample.sampleName,Generators:p,Modulators:c.modulators.map(b=>b.debugString()),Velocity:t,TargetKey:y,MidiNote:A,WorkletSample:J}]),Q.push(new Je(sampleRate,J,A,t,e,n,y,s,p,c.modulators.map(b=>K.copy(b)))),Q},[]),d&&(g.cachedVoices[A][t]=i.map(Q=>Je.copy(Q,n))),i}var co=.1,Fr=4600,Rr=2e3,Bo=Math.PI/2,Dt=-500,lo=500,Cn=lo-Dt,Qo=new Float32Array(Cn+1),uo=new Float32Array(Cn+1);for(let e=Dt;e<=lo;e++){let A=(e-Dt)/Cn,t=e-Dt;Qo[t]=Math.cos(Bo*A),uo[t]=Math.sin(Bo*A)}function fo(e,A,t,n,s,o,i,g){if(isNaN(A[0]))return;let E;if(e.overridePan)E=e.overridePan;else{let c=Math.max(-500,Math.min(500,e.modulatedGenerators[r.pan]));e.currentPan+=(c-e.currentPan)*this.synth.panSmoothingFactor,E=e.currentPan}let C=this.synth.currentGain,d=~~(E+500),B=Qo[d]*C*this.synth.panLeft,Q=uo[d]*C*this.synth.panRight;if(!this.synth.oneOutputMode){let c=this.synth.reverbGain*e.modulatedGenerators[r.reverbEffectsSend]/Fr*C,p=this.synth.chorusGain*e.modulatedGenerators[r.chorusEffectsSend]/Rr;if(c>0){for(let f=0;f<A.length;f++)s[f]+=c*A[f];o.set(s)}if(p>0){let f=B*p,y=Q*p;for(let F=0;F<A.length;F++)i[F]+=f*A[F],g[F]+=y*A[F]}}if(B>0)for(let c=0;c<A.length;c++)t[c]+=B*A[c];if(Q>0)for(let c=0;c<A.length;c++)n[c]+=Q*A[c]}function mo(e=!1){m("%cStop all received!",a.info);for(let A=0;A<this.workletProcessorChannels.length;A++)this.workletProcessorChannels[A].stopAllNotes(e);this.callEvent("stopall",void 0)}function po(e,A){this.soundfontBankOffset=A,this.reloadSoundFont(e,!0),this.overrideSoundfont.samples.forEach(t=>t.getAudioData()),this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers())}function yo(e,A=!1){this.clearSoundFont(!1,A);try{A?(this.overrideSoundfont=Ye(e),this.overrideSoundfont.setSampleIDOffset(this.soundfontManager.totalSoundfontOffset)):this.soundfontManager.reloadManager(e)}catch(t){this.post({messageType:RA.soundfontError,messageData:t});return}this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels.forEach(t=>t.programChange(t.preset.program)),this.post({messageType:RA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",a.recognized)}function So(e=!0,A=!0){this.stopAllChannels(!0),A&&(delete this.overrideSoundfont,this.overrideSoundfont=void 0),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let t=0;t<this.workletProcessorChannels.length;t++){let n=this.workletProcessorChannels[t];n.cachedVoices=[];for(let s=0;s<128;s++)n.cachedVoices.push([]);(!A||A&&n.presetUsesOverride)&&(n.lockPreset=!1),n.programChange(n.preset.program)}e&&this.sendPresetList()}function Do(){let e=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,n=e.find(s=>s.bank===t&&s.program===A.program);n!==void 0?n.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.callEvent("presetlistchange",e)}function ko(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,n=this.overrideSoundfont.getPresetNoFallback(t,A);if(n)return n}return this.soundfontManager.getPreset(e,A)}function wo(e,A=!1){this.transposition=0;for(let t=0;t<this.workletProcessorChannels.length;t++)this.workletProcessorChannels[t].transposeChannel(e,A);this.transposition=e}function Fo(e){e=Math.round(e);for(let A=0;A<this.workletProcessorChannels.length;A++)this.workletProcessorChannels[A].customControllers[rA.masterTuning]=e}var qe=class e{program;bank;patchName;lockPreset;midiControllers;lockedControllers;customControllers;lockVibrato;channelVibrato;channelTransposeKeyShift;channelOctaveTuning;keyCentTuning;isMuted;velocityOverride;drumChannel;static getChannelSnapshot(A,t){let n=A.workletProcessorChannels[t],s=new e;return s.program=n.preset.program,s.bank=n.getBankSelect(),s.lockPreset=n.lockPreset,s.patchName=n.preset.presetName,s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.channelVibrato=n.channelVibrato,s.lockVibrato=n.lockGSNRPNParams,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.keyCentTuning=n.keyCentTuning,s.isMuted=n.isMuted,s.velocityOverride=n.velocityOverride,s.drumChannel=n.drumChannel,s}static applyChannelSnapshot(A,t,n){let s=A.workletProcessorChannels[t];s.muteChannel(n.isMuted),s.setDrums(n.drumChannel),s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.channelVibrato=n.channelVibrato,s.lockGSNRPNParams=n.lockVibrato,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.velocityOverride=n.velocityOverride,s.lockPreset=!1,s.setBankSelect(n.bank),s.programChange(n.program),s.lockPreset=n.lockPreset}};var Fe=class e{channelSnapshots;keyMappings;mainVolume;pan;interpolation;system;transposition;effectsConfig;static createSynthesizerSnapshot(A){let t=new e;return t.channelSnapshots=A.workletProcessorChannels.map((n,s)=>qe.getChannelSnapshot(A,s)),t.keyMappings=A.keyModifierManager.getMappings(),t.mainVolume=A.midiVolume,t.pan=A.pan,t.system=A.system,t.interpolation=A.interpolationType,t.transposition=A.transposition,t.effectsConfig={},t}static applySnapshot(A,t){for(A.system=t.system,A.setMasterGain(t.mainVolume),A.setMasterPan(t.pan),A.transposeAllChannels(t.transposition),A.interpolationType=t.interpolation,A.keyModifierManager.setMappings(t.keyMappings);A.workletProcessorChannels.length<t.channelSnapshots.length;)A.createWorkletChannel();t.channelSnapshots.forEach((n,s)=>{qe.applyChannelSnapshot(A,s,n)}),m("%cFinished restoring controllers!",a.info)}};function Ro(){this.post({messageType:RA.synthesizerSnapshot,messageData:Fe.createSynthesizerSnapshot(this)})}function Go(e){Fe.applySnapshot(this,e),m("%cFinished applying snapshot!",a.info)}function kt(e,A,t){if(t<e)return 0;let n=(t-e)/(1/A)+.25;return Math.abs(n-~~(n+.5))*4-1}function Mo(e,A,t,n,s,o,i){if(e.isInRelease||currentTime>=e.releaseStartTime&&(e.isInRelease=!0,PA.startRelease(e),OA.startRelease(e),e.sample.loopingMode===3&&(e.sample.isLooping=!1)),e.modulatedGenerators[r.initialAttenuation]>2500)return e.isInRelease&&(e.finished=!0),e.finished;let g=e.targetKey,E=e.modulatedGenerators[r.fineTune]+this.customControllers[rA.channelTuning]+this.customControllers[rA.channelTransposeFine]+this.customControllers[rA.masterTuning]+this.channelOctaveTuning[e.midiNote%12]+this.keyCentTuning[e.midiNote],C=e.modulatedGenerators[r.coarseTune]+this.customControllers[rA.channelTuningSemitones],d=this.synth.tunings[this.preset.program]?.[e.realKey];if(d?.midiNote>=0&&(g=d.midiNote,E+=d.centTuning),e.portamentoFromKey>-1){let j=Math.min((currentTime-e.startTime)/e.portamentoDuration,1),P=g-e.portamentoFromKey;C-=P*(1-j)}E+=(g-e.sample.rootKey)*e.modulatedGenerators[r.scaleTuning];let B=e.modulatedGenerators[r.vibLfoToPitch];if(B!==0){let j=e.startTime+ZA(e.modulatedGenerators[r.delayVibLFO]),P=Te(e.modulatedGenerators[r.freqVibLFO]),iA=kt(j,P,currentTime);E+=iA*(B*this.customControllers[rA.modulationMultiplier])}let Q=e.modulatedGenerators[r.initialFilterFc],c=Q,p=e.modulatedGenerators[r.modLfoToPitch],f=e.modulatedGenerators[r.modLfoToVolume],y=e.modulatedGenerators[r.modLfoToFilterFc],F=0;if(p+y+f!==0){let j=e.startTime+ZA(e.modulatedGenerators[r.delayModLFO]),P=Te(e.modulatedGenerators[r.freqModLFO]),iA=kt(j,P,currentTime);E+=iA*(p*this.customControllers[rA.modulationMultiplier]),F=-iA*f,c+=iA*y}if(this.channelVibrato.depth>0){let j=kt(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,currentTime);j&&(E+=j*this.channelVibrato.depth)}let L=e.modulatedGenerators[r.modEnvToPitch],T=e.modulatedGenerators[r.modEnvToFilterFc],J=OA.getValue(e,currentTime);c+=J*T,E+=J*L;let b=~~(E+C*100);b!==e.currentTuningCents&&(e.currentTuningCents=b,e.currentTuningCalculated=Math.pow(2,b/1200));let I=new Float32Array(A.length);switch(this.synth.interpolationType){case ke.fourthOrder:De.getSampleCubic(e,I);break;case ke.linear:default:De.getSampleLinear(e,I);break;case ke.nearestNeighbor:De.getSampleNearest(e,I);break}return we.apply(e,I,c,Q>13499),PA.apply(e,I,F,this.synth.volumeEnvelopeSmoothingFactor),this.panVoice(e,I,A,t,n,s,o,i),e.finished}function xo(e,A=-12e3){this.voices.forEach(t=>{t.realKey===e&&(t.modulatedGenerators[r.releaseVolEnv]=A,t.release())})}function No(e,A=!0){e=Math.round(e),this.customControllers[rA.channelTuning]=e,A&&m(`%cChannel ${this.channelNumber} fine tuning. Cents: %c${e}`,a.info,a.value)}function bo(e){e=Math.round(e),m(`%cChannel ${this.channelNumber} modulation depth. Cents: %c${e}`,a.info,a.value),this.customControllers[rA.modulationMultiplier]=e/50}function Lo(e){switch(this.dataEntryState){default:break;case FA.RPCoarse:case FA.RPFine:switch(this.RPValue){default:break;case 0:if(e===0)break;this.midiControllers[cA+q.pitchWheelRange]|=e;let A=(this.midiControllers[cA+q.pitchWheelRange]>>7)+e/127;m(`%cChannel ${this.channelNumber} bend range. Semitones: %c${A}`,a.info,a.value);break;case 1:let n=this.customControllers[rA.channelTuning]<<7|e;this.setTuning(n*.01220703125);break;case 5:let o=this.customControllers[rA.modulationMultiplier]*50+e/128*100;this.setModulationDepth(o);break;case 16383:this.resetParameters();break}}}function Uo(e){e=Math.round(e),this.customControllers[rA.channelTuningSemitones]=e,m(`%cChannel ${this.channelNumber} coarse tuning. Semitones: %c${e}`,a.info,a.value)}var Gr=1e3/200;function To(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=e[A.sourceIndex];else{let C=A.sourceIndex+cA;switch(A.sourceIndex){case q.noController:n=16383;break;case q.noteOnKeyNum:n=t.midiNote<<7;break;case q.noteOnVelocity:n=t.velocity<<7;break;case q.polyPressure:n=t.pressure<<7;break;default:n=e[C];break}}let s=ce[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let C=A.secSrcIndex+cA;switch(A.secSrcIndex){case q.noController:o=16383;break;case q.noteOnKeyNum:o=t.midiNote<<7;break;case q.noteOnVelocity:o=t.velocity<<7;break;case q.polyPressure:o=t.pressure<<7;break;default:o=e[C]}}let i=ce[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=A.transformAmount;A.isEffectModulator&&g<=1e3&&(g*=Gr,g=Math.min(g,1e3));let E=s*i*g;return A.transformType===2&&(E=Math.abs(E)),A.currentValue=E,E}function WA(e,A,t=-1,n=0){let s=e.modulators,o=e.generators,i=e.modulatedGenerators;if(t===-1){i.set(o),s.forEach(C=>{let d=Y[C.modulatorDestination],B=i[C.modulatorDestination]+To(A,C,e);i[C.modulatorDestination]=Math.max(d.min,Math.min(B,d.max))}),PA.recalculate(e),OA.recalculate(e);return}let g=new Set([r.initialAttenuation,r.delayVolEnv,r.attackVolEnv,r.holdVolEnv,r.decayVolEnv,r.sustainVolEnv,r.releaseVolEnv,r.keyNumToVolEnvHold,r.keyNumToVolEnvDecay]),E=new Set;s.forEach(C=>{if(C.sourceUsesCC===t&&C.sourceIndex===n||C.secSrcUsesCC===t&&C.secSrcIndex===n){let d=C.modulatorDestination;E.has(d)||(i[d]=o[d],To(A,C,e),s.forEach(B=>{if(B.modulatorDestination===d){let Q=Y[C.modulatorDestination],c=i[C.modulatorDestination]+B.currentValue;i[C.modulatorDestination]=Math.max(Q.min,Math.min(c,Q.max))}}),E.add(d))}}),[...E].some(C=>g.has(C))&&PA.recalculate(e),OA.recalculate(e)}var ce=[];for(let e=0;e<4;e++){ce[e]=[[new Float32Array(mA),new Float32Array(mA)],[new Float32Array(mA),new Float32Array(mA)]];for(let A=0;A<mA;A++)ce[e][0][0][A]=Be(0,e,A/mA,0),ce[e][1][0][A]=Be(0,e,A/mA,1),ce[e][0][1][A]=Be(1,e,A/mA,0),ce[e][1][1][A]=Be(1,e,A/mA,1)}function vo(e,A,t=!1){if(e>127){if(!t)return;switch(e){default:return;case Vt.velocityOverride:this.velocityOverride=A}}if(e>=D.lsbForControl1ModulationWheel&&e<=D.lsbForControl13EffectControl2&&e!==D.lsbForControl6DataEntry){let n=e-32;if(this.lockedControllers[n])return;this.midiControllers[n]=this.midiControllers[n]&16256|A&127,this.voices.forEach(s=>WA(s,this.midiControllers,1,n))}switch(e){case D.allNotesOff:this.stopAllNotes();break;case D.allSoundOff:this.stopAllNotes(!0);break;case D.bankSelect:let n=A;if(!t){switch(this.synth.system){case"gm":m(`%cIgnoring the Bank Select (${A}), as the synth is in GM mode.`,a.info);return;case"xg":n===120||n===126||n===127?this.setDrums(!0):this.channelNumber%16!==xA&&this.setDrums(!1);break;case"gm2":n===120&&this.setDrums(!0)}this.drumChannel&&(n=128),n===128&&!this.drumChannel&&(n=this.getBankSelect())}this.setBankSelect(n);break;case D.lsbForControl0BankSelect:this.synth.system==="xg"?this.drumChannel||A!==127&&this.setBankSelect(A):this.synth.system==="gm2"&&this.setBankSelect(A);break;case D.RPNLsb:this.RPValue=this.RPValue<<7|A,this.dataEntryState=FA.RPFine;break;case D.RPNMsb:this.RPValue=A,this.dataEntryState=FA.RPCoarse;break;case D.NRPNMsb:this.NRPCoarse=A,this.dataEntryState=FA.NRPCoarse;break;case D.NRPNLsb:this.NRPFine=A,this.dataEntryState=FA.NRPFine;break;case D.dataEntryMsb:this.dataEntryCoarse(A);break;case D.lsbForControl6DataEntry:this.dataEntryFine(A);break;case D.resetAllControllers:this.resetControllers();break;case D.sustainPedal:A>=64?this.holdPedal=!0:(this.holdPedal=!1,this.sustainedVoices.forEach(s=>{s.release()}),this.sustainedVoices=[]);break;default:if(this.lockedControllers[e])return;this.midiControllers[e]=A<<7,this.voices.forEach(s=>WA(s,this.midiControllers,1,e));break}this.synth.callEvent("controllerchange",{channel:this.channelNumber,controllerNumber:e,controllerValue:A})}function Ho(e=!1){e?(this.voices.length=0,this.sustainedVoices.length=0,this.synth.sendChannelProperties()):(this.voices.forEach(A=>{A.isInRelease||A.release()}),this.sustainedVoices.forEach(A=>{A.release()}))}function Yo(e){e&&this.stopAllNotes(!0),this.isMuted=e,this.synth.sendChannelProperties(),this.synth.callEvent("mutechannel",{channel:this.channelNumber,isMuted:e})}function Jo(e,A=!1){this.drumChannel||(e+=this.synth.transposition);let t=Math.trunc(e),n=this.channelTransposeKeyShift+this.customControllers[rA.channelTransposeFine]/100;this.drumChannel&&!A||e===n||(t!==this.channelTransposeKeyShift&&this.stopAllNotes(!1),this.channelTransposeKeyShift=t,this.customControllers[rA.channelTransposeFine]=(e-t)*100)}function qo(e){let A=()=>{this.channelVibrato.delay===0&&this.channelVibrato.rate===0&&this.channelVibrato.depth===0&&(this.channelVibrato.depth=50,this.channelVibrato.rate=8,this.channelVibrato.delay=.6)};switch(this.dataEntryState){default:case FA.Idle:break;case FA.NRPFine:if(this.synth.system!=="gs"||this.lockGSNRPNParams)return;switch(this.NRPCoarse){default:if(e===64)return;v(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${this.NRPCoarse.toString(16).toUpperCase()} 0x${this.NRPFine.toString(16).toUpperCase()})%c data value: %c${e}`,a.warn,a.recognized,a.warn,a.unrecognized,a.warn,a.value);break;case 1:switch(this.NRPFine){default:if(e===64)return;v(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${this.NRPCoarse.toString(16)} 0x${this.NRPFine.toString(16)})%c data value: %c${e}`,a.warn,a.recognized,a.warn,a.unrecognized,a.warn,a.value);break;case 8:if(e===64)return;A(),this.channelVibrato.rate=e/64*8,m(`%cVibrato rate for %c${this.channelNumber}%c is now set to %c${e} = ${this.channelVibrato.rate}%cHz.`,a.info,a.recognized,a.info,a.value,a.info);break;case 9:if(e===64)return;A(),this.channelVibrato.depth=e/2,m(`%cVibrato depth for %c${this.channelNumber}%c is now set to %c${e} = ${this.channelVibrato.depth}%c cents range of detune.`,a.info,a.recognized,a.info,a.value,a.info);break;case 10:if(e===64)return;A(),this.channelVibrato.delay=e/64/3,m(`%cVibrato delay for %c${this.channelNumber}%c is now set to %c${e} = ${this.channelVibrato.delay}%c seconds.`,a.info,a.recognized,a.info,a.value,a.info);break;case 32:let n=e;this.controllerChange(D.brightness,e),m(`%cFilter cutoff for %c${this.channelNumber}%c is now set to %c${n}`,a.info,a.recognized,a.info,a.value)}break;case 29:let t=e;this.controllerChange(D.reverbDepth,t),m(`%cGS Drum reverb for %c${this.channelNumber}%c: %c${t}`,a.info,a.recognized,a.info,a.value);break}break;case FA.RPCoarse:case FA.RPFine:switch(this.RPValue){default:v(`%cUnrecognized RPN for %c${this.channelNumber}%c: %c(0x${this.RPValue.toString(16)})%c data value: %c${e}`,a.warn,a.recognized,a.warn,a.unrecognized,a.warn,a.value);break;case 0:this.midiControllers[cA+q.pitchWheelRange]=e<<7,m(`%cChannel ${this.channelNumber} bend range. Semitones: %c${e}`,a.info,a.value);break;case 2:this.setTuningSemitones(e-64);break;case 1:this.setTuning(e-64,!1);break;case 5:this.setModulationDepth(e*100);break;case 16383:this.resetParameters();break}}}var Ke={0:0,1:.006,2:.023,4:.05,8:.11,16:.25,32:.5,64:2.06,80:4.2,96:8.4,112:19.5,116:26.7,120:40,124:80,127:480};function Mr(e){if(Ke[e]!==void 0)return Ke[e];let A=null,t=null;for(let n of Object.keys(Ke))n=parseInt(n),n<e&&(A===null||n>A)&&(A=n),n>e&&(t===null||n<t)&&(t=n);if(A!==null&&t!==null){let n=Ke[A],s=Ke[t];return n+(e-A)*(s-n)/(t-A)}return 0}function Ko(e,A){return Mr(e)*(A/30)}var xr=-2320,Nr=-1130;function Po(e,A,t=!1,n=!0,s=currentTime){if(A<1){this.noteOff(e);return}if(A=Math.min(127,A),this.synth.highPerformanceMode&&this.totalVoicesAmount>200&&A<40||this.synth.highPerformanceMode&&A<10||this.isMuted)return;let o=e+this.channelTransposeKeyShift,i=o;if(o>127||o<0)return;let g=this.preset.program;this.synth.tunings[g]?.[o]?.midiNote>=0&&(i=this.synth.tunings[g]?.[o].midiNote),this.velocityOverride>0&&(A=this.velocityOverride);let E=this.synth.keyModifierManager.getVelocity(this.channelNumber,o);E>-1&&(A=E);let C=-1,d=0,B=this.midiControllers[D.portamentoTime]>>7,Q=this.midiControllers[D.portamentoControl]>>7;if(!this.drumChannel&&Q!==i&&this.midiControllers[D.portamentoOnOff]>=8192&&B>0){let y=Math.abs(i-Q);d=Ko(B,y),C=Q,this.controllerChange(D.portamentoControl,i)}let c=this.synth.getWorkletVoices(this.channelNumber,i,A,s,o,t),p=0;this.randomPan&&(p=Math.round(Math.random()*1e3-500));let f=this.voices;c.forEach(y=>{y.portamentoFromKey=C,y.portamentoDuration=d,y.overridePan=p;let F=y.generators[r.exclusiveClass];F!==0&&f.forEach(P=>{P.generators[r.exclusiveClass]===F&&(P.release(Oo),P.modulatedGenerators[r.releaseVolEnv]=xr,P.modulatedGenerators[r.releaseModEnv]=Nr,PA.recalculate(P),OA.recalculate(P))}),WA(y,this.midiControllers);let L=y.modulatedGenerators[r.startAddrsOffset]+y.modulatedGenerators[r.startAddrsCoarseOffset]*32768,T=y.modulatedGenerators[r.endAddrOffset]+y.modulatedGenerators[r.endAddrsCoarseOffset]*32768,J=y.modulatedGenerators[r.startloopAddrsOffset]+y.modulatedGenerators[r.startloopAddrsCoarseOffset]*32768,b=y.modulatedGenerators[r.endloopAddrsOffset]+y.modulatedGenerators[r.endloopAddrsCoarseOffset]*32768,I=y.sample,j=P=>Math.max(0,Math.min(I.sampleData.length-1,P));if(I.cursor=j(I.cursor+L),I.end=j(I.end+T),I.loopStart=j(I.loopStart+J),I.loopEnd=j(I.loopEnd+b),I.loopEnd<I.loopStart){let P=I.loopStart;I.loopStart=I.loopEnd,I.loopEnd=P}I.loopEnd-I.loopStart<1&&(I.loopingMode=0,I.isLooping=!1),y.volumeEnvelope.attenuation=y.volumeEnvelope.attenuationTargetGain,y.currentPan=Math.max(-500,Math.min(500,y.modulatedGenerators[r.pan]))}),this.synth.totalVoicesAmount+=c.length,this.synth.totalVoicesAmount>this.synth.voiceCap&&this.synth.voiceKilling(c.length),f.push(...c),n&&(this.synth.sendChannelProperties(),this.synth.callEvent("noteon",{midiNote:e,channel:this.channelNumber,velocity:A}))}function Vo(e){if(e>127||e<0){v("Received a noteOn for note",e,"Ignoring.");return}let A=e+this.channelTransposeKeyShift;if(this.synth.highPerformanceMode&&!this.drumChannel){this.killNote(A,-6950),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber});return}this.voices.forEach(n=>{n.realKey!==A||n.isInRelease===!0||(this.holdPedal?this.sustainedVoices.push(n):n.release())}),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber})}function Zo(e,A){this.voices.forEach(t=>{t.midiNote===e&&(t.pressure=A,WA(t,this.midiControllers,0,q.polyPressure))}),this.synth.callEvent("polypressure",{channel:this.channelNumber,midiNote:e,pressure:A})}function Wo(e){this.midiControllers[cA+q.channelPressure]=e<<7,this.voices.forEach(A=>WA(A,this.midiControllers,0,q.channelPressure)),this.synth.callEvent("channelpressure",{channel:this.channelNumber,pressure:e})}function Xo(e,A){if(this.lockedControllers[cA+q.pitchWheel])return;let t=A|e<<7;this.synth.callEvent("pitchwheel",{channel:this.channelNumber,MSB:e,LSB:A}),this.midiControllers[cA+q.pitchWheel]=t,this.voices.forEach(n=>WA(n,this.midiControllers,0,q.pitchWheel)),this.synth.sendChannelProperties()}function _o(e){if(e.length!==12)throw new Error("Tuning is not the length of 12.");this.channelOctaveTuning=e}function zo(e,A=!1){if(this.lockPreset)return;let t=this.getBankSelect(),n,s;if(this.synth.overrideSoundfont){let o=t===128?128:t-this.synth.soundfontBankOffset,i=this.synth.overrideSoundfont.getPresetNoFallback(o,e);i?(n=t,s=i,this.presetUsesOverride=!0):(s=this.synth.soundfontManager.getPreset(t,e),n=s.bank,this.presetUsesOverride=!1)}else s=this.synth.soundfontManager.getPreset(t,e),n=s.bank,this.presetUsesOverride=!1;this.setPreset(s),this.synth.callEvent("programchange",{channel:this.channelNumber,program:s.program,bank:n,userCalled:A})}var IA=class{midiControllers=new Int16Array(tt);lockedControllers=Array(tt).fill(!1);customControllers=new Float32Array(Pt);channelTransposeKeyShift=0;channelOctaveTuning=new Int8Array(12);keyCentTuning=new Int16Array(128);holdPedal=!1;drumChannel=!1;velocityOverride=0;randomPan=!1;dataEntryState=FA.Idle;NRPCoarse=0;NRPFine=0;RPValue=0;bank=0;preset=void 0;lockPreset=!1;presetUsesOverride=!1;lockGSNRPNParams=!1;channelVibrato={delay:0,depth:0,rate:0};isMuted=!1;voices=[];sustainedVoices=[];cachedVoices=[];channelNumber;synth;constructor(A,t,n){this.synth=A,this.preset=t,this.channelNumber=n;for(let s=0;s<128;s++)this.cachedVoices.push([])}renderAudio(A,t,n,s,o,i){this.voices=this.voices.filter(g=>!this.renderVoice(g,A,t,n,s,o,i))}setBankSelect(A){this.lockPreset||(this.bank=A)}getBankSelect(){return this.drumChannel?128:this.bank}setPreset(A){if(!this.lockPreset){delete this.preset,this.preset=A,this.cachedVoices=[];for(let t=0;t<128;t++)this.cachedVoices.push([])}}setDrums(A){this.lockPreset||this.drumChannel!==A&&(A?(this.channelTransposeKeyShift=0,this.drumChannel=!0,this.setPreset(this.synth.getPreset(this.getBankSelect(),this.preset.program))):(this.drumChannel=!1,this.setPreset(this.synth.getPreset(this.getBankSelect(),this.preset.program))),this.presetUsesOverride=!1,this.synth.callEvent("drumchange",{channel:this.channelNumber,isDrumChannel:this.drumChannel}),this.synth.sendChannelProperties())}setVibrato(A,t,n){this.lockGSNRPNParams||(this.channelVibrato.rate=t,this.channelVibrato.delay=n,this.channelVibrato.depth=A)}disableAndLockGSNRPN(){this.lockGSNRPNParams=!0,this.channelVibrato.rate=0,this.channelVibrato.delay=0,this.channelVibrato.depth=0}};IA.prototype.renderVoice=Mo;IA.prototype.panVoice=fo;IA.prototype.killNote=xo;IA.prototype.stopAllNotes=Ho;IA.prototype.muteChannel=Yo;IA.prototype.noteOn=Po;IA.prototype.noteOff=Vo;IA.prototype.polyPressure=Zo;IA.prototype.channelPressure=Wo;IA.prototype.pitchWheel=Xo;IA.prototype.programChange=zo;IA.prototype.setTuning=No;IA.prototype.setTuningSemitones=Uo;IA.prototype.setOctaveTuning=_o;IA.prototype.setModulationDepth=bo;IA.prototype.transposeChannel=Jo;IA.prototype.controllerChange=vo;IA.prototype.resetControllers=ws;IA.prototype.resetParameters=Fs;IA.prototype.dataEntryFine=Lo;IA.prototype.dataEntryCoarse=qo;function jo(e=!1){let A=new IA(this,this.defaultPreset,this.workletProcessorChannels.length);this.workletProcessorChannels.push(A),A.resetControllers(),this.sendChannelProperties(),e&&this.callEvent("newchannel",void 0),A.channelNumber%16===xA&&this.workletProcessorChannels[this.workletProcessorChannels.length-1].setDrums(!0)}var ho=.03,Oo=.07,$t=1,EA=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.alive=!0,this.deviceID=LA,this.interpolationType=ke.fourthOrder,this.sequencer=new hA(this),this.transposition=0,this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=$t,this.midiVolume=1,this.reverbGain=1,this.chorusGain=1,this.voiceCap=On,this.pan=0,this.panLeft=.5,this.highPerformanceMode=!1,this.keyModifierManager=new At,this.overrideSoundfont=void 0,this.panRight=.5;try{this.soundfontManager=new yt(A.processorOptions.soundfont,this.postReady.bind(this))}catch(t){throw this.post({messageType:RA.soundfontError,messageData:t}),t}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletProcessorChannels=[];for(let t=0;t<A.processorOptions.midiChannels;t++)this.createWorkletChannel(!1);this.workletProcessorChannels[xA].preset=this.drumPreset,this.workletProcessorChannels[xA].drumChannel=!0,this.volumeEnvelopeSmoothingFactor=us*(44100/sampleRate),this.panSmoothingFactor=co*(44100/sampleRate),this.system=st,this.totalVoicesAmount=0,this._snapshot=A.processorOptions?.startRenderingData?.snapshot,this.port.onmessage=t=>this.handleMessage(t.data),A.processorOptions.startRenderingData&&(this._snapshot!==void 0&&(this.applySynthesizerSnapshot(this._snapshot),this.resetAllControllers()),m("%cRendering enabled! Starting render.",a.info),A.processorOptions.startRenderingData.parsedMIDI&&(A.processorOptions.startRenderingData?.loopCount!==void 0?(this.sequencer.loopCount=A.processorOptions.startRenderingData?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.voiceCap=1/0,this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]))),zA.isInitialized.then(()=>{this.postReady(),m("%cSpessaSynth is ready!",a.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:RA.ready,messageData:void 0})}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){if(!this.alive)return!1;this.sequencer.processTick();let n=0;return this.workletProcessorChannels.forEach((s,o)=>{if(s.voices.length<1||s.isMuted)return;let i,g,E,C,d,B,Q;if(this.oneOutputMode){let c=t[0];i=o%16*2,g=c[i],E=c[i+1]}else i=o%this._outputsAmount+2,g=t[i][0],E=t[i][1],C=t[0][0],d=t[0][1],B=t[1][0],Q=t[1][1];s.renderAudio(g,E,C,d,B,Q),n+=s.voices.length}),n!==this.totalVoicesAmount&&(this.totalVoicesAmount=n,this.sendChannelProperties()),!0}destroyWorkletProcessor(){this.alive=!1,this.workletProcessorChannels.forEach(A=>{delete A.midiControllers,delete A.voices,delete A.sustainedVoices,delete A.cachedVoices,delete A.lockedControllers,delete A.preset,delete A.customControllers}),delete this.workletProcessorChannels,delete this.sequencer.midiData,delete this.sequencer,this.soundfontManager.destroyManager(),delete this.soundfontManager}controllerChange(A,t,n,s=!1){this.workletProcessorChannels[A].controllerChange(t,n,s)}noteOn(A,t,n,s=!1,o=!0){this.workletProcessorChannels[A].noteOn(t,n,s,o)}noteOff(A,t){this.workletProcessorChannels[A].noteOff(t)}polyPressure(A,t,n){this.workletProcessorChannels[A].polyPressure(t,n)}channelPressure(A,t){this.workletProcessorChannels[A].channelPressure(t)}pitchWheel(A,t,n){this.workletProcessorChannels[A].pitchWheel(t,n)}programChange(A,t,n=!1){this.workletProcessorChannels[A].programChange(t,n)}};EA.prototype.voiceKilling=Bs;EA.prototype.getWorkletVoices=Co;EA.prototype.handleMessage=ds;EA.prototype.sendChannelProperties=ms;EA.prototype.callEvent=fs;EA.prototype.systemExclusive=ps;EA.prototype.stopAllChannels=mo;EA.prototype.createWorkletChannel=jo;EA.prototype.resetAllControllers=ks;EA.prototype.setMasterGain=Ss;EA.prototype.setMasterPan=Ds;EA.prototype.setMIDIVolume=ys;EA.prototype.transposeAllChannels=wo;EA.prototype.setMasterTuning=Fo;EA.prototype.getPreset=ko;EA.prototype.reloadSoundFont=yo;EA.prototype.clearSoundFont=So;EA.prototype.setEmbeddedSoundFont=po;EA.prototype.sendPresetList=Do;EA.prototype.sendSynthesizerSnapshot=Ro;EA.prototype.applySynthesizerSnapshot=Go;registerProcessor(Pn,EA);m("%cProcessor succesfully registered!",a.recognized);
|
|
@@ -3,9 +3,10 @@ import { generatorTypes } from "../../../../soundfont/basic_soundfont/generator.
|
|
|
3
3
|
/**
|
|
4
4
|
* Stops a note nearly instantly
|
|
5
5
|
* @param midiNote {number}
|
|
6
|
+
* @param releaseTime {number} ticks
|
|
6
7
|
* @this {WorkletProcessorChannel}
|
|
7
8
|
*/
|
|
8
|
-
export function killNote(midiNote)
|
|
9
|
+
export function killNote(midiNote, releaseTime = -12000)
|
|
9
10
|
{
|
|
10
11
|
this.voices.forEach(v =>
|
|
11
12
|
{
|
|
@@ -13,7 +14,7 @@ export function killNote(midiNote)
|
|
|
13
14
|
{
|
|
14
15
|
return;
|
|
15
16
|
}
|
|
16
|
-
v.modulatedGenerators[generatorTypes.releaseVolEnv] =
|
|
17
|
+
v.modulatedGenerators[generatorTypes.releaseVolEnv] = releaseTime; // set release to be very short
|
|
17
18
|
v.release();
|
|
18
19
|
});
|
|
19
20
|
}
|
|
@@ -21,7 +21,11 @@ export function noteOff(midiNote)
|
|
|
21
21
|
// if the channel is percussion channel, do not kill the notes
|
|
22
22
|
if (!this.drumChannel)
|
|
23
23
|
{
|
|
24
|
-
this.killNote(realKey);
|
|
24
|
+
this.killNote(realKey, -6950);
|
|
25
|
+
this.synth.callEvent("noteoff", {
|
|
26
|
+
midiNote: midiNote,
|
|
27
|
+
channel: this.channelNumber
|
|
28
|
+
});
|
|
25
29
|
return;
|
|
26
30
|
}
|
|
27
31
|
}
|