spessasynth_lib 3.9.16 → 3.9.17
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
|
@@ -10,4 +10,4 @@ var bt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>(
|
|
|
10
10
|
`+g.extraStackTrace()),(o=r).replace(/__Z[\w\d_]+/g,function(E){var l,D=l=E;return E===D?E:E+" ["+D+"]"})}function xe(o,r){return o%r>0&&(o+=r-o%r),o}function St(o){g.buffer=I=o}function be(){g.HEAP8=s=new Int8Array(I),g.HEAP16=i=new Int16Array(I),g.HEAP32=h=new Int32Array(I),g.HEAPU8=n=new Uint8Array(I),g.HEAPU16=B=new Uint16Array(I),g.HEAPU32=d=new Uint32Array(I),g.HEAPF32=f=new Float32Array(I),g.HEAPF64=c=new Float64Array(I)}function Dt(){var o=g.usingWasm?65536:16777216,r=2147483648-o;if(h[x>>2]>r)return!1;var E=gA;for(gA=Math.max(gA,16777216);gA<h[x>>2];)gA=gA<=536870912?xe(2*gA,o):Math.min(xe((3*gA+2147483648)/4,o),r);var l=g.reallocBuffer(gA);return l&&l.byteLength==gA?(St(l),be(),!0):(gA=E,!1)}Q=u=Y=M=L=q=x=0,p=!1,g.reallocBuffer||(g.reallocBuffer=function(o){try{if(ArrayBuffer.transfer)r=ArrayBuffer.transfer(I,o);else{var r,E=s;r=new ArrayBuffer(o),new Int8Array(r).set(E)}}catch{return!1}return!!vs(r)&&r});try{(V=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{V=function(r){return r.byteLength}}var Le=g.TOTAL_STACK||5242880,gA=g.TOTAL_MEMORY||16777216;function Ts(){return gA}function jA(o){for(;o.length>0;){var r=o.shift();if(typeof r=="function"){r();continue}var E=r.func;typeof E=="number"?r.arg===void 0?g.dynCall_v(E):g.dynCall_vi(E,r.arg):E(r.arg===void 0?null:r.arg)}}gA<Le&&FA("TOTAL_MEMORY should be larger than TOTAL_STACK, was "+gA+"! (TOTAL_STACK="+Le+")"),g.buffer?I=g.buffer:(typeof WebAssembly=="object"&&typeof WebAssembly.Memory=="function"?(g.wasmMemory=new WebAssembly.Memory({initial:gA/65536}),I=g.wasmMemory.buffer):I=new ArrayBuffer(gA),g.buffer=I),be();var wt=[],He=[],Ft=[],Rt=[],Gt=[],Ye=!1,qs=!1;function Ks(o){wt.unshift(o)}function Do(o){He.unshift(o)}function wo(o){Ft.unshift(o)}function Fo(o){Rt.unshift(o)}function Vs(o){Gt.unshift(o)}function Ro(o,r,E){var l,D;zA("writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!"),E&&(l=s[D=r+ae(o)]),pt(o,r,1/0),E&&(s[D]=l)}function Go(o,r,E){return o>=0?o:r<=32?2*Math.abs(1<<r-1)+o:Math.pow(2,r)+o}function ko(o,r,E){if(o<=0)return o;var l=r<=32?Math.abs(1<<r-1):Math.pow(2,r-1);return o>=l&&(r<=32||o>l)&&(o=-2*l+o),o}var Ps=Math.abs,Os=Math.ceil,kt=Math.floor,Zs=Math.min,TA=0,Je=null,$A=null;function No(o){return o}g.preloadedImages={},g.preloadedAudios={};var Nt="data:application/octet-stream;base64,";function Be(o){return String.prototype.startsWith?o.startsWith(Nt):o.indexOf(Nt)===0}(function(){var r="main.wast",E="main.wasm",l="main.temp.asm.js";Be(r)||(r=ke(r)),Be(E)||(E=ke(E)),Be(l)||(l=ke(l));var D={global:null,env:null,asm2wasm:Hs,parent:g},N=null;function b(P){return P}function w(){try{if(g.wasmBinary)return new Uint8Array(g.wasmBinary);if(g.readBinary)return g.readBinary(E);throw"both async and sync fetching of the wasm failed"}catch(P){UA(P)}}g.asmPreload=g.asm;var nA=g.reallocBuffer,W=function(P){P=xe(P,g.usingWasm?65536:16777216);var k=g.buffer.byteLength;if(g.usingWasm)try{var hA=g.wasmMemory.grow((P-k)/65536);return hA!==-1?g.buffer=g.wasmMemory.buffer:null}catch{return null}};g.reallocBuffer=function(P){return _==="asmjs"?nA(P):W(P)};var _="";g.asm=function(P,k,hA){var mA;if(!(k=mA=k).table){var pA,yA=g.wasmTableSize;yA===void 0&&(yA=1024);var qA=g.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?qA!==void 0?k.table=new WebAssembly.Table({initial:yA,maximum:qA,element:"anyfunc"}):k.table=new WebAssembly.Table({initial:yA,element:"anyfunc"}):k.table=Array(yA),g.wasmTable=k.table}return k.memoryBase||(k.memoryBase=g.STATIC_BASE),k.tableBase||(k.tableBase=0),pA=function(ee,vA,Ve){if(typeof WebAssembly!="object")return FA("no native wasm support detected"),!1;if(!(g.wasmMemory instanceof WebAssembly.Memory))return FA("no native wasm Memory in use"),!1;function le(RA,GA){if((N=RA.exports).memory){var te,Pe,xt;te=N.memory,Pe=g.buffer,te.byteLength<Pe.byteLength&&FA("the new buffer in mergeMemory is smaller than the previous one. in native wasm, we should grow memory here"),xt=new Int8Array(Pe),new Int8Array(te).set(xt),St(te),be()}g.asm=N,g.usingWasm=!0,function(Yo){if(TA--,g.monitorRunDependencies&&g.monitorRunDependencies(TA),TA==0&&(Je!==null&&(clearInterval(Je),Je=null),$A)){var Xs=$A;$A=null,Xs()}}("wasm-instantiate")}if(vA.memory=g.wasmMemory,D.global={NaN:NaN,Infinity:1/0},D["global.Math"]=Math,D.env=vA,TA++,g.monitorRunDependencies&&g.monitorRunDependencies(TA),g.instantiateWasm)try{return g.instantiateWasm(D,le)}catch(RA){return FA("Module.instantiateWasm callback failed with error: "+RA),!1}function XA(RA){le(RA.instance,RA.module)}function Ut(RA){(!g.wasmBinary&&(j||IA)&&typeof fetch=="function"?fetch(E,{credentials:"same-origin"}).then(function(GA){if(!GA.ok)throw"failed to load wasm binary file at '"+E+"'";return GA.arrayBuffer()}).catch(function(){return w()}):new Promise(function(GA,te){GA(w())})).then(function(GA){return WebAssembly.instantiate(GA,D)}).then(RA).catch(function(GA){FA("failed to asynchronously prepare wasm: "+GA),UA(GA)})}return g.wasmBinary||typeof WebAssembly.instantiateStreaming!="function"||Be(E)||typeof fetch!="function"?Ut(XA):WebAssembly.instantiateStreaming(fetch(E,{credentials:"same-origin"}),D).then(XA).catch(function(RA){FA("wasm streaming compile failed: "+RA),FA("falling back to ArrayBuffer instantiation"),Ut(XA)}),{}}(P,k,hA),LA(pA,"no binaryen method succeeded."),pA},g.asm})(),u=(Q=1024)+4816,He.push(),g.STATIC_BASE=Q,g.STATIC_BUMP=4816;var dA=u;function Mo(o){s[dA]=s[o],s[dA+1]=s[o+1],s[dA+2]=s[o+2],s[dA+3]=s[o+3]}function Uo(o){s[dA]=s[o],s[dA+1]=s[o+1],s[dA+2]=s[o+2],s[dA+3]=s[o+3],s[dA+4]=s[o+4],s[dA+5]=s[o+5],s[dA+6]=s[o+6],s[dA+7]=s[o+7]}function xo(o,r,E){var l=E>0?E:ae(o)+1,D=Array(l),N=Ee(o,D,0,D.length);return r&&(D.length=N),D}function bo(o){for(var r=[],E=0;E<o.length;E++){var l=o[E];l>255&&(l&=255),r.push(String.fromCharCode(l))}return r.join("")}u+=16,x=re(4),L=(Y=M=lt(u))+Le,q=lt(L),h[x>>2]=q,p=!0,g.wasmTableSize=4,g.wasmMaxTableSize=4,g.asmGlobalArg={},g.asmLibraryArg={abort:UA,assert:LA,enlargeMemory:Dt,getTotalMemory:Ts,abortOnCannotGrowMemory:function(){UA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+gA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(r,E,l){var D=qe();try{return g.dynCall_iii(r,E,l)}catch(N){if(Te(D),typeof N!="number"&&N!=="longjmp")throw N;g.setThrew(1,0)}},___assert_fail:function(r,E,l,D){UA("Assertion failed: "+Ce(r)+", at: "+[E?Ce(E):"unknown filename",l,D?Ce(D):"unknown function"])},___setErrNo:function(r){return g.___errno_location&&(h[g.___errno_location()>>2]=r),r},_abort:function(){g.abort()},_emscripten_memcpy_big:function(r,E,l){return n.set(n.subarray(E,E+l),r),r},_llvm_floor_f64:kt,DYNAMICTOP_PTR:x,tempDoublePtr:dA,ABORT:ie,STACKTOP:M,STACK_MAX:L};var Mt=g.asm(g.asmGlobalArg,g.asmLibraryArg,I);g.asm=Mt,g.___errno_location=function(){return g.asm.___errno_location.apply(null,arguments)};var vs=g._emscripten_replace_memory=function(){return g.asm._emscripten_replace_memory.apply(null,arguments)};g._free=function(){return g.asm._free.apply(null,arguments)};var Qe=g._malloc=function(){return g.asm._malloc.apply(null,arguments)};g._memcpy=function(){return g.asm._memcpy.apply(null,arguments)},g._memset=function(){return g.asm._memset.apply(null,arguments)},g._sbrk=function(){return g.asm._sbrk.apply(null,arguments)},g._stb_vorbis_js_channels=function(){return g.asm._stb_vorbis_js_channels.apply(null,arguments)},g._stb_vorbis_js_close=function(){return g.asm._stb_vorbis_js_close.apply(null,arguments)},g._stb_vorbis_js_decode=function(){return g.asm._stb_vorbis_js_decode.apply(null,arguments)},g._stb_vorbis_js_open=function(){return g.asm._stb_vorbis_js_open.apply(null,arguments)},g._stb_vorbis_js_sample_rate=function(){return g.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},g.establishStackSpace=function(){return g.asm.establishStackSpace.apply(null,arguments)},g.getTempRet0=function(){return g.asm.getTempRet0.apply(null,arguments)},g.runPostSets=function(){return g.asm.runPostSets.apply(null,arguments)},g.setTempRet0=function(){return g.asm.setTempRet0.apply(null,arguments)},g.setThrew=function(){return g.asm.setThrew.apply(null,arguments)};var he=g.stackAlloc=function(){return g.asm.stackAlloc.apply(null,arguments)},Te=g.stackRestore=function(){return g.asm.stackRestore.apply(null,arguments)},qe=g.stackSave=function(){return g.asm.stackSave.apply(null,arguments)};function Ae(o){this.name="ExitStatus",this.message="Program terminated with exit("+o+")",this.status=o}function Ke(o){o=o||g.arguments,!(TA>0)&&(function(){if(g.preRun)for(typeof g.preRun=="function"&&(g.preRun=[g.preRun]);g.preRun.length;)Ks(g.preRun.shift());jA(wt)}(),!(TA>0)&&(g.calledRun||(g.setStatus?(g.setStatus("Running..."),setTimeout(function(){setTimeout(function(){g.setStatus("")},1),r()},1)):r())));function r(){!g.calledRun&&(g.calledRun=!0,ie||(Ye||(Ye=!0,jA(He)),jA(Ft),g.onRuntimeInitialized&&g.onRuntimeInitialized(),function(){if(g.postRun)for(typeof g.postRun=="function"&&(g.postRun=[g.postRun]);g.postRun.length;)Vs(g.postRun.shift());jA(Gt)}()))}}function Lo(o,r){(!r||!g.noExitRuntime||o!==0)&&(g.noExitRuntime||(ie=!0,ct=o,M=X,jA(Rt),qs=!0,g.onExit&&g.onExit(o)),g.quit(o,new Ae(o)))}function UA(o){throw g.onAbort&&g.onAbort(o),o!==void 0?(Qt(o),FA(o),o=JSON.stringify(o)):o="",ie=!0,ct=1,"abort("+o+"). Build with -s ASSERTIONS=1 for more info."}if(g.dynCall_iii=function(){return g.asm.dynCall_iii.apply(null,arguments)},g.asm=Mt,g.ccall=ft,g.cwrap=function(r,E,l,D){var N=(l=l||[]).every(function(b){return b==="number"});return E!=="string"&&N&&!D?dt(r):function(){return ft(r,E,l,arguments,D)}},Ae.prototype=Error(),Ae.prototype.constructor=Ae,$A=function o(){g.calledRun||Ke(),g.calledRun||($A=o)},g.run=Ke,g.abort=UA,g.preInit)for(typeof g.preInit=="function"&&(g.preInit=[g.preInit]);g.preInit.length>0;)g.preInit.pop()();g.noExitRuntime=!0,Ke(),g.onRuntimeInitialized=()=>{jt=!0,$t()},YA.decode=function(o){return function(E){if(!jt)throw Error("Not initialized");var l={};function D(vA){return new Int32Array(g.HEAPU8.buffer,vA,1)[0]}function N(vA,Ve){var le=new ArrayBuffer(Ve*Float32Array.BYTES_PER_ELEMENT),XA=new Float32Array(le);return XA.set(new Float32Array(g.HEAPU8.buffer,vA,Ve)),XA}l.open=g.cwrap("stb_vorbis_js_open","number",[]),l.close=g.cwrap("stb_vorbis_js_close","void",["number"]),l.channels=g.cwrap("stb_vorbis_js_channels","number",["number"]),l.sampleRate=g.cwrap("stb_vorbis_js_sample_rate","number",["number"]),l.decode=g.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var b,w,nA,W,_=l.open(),P=(b=E,w=E.byteLength,nA=g._malloc(w),(W=new Uint8Array(g.HEAPU8.buffer,nA,w)).set(new Uint8Array(b,0,w)),W),k=g._malloc(4),hA=g._malloc(4),mA=l.decode(_,P.byteOffset,P.byteLength,k,hA);if(g._free(P.byteOffset),mA<0)throw l.close(_),g._free(k),Error("stbvorbis decode failed: "+mA);for(var pA=l.channels(_),yA=Array(pA),qA=new Int32Array(g.HEAPU32.buffer,D(k),pA),SA=0;SA<pA;SA++)yA[SA]=N(qA[SA],mA),g._free(qA[SA]);var ee=l.sampleRate(_);return l.close(_),g._free(D(k)),g._free(k),{data:yA,sampleRate:ee,eof:!0,error:null}}(o)}})();var $e=class{constructor(A,t,I,s,n,i,B,h){this.sampleName=A,this.sampleRate=t,this.samplePitch=I,this.samplePitchCorrection=s,this.sampleLink=n,this.sampleType=i,this.sampleLoopStartIndex=B,this.sampleLoopEndIndex=h,this.isCompressed=(i&16)>0,this.compressedData=void 0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,t){if(!this.isCompressed)try{this.compressedData=t([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{J(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}},At=class extends $e{constructor(A,t,I,s,n,i,B,h,d,f,c,Q){super(A,i,B,h,d,f,s-t,n-t),this.sampleName=A,this.sampleStartIndex=t,this.sampleEndIndex=I,this.isSampleLoaded=!1,this.sampleID=Q,this.useCount=0,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=c,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex,this.sampleLoopEndIndex+=this.sampleStartIndex,this.sampleLength=99999999)}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{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,I=A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t);this.sampleData=new Float32Array(0);let s=YA.decode(I.buffer);this.sampleData=s.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.loadBufferData()}loadUncompressedData(){if(this.isCompressed)return J("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),t=this.sampleDataArray.currentIndex,I=new Int16Array(this.sampleDataArray.slice(t+this.sampleStartIndex,t+this.sampleEndIndex).buffer);for(let s=0;s<I.length;s++)A[s]=I[s]/32768;return this.sampleData=A,this.isSampleLoaded=!0,A}loadBufferData(){return this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.loadUncompressedData()}};function AI(e,A){let t=[],I=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let s=zs(I,e.chunkData,A);t.push(s),I++}return t.length>1&&t.pop(),t}function zs(e,A,t){let I=z(A,20),s=T(A,4)*2,n=T(A,4)*2,i=T(A,4)*2,B=T(A,4)*2,h=T(A,4),d=A[A.currentIndex++];d===255&&(d=60);let f=vt(A[A.currentIndex++]),c=T(A,2),Q=T(A,2);return new At(I,s,n,i,B,h,d,f,c,Q,t,e)}var et=class{constructor(A){this.instrumentName=z(A.chunkData,20).trim(),this.instrumentZoneIndex=T(A.chunkData,2),this.instrumentZonesAmount=0,this.instrumentZones=[],this._useCount=0}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;A<this.instrumentZones.length;A++)this.safeDeleteZone(A)&&A--}get useCount(){return this._useCount}deleteInstrument(){this.instrumentZones.forEach(A=>A.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}getInstrumentZones(A,t){this.instrumentZonesAmount=A;for(let I=this.instrumentZoneIndex;I<this.instrumentZonesAmount+this.instrumentZoneIndex;I++)this.instrumentZones.push(t[I])}};function eI(e,A){let t=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let I=new et(e);if(t.length>0){let s=I.instrumentZoneIndex-t[t.length-1].instrumentZoneIndex;t[t.length-1].getInstrumentZones(s,A)}t.push(I)}return t.length>1&&t.pop(),t}var tt=class{constructor(A,t){this.generatorZoneStartIndex=T(A,2),this.modulatorZoneStartIndex=T(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(I=>I.generatorType===a.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function tI(e,A,t,I){let s=[],n=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let i=new tt(e.chunkData,n);if(s.length>0){let B=i.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,h=i.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(B,h),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(t),s[s.length-1].getSample(I),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(i),n++}return s.length>1&&s.pop(),s}var It=class{constructor(A,t){this.generatorZoneStartIndex=T(A,2),this.modulatorZoneStartIndex=T(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(I=>I.generatorType===a.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function II(e,A,t,I){let s=[],n=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let i=new It(e.chunkData,n);if(s.length>0){let B=i.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,h=i.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(B,h),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(t),s[s.length-1].getInstrument(I),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(i),n++}return s.length>1&&s.pop(),s}var st=class{constructor(A){this.presetName=z(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=T(A.chunkData,2),this.bank=T(A.chunkData,2),this.presetZoneStartIndex=T(A.chunkData,2),this.presetZonesAmount=0,this.presetZones=[],this.foundSamplesAndGenerators=[];for(let t=0;t<128;t++)this.foundSamplesAndGenerators[t]=[];this.library=T(A.chunkData,4),this.genre=T(A.chunkData,4),this.morphology=T(A.chunkData,4)}getPresetZones(A,t){this.presetZonesAmount=A;for(let I=this.presetZoneStartIndex;I<this.presetZonesAmount+this.presetZoneStartIndex;I++)this.presetZones.push(t[I])}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 I=A;I<t+1;I++)for(let s=0;s<128;s++)this.getSamplesAndGenerators(I,s).forEach(n=>{n.sample.isSampleLoaded||n.sample.getAudioData()})}preloadSpecific(A,t){this.getSamplesAndGenerators(A,t).forEach(I=>{I.sample.isSampleLoaded||I.sample.getAudioData()})}getSamplesAndGenerators(A,t){let I=this.foundSamplesAndGenerators[A][t];if(I)return I;function s(Q,u,p){return p>=Q&&p<=u}function n(Q,u){return Q.modulatorSource===u.modulatorSource&&Q.modulatorDestination===u.modulatorDestination&&Q.modulationSecondarySrc===u.modulationSecondarySrc&&Q.transformType===u.transformType}function i(Q,u){Q.push(...u.filter(p=>!Q.find(Y=>Y.generatorType===p.generatorType)))}function B(Q,u){Q.push(...u.filter(p=>!Q.find(Y=>n(p,Y))))}let h=[],d=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],f=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(Q=>s(Q.keyRange.min,Q.keyRange.max,A)&&s(Q.velRange.min,Q.velRange.max,t)&&!Q.isGlobal).forEach(Q=>{let u=Q.generators,p=Q.modulators,Y=Q.instrument.instrumentZones[0].isGlobal?[...Q.instrument.instrumentZones[0].generators]:[],M=Q.instrument.instrumentZones[0].isGlobal?[...Q.instrument.instrumentZones[0].modulators]:[];Q.instrument.instrumentZones.filter(q=>s(q.keyRange.min,q.keyRange.max,A)&&s(q.velRange.min,q.velRange.max,t)&&!q.isGlobal).forEach(q=>{let x=[...q.generators],V=[...q.modulators];i(u,d),i(x,Y),B(p,f),B(V,M),B(V,Wt);let X=[...V];for(let g=0;g<p.length;g++){let v=p[g],j=X.findIndex(IA=>n(v,IA));j!==-1?X[j]=X[j].sumTransform(v):X.push(v)}h.push({instrumentGenerators:x,presetGenerators:u,modulators:X,sample:q.sample,sampleID:q.generators.find(g=>g.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=h,h}};function sI(e,A){let t=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let I=new st(e);if(t.length>0){let s=I.presetZoneStartIndex-t[t.length-1].presetZoneStartIndex;t[t.length-1].getPresetZones(s,A)}t.push(I)}return t.length>1&&t.pop(),t}function oI(){let e=4;for(let I of this.instruments)e+=I.instrumentZones.reduce((s,n)=>(n.generators=n.generators.filter(i=>i.generatorType!==a.sampleID&&i.generatorType!==a.keyRange&&i.generatorType!==a.velRange),(n.velRange.max!==127||n.velRange.min!==0)&&n.generators.unshift({generatorType:a.velRange,generatorValue:n.velRange.max<<8|n.velRange.min}),(n.keyRange.max!==127||n.keyRange.min!==0)&&n.generators.unshift({generatorType:a.keyRange,generatorValue:n.keyRange.max<<8|n.keyRange.min}),n.isGlobal||n.generators.push({generatorType:a.sampleID,generatorValue:this.samples.indexOf(n.sample)}),n.generators.length*4+s),0);let A=new U(e),t=0;for(let I of this.instruments)for(let s of I.instrumentZones){s.generatorZoneStartIndex=t;for(let n of s.generators)G(A,n.generatorType),G(A,n.generatorValue),t++}return iA(A,0),Z(new K("igen",A.length,A))}function gI(e,A,t,I,s){let n=this.samples.map((d,f)=>{t&&d.compressSample(I,s);let c=d.getRawData();return m(`%cEncoded sample %c${f}. ${d.sampleName}%c of %c${this.samples.length}`,C.info,C.recognized,C.info,C.recognized),c}),i=this.samples.reduce((d,f,c)=>d+n[c].length+46,0),B=new U(i);this.samples.forEach((d,f)=>{let c=n[f],Q,u,p=c.length;d.isCompressed?(Q=B.currentIndex,u=Q+c.length):(Q=B.currentIndex/2,u=Q+c.length/2,p+=46),e.push(Q),B.set(c,B.currentIndex),B.currentIndex+=p,A.push(u)});let h=Z(new K("smpl",B.length,B),new U([115,100,116,97]));return Z(new K("LIST",h.length,h))}function nI(e,A){let I=new U(46*(this.samples.length+1));return this.samples.forEach((s,n)=>{uA(I,s.sampleName,20);let i=e[n];iA(I,i);let B=A[n];iA(I,B);let h=s.sampleLoopStartIndex/2+i,d=s.sampleLoopEndIndex/2+i;s.isCompressed&&(h-=i,d-=i),iA(I,h),iA(I,d),iA(I,s.sampleRate),I[I.currentIndex++]=s.samplePitch,I[I.currentIndex++]=s.samplePitchCorrection,G(I,s.sampleLink),G(I,s.sampleType)}),uA(I,"EOS",46),Z(new K("shdr",I.length,I))}function rI(){let e=10;for(let I of this.instruments)e+=I.instrumentZones.reduce((s,n)=>n.modulators.length*10+s,0);let A=new U(e),t=0;for(let I of this.instruments)for(let s of I.instrumentZones){s.modulatorZoneStartIndex=t;for(let n of s.modulators)G(A,n.modulatorSource),G(A,n.modulatorDestination),G(A,n.transformAmount),G(A,n.modulationSecondarySrc),G(A,n.transformType),t++}return oe(A,0,10),Z(new K("imod",A.length,A))}function iI(){let e=this.instruments.reduce((n,i)=>i.instrumentZones.length*4+n,4),A=new U(e),t=0,I=0,s=0;for(let n of this.instruments){n.instrumentZoneIndex=t;for(let i of n.instrumentZones)i.zoneID=t,G(A,I),G(A,s),I+=i.generators.length,s+=i.modulators.length,t++}return G(A,I),G(A,s),Z(new K("ibag",A.length,A))}function CI(){let e=this.instruments.length*22+22,A=new U(e),t=0,I=0;for(let s of this.instruments)uA(A,s.instrumentName,20),G(A,t),t+=s.instrumentZones.length,s.instrumentID=I,I++;return uA(A,"EOI",20),G(A,t),Z(new K("inst",A.length,A))}function EI(){let e=4;for(let I of this.presets)e+=I.presetZones.reduce((s,n)=>(n.generators=n.generators.filter(i=>i.generatorType!==a.instrument&&i.generatorType!==a.keyRange&&i.generatorType!==a.velRange),(n.velRange.max!==127||n.velRange.min!==0)&&n.generators.unshift({generatorType:a.velRange,generatorValue:n.velRange.max<<8|n.velRange.min}),(n.keyRange.max!==127||n.keyRange.min!==0)&&n.generators.unshift({generatorType:a.keyRange,generatorValue:n.keyRange.max<<8|n.keyRange.min}),n.isGlobal||n.generators.push({generatorType:a.instrument,generatorValue:this.instruments.indexOf(n.instrument)}),n.generators.length*4+s),0);let A=new U(e),t=0;for(let I of this.presets)for(let s of I.presetZones){s.generatorZoneStartIndex=t;for(let n of s.generators)G(A,n.generatorType),G(A,n.generatorValue);t+=s.generators.length}return G(A,0),G(A,0),Z(new K("pgen",A.length,A))}function aI(){let e=10;for(let I of this.presets)e+=I.presetZones.reduce((s,n)=>n.modulators.length*10+s,0);let A=new U(e),t=0;for(let I of this.presets)for(let s of I.presetZones){s.modulatorZoneStartIndex=t;for(let n of s.modulators)G(A,n.modulatorSource),G(A,n.modulatorDestination),G(A,n.transformAmount),G(A,n.modulationSecondarySrc),G(A,n.transformType),t++}return oe(A,0,10),Z(new K("pmod",A.length,A))}function BI(){let e=this.presets.reduce((n,i)=>i.presetZones.length*4+n,4),A=new U(e),t=0,I=0,s=0;for(let n of this.presets){n.presetZoneStartIndex=t;for(let i of n.presetZones)i.zoneID=t,G(A,I),G(A,s),I+=i.generators.length,s+=i.modulators.length,t++}return G(A,I),G(A,s),Z(new K("pbag",A.length,A))}function QI(){let e=this.presets.length*38+38,A=new U(e),t=0;for(let I of this.presets)uA(A,I.presetName,20),G(A,I.program),G(A,I.bank),G(A,t),iA(A,I.library),iA(A,I.genre),iA(A,I.morphology),t+=I.presetZones.length;return uA(A,"EOP",20),G(A,0),G(A,0),G(A,t),iA(A,0),iA(A,0),iA(A,0),Z(new K("phdr",A.length,A))}var js={compress:!1,compressionQuality:.5,compressionFunction:void 0};function hI(e=js){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");HA("%cSaving soundfont...",C.info),m(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,C.info,C.recognized,C.info,C.recognized),m("%cWriting INFO...",C.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.compress&&(this.soundFontInfo.ifil="3.0");for(let[V,X]of Object.entries(this.soundFontInfo))if(V==="ifil"||V==="iver"){let g=parseInt(X.split(".")[0]),v=parseInt(X.split(".")[1]),j=new U(4);G(j,g),G(j,v),A.push(Z(new K(V,4,j)))}else{let g=new U(X.length);uA(g,X),A.push(Z(new K(V,X.length,g)))}let t=ce([new U([73,78,70,79]),...A]),I=Z(new K("LIST",t.length,t));m("%cWriting SDTA...",C.info);let s=[],n=[],i=gI.call(this,s,n,e?.compress,e?.compressionQuality||.5,e.compressionFunction);m("%cWriting PDTA...",C.info),m("%cWriting SHDR...",C.info);let B=nI.call(this,s,n);m("%cWriting IGEN...",C.info);let h=oI.call(this);m("%cWriting IMOD...",C.info);let d=rI.call(this);m("%cWriting IBAG...",C.info);let f=iI.call(this);m("%cWriting INST...",C.info);let c=CI.call(this),Q=EI.call(this);m("%cWriting PMOD...",C.info);let u=aI.call(this);m("%cWriting PBAG...",C.info);let p=BI.call(this);m("%cWriting PHDR...",C.info);let Y=QI.call(this),M=ce([new U([112,100,116,97]),Y,p,u,Q,c,f,d,h,B]),L=Z(new K("LIST",M.length,M));m("%cWriting the output file...",C.info);let q=ce([new U([115,102,98,107]),I,i,L]),x=Z(new K("RIFF",q.length,q));return m(`%cSaved succesfully! Final file size: %c${x.length}`,C.info,C.recognized),sA(),x}var PA=class e{constructor(A){if(A.presets){this.presets=A.presets,this.soundFontInfo=A.info;return}if(this.dataArray=new U(A),Pt("%cParsing SoundFont...",C.info),!this.dataArray)throw sA(),new TypeError("No data!");let t=oA(this.dataArray,!1);this.verifyHeader(t,"riff"),this.verifyText(z(this.dataArray,4),"sfbk");let I=oA(this.dataArray);for(this.verifyHeader(I,"list"),z(I.chunkData,4),this.soundFontInfo={};I.chunkData.length>I.chunkData.currentIndex;){let g=oA(I.chunkData),v;switch(g.header.toLowerCase()){case"ifil":case"iver":v=`${T(g.chunkData,2)}.${T(g.chunkData,2)}`;break;case"icmt":v=z(g.chunkData,g.chunkData.length,void 0,!1);break;default:v=z(g.chunkData,g.chunkData.length)}m(`%c"${g.header}": %c"${v}"`,C.info,C.recognized),this.soundFontInfo[g.header]=v}let s=oA(this.dataArray,!1);this.verifyHeader(s,"list"),this.verifyText(z(this.dataArray,4),"sdta"),m("%cVerifying smpl chunk...",C.warn);let n=oA(this.dataArray,!1);this.verifyHeader(n,"smpl"),this.sampleDataStartIndex=this.dataArray.currentIndex,m(`%cSkipping sample chunk, length: %c${s.size-12}`,C.info,C.value),this.dataArray.currentIndex+=s.size-12,m("%cLoading preset data chunk...",C.warn);let i=oA(this.dataArray);this.verifyHeader(i,"list"),z(i.chunkData,4);let B=oA(i.chunkData);this.verifyHeader(B,"phdr");let h=oA(i.chunkData);this.verifyHeader(h,"pbag");let d=oA(i.chunkData);this.verifyHeader(d,"pmod");let f=oA(i.chunkData);this.verifyHeader(f,"pgen");let c=oA(i.chunkData);this.verifyHeader(c,"inst");let Q=oA(i.chunkData);this.verifyHeader(Q,"ibag");let u=oA(i.chunkData);this.verifyHeader(u,"imod");let p=oA(i.chunkData);this.verifyHeader(p,"igen");let Y=oA(i.chunkData);this.verifyHeader(Y,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples=AI(Y,this.dataArray);let M=ve(p),L=_e(u),q=tI(Q,M,L,this.samples);this.instruments=eI(c,q);let x=ve(f),V=_e(d),X=II(h,x,V,this.instruments);this.presets=sI(B,X),this.presets.sort((g,v)=>g.program-v.program+(g.bank-v.bank)),m(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets,
|
|
11
11
|
%c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,C.info,C.recognized,C.info,C.recognized,C.info,C.recognized,C.info,C.recognized,C.info),sA()}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 sA(),new SyntaxError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw sA(),new SyntaxError(`Invalid soundFont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}getPreset(A,t){let I=this.presets.find(s=>s.bank===A&&s.program===t);return I||(I=this.presets.find(s=>s.program===t&&s.bank!==128),A===128&&(I=this.presets.find(s=>s.bank===128&&s.program===t),I||(I=this.presets.find(s=>s.bank===128))),I&&J(`%cPreset ${A}.${t} not found. Replaced with %c${I.presetName} (${I.bank}.${I.program})`,C.warn,C.recognized)),I||(J(`Preset ${t} not found. Defaulting to`,this.presets[0].presetName),I=this.presets[0]),I}getPresetByName(A){let t=this.presets.find(I=>I.presetName===A);return t||(J("Preset not found. Defaulting to:",this.presets[0].presetName),t=this.presets[0]),t}static mergeSoundfonts(...A){let t=A.shift(),I=t.presets;for(;A.length;)A.shift().presets.forEach(n=>{I.find(i=>i.bank===n.bank&&i.program===n.program)===void 0&&I.push(n)});return new e({presets:I,info:t.soundFontInfo})}};PA.prototype.write=hI;function lI(e){let A=e.messageData,t=e.channelNumber,I={};switch(t>=0&&(I=this.workletProcessorChannels[t]),e.messageType){case O.noteOn:this.noteOn(t,A[0],A[1],A[2]);break;case O.noteOff:this.noteOff(t,A);break;case O.pitchWheel:this.pitchWheel(t,A[0],A[1]);break;case O.ccChange:this.controllerChange(t,A[0],A[1],A[2]);break;case O.customcCcChange:I.customControllers[A[0]]=A[1];break;case O.killNote:this.killNote(t,A);break;case O.programChange:this.programChange(t,A[0],A[1]);break;case O.channelPressure:this.channelPressure(t,A);break;case O.polyPressure:this.polyPressure(t,A[0],A[1]);break;case O.ccReset:t===KA?this.resetAllControllers():this.resetControllers(t);break;case O.systemExclusive:this.systemExclusive(A);break;case O.setChannelVibrato:if(t===KA)for(let i=0;i<this.workletProcessorChannels.length;i++)A.rate===-1?this.disableAndLockVibrato(i):this.setVibrato(i,A.depth,A.rate,A.delay);A.rate===-1?this.disableAndLockVibrato(t):this.setVibrato(t,A.depth,A.rate,A.delay);break;case O.reloadSoundFont:this.reloadSoundFont(A);break;case O.stopAll:t===KA?this.stopAllChannels(A===1):this.stopAll(t,A===1);break;case O.killNotes:this.voiceKilling(A);break;case O.muteChannel:this.muteChannel(t,A);break;case O.addNewChannel:this.createWorkletChannel(!0);break;case O.debugMessage:this.debugMessage();break;case O.setMasterParameter:let s=A[0],n=A[1];switch(s){case se.masterPan:this.setMasterPan(n);break;case se.mainVolume:this.setMasterGain(n);break;case se.voicesCap:this.voiceCap=n;break}break;case O.setDrums:this.setDrums(t,A);break;case O.transpose:t===KA?this.transposeAllChannels(A[0],A[1]):this.transposeChannel(t,A[0],A[1]);break;case O.highPerformanceMode:this.highPerformanceMode=A;break;case O.lockController:A[0]===KA?I.lockPreset=A[1]:I.lockedControllers[A[0]]=A[1];break;case O.sequencerSpecific:this.sequencer.processMessage(A.messageType,A.messageData);break;case O.requestSynthesizerSnapshot:this.sendSynthesizerSnapshot();break;case O.setLogLevel:Kt(A[0],A[1],A[2],A[3]);break;default:J("Unrecognized event:",A);break}}function cI(e,A=0){switch(e[0]){default:J(`%cUnrecognized SysEx: %c${CA(e)}`,C.warn,C.unrecognized);break;case 126:e[2]===9&&(e[3]===1?(m("%cGM system on",C.info),this.system="gm"):e[3]===3?(m("%cGM2 system on",C.info),this.system="gm2"):(m("%cGM system off, defaulting to GS",C.info),this.system="gs"));break;case 127:if(e[2]===4){let I;switch(e[3]){case 1:let s=e[5]<<7|e[4];this.setMIDIVolume(s/16384),m(`%cMaster Volume. Volume: %c${s}`,C.info,C.value);break;case 2:let i=((e[5]<<7|e[4])-8192)/8192;this.setMasterPan(i),m(`%cMaster Pan. Pan: %c${i}`,C.info,C.value);break;case 3:let B=(e[5]<<7|e[6])-8192;I=Math.floor(B/81.92),this.setMasterTuning(I),m(`%cMaster Fine Tuning. Cents: %c${I}`,C.info,C.value);break;case 4:I=(e[5]-64)*100,this.setMasterTuning(I),m(`%cMaster Coarse Tuning. Cents: %c${I}`,C.info,C.value);break;default:J(`%cUnrecognized MIDI Device Control Real-time message: %c${CA(e)}`,C.warn,C.unrecognized)}}else J(`%cUnrecognized MIDI Real-time message: %c${CA(e)}`,C.warn,C.unrecognized);break;case 65:if(e[2]===66&&e[3]===18){let I=e[7];if(e[6]===127){I===0?(m("%cGS system on",C.info),this.system="gs"):I===127&&(m("%cGS system off, switching to GM2",C.info),this.system="gm2");return}else if(e[4]===64){if((e[5]&16)>0){let s=[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 n=I>0&&e[5]>>4;this.setDrums(s,n),m(`%cChannel %c${s}%c ${n?"is now a drum channel":"now isn't a drum channel"}%c via: %c${CA(e)}`,C.info,C.value,C.recognized,C.info,C.value);return;case 22:let i=I-64;this.transposeChannel(s,i),m(`%cChannel %c${s}%c pitch shift. Semitones %c${i}%c, with %c${CA(e)}`,C.info,C.recognized,C.info,C.value,C.info,C.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 B=I-64;m(`%cChannel %c${s}%c tuning. Cents %c${B}%c, with %c${CA(e)}`,C.info,C.recognized,C.info,C.value,C.info,C.value),this.setChannelTuning(s,B)}}else if(e[5]===0&&e[6]===6){m(`%cRoland GS Master Pan set to: %c${I}%c with: %c${CA(e)}`,C.info,C.value,C.info,C.value),this.setMasterPan((I-64)/64);return}else if(e[5]===0&&e[6]===5){let s=I-64;m(`%cRoland GS Master Key-Shift set to: %c${s}%c with: %c${CA(e)}`,C.info,C.value,C.info,C.value),this.setMasterTuning(s*100);return}else if(e[5]===0&&e[6]===4){m(`%cRoland GS Master Volume set to: %c${I}%c with: %c${CA(e)}`,C.info,C.value,C.info,C.value),this.setMIDIVolume(I/127);return}}J(`%cUnrecognized Roland %cGS %cSysEx: %c${CA(e)}`,C.warn,C.recognized,C.warn,C.unrecognized);return}else if(e[2]===22&&e[3]===18&&e[4]===16){this.setMIDIVolume(e[7]/100),m(`%cRoland Master Volume control set to: %c${e[7]}%c via: %c${CA(e)}`,C.info,C.value,C.info,C.value);return}else{J(`%cUnrecognized Roland SysEx: %c${CA(e)}`,C.warn,C.unrecognized);return}case 67:e[2]===76&&e[5]===126&&e[6]===0?(m("%cXG system on",C.info),this.system="xg"):this.system==="xg"&&J(`%cUnrecognized Yamaha SysEx: %c${CA(e)}`,C.warn,C.unrecognized);break}}var ot=new Float32Array(30001);for(let e=0;e<ot.length;e++){let A=-15e3+e;ot[e]=Math.pow(2,A/1200)}function BA(e){return ot[e- -15e3]}var ye=-2e4,dI=16500,gt=new Float32Array(dI-ye+1);for(let e=0;e<gt.length;e++){let A=ye+e;gt[e]=440*Math.pow(2,(A-6900)/1200)}function ge(e){return e<ye||e>dI?440*Math.pow(2,(e-6900)/1200):gt[~~e-ye]}var rt=-1660,$s=1600,nt=new Float32Array(($s-rt)*100+1);for(let e=0;e<nt.length;e++){let A=(rt*100+e)/100;nt[e]=Math.pow(10,-A/20)}function DA(e){return nt[Math.floor((e-rt)*100)]}var fI={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},mI=.001,uI=100,Ao=.005;function OA(e){let A=e.volumeEnvelope;if(A.attackDuration=BA(e.modulatedGenerators[a.attackVolEnv]),A.decayDuration=BA(e.modulatedGenerators[a.decayVolEnv]+(60-e.midiNote)*e.modulatedGenerators[a.keyNumToVolEnvDecay]),A.releaseDuration=BA(e.modulatedGenerators[a.releaseVolEnv]),A.attenuation=e.modulatedGenerators[a.initialAttenuation]/10,A.sustainDb=e.volumeEnvelope.attenuation+e.modulatedGenerators[a.sustainVolEnv]/10,A.delayEnd=BA(e.modulatedGenerators[a.delayVolEnv])+e.startTime,A.attackEnd=A.attackDuration+A.delayEnd,A.holdEnd=BA(e.modulatedGenerators[a.holdVolEnv]+(60-e.midiNote)*e.modulatedGenerators[a.keyNumToVolEnvHold])+A.attackEnd,A.decayEnd=A.decayDuration+A.holdEnd,e.isInRelease)switch(A.state){case 0:A.releaseStartDb=0;break;case 1:let I=(1-(A.attackEnd-e.releaseStartTime)/A.attackDuration)*DA(A.attenuation);A.releaseStartDb=20*Math.log10(I)*-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 pI(e,A,t,I,s,n){let i=I/10,B=e.volumeEnvelope;if(e.isInRelease){let f=n*10,c=B.releaseStartDb+i,Q=t-e.releaseStartTime,u=uI-c,p=B.currentReleaseGain;for(let Y=0;Y<A.length;Y++){let M=Q/B.releaseDuration*u+c;p=DA(M+i),B.currentReleaseGain+=(p-B.currentReleaseGain)*f,A[Y]*=B.currentReleaseGain,Q+=s}B.currentReleaseGain<=Ao&&(e.finished=!0);return}let h=t,d=0;switch(B.state){case 0:for(;h<B.delayEnd;)if(B.currentAttenuationDb=uI,A[d]=0,h+=s,++d>=A.length)return;B.state++;case 1:for(;h<B.attackEnd;){let c=(1-(B.attackEnd-h)/B.attackDuration)*DA(B.attenuation+i);if(A[d]*=c,B.currentAttenuationDb=B.attenuation,h+=s,++d>=A.length)return}B.state++;case 2:for(;h<B.holdEnd;){let f=B.attenuation+i;if(B.currentAttenuationDb+=(f-B.currentAttenuationDb)*n,A[d]*=DA(B.currentAttenuationDb),h+=s,++d>=A.length)return}B.state++;case 3:for(;h<B.decayEnd;){let f=(1-(B.decayEnd-h)/B.decayDuration)*(B.sustainDb-B.attenuation)+B.attenuation+i;if(B.currentAttenuationDb+=(f-B.currentAttenuationDb)*n,A[d]*=DA(B.currentAttenuationDb),h+=s,++d>=A.length)return}B.state++;case 4:for(;;){let f=B.sustainDb+i;if(B.currentAttenuationDb+=(f-B.currentAttenuationDb)*n,A[d]*=DA(B.currentAttenuationDb),++d>=A.length)return}}}var yI={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 SI(e,A,t){if(!(t>13499)){(e.filter.cutoffCents!==t||e.filter.reasonanceCb!==e.modulatedGenerators[a.initialFilterQ])&&(e.filter.cutoffCents=t,e.filter.reasonanceCb=e.modulatedGenerators[a.initialFilterQ],eo(e));for(let I=0;I<A.length;I++){let s=A[I],n=e.filter.a0*s+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=s,e.filter.y2=e.filter.y1,e.filter.y1=n,A[I]=n}}}function eo(e){e.filter.cutoffHz=ge(e.filter.cutoffCents),e.filter.cutoffHz>.45*sampleRate&&(e.filter.cutoffHz=.45*sampleRate);let A=e.filter.reasonanceCb/10-3.01;e.filter.reasonanceGain=DA(-1*A);let t=1/Math.sqrt(e.filter.reasonanceGain),I=2*Math.PI*e.filter.cutoffHz/sampleRate,s=Math.cos(I),n=Math.sin(I)/(2*e.filter.reasonanceGain),i=(1-s)*t,B=i/2,h=B,d=1+n,f=-2*s,c=1-n;e.filter.a0=B/d,e.filter.a1=i/d,e.filter.a2=h/d,e.filter.a3=f/d,e.filter.a4=c/d}var Se=[];function DI(){Se=[]}function to(e,A,t,I){Se[t]=!1,I({channel:e,sampleID:t,sampleData:A.getAudioData()}),Se[t]=!0}function ne(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]=ne(e[t]):e[t]instanceof Int16Array?A[t]=new Int16Array(e[t]):A[t]=e[t]);return A}function wI(e,A,t,I,s,n,i,B,h=!1){let d,f=B[A][t];return f!==void 0?(d=f.map(ne),d.forEach(c=>{c.startTime=s})):(d=I.getSamplesAndGenerators(A,t).reduce((c,Q)=>{if(Se[Q.sampleID]!==!0&&to(e,Q.sample,Q.sampleID,i),Q.sample.sampleData===void 0)return J(`Discarding invalid sample: ${Q.sample.sampleName}`),c;let u=new Int16Array(60);for(let V=0;V<60;V++)u[V]=Xt(V,Q.presetGenerators,Q.instrumentGenerators);u[a.initialAttenuation]=Math.floor(u[a.initialAttenuation]*.4);let p=Q.sample.samplePitch;u[a.overridingRootKey]>-1&&(p=u[a.overridingRootKey]);let Y=A;u[a.keyNum]>-1&&(Y=u[a.keyNum]);let M=Q.sample.sampleLoopStartIndex/2+(u[a.startloopAddrsOffset]+u[a.startloopAddrsCoarseOffset]*32768),L=Q.sample.sampleLoopEndIndex/2+(u[a.endloopAddrsOffset]+u[a.endloopAddrsCoarseOffset]*32768),q=u[a.sampleModes];L-M<1&&(q=0);let x={sampleID:Q.sampleID,playbackStep:Q.sample.sampleRate/n*Math.pow(2,Q.sample.samplePitchCorrection/1200),cursor:u[a.startAddrsOffset]+u[a.startAddrsCoarseOffset]*32768,rootKey:p,loopStart:M,loopEnd:L,end:Math.floor(Q.sample.sampleData.length)-1+(u[a.endAddrOffset]+u[a.endAddrsCoarseOffset]*32768),loopingMode:q};return u[a.velocity]>-1&&(t=u[a.velocity]),h&&Vt([{Sample:Q.sample.sampleName,Generators:u,Modulators:Q.modulators.map(V=>V.debugString()),Velocity:t,TargetKey:Y,MidiNote:A,WorkletSample:x}]),c.push({filter:ne(yI),generators:u,modulators:Q.modulators,modulatedGenerators:new Int16Array(60),sample:x,velocity:t,midiNote:A,pressure:0,channelNumber:e,startTime:s,targetKey:Y,currentTuningCalculated:1,currentTuningCents:0,releaseStartTime:1/0,finished:!1,isInRelease:!1,currentModEnvValue:0,releaseStartModEnv:1,currentPan:.5,volumeEnvelope:ne(fI)}),c},[]),B[A][t]=d.map(ne)),d}var $=16384,WA=new Float32Array($),_A=new Float32Array($);WA[0]=0;WA[$-1]=1;_A[0]=0;_A[$-1]=1;for(let e=1;e<$-1;e++){let A=-.4166666666666667*Math.log(e/($-1))/Math.LN10;_A[e]=1-A,WA[$-1-e]=A}function ZA(e,A,t,I){switch(e&&(t=1-t),A){case cA.linear:return I?t*2-1:t;case cA.switch:return t=t>.5?1:0,I?t*2-1:t;case cA.concave:return I?(t=t*2-1,t<0?1-WA[~~(t*-$)]-1:WA[~~t*$]):WA[~~(t*$)];case cA.convex:return I?(t=t*2-1,t<0?1-_A[~~(t*-$)]-1:_A[~~(t*$)]):_A[~~(t*$)]}}function FI(e,A,t){if(A.transformAmount===0)return 0;let I;if(A.sourceUsesCC)I=e[A.sourceIndex];else{let h=A.sourceIndex+eA;switch(A.sourceIndex){case H.noController:I=16383;break;case H.noteOnKeyNum:I=t.midiNote<<7;break;case H.noteOnVelocity:I=t.velocity<<7;break;case H.polyPressure:I=t.pressure<<7;break;default:I=e[h];break}}let s=QA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][I],n;if(A.secSrcUsesCC)n=e[A.secSrcIndex];else{let h=A.secSrcIndex+eA;switch(A.secSrcIndex){case H.noController:n=16383;break;case H.noteOnKeyNum:n=t.midiNote<<7;break;case H.noteOnVelocity:n=t.velocity<<7;break;case H.polyPressure:n=t.pressure<<7;break;default:n=e[h]}}let i=QA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][n],B=s*i*A.transformAmount;return A.transformType===2?Math.abs(B):B}function xA(e,A,t=-1,I=0){let{modulators:s,generators:n,modulatedGenerators:i}=e;if(t===-1){i.set(n),s.forEach(d=>{i[d.modulatorDestination]+=FI(A,d,e)}),OA(e);return}let B=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),h=new Set;s.forEach(d=>{if(d.sourceUsesCC===t&&d.sourceIndex===I||d.secSrcUsesCC===t&&d.secSrcIndex===I){let f=d.modulatorDestination;h.has(f)||(i[f]=n[f],s.forEach(c=>{c.modulatorDestination===f&&(i[f]+=FI(A,c,e))}),h.add(f))}}),[...h].some(d=>B.has(d))&&OA(e)}var QA=[];for(let e=0;e<4;e++){QA[e]=[[new Float32Array($),new Float32Array($)],[new Float32Array($),new Float32Array($)]];for(let A=0;A<$;A++)QA[e][0][0][A]=ZA(0,e,A/$,0),isNaN(QA[e][0][0][A])&&(QA[e][0][0][A]=1),QA[e][1][0][A]=ZA(0,e,A/$,1),isNaN(QA[e][1][0][A])&&(QA[e][1][0][A]=1),QA[e][0][1][A]=ZA(1,e,A/$,0),isNaN(QA[e][0][1][A])&&(QA[e][0][1][A]=1),QA[e][1][1][A]=ZA(1,e,A/$,1),isNaN(QA[e][1][1][A])&&(QA[e][1][1][A]=1)}function RI(e,A,t,I=!1,s=!0,n=currentTime){if(t===0){this.noteOff(e,A);return}if(this.highPerformanceMode&&this.totalVoicesAmount>200&&t<40||this.highPerformanceMode&&t<10||this.workletProcessorChannels[e].isMuted||(A+=this.workletProcessorChannels[e].channelTransposeKeyShift,A>127||A<0))return;let i=wI(e,A,t,this.workletProcessorChannels[e].preset,n,sampleRate,h=>this.sampleDump(h.channel,h.sampleID,h.sampleData),this.workletProcessorChannels[e].cachedVoices,I),B=this.workletProcessorChannels[e].voices;i.forEach(h=>{let d=h.generators[a.exclusiveClass];d!==0&&B.forEach(f=>{f.generators[a.exclusiveClass]===d&&(this.releaseVoice(f),f.modulatedGenerators[a.releaseVolEnv]=-7e3,f.modulatedGenerators[a.releaseModEnv]=-7e3,OA(f))}),xA(h,this.workletProcessorChannels[e].midiControllers),h.currentPan=(Math.max(-500,Math.min(500,h.modulatedGenerators[a.pan]))+500)/1e3}),this.totalVoicesAmount+=i.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(i.length),B.push(...i),s&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A-this.workletProcessorChannels[e].channelTransposeKeyShift,channel:e,velocity:t}))}function GI(e,A){let t=this.workletProcessorChannels[e],I=()=>{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 aA.Idle:break;case aA.NRPFine:switch(t.NRPCoarse){default:if(A===64)return;J(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16).toUpperCase()} 0x${t.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,C.warn,C.recognized,C.warn,C.unrecognized,C.warn,C.value);break;case 1:switch(t.NRPFine){default:if(A===64)return;J(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16)} 0x${t.NRPFine.toString(16)})%c data value: %c${A}`,C.warn,C.recognized,C.warn,C.unrecognized,C.warn,C.value);break;case 8:if(t.lockVibrato||A===64)return;I(),t.channelVibrato.rate=A/64*8,m(`%cVibrato rate for channel %c${e}%c is now set to %c${t.channelVibrato.rate}%cHz.`,C.info,C.recognized,C.info,C.value,C.info);break;case 9:if(t.lockVibrato||A===64)return;I(),t.channelVibrato.depth=A/2,m(`%cVibrato depth for %c${e}%c is now set to %c${t.channelVibrato.depth}%c cents range of detune.`,C.info,C.recognized,C.info,C.value,C.info);break;case 10:if(t.lockVibrato||A===64)return;I(),t.channelVibrato.delay=A/64/3,m(`%cVibrato delay for %c${e}%c is now set to %c${t.channelVibrato.delay}%c seconds.`,C.info,C.recognized,C.info,C.value,C.info);break;case 32:let n=A;this.controllerChange(e,y.brightness,A),m(`%cFilter cutoff for %c${e}%c is now set to %c${n}`,C.info,C.recognized,C.info,C.value)}break;case 29:if(!t.drumChannel)return;let s=A;this.controllerChange(e,y.effects1Depth,s),m(`%cGS Drum reverb for %c${e}%c: %c${s}`,C.info,C.recognized,C.info,C.value);break}break;case aA.RPCoarse:case aA.RPFine:switch(t.RPValue){default:J(`%cUnrecognized RPN for %c${e}%c: %c(0x${t.RPValue.toString(16)})%c data value: %c${A}`,C.warn,C.recognized,C.warn,C.unrecognized,C.warn,C.value);break;case 0:t.midiControllers[eA+H.pitchWheelRange]=A<<7,m(`%cChannel ${e} bend range. Semitones: %c${A}`,C.info,C.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 kI(e,A){let t=this.workletProcessorChannels[e];switch(t.dataEntryState){default:break;case aA.RPCoarse:case aA.RPFine:switch(t.RPValue){default:break;case 0:if(A===0)break;t.midiControllers[eA+H.pitchWheelRange]|=A;let I=(t.midiControllers[eA+H.pitchWheelRange]>>7)+A/127;m(`%cChannel ${e} bend range. Semitones: %c${I}`,C.info,C.value);break;case 1:let n=t.customControllers[AA.channelTuning]<<7|A;this.setChannelTuning(e,n*.01220703125);break;case 5:let B=t.customControllers[AA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(e,B);break;case 16383:this.resetParameters(e);break}}}function NI(e,A){if(A>127||A<0){J("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(I=>{I.midiNote!==A||I.isInRelease===!0||(this.workletProcessorChannels[e].holdPedal?this.workletProcessorChannels[e].sustainedVoices.push(I):this.releaseVoice(I))}),this.callEvent("noteoff",{midiNote:A-this.workletProcessorChannels[e].channelTransposeKeyShift,channel:e})}function MI(e,A){this.workletProcessorChannels[e].voices.forEach(t=>{t.midiNote===A&&(t.modulatedGenerators[a.releaseVolEnv]=-12e3,this.releaseVoice(t))})}function UI(e,A=!1){let t=this.workletProcessorChannels[e].voices;A?(t.length=0,this.workletProcessorChannels[e].sustainedVoices.length=0,this.sendChannelProperties()):(t.forEach(I=>{I.isInRelease||this.releaseVoice(I)}),this.workletProcessorChannels[e].sustainedVoices.forEach(I=>{this.releaseVoice(I)}))}function xI(e=!1){m("%cStop all received!",C.info);for(let A=0;A<this.workletProcessorChannels.length;A++)this.stopAll(A,e);this.callEvent("stopall",void 0)}function bI(e,A,t,I=!1){let s=this.workletProcessorChannels[e];if(A>=y.lsbForControl1ModulationWheel&&A<=y.lsbForControl13EffectControl2&&A!==y.lsbForControl6DataEntry){let n=A-32;if(s.lockedControllers[n])return;s.midiControllers[n]=s.midiControllers[n]&16256|t&127,s.voices.forEach(i=>xA(i,s.midiControllers,1,n))}switch(A){case y.allNotesOff:this.stopAll(e);break;case y.allSoundOff:this.stopAll(e,!0);break;case y.bankSelect:let n=t;if(!I){switch(this.system){case"gm":m(`%cIgnoring the Bank Select (${t}), as the synth is in GM mode.`,C.info);return;case"xg":n===120||n===126||n===127?this.setDrums(e,!0):this.setDrums(e,!1);break;case"gm2":n===120&&(s.drumChannel=!0,this.callEvent("drumchange",{channel:e,isDrumChannel:!0}))}s.drumChannel&&(n=128),n===128&&!s.drumChannel&&(n=s.midiControllers[y.bankSelect])}s.midiControllers[y.bankSelect]=n;break;case y.lsbForControl0BankSelect:this.system==="xg"?s.drumChannel||t!==127&&(s.midiControllers[y.bankSelect]=t):this.system==="gm2"&&(s.midiControllers[y.bankSelect]=t);break;case y.RPNLsb:s.RPValue=s.RPValue<<7|t,s.dataEntryState=aA.RPFine;break;case y.RPNMsb:s.RPValue=t,s.dataEntryState=aA.RPCoarse;break;case y.NRPNMsb:s.NRPCoarse=t,s.dataEntryState=aA.NRPCoarse;break;case y.NRPNLsb:s.NRPFine=t,s.dataEntryState=aA.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?s.holdPedal=!0:(s.holdPedal=!1,s.sustainedVoices.forEach(i=>{this.releaseVoice(i)}),s.sustainedVoices=[]);break;default:if(s.lockedControllers[A])return;s.midiControllers[A]=t<<7,s.voices.forEach(i=>xA(i,s.midiControllers,1,A)),this.callEvent("controllerchange",{channel:e,controllerNumber:A,controllerValue:t});break}}function LI(e){this.midiVolume=e,this.setMasterPan(this.pan)}function HI(e){this.masterGain=e*it,this.setMasterPan(this.pan)}function YI(e){this.pan=e,e=e/2+.5,this.panLeft=(1-e)*this.currentGain,this.panRight=e*this.currentGain}function JI(e,A){A&&this.stopAll(e,!0),this.workletProcessorChannels[e].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:e,isMuted:A})}function TI(e,A){this.enableEventSystem&&this.post({messageType:lA.eventCall,messageData:{eventName:e,eventData:A}})}function qI(e){this.enableEventSystem&&this.port.postMessage(e)}function KI(){if(!this.enableEventSystem)return;let e=this.workletProcessorChannels.map(A=>{let t=(A.midiControllers[eA+H.pitchWheelRange]>>7)+(A.midiControllers[eA+H.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[eA+H.pitchWheel],pitchBendRangeSemitones:t,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:lA.channelProperties,messageData:e})}function VI(e,A=!1){this.transposition=0;for(let t=0;t<this.workletProcessorChannels.length;t++)this.transposeChannel(t,e,A);this.transposition=e}function PI(e,A,t=!1){let I=this.workletProcessorChannels[e];I.drumChannel||(A+=this.transposition);let s=Math.trunc(A),n=I.channelTransposeKeyShift+I.customControllers[AA.channelTransposeFine]/100;I.drumChannel&&!t||A===n||(s!==I.channelTransposeKeyShift&&this.stopAll(e,!1),I.channelTransposeKeyShift=s,I.customControllers[AA.channelTransposeFine]=(A-s)*100)}function OI(e,A,t=!0){let I=this.workletProcessorChannels[e];A=Math.round(A),I.customControllers[AA.channelTuning]=A,t&&m(`%cChannel ${e} fine tuning. Cents: %c${A}`,C.info,C.value)}function ZI(e,A){let t=this.workletProcessorChannels[e];A=Math.round(A),t.customControllers[AA.channelTuningSemitones]=A,m(`%cChannel ${e} coarse tuning. Semitones: %c${A}`,C.info,C.value)}function vI(e){e=Math.round(e);for(let A=0;A<this.workletProcessorChannels.length;A++)this.workletProcessorChannels[A].customControllers[AA.masterTuning]=e}function XI(e,A){let t=this.workletProcessorChannels[e];A=Math.round(A),m(`%cChannel ${e} modulation depth. Cents: %c${A}`,C.info,C.value),t.customControllers[AA.modulationMultiplier]=A/50}function WI(e,A,t){if(this.workletProcessorChannels[e].lockedControllers[eA+H.pitchWheel])return;let I=t|A<<7;this.callEvent("pitchwheel",{channel:e,MSB:A,LSB:t}),this.workletProcessorChannels[e].midiControllers[eA+H.pitchWheel]=I,this.workletProcessorChannels[e].voices.forEach(s=>xA(s,this.workletProcessorChannels[e].midiControllers,0,H.pitchWheel)),this.sendChannelProperties()}function _I(e,A){let t=this.workletProcessorChannels[e];t.midiControllers[eA+H.channelPressure]=A<<7,this.workletProcessorChannels[e].voices.forEach(I=>xA(I,t.midiControllers,0,H.channelPressure)),this.callEvent("channelpressure",{channel:e,pressure:A})}function zI(e,A,t){this.workletProcessorChannels[e].voices.forEach(I=>{I.midiNote===A&&(I.pressure=t,xA(I,this.workletProcessorChannels[e].midiControllers,0,H.polyPressure))}),this.callEvent("polypressure",{channel:e,midiNote:A,pressure:t})}function jI(e,A,t=!1){let I=this.workletProcessorChannels[e];if(I.lockPreset)return;let s=I.drumChannel?128:I.midiControllers[y.bankSelect],n=this.soundfont.getPreset(s,A);this.setPreset(e,n),this.callEvent("programchange",{channel:e,program:n.program,bank:n.bank,userCalled:t})}function $I(e,A){if(!this.workletProcessorChannels[e].lockPreset){this.workletProcessorChannels[e].preset=A,this.workletProcessorChannels[e].cachedVoices=[];for(let t=0;t<128;t++)this.workletProcessorChannels[e].cachedVoices.push([])}}function As(e,A){let t=this.workletProcessorChannels[e];t.lockPreset||(A?(t.channelTransposeKeyShift=0,t.drumChannel=!0,this.setPreset(e,this.soundfont.getPreset(128,t.preset.program))):(t.drumChannel=!1,this.setPreset(e,this.soundfont.getPreset(t.midiControllers[y.bankSelect],t.preset.program))),this.callEvent("drumchange",{channel:e,isDrumChannel:t.drumChannel}),this.sendChannelProperties())}function es(){this.callEvent("presetlistchange",this.soundfont.presets.map(e=>({presetName:e.presetName,bank:e.bank,program:e.program})))}function ts(e){this.stopAllChannels(!0),delete this.soundfont;try{this.soundfont=new PA(e)}catch(A){this.post({messageType:lA.soundfontError,messageData:A});return}DI(),delete this.workletDumpedSamplesList,this.workletDumpedSamplesList=[],this.defaultPreset=this.soundfont.getPreset(0,0),this.drumPreset=this.soundfont.getPreset(128,0);for(let A=0;A<this.workletProcessorChannels.length;A++){let t=this.workletProcessorChannels[A];t.cachedVoices=[];for(let I=0;I<128;I++)t.cachedVoices.push([]);t.lockPreset=!1,this.programChange(A,t.preset.program)}this.post({messageType:lA.ready,messageData:void 0}),this.sendPresetList(),m("%cSpessaSynth is ready!",C.recognized)}function Is(e,A,t){this.workletDumpedSamplesList[A]=t,this.workletProcessorChannels[e].voices.forEach(I=>{if(I.sample.sampleID===A){if(I.sample.end=t.length-1+I.generators[a.endAddrOffset]+I.generators[a.endAddrsCoarseOffset]*32768,I.sample.cursor=I.sample.playbackStep*sampleRate*(currentTime-I.startTime),I.sample.loopingMode===0){if(I.sample.cursor>=I.sample.end){I.finished=!0;return}}else I.sample.cursor>I.sample.loopEnd&&(I.sample.cursor=I.sample.cursor%(I.sample.loopEnd-I.sample.loopStart)+I.sample.loopStart-1);I.startTime=currentTime}})}function ss(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 os(e,A,t,I){this.workletProcessorChannels[e].lockVibrato||(this.workletProcessorChannels[e].channelVibrato.rate=t,this.workletProcessorChannels[e].channelVibrato.delay=I,this.workletProcessorChannels[e].channelVibrato.depth=A)}var wA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9},fA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function JA(e,A){let t=0;for(let I=8*(A-1);I>=0;I-=8)t|=e[e.currentIndex++]<<I;return t>>>0}function gs(e,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=Ie(e.messageStatusByte),I=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=I,t.status){case S.noteOn:let s=e.messageData[1];if(s>0)this.synth.noteOn(t.channel,e.messageData[0],s),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:s,startTime:this.currentTime});else{this.synth.noteOff(t.channel,e.messageData[0]);let B=this.playingNotes.findIndex(h=>h.midiNote===e.messageData[0]&&h.channel===t.channel);B!==-1&&this.playingNotes.splice(B,1)}break;case S.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let n=this.playingNotes.findIndex(B=>B.midiNote===e.messageData[0]&&B.channel===t.channel);n!==-1&&this.playingNotes.splice(n,1);break;case S.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case S.controllerChange:let i=e.messageData[1];this.midiData.embeddedSoundFont&&e.messageData[0]===y.bankSelect&&i--,this.synth.controllerChange(t.channel,e.messageData[0],i);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,I);break;case S.setTempo:this.oneTickToSeconds=60/(Io(e)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),J("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(fA.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:J(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(S).find(B=>S[B]===t.status)}`,C.warn,C.unrecognized,C.warn,C.value);break}}function ns(){for(let e=0;e<16;e++)this.synth.createWorkletChannel(!0),e===kA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function Io(e){return e.messageData.currentIndex=0,6e7/JA(e.messageData,3)}function rs(){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 I=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(I.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 is(){let e=0,A=1/0;return this.tracks.forEach((t,I)=>{this.eventIndex[I]>=t.length||t[this.eventIndex[I]].ticks<A&&(e=I,A=t[this.eventIndex[I]].ticks)}),e}var MA=new Int16Array(127);MA[y.mainVolume]=100;MA[y.expressionController]=127;MA[y.pan]=64;MA[y.releaseTime]=64;MA[y.brightness]=64;MA[y.effects1Depth]=40;function Cs(e,A=void 0){if(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIMessages){this.sendMIDIMessage([S.reset]);for(let i=0;i<fe;i++)this.sendMIDIMessage([S.controllerChange|i,y.resetAllControllers,0])}this._resetTimers();let t=this.synth.workletProcessorChannels.length,I=Array(t).fill(8192),s=Array(t).fill(-1),n=[];for(let i=0;i<t;i++)n.push(Array.from(MA));for(;;){let i=this._findFirstEventIndex(),B=this.tracks[i][this.eventIndex[i]];if(A!==void 0){if(B.ticks>=A)break}else if(this.playedTime>=e)break;let h=Ie(B.messageStatusByte),d=h.channel+(this.midiPortChannelOffsets[this.midiPorts[i]]||0);switch(h.status){case S.noteOn:case S.noteOff:case S.keySignature:break;case S.pitchBend:I[d]=B.messageData[1]<<7|B.messageData[0];break;case S.programChange:s[d]=B.messageData[0];break;case S.controllerChange:let c=B.messageData[0];if(c===y.dataDecrement||c===y.dataIncrement||c===y.dataEntryMsb||c===y.dataDecrement||c===y.lsbForControl6DataEntry||c===y.RPNLsb||c===y.RPNMsb||c===y.NRPNLsb||c===y.NRPNMsb||c===y.bankSelect||c===y.lsbForControl0BankSelect||c===y.resetAllControllers)if(this.sendMIDIMessages)this.sendMIDIMessage([S.controllerChange|d%16,c,B.messageData[1]]);else{let Q=B.messageData[1];this.midiData.embeddedSoundFont!==void 0&&c===y.bankSelect&&Q--,this.synth.controllerChange(d,c,Q)}else n[d]===void 0&&(n[d]=Array.from(MA)),n[d][c]=B.messageData[1];break;default:this._processEvent(B,i);break}this.eventIndex[i]++,i=this._findFirstEventIndex();let f=this.tracks[i][this.eventIndex[i]];if(f===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(f.ticks-B.ticks)}if(this.sendMIDIMessages)for(let i=0;i<t;i++)this.sendMIDIMessage([S.pitchBend|i%16,I[i]&127,I[i]>>7]),n[i].forEach((B,h)=>{B!==MA[h]&&this.sendMIDIMessage([S.controllerChange|i%16,h,B])}),s[i]!==0&&this.sendMIDIMessage([S.programChange|i%16,s[i]]);else for(let i=0;i<t;i++)I[i]!==void 0&&this.synth.pitchWheel(i,I[i]>>7,I[i]&127),n[i]!==void 0&&n[i].forEach((B,h)=>{B!==MA[h]&&this.synth.controllerChange(i,h,B)}),s[i]!==-1&&this.synth.programChange(i,s[i]);return!0}function Es(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 I=t.startTime-A;this.synth.noteOn(t.channel,t.midiNote,t.velocity,!1,!0,currentTime+I)})}this.setProcessHandler()}}function De(e,A,t){if(A<=0)return 0;let I=e.find(n=>n.ticks<A),s=A-I.ticks;return De(e,A-s,t)+s*60/(I.tempo*t)}function as(e){this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(fA.timeChange,currentTime-De(this.midiData.tempoChanges,e,this.midiData.timeDivision));let A=this._playTo(0,e);this._recalculateStartTime(this.playedTime),A&&this.play()}function Bs(e){this.absoluteStartTime=currentTime-e/this._playbackRate}var we=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}},RC={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}};function Fe(e){let A=0;for(;e;){let t=e[e.currentIndex++];if(A=A<<7|t&127,t>>7!==1)break}return A}var Re=class{constructor(A,t=""){HA("%cParsing MIDI File...",C.info);let I=new U(A),s;this.embeddedSoundFont=void 0,this.copyright="";let n=z(I,4);if(I.currentIndex-=4,n==="RIFF"){I.currentIndex+=8;let Q=z(I,4,void 0,!1);if(Q!=="RMID")throw sA(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${Q}"`);let u=oA(I);if(u.header!=="data")throw sA(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${Q}"`);for(s=u.chunkData;I.currentIndex<=I.length;){let p=I.currentIndex,Y=oA(I,!0);Y.header==="RIFF"&&z(Y.chunkData,4)==="sfbk"&&(m("%cFound embedded soundfont!",C.recognized),this.embeddedSoundFont=I.slice(p,p+Y.size).buffer)}}else s=I;let i=this.readMIDIChunk(s);if(i.type!=="MThd")throw sA(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${i.type}"`);if(i.size!==6)throw sA(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${i.size}`);this.format=JA(i.data,2),this.tracksAmount=JA(i.data,2),this.timeDivision=JA(i.data,2),this.keyRange={min:127,max:0},this.lyrics=[],this.tempoChanges=[{ticks:0,tempo:120}];let B=null,h=null;this.lastVoiceEventTick=0,this.midiPorts=[];let d=0;this.midiPortChannelOffsets=[],this.usedChannelsOnTrack=[],this.tracks=[];for(let Q=0;Q<this.tracksAmount;Q++){let u=[],p=this.readMIDIChunk(s),Y=new Set;if(this.midiPorts.push(-1),p.type!=="MTrk")throw sA(),new SyntaxError(`Invalid track header! Expected "MTrk" got "${p.type}"`);let M,L=0;for(this.format===2&&Q>0&&(L+=this.tracks[Q-1][this.tracks[Q-1].length-1].ticks);p.data.currentIndex<p.size;){L+=Fe(p.data);let q=p.data[p.data.currentIndex],x;if(M!==void 0&&q<128)x=M;else{if(!M&&q<128)throw sA(),new SyntaxError(`Unexpected byte with no running byte. (${q})`);x=p.data[p.data.currentIndex++]}let V=Ht(x),X;switch(V){case-1:X=0;break;case-2:x=p.data[p.data.currentIndex++],X=Fe(p.data);break;case-3:X=Fe(p.data);break;default:if(L>this.lastVoiceEventTick&&(this.lastVoiceEventTick=L),X=Yt[x>>4],(x&240)===S.noteOn){Y.add(V);let IA=p.data[p.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,IA),this.keyRange.max=Math.max(this.keyRange.max,IA)}M=x;break}let g=new U(X),v=p.data.slice(p.data.currentIndex,p.data.currentIndex+X);p.data.currentIndex+=X,g.set(v,0);let j=new de(L,x,g);switch(u.push(j),V){case-2:switch(x){case S.setTempo:this.tempoChanges.push({ticks:L,tempo:6e7/JA(v,3)});break;case S.marker:switch(z(g,g.length).trim().toLowerCase()){default:break;case"start":case"loopstart":B=L;break;case"loopend":h=L}g.currentIndex=0;break;case S.midiPort:let rA=g[0];this.midiPorts[Q]=rA,this.midiPortChannelOffsets[rA]===void 0&&(this.midiPortChannelOffsets[rA]=d,d+=16);break;case S.copyright:this.copyright+=z(g,g.length)+`
|
|
12
12
|
`;break;case S.lyric:this.lyrics.push(g)}break;case-3:if(CA(g.slice(0,7)).trim()==="41 10 45 12 10 00 00"){let IA=g.slice(7,v.length-3),rA=z(IA,IA.length)+`
|
|
13
|
-
`;this.copyright+=rA,m(`%cDecoded Roland SC message! %c${rA}`,C.recognized,C.value)}break;default:if((x&240)===S.controllerChange)switch(g[0]){case 2:case 116:B=L;break;case 4:case 117:h===null?h=L:h=0;break}}}this.tracks.push(u),this.usedChannelsOnTrack.push(Y),m(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,C.info,C.value,C.info,C.value)}let f=[];for(let Q of this.tracks){let u=Q.find(p=>(p.messageStatusByte&240)===S.noteOn);u&&f.push(u.ticks)}this.firstNoteOn=Math.min(...f),m(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}`,C.info,C.recognized),sA(),B!==null&&h===null?(B=this.firstNoteOn,h=this.lastVoiceEventTick):(B===null&&(B=this.firstNoteOn),(h===null||h===0)&&(h=this.lastVoiceEventTick));let c=0;for(let Q of this.midiPorts)if(Q!==-1){c=Q;break}if(this.midiPorts=this.midiPorts.map(Q=>Q===-1?c:Q),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.loop={start:B,end:h},this.midiName="",this.rawMidiName=new Uint8Array(0),this.tracks.length>1){if(this.tracks[0].find(Q=>Q.messageStatusByte>=S.noteOn&&Q.messageStatusByte<S.systemExclusive)===void 0){let Q=this.tracks[0].find(u=>u.messageStatusByte===S.trackName);Q&&(this.rawMidiName=Q.messageData,this.midiName=z(Q.messageData,Q.messageData.length,void 0,!1))}}else{let Q=this.tracks[0].find(u=>u.messageStatusByte===S.trackName);Q&&(this.rawMidiName=Q.messageData,this.midiName=z(Q.messageData,Q.messageData.length,void 0,!1))}if(this.fileName=t,this.midiName=this.midiName.trim(),this.midiName.length===0){this.midiName=Lt(t),this.rawMidiName=new Uint8Array(this.midiName.length);for(let Q=0;Q<this.midiName.length;Q++)this.rawMidiName[Q]=this.midiName.charCodeAt(Q)}this.tempoChanges.reverse(),this.duration=this._ticksToSeconds(this.lastVoiceEventTick)}readMIDIChunk(A){let t={};t.type=z(A,4),t.size=JA(A,4),t.data=new U(t.size);let I=A.slice(A.currentIndex,A.currentIndex+t.size);return t.data.set(I,0),A.currentIndex+=t.size,t}_ticksToSeconds(A){if(A<=0)return 0;let t=this.tempoChanges.find(s=>s.ticks<A),I=A-t.ticks;return this._ticksToSeconds(A-I)+I*60/(t.tempo*this.timeDivision)}};function Qs(e,A){HA("%cSearching for all used programs and keys...",C.info);let t=16+Math.max.apply(void 0,e.midiPortChannelOffsets),I=[];for(let c=0;c<t;c++){let Q=c%16===kA?128:0;I.push({program:0,bank:Q,drums:c%16===kA,string:`${Q}:0`})}function s(c){let Q=A.getPreset(c.bank,c.program);Q.bank!==c.bank&&e.embeddedSoundFont&&(Q=A.getPreset(c.bank-1,c.program)),c.bank=Q.bank,c.program=Q.program,c.string=c.bank+":"+c.program,n[c.string]||(m(`%cDetected a new preset: %c${c.string}`,C.info,C.recognized),n[c.string]=new Set)}let n={},i=Array(e.tracks.length).fill(0),B=e.tracks.length;function h(){let c=0,Q=1/0;return e.tracks.forEach((u,p)=>{i[p]>=u.length||u[i[p]].ticks<Q&&(c=p,Q=u[i[p]].ticks)}),c}let d=e.midiPorts.slice(),f="gs";for(;B>0;){let c=h(),Q=e.tracks[c];if(i[c]>=Q.length){B--;continue}let u=Q[i[c]];if(i[c]++,u.messageStatusByte===S.midiPort){d[c]=u.messageData[0];continue}let p=u.messageStatusByte&240;if(p!==S.noteOn&&p!==S.controllerChange&&p!==S.programChange&&p!==S.systemExclusive)continue;let Y=(u.messageStatusByte&15)+e.midiPortChannelOffsets[d[c]]||0,M=I[Y];switch(p){case S.programChange:M.program=u.messageData[0],s(M);break;case S.controllerChange:if(u.messageData[0]!==y.bankSelect||f==="gs"&&M.drums)continue;let L=u.messageData[1];if(f==="xg"){let V=L===120||L===126||L===127;V!==M.drums?(M.drums=V,M.bank=M.drums?128:L,s(M)):M.bank=M.drums?128:L;continue}I[Y].bank=L;break;case S.noteOn:if(u.messageData[1]===0)continue;n[M.string].add(`${u.messageData[0]}-${u.messageData[1]}`);break;case S.systemExclusive:if(u.messageData[0]!==65||u.messageData[2]!==66||u.messageData[3]!==18||u.messageData[4]!==64||!(u.messageData[5]&16)||u.messageData[6]!==21){u.messageData[0]===67&&u.messageData[2]===76&&u.messageData[5]===126&&u.messageData[6]===0&&(f="xg");continue}let q=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+e.midiPortChannelOffsets[d[c]],x=!!(u.messageData[7]>0&&u.messageData[5]>>4);M=I[q],M.drums=x,M.bank=x?128:0,s(M);break}}for(let c of Object.keys(n))n[c].size===0&&(m(`%cDetected change but no keys for %c${c}`,C.info,C.value),delete n[c]);return sA(),n}function hs(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 ls(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)this.synth.reloadSoundFont(this.midiData.embeddedSoundFont),this.synth.soundfont.samples.forEach(A=>A.getAudioData());else{HA("%cPreloading samples...",C.info);let A=Qs(this.midiData,this.synth.soundfont);for(let[t,I]of Object.entries(A)){let s=parseInt(t.split(":")[0]),n=parseInt(t.split(":")[1]),i=this.synth.soundfont.getPreset(s,n);m(`%cPreloading used samples on %c${i.presetName}%c...`,C.info,C.recognized,C.info);for(let B of I){let h=B.split("-");i.preloadSpecific(parseInt(h[0]),parseInt(h[1]))}}sA()}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=De(this.midiData.tempoChanges,this.midiData.firstNoteOn,this.midiData.timeDivision),m(`%cTotal song time: ${Oe(Math.ceil(this.duration)).time}`,C.recognized),this.post(fA.songChange,[new we(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(J(`%cVery short song: (${Oe(Math.round(this.duration)).time}). Disabling loop!`,C.warn),this.loop=!1),this.play(!0)}function cs(e){if(this.songs=e.reduce((A,t)=>{if(t.duration)return A.push(t),A;try{A.push(new Re(t.binary,t.altName||""))}catch(I){return this.post(fA.midiError,I.message),A}return A},[]),this.songs.length<1){console.log("no valid songs!");return}this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex])}function ds(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function us(){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 fs(e,A){switch(e){default:break;case wA.loadNewSongList:this.loadNewSongList(A);break;case wA.pause:this.pause();break;case wA.play:this.play(A);break;case wA.stop:this.stop();break;case wA.setTime:this.currentTime=A;break;case wA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case wA.setPlaybackRate:this.playbackRate=A;break;case wA.setLoop:this.loop=A;break;case wA.changeSong:A?this.nextSong():this.previousSong();break;case wA.getMIDI:this.post(fA.getMIDI,this.midiData)}}function ms(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:lA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function ps(e){this.post(fA.midiEvent,e)}var tA=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={}}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.firstNoteTime||A>this.duration){this.setTimeTicks(this.midiData.firstNoteOn-1);return}this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(fA.timeChange,currentTime-A);let t=this._playTo(A);this._recalculateStartTime(A),t&&this.play()}pause(A=!1){if(this.paused){J("Already paused");return}this.pausedTime=this.currentTime,this.stop(),this.post(fA.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<fe;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}};tA.prototype.post=ms;tA.prototype.sendMIDIMessage=ps;tA.prototype.assignMIDIPort=hs;tA.prototype.processMessage=fs;tA.prototype._processEvent=gs;tA.prototype._addNewMidiPort=ns;tA.prototype._processTick=rs;tA.prototype._findFirstEventIndex=is;tA.prototype.loadNewSequence=ls;tA.prototype.loadNewSongList=cs;tA.prototype.nextSong=ds;tA.prototype.previousSong=us;tA.prototype.play=Es;tA.prototype._playTo=Cs;tA.prototype.setTimeTicks=as;tA.prototype._recalculateStartTime=Bs;function ys(){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,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 Ss(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 I=this.workletProcessorChannels[t];this.muteChannel(t,A.isMuted),this.setDrums(t,A.drumChannel),I.midiControllers=A.midiControllers,I.lockedControllers=A.lockedControllers,I.customControllers=A.customControllers,I.channelVibrato=A.channelVibrato,I.lockVibrato=A.lockVibrato,I.channelTransposeKeyShift=A.channelTransposeKeyShift,I.lockPreset=!1,I.midiControllers[y.bankSelect]=A.bank,this.programChange(t,A.program),I.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",C.info)}function Ge(e,A,t){if(t<e)return 0;let I=(t-e)/(1/A)-.25;return Math.abs(I-~~(I+.5))*4-1}var Ct=1,Et=new Float32Array(1e3);for(let e=0;e<Et.length;e++)Et[e]=ZA(0,cA.convex,e/1e3,0);function Ds(e,A){let t=BA(e.modulatedGenerators[a.attackModEnv]),I=BA(e.modulatedGenerators[a.decayModEnv]+(60-e.midiNote)*e.modulatedGenerators[a.keyNumToModEnvDecay]),s=BA(e.modulatedGenerators[a.holdModEnv]+(60-e.midiNote)*e.modulatedGenerators[a.keyNumToModEnvHold]);if(e.isInRelease&&e.releaseStartTime<A){let c=BA(e.modulatedGenerators[a.releaseModEnv]);return e.modulatedGenerators[a.releaseModEnv]<-7199?e.releaseStartModEnv:(1-(A-e.releaseStartTime)/c)*e.releaseStartModEnv}let n=1-e.modulatedGenerators[a.sustainModEnv]/1e3,i=BA(e.modulatedGenerators[a.delayModEnv])+e.startTime,B=t+i,h=s+B,d=I+h,f;return A<i?f=0:A<B?f=Et[~~((1-(B-A)/t)*1e3)]:A<h?f=Ct:A<d?f=(1-(d-A)/I)*(n-Ct)+Ct:f=n,e.currentModEnvValue=f,f}function ws(e,A,t){let I=e.sample.cursor,s=e.sample.loopingMode===1||e.sample.loopingMode===3&&!e.isInRelease,n=e.sample.loopEnd-e.sample.loopStart;if(s)for(let i=0;i<t.length;i++){for(;I>=e.sample.loopEnd;)I-=n;let B=~~I,h=B+1;for(;h>=e.sample.loopEnd;)h-=n;let d=I-B,f=A[h],c=A[B];t[i]=c+(f-c)*d,I+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=A.length&&(e.sample.end=A.length-1);for(let i=0;i<t.length;i++){let B=~~I,h=B+1;if(h>=e.sample.end){e.finished=!0;return}let d=I-B,f=A[h],c=A[B];t[i]=c+(f-c)*d,I+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=I}function Fs(e,A,t,I,s,n,i,B,h){if(!isNaN(t[0])){if(i>0){let d=n[0],f=n[1];i=Math.min(i,1e3);let c=i/500,Q=e*c,u=A*c;for(let p=0;p<t.length;p++)d[p]+=Q*t[p],f[p]+=u*t[p]}if(h>0){let d=B[0],f=B[1];h=Math.min(h,1e3);let c=h/500,Q=e*c,u=A*c;for(let p=0;p<t.length;p++)d[p]+=Q*t[p],f[p]+=u*t[p]}if(e>0)for(let d=0;d<t.length;d++)I[d]+=e*t[d];if(A>0)for(let d=0;d<t.length;d++)s[d]+=A*t[d]}}var Rs=Math.PI/2,Gs=.01;function ks(e,A,t,I,s,n){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.releaseStartModEnv=A.currentModEnvValue,A.isInRelease=!0,OA(A),A.volumeEnvelope.currentReleaseGain=DA(A.volumeEnvelope.currentAttenuationDb)),A.modulatedGenerators[a.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let i=A.modulatedGenerators[a.fineTune]+e.customControllers[AA.channelTuning]+e.customControllers[AA.channelTransposeFine]+e.customControllers[AA.masterTuning],B=A.modulatedGenerators[a.coarseTune]+e.customControllers[AA.channelTuningSemitones];i+=(A.targetKey-A.sample.rootKey)*A.modulatedGenerators[a.scaleTuning];let h=A.modulatedGenerators[a.vibLfoToPitch];if(h!==0){let j=A.startTime+BA(A.modulatedGenerators[a.delayVibLFO]),IA=ge(A.modulatedGenerators[a.freqVibLFO]),rA=Ge(j,IA,currentTime);rA&&(i+=rA*(h*e.customControllers[AA.modulationMultiplier]))}let d=A.modulatedGenerators[a.initialFilterFc],f=A.modulatedGenerators[a.modLfoToPitch],c=A.modulatedGenerators[a.modLfoToVolume],Q=A.modulatedGenerators[a.modLfoToFilterFc],u=0;if(f+Q+c!==0){let j=A.startTime+BA(A.modulatedGenerators[a.delayModLFO]),IA=ge(A.modulatedGenerators[a.freqModLFO]),rA=Ge(j,IA,currentTime);i+=rA*(f*e.customControllers[AA.modulationMultiplier]),u=rA*c,d+=rA*Q}if(e.channelVibrato.depth>0){let j=Ge(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);j&&(i+=j*e.channelVibrato.depth)}let p=A.modulatedGenerators[a.modEnvToPitch],Y=A.modulatedGenerators[a.modEnvToFilterFc],M=Ds(A,currentTime);d+=M*Y,i+=M*p;let L=~~(i+B*100);L!==A.currentTuningCents&&(A.currentTuningCents=L,A.currentTuningCalculated=Math.pow(2,L/1200));let q=(Math.max(-500,Math.min(500,A.modulatedGenerators[a.pan]))+500)/1e3,x=new Float32Array(t.length);ws(A,this.workletDumpedSamplesList[A.sample.sampleID],x),SI(A,x,d),pI(A,x,currentTime,u,this.sampleTime,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(q-A.currentPan)*this.panSmoothingFactor;let V=Math.cos(Rs*A.currentPan)*this.panLeft,X=Math.sin(Rs*A.currentPan)*this.panRight,g=this.oneOutputMode?0:A.modulatedGenerators[a.reverbEffectsSend],v=this.oneOutputMode?0:A.modulatedGenerators[a.chorusEffectsSend];Fs(V,X,x,t,I,s,g,n,v)}function so(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 Ns(e){let A=[];for(let I of this.workletProcessorChannels)for(let s of I.voices)if(!s.finished){let n=so(I,s);A.push({channel:I,voice:s,priority:n})}A.sort((I,s)=>I.priority-s.priority);let t=A.slice(0,e);for(let{channel:I,voice:s}of t){let n=I.voices.indexOf(s);n>-1&&I.voices.splice(n,1)}}function Ms(e){e.releaseStartTime=currentTime,e.releaseStartTime-e.startTime<at&&(e.releaseStartTime=e.startTime+at)}function Us(){m("%cResetting all controllers!",C.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.midiControllers[y.bankSelect]=0,e%16===kA?(this.setPreset(e,this.drumPreset),A.drumChannel=!0,this.callEvent("drumchange",{channel:e,isDrumChannel:!0})):(A.drumChannel=!1,this.setPreset(e,this.defaultPreset),this.callEvent("drumchange",{channel:e,isDrumChannel:!1}))),this.callEvent("programchange",{channel:e,program:A.preset.program,bank:A.preset.bank,userCalled:!1});let t=I=>{this.workletProcessorChannels[e].lockedControllers[I]&&this.callEvent("controllerchange",{channel:e,controllerNumber:I,controllerValue:this.workletProcessorChannels[e].midiControllers[I]>>7})};if(t(y.mainVolume),t(y.pan),t(y.expressionController),t(y.modulationWheel),t(y.effects3Depth),t(y.effects1Depth),this.workletProcessorChannels[e].lockedControllers[eA+H.pitchWheel]){let I=this.workletProcessorChannels[e].midiControllers[eA+H.pitchWheel],s=I>>7,n=I&127;this.callEvent("pitchwheel",{channel:e,MSB:s,LSB:n})}}this.setMIDIVolume(1),this.system=me}function xs(e){let A=this.workletProcessorChannels[e],I=A.lockedControllers.reduce((n,i,B)=>(i&&n.push(B),n),[]).map(n=>({ccNum:n,ccVal:A.midiControllers[n]}));A.midiControllers.set(NA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,I.forEach(n=>{A.midiControllers[n.ccNum]=n.ccVal});let s=A.customControllers[AA.channelTransposeFine];A.customControllers.set(je),A.customControllers[AA.channelTransposeFine]=s,this.resetParameters(e)}function bs(e){let A=this.workletProcessorChannels[e];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=aA.Idle}var at=.07,it=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.processTickCallback=void 0,this.sequencer=new tA(this),this.transposition=0,this.masterGain=it,this.midiVolume=1,this.voiceCap=Zt,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.panRight=.5*this.currentGain;try{this.soundfont=new PA(A.processorOptions.soundfont)}catch(t){throw this.post({messageType:lA.soundfontError,messageData:t}),t}this.sendPresetList(),this.defaultPreset=this.soundfont.getPreset(0,0),this.drumPreset=this.soundfont.getPreset(128,0),this.workletDumpedSamplesList=[],this.workletProcessorChannels=[];for(let t=0;t<A.processorOptions.midiChannels;t++)this.createWorkletChannel(!1);this.workletProcessorChannels[kA].preset=this.drumPreset,this.workletProcessorChannels[kA].drumChannel=!0,this.sampleTime=1/sampleRate,this.volumeEnvelopeSmoothingFactor=mI*(sampleRate/44100),this.panSmoothingFactor=Gs*(sampleRate/44100),this.system=me,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()),m("%cRendering enabled! Starting render.",C.info),A.processorOptions.startRenderingData.parsedMIDI&&(this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]),this.sequencer.loop=!1)),YA.isInitialized.then(()=>{this.post({messageType:lA.ready,messageData:void 0}),m("%cSpessaSynth is ready!",C.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){this.processTickCallback&&this.processTickCallback();let I=0;return this.workletProcessorChannels.forEach((s,n)=>{if(s.voices.length<1||s.isMuted)return;let i,B,h,d,f;if(this.oneOutputMode){let Q=t[0];i=n%16*2,B=Q[i],h=Q[i+1]}else i=n%this._outputsAmount+2,B=t[i][0],h=t[i][1],d=t[0],f=t[1];let c=s.voices;s.voices=[],c.forEach(Q=>{this.renderVoice(s,Q,B,h,d,f),Q.finished||s.voices.push(Q)}),I+=c.length}),I!==this.totalVoicesAmount&&(this.totalVoicesAmount=I,this.sendChannelProperties()),!0}};R.prototype.renderVoice=ks;R.prototype.releaseVoice=Ms;R.prototype.voiceKilling=Ns;R.prototype.handleMessage=lI;R.prototype.post=qI;R.prototype.sendChannelProperties=KI;R.prototype.callEvent=TI;R.prototype.systemExclusive=cI;R.prototype.noteOn=RI;R.prototype.noteOff=NI;R.prototype.polyPressure=zI;R.prototype.killNote=MI;R.prototype.stopAll=UI;R.prototype.stopAllChannels=xI;R.prototype.muteChannel=JI;R.prototype.setVibrato=os;R.prototype.disableAndLockVibrato=ss;R.prototype.dataEntryCoarse=GI;R.prototype.dataEntryFine=kI;R.prototype.createWorkletChannel=_t;R.prototype.controllerChange=bI;R.prototype.channelPressure=_I;R.prototype.resetAllControllers=Us;R.prototype.resetControllers=xs;R.prototype.resetParameters=bs;R.prototype.setMasterGain=HI;R.prototype.setMasterPan=YI;R.prototype.setMIDIVolume=LI;R.prototype.transposeAllChannels=VI;R.prototype.transposeChannel=PI;R.prototype.setChannelTuning=OI;R.prototype.setChannelTuningSemitones=ZI;R.prototype.setMasterTuning=vI;R.prototype.setModulationDepth=XI;R.prototype.pitchWheel=WI;R.prototype.programChange=jI;R.prototype.setPreset=$I;R.prototype.setDrums=As;R.prototype.reloadSoundFont=ts;R.prototype.sampleDump=Is;R.prototype.sendPresetList=es;R.prototype.sendSynthesizerSnapshot=ys;R.prototype.applySynthesizerSnapshot=Ss;registerProcessor(Ot,R);m("%cProcessor succesfully registered!",C.recognized);
|
|
13
|
+
`;this.copyright+=rA,m(`%cDecoded Roland SC message! %c${rA}`,C.recognized,C.value)}break;default:if((x&240)===S.controllerChange)switch(g[0]){case 2:case 116:B=L;break;case 4:case 117:h===null?h=L:h=0;break}}}this.tracks.push(u),this.usedChannelsOnTrack.push(Y),m(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,C.info,C.value,C.info,C.value)}let f=[];for(let Q of this.tracks){let u=Q.find(p=>(p.messageStatusByte&240)===S.noteOn);u&&f.push(u.ticks)}this.firstNoteOn=Math.min(...f),m(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}`,C.info,C.recognized),sA(),B!==null&&h===null?(B=this.firstNoteOn,h=this.lastVoiceEventTick):(B===null&&(B=this.firstNoteOn),(h===null||h===0)&&(h=this.lastVoiceEventTick));let c=0;for(let Q of this.midiPorts)if(Q!==-1){c=Q;break}if(this.midiPorts=this.midiPorts.map(Q=>Q===-1?c:Q),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.loop={start:B,end:h},this.midiName="",this.rawMidiName=new Uint8Array(0),this.tracks.length>1){if(this.tracks[0].find(Q=>Q.messageStatusByte>=S.noteOn&&Q.messageStatusByte<S.systemExclusive)===void 0){let Q=this.tracks[0].find(u=>u.messageStatusByte===S.trackName);Q&&(this.rawMidiName=Q.messageData,this.midiName=z(Q.messageData,Q.messageData.length,void 0,!1))}}else{let Q=this.tracks[0].find(u=>u.messageStatusByte===S.trackName);Q&&(this.rawMidiName=Q.messageData,this.midiName=z(Q.messageData,Q.messageData.length,void 0,!1))}if(this.fileName=t,this.midiName=this.midiName.trim(),this.midiName.length===0){this.midiName=Lt(t),this.rawMidiName=new Uint8Array(this.midiName.length);for(let Q=0;Q<this.midiName.length;Q++)this.rawMidiName[Q]=this.midiName.charCodeAt(Q)}this.tempoChanges.reverse(),this.duration=this._ticksToSeconds(this.lastVoiceEventTick)}readMIDIChunk(A){let t={};t.type=z(A,4),t.size=JA(A,4),t.data=new U(t.size);let I=A.slice(A.currentIndex,A.currentIndex+t.size);return t.data.set(I,0),A.currentIndex+=t.size,t}_ticksToSeconds(A){if(A<=0)return 0;let t=this.tempoChanges.find(s=>s.ticks<A),I=A-t.ticks;return this._ticksToSeconds(A-I)+I*60/(t.tempo*this.timeDivision)}};function Qs(e,A){HA("%cSearching for all used programs and keys...",C.info);let t=16+Math.max.apply(void 0,e.midiPortChannelOffsets),I=[];for(let c=0;c<t;c++){let Q=c%16===kA?128:0;I.push({program:0,bank:Q,drums:c%16===kA,string:`${Q}:0`})}function s(c){let Q=A.getPreset(c.bank,c.program);Q.bank!==c.bank&&e.embeddedSoundFont&&(Q=A.getPreset(c.bank-1,c.program)),c.bank=Q.bank,c.program=Q.program,c.string=c.bank+":"+c.program,n[c.string]||(m(`%cDetected a new preset: %c${c.string}`,C.info,C.recognized),n[c.string]=new Set)}let n={},i=Array(e.tracks.length).fill(0),B=e.tracks.length;function h(){let c=0,Q=1/0;return e.tracks.forEach((u,p)=>{i[p]>=u.length||u[i[p]].ticks<Q&&(c=p,Q=u[i[p]].ticks)}),c}let d=e.midiPorts.slice(),f="gs";for(;B>0;){let c=h(),Q=e.tracks[c];if(i[c]>=Q.length){B--;continue}let u=Q[i[c]];if(i[c]++,u.messageStatusByte===S.midiPort){d[c]=u.messageData[0];continue}let p=u.messageStatusByte&240;if(p!==S.noteOn&&p!==S.controllerChange&&p!==S.programChange&&p!==S.systemExclusive)continue;let Y=(u.messageStatusByte&15)+e.midiPortChannelOffsets[d[c]]||0,M=I[Y];switch(p){case S.programChange:M.program=u.messageData[0],s(M);break;case S.controllerChange:if(u.messageData[0]!==y.bankSelect||f==="gs"&&M.drums)continue;let L=u.messageData[1];if(f==="xg"){let V=L===120||L===126||L===127;V!==M.drums?(M.drums=V,M.bank=M.drums?128:L,s(M)):M.bank=M.drums?128:L;continue}I[Y].bank=L;break;case S.noteOn:if(u.messageData[1]===0)continue;s(M),n[M.string].add(`${u.messageData[0]}-${u.messageData[1]}`);break;case S.systemExclusive:if(u.messageData[0]!==65||u.messageData[2]!==66||u.messageData[3]!==18||u.messageData[4]!==64||!(u.messageData[5]&16)||u.messageData[6]!==21){u.messageData[0]===67&&u.messageData[2]===76&&u.messageData[5]===126&&u.messageData[6]===0&&(f="xg");continue}let q=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][u.messageData[5]&15]+e.midiPortChannelOffsets[d[c]],x=!!(u.messageData[7]>0&&u.messageData[5]>>4);M=I[q],M.drums=x,M.bank=x?128:0,s(M);break}}for(let c of Object.keys(n))n[c].size===0&&(m(`%cDetected change but no keys for %c${c}`,C.info,C.value),delete n[c]);return sA(),n}function hs(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 ls(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)this.synth.reloadSoundFont(this.midiData.embeddedSoundFont),this.synth.soundfont.samples.forEach(A=>A.getAudioData());else{HA("%cPreloading samples...",C.info);let A=Qs(this.midiData,this.synth.soundfont);for(let[t,I]of Object.entries(A)){let s=parseInt(t.split(":")[0]),n=parseInt(t.split(":")[1]),i=this.synth.soundfont.getPreset(s,n);m(`%cPreloading used samples on %c${i.presetName}%c...`,C.info,C.recognized,C.info);for(let B of I){let h=B.split("-");i.preloadSpecific(parseInt(h[0]),parseInt(h[1]))}}sA()}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=De(this.midiData.tempoChanges,this.midiData.firstNoteOn,this.midiData.timeDivision),m(`%cTotal song time: ${Oe(Math.ceil(this.duration)).time}`,C.recognized),this.post(fA.songChange,[new we(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(J(`%cVery short song: (${Oe(Math.round(this.duration)).time}). Disabling loop!`,C.warn),this.loop=!1),this.play(!0)}function cs(e){if(this.songs=e.reduce((A,t)=>{if(t.duration)return A.push(t),A;try{A.push(new Re(t.binary,t.altName||""))}catch(I){return this.post(fA.midiError,I.message),A}return A},[]),this.songs.length<1){console.log("no valid songs!");return}this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex])}function ds(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function us(){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 fs(e,A){switch(e){default:break;case wA.loadNewSongList:this.loadNewSongList(A);break;case wA.pause:this.pause();break;case wA.play:this.play(A);break;case wA.stop:this.stop();break;case wA.setTime:this.currentTime=A;break;case wA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case wA.setPlaybackRate:this.playbackRate=A;break;case wA.setLoop:this.loop=A;break;case wA.changeSong:A?this.nextSong():this.previousSong();break;case wA.getMIDI:this.post(fA.getMIDI,this.midiData)}}function ms(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:lA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function ps(e){this.post(fA.midiEvent,e)}var tA=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={}}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.firstNoteTime||A>this.duration){this.setTimeTicks(this.midiData.firstNoteOn-1);return}this.stop(),this.playingNotes=[],this.pausedTime=void 0,this.post(fA.timeChange,currentTime-A);let t=this._playTo(A);this._recalculateStartTime(A),t&&this.play()}pause(A=!1){if(this.paused){J("Already paused");return}this.pausedTime=this.currentTime,this.stop(),this.post(fA.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<fe;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}};tA.prototype.post=ms;tA.prototype.sendMIDIMessage=ps;tA.prototype.assignMIDIPort=hs;tA.prototype.processMessage=fs;tA.prototype._processEvent=gs;tA.prototype._addNewMidiPort=ns;tA.prototype._processTick=rs;tA.prototype._findFirstEventIndex=is;tA.prototype.loadNewSequence=ls;tA.prototype.loadNewSongList=cs;tA.prototype.nextSong=ds;tA.prototype.previousSong=us;tA.prototype.play=Es;tA.prototype._playTo=Cs;tA.prototype.setTimeTicks=as;tA.prototype._recalculateStartTime=Bs;function ys(){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,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 Ss(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 I=this.workletProcessorChannels[t];this.muteChannel(t,A.isMuted),this.setDrums(t,A.drumChannel),I.midiControllers=A.midiControllers,I.lockedControllers=A.lockedControllers,I.customControllers=A.customControllers,I.channelVibrato=A.channelVibrato,I.lockVibrato=A.lockVibrato,I.channelTransposeKeyShift=A.channelTransposeKeyShift,I.lockPreset=!1,I.midiControllers[y.bankSelect]=A.bank,this.programChange(t,A.program),I.lockPreset=A.lockPreset}),m("%cFinished restoring controllers!",C.info)}function Ge(e,A,t){if(t<e)return 0;let I=(t-e)/(1/A)-.25;return Math.abs(I-~~(I+.5))*4-1}var Ct=1,Et=new Float32Array(1e3);for(let e=0;e<Et.length;e++)Et[e]=ZA(0,cA.convex,e/1e3,0);function Ds(e,A){let t=BA(e.modulatedGenerators[a.attackModEnv]),I=BA(e.modulatedGenerators[a.decayModEnv]+(60-e.midiNote)*e.modulatedGenerators[a.keyNumToModEnvDecay]),s=BA(e.modulatedGenerators[a.holdModEnv]+(60-e.midiNote)*e.modulatedGenerators[a.keyNumToModEnvHold]);if(e.isInRelease&&e.releaseStartTime<A){let c=BA(e.modulatedGenerators[a.releaseModEnv]);return e.modulatedGenerators[a.releaseModEnv]<-7199?e.releaseStartModEnv:(1-(A-e.releaseStartTime)/c)*e.releaseStartModEnv}let n=1-e.modulatedGenerators[a.sustainModEnv]/1e3,i=BA(e.modulatedGenerators[a.delayModEnv])+e.startTime,B=t+i,h=s+B,d=I+h,f;return A<i?f=0:A<B?f=Et[~~((1-(B-A)/t)*1e3)]:A<h?f=Ct:A<d?f=(1-(d-A)/I)*(n-Ct)+Ct:f=n,e.currentModEnvValue=f,f}function ws(e,A,t){let I=e.sample.cursor,s=e.sample.loopingMode===1||e.sample.loopingMode===3&&!e.isInRelease,n=e.sample.loopEnd-e.sample.loopStart;if(s)for(let i=0;i<t.length;i++){for(;I>=e.sample.loopEnd;)I-=n;let B=~~I,h=B+1;for(;h>=e.sample.loopEnd;)h-=n;let d=I-B,f=A[h],c=A[B];t[i]=c+(f-c)*d,I+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=A.length&&(e.sample.end=A.length-1);for(let i=0;i<t.length;i++){let B=~~I,h=B+1;if(h>=e.sample.end){e.finished=!0;return}let d=I-B,f=A[h],c=A[B];t[i]=c+(f-c)*d,I+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=I}function Fs(e,A,t,I,s,n,i,B,h){if(!isNaN(t[0])){if(i>0){let d=n[0],f=n[1];i=Math.min(i,1e3);let c=i/500,Q=e*c,u=A*c;for(let p=0;p<t.length;p++)d[p]+=Q*t[p],f[p]+=u*t[p]}if(h>0){let d=B[0],f=B[1];h=Math.min(h,1e3);let c=h/500,Q=e*c,u=A*c;for(let p=0;p<t.length;p++)d[p]+=Q*t[p],f[p]+=u*t[p]}if(e>0)for(let d=0;d<t.length;d++)I[d]+=e*t[d];if(A>0)for(let d=0;d<t.length;d++)s[d]+=A*t[d]}}var Rs=Math.PI/2,Gs=.01;function ks(e,A,t,I,s,n){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.releaseStartModEnv=A.currentModEnvValue,A.isInRelease=!0,OA(A),A.volumeEnvelope.currentReleaseGain=DA(A.volumeEnvelope.currentAttenuationDb)),A.modulatedGenerators[a.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let i=A.modulatedGenerators[a.fineTune]+e.customControllers[AA.channelTuning]+e.customControllers[AA.channelTransposeFine]+e.customControllers[AA.masterTuning],B=A.modulatedGenerators[a.coarseTune]+e.customControllers[AA.channelTuningSemitones];i+=(A.targetKey-A.sample.rootKey)*A.modulatedGenerators[a.scaleTuning];let h=A.modulatedGenerators[a.vibLfoToPitch];if(h!==0){let j=A.startTime+BA(A.modulatedGenerators[a.delayVibLFO]),IA=ge(A.modulatedGenerators[a.freqVibLFO]),rA=Ge(j,IA,currentTime);rA&&(i+=rA*(h*e.customControllers[AA.modulationMultiplier]))}let d=A.modulatedGenerators[a.initialFilterFc],f=A.modulatedGenerators[a.modLfoToPitch],c=A.modulatedGenerators[a.modLfoToVolume],Q=A.modulatedGenerators[a.modLfoToFilterFc],u=0;if(f+Q+c!==0){let j=A.startTime+BA(A.modulatedGenerators[a.delayModLFO]),IA=ge(A.modulatedGenerators[a.freqModLFO]),rA=Ge(j,IA,currentTime);i+=rA*(f*e.customControllers[AA.modulationMultiplier]),u=rA*c,d+=rA*Q}if(e.channelVibrato.depth>0){let j=Ge(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);j&&(i+=j*e.channelVibrato.depth)}let p=A.modulatedGenerators[a.modEnvToPitch],Y=A.modulatedGenerators[a.modEnvToFilterFc],M=Ds(A,currentTime);d+=M*Y,i+=M*p;let L=~~(i+B*100);L!==A.currentTuningCents&&(A.currentTuningCents=L,A.currentTuningCalculated=Math.pow(2,L/1200));let q=(Math.max(-500,Math.min(500,A.modulatedGenerators[a.pan]))+500)/1e3,x=new Float32Array(t.length);ws(A,this.workletDumpedSamplesList[A.sample.sampleID],x),SI(A,x,d),pI(A,x,currentTime,u,this.sampleTime,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(q-A.currentPan)*this.panSmoothingFactor;let V=Math.cos(Rs*A.currentPan)*this.panLeft,X=Math.sin(Rs*A.currentPan)*this.panRight,g=this.oneOutputMode?0:A.modulatedGenerators[a.reverbEffectsSend],v=this.oneOutputMode?0:A.modulatedGenerators[a.chorusEffectsSend];Fs(V,X,x,t,I,s,g,n,v)}function so(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 Ns(e){let A=[];for(let I of this.workletProcessorChannels)for(let s of I.voices)if(!s.finished){let n=so(I,s);A.push({channel:I,voice:s,priority:n})}A.sort((I,s)=>I.priority-s.priority);let t=A.slice(0,e);for(let{channel:I,voice:s}of t){let n=I.voices.indexOf(s);n>-1&&I.voices.splice(n,1)}}function Ms(e){e.releaseStartTime=currentTime,e.releaseStartTime-e.startTime<at&&(e.releaseStartTime=e.startTime+at)}function Us(){m("%cResetting all controllers!",C.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.midiControllers[y.bankSelect]=0,e%16===kA?(this.setPreset(e,this.drumPreset),A.drumChannel=!0,this.callEvent("drumchange",{channel:e,isDrumChannel:!0})):(A.drumChannel=!1,this.setPreset(e,this.defaultPreset),this.callEvent("drumchange",{channel:e,isDrumChannel:!1}))),this.callEvent("programchange",{channel:e,program:A.preset.program,bank:A.preset.bank,userCalled:!1});let t=I=>{this.workletProcessorChannels[e].lockedControllers[I]&&this.callEvent("controllerchange",{channel:e,controllerNumber:I,controllerValue:this.workletProcessorChannels[e].midiControllers[I]>>7})};if(t(y.mainVolume),t(y.pan),t(y.expressionController),t(y.modulationWheel),t(y.effects3Depth),t(y.effects1Depth),this.workletProcessorChannels[e].lockedControllers[eA+H.pitchWheel]){let I=this.workletProcessorChannels[e].midiControllers[eA+H.pitchWheel],s=I>>7,n=I&127;this.callEvent("pitchwheel",{channel:e,MSB:s,LSB:n})}}this.setMIDIVolume(1),this.system=me}function xs(e){let A=this.workletProcessorChannels[e],I=A.lockedControllers.reduce((n,i,B)=>(i&&n.push(B),n),[]).map(n=>({ccNum:n,ccVal:A.midiControllers[n]}));A.midiControllers.set(NA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,I.forEach(n=>{A.midiControllers[n.ccNum]=n.ccVal});let s=A.customControllers[AA.channelTransposeFine];A.customControllers.set(je),A.customControllers[AA.channelTransposeFine]=s,this.resetParameters(e)}function bs(e){let A=this.workletProcessorChannels[e];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=aA.Idle}var at=.07,it=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.processTickCallback=void 0,this.sequencer=new tA(this),this.transposition=0,this.masterGain=it,this.midiVolume=1,this.voiceCap=Zt,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.panRight=.5*this.currentGain;try{this.soundfont=new PA(A.processorOptions.soundfont)}catch(t){throw this.post({messageType:lA.soundfontError,messageData:t}),t}this.sendPresetList(),this.defaultPreset=this.soundfont.getPreset(0,0),this.drumPreset=this.soundfont.getPreset(128,0),this.workletDumpedSamplesList=[],this.workletProcessorChannels=[];for(let t=0;t<A.processorOptions.midiChannels;t++)this.createWorkletChannel(!1);this.workletProcessorChannels[kA].preset=this.drumPreset,this.workletProcessorChannels[kA].drumChannel=!0,this.sampleTime=1/sampleRate,this.volumeEnvelopeSmoothingFactor=mI*(sampleRate/44100),this.panSmoothingFactor=Gs*(sampleRate/44100),this.system=me,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()),m("%cRendering enabled! Starting render.",C.info),A.processorOptions.startRenderingData.parsedMIDI&&(this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]),this.sequencer.loop=!1)),YA.isInitialized.then(()=>{this.post({messageType:lA.ready,messageData:void 0}),m("%cSpessaSynth is ready!",C.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){m({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){this.processTickCallback&&this.processTickCallback();let I=0;return this.workletProcessorChannels.forEach((s,n)=>{if(s.voices.length<1||s.isMuted)return;let i,B,h,d,f;if(this.oneOutputMode){let Q=t[0];i=n%16*2,B=Q[i],h=Q[i+1]}else i=n%this._outputsAmount+2,B=t[i][0],h=t[i][1],d=t[0],f=t[1];let c=s.voices;s.voices=[],c.forEach(Q=>{this.renderVoice(s,Q,B,h,d,f),Q.finished||s.voices.push(Q)}),I+=c.length}),I!==this.totalVoicesAmount&&(this.totalVoicesAmount=I,this.sendChannelProperties()),!0}};R.prototype.renderVoice=ks;R.prototype.releaseVoice=Ms;R.prototype.voiceKilling=Ns;R.prototype.handleMessage=lI;R.prototype.post=qI;R.prototype.sendChannelProperties=KI;R.prototype.callEvent=TI;R.prototype.systemExclusive=cI;R.prototype.noteOn=RI;R.prototype.noteOff=NI;R.prototype.polyPressure=zI;R.prototype.killNote=MI;R.prototype.stopAll=UI;R.prototype.stopAllChannels=xI;R.prototype.muteChannel=JI;R.prototype.setVibrato=os;R.prototype.disableAndLockVibrato=ss;R.prototype.dataEntryCoarse=GI;R.prototype.dataEntryFine=kI;R.prototype.createWorkletChannel=_t;R.prototype.controllerChange=bI;R.prototype.channelPressure=_I;R.prototype.resetAllControllers=Us;R.prototype.resetControllers=xs;R.prototype.resetParameters=bs;R.prototype.setMasterGain=HI;R.prototype.setMasterPan=YI;R.prototype.setMIDIVolume=LI;R.prototype.transposeAllChannels=VI;R.prototype.transposeChannel=PI;R.prototype.setChannelTuning=OI;R.prototype.setChannelTuningSemitones=ZI;R.prototype.setMasterTuning=vI;R.prototype.setModulationDepth=XI;R.prototype.pitchWheel=WI;R.prototype.programChange=jI;R.prototype.setPreset=$I;R.prototype.setDrums=As;R.prototype.reloadSoundFont=ts;R.prototype.sampleDump=Is;R.prototype.sendPresetList=es;R.prototype.sendSynthesizerSnapshot=ys;R.prototype.applySynthesizerSnapshot=Ss;registerProcessor(Ot,R);m("%cProcessor succesfully registered!",C.recognized);
|