spessasynth_lib 4.0.3 → 4.0.4

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.
@@ -2,7 +2,7 @@ var Fe=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>(
2
2
  `+E.extraStackTrace()),(l=u).replace(/__Z[\w\d_]+/g,function(f){var w,U=w=f;return f===U?f:f+" ["+U+"]"})}function re(l,u){return l%u>0&&(l+=u-l%u),l}function He(l){E.buffer=n=l}function ke(){E.HEAP8=s=new Int8Array(n),E.HEAP16=i=new Int16Array(n),E.HEAP32=o=new Int32Array(n),E.HEAPU8=a=new Uint8Array(n),E.HEAPU16=I=new Uint16Array(n),E.HEAPU32=g=new Uint32Array(n),E.HEAPF32=B=new Float32Array(n),E.HEAPF64=d=new Float64Array(n)}function nt(){var l=E.usingWasm?65536:16777216,u=2147483648-l;if(o[D>>2]>u)return!1;var f=pA;for(pA=Math.max(pA,16777216);pA<o[D>>2];)pA=pA<=536870912?re(2*pA,l):Math.min(re((3*pA+2147483648)/4,l),u);var w=E.reallocBuffer(pA);return w&&w.byteLength==pA?(He(w),ke(),!0):(pA=f,!1)}h=C=m=y=F=k=D=0,Q=!1,E.reallocBuffer||(E.reallocBuffer=function(l){try{if(ArrayBuffer.transfer)u=ArrayBuffer.transfer(n,l);else{var u,f=s;u=new ArrayBuffer(l),new Int8Array(u).set(f)}}catch{return!1}return!!Ya(u)&&u});try{(v=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{v=function(u){return u.byteLength}}var Ye=E.TOTAL_STACK||5242880,pA=E.TOTAL_MEMORY||16777216;function yt(){return pA}function de(l){for(;l.length>0;){var u=l.shift();if(typeof u=="function"){u();continue}var f=u.func;typeof f=="number"?u.arg===void 0?E.dynCall_v(f):E.dynCall_vi(f,u.arg):f(u.arg===void 0?null:u.arg)}}pA<Ye&&rA("TOTAL_MEMORY should be larger than TOTAL_STACK, was "+pA+"! (TOTAL_STACK="+Ye+")"),E.buffer?n=E.buffer:(typeof WebAssembly=="object"&&typeof WebAssembly.Memory=="function"?(E.wasmMemory=new WebAssembly.Memory({initial:pA/65536}),n=E.wasmMemory.buffer):n=new ArrayBuffer(pA),E.buffer=n),ke();var st=[],an=[],Es=[],Bs=[],Cs=[],on=!1,La=!1;function Na(l){st.unshift(l)}function Yi(l){an.unshift(l)}function Pi(l){Es.unshift(l)}function Ji(l){Bs.unshift(l)}function Ua(l){Cs.unshift(l)}function qi(l,u,f){var w,U;eA("writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!"),f&&(w=s[U=u+RA(l)]),et(l,u,1/0),f&&(s[U]=w)}function Ki(l,u,f){return l>=0?l:u<=32?2*Math.abs(1<<u-1)+l:Math.pow(2,u)+l}function Oi(l,u,f){if(l<=0)return l;var w=u<=32?Math.abs(1<<u-1):Math.pow(2,u-1);return l>=w&&(u<=32||l>w)&&(l=-2*w+l),l}var Ta=Math.abs,xa=Math.ceil,hs=Math.floor,Ha=Math.min,De=0,rn=null,at=null;function Vi(l){return l}E.preloadedImages={},E.preloadedAudios={};var ls="data:application/octet-stream;base64,";function kt(l){return String.prototype.startsWith?l.startsWith(ls):l.indexOf(ls)===0}(function(){var u="main.wast",f="main.wasm",w="main.temp.asm";kt(u)||(u=z(u)),kt(f)||(f=z(f)),kt(w)||(w=z(w));var U={global:null,env:null,asm2wasm:aA,parent:E},_=null;function oA(CA){return CA}function H(){try{if(E.wasmBinary)return new Uint8Array(E.wasmBinary);if(E.readBinary)return E.readBinary(f);throw"both async and sync fetching of the wasm failed"}catch(CA){Ie(CA)}}E.asmPreload=E.asm;var DA=E.reallocBuffer,lA=function(CA){CA=re(CA,E.usingWasm?65536:16777216);var W=E.buffer.byteLength;if(E.usingWasm)try{var LA=E.wasmMemory.grow((CA-W)/65536);return LA!==-1?E.buffer=E.wasmMemory.buffer:null}catch{return null}};E.reallocBuffer=function(CA){return dA==="asmjs"?DA(CA):lA(CA)};var dA="";E.asm=function(CA,W,LA){var PA;if(!(W=PA=W).table){var JA,qA=E.wasmTableSize;qA===void 0&&(qA=1024);var we=E.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?we!==void 0?W.table=new WebAssembly.Table({initial:qA,maximum:we,element:"anyfunc"}):W.table=new WebAssembly.Table({initial:qA,element:"anyfunc"}):W.table=Array(qA),E.wasmTable=W.table}return W.memoryBase||(W.memoryBase=E.STATIC_BASE),W.tableBase||(W.tableBase=0),JA=(function(it,Pe,En){if(typeof WebAssembly!="object")return rA("no native wasm support detected"),!1;if(!(E.wasmMemory instanceof WebAssembly.Memory))return rA("no native wasm Memory in use"),!1;function Ft(jA,$A){if((_=jA.exports).memory){var rt,Bn,us;rt=_.memory,Bn=E.buffer,rt.byteLength<Bn.byteLength&&rA("the new buffer in mergeMemory is smaller than the previous one. in native wasm, we should grow memory here"),us=new Int8Array(Bn),new Int8Array(rt).set(us),He(rt),ke()}E.asm=_,E.usingWasm=!0,(function($i){if(De--,E.monitorRunDependencies&&E.monitorRunDependencies(De),De==0&&(rn!==null&&(clearInterval(rn),rn=null),at)){var Pa=at;at=null,Pa()}})("wasm-instantiate")}if(Pe.memory=E.wasmMemory,U.global={NaN:NaN,Infinity:1/0},U["global.Math"]=Math,U.env=Pe,De++,E.monitorRunDependencies&&E.monitorRunDependencies(De),E.instantiateWasm)try{return E.instantiateWasm(U,Ft)}catch(jA){return rA("Module.instantiateWasm callback failed with error: "+jA),!1}function Je(jA){Ft(jA.instance,jA.module)}function Qs(jA){(!E.wasmBinary&&(O||nA)&&typeof fetch=="function"?fetch(f,{credentials:"same-origin"}).then(function($A){if(!$A.ok)throw"failed to load wasm binary file at '"+f+"'";return $A.arrayBuffer()}).catch(function(){return H()}):new Promise(function($A,rt){$A(H())})).then(function($A){return WebAssembly.instantiate($A,U)}).then(jA).catch(function($A){rA("failed to asynchronously prepare wasm: "+$A),Ie($A)})}return E.wasmBinary||typeof WebAssembly.instantiateStreaming!="function"||kt(f)||typeof fetch!="function"?Qs(Je):WebAssembly.instantiateStreaming(fetch(f,{credentials:"same-origin"}),U).then(Je).catch(function(jA){rA("wasm streaming compile failed: "+jA),rA("falling back to ArrayBuffer instantiation"),Qs(Je)}),{}})(CA,W,LA),UA(JA,"no binaryen method succeeded."),JA},E.asm})(),C=(h=1024)+4816,an.push(),E.STATIC_BASE=h,E.STATIC_BUMP=4816;var xA=C;function Xi(l){s[xA]=s[l],s[xA+1]=s[l+1],s[xA+2]=s[l+2],s[xA+3]=s[l+3]}function Zi(l){s[xA]=s[l],s[xA+1]=s[l+1],s[xA+2]=s[l+2],s[xA+3]=s[l+3],s[xA+4]=s[l+4],s[xA+5]=s[l+5],s[xA+6]=s[l+6],s[xA+7]=s[l+7]}function zi(l,u,f){var w=f>0?f:RA(l)+1,U=Array(w),_=xe(l,U,0,U.length);return u&&(U.length=_),U}function Wi(l){for(var u=[],f=0;f<l.length;f++){var w=l[f];w>255&&(w&=255),u.push(String.fromCharCode(w))}return u.join("")}C+=16,D=P(4),F=(m=y=b(C))+Ye,k=b(F),o[D>>2]=k,Q=!0,E.wasmTableSize=4,E.wasmMaxTableSize=4,E.asmGlobalArg={},E.asmLibraryArg={abort:Ie,assert:UA,enlargeMemory:nt,getTotalMemory:yt,abortOnCannotGrowMemory:function(){Ie("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+pA+", (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(u,f,w){var U=gn();try{return E.dynCall_iii(u,f,w)}catch(_){if(In(U),typeof _!="number"&&_!=="longjmp")throw _;E.setThrew(1,0)}},___assert_fail:function(u,f,w,U){Ie("Assertion failed: "+le(u)+", at: "+[f?le(f):"unknown filename",w,U?le(U):"unknown function"])},___setErrNo:function(u){return E.___errno_location&&(o[E.___errno_location()>>2]=u),u},_abort:function(){E.abort()},_emscripten_memcpy_big:function(u,f,w){return a.set(a.subarray(f,f+w),u),u},_llvm_floor_f64:hs,DYNAMICTOP_PTR:D,tempDoublePtr:xA,ABORT:BA,STACKTOP:y,STACK_MAX:F};var ds=E.asm(E.asmGlobalArg,E.asmLibraryArg,n);E.asm=ds,E.___errno_location=function(){return E.asm.___errno_location.apply(null,arguments)};var Ya=E._emscripten_replace_memory=function(){return E.asm._emscripten_replace_memory.apply(null,arguments)};E._free=function(){return E.asm._free.apply(null,arguments)};var Dt=E._malloc=function(){return E.asm._malloc.apply(null,arguments)};E._memcpy=function(){return E.asm._memcpy.apply(null,arguments)},E._memset=function(){return E.asm._memset.apply(null,arguments)},E._sbrk=function(){return E.asm._sbrk.apply(null,arguments)},E._stb_vorbis_js_channels=function(){return E.asm._stb_vorbis_js_channels.apply(null,arguments)},E._stb_vorbis_js_close=function(){return E.asm._stb_vorbis_js_close.apply(null,arguments)},E._stb_vorbis_js_decode=function(){return E.asm._stb_vorbis_js_decode.apply(null,arguments)},E._stb_vorbis_js_open=function(){return E.asm._stb_vorbis_js_open.apply(null,arguments)},E._stb_vorbis_js_sample_rate=function(){return E.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},E.establishStackSpace=function(){return E.asm.establishStackSpace.apply(null,arguments)},E.getTempRet0=function(){return E.asm.getTempRet0.apply(null,arguments)},E.runPostSets=function(){return E.asm.runPostSets.apply(null,arguments)},E.setTempRet0=function(){return E.asm.setTempRet0.apply(null,arguments)},E.setThrew=function(){return E.asm.setThrew.apply(null,arguments)};var wt=E.stackAlloc=function(){return E.asm.stackAlloc.apply(null,arguments)},In=E.stackRestore=function(){return E.asm.stackRestore.apply(null,arguments)},gn=E.stackSave=function(){return E.asm.stackSave.apply(null,arguments)};function ot(l){this.name="ExitStatus",this.message="Program terminated with exit("+l+")",this.status=l}function cn(l){l=l||E.arguments,!(De>0)&&((function(){if(E.preRun)for(typeof E.preRun=="function"&&(E.preRun=[E.preRun]);E.preRun.length;)Na(E.preRun.shift());de(st)})(),!(De>0)&&(E.calledRun||(E.setStatus?(E.setStatus("Running..."),setTimeout(function(){setTimeout(function(){E.setStatus("")},1),u()},1)):u())));function u(){!E.calledRun&&(E.calledRun=!0,BA||(on||(on=!0,de(an)),de(Es),E.onRuntimeInitialized&&E.onRuntimeInitialized(),(function(){if(E.postRun)for(typeof E.postRun=="function"&&(E.postRun=[E.postRun]);E.postRun.length;)Ua(E.postRun.shift());de(Cs)})()))}}function _i(l,u){(!u||!E.noExitRuntime||l!==0)&&(E.noExitRuntime||(BA=!0,_A=l,y=L,de(Bs),La=!0,E.onExit&&E.onExit(l)),E.quit(l,new ot(l)))}function Ie(l){throw E.onAbort&&E.onAbort(l),l!==void 0?(tA(l),rA(l),l=JSON.stringify(l)):l="",BA=!0,_A=1,"abort("+l+"). Build with -s ASSERTIONS=1 for more info."}if(E.dynCall_iii=function(){return E.asm.dynCall_iii.apply(null,arguments)},E.asm=ds,E.ccall=Ue,E.cwrap=function(u,f,w,U){var _=(w=w||[]).every(function(oA){return oA==="number"});return f!=="string"&&_&&!U?Ce(u):function(){return Ue(u,f,w,arguments,U)}},ot.prototype=Error(),ot.prototype.constructor=ot,at=function l(){E.calledRun||cn(),E.calledRun||(at=l)},E.run=cn,E.abort=Ie,E.preInit)for(typeof E.preInit=="function"&&(E.preInit=[E.preInit]);E.preInit.length>0;)E.preInit.pop()();E.noExitRuntime=!0,cn(),E.onRuntimeInitialized=()=>{ks=!0,aa()},lt.decode=function(l){return(function(f){if(!ks)throw Error("SF3 decoder has not been initialized yet. Did you await synth.isReady?");var w={};function U(Pe){return new Int32Array(E.HEAPU8.buffer,Pe,1)[0]}function _(Pe,En){var Ft=new ArrayBuffer(En*Float32Array.BYTES_PER_ELEMENT),Je=new Float32Array(Ft);return Je.set(new Float32Array(E.HEAPU8.buffer,Pe,En)),Je}w.open=E.cwrap("stb_vorbis_js_open","number",[]),w.close=E.cwrap("stb_vorbis_js_close","void",["number"]),w.channels=E.cwrap("stb_vorbis_js_channels","number",["number"]),w.sampleRate=E.cwrap("stb_vorbis_js_sample_rate","number",["number"]),w.decode=E.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var oA,H,DA,lA,dA=w.open(),CA=(oA=f,H=f.byteLength,DA=E._malloc(H),(lA=new Uint8Array(E.HEAPU8.buffer,DA,H)).set(new Uint8Array(oA,0,H)),lA),W=E._malloc(4),LA=E._malloc(4),PA=w.decode(dA,CA.byteOffset,CA.byteLength,W,LA);if(E._free(CA.byteOffset),PA<0)throw w.close(dA),E._free(W),Error("stbvorbis decode failed: "+PA);for(var JA=w.channels(dA),qA=Array(JA),we=new Int32Array(E.HEAPU32.buffer,U(W),JA),KA=0;KA<JA;KA++)qA[KA]=_(we[KA],PA),E._free(we[KA]);var it=w.sampleRate(dA);return w.close(dA),E._free(U(W)),E._free(W),{data:qA,sampleRate:it,eof:!0,error:null}})(l)}})();var Ot=lt,ss=-15e3,Go=15e3,vn=new Float32Array(Go-ss+1);for(let e=0;e<vn.length;e++){let A=ss+e;vn[e]=Math.pow(2,A/1200)}function Qe(e){return e<=-32767?0:vn[e-ss]}var Yt=-2e4,oa=16500,Ln=new Float32Array(oa-Yt+1);for(let e=0;e<Ln.length;e++){let A=Yt+e;Ln[e]=440*Math.pow(2,(A-6900)/1200)}function Nn(e){return e<Yt||e>oa?440*Math.pow(2,(e-6900)/1200):Ln[~~e-Yt]}var as=-1660,Ro=1600,Un=new Float32Array((Ro-as)*100+1);for(let e=0;e<Un.length;e++){let A=(as*100+e)/100;Un[e]=Math.pow(10,-A/20)}function Ae(e){return Un[Math.floor((e-as)*100)]}var Mo=.01,HA=100,Qn=90,bo=15e-6,be=class ia{sampleRate;currentAttenuationDb=HA;state=0;attenuation=0;attenuationTargetGain=0;currentSampleTime=0;releaseStartDb=HA;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuationTarget=0;sustainDbRelative=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;canEndOnSilentSustain;constructor(A,t){this.sampleRate=A,this.canEndOnSilentSustain=t/10>=Qn}static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=Ae(A.volumeEnvelope.currentAttenuationDb),ia.recalculate(A)}static recalculate(A){let t=A.volumeEnvelope,n=g=>Math.max(0,Math.floor(Qe(g)*t.sampleRate));t.attenuationTarget=Math.max(0,Math.min(A.modulatedGenerators[r.initialAttenuation],1440))/10,t.attenuationTargetGain=Ae(t.attenuationTarget),t.sustainDbRelative=Math.min(HA,A.modulatedGenerators[r.sustainVolEnv]/10);let s=Math.min(HA,t.sustainDbRelative);t.attackDuration=n(A.modulatedGenerators[r.attackVolEnv]);let a=A.modulatedGenerators[r.decayVolEnv],i=(60-A.targetKey)*A.modulatedGenerators[r.keyNumToVolEnvDecay],I=s/HA;t.decayDuration=n(a+i)*I,t.releaseDuration=n(Math.max(-7200,A.modulatedGenerators[r.releaseVolEnv])),t.delayEnd=n(A.modulatedGenerators[r.delayVolEnv]),t.attackEnd=t.attackDuration+t.delayEnd;let o=(60-A.targetKey)*A.modulatedGenerators[r.keyNumToVolEnvHold];if(t.holdEnd=n(A.modulatedGenerators[r.holdVolEnv]+o)+t.attackEnd,t.decayEnd=t.decayDuration+t.holdEnd,t.state===0&&t.attackEnd===0&&(t.state=2),A.isInRelease){let g=Math.max(0,Math.min(HA,t.sustainDbRelative)),B=g/HA;switch(t.decayDuration=n(a+i)*B,t.state){case 0:t.releaseStartDb=HA;break;case 1:{let h=1-(t.attackEnd-t.releaseStartTimeSamples)/t.attackDuration;t.releaseStartDb=20*Math.log10(h)*-1;break}case 2:t.releaseStartDb=0;break;case 3:t.releaseStartDb=(1-(t.decayEnd-t.releaseStartTimeSamples)/t.decayDuration)*g;break;case 4:t.releaseStartDb=g;break}t.releaseStartDb=Math.max(0,Math.min(t.releaseStartDb,HA)),t.releaseStartDb>=Qn&&(A.finished=!0),t.currentReleaseGain=Ae(t.releaseStartDb);let d=(HA-t.releaseStartDb)/HA;t.releaseDuration*=d}}static apply(A,t,n,s){let a=A.volumeEnvelope,i=n/10,I=s;if(A.isInRelease){let g=a.currentSampleTime-a.releaseStartTimeSamples;if(g>=a.releaseDuration){for(let d=0;d<t.length;d++)t[d]=0;A.finished=!0;return}let B=HA-a.releaseStartDb;for(let d=0;d<t.length;d++){a.attenuation+=(a.attenuationTargetGain-a.attenuation)*I;let h=g/a.releaseDuration*B+a.releaseStartDb;a.currentReleaseGain=a.attenuation*Ae(h+i),t[d]*=a.currentReleaseGain,a.currentSampleTime++,g++}a.currentReleaseGain<=bo&&(A.finished=!0);return}let o=0;switch(a.state){case 0:for(;a.currentSampleTime<a.delayEnd;)if(a.currentAttenuationDb=HA,t[o]=0,a.currentSampleTime++,++o>=t.length)return;a.state++;case 1:for(;a.currentSampleTime<a.attackEnd;){a.attenuation+=(a.attenuationTargetGain-a.attenuation)*I;let g=1-(a.attackEnd-a.currentSampleTime)/a.attackDuration;if(t[o]*=g*a.attenuation*Ae(i),a.currentAttenuationDb=0,a.currentSampleTime++,++o>=t.length)return}a.state++;case 2:for(;a.currentSampleTime<a.holdEnd;)if(a.attenuation+=(a.attenuationTargetGain-a.attenuation)*I,t[o]*=a.attenuation*Ae(i),a.currentAttenuationDb=0,a.currentSampleTime++,++o>=t.length)return;a.state++;case 3:for(;a.currentSampleTime<a.decayEnd;)if(a.attenuation+=(a.attenuationTargetGain-a.attenuation)*I,a.currentAttenuationDb=(1-(a.decayEnd-a.currentSampleTime)/a.decayDuration)*a.sustainDbRelative,t[o]*=a.attenuation*Ae(a.currentAttenuationDb+i),a.currentSampleTime++,++o>=t.length)return;a.state++;case 4:for(a.canEndOnSilentSustain&&a.sustainDbRelative>=Qn&&(A.finished=!0);;)if(a.attenuation+=(a.attenuationTargetGain-a.attenuation)*I,t[o]*=a.attenuation*Ae(a.sustainDbRelative+i),a.currentAttenuationDb=a.sustainDbRelative,a.currentSampleTime++,++o>=t.length)return}}};function vo(e,A){switch(this.privateProps.masterParameters[e]=A,e){case"masterPan":{let t=A;t=t/2+.5,this.privateProps.panLeft=1-t,this.privateProps.panRight=t;break}case"masterGain":break;case"voiceCap":break;case"interpolationType":break;case"midiSystem":break;case"monophonicRetriggerMode":break;case"transposition":{let t=A;this.privateProps.masterParameters.transposition=0;for(let n of this.midiChannels)n.transposeChannel(t);this.privateProps.masterParameters.transposition=t}}this.callEvent("masterParameterChange",{parameter:e,value:A})}function Lo(e){return this.privateProps.masterParameters[e]}function No(){return{...this.privateProps.masterParameters}}function Me(e,A){return(e>>A&1)>0}function un(e){return e?1:0}var NA=16384,Pt=Object.keys(QA).length,ra=4,ce=new Float32Array(NA+1),ve=new Float32Array(NA+1);ce[0]=0;ce[ce.length-1]=1;ve[0]=0;ve[ve.length-1]=1;for(let e=1;e<NA-1;e++){let A=-.4166666666666667*Math.log(e/(ce.length-1))/Math.LN10;ve[e]=1-A,ce[ce.length-1-e]=A}function Ia(e,A,t){let n=!!(e&2);switch(!!(e&1)&&(t=1-t),A){case QA.linear:return n?t*2-1:t;case QA.switch:return t=t>.5?1:0,n?t*2-1:t;case QA.concave:return n?(t=t*2-1,t<0?-ce[~~(t*-NA)]:ce[~~(t*NA)]):ce[~~(t*NA)];case QA.convex:return n?(t=t*2-1,t<0?-ve[~~(t*-NA)]:ve[~~(t*NA)]):ve[~~(t*NA)]}}var XA=class Tn{isBipolar;isNegative;index;isCC;curveType;constructor(A=j.noController,t=QA.linear,n=!1,s=!1,a=!1){this.isBipolar=s,this.isNegative=a,this.index=A,this.isCC=n,this.curveType=t}get sourceName(){return this.isCC?Object.keys(S).find(A=>S[A]===this.index)??this.index.toString():Object.keys(j).find(A=>j[A]===this.index)??this.index.toString()}get curveTypeName(){return Object.keys(QA).find(A=>QA[A]===this.curveType)??this.curveType.toString()}static fromSourceEnum(A){let t=Me(A,9),n=Me(A,8),s=Me(A,7),a=A&127,i=A>>10&3;return new Tn(a,i,s,t,n)}static copyFrom(A){return new Tn(A.index,A.curveType,A.isCC,A.isBipolar,A.isNegative)}toString(){return`${this.sourceName} ${this.curveTypeName} ${this.isBipolar?"bipolar":"unipolar"} ${this.isNegative?"negative":"positive"}`}toSourceEnum(){return this.curveType<<10|un(this.isBipolar)<<9|un(this.isNegative)<<8|un(this.isCC)<<7|this.index}isIdentical(A){return this.index===A.index&&this.isNegative===A.isNegative&&this.isCC===A.isCC&&this.isBipolar===A.isBipolar&&this.curveType===A.curveType}getValue(A,t){let n;if(this.isCC)n=A[this.index];else switch(this.index){case j.noController:n=16383;break;case j.noteOnKeyNum:n=t.midiNote<<7;break;case j.noteOnVelocity:n=t.velocity<<7;break;case j.polyPressure:n=t.pressure<<7;break;default:n=A[this.index+mA];break}let s=(this.isBipolar?2:0)|(this.isNegative?1:0);return ga[NA*(this.curveType*Pt+s)+n]}},ga=new Float32Array(NA*ra*Pt);for(let e=0;e<Pt;e++)for(let A=0;A<ra;A++){let t=NA*(e*Pt+A);for(let n=0;n<NA;n++)ga[t+n]=Ia(A,e,n/NA)}var me=10;function ge(e,A,t,n,s){return new XA(s,e,n,A,t).toSourceEnum()}var ca=ge(QA.linear,!0,!1,!0,S.filterResonance),EA=class xn{currentValue=0;destination=r.initialAttenuation;transformAmount=0;transformType=0;isEffectModulator=!1;isDefaultResonantModulator=!1;primarySource;secondarySource;constructor(A=new XA,t=new XA,n=r.INVALID,s=0,a=0,i=!1,I=!1){this.primarySource=A,this.secondarySource=t,this.destination=n,this.transformAmount=s,this.transformType=a,this.isEffectModulator=i,this.isDefaultResonantModulator=I}get destinationName(){return Object.keys(r).find(A=>r[A]===this.destination)}static isIdentical(A,t,n=!1){return A.primarySource.isIdentical(t.primarySource)&&A.secondarySource.isIdentical(t.secondarySource)&&A.destination===t.destination&&A.transformType===t.transformType&&(!n||A.transformAmount===t.transformAmount)}static copyFrom(A){return new xn(XA.copyFrom(A.primarySource),XA.copyFrom(A.secondarySource),A.destination,A.transformAmount,A.transformType,A.isEffectModulator,A.isDefaultResonantModulator)}toString(){return`Source: ${this.primarySource.toString()}
3
3
  Secondary source: ${this.secondarySource.toString()}
4
4
  to: ${this.destinationName}
5
- amount: ${this.transformAmount}`+(this.transformType===2?"absolute value":"")}write(A,t){J(A,this.primarySource.toSourceEnum()),J(A,this.destination),J(A,this.transformAmount),J(A,this.secondarySource.toSourceEnum()),J(A,this.transformType),t&&t.mod++}sumTransform(A){let t=xn.copyFrom(this);return t.transformAmount+=A.transformAmount,t}},yA=class extends EA{constructor(e,A,t,n,s){let a=(e===219||e===221)&&A===0&&(t===r.reverbEffectsSend||t===r.chorusEffectsSend),i=e===ca&&A===0&&t===r.initialFilterQ;super(XA.fromSourceEnum(e),XA.fromSourceEnum(A),t,n,s,a,i),this.destination>mo&&(this.destination=r.INVALID)}},fn=960,mn=QA.concave,Uo=[new yA(ge(mn,!1,!0,!1,j.noteOnVelocity),0,r.initialAttenuation,fn,0),new yA(129,0,r.vibLfoToPitch,50,0),new yA(ge(mn,!1,!0,!0,S.mainVolume),0,r.initialAttenuation,fn,0),new yA(13,0,r.vibLfoToPitch,50,0),new yA(526,16,r.fineTune,12700,0),new yA(650,0,r.pan,500,0),new yA(ge(mn,!1,!0,!0,S.expressionController),0,r.initialAttenuation,fn,0),new yA(219,0,r.reverbEffectsSend,200,0),new yA(221,0,r.chorusEffectsSend,200,0)],To=[new yA(ge(QA.linear,!1,!1,!1,j.polyPressure),0,r.vibLfoToPitch,50,0),new yA(ge(QA.linear,!1,!1,!0,S.tremoloDepth),0,r.modLfoToVolume,24,0),new yA(ge(QA.convex,!0,!1,!0,S.attackTime),0,r.attackVolEnv,6e3,0),new yA(ge(QA.linear,!0,!1,!0,S.releaseTime),0,r.releaseVolEnv,3600,0),new yA(ge(QA.linear,!0,!1,!0,S.brightness),0,r.initialFilterFc,6e3,0),new yA(ca,0,r.initialFilterQ,250,0)],Ea=Uo.concat(To),Ct=4,FA=class{generatorType;generatorValue=0;constructor(e,A,t=!0){if(this.generatorType=e,A===void 0)throw new Error("No value provided.");if(this.generatorValue=Math.round(A),t){let n=x[e];n!==void 0&&(this.generatorValue=Math.max(n.min,Math.min(n.max,this.generatorValue)))}}write(e,A){J(e,this.generatorType),J(e,this.generatorValue),A.gen++}toString(){return`${Object.keys(r).find(e=>r[e]===this.generatorType)}: ${this.generatorValue}`}};function xo(e,A,t){let n=x[e]||{min:0,max:32768,def:0},s=A.find(o=>o.generatorType===e),a=0;s&&(a=s.generatorValue);let i=t.find(o=>o.generatorType===e),I=n.def;return i&&(I=i.generatorValue),Math.max(-32767,Math.min(32767,I+a))}var Jt=4,Vt=class{velRange={min:-1,max:127};keyRange={min:-1,max:127};generators=[];modulators=[];get hasKeyRange(){return this.keyRange.min!==-1}get hasVelRange(){return this.velRange.min!==-1}get fineTuning(){let e=this.getGenerator(r.coarseTune,0),A=this.getGenerator(r.fineTune,0);return e*100+A}set fineTuning(e){let A=Math.trunc(e/100),t=e%100;this.setGenerator(r.coarseTune,A),this.setGenerator(r.fineTune,t)}addToGenerator(e,A,t=!0){let n=this.getGenerator(e,x[e].def);this.setGenerator(e,A+n,t)}setGenerator(e,A,t=!0){switch(e){case r.sampleID:throw new Error("Use setSample()");case r.instrument:throw new Error("Use setInstrument()");case r.velRange:case r.keyRange:throw new Error("Set the range manually")}if(A===void 0){this.generators=this.generators.filter(s=>s.generatorType!==e);return}let n=this.generators.findIndex(s=>s.generatorType===e);n>0?this.generators[n]=new FA(e,A,t):this.addGenerators(new FA(e,A,t))}addGenerators(...e){e.forEach(A=>{switch(A.generatorType){default:this.generators.push(A);break;case r.sampleID:case r.instrument:break;case r.velRange:this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127;break;case r.keyRange:this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127}})}addModulators(...e){this.modulators.push(...e)}getGenerator(e,A){return this.generators.find(t=>t.generatorType===e)?.generatorValue??A}copyFrom(e){this.generators=e.generators.map(A=>new FA(A.generatorType,A.generatorValue,!1)),this.modulators=e.modulators.map(EA.copyFrom.bind(EA)),this.velRange={...e.velRange},this.keyRange={...e.keyRange}}getGenCount(){let e=this.generators.filter(A=>A.generatorType!==r.sampleID&&A.generatorType!==r.instrument&&A.generatorType!==r.keyRange&&A.generatorType!==r.velRange).length;return this.hasVelRange&&e++,this.hasKeyRange&&e++,e}write(e,A,t,n,s){let a=n.gen,i=n.mod;J(t.pdta,a&65535),J(t.pdta,i&65535),J(t.xdta,a>>16),J(t.xdta,i>>16),n.bag++,this.getWriteGenerators(s).forEach(o=>o.write(e,n)),this.modulators.forEach(o=>o.write(A,n))}getWriteGenerators(e){let A=this.generators.filter(t=>t.generatorType!==r.sampleID&&t.generatorType!==r.instrument&&t.generatorType!==r.keyRange&&t.generatorType!==r.velRange);if(!e)throw new Error("No bank provided! ");return this.hasVelRange&&A.unshift(new FA(r.velRange,this.velRange.max<<8|Math.max(this.velRange.min,0),!1)),this.hasKeyRange&&A.unshift(new FA(r.keyRange,this.keyRange.max<<8|Math.max(this.keyRange.min,0),!1)),A}},Ba=class extends Vt{},Ca=class extends Vt{parentPreset;constructor(e,A){super(),this.parentPreset=e,this._instrument=A,this._instrument.linkTo(this.parentPreset)}_instrument;get instrument(){return this._instrument}set instrument(e){this._instrument&&this._instrument.unlinkFrom(this.parentPreset),this._instrument=e,this._instrument.linkTo(this.parentPreset)}getGenCount(){return super.getGenCount()+1}getWriteGenerators(e){let A=super.getWriteGenerators(e);if(!e)throw new Error("Instrument ID cannot be determined without the sound bank itself.");return A.push(new FA(r.instrument,e.instruments.indexOf(this.instrument),!1)),A}},ha=class extends Vt{parentInstrument;useCount;constructor(e,A){super(),this.parentInstrument=e,this._sample=A,A.linkTo(this.parentInstrument),this.useCount=e.useCount}_sample;get sample(){return this._sample}set sample(e){this._sample&&this._sample.unlinkFrom(this.parentInstrument),this._sample=e,e.linkTo(this.parentInstrument)}getGenCount(){return super.getGenCount()+1}getWriteGenerators(e){let A=super.getWriteGenerators(e);return A.push(new FA(r.sampleID,e.samples.indexOf(this.sample),!1)),A}},la=22,Ho=new Set([r.velRange,r.keyRange,r.instrument,r.sampleID,r.exclusiveClass,r.endOper,r.sampleModes,r.startloopAddrsOffset,r.startloopAddrsCoarseOffset,r.endloopAddrsOffset,r.endloopAddrsCoarseOffset,r.startAddrsOffset,r.startAddrsCoarseOffset,r.endAddrOffset,r.endAddrsCoarseOffset,r.initialAttenuation,r.fineTune,r.coarseTune,r.keyNumToVolEnvHold,r.keyNumToVolEnvDecay,r.keyNumToModEnvHold,r.keyNumToModEnvDecay]),dt=class{name="";zones=[];globalZone=new Ba;linkedTo=[];get useCount(){return this.linkedTo.length}createZone(e){let A=new ha(this,e);return this.zones.push(A),A}linkTo(e){this.linkedTo.push(e),this.zones.forEach(A=>A.useCount++)}unlinkFrom(e){let A=this.linkedTo.indexOf(e);if(A<0){sA(`Cannot unlink ${e.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(A,1),this.zones.forEach(t=>t.useCount--)}deleteUnusedZones(){this.zones=this.zones.filter(e=>{let A=e.useCount>0;return A||e.sample.unlinkFrom(this),A})}delete(){if(this.useCount>0)throw new Error(`Cannot delete an instrument that is used by: ${this.linkedTo.map(e=>e.name).toString()}.`);this.zones.forEach(e=>e.sample.unlinkFrom(this))}deleteZone(e,A=!1){let t=this.zones[e];return t.useCount-=1,t.useCount<1||A?(t.sample.unlinkFrom(this),this.zones.splice(e,1),!0):!1}globalize(){let e=this.globalZone;for(let n=0;n<58;n++){if(Ho.has(n))continue;n=n;let s={},a=x[n]?.def||0;s[a]=0;for(let i of this.zones){let I=i.getGenerator(n,void 0);I!==void 0?s[I]===void 0?s[I]=1:s[I]++:s[a]++;let o;switch(n){default:continue;case r.decayVolEnv:o=r.keyNumToVolEnvDecay;break;case r.holdVolEnv:o=r.keyNumToVolEnvHold;break;case r.decayModEnv:o=r.keyNumToModEnvDecay;break;case r.holdModEnv:o=r.keyNumToModEnvHold}if(i.getGenerator(o,void 0)!==void 0){s={};break}}if(Object.keys(s).length>0){let I=Object.entries(s).reduce((g,B)=>g[1]<B[1]?B:g,["0",0]),o=parseInt(I[0]);o!==a&&e.setGenerator(n,o,!1),this.zones.forEach(g=>{let B=g.getGenerator(n,void 0);B!==void 0?B===o&&g.setGenerator(n,void 0):o!==a&&g.setGenerator(n,a)})}}let t=this.zones[0].modulators.map(n=>EA.copyFrom(n));for(let n of t){let s=!0;for(let a of this.zones){if(!s)continue;a.modulators.find(I=>EA.isIdentical(I,n))||(s=!1)}if(s){e.addModulators(EA.copyFrom(n));for(let a of this.zones){let i=a.modulators.find(I=>EA.isIdentical(I,n));i&&i.transformAmount===n.transformAmount&&a.modulators.splice(a.modulators.indexOf(i),1)}}}}getSize(){let e=this.zones.reduce((t,n)=>n.modulators.length+t,0)+this.globalZone.modulators.length,A=this.zones.reduce((t,n)=>n.getGenCount()+t,0)+this.globalZone.getGenCount();return{mod:e*me,bag:(this.zones.length+1)*Jt,gen:A*Ct,hdr:la}}write(e,A,t,n,s,a){p(`%cWriting ${this.name}...`,c.info),kA(n.pdta,this.name.substring(0,20),20),kA(n.xdta,this.name.substring(20),20),J(n.pdta,s.hdr&65535),J(n.xdta,s.hdr>>>16),s.hdr+=this.zones.length+1,this.globalZone.write(e,A,t,s,a),this.zones.forEach(i=>i.write(e,A,t,s,a))}},da=38,pe=class{parentSoundBank;name="";program=0;bankMSB=0;bankLSB=0;isGMGSDrum=!1;zones=[];globalZone;library=0;genre=0;morphology=0;constructor(e,A=new Ba){this.parentSoundBank=e,this.globalZone=A}get isXGDrums(){return this.parentSoundBank.isXGBank&&fA.isXGDrums(this.bankMSB)}get isAnyDrums(){let e=this.parentSoundBank.isXGBank;return this.isGMGSDrum||e&&fA.isXGDrums(this.bankMSB)&&this.bankMSB!==126}delete(){this.zones.forEach(e=>e.instrument?.unlinkFrom(this))}deleteZone(e){this.zones[e]?.instrument?.unlinkFrom(this),this.zones.splice(e,1)}createZone(e){let A=new Ca(this,e);return this.zones.push(A),A}preload(e,A){for(let t=e;t<A+1;t++)for(let n=0;n<128;n++)this.getSynthesisData(t,n).forEach(s=>{s.sample.getAudioData()})}matches(e){return te.matches(this,e)}getSize(){let e=this.zones.reduce((t,n)=>n.modulators.length+t,0)+this.globalZone.modulators.length,A=this.zones.reduce((t,n)=>n.getGenCount()+t,0)+this.globalZone.getGenCount();return{mod:e*me,bag:(this.zones.length+1)*Jt,gen:A*Ct,hdr:da}}getSynthesisData(e,A){if(this.zones.length<1)return[];function t(d,h){return h>=d.min&&h<=d.max}function n(d,h){d.push(...h.filter(C=>!d.find(Q=>Q.generatorType===C.generatorType)))}function s(d,h){d.push(...h.filter(C=>!d.find(Q=>EA.isIdentical(C,Q))))}let a=[],i=[...this.globalZone.generators],I=[...this.globalZone.modulators],o=this.globalZone.keyRange,g=this.globalZone.velRange;return this.zones.filter(d=>t(d.hasKeyRange?d.keyRange:o,e)&&t(d.hasVelRange?d.velRange:g,A)).forEach(d=>{let h=d.instrument;if(!h||h.zones.length<1)return;let C=d.generators,Q=d.modulators,m=[...h.globalZone.generators],y=[...h.globalZone.modulators],F=h.globalZone.keyRange,k=h.globalZone.velRange;h.zones.filter(v=>t(v.hasKeyRange?v.keyRange:F,e)&&t(v.hasVelRange?v.velRange:k,A)).forEach(v=>{let L=[...v.generators],E=[...v.modulators];n(C,i),n(L,m),s(Q,I),s(E,y),s(E,this.parentSoundBank.defaultModulators);let X=[...E];for(let O of Q){let nA=X.findIndex($=>EA.isIdentical(O,$));nA!==-1?X[nA]=X[nA].sumTransform(O):X.push(O)}v.sample&&a.push({instrumentGenerators:L,presetGenerators:C,modulators:X,sample:v.sample})})}),a}toMIDIString(){return te.toMIDIString(this)}toString(){return te.toNamedMIDIString(this)}toFlattenedInstrument(){let e=(g,B)=>{g.push(...B.filter(d=>!g.find(h=>h.generatorType===d.generatorType)))},A=(g,B)=>({min:Math.max(g.min,B.min),max:Math.min(g.max,B.max)}),t=(g,B)=>{g.push(...B.filter(d=>!g.find(h=>EA.isIdentical(d,h))))},n=new dt;n.name=this.name;let s=[],a=[],i=this.globalZone;s.push(...i.generators),a.push(...i.modulators);let I=i.keyRange,o=i.velRange;for(let g of this.zones){if(!g.instrument)throw new Error("No instrument in a preset zone.");let B=g.keyRange;g.hasKeyRange||(B=I);let d=g.velRange;g.hasVelRange||(d=o);let h=g.generators.map(L=>new FA(L.generatorType,L.generatorValue));e(h,s);let C=[...g.modulators];t(C,a);let Q=g.instrument,m=Q.zones,y=[],F=[],k=Q.globalZone;y.push(...k.generators),F.push(...k.modulators);let D=k.keyRange,v=k.velRange;for(let L of m){if(!L.sample)throw new Error("No sample in an instrument zone.");let E=L.keyRange;L.hasKeyRange||(E=D);let X=L.velRange;if(L.hasVelRange||(X=v),E=A(E,B),X=A(X,d),E.max<E.min||X.max<X.min)continue;let O=L.generators.map(z=>new FA(z.generatorType,z.generatorValue));e(O,y);let nA=[...L.modulators];t(nA,F);let $=[...nA];for(let z of C){let tA=$.findIndex(rA=>EA.isIdentical(z,rA));tA!==-1?$[tA]=$[tA].sumTransform(z):$.push(z)}let V=O.map(z=>new FA(z.generatorType,z.generatorValue));for(let z of h){if(z.generatorType===r.velRange||z.generatorType===r.keyRange||z.generatorType===r.instrument||z.generatorType===r.endOper||z.generatorType===r.sampleModes)continue;let tA=O.findIndex(rA=>rA.generatorType===z.generatorType);if(tA!==-1){let rA=V[tA].generatorValue+z.generatorValue;V[tA]=new FA(z.generatorType,rA)}else{let rA=x[z.generatorType].def+z.generatorValue;V.push(new FA(z.generatorType,rA))}}V=V.filter(z=>z.generatorType!==r.sampleID&&z.generatorType!==r.keyRange&&z.generatorType!==r.velRange&&z.generatorType!==r.endOper&&z.generatorType!==r.instrument&&z.generatorValue!==x[z.generatorType].def);let q=n.createZone(L.sample);q.keyRange=E,q.velRange=X,q.keyRange.min===0&&q.keyRange.max===127&&(q.keyRange.min=-1),q.velRange.min===0&&q.velRange.max===127&&(q.velRange.min=-1),q.addGenerators(...V),q.addModulators(...$)}}return n}write(e,A,t,n,s,a){p(`%cWriting ${this.name}...`,c.info),kA(n.pdta,this.name.substring(0,20),20),kA(n.xdta,this.name.substring(20),20),J(n.pdta,this.program);let i=this.bankMSB;this.isGMGSDrum?i=128:this.bankMSB===0&&(i=this.bankLSB),J(n.pdta,i),n.xdta.currentIndex+=4,J(n.pdta,s.hdr&65535),J(n.xdta,s.hdr>>16),gA(n.pdta,this.library),gA(n.pdta,this.genre),gA(n.pdta,this.morphology),n.xdta.currentIndex+=12,s.hdr+=this.zones.length+1,this.globalZone.write(e,A,t,s,a),this.zones.forEach(I=>I.write(e,A,t,s,a))}};function Ds(e,A){let t;return A?t=e.find(n=>n.isXGDrums):t=e.find(n=>n.isGMGSDrum),t||(e.find(n=>n.isAnyDrums)??e[0])}function Qa(e,A,t){if(e.length<1)throw new Error("No presets!");A.isGMGSDrum&&fA.isSystemXG(t)&&(A={...A,isGMGSDrum:!1,bankLSB:0,bankMSB:fA.getDrumBank(t)});let{isGMGSDrum:n,bankLSB:s,bankMSB:a,program:i}=A,I=fA.isSystemXG(t),o=fA.isXGDrums(a)&&I,g=e.find(C=>C.matches(A));if(g&&(!o||o&&g.isXGDrums))return g;let B=C=>{p(`%cPreset %c${te.toMIDIString(A)}%c not found. (${t}) Replaced with %c${C.toString()}`,c.warn,c.unrecognized,c.warn,c.value)};if(n){let C=e.find(Q=>Q.isGMGSDrum&&Q.program===i);return C||(C=e.find(Q=>Q.isAnyDrums&&Q.program===i),C)?(B(C),C):(C=Ds(e,!1),B(C),C)}if(o){let C=e.find(Q=>Q.program===i&&Q.isXGDrums);return C||(C=e.find(Q=>Q.isAnyDrums&&Q.program===i),C)?(B(C),C):(C=Ds(e,!0),B(C),C)}let d=e.filter(C=>C.program===i&&!C.isAnyDrums);if(d.length<1)return B(e[0]),e[0];if(I?g=d.find(C=>C.bankLSB===s):g=d.find(C=>C.bankMSB===a),g)return B(g),g;let h=Math.max(a,s);return g=d.find(C=>C.bankLSB===h||C.bankMSB===h),g?(B(g),g):(B(d[0]),d[0])}var Yo=class extends pe{constructor(e,A){super(e.parentSoundBank,e.globalZone),this.bankMSB=fA.addBankOffset(e.bankMSB,A,e.isXGDrums),this.name=e.name,this.bankLSB=e.bankLSB,this.isGMGSDrum=e.isGMGSDrum,this.program=e.program,this.genre=e.genre,this.morphology=e.morphology,this.library=e.library,this.zones=e.zones}},Po=class{soundBankList=[];presetListChangeCallback;selectablePresetList=[];constructor(e){this.presetListChangeCallback=e}_presetList=[];get presetList(){return[...this._presetList]}get priorityOrder(){return this.soundBankList.map(e=>e.id)}set priorityOrder(e){this.soundBankList.sort((A,t)=>e.indexOf(A.id)-e.indexOf(t.id)),this.generatePresetList()}deleteSoundBank(e){if(this.soundBankList.length===0){sA("1 soundbank left. Aborting!");return}let A=this.soundBankList.findIndex(t=>t.id===e);if(A===-1)throw new Error(`No sound bank with id "${e}"`);this.soundBankList.splice(A,1),this.generatePresetList()}addSoundBank(e,A,t=0){let n=this.soundBankList.find(s=>s.id===A);n!==void 0?(n.soundBank=e,n.bankOffset=t):this.soundBankList.push({id:A,soundBank:e,bankOffset:t}),this.generatePresetList()}getPreset(e,A){if(this.soundBankList.length<1)throw new Error("No sound banks! Did you forget to add one?");return Qa(this.selectablePresetList,e,A)}destroy(){this.soundBankList.forEach(e=>{e.soundBank.destroySoundBank()}),this.soundBankList=[]}generatePresetList(){let e=new Array,A=new Set;this.soundBankList.forEach(t=>{let n=t.soundBank,s=t.bankOffset;n.presets.forEach(a=>{let i=new Yo(a,s);A.has(i.toMIDIString())||(A.add(i.toMIDIString()),e.push(i))})}),e.sort(te.sorter.bind(te)),this.selectablePresetList=e,this._presetList=e.map(t=>({bankMSB:t.bankMSB,bankLSB:t.bankLSB,program:t.program,isGMGSDrum:t.isGMGSDrum,name:t.name,isAnyDrums:t.isAnyDrums})),this.presetListChangeCallback()}},Jo=.05,qo=3070,Ko=2e3,ws=Math.PI/2,Nt=-500,ua=500,os=ua-Nt,fa=new Float32Array(os+1),ma=new Float32Array(os+1);for(let e=Nt;e<=ua;e++){let A=(e-Nt)/os,t=e-Nt;fa[t]=Math.cos(ws*A),ma[t]=Math.sin(ws*A)}function Oo(e,A,t,n,s,a,i,I,o){if(isNaN(A[0]))return;let g;e.overridePan?g=e.overridePan:(e.currentPan+=(e.modulatedGenerators[r.pan]-e.currentPan)*this.synthProps.panSmoothingFactor,g=e.currentPan);let B=this.synthProps.masterParameters.masterGain*this.synthProps.midiVolume*e.gain,d=~~(g+500),h=fa[d]*B*this.synthProps.panLeft,C=ma[d]*B*this.synthProps.panRight;if(this.synth.enableEffects){let Q=e.modulatedGenerators[r.reverbEffectsSend];if(Q>0){let y=this.synthProps.masterParameters.reverbGain*this.synthProps.reverbSend*B*(Q/qo);for(let F=0;F<A.length;F++){let k=F+o;s[k]+=y*A[F],a[k]+=y*A[F]}}let m=e.modulatedGenerators[r.chorusEffectsSend];if(m>0){let y=this.synthProps.masterParameters.chorusGain*this.synthProps.chorusSend*(m/Ko),F=h*y,k=C*y;for(let D=0;D<A.length;D++){let v=D+o;i[v]+=F*A[D],I[v]+=k*A[D]}}}if(h>0)for(let Q=0;Q<A.length;Q++)t[Q+o]+=h*A[Q];if(C>0)for(let Q=0;Q<A.length;Q++)n[Q+o]+=C*A[Q]}var Vo=.1,Xt=class Et{static cachedCoefficients=[];resonanceCb=0;currentInitialFc=13500;a0=0;a1=0;a2=0;a3=0;a4=0;x1=0;x2=0;y1=0;y2=0;lastTargetCutoff=1/0;initialized=!1;sampleRate;maxCutoff;constructor(A){this.sampleRate=A,this.maxCutoff=A*.45}static apply(A,t,n,s){let a=A.modulatedGenerators[r.initialFilterFc],i=A.filter;i.initialized?i.currentInitialFc+=(a-i.currentInitialFc)*s:(i.initialized=!0,i.currentInitialFc=a);let I=i.currentInitialFc+n,o=A.modulatedGenerators[r.initialFilterQ];if(i.currentInitialFc>13499&&I>13499&&o===0){i.currentInitialFc=13500;return}(Math.abs(i.lastTargetCutoff-I)>1||i.resonanceCb!==o)&&(i.lastTargetCutoff=I,i.resonanceCb=o,Et.calculateCoefficients(i,I));for(let g=0;g<t.length;g++){let B=t[g],d=i.a0*B+i.a1*i.x1+i.a2*i.x2-i.a3*i.y1-i.a4*i.y2;i.x2=i.x1,i.x1=B,i.y2=i.y1,i.y1=d,t[g]=d}}static calculateCoefficients(A,t){t=~~t;let n=A.resonanceCb,s=Et.cachedCoefficients?.[n]?.[t];if(s!==void 0){A.a0=s.a0,A.a1=s.a1,A.a2=s.a2,A.a3=s.a3,A.a4=s.a4;return}let a=Nn(t);a=Math.min(a,A.maxCutoff);let i=n/10,I=Ae(-(i-3.01)),o=1/Math.sqrt(Ae(-i)),g=2*Math.PI*a/A.sampleRate,B=Math.cos(g),d=Math.sin(g)/(2*I),h=(1-B)*o,C=h/2,Q=C,m=1+d,y=-2*B,F=1-d,k={a0:C/m,a1:h/m,a2:Q/m,a3:y/m,a4:F/m};A.a0=k.a0,A.a1=k.a1,A.a2=k.a2,A.a3=k.a3,A.a4=k.a4,Et.cachedCoefficients[n]??=[],Et.cachedCoefficients[n][t]=k}},Hn=new Xt(44100);Hn.resonanceCb=0;for(let e=1500;e<13500;e++)Hn.currentInitialFc=e,Xt.calculateCoefficients(Hn,e);var Fs={enableEventSystem:!0,initialTime:0,enableEffects:!0};function Xo(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 Zo(e){let A=[];for(let n of this.midiChannels)for(let s of n.voices)if(!s.finished){let a=Xo(n,s);A.push({channel:n,voice:s,priority:a})}A.sort((n,s)=>n.priority-s.priority);let t=A.slice(0,e);for(let{channel:n,voice:s}of t){let a=n.voices.indexOf(s);a>-1&&n.voices.splice(a,1)}}var Sn=1,Yn=new Float32Array(1e3);for(let e=0;e<Yn.length;e++)Yn[e]=Ia(0,QA.convex,e/1e3);var _e=class Pn{attackDuration=0;decayDuration=0;holdDuration=0;releaseDuration=0;sustainLevel=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;releaseStartLevel=0;currentValue=0;static startRelease(A){Pn.recalculate(A)}static recalculate(A){let t=A.modulationEnvelope;A.isInRelease&&(t.releaseStartLevel=Pn.getValue(A,A.releaseStartTime,!0)),t.sustainLevel=1-A.modulatedGenerators[r.sustainModEnv]/1e3,t.attackDuration=Qe(A.modulatedGenerators[r.attackModEnv]);let n=(60-A.midiNote)*A.modulatedGenerators[r.keyNumToModEnvDecay],s=Qe(A.modulatedGenerators[r.decayModEnv]+n);t.decayDuration=s*(1-t.sustainLevel);let a=(60-A.midiNote)*A.modulatedGenerators[r.keyNumToModEnvHold];t.holdDuration=Qe(a+A.modulatedGenerators[r.holdModEnv]);let i=Qe(Math.max(A.modulatedGenerators[r.releaseModEnv],-7200));t.releaseDuration=i*t.releaseStartLevel,t.delayEnd=A.startTime+Qe(A.modulatedGenerators[r.delayModEnv]),t.attackEnd=t.delayEnd+t.attackDuration,t.holdEnd=t.attackEnd+t.holdDuration,t.decayEnd=t.holdEnd+t.decayDuration}static getValue(A,t,n=!1){let s=A.modulationEnvelope;return A.isInRelease&&!n?s.releaseStartLevel===0?0:Math.max(0,(1-(t-A.releaseStartTime)/s.releaseDuration)*s.releaseStartLevel):(t<s.delayEnd?s.currentValue=0:t<s.attackEnd?s.currentValue=Yn[~~((1-(s.attackEnd-t)/s.attackDuration)*1e3)]:t<s.holdEnd?s.currentValue=Sn:t<s.decayEnd?s.currentValue=(1-(s.decayEnd-t)/s.decayDuration)*(s.sustainLevel-Sn)+Sn:s.currentValue=s.sustainLevel,s.currentValue)}},Sa=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(e,A,t,n,s,a,i,I){this.sampleData=e,this.playbackStep=A,this.cursor=t,this.rootKey=n,this.loopStart=s,this.loopEnd=a,this.end=i,this.loopingMode=I,this.isLooping=this.loopingMode===1||this.loopingMode===3}},zo=-2320,Wo=-1130,Jn=class pa{sample;filter;gain=1;generators;modulators=[];resonanceOffset=0;modulatedGenerators;finished=!1;isInRelease=!1;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new _e;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=0;realKey;portamentoFromKey=-1;portamentoDuration=0;overridePan=0;exclusiveClass=0;constructor(A,t,n,s,a,i,I,o,g){this.sample=t,this.generators=o,this.exclusiveClass=this.generators[r.exclusiveClass],this.modulatedGenerators=new Int16Array(o),this.modulators=g,this.filter=new Xt(A),this.velocity=s,this.midiNote=n,this.startTime=a,this.targetKey=i,this.realKey=I,this.volumeEnvelope=new be(A,o[r.sustainVolEnv])}static copyFrom(A,t,n){let s=A.sample,a=new Sa(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new pa(A.volumeEnvelope.sampleRate,a,A.midiNote,A.velocity,t,A.targetKey,n,new Int16Array(A.generators),A.modulators.map(EA.copyFrom.bind(EA)))}exclusiveRelease(A){this.release(A,Wa),this.modulatedGenerators[r.releaseVolEnv]=zo,this.modulatedGenerators[r.releaseModEnv]=Wo,be.recalculate(this),_e.recalculate(this)}release(A,t=za){this.releaseStartTime=A,this.releaseStartTime-this.startTime<t&&(this.releaseStartTime=this.startTime+t)}};function _o(e,A,t,n){let s=e.getSynthesisData(A,t).reduce((a,i)=>{if(i.sample.getAudioData()===void 0)return sA(`Discarding invalid sample: ${i.sample.name}`),a;let I=new Int16Array(Mn);for(let m=0;m<60;m++)I[m]=xo(m,i.presetGenerators,i.instrumentGenerators);I[r.initialAttenuation]=Math.floor(I[r.initialAttenuation]*.4);let o=i.sample.originalKey;I[r.overridingRootKey]>-1&&(o=I[r.overridingRootKey]);let g=A;I[r.keyNum]>-1&&(g=I[r.keyNum]);let B=i.sample.loopStart,d=i.sample.loopEnd,h=I[r.sampleModes],C=i.sample.getAudioData(),Q=new Sa(C,i.sample.sampleRate/this.sampleRate*Math.pow(2,i.sample.pitchCorrection/1200),0,o,B,d,Math.floor(C.length)-1,h);return I[r.velocity]>-1&&(t=I[r.velocity]),a.push(new Jn(this.sampleRate,Q,A,t,this.currentSynthTime,g,n,I,i.modulators.map(EA.copyFrom.bind(EA)))),a},[]);return this.setCachedVoice(e,A,t,s),s.map(a=>Jn.copyFrom(a,this.currentSynthTime,n))}function jo(e,A,t,n){let s=this.midiChannels[e],a=this.keyModifierManager.hasOverridePatch(e,A),i=s.preset;if(!i)return sA(`No preset for channel ${e}!`),[];let I={...i};a&&(I=this.keyModifierManager.getPatch(e,A));let o=this.getCachedVoice(I,A,t);return o!==void 0?o.map(g=>Jn.copyFrom(g,this.currentSynthTime,n)):(a&&(i=this.soundBankManager.getPreset(I,this.privateProps.masterParameters.midiSystem)),this.getVoicesForPreset(i,A,t,n))}function Gs(e,A,t){let n=e,s=A<<7|t;return e===127&&A===127&&t===127?{midiNote:-1,centTuning:null}:{midiNote:n,centTuning:s*.0061}}function $o(e,A=0){let t=e[0];if(this.privateProps.masterParameters.deviceID!==Be&&e[1]!==127&&this.privateProps.masterParameters.deviceID!==e[1])return;function n(a,i,I,o){p(`%cChannel %c${a}%c ${I}. %c${i} ${o}%c, with %c${MA(e)}`,c.info,c.recognized,c.info,c.value,c.info,c.value)}function s(){p(`%cUnrecognized Roland %cGS %cSysEx: %c${MA(e)}`,c.warn,c.recognized,c.warn,c.unrecognized)}switch(t){default:p(`%cUnrecognized SysEx: %c${MA(e)}`,c.warn,c.unrecognized);break;case 126:case 127:switch(e[2]){case 4:{let a;switch(e[3]){case 1:{let i=e[5]<<7|e[4];this.setMIDIVolume(i/16384),p(`%cMaster Volume. Volume: %c${i}`,c.info,c.value);break}case 2:{let I=((e[5]<<7|e[4])-8192)/8192;this.setMasterParameter("masterPan",I),p(`%cMaster Pan. Pan: %c${I}`,c.info,c.value);break}case 3:{let i=(e[5]<<7|e[6])-8192;a=Math.floor(i/81.92),this.setMasterTuning(a),p(`%cMaster Fine Tuning. Cents: %c${a}`,c.info,c.value);break}case 4:{a=(e[5]-64)*100,this.setMasterTuning(a),p(`%cMaster Coarse Tuning. Cents: %c${a}`,c.info,c.value);break}default:p(`%cUnrecognized MIDI Device Control Real-time message: %c${MA(e)}`,c.warn,c.unrecognized)}break}case 9:e[3]===1?(p("%cGM1 system on",c.info),this.setMasterParameter("midiSystem","gm")):e[3]===3?(p("%cGM2 system on",c.info),this.setMasterParameter("midiSystem","gm2")):(p("%cGM system off, defaulting to GS",c.info),this.setMasterParameter("midiSystem","gs"));break;case 8:{let a=4;switch(e[3]){case 1:{let i=e[a++],I=ee(e,16,a);if(a+=16,e.length<384){sA(`The Bulk Tuning Dump is too short! (${e.length} bytes, at least 384 are expected)`);return}for(let o=0;o<128;o++)this.privateProps.tunings[i][o]=Gs(e[a++],e[a++],e[a++]);p(`%cBulk Tuning Dump %c${I}%c Program: %c${i}`,c.info,c.value,c.info,c.recognized);break}case 2:case 7:{e[3]===7&&a++;let i=e[a++],I=e[a++];for(let o=0;o<I;o++)this.privateProps.tunings[i][e[a++]]=Gs(e[a++],e[a++],e[a++]);p(`%cSingle Note Tuning. Program: %c${i}%c Keys affected: %c${I}`,c.info,c.recognized,c.info,c.recognized);break}case 9:case 8:{let i=new Int8Array(12);if(e[3]===8)for(let I=0;I<12;I++)i[I]=e[7+I]-64;else for(let I=0;I<24;I+=2){let o=(e[7+I]<<7|e[8+I])-8192;i[I/2]=Math.floor(o/81.92)}(e[4]&1)===1&&this.midiChannels[14+A].setOctaveTuning(i),(e[4]>>1&1)===1&&this.midiChannels[15+A].setOctaveTuning(i);for(let I=0;I<7;I++)(e[5]>>I&1)===1&&this.midiChannels[7+I+A].setOctaveTuning(i);for(let I=0;I<7;I++)(e[6]>>I&1)===1&&this.midiChannels[I+A].setOctaveTuning(i);p(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${i.join(" ")}`,c.info,c.value);break}default:p(`%cUnrecognized MIDI Tuning standard message: %c${MA(e)}`,c.warn,c.unrecognized);break}break}default:p(`%cUnrecognized MIDI Realtime/non realtime message: %c${MA(e)}`,c.warn,c.unrecognized)}break;case 65:if(e[2]===66&&e[3]===18){let a=e[7];if(e[4]===64||e[4]===0&&e[6]===127){if((e[5]&16)>0){let i=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A,I=this.midiChannels[i];switch(e[6]){default:s();break;case 21:{let o=a>0&&e[5]>>4>0;I.setGSDrums(o),p(`%cChannel %c${i}%c ${o?"is now a drum channel":"now isn't a drum channel"}%c via: %c${MA(e)}`,c.info,c.value,c.recognized,c.info,c.value);return}case 22:{let o=a-64;I.setCustomController(IA.channelKeyShift,o),n(i,o,"key shift","keys");return}case 28:{let o=a;o===0?(I.randomPan=!0,p(`%cRandom pan is set to %cON%c for %c${i}`,c.info,c.recognized,c.info,c.value)):(I.randomPan=!1,I.controllerChange(S.pan,o));break}case 33:I.controllerChange(S.chorusDepth,a);break;case 34:I.controllerChange(S.reverbDepth,a);break;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:{let o=e.length-9,g=new Int8Array(12);for(let d=0;d<o;d++)g[d]=e[d+7]-64;I.setOctaveTuning(g);let B=a-64;n(i,g.join(" "),"octave scale tuning","cents"),I.setTuning(B);break}}return}else if((e[5]&32)>0){let i=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A,I=this.midiChannels[i],o=a-64,g=o/64,B=a/128,d=(h,C,Q=!1)=>{switch(e[6]&15){case 0:h===mA+j.pitchWheel?(I.controllerChange(S.registeredParameterMSB,0),I.controllerChange(S.registeredParameterLSB,0),I.controllerChange(S.dataEntryMSB,Math.floor(o))):(I.sysExModulators.setModulator(h,r.fineTune,o*100,Q),n(i,o,`${C} pitch control`,"semitones"));break;case 1:I.sysExModulators.setModulator(h,r.initialFilterFc,g*9600,Q),n(i,g*9600,`${C} pitch control`,"cents");break;case 2:I.sysExModulators.setModulator(h,r.initialAttenuation,g*960,Q),n(i,g*960,`${C} amplitude`,"cB");break;case 4:I.sysExModulators.setModulator(h,r.vibLfoToPitch,B*600,Q),n(i,B*600,`${C} LFO1 pitch depth`,"cents");break;case 5:I.sysExModulators.setModulator(h,r.vibLfoToFilterFc,B*2400,Q),n(i,B*2400,`${C} LFO1 filter depth`,"cents");break;case 6:I.sysExModulators.setModulator(h,r.vibLfoToVolume,g*960,Q),n(i,g*960,`${C} LFO1 amplitude depth`,"cB");break;case 8:I.sysExModulators.setModulator(h,r.modLfoToPitch,B*600,Q),n(i,B*600,`${C} LFO2 pitch depth`,"cents");break;case 9:I.sysExModulators.setModulator(h,r.modLfoToFilterFc,B*2400,Q),n(i,B*2400,`${C} LFO2 filter depth`,"cents");break;case 10:I.sysExModulators.setModulator(h,r.modLfoToVolume,g*960,Q),n(i,g*960,`${C} LFO2 amplitude depth`,"cB");break}};switch(e[6]&240){default:s();break;case 0:d(S.modulationWheel,"mod wheel");break;case 16:d(mA+j.pitchWheel,"pitch wheel",!0);break;case 32:d(mA+j.channelPressure,"channel pressure");break;case 48:d(mA+j.polyPressure,"poly pressure");break}return}else if(e[5]===0){switch(e[6]){default:s();break;case 127:a===0?(p("%cGS Reset received!",c.info),this.resetAllControllers(!1),this.setMasterParameter("midiSystem","gs")):a===127&&(p("%cGS system off, switching to GM2",c.info),this.resetAllControllers(!1),this.setMasterParameter("midiSystem","gm2"));break;case 6:p(`%cRoland GS Master Pan set to: %c${a}%c with: %c${MA(e)}`,c.info,c.value,c.info,c.value),this.setMasterParameter("masterPan",(a-64)/64);break;case 4:p(`%cRoland GS Master Volume set to: %c${a}%c with: %c${MA(e)}`,c.info,c.value,c.info,c.value),this.setMIDIVolume(a/127);break;case 5:{let i=a-64;p(`%cRoland GS Master Key-Shift set to: %c${i}%c with: %c${MA(e)}`,c.info,c.value,c.info,c.value),this.setMasterTuning(i*100);break}}return}else if(e[5]===1)switch(e[6]){default:s();break;case 0:{let i=ee(e,16,7);p(`%cGS Patch name: %c${i}`,c.info,c.value);break}case 51:p(`%cGS Reverb level: %c${a}`,c.info,c.value),this.privateProps.reverbSend=a/64;break;case 48:case 49:case 50:case 52:case 53:case 55:p(`%cUnsupported GS Reverb Parameter: %c${e[6].toString(16)}`,c.warn,c.unrecognized);break;case 58:p(`%cGS Chorus level: %c${a}`,c.info,c.value),this.privateProps.chorusSend=a/64;break;case 56:case 57:case 59:case 60:case 61:case 62:case 63:case 64:p(`%cUnsupported GS Chorus Parameter: %c${e[6].toString(16)}`,c.warn,c.unrecognized);break}}else s();return}else if(e[2]===69&&e[3]===18){if(e[4]===16&&e[6]===0)if(e[5]===0){let a=new Uint8Array(e.slice(7,e.length-2));this.privateProps.callEvent("synthDisplay",{displayData:a,displayType:hn.soundCanvasText})}else if(e[5]===1){let a=new Uint8Array(e.slice(7,e.length-3));this.privateProps.callEvent("synthDisplay",{displayData:a,displayType:hn.soundCanvasDotMatrix}),p(`%cRoland SC Display Dot Matrix via: %c${MA(e)}`,c.info,c.value)}else s()}else if(e[2]===22&&e[3]===18&&e[4]===16){this.setMIDIVolume(e[7]/100),p(`%cRoland Master Volume control set to: %c${e[7]}%c via: %c${MA(e)}`,c.info,c.value,c.info,c.value);return}else{p(`%cUnrecognized Roland SysEx: %c${MA(e)}`,c.warn,c.unrecognized);return}break;case 67:if(e[2]===76)if(e[3]===0&&e[4]===0)switch(e[5]){case 4:{let a=e[6];this.setMIDIVolume(a/127),p(`%cXG master volume. Volume: %c${a}`,c.info,c.recognized);break}case 6:{let a=e[6]-64;this.setMasterParameter("transposition",a),p(`%cXG master transpose. Volume: %c${a}`,c.info,c.recognized);break}case 126:p("%cXG system on",c.info),this.resetAllControllers(!1),this.setMasterParameter("midiSystem","xg");break}else if(e[3]===8){if(!fA.isSystemXG(this.privateProps.masterParameters.midiSystem))return;let a=e[4]+A;if(a>=this.midiChannels.length)return;let i=this.midiChannels[a],I=e[6];switch(e[5]){case 1:i.controllerChange(S.bankSelect,I);break;case 2:i.controllerChange(S.bankSelectLSB,I);break;case 3:i.programChange(I);break;case 8:{if(i.drumChannel)return;i.channelTransposeKeyShift=I-64;break}case 11:i.controllerChange(S.mainVolume,I);break;case 14:{let o=I;o===0?(i.randomPan=!0,p(`%cRandom pan is set to %cON%c for %c${a}`,c.info,c.recognized,c.info,c.value)):i.controllerChange(S.pan,o);break}case 19:i.controllerChange(S.reverbDepth,I);break;case 18:i.controllerChange(S.chorusDepth,I);break;default:p(`%cUnrecognized Yamaha XG Part Setup: %c${e[5].toString(16).toUpperCase()}`,c.warn,c.unrecognized)}}else if(e[3]===6&&e[4]===0){let a=new Uint8Array(e.slice(5,e.length-1));this.privateProps.callEvent("synthDisplay",{displayData:a,displayType:hn.yamahaXGText})}else fA.isSystemXG(this.privateProps.masterParameters.midiSystem)&&p(`%cUnrecognized Yamaha XG SysEx: %c${MA(e)}`,c.warn,c.unrecognized);else fA.isSystemXG(this.privateProps.masterParameters.midiSystem)&&p(`%cUnrecognized Yamaha SysEx: %c${MA(e)}`,c.warn,c.unrecognized);break}}var Rs=class qn{patch;lockPreset;lockedSystem;midiControllers;lockedControllers;customControllers;lockVibrato;channelVibrato;channelTransposeKeyShift;channelOctaveTuning;isMuted;drumChannel;channelNumber;constructor(A,t,n,s,a,i,I,o,g,B,d,h,C){this.patch=A,this.lockPreset=t,this.lockedSystem=n,this.midiControllers=s,this.lockedControllers=a,this.customControllers=i,this.lockVibrato=I,this.channelVibrato=o,this.channelTransposeKeyShift=g,this.channelOctaveTuning=B,this.isMuted=d,this.drumChannel=h,this.channelNumber=C}static copyFrom(A){return new qn({...A.patch},A.lockPreset,A.lockedSystem,A.midiControllers.slice(),[...A.lockedControllers],A.customControllers.slice(),A.lockVibrato,{...A.channelVibrato},A.channelTransposeKeyShift,A.channelOctaveTuning,A.isMuted,A.drumChannel,A.channelNumber)}static create(A,t){let n=A.midiChannels[t];return new qn({...n.patch,name:n?.preset?.name??"undefined"},n.lockPreset,n.lockedSystem,n.midiControllers.slice(),[...n.lockedControllers],n.customControllers.slice(),n.lockGSNRPNParams,{...n.channelVibrato},n.channelTransposeKeyShift,n.channelOctaveTuning.slice(),n.isMuted,n.drumChannel,t)}apply(A){let t=A.midiChannels[this.channelNumber];t.muteChannel(this.isMuted),t.setDrums(this.drumChannel),t.midiControllers.set(this.midiControllers),t.lockedControllers=this.lockedControllers,t.customControllers.set(this.customControllers),t.updateChannelTuning(),t.channelVibrato=this.channelVibrato,t.lockGSNRPNParams=this.lockVibrato,t.channelTransposeKeyShift=this.channelTransposeKeyShift,t.channelOctaveTuning=this.channelOctaveTuning,t.setPresetLock(!1),t.setPatch(this.patch),t.setPresetLock(this.lockPreset),t.lockedSystem=this.lockedSystem}};var Ai=class{keyMappings=[];addMapping(e,A,t){this.keyMappings[e]??=[],this.keyMappings[e][A]=t}deleteMapping(e,A){this.keyMappings[e]?.[A]!==void 0&&(this.keyMappings[e][A]=void 0)}clearMappings(){this.keyMappings=[]}setMappings(e){this.keyMappings=e}getMappings(){return this.keyMappings}getVelocity(e,A){return this.keyMappings[e]?.[A]?.velocity??-1}getGain(e,A){return this.keyMappings[e]?.[A]?.gain??1}hasOverridePatch(e,A){let t=this.keyMappings[e]?.[A]?.patch?.bankMSB;return t!==void 0&&t>=0}getPatch(e,A){let t=this.keyMappings[e]?.[A];if(t)return t.patch;throw new Error("No modifier.")}},is=class Kn{channelSnapshots;keyMappings;masterParameters;constructor(A,t,n){this.channelSnapshots=A,this.masterParameters=t,this.keyMappings=n}static create(A){let t=A.midiChannels.map((n,s)=>Rs.create(A,s));return new Kn(t,A.getAllMasterParameters(),A.keyModifierManager.getMappings())}static copyFrom(A){return new Kn(A.channelSnapshots.map(t=>Rs.copyFrom(t)),{...A.masterParameters},[...A.keyMappings])}apply(A){for(Object.entries(this.masterParameters).forEach(([n,s])=>{A.setMasterParameter(n,s)}),A.keyModifierManager.setMappings(this.keyMappings);A.midiChannels.length<this.channelSnapshots.length;)A.createMIDIChannel();this.channelSnapshots.forEach(n=>{n.apply(A)})}},ei={masterGain:_a,masterPan:0,voiceCap:Xa,interpolationType:vt.hermite,midiSystem:Os,monophonicRetriggerMode:!1,reverbGain:1,chorusGain:1,blackMIDIMode:!1,transposition:0,deviceID:Be},ti=class{tunings=[];masterParameters=ei;midiVolume=1;reverbSend=1;chorusSend=1;panLeft=.5;panRight=.5;defaultPreset;drumPreset;volumeEnvelopeSmoothingFactor;panSmoothingFactor;filterSmoothingFactor;eventCallbackHandler;getVoices;voiceKilling;cachedVoices=[];constructor(e,A,t,n,s,a){this.eventCallbackHandler=e,this.getVoices=A,this.voiceKilling=t,this.volumeEnvelopeSmoothingFactor=n,this.panSmoothingFactor=s,this.filterSmoothingFactor=a;for(let i=0;i<128;i++)this.tunings.push([])}callEvent(e,A){this.eventCallbackHandler(e,A)}};function pn(e,A,t){if(t<e)return 0;let n=(t-e)/(1/A)+.25;return Math.abs(n-~~(n+.5))*4-1}var ni=class On{static getSample(A,t,n){let s=A.currentTuningCalculated*A.sample.playbackStep;if(s===1){On.getSampleNearest(A,t,s);return}switch(n){case vt.hermite:this.getSampleHermite(A,t,s);return;case vt.linear:default:this.getSampleLinear(A,t,s);return;case vt.nearestNeighbor:On.getSampleNearest(A,t,s);return}}static getSampleLinear(A,t,n){let s=A.sample,a=s.cursor,i=s.sampleData;if(s.isLooping){let I=s.loopEnd-s.loopStart;for(let o=0;o<t.length;o++){for(;a>=s.loopEnd;)a-=I;let g=~~a,B=g+1;for(;B>=s.loopEnd;)B-=I;let d=a-g,h=i[B],C=i[g];t[o]=C+(h-C)*d,a+=n}}else for(let I=0;I<t.length;I++){let o=~~a,g=o+1;if(g>=s.end){A.finished=!0;return}let B=a-o,d=i[g],h=i[o];t[I]=h+(d-h)*B,a+=n}A.sample.cursor=a}static getSampleNearest(A,t,n){let s=A.sample,a=s.cursor,i=s.sampleData;if(s.isLooping){let I=s.loopEnd-s.loopStart;for(let o=0;o<t.length;o++){for(;a>=s.loopEnd;)a-=I;let g=~~a+1;for(;g>=s.loopEnd;)g-=I;t[o]=i[g],a+=n}}else for(let I=0;I<t.length;I++){let o=~~a+1;if(o>=s.end){A.finished=!0;return}t[I]=i[o],a+=n}s.cursor=a}static getSampleHermite(A,t,n){let s=A.sample,a=s.cursor,i=s.sampleData;if(s.isLooping){let I=s.loopEnd-s.loopStart;for(let o=0;o<t.length;o++){for(;a>=s.loopEnd;)a-=I;let g=~~a,B=g+1,d=g+2,h=g+3,C=a-g;B>=s.loopEnd&&(B-=I),d>=s.loopEnd&&(d-=I),h>=s.loopEnd&&(h-=I);let Q=i[g],m=i[B],y=i[d],F=i[h],k=(y-Q)*.5,D=m-y,v=k+D,L=v+D+(F-m)*.5,E=v+L;t[o]=((L*C-E)*C+k)*C+m,a+=n}}else for(let I=0;I<t.length;I++){let o=~~a,g=o+1,B=o+2,d=o+3,h=a-o;if(g>=s.end||B>=s.end||d>=s.end){A.finished=!0;return}let C=i[o],Q=i[g],m=i[B],y=i[d],F=(m-C)*.5,k=Q-m,D=F+k,v=D+k+(y-Q)*.5,L=D+v;t[I]=((v*h-L)*h+F)*h+Q,a+=n}A.sample.cursor=a}};function si(e,A,t,n,s,a,i,I,o,g){if(e.isInRelease||A>=e.releaseStartTime&&(e.isInRelease=!0,be.startRelease(e),_e.startRelease(e),e.sample.loopingMode===3&&(e.sample.isLooping=!1)),e.modulatedGenerators[r.initialAttenuation]>2500)return e.isInRelease&&(e.finished=!0),e.finished;let B=e.targetKey,d=e.modulatedGenerators[r.fineTune]+this.channelOctaveTuning[e.midiNote]+this.channelTuningCents,h=e.modulatedGenerators[r.coarseTune],C=this.synthProps.tunings[this.preset?.program??0]?.[e.realKey];if(C?.centTuning&&(B=C.midiNote,d+=C.centTuning),e.portamentoFromKey>-1){let $=Math.min((A-e.startTime)/e.portamentoDuration,1),V=B-e.portamentoFromKey;h-=V*(1-$)}d+=(B-e.sample.rootKey)*e.modulatedGenerators[r.scaleTuning];let Q=0,m=0,y=e.modulatedGenerators[r.vibLfoToPitch],F=e.modulatedGenerators[r.vibLfoToVolume],k=e.modulatedGenerators[r.vibLfoToFilterFc];if(y!==0||F!==0||k!==0){let $=e.startTime+Qe(e.modulatedGenerators[r.delayVibLFO]),V=Nn(e.modulatedGenerators[r.freqVibLFO]),q=pn($,V,A);d+=q*(y*this.customControllers[IA.modulationMultiplier]),m+=-q*F,Q+=q*k}let D=e.modulatedGenerators[r.modLfoToPitch],v=e.modulatedGenerators[r.modLfoToVolume],L=e.modulatedGenerators[r.modLfoToFilterFc];if(D!==0||L!==0||v!==0){let $=e.startTime+Qe(e.modulatedGenerators[r.delayModLFO]),V=Nn(e.modulatedGenerators[r.freqModLFO]),q=pn($,V,A);d+=q*(D*this.customControllers[IA.modulationMultiplier]),m+=-q*v,Q+=q*L}if(this.channelVibrato.depth>0){let $=pn(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,A);$&&(d+=$*this.channelVibrato.depth)}let E=e.modulatedGenerators[r.modEnvToPitch],X=e.modulatedGenerators[r.modEnvToFilterFc];if(X!==0||E!==0){let $=_e.getValue(e,A);Q+=$*X,d+=$*E}m-=e.resonanceOffset;let O=~~(d+h*100);O!==e.currentTuningCents&&(e.currentTuningCents=O,e.currentTuningCalculated=Math.pow(2,O/1200));let nA=new Float32Array(g);return e.sample.loopingMode===2&&!e.isInRelease?(be.apply(e,nA,m,this.synthProps.volumeEnvelopeSmoothingFactor),e.finished):(ni.getSample(e,nA,this.synthProps.masterParameters.interpolationType),Xt.apply(e,nA,Q,this.synthProps.filterSmoothingFactor),be.apply(e,nA,m,this.synthProps.volumeEnvelopeSmoothingFactor),this.panAndMixVoice(e,nA,t,n,s,a,i,I,o),e.finished)}var ue={pitchWheelRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},Ze={partParameter:1,awe32:127,SF2:120},Oe={vibratoRate:8,vibratoDepth:9,vibratoDelay:10,TVFFilterCutoff:32,TVFFilterResonance:33,EGAttackTime:99,EGReleaseTime:102};function ai(e){this.midiControllers[S.dataEntryMSB]=e<<7;let A=()=>{this.channelVibrato.delay===0&&this.channelVibrato.rate===0&&this.channelVibrato.depth===0&&(this.channelVibrato.depth=50,this.channelVibrato.rate=8,this.channelVibrato.delay=.6)},t=(n,s,a)=>{a.length>0&&(a=" "+a),p(`%c${n} for %c${this.channelNumber}%c is now set to %c${s}%c${a}.`,c.info,c.recognized,c.info,c.value,c.info)};switch(this.dataEntryState){default:case YA.Idle:break;case YA.NRPFine:{if(this.lockGSNRPNParams)return;let n=this.midiControllers[S.nonRegisteredParameterMSB]>>7,s=this.midiControllers[S.nonRegisteredParameterLSB]>>7,a=this.midiControllers[S.dataEntryLSB]>>7;switch(n){default:if(e===64)return;p(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${s.toString(16).toUpperCase()} 0x${s.toString(16).toUpperCase()})%c data value: %c${e}`,c.warn,c.recognized,c.warn,c.unrecognized,c.warn,c.value);break;case Ze.partParameter:switch(s){default:if(e===64)return;p(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${n.toString(16)} 0x${s.toString(16)})%c data value: %c${e}`,c.warn,c.recognized,c.warn,c.unrecognized,c.warn,c.value);break;case Oe.vibratoRate:if(e===64)return;A(),this.channelVibrato.rate=e/64*8,t("Vibrato rate",`${e} = ${this.channelVibrato.rate}`,"Hz");break;case Oe.vibratoDepth:if(e===64)return;A(),this.channelVibrato.depth=e/2,t("Vibrato depth",`${e} = ${this.channelVibrato.depth}`,"cents of detune");break;case Oe.vibratoDelay:if(e===64)return;A(),this.channelVibrato.delay=e/64/3,t("Vibrato delay",`${e} = ${this.channelVibrato.delay}`,"seconds");break;case Oe.TVFFilterCutoff:this.controllerChange(S.brightness,e),t("Filter cutoff",e.toString(),"");break;case Oe.EGAttackTime:this.controllerChange(S.attackTime,e),t("EG attack time",e.toString(),"");break;case Oe.EGReleaseTime:this.controllerChange(S.releaseTime,e),t("EG release time",e.toString(),"");break}break;case Ze.awe32:break;case Ze.SF2:{if(s>100)break;let i=this.customControllers[IA.sf2NPRNGeneratorLSB],I=(e<<7|a)-8192;this.setGeneratorOffset(i,I);break}}break}case YA.RPCoarse:case YA.RPFine:{let n=this.midiControllers[S.registeredParameterMSB]|this.midiControllers[S.registeredParameterLSB]>>7;switch(n){default:p(`%cUnrecognized RPN for %c${this.channelNumber}%c: %c(0x${n.toString(16)})%c data value: %c${e}`,c.warn,c.recognized,c.warn,c.unrecognized,c.warn,c.value);break;case ue.pitchWheelRange:this.midiControllers[mA+j.pitchWheelRange]=e<<7,t("Pitch wheel range",e.toString(),"semitones");break;case ue.coarseTuning:{let s=e-64;this.setCustomController(IA.channelTuningSemitones,s),t("Coarse tuning",s.toString(),"semitones");break}case ue.fineTuning:this.setTuning(e-64,!1);break;case ue.modulationDepth:this.setModulationDepth(e*100);break;case ue.resetParameters:this.resetParameters();break}}}}var oi=[r.delayModLFO,r.freqModLFO,r.delayVibLFO,r.freqVibLFO,r.delayModEnv,r.attackModEnv,r.holdModEnv,r.decayModEnv,r.sustainModEnv,r.releaseModEnv,r.delayVolEnv,r.attackVolEnv,r.holdVolEnv,r.decayVolEnv,r.sustainVolEnv,r.releaseVolEnv,r.fineTune,r.modLfoToPitch,r.vibLfoToPitch,r.modEnvToPitch,r.modLfoToVolume,r.initialFilterFc,r.initialFilterQ,r.modLfoToFilterFc,r.modEnvToFilterFc,r.chorusEffectsSend,r.reverbEffectsSend];function ii(e,A,t){let n=(h,C,Q)=>Math.max(C,Math.min(Q,h)),s=h=>Math.max(-32768,1200*Math.log2(h/1e3)),a=h=>6900+1200*Math.log2(h/440),i=t<<7|A;i-=8192;let I=oi[e];I||sA(`Invalid AWE32 LSB: %c${e}`,c.unrecognized);let o,g,B,d;switch(I){default:break;case r.delayModLFO:case r.delayVibLFO:case r.delayVolEnv:case r.delayModEnv:o=4*n(i,0,5900),this.setGeneratorOverride(I,s(o));break;case r.attackVolEnv:case r.attackModEnv:o=n(i,0,5940),this.setGeneratorOverride(I,s(o));break;case r.holdVolEnv:case r.holdModEnv:o=n(i,0,8191),this.setGeneratorOverride(I,s(o));break;case r.decayModEnv:case r.decayVolEnv:case r.releaseVolEnv:case r.releaseModEnv:o=4*n(i,0,5940),this.setGeneratorOverride(I,s(o));break;case r.freqVibLFO:case r.freqModLFO:g=.084*A,this.setGeneratorOverride(I,a(g),!0);break;case r.sustainVolEnv:case r.sustainModEnv:B=A*7.5,this.setGeneratorOverride(I,B);break;case r.fineTune:this.setGeneratorOverride(I,i,!0);break;case r.modLfoToPitch:case r.vibLfoToPitch:d=n(i,-127,127)*9.375,this.setGeneratorOverride(I,d,!0);break;case r.modEnvToPitch:d=n(i,-127,127)*9.375,this.setGeneratorOverride(I,d);break;case r.modLfoToVolume:B=1.875*A,this.setGeneratorOverride(I,B,!0);break;case r.initialFilterFc:{let h=4335+59*A;this.setGeneratorOverride(I,h,!0);break}case r.initialFilterQ:B=215*(A/127),this.setGeneratorOverride(I,B,!0);break;case r.modLfoToFilterFc:d=n(i,-64,63)*56.25,this.setGeneratorOverride(I,d,!0);break;case r.modEnvToFilterFc:d=n(i,-64,63)*56.25,this.setGeneratorOverride(I,d);break;case r.chorusEffectsSend:case r.reverbEffectsSend:this.setGeneratorOverride(I,n(i,0,255)*(1e3/255));break}}function ri(e){switch(this.midiControllers[S.dataEntryLSB]=e<<7,this.dataEntryState){default:break;case YA.RPCoarse:case YA.RPFine:{switch(this.midiControllers[S.registeredParameterMSB]|this.midiControllers[S.registeredParameterLSB]>>7){default:break;case ue.pitchWheelRange:{if(e===0)break;this.midiControllers[mA+j.pitchWheelRange]|=e;let t=(this.midiControllers[mA+j.pitchWheelRange]>>7)+e/128;p(`%cChannel ${this.channelNumber} pitch wheel range. Semitones: %c${t}`,c.info,c.value);break}case ue.fineTuning:{let n=this.customControllers[IA.channelTuning]<<7|e;this.setTuning(n*.01220703125);break}case ue.modulationDepth:{let n=this.customControllers[IA.modulationMultiplier]*50+e/128*100;this.setModulationDepth(n);break}case 16383:this.resetParameters();break}break}case YA.NRPFine:{let A=this.midiControllers[S.nonRegisteredParameterMSB]>>7,t=this.midiControllers[S.nonRegisteredParameterLSB]>>7;if(A===Ze.SF2)return;switch(A){default:p(`%cUnrecognized NRPN LSB for %c${this.channelNumber}%c: %c(0x${t.toString(16).toUpperCase()} 0x${t.toString(16).toUpperCase()})%c data value: %c${e}`,c.warn,c.recognized,c.warn,c.unrecognized,c.warn,c.value);break;case Ze.awe32:ii.call(this,t,e,this.midiControllers[S.dataEntryMSB]>>7);break}}}}function Ii(e,A,t=!0){if(e>127)throw new Error("Invalid MIDI Controller.");if(e>=S.modulationWheelLSB&&e<=S.effectControl2LSB&&e!==S.dataEntryLSB){let n=e-32;if(this.lockedControllers[n])return;this.midiControllers[n]=this.midiControllers[n]&16256|A&127,this.voices.forEach(s=>this.computeModulators(s,1,n))}if(!this.lockedControllers[e]){switch(this.midiControllers[e]=A<<7,e){case S.allNotesOff:this.stopAllNotes();break;case S.allSoundOff:this.stopAllNotes(!0);break;case S.bankSelect:this.setBankMSB(A),this.channelNumber%16===Se&&fA.isSystemXG(this.channelSystem)&&this.setBankMSB(127);break;case S.bankSelectLSB:this.setBankLSB(A);break;case S.registeredParameterLSB:this.dataEntryState=YA.RPFine;break;case S.registeredParameterMSB:this.dataEntryState=YA.RPCoarse;break;case S.nonRegisteredParameterMSB:this.customControllers[IA.sf2NPRNGeneratorLSB]=0,this.dataEntryState=YA.NRPCoarse;break;case S.nonRegisteredParameterLSB:this.midiControllers[S.nonRegisteredParameterMSB]>>7===Ze.SF2&&(this.customControllers[IA.sf2NPRNGeneratorLSB]%100!==0&&(this.customControllers[IA.sf2NPRNGeneratorLSB]=0),A===100?this.customControllers[IA.sf2NPRNGeneratorLSB]+=100:A===101?this.customControllers[IA.sf2NPRNGeneratorLSB]+=1e3:A===102?this.customControllers[IA.sf2NPRNGeneratorLSB]+=1e4:A<100&&(this.customControllers[IA.sf2NPRNGeneratorLSB]+=A)),this.dataEntryState=YA.NRPFine;break;case S.dataEntryMSB:this.dataEntryCoarse(A);break;case S.dataEntryLSB:this.dataEntryFine(A);break;case S.resetAllControllers:this.resetControllersRP15Compliant();break;case S.sustainPedal:A<64&&(this.sustainedVoices.forEach(n=>{n.release(this.synth.currentSynthTime)}),this.sustainedVoices=[]);break;default:this.voices.forEach(n=>this.computeModulators(n,1,e));break}t&&this.synthProps.callEvent("controllerChange",{channel:this.channelNumber,controllerNumber:e,controllerValue:A})}}var It={0:0,1:.006,2:.023,4:.05,8:.11,16:.25,32:.5,64:2.06,80:4.2,96:8.4,112:19.5,116:26.7,120:40,124:80,127:480};function gi(e){if(It[e]!==void 0)return It[e];let A=null,t=null;for(let n of Object.keys(It)){let s=parseInt(n);s<e&&(A===null||s>A)&&(A=s),s>e&&(t===null||s<t)&&(t=s)}if(A!==null&&t!==null){let n=It[A],s=It[t];return n+(e-A)*(s-n)/(t-A)}return 0}function ci(e,A){return gi(e)*(A/30)}function Ei(e,A){if(A<1){this.noteOff(e);return}if(A=Math.min(127,A),this.synthProps.masterParameters.blackMIDIMode&&this.synth.totalVoicesAmount>200&&A<40||this.synthProps.masterParameters.blackMIDIMode&&A<10||this._isMuted)return;if(!this.preset){sA(`No preset for channel ${this.channelNumber}!`);return}let t=e+this.channelTransposeKeyShift+this.customControllers[IA.channelKeyShift],n=t;if(t>127||t<0)return;let s=this.preset?.program,a=this.synthProps.tunings[s]?.[t]?.midiNote;a>=0&&(n=a),this.synthProps.masterParameters.monophonicRetriggerMode&&this.killNote(e,-7200);let i=this.synth.keyModifierManager.getVelocity(this.channelNumber,t);i>-1&&(A=i);let I=this.synth.keyModifierManager.getGain(this.channelNumber,t),o=-1,g=0,B=this.midiControllers[S.portamentoTime]>>7,d=this.midiControllers[S.portamentoControl],h=d>>7;if(!this.drumChannel&&h!==n&&this.midiControllers[S.portamentoOnOff]>=8192&&B>0){if(d!==1){let y=Math.abs(n-h);g=ci(B,y),o=h}this.controllerChange(S.portamentoControl,n)}let C=this.synthProps.getVoices(this.channelNumber,n,A,t),Q=0;this.randomPan&&(Q=Math.round(Math.random()*1e3-500));let m=this.voices;C.forEach(y=>{y.portamentoFromKey=o,y.portamentoDuration=g,y.overridePan=Q,y.gain=I,this.sysExModulators.modulatorList.forEach(O=>{let nA=O.mod,$=y.modulators.findIndex(V=>EA.isIdentical(V,nA));$!==-1?y.modulators[$]=EA.copyFrom(nA):y.modulators.push(EA.copyFrom(nA))}),this.generatorOverridesEnabled&&this.generatorOverrides.forEach((O,nA)=>{O!==Vs&&(y.generators[nA]=O)});let F=y.exclusiveClass;F!==0&&m.forEach(O=>{O.exclusiveClass===F&&O.exclusiveRelease(this.synth.currentSynthTime)}),this.computeModulators(y);let k=y.modulatedGenerators[r.startAddrsOffset]+y.modulatedGenerators[r.startAddrsCoarseOffset]*32768,D=y.modulatedGenerators[r.endAddrOffset]+y.modulatedGenerators[r.endAddrsCoarseOffset]*32768,v=y.modulatedGenerators[r.startloopAddrsOffset]+y.modulatedGenerators[r.startloopAddrsCoarseOffset]*32768,L=y.modulatedGenerators[r.endloopAddrsOffset]+y.modulatedGenerators[r.endloopAddrsCoarseOffset]*32768,E=y.sample,X=O=>Math.max(0,Math.min(E.sampleData.length-1,O));if(E.cursor=X(E.cursor+k),E.end=X(E.end+D),E.loopStart=X(E.loopStart+v),E.loopEnd=X(E.loopEnd+L),E.loopEnd<E.loopStart){let O=E.loopStart;E.loopStart=E.loopEnd,E.loopEnd=O}E.loopEnd-E.loopStart<1&&(E.loopingMode===1||E.loopingMode===3)&&(E.loopingMode=0,E.isLooping=!1),y.volumeEnvelope.attenuation=y.volumeEnvelope.attenuationTargetGain,y.currentPan=Math.max(-500,Math.min(500,y.modulatedGenerators[r.pan]))}),this.synth.totalVoicesAmount+=C.length,this.synth.totalVoicesAmount>this.synthProps.masterParameters.voiceCap&&this.synthProps.voiceKilling(C.length),m.push(...C),this.sendChannelProperty(),this.synthProps.callEvent("noteOn",{midiNote:e,channel:this.channelNumber,velocity:A})}function Bi(e){if(e>127||e<0){sA("Received a noteOn for note",e,"Ignoring.");return}let A=e+this.channelTransposeKeyShift+this.customControllers[IA.channelKeyShift];if(this.synthProps.masterParameters.blackMIDIMode&&!this.drumChannel){this.killNote(A,-6950),this.synthProps.callEvent("noteOff",{midiNote:e,channel:this.channelNumber});return}this.voices.forEach(n=>{n.realKey!==A||n.isInRelease||(this.holdPedal?this.sustainedVoices.push(n):n.release(this.synth.currentSynthTime))}),this.synthProps.callEvent("noteOff",{midiNote:e,channel:this.channelNumber})}function Ci(e){if(this.lockPreset)return;this.patch.program=e;let A=this.synth.soundBankManager.getPreset(this.patch,this.channelSystem);A||(sA("No presets! Using empty fallback."),A=new pe(this.synth.soundBankManager.soundBankList[0].soundBank),A.name="SPESSA EMPTY FALLBACK PRESET"),this.preset=A,A.isAnyDrums!==this.drumChannel&&this.setDrumFlag(A.isAnyDrums),this.synthProps.callEvent("programChange",{channel:this.channelNumber,bankLSB:this.preset.bankLSB,bankMSB:this.preset.bankMSB,program:this.preset.program,isGMGSDrum:this.preset.isGMGSDrum}),this.sendChannelProperty()}var hi=class{modulatorList=[];resetModulators(){this.modulatorList=[]}setModulator(e,A,t,n=!1,s=!1){let a=this.getModulatorID(e,A,n,s);t===0&&this.deleteModulator(a);let i=this.modulatorList.find(I=>I.id===a);if(i)i.mod.transformAmount=t;else{let I,o;e>=mA?(I=e-mA,o=!1):(I=e,o=!0);let g=new EA(new XA(I,QA.linear,o,n),new XA,A,t,0);this.modulatorList.push({mod:g,id:a})}}getModulatorID(e,A,t,n){return`${e}-${A}-${t}-${n}`}deleteModulator(e){this.modulatorList=this.modulatorList.filter(A=>A.id!==e)}},li=1e3/200;function Ms(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n=A.primarySource.getValue(e,t),s=A.secondarySource.getValue(e,t),a=A.transformAmount;A.isEffectModulator&&a<=1e3&&(a*=li,a=Math.min(a,1e3));let i=n*s*a;return A.transformType===2&&(i=Math.abs(i)),A.isDefaultResonantModulator&&(t.resonanceOffset=Math.max(0,i/2)),A.currentValue=i,i}function di(e,A=-1,t=0){let n=e.modulators,s=e.generators;if(this.generatorOffsetsEnabled){s=new Int16Array(s);for(let g=0;g<s.length;g++)s[g]+=this.generatorOffsets[g]}let a=e.modulatedGenerators;if(A===-1){a.set(s),n.forEach(g=>{a[g.destination]+=Ms(this.midiControllers,g,e)});for(let g=0;g<a.length;g++){let B=x[g];B&&(a[g]=Math.min(B.max,Math.max(B.min,a[g])))}be.recalculate(e),_e.recalculate(e);return}let i=new Set([r.initialAttenuation,r.delayVolEnv,r.attackVolEnv,r.holdVolEnv,r.decayVolEnv,r.sustainVolEnv,r.releaseVolEnv,r.keyNumToVolEnvHold,r.keyNumToVolEnvDecay]),I=new Set,o=!!A;n.forEach(g=>{if(g.primarySource.isCC===o&&g.primarySource.index===t||g.secondarySource.isCC===o&&g.secondarySource.index===t){let B=g.destination;if(!I.has(B)){a[B]=s[B],Ms(this.midiControllers,g,e),n.forEach(h=>{h.destination===B&&(a[B]+=h.currentValue)});let d=x[B];a[B]=Math.max(d.min,Math.min(a[B],d.max)),I.add(B)}}}),[...I].some(g=>i.has(g))&&be.recalculate(e),_e.recalculate(e)}var Qi=class{midiControllers=new Int16Array(bn);lockedControllers=Array(bn).fill(!1);customControllers=new Float32Array(ea);channelTransposeKeyShift=0;channelOctaveTuning=new Int8Array(128);sysExModulators=new hi;drumChannel=!1;randomPan=!1;dataEntryState=YA.Idle;patch={bankMSB:0,bankLSB:0,program:0,isGMGSDrum:!1};preset;lockPreset=!1;lockedSystem="gs";lockGSNRPNParams=!1;channelVibrato={delay:0,depth:0,rate:0};voices=[];sustainedVoices=[];channelNumber;synth;synthProps;noteOn=Ei.bind(this);noteOff=Bi.bind(this);programChange=Ci.bind(this);controllerChange=Ii.bind(this);resetControllers=po.bind(this);resetPreset=yo.bind(this);resetControllersRP15Compliant=ko.bind(this);resetParameters=Do.bind(this);dataEntryFine=ri.bind(this);dataEntryCoarse=ai.bind(this);channelTuningCents=0;generatorOffsets=new Int16Array(Mn);generatorOffsetsEnabled=!1;generatorOverrides=new Int16Array(Mn);generatorOverridesEnabled=!1;renderVoice=si.bind(this);panAndMixVoice=Oo.bind(this);computeModulators=di.bind(this);constructor(e,A,t,n){this.synth=e,this.synthProps=A,this.preset=t,this.channelNumber=n,this.resetGeneratorOverrides(),this.resetGeneratorOffsets()}_isMuted=!1;get isMuted(){return this._isMuted}get holdPedal(){return this.midiControllers[S.sustainPedal]>=8192}get channelSystem(){return this.lockPreset?this.lockedSystem:this.synthProps.masterParameters.midiSystem}transposeChannel(e,A=!1){this.drumChannel||(e+=this.synthProps.masterParameters.transposition);let t=Math.trunc(e),n=this.channelTransposeKeyShift+this.customControllers[IA.channelTransposeFine]/100;this.drumChannel&&!A||e===n||(t!==this.channelTransposeKeyShift&&this.stopAllNotes(),this.channelTransposeKeyShift=t,this.setCustomController(IA.channelTransposeFine,(e-t)*100),this.sendChannelProperty())}setOctaveTuning(e){if(e.length!==12)throw new Error("Tuning is not the length of 12.");this.channelOctaveTuning=new Int8Array(128);for(let A=0;A<128;A++)this.channelOctaveTuning[A]=e[A%12]}setModulationDepth(e){e=Math.round(e),p(`%cChannel ${this.channelNumber} modulation depth. Cents: %c${e}`,c.info,c.value),this.setCustomController(IA.modulationMultiplier,e/50)}setTuning(e,A=!0){e=Math.round(e),this.setCustomController(IA.channelTuning,e),A&&p(`%cFine tuning for %c${this.channelNumber}%c is now set to %c${e}%c cents.`,c.info,c.recognized,c.info,c.value,c.info)}pitchWheel(e){this.lockedControllers[mA+j.pitchWheel]||(this.synthProps.callEvent("pitchWheel",{channel:this.channelNumber,pitch:e}),this.midiControllers[mA+j.pitchWheel]=e,this.voices.forEach(A=>this.computeModulators(A,0,j.pitchWheel)),this.sendChannelProperty())}channelPressure(e){this.midiControllers[mA+j.channelPressure]=e<<7,this.updateChannelTuning(),this.voices.forEach(A=>this.computeModulators(A,0,j.channelPressure)),this.synthProps.callEvent("channelPressure",{channel:this.channelNumber,pressure:e})}polyPressure(e,A){this.voices.forEach(t=>{t.midiNote===e&&(t.pressure=A,this.computeModulators(t,0,j.polyPressure))}),this.synthProps.callEvent("polyPressure",{channel:this.channelNumber,midiNote:e,pressure:A})}setCustomController(e,A){this.customControllers[e]=A,this.updateChannelTuning()}updateChannelTuning(){this.channelTuningCents=this.customControllers[IA.channelTuning]+this.customControllers[IA.channelTransposeFine]+this.customControllers[IA.masterTuning]+this.customControllers[IA.channelTuningSemitones]*100}renderAudio(e,A,t,n,s,a,i,I){this.voices=this.voices.filter(o=>!this.renderVoice(o,this.synth.currentSynthTime,e,A,t,n,s,a,i,I))}setPresetLock(e){this.lockPreset!==e&&(this.lockPreset=e,e&&(this.lockedSystem=this.synthProps.masterParameters.midiSystem))}setDrums(e){if(fA.isSystemXG(this.channelSystem))if(e)this.setBankMSB(fA.getDrumBank(this.channelSystem)),this.setBankLSB(0);else{if(this.channelNumber%16===Se)throw new Error(`Cannot disable drums on channel ${this.channelNumber} for XG.`);this.setBankMSB(0),this.setBankLSB(0)}else this.setGSDrums(e);this.setDrumFlag(e),this.programChange(this.patch.program)}setPatch(e){this.setBankMSB(e.bankMSB),this.setBankLSB(e.bankLSB),this.setGSDrums(e.isGMGSDrum),this.programChange(e.program)}setGSDrums(e){e!==this.patch.isGMGSDrum&&(this.setBankLSB(0),this.setBankMSB(0),this.patch.isGMGSDrum=e)}setVibrato(e,A,t){this.lockGSNRPNParams||(this.channelVibrato.rate=A,this.channelVibrato.delay=t,this.channelVibrato.depth=e)}disableAndLockGSNRPN(){this.lockGSNRPNParams=!0,this.channelVibrato.rate=0,this.channelVibrato.delay=0,this.channelVibrato.depth=0}resetGeneratorOverrides(){this.generatorOverrides.fill(Vs),this.generatorOverridesEnabled=!1}setGeneratorOverride(e,A,t=!1){this.generatorOverrides[e]=A,this.generatorOverridesEnabled=!0,t&&this.voices.forEach(n=>{n.generators[e]=A,this.computeModulators(n)})}resetGeneratorOffsets(){this.generatorOffsets.fill(0),this.generatorOffsetsEnabled=!1}setGeneratorOffset(e,A){this.generatorOffsets[e]=A*x[e].nrpn,this.generatorOffsetsEnabled=!0,this.voices.forEach(t=>{this.computeModulators(t)})}killNote(e,A=-12e3){e+=this.customControllers[IA.channelKeyShift],this.voices.forEach(t=>{t.realKey===e&&(t.modulatedGenerators[r.releaseVolEnv]=A,t.release(this.synth.currentSynthTime))})}stopAllNotes(e=!1){e?(this.voices.length=0,this.sustainedVoices.length=0,this.sendChannelProperty()):(this.voices.forEach(A=>{A.isInRelease||A.release(this.synth.currentSynthTime)}),this.sustainedVoices.forEach(A=>{A.release(this.synth.currentSynthTime)})),this.synthProps.callEvent("stopAll",{channel:this.channelNumber,force:e})}muteChannel(e){e&&this.stopAllNotes(!0),this._isMuted=e,this.sendChannelProperty(),this.synthProps.callEvent("muteChannel",{channel:this.channelNumber,isMuted:e})}sendChannelProperty(){if(!this.synth.enableEventSystem)return;let e={voicesAmount:this.voices.length,pitchWheel:this.midiControllers[mA+j.pitchWheel],pitchWheelRange:this.midiControllers[mA+j.pitchWheelRange]/128,isMuted:this.isMuted,transposition:this.channelTransposeKeyShift+this.customControllers[IA.channelTransposeFine]/100,isDrum:this.drumChannel};this.synthProps.callEvent("channelPropertyChange",{channel:this.channelNumber,property:e})}setBankMSB(e){this.lockPreset||(this.patch.bankMSB=e)}setBankLSB(e){this.lockPreset||(this.patch.bankLSB=e)}setDrumFlag(e){this.lockPreset||!this.preset||this.drumChannel!==e&&(e?(this.channelTransposeKeyShift=0,this.drumChannel=!0):this.drumChannel=!1,this.synthProps.callEvent("drumChange",{channel:this.channelNumber,isDrumChannel:this.drumChannel}))}},yn=20;async function ui(e,A,t,n,s,a,i){let I=0,o=0,g=[];for(let h of e.samples){n&&a&&await h.compressSample(a),s&&h.setAudioData(h.getAudioData(),h.sampleRate);let C=h.getRawData(!0);I++,await i?.(h.name,I,e.samples.length),p(`%cEncoded sample %c${I}. ${h.name}%c of %c${e.samples.length}%c. Compressed: %c${h.isCompressed}%c.`,c.info,c.recognized,c.info,c.recognized,c.info,h.isCompressed?c.recognized:c.unrecognized,c.info),o+=C.length+(h.isCompressed?0:92),g.push(C)}o%2!==0&&o++;let B=new Y(o+yn);kA(B,"LIST"),ht(B,o+yn-8,4),kA(B,"sdta"),kA(B,"smpl"),ht(B,o,4);let d=0;return e.samples.forEach((h,C)=>{let Q=g[C];B.set(Q,d+yn);let m,y;h.isCompressed?(m=d,y=m+Q.length):(m=d/2,y=m+Q.length/2,d+=92),d+=Q.length,A.push(m),t.push(y)}),B}var fi=48e3,Zt=class{name;sampleRate;originalKey;pitchCorrection;linkedSample;sampleType;loopStart;loopEnd;linkedTo=[];dataOverridden=!0;compressedData;audioData;constructor(e,A,t,n,s,a,i){this.name=e,this.sampleRate=A,this.originalKey=t,this.pitchCorrection=n,this.loopStart=a,this.loopEnd=i,this.sampleType=s}get isCompressed(){return this.compressedData!==void 0}get isLinked(){return this.sampleType===wA.rightSample||this.sampleType===wA.leftSample||this.sampleType===wA.linkedSample}get useCount(){return this.linkedTo.length}getRawData(e){return this.compressedData&&e&&!this.dataOverridden?this.compressedData:this.encodeS16LE()}resampleData(e){let A=this.getAudioData(),t=e/this.sampleRate,n=new Float32Array(Math.floor(A.length*t));for(let s=0;s<n.length;s++)n[s]=A[Math.floor(s*(1/t))];A=n,this.sampleRate=e,this.loopStart=Math.floor(this.loopStart*t),this.loopEnd=Math.floor(this.loopEnd*t),this.audioData=A}async compressSample(e){if(!this.isCompressed)try{let A=this.getAudioData();(this.sampleRate<8e3||this.sampleRate>96e3)&&(this.resampleData(fi),A=this.getAudioData());let t=await e(A,this.sampleRate);this.setCompressedData(t)}catch(A){sA(`Failed to compress ${this.name}. Leaving as uncompressed!`,A),this.compressedData=void 0}}setSampleType(e){if(this.sampleType=e,this.isLinked||(this.linkedSample&&(this.linkedSample.linkedSample=void 0,this.linkedSample.sampleType=e),this.linkedSample=void 0),(e&32768)>0)throw new Error("ROM samples are not supported.")}unlinkSample(){this.setSampleType(wA.monoSample)}setLinkedSample(e,A){if(e.linkedSample)throw new Error(`${e.name} is linked tp ${e.linkedSample.name}. Unlink it first.`);if(this.linkedSample=e,e.linkedSample=this,A===wA.leftSample)this.setSampleType(wA.leftSample),e.setSampleType(wA.rightSample);else if(A===wA.rightSample)this.setSampleType(wA.rightSample),e.setSampleType(wA.leftSample);else if(A===wA.linkedSample)this.setSampleType(wA.linkedSample),e.setSampleType(wA.linkedSample);else throw new Error("Invalid sample type: "+A)}linkTo(e){this.linkedTo.push(e)}unlinkFrom(e){let A=this.linkedTo.indexOf(e);if(A<0){sA(`Cannot unlink ${e.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(A,1)}getAudioData(){if(this.audioData)return this.audioData;if(this.isCompressed)return this.audioData=this.decodeVorbis(),this.audioData;throw new Error("Sample data is undefined for a BasicSample instance.")}setAudioData(e,A){this.audioData=e,this.sampleRate=A,this.dataOverridden=!0,this.compressedData=void 0}setCompressedData(e){this.audioData=void 0,this.compressedData=e,this.dataOverridden=!1}encodeS16LE(){let e=this.getAudioData(),A=new Int16Array(e.length),t=e.length;for(let n=0;n<t;n++){let s=e[n]*32768;s>32767?s=32767:s<-32768&&(s=-32768),A[n]=s}return new Y(A.buffer)}decodeVorbis(){if(this.audioData)return this.audioData;if(!this.compressedData)throw new Error("Compressed data is missing.");try{let A=Ot.decode(this.compressedData).data[0];if(A===void 0)return sA(`Error decoding sample ${this.name}: Vorbis decode returned undefined.`),new Float32Array(0);for(let t=0;t<A.length;t++)A[t]=Math.max(-1,Math.min(A[t],.999969482421875));return A}catch(e){return sA(`Error decoding sample ${this.name}: ${e}`),new Float32Array(this.loopEnd+1)}}},mi=class extends Zt{constructor(){super("",44100,60,0,wA.monoSample,0,0)}},Vn=16,Si=class extends Zt{linkedSampleIndex;s16leData;startByteOffset;endByteOffset;sampleID;constructor(e,A,t,n,s,a,i,I,o,g,B,d){let h=(g&Vn)>0;g&=~Vn,super(e,a,i,I,g,n-A/2,s-A/2),this.dataOverridden=!1,this.name=e,this.startByteOffset=A,this.endByteOffset=t,this.sampleID=d;let C=B instanceof Y?B.currentIndex:0;B instanceof Y?h?(this.loopStart+=this.startByteOffset/2,this.loopEnd+=this.startByteOffset/2,this.setCompressedData(B.slice(this.startByteOffset/2+C,this.endByteOffset/2+C))):this.s16leData=B.slice(C+this.startByteOffset,C+this.endByteOffset):this.setAudioData(B.slice(this.startByteOffset/2,this.endByteOffset/2),a),this.linkedSampleIndex=o}getLinkedSample(e){if(this.linkedSample||!this.isLinked)return;let A=e[this.linkedSampleIndex];A?A.linkedSample?(p(`%cInvalid linked sample for ${this.name}: Already linked to ${A.linkedSample.name}`,c.warn),this.unlinkSample()):this.setLinkedSample(A,this.sampleType):(p(`%cInvalid linked sample for ${this.name}. Setting to mono.`,c.warn),this.unlinkSample())}getAudioData(){if(this.audioData)return this.audioData;if(this.isCompressed)return super.getAudioData();if(!this.s16leData)throw console.error(this),new Error("Unexpected lack of audio data.");let e=this.endByteOffset-this.startByteOffset;if(e<1)return sA(`Invalid sample ${this.name}! Invalid length: ${e}`),new Float32Array(1);let A=new Float32Array(e/2),t=new Int16Array(this.s16leData.buffer);for(let n=0;n<t.length;n++)A[n]=t[n]/32768;return this.audioData=A,A}getRawData(e){return this.dataOverridden||this.compressedData?super.getRawData(e):this.s16leData??new Uint8Array(0)}};function bs(e,A,t=!0){let n=[],s=0;for(;e.data.length>e.data.currentIndex;){let a=pi(s,e.data,A);n.push(a),s++}return n.pop(),t&&n.forEach(a=>a.getLinkedSample(n)),n}function pi(e,A,t){let n=hA(A,20),s=N(A,4)*2,a=N(A,4)*2,i=N(A,4),I=N(A,4),o=N(A,4),g=A[A.currentIndex++];g>127&&(g=60);let B=qa(A[A.currentIndex++]),d=N(A,2),h=N(A,2);return new Si(n,s,a,i,I,o,g,B,d,h,t,e)}function yi(e,A,t){let s=46*(e.samples.length+1),a=new Y(s),i=new Y(s),I=0;e.samples.forEach((B,d)=>{kA(a,B.name.substring(0,20),20),kA(i,B.name.substring(20),20);let h=A[d];gA(a,h),i.currentIndex+=4;let C=t[d];gA(a,C),i.currentIndex+=4;let Q=B.loopStart+h,m=B.loopEnd+h;B.isCompressed&&(Q-=h,m-=h),gA(a,Q),gA(a,m),gA(a,B.sampleRate),a[a.currentIndex++]=B.originalKey,a[a.currentIndex++]=B.pitchCorrection,i.currentIndex+=14;let y=B.linkedSample?e.samples.indexOf(B.linkedSample):0;J(a,Math.max(0,y)&65535),J(i,Math.max(0,y)>>16),I=Math.max(I,y);let F=B.sampleType;B.isCompressed&&(F|=Vn),J(a,F),i.currentIndex+=2}),kA(a,"EOS",46),kA(i,"EOS",46);let o=cA("shdr",a),g=cA("shdr",i);return{pdta:o,xdta:g}}function vs(e,A=!1){let t=A?e.presets:e.instruments,n=A?"pgen":"igen",s=A?"pmod":"imod",a=A?"pbag":"ibag",i=A?"phdr":"inst",I=A?da:la,o=t.map(k=>(k instanceof pe,k.getSize())),g=o.reduce((k,D)=>k+D.gen,0)+Ct,B=new Y(g),d=o.reduce((k,D)=>k+D.mod,0)+me,h=new Y(d),C=o.reduce((k,D)=>k+D.bag,0)+Jt,Q={pdta:new Y(C),xdta:new Y(C)},m=o.reduce((k,D)=>D.hdr+k,0)+I,y={pdta:new Y(m),xdta:new Y(m)},F={gen:0,bag:0,mod:0,hdr:0};return t.forEach(k=>{k instanceof pe,k.write(B,h,Q,y,F,e)}),A?(kA(y.pdta,"EOP",20),y.pdta.currentIndex+=4,J(y.pdta,F.hdr&65535),y.pdta.currentIndex+=12,kA(y.xdta,"",20),y.xdta.currentIndex+=4,J(y.xdta,F.hdr>>16),y.xdta.currentIndex+=12):(kA(y.pdta,"EOI",20),kA(y.xdta,"",20),J(y.pdta,F.hdr&65535),J(y.xdta,F.hdr>>16)),J(Q.pdta,F.gen&65535),J(Q.xdta,F.gen>>16),J(Q.pdta,F.mod&65535),J(Q.xdta,F.mod>>16),{writeXdta:Math.max(g/Ct,d/me,C/Jt,m/I)>65535,gen:{pdta:cA(n,B),xdta:cA(s,new Y(Ct))},mod:{pdta:cA(s,h),xdta:cA(s,new Y(me))},bag:{pdta:cA(a,Q.pdta),xdta:cA(a,Q.xdta)},hdr:{pdta:cA(i,y.pdta),xdta:cA(i,y.xdta)}}}var Xn={compress:!1,compressionFunction:void 0,progressFunction:void 0,writeDefaultModulators:!0,writeExtendedLimits:!0,decompress:!1};async function ki(e,A=Xn){let t=$n(A,Xn);if(t?.compress){if(typeof t?.compressionFunction!="function")throw new Error("No compression function supplied but compression enabled.");if(t?.decompress)throw new Error("Decompressed and compressed at the same time.")}bA("%cSaving soundbank...",c.info),p(`%cCompression: %c${t?.compress||"false"}%c`,c.info,c.recognized,c.info,c.recognized),OA("%cWriting INFO...",c.info);let n=[];e.soundBankInfo.software="SpessaSynth",(t?.compress||e.samples.some(D=>D.isCompressed))&&(e.soundBankInfo.version.major=3,e.soundBankInfo.version.minor=0),t?.decompress&&(e.soundBankInfo.version.major=2,e.soundBankInfo.version.minor=4);let s=(D,v)=>{n.push(cA(D,ne(v,!0,!0)))},a=new Y(4);if(J(a,e.soundBankInfo.version.major),J(a,e.soundBankInfo.version.minor),n.push(cA("ifil",a)),e.soundBankInfo.romVersion){let D=new Y(4);J(D,e.soundBankInfo.romVersion.major),J(D,e.soundBankInfo.romVersion.minor),n.push(cA("iver",D))}let i=(e.soundBankInfo?.comment??"")+(e.soundBankInfo.subject?`
5
+ amount: ${this.transformAmount}`+(this.transformType===2?"absolute value":"")}write(A,t){J(A,this.primarySource.toSourceEnum()),J(A,this.destination),J(A,this.transformAmount),J(A,this.secondarySource.toSourceEnum()),J(A,this.transformType),t&&t.mod++}sumTransform(A){let t=xn.copyFrom(this);return t.transformAmount+=A.transformAmount,t}},yA=class extends EA{constructor(e,A,t,n,s){let a=(e===219||e===221)&&A===0&&(t===r.reverbEffectsSend||t===r.chorusEffectsSend),i=e===ca&&A===0&&t===r.initialFilterQ;super(XA.fromSourceEnum(e),XA.fromSourceEnum(A),t,n,s,a,i),this.destination>mo&&(this.destination=r.INVALID)}},fn=960,mn=QA.concave,Uo=[new yA(ge(mn,!1,!0,!1,j.noteOnVelocity),0,r.initialAttenuation,fn,0),new yA(129,0,r.vibLfoToPitch,50,0),new yA(ge(mn,!1,!0,!0,S.mainVolume),0,r.initialAttenuation,fn,0),new yA(13,0,r.vibLfoToPitch,50,0),new yA(526,16,r.fineTune,12700,0),new yA(650,0,r.pan,500,0),new yA(ge(mn,!1,!0,!0,S.expressionController),0,r.initialAttenuation,fn,0),new yA(219,0,r.reverbEffectsSend,200,0),new yA(221,0,r.chorusEffectsSend,200,0)],To=[new yA(ge(QA.linear,!1,!1,!1,j.polyPressure),0,r.vibLfoToPitch,50,0),new yA(ge(QA.linear,!1,!1,!0,S.tremoloDepth),0,r.modLfoToVolume,24,0),new yA(ge(QA.convex,!0,!1,!0,S.attackTime),0,r.attackVolEnv,6e3,0),new yA(ge(QA.linear,!0,!1,!0,S.releaseTime),0,r.releaseVolEnv,3600,0),new yA(ge(QA.linear,!0,!1,!0,S.brightness),0,r.initialFilterFc,6e3,0),new yA(ca,0,r.initialFilterQ,250,0)],Ea=Uo.concat(To),Ct=4,FA=class{generatorType;generatorValue=0;constructor(e,A,t=!0){if(this.generatorType=e,A===void 0)throw new Error("No value provided.");if(this.generatorValue=Math.round(A),t){let n=x[e];n!==void 0&&(this.generatorValue=Math.max(n.min,Math.min(n.max,this.generatorValue)))}}write(e,A){J(e,this.generatorType),J(e,this.generatorValue),A.gen++}toString(){return`${Object.keys(r).find(e=>r[e]===this.generatorType)}: ${this.generatorValue}`}};function xo(e,A,t){let n=x[e]||{min:0,max:32768,def:0},s=A.find(o=>o.generatorType===e),a=0;s&&(a=s.generatorValue);let i=t.find(o=>o.generatorType===e),I=n.def;return i&&(I=i.generatorValue),Math.max(-32767,Math.min(32767,I+a))}var Jt=4,Vt=class{velRange={min:-1,max:127};keyRange={min:-1,max:127};generators=[];modulators=[];get hasKeyRange(){return this.keyRange.min!==-1}get hasVelRange(){return this.velRange.min!==-1}get fineTuning(){let e=this.getGenerator(r.coarseTune,0),A=this.getGenerator(r.fineTune,0);return e*100+A}set fineTuning(e){let A=Math.trunc(e/100),t=e%100;this.setGenerator(r.coarseTune,A),this.setGenerator(r.fineTune,t)}addToGenerator(e,A,t=!0){let n=this.getGenerator(e,x[e].def);this.setGenerator(e,A+n,t)}setGenerator(e,A,t=!0){switch(e){case r.sampleID:throw new Error("Use setSample()");case r.instrument:throw new Error("Use setInstrument()");case r.velRange:case r.keyRange:throw new Error("Set the range manually")}if(A===null){this.generators=this.generators.filter(s=>s.generatorType!==e);return}let n=this.generators.findIndex(s=>s.generatorType===e);n>=0?this.generators[n]=new FA(e,A,t):this.addGenerators(new FA(e,A,t))}addGenerators(...e){e.forEach(A=>{switch(A.generatorType){default:this.generators.push(A);break;case r.sampleID:case r.instrument:break;case r.velRange:this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127;break;case r.keyRange:this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127}})}addModulators(...e){this.modulators.push(...e)}getGenerator(e,A){return this.generators.find(t=>t.generatorType===e)?.generatorValue??A}copyFrom(e){this.generators=e.generators.map(A=>new FA(A.generatorType,A.generatorValue,!1)),this.modulators=e.modulators.map(EA.copyFrom.bind(EA)),this.velRange={...e.velRange},this.keyRange={...e.keyRange}}getGenCount(){let e=this.generators.filter(A=>A.generatorType!==r.sampleID&&A.generatorType!==r.instrument&&A.generatorType!==r.keyRange&&A.generatorType!==r.velRange).length;return this.hasVelRange&&e++,this.hasKeyRange&&e++,e}write(e,A,t,n,s){let a=n.gen,i=n.mod;J(t.pdta,a&65535),J(t.pdta,i&65535),J(t.xdta,a>>16),J(t.xdta,i>>16),n.bag++,this.getWriteGenerators(s).forEach(o=>o.write(e,n)),this.modulators.forEach(o=>o.write(A,n))}getWriteGenerators(e){let A=this.generators.filter(t=>t.generatorType!==r.sampleID&&t.generatorType!==r.instrument&&t.generatorType!==r.keyRange&&t.generatorType!==r.velRange);if(!e)throw new Error("No bank provided! ");return this.hasVelRange&&A.unshift(new FA(r.velRange,this.velRange.max<<8|Math.max(this.velRange.min,0),!1)),this.hasKeyRange&&A.unshift(new FA(r.keyRange,this.keyRange.max<<8|Math.max(this.keyRange.min,0),!1)),A}},Ba=class extends Vt{},Ca=class extends Vt{parentPreset;constructor(e,A){super(),this.parentPreset=e,this._instrument=A,this._instrument.linkTo(this.parentPreset)}_instrument;get instrument(){return this._instrument}set instrument(e){this._instrument&&this._instrument.unlinkFrom(this.parentPreset),this._instrument=e,this._instrument.linkTo(this.parentPreset)}getGenCount(){return super.getGenCount()+1}getWriteGenerators(e){let A=super.getWriteGenerators(e);if(!e)throw new Error("Instrument ID cannot be determined without the sound bank itself.");return A.push(new FA(r.instrument,e.instruments.indexOf(this.instrument),!1)),A}},ha=class extends Vt{parentInstrument;useCount;constructor(e,A){super(),this.parentInstrument=e,this._sample=A,A.linkTo(this.parentInstrument),this.useCount=e.useCount}_sample;get sample(){return this._sample}set sample(e){this._sample&&this._sample.unlinkFrom(this.parentInstrument),this._sample=e,e.linkTo(this.parentInstrument)}getGenCount(){return super.getGenCount()+1}getWriteGenerators(e){let A=super.getWriteGenerators(e);return A.push(new FA(r.sampleID,e.samples.indexOf(this.sample),!1)),A}},la=22,Ho=new Set([r.velRange,r.keyRange,r.instrument,r.sampleID,r.exclusiveClass,r.endOper,r.sampleModes,r.startloopAddrsOffset,r.startloopAddrsCoarseOffset,r.endloopAddrsOffset,r.endloopAddrsCoarseOffset,r.startAddrsOffset,r.startAddrsCoarseOffset,r.endAddrOffset,r.endAddrsCoarseOffset,r.initialAttenuation,r.fineTune,r.coarseTune,r.keyNumToVolEnvHold,r.keyNumToVolEnvDecay,r.keyNumToModEnvHold,r.keyNumToModEnvDecay]),dt=class{name="";zones=[];globalZone=new Ba;linkedTo=[];get useCount(){return this.linkedTo.length}createZone(e){let A=new ha(this,e);return this.zones.push(A),A}linkTo(e){this.linkedTo.push(e),this.zones.forEach(A=>A.useCount++)}unlinkFrom(e){let A=this.linkedTo.indexOf(e);if(A<0){sA(`Cannot unlink ${e.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(A,1),this.zones.forEach(t=>t.useCount--)}deleteUnusedZones(){this.zones=this.zones.filter(e=>{let A=e.useCount>0;return A||e.sample.unlinkFrom(this),A})}delete(){if(this.useCount>0)throw new Error(`Cannot delete an instrument that is used by: ${this.linkedTo.map(e=>e.name).toString()}.`);this.zones.forEach(e=>e.sample.unlinkFrom(this))}deleteZone(e,A=!1){let t=this.zones[e];return t.useCount-=1,t.useCount<1||A?(t.sample.unlinkFrom(this),this.zones.splice(e,1),!0):!1}globalize(){let e=this.globalZone;for(let n=0;n<58;n++){if(Ho.has(n))continue;n=n;let s={},a=x[n]?.def||0;s[a]=0;for(let i of this.zones){let I=i.getGenerator(n,void 0);I!==void 0?s[I]===void 0?s[I]=1:s[I]++:s[a]++;let o;switch(n){default:continue;case r.decayVolEnv:o=r.keyNumToVolEnvDecay;break;case r.holdVolEnv:o=r.keyNumToVolEnvHold;break;case r.decayModEnv:o=r.keyNumToModEnvDecay;break;case r.holdModEnv:o=r.keyNumToModEnvHold}if(i.getGenerator(o,void 0)!==void 0){s={};break}}if(Object.keys(s).length>0){let I=Object.entries(s).reduce((g,B)=>g[1]<B[1]?B:g,["0",0]),o=parseInt(I[0]);o!==a&&e.setGenerator(n,o,!1),this.zones.forEach(g=>{let B=g.getGenerator(n,void 0);B!==void 0?B===o&&g.setGenerator(n,null):o!==a&&g.setGenerator(n,a)})}}let t=this.zones[0].modulators.map(n=>EA.copyFrom(n));for(let n of t){let s=!0;for(let a of this.zones){if(!s)continue;a.modulators.find(I=>EA.isIdentical(I,n))||(s=!1)}if(s){e.addModulators(EA.copyFrom(n));for(let a of this.zones){let i=a.modulators.find(I=>EA.isIdentical(I,n));i&&i.transformAmount===n.transformAmount&&a.modulators.splice(a.modulators.indexOf(i),1)}}}}getSize(){let e=this.zones.reduce((t,n)=>n.modulators.length+t,0)+this.globalZone.modulators.length,A=this.zones.reduce((t,n)=>n.getGenCount()+t,0)+this.globalZone.getGenCount();return{mod:e*me,bag:(this.zones.length+1)*Jt,gen:A*Ct,hdr:la}}write(e,A,t,n,s,a){p(`%cWriting ${this.name}...`,c.info),kA(n.pdta,this.name.substring(0,20),20),kA(n.xdta,this.name.substring(20),20),J(n.pdta,s.hdr&65535),J(n.xdta,s.hdr>>>16),s.hdr+=this.zones.length+1,this.globalZone.write(e,A,t,s,a),this.zones.forEach(i=>i.write(e,A,t,s,a))}},da=38,pe=class{parentSoundBank;name="";program=0;bankMSB=0;bankLSB=0;isGMGSDrum=!1;zones=[];globalZone;library=0;genre=0;morphology=0;constructor(e,A=new Ba){this.parentSoundBank=e,this.globalZone=A}get isXGDrums(){return this.parentSoundBank.isXGBank&&fA.isXGDrums(this.bankMSB)}get isAnyDrums(){let e=this.parentSoundBank.isXGBank;return this.isGMGSDrum||e&&fA.isXGDrums(this.bankMSB)&&this.bankMSB!==126}delete(){this.zones.forEach(e=>e.instrument?.unlinkFrom(this))}deleteZone(e){this.zones[e]?.instrument?.unlinkFrom(this),this.zones.splice(e,1)}createZone(e){let A=new Ca(this,e);return this.zones.push(A),A}preload(e,A){for(let t=e;t<A+1;t++)for(let n=0;n<128;n++)this.getSynthesisData(t,n).forEach(s=>{s.sample.getAudioData()})}matches(e){return te.matches(this,e)}getSize(){let e=this.zones.reduce((t,n)=>n.modulators.length+t,0)+this.globalZone.modulators.length,A=this.zones.reduce((t,n)=>n.getGenCount()+t,0)+this.globalZone.getGenCount();return{mod:e*me,bag:(this.zones.length+1)*Jt,gen:A*Ct,hdr:da}}getSynthesisData(e,A){if(this.zones.length<1)return[];function t(d,h){return h>=d.min&&h<=d.max}function n(d,h){d.push(...h.filter(C=>!d.find(Q=>Q.generatorType===C.generatorType)))}function s(d,h){d.push(...h.filter(C=>!d.find(Q=>EA.isIdentical(C,Q))))}let a=[],i=[...this.globalZone.generators],I=[...this.globalZone.modulators],o=this.globalZone.keyRange,g=this.globalZone.velRange;return this.zones.filter(d=>t(d.hasKeyRange?d.keyRange:o,e)&&t(d.hasVelRange?d.velRange:g,A)).forEach(d=>{let h=d.instrument;if(!h||h.zones.length<1)return;let C=d.generators,Q=d.modulators,m=[...h.globalZone.generators],y=[...h.globalZone.modulators],F=h.globalZone.keyRange,k=h.globalZone.velRange;h.zones.filter(v=>t(v.hasKeyRange?v.keyRange:F,e)&&t(v.hasVelRange?v.velRange:k,A)).forEach(v=>{let L=[...v.generators],E=[...v.modulators];n(C,i),n(L,m),s(Q,I),s(E,y),s(E,this.parentSoundBank.defaultModulators);let X=[...E];for(let O of Q){let nA=X.findIndex($=>EA.isIdentical(O,$));nA!==-1?X[nA]=X[nA].sumTransform(O):X.push(O)}v.sample&&a.push({instrumentGenerators:L,presetGenerators:C,modulators:X,sample:v.sample})})}),a}toMIDIString(){return te.toMIDIString(this)}toString(){return te.toNamedMIDIString(this)}toFlattenedInstrument(){let e=(g,B)=>{g.push(...B.filter(d=>!g.find(h=>h.generatorType===d.generatorType)))},A=(g,B)=>({min:Math.max(g.min,B.min),max:Math.min(g.max,B.max)}),t=(g,B)=>{g.push(...B.filter(d=>!g.find(h=>EA.isIdentical(d,h))))},n=new dt;n.name=this.name;let s=[],a=[],i=this.globalZone;s.push(...i.generators),a.push(...i.modulators);let I=i.keyRange,o=i.velRange;for(let g of this.zones){if(!g.instrument)throw new Error("No instrument in a preset zone.");let B=g.keyRange;g.hasKeyRange||(B=I);let d=g.velRange;g.hasVelRange||(d=o);let h=g.generators.map(L=>new FA(L.generatorType,L.generatorValue));e(h,s);let C=[...g.modulators];t(C,a);let Q=g.instrument,m=Q.zones,y=[],F=[],k=Q.globalZone;y.push(...k.generators),F.push(...k.modulators);let D=k.keyRange,v=k.velRange;for(let L of m){if(!L.sample)throw new Error("No sample in an instrument zone.");let E=L.keyRange;L.hasKeyRange||(E=D);let X=L.velRange;if(L.hasVelRange||(X=v),E=A(E,B),X=A(X,d),E.max<E.min||X.max<X.min)continue;let O=L.generators.map(z=>new FA(z.generatorType,z.generatorValue));e(O,y);let nA=[...L.modulators];t(nA,F);let $=[...nA];for(let z of C){let tA=$.findIndex(rA=>EA.isIdentical(z,rA));tA!==-1?$[tA]=$[tA].sumTransform(z):$.push(z)}let V=O.map(z=>new FA(z.generatorType,z.generatorValue));for(let z of h){if(z.generatorType===r.velRange||z.generatorType===r.keyRange||z.generatorType===r.instrument||z.generatorType===r.endOper||z.generatorType===r.sampleModes)continue;let tA=O.findIndex(rA=>rA.generatorType===z.generatorType);if(tA!==-1){let rA=V[tA].generatorValue+z.generatorValue;V[tA]=new FA(z.generatorType,rA)}else{let rA=x[z.generatorType].def+z.generatorValue;V.push(new FA(z.generatorType,rA))}}V=V.filter(z=>z.generatorType!==r.sampleID&&z.generatorType!==r.keyRange&&z.generatorType!==r.velRange&&z.generatorType!==r.endOper&&z.generatorType!==r.instrument&&z.generatorValue!==x[z.generatorType].def);let q=n.createZone(L.sample);q.keyRange=E,q.velRange=X,q.keyRange.min===0&&q.keyRange.max===127&&(q.keyRange.min=-1),q.velRange.min===0&&q.velRange.max===127&&(q.velRange.min=-1),q.addGenerators(...V),q.addModulators(...$)}}return n}write(e,A,t,n,s,a){p(`%cWriting ${this.name}...`,c.info),kA(n.pdta,this.name.substring(0,20),20),kA(n.xdta,this.name.substring(20),20),J(n.pdta,this.program);let i=this.bankMSB;this.isGMGSDrum?i=128:this.bankMSB===0&&(i=this.bankLSB),J(n.pdta,i),n.xdta.currentIndex+=4,J(n.pdta,s.hdr&65535),J(n.xdta,s.hdr>>16),gA(n.pdta,this.library),gA(n.pdta,this.genre),gA(n.pdta,this.morphology),n.xdta.currentIndex+=12,s.hdr+=this.zones.length+1,this.globalZone.write(e,A,t,s,a),this.zones.forEach(I=>I.write(e,A,t,s,a))}};function Ds(e,A){let t;return A?t=e.find(n=>n.isXGDrums):t=e.find(n=>n.isGMGSDrum),t||(e.find(n=>n.isAnyDrums)??e[0])}function Qa(e,A,t){if(e.length<1)throw new Error("No presets!");A.isGMGSDrum&&fA.isSystemXG(t)&&(A={...A,isGMGSDrum:!1,bankLSB:0,bankMSB:fA.getDrumBank(t)});let{isGMGSDrum:n,bankLSB:s,bankMSB:a,program:i}=A,I=fA.isSystemXG(t),o=fA.isXGDrums(a)&&I,g=e.find(C=>C.matches(A));if(g&&(!o||o&&g.isXGDrums))return g;let B=C=>{p(`%cPreset %c${te.toMIDIString(A)}%c not found. (${t}) Replaced with %c${C.toString()}`,c.warn,c.unrecognized,c.warn,c.value)};if(n){let C=e.find(Q=>Q.isGMGSDrum&&Q.program===i);return C||(C=e.find(Q=>Q.isAnyDrums&&Q.program===i),C)?(B(C),C):(C=Ds(e,!1),B(C),C)}if(o){let C=e.find(Q=>Q.program===i&&Q.isXGDrums);return C||(C=e.find(Q=>Q.isAnyDrums&&Q.program===i),C)?(B(C),C):(C=Ds(e,!0),B(C),C)}let d=e.filter(C=>C.program===i&&!C.isAnyDrums);if(d.length<1)return B(e[0]),e[0];if(I?g=d.find(C=>C.bankLSB===s):g=d.find(C=>C.bankMSB===a),g)return B(g),g;let h=Math.max(a,s);return g=d.find(C=>C.bankLSB===h||C.bankMSB===h),g?(B(g),g):(B(d[0]),d[0])}var Yo=class extends pe{constructor(e,A){super(e.parentSoundBank,e.globalZone),this.bankMSB=fA.addBankOffset(e.bankMSB,A,e.isXGDrums),this.name=e.name,this.bankLSB=e.bankLSB,this.isGMGSDrum=e.isGMGSDrum,this.program=e.program,this.genre=e.genre,this.morphology=e.morphology,this.library=e.library,this.zones=e.zones}},Po=class{soundBankList=[];presetListChangeCallback;selectablePresetList=[];constructor(e){this.presetListChangeCallback=e}_presetList=[];get presetList(){return[...this._presetList]}get priorityOrder(){return this.soundBankList.map(e=>e.id)}set priorityOrder(e){this.soundBankList.sort((A,t)=>e.indexOf(A.id)-e.indexOf(t.id)),this.generatePresetList()}deleteSoundBank(e){if(this.soundBankList.length===0){sA("1 soundbank left. Aborting!");return}let A=this.soundBankList.findIndex(t=>t.id===e);if(A===-1)throw new Error(`No sound bank with id "${e}"`);this.soundBankList.splice(A,1),this.generatePresetList()}addSoundBank(e,A,t=0){let n=this.soundBankList.find(s=>s.id===A);n!==void 0?(n.soundBank=e,n.bankOffset=t):this.soundBankList.push({id:A,soundBank:e,bankOffset:t}),this.generatePresetList()}getPreset(e,A){if(this.soundBankList.length<1)throw new Error("No sound banks! Did you forget to add one?");return Qa(this.selectablePresetList,e,A)}destroy(){this.soundBankList.forEach(e=>{e.soundBank.destroySoundBank()}),this.soundBankList=[]}generatePresetList(){let e=new Array,A=new Set;this.soundBankList.forEach(t=>{let n=t.soundBank,s=t.bankOffset;n.presets.forEach(a=>{let i=new Yo(a,s);A.has(i.toMIDIString())||(A.add(i.toMIDIString()),e.push(i))})}),e.sort(te.sorter.bind(te)),this.selectablePresetList=e,this._presetList=e.map(t=>({bankMSB:t.bankMSB,bankLSB:t.bankLSB,program:t.program,isGMGSDrum:t.isGMGSDrum,name:t.name,isAnyDrums:t.isAnyDrums})),this.presetListChangeCallback()}},Jo=.05,qo=3070,Ko=2e3,ws=Math.PI/2,Nt=-500,ua=500,os=ua-Nt,fa=new Float32Array(os+1),ma=new Float32Array(os+1);for(let e=Nt;e<=ua;e++){let A=(e-Nt)/os,t=e-Nt;fa[t]=Math.cos(ws*A),ma[t]=Math.sin(ws*A)}function Oo(e,A,t,n,s,a,i,I,o){if(isNaN(A[0]))return;let g;e.overridePan?g=e.overridePan:(e.currentPan+=(e.modulatedGenerators[r.pan]-e.currentPan)*this.synthProps.panSmoothingFactor,g=e.currentPan);let B=this.synthProps.masterParameters.masterGain*this.synthProps.midiVolume*e.gain,d=~~(g+500),h=fa[d]*B*this.synthProps.panLeft,C=ma[d]*B*this.synthProps.panRight;if(this.synth.enableEffects){let Q=e.modulatedGenerators[r.reverbEffectsSend];if(Q>0){let y=this.synthProps.masterParameters.reverbGain*this.synthProps.reverbSend*B*(Q/qo);for(let F=0;F<A.length;F++){let k=F+o;s[k]+=y*A[F],a[k]+=y*A[F]}}let m=e.modulatedGenerators[r.chorusEffectsSend];if(m>0){let y=this.synthProps.masterParameters.chorusGain*this.synthProps.chorusSend*(m/Ko),F=h*y,k=C*y;for(let D=0;D<A.length;D++){let v=D+o;i[v]+=F*A[D],I[v]+=k*A[D]}}}if(h>0)for(let Q=0;Q<A.length;Q++)t[Q+o]+=h*A[Q];if(C>0)for(let Q=0;Q<A.length;Q++)n[Q+o]+=C*A[Q]}var Vo=.1,Xt=class Et{static cachedCoefficients=[];resonanceCb=0;currentInitialFc=13500;a0=0;a1=0;a2=0;a3=0;a4=0;x1=0;x2=0;y1=0;y2=0;lastTargetCutoff=1/0;initialized=!1;sampleRate;maxCutoff;constructor(A){this.sampleRate=A,this.maxCutoff=A*.45}static apply(A,t,n,s){let a=A.modulatedGenerators[r.initialFilterFc],i=A.filter;i.initialized?i.currentInitialFc+=(a-i.currentInitialFc)*s:(i.initialized=!0,i.currentInitialFc=a);let I=i.currentInitialFc+n,o=A.modulatedGenerators[r.initialFilterQ];if(i.currentInitialFc>13499&&I>13499&&o===0){i.currentInitialFc=13500;return}(Math.abs(i.lastTargetCutoff-I)>1||i.resonanceCb!==o)&&(i.lastTargetCutoff=I,i.resonanceCb=o,Et.calculateCoefficients(i,I));for(let g=0;g<t.length;g++){let B=t[g],d=i.a0*B+i.a1*i.x1+i.a2*i.x2-i.a3*i.y1-i.a4*i.y2;i.x2=i.x1,i.x1=B,i.y2=i.y1,i.y1=d,t[g]=d}}static calculateCoefficients(A,t){t=~~t;let n=A.resonanceCb,s=Et.cachedCoefficients?.[n]?.[t];if(s!==void 0){A.a0=s.a0,A.a1=s.a1,A.a2=s.a2,A.a3=s.a3,A.a4=s.a4;return}let a=Nn(t);a=Math.min(a,A.maxCutoff);let i=n/10,I=Ae(-(i-3.01)),o=1/Math.sqrt(Ae(-i)),g=2*Math.PI*a/A.sampleRate,B=Math.cos(g),d=Math.sin(g)/(2*I),h=(1-B)*o,C=h/2,Q=C,m=1+d,y=-2*B,F=1-d,k={a0:C/m,a1:h/m,a2:Q/m,a3:y/m,a4:F/m};A.a0=k.a0,A.a1=k.a1,A.a2=k.a2,A.a3=k.a3,A.a4=k.a4,Et.cachedCoefficients[n]??=[],Et.cachedCoefficients[n][t]=k}},Hn=new Xt(44100);Hn.resonanceCb=0;for(let e=1500;e<13500;e++)Hn.currentInitialFc=e,Xt.calculateCoefficients(Hn,e);var Fs={enableEventSystem:!0,initialTime:0,enableEffects:!0};function Xo(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 Zo(e){let A=[];for(let n of this.midiChannels)for(let s of n.voices)if(!s.finished){let a=Xo(n,s);A.push({channel:n,voice:s,priority:a})}A.sort((n,s)=>n.priority-s.priority);let t=A.slice(0,e);for(let{channel:n,voice:s}of t){let a=n.voices.indexOf(s);a>-1&&n.voices.splice(a,1)}}var Sn=1,Yn=new Float32Array(1e3);for(let e=0;e<Yn.length;e++)Yn[e]=Ia(0,QA.convex,e/1e3);var _e=class Pn{attackDuration=0;decayDuration=0;holdDuration=0;releaseDuration=0;sustainLevel=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;releaseStartLevel=0;currentValue=0;static startRelease(A){Pn.recalculate(A)}static recalculate(A){let t=A.modulationEnvelope;A.isInRelease&&(t.releaseStartLevel=Pn.getValue(A,A.releaseStartTime,!0)),t.sustainLevel=1-A.modulatedGenerators[r.sustainModEnv]/1e3,t.attackDuration=Qe(A.modulatedGenerators[r.attackModEnv]);let n=(60-A.midiNote)*A.modulatedGenerators[r.keyNumToModEnvDecay],s=Qe(A.modulatedGenerators[r.decayModEnv]+n);t.decayDuration=s*(1-t.sustainLevel);let a=(60-A.midiNote)*A.modulatedGenerators[r.keyNumToModEnvHold];t.holdDuration=Qe(a+A.modulatedGenerators[r.holdModEnv]);let i=Qe(Math.max(A.modulatedGenerators[r.releaseModEnv],-7200));t.releaseDuration=i*t.releaseStartLevel,t.delayEnd=A.startTime+Qe(A.modulatedGenerators[r.delayModEnv]),t.attackEnd=t.delayEnd+t.attackDuration,t.holdEnd=t.attackEnd+t.holdDuration,t.decayEnd=t.holdEnd+t.decayDuration}static getValue(A,t,n=!1){let s=A.modulationEnvelope;return A.isInRelease&&!n?s.releaseStartLevel===0?0:Math.max(0,(1-(t-A.releaseStartTime)/s.releaseDuration)*s.releaseStartLevel):(t<s.delayEnd?s.currentValue=0:t<s.attackEnd?s.currentValue=Yn[~~((1-(s.attackEnd-t)/s.attackDuration)*1e3)]:t<s.holdEnd?s.currentValue=Sn:t<s.decayEnd?s.currentValue=(1-(s.decayEnd-t)/s.decayDuration)*(s.sustainLevel-Sn)+Sn:s.currentValue=s.sustainLevel,s.currentValue)}},Sa=class{sampleData;playbackStep=0;cursor=0;rootKey=0;loopStart=0;loopEnd=0;end=0;loopingMode=0;isLooping=!1;constructor(e,A,t,n,s,a,i,I){this.sampleData=e,this.playbackStep=A,this.cursor=t,this.rootKey=n,this.loopStart=s,this.loopEnd=a,this.end=i,this.loopingMode=I,this.isLooping=this.loopingMode===1||this.loopingMode===3}},zo=-2320,Wo=-1130,Jn=class pa{sample;filter;gain=1;generators;modulators=[];resonanceOffset=0;modulatedGenerators;finished=!1;isInRelease=!1;velocity=0;midiNote=0;pressure=0;targetKey=0;modulationEnvelope=new _e;volumeEnvelope;startTime=0;releaseStartTime=1/0;currentTuningCents=0;currentTuningCalculated=1;currentPan=0;realKey;portamentoFromKey=-1;portamentoDuration=0;overridePan=0;exclusiveClass=0;constructor(A,t,n,s,a,i,I,o,g){this.sample=t,this.generators=o,this.exclusiveClass=this.generators[r.exclusiveClass],this.modulatedGenerators=new Int16Array(o),this.modulators=g,this.filter=new Xt(A),this.velocity=s,this.midiNote=n,this.startTime=a,this.targetKey=i,this.realKey=I,this.volumeEnvelope=new be(A,o[r.sustainVolEnv])}static copyFrom(A,t,n){let s=A.sample,a=new Sa(s.sampleData,s.playbackStep,s.cursor,s.rootKey,s.loopStart,s.loopEnd,s.end,s.loopingMode);return new pa(A.volumeEnvelope.sampleRate,a,A.midiNote,A.velocity,t,A.targetKey,n,new Int16Array(A.generators),A.modulators.map(EA.copyFrom.bind(EA)))}exclusiveRelease(A){this.release(A,Wa),this.modulatedGenerators[r.releaseVolEnv]=zo,this.modulatedGenerators[r.releaseModEnv]=Wo,be.recalculate(this),_e.recalculate(this)}release(A,t=za){this.releaseStartTime=A,this.releaseStartTime-this.startTime<t&&(this.releaseStartTime=this.startTime+t)}};function _o(e,A,t,n){let s=e.getSynthesisData(A,t).reduce((a,i)=>{if(i.sample.getAudioData()===void 0)return sA(`Discarding invalid sample: ${i.sample.name}`),a;let I=new Int16Array(Mn);for(let m=0;m<60;m++)I[m]=xo(m,i.presetGenerators,i.instrumentGenerators);I[r.initialAttenuation]=Math.floor(I[r.initialAttenuation]*.4);let o=i.sample.originalKey;I[r.overridingRootKey]>-1&&(o=I[r.overridingRootKey]);let g=A;I[r.keyNum]>-1&&(g=I[r.keyNum]);let B=i.sample.loopStart,d=i.sample.loopEnd,h=I[r.sampleModes],C=i.sample.getAudioData(),Q=new Sa(C,i.sample.sampleRate/this.sampleRate*Math.pow(2,i.sample.pitchCorrection/1200),0,o,B,d,Math.floor(C.length)-1,h);return I[r.velocity]>-1&&(t=I[r.velocity]),a.push(new Jn(this.sampleRate,Q,A,t,this.currentSynthTime,g,n,I,i.modulators.map(EA.copyFrom.bind(EA)))),a},[]);return this.setCachedVoice(e,A,t,s),s.map(a=>Jn.copyFrom(a,this.currentSynthTime,n))}function jo(e,A,t,n){let s=this.midiChannels[e],a=this.keyModifierManager.hasOverridePatch(e,A),i=s.preset;if(!i)return sA(`No preset for channel ${e}!`),[];let I={...i};a&&(I=this.keyModifierManager.getPatch(e,A));let o=this.getCachedVoice(I,A,t);return o!==void 0?o.map(g=>Jn.copyFrom(g,this.currentSynthTime,n)):(a&&(i=this.soundBankManager.getPreset(I,this.privateProps.masterParameters.midiSystem)),this.getVoicesForPreset(i,A,t,n))}function Gs(e,A,t){let n=e,s=A<<7|t;return e===127&&A===127&&t===127?{midiNote:-1,centTuning:null}:{midiNote:n,centTuning:s*.0061}}function $o(e,A=0){let t=e[0];if(this.privateProps.masterParameters.deviceID!==Be&&e[1]!==127&&this.privateProps.masterParameters.deviceID!==e[1])return;function n(a,i,I,o){p(`%cChannel %c${a}%c ${I}. %c${i} ${o}%c, with %c${MA(e)}`,c.info,c.recognized,c.info,c.value,c.info,c.value)}function s(){p(`%cUnrecognized Roland %cGS %cSysEx: %c${MA(e)}`,c.warn,c.recognized,c.warn,c.unrecognized)}switch(t){default:p(`%cUnrecognized SysEx: %c${MA(e)}`,c.warn,c.unrecognized);break;case 126:case 127:switch(e[2]){case 4:{let a;switch(e[3]){case 1:{let i=e[5]<<7|e[4];this.setMIDIVolume(i/16384),p(`%cMaster Volume. Volume: %c${i}`,c.info,c.value);break}case 2:{let I=((e[5]<<7|e[4])-8192)/8192;this.setMasterParameter("masterPan",I),p(`%cMaster Pan. Pan: %c${I}`,c.info,c.value);break}case 3:{let i=(e[5]<<7|e[6])-8192;a=Math.floor(i/81.92),this.setMasterTuning(a),p(`%cMaster Fine Tuning. Cents: %c${a}`,c.info,c.value);break}case 4:{a=(e[5]-64)*100,this.setMasterTuning(a),p(`%cMaster Coarse Tuning. Cents: %c${a}`,c.info,c.value);break}default:p(`%cUnrecognized MIDI Device Control Real-time message: %c${MA(e)}`,c.warn,c.unrecognized)}break}case 9:e[3]===1?(p("%cGM1 system on",c.info),this.setMasterParameter("midiSystem","gm")):e[3]===3?(p("%cGM2 system on",c.info),this.setMasterParameter("midiSystem","gm2")):(p("%cGM system off, defaulting to GS",c.info),this.setMasterParameter("midiSystem","gs"));break;case 8:{let a=4;switch(e[3]){case 1:{let i=e[a++],I=ee(e,16,a);if(a+=16,e.length<384){sA(`The Bulk Tuning Dump is too short! (${e.length} bytes, at least 384 are expected)`);return}for(let o=0;o<128;o++)this.privateProps.tunings[i][o]=Gs(e[a++],e[a++],e[a++]);p(`%cBulk Tuning Dump %c${I}%c Program: %c${i}`,c.info,c.value,c.info,c.recognized);break}case 2:case 7:{e[3]===7&&a++;let i=e[a++],I=e[a++];for(let o=0;o<I;o++)this.privateProps.tunings[i][e[a++]]=Gs(e[a++],e[a++],e[a++]);p(`%cSingle Note Tuning. Program: %c${i}%c Keys affected: %c${I}`,c.info,c.recognized,c.info,c.recognized);break}case 9:case 8:{let i=new Int8Array(12);if(e[3]===8)for(let I=0;I<12;I++)i[I]=e[7+I]-64;else for(let I=0;I<24;I+=2){let o=(e[7+I]<<7|e[8+I])-8192;i[I/2]=Math.floor(o/81.92)}(e[4]&1)===1&&this.midiChannels[14+A].setOctaveTuning(i),(e[4]>>1&1)===1&&this.midiChannels[15+A].setOctaveTuning(i);for(let I=0;I<7;I++)(e[5]>>I&1)===1&&this.midiChannels[7+I+A].setOctaveTuning(i);for(let I=0;I<7;I++)(e[6]>>I&1)===1&&this.midiChannels[I+A].setOctaveTuning(i);p(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${i.join(" ")}`,c.info,c.value);break}default:p(`%cUnrecognized MIDI Tuning standard message: %c${MA(e)}`,c.warn,c.unrecognized);break}break}default:p(`%cUnrecognized MIDI Realtime/non realtime message: %c${MA(e)}`,c.warn,c.unrecognized)}break;case 65:if(e[2]===66&&e[3]===18){let a=e[7];if(e[4]===64||e[4]===0&&e[6]===127){if((e[5]&16)>0){let i=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A,I=this.midiChannels[i];switch(e[6]){default:s();break;case 21:{let o=a>0&&e[5]>>4>0;I.setGSDrums(o),p(`%cChannel %c${i}%c ${o?"is now a drum channel":"now isn't a drum channel"}%c via: %c${MA(e)}`,c.info,c.value,c.recognized,c.info,c.value);return}case 22:{let o=a-64;I.setCustomController(IA.channelKeyShift,o),n(i,o,"key shift","keys");return}case 28:{let o=a;o===0?(I.randomPan=!0,p(`%cRandom pan is set to %cON%c for %c${i}`,c.info,c.recognized,c.info,c.value)):(I.randomPan=!1,I.controllerChange(S.pan,o));break}case 33:I.controllerChange(S.chorusDepth,a);break;case 34:I.controllerChange(S.reverbDepth,a);break;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:{let o=e.length-9,g=new Int8Array(12);for(let d=0;d<o;d++)g[d]=e[d+7]-64;I.setOctaveTuning(g);let B=a-64;n(i,g.join(" "),"octave scale tuning","cents"),I.setTuning(B);break}}return}else if((e[5]&32)>0){let i=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A,I=this.midiChannels[i],o=a-64,g=o/64,B=a/128,d=(h,C,Q=!1)=>{switch(e[6]&15){case 0:h===mA+j.pitchWheel?(I.controllerChange(S.registeredParameterMSB,0),I.controllerChange(S.registeredParameterLSB,0),I.controllerChange(S.dataEntryMSB,Math.floor(o))):(I.sysExModulators.setModulator(h,r.fineTune,o*100,Q),n(i,o,`${C} pitch control`,"semitones"));break;case 1:I.sysExModulators.setModulator(h,r.initialFilterFc,g*9600,Q),n(i,g*9600,`${C} pitch control`,"cents");break;case 2:I.sysExModulators.setModulator(h,r.initialAttenuation,g*960,Q),n(i,g*960,`${C} amplitude`,"cB");break;case 4:I.sysExModulators.setModulator(h,r.vibLfoToPitch,B*600,Q),n(i,B*600,`${C} LFO1 pitch depth`,"cents");break;case 5:I.sysExModulators.setModulator(h,r.vibLfoToFilterFc,B*2400,Q),n(i,B*2400,`${C} LFO1 filter depth`,"cents");break;case 6:I.sysExModulators.setModulator(h,r.vibLfoToVolume,g*960,Q),n(i,g*960,`${C} LFO1 amplitude depth`,"cB");break;case 8:I.sysExModulators.setModulator(h,r.modLfoToPitch,B*600,Q),n(i,B*600,`${C} LFO2 pitch depth`,"cents");break;case 9:I.sysExModulators.setModulator(h,r.modLfoToFilterFc,B*2400,Q),n(i,B*2400,`${C} LFO2 filter depth`,"cents");break;case 10:I.sysExModulators.setModulator(h,r.modLfoToVolume,g*960,Q),n(i,g*960,`${C} LFO2 amplitude depth`,"cB");break}};switch(e[6]&240){default:s();break;case 0:d(S.modulationWheel,"mod wheel");break;case 16:d(mA+j.pitchWheel,"pitch wheel",!0);break;case 32:d(mA+j.channelPressure,"channel pressure");break;case 48:d(mA+j.polyPressure,"poly pressure");break}return}else if(e[5]===0){switch(e[6]){default:s();break;case 127:a===0?(p("%cGS Reset received!",c.info),this.resetAllControllers(!1),this.setMasterParameter("midiSystem","gs")):a===127&&(p("%cGS system off, switching to GM2",c.info),this.resetAllControllers(!1),this.setMasterParameter("midiSystem","gm2"));break;case 6:p(`%cRoland GS Master Pan set to: %c${a}%c with: %c${MA(e)}`,c.info,c.value,c.info,c.value),this.setMasterParameter("masterPan",(a-64)/64);break;case 4:p(`%cRoland GS Master Volume set to: %c${a}%c with: %c${MA(e)}`,c.info,c.value,c.info,c.value),this.setMIDIVolume(a/127);break;case 5:{let i=a-64;p(`%cRoland GS Master Key-Shift set to: %c${i}%c with: %c${MA(e)}`,c.info,c.value,c.info,c.value),this.setMasterTuning(i*100);break}}return}else if(e[5]===1)switch(e[6]){default:s();break;case 0:{let i=ee(e,16,7);p(`%cGS Patch name: %c${i}`,c.info,c.value);break}case 51:p(`%cGS Reverb level: %c${a}`,c.info,c.value),this.privateProps.reverbSend=a/64;break;case 48:case 49:case 50:case 52:case 53:case 55:p(`%cUnsupported GS Reverb Parameter: %c${e[6].toString(16)}`,c.warn,c.unrecognized);break;case 58:p(`%cGS Chorus level: %c${a}`,c.info,c.value),this.privateProps.chorusSend=a/64;break;case 56:case 57:case 59:case 60:case 61:case 62:case 63:case 64:p(`%cUnsupported GS Chorus Parameter: %c${e[6].toString(16)}`,c.warn,c.unrecognized);break}}else s();return}else if(e[2]===69&&e[3]===18){if(e[4]===16&&e[6]===0)if(e[5]===0){let a=new Uint8Array(e.slice(7,e.length-2));this.privateProps.callEvent("synthDisplay",{displayData:a,displayType:hn.soundCanvasText})}else if(e[5]===1){let a=new Uint8Array(e.slice(7,e.length-3));this.privateProps.callEvent("synthDisplay",{displayData:a,displayType:hn.soundCanvasDotMatrix}),p(`%cRoland SC Display Dot Matrix via: %c${MA(e)}`,c.info,c.value)}else s()}else if(e[2]===22&&e[3]===18&&e[4]===16){this.setMIDIVolume(e[7]/100),p(`%cRoland Master Volume control set to: %c${e[7]}%c via: %c${MA(e)}`,c.info,c.value,c.info,c.value);return}else{p(`%cUnrecognized Roland SysEx: %c${MA(e)}`,c.warn,c.unrecognized);return}break;case 67:if(e[2]===76)if(e[3]===0&&e[4]===0)switch(e[5]){case 4:{let a=e[6];this.setMIDIVolume(a/127),p(`%cXG master volume. Volume: %c${a}`,c.info,c.recognized);break}case 6:{let a=e[6]-64;this.setMasterParameter("transposition",a),p(`%cXG master transpose. Volume: %c${a}`,c.info,c.recognized);break}case 126:p("%cXG system on",c.info),this.resetAllControllers(!1),this.setMasterParameter("midiSystem","xg");break}else if(e[3]===8){if(!fA.isSystemXG(this.privateProps.masterParameters.midiSystem))return;let a=e[4]+A;if(a>=this.midiChannels.length)return;let i=this.midiChannels[a],I=e[6];switch(e[5]){case 1:i.controllerChange(S.bankSelect,I);break;case 2:i.controllerChange(S.bankSelectLSB,I);break;case 3:i.programChange(I);break;case 8:{if(i.drumChannel)return;i.channelTransposeKeyShift=I-64;break}case 11:i.controllerChange(S.mainVolume,I);break;case 14:{let o=I;o===0?(i.randomPan=!0,p(`%cRandom pan is set to %cON%c for %c${a}`,c.info,c.recognized,c.info,c.value)):i.controllerChange(S.pan,o);break}case 19:i.controllerChange(S.reverbDepth,I);break;case 18:i.controllerChange(S.chorusDepth,I);break;default:p(`%cUnrecognized Yamaha XG Part Setup: %c${e[5].toString(16).toUpperCase()}`,c.warn,c.unrecognized)}}else if(e[3]===6&&e[4]===0){let a=new Uint8Array(e.slice(5,e.length-1));this.privateProps.callEvent("synthDisplay",{displayData:a,displayType:hn.yamahaXGText})}else fA.isSystemXG(this.privateProps.masterParameters.midiSystem)&&p(`%cUnrecognized Yamaha XG SysEx: %c${MA(e)}`,c.warn,c.unrecognized);else fA.isSystemXG(this.privateProps.masterParameters.midiSystem)&&p(`%cUnrecognized Yamaha SysEx: %c${MA(e)}`,c.warn,c.unrecognized);break}}var Rs=class qn{patch;lockPreset;lockedSystem;midiControllers;lockedControllers;customControllers;lockVibrato;channelVibrato;channelTransposeKeyShift;channelOctaveTuning;isMuted;drumChannel;channelNumber;constructor(A,t,n,s,a,i,I,o,g,B,d,h,C){this.patch=A,this.lockPreset=t,this.lockedSystem=n,this.midiControllers=s,this.lockedControllers=a,this.customControllers=i,this.lockVibrato=I,this.channelVibrato=o,this.channelTransposeKeyShift=g,this.channelOctaveTuning=B,this.isMuted=d,this.drumChannel=h,this.channelNumber=C}static copyFrom(A){return new qn({...A.patch},A.lockPreset,A.lockedSystem,A.midiControllers.slice(),[...A.lockedControllers],A.customControllers.slice(),A.lockVibrato,{...A.channelVibrato},A.channelTransposeKeyShift,A.channelOctaveTuning,A.isMuted,A.drumChannel,A.channelNumber)}static create(A,t){let n=A.midiChannels[t];return new qn({...n.patch,name:n?.preset?.name??"undefined"},n.lockPreset,n.lockedSystem,n.midiControllers.slice(),[...n.lockedControllers],n.customControllers.slice(),n.lockGSNRPNParams,{...n.channelVibrato},n.channelTransposeKeyShift,n.channelOctaveTuning.slice(),n.isMuted,n.drumChannel,t)}apply(A){let t=A.midiChannels[this.channelNumber];t.muteChannel(this.isMuted),t.setDrums(this.drumChannel),t.midiControllers.set(this.midiControllers),t.lockedControllers=this.lockedControllers,t.customControllers.set(this.customControllers),t.updateChannelTuning(),t.channelVibrato=this.channelVibrato,t.lockGSNRPNParams=this.lockVibrato,t.channelTransposeKeyShift=this.channelTransposeKeyShift,t.channelOctaveTuning=this.channelOctaveTuning,t.setPresetLock(!1),t.setPatch(this.patch),t.setPresetLock(this.lockPreset),t.lockedSystem=this.lockedSystem}};var Ai=class{keyMappings=[];addMapping(e,A,t){this.keyMappings[e]??=[],this.keyMappings[e][A]=t}deleteMapping(e,A){this.keyMappings[e]?.[A]!==void 0&&(this.keyMappings[e][A]=void 0)}clearMappings(){this.keyMappings=[]}setMappings(e){this.keyMappings=e}getMappings(){return this.keyMappings}getVelocity(e,A){return this.keyMappings[e]?.[A]?.velocity??-1}getGain(e,A){return this.keyMappings[e]?.[A]?.gain??1}hasOverridePatch(e,A){let t=this.keyMappings[e]?.[A]?.patch?.bankMSB;return t!==void 0&&t>=0}getPatch(e,A){let t=this.keyMappings[e]?.[A];if(t)return t.patch;throw new Error("No modifier.")}},is=class Kn{channelSnapshots;keyMappings;masterParameters;constructor(A,t,n){this.channelSnapshots=A,this.masterParameters=t,this.keyMappings=n}static create(A){let t=A.midiChannels.map((n,s)=>Rs.create(A,s));return new Kn(t,A.getAllMasterParameters(),A.keyModifierManager.getMappings())}static copyFrom(A){return new Kn(A.channelSnapshots.map(t=>Rs.copyFrom(t)),{...A.masterParameters},[...A.keyMappings])}apply(A){for(Object.entries(this.masterParameters).forEach(([n,s])=>{A.setMasterParameter(n,s)}),A.keyModifierManager.setMappings(this.keyMappings);A.midiChannels.length<this.channelSnapshots.length;)A.createMIDIChannel();this.channelSnapshots.forEach(n=>{n.apply(A)})}},ei={masterGain:_a,masterPan:0,voiceCap:Xa,interpolationType:vt.hermite,midiSystem:Os,monophonicRetriggerMode:!1,reverbGain:1,chorusGain:1,blackMIDIMode:!1,transposition:0,deviceID:Be},ti=class{tunings=[];masterParameters=ei;midiVolume=1;reverbSend=1;chorusSend=1;panLeft=.5;panRight=.5;defaultPreset;drumPreset;volumeEnvelopeSmoothingFactor;panSmoothingFactor;filterSmoothingFactor;eventCallbackHandler;getVoices;voiceKilling;cachedVoices=[];constructor(e,A,t,n,s,a){this.eventCallbackHandler=e,this.getVoices=A,this.voiceKilling=t,this.volumeEnvelopeSmoothingFactor=n,this.panSmoothingFactor=s,this.filterSmoothingFactor=a;for(let i=0;i<128;i++)this.tunings.push([])}callEvent(e,A){this.eventCallbackHandler(e,A)}};function pn(e,A,t){if(t<e)return 0;let n=(t-e)/(1/A)+.25;return Math.abs(n-~~(n+.5))*4-1}var ni=class On{static getSample(A,t,n){let s=A.currentTuningCalculated*A.sample.playbackStep;if(s===1){On.getSampleNearest(A,t,s);return}switch(n){case vt.hermite:this.getSampleHermite(A,t,s);return;case vt.linear:default:this.getSampleLinear(A,t,s);return;case vt.nearestNeighbor:On.getSampleNearest(A,t,s);return}}static getSampleLinear(A,t,n){let s=A.sample,a=s.cursor,i=s.sampleData;if(s.isLooping){let I=s.loopEnd-s.loopStart;for(let o=0;o<t.length;o++){for(;a>=s.loopEnd;)a-=I;let g=~~a,B=g+1;for(;B>=s.loopEnd;)B-=I;let d=a-g,h=i[B],C=i[g];t[o]=C+(h-C)*d,a+=n}}else for(let I=0;I<t.length;I++){let o=~~a,g=o+1;if(g>=s.end){A.finished=!0;return}let B=a-o,d=i[g],h=i[o];t[I]=h+(d-h)*B,a+=n}A.sample.cursor=a}static getSampleNearest(A,t,n){let s=A.sample,a=s.cursor,i=s.sampleData;if(s.isLooping){let I=s.loopEnd-s.loopStart;for(let o=0;o<t.length;o++){for(;a>=s.loopEnd;)a-=I;let g=~~a+1;for(;g>=s.loopEnd;)g-=I;t[o]=i[g],a+=n}}else for(let I=0;I<t.length;I++){let o=~~a+1;if(o>=s.end){A.finished=!0;return}t[I]=i[o],a+=n}s.cursor=a}static getSampleHermite(A,t,n){let s=A.sample,a=s.cursor,i=s.sampleData;if(s.isLooping){let I=s.loopEnd-s.loopStart;for(let o=0;o<t.length;o++){for(;a>=s.loopEnd;)a-=I;let g=~~a,B=g+1,d=g+2,h=g+3,C=a-g;B>=s.loopEnd&&(B-=I),d>=s.loopEnd&&(d-=I),h>=s.loopEnd&&(h-=I);let Q=i[g],m=i[B],y=i[d],F=i[h],k=(y-Q)*.5,D=m-y,v=k+D,L=v+D+(F-m)*.5,E=v+L;t[o]=((L*C-E)*C+k)*C+m,a+=n}}else for(let I=0;I<t.length;I++){let o=~~a,g=o+1,B=o+2,d=o+3,h=a-o;if(g>=s.end||B>=s.end||d>=s.end){A.finished=!0;return}let C=i[o],Q=i[g],m=i[B],y=i[d],F=(m-C)*.5,k=Q-m,D=F+k,v=D+k+(y-Q)*.5,L=D+v;t[I]=((v*h-L)*h+F)*h+Q,a+=n}A.sample.cursor=a}};function si(e,A,t,n,s,a,i,I,o,g){if(e.isInRelease||A>=e.releaseStartTime&&(e.isInRelease=!0,be.startRelease(e),_e.startRelease(e),e.sample.loopingMode===3&&(e.sample.isLooping=!1)),e.modulatedGenerators[r.initialAttenuation]>2500)return e.isInRelease&&(e.finished=!0),e.finished;let B=e.targetKey,d=e.modulatedGenerators[r.fineTune]+this.channelOctaveTuning[e.midiNote]+this.channelTuningCents,h=e.modulatedGenerators[r.coarseTune],C=this.synthProps.tunings[this.preset?.program??0]?.[e.realKey];if(C?.centTuning&&(B=C.midiNote,d+=C.centTuning),e.portamentoFromKey>-1){let $=Math.min((A-e.startTime)/e.portamentoDuration,1),V=B-e.portamentoFromKey;h-=V*(1-$)}d+=(B-e.sample.rootKey)*e.modulatedGenerators[r.scaleTuning];let Q=0,m=0,y=e.modulatedGenerators[r.vibLfoToPitch],F=e.modulatedGenerators[r.vibLfoToVolume],k=e.modulatedGenerators[r.vibLfoToFilterFc];if(y!==0||F!==0||k!==0){let $=e.startTime+Qe(e.modulatedGenerators[r.delayVibLFO]),V=Nn(e.modulatedGenerators[r.freqVibLFO]),q=pn($,V,A);d+=q*(y*this.customControllers[IA.modulationMultiplier]),m+=-q*F,Q+=q*k}let D=e.modulatedGenerators[r.modLfoToPitch],v=e.modulatedGenerators[r.modLfoToVolume],L=e.modulatedGenerators[r.modLfoToFilterFc];if(D!==0||L!==0||v!==0){let $=e.startTime+Qe(e.modulatedGenerators[r.delayModLFO]),V=Nn(e.modulatedGenerators[r.freqModLFO]),q=pn($,V,A);d+=q*(D*this.customControllers[IA.modulationMultiplier]),m+=-q*v,Q+=q*L}if(this.channelVibrato.depth>0){let $=pn(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,A);$&&(d+=$*this.channelVibrato.depth)}let E=e.modulatedGenerators[r.modEnvToPitch],X=e.modulatedGenerators[r.modEnvToFilterFc];if(X!==0||E!==0){let $=_e.getValue(e,A);Q+=$*X,d+=$*E}m-=e.resonanceOffset;let O=~~(d+h*100);O!==e.currentTuningCents&&(e.currentTuningCents=O,e.currentTuningCalculated=Math.pow(2,O/1200));let nA=new Float32Array(g);return e.sample.loopingMode===2&&!e.isInRelease?(be.apply(e,nA,m,this.synthProps.volumeEnvelopeSmoothingFactor),e.finished):(ni.getSample(e,nA,this.synthProps.masterParameters.interpolationType),Xt.apply(e,nA,Q,this.synthProps.filterSmoothingFactor),be.apply(e,nA,m,this.synthProps.volumeEnvelopeSmoothingFactor),this.panAndMixVoice(e,nA,t,n,s,a,i,I,o),e.finished)}var ue={pitchWheelRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},Ze={partParameter:1,awe32:127,SF2:120},Oe={vibratoRate:8,vibratoDepth:9,vibratoDelay:10,TVFFilterCutoff:32,TVFFilterResonance:33,EGAttackTime:99,EGReleaseTime:102};function ai(e){this.midiControllers[S.dataEntryMSB]=e<<7;let A=()=>{this.channelVibrato.delay===0&&this.channelVibrato.rate===0&&this.channelVibrato.depth===0&&(this.channelVibrato.depth=50,this.channelVibrato.rate=8,this.channelVibrato.delay=.6)},t=(n,s,a)=>{a.length>0&&(a=" "+a),p(`%c${n} for %c${this.channelNumber}%c is now set to %c${s}%c${a}.`,c.info,c.recognized,c.info,c.value,c.info)};switch(this.dataEntryState){default:case YA.Idle:break;case YA.NRPFine:{if(this.lockGSNRPNParams)return;let n=this.midiControllers[S.nonRegisteredParameterMSB]>>7,s=this.midiControllers[S.nonRegisteredParameterLSB]>>7,a=this.midiControllers[S.dataEntryLSB]>>7;switch(n){default:if(e===64)return;p(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${s.toString(16).toUpperCase()} 0x${s.toString(16).toUpperCase()})%c data value: %c${e}`,c.warn,c.recognized,c.warn,c.unrecognized,c.warn,c.value);break;case Ze.partParameter:switch(s){default:if(e===64)return;p(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${n.toString(16)} 0x${s.toString(16)})%c data value: %c${e}`,c.warn,c.recognized,c.warn,c.unrecognized,c.warn,c.value);break;case Oe.vibratoRate:if(e===64)return;A(),this.channelVibrato.rate=e/64*8,t("Vibrato rate",`${e} = ${this.channelVibrato.rate}`,"Hz");break;case Oe.vibratoDepth:if(e===64)return;A(),this.channelVibrato.depth=e/2,t("Vibrato depth",`${e} = ${this.channelVibrato.depth}`,"cents of detune");break;case Oe.vibratoDelay:if(e===64)return;A(),this.channelVibrato.delay=e/64/3,t("Vibrato delay",`${e} = ${this.channelVibrato.delay}`,"seconds");break;case Oe.TVFFilterCutoff:this.controllerChange(S.brightness,e),t("Filter cutoff",e.toString(),"");break;case Oe.EGAttackTime:this.controllerChange(S.attackTime,e),t("EG attack time",e.toString(),"");break;case Oe.EGReleaseTime:this.controllerChange(S.releaseTime,e),t("EG release time",e.toString(),"");break}break;case Ze.awe32:break;case Ze.SF2:{if(s>100)break;let i=this.customControllers[IA.sf2NPRNGeneratorLSB],I=(e<<7|a)-8192;this.setGeneratorOffset(i,I);break}}break}case YA.RPCoarse:case YA.RPFine:{let n=this.midiControllers[S.registeredParameterMSB]|this.midiControllers[S.registeredParameterLSB]>>7;switch(n){default:p(`%cUnrecognized RPN for %c${this.channelNumber}%c: %c(0x${n.toString(16)})%c data value: %c${e}`,c.warn,c.recognized,c.warn,c.unrecognized,c.warn,c.value);break;case ue.pitchWheelRange:this.midiControllers[mA+j.pitchWheelRange]=e<<7,t("Pitch wheel range",e.toString(),"semitones");break;case ue.coarseTuning:{let s=e-64;this.setCustomController(IA.channelTuningSemitones,s),t("Coarse tuning",s.toString(),"semitones");break}case ue.fineTuning:this.setTuning(e-64,!1);break;case ue.modulationDepth:this.setModulationDepth(e*100);break;case ue.resetParameters:this.resetParameters();break}}}}var oi=[r.delayModLFO,r.freqModLFO,r.delayVibLFO,r.freqVibLFO,r.delayModEnv,r.attackModEnv,r.holdModEnv,r.decayModEnv,r.sustainModEnv,r.releaseModEnv,r.delayVolEnv,r.attackVolEnv,r.holdVolEnv,r.decayVolEnv,r.sustainVolEnv,r.releaseVolEnv,r.fineTune,r.modLfoToPitch,r.vibLfoToPitch,r.modEnvToPitch,r.modLfoToVolume,r.initialFilterFc,r.initialFilterQ,r.modLfoToFilterFc,r.modEnvToFilterFc,r.chorusEffectsSend,r.reverbEffectsSend];function ii(e,A,t){let n=(h,C,Q)=>Math.max(C,Math.min(Q,h)),s=h=>Math.max(-32768,1200*Math.log2(h/1e3)),a=h=>6900+1200*Math.log2(h/440),i=t<<7|A;i-=8192;let I=oi[e];I||sA(`Invalid AWE32 LSB: %c${e}`,c.unrecognized);let o,g,B,d;switch(I){default:break;case r.delayModLFO:case r.delayVibLFO:case r.delayVolEnv:case r.delayModEnv:o=4*n(i,0,5900),this.setGeneratorOverride(I,s(o));break;case r.attackVolEnv:case r.attackModEnv:o=n(i,0,5940),this.setGeneratorOverride(I,s(o));break;case r.holdVolEnv:case r.holdModEnv:o=n(i,0,8191),this.setGeneratorOverride(I,s(o));break;case r.decayModEnv:case r.decayVolEnv:case r.releaseVolEnv:case r.releaseModEnv:o=4*n(i,0,5940),this.setGeneratorOverride(I,s(o));break;case r.freqVibLFO:case r.freqModLFO:g=.084*A,this.setGeneratorOverride(I,a(g),!0);break;case r.sustainVolEnv:case r.sustainModEnv:B=A*7.5,this.setGeneratorOverride(I,B);break;case r.fineTune:this.setGeneratorOverride(I,i,!0);break;case r.modLfoToPitch:case r.vibLfoToPitch:d=n(i,-127,127)*9.375,this.setGeneratorOverride(I,d,!0);break;case r.modEnvToPitch:d=n(i,-127,127)*9.375,this.setGeneratorOverride(I,d);break;case r.modLfoToVolume:B=1.875*A,this.setGeneratorOverride(I,B,!0);break;case r.initialFilterFc:{let h=4335+59*A;this.setGeneratorOverride(I,h,!0);break}case r.initialFilterQ:B=215*(A/127),this.setGeneratorOverride(I,B,!0);break;case r.modLfoToFilterFc:d=n(i,-64,63)*56.25,this.setGeneratorOverride(I,d,!0);break;case r.modEnvToFilterFc:d=n(i,-64,63)*56.25,this.setGeneratorOverride(I,d);break;case r.chorusEffectsSend:case r.reverbEffectsSend:this.setGeneratorOverride(I,n(i,0,255)*(1e3/255));break}}function ri(e){switch(this.midiControllers[S.dataEntryLSB]=e<<7,this.dataEntryState){default:break;case YA.RPCoarse:case YA.RPFine:{switch(this.midiControllers[S.registeredParameterMSB]|this.midiControllers[S.registeredParameterLSB]>>7){default:break;case ue.pitchWheelRange:{if(e===0)break;this.midiControllers[mA+j.pitchWheelRange]|=e;let t=(this.midiControllers[mA+j.pitchWheelRange]>>7)+e/128;p(`%cChannel ${this.channelNumber} pitch wheel range. Semitones: %c${t}`,c.info,c.value);break}case ue.fineTuning:{let n=this.customControllers[IA.channelTuning]<<7|e;this.setTuning(n*.01220703125);break}case ue.modulationDepth:{let n=this.customControllers[IA.modulationMultiplier]*50+e/128*100;this.setModulationDepth(n);break}case 16383:this.resetParameters();break}break}case YA.NRPFine:{let A=this.midiControllers[S.nonRegisteredParameterMSB]>>7,t=this.midiControllers[S.nonRegisteredParameterLSB]>>7;if(A===Ze.SF2)return;switch(A){default:p(`%cUnrecognized NRPN LSB for %c${this.channelNumber}%c: %c(0x${t.toString(16).toUpperCase()} 0x${t.toString(16).toUpperCase()})%c data value: %c${e}`,c.warn,c.recognized,c.warn,c.unrecognized,c.warn,c.value);break;case Ze.awe32:ii.call(this,t,e,this.midiControllers[S.dataEntryMSB]>>7);break}}}}function Ii(e,A,t=!0){if(e>127)throw new Error("Invalid MIDI Controller.");if(e>=S.modulationWheelLSB&&e<=S.effectControl2LSB&&e!==S.dataEntryLSB){let n=e-32;if(this.lockedControllers[n])return;this.midiControllers[n]=this.midiControllers[n]&16256|A&127,this.voices.forEach(s=>this.computeModulators(s,1,n))}if(!this.lockedControllers[e]){switch(this.midiControllers[e]=A<<7,e){case S.allNotesOff:this.stopAllNotes();break;case S.allSoundOff:this.stopAllNotes(!0);break;case S.bankSelect:this.setBankMSB(A),this.channelNumber%16===Se&&fA.isSystemXG(this.channelSystem)&&this.setBankMSB(127);break;case S.bankSelectLSB:this.setBankLSB(A);break;case S.registeredParameterLSB:this.dataEntryState=YA.RPFine;break;case S.registeredParameterMSB:this.dataEntryState=YA.RPCoarse;break;case S.nonRegisteredParameterMSB:this.customControllers[IA.sf2NPRNGeneratorLSB]=0,this.dataEntryState=YA.NRPCoarse;break;case S.nonRegisteredParameterLSB:this.midiControllers[S.nonRegisteredParameterMSB]>>7===Ze.SF2&&(this.customControllers[IA.sf2NPRNGeneratorLSB]%100!==0&&(this.customControllers[IA.sf2NPRNGeneratorLSB]=0),A===100?this.customControllers[IA.sf2NPRNGeneratorLSB]+=100:A===101?this.customControllers[IA.sf2NPRNGeneratorLSB]+=1e3:A===102?this.customControllers[IA.sf2NPRNGeneratorLSB]+=1e4:A<100&&(this.customControllers[IA.sf2NPRNGeneratorLSB]+=A)),this.dataEntryState=YA.NRPFine;break;case S.dataEntryMSB:this.dataEntryCoarse(A);break;case S.dataEntryLSB:this.dataEntryFine(A);break;case S.resetAllControllers:this.resetControllersRP15Compliant();break;case S.sustainPedal:A<64&&(this.sustainedVoices.forEach(n=>{n.release(this.synth.currentSynthTime)}),this.sustainedVoices=[]);break;default:this.voices.forEach(n=>this.computeModulators(n,1,e));break}t&&this.synthProps.callEvent("controllerChange",{channel:this.channelNumber,controllerNumber:e,controllerValue:A})}}var It={0:0,1:.006,2:.023,4:.05,8:.11,16:.25,32:.5,64:2.06,80:4.2,96:8.4,112:19.5,116:26.7,120:40,124:80,127:480};function gi(e){if(It[e]!==void 0)return It[e];let A=null,t=null;for(let n of Object.keys(It)){let s=parseInt(n);s<e&&(A===null||s>A)&&(A=s),s>e&&(t===null||s<t)&&(t=s)}if(A!==null&&t!==null){let n=It[A],s=It[t];return n+(e-A)*(s-n)/(t-A)}return 0}function ci(e,A){return gi(e)*(A/30)}function Ei(e,A){if(A<1){this.noteOff(e);return}if(A=Math.min(127,A),this.synthProps.masterParameters.blackMIDIMode&&this.synth.totalVoicesAmount>200&&A<40||this.synthProps.masterParameters.blackMIDIMode&&A<10||this._isMuted)return;if(!this.preset){sA(`No preset for channel ${this.channelNumber}!`);return}let t=e+this.channelTransposeKeyShift+this.customControllers[IA.channelKeyShift],n=t;if(t>127||t<0)return;let s=this.preset?.program,a=this.synthProps.tunings[s]?.[t]?.midiNote;a>=0&&(n=a),this.synthProps.masterParameters.monophonicRetriggerMode&&this.killNote(e,-7200);let i=this.synth.keyModifierManager.getVelocity(this.channelNumber,t);i>-1&&(A=i);let I=this.synth.keyModifierManager.getGain(this.channelNumber,t),o=-1,g=0,B=this.midiControllers[S.portamentoTime]>>7,d=this.midiControllers[S.portamentoControl],h=d>>7;if(!this.drumChannel&&h!==n&&this.midiControllers[S.portamentoOnOff]>=8192&&B>0){if(d!==1){let y=Math.abs(n-h);g=ci(B,y),o=h}this.controllerChange(S.portamentoControl,n)}let C=this.synthProps.getVoices(this.channelNumber,n,A,t),Q=0;this.randomPan&&(Q=Math.round(Math.random()*1e3-500));let m=this.voices;C.forEach(y=>{y.portamentoFromKey=o,y.portamentoDuration=g,y.overridePan=Q,y.gain=I,this.sysExModulators.modulatorList.forEach(O=>{let nA=O.mod,$=y.modulators.findIndex(V=>EA.isIdentical(V,nA));$!==-1?y.modulators[$]=EA.copyFrom(nA):y.modulators.push(EA.copyFrom(nA))}),this.generatorOverridesEnabled&&this.generatorOverrides.forEach((O,nA)=>{O!==Vs&&(y.generators[nA]=O)});let F=y.exclusiveClass;F!==0&&m.forEach(O=>{O.exclusiveClass===F&&O.exclusiveRelease(this.synth.currentSynthTime)}),this.computeModulators(y);let k=y.modulatedGenerators[r.startAddrsOffset]+y.modulatedGenerators[r.startAddrsCoarseOffset]*32768,D=y.modulatedGenerators[r.endAddrOffset]+y.modulatedGenerators[r.endAddrsCoarseOffset]*32768,v=y.modulatedGenerators[r.startloopAddrsOffset]+y.modulatedGenerators[r.startloopAddrsCoarseOffset]*32768,L=y.modulatedGenerators[r.endloopAddrsOffset]+y.modulatedGenerators[r.endloopAddrsCoarseOffset]*32768,E=y.sample,X=O=>Math.max(0,Math.min(E.sampleData.length-1,O));if(E.cursor=X(E.cursor+k),E.end=X(E.end+D),E.loopStart=X(E.loopStart+v),E.loopEnd=X(E.loopEnd+L),E.loopEnd<E.loopStart){let O=E.loopStart;E.loopStart=E.loopEnd,E.loopEnd=O}E.loopEnd-E.loopStart<1&&(E.loopingMode===1||E.loopingMode===3)&&(E.loopingMode=0,E.isLooping=!1),y.volumeEnvelope.attenuation=y.volumeEnvelope.attenuationTargetGain,y.currentPan=Math.max(-500,Math.min(500,y.modulatedGenerators[r.pan]))}),this.synth.totalVoicesAmount+=C.length,this.synth.totalVoicesAmount>this.synthProps.masterParameters.voiceCap&&this.synthProps.voiceKilling(C.length),m.push(...C),this.sendChannelProperty(),this.synthProps.callEvent("noteOn",{midiNote:e,channel:this.channelNumber,velocity:A})}function Bi(e){if(e>127||e<0){sA("Received a noteOn for note",e,"Ignoring.");return}let A=e+this.channelTransposeKeyShift+this.customControllers[IA.channelKeyShift];if(this.synthProps.masterParameters.blackMIDIMode&&!this.drumChannel){this.killNote(A,-6950),this.synthProps.callEvent("noteOff",{midiNote:e,channel:this.channelNumber});return}this.voices.forEach(n=>{n.realKey!==A||n.isInRelease||(this.holdPedal?this.sustainedVoices.push(n):n.release(this.synth.currentSynthTime))}),this.synthProps.callEvent("noteOff",{midiNote:e,channel:this.channelNumber})}function Ci(e){if(this.lockPreset)return;this.patch.program=e;let A=this.synth.soundBankManager.getPreset(this.patch,this.channelSystem);A||(sA("No presets! Using empty fallback."),A=new pe(this.synth.soundBankManager.soundBankList[0].soundBank),A.name="SPESSA EMPTY FALLBACK PRESET"),this.preset=A,A.isAnyDrums!==this.drumChannel&&this.setDrumFlag(A.isAnyDrums),this.synthProps.callEvent("programChange",{channel:this.channelNumber,bankLSB:this.preset.bankLSB,bankMSB:this.preset.bankMSB,program:this.preset.program,isGMGSDrum:this.preset.isGMGSDrum}),this.sendChannelProperty()}var hi=class{modulatorList=[];resetModulators(){this.modulatorList=[]}setModulator(e,A,t,n=!1,s=!1){let a=this.getModulatorID(e,A,n,s);t===0&&this.deleteModulator(a);let i=this.modulatorList.find(I=>I.id===a);if(i)i.mod.transformAmount=t;else{let I,o;e>=mA?(I=e-mA,o=!1):(I=e,o=!0);let g=new EA(new XA(I,QA.linear,o,n),new XA,A,t,0);this.modulatorList.push({mod:g,id:a})}}getModulatorID(e,A,t,n){return`${e}-${A}-${t}-${n}`}deleteModulator(e){this.modulatorList=this.modulatorList.filter(A=>A.id!==e)}},li=1e3/200;function Ms(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n=A.primarySource.getValue(e,t),s=A.secondarySource.getValue(e,t),a=A.transformAmount;A.isEffectModulator&&a<=1e3&&(a*=li,a=Math.min(a,1e3));let i=n*s*a;return A.transformType===2&&(i=Math.abs(i)),A.isDefaultResonantModulator&&(t.resonanceOffset=Math.max(0,i/2)),A.currentValue=i,i}function di(e,A=-1,t=0){let n=e.modulators,s=e.generators;if(this.generatorOffsetsEnabled){s=new Int16Array(s);for(let g=0;g<s.length;g++)s[g]+=this.generatorOffsets[g]}let a=e.modulatedGenerators;if(A===-1){a.set(s),n.forEach(g=>{a[g.destination]+=Ms(this.midiControllers,g,e)});for(let g=0;g<a.length;g++){let B=x[g];B&&(a[g]=Math.min(B.max,Math.max(B.min,a[g])))}be.recalculate(e),_e.recalculate(e);return}let i=new Set([r.initialAttenuation,r.delayVolEnv,r.attackVolEnv,r.holdVolEnv,r.decayVolEnv,r.sustainVolEnv,r.releaseVolEnv,r.keyNumToVolEnvHold,r.keyNumToVolEnvDecay]),I=new Set,o=!!A;n.forEach(g=>{if(g.primarySource.isCC===o&&g.primarySource.index===t||g.secondarySource.isCC===o&&g.secondarySource.index===t){let B=g.destination;if(!I.has(B)){a[B]=s[B],Ms(this.midiControllers,g,e),n.forEach(h=>{h.destination===B&&(a[B]+=h.currentValue)});let d=x[B];a[B]=Math.max(d.min,Math.min(a[B],d.max)),I.add(B)}}}),[...I].some(g=>i.has(g))&&be.recalculate(e),_e.recalculate(e)}var Qi=class{midiControllers=new Int16Array(bn);lockedControllers=Array(bn).fill(!1);customControllers=new Float32Array(ea);channelTransposeKeyShift=0;channelOctaveTuning=new Int8Array(128);sysExModulators=new hi;drumChannel=!1;randomPan=!1;dataEntryState=YA.Idle;patch={bankMSB:0,bankLSB:0,program:0,isGMGSDrum:!1};preset;lockPreset=!1;lockedSystem="gs";lockGSNRPNParams=!1;channelVibrato={delay:0,depth:0,rate:0};voices=[];sustainedVoices=[];channelNumber;synth;synthProps;noteOn=Ei.bind(this);noteOff=Bi.bind(this);programChange=Ci.bind(this);controllerChange=Ii.bind(this);resetControllers=po.bind(this);resetPreset=yo.bind(this);resetControllersRP15Compliant=ko.bind(this);resetParameters=Do.bind(this);dataEntryFine=ri.bind(this);dataEntryCoarse=ai.bind(this);channelTuningCents=0;generatorOffsets=new Int16Array(Mn);generatorOffsetsEnabled=!1;generatorOverrides=new Int16Array(Mn);generatorOverridesEnabled=!1;renderVoice=si.bind(this);panAndMixVoice=Oo.bind(this);computeModulators=di.bind(this);constructor(e,A,t,n){this.synth=e,this.synthProps=A,this.preset=t,this.channelNumber=n,this.resetGeneratorOverrides(),this.resetGeneratorOffsets()}_isMuted=!1;get isMuted(){return this._isMuted}get holdPedal(){return this.midiControllers[S.sustainPedal]>=8192}get channelSystem(){return this.lockPreset?this.lockedSystem:this.synthProps.masterParameters.midiSystem}transposeChannel(e,A=!1){this.drumChannel||(e+=this.synthProps.masterParameters.transposition);let t=Math.trunc(e),n=this.channelTransposeKeyShift+this.customControllers[IA.channelTransposeFine]/100;this.drumChannel&&!A||e===n||(t!==this.channelTransposeKeyShift&&this.stopAllNotes(),this.channelTransposeKeyShift=t,this.setCustomController(IA.channelTransposeFine,(e-t)*100),this.sendChannelProperty())}setOctaveTuning(e){if(e.length!==12)throw new Error("Tuning is not the length of 12.");this.channelOctaveTuning=new Int8Array(128);for(let A=0;A<128;A++)this.channelOctaveTuning[A]=e[A%12]}setModulationDepth(e){e=Math.round(e),p(`%cChannel ${this.channelNumber} modulation depth. Cents: %c${e}`,c.info,c.value),this.setCustomController(IA.modulationMultiplier,e/50)}setTuning(e,A=!0){e=Math.round(e),this.setCustomController(IA.channelTuning,e),A&&p(`%cFine tuning for %c${this.channelNumber}%c is now set to %c${e}%c cents.`,c.info,c.recognized,c.info,c.value,c.info)}pitchWheel(e){this.lockedControllers[mA+j.pitchWheel]||(this.synthProps.callEvent("pitchWheel",{channel:this.channelNumber,pitch:e}),this.midiControllers[mA+j.pitchWheel]=e,this.voices.forEach(A=>this.computeModulators(A,0,j.pitchWheel)),this.sendChannelProperty())}channelPressure(e){this.midiControllers[mA+j.channelPressure]=e<<7,this.updateChannelTuning(),this.voices.forEach(A=>this.computeModulators(A,0,j.channelPressure)),this.synthProps.callEvent("channelPressure",{channel:this.channelNumber,pressure:e})}polyPressure(e,A){this.voices.forEach(t=>{t.midiNote===e&&(t.pressure=A,this.computeModulators(t,0,j.polyPressure))}),this.synthProps.callEvent("polyPressure",{channel:this.channelNumber,midiNote:e,pressure:A})}setCustomController(e,A){this.customControllers[e]=A,this.updateChannelTuning()}updateChannelTuning(){this.channelTuningCents=this.customControllers[IA.channelTuning]+this.customControllers[IA.channelTransposeFine]+this.customControllers[IA.masterTuning]+this.customControllers[IA.channelTuningSemitones]*100}renderAudio(e,A,t,n,s,a,i,I){this.voices=this.voices.filter(o=>!this.renderVoice(o,this.synth.currentSynthTime,e,A,t,n,s,a,i,I))}setPresetLock(e){this.lockPreset!==e&&(this.lockPreset=e,e&&(this.lockedSystem=this.synthProps.masterParameters.midiSystem))}setDrums(e){if(fA.isSystemXG(this.channelSystem))if(e)this.setBankMSB(fA.getDrumBank(this.channelSystem)),this.setBankLSB(0);else{if(this.channelNumber%16===Se)throw new Error(`Cannot disable drums on channel ${this.channelNumber} for XG.`);this.setBankMSB(0),this.setBankLSB(0)}else this.setGSDrums(e);this.setDrumFlag(e),this.programChange(this.patch.program)}setPatch(e){this.setBankMSB(e.bankMSB),this.setBankLSB(e.bankLSB),this.setGSDrums(e.isGMGSDrum),this.programChange(e.program)}setGSDrums(e){e!==this.patch.isGMGSDrum&&(this.setBankLSB(0),this.setBankMSB(0),this.patch.isGMGSDrum=e)}setVibrato(e,A,t){this.lockGSNRPNParams||(this.channelVibrato.rate=A,this.channelVibrato.delay=t,this.channelVibrato.depth=e)}disableAndLockGSNRPN(){this.lockGSNRPNParams=!0,this.channelVibrato.rate=0,this.channelVibrato.delay=0,this.channelVibrato.depth=0}resetGeneratorOverrides(){this.generatorOverrides.fill(Vs),this.generatorOverridesEnabled=!1}setGeneratorOverride(e,A,t=!1){this.generatorOverrides[e]=A,this.generatorOverridesEnabled=!0,t&&this.voices.forEach(n=>{n.generators[e]=A,this.computeModulators(n)})}resetGeneratorOffsets(){this.generatorOffsets.fill(0),this.generatorOffsetsEnabled=!1}setGeneratorOffset(e,A){this.generatorOffsets[e]=A*x[e].nrpn,this.generatorOffsetsEnabled=!0,this.voices.forEach(t=>{this.computeModulators(t)})}killNote(e,A=-12e3){e+=this.customControllers[IA.channelKeyShift],this.voices.forEach(t=>{t.realKey===e&&(t.modulatedGenerators[r.releaseVolEnv]=A,t.release(this.synth.currentSynthTime))})}stopAllNotes(e=!1){e?(this.voices.length=0,this.sustainedVoices.length=0,this.sendChannelProperty()):(this.voices.forEach(A=>{A.isInRelease||A.release(this.synth.currentSynthTime)}),this.sustainedVoices.forEach(A=>{A.release(this.synth.currentSynthTime)})),this.synthProps.callEvent("stopAll",{channel:this.channelNumber,force:e})}muteChannel(e){e&&this.stopAllNotes(!0),this._isMuted=e,this.sendChannelProperty(),this.synthProps.callEvent("muteChannel",{channel:this.channelNumber,isMuted:e})}sendChannelProperty(){if(!this.synth.enableEventSystem)return;let e={voicesAmount:this.voices.length,pitchWheel:this.midiControllers[mA+j.pitchWheel],pitchWheelRange:this.midiControllers[mA+j.pitchWheelRange]/128,isMuted:this.isMuted,transposition:this.channelTransposeKeyShift+this.customControllers[IA.channelTransposeFine]/100,isDrum:this.drumChannel};this.synthProps.callEvent("channelPropertyChange",{channel:this.channelNumber,property:e})}setBankMSB(e){this.lockPreset||(this.patch.bankMSB=e)}setBankLSB(e){this.lockPreset||(this.patch.bankLSB=e)}setDrumFlag(e){this.lockPreset||!this.preset||this.drumChannel!==e&&(e?(this.channelTransposeKeyShift=0,this.drumChannel=!0):this.drumChannel=!1,this.synthProps.callEvent("drumChange",{channel:this.channelNumber,isDrumChannel:this.drumChannel}))}},yn=20;async function ui(e,A,t,n,s,a,i){let I=0,o=0,g=[];for(let h of e.samples){n&&a&&await h.compressSample(a),s&&h.setAudioData(h.getAudioData(),h.sampleRate);let C=h.getRawData(!0);I++,await i?.(h.name,I,e.samples.length),p(`%cEncoded sample %c${I}. ${h.name}%c of %c${e.samples.length}%c. Compressed: %c${h.isCompressed}%c.`,c.info,c.recognized,c.info,c.recognized,c.info,h.isCompressed?c.recognized:c.unrecognized,c.info),o+=C.length+(h.isCompressed?0:92),g.push(C)}o%2!==0&&o++;let B=new Y(o+yn);kA(B,"LIST"),ht(B,o+yn-8,4),kA(B,"sdta"),kA(B,"smpl"),ht(B,o,4);let d=0;return e.samples.forEach((h,C)=>{let Q=g[C];B.set(Q,d+yn);let m,y;h.isCompressed?(m=d,y=m+Q.length):(m=d/2,y=m+Q.length/2,d+=92),d+=Q.length,A.push(m),t.push(y)}),B}var fi=48e3,Zt=class{name;sampleRate;originalKey;pitchCorrection;linkedSample;sampleType;loopStart;loopEnd;linkedTo=[];dataOverridden=!0;compressedData;audioData;constructor(e,A,t,n,s,a,i){this.name=e,this.sampleRate=A,this.originalKey=t,this.pitchCorrection=n,this.loopStart=a,this.loopEnd=i,this.sampleType=s}get isCompressed(){return this.compressedData!==void 0}get isLinked(){return this.sampleType===wA.rightSample||this.sampleType===wA.leftSample||this.sampleType===wA.linkedSample}get useCount(){return this.linkedTo.length}getRawData(e){return this.compressedData&&e&&!this.dataOverridden?this.compressedData:this.encodeS16LE()}resampleData(e){let A=this.getAudioData(),t=e/this.sampleRate,n=new Float32Array(Math.floor(A.length*t));for(let s=0;s<n.length;s++)n[s]=A[Math.floor(s*(1/t))];A=n,this.sampleRate=e,this.loopStart=Math.floor(this.loopStart*t),this.loopEnd=Math.floor(this.loopEnd*t),this.audioData=A}async compressSample(e){if(!this.isCompressed)try{let A=this.getAudioData();(this.sampleRate<8e3||this.sampleRate>96e3)&&(this.resampleData(fi),A=this.getAudioData());let t=await e(A,this.sampleRate);this.setCompressedData(t)}catch(A){sA(`Failed to compress ${this.name}. Leaving as uncompressed!`,A),this.compressedData=void 0}}setSampleType(e){if(this.sampleType=e,this.isLinked||(this.linkedSample&&(this.linkedSample.linkedSample=void 0,this.linkedSample.sampleType=e),this.linkedSample=void 0),(e&32768)>0)throw new Error("ROM samples are not supported.")}unlinkSample(){this.setSampleType(wA.monoSample)}setLinkedSample(e,A){if(e.linkedSample)throw new Error(`${e.name} is linked tp ${e.linkedSample.name}. Unlink it first.`);if(this.linkedSample=e,e.linkedSample=this,A===wA.leftSample)this.setSampleType(wA.leftSample),e.setSampleType(wA.rightSample);else if(A===wA.rightSample)this.setSampleType(wA.rightSample),e.setSampleType(wA.leftSample);else if(A===wA.linkedSample)this.setSampleType(wA.linkedSample),e.setSampleType(wA.linkedSample);else throw new Error("Invalid sample type: "+A)}linkTo(e){this.linkedTo.push(e)}unlinkFrom(e){let A=this.linkedTo.indexOf(e);if(A<0){sA(`Cannot unlink ${e.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(A,1)}getAudioData(){if(this.audioData)return this.audioData;if(this.isCompressed)return this.audioData=this.decodeVorbis(),this.audioData;throw new Error("Sample data is undefined for a BasicSample instance.")}setAudioData(e,A){this.audioData=e,this.sampleRate=A,this.dataOverridden=!0,this.compressedData=void 0}setCompressedData(e){this.audioData=void 0,this.compressedData=e,this.dataOverridden=!1}encodeS16LE(){let e=this.getAudioData(),A=new Int16Array(e.length),t=e.length;for(let n=0;n<t;n++){let s=e[n]*32768;s>32767?s=32767:s<-32768&&(s=-32768),A[n]=s}return new Y(A.buffer)}decodeVorbis(){if(this.audioData)return this.audioData;if(!this.compressedData)throw new Error("Compressed data is missing.");try{let A=Ot.decode(this.compressedData).data[0];if(A===void 0)return sA(`Error decoding sample ${this.name}: Vorbis decode returned undefined.`),new Float32Array(0);for(let t=0;t<A.length;t++)A[t]=Math.max(-1,Math.min(A[t],.999969482421875));return A}catch(e){return sA(`Error decoding sample ${this.name}: ${e}`),new Float32Array(this.loopEnd+1)}}},mi=class extends Zt{constructor(){super("",44100,60,0,wA.monoSample,0,0)}},Vn=16,Si=class extends Zt{linkedSampleIndex;s16leData;startByteOffset;endByteOffset;sampleID;constructor(e,A,t,n,s,a,i,I,o,g,B,d){let h=(g&Vn)>0;g&=~Vn,super(e,a,i,I,g,n-A/2,s-A/2),this.dataOverridden=!1,this.name=e,this.startByteOffset=A,this.endByteOffset=t,this.sampleID=d;let C=B instanceof Y?B.currentIndex:0;B instanceof Y?h?(this.loopStart+=this.startByteOffset/2,this.loopEnd+=this.startByteOffset/2,this.setCompressedData(B.slice(this.startByteOffset/2+C,this.endByteOffset/2+C))):this.s16leData=B.slice(C+this.startByteOffset,C+this.endByteOffset):this.setAudioData(B.slice(this.startByteOffset/2,this.endByteOffset/2),a),this.linkedSampleIndex=o}getLinkedSample(e){if(this.linkedSample||!this.isLinked)return;let A=e[this.linkedSampleIndex];A?A.linkedSample?(p(`%cInvalid linked sample for ${this.name}: Already linked to ${A.linkedSample.name}`,c.warn),this.unlinkSample()):this.setLinkedSample(A,this.sampleType):(p(`%cInvalid linked sample for ${this.name}. Setting to mono.`,c.warn),this.unlinkSample())}getAudioData(){if(this.audioData)return this.audioData;if(this.isCompressed)return super.getAudioData();if(!this.s16leData)throw console.error(this),new Error("Unexpected lack of audio data.");let e=this.endByteOffset-this.startByteOffset;if(e<1)return sA(`Invalid sample ${this.name}! Invalid length: ${e}`),new Float32Array(1);let A=new Float32Array(e/2),t=new Int16Array(this.s16leData.buffer);for(let n=0;n<t.length;n++)A[n]=t[n]/32768;return this.audioData=A,A}getRawData(e){return this.dataOverridden||this.compressedData?super.getRawData(e):this.s16leData??new Uint8Array(0)}};function bs(e,A,t=!0){let n=[],s=0;for(;e.data.length>e.data.currentIndex;){let a=pi(s,e.data,A);n.push(a),s++}return n.pop(),t&&n.forEach(a=>a.getLinkedSample(n)),n}function pi(e,A,t){let n=hA(A,20),s=N(A,4)*2,a=N(A,4)*2,i=N(A,4),I=N(A,4),o=N(A,4),g=A[A.currentIndex++];g>127&&(g=60);let B=qa(A[A.currentIndex++]),d=N(A,2),h=N(A,2);return new Si(n,s,a,i,I,o,g,B,d,h,t,e)}function yi(e,A,t){let s=46*(e.samples.length+1),a=new Y(s),i=new Y(s),I=0;e.samples.forEach((B,d)=>{kA(a,B.name.substring(0,20),20),kA(i,B.name.substring(20),20);let h=A[d];gA(a,h),i.currentIndex+=4;let C=t[d];gA(a,C),i.currentIndex+=4;let Q=B.loopStart+h,m=B.loopEnd+h;B.isCompressed&&(Q-=h,m-=h),gA(a,Q),gA(a,m),gA(a,B.sampleRate),a[a.currentIndex++]=B.originalKey,a[a.currentIndex++]=B.pitchCorrection,i.currentIndex+=14;let y=B.linkedSample?e.samples.indexOf(B.linkedSample):0;J(a,Math.max(0,y)&65535),J(i,Math.max(0,y)>>16),I=Math.max(I,y);let F=B.sampleType;B.isCompressed&&(F|=Vn),J(a,F),i.currentIndex+=2}),kA(a,"EOS",46),kA(i,"EOS",46);let o=cA("shdr",a),g=cA("shdr",i);return{pdta:o,xdta:g}}function vs(e,A=!1){let t=A?e.presets:e.instruments,n=A?"pgen":"igen",s=A?"pmod":"imod",a=A?"pbag":"ibag",i=A?"phdr":"inst",I=A?da:la,o=t.map(k=>(k instanceof pe,k.getSize())),g=o.reduce((k,D)=>k+D.gen,0)+Ct,B=new Y(g),d=o.reduce((k,D)=>k+D.mod,0)+me,h=new Y(d),C=o.reduce((k,D)=>k+D.bag,0)+Jt,Q={pdta:new Y(C),xdta:new Y(C)},m=o.reduce((k,D)=>D.hdr+k,0)+I,y={pdta:new Y(m),xdta:new Y(m)},F={gen:0,bag:0,mod:0,hdr:0};return t.forEach(k=>{k instanceof pe,k.write(B,h,Q,y,F,e)}),A?(kA(y.pdta,"EOP",20),y.pdta.currentIndex+=4,J(y.pdta,F.hdr&65535),y.pdta.currentIndex+=12,kA(y.xdta,"",20),y.xdta.currentIndex+=4,J(y.xdta,F.hdr>>16),y.xdta.currentIndex+=12):(kA(y.pdta,"EOI",20),kA(y.xdta,"",20),J(y.pdta,F.hdr&65535),J(y.xdta,F.hdr>>16)),J(Q.pdta,F.gen&65535),J(Q.xdta,F.gen>>16),J(Q.pdta,F.mod&65535),J(Q.xdta,F.mod>>16),{writeXdta:Math.max(g/Ct,d/me,C/Jt,m/I)>65535,gen:{pdta:cA(n,B),xdta:cA(s,new Y(Ct))},mod:{pdta:cA(s,h),xdta:cA(s,new Y(me))},bag:{pdta:cA(a,Q.pdta),xdta:cA(a,Q.xdta)},hdr:{pdta:cA(i,y.pdta),xdta:cA(i,y.xdta)}}}var Xn={compress:!1,compressionFunction:void 0,progressFunction:void 0,writeDefaultModulators:!0,writeExtendedLimits:!0,decompress:!1};async function ki(e,A=Xn){let t=$n(A,Xn);if(t?.compress){if(typeof t?.compressionFunction!="function")throw new Error("No compression function supplied but compression enabled.");if(t?.decompress)throw new Error("Decompressed and compressed at the same time.")}bA("%cSaving soundbank...",c.info),p(`%cCompression: %c${t?.compress||"false"}%c`,c.info,c.recognized,c.info,c.recognized),OA("%cWriting INFO...",c.info);let n=[];e.soundBankInfo.software="SpessaSynth",(t?.compress||e.samples.some(D=>D.isCompressed))&&(e.soundBankInfo.version.major=3,e.soundBankInfo.version.minor=0),t?.decompress&&(e.soundBankInfo.version.major=2,e.soundBankInfo.version.minor=4);let s=(D,v)=>{n.push(cA(D,ne(v,!0,!0)))},a=new Y(4);if(J(a,e.soundBankInfo.version.major),J(a,e.soundBankInfo.version.minor),n.push(cA("ifil",a)),e.soundBankInfo.romVersion){let D=new Y(4);J(D,e.soundBankInfo.romVersion.major),J(D,e.soundBankInfo.romVersion.minor),n.push(cA("iver",D))}let i=(e.soundBankInfo?.comment??"")+(e.soundBankInfo.subject?`
6
6
  ${e.soundBankInfo.subject}`:"");for(let[D,v]of Object.entries(e.soundBankInfo)){let L=D,E=v;if(E)switch(L){case"name":s("INAM",E);break;case"comment":s("ICMT",i);break;case"copyright":s("ICOP",E);break;case"creationDate":s("ICRD",E.toISOString());break;case"engineer":s("IENG",E);break;case"product":s("IPRD",E);break;case"romInfo":s("irom",E);break;case"software":s("ISFT",E);break;case"soundEngine":s("isng",E);break;case"subject":break}}if(e.defaultModulators.some(D=>Ea.findIndex(v=>EA.isIdentical(v,D,!0))===-1)&&t?.writeDefaultModulators){let D=e.defaultModulators;p(`%cWriting %c${D.length}%c default modulators...`,c.info,c.recognized,c.info);let v=me+D.length*me,L=new Y(v);for(let E of D)E.write(L);ht(L,0,me),n.push(cA("DMOD",L))}Z(),p("%cWriting SDTA...",c.info);let o=[],g=[],B=await ui(e,o,g,t.compress,t.decompress,t?.compressionFunction,t?.progressFunction);p("%cWriting PDTA...",c.info),p("%cWriting SHDR...",c.info);let d=yi(e,o,g);OA("%cWriting instruments...",c.info);let h=vs(e,!1);Z(),OA("%cWriting presets...",c.info);let C=vs(e,!0);Z();let Q=[C.hdr,C.bag,C.mod,C.gen,h.hdr,h.bag,h.mod,h.gen,d],m=vA("pdta",Q.map(D=>D.pdta),!0);if(t.writeExtendedLimits&&(h.writeXdta||C.writeXdta||e.presets.some(D=>D.name.length>20)||e.instruments.some(D=>D.name.length>20)||e.samples.some(D=>D.name.length>20))){p("%cWriting the xdta chunk as writeExendedLimits is enabled and at least one condition was met.",c.info,c.value);let D=vA("xdta",Q.map(v=>v.xdta),!0);n.push(D)}let F=vA("INFO",n,!0);p("%cWriting the output file...",c.info);let k=vA("RIFF",[ne("sfbk"),F,B,m]);return p(`%cSaved succesfully! Final file size: %c${k.length}`,c.info,c.recognized),Z(),k.buffer}var je=class{static verifyHeader(e,...A){for(let t of A)if(e.header.toLowerCase()===t.toLowerCase())return;this.parsingError(`Invalid DLS chunk header! Expected "${A.join(", or ")}" got "${e.header.toLowerCase()}"`)}static verifyText(e,...A){for(let t of A)if(e.toLowerCase()===t.toLowerCase())return;this.parsingError(`FourCC error: Expected "${A.join(", or ")}" got "${e.toLowerCase()}"`)}static parsingError(e){throw Z(),new Error(`DLS parse error: ${e} The file may be corrupted.`)}static verifyAndReadList(e,...A){this.verifyHeader(e,"LIST"),e.data.currentIndex=0,this.verifyText(hA(e.data,4),...A);let t=[];for(;e.data.length>e.data.currentIndex;)t.push(iA(e.data));return t}},gt=20,kn=16,ze=class Bt extends je{gain=0;unityNote=60;fineTune=0;loops=new Array;fulOptions=2;static copyFrom(A){let t=new Bt;return t.unityNote=A.unityNote,t.gain=A.gain,t.fineTune=A.fineTune,t.loops=A.loops.map(n=>({...n})),t.fulOptions=A.fulOptions,t}static read(A){this.verifyHeader(A,"wsmp");let t=new Bt,n=N(A.data,4);if(n!==gt&&sA(`Wsmp cbSize mismatch: got ${n}, expected ${gt}.`),t.unityNote=N(A.data,2),t.fineTune=jn(A.data[A.data.currentIndex++],A.data[A.data.currentIndex++]),t.gain=N(A.data,4)|0,t.fulOptions=N(A.data,4),N(A.data,4)!==0){let a=N(A.data,4);a!==kn&&sA(`CbSize for loop in wsmp mismatch. Expected ${gt}, got ${a}.`);let i=N(A.data,4),I=N(A.data,4),o=N(A.data,4);t.loops.push({loopStart:I,loopLength:o,loopType:i})}return t}static fromSFSample(A){let t=new Bt;return t.unityNote=A.originalKey,t.fineTune=A.pitchCorrection,(A.loopEnd!==0||A.loopStart!==0)&&t.loops.push({loopStart:A.loopStart,loopLength:A.loopEnd-A.loopStart,loopType:ys.forward}),t}static fromSFZone(A){let t=new Bt;t.unityNote=A.getGenerator(r.overridingRootKey,A.sample.originalKey),A.getGenerator(r.scaleTuning,100)===0&&A.keyRange.max-A.keyRange.min===0&&(t.unityNote=A.keyRange.min),t.fineTune=A.fineTuning+A.sample.pitchCorrection;let n=A.getGenerator(r.initialAttenuation,0)*.4;t.gain=-n<<16;let s=A.getGenerator(r.sampleModes,0);if(s!==0){let a=A.sample.loopStart+A.getGenerator(r.startloopAddrsOffset,0)+A.getGenerator(r.startloopAddrsCoarseOffset,0)*32768,i=A.sample.loopEnd+A.getGenerator(r.endloopAddrsOffset,0)+A.getGenerator(r.endloopAddrsCoarseOffset,0)*32768,I;switch(s){case 1:default:I=0;break;case 3:I=1}t.loops.push({loopType:I,loopStart:a,loopLength:i-a})}return t}toSFZone(A,t){let n=0,s=this.loops[0];s&&(n=s.loopType===ys.loopAndRelease?3:1),n!==0&&A.setGenerator(r.sampleModes,n);let I=-(this.gain>>16)/.4;if(I!==0&&A.setGenerator(r.initialAttenuation,I),A.fineTuning=this.fineTune-t.pitchCorrection,this.unityNote!==t.originalKey&&A.setGenerator(r.overridingRootKey,this.unityNote),s){let o=s.loopStart-t.loopStart,B=s.loopStart+s.loopLength-t.loopEnd;if(o!==0){let d=o%32768;A.setGenerator(r.startloopAddrsOffset,d);let h=Math.trunc(o/32768);h!==0&&A.setGenerator(r.startloopAddrsCoarseOffset,h)}if(B!==0){let d=B%32768;A.setGenerator(r.endloopAddrsOffset,d);let h=Math.trunc(B/32768);h!==0&&A.setGenerator(r.endloopAddrsCoarseOffset,h)}}}write(){let A=new Y(gt+this.loops.length*kn);return gA(A,gt),J(A,this.unityNote),J(A,this.fineTune),gA(A,this.gain),gA(A,this.fulOptions),gA(A,this.loops.length),this.loops.forEach(t=>{gA(A,kn),gA(A,t.loopType),gA(A,t.loopStart),gA(A,t.loopLength)}),cA("wsmp",A)}},Dn={PCM:1,ALAW:6};function Di(e,A){let t=Math.pow(2,A*8-1),n=Math.pow(2,A*8),s,a=!1;A===1?(s=255,a=!0):s=t;let i=e.length/A,I=new Float32Array(i);if(A===2){let o=new Int16Array(e.buffer);for(let g=0;g<o.length;g++)I[g]=o[g]/32768}else for(let o=0;o<I.length;o++){let g=N(e,A);a?I[o]=g/s-.5:(g>=t&&(g-=n),I[o]=g/s)}return I}function wi(e,A){let t=e.length/A,n=new Float32Array(t);for(let s=0;s<n.length;s++){let a=N(e,A),i=a^85;i&=127;let I=i>>4,o=i&15;I>0&&(o+=16),o=(o<<4)+8,I>1&&(o=o<<I-1);let g=a>127?o:-o;n[s]=g/32678}return n}var Fi=class extends Zt{wFormatTag;bytesPerSample;rawData;constructor(e,A,t,n,s,a,i,I,o){super(e,A,t,n,wA.monoSample,s,a),this.dataOverridden=!1,this.rawData=i.data,this.wFormatTag=I,this.bytesPerSample=o}getAudioData(){if(!this.rawData)return new Float32Array(0);if(!this.audioData){let e;switch(this.wFormatTag){default:sA(`Failed to decode sample. Unknown wFormatTag: ${this.wFormatTag}`),e=new Float32Array(this.rawData.length/this.bytesPerSample);break;case Dn.PCM:e=Di(this.rawData,this.bytesPerSample);break;case Dn.ALAW:e=wi(this.rawData,this.bytesPerSample);break}this.setAudioData(e,this.sampleRate)}return this.audioData??new Float32Array(0)}getRawData(e){return this.dataOverridden||this.isCompressed?super.getRawData(e):this.wFormatTag===Dn.PCM&&this.bytesPerSample===2?this.rawData:this.encodeS16LE()}},Ls=class Zn extends je{waveSample=new ze;wFormatTag;bytesPerSample;sampleRate;dataChunk;name="Unnamed sample";constructor(A,t,n,s){super(),this.wFormatTag=A,this.bytesPerSample=t,this.sampleRate=n,this.dataChunk=s}static read(A){let t=this.verifyAndReadList(A,"wave"),n=t.find(C=>C.header==="fmt ");if(!n)throw new Error("No fmt chunk in the wave file!");let s=N(n.data,2),a=N(n.data,2);if(a!==1)throw new Error(`Only mono samples are supported. Fmt reports ${a} channels.`);let i=N(n.data,4);N(n.data,4),N(n.data,2);let o=N(n.data,2)/8,g=t.find(C=>C.header==="data");if(!g)throw new Error("No data chunk in the WAVE chunk!");let B=new Zn(s,o,i,g),d=fe(t,"INFO");if(d){let C=iA(d.data);for(;C.header!=="INAM"&&d.data.currentIndex<d.data.length;)C=iA(d.data);C.header==="INAM"&&(B.name=hA(C.data,C.size).trim())}let h=t.find(C=>C.header==="wsmp");return h&&(B.waveSample=ze.read(h)),B}static fromSFSample(A){let t=A.getRawData(!1),n=new Zn(1,2,A.sampleRate,new Hs("data",t.length,new Y(t.buffer)));return n.name=A.name,n.waveSample=ze.fromSFSample(A),n}toSFSample(A){let t=this.waveSample.unityNote,n=this.waveSample.fineTune,s=Math.trunc(n/100);t+=s,n-=s*100;let a=0,i=0,I=this.waveSample.loops?.[0];I&&(a=I.loopStart,i=I.loopStart+I.loopLength);let o=new Fi(this.name,this.sampleRate,t,n,a,i,this.dataChunk,this.wFormatTag,this.bytesPerSample);A.addSamples(o)}write(){let A=this.writeFmt(),t=this.waveSample.write(),n=cA("data",this.dataChunk.data),s=cA("INAM",ne(this.name,!0)),a=cA("INFO",s,!1,!0);return p(`%cSaved %c${this.name}%c successfully!`,c.recognized,c.value,c.recognized),vA("wave",[A,t,n,a],!0)}writeFmt(){let A=new Y(18);return J(A,this.wFormatTag),J(A,1),gA(A,this.sampleRate),gA(A,this.sampleRate*2),J(A,2),J(A,this.bytesPerSample*8),cA("fmt ",A)}},ya=new yA(219,0,r.reverbEffectsSend,1e3,0),ka=new yA(221,0,r.chorusEffectsSend,1e3,0),Gi=new yA(129,0,r.vibLfoToPitch,0,0),Ri=new yA(13,0,r.vibLfoToPitch,0,0),VA=class zn{source;transform;bipolar;invert;constructor(A=T.none,t=QA.linear,n=!1,s=!1){this.source=A,this.transform=t,this.bipolar=n,this.invert=s}get sourceName(){return Object.keys(T).find(A=>T[A]===this.source)??this.source.toString()}get transformName(){return Object.keys(QA).find(A=>QA[A]===this.transform)??this.transform.toString()}static copyFrom(A){return new zn(A.source,A.transform,A.bipolar,A.invert)}static fromSFSource(A){let t;if(A.isCC)switch(A.index){case S.modulationWheel:t=T.modulationWheel;break;case S.mainVolume:t=T.volume;break;case S.pan:t=T.pan;break;case S.expressionController:t=T.expression;break;case S.chorusDepth:t=T.chorus;break;case S.reverbDepth:t=T.reverb;break}else switch(A.index){case j.noController:t=T.none;break;case j.noteOnKeyNum:t=T.keyNum;break;case j.noteOnVelocity:t=T.velocity;break;case j.pitchWheel:t=T.pitchWheel;break;case j.pitchWheelRange:t=T.pitchWheelRange;break;case j.polyPressure:t=T.polyPressure;break;case j.channelPressure:t=T.channelPressure}if(t!==void 0)return new zn(t,A.curveType,A.isBipolar,A.isNegative)}toString(){return`${this.sourceName} ${this.transformName} ${this.bipolar?"bipolar":"unipolar"} ${this.invert?"inverted":"positive"}`}toTransformFlag(){return this.transform|(this.bipolar?1:0)<<4|(this.invert?1:0)<<5}toSFSource(){let A,t=!1;switch(this.source){default:case T.modLfo:case T.vibratoLfo:case T.coarseTune:case T.fineTune:case T.modEnv:return;case T.keyNum:A=j.noteOnKeyNum;break;case T.none:A=j.noController;break;case T.modulationWheel:A=S.modulationWheel,t=!0;break;case T.pan:A=S.pan,t=!0;break;case T.reverb:A=S.reverbDepth,t=!0;break;case T.chorus:A=S.chorusDepth,t=!0;break;case T.expression:A=S.expressionController,t=!0;break;case T.volume:A=S.mainVolume,t=!0;break;case T.velocity:A=j.noteOnVelocity;break;case T.polyPressure:A=j.polyPressure;break;case T.channelPressure:A=j.channelPressure;break;case T.pitchWheel:A=j.pitchWheel;break;case T.pitchWheelRange:A=j.pitchWheelRange;break}if(A!==void 0)return new XA(A,this.transform,t,this.bipolar,this.invert)}},Mi=new Set([r.sampleModes,r.initialAttenuation,r.keyRange,r.velRange,r.sampleID,r.fineTune,r.coarseTune,r.startAddrsOffset,r.startAddrsCoarseOffset,r.endAddrOffset,r.endAddrsCoarseOffset,r.startloopAddrsOffset,r.startloopAddrsCoarseOffset,r.endloopAddrsOffset,r.endloopAddrsCoarseOffset,r.overridingRootKey,r.exclusiveClass]),ct=class Re{source;control;destination;scale;transform;constructor(A=new VA,t=new VA,n,s,a){this.source=A,this.control=t,this.destination=n,this.transform=s,this.scale=a}get isStaticParameter(){return this.source.source===T.none&&this.control.source===T.none}get shortScale(){return this.scale>>16}get transformName(){return Object.keys(QA).find(A=>QA[A]===this.transform)??this.transform.toString()}get destinationName(){return Object.keys(R).find(A=>R[A]===this.destination)??this.destination.toString()}static read(A){let t=N(A,2),n=N(A,2),s=N(A,2),a=N(A,2),i=N(A,4)|0,I=a&15,o=a>>4&15,g=Me(a,8),B=Me(a,9),d=new VA(n,o,g,B),h=a>>10&15,C=Me(a,14),Q=Me(a,15),m=new VA(t,h,C,Q);return new Re(m,d,s,I,i)}static fromSFModulator(A,t){let n=B=>{sA(`Failed converting SF modulator into DLS:
7
7
  ${A.toString()}
8
8
  (${B})`)};if(A.transformType!==0){n("Absolute transform type is not supported");return}if(EA.isIdentical(A,ka,!0)||EA.isIdentical(A,ya,!0))return;let s=VA.fromSFSource(A.primarySource);if(!s){n("Invalid primary source");return}let a=VA.fromSFSource(A.secondarySource);if(!a){n("Invalid secondary source");return}let i=Re.fromSFDestination(A.destination,A.transformAmount);if(i===void 0){n("Invalid destination");return}let I=A.transformAmount,o;if(typeof i=="number")o=i;else if(o=i.destination,I=i.amount,i.source!==T.none){if(a.source!==T.none&&s.source!==T.none){n("Articulation generators with secondary source are not supported");return}s.source!==T.none&&(a=s),s=new VA(i.source,QA.linear,i.isBipolar)}let g=new Re(s,a,o,0,I<<16);t.connectionBlocks.push(g)}static copyFrom(A){return new Re(VA.copyFrom(A.source),VA.copyFrom(A.control),A.destination,A.transform,A.scale)}static fromSFGenerator(A,t){if(Mi.has(A.generatorType))return;let n=o=>{sA(`Failed converting SF2 generator into DLS:
@@ -14,7 +14,7 @@ Output transform: ${this.transformName}
14
14
  Destination: ${this.destinationName}`}write(){let A=new Y(12);J(A,this.source.source),J(A,this.control.source),J(A,this.destination);let t=this.transform|this.control.toTransformFlag()<<4|this.source.toTransformFlag()<<10;return J(A,t),gA(A,this.scale),A}toSFGenerator(A){let t=this.destination,n=this.shortScale;switch(t){default:p(`%cFailed converting DLS articulator into SF generator: %c${this.toString()}%c
15
15
  (invalid destination)`,c.warn,c.value,c.unrecognized);return;case R.pan:A.setGenerator(r.pan,n);break;case R.gain:A.addToGenerator(r.initialAttenuation,-n/.4);break;case R.filterCutoff:A.setGenerator(r.initialFilterFc,n);break;case R.filterQ:A.setGenerator(r.initialFilterQ,n);break;case R.modLfoFreq:A.setGenerator(r.freqModLFO,n);break;case R.modLfoDelay:A.setGenerator(r.delayModLFO,n);break;case R.vibLfoFreq:A.setGenerator(r.freqVibLFO,n);break;case R.vibLfoDelay:A.setGenerator(r.delayVibLFO,n);break;case R.volEnvDelay:A.setGenerator(r.delayVolEnv,n);break;case R.volEnvAttack:A.setGenerator(r.attackVolEnv,n);break;case R.volEnvHold:A.setGenerator(r.holdVolEnv,n);break;case R.volEnvDecay:A.setGenerator(r.decayVolEnv,n);break;case R.volEnvRelease:A.setGenerator(r.releaseVolEnv,n);break;case R.volEnvSustain:A.setGenerator(r.sustainVolEnv,1e3-n);break;case R.modEnvDelay:A.setGenerator(r.delayModEnv,n);break;case R.modEnvAttack:A.setGenerator(r.attackModEnv,n);break;case R.modEnvHold:A.setGenerator(r.holdModEnv,n);break;case R.modEnvDecay:A.setGenerator(r.decayModEnv,n);break;case R.modEnvRelease:A.setGenerator(r.releaseModEnv,n);break;case R.modEnvSustain:A.setGenerator(r.sustainModEnv,1e3-n);break;case R.reverbSend:A.setGenerator(r.reverbEffectsSend,n);break;case R.chorusSend:A.setGenerator(r.chorusEffectsSend,n);break;case R.pitch:A.fineTuning+=n;break}}toSFModulator(A){let t=this.shortScale,n,s,a=new XA,i=g=>{p(`%cFailed converting DLS articulator into SF2:
16
16
  %c${this.toString()}%c
17
- (${g})`,c.warn,c.value,c.unrecognized)},I=this.toCombinedSFDestination();if(I){n=I;let g=this.control.toSFSource();if(!g){i("Invalid control");return}s=g}else{let g=this.toSFDestination();if(!g){i("Invalid destination");return}typeof g=="object"?(t=g.newAmount,n=g.gen):n=g;let B=this.source.toSFSource();if(!B){i("Invalid source");return}s=B;let d=this.control.toSFSource();if(!d){i("Invalid control");return}a=d}this.transform!==QA.linear&&s.curveType===QA.linear&&(s.curveType=this.transform),n===r.initialAttenuation&&((this.source.source===T.velocity||this.source.source===T.volume||this.source.source===T.expression)&&(s.isNegative=!0),t=Math.min(960,Math.max(0,t)));let o=new EA(s,a,n,t,0);A.addModulators(o)}toCombinedSFDestination(){let A=this.source.source,t=this.destination;return A===T.vibratoLfo&&t===R.pitch?r.vibLfoToPitch:A===T.modLfo&&t===R.pitch?r.modLfoToPitch:A===T.modLfo&&t===R.filterCutoff?r.modLfoToFilterFc:A===T.modLfo&&t===R.gain?r.modLfoToVolume:A===T.modEnv&&t===R.filterCutoff?r.modEnvToFilterFc:A===T.modEnv&&t===R.pitch?r.modEnvToPitch:void 0}toSFDestination(){let A=this.shortScale;switch(this.destination){default:case R.none:return;case R.pan:return r.pan;case R.gain:return{gen:r.initialAttenuation,newAmount:-A};case R.pitch:return r.fineTune;case R.keyNum:return r.overridingRootKey;case R.volEnvDelay:return r.delayVolEnv;case R.volEnvAttack:return r.attackVolEnv;case R.volEnvHold:return r.holdVolEnv;case R.volEnvDecay:return r.decayVolEnv;case R.volEnvSustain:return{gen:r.sustainVolEnv,newAmount:1e3-A};case R.volEnvRelease:return r.releaseVolEnv;case R.modEnvDelay:return r.delayModEnv;case R.modEnvAttack:return r.attackModEnv;case R.modEnvHold:return r.holdModEnv;case R.modEnvDecay:return r.decayModEnv;case R.modEnvSustain:return{gen:r.sustainModEnv,newAmount:1e3-A};case R.modEnvRelease:return r.releaseModEnv;case R.filterCutoff:return r.initialFilterFc;case R.filterQ:return r.initialFilterQ;case R.chorusSend:return r.chorusEffectsSend;case R.reverbSend:return r.reverbEffectsSend;case R.modLfoFreq:return r.freqModLFO;case R.modLfoDelay:return r.delayModLFO;case R.vibLfoFreq:return r.freqVibLFO;case R.vibLfoDelay:return r.delayVibLFO}}},Da=class Wn extends je{connectionBlocks=new Array;mode="dls2";get length(){return this.connectionBlocks.length}copyFrom(A){this.mode=A.mode,A.connectionBlocks.forEach(t=>{this.connectionBlocks.push(ct.copyFrom(t))})}fromSFZone(A){this.mode="dls2";let t=new Vt;t.copyFrom(A);for(let n of t.generators){let s;switch(n.generatorType){default:continue;case r.keyNumToVolEnvDecay:s=r.decayVolEnv;break;case r.keyNumToVolEnvHold:s=r.holdVolEnv;break;case r.keyNumToModEnvDecay:s=r.decayModEnv;break;case r.keyNumToModEnvHold:s=r.holdModEnv}let a=t.getGenerator(s,void 0),i=n.generatorValue*-128;if(a===void 0)continue;let I=60/128*i,o=a-I;t.setGenerator(n.generatorType,i,!1),t.setGenerator(s,o,!1)}for(let n of t.generators)ct.fromSFGenerator(n,this);for(let n of t.modulators)ct.fromSFModulator(n,this)}read(A){let t=fe(A,"lart"),n=fe(A,"lar2");if(t)for(this.mode="dls1";t.data.currentIndex<t.data.length;){let s=iA(t.data);Wn.verifyHeader(s,"art1");let a=s.data,i=N(a,4);i!==8&&sA(`CbSize in articulation mismatch. Expected 8, got ${i}`);let I=N(a,4);for(let o=0;o<I;o++)this.connectionBlocks.push(ct.read(a))}else if(n)for(this.mode="dls2";n.data.currentIndex<n.data.length;){let s=iA(n.data);Wn.verifyHeader(s,"art2");let a=s.data,i=N(a,4);i!==8&&sA(`CbSize in articulation mismatch. Expected 8, got ${i}`);let I=N(a,4);for(let o=0;o<I;o++)this.connectionBlocks.push(ct.read(a))}}write(){let A=new Y(8);gA(A,8),gA(A,this.connectionBlocks.length);let t=this.connectionBlocks.map(s=>s.write()),n=vA(this.mode==="dls2"?"art2":"art1",[A,...t]);return cA(this.mode==="dls2"?"lar2":"lart",n,!1,!0)}toSFZone(A){let t=(n,s,a,i)=>{let I=n/-128;if(A.setGenerator(s,I),I<=120){let o=Math.round(.46875*n),g=this.connectionBlocks.find(B=>B.isStaticParameter&&B.destination===i);g&&A.setGenerator(a,o+g.shortScale)}};for(let n of this.connectionBlocks){let s=n.shortScale,a=n.source.source,i=n.control.source,I=n.destination;if(n.isStaticParameter){n.toSFGenerator(A);continue}if(i===T.none)if(a===T.keyNum){if(I===R.pitch){A.setGenerator(r.scaleTuning,s/128);continue}if(I===R.modEnvHold||I===R.modEnvDecay||I===R.volEnvHold||I==R.volEnvDecay)continue}else{let o=n.toCombinedSFDestination();if(o){A.setGenerator(o,s);continue}}n.toSFModulator(A)}this.mode==="dls1"&&A.addModulators(EA.copyFrom(Gi),EA.copyFrom(Ri));for(let n of this.connectionBlocks){if(n.source.source!==T.keyNum)continue;let s=n.shortScale;switch(n.destination){default:continue;case R.volEnvHold:t(s,r.keyNumToVolEnvHold,r.holdVolEnv,R.volEnvHold);break;case R.volEnvDecay:t(s,r.keyNumToVolEnvDecay,r.decayVolEnv,R.volEnvDecay);break;case R.modEnvHold:t(s,r.keyNumToModEnvHold,r.holdModEnv,R.modEnvHold);break;case R.modEnvDecay:t(s,r.keyNumToModEnvDecay,r.decayModEnv,R.modEnvDecay);break}}}},wn=class Ut{channel=1;tableIndex;fusOptions=0;phaseGroup=0;constructor(A){this.tableIndex=A}static copyFrom(A){let t=new Ut(A.tableIndex);return t.channel=A.channel,t.phaseGroup=A.phaseGroup,t.fusOptions=A.fusOptions,t}static read(A){let t=N(A.data,2),n=N(A.data,2),s=N(A.data,4),a=N(A.data,4),i=new Ut(a);return i.channel=s,i.fusOptions=t,i.phaseGroup=n,i}static fromSFZone(A,t){let n=A.indexOf(t.sample);if(n<0)throw new Error(`Wave link error: Sample ${t.sample.name} does not exist in the sample list.`);let s=new Ut(n);switch(t.sample.sampleType){default:case wA.leftSample:case wA.monoSample:s.channel=1;break;case wA.rightSample:s.channel=2}return s}write(){let A=new Y(12);return J(A,this.fusOptions),J(A,this.phaseGroup),gA(A,this.channel),gA(A,this.tableIndex),cA("wlnk",A)}},Tt=class Ve extends je{articulation=new Da;keyRange={min:0,max:127};velRange={min:0,max:127};keyGroup=0;fusOptions=0;usLayer=0;waveSample;waveLink;constructor(A,t){super(),this.waveSample=t,this.waveLink=A}static copyFrom(A){let t=new Ve(wn.copyFrom(A.waveLink),ze.copyFrom(A.waveSample));return t.keyGroup=A.keyGroup,t.keyRange={...A.keyRange},t.velRange={...A.velRange},t.usLayer=A.usLayer,t.fusOptions=A.fusOptions,t.articulation.copyFrom(A.articulation),t}static read(A,t){let n=this.verifyAndReadList(t,"rgn ","rgn2"),s=n.find(m=>m.header==="wsmp"),a=s?ze.read(s):void 0,i=n.find(m=>m.header==="wlnk");if(!i){sA("Invalid DLS region: missing 'wlnk' chunk! Discarding...");return}let I=wn.read(i),o=n.find(m=>m.header==="rgnh");if(!o){sA("Invalid DLS region: missing 'rgnh' chunk! Discarding...");return}let g=A[I.tableIndex];g||Ve.parsingError(`Invalid sample index: ${I.tableIndex}. Samples available: ${A.length}`),a??=g.waveSample;let B=new Ve(I,a),d=N(o.data,2),h=N(o.data,2),C=N(o.data,2),Q=N(o.data,2);return C===0&&Q===0&&(Q=127,C=0),B.keyRange.max=h,B.keyRange.min=d,B.velRange.max=Q,B.velRange.min=C,B.fusOptions=N(o.data,2),B.keyGroup=N(o.data,2),o.data.length-o.data.currentIndex>=2&&(B.usLayer=N(o.data,2)),B.articulation.read(n),B}static fromSFZone(A,t){let n=ze.fromSFZone(A),s=wn.fromSFZone(t,A),a=new Ve(s,n);return a.keyRange.min=Math.max(A.keyRange.min,0),a.keyRange.max=A.keyRange.max,a.velRange.min=Math.max(A.velRange.min,0),a.velRange.max=A.velRange.max,a.keyGroup=A.getGenerator(r.exclusiveClass,0),a.articulation.fromSFZone(A),a}write(){let A=[this.writeHeader(),this.waveSample.write(),this.waveLink.write(),this.articulation.write()];return vA("rgn2",A,!0)}toSFZone(A,t){let n=t[this.waveLink.tableIndex];n||Ve.parsingError(`Invalid sample index: ${this.waveLink.tableIndex}`);let s=A.createZone(n);return s.keyRange=this.keyRange,s.velRange=this.velRange,this.keyRange.max===127&&this.keyRange.min===0&&(s.keyRange.min=-1),this.velRange.max===127&&this.velRange.min===0&&(s.velRange.min=-1),this.keyGroup!==0&&s.setGenerator(r.exclusiveClass,this.keyGroup),this.waveSample.toSFZone(s,n),this.articulation.toSFZone(s),s.generators=s.generators.filter(a=>a.generatorValue!==x[a.generatorType].def),s}writeHeader(){let A=new Y(12);return J(A,Math.max(this.keyRange.min,0)),J(A,this.keyRange.max),J(A,Math.max(this.velRange.min,0)),J(A,this.velRange.max),J(A,this.fusOptions),J(A,this.keyGroup),J(A,this.usLayer),cA("rgnh",A)}},Fn=class xt extends je{articulation=new Da;regions=new Array;name="Unnamed";bankLSB=0;bankMSB=0;isGMGSDrum=!1;program=0;static copyFrom(A){let t=new xt;return t.name=A.name,t.isGMGSDrum=A.isGMGSDrum,t.bankMSB=A.bankMSB,t.bankLSB=A.bankLSB,t.program=A.program,t.articulation.copyFrom(A.articulation),A.regions.forEach(n=>{t.regions.push(Tt.copyFrom(n))}),t}static read(A,t){let n=this.verifyAndReadList(t,"ins "),s=n.find(h=>h.header==="insh");if(!s)throw Z(),new Error("No instrument header!");let a="",i=fe(n,"INFO");if(i){let h=iA(i.data);for(;h.header!=="INAM";)h=iA(i.data);a=hA(h.data,h.data.length).trim()}a.length<1&&(a="Unnamed Instrument");let I=new xt;I.name=a;let o=N(s.data,4),g=N(s.data,4),B=N(s.data,4);I.program=B&127,I.bankMSB=g>>>8&127,I.bankLSB=g&127,I.isGMGSDrum=g>>>31>0,bA(`%cParsing %c"${a}"%c...`,c.info,c.recognized,c.info);let d=fe(n,"lrgn");if(!d)throw Z(),new Error("No region list!");I.articulation.read(n);for(let h=0;h<o;h++){let C=iA(d.data);this.verifyHeader(C,"LIST");let Q=hA(C.data,4);Q!=="rgn "&&Q!=="rgn2"&&(Z(),this.parsingError(`Invalid DLS region! Expected "rgn " or "rgn2" got "${Q}"`));let m=Tt.read(A,C);m&&I.regions.push(m)}return Z(),I}static fromSFPreset(A,t){let n=new xt;return n.name=A.name,n.bankLSB=A.bankLSB,n.bankMSB=A.bankMSB,n.program=A.program,n.isGMGSDrum=A.isGMGSDrum,OA(`%cConverting %c${A.toString()}%c to DLS...`,c.info,c.value,c.info),A.toFlattenedInstrument().zones.forEach(a=>{n.regions.push(Tt.fromSFZone(a,t))}),Z(),n}write(){bA(`%cWriting %c${this.name}%c...`,c.info,c.recognized,c.info);let A=[this.writeHeader()],t=this.regions.map(s=>s.write());A.push(vA("lrgn",t,!0)),this.articulation.length>0&&A.push(this.articulation.write());let n=cA("INAM",ne(this.name,!0));return A.push(cA("INFO",n,!1,!0)),Z(),vA("ins ",A,!0)}toSFPreset(A){let t=new pe(A);t.name=this.name,t.bankMSB=this.bankMSB,t.bankLSB=this.bankLSB,t.isGMGSDrum=this.isGMGSDrum,t.program=this.program;let n=new dt;n.name=this.name,t.createZone(n),this.articulation.toSFZone(n.globalZone),this.regions.forEach(s=>s.toSFZone(n,A.samples)),n.globalize(),n.globalZone.modulators.find(s=>s.destination===r.reverbEffectsSend)===void 0&&n.globalZone.addModulators(EA.copyFrom(ya)),n.globalZone.modulators.find(s=>s.destination===r.chorusEffectsSend)===void 0&&n.globalZone.addModulators(EA.copyFrom(ka)),n.globalZone.generators=n.globalZone.generators.filter(s=>s.generatorValue!==x[s.generatorType].def),A.addPresets(t),A.addInstruments(n)}writeHeader(){let A=new Y(12);gA(A,this.regions.length);let t=(this.bankMSB&127)<<8|this.bankLSB&127;return this.isGMGSDrum&&(t|=1<<31),gA(A,t),gA(A,this.program&127),cA("insh",A)}},wa={progressFunction:void 0},Fa=class _n extends je{samples=new Array;instruments=new Array;soundBankInfo={name:"Unnamed",creationDate:new Date,software:"SpessaSynth",soundEngine:"DLS Level 2.2",version:{major:2,minor:4}};static read(A){if(!A)throw new Error("No data provided!");let t=new Y(A);OA("%cParsing DLS file...",c.info);let n=iA(t,!1);this.verifyHeader(n,"RIFF"),this.verifyText(hA(t,4).toLowerCase(),"dls ");let s=[];for(;t.currentIndex<t.length;)s.push(iA(t));let a=new _n;a.soundBankInfo.name="Unnamed DLS",a.soundBankInfo.product="SpessaSynth DLS",a.soundBankInfo.comment="(no description)";let i=fe(s,"INFO");if(i)for(;i.data.currentIndex<i.data.length;){let Q=iA(i.data),m=Q.header,y=hA(Q.data,Q.size);switch(m){case"INAM":a.soundBankInfo.name=y;break;case"ICRD":a.soundBankInfo.creationDate=ts(y);break;case"ICMT":a.soundBankInfo.comment=y;break;case"ISBJ":a.soundBankInfo.subject=y;break;case"ICOP":a.soundBankInfo.copyright=y;break;case"IENG":a.soundBankInfo.engineer=y;break;case"IPRD":a.soundBankInfo.product=y;break;case"ISFT":a.soundBankInfo.software=y}}this.printInfo(a);let I=s.find(Q=>Q.header==="colh");if(!I)return this.parsingError("No colh chunk!"),5;let o=N(I.data,4);p(`%cInstruments amount: %c${o}`,c.info,c.recognized);let g=fe(s,"wvpl");if(!g)return this.parsingError("No wvpl chunk!"),5;this.verifyAndReadList(g,"wvpl").forEach(Q=>{a.samples.push(Ls.read(Q))});let d=fe(s,"lins");if(!d)return this.parsingError("No lins chunk!"),5;let h=this.verifyAndReadList(d,"lins");bA("%cLoading instruments...",c.info),h.length!==o&&sA(`Colh reported invalid amount of instruments. Detected ${h.length}, expected ${o}`),h.forEach(Q=>{a.instruments.push(Fn.read(a.samples,Q))}),Z();let C=s.find(Q=>Q.header==="pgal");if(C){p("%cFound the instrument aliasing chunk!",c.recognized);let Q=C.data;Q[0]===2&&Q[1]+Q[2]+Q[3]===0&&(Q.currentIndex+=4);let m=a.instruments.find(F=>fA.isXGDrums(F.bankMSB)||F.isGMGSDrum);if(!m)return sA("MobileBAE aliasing chunk without a drum preset. Aborting!"),a;let y=Q.slice(Q.currentIndex,Q.currentIndex+128);Q.currentIndex+=128;for(let F=0;F<128;F++){let k=y[F];if(k===F)continue;let D=m.regions.find(L=>L.keyRange.max===k&&L.keyRange.min===k);if(!D){sA(`Invalid drum alias ${F} to ${k}: region does not exist.`);continue}let v=Tt.copyFrom(D);v.keyRange.max=F,v.keyRange.min=F,m.regions.push(v)}for(Q.currentIndex+=4;Q.currentIndex<Q.length;){let F=N(Q,2),k=F&127,D=F>>7&127,v=Q[Q.currentIndex++],L=Q[Q.currentIndex++];L!==0&&sA(`Invalid alias byte. Expected 0, got ${L}`);let E=N(Q,2),X=E&127,O=E>>7&127,nA=Q[Q.currentIndex++];L=Q[Q.currentIndex++],L!==0&&sA(`Invalid alias header. Expected 0, got ${L}`);let $=a.instruments.find(q=>q.bankLSB===X&&q.bankMSB===O&&q.program===nA&&!q.isGMGSDrum);if(!$){sA(`Invalid alias. Missing instrument: ${X}:${O}:${nA}`);continue}let V=Fn.copyFrom($);V.bankMSB=D,V.bankLSB=k,V.program=v,a.instruments.push(V)}}return p(`%cParsing finished! %c"${a.soundBankInfo.name||"UNNAMED"}"%c has %c${a.instruments.length}%c instruments and %c${a.samples.length}%c samples.`,c.info,c.recognized,c.info,c.recognized,c.info,c.recognized,c.info),Z(),a}static fromSF(A){bA("%cSaving SF2 to DLS level 2...",c.info);let t=new _n;return t.soundBankInfo={...A.soundBankInfo},t.soundBankInfo.comment=(t.soundBankInfo.comment??"(No description)")+`
17
+ (${g})`,c.warn,c.value,c.unrecognized)},I=this.toCombinedSFDestination();if(I){n=I;let g=this.control.toSFSource();if(!g){i("Invalid control");return}s=g}else{let g=this.toSFDestination();if(!g){i("Invalid destination");return}typeof g=="object"?(t=g.newAmount,n=g.gen):n=g;let B=this.source.toSFSource();if(!B){i("Invalid source");return}s=B;let d=this.control.toSFSource();if(!d){i("Invalid control");return}a=d}this.transform!==QA.linear&&s.curveType===QA.linear&&(s.curveType=this.transform),n===r.initialAttenuation&&((this.source.source===T.velocity||this.source.source===T.volume||this.source.source===T.expression)&&(s.isNegative=!0),t=Math.min(960,Math.max(0,t)));let o=new EA(s,a,n,t,0);A.addModulators(o)}toCombinedSFDestination(){let A=this.source.source,t=this.destination;return A===T.vibratoLfo&&t===R.pitch?r.vibLfoToPitch:A===T.modLfo&&t===R.pitch?r.modLfoToPitch:A===T.modLfo&&t===R.filterCutoff?r.modLfoToFilterFc:A===T.modLfo&&t===R.gain?r.modLfoToVolume:A===T.modEnv&&t===R.filterCutoff?r.modEnvToFilterFc:A===T.modEnv&&t===R.pitch?r.modEnvToPitch:void 0}toSFDestination(){let A=this.shortScale;switch(this.destination){default:case R.none:return;case R.pan:return r.pan;case R.gain:return{gen:r.initialAttenuation,newAmount:-A};case R.pitch:return r.fineTune;case R.keyNum:return r.overridingRootKey;case R.volEnvDelay:return r.delayVolEnv;case R.volEnvAttack:return r.attackVolEnv;case R.volEnvHold:return r.holdVolEnv;case R.volEnvDecay:return r.decayVolEnv;case R.volEnvSustain:return{gen:r.sustainVolEnv,newAmount:1e3-A};case R.volEnvRelease:return r.releaseVolEnv;case R.modEnvDelay:return r.delayModEnv;case R.modEnvAttack:return r.attackModEnv;case R.modEnvHold:return r.holdModEnv;case R.modEnvDecay:return r.decayModEnv;case R.modEnvSustain:return{gen:r.sustainModEnv,newAmount:1e3-A};case R.modEnvRelease:return r.releaseModEnv;case R.filterCutoff:return r.initialFilterFc;case R.filterQ:return r.initialFilterQ;case R.chorusSend:return r.chorusEffectsSend;case R.reverbSend:return r.reverbEffectsSend;case R.modLfoFreq:return r.freqModLFO;case R.modLfoDelay:return r.delayModLFO;case R.vibLfoFreq:return r.freqVibLFO;case R.vibLfoDelay:return r.delayVibLFO}}},Da=class Wn extends je{connectionBlocks=new Array;mode="dls2";get length(){return this.connectionBlocks.length}copyFrom(A){this.mode=A.mode,A.connectionBlocks.forEach(t=>{this.connectionBlocks.push(ct.copyFrom(t))})}fromSFZone(A){this.mode="dls2";let t=new Vt;t.copyFrom(A);for(let n of t.generators){let s;switch(n.generatorType){default:continue;case r.keyNumToVolEnvDecay:s=r.decayVolEnv;break;case r.keyNumToVolEnvHold:s=r.holdVolEnv;break;case r.keyNumToModEnvDecay:s=r.decayModEnv;break;case r.keyNumToModEnvHold:s=r.holdModEnv}let a=t.getGenerator(s,void 0),i=n.generatorValue*-128;if(a===void 0)continue;let I=60/128*i,o=a-I;t.setGenerator(n.generatorType,i,!1),t.setGenerator(s,o,!1)}for(let n of t.generators)ct.fromSFGenerator(n,this);for(let n of t.modulators)ct.fromSFModulator(n,this)}read(A){let t=fe(A,"lart"),n=fe(A,"lar2");if(t)for(this.mode="dls1";t.data.currentIndex<t.data.length;){let s=iA(t.data);Wn.verifyHeader(s,"art1","art2");let a=s.data,i=N(a,4);i!==8&&sA(`CbSize in articulation mismatch. Expected 8, got ${i}`);let I=N(a,4);for(let o=0;o<I;o++)this.connectionBlocks.push(ct.read(a))}else if(n)for(this.mode="dls2";n.data.currentIndex<n.data.length;){let s=iA(n.data);Wn.verifyHeader(s,"art2","art1");let a=s.data,i=N(a,4);i!==8&&sA(`CbSize in articulation mismatch. Expected 8, got ${i}`);let I=N(a,4);for(let o=0;o<I;o++)this.connectionBlocks.push(ct.read(a))}}write(){let A=new Y(8);gA(A,8),gA(A,this.connectionBlocks.length);let t=this.connectionBlocks.map(s=>s.write()),n=vA(this.mode==="dls2"?"art2":"art1",[A,...t]);return cA(this.mode==="dls2"?"lar2":"lart",n,!1,!0)}toSFZone(A){let t=(n,s,a,i)=>{let I=n/-128;if(A.setGenerator(s,I),I<=120){let o=Math.round(.46875*n),g=this.connectionBlocks.find(B=>B.isStaticParameter&&B.destination===i);g&&A.setGenerator(a,o+g.shortScale)}};for(let n of this.connectionBlocks){let s=n.shortScale,a=n.source.source,i=n.control.source,I=n.destination;if(n.isStaticParameter){n.toSFGenerator(A);continue}if(i===T.none)if(a===T.keyNum){if(I===R.pitch){A.setGenerator(r.scaleTuning,s/128);continue}if(I===R.modEnvHold||I===R.modEnvDecay||I===R.volEnvHold||I==R.volEnvDecay)continue}else{let o=n.toCombinedSFDestination();if(o){A.setGenerator(o,s);continue}}n.toSFModulator(A)}this.mode==="dls1"&&A.addModulators(EA.copyFrom(Gi),EA.copyFrom(Ri));for(let n of this.connectionBlocks){if(n.source.source!==T.keyNum)continue;let s=n.shortScale;switch(n.destination){default:continue;case R.volEnvHold:t(s,r.keyNumToVolEnvHold,r.holdVolEnv,R.volEnvHold);break;case R.volEnvDecay:t(s,r.keyNumToVolEnvDecay,r.decayVolEnv,R.volEnvDecay);break;case R.modEnvHold:t(s,r.keyNumToModEnvHold,r.holdModEnv,R.modEnvHold);break;case R.modEnvDecay:t(s,r.keyNumToModEnvDecay,r.decayModEnv,R.modEnvDecay);break}}}},wn=class Ut{channel=1;tableIndex;fusOptions=0;phaseGroup=0;constructor(A){this.tableIndex=A}static copyFrom(A){let t=new Ut(A.tableIndex);return t.channel=A.channel,t.phaseGroup=A.phaseGroup,t.fusOptions=A.fusOptions,t}static read(A){let t=N(A.data,2),n=N(A.data,2),s=N(A.data,4),a=N(A.data,4),i=new Ut(a);return i.channel=s,i.fusOptions=t,i.phaseGroup=n,i}static fromSFZone(A,t){let n=A.indexOf(t.sample);if(n<0)throw new Error(`Wave link error: Sample ${t.sample.name} does not exist in the sample list.`);let s=new Ut(n);switch(t.sample.sampleType){default:case wA.leftSample:case wA.monoSample:s.channel=1;break;case wA.rightSample:s.channel=2}return s}write(){let A=new Y(12);return J(A,this.fusOptions),J(A,this.phaseGroup),gA(A,this.channel),gA(A,this.tableIndex),cA("wlnk",A)}},Tt=class Ve extends je{articulation=new Da;keyRange={min:0,max:127};velRange={min:0,max:127};keyGroup=0;fusOptions=0;usLayer=0;waveSample;waveLink;constructor(A,t){super(),this.waveSample=t,this.waveLink=A}static copyFrom(A){let t=new Ve(wn.copyFrom(A.waveLink),ze.copyFrom(A.waveSample));return t.keyGroup=A.keyGroup,t.keyRange={...A.keyRange},t.velRange={...A.velRange},t.usLayer=A.usLayer,t.fusOptions=A.fusOptions,t.articulation.copyFrom(A.articulation),t}static read(A,t){let n=this.verifyAndReadList(t,"rgn ","rgn2"),s=n.find(m=>m.header==="wsmp"),a=s?ze.read(s):void 0,i=n.find(m=>m.header==="wlnk");if(!i){sA("Invalid DLS region: missing 'wlnk' chunk! Discarding...");return}let I=wn.read(i),o=n.find(m=>m.header==="rgnh");if(!o){sA("Invalid DLS region: missing 'rgnh' chunk! Discarding...");return}let g=A[I.tableIndex];g||Ve.parsingError(`Invalid sample index: ${I.tableIndex}. Samples available: ${A.length}`),a??=g.waveSample;let B=new Ve(I,a),d=N(o.data,2),h=N(o.data,2),C=N(o.data,2),Q=N(o.data,2);return C===0&&Q===0&&(Q=127,C=0),B.keyRange.max=h,B.keyRange.min=d,B.velRange.max=Q,B.velRange.min=C,B.fusOptions=N(o.data,2),B.keyGroup=N(o.data,2),o.data.length-o.data.currentIndex>=2&&(B.usLayer=N(o.data,2)),B.articulation.read(n),B}static fromSFZone(A,t){let n=ze.fromSFZone(A),s=wn.fromSFZone(t,A),a=new Ve(s,n);return a.keyRange.min=Math.max(A.keyRange.min,0),a.keyRange.max=A.keyRange.max,a.velRange.min=Math.max(A.velRange.min,0),a.velRange.max=A.velRange.max,a.keyGroup=A.getGenerator(r.exclusiveClass,0),a.articulation.fromSFZone(A),a}write(){let A=[this.writeHeader(),this.waveSample.write(),this.waveLink.write(),this.articulation.write()];return vA("rgn2",A,!0)}toSFZone(A,t){let n=t[this.waveLink.tableIndex];n||Ve.parsingError(`Invalid sample index: ${this.waveLink.tableIndex}`);let s=A.createZone(n);return s.keyRange=this.keyRange,s.velRange=this.velRange,this.keyRange.max===127&&this.keyRange.min===0&&(s.keyRange.min=-1),this.velRange.max===127&&this.velRange.min===0&&(s.velRange.min=-1),this.keyGroup!==0&&s.setGenerator(r.exclusiveClass,this.keyGroup),this.waveSample.toSFZone(s,n),this.articulation.toSFZone(s),s.generators=s.generators.filter(a=>a.generatorValue!==x[a.generatorType].def),s}writeHeader(){let A=new Y(12);return J(A,Math.max(this.keyRange.min,0)),J(A,this.keyRange.max),J(A,Math.max(this.velRange.min,0)),J(A,this.velRange.max),J(A,this.fusOptions),J(A,this.keyGroup),J(A,this.usLayer),cA("rgnh",A)}},Fn=class xt extends je{articulation=new Da;regions=new Array;name="Unnamed";bankLSB=0;bankMSB=0;isGMGSDrum=!1;program=0;static copyFrom(A){let t=new xt;return t.name=A.name,t.isGMGSDrum=A.isGMGSDrum,t.bankMSB=A.bankMSB,t.bankLSB=A.bankLSB,t.program=A.program,t.articulation.copyFrom(A.articulation),A.regions.forEach(n=>{t.regions.push(Tt.copyFrom(n))}),t}static read(A,t){let n=this.verifyAndReadList(t,"ins "),s=n.find(h=>h.header==="insh");if(!s)throw Z(),new Error("No instrument header!");let a="",i=fe(n,"INFO");if(i){let h=iA(i.data);for(;h.header!=="INAM";)h=iA(i.data);a=hA(h.data,h.data.length).trim()}a.length<1&&(a="Unnamed Instrument");let I=new xt;I.name=a;let o=N(s.data,4),g=N(s.data,4),B=N(s.data,4);I.program=B&127,I.bankMSB=g>>>8&127,I.bankLSB=g&127,I.isGMGSDrum=g>>>31>0,bA(`%cParsing %c"${a}"%c...`,c.info,c.recognized,c.info);let d=fe(n,"lrgn");if(!d)throw Z(),new Error("No region list!");I.articulation.read(n);for(let h=0;h<o;h++){let C=iA(d.data);this.verifyHeader(C,"LIST");let Q=hA(C.data,4);Q!=="rgn "&&Q!=="rgn2"&&(Z(),this.parsingError(`Invalid DLS region! Expected "rgn " or "rgn2" got "${Q}"`));let m=Tt.read(A,C);m&&I.regions.push(m)}return Z(),I}static fromSFPreset(A,t){let n=new xt;return n.name=A.name,n.bankLSB=A.bankLSB,n.bankMSB=A.bankMSB,n.program=A.program,n.isGMGSDrum=A.isGMGSDrum,OA(`%cConverting %c${A.toString()}%c to DLS...`,c.info,c.value,c.info),A.toFlattenedInstrument().zones.forEach(a=>{n.regions.push(Tt.fromSFZone(a,t))}),Z(),n}write(){bA(`%cWriting %c${this.name}%c...`,c.info,c.recognized,c.info);let A=[this.writeHeader()],t=this.regions.map(s=>s.write());A.push(vA("lrgn",t,!0)),this.articulation.length>0&&A.push(this.articulation.write());let n=cA("INAM",ne(this.name,!0));return A.push(cA("INFO",n,!1,!0)),Z(),vA("ins ",A,!0)}toSFPreset(A){let t=new pe(A);t.name=this.name,t.bankMSB=this.bankMSB,t.bankLSB=this.bankLSB,t.isGMGSDrum=this.isGMGSDrum,t.program=this.program;let n=new dt;n.name=this.name,t.createZone(n),this.articulation.toSFZone(n.globalZone),this.regions.forEach(s=>s.toSFZone(n,A.samples)),n.globalize(),n.globalZone.modulators.find(s=>s.destination===r.reverbEffectsSend)===void 0&&n.globalZone.addModulators(EA.copyFrom(ya)),n.globalZone.modulators.find(s=>s.destination===r.chorusEffectsSend)===void 0&&n.globalZone.addModulators(EA.copyFrom(ka)),n.globalZone.generators=n.globalZone.generators.filter(s=>s.generatorValue!==x[s.generatorType].def),A.addPresets(t),A.addInstruments(n)}writeHeader(){let A=new Y(12);gA(A,this.regions.length);let t=(this.bankMSB&127)<<8|this.bankLSB&127;return this.isGMGSDrum&&(t|=1<<31),gA(A,t),gA(A,this.program&127),cA("insh",A)}},wa={progressFunction:void 0},Fa=class _n extends je{samples=new Array;instruments=new Array;soundBankInfo={name:"Unnamed",creationDate:new Date,software:"SpessaSynth",soundEngine:"DLS Level 2.2",version:{major:2,minor:4}};static read(A){if(!A)throw new Error("No data provided!");let t=new Y(A);OA("%cParsing DLS file...",c.info);let n=iA(t,!1);this.verifyHeader(n,"RIFF"),this.verifyText(hA(t,4).toLowerCase(),"dls ");let s=[];for(;t.currentIndex<t.length;)s.push(iA(t));let a=new _n;a.soundBankInfo.name="Unnamed DLS",a.soundBankInfo.product="SpessaSynth DLS",a.soundBankInfo.comment="(no description)";let i=fe(s,"INFO");if(i)for(;i.data.currentIndex<i.data.length;){let Q=iA(i.data),m=Q.header,y=hA(Q.data,Q.size);switch(m){case"INAM":a.soundBankInfo.name=y;break;case"ICRD":a.soundBankInfo.creationDate=ts(y);break;case"ICMT":a.soundBankInfo.comment=y;break;case"ISBJ":a.soundBankInfo.subject=y;break;case"ICOP":a.soundBankInfo.copyright=y;break;case"IENG":a.soundBankInfo.engineer=y;break;case"IPRD":a.soundBankInfo.product=y;break;case"ISFT":a.soundBankInfo.software=y}}this.printInfo(a);let I=s.find(Q=>Q.header==="colh");if(!I)return this.parsingError("No colh chunk!"),5;let o=N(I.data,4);p(`%cInstruments amount: %c${o}`,c.info,c.recognized);let g=fe(s,"wvpl");if(!g)return this.parsingError("No wvpl chunk!"),5;this.verifyAndReadList(g,"wvpl").forEach(Q=>{a.samples.push(Ls.read(Q))});let d=fe(s,"lins");if(!d)return this.parsingError("No lins chunk!"),5;let h=this.verifyAndReadList(d,"lins");bA("%cLoading instruments...",c.info),h.length!==o&&sA(`Colh reported invalid amount of instruments. Detected ${h.length}, expected ${o}`),h.forEach(Q=>{a.instruments.push(Fn.read(a.samples,Q))}),Z();let C=s.find(Q=>Q.header==="pgal");if(C){p("%cFound the instrument aliasing chunk!",c.recognized);let Q=C.data;Q[0]===2&&Q[1]+Q[2]+Q[3]===0&&(Q.currentIndex+=4);let m=a.instruments.find(F=>fA.isXGDrums(F.bankMSB)||F.isGMGSDrum);if(!m)return sA("MobileBAE aliasing chunk without a drum preset. Aborting!"),a;let y=Q.slice(Q.currentIndex,Q.currentIndex+128);Q.currentIndex+=128;for(let F=0;F<128;F++){let k=y[F];if(k===F)continue;let D=m.regions.find(L=>L.keyRange.max===k&&L.keyRange.min===k);if(!D){sA(`Invalid drum alias ${F} to ${k}: region does not exist.`);continue}let v=Tt.copyFrom(D);v.keyRange.max=F,v.keyRange.min=F,m.regions.push(v)}for(Q.currentIndex+=4;Q.currentIndex<Q.length;){let F=N(Q,2),k=F&127,D=F>>7&127,v=Q[Q.currentIndex++],L=Q[Q.currentIndex++];L!==0&&sA(`Invalid alias byte. Expected 0, got ${L}`);let E=N(Q,2),X=E&127,O=E>>7&127,nA=Q[Q.currentIndex++];L=Q[Q.currentIndex++],L!==0&&sA(`Invalid alias header. Expected 0, got ${L}`);let $=a.instruments.find(q=>q.bankLSB===X&&q.bankMSB===O&&q.program===nA&&!q.isGMGSDrum);if(!$){sA(`Invalid alias. Missing instrument: ${X}:${O}:${nA}`);continue}let V=Fn.copyFrom($);V.bankMSB=D,V.bankLSB=k,V.program=v,a.instruments.push(V)}}return p(`%cParsing finished! %c"${a.soundBankInfo.name||"UNNAMED"}"%c has %c${a.instruments.length}%c instruments and %c${a.samples.length}%c samples.`,c.info,c.recognized,c.info,c.recognized,c.info,c.recognized,c.info),Z(),a}static fromSF(A){bA("%cSaving SF2 to DLS level 2...",c.info);let t=new _n;return t.soundBankInfo={...A.soundBankInfo},t.soundBankInfo.comment=(t.soundBankInfo.comment??"(No description)")+`
18
18
  Converted from SF2 to DLS with SpessaSynth`,A.samples.forEach(n=>{t.samples.push(Ls.fromSFSample(n))}),A.presets.forEach(n=>{t.instruments.push(Fn.fromSFPreset(n,A.samples))}),p("%cConversion complete!",c.recognized),Z(),t}static printInfo(A){for(let[t,n]of Object.entries(A.soundBankInfo)){if(typeof n=="object"&&"major"in n){let s=n;p(`%c${t}: %c"${s.major}.${s.minor}"`,c.info,c.recognized)}p(`%c${t}: %c${n.toLocaleString()}`,c.info,c.recognized)}}async write(A=wa){bA("%cSaving DLS...",c.info);let t=new Y(4);gA(t,this.instruments.length);let n=cA("colh",t);bA("%cWriting instruments...",c.info);let s=vA("lins",this.instruments.map(y=>y.write()),!0);p("%cSuccess!",c.recognized),Z(),bA("%cWriting WAVE samples...",c.info);let a=0,i=[],I=[],o=0;for(let y of this.samples){let F=y.write();await A?.progressFunction?.(y.name,o,this.samples.length),i.push(a),a+=F.length,I.push(F),o++}let g=vA("wvpl",I,!0);p("%cSucceeded!",c.recognized);let B=new Y(8+4*i.length);gA(B,8),gA(B,i.length);for(let y of i)gA(B,y);let d=cA("ptbl",B);this.soundBankInfo.software="SpessaSynth";let h=[],C=(y,F)=>{h.push(cA(y,ne(F,!0)))};for(let[y,F]of Object.entries(this.soundBankInfo)){let k=y,D=F;if(D)switch(k){case"name":C("INAM",D);break;case"comment":C("ICMT",D);break;case"copyright":C("ICOP",D);break;case"creationDate":C("ICRD",D.toISOString());break;case"engineer":C("IENG",D);break;case"product":C("IPRD",D);break;case"romVersion":case"version":case"soundEngine":case"romInfo":break;case"software":C("ISFT",D);break;case"subject":C("ISBJ",D)}}let Q=vA("INFO",h,!0);p("%cCombining everything...");let m=vA("RIFF",[ne("DLS "),n,s,d,g,Q]);return p("%cSaved successfully!",c.recognized),Z(),m.buffer}toSF(){OA("%cConverting DLS to SF2...",c.info);let A=new Ga;return A.soundBankInfo.version.minor=4,A.soundBankInfo.version.major=2,A.soundBankInfo={...this.soundBankInfo},A.soundBankInfo.comment=(A.soundBankInfo.comment??"(No description)")+`
19
19
  Converted from DLS to SF2 with SpessaSynth`,this.samples.forEach(t=>{t.toSFSample(A)}),this.instruments.forEach(t=>{t.toSFPreset(A)}),A.flush(),p("%cConversion complete!",c.recognized),Z(),A}},Ga=class Ht{static isSF3DecoderReady=Ot.isInitialized;soundBankInfo={name:"Unnamed",creationDate:new Date,software:"SpessaSynth",soundEngine:"E-mu 10K2",version:{major:2,minor:4}};presets=[];samples=[];instruments=[];defaultModulators=Ea.map(EA.copyFrom.bind(EA));customDefaultModulators=!1;_isXGBank=!1;get isXGBank(){return this._isXGBank}static mergeSoundBanks(...A){let t=A.shift();if(!t)throw new Error("No sound banks provided!");let n=t.presets;for(;A.length;){let a=A?.shift()?.presets;a&&a.forEach(i=>{n.find(I=>i.matches(I))===void 0&&n.push(i)})}let s=new Ht;return s.addCompletePresets(n),s.soundBankInfo={...t.soundBankInfo},s}static async getSampleSoundBankFile(){let A=new Ht,t=new Float32Array(128);for(let I=0;I<128;I++)t[I]=I/128*2-1;let n=new mi;n.name="Saw",n.originalKey=65,n.pitchCorrection=20,n.loopEnd=127,n.setAudioData(t,44100),A.addSamples(n);let s=new dt;s.name="Saw Wave",s.globalZone.addGenerators(new FA(r.initialAttenuation,375),new FA(r.releaseVolEnv,-1e3),new FA(r.sampleModes,1)),s.createZone(n),s.createZone(n).addGenerators(new FA(r.fineTune,-9)),A.addInstruments(s);let i=new pe(A);return i.name="Saw Wave",i.createZone(s),A.addPresets(i),A.soundBankInfo.name="Dummy",A.flush(),await A.writeSF2()}static copyFrom(A){let t=new Ht;return A.presets.forEach(n=>t.clonePreset(n)),t.soundBankInfo={...A.soundBankInfo},t}addCompletePresets(A){this.addPresets(...A);let t=[];for(let s of A)for(let a of s.zones)a.instrument&&!t.includes(a.instrument)&&t.push(a.instrument);this.addInstruments(...t);let n=[];for(let s of t)for(let a of s.zones)a.sample&&!n.includes(a.sample)&&n.push(a.sample);this.addSamples(...n)}async writeDLS(A=wa){return Fa.fromSF(this).write(A)}async writeSF2(A=Xn){return ki(this,A)}addPresets(...A){this.presets.push(...A)}addInstruments(...A){this.instruments.push(...A)}addSamples(...A){this.samples.push(...A)}cloneSample(A){let t=this.samples.find(s=>s.name===A.name);if(t)return t;let n=new Zt(A.name,A.sampleRate,A.originalKey,A.pitchCorrection,A.sampleType,A.loopStart,A.loopEnd);if(A.isCompressed?n.setCompressedData(A.getRawData(!0)):n.setAudioData(A.getAudioData(),A.sampleRate),this.addSamples(n),A.linkedSample){let s=this.cloneSample(A.linkedSample);s.linkedSample||n.setLinkedSample(s,n.sampleType)}return n}cloneInstrument(A){let t=this.instruments.find(s=>s.name===A.name);if(t)return t;let n=new dt;n.name=A.name,n.globalZone.copyFrom(A.globalZone);for(let s of A.zones)n.createZone(this.cloneSample(s.sample)).copyFrom(s);return this.addInstruments(n),n}clonePreset(A){let t=this.presets.find(s=>s.name===A.name);if(t)return t;let n=new pe(this);n.name=A.name,n.bankMSB=A.bankMSB,n.bankLSB=A.bankLSB,n.isGMGSDrum=A.isGMGSDrum,n.program=A.program,n.library=A.library,n.genre=A.genre,n.morphology=A.morphology,n.globalZone.copyFrom(A.globalZone);for(let s of A.zones)n.createZone(this.cloneInstrument(s.instrument)).copyFrom(s);return this.addPresets(n),n}flush(){this.presets.sort(te.sorter.bind(te)),this.parseInternal()}trimSoundBank(A){let t=(s,a)=>{let i=0;for(let I=0;I<s.zones.length;I++){let o=s.zones[I],g=o.keyRange,B=o.velRange,d=!1;for(let h of a)if(h.key>=g.min&&h.key<=g.max&&h.velocity>=B.min&&h.velocity<=B.max){d=!0;break}!d&&o.sample&&(p(`%c${o.sample.name}%c removed from %c${s.name}%c.`,c.recognized,c.info,c.recognized,c.info),s.deleteZone(I)&&(i++,I--,p(`%c${o.sample.name}%c deleted`,c.recognized,c.info)),o.sample.useCount<1&&this.deleteSample(o.sample))}return i};OA("%cTrimming sound bank...",c.info);let n=A.getUsedProgramsAndKeys(this);bA("%cModifying sound bank...",c.info),p("Detected keys for midi:",n);for(let s=0;s<this.presets.length;s++){let a=this.presets[s],i=n.get(a);if(i===void 0)p(`%cDeleting preset %c${a.name}%c and its zones`,c.info,c.recognized,c.info),this.deletePreset(a),s--;else{let I=[...i].map(g=>{let B=g.split("-");return{key:parseInt(B[0]),velocity:parseInt(B[1])}});bA(`%cTrimming %c${a.name}`,c.info,c.recognized),p(`Keys for ${a.name}:`,I);let o=0;for(let g=0;g<a.zones.length;g++){let B=a.zones[g],d=B.keyRange,h=B.velRange,C=!1;for(let Q of I)if(Q.key>=d.min&&Q.key<=d.max&&Q.velocity>=h.min&&Q.velocity<=h.max&&B.instrument){C=!0;let m=t(B.instrument,I);p(`%cTrimmed off %c${m}%c zones from %c${B.instrument.name}`,c.info,c.recognized,c.info,c.recognized);break}!C&&B.instrument&&(o++,a.deleteZone(g),B.instrument.useCount<1&&this.deleteInstrument(B.instrument),g--)}p(`%cTrimmed off %c${o}%c zones from %c${a.name}`,c.info,c.recognized,c.info,c.recognized),Z()}}this.removeUnusedElements(),p("%cSound bank modified!",c.recognized),Z(),Z()}removeUnusedElements(){this.instruments=this.instruments.filter(A=>{A.deleteUnusedZones();let t=A.useCount<1;return t&&A.delete(),!t}),this.samples=this.samples.filter(A=>{let t=A.useCount<1;return t&&A.unlinkSample(),!t})}deleteInstrument(A){A.delete(),this.instruments.splice(this.instruments.indexOf(A),1)}deletePreset(A){A.delete(),this.presets.splice(this.presets.indexOf(A),1)}deleteSample(A){A.unlinkSample(),this.samples.splice(this.samples.indexOf(A),1)}getPreset(A,t){return Qa(this.presets,A,t)}destroySoundBank(){this.presets.length=0,this.instruments.length=0,this.samples.length=0}parsingError(A){throw new Error(`SF parsing error: ${A} The file may be corrupted.`)}parseInternal(){this._isXGBank=!1;let A=new Set([0,1,2,3,4,5,6,7,8,9,16,17,24,25,26,27,28,29,30,31,32,33,40,41,48,56,57,58,64,65,66,126,127]);for(let t of this.presets)if(fA.isXGDrums(t.bankMSB)&&(this._isXGBank=!0,!A.has(t.program))){this._isXGBank=!1,p(`%cThis bank is not valid XG. Preset %c${t.toString()}%c is not a valid XG drum. XG mode will use presets on bank 128.`,c.info,c.value,c.info);break}}printInfo(){for(let[A,t]of Object.entries(this.soundBankInfo)){if(typeof t=="object"&&"major"in t){let n=t;p(`%c${A}: %c"${n.major}.${n.minor}"`,c.info,c.recognized)}p(`%c${A}: %c${t.toLocaleString()}`,c.info,c.recognized)}}},bi=class extends FA{constructor(e){let A=e.currentIndex,t=e[A+1]<<8|e[A],n=jn(e[A+2],e[A+3]);e.currentIndex+=4,super(t,n,!1)}};function Ns(e){let A=[];for(;e.data.length>e.data.currentIndex;)A.push(new bi(e.data));return A.pop(),A}var vi=class extends Ca{constructor(e,A,t,n){let s=t.find(i=>i.generatorType===r.instrument),a;if(s)a=n[s.generatorValue];else throw new Error("No instrument ID found in preset zone.");super(e,a),this.addGenerators(...t),this.addModulators(...A)}};function Li(e,A,t,n,s){let a=e.gen,i=e.mod,I=0,o=0;for(let g of s)for(let B=0;B<g.zonesCount;B++){let d=a[o++],h=a[o],C=A.slice(d,h),Q=i[I++],m=i[I],y=t.slice(Q,m);C.find(F=>F.generatorType===r.instrument)!==void 0?g.createSoundFontZone(y,C,n):(g.globalZone.addGenerators(...C),g.globalZone.addModulators(...y))}}var Ni=class extends pe{zoneStartIndex;zonesCount=0;constructor(e,A){super(A),this.name=hA(e.data,20).replace(/\d{3}:\d{3}/,""),this.program=N(e.data,2);let t=N(e.data,2);this.bankMSB=t&127,this.isGMGSDrum=(t&128)>0,this.bankLSB=t>>8,this.zoneStartIndex=N(e.data,2),this.library=N(e.data,4),this.genre=N(e.data,4),this.morphology=N(e.data,4)}createSoundFontZone(e,A,t){let n=new vi(this,e,A,t);return this.zones.push(n),n}};function Us(e,A){let t=[];for(;e.data.length>e.data.currentIndex;){let n=new Ni(e,A);if(t.length>0){let s=t[t.length-1];s.zonesCount=n.zoneStartIndex-s.zoneStartIndex}t.push(n)}return t.pop(),t}var Ui=class extends ha{constructor(e,A,t,n){let s=t.find(i=>i.generatorType===r.sampleID),a;if(s)a=n[s.generatorValue];else throw new Error("No sample ID found in instrument zone.");super(e,a),this.addGenerators(...t),this.addModulators(...A)}};function Ti(e,A,t,n,s){let a=e.gen,i=e.mod,I=0,o=0;for(let g of s)for(let B=0;B<g.zonesCount;B++){let d=a[o++],h=a[o],C=A.slice(d,h),Q=i[I++],m=i[I],y=t.slice(Q,m);C.find(F=>F.generatorType===r.sampleID)?g.createSoundFontZone(y,C,n):(g.globalZone.addGenerators(...C),g.globalZone.addModulators(...y))}}var xi=class extends dt{zoneStartIndex;zonesCount=0;constructor(e){super(),this.name=hA(e.data,20),this.zoneStartIndex=N(e.data,2)}createSoundFontZone(e,A,t){let n=new Ui(this,e,A,t);return this.zones.push(n),n}};function Ts(e){let A=[];for(;e.data.length>e.data.currentIndex;){let t=new xi(e);if(A.length>0){let n=A[A.length-1];n.zonesCount=t.zoneStartIndex-n.zoneStartIndex}A.push(t)}return A.pop(),A}function Gn(e){let A=[];for(;e.data.length>e.data.currentIndex;){let t=e.data,n=N(t,2),s=N(t,2),a=jn(t[t.currentIndex++],t[t.currentIndex++]),i=N(t,2),I=N(t,2);A.push(new yA(n,i,s,a,I))}return A.pop(),A}function bt(e){let A=[],t=[];for(;e.data.length>e.data.currentIndex;)t.push(N(e.data,2)),A.push(N(e.data,2));return{mod:A,gen:t}}var Hi=class extends Ga{sampleDataStartIndex=0;constructor(e,A=!0){if(super(),A)throw new Error("Using the constructor directly is deprecated. Use SoundBankLoader.fromArrayBuffer() instead.");let t=new Y(e);OA("%cParsing a SoundFont2 file...",c.info),t||(Z(),this.parsingError("No data provided!"));let n=iA(t,!1);this.verifyHeader(n,"riff");let s=hA(t,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw Z(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let a=s==="sfpk",i=iA(t);this.verifyHeader(i,"list");let I=hA(i.data,4);if(I!=="INFO")throw Z(),new SyntaxError(`Invalid soundFont! Expected "INFO" or "${I}"`);let o;for(;i.data.length>i.data.currentIndex;){let P=iA(i.data),G=ee(P.data,P.data.length),b=P.header;switch(b){case"ifil":case"iver":let K=N(P.data,2),eA=N(P.data,2);b==="ifil"?this.soundBankInfo.version={major:K,minor:eA}:this.soundBankInfo.romVersion={major:K,minor:eA};break;case"DMOD":{this.defaultModulators=Gn(P),this.customDefaultModulators=!0;break}case"LIST":{hA(P.data,4)==="xdta"&&(p("%cExtended SF2 found!",c.recognized),o=P);break}case"ICRD":this.soundBankInfo.creationDate=ts(hA(P.data,P.data.length));break;case"ISFT":this.soundBankInfo.software=G;break;case"IPRD":this.soundBankInfo.product=G;break;case"IENG":this.soundBankInfo.engineer=G;break;case"ICOP":this.soundBankInfo.copyright=G;break;case"INAM":this.soundBankInfo.name=G;break;case"ICMT":this.soundBankInfo.comment=G;break;case"irom":this.soundBankInfo.romInfo=G;break;case"isng":this.soundBankInfo.soundEngine=G}}this.printInfo();let g={};o!==void 0&&(g.phdr=iA(o.data),g.pbag=iA(o.data),g.pmod=iA(o.data),g.pgen=iA(o.data),g.inst=iA(o.data),g.ibag=iA(o.data),g.imod=iA(o.data),g.igen=iA(o.data),g.shdr=iA(o.data));let B=iA(t,!1);this.verifyHeader(B,"list"),this.verifyText(hA(t,4),"sdta"),p("%cVerifying smpl chunk...",c.warn);let d=iA(t,!1);this.verifyHeader(d,"smpl");let h;if(a){p("%cSF2Pack detected, attempting to decode the smpl chunk...",c.info);try{h=Ot.decode(t.buffer.slice(t.currentIndex,t.currentIndex+B.size-12)).data[0]}catch(P){throw Z(),new Error(`SF2Pack Ogg Vorbis decode error: ${P}`)}p(`%cDecoded the smpl chunk! Length: %c${h.length}`,c.info,c.value)}else h=t,this.sampleDataStartIndex=t.currentIndex;p(`%cSkipping sample chunk, length: %c${B.size-12}`,c.info,c.value),t.currentIndex+=B.size-12,p("%cLoading preset data chunk...",c.warn);let C=iA(t);this.verifyHeader(C,"list"),hA(C.data,4);let Q=iA(C.data);this.verifyHeader(Q,"phdr");let m=iA(C.data);this.verifyHeader(m,"pbag");let y=iA(C.data);this.verifyHeader(y,"pmod");let F=iA(C.data);this.verifyHeader(F,"pgen");let k=iA(C.data);this.verifyHeader(k,"inst");let D=iA(C.data);this.verifyHeader(D,"ibag");let v=iA(C.data);this.verifyHeader(v,"imod");let L=iA(C.data);this.verifyHeader(L,"igen");let E=iA(C.data);this.verifyHeader(E,"shdr"),p("%cParsing samples...",c.info),t.currentIndex=this.sampleDataStartIndex;let X=bs(E,h,o===void 0);if(o&&g.shdr){let P=bs(g.shdr,new Float32Array(1),!1);P.length===X.length&&X.forEach((G,b)=>{G.name+=P[b].name,G.linkedSampleIndex|=P[b].linkedSampleIndex<<16})}X.forEach(P=>P.name=P.name.trim()),this.samples.push(...X);let O=Ns(L),nA=Gn(v),$=Ts(k);if(o&&g.inst){let P=Ts(g.inst);P.length===$.length&&($.forEach((G,b)=>{G.name+=P[b].name,G.zoneStartIndex|=P[b].zoneStartIndex}),$.forEach((G,b)=>{b<$.length-1&&(G.zonesCount=$[b+1].zoneStartIndex-G.zoneStartIndex)}))}$.forEach(P=>P.name=P.name.trim()),this.instruments.push(...$);let V=bt(D);if(o&&g.ibag){let P=bt(g.ibag);for(let G=0;G<V.mod.length;G++)V.mod[G]|=P.mod[G]<<16;for(let G=0;G<V.gen.length;G++)V.gen[G]|=P.gen[G]<<16}Ti(V,O,nA,this.samples,$);let q=Ns(F),z=Gn(y),tA=Us(Q,this);if(o&&g.phdr){let P=Us(g.phdr,this);P.length===tA.length&&(tA.forEach((G,b)=>{G.name+=P[b].name,G.zoneStartIndex|=P[b].zoneStartIndex}),tA.forEach((G,b)=>{b<tA.length-1&&(G.zonesCount=tA[b+1].zoneStartIndex-G.zoneStartIndex)}))}tA.forEach(P=>P.name===P.name.trim()),this.addPresets(...tA);let rA=bt(m);if(o&&g.pbag){let P=bt(g.pbag);for(let G=0;G<rA.mod.length;G++)rA.mod[G]|=P.mod[G]<<16;for(let G=0;G<rA.gen.length;G++)rA.gen[G]|=P.gen[G]<<16}Li(rA,q,z,this.instruments,tA),this.flush(),p(`%cParsing finished! %c"${this.soundBankInfo.name}"%c has %c${this.presets.length}%c presets,
20
20
  %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),Z()}verifyHeader(e,A){e.header.toLowerCase()!==A.toLowerCase()&&(Z(),this.parsingError(`Invalid chunk header! Expected "${A.toLowerCase()}" got "${e.header.toLowerCase()}"`))}verifyText(e,A){e.toLowerCase()!==A.toLowerCase()&&(Z(),this.parsingError(`Invalid FourCC: Expected "${A.toLowerCase()}" got "${e.toLowerCase()}"\``))}},ut=class{static fromArrayBuffer(e){let A=e.slice(8,12),t=new Y(A);return hA(t,4).toLowerCase()==="dls "?this.loadDLS(e):new Hi(e,!1)}static loadDLS(e){return Fa.read(e).toSF()}},Ra=class{soundBankManager=new Po(this.updatePresetList.bind(this));midiChannels=[];keyModifierManager=new Ai;totalVoicesAmount=0;processorInitialized=Ot.isInitialized;currentSynthTime=0;sampleRate;enableEffects=!0;enableEventSystem;onEventCall;systemExclusive=$o.bind(this);resetAllControllers=So.bind(this);setMasterParameter=vo.bind(this);getMasterParameter=Lo.bind(this);getAllMasterParameters=No.bind(this);getVoicesForPreset=_o.bind(this);killVoices=Zo.bind(this);getVoices=jo.bind(this);privateProps;savedSnapshot;eventQueue=[];sampleTime;constructor(e,A=Fs){let t=$n(A,Fs);if(this.enableEffects=t.enableEffects,this.enableEventSystem=t.enableEventSystem,this.currentSynthTime=t.initialTime,this.sampleRate=e,this.sampleTime=1/e,isNaN(t.initialTime)||isNaN(e))throw new Error("Initial time or sample rate is NaN!");this.privateProps=new ti(this.callEvent.bind(this),this.getVoices.bind(this),this.killVoices.bind(this),Mo*(44100/e),Jo*(44100/e),Vo*(44100/e));for(let n=0;n<Rn;n++)this.createMIDIChannelInternal(!1);this.processorInitialized.then(()=>{p("%cSpessaSynth is ready!",c.recognized)})}applySynthesizerSnapshot(e){this.savedSnapshot=e,e.apply(this),p("%cFinished applying snapshot!",c.info),this.resetAllControllers()}getSnapshot(){return is.create(this)}setEmbeddedSoundBank(e,A){let t=ut.fromArrayBuffer(e);this.soundBankManager.addSoundBank(t,Rt,A);let n=this.soundBankManager.priorityOrder;n.pop(),n.unshift(Rt),this.soundBankManager.priorityOrder=n,this.savedSnapshot!==void 0&&this.applySynthesizerSnapshot(this.savedSnapshot),p(`%cEmbedded sound bank set at offset %c${A}`,c.recognized,c.value)}clearEmbeddedBank(){this.soundBankManager.soundBankList.some(e=>e.id===Rt)&&this.soundBankManager.deleteSoundBank(Rt)}createMIDIChannel(){this.createMIDIChannelInternal(!0)}stopAllChannels(e=!1){p("%cStop all received!",c.info);for(let A of this.midiChannels)A.stopAllNotes(e)}renderAudio(e,A,t,n=0,s=0){this.renderAudioSplit(A,t,Array(16).fill(e),n,s)}renderAudioSplit(e,A,t,n=0,s=0){let a=this.currentSynthTime;for(;this.eventQueue[0]?.time<=a;)this.eventQueue.shift()?.callback();let i=e[0],I=e[1],o=A[0],g=A[1];n=Math.max(n,0);let B=s||t[0][0].length-n;this.totalVoicesAmount=0,this.midiChannels.forEach((d,h)=>{if(d.voices.length<1||d.isMuted)return;let C=d.voices.length,Q=h%16;d.renderAudio(t[Q][0],t[Q][1],i,I,o,g,n,B),this.totalVoicesAmount+=d.voices.length,d.voices.length!==C&&d.sendChannelProperty()}),this.currentSynthTime+=B*this.sampleTime}destroySynthProcessor(){this.midiChannels.forEach(e=>{e.voices.length=0,e.sustainedVoices.length=0,e.lockedControllers=[],e.preset=void 0}),this.clearCache(),this.midiChannels.length=0,this.soundBankManager.destroy()}controllerChange(e,A,t){this.midiChannels[e].controllerChange(A,t)}noteOn(e,A,t){this.midiChannels[e].noteOn(A,t)}noteOff(e,A){this.midiChannels[e].noteOff(A)}polyPressure(e,A,t){this.midiChannels[e].polyPressure(A,t)}channelPressure(e,A){this.midiChannels[e].channelPressure(A)}pitchWheel(e,A){this.midiChannels[e].pitchWheel(A)}programChange(e,A){this.midiChannels[e].programChange(A)}processMessage(e,A=0,t=!1,n=Za){let s=()=>{let i=As(e[0]),I=i.channel+A;switch(i.status){case M.noteOn:{let o=e[2];o>0?this.noteOn(I,e[1],o):this.noteOff(I,e[1]);break}case M.noteOff:t?this.midiChannels[I].killNote(e[1]):this.noteOff(I,e[1]);break;case M.pitchWheel:this.pitchWheel(I,e[2]<<7|e[1]);break;case M.controllerChange:this.controllerChange(I,e[1],e[2]);break;case M.programChange:this.programChange(I,e[1]);break;case M.polyPressure:this.polyPressure(I,e[0],e[1]);break;case M.channelPressure:this.channelPressure(I,e[1]);break;case M.systemExclusive:this.systemExclusive(new Y(e.slice(1)),A);break;case M.reset:this.stopAllChannels(!0),this.resetAllControllers();break;default:break}},a=n.time;a>this.currentSynthTime?(this.eventQueue.push({callback:s.bind(this),time:a}),this.eventQueue.sort((i,I)=>i.time-I.time)):s()}clearCache(){this.privateProps.cachedVoices=[]}setMIDIVolume(e){this.privateProps.midiVolume=Math.pow(e,Math.E)}setMasterTuning(e){e=Math.round(e);for(let A of this.midiChannels)A.setCustomController(IA.masterTuning,e)}callEvent(e,A){this.onEventCall?.({type:e,data:A})}getCachedVoice(e,A,t){let n=e.bankMSB,s=e.bankLSB,{isGMGSDrum:a,program:i}=e;return a&&(n=128,s=0),this.privateProps.cachedVoices?.[n]?.[s]?.[i]?.[A]?.[t]}setCachedVoice(e,A,t,n){let s=e.bankMSB,a=e.bankLSB,{isGMGSDrum:i,program:I}=e;i&&(s=128,a=0),this.privateProps.cachedVoices[s]||(this.privateProps.cachedVoices[s]=[]),this.privateProps.cachedVoices[s][a]||(this.privateProps.cachedVoices[s][a]=[]),this.privateProps.cachedVoices[s][a][I]||(this.privateProps.cachedVoices[s][a][I]=[]),this.privateProps.cachedVoices[s][a][I][A]||(this.privateProps.cachedVoices[s][a][I][A]=[]),this.privateProps.cachedVoices[s][a][I][A][t]=n}createMIDIChannelInternal(e){let A=new Qi(this,this.privateProps,this.privateProps.defaultPreset,this.midiChannels.length);this.midiChannels.push(A),e&&(this.callEvent("newChannel",void 0),A.sendChannelProperty(),this.midiChannels[this.midiChannels.length-1].setDrums(!0))}updatePresetList(){let e=this.soundBankManager.presetList;this.clearCache(),this.privateProps.callEvent("presetListChange",e),this.getDefaultPresets(),this.midiChannels.forEach(A=>{A.setPresetLock(!1)}),this.resetAllControllers(!1)}getDefaultPresets(){this.privateProps.defaultPreset=this.soundBankManager.getPreset({bankLSB:0,bankMSB:0,program:0,isGMGSDrum:!1},"xg"),this.privateProps.drumPreset=this.soundBankManager.getPreset({bankLSB:0,bankMSB:0,program:0,isGMGSDrum:!0},"gs")}};var zt=Ee.consoleColors;var Ma="spessasynth-worklet-processor";function ba(e,A){return{...A,...e??{}}}var va={skipToFirstNoteOn:!0,initialPlaybackRate:1};var rs=class extends Kt{events=[];constructor(A){super(),super.copyFrom(A),this.events=[]}},Wt=class extends Le{tracks;embeddedSoundBank=void 0;embeddedSoundBankSize;constructor(A){super(),super.copyMetadataFrom(A),this.tracks=A.tracks.map(t=>new rs(t)),this.embeddedSoundBankSize=A?.embeddedSoundBank?.byteLength}};var _t={shuffleOn:1,shuffleOff:2,index:3};var jt=class{synthesizer;sequencer;post;alive=!1;constructor(A,t,n){this.synthesizer=new Ra(A,t),this.sequencer=new sa(this.synthesizer),this.post=n,this.synthesizer.onEventCall=s=>{this.post({type:"eventCall",data:s,currentTime:this.synthesizer.currentSynthTime})},this.sequencer.onEventCall=s=>{if(s.type==="songListChange"){let i=s.data.newSongList.map(I=>new Wt(I));this.post({type:"sequencerReturn",data:{type:s.type,data:{newSongList:i}},currentTime:this.synthesizer.currentSynthTime});return}this.post({type:"sequencerReturn",data:s,currentTime:this.synthesizer.currentSynthTime})}}postReady(A,t,n=[]){this.post({type:"isFullyInitialized",data:{type:A,data:t},currentTime:this.synthesizer.currentSynthTime},n)}postProgress(A,t){this.post({type:"renderingProgress",data:{type:A,data:t},currentTime:this.synthesizer.currentSynthTime})}destroy(){this.synthesizer.destroySynthProcessor(),delete this.synthesizer,delete this.sequencer}handleMessage(A){let t=A.channelNumber,n;if(t>=0&&(n=this.synthesizer.midiChannels[t],n===void 0)){Ee.SpessaSynthWarn(`Trying to access channel ${t} which does not exist... ignoring!`);return}switch(A.type){case"midiMessage":this.synthesizer.processMessage(A.data.messageData,A.data.channelOffset,A.data.force,A.data.options);break;case"customCcChange":n?.setCustomController(A.data.ccNumber,A.data.ccValue);break;case"ccReset":t===Be?this.synthesizer.resetAllControllers():n?.resetControllers();break;case"setChannelVibrato":if(t===Be)for(let s of this.synthesizer.midiChannels)A.data.rate===Be?s.disableAndLockGSNRPN():s.setVibrato(A.data.depth,A.data.rate,A.data.delay);else A.data.rate===Be?n?.disableAndLockGSNRPN():n?.setVibrato(A.data.depth,A.data.rate,A.data.delay);break;case"stopAll":t===Be?this.synthesizer.stopAllChannels(A.data===1):n?.stopAllNotes(A.data===1);break;case"killNotes":this.synthesizer.killVoices(A.data);break;case"muteChannel":n?.muteChannel(A.data);break;case"addNewChannel":this.synthesizer.createMIDIChannel();break;case"setMasterParameter":this.synthesizer.setMasterParameter(A.data.type,A.data.data);break;case"setDrums":n?.setDrums(A.data);break;case"transposeChannel":n?.transposeChannel(A.data.semitones,A.data.force);break;case"lockController":if(A.data.controllerNumber===Be)n?.setPresetLock(A.data.isLocked);else{if(!n)return;n.lockedControllers[A.data.controllerNumber]=A.data.isLocked}break;case"sequencerSpecific":{if(!this.sequencer)return;let s=this.sequencer,a=A.data;switch(a.type){default:break;case"loadNewSongList":try{let I=a.data.map(o=>"duration"in o?Le.copyFrom(o):Le.fromArrayBuffer(o.binary,o.fileName));s.loadNewSongList(I)}catch(i){console.error(i),this.post({type:"sequencerReturn",data:{type:"midiError",data:i},currentTime:this.synthesizer.currentSynthTime})}break;case"pause":s.pause();break;case"play":s.play();break;case"setTime":s.currentTime=a.data;break;case"changeMIDIMessageSending":s.externalMIDIPlayback=a.data;break;case"setPlaybackRate":s.playbackRate=a.data;break;case"setLoopCount":s.loopCount=a.data;break;case"changeSong":switch(a.data.changeType){case _t.shuffleOff:s.shuffleMode=!1;break;case _t.shuffleOn:s.shuffleMode=!0;break;case _t.index:a.data.data!==void 0&&(console.log("INDEX",a.data),s.songIndex=a.data.data);break}break;case"getMIDI":if(!s.midiData)throw new Error("No MIDI is loaded!");this.post({type:"sequencerReturn",data:{type:"getMIDI",data:s.midiData},currentTime:this.synthesizer.currentSynthTime});break;case"setSkipToFirstNote":s.skipToFirstNoteOn=a.data;break}break}case"soundBankManager":try{let s=this.synthesizer.soundBankManager,a=A.data,i;switch(a.type){case"addSoundBank":i=ut.fromArrayBuffer(a.data.soundBankBuffer),s.addSoundBank(i,a.data.id,a.data.bankOffset),this.postReady("soundBankManager",null);break;case"deleteSoundBank":s.deleteSoundBank(a.data),this.postReady("soundBankManager",null);break;case"rearrangeSoundBanks":s.priorityOrder=a.data,this.postReady("soundBankManager",null)}}catch(s){this.post({type:"soundBankError",data:s,currentTime:this.synthesizer.currentSynthTime})}break;case"keyModifierManager":{let s=A.data,a=this.synthesizer.keyModifierManager;switch(s.type){default:return;case"addMapping":a.addMapping(s.data.channel,s.data.midiNote,s.data.mapping);break;case"clearMappings":a.clearMappings();break;case"deleteMapping":a.deleteMapping(s.data.channel,s.data.midiNote)}break}case"requestSynthesizerSnapshot":{let s=is.create(this.synthesizer);this.postReady("synthesizerSnapshot",s);break}case"setLogLevel":Ks(A.data.enableInfo,A.data.enableWarning,A.data.enableGroup);break;case"destroyWorklet":this.alive=!1,this.synthesizer.destroySynthProcessor(),this.destroy();break;default:Ee.SpessaSynthWarn("Unrecognized event!",A);break}}};var $t=class extends jt{alive=!0;oneOutputMode;port;constructor(A,t,n,s){super(A,{enableEffects:!s.oneOutput,enableEventSystem:s?.enableEventSystem,initialTime:t},(a,i)=>{n.postMessage(a,i)}),this.port=n,this.oneOutputMode=s.oneOutput,this.synthesizer.processorInitialized.then(()=>{this.port.onmessage=a=>this.handleMessage(a.data),this.postReady("sf3Decoder",null)})}process(A,t){if(!this.alive)return!1;if(this.sequencer.processTick(),this.oneOutputMode){let n=t[0],s=[];for(let a=0;a<32;a+=2)s.push([n[a],n[a+1]]);this.synthesizer.renderAudioSplit([],[],s)}else this.synthesizer.renderAudioSplit(t[0],t[1],t.slice(2));return!0}handleMessage(A){if(A.type==="startOfflineRender"){this.startOfflineRender(A.data);return}super.handleMessage(A)}startOfflineRender(A){if(!this.sequencer)return;A.soundBankList.forEach((n,s)=>{try{this.synthesizer.soundBankManager.addSoundBank(ut.fromArrayBuffer(n.soundBankBuffer),`bank-${s}`,n.bankOffset)}catch(a){this.post({type:"soundBankError",data:a,currentTime:this.synthesizer.currentSynthTime})}}),A.snapshot!==void 0&&this.synthesizer.applySynthesizerSnapshot(A.snapshot),Ee.SpessaSynthInfo("%cRendering enabled! Starting render.",zt.info),this.sequencer.loopCount=A.loopCount,this.synthesizer.setMasterParameter("voiceCap",1/0);let t=ba(A.sequencerOptions,va);this.sequencer.skipToFirstNoteOn=t.skipToFirstNoteOn,this.sequencer.playbackRate=t.initialPlaybackRate;try{this.sequencer.loadNewSongList([Le.copyFrom(A.midiSequence)]),this.sequencer.play()}catch(n){console.error(n),this.post({type:"sequencerReturn",data:{type:"midiError",data:n},currentTime:this.synthesizer.currentSynthTime})}this.postReady("startOfflineRender",null)}};var Is=class extends AudioWorkletProcessor{process;core;constructor(A){super(),this.core=new $t(sampleRate,currentTime,this.port,A.processorOptions),this.process=this.core.process.bind(this.core)}};registerProcessor(Ma,Is);Ee.SpessaSynthInfo("%cProcessor successfully registered!",zt.recognized);