diff --git a/app/static/js/services/soundfontPlayer.js b/app/static/js/services/soundfontPlayer.js index 491bf6e..2a13b0a 100644 --- a/app/static/js/services/soundfontPlayer.js +++ b/app/static/js/services/soundfontPlayer.js @@ -107,9 +107,12 @@ const bufCopy = buffer.slice(0); await _synthInstance.soundBankManager.addSoundBank(bufCopy, sfId); await _synthInstance.isReady; - // Force program 0 on channel 0 to activate loaded bank - this.controllerChange(0, 0, 0); - this.programChange(0, 0); + // Force bank+program select on all channels to activate loaded bank + for (let ch = 0; ch < 16; ch++) { + try { _synthInstance.controllerChange(ch, 0, 0); } catch (e) {} + try { _synthInstance.controllerChange(ch, 32, 0); } catch (e) {} + try { _synthInstance.programChange(ch, 0); } catch (e) {} + } _currentSfId = sfId; console.log("[SonicSF] SoundFont loaded:", sfId); } catch (e) { diff --git a/app/static/js/services/spessasynth_processor.min.js b/app/static/js/services/spessasynth_processor.min.js new file mode 100644 index 0000000..144cae2 --- /dev/null +++ b/app/static/js/services/spessasynth_processor.min.js @@ -0,0 +1,18 @@ +function xt(t,e,A=0){let s=0;for(let n=0;n>>0}function Nt(t,e){let A=xt(t,e,t.currentIndex);return t.currentIndex+=e,A}function sA(t,e){let A=new Array(e).fill(0);for(let s=e-1;s>=0;s--)A[s]=t&255,t>>=8;return A}function V(t,e){let A=cs(t,e,t.currentIndex);return t.currentIndex+=e,A}function cs(t,e,A=0){let s=0;for(let n=0;n>>0}function hs(t,e,A){for(let s=0;s>s*8&255}function Ae(t,e){t[t.currentIndex++]=e&255,t[t.currentIndex++]=e>>8}function ge(t,e){hs(t,e,4)}function ls(t,e){let A=e<<8|t;return A>32767?A-65536:A}function Yn(t){return t>127?t-256:t}var ee=class extends Uint8Array{currentIndex=0;slice(t,e){let A=super.slice(t,e);return A.currentIndex=0,A}};function _e(t,e=t.length,A=0){let s="";for(let n=0;n0&&e.length>A&&(e=e.slice(0,A));for(let s=0;se.length)for(let s=0;s>7!==1)break}return e}function UA(t){let e=[t&127];for(t>>=7;t>0;)e.unshift(t&127|128),t>>=7;return e}function _A(t){t=Math.floor(t);let e=Math.floor(t/60),A=Math.round(t-e*60);return{minutes:e,seconds:A,time:`${e.toString().padStart(2,"0")}:${A.toString().padStart(2,"0")}`}}function zs(t){let e="";for(let A=0;A{var t=Uint8Array,e=Uint16Array,A=Int32Array,s=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),n=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),r=function(T,F){for(var u=new e(31),x=0;x<31;++x)u[x]=F+=1<>1|(y&21845)<<1,I=(I&52428)>>2|(I&13107)<<2,I=(I&61680)>>4|(I&3855)<<4,B[y]=((I&65280)>>8|(I&255)<<8)>>1;var I,y,E=function(T,F,u){for(var x=T.length,P=0,te=new e(F);P>$]=ne}else for(_=new e(x),P=0;P>15-T[P]);return _},m=new t(288);for(y=0;y<144;++y)m[y]=8;var y;for(y=144;y<256;++y)m[y]=9;var y;for(y=256;y<280;++y)m[y]=7;var y;for(y=280;y<288;++y)m[y]=8;var y,k=new t(32);for(y=0;y<32;++y)k[y]=5;var y,b=E(m,9,1),R=E(k,5,1),M=function(T){for(var F=T[0],u=1;uF&&(F=T[u]);return F},S=function(T,F,u){var x=F/8|0;return(T[x]|T[x+1]<<8)>>(F&7)&u},Q=function(T,F){var u=F/8|0;return(T[u]|T[u+1]<<8|T[u+2]<<16)>>(F&7)},p=function(T){return(T+7)/8|0},D=function(T,F,u){return(F==null||F<0)&&(F=0),(u==null||u>T.length)&&(u=T.length),new t(T.subarray(F,u))},q=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],K=function(T,F,u){var x=new Error(F||q[T]);if(x.code=T,Error.captureStackTrace&&Error.captureStackTrace(x,K),!u)throw x;return x},O=function(T,F,u,x){var P=T.length,te=x?x.length:0;if(!P||F.f&&!F.l)return u||new t(0);var W=!u,_=W||F.i!=2,$=F.i;W&&(u=new t(P*3));var ne=function(Ce){var he=u.length;if(Ce>he){var Te=new t(Math.max(he*2,Ce));Te.set(u),u=Te}},ae=F.f||0,J=F.p||0,ie=F.b||0,pe=F.l,ve=F.d,Be=F.m,be=F.n,xe=P*8;do{if(!pe){ae=S(T,J,1);var ht=S(T,J+1,3);if(J+=3,ht)if(ht==1)pe=b,ve=R,Be=9,be=5;else if(ht==2){var lt=S(T,J,31)+257,jt=S(T,J+10,15)+4,eA=lt+S(T,J+5,31)+1;J+=14;for(var Ye=new t(eA),Et=new t(19),Re=0;Re>4;if(Xe<16)Ye[Re++]=Xe;else{var it=0,Ct=0;for(Xe==16?(Ct=3+S(T,J,3),J+=2,it=Ye[Re-1]):Xe==17?(Ct=3+S(T,J,7),J+=3):Xe==18&&(Ct=11+S(T,J,127),J+=7);Ct--;)Ye[Re++]=it}}var bt=Ye.subarray(0,lt),qe=Ye.subarray(lt);Be=M(bt),be=M(qe),pe=E(bt,Be,1),ve=E(qe,be,1)}else K(1);else{var Xe=p(J)+4,dt=T[Xe-4]|T[Xe-3]<<8,je=Xe+dt;if(je>P){$&&K(0);break}_&&ne(ie+dt),u.set(T.subarray(Xe,je),ie),F.b=ie+=dt,F.p=J=je*8,F.f=ae;continue}if(J>xe){$&&K(0);break}}_&&ne(ie+131072);for(var v=(1<>4;if(J+=it&15,J>xe){$&&K(0);break}if(it||K(2),z<256)u[ie++]=z;else if(z==256){L=J,pe=null;break}else{var re=z-254;if(z>264){var Re=z-257,ce=s[Re];re=S(T,J,(1<>4;de||K(3),J+=de&15;var qe=C[j];if(j>3){var ce=n[j];qe+=Q(T,J)&(1<xe){$&&K(0);break}_&&ne(ie+131072);var Ne=ie+re;if(ieg.length+o,0);s&&(a+=4,n="LIST");let r=new ee(4);ge(r,a);let i=[$e(n),r];return s&&i.push($e(e)),i.push(...A),a%2!==0&&i.push(new Uint8Array(1)),i}static writeParts(e,A,s=!1){let n=8,a=e,r=A.reduce((l,C)=>C.length+l,0),i=r;s&&(n+=4,i+=4,a="LIST");let o=n+r;o%2!==0&&o++;let g=new ee(o);Le(g,a),ge(g,i),s&&Le(g,e);for(let l of A)g.set(l,n),n+=l.length;return g}static findListType(e,A){return e.find(s=>s.header!=="LIST"?!1:(s.data.currentIndex=4,_e(s.data,4)===A))}};function bA(t,e){return{...e,...t}}var h=class WA{static infoEnabled=!1;static warnEnabled=!0;static groupEnabled=!1;static setLogLevel(e,A,s){this.infoEnabled=e,this.warnEnabled=A,this.groupEnabled=s}static info(...e){this.infoEnabled&&console.info(...e)}static warn(...e){this.warnEnabled&&console.warn(...e)}static group(...e){this.groupEnabled&&console.group(...e)}static groupCollapsed(...e){this.groupEnabled&&console.groupCollapsed(...e)}static groupEnd(){this.groupEnabled&&console.groupEnd()}static unsupported(e,A,s=""){this.infoEnabled&&this.info(`%cUnsupported %c${e}%c message: %c${zs(A)}%c. ${s}`,d.warn,d.recognized,d.warn,d.unrecognized,d.warn)}static gmInfo(e,A,s=""){this.infoEnabled&&this.coolInfo(`General MIDI ${e}`,A,s)}static gmFail(e,A){this.infoEnabled&&this.unsupported(`General MIDI ${e}`,A)}static gsInfo(e,A,s=""){this.infoEnabled&&this.coolInfo(`Roland GS ${e}`,A,s)}static gsFail(e,A,s=""){this.infoEnabled&&this.unsupported(`Roland GS ${e}`,A,s)}static xgInfo(e,A,s=""){this.infoEnabled&&this.coolInfo(`Yamaha XG ${e}`,A,s)}static xgFail(e,A,s=""){this.infoEnabled&&this.unsupported(`Yamaha XG ${e}`,A,s)}static coolInfo(e,A,s=""){this.infoEnabled&&(s?WA.info(`%c${e}%c is now set to %c${A}%c ${s}.`,d.recognized,d.info,d.value,d.info):WA.info(`%c${e}%c is now set to %c${A}%c.`,d.recognized,d.info,d.value,d.info))}},tn={ConsoleColors:d,readBigEndian:xt,readLittleEndian:cs,readLittleEndianIndexed:V,readBinaryString:_e,readBinaryStringIndexed:Ee,readVariableLengthQuantity:Qe,inflateSync:js},G={noteOff:128,noteOn:144,polyPressure:160,controllerChange:176,programChange:192,channelPressure:208,pitchWheel:224,systemExclusive:240,timecode:241,songPosition:242,songSelect:243,tuneRequest:246,clock:248,start:250,continue:251,stop:252,activeSensing:254,reset:255,sequenceNumber:0,text:1,copyright:2,trackName:3,instrumentName:4,lyric:5,marker:6,cuePoint:7,programName:8,midiChannelPrefix:32,midiPort:33,endOfTrack:47,setTempo:81,smpteOffset:84,timeSignature:88,keySignature:89,sequenceSpecific:127},f={bankSelect:0,modulationWheel:1,breathController:2,undefinedCC3:3,footController:4,portamentoTime:5,dataEntryMSB:6,mainVolume:7,balance:8,undefinedCC9:9,pan:10,expression:11,effectControl1:12,effectControl2:13,undefinedCC14:14,undefinedCC15:15,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,undefinedCC20:20,undefinedCC21:21,undefinedCC22:22,undefinedCC23:23,undefinedCC24:24,undefinedCC25:25,undefinedCC26:26,undefinedCC27:27,undefinedCC28:28,undefinedCC29:29,undefinedCC30:30,undefinedCC31:31,bankSelectLSB:32,modulationWheelLSB:33,breathControllerLSB:34,undefinedCC3LSB:35,footControllerLSB:36,portamentoTimeLSB:37,dataEntryLSB:38,mainVolumeLSB:39,balanceLSB:40,undefinedCC9LSB:41,panLSB:42,expressionLSB:43,effectControl1LSB:44,effectControl2LSB:45,undefinedCC14LSB:46,undefinedCC15LSB:47,undefinedCC16LSB:48,undefinedCC17LSB:49,undefinedCC18LSB:50,undefinedCC19LSB:51,undefinedCC20LSB:52,undefinedCC21LSB:53,undefinedCC22LSB:54,undefinedCC23LSB:55,undefinedCC24LSB:56,undefinedCC25LSB:57,undefinedCC26LSB:58,undefinedCC27LSB:59,undefinedCC28LSB:60,undefinedCC29LSB:61,undefinedCC30LSB:62,undefinedCC31LSB:63,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,filterResonance:71,releaseTime:72,attackTime:73,brightness:74,decayTime:75,vibratoRate:76,vibratoDepth:77,vibratoDelay:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,undefinedCC85:85,undefinedCC86:86,undefinedCC87:87,undefinedCC88:88,undefinedCC89:89,undefinedCC90:90,reverbDepth:91,tremoloDepth:92,chorusDepth:93,variationDepth:94,phaserDepth:95,dataIncrement:96,dataDecrement:97,nonRegisteredParameterLSB:98,nonRegisteredParameterMSB:99,registeredParameterLSB:100,registeredParameterMSB:101,undefinedCC102LSB:102,undefinedCC103LSB:103,undefinedCC104LSB:104,undefinedCC105LSB:105,undefinedCC106LSB:106,undefinedCC107LSB:107,undefinedCC108LSB:108,undefinedCC109LSB:109,undefinedCC110LSB:110,undefinedCC111LSB:111,undefinedCC112LSB:112,undefinedCC113LSB:113,undefinedCC114LSB:114,undefinedCC115LSB:115,undefinedCC116LSB:116,undefinedCC117LSB:117,undefinedCC118LSB:118,undefinedCC119LSB:119,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127},ut={pitchWheelRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},ye={partParameter:1,drumPitch:24,drumPitchFine:25,drumLevel:26,drumPan:28,drumReverb:29,drumChorus:30,drumDelay:31,awe32:127,SF2:120},Pe={vibratoRate:8,vibratoDepth:9,vibratoDelay:10,tvfCutoffFrequency:32,tvfResonance:33,envelopeAttackTime:99,envelopeDecayTime:100,envelopeReleaseTime:102},We=class{ticks;statusByte;data;constructor(t,e,A){this.ticks=t,this.statusByte=e,this.data=A}},ws=(t,e)=>{for(let A=0;A3||A.length<2)throw new Error(`Invalid MIDI string: ${e}`);return e.startsWith("DRUM")?{bankMSB:0,bankLSB:0,program:Number.parseInt(A[1]),isGMGSDrum:!0}:{bankLSB:Number.parseInt(A[0]),bankMSB:Number.parseInt(A[1]),program:Number.parseInt(A[2]),isGMGSDrum:!1}}static toFullMIDIString(e){return`${this.toMIDIString(e)} ${e.isDrum?"D":"M"} ${e.name}`}static fromFullMIDIString(e){let A=e.indexOf(" "),s=e.indexOf(" ",A+1);if(A===-1||s===-1)throw new Error(`Invalid named MIDI string: ${e}`);let n=e.slice(0,Math.max(0,A)),a=e.slice(A+1,s),r=e.slice(Math.max(0,s+1));return{...zA.fromMIDIString(n),isDrum:a==="D",name:r}}static matches(e,A){return e.isGMGSDrum||A.isGMGSDrum?e.isGMGSDrum===A.isGMGSDrum&&e.program===A.program:e.program===A.program&&e.bankLSB===A.bankLSB&&e.bankMSB===A.bankMSB}static compare(e,A){return e.isGMGSDrum&&!A.isGMGSDrum?1:!e.isGMGSDrum&&A.isGMGSDrum?-1:e.program!==A.program?e.program-A.program:e.bankMSB!==A.bankMSB?e.bankMSB-A.bankMSB:e.bankLSB-A.bankLSB}static isXGDrum(e){return e.isDrum&&!e.isGMGSDrum}static selectPatch(e,A,s){if(e.length===0)throw new Error("No presets!");A.isGMGSDrum&&Se.isSystemXG(s)&&(A={...A,isGMGSDrum:!1,bankLSB:0,bankMSB:Se.getDrumBank(s)});let{isGMGSDrum:n,bankLSB:a,bankMSB:r,program:i}=A,o=Se.isSystemXG(s),g=Se.isXGDrum(r)&&o,l=e.find(I=>this.matches(I,A));if(l&&(!g||g&&this.isXGDrum(l)))return l;let C=I=>{h.info(`%cPreset %c${zA.toMIDIString(A)}%c not found. (${s}) Replaced with %c${this.toFullMIDIString(I)}`,d.warn,d.unrecognized,d.warn,d.value)};if(n){let I=e.find(E=>E.isGMGSDrum&&E.program===i);return I||(I=e.find(E=>E.isDrum&&E.program===i),I)?(C(I),I):(I=this.getAnyDrums(e,!1),C(I),I)}if(g){let I=e.find(E=>E.program===i&&E.isDrum&&!E.isGMGSDrum);return I||(I=e.find(E=>E.isDrum&&E.program===i),I&&I.program<49)?(C(I),I):(I=this.getAnyDrums(e,!0),C(I),I)}let B=e.filter(I=>I.program===i&&!I.isDrum);if(B.length===0)return C(e[0]),e[0];if(l=o?B.find(I=>I.bankLSB===a):B.find(I=>I.bankMSB===r),l)return C(l),l;if(a!==64||!o){let I=Math.max(r,a);if(l=B.find(E=>E.bankLSB===I||E.bankMSB===I),l)return C(l),l}return C(B[0]),B[0]}static getAnyDrums(e,A){let s=A?e.find(n=>this.isXGDrum(n)):e.find(n=>n.isGMGSDrum);return s||(e.find(n=>n.isDrum)??e[0])}},fe=Object.freeze({type:"Other"}),se=class $A{static analyzeSysEx(e){if(e.length<3)return fe;switch(e[0]){default:return fe;case 126:case 127:return this.analyzeGM(e);case 65:return this.analyzeGS(e);case 67:return this.analyzeXG(e)}}static analyzeRPN(e,A,s){switch(A){default:return fe;case ut.fineTuning:return{type:"Fine Tune",channel:e,value:(s-8192)/81.92};case ut.coarseTuning:return{type:"Key Shift",channel:e,value:(s>>7)-64}}}static analyzeNRPN(e,A,s){let n=A>>7,a=A&127;switch(n){default:return fe;case ye.partParameter:switch(a){default:return fe;case Pe.vibratoRate:return{type:"Controller Change",channel:e,controller:f.vibratoRate,value:s>>7};case Pe.vibratoDepth:return{type:"Controller Change",channel:e,controller:f.vibratoDepth,value:s>>7};case Pe.vibratoDelay:return{type:"Controller Change",channel:e,controller:f.vibratoDelay,value:s>>7};case Pe.tvfCutoffFrequency:return{type:"Controller Change",channel:e,controller:f.brightness,value:s>>7};case Pe.tvfResonance:return{type:"Controller Change",channel:e,controller:f.filterResonance,value:s>>7};case Pe.envelopeAttackTime:return{type:"Controller Change",channel:e,controller:f.attackTime,value:s>>7};case Pe.envelopeDecayTime:return{type:"Controller Change",channel:e,controller:f.decayTime,value:s>>7};case Pe.envelopeReleaseTime:return{type:"Controller Change",channel:e,controller:f.releaseTime,value:s>>7}}case ye.drumPitch:case ye.drumPitchFine:case ye.drumLevel:case ye.drumPan:case ye.drumReverb:case ye.drumChorus:case ye.drumDelay:return{type:"Drum Setup"}}}static syxToChannel(e){return[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e%16]}static channelToSyx(e){return[1,2,3,4,5,6,7,8,9,0,10,11,12,13,14,15][e%16]}static gsData(e,A,s,n){let a=128-(e+A+s+n.reduce((r,i)=>r+i,0))%128&127;return[65,16,66,18,e,A,s,...n,a,247]}static gsMessage(e,A,s,n,a){return new We(e,G.systemExclusive,new Uint8Array(this.gsData(A,s,n,a)))}static gsDrumChange(e,A,s){let n=16|this.channelToSyx(A);return this.gsMessage(e,40,n,21,[s])}static gsReset(e){return this.gsMessage(e,64,0,127,[0])}static analyzeGM(e){if(e.length<4)return fe;if(e[2]===4)switch(e[3]){default:return fe;case 3:return{type:"Master Fine Tune",value:((e[5]<<7|e[6])-8192)/81.92};case 4:return{type:"Master Key Shift",value:e[5]-64};case 5:if(e[4]!==1||e[5]!==1||e[6]!==1||e[7]!==1)return fe;switch(e[8]){default:return fe;case 1:switch(e[9]){default:return fe;case 1:case 2:return{type:"Reverb Param"}}case 2:switch(e[9]){default:return fe;case 1:case 2:case 3:case 4:return{type:"Chorus Param"}}}}if(e[2]!==9)return fe;switch(e[3]){default:return fe;case 1:return{type:"GM On"};case 2:return{type:"GM Off"};case 3:return{type:"GM2 On"}}}static analyzeXG(e){if(e[2]!==76||e.length<7)return fe;let A=e[3],s=e[4],n=e[5],a=e[6];if(A===0&&s===0)switch(n){default:return fe;case 0:return{type:"Master Fine Tune",value:(((e[6]&15)<<12|(e[7]&15)<<8|(e[8]&15)<<4|e[9]&15)-1024)/10};case 6:return{type:"Master Key Shift",value:a-64};case 126:case 127:return{type:"XG Reset"}}if(A===2&&s===1)return n<=21?{type:"Reverb Param"}:n<=53?{type:"Chorus Param"}:{type:"Variation Param"};if(A===3&&s===0)return{type:"Variation Param"};if(A===8){let r=s;if(r>=16)return fe;switch(n){default:return fe;case 1:return{type:"Controller Change",channel:r,controller:f.bankSelect,value:a};case 2:return{type:"Controller Change",channel:r,controller:f.bankSelectLSB,value:a};case 3:return{type:"Program Change",channel:r,value:a};case 5:return{type:"Controller Change",channel:r,controller:a===1?f.polyModeOn:f.monoModeOn,value:0};case 7:return{type:"Drums On",channel:r,isDrum:a>0};case 8:return{type:"Key Shift",channel:r,value:a-64};case 11:return{type:"Controller Change",channel:r,controller:f.mainVolume,value:a};case 14:return{type:"Controller Change",channel:r,controller:f.pan,value:a};case 18:return{type:"Controller Change",channel:r,controller:f.chorusDepth,value:a};case 19:return{type:"Controller Change",channel:r,controller:f.reverbDepth,value:a};case 21:return{type:"Controller Change",channel:r,controller:f.vibratoRate,value:a};case 22:return{type:"Controller Change",channel:r,controller:f.vibratoDepth,value:a};case 23:return{type:"Controller Change",channel:r,controller:f.vibratoDelay,value:a};case 24:return{type:"Controller Change",channel:r,controller:f.brightness,value:a};case 25:return{type:"Controller Change",channel:r,controller:f.filterResonance,value:a};case 26:return{type:"Controller Change",channel:r,controller:f.attackTime,value:a};case 27:return{type:"Controller Change",channel:r,controller:f.decayTime,value:a};case 12:return{type:"Controller Change",channel:r,controller:f.releaseTime,value:a}}}return A>>4===3?{type:"Drum Setup"}:fe}static analyzeGS(e){if(e.length<10||e[2]!==66||e[3]!==18)return fe;let A=e[4],s=e[5],n=e[6],a=e[7];if((A===0||A===64)&&s===0)switch(n){case 127:switch(a){case 0:return{type:"GS Reset"};case 127:return{type:"GM On"}}return fe;case 0:return{type:"Master Fine Tune",value:((a<<12|e[8]<<8|e[9]<<4|e[10])-1024)/10}}if(A===65)return{type:"Drum Setup"};if(A!==64)return fe;if(s===0&&n===5)return{type:"Master Key Shift",value:a-64};if(s===1){if(n>=48&&n<=55)return{type:"Reverb Param"};if(n>=56&&n<=64)return{type:"Chorus Param"};if(n>=80&&n<=90)return{type:"Delay Param"}}if(s===3&&n>=0&&n<=127)return{type:"Insertion Param"};if(s>>4===1){let r=$A.syxToChannel(s&15);switch(n){default:return fe;case 0:return{type:"Program Change",channel:r,value:a};case 19:return{type:"Controller Change",channel:r,controller:a===1?f.polyModeOn:f.monoModeOn,value:0};case 21:return{type:"Drums On",channel:r,isDrum:a>0};case 22:return{type:"Key Shift",channel:r,value:a-64};case 25:return{type:"Controller Change",channel:r,controller:f.mainVolume,value:a};case 28:return{type:"Controller Change",channel:r,controller:f.pan,value:a};case 33:return{type:"Controller Change",channel:r,controller:f.chorusDepth,value:a};case 34:return{type:"Controller Change",channel:r,controller:f.reverbDepth,value:a};case 42:return{type:"Fine Tune",channel:r,value:((a<<7|e[8])-8192)/81.92};case 44:return{type:"Controller Change",channel:r,controller:f.variationDepth,value:a};case 48:return{type:"Controller Change",channel:r,controller:f.vibratoRate,value:a};case 49:return{type:"Controller Change",channel:r,controller:f.vibratoDepth,value:a};case 50:return{type:"Controller Change",channel:r,controller:f.brightness,value:a};case 51:return{type:"Controller Change",channel:r,controller:f.filterResonance,value:a};case 52:return{type:"Controller Change",channel:r,controller:f.attackTime,value:a};case 53:return{type:"Controller Change",channel:r,controller:f.decayTime,value:a};case 54:return{type:"Controller Change",channel:r,controller:f.releaseTime,value:a};case 55:return{type:"Controller Change",channel:r,controller:f.vibratoDelay,value:a}}}if(s>>4===4){let r=$A.syxToChannel(s&15);switch(n){default:return fe;case 0:case 1:return{type:"Controller Change",channel:r,controller:f.bankSelectLSB,value:a};case 34:return{type:"Insertion Param"}}}return fe}},_n="Created using SpessaSynth";function Wn(t,e,A){let s="gm",n=[],a=new Array(t.tracks.length).fill(0),r=16+Math.max(...t.portChannelOffsetMap),i=[];for(let o=0;o{let C=t.portChannelOffsetMap[a[g]];if(o.statusByte===G.midiPort){a[g]=o.data[0];return}let B=o.statusByte&240;if(B!==G.controllerChange&&B!==G.programChange&&B!==G.systemExclusive)return;if(B===G.systemExclusive){let k=se.analyzeSysEx(o.data);switch(k.type){default:return;case"Drums On":{let y=k.channel+C;i[y].isDrum=k.isDrum;return}case"XG Reset":s="xg";return;case"GS Reset":s="gs";return;case"GM Off":case"GM On":s="gm",n.push({tNum:g,e:o});return;case"GM2 On":s="gm2";return;case"Controller Change":{let y=t.tracks[g],b=new We(o.ticks,G.controllerChange|k.channel,new Uint8Array([k.controller,k.value]));y.events[l[g]]=b,o=b,h.info("%cReplaced a system exclusive with controller change!",d.info);break}case"Program Change":{let y=t.tracks[g],b=new We(o.ticks,G.programChange|k.channel,new Uint8Array([k.value]));y.events[l[g]]=b,o=b,h.info("%cReplaced a system exclusive with program change!",d.info);break}}}let I=(o.statusByte&15)+C,E=i[I];if(B===G.programChange){let k={program:o.data[0],bankLSB:E.lastBankLSB?.data?.[1]??0,bankMSB:Se.subtractBankOffset(E.lastBank?.data?.[1]??0,t.bankOffset,s==="xg"),isGMGSDrum:E.isDrum},y=A.getPreset(k,s);if(h.info(`%cInput patch: %c${ze.toMIDIString(k)}%c. Channel %c${I}%c. Changing patch to ${y.toString()}.`,d.info,d.unrecognized,d.info,d.recognized,d.info),o.data[0]=y.program,y.isGMGSDrum&&Se.isSystemXG(s)||E.lastBank===void 0||(E.lastBank.data[1]=Se.addBankOffset(y.bankMSB,e,s==="xg"),E.lastBankLSB===void 0))return;E.lastBankLSB.data[1]=y.bankLSB;return}let m=o.data[0]===f.bankSelectLSB;o.data[0]!==f.bankSelect&&!m||(E.hasBankSelect=!0,m?E.lastBankLSB=o:E.lastBank=o)});for(let o=0;oR.port===I&&R.channels.has(l));if(E===void 0)continue;let m=E.events.findIndex(R=>R.statusByte===C);if(m===-1){let R=E.events.findIndex(Q=>Q.statusByte>128&&Q.statusByte<240&&(Q.statusByte&15)===l);if(R===-1)continue;let M=E.events[R].ticks,S=A.getPreset({bankMSB:0,bankLSB:0,program:0,isGMGSDrum:!1},s).program;E.addEvents(R,new We(M,G.programChange|l,new ee([S]))),m=R}h.info(`%cAdding bank select for %c${o}`,d.info,d.recognized);let k=E.events[m].ticks,y=A.getPreset({bankLSB:0,bankMSB:0,program:g.program,isGMGSDrum:g.isDrum},s),b=Se.addBankOffset(y.bankMSB,e,s==="xg");E.addEvents(m,new We(k,G.controllerChange|l,new ee([f.bankSelect,b])))}if(s==="gm"&&!Se.isSystemXG(s)){for(let g of n){let l=t.tracks[g.tNum];l.deleteEvent(l.events.indexOf(g.e))}let o=0;t.tracks[0].events[0].statusByte===G.trackName&&o++,t.tracks[0].addEvents(o,se.gsReset(0))}t.flush()}var Rs={bankOffset:0,metadata:{},correctBankOffset:!0,soundBank:void 0};function zn(t,e,A){let s=A.metadata;if(h.group("%cWriting the RMIDI File...",d.info),h.info("metadata",s),h.info("Initial bank offset",t.bankOffset),A.correctBankOffset){if(!A.soundBank)throw new Error("Sound bank must be provided if correcting bank offset.");Wn(t,A.bankOffset,A.soundBank)}let n=new ee(t.writeMIDI());s.name??=t.getName(),s.creationDate??=new Date,s.copyright??=_n,s.software??="SpessaSynth",Object.entries(s).forEach(o=>{let g=o;g[1]&&t.setRMIDInfo(g[0],g[1])});let a=[],r=(o,g)=>{a.push(U.write(o,g))};for(let o of Object.entries(t.rmidiInfo)){let g=o[0],l=o[1];switch(g){case"album":r("IALB",l),r("IPRD",l);break;case"software":r("ISFT",l);break;case"infoEncoding":r("IENC",l);break;case"creationDate":r("ICRD",l);break;case"picture":r("IPIC",l);break;case"name":r("INAM",l);break;case"artist":r("IART",l);break;case"genre":r("IGNR",l);break;case"copyright":r("ICOP",l);break;case"comment":r("ICMT",l);break;case"engineer":r("IENG",l);break;case"subject":r("ISBJ",l);break;case"midiEncoding":r("MENC",l);break}}let i=new ee(2);return hs(i,A.bankOffset,2),a.push(U.write("DBNK",i)),h.info("%cFinished!",d.info),h.groupEnd(),U.writeParts("RIFF",[$e("RMID"),U.write("data",n),U.writeParts("INFO",a,!0),new ee(e)]).buffer}var QA=class{rpnMSB={v:127,track:0,event:0};rpnLSB={v:127,track:0,event:0};nrpnMSB={v:0,track:0,event:0};nrpnLSB={v:0,track:0,event:0};dataMSB={v:0,track:0,event:0};dataLSB={v:0,track:0,event:0};channel;isRegistered=!0;constructor(t){this.channel=t}get paramMSB(){return this.isRegistered?this.rpnMSB:this.nrpnMSB}get paramLSB(){return this.isRegistered?this.rpnLSB:this.nrpnLSB}reset(){this.isRegistered=!0,this.rpnLSB.v=127,this.rpnMSB.v=127,this.nrpnMSB.v=0,this.nrpnLSB.v=0,this.resetData()}controllerChange(t,e,A,s){switch(t){case f.registeredParameterMSB:this.resetData(),this.isRegistered=!0,this.rpnMSB={v:e,track:A,event:s};break;case f.registeredParameterLSB:this.resetData(),this.isRegistered=!0,this.rpnLSB={v:e,track:A,event:s};break;case f.nonRegisteredParameterMSB:this.resetData(),this.isRegistered=!1,this.nrpnMSB={v:e,track:A,event:s};break;case f.nonRegisteredParameterLSB:this.resetData(),this.isRegistered=!1,this.nrpnLSB={v:e,track:A,event:s};break;case f.dataEntryMSB:return this.dataMSB={v:e,track:A,event:s},this.analyze();case f.dataEntryLSB:return this.dataLSB={v:e,track:A,event:s},this.analyze()}}resetData(){this.dataLSB.v=0,this.dataMSB.v=0}analyze(){let t=this.dataMSB.v<<7|this.dataLSB.v;return this.isRegistered?se.analyzeRPN(this.channel,this.rpnMSB.v<<7|this.rpnLSB.v,t):se.analyzeNRPN(this.channel,this.nrpnMSB.v<<7|this.nrpnLSB.v,t)}};function $n(t,e){h.groupCollapsed("%cSearching for all used programs and keys...",d.info);let A=16+Math.max(...t.portChannelOffsetMap),s=[],n="gs",a=0,r=B=>{n=B,a=0;for(let I=0;IB.port),g=t.portChannelOffsetMap,{timeline:l,tracks:C}=t;for(let B of l){let I=B.tr,E=B.ev,m=C[I].events[E];if(m.statusByte===G.midiPort&&t.tracks[I].channels.size>0){let b=m.data[0];g[b]===void 0&&(h.warn(`Invalid port ${b} on track ${I}. (No offset found in the MIDI map.`),b=0),o[I]=b;continue}let k=m.statusByte&240;if(k!==G.noteOn&&k!==G.controllerChange&&k!==G.programChange&&k!==G.systemExclusive)continue;let y=g[o[I]]||0;switch(k){case G.programChange:{let b=s[(m.statusByte&15)+y];b.preset=e.getPreset({bankMSB:b.bankMSB,bankLSB:b.bankLSB,program:m.data[0],isGMGSDrum:b.isDrum},n);break}case G.controllerChange:{let b=s[(m.statusByte&15)+y],R=m.data[0],M=m.data[1];switch(R){case f.registeredParameterMSB:case f.registeredParameterLSB:case f.nonRegisteredParameterLSB:case f.nonRegisteredParameterMSB:b.param.controllerChange(R,M,I,E);break;case f.dataEntryMSB:case f.dataEntryLSB:{let S=b.param.controllerChange(R,M,I,E);S?.type==="Key Shift"&&(b.keyShift=b.isDrum?0:S.value);break}case f.resetAllControllers:b.param.reset();break;case f.bankSelect:b.bankMSB=M;break;case f.bankSelectLSB:b.bankLSB=M;break}break}case G.noteOn:{let b=s[(m.statusByte&15)+y];if(m.data[1]===0||!b.preset)continue;let R=i.get(b.preset);R||(R=new Map,i.set(b.preset,R));let M=m.data[0]+(b.isDrum?0:a)+b.keyShift,S=R.get(M);S||(S=new Set,R.set(M,S)),S.add(m.data[1]);break}case G.systemExclusive:{let b=se.analyzeSysEx(m.data);switch(b.type){default:break;case"XG Reset":r("xg"),h.info("%cXG on detected!",d.recognized);break;case"GM2 On":r("gm2"),h.info("%cGM2 on detected!",d.recognized);break;case"GM On":r("gm"),h.info("%cGM on detected!",d.recognized);break;case"GM Off":case"GS Reset":r("gs"),h.info("%cGS on detected!",d.recognized);break;case"Master Key Shift":a=b.value;break;case"Key Shift":{let R=s[b.channel];R.keyShift=R.isDrum?0:b.value;break}case"Drums On":{let R=b.channel+y;s[R].isDrum=b.isDrum;break}case"Program Change":{let R=s[b.channel+y];R.preset=e.getPreset({bankMSB:R.bankMSB,bankLSB:R.bankLSB,program:b.value,isGMGSDrum:R.isDrum},n);break}case"Controller Change":{let R=b.channel+y;b.controller===f.bankSelectLSB?s[R].bankLSB=b.value:b.controller===f.bankSelect&&(s[R].bankMSB=b.value)}}}}}for(let[B,I]of i.entries())I.size===0&&(h.info(`%cDetected change but no keys for %c${B.name}`,d.info,d.value),i.delete(B));return h.groupEnd(),i}var jn=t=>(t.data=new ee(t.data.buffer),6e7/xt(t.data,3));function ea(t,e=0){let A=[];for(let C=0;C<16;C++)A.push([]);let s=0,n=60/(120*t.timeDivision),a=0,r=0,i=[];for(let C=0;C<16;C++)i.push([]);let o=(C,B)=>{let I=i[B].findIndex(m=>m.midiNote===C),E=i[B][I];if(E){let m=s-E.start;E.length=m,B===9&&(E.length=Math.max(m,e)),i[B].splice(I,1)}r--},{timeline:g,tracks:l}=t;for(;a>4,E=B.statusByte&15;if(I===8)o(B.data[0],E);else if(I===9)if(B.data[1]===0)o(B.data[0],E);else{o(B.data[0],E);let m={midiNote:B.data[0],start:s,length:-1,velocity:B.data[1]/127};A[E].push(m),i[E].push(m),r++}else B.statusByte===81&&(n=60/(jn(B)*t.timeDivision));if(++a>=g.length)break;s+=n*(l[g[a].tr].events[g[a].ev].ticks-B.ticks)}if(r>0)for(let[C,B]of i.entries())for(let I of B){let E=s-I.start;I.length=E,C===9&&(I.length=Math.max(E,e))}return A}var ta={character:49,preLowpass:50,level:51,time:52,delayFeedback:53,preDelayTime:55},Aa={preLowpass:57,level:58,feedback:59,delay:60,rate:61,depth:62,sendLevelToReverb:63,sendLevelToDelay:64},sa={preLowpass:81,timeCenter:82,timeRatioLeft:83,timeRatioRight:84,levelCenter:85,levelLeft:86,levelRight:87,level:88,feedback:89,sendLevelToReverb:90};function Mt(t,e,A,s){return new We(s,G.controllerChange|t%16,new ee([e,A]))}function na(t,e){h.groupCollapsed("%cApplying changes to the MIDI file...",d.info);let{channels:A,reverbParams:s,chorusParams:n,delayParams:a,insertionParams:r}=e;h.info("Desired channel changes",A),h.info("Desired reverb parameters",s),h.info("Desired chorus parameters",n),h.info("Desired delay parameters",a),h.info("Desired insertion parameters",r);let i=e.drumSetupParams==="clear",o=new Set,g=new Map;if(A)for(let[p,D]of A)D==="clear"?o.add(p):g.set(p,D);let l="gs",C=!1,B=0,I=0,E=t.tracks.map(p=>p.port),m={},k=0,y=(p,D)=>{t.tracks[p].channels.size!==0&&(k===0&&(k+=16,m[D]=0),m[D]===void 0&&(m[D]=k,k+=16),E[p]=D)};for(let[p,D]of t.tracks.entries())y(p,D.port);let b=k,R=[];for(let p=0;p{let K=t.tracks[D],O=q[D],Y=()=>{K.deleteEvent(O),q[D]--},H=W=>{let _=R[W],$=_.param,ne=$.paramMSB,ae=$.paramLSB;h.info(`%cClearing Non/Registered Parameter on ${W}. Clear MSB: %c${_.clearedParams.pMSB}%c, clear LSB: %c${_.clearedParams.pLSB}%c, clear data: %c${_.clearedParams.data}.`,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized),_.clearedParams.data||(Y(),D===ne.track&&O{K.addEvents(O+_,W),q[D]++},T=m[E[D]]||0;if(p.statusByte===G.midiPort){y(D,p.data[0]);return}if(p.statusByteG.systemExclusive)return;let F=p.statusByte&240,u=p.statusByte&15,x=u+T;if(p.statusByte!==G.systemExclusive&&o.has(x)){Y();return}let P=R[x],te=g.get(x);switch(F){case G.noteOn:if(!te)break;if(P.isFirstNoteOn){if(P.isFirstNoteOn=!1,te.controllers)for(let[_,$]of te.controllers)$!=="clear"&&Z(Mt(u,_,$,p.ticks));if(P.fineTune!==0){let _=Math.floor(P.fineTune*81.92)+8192,$=Mt(u,f.registeredParameterMSB,0,p.ticks),ne=Mt(u,f.registeredParameterLSB,1,p.ticks),ae=Mt(x,f.dataEntryMSB,_>>7&127,p.ticks);Z(Mt(u,f.dataEntryLSB,_&127,p.ticks)),Z(ae),Z(ne),Z($)}let W=te.patch;if(W&&W!=="clear"){h.info(`%cSetting %c${x}%c to %c${ze.toMIDIString(W)}%c. Track num: %c${D}`,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized);let _=W.bankMSB,$=W.bankLSB,ne=W.program;Z(new We(p.ticks,G.programChange|u,new ee([ne])));let ae=(J,ie)=>{Z(Mt(u,J?f.bankSelectLSB:f.bankSelect,ie,p.ticks))};Se.isSystemXG(l)&&W.isGMGSDrum&&(h.info(`%cAdding XG Drum change on track %c${D}`,d.recognized,d.value),_=Se.getDrumBank(l),$=0),ae(!1,_),ae(!0,$),W.isGMGSDrum&&!Se.isSystemXG(l)&&u!==9&&(h.info(`%cAdding GS Drum change on track %c${D}`,d.recognized,d.value),Z(se.gsDrumChange(p.ticks,u,1)))}}p.data[0]+=P.keyShift;break;case G.noteOff:if(!te)break;p.data[0]+=P.keyShift;break;case G.programChange:if(te?.patch){Y();return}break;case G.controllerChange:{let W=p.data[0],_=p.data[1];if(te?.controllers?.get(W)){Y();return}switch(W){case f.bankSelect:case f.bankSelectLSB:te?.patch&&Y();return;case f.registeredParameterLSB:case f.registeredParameterMSB:case f.nonRegisteredParameterMSB:case f.nonRegisteredParameterLSB:W===f.nonRegisteredParameterLSB||W===f.registeredParameterLSB?P.clearedParams.pLSB=!1:P.clearedParams.pMSB=!1,P.param.controllerChange(W,_,D,O);return;case f.dataEntryMSB:case f.dataEntryLSB:{P.clearedParams.data=!1;let $=P.param.controllerChange(W,_,D,O);if(!$)return;switch($.type){case"Drum Setup":i&&H(x);return;case"Controller Change":{let ne=$.controller,ae=$.channel;if(te?.controllers?.get(ne)){H(ae);return}(ne===f.bankSelect||ne===f.bankSelectLSB)&&te?.patch&&H(ae);break}case"Fine Tune":if(P.fineTune){if(P.isFirstNoteOn){let ne=P.fineTune+$.value;P.keyShift+=Math.trunc(ne/100),P.fineTune=ne%100,h.info(`%cFine tuning already present on ${x}, new relative tune: %c${ne} cents`,d.info,d.recognized)}H(x)}return}P.clearedParams.pLSB=!0,P.clearedParams.pMSB=!0;return}default:return}}case G.systemExclusive:{let W=se.analyzeSysEx(p.data);switch(W.type){default:return;case"XG Reset":h.info("%cXG system on detected",d.info),l="xg",C=!0,B=D,I=O;for(let _ of R)_.param.reset(),_.clearedParams={pLSB:!0,pMSB:!0,data:!0};return;case"GM2 On":h.info("%cGM2 system on detected",d.info),l="gm2",C=!0,B=D,I=O;for(let _ of R)_.param.reset(),_.clearedParams={pLSB:!0,pMSB:!0,data:!0};return;case"GS Reset":h.info("%cGS on detected!",d.recognized),C=!0,B=D,I=O;for(let _ of R)_.param.reset(),_.clearedParams={pLSB:!0,pMSB:!0,data:!0};return;case"GM Off":case"GM On":h.info("%cGM on detected, removing!",d.info),Y(),C=!1;return;case"Drum Setup":i&&Y();return;case"Reverb Param":s&&Y();return;case"Chorus Param":n&&Y();return;case"Delay Param":a&&Y();return;case"Insertion Param":r&&Y();return;case"Program Change":g.get(W.channel+T)?.patch&&Y();return;case"Fine Tune":{let _=g.get(W.channel+T),$=R[W.channel+T];if($.isFirstNoteOn&&_){let ne=$.fineTune+W.value;$.keyShift+=Math.trunc(ne/100),$.fineTune=ne%100,h.info(`%cFine tuning already present on ${W.channel+T}, new relative tune: %c${ne} cents`,d.info,d.recognized),Y()}break}case"Controller Change":{let _=W.controller,$=g.get(W.channel+T);if($?.controllers?.get(_)!==void 0){Y();return}(_===f.bankSelect||_===f.bankSelectLSB)&&$?.patch&&Y();return}}}}}),!C&&[...g.values()].some(p=>p.patch&&p.patch!=="clear")){let p=0;t.tracks[0].events[0].statusByte===G.trackName&&p++,t.tracks[0].addEvents(p,se.gsReset(0)),B=0,I=p,h.info("%cGS on not detected. Adding it.",d.info)}let M=Math.max(0,t.firstNoteOn),S=t.tracks[B],Q=I+1;if(s&&s!=="clear"){let p=ta,D=s;S.addEvents(Q,se.gsMessage(M,64,1,p.level,[D.level]),se.gsMessage(M,64,1,p.preLowpass,[D.preLowpass]),se.gsMessage(M,64,1,p.character,[D.character]),se.gsMessage(M,64,1,p.time,[D.time]),se.gsMessage(M,64,1,p.delayFeedback,[D.delayFeedback]),se.gsMessage(M,64,1,p.preDelayTime,[D.preDelayTime]))}if(n&&n!=="clear"){let p=Aa,D=n;S.addEvents(Q,se.gsMessage(M,64,1,p.level,[D.level]),se.gsMessage(M,64,1,p.preLowpass,[D.preLowpass]),se.gsMessage(M,64,1,p.feedback,[D.feedback]),se.gsMessage(M,64,1,p.delay,[D.delay]),se.gsMessage(M,64,1,p.rate,[D.rate]),se.gsMessage(M,64,1,p.depth,[D.depth]),se.gsMessage(M,64,1,p.sendLevelToReverb,[D.sendLevelToReverb]),se.gsMessage(M,64,1,p.sendLevelToDelay,[D.sendLevelToDelay]))}if(a&&a!=="clear"){let p=sa,D=a;S.addEvents(Q,se.gsMessage(M,64,1,p.level,[D.level]),se.gsMessage(M,64,1,p.preLowpass,[D.preLowpass]),se.gsMessage(M,64,1,p.timeCenter,[D.timeCenter]),se.gsMessage(M,64,1,p.timeRatioLeft,[D.timeRatioLeft]),se.gsMessage(M,64,1,p.timeRatioRight,[D.timeRatioRight]),se.gsMessage(M,64,1,p.levelCenter,[D.levelCenter]),se.gsMessage(M,64,1,p.levelLeft,[D.levelLeft]),se.gsMessage(M,64,1,p.levelRight,[D.levelRight]),se.gsMessage(M,64,1,p.feedback,[D.feedback]),se.gsMessage(M,64,1,p.sendLevelToReverb,[D.sendLevelToReverb]))}if(r&&r!=="clear"){let p=r;for(let D=0;D>8,p.type&127]))}t.flush(),h.groupEnd()}var RA=class An{name="";port=0;channels=new Set;events=[];static copyFrom(e){let A=new An;return A.copyFrom(e),A}copyFrom(e){this.name=e.name,this.port=e.port,this.channels=new Set(e.channels),this.events=e.events.map(A=>new We(A.ticks,A.statusByte,new ee(A.data)))}addEvent(e,A){this.events.splice(A,0,e)}addEvents(e,...A){this.events.splice(e,0,...A)}deleteEvent(e){this.events.splice(e,1)}pushEvent(e){this.events.push(e)}},aa={8:2,9:2,10:2,11:2,12:1,13:1,14:2};function Cs(t,e,A){h.groupCollapsed("%cParsing MIDI File...",d.info),t.fileName=A;let s=r=>{let i=Ee(r,4),o=Nt(r,4),g={type:i,size:o,data:new ee(o)},l=r.slice(r.currentIndex,r.currentIndex+g.size);return g.data.set(l,0),r.currentIndex+=g.size,g},n=s(e);if(n.type!=="MThd")throw h.groupEnd(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${n.type}"`);if(n.size!==6)throw h.groupEnd(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${n.size}`);t.format=Nt(n.data,2);let a=Nt(n.data,2);t.timeDivision=Nt(n.data,2);for(let r=0;r0&&(l+=t.tracks[r-1].events[t.tracks[r-1].events.length-1].ticks);let C=o.data;for(;C.currentIndex=G.noteOff&&I>4],g=I):I===G.systemExclusive?E=Qe(C):I===255?(I=C[C.currentIndex++],E=Qe(C)):E=0;let m=new ee(E);m.set(C.slice(C.currentIndex,C.currentIndex+E)),i.pushEvent(new We(l,I,m)),C.currentIndex+=E}t.tracks.push(i),h.info(`%cParsed %c${t.tracks.length}%c / %c${t.tracks.length}`,d.info,d.value,d.info,d.value)}h.info("%cAll tracks parsed correctly!",d.recognized),t.flush(!1),h.groupEnd()}function Bs(t){return t.toISOString().split(".")[0]+"Z"}var ra=[new Map([["domingo","Sunday"],["segunda-feira","Monday"],["ter\xE7a-feira","Tuesday"],["quarta-feira","Wednesday"],["quinta-feira","Thursday"],["sexta-feira","Friday"],["s\xE1bado","Saturday"],["janeiro","January"],["fevereiro","February"],["mar\xE7o","March"],["abril","April"],["maio","May"],["junho","June"],["julho","July"],["agosto","August"],["setembro","September"],["outubro","October"],["novembro","November"],["dezembro","December"]])];function ia(t){for(let e of ra){let A=t;for(let[n,a]of e.entries()){let r=new RegExp(n,"gi");A=A.replace(r,a)}let s=new Date(A);if(!Number.isNaN(s.getTime()))return s}}function oa(t){let e=/^(\d{2})\.(\d{2})\.(\d{4})$/.exec(t);if(e){let A=Number.parseInt(e[1]),s=Number.parseInt(e[2])-1,n=Number.parseInt(e[3]),a=new Date(n,s,A);if(!Number.isNaN(a.getTime()))return a}}function ga(t){let e=/^(\d{1,2})\s{1,2}(\d{1,2})\s{1,2}(\d{2})$/.exec(t);if(e){let A=e[1],s=(Number.parseInt(e[2])+1).toString(),n=e[3],a=new Date(`${s}/${A}/${n}`);if(!Number.isNaN(a.getTime()))return a}}function Ia(t){let e=/\b\d{4}\b/.exec(t);return e?new Date(e[0]):void 0}function Es(t){if(t=t.trim(),t.length===0)return new Date;let e=t.replaceAll(/\b(\d+)(st|nd|rd|th)\b/g,"$1").replace(/\s+at\s+/i," "),A=new Date(e);if(Number.isNaN(A.getTime())){let s=ia(t);if(s)return s;let n=oa(t);if(n)return n;let a=ga(t);if(a)return a;let r=Ia(t);return r||(h.warn(`Invalid date: "${t}". Replacing with the current date!`),new Date)}return A}function ca(t,e,A){e.currentIndex+=8;let s=Ee(e,4);if(s!=="RMID")throw h.groupEnd(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${s}"`);let n=U.read(e);if(n.header!=="data")throw h.groupEnd(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${n.header}"`);let a=n.data,r=!1,i=!1;for(;e.currentIndexxA[I]===i)??"":(h.info(`Unknown field specifier: ${i}`),o=`unknown_${i}`)):(i=Ee(r,Qe(r)),o=i);let B=Qe(r);if(B===0){let I=Qe(r),E=r.slice(r.currentIndex,r.currentIndex+I);r.currentIndex+=I;let m=Qe(E);this.metadata[o]=m<4?Ee(E,I-1):E.slice(E.currentIndex)}else h.info(`International content: ${B}`),r.currentIndex+=Qe(r)}let g=a.currentIndex,l=Qe(a),C=a.slice(a.currentIndex,g+l);if(a.currentIndex=g+l,l>0)for(this.packedContent=!0;C.currentIndexHA[E]===I):h.info(`Unrecognized resource format: ${I}`)}}else for(this.resourceFormat="folder";this.nodeData.currentIndex{let l=(C,B)=>{g.metadata[C]!==void 0&&typeof g.metadata[C]=="string"&&(t.rmidiInfo[B]=$e(g.metadata[C]))};if(l("nodeName","name"),l("title","name"),l("copyrightNotice","copyright"),l("comment","comment"),g.isFile)switch(g.resourceFormat){default:return;case"DLS1":case"DLS2":case"DLS22":case"mobileDLS":h.info("%cFound embedded DLS!",d.recognized),t.embeddedSoundBank=g.nodeData.buffer;break;case"StandardMIDIFile":case"StandardMIDIFileType1":h.info("%cFound embedded MIDI!",d.recognized),i=g.nodeData;break}else for(let C of g.innerNodes)o(C)};if(o(r),h.groupEnd(),!i)throw new Error("No MIDI data in the XMF file!");Cs(t,i,A)}function Ba(t,e){let A=new Map,s=e.systemParameters.keyShift,n=e.systemParameters.fineTune;for(let a=0;a>7;l.set(C,B)}A.set(a,{keyShift:i,fineTune:o,patch:g,controllers:l})}t.modify({channels:A,drumSetupParams:e.systemParameters.drumLock?"clear":void 0,reverbParams:e.systemParameters.reverbLock?e.reverbProcessor:void 0,chorusParams:e.systemParameters.chorusLock?e.chorusProcessor:void 0,delayParams:e.systemParameters.delayLock?e.delayProcessor:void 0,insertionParams:e.systemParameters.insertionEffectLock?e.insertionProcessor:void 0})}var Dt=class jA{tracks=[];timeline=[];timeDivision=480;duration=0;tempoChanges=[{ticks:0,tempo:120}];extraMetadata=[];lyrics=[];firstNoteOn=0;keyRange={min:0,max:127};lastVoiceEventTick=0;portChannelOffsetMap=[0];loop={start:0,end:0,type:"hard"};fileName;format=0;rmidiInfo={};bankOffset=0;isKaraokeFile=!1;isMultiPort=!1;isDLSRMIDI=!1;embeddedSoundBank;binaryName;get infoEncoding(){let e=this.rmidiInfo.infoEncoding;if(!e)return;let A=e.byteLength;return e[e.byteLength-1]===0&&A--,_e(e,A)}static fromArrayBuffer(e,A=""){let s=new jA,n=new ee(e);switch(_e(n,4)){case"RIFF":ca(s,n,A);break;case"XMF_":Ca(s,n,A);break;default:Cs(s,n,A);break}return s}static async fromFile(e){return this.fromArrayBuffer(await e.arrayBuffer(),e.name)}static copyFrom(e){let A=new jA;return A.copyFrom(e),A}copyFrom(e){this.copyMetadataFrom(e),this.embeddedSoundBank=e?.embeddedSoundBank?.slice(0)??void 0,this.tracks=e.tracks.map(A=>RA.copyFrom(A)),this.timeline=e.timeline.map(A=>({...A}))}midiTicksToSeconds(e){if(e=Math.max(e,0),this.tempoChanges.length===0)throw new Error("There are no tempo changes in the sequence. At least one is needed.");if(this.tempoChanges[this.tempoChanges.length-1].ticks!==0)throw new Error(`The last tempo change is not at 0 ticks. Got ${this.tempoChanges[this.tempoChanges.length-1].ticks} ticks.`);let A=this.tempoChanges.findIndex(n=>n.ticks<=e),s=0;for(;A=0;n--){let a=this.tempoChanges[n],r=this.tempoChanges[n-1],i=r?r.ticks-a.ticks:1/0,o=60/(a.tempo*this.timeDivision),g=i*o;if(A<=g)return s+=Math.round(A/o),s;s+=i,A-=g}return s}getUsedProgramsAndKeys(e){return $n(this,e)}preloadSynth(e){h.groupCollapsed("%cPreloading samples...",d.info);let A=this.getUsedProgramsAndKeys(e.soundBankManager);for(let[s,n]of A.entries()){h.info(`%cPreloading used samples on %c${s.name}%c...`,d.info,d.recognized,d.info);for(let[a,r]of n.entries())for(let i of r)e.getVoicesForPreset(s,a,i)}h.groupEnd()}flush(e=!0){if(e)for(let A of this.tracks)A.events.sort((s,n)=>s.ticks-n.ticks);this.parseInternal()}getNoteTimes(e=0){return ea(this,e)}writeMIDI(){return qn(this)}writeRMIDI(e,A=Rs){return zn(this,e,bA(A,Rs))}modify(e){na(this,e)}applySnapshot(e){Ba(this,e)}getName(e="Shift_JIS"){let A="",s=this.getRMIDInfo("name");if(s)return s.trim();if(this.binaryName){e=this.getRMIDInfo("midiEncoding")??e;try{A=new TextDecoder(e).decode(this.binaryName).trim()}catch(n){h.warn(`Failed to decode MIDI name: ${n}`)}}return A||this.fileName}getExtraMetadata(e="Shift_JIS"){e=this.infoEncoding??e;let A=new TextDecoder(e);return this.extraMetadata.map(s=>A.decode(s.data).replaceAll(/@T|@A/g,"").trim())}setRMIDInfo(e,A){if(this.rmidiInfo.infoEncoding=$e("utf-8",!0),e==="picture")this.rmidiInfo.picture=new Uint8Array(A);else if(e==="creationDate")this.rmidiInfo.creationDate=$e(Bs(A),!0);else{let s=new TextEncoder().encode(A);this.rmidiInfo[e]=new Uint8Array([...s,0])}}getRMIDInfo(e){if(!this.rmidiInfo[e])return;let A=this.infoEncoding??"UTF-8";if(e==="picture")return this.rmidiInfo[e].buffer;if(e==="creationDate")return Es(_e(this.rmidiInfo[e]));try{let s=new TextDecoder(A),n=this.rmidiInfo[e];return n[n.length-1]===0&&(n=n?.slice(0,-1)),s.decode(n.buffer).trim()}catch(s){h.warn(`Failed to decode ${e} name: ${s}`);return}}iterate(e){let A=new Array(this.tracks.length).fill(0),s=this.tracks.length;for(;s>0;){let n=0,a=1/0;for(let o=0;o=g.length||g[A[o]].ticks=r.length){s--;continue}let i=A[n];e(r[i],n,A),A[n]++}}copyMetadataFrom(e){this.fileName=e.fileName,this.timeDivision=e.timeDivision,this.duration=e.duration,this.firstNoteOn=e.firstNoteOn,this.lastVoiceEventTick=e.lastVoiceEventTick,this.format=e.format,this.bankOffset=e.bankOffset,this.isKaraokeFile=e.isKaraokeFile,this.isMultiPort=e.isMultiPort,this.isDLSRMIDI=e.isDLSRMIDI,this.isDLSRMIDI=e.isDLSRMIDI,this.tempoChanges=[...e.tempoChanges],this.extraMetadata=e.extraMetadata.map(A=>new We(A.ticks,A.statusByte,new ee(A.data))),this.lyrics=e.lyrics.map(A=>new We(A.ticks,A.statusByte,new ee(A.data))),this.portChannelOffsetMap=[...e.portChannelOffsetMap],this.binaryName=e?.binaryName?.slice(),this.loop={...e.loop},this.keyRange={...e.keyRange},this.rmidiInfo={};for(let A of Object.entries(e.rmidiInfo)){let s=A[0],n=A[1];this.rmidiInfo[s]=new Uint8Array(n)}}parseInternal(){h.group("%cInterpreting MIDI events...",d.info);let e=!1;this.tempoChanges=[{ticks:0,tempo:120}],this.extraMetadata=[],this.lyrics=[],this.firstNoteOn=0,this.keyRange={max:0,min:127},this.lastVoiceEventTick=0,this.portChannelOffsetMap=[0],this.loop={start:0,end:0,type:"hard"},this.isKaraokeFile=!1,this.isMultiPort=!1;let A=!1;this.rmidiInfo.name!==void 0&&(A=!0);let s=null,n=null,a="hard";for(let g of this.tracks){let l=new Set,C=!1;for(let I=0;I=128&&E.statusByte<240)switch(C=!0,E.ticks>this.lastVoiceEventTick&&(this.lastVoiceEventTick=E.ticks),E.statusByte&240){case G.controllerChange:switch(E.data[0]){case 2:case 111:E.data[1]===0&&(s=E.ticks);break;case 116:s=E.ticks;break;case 4:case 117:n===null&&(E.data[0]!==4||E.data[0]===4&&E.data[1]===0)?(a="soft",n=E.ticks):(n=0,a="hard");break;case 0:this.isDLSRMIDI&&E.data[1]!==0&&E.data[1]!==127&&(h.info("%cDLS RMIDI with offset 1 detected!",d.recognized),this.bankOffset=1)}break;case G.noteOn:{l.add(E.statusByte&15);let k=E.data[0];this.keyRange.min=Math.min(this.keyRange.min,k),this.keyRange.max=Math.max(this.keyRange.max,k);break}}let m=_e(E.data);switch(E.statusByte){case G.endOfTrack:I!==g.events.length-1&&(g.deleteEvent(I),I--,h.warn("Unexpected EndOfTrack. Removing!"));break;case G.setTempo:this.tempoChanges.push({ticks:E.ticks,tempo:6e7/xt(E.data,3)});break;case G.marker:switch(m.trim().toLowerCase()){default:break;case"start":case"loopstart":s=E.ticks;break;case"loopend":n=E.ticks}break;case G.copyright:this.extraMetadata.push(E);break;case G.lyric:m.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,h.info("%cKaraoke MIDI detected!",d.recognized)),this.isKaraokeFile?E.statusByte=G.text:this.lyrics.push(E);case G.text:{let k=m.trim();k.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,h.info("%cKaraoke MIDI detected!",d.recognized)):this.isKaraokeFile&&(k.startsWith("@T")||k.startsWith("@A")?e?this.extraMetadata.push(E):(this.binaryName=E.data.slice(2),e=!0,A=!0):k.startsWith("@")||this.lyrics.push(E));break}}}g.channels=l,g.name="";let B=g.events.find(I=>I.statusByte===G.trackName);B&&this.tracks.indexOf(g)>0&&(g.name=_e(B.data),!C&&!g.name.toLowerCase().includes("setup")&&this.extraMetadata.push(B))}this.tempoChanges.reverse(),h.info("%cCorrecting loops, ports and detecting notes...",d.info);let r=[];for(let g of this.tracks){let l=g.events.find(C=>(C.statusByte&240)===G.noteOn);l&&r.push(l.ticks)}this.firstNoteOn=Math.min(...r),h.info(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,d.info,d.recognized,d.info),s??=this.firstNoteOn,(n===null||n===0)&&(n=this.lastVoiceEventTick),this.loop={start:s,end:n,type:a},this.lastVoiceEventTick=Math.max(this.lastVoiceEventTick,this.loop.end),h.info(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,d.info,d.recognized,d.info,d.recognized);let i=0;this.portChannelOffsetMap=[];for(let g of this.tracks)if(g.port=-1,g.channels.size!==0)for(let l of g.events){if(l.statusByte!==G.midiPort)continue;let C=l.data[0];g.port=C,this.portChannelOffsetMap[C]===void 0&&(this.portChannelOffsetMap[C]=i,i+=16)}this.portChannelOffsetMap=[...this.portChannelOffsetMap].map(g=>g??0);let o=1/0;for(let g of this.tracks)g.port!==-1&&o>g.port&&(o=g.port);o===1/0&&(o=0);for(let g of this.tracks)(g.port===-1||g.port===void 0)&&(g.port=o);if(this.portChannelOffsetMap.length===0&&(this.portChannelOffsetMap=[0]),this.portChannelOffsetMap.length<2?h.info("%cNo additional MIDI Ports detected.",d.info):(this.isMultiPort=!0,h.info("%cMIDI Ports detected!",d.recognized)),!A)if(this.tracks.length>1){if(!this.tracks[0].events.some(g=>g.statusByte>=G.noteOn&&g.statusBytel.statusByte===G.trackName);g&&(this.binaryName=g.data)}}else{let g=this.tracks[0].events.find(l=>l.statusByte===G.trackName);g&&(this.binaryName=g.data)}if(this.extraMetadata=this.extraMetadata.filter(g=>g.data.length>0),this.lyrics.sort((g,l)=>g.ticks-l.ticks),!this.tracks.some(g=>g.events[0].ticks===0)){let g=this.tracks[0],l=this?.binaryName?.buffer;l||(l=new Uint8Array(0).buffer),g.addEvents(0,new We(0,G.trackName,new ee(l)))}this.duration=this.midiTicksToSeconds(this.lastVoiceEventTick),this.timeline.length=0,this.iterate((g,l,C)=>{this.timeline.push(Object.freeze({ev:C[l],tr:l}))}),this.binaryName?.length===0&&(this.binaryName=void 0),h.info(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}%c, total seconds time: %c${_A(Math.ceil(this.duration)).time}`,d.info,d.recognized,d.info,d.recognized),h.groupEnd()}};function Ea(t,e){if(this.externalMIDIPlayback&&t.statusByte>=128){this.sendMIDIMessage([t.statusByte,...t.data]);return}let A=this._midiData.tracks[e],s,n=0;t.statusByte>=128&&t.statusByte<240?(s=t.statusByte&240,n=t.statusByte&15):s=t.statusByte;let a=this.midiPortChannelOffsets[this.currentMIDIPorts[e]]||0;switch(n+=a,s){case G.noteOn:{let r=t.data[1];r>0?(this.synth.noteOn(n,t.data[0],r),this.playingNotes[n].set(t.data[0],r)):(this.synth.noteOff(n,t.data[0]),this.playingNotes[n].delete(t.data[0]));break}case G.noteOff:this.synth.noteOff(n,t.data[0]),this.playingNotes[n].delete(t.data[0]);break;case G.pitchWheel:this.synth.pitchWheel(n,t.data[1]<<7|t.data[0]);break;case G.controllerChange:if(this._midiData.isMultiPort&&A.channels.size===0)return;this.synth.controllerChange(n,t.data[0],t.data[1]);break;case G.programChange:if(this._midiData.isMultiPort&&A.channels.size===0)return;this.synth.programChange(n,t.data[0]);break;case G.polyPressure:this.synth.polyPressure(n,t.data[0],t.data[1]);break;case G.channelPressure:this.synth.channelPressure(n,t.data[0]);break;case G.systemExclusive:this.synth.systemExclusive(t.data,a);break;case G.setTempo:{let r=6e7/xt(t.data,3);this.oneTickToSeconds=60/(r*this._midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this._midiData.timeDivision),h.info("invalid tempo! falling back to 120 BPM"));break}case G.timeSignature:case G.endOfTrack:case G.midiChannelPrefix:case G.songPosition:case G.activeSensing:case G.keySignature:case G.sequenceNumber:case G.sequenceSpecific:case G.text:case G.lyric:case G.copyright:case G.trackName:case G.marker:case G.cuePoint:case G.instrumentName:case G.programName:break;case G.midiPort:this.assignMIDIPort(e,t.data[0]);break;case G.reset:this.synth.stopAllChannels(),this.synth.reset();break;default:h.info(`%cUnrecognized Event: %c${t.statusByte}%c status byte: %c${Object.keys(G).find(r=>G[r]===s)}`,d.warn,d.unrecognized,d.warn,d.value);break}s>=0&&s<128&&this.callEvent("metaEvent",{event:t,trackIndex:e})}function da(){if(this.paused||!this._midiData)return;let t=this.currentTime;for(;this.playedTime0&&n.end<=r.ticks){this.loopCount!==1/0&&(this.loopCount--,this.callEvent("loopCountChange",{newCount:this.loopCount})),n.type==="soft"?this.jumpToTick(n.start):this.setTimeTicks(n.start);return}if(this.index>=e.length||r.ticks>=s){this.songIsFinished();return}let i=e[this.index],o=A[i.tr].events[i.ev];this.playedTime+=this.oneTickToSeconds*(o.ticks-r.ticks)}}function fa(t,e){this._midiData.tracks[t].channels.size!==0&&(this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[e]=0),this.midiPortChannelOffsets[e]===void 0&&(this.synth.midiChannels.lengthe.port),this.midiPortChannelOffset=0,this.midiPortChannelOffsets={};for(let[e,A]of this._midiData.tracks.entries())this.assignMIDIPort(e,A.port);this.firstNoteTime=this._midiData.midiTicksToSeconds(this._midiData.firstNoteOn),h.info(`%cTotal song time: ${_A(Math.ceil(this._midiData.duration)).time}`,d.recognized),this.callEvent("songChange",{songIndex:this._songIndex}),this._midiData.duration<=.2&&(h.warn(`%cVery short song: (${_A(Math.round(this._midiData.duration)).time}). Disabling loop!`,d.warn),this.loopCount=0),this.currentTime=0}function ua(){this.lastNote=this.channelSystem==="xg"?60:-1}var mt=new Int16Array(128).fill(0),Me=(t,e)=>mt[t]=e<<7;Me(f.mainVolume,100);Me(f.balance,64);Me(f.expression,127);Me(f.pan,64);Me(f.filterResonance,64);Me(f.releaseTime,64);Me(f.attackTime,64);Me(f.brightness,64);Me(f.decayTime,64);Me(f.vibratoRate,64);Me(f.vibratoDepth,64);Me(f.vibratoDelay,64);Me(f.generalPurposeController6,64);Me(f.generalPurposeController8,64);Me(f.registeredParameterLSB,127);Me(f.registeredParameterMSB,127);Me(f.nonRegisteredParameterLSB,0);Me(f.nonRegisteredParameterMSB,0);var uA=new Int8Array(128).fill(127);uA[35]=0;uA[36]=0;function ma(t=!0){for(let e=0;e<128;e++){if(this.lockedControllers[e]){this.synthCore.callEvent("controllerChange",{channel:this.channel,controller:e,value:this._midiControllers[e]>>7});continue}let A=mt[e];this._midiControllers[e]!==A&&e!==f.portamentoControl&&e!==f.dataEntryMSB&&e!==f.registeredParameterMSB&&e!==f.registeredParameterLSB&&e!==f.nonRegisteredParameterMSB&&e!==f.nonRegisteredParameterLSB&&this.controllerChange(e,A>>7,t)}this.synthCore.systemParameters.insertionEffectLock||this.setMIDIParameter("efxAssign",!1),this.setMIDIParameter("rxChannel",this.channel),this.setMIDIParameter("assignMode",2),this.setMIDIParameter("randomPan",!1),this.setMIDIParameter("cc1",16),this.setMIDIParameter("cc2",17),this.setMIDIParameter("drumMap",this.channel%16===9?1:0),this.pitchWheel(8192),this.pitchWheelRange(2,!1),this.keyShift(0,!1),this.fineTune(0,!1),this.setMIDIParameter("pressure",0),this.modulationDepth(50,!1),!this.lockedControllers[f.monoModeOn]&&!this.lockedControllers[f.polyModeOn]&&this.setMIDIParameter("polyMode",!0),this.octaveTuning.fill(0),ua.call(this),this.resetDrumParams(),this.resetGeneratorOverrides(),this.resetGeneratorOffsets(),this.dynamicModulators.resetModulators(),this.sf2NRPNGeneratorLSB=0,this.lastParameterIsRegistered=!0,this._midiControllers[f.nonRegisteredParameterLSB]=0,this._midiControllers[f.nonRegisteredParameterMSB]=0,this._midiControllers[f.registeredParameterLSB]=16256,this._midiControllers[f.registeredParameterMSB]=16256,this._midiControllers[f.dataEntryMSB]=0,this._midiControllers[f.dataEntryLSB]=0,this.setBankMSB(Se.getDefaultBank(this.channelSystem)),this.setBankLSB(0),this.setGSDrums(!1),this.setDrums(this.channel%16===9),this.programChange(0)}var nn=[f.modulationWheel,f.expression,f.sustainPedal,f.portamentoOnOff,f.sostenutoPedal,f.softPedal,f.registeredParameterMSB,f.registeredParameterLSB];function pa(){this.pitchWheel(8192),this.setMIDIParameter("pressure",0);for(let t of nn){let e=mt[t];e!==this._midiControllers[t]&&this.controllerChange(t,e>>7)}}var rA=new Set([f.dataDecrement,f.dataIncrement,f.dataEntryMSB,f.dataEntryLSB,f.registeredParameterLSB,f.registeredParameterMSB,f.nonRegisteredParameterLSB,f.nonRegisteredParameterMSB,f.bankSelect,f.bankSelectLSB,f.resetAllControllers,f.monoModeOn,f.polyModeOn]);function ya(t,e=void 0){if(!this._midiData)return!1;this.oneTickToSeconds=60/(120*this._midiData.timeDivision),this.sendMIDIReset(),this.playedTime=0,this.index=0;let A=this.synth.midiChannels.length,s=[];for(let g=0;g=t)break}else if(B.ticks>=e)break;let I,E=0;B.statusByte>=128&&B.statusByte<240?(I=B.statusByte&240,E=B.statusByte&15):I=B.statusByte;let m=E+(this.midiPortChannelOffsets[C.port]||0);s[m]??={pitchWheel:8192,controllers:new Int16Array(mt),param:new QA(m),portamentoNote:-1};let k=s[m];switch(I){case G.noteOn:k.portamentoNote=B.data[0];break;case G.noteOff:break;case G.pitchWheel:k.pitchWheel=B.data[1]<<7|B.data[0];break;case G.systemExclusive:{let R=se.analyzeSysEx(B.data);switch(R.type){default:this.processEvent(B,l);break;case"Controller Change":{let{controller:M,value:S,channel:Q}=R;if(this._midiData.isMultiPort&&C.channels.size===0)break;if(M===f.resetAllControllers){r(Q);break}rA.has(M)?this.sendMIDICC(Q,M,S):s[Q].controllers[M]=S<<7}}break}case G.controllerChange:{if(this._midiData.isMultiPort&&C.channels.size===0)break;let R=B.data[0],M=B.data[1];switch(R){default:if(R===f.resetAllControllers){r(m);break}rA.has(R)?this.sendMIDICC(m,R,M):k.controllers[R]=M<<7;break;case f.registeredParameterMSB:case f.registeredParameterLSB:case f.nonRegisteredParameterLSB:case f.nonRegisteredParameterMSB:k.param.controllerChange(R,M,0,0),this.sendMIDICC(m,R,M);break;case f.dataEntryMSB:case f.dataEntryLSB:{let S=k.param.controllerChange(R,M,0,0);this.sendMIDICC(m,R,M),S.type==="Controller Change"&&(rA.has(S.controller)?this.sendMIDICC(m,S.controller,S.value):k.controllers[S.controller]=S.value<<7);break}}break}case G.setTempo:{let R=6e7/xt(B.data,3);this.oneTickToSeconds=60/(R*this._midiData.timeDivision),n=B,a=l;break}default:this.processEvent(B,l);break}let y=i[++this.index],b=o[y.tr].events[y.ev];if(b===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(b.ticks-B.ticks)}for(let g=0;g=0&&(this.externalMIDIPlayback?this.sendMIDICC(g,f.portamentoControl,l.portamentoNote):this.synth.midiChannels[g].setLastNote(l.portamentoNote));for(let C=0;C<128;C++){let B=l.controllers[C]>>7;B!==mt[C]&&!rA.has(C)&&this.sendMIDICC(g,C,B)}}return n&&this.callEvent("metaEvent",{event:n,trackIndex:a}),this.paused&&(this.pausedTime=this.playedTime),!0}var an=class{songs=[];shuffledSongIndexes=[];synth;externalMIDIPlayback=!1;retriggerPausedNotes=!0;loopCount=0;skipToFirstNoteOn=!0;isFinished=!1;preload=!0;onEventCall;processTick=da.bind(this);firstNoteTime=0;oneTickToSeconds=0;index=0;playedTime=0;pausedTime=-1;absoluteStartTime=0;playingNotes=[];currentMIDIPorts=[];midiPortChannelOffset=0;midiPortChannelOffsets={};assignMIDIPort=fa.bind(this);loadNewSequence=Qa.bind(this);processEvent=Ea.bind(this);setTimeTo=ya.bind(this);constructor(t){this.synth=t,this.absoluteStartTime=this.synth.currentTime;for(let e=0;e<16;e++)this.playingNotes.push(new Map)}_midiData;get midiData(){return this._midiData}get duration(){return this._midiData?.duration??0}_songIndex=0;get songIndex(){return this._songIndex}set songIndex(t){this._songIndex=t,this._songIndex=Math.max(0,t%this.songs.length),this.loadCurrentSong()}_shuffleMode=!1;get shuffleMode(){return this._shuffleMode}set shuffleMode(t){this._shuffleMode=t}_playbackRate=1;get playbackRate(){return this._playbackRate}set playbackRate(t){let e=this.currentTime;this._playbackRate=t,this.recalculateStartTime(e)}get currentTime(){return this.pausedTime!==void 0?this.pausedTime:(this.synth.currentTime-this.absoluteStartTime)*this._playbackRate}set currentTime(t){if(this._midiData)if(this.paused&&(this.pausedTime=t),t>this._midiData.duration||t<0)this.skipToFirstNoteOn?this.setTimeTicks(this._midiData.firstNoteOn-1):this.setTimeTicks(0);else if(this.skipToFirstNoteOn&&t=this._midiData.duration&&(this.currentTime=0),this.paused&&this.recalculateStartTime(this.pausedTime??0),this.retriggerPausedNotes&&!this.externalMIDIPlayback)for(let t=0;tA);for(this.shuffledSongIndexes.length=0;t.length>0;){let e=t[Math.floor(Math.random()*t.length)];this.shuffledSongIndexes.push(e),t.splice(t.indexOf(e),1)}}setTimeTicks(t){if(!this._midiData)return;for(let s of this.playingNotes)s.clear();let e=this._midiData.midiTicksToSeconds(t);this.callEvent("timeChange",{newTime:e});let A=this.setTimeTo(0,t);this.recalculateStartTime(this.playedTime)}recalculateStartTime(t){this.absoluteStartTime=this.synth.currentTime-t/this._playbackRate}jumpToTick(t){if(!this._midiData)return;this.sendMIDIAllOff();let e=this._midiData,A=e.midiTicksToSeconds(t);this.callEvent("timeChange",{newTime:A}),this.recalculateStartTime(A),this.playedTime=A;let s=e.timeline.findIndex(a=>e.tracks[a.tr].events[a.ev].ticks>=t);this.index=s===-1?e.timeline.length:s;let n=e.tempoChanges.find(a=>a.ticks<=t);this.oneTickToSeconds=60/(n.tempo*e.timeDivision)}sendMIDINoteOn(t,e,A){if(!this.externalMIDIPlayback){this.synth.noteOn(t,e,A);return}t%=16,this.sendMIDIMessage([G.noteOn|t,e,A])}sendMIDINoteOff(t,e){if(!this.externalMIDIPlayback){this.synth.noteOff(t,e);return}t%=16,this.sendMIDIMessage([G.noteOff|t,e,64])}sendMIDICC(t,e,A){if(!this.externalMIDIPlayback){this.synth.controllerChange(t,e,A);return}t%=16,this.sendMIDIMessage([G.controllerChange|t,e,A])}sendMIDISysEx(t){if(!this.externalMIDIPlayback){this.synth.systemExclusive(t);return}this.sendMIDIMessage([G.systemExclusive,...t])}sendMIDIPitchWheel(t,e){if(!this.externalMIDIPlayback){this.synth.pitchWheel(t,e);return}t%=16,this.sendMIDIMessage([G.pitchWheel|t,e&127,e>>7])}},Sa={linear:0,nearestNeighbor:1,hermite:2},Zt=Zt!==void 0?Zt:{},Fs=!1,rn;Zt.isInitialized=new Promise(t=>rn=t);var ka=function(t){var e,A,s,n,a,r,i,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",g="",l=0;t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=o.indexOf(t.charAt(l++)),a=o.indexOf(t.charAt(l++)),r=o.indexOf(t.charAt(l++)),i=o.indexOf(t.charAt(l++)),e=n<<2|a>>4,A=(15&a)<<4|r>>2,s=(3&r)<<6|i,g+=String.fromCharCode(e),r!==64&&(g+=String.fromCharCode(A)),i!==64&&(g+=String.fromCharCode(s));while(l1&&(I.thisProgram=process.argv[1].replace(/\\/g,"/")),I.arguments=process.argv.slice(2),process.on("uncaughtException",function(v){if(!(v instanceof qe))throw v}),process.on("unhandledRejection",function(v,w){process.exit(1)}),I.quit=function(v){process.exit(v)},I.inspect=function(){return"[Emscripten Module object]"}):b?(typeof read<"u"&&(I.read=function(w){return read(w)}),I.readBinary=function(w){var L;return typeof readbuffer=="function"?new Uint8Array(readbuffer(w)):(Y(typeof(L=read(w,"binary"))=="object"),L)},typeof scriptArgs<"u"?I.arguments=scriptArgs:typeof arguments<"u"&&(I.arguments=arguments),typeof quit=="function"&&(I.quit=function(v){quit(v)})):(m||k)&&(m?document.currentScript&&(R=document.currentScript.src):R=self.location.href,R=R.indexOf("blob:")!==0?R.split("/").slice(0,-1).join("/")+"/":"",I.read=function(w){var L=new XMLHttpRequest;return L.open("GET",w,!1),L.send(null),L.responseText},k&&(I.readBinary=function(w){var L=new XMLHttpRequest;return L.open("GET",w,!1),L.responseType="arraybuffer",L.send(null),new Uint8Array(L.response)}),I.readAsync=function(w,L,z){var re=new XMLHttpRequest;re.open("GET",w,!0),re.responseType="arraybuffer",re.onload=function(){if(re.status==200||re.status==0&&re.response){L(re.response);return}z()},re.onerror=z,re.send(null)},I.setWindowTitle=function(v){document.title=v});var S=I.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),Q=I.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||S);for(t in E)E.hasOwnProperty(t)&&(I[t]=E[t]);function p(v){var w=o;return o=o+v+15&-16,w}function D(v,w){return w||(w=16),v=Math.ceil(v/w)*w}function q(v){q.shown||(q.shown={}),q.shown[v]||(q.shown[v]=1,Q(v))}E=void 0;var K={"f64-rem":function(v,w){return v%w},debugger:function(){}},O=0;function Y(v,w){v||je("Assertion failed: "+w)}function H(v){var w=I["_"+v];return Y(w,"Cannot call unknown function "+v+", make sure it is exported"),w}var Z={stackSave:function(){bt()},stackRestore:function(){Ct()},arrayToC:function(v){var w,L,z=it(v.length);return w=v,L=z,n.set(w,L),z},stringToC:function(v){var w=0;if(v!=null&&v!==0){var L=(v.length<<2)+1;w=it(L),te(v,w,L)}return w}},T={string:Z.stringToC,array:Z.arrayToC};function F(v,w,L,z,re){var ce=H(v),de=[],j=0;if(z)for(var Ne=0;Ne>0],(z!=0||w)&&(de++,!w||de!=w););w||(w=de);var j="";if(ce<128){for(;w>0;)re=String.fromCharCode.apply(String,a.subarray(v,v+Math.min(w,1024))),j=j?j+re:re,v+=1024,w-=1024;return j}return L=v,(function(De,oe){for(var Ce=oe;De[Ce];)++Ce;if(Ce-oe>16&&De.subarray&&x)return x.decode(De.subarray(oe,Ce));for(var he,Te,Ue,et,ft,ot="";;){if(!(he=De[oe++]))return ot;if(!(128&he)){ot+=String.fromCharCode(he);continue}if(Te=63&De[oe++],(224&he)==192){ot+=String.fromCharCode((31&he)<<6|Te);continue}if(Ue=63&De[oe++],(240&he)==224?he=(15&he)<<12|Te<<6|Ue:(et=63&De[oe++],(248&he)==240?he=(7&he)<<18|Te<<12|Ue<<6|et:(ft=63&De[oe++],he=(252&he)==248?(3&he)<<24|Te<<18|Ue<<12|et<<6|ft:(1&he)<<30|Te<<24|Ue<<18|et<<12|ft<<6|63&De[oe++])),he<65536)ot+=String.fromCharCode(he);else{var tt=he-65536;ot+=String.fromCharCode(55296|tt>>10,56320|1023&tt)}}})(a,L)}var x=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function P(v,w,L,z){if(!(z>0))return 0;for(var re=L,ce=L+z-1,de=0;de=55296&&j<=57343&&(j=65536+((1023&j)<<10)|1023&v.charCodeAt(++de)),j<=127){if(L>=ce)break;w[L++]=j}else if(j<=2047){if(L+1>=ce)break;w[L++]=192|j>>6,w[L++]=128|63&j}else if(j<=65535){if(L+2>=ce)break;w[L++]=224|j>>12,w[L++]=128|j>>6&63,w[L++]=128|63&j}else if(j<=2097151){if(L+3>=ce)break;w[L++]=240|j>>18,w[L++]=128|j>>12&63,w[L++]=128|j>>6&63,w[L++]=128|63&j}else if(j<=67108863){if(L+4>=ce)break;w[L++]=248|j>>24,w[L++]=128|j>>18&63,w[L++]=128|j>>12&63,w[L++]=128|j>>6&63,w[L++]=128|63&j}else{if(L+5>=ce)break;w[L++]=252|j>>30,w[L++]=128|j>>24&63,w[L++]=128|j>>18&63,w[L++]=128|j>>12&63,w[L++]=128|j>>6&63,w[L++]=128|63&j}}return w[L]=0,L-re}function te(v,w,L){return P(v,a,w,L)}typeof TextDecoder<"u"&&new TextDecoder("utf-16le");function W(v,w){return v%w>0&&(v+=w-v%w),v}function _(v){I.buffer=s=v}function $(){I.HEAP8=n=new Int8Array(s),I.HEAP16=new Int16Array(s),I.HEAP32=r=new Int32Array(s),I.HEAPU8=a=new Uint8Array(s),I.HEAPU16=new Uint16Array(s),I.HEAPU32=new Uint32Array(s),I.HEAPF32=new Float32Array(s),I.HEAPF64=new Float64Array(s)}function ne(){var v=I.usingWasm?65536:16777216,w=2147483648-v;if(r[B>>2]>w)return!1;var L=J;for(J=Math.max(J,16777216);J>2];)J=J<=536870912?W(2*J,v):Math.min(W((3*J+2147483648)/4,v),w);var z=I.reallocBuffer(J);return z&&z.byteLength==J?(_(z),$(),!0):(J=L,!1)}i=o=g=l=C=B=0,I.reallocBuffer||(I.reallocBuffer=function(v){try{if(ArrayBuffer.transfer)w=ArrayBuffer.transfer(s,v);else{var w,L=n;w=new ArrayBuffer(v),new Int8Array(w).set(L)}}catch{return!1}return!!Xe(w)&&w});try{Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get)(new ArrayBuffer(4))}catch{}var ae=I.TOTAL_STACK||5242880,J=I.TOTAL_MEMORY||16777216;function ie(){return J}function pe(v){for(;v.length>0;){var w=v.shift();if(typeof w=="function"){w();continue}var L=w.func;typeof L=="number"?w.arg===void 0?I.dynCall_v(L):I.dynCall_vi(L,w.arg):L(w.arg===void 0?null:w.arg)}}J>2]=C,I.wasmTableSize=4,I.wasmMaxTableSize=4,I.asmGlobalArg={},I.asmLibraryArg={abort:je,assert:Y,enlargeMemory:ne,getTotalMemory:ie,abortOnCannotGrowMemory:function(){je("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+J+", (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(w,L,z){var re=bt();try{return I.dynCall_iii(w,L,z)}catch(ce){if(Ct(re),typeof ce!="number"&&ce!=="longjmp")throw ce;I.setThrew(1,0)}},___assert_fail:function(w,L,z,re){je("Assertion failed: "+u(w)+", at: "+[L?u(L):"unknown filename",z,re?u(re):"unknown function"])},___setErrNo:function(w){return I.___errno_location&&(r[I.___errno_location()>>2]=w),w},_abort:function(){I.abort()},_emscripten_memcpy_big:function(w,L,z){return a.set(a.subarray(L,L+z),w),w},_llvm_floor_f64:eA,DYNAMICTOP_PTR:B,tempDoublePtr:TA,ABORT:O,STACKTOP:g,STACK_MAX:l};var Yt=I.asm(I.asmGlobalArg,I.asmLibraryArg,s);I.asm=Yt,I.___errno_location=function(){return I.asm.___errno_location.apply(null,arguments)};var Xe=I._emscripten_replace_memory=function(){return I.asm._emscripten_replace_memory.apply(null,arguments)};I._free=function(){return I.asm._free.apply(null,arguments)},I._malloc=function(){return I.asm._malloc.apply(null,arguments)},I._memcpy=function(){return I.asm._memcpy.apply(null,arguments)},I._memset=function(){return I.asm._memset.apply(null,arguments)},I._sbrk=function(){return I.asm._sbrk.apply(null,arguments)},I._stb_vorbis_js_channels=function(){return I.asm._stb_vorbis_js_channels.apply(null,arguments)},I._stb_vorbis_js_close=function(){return I.asm._stb_vorbis_js_close.apply(null,arguments)},I._stb_vorbis_js_decode=function(){return I.asm._stb_vorbis_js_decode.apply(null,arguments)},I._stb_vorbis_js_open=function(){return I.asm._stb_vorbis_js_open.apply(null,arguments)},I._stb_vorbis_js_sample_rate=function(){return I.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},I.establishStackSpace=function(){return I.asm.establishStackSpace.apply(null,arguments)},I.getTempRet0=function(){return I.asm.getTempRet0.apply(null,arguments)},I.runPostSets=function(){return I.asm.runPostSets.apply(null,arguments)},I.setTempRet0=function(){return I.asm.setTempRet0.apply(null,arguments)},I.setThrew=function(){return I.asm.setThrew.apply(null,arguments)};var it=I.stackAlloc=function(){return I.asm.stackAlloc.apply(null,arguments)},Ct=I.stackRestore=function(){return I.asm.stackRestore.apply(null,arguments)},bt=I.stackSave=function(){return I.asm.stackSave.apply(null,arguments)};function qe(v){this.name="ExitStatus",this.message="Program terminated with exit("+v+")",this.status=v}function dt(v){v=v||I.arguments,!(Ye>0)&&((function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)lt(I.preRun.shift());pe(ve)})(),!(Ye>0)&&(I.calledRun||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),w()},1)):w())));function w(){!I.calledRun&&(I.calledRun=!0,O||(ht||(ht=!0,pe(Be)),pe(be),I.onRuntimeInitialized&&I.onRuntimeInitialized(),(function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)jt(I.postRun.shift());pe(xe)})()))}}function je(v){throw I.onAbort&&I.onAbort(v),v!==void 0?(S(v),Q(v),v=JSON.stringify(v)):v="",O=!0,"abort("+v+"). Build with -s ASSERTIONS=1 for more info."}if(I.dynCall_iii=function(){return I.asm.dynCall_iii.apply(null,arguments)},I.asm=Yt,I.ccall=F,I.cwrap=function(w,L,z,re){var ce=(z=z||[]).every(function(de){return de==="number"});return L!=="string"&&ce&&!re?H(w):function(){return F(w,L,z,arguments,re)}},qe.prototype=Error(),qe.prototype.constructor=qe,Re=function v(){I.calledRun||dt(),I.calledRun||(Re=v)},I.run=dt,I.abort=je,I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();I.noExitRuntime=!0,dt(),I.onRuntimeInitialized=()=>{Fs=!0,rn()},Zt.decode=function(v){return(function(L){if(!Fs)throw Error("SF3 decoder has not been initialized yet. Did you await synth.isReady?");var z={};function re(Rt){return new Int32Array(I.HEAPU8.buffer,Rt,1)[0]}function ce(Rt,Ft){var tA=new ArrayBuffer(Ft*Float32Array.BYTES_PER_ELEMENT),Je=new Float32Array(tA);return Je.set(new Float32Array(I.HEAPU8.buffer,Rt,Ft)),Je}z.open=I.cwrap("stb_vorbis_js_open","number",[]),z.close=I.cwrap("stb_vorbis_js_close","void",["number"]),z.channels=I.cwrap("stb_vorbis_js_channels","number",["number"]),z.sampleRate=I.cwrap("stb_vorbis_js_sample_rate","number",["number"]),z.decode=I.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var de,j,Ne,De,oe=z.open(),Ce=(de=L,j=L.byteLength,Ne=I._malloc(j),(De=new Uint8Array(I.HEAPU8.buffer,Ne,j)).set(new Uint8Array(de,0,j)),De),he=I._malloc(4),Te=I._malloc(4),Ue=z.decode(oe,Ce.byteOffset,Ce.byteLength,he,Te);if(I._free(Ce.byteOffset),Ue<0)throw z.close(oe),I._free(he),Error("stbvorbis decode failed: "+Ue);for(var et=z.channels(oe),ft=Array(et),ot=new Int32Array(I.HEAPU32.buffer,re(he),et),tt=0;tt=0}getPatch(t,e){let A=this.keyMappings[t]?.[e];if(A)return A.patch;throw new Error("No modifier.")}};function ba(t){for(this.keyModifierManager.setMappings(t.keyMappings);this.midiChannels.length>8,e.type&127]));for(let A=0;At.getSnapshot()),keyMappings:this.keyModifierManager.getMappings(),reverbProcessor:this.reverbProcessor.getSnapshot(),chorusProcessor:this.chorusProcessor.getSnapshot(),delayProcessor:this.delayProcessor.getSnapshot(),insertionProcessor:this.getInsertionSnapshot()}}var on={effectsEnabled:!0,eventsEnabled:!0,voiceCap:350,autoAllocateVoices:!1,reverbGain:1,reverbLock:!1,chorusGain:1,chorusLock:!1,delayGain:1,delayLock:!1,insertionEffectLock:!1,drumLock:!1,blackMIDIMode:!1,deviceID:-1,gain:1,pan:0,keyShift:0,fineTune:0,interpolationType:Sa.hermite,nrpnParamLock:!1,monophonicRetrigger:!1};function Fa(t,e){if(this.systemParameters[t]===e)return;let A=this.systemParameters[t];this.systemParameters[t]=e;for(let s of this.midiChannels)s.updateInternalParams();switch(t){default:break;case"voiceCap":{let s=Math.min(e,1e6);this.systemParameters.voiceCap=s;for(let n=s;nthis.voices.length&&(h.warn(`Allocating ${s-this.voices.length} new voices!`),this.allocateNewVoices(s-this.voices.length));break}case"keyShift":A!==e&&this.stopAllChannels(!0)}}var ds=-15e3,es=new Float32Array(15e3-ds+1);for(let t=0;tgn?440*Math.pow(2,(t-6900)/1200):ts[t-pA|0]}var Pt=-16600,Tt=new Float32Array(16e3-Pt+1);for(let t=0;t=iA&&(t.isActive=!1)}init(t){this.enteredRelease=!1,this.state=0,this.sampleTime=0,this.outputGain=0,this.canEndOnSilentSustain=t.modulatedGenerators[c.sustainVolEnv]>=iA,this.sustainCb=Math.min(Ke,t.modulatedGenerators[c.sustainVolEnv]),this.attackDuration=this.timecentsToSamples(t.modulatedGenerators[c.attackVolEnv]);let e=(60-t.targetKey)*t.modulatedGenerators[c.keyNumToVolEnvDecay],A=this.sustainCb/Ke;this.decayDuration=this.timecentsToSamples(t.modulatedGenerators[c.decayVolEnv]+e)*A,this.delayEnd=this.timecentsToSamples(t.modulatedGenerators[c.delayVolEnv]),this.attackEnd=this.attackDuration+this.delayEnd;let s=(60-t.targetKey)*t.modulatedGenerators[c.keyNumToVolEnvHold];this.holdEnd=this.timecentsToSamples(t.modulatedGenerators[c.holdVolEnv]+s)+this.attackEnd,this.decayEnd=this.decayDuration+this.holdEnd,this.attackEnd<=this.updateInterval&&(this.state=2)}process(t,e){let{releaseStartTimeSamples:A,releaseStartCb:s,releaseDuration:n,delayEnd:a,attackEnd:r,attackDuration:i,holdEnd:o,decayEnd:g,decayDuration:l,sustainCb:C}=this,B=this.sampleTime+=t;if(this.enteredRelease){let I=B-A,E=Ke-s;return this.attenuationCb=I/n*E+s,this.outputGain=Tt[this.attenuationCb-Pt|0]*e,this.attenuationCb=iA?(this.attenuationCb=Ke,this.outputGain=0,!1):(this.attenuationCb=C,this.outputGain=e*Tt[C-Pt|0],!0)}}timecentsToSamples(t){return Math.max(0,Math.floor(mA(t)*this.sampleRate))}},Fe={monoSample:1,rightSample:2,leftSample:4,linkedSample:8,romMonoSample:32769,romRightSample:32770,romLeftSample:32772,romLinkedSample:32776},Ie={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},le={linear:0,concave:1,convex:2,switch:3};var He=16384,SA=Object.keys(le).length,It=new Float32Array(He+1),yt=new Float32Array(He+1);It[0]=0;It[It.length-1]=1;yt[0]=0;yt[yt.length-1]=1;for(let t=1;t.5?1:0,s?A*2-1:A;case le.concave:return s?(A=A*2-1,A<0?-It[Math.trunc(A*-He)]:It[Math.trunc(A*He)]):It[Math.trunc(A*He)];case le.convex:return s?(A=A*2-1,A<0?-yt[Math.trunc(A*-He)]:yt[Math.trunc(A*He)]):yt[Math.trunc(A*He)]}}var OA=1,ss=new Float32Array(1e3);for(let t=0;ti&&(g=i+(g-i)%r);let C=g|0,B=C+1;B>=a&&(B-=r);let I=g-C,E=n[B],m=n[C];A[l]=m+(E-m)*I,g+=s}else for(let l=0;l=o)return A.fill(0,l,t),!1;let I=g-C,E=n[B],m=n[C];A[l]=m+(E-m)*I,g+=s}return this.cursor=g,!0}},Na=class extends Qs{process(t,e,A){let s=e*this.playbackStep,n=this.sampleData,{loopLength:a,loopStart:r,end:i}=this,o=this.cursor;if(this.isLooping)for(let g=0;gr&&(o=r+(o-r)%a),A[g]=n[o|0],o+=s;else for(let g=0;g=i)return A.fill(0,g,t),!1;A[g]=n[o|0],o+=s}return this.cursor=o,!0}},Pa=class extends Qs{process(t,e,A){let s=e*this.playbackStep,n=this.sampleData,{loopEnd:a,loopLength:r,loopStart:i,end:o}=this,g=this.cursor;if(this.isLooping)for(let l=0;li&&(g=i+(g-i)%r);let C=g|0,B=C+1,I=C+2,E=C+3,m=g-C;B>=a&&(B-=r),I>=a&&(I-=r),E>=a&&(E-=r);let k=n[C],y=n[B],b=n[I],R=n[E],M=(b-k)*.5,S=y-b,Q=M+S,p=Q+S+(R-y)*.5,D=Q+p;A[l]=((p*m-D)*m+M)*m+y,g+=s}else for(let l=0;l=o)return A.fill(0,l,t),!1;let k=n[C],y=n[B],b=n[I],R=n[E],M=(b-k)*.5,S=y-b,Q=M+S,p=Q+S+(R-y)*.5,D=Q+p;A[l]=((p*m-D)*m+M)*m+y,g+=s}return this.cursor=g,!0}},Ta=-2320,Ua=class{oscillators=[new La,new Na,new Pa];wavetable=this.oscillators[on.interpolationType];filter;generators=new Int16Array(St);modulatedGenerators=new Int16Array(St);modulators=new Array;modulatorValues=new Int16Array(64);modEnv=new Ga;volEnv;resonanceOffset=0;priority=0;isActive=!1;hasRendered=!1;isInRelease=!1;isHeld=!1;channel=0;midiNote=0;targetKey=0;velocity=0;rootKey=0;pressure=0;gainModifier=1;loopingMode=0;startTime=0;releaseStartTime=1/0;tuningCents=0;tuningRatio=1;currentPan=0;portamentoFromKey=-1;portamentoDuration=0;overridePan=0;pitchOffset=0;reverbSend=1;chorusSend=1;delaySend=1;exclusiveClass=0;overrideReleaseVolEnv=0;vibLfoPhase=0;vibLfoStartTime=0;modLfoPhase=0;modLfoStartTime=0;constructor(t,e){this.volEnv=new va(t,e),this.filter=new fs(t)}exclusiveRelease(t,e=Xn){this.overrideReleaseVolEnv=Ta,this.isInRelease=!1,this.releaseVoice(t,e)}releaseVoice(t,e=Vn){this.releaseStartTime=t,this.releaseStartTime-this.startTime>e&1)>0}function YA(t){return t?1:0}var st=class ns{isBipolar;isNegative;index;isCC;curveType;constructor(e=Ie.noController,A=le.linear,s=!1,n=!1,a=!1){this.isBipolar=n,this.isNegative=a,this.index=e,this.isCC=s,this.curveType=A}get sourceName(){return this.isCC?Object.keys(f).find(e=>f[e]===this.index)??this.index.toString():Object.keys(Ie).find(e=>Ie[e]===this.index)??this.index.toString()}get curveTypeName(){return Object.keys(le).find(e=>le[e]===this.curveType)??this.curveType.toString()}static fromSourceEnum(e){let A=pt(e,9),s=pt(e,8),n=pt(e,7);return new ns(e&127,e>>10&3,n,A,s)}static copyFrom(e){return new ns(e.index,e.curveType,e.isCC,e.isBipolar,e.isNegative)}toString(){return`${this.sourceName} ${this.curveTypeName} ${this.isBipolar?"bipolar":"unipolar"} ${this.isNegative?"negative":"positive"}`}toSourceEnum(){return this.curveType<<10|YA(this.isBipolar)<<9|YA(this.isNegative)<<8|YA(this.isCC)<<7|this.index}isIdentical(e){return this.index===e.index&&this.isNegative===e.isNegative&&this.isCC===e.isCC&&this.isBipolar===e.isBipolar&&this.curveType===e.curveType}getValue(e,A,s){let n;if(this.isCC)n=e.midiControllers[this.index];else switch(this.index){default:case Ie.noController:n=16383;break;case Ie.noteOnVelocity:n=s.velocity<<7;break;case Ie.noteOnKeyNum:n=s.targetKey<<7;break;case Ie.polyPressure:n=s.pressure<<7;break;case Ie.channelPressure:n=e.midiParameters.pressure<<7;break;case Ie.pitchWheel:n=A;break;case Ie.pitchWheelRange:n=Math.floor(e.midiParameters.pitchWheelRange*128)}let a=(this.isBipolar?2:0)|(this.isNegative?1:0);return hn[He*(this.curveType*SA+a)+n]}},hn=new Float32Array(He*4*SA);for(let t=0;tc[e]===this.destination)}static isIdentical(e,A,s=!1){return e.primarySource.isIdentical(A.primarySource)&&e.secondarySource.isIdentical(A.secondarySource)&&e.destination===A.destination&&e.transformType===A.transformType&&(!s||e.transformAmount===A.transformAmount)}static copyFrom(e){return new as(st.copyFrom(e.primarySource),st.copyFrom(e.secondarySource),e.destination,e.transformAmount,e.transformType)}toString(){return`Source: ${this.primarySource.toString()} +Secondary source: ${this.secondarySource.toString()} +to: ${this.destinationName} +amount: ${this.transformAmount}`+(this.transformType===2?"absolute value":"")}write(e,A){Ae(e,this.primarySource.toSourceEnum()),Ae(e,this.destination),Ae(e,this.transformAmount),Ae(e,this.secondarySource.toSourceEnum()),Ae(e,this.transformType),A&&A.mod++}sumTransform(e){let A=as.copyFrom(this);return A.transformAmount+=e.transformAmount,A}},ue=class extends ke{constructor(t,e,A,s,n){super(st.fromSourceEnum(t),st.fromSourceEnum(e),A,s,n),this.destination>In&&(this.destination=c.invalid)}},xa=[new ue(Ze(le.concave,!1,!0,!1,Ie.noteOnVelocity),0,c.initialAttenuation,960,0),new ue(129,0,c.vibLfoToPitch,50,0),new ue(Ze(le.concave,!1,!0,!0,f.mainVolume),0,c.initialAttenuation,960,0),new ue(13,0,c.vibLfoToPitch,50,0),new ue(526,16,c.fineTune,12700,0),new ue(650,0,c.pan,500,0),new ue(Ze(le.concave,!1,!0,!0,f.expression),0,c.initialAttenuation,960,0),new ue(219,0,c.reverbEffectsSend,200,0),new ue(221,0,c.chorusEffectsSend,200,0)],Ha=[new ue(Ze(le.convex,!0,!1,!0,f.attackTime),0,c.attackVolEnv,6e3,0),new ue(Ze(le.linear,!0,!1,!0,f.releaseTime),0,c.releaseVolEnv,3600,0),new ue(Ze(le.linear,!0,!1,!0,f.decayTime),0,c.decayVolEnv,3600,0),new ue(Ze(le.linear,!0,!1,!0,f.brightness),0,c.initialFilterFc,9600,0),new ue(ln,0,c.initialFilterQ,250,0),new ue(Ze(le.switch,!1,!1,!0,f.softPedal),0,c.initialAttenuation,50,0),new ue(Ze(le.switch,!1,!1,!0,f.softPedal),0,c.initialFilterFc,-2400,0),new ue(Ze(le.linear,!0,!1,!0,f.balance),0,c.pan,500,0)],Cn=[...xa,...Ha],Ge=class{type;value=0;constructor(t,e,A=!0){if(this.type=t,e===void 0)throw new Error("No value provided.");if(this.value=Math.round(e),A){let s=Ve[t];s!==void 0&&(this.value=Math.max(s.min,Math.min(s.max,this.value)))}}write(t){Ae(t,this.type),Ae(t,this.value)}toString(){return`${Object.keys(c).find(t=>c[t]===this.type)}: ${this.value}`}},zt=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 t=this.getGenerator(c.coarseTune,0),e=this.getGenerator(c.fineTune,0);return t*100+e}set fineTuning(t){let e=Math.trunc(t/100),A=t%100;this.setGenerator(c.coarseTune,e),this.setGenerator(c.fineTune,A)}addToGenerator(t,e,A=!0){let s=this.getGenerator(t,Ve[t].def);this.setGenerator(t,e+s,A)}setGenerator(t,e,A=!0){switch(t){case c.sampleID:throw new Error("Use setSample()");case c.instrument:throw new Error("Use setInstrument()");case c.velRange:case c.keyRange:throw new Error("Set the range manually")}if(e===null){this.generators=this.generators.filter(n=>n.type!==t);return}let s=this.generators.findIndex(n=>n.type===t);s===-1?this.addGenerators(new Ge(t,e,A)):this.generators[s]=new Ge(t,e,A)}addGenerators(...t){for(let e of t)switch(e.type){default:this.generators.push(e);break;case c.sampleID:case c.instrument:break;case c.velRange:this.velRange.min=e.value&127,this.velRange.max=e.value>>8&127;break;case c.keyRange:this.keyRange.min=e.value&127,this.keyRange.max=e.value>>8&127}}addModulators(...t){this.modulators.push(...t)}getGenerator(t,e){return this.generators.find(A=>A.type===t)?.value??e}copyFrom(t){this.generators=t.generators.map(e=>new Ge(e.type,e.value,!1)),this.modulators=t.modulators.map(ke.copyFrom.bind(ke)),this.velRange={...t.velRange},this.keyRange={...t.keyRange}}getWriteGenerators(t){let e=this.generators.filter(A=>A.type!==c.sampleID&&A.type!==c.instrument&&A.type!==c.keyRange&&A.type!==c.velRange);if(!t)throw new Error("No bank provided! ");return this.hasVelRange&&e.unshift(new Ge(c.velRange,this.velRange.max<<8|Math.max(this.velRange.min,0),!1)),this.hasKeyRange&&e.unshift(new Ge(c.keyRange,this.keyRange.max<<8|Math.max(this.keyRange.min,0),!1)),e}},Oa=48e3,MA=class{name;sampleRate;originalKey;pitchCorrection;linkedSample;sampleType;loopStart;loopEnd;linkedTo=[];dataOverridden=!0;compressedData;audioData;constructor(t,e,A,s,n,a,r){this.name=t,this.sampleRate=e,this.originalKey=A,this.pitchCorrection=s,this.loopStart=a,this.loopEnd=r,this.sampleType=n}get isCompressed(){return this.compressedData!==void 0}get isLinked(){return this.sampleType===Fe.rightSample||this.sampleType===Fe.leftSample||this.sampleType===Fe.linkedSample}get useCount(){return this.linkedTo.length}getRawData(t){return this.compressedData&&t&&!this.dataOverridden?this.compressedData:this.encodeS16LE()}resampleData(t){let e=this.getAudioData(),A=t/this.sampleRate,s=new Float32Array(Math.floor(e.length*A));for(let n=0;n96e3)&&(this.resampleData(Oa),e=this.getAudioData());let A=await t(e,this.sampleRate);this.setCompressedData(A)}catch(e){h.warn(`Failed to compress ${this.name}. Leaving as uncompressed!`,e),this.compressedData=void 0}}setSampleType(t){if(this.sampleType=t,this.isLinked||(this.linkedSample&&(this.linkedSample.linkedSample=void 0,this.linkedSample.sampleType=t),this.linkedSample=void 0),(t&32768)>0)throw new Error("ROM samples are not supported.")}unlinkSample(){this.setSampleType(Fe.monoSample)}setLinkedSample(t,e){if(t.linkedSample)throw new Error(`${t.name} is linked tp ${t.linkedSample.name}. Unlink it first.`);switch(this.linkedSample=t,t.linkedSample=this,e){case Fe.leftSample:this.setSampleType(Fe.leftSample),t.setSampleType(Fe.rightSample);break;case Fe.rightSample:this.setSampleType(Fe.rightSample),t.setSampleType(Fe.leftSample);break;case Fe.linkedSample:this.setSampleType(Fe.linkedSample),t.setSampleType(Fe.linkedSample);break;default:throw new Error("Invalid sample type: "+e)}}linkTo(t){this.linkedTo.push(t)}unlinkFrom(t){let e=this.linkedTo.indexOf(t);if(e===-1){h.warn(`Cannot unlink ${t.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(e,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(t,e){this.audioData=t,this.sampleRate=e,this.dataOverridden=!0,this.compressedData=void 0}setCompressedData(t){this.audioData=void 0,this.compressedData=t,this.dataOverridden=!1}encodeS16LE(){let t=this.getAudioData(),e=new Int16Array(t.length),A=t.length;for(let s=0;s32767?n=32767:n<-32768&&(n=-32768),e[s]=n}return new ee(e.buffer)}decodeVorbis(){if(this.audioData)return this.audioData;if(!this.compressedData)throw new Error("Compressed data is missing.");try{let t=FA.decode(this.compressedData).data[0];if(t===void 0)return h.warn(`Error decoding sample ${this.name}: Vorbis decode returned undefined.`),new Float32Array(0);for(let e=0;e=e.min&&A<=e.max}static addUniqueModulators(e,A){for(let s of A)e.some(n=>ke.isIdentical(s,n))||e.push(s)}static subtractRanges(e,A){return{min:Math.max(e.min,A.min),max:Math.min(e.max,A.max)}}delete(){for(let e of this.zones)e.instrument?.unlinkFrom(this)}deleteZone(e){this.zones[e]?.instrument?.unlinkFrom(this),this.zones.splice(e,1)}createZone(e){let A=new En(this,e);return this.zones.push(A),A}preload(e,A){for(let s=e;ske.isIdentical(C,I));B===-1?g.push(C):g[B]=g[B].sumTransform(C)}let l=new Int16Array(rs);for(let C of a.globalZone.generators)l[C.type]=C.value;for(let C of o.generators)l[C.type]=C.value;for(let C=0;C{g.push(...l.filter(C=>!g.some(B=>B.type===C.type)))},A=(g,l)=>{g.push(...l.filter(C=>!g.some(B=>ke.isIdentical(C,B))))},s=new Wt;s.name=this.name;let n=[],a=[],r=this.globalZone;n.push(...r.generators),a.push(...r.modulators);let i=r.keyRange,o=r.velRange;for(let g of this.zones){if(!g.instrument)throw new Error("No instrument in a preset zone.");let l=g.keyRange;g.hasKeyRange||(l=i);let C=g.velRange;g.hasVelRange||(C=o);let B=g.generators.map(S=>new Ge(S.type,S.value));e(B,n);let I=[...g.modulators];A(I,a);let E=g.instrument,m=E.zones,k=[],y=[],b=E.globalZone;k.push(...b.generators),y.push(...b.modulators);let R=b.keyRange,M=b.velRange;for(let S of m){if(!S.sample)throw new Error("No sample in an instrument zone.");let Q=S.keyRange;S.hasKeyRange||(Q=R);let p=S.velRange;if(S.hasVelRange||(p=M),Q=at.subtractRanges(Q,l),p=at.subtractRanges(p,C),Q.maxnew Ge(H.type,H.value));e(D,k);let q=[...S.modulators];A(q,y);let K=[...q];for(let H of I){let Z=K.findIndex(T=>ke.isIdentical(H,T));Z===-1?K.push(H):K[Z]=K[Z].sumTransform(H)}let O=D.map(H=>new Ge(H.type,H.value));for(let H of B){if(H.type===c.velRange||H.type===c.keyRange||H.type===c.instrument||H.type===c.endOper||H.type===c.sampleModes)continue;let Z=D.findIndex(T=>T.type===H.type);if(Z===-1){let T=Ve[H.type].def+H.value;O.push(new Ge(H.type,T))}else{let T=O[Z].value+H.value;O[Z]=new Ge(H.type,T)}}O=O.filter(H=>H.type!==c.sampleID&&H.type!==c.keyRange&&H.type!==c.velRange&&H.type!==c.endOper&&H.type!==c.instrument&&(!(H.type in Ve)||H.value!==Ve[H.type].def));let Y=s.createZone(S.sample);Y.keyRange=Q,Y.velRange=p,Y.keyRange.min===0&&Y.keyRange.max===127&&(Y.keyRange.min=-1),Y.velRange.min===0&&Y.velRange.max===127&&(Y.velRange.min=-1),Y.addGenerators(...O),Y.addModulators(...K)}}return s}write(e,A){h.info(`%cWriting ${this.name}...`,d.info),Le(e.pdta,this.name.slice(0,20),20),Le(e.xdta,this.name.slice(20),20),Ae(e.pdta,this.program);let s=this.bankMSB;this.isGMGSDrum?s=128:this.bankMSB===0&&(s=this.bankLSB),Ae(e.pdta,s),e.xdta.currentIndex+=4,Ae(e.pdta,A&65535),Ae(e.xdta,A>>16),ge(e.pdta,this.library),ge(e.pdta,this.genre),ge(e.pdta,this.morphology),e.xdta.currentIndex+=12}},qa=new Set([c.velRange,c.keyRange,c.instrument,c.sampleID,c.exclusiveClass,c.endOper,c.sampleModes,c.startloopAddrsOffset,c.startloopAddrsCoarseOffset,c.endloopAddrsOffset,c.endloopAddrsCoarseOffset,c.startAddrsOffset,c.startAddrsCoarseOffset,c.endAddrOffset,c.endAddrsCoarseOffset,c.initialAttenuation,c.fineTune,c.coarseTune,c.keyNumToVolEnvHold,c.keyNumToVolEnvDecay,c.keyNumToModEnvHold,c.keyNumToModEnvDecay]),Wt=class{name="";zones=[];globalZone=new zt;linkedTo=[];get useCount(){return this.linkedTo.length}createZone(t){let e=new Bn(this,t);return this.zones.push(e),e}linkTo(t){this.linkedTo.push(t);for(let e of this.zones)e.useCount++}unlinkFrom(t){let e=this.linkedTo.indexOf(t);if(e===-1){h.warn(`Cannot unlink ${t.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(e,1);for(let A of this.zones)A.useCount--}deleteUnusedZones(){this.zones=this.zones.filter(t=>{let e=t.useCount>0;return e||t.sample.unlinkFrom(this),e})}delete(){if(this.useCount>0)throw new Error(`Cannot delete an instrument that is used by: ${this.linkedTo.map(t=>t.name).toString()}.`);for(let t of this.zones)t.sample.unlinkFrom(this)}deleteZone(t,e=!1){let A=this.zones[t];return A.useCount-=1,A.useCount<1||e?(A.sample.unlinkFrom(this),this.zones.splice(t,1),!0):!1}globalize(){let t=this.globalZone;for(let A=0;A<58;A++){if(qa.has(A))continue;A=A;let s={},n=Ve[A]?.def||0;s[n]=0;for(let a of this.zones){let r=a.getGenerator(A,void 0);r===void 0?s[n]++:s[r]===void 0?s[r]=1:s[r]++;let i;switch(A){default:continue;case c.decayVolEnv:i=c.keyNumToVolEnvDecay;break;case c.holdVolEnv:i=c.keyNumToVolEnvHold;break;case c.decayModEnv:i=c.keyNumToModEnvDecay;break;case c.holdModEnv:i=c.keyNumToModEnvHold}if(a.getGenerator(i,void 0)!==void 0){s={};break}}if(Object.keys(s).length>0){let a=["0",0];for(let[i,o]of Object.entries(s))o>a[1]&&(a=[i,o]);let r=Number.parseInt(a[0]);r!==n&&t.setGenerator(A,r,!1);for(let i of this.zones){let o=i.getGenerator(A,void 0);o===void 0?r!==n&&i.setGenerator(A,n):o===r&&i.setGenerator(A,null)}}}let e=this.zones.length===0?[]:this.zones[0].modulators.map(A=>ke.copyFrom(A));for(let A of e){let s=!0;for(let n of this.zones)s&&(n.modulators.find(a=>ke.isIdentical(a,A))||(s=!1));if(s){t.addModulators(ke.copyFrom(A));for(let n of this.zones){let a=n.modulators.find(r=>ke.isIdentical(r,A));a&&a.transformAmount===A.transformAmount&&n.modulators.splice(n.modulators.indexOf(a),1)}}}}write(t,e){h.info(`%cWriting ${this.name}...`,d.info),Le(t.pdta,this.name.slice(0,20),20),Le(t.xdta,this.name.slice(20),20),Ae(t.pdta,e&65535),Ae(t.xdta,e>>>16)}};function Ja(t,e,A,s){let n=0,a=[],r=[];for(let l of t.samples){let C=l.getRawData(!0);n++,s?.(n/t.samples.length),h.info(`%cWrote sample %c${n}. ${l.name}%c of %c${t.samples.length}.`,d.info,d.recognized,d.info,d.recognized),a.push(C),r.push(C.length),l.isCompressed||a.push(new Uint8Array(92))}let i=U.getParts("smpl",a),o=U.getParts("sdta",i,!0),g=0;for(let[l,C]of t.samples.entries()){let B=r[l],I,E;C.isCompressed?(I=g,E=I+B):(I=g/2,E=I+B/2,g+=92),g+=B,e.push(I),A.push(E)}return o}var Ka=class extends MA{linkedSampleIndex;s16leData;startByteOffset;endByteOffset;sampleID;constructor(t,e,A,s,n,a,r,i,o,g,l,C){let B=(g&16)>0;g&=-17,super(t,a,r,i,g,s-e/2,n-e/2),this.dataOverridden=!1,this.name=t,this.startByteOffset=e,this.endByteOffset=A,this.sampleID=C;let I=l instanceof ee?l.currentIndex:0;l instanceof ee?B?(this.loopStart+=this.startByteOffset/2,this.loopEnd+=this.startByteOffset/2,this.setCompressedData(l.slice(this.startByteOffset/2+I,this.endByteOffset/2+I))):this.s16leData=l.slice(I+this.startByteOffset,I+this.endByteOffset):this.setAudioData(l.slice(this.startByteOffset/2,this.endByteOffset/2),a),this.linkedSampleIndex=o}getLinkedSample(t){if(this.linkedSample||!this.isLinked)return;let e=t[this.linkedSampleIndex];e?e.linkedSample?(h.info(`%cInvalid linked sample for ${this.name}: ${e.name} is already linked to ${e.linkedSample.name}`,d.warn),this.unlinkSample()):this.setLinkedSample(e,this.sampleType):(h.info(`%cInvalid linked sample for ${this.name}. Setting to mono.`,d.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 t=this.endByteOffset-this.startByteOffset;if(t<1)return h.warn(`Invalid sample ${this.name}! Invalid length: ${t}`),new Float32Array(1);let e=new Float32Array(t/2),A=new Int16Array(this.s16leData.buffer);for(let[s,n]of A.entries())e[s]=n/32768;return this.audioData=e,e}getRawData(t){return this.dataOverridden||this.compressedData?super.getRawData(t):this.s16leData??new Uint8Array(0)}};function Ms(t,e,A=!0){let s=[],n=0;for(;t.data.length>t.data.currentIndex;){let a=Va(n,t.data,e);s.push(a),n++}if(s.pop(),A)for(let a of s)a.getLinkedSample(s);return s}function Va(t,e,A){let s=Ee(e,20),n=V(e,4)*2,a=V(e,4)*2,r=V(e,4),i=V(e,4),o=V(e,4),g=e[e.currentIndex++];g>127&&(g=60);let l=Yn(e[e.currentIndex++]),C=V(e,2),B=V(e,2);return new Ka(s,n,a,r,i,o,g,l,C,B,A,t)}function Xa(t,e,A){let n=46*(t.samples.length+1),a=new ee(n),r=new ee(n),i=0;for(let[o,g]of t.samples.entries()){Le(a,g.name.slice(0,20),20),Le(r,g.name.slice(20),20);let l=e[o];ge(a,l),r.currentIndex+=4;let C=A[o];ge(a,C),r.currentIndex+=4;let B=g.loopStart+l,I=g.loopEnd+l;g.isCompressed&&(B-=l,I-=l),ge(a,B),ge(a,I),ge(a,g.sampleRate),a[a.currentIndex++]=g.originalKey,a[a.currentIndex++]=g.pitchCorrection,r.currentIndex+=14;let E=g.linkedSample?t.samples.indexOf(g.linkedSample):0;Ae(a,Math.max(0,E)&65535),Ae(r,Math.max(0,E)>>16),i=Math.max(i,E);let m=g.sampleType;g.isCompressed&&(m|=16),Ae(a,m),r.currentIndex+=2}return Le(a,"EOS",46),Le(r,"EOS",46),{pdta:U.write("shdr",a),xdta:U.write("shdr",r)}}function vs(t,e=!1){let A=e?t.presets:t.instruments,s=e?"pgen":"igen",n=e?"pmod":"imod",a=e?"pbag":"ibag",r=e?"phdr":"inst",i=e?38:22,o=0,g=new Array,l=0,C=new Array,B=new Array,I=new Array,E=0,m=new Array,k=p=>{g.push(o);let D=p.getWriteGenerators(t);o+=D.length,B.push(...D),C.push(l);let q=p.modulators;l+=q.length,I.push(...q)};for(let p of A){m.push(E),k(p.globalZone);for(let D of p.zones)k(D);E+=p.zones.length+1}B.push(new Ge(0,0,!1)),I.push(new ue(0,0,0,0,0)),g.push(o),C.push(l),m.push(E);let y=new ee(B.length*4);for(let p of B)p.write(y);let b=new ee(I.length*10);for(let p of I)p.write(b);let R=C.length*4,M={pdta:new ee(R),xdta:new ee(R)};for(let[p,D]of C.entries()){let q=g[p];Ae(M.pdta,q&65535),Ae(M.pdta,D&65535),Ae(M.xdta,q>>16),Ae(M.xdta,D>>16)}let S=(A.length+1)*i,Q={pdta:new ee(S),xdta:new ee(S)};for(let[p,D]of A.entries())D.write(Q,m[p]);return e?(Le(Q.pdta,"EOP",20),Q.pdta.currentIndex+=4,Ae(Q.pdta,E&65535),Q.pdta.currentIndex+=12,Le(Q.xdta,"",20),Q.xdta.currentIndex+=4,Ae(Q.xdta,E>>16),Q.xdta.currentIndex+=12):(Le(Q.pdta,"EOI",20),Ae(Q.pdta,E&65535),Le(Q.xdta,"",20),Ae(Q.xdta,E>>16)),{writeXdta:Math.max(o,l,E)>65535,gen:{pdta:U.write(s,y),xdta:U.write(n,new ee(4))},mod:{pdta:U.write(n,b),xdta:U.write(n,new ee(10))},bag:{pdta:U.write(a,M.pdta),xdta:U.write(a,M.xdta)},hdr:{pdta:U.write(r,Q.pdta),xdta:U.write(r,Q.xdta)}}}var dn={writeDefaultModulators:!0,writeExtendedLimits:!0,software:"SpessaSynth"};function Za(t,e){let A=bA(e,dn);h.groupCollapsed("%cSaving soundbank...",d.info),h.group("%cWriting INFO...",d.info);let s=[],n=(y,b)=>{b&&s.push(...U.getParts(y,[$e(b,!0,!0)]))},a=t.soundBankInfo;{let y=new ee(4);Ae(y,a.version.major),Ae(y,a.version.minor),s.push(U.write("ifil",y))}if(n("isng",a.soundEngine),n("INAM",a.name),n("irom",a.romInfo),a.romVersion){let y=new ee(4);Ae(y,a.romVersion.major),Ae(y,a.romVersion.minor),s.push(U.write("iver",y))}n("ICRD",Bs(a.creationDate)),n("IENG",a.engineer),n("IPRD",a.product),n("ICOP",a.copyright),n("ICMT",a?.subject?(a?.comment?a.comment+` +`:"")+a.subject:a?.comment);let r=A.software;if(n("ISFT",r),t.defaultModulators.some(y=>!Cn.some(b=>ke.isIdentical(b,y,!0)))&&A?.writeDefaultModulators){let y=t.defaultModulators;h.info(`%cWriting %c${y.length}%c default modulators...`,d.info,d.recognized,d.info);let b=new ee(10+y.length*10);for(let R of y)R.write(b);hs(b,0,10),s.push(...U.getParts("DMOD",[b]))}h.groupEnd(),h.info("%cWriting SDTA...",d.info);let i=[],o=[],g=Ja(t,i,o);h.info("%cWriting PDTA...",d.info),h.info("%cWriting SHDR...",d.info);let l=Xa(t,i,o);h.group("%cWriting instruments...",d.info);let C=vs(t,!1);h.groupEnd(),h.group("%cWriting presets...",d.info);let B=vs(t,!0);h.groupEnd();let I=[B.hdr,B.bag,B.mod,B.gen,C.hdr,C.bag,C.mod,C.gen,l],E=U.getParts("pdta",I.map(y=>y.pdta),!0);A.writeExtendedLimits&&(C.writeXdta||B.writeXdta||t.presets.some(y=>y.name.length>20)||t.instruments.some(y=>y.name.length>20)||t.samples.some(y=>y.name.length>20))&&(h.info("%cWriting the xdta chunk as writeExtendedLimits is enabled and at least one condition was met.",d.info,d.value),s.push(...U.getParts("xdta",I.map(y=>y.xdta),!0)));let m=U.getParts("INFO",s,!0);h.info("%cWriting the output file...",d.info);let k=U.writeParts("RIFF",[$e("sfbk"),...m,...g,...E]);return h.info(`%cSaved successfully! Final file size: %c${k.length}`,d.info,d.recognized),h.groupEnd(),k.buffer}var Ht=class{static verifyHeader(t,...e){for(let A of e)if(t.header.toLowerCase()===A.toLowerCase())return;this.parsingError(`Invalid DLS chunk header! Expected "${e.join(", or ")}" got "${t.header.toLowerCase()}"`)}static verifyText(t,...e){for(let A of e)if(t.toLowerCase()===A.toLowerCase())return;this.parsingError(`FourCC error: Expected "${e.join(", or ")}" got "${t.toLowerCase()}"`)}static parsingError(t){throw h.groupEnd(),new Error(`DLS parse error: ${t} The file may be corrupted.`)}static verifyAndReadList(t,...e){this.verifyHeader(t,"LIST"),t.data.currentIndex=0,this.verifyText(Ee(t.data,4),...e);let A=[];for(;t.data.length>t.data.currentIndex;)A.push(U.read(t.data));return A}},X={none:0,modLfo:1,velocity:2,keyNum:3,volEnv:4,modEnv:5,pitchWheel:6,polyPressure:7,channelPressure:8,vibratoLfo:9,modulationWheel:129,volume:135,pan:138,expression:139,chorus:221,reverb:219,pitchWheelRange:256,fineTune:257,coarseTune:258},N={none:0,gain:1,reserved:2,pitch:3,pan:4,keyNum:5,chorusSend:128,reverbSend:129,modLfoFreq:260,modLfoDelay:261,vibLfoFreq:276,vibLfoDelay:277,volEnvAttack:518,volEnvDecay:519,reservedEG1:520,volEnvRelease:521,volEnvSustain:522,volEnvDelay:523,volEnvHold:524,modEnvAttack:778,modEnvDecay:779,reservedEG2:780,modEnvRelease:781,modEnvSustain:782,modEnvDelay:783,modEnvHold:784,filterCutoff:1280,filterQ:1281},Gs={forward:0,loopAndRelease:1},oA=20,gA=16,Ut=class Vt extends Ht{gain=0;unityNote=60;fineTune=0;loops=new Array;fulOptions=2;static copyFrom(e){let A=new Vt;return A.unityNote=e.unityNote,A.gain=e.gain,A.fineTune=e.fineTune,A.loops=e.loops.map(s=>({...s})),A.fulOptions=e.fulOptions,A}static read(e){this.verifyHeader(e,"wsmp");let A=new Vt,s=V(e.data,4);if(s!==oA&&h.warn(`Wsmp cbSize mismatch: got ${s}, expected ${oA}.`),A.unityNote=V(e.data,2),A.fineTune=ls(e.data[e.data.currentIndex++],e.data[e.data.currentIndex++]),A.gain=V(e.data,4)|0,A.fulOptions=V(e.data,4),V(e.data,4)!==0){let n=V(e.data,4);n!==gA&&h.warn(`CbSize for loop in wsmp mismatch. Expected ${gA}, got ${n}.`);let a=V(e.data,4),r=V(e.data,4),i=V(e.data,4);A.loops.push({loopStart:r,loopLength:i,loopType:a})}return A}static fromSFSample(e){let A=new Vt;return A.unityNote=e.originalKey,A.fineTune=e.pitchCorrection,(e.loopEnd!==0||e.loopStart!==0)&&A.loops.push({loopStart:e.loopStart,loopLength:e.loopEnd-e.loopStart,loopType:Gs.forward}),A}static fromSFZone(e){let A=new Vt;A.unityNote=e.getGenerator(c.overridingRootKey,e.sample.originalKey),e.getGenerator(c.scaleTuning,100)===0&&e.keyRange.max-e.keyRange.min===0&&(A.unityNote=e.keyRange.min),A.fineTune=e.fineTuning+e.sample.pitchCorrection,A.gain=-(e.getGenerator(c.initialAttenuation,0)*.4)<<16;let s=e.getGenerator(c.sampleModes,0);if(s!==0){let n=e.sample.loopStart+e.getGenerator(c.startloopAddrsOffset,0)+e.getGenerator(c.startloopAddrsCoarseOffset,0)*32768,a=e.sample.loopEnd+e.getGenerator(c.endloopAddrsOffset,0)+e.getGenerator(c.endloopAddrsCoarseOffset,0)*32768,r;switch(s){case 1:default:r=0;break;case 3:r=1}A.loops.push({loopType:r,loopStart:n,loopLength:a-n})}return A}toSFZone(e,A){let s=0,n=this.loops[0];n&&(s=n.loopType===Gs.loopAndRelease?3:1),s!==0&&e.setGenerator(c.sampleModes,s);let a=-(this.gain>>16)/.4;if(a!==0&&e.setGenerator(c.initialAttenuation,a),e.fineTuning=this.fineTune-A.pitchCorrection,this.unityNote!==A.originalKey&&e.setGenerator(c.overridingRootKey,this.unityNote),n){let r=n.loopStart-A.loopStart,i=n.loopStart+n.loopLength-A.loopEnd;if(r!==0){let o=r%32768;e.setGenerator(c.startloopAddrsOffset,o);let g=Math.trunc(r/32768);g!==0&&e.setGenerator(c.startloopAddrsCoarseOffset,g)}if(i!==0){let o=i%32768;e.setGenerator(c.endloopAddrsOffset,o);let g=Math.trunc(i/32768);g!==0&&e.setGenerator(c.endloopAddrsCoarseOffset,g)}}}write(){let e=new ee(oA+this.loops.length*gA);ge(e,oA),Ae(e,this.unityNote),Ae(e,this.fineTune),ge(e,this.gain),ge(e,this.fulOptions),ge(e,this.loops.length);for(let A of this.loops)ge(e,gA),ge(e,A.loopType),ge(e,A.loopStart),ge(e,A.loopLength);return U.write("wsmp",e)}},qA={PCM:1,ALAW:6};function _a(t,e){let A=Math.pow(2,e*8-1),s=Math.pow(2,e*8),n,a=!1;e===1?(n=255,a=!0):n=A;let r=t.length/e,i=new Float32Array(r);if(e===2){let o=new Int16Array(t.buffer);for(let[g,l]of o.entries())i[g]=l/32768}else for(let o=0;o=A&&(g-=s),i[o]=g/n)}return i}function Wa(t,e){let A=t.length/e,s=new Float32Array(A);for(let n=0;n>4,o=r&15;i>0&&(o+=16),o=(o<<4)+8,i>1&&(o=o<127?o:-o)/32768}return s}var za=class extends MA{wFormatTag;bytesPerSample;rawData;constructor(t,e,A,s,n,a,r,i,o){super(t,e,A,s,Fe.monoSample,n,a),this.dataOverridden=!1,this.rawData=r.data,this.wFormatTag=i,this.bytesPerSample=o}getAudioData(){if(!this.rawData)return new Float32Array(0);if(!this.audioData){let t;switch(this.wFormatTag){default:h.warn(`Failed to decode sample. Unknown wFormatTag: ${this.wFormatTag}`),t=new Float32Array(this.rawData.length/this.bytesPerSample);break;case qA.PCM:t=_a(this.rawData,this.bytesPerSample);break;case qA.ALAW:t=Wa(this.rawData,this.bytesPerSample);break}this.setAudioData(t,this.sampleRate)}return this.audioData??new Float32Array(0)}getRawData(t){return this.dataOverridden||this.isCompressed?super.getRawData(t):this.wFormatTag===qA.PCM&&this.bytesPerSample===2?this.rawData:this.encodeS16LE()}},Ls=class is extends Ht{waveSample=new Ut;wFormatTag;bytesPerSample;sampleRate;dataChunk;name="Unnamed sample";constructor(e,A,s,n){super(),this.wFormatTag=e,this.bytesPerSample=A,this.sampleRate=s,this.dataChunk=n}static read(e){let A=this.verifyAndReadList(e,"wave"),s=A.find(B=>B.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");let n=V(s.data,2),a=V(s.data,2);if(a!==1)throw new Error(`Only mono samples are supported. Fmt reports ${a} channels.`);let r=V(s.data,4);V(s.data,4),V(s.data,2);let i=V(s.data,2)/8,o=A.find(B=>B.header==="data");if(!o)throw new Error("No data chunk in the WAVE chunk!");let g=new is(n,i,r,o),l=U.findListType(A,"INFO");if(l){let B=U.read(l.data);for(;B.header!=="INAM"&&l.data.currentIndexB.header==="wsmp");return C&&(g.waveSample=Ut.read(C)),g}static fromSFSample(e){let A=e.getRawData(!1),s=new is(1,2,e.sampleRate,new U("data",A.length,new ee(A.buffer)));return s.name=e.name,s.waveSample=Ut.fromSFSample(e),s}toSFSample(e){let A=this.waveSample.unityNote,s=this.waveSample.fineTune,n=Math.trunc(s/100);A+=n,s-=n*100;let a=0,r=0,i=this.waveSample.loops?.[0];i&&(a=i.loopStart,r=i.loopStart+i.loopLength);let o=new za(this.name,this.sampleRate,A,s,a,r,this.dataChunk,this.wFormatTag,this.bytesPerSample);e.addSamples(o)}write(){let e=this.writeFmt(),A=this.waveSample.write(),s=U.getParts("data",[this.dataChunk.data]),n=U.write("INAM",$e(this.name,!0)),a=U.write("INFO",n,!1,!0);return h.info(`%cSaved %c${this.name}%c successfully!`,d.recognized,d.value,d.recognized),U.getParts("wave",[e,A,...s,a],!0)}writeFmt(){let e=new ee(18);return Ae(e,this.wFormatTag),Ae(e,1),ge(e,this.sampleRate),ge(e,this.sampleRate*2),Ae(e,2),Ae(e,this.bytesPerSample*8),U.write("fmt ",e)}},At=class os{source;transform;bipolar;invert;constructor(e=X.none,A=le.linear,s=!1,n=!1){this.source=e,this.transform=A,this.bipolar=s,this.invert=n}get sourceName(){return Object.keys(X).find(e=>X[e]===this.source)??this.source.toString()}get transformName(){return Object.keys(le).find(e=>le[e]===this.transform)??this.transform.toString()}static copyFrom(e){return new os(e.source,e.transform,e.bipolar,e.invert)}static fromSFSource(e){let A;if(e.isCC)switch(e.index){case f.modulationWheel:A=X.modulationWheel;break;case f.mainVolume:A=X.volume;break;case f.pan:A=X.pan;break;case f.expression:A=X.expression;break;case f.chorusDepth:A=X.chorus;break;case f.reverbDepth:A=X.reverb;break}else switch(e.index){case Ie.noController:A=X.none;break;case Ie.noteOnKeyNum:A=X.keyNum;break;case Ie.noteOnVelocity:A=X.velocity;break;case Ie.pitchWheel:A=X.pitchWheel;break;case Ie.pitchWheelRange:A=X.pitchWheelRange;break;case Ie.polyPressure:A=X.polyPressure;break;case Ie.channelPressure:A=X.channelPressure}if(A!==void 0)return new os(A,e.curveType,e.isBipolar,e.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 e,A=!1;switch(this.source){default:case X.modLfo:case X.vibratoLfo:case X.coarseTune:case X.fineTune:case X.modEnv:return;case X.keyNum:e=Ie.noteOnKeyNum;break;case X.none:e=Ie.noController;break;case X.modulationWheel:e=f.modulationWheel,A=!0;break;case X.pan:e=f.pan,A=!0;break;case X.reverb:e=f.reverbDepth,A=!0;break;case X.chorus:e=f.chorusDepth,A=!0;break;case X.expression:e=f.expression,A=!0;break;case X.volume:e=f.mainVolume,A=!0;break;case X.velocity:e=Ie.noteOnVelocity;break;case X.polyPressure:e=Ie.polyPressure;break;case X.channelPressure:e=Ie.channelPressure;break;case X.pitchWheel:e=Ie.pitchWheel;break;case X.pitchWheelRange:e=Ie.pitchWheelRange;break}if(e!==void 0)return new st(e,this.transform,A,this.bipolar,this.invert)}},fn=new ue(219,0,c.reverbEffectsSend,1e3,0),Qn=new ue(221,0,c.chorusEffectsSend,1e3,0);new ue(129,0,c.vibLfoToPitch,0,0);new ue(13,0,c.vibLfoToPitch,0,0);var $a=new Set([c.sampleModes,c.initialAttenuation,c.keyRange,c.velRange,c.sampleID,c.fineTune,c.coarseTune,c.startAddrsOffset,c.startAddrsCoarseOffset,c.endAddrOffset,c.endAddrsCoarseOffset,c.startloopAddrsOffset,c.startloopAddrsCoarseOffset,c.endloopAddrsOffset,c.endloopAddrsCoarseOffset,c.overridingRootKey,c.exclusiveClass]),qt=class Qt{source;control;destination;scale;transform;constructor(e=new At,A=new At,s,n,a){this.source=e,this.control=A,this.destination=s,this.transform=n,this.scale=a}get isStaticParameter(){return this.source.source===X.none&&this.control.source===X.none}get shortScale(){return this.scale>>16}get transformName(){return Object.keys(le).find(e=>le[e]===this.transform)??this.transform.toString()}get destinationName(){return Object.keys(N).find(e=>N[e]===this.destination)??this.destination.toString()}static read(e){let A=V(e,2),s=V(e,2),n=V(e,2),a=V(e,2),r=V(e,4)|0,i=a&15,o=new At(s,a>>4&15,pt(a,8),pt(a,9));return new Qt(new At(A,a>>10&15,pt(a,14),pt(a,15)),o,n,i,r)}static fromSFModulator(e,A){let s=l=>{h.warn(`Failed converting SF modulator into DLS: + ${e.toString()} +(${l})`)};if(e.transformType!==0){s("Absolute transform type is not supported");return}if(ke.isIdentical(e,Qn,!0)||ke.isIdentical(e,fn,!0))return;let n=At.fromSFSource(e.primarySource);if(!n){s("Invalid primary source");return}let a=At.fromSFSource(e.secondarySource);if(!a){s("Invalid secondary source");return}let r=Qt.fromSFDestination(e.destination,e.transformAmount);if(r===void 0){s("Invalid destination");return}let i=e.transformAmount,o;if(typeof r=="number")o=r;else if(o=r.destination,i=r.amount,r.source!==X.none){if(a.source!==X.none&&n.source!==X.none){s("Articulation generators with secondary source are not supported");return}n.source!==X.none&&(a=n),n=new At(r.source,le.linear,r.isBipolar)}let g=new Qt(n,a,o,0,i<<16);A.connectionBlocks.push(g)}static copyFrom(e){return new Qt(At.copyFrom(e.source),At.copyFrom(e.control),e.destination,e.transform,e.scale)}static fromSFGenerator(e,A){if($a.has(e.type))return;let s=o=>{h.warn(`Failed converting SF2 generator into DLS: + ${e.toString()} +(${o})`)},n=Qt.fromSFDestination(e.type,e.value);if(n===void 0){s("Invalid type");return}let a=new At,r,i=e.value;typeof n=="number"?r=n:(r=n.destination,i=n.amount,a.source=n.source,a.bipolar=n.isBipolar),A.connectionBlocks.push(new Qt(a,new At,r,0,i<<16))}static fromSFDestination(e,A){switch(e){default:return;case c.initialAttenuation:return{destination:N.gain,amount:-A,isBipolar:!1,source:X.none};case c.fineTune:return N.pitch;case c.pan:return N.pan;case c.keyNum:return N.keyNum;case c.reverbEffectsSend:return N.reverbSend;case c.chorusEffectsSend:return N.chorusSend;case c.freqModLFO:return N.modLfoFreq;case c.delayModLFO:return N.modLfoDelay;case c.delayVibLFO:return N.vibLfoDelay;case c.freqVibLFO:return N.vibLfoFreq;case c.delayVolEnv:return N.volEnvDelay;case c.attackVolEnv:return N.volEnvAttack;case c.holdVolEnv:return N.volEnvHold;case c.decayVolEnv:return N.volEnvDecay;case c.sustainVolEnv:return{destination:N.volEnvSustain,amount:1e3-A,isBipolar:!1,source:X.none};case c.releaseVolEnv:return N.volEnvRelease;case c.delayModEnv:return N.modEnvDelay;case c.attackModEnv:return N.modEnvAttack;case c.holdModEnv:return N.modEnvHold;case c.decayModEnv:return N.modEnvDecay;case c.sustainModEnv:return{destination:N.modEnvSustain,amount:1e3-A,isBipolar:!1,source:X.none};case c.releaseModEnv:return N.modEnvRelease;case c.initialFilterFc:return N.filterCutoff;case c.initialFilterQ:return N.filterQ;case c.modEnvToFilterFc:return{source:X.modEnv,destination:N.filterCutoff,amount:A,isBipolar:!1};case c.modEnvToPitch:return{source:X.modEnv,destination:N.pitch,amount:A,isBipolar:!1};case c.modLfoToFilterFc:return{source:X.modLfo,destination:N.filterCutoff,amount:A,isBipolar:!0};case c.modLfoToVolume:return{source:X.modLfo,destination:N.gain,amount:A,isBipolar:!0};case c.modLfoToPitch:return{source:X.modLfo,destination:N.pitch,amount:A,isBipolar:!0};case c.vibLfoToPitch:return{source:X.vibratoLfo,destination:N.pitch,amount:A,isBipolar:!0};case c.keyNumToVolEnvHold:return{source:X.keyNum,destination:N.volEnvHold,amount:A,isBipolar:!0};case c.keyNumToVolEnvDecay:return{source:X.keyNum,destination:N.volEnvDecay,amount:A,isBipolar:!0};case c.keyNumToModEnvHold:return{source:X.keyNum,destination:N.modEnvHold,amount:A,isBipolar:!0};case c.keyNumToModEnvDecay:return{source:X.keyNum,destination:N.modEnvDecay,amount:A,isBipolar:!0};case c.scaleTuning:return{source:X.keyNum,destination:N.pitch,amount:A*128,isBipolar:!1}}}toString(){return`Source: ${this.source.toString()}, +Control: ${this.control.toString()}, +Scale: ${this.scale} >> 16 = ${this.shortScale}, +Output transform: ${this.transformName} +Destination: ${this.destinationName}`}write(){let e=new ee(12);return Ae(e,this.source.source),Ae(e,this.control.source),Ae(e,this.destination),Ae(e,this.transform|this.control.toTransformFlag()<<4|this.source.toTransformFlag()<<10),ge(e,this.scale),e}toSFGenerator(e){let A=this.destination,s=this.shortScale;switch(A){default:h.info(`%cFailed converting DLS articulator into SF generator: %c${this.toString()}%c +(invalid destination)`,d.warn,d.value,d.unrecognized);return;case N.pan:e.setGenerator(c.pan,s);break;case N.gain:e.addToGenerator(c.initialAttenuation,-s/.4);break;case N.filterCutoff:e.setGenerator(c.initialFilterFc,s);break;case N.filterQ:e.setGenerator(c.initialFilterQ,s);break;case N.modLfoFreq:e.setGenerator(c.freqModLFO,s);break;case N.modLfoDelay:e.setGenerator(c.delayModLFO,s);break;case N.vibLfoFreq:e.setGenerator(c.freqVibLFO,s);break;case N.vibLfoDelay:e.setGenerator(c.delayVibLFO,s);break;case N.volEnvDelay:e.setGenerator(c.delayVolEnv,s);break;case N.volEnvAttack:e.setGenerator(c.attackVolEnv,s);break;case N.volEnvHold:e.setGenerator(c.holdVolEnv,s);break;case N.volEnvDecay:e.setGenerator(c.decayVolEnv,s);break;case N.volEnvRelease:e.setGenerator(c.releaseVolEnv,s);break;case N.volEnvSustain:e.setGenerator(c.sustainVolEnv,1e3-s);break;case N.modEnvDelay:e.setGenerator(c.delayModEnv,s);break;case N.modEnvAttack:e.setGenerator(c.attackModEnv,s);break;case N.modEnvHold:e.setGenerator(c.holdModEnv,s);break;case N.modEnvDecay:e.setGenerator(c.decayModEnv,s);break;case N.modEnvRelease:e.setGenerator(c.releaseModEnv,s);break;case N.modEnvSustain:e.setGenerator(c.sustainModEnv,1e3-s);break;case N.reverbSend:e.setGenerator(c.reverbEffectsSend,s);break;case N.chorusSend:e.setGenerator(c.chorusEffectsSend,s);break;case N.pitch:e.fineTuning+=s;break}}toSFModulator(e){let A=this.shortScale,s,n,a=new st,r=this.toCombinedSFDestination();if(r){s=r;let o=this.control.toSFSource();if(!o){this.failedConversion("Invalid control");return}n=o}else{let o=this.toSFDestination();if(!o){this.failedConversion("Invalid destination");return}typeof o=="object"?(A=o.newAmount,s=o.gen):s=o;let g=this.source.toSFSource();if(!g){this.failedConversion("Invalid source");return}n=g;let l=this.control.toSFSource();if(!l){this.failedConversion("Invalid control");return}a=l}this.transform!==le.linear&&n.curveType===le.linear&&(n.curveType=this.transform),s===c.initialAttenuation&&((this.source.source===X.velocity||this.source.source===X.volume||this.source.source===X.expression)&&(n.isNegative=!0),A=Math.min(960,Math.max(0,A)));let i=new ke(n,a,s,A,0);e.addModulators(i)}toCombinedSFDestination(){let e=this.source.source,A=this.destination;return e===X.vibratoLfo&&A===N.pitch?c.vibLfoToPitch:e===X.modLfo&&A===N.pitch?c.modLfoToPitch:e===X.modLfo&&A===N.filterCutoff?c.modLfoToFilterFc:e===X.modLfo&&A===N.gain?c.modLfoToVolume:e===X.modEnv&&A===N.filterCutoff?c.modEnvToFilterFc:e===X.modEnv&&A===N.pitch?c.modEnvToPitch:void 0}failedConversion(e){h.info(`%cFailed converting DLS articulator into SF2: + %c${this.toString()}%c +(${e})`,d.warn,d.value,d.unrecognized)}toSFDestination(){let e=this.shortScale;switch(this.destination){default:case N.none:return;case N.pan:return c.pan;case N.gain:return{gen:c.initialAttenuation,newAmount:-e};case N.pitch:return c.fineTune;case N.keyNum:return c.overridingRootKey;case N.volEnvDelay:return c.delayVolEnv;case N.volEnvAttack:return c.attackVolEnv;case N.volEnvHold:return c.holdVolEnv;case N.volEnvDecay:return c.decayVolEnv;case N.volEnvSustain:return{gen:c.sustainVolEnv,newAmount:1e3-e};case N.volEnvRelease:return c.releaseVolEnv;case N.modEnvDelay:return c.delayModEnv;case N.modEnvAttack:return c.attackModEnv;case N.modEnvHold:return c.holdModEnv;case N.modEnvDecay:return c.decayModEnv;case N.modEnvSustain:return{gen:c.sustainModEnv,newAmount:1e3-e};case N.modEnvRelease:return c.releaseModEnv;case N.filterCutoff:return c.initialFilterFc;case N.filterQ:return c.initialFilterQ;case N.chorusSend:return c.chorusEffectsSend;case N.reverbSend:return c.reverbEffectsSend;case N.modLfoFreq:return c.freqModLFO;case N.modLfoDelay:return c.delayModLFO;case N.vibLfoFreq:return c.freqVibLFO;case N.vibLfoDelay:return c.delayVibLFO}}},un=class extends Ht{connectionBlocks=new Array;mode="dls2";get length(){return this.connectionBlocks.length}copyFrom(t){this.mode=t.mode;for(let e of t.connectionBlocks)this.connectionBlocks.push(qt.copyFrom(e))}fromSFZone(t){this.mode="dls2";let e=new zt;e.copyFrom(t);for(let A of e.generators){let s;switch(A.type){default:continue;case c.keyNumToVolEnvDecay:s=c.decayVolEnv;break;case c.keyNumToVolEnvHold:s=c.holdVolEnv;break;case c.keyNumToModEnvDecay:s=c.decayModEnv;break;case c.keyNumToModEnvHold:s=c.holdModEnv}let n=e.getGenerator(s,void 0),a=A.value*-128;if(n===void 0)continue;let r=n-60/128*a;e.setGenerator(A.type,a,!1),e.setGenerator(s,r,!1)}for(let A of e.generators)qt.fromSFGenerator(A,this);for(let A of e.modulators)qt.fromSFModulator(A,this)}read(t){let e=U.findListType(t,"lart"),A=U.findListType(t,"lar2");if(e)for(this.mode="dls1";e.data.currentIndexs.write()),A=U.getParts(this.mode==="dls2"?"art2":"art1",[t,...e]);return U.getParts(this.mode==="dls2"?"lar2":"lart",A,!0)}toSFZone(t){let e=(A,s,n,a)=>{let r=A/-128;if(t.setGenerator(s,r),r<=120){let i=Math.round(.46875*A),o=this.connectionBlocks.find(g=>g.isStaticParameter&&g.destination===a);o&&t.setGenerator(n,i+o.shortScale)}};for(let A of this.connectionBlocks){let s=A.shortScale,n=A.source.source,a=A.control.source,r=A.destination;if(A.isStaticParameter){A.toSFGenerator(t);continue}if(a===X.none)if(n===X.keyNum){if(r===N.pitch){t.setGenerator(c.scaleTuning,s/128);continue}if(r===N.modEnvHold||r===N.modEnvDecay||r===N.volEnvHold||r===N.volEnvDecay)continue}else{let i=A.toCombinedSFDestination();if(i){t.setGenerator(i,s);continue}}A.toSFModulator(t)}for(let A of this.connectionBlocks){if(A.source.source!==X.keyNum)continue;let s=A.shortScale;switch(A.destination){default:case N.volEnvHold:e(s,c.keyNumToVolEnvHold,c.holdVolEnv,N.volEnvHold);break;case N.volEnvDecay:e(s,c.keyNumToVolEnvDecay,c.decayVolEnv,N.volEnvDecay);break;case N.modEnvHold:e(s,c.keyNumToModEnvHold,c.holdModEnv,N.modEnvHold);break;case N.modEnvDecay:e(s,c.keyNumToModEnvDecay,c.decayModEnv,N.modEnvDecay);break}}if(this.mode==="dls1"){t.setGenerator(c.delayVibLFO,t.getGenerator(c.delayModLFO,null)),t.setGenerator(c.freqVibLFO,t.getGenerator(c.freqModLFO,null)),t.setGenerator(c.vibLfoToPitch,t.getGenerator(c.modLfoToPitch,null)),t.setGenerator(c.modLfoToPitch,null);for(let A of t.modulators)A.destination===c.modLfoToPitch&&(A.destination=c.vibLfoToPitch)}}},JA=class lA{channel=1;tableIndex;fusOptions=0;phaseGroup=0;constructor(e){this.tableIndex=e}static copyFrom(e){let A=new lA(e.tableIndex);return A.channel=e.channel,A.phaseGroup=e.phaseGroup,A.fusOptions=e.fusOptions,A}static read(e){let A=V(e.data,2),s=V(e.data,2),n=V(e.data,4),a=new lA(V(e.data,4));return a.channel=n,a.fusOptions=A,a.phaseGroup=s,a}static fromSFZone(e,A){let s=e.indexOf(A.sample);if(s===-1)throw new Error(`Wave link error: Sample ${A.sample.name} does not exist in the sample list.`);let n=new lA(s);switch(A.sample.sampleType){default:case Fe.leftSample:case Fe.monoSample:n.channel=Math.trunc(1);break;case Fe.rightSample:n.channel=2}return n}write(){let e=new ee(12);return Ae(e,this.fusOptions),Ae(e,this.phaseGroup),ge(e,this.channel),ge(e,this.tableIndex),U.write("wlnk",e)}},CA=class Lt extends Ht{articulation=new un;keyRange={min:0,max:127};velRange={min:0,max:127};keyGroup=0;fusOptions=0;usLayer=0;waveSample;waveLink;constructor(e,A){super(),this.waveSample=A,this.waveLink=e}static copyFrom(e){let A=new Lt(JA.copyFrom(e.waveLink),Ut.copyFrom(e.waveSample));return A.keyGroup=e.keyGroup,A.keyRange={...e.keyRange},A.velRange={...e.velRange},A.usLayer=e.usLayer,A.fusOptions=e.fusOptions,A.articulation.copyFrom(e.articulation),A}static read(e,A){let s=this.verifyAndReadList(A,"rgn ","rgn2"),n=s.find(m=>m.header==="wsmp"),a=n?Ut.read(n):void 0,r=s.find(m=>m.header==="wlnk");if(!r){h.warn("Invalid DLS region: missing 'wlnk' chunk! Discarding...");return}let i=JA.read(r),o=s.find(m=>m.header==="rgnh");if(!o){h.warn("Invalid DLS region: missing 'rgnh' chunk! Discarding...");return}let g=e[i.tableIndex];g||Lt.parsingError(`Invalid sample index: ${i.tableIndex}. Samples available: ${e.length}`),a??=g.waveSample;let l=new Lt(i,a),C=V(o.data,2),B=V(o.data,2),I=V(o.data,2),E=V(o.data,2);return I===0&&E===0&&(E=127,I=0),l.keyRange.max=B,l.keyRange.min=C,l.velRange.max=E,l.velRange.min=I,l.fusOptions=V(o.data,2),l.keyGroup=V(o.data,2),o.data.length-o.data.currentIndex>=2&&(l.usLayer=V(o.data,2)),l.articulation.read(s),l}static fromSFZone(e,A){let s=Ut.fromSFZone(e),n=new Lt(JA.fromSFZone(A,e),s);return n.keyRange.min=Math.max(e.keyRange.min,0),n.keyRange.max=e.keyRange.max,n.velRange.min=Math.max(e.velRange.min,0),n.velRange.max=e.velRange.max,n.keyGroup=e.getGenerator(c.exclusiveClass,0),n.articulation.fromSFZone(e),n}write(){let e=[this.writeHeader(),this.waveSample.write(),this.waveLink.write(),...this.articulation.write()];return U.getParts("rgn2",e,!0)}toSFZone(e,A){let s=A[this.waveLink.tableIndex];s||Lt.parsingError(`Invalid sample index: ${this.waveLink.tableIndex}`);let n=e.createZone(s);return n.keyRange=this.keyRange,n.velRange=this.velRange,this.keyRange.max===127&&this.keyRange.min===0&&(n.keyRange.min=-1),this.velRange.max===127&&this.velRange.min===0&&(n.velRange.min=-1),this.keyGroup!==0&&n.setGenerator(c.exclusiveClass,this.keyGroup),this.waveSample.toSFZone(n,s),this.articulation.toSFZone(n),n.generators=n.generators.filter(a=>a.value!==Ve[a.type].def),n}writeHeader(){let e=new ee(14);return Ae(e,Math.max(this.keyRange.min,0)),Ae(e,this.keyRange.max),Ae(e,Math.max(this.velRange.min,0)),Ae(e,this.velRange.max),Ae(e,this.fusOptions),Ae(e,this.keyGroup),Ae(e,this.usLayer),U.write("rgnh",e)}},KA=class BA extends Ht{articulation=new un;regions=new Array;name="Unnamed";bankLSB=0;bankMSB=0;isGMGSDrum=!1;program=0;static copyFrom(e){let A=new BA;A.name=e.name,A.isGMGSDrum=e.isGMGSDrum,A.bankMSB=e.bankMSB,A.bankLSB=e.bankLSB,A.program=e.program,A.articulation.copyFrom(e.articulation);for(let s of e.regions)A.regions.push(CA.copyFrom(s));return A}static read(e,A){let s=this.verifyAndReadList(A,"ins "),n=s.find(C=>C.header==="insh");if(!n)throw h.groupEnd(),new Error("No instrument header!");let a="",r=U.findListType(s,"INFO");if(r){let C=U.read(r.data);for(;C.header!=="INAM";)C=U.read(r.data);a=Ee(C.data,C.data.length).trim()}a.length===0&&(a="Unnamed Instrument");let i=new BA;i.name=a;let o=V(n.data,4),g=V(n.data,4);i.program=V(n.data,4)&127,i.bankMSB=g>>>8&127,i.bankLSB=g&127,i.isGMGSDrum=g>>>31>0,h.groupCollapsed(`%cParsing %c"${a}"%c...`,d.info,d.recognized,d.info);let l=U.findListType(s,"lrgn");if(!l)throw h.groupEnd(),new Error("No region list!");i.articulation.read(s);for(let C=0;Cn.write());e.push(...U.getParts("lrgn",A,!0)),this.articulation.length>0&&e.push(...this.articulation.write());let s=U.write("INAM",$e(this.name,!0));return e.push(U.write("INFO",s,!1,!0)),h.groupEnd(),U.writeParts("ins ",e,!0)}toSFPreset(e){let A=new _t(e);A.name=this.name,A.bankMSB=this.bankMSB,A.bankLSB=this.bankLSB,A.isGMGSDrum=this.isGMGSDrum,A.program=this.program;let s=new Wt;s.name=this.name,A.createZone(s),this.articulation.toSFZone(s.globalZone);for(let n of this.regions)n.toSFZone(s,e.samples);s.globalize(),s.globalZone.modulators.some(n=>n.destination===c.reverbEffectsSend)||s.globalZone.addModulators(ke.copyFrom(fn)),s.globalZone.modulators.some(n=>n.destination===c.chorusEffectsSend)||s.globalZone.addModulators(ke.copyFrom(Qn)),s.globalZone.generators=s.globalZone.generators.filter(n=>n.value!==Ve[n.type].def),e.addPresets(A),e.addInstruments(s)}writeHeader(){let e=new ee(12);ge(e,this.regions.length);let A=(this.bankMSB&127)<<8|this.bankLSB&127;return this.isGMGSDrum&&(A|=1<<31),ge(e,A),ge(e,this.program&127),U.write("insh",e)}},gs={software:"SpessaSynth"},mn=class Is extends Ht{samples=new Array;instruments=new Array;soundBankInfo={name:"Unnamed DLS sound bank",creationDate:new Date,software:"SpessaSynth",soundEngine:"DLS Level 2.2",product:"SpessaSynth DLS",version:{major:2,minor:4}};static read(e){if(!e)throw new Error("No data provided!");let A=new ee(e);h.group("%cParsing DLS file...",d.info);let s=U.read(A,!1);this.verifyHeader(s,"RIFF"),this.verifyText(Ee(A,4).toLowerCase(),"dls ");let n=[];for(;A.currentIndexE.header==="colh");if(!i)return this.parsingError("No colh chunk!"),5;let o=V(i.data,4);h.info(`%cInstruments amount: %c${o}`,d.info,d.recognized);let g=U.findListType(n,"wvpl");if(!g)return this.parsingError("No wvpl chunk!"),5;let l=this.verifyAndReadList(g,"wvpl");for(let E of l)a.samples.push(Ls.read(E));let C=U.findListType(n,"lins");if(!C)return this.parsingError("No lins chunk!"),5;let B=this.verifyAndReadList(C,"lins");h.groupCollapsed("%cLoading instruments...",d.info),B.length!==o&&h.warn(`Colh reported invalid amount of instruments. Detected ${B.length}, expected ${o}`);for(let E of B)a.instruments.push(KA.read(a.samples,E));h.groupEnd();let I=n.find(E=>E.header==="pgal");if(I){h.info("%cFound the instrument aliasing chunk!",d.recognized);let E=I.data;(E[0]!==0||E[1]!==1||E[2]!==2||E[3]!==3)&&(E.currentIndex+=4);let m=a.instruments.find(y=>Se.isXGDrum(y.bankMSB)||y.isGMGSDrum);if(!m)return h.warn("MobileBAE aliasing chunk without a drum preset. Aborting!"),a;let k=E.slice(E.currentIndex,E.currentIndex+128);E.currentIndex+=128;for(let y=0;y<128;y++){let b=k[y];if(b===y)continue;let R=m.regions.find(S=>S.keyRange.max===b&&S.keyRange.min===b);if(!R){h.warn(`Invalid drum alias ${y} to ${b}: region does not exist.`);continue}let M=CA.copyFrom(R);M.keyRange.max=y,M.keyRange.min=y,m.regions.push(M)}for(E.currentIndex+=4;E.currentIndex>7&127,M=E[E.currentIndex++],S=E[E.currentIndex++];S!==0&&h.warn(`Invalid alias byte. Expected 0, got ${S}`);let Q=V(E,2),p=Q&127,D=Q>>7&127,q=E[E.currentIndex++];S=E[E.currentIndex++],S!==0&&h.warn(`Invalid alias header. Expected 0, got ${S}`);let K=a.instruments.find(Y=>Y.bankLSB===p&&Y.bankMSB===D&&Y.program===q&&!Y.isGMGSDrum);if(!K){h.warn(`Invalid alias. Missing instrument: ${p}:${D}:${q}`);continue}let O=KA.copyFrom(K);O.bankMSB=R,O.bankLSB=b,O.program=M,a.instruments.push(O)}}return h.info(`%cParsing finished! %c"${a.soundBankInfo.name||"UNNAMED"}"%c has %c${a.instruments.length}%c instruments and %c${a.samples.length}%c samples.`,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized,d.info),h.groupEnd(),a}static fromSF(e,A){h.groupCollapsed("%cSaving SF2 to DLS level 2...",d.info);let s=new Is;s.soundBankInfo={...e.soundBankInfo};for(let n=0;ny.write()),!0);h.info("%cSuccess!",d.recognized),h.groupEnd(),h.groupCollapsed("%cWriting WAVE samples...",d.info);let r=0,i=[],o=[],g=0;for(let y of this.samples){let b=y.write();A.progressFunction?.(g/this.samples.length),h.info(`%cWrote sample %c${g}. ${y.name}%c of %c${this.samples.length}.`,d.info,d.recognized,d.info,d.recognized),i.push(r),r+=b.reduce((R,M)=>R+M.length,0),o.push(...b),g++}let l=U.getParts("wvpl",o,!0);h.info("%cSucceeded!",d.recognized);let C=new ee(8+4*i.length);ge(C,8),ge(C,i.length);for(let y of i)ge(C,y);let B=U.write("ptbl",C);this.soundBankInfo.software=A.software;let I=[],E=this.soundBankInfo,m=(y,b)=>{b&&I.push(...U.getParts(y,[$e(b,!0)]))};m("INAM",E.name),m("ICMT",E.comment),m("ICOP",E.copyright),m("ICRD",Bs(E.creationDate)),m("IENG",E.engineer),m("IPRD",E.product),m("ISFT",A.software),m("ISBJ",E.subject),h.info("%cCombining everything...");let k=U.writeParts("RIFF",[$e("DLS "),n,...a,B,...l,...U.getParts("INFO",I,!0)]);return h.info("%cSaved successfully!",d.recognized),h.groupEnd(),k.buffer}toSF(){h.group("%cConverting DLS to SF2...",d.info);let e=new pn;e.soundBankInfo.version.minor=4,e.soundBankInfo.version.major=2,e.soundBankInfo={...this.soundBankInfo};for(let A of this.samples)A.toSFSample(e);for(let A of this.instruments)A.toSFPreset(e);return e.flush(),h.info("%cConversion complete!",d.recognized),h.groupEnd(),e}},pn=class EA{static isSF3DecoderReady=FA.isInitialized;soundBankInfo={name:"Unnamed",creationDate:new Date,software:"SpessaSynth",soundEngine:"E-mu 10K2",version:{major:2,minor:4}};presets=[];samples=[];instruments=[];defaultModulators=Cn.map(ke.copyFrom.bind(ke));customDefaultModulators=!1;_isXGBank=!1;get isXGBank(){return this._isXGBank}static mergeSoundBanks(...e){let A=e.shift();if(!A)throw new Error("No sound banks provided!");let s=A.presets;for(;e.length>0;){let a=e?.shift()?.presets;if(a)for(let r of a)s.some(i=>r.matches(i))||s.push(r)}let n=new EA;return n.addCompletePresets(s),n.soundBankInfo={...A.soundBankInfo},n}static getSampleSoundBankFile(){let e=new EA,A=new Float32Array(128);for(let r=0;r<128;r++)A[r]=r/128*2-1;let s=new Ya;s.name="Saw",s.originalKey=65,s.pitchCorrection=20,s.loopEnd=127,s.setAudioData(A,44100),e.addSamples(s);let n=new Wt;n.name="Saw Wave",n.globalZone.addGenerators(new Ge(c.initialAttenuation,375),new Ge(c.releaseVolEnv,-1e3),new Ge(c.sampleModes,1)),n.createZone(s),n.createZone(s).setGenerator(c.fineTune,-9),e.addInstruments(n);let a=new _t(e);return a.name="Saw Wave",a.createZone(n),e.addPresets(a),e.soundBankInfo.name="Dummy",e.flush(),e.writeSF2()}static copyFrom(e){let A=new EA;for(let s of e.presets)A.clonePreset(s);return A.soundBankInfo={...e.soundBankInfo},A}addCompletePresets(e){this.addPresets(...e);let A=[];for(let n of e)for(let a of n.zones)a.instrument&&!A.includes(a.instrument)&&A.push(a.instrument);this.addInstruments(...A);let s=[];for(let n of A)for(let a of n.zones)a.sample&&!s.includes(a.sample)&&s.push(a.sample);this.addSamples(...s)}async setSampleFormat(e){let A=0,s=e.format,n=e.progressFunction;for(let a of this.samples){switch(s){default:case"pcm":a.setAudioData(a.getAudioData(),a.sampleRate);break;case"compressed":{let r=e.compressionFunction;if(!r)throw new Error(`No compression function supplied but '${s}' was requested.`);await a.compressSample(r)}}A++,n?.(A/this.samples.length),h.info(`%cEncoded sample %c${A}. ${a.name}%c of %c${this.samples.length}%c. Compressed: %c${a.isCompressed}%c.`,d.info,d.recognized,d.info,d.recognized,d.info,a.isCompressed?d.recognized:d.unrecognized,d.info)}switch(s){default:case"pcm":this.soundBankInfo.version.major=2,this.soundBankInfo.version.minor=4;break;case"compressed":this.soundBankInfo.version.major=3,this.soundBankInfo.version.minor=0}}writeDLS(e=gs){let A=e.progressFunction;return mn.fromSF(this,A?s=>A(s/2):void 0).write({...e,progressFunction:A?s=>A(.5+s/2):void 0})}writeSF2(e=dn){return Za(this,e)}addPresets(...e){this.presets.push(...e)}addInstruments(...e){this.instruments.push(...e)}addSamples(...e){this.samples.push(...e)}cloneSample(e){let A=this.samples.find(n=>n.name===e.name);if(A)return A;let s=new MA(e.name,e.sampleRate,e.originalKey,e.pitchCorrection,e.sampleType,e.loopStart,e.loopEnd);if(e.isCompressed?s.setCompressedData(e.getRawData(!0)):s.setAudioData(e.getAudioData(),e.sampleRate),this.addSamples(s),e.linkedSample){let n=this.cloneSample(e.linkedSample);n.linkedSample||s.setLinkedSample(n,s.sampleType)}return s}cloneInstrument(e){let A=this.instruments.find(n=>n.name===e.name);if(A)return A;let s=new Wt;s.name=e.name,s.globalZone.copyFrom(e.globalZone);for(let n of e.zones)s.createZone(this.cloneSample(n.sample)).copyFrom(n);return this.addInstruments(s),s}clonePreset(e){let A=this.presets.find(n=>n.name===e.name);if(A)return A;let s=new _t(this);s.name=e.name,s.bankMSB=e.bankMSB,s.bankLSB=e.bankLSB,s.isGMGSDrum=e.isGMGSDrum,s.program=e.program,s.library=e.library,s.genre=e.genre,s.morphology=e.morphology,s.globalZone.copyFrom(e.globalZone);for(let n of e.zones)s.createZone(this.cloneInstrument(n.instrument)).copyFrom(n);return this.addPresets(s),s}flush(){this.presets.sort(ze.compare.bind(ze)),this.parseInternal()}trim(e){let A=(s,n)=>{let a=0;for(let r=0;r=o.min&&C<=o.max&&[...B].some(I=>I>=g.min&&I<=g.max)){l=!0;break}l||(h.info(`%c${i.sample.name}%c removed from %c${s.name}%c.`,d.recognized,d.info,d.recognized,d.info),s.deleteZone(r)&&(a++,r--,h.info(`%c${i.sample.name}%c deleted`,d.recognized,d.info)),i.sample.useCount<1&&this.deleteSample(i.sample))}return a};h.groupCollapsed("%cTrimming sound bank...",d.info),h.info("Combinations to trim for:",e);for(let s=0;s=g.min&&B<=g.max&&[...I].some(E=>E>=l.min&&E<=l.max)){C=!0;let E=A(o.instrument,a);h.info(`%cTrimmed off %c${E}%c instrument zones from %c${o.instrument.name}`,d.info,d.recognized,d.info,d.recognized);break}C||(r++,n.deleteZone(i),o.instrument.useCount<1&&this.deleteInstrument(o.instrument),i--)}h.info(`%cTrimmed off %c${r}%c preset zones from %c${n.name}`,d.info,d.recognized,d.info,d.recognized),h.groupEnd()}}this.removeUnusedElements(),h.info("%cSound bank modified!",d.recognized),h.groupEnd()}removeUnusedElements(){this.instruments=this.instruments.filter(e=>{e.deleteUnusedZones();let A=e.useCount<1;return A&&e.delete(),!A}),this.samples=this.samples.filter(e=>{let A=e.useCount<1;return A&&e.unlinkSample(),!A})}deleteInstrument(e){e.delete(),this.instruments.splice(this.instruments.indexOf(e),1)}deletePreset(e){e.delete(),this.presets.splice(this.presets.indexOf(e),1)}deleteSample(e){e.unlinkSample(),this.samples.splice(this.samples.indexOf(e),1)}getPreset(e,A){return ze.selectPatch(this.presets,e,A)}destroySoundBank(){this.presets.length=0,this.instruments.length=0,this.samples.length=0}parsingError(e){throw new Error(`SF parsing error: ${e} The file may be corrupted.`)}parseInternal(){this._isXGBank=!1;let e=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 A of this.presets)if(Se.isXGDrum(A.bankMSB)&&(this._isXGBank=!0,!e.has(A.program))){this._isXGBank=!1,h.info(`%cThis bank is not valid XG. Preset %c${A.toString()}%c is not a valid XG drum. XG mode will use presets on bank 128.`,d.info,d.value,d.info);break}}printInfo(){for(let[e,A]of Object.entries(this.soundBankInfo))if(typeof A=="object"&&"major"in A){let s=A;h.info(`%c${e}: %c"${s.major}.${s.minor}"`,d.info,d.recognized)}else h.info(`%c${e}: %c${A.toLocaleString()}`,d.info,d.recognized)}},ja=class extends Ge{constructor(t){let e=t.currentIndex,A=t[e+1]<<8|t[e],s=ls(t[e+2],t[e+3]);t.currentIndex+=4,super(A,s,!1)}};function Ns(t){let e=[];for(;t.data.length>t.data.currentIndex;)e.push(new ja(t.data));return e.pop(),e}function er(t,e,A,s,n){let a=t.gen,r=t.mod,i=0,o=0;for(let g of n)for(let l=0;ly.type===c.instrument)?g.createSoundFontZone(k,I,s):(g.globalZone.addGenerators(...I),g.globalZone.addModulators(...k))}}var tr=class extends _t{zoneStartIndex;zonesCount=0;constructor(t,e){super(e),this.name=Ee(t.data,20),this.program=V(t.data,2);let A=V(t.data,2);this.bankMSB=A&127,this.isGMGSDrum=(A&128)>0,this.bankLSB=A>>8,this.zoneStartIndex=V(t.data,2),this.library=V(t.data,4),this.genre=V(t.data,4),this.morphology=V(t.data,4)}createSoundFontZone(t,e,A){let s=e.find(r=>r.type===c.instrument),n;if(s)n=A[s.value];else throw new Error("No instrument ID found in preset zone.");if(!n)throw new Error(`Invalid instrument ID: ${s.value}, available instruments: ${A.length}`);let a=new En(this,n);return a.addGenerators(...e),a.addModulators(...t),this.zones.push(a),a}};function Ps(t,e){let A=[];for(;t.data.length>t.data.currentIndex;){let s=new tr(t,e);if(A.length>0){let n=A[A.length-1];n.zonesCount=s.zoneStartIndex-n.zoneStartIndex}A.push(s)}return A.pop(),A}var Ar=class extends Wt{zoneStartIndex;zonesCount=0;constructor(t){super(),this.name=Ee(t.data,20),this.zoneStartIndex=V(t.data,2)}createSoundFontZone(t,e,A){let s=e.find(r=>r.type===c.sampleID),n;if(s)n=A[s.value];else throw new Error("No sample ID found in instrument zone.");if(!n)throw new Error(`Invalid sample ID: ${s.value}, available samples: ${A.length}`);let a=new Bn(this,n);return a.addGenerators(...e),a.addModulators(...t),this.zones.push(a),a}};function Ts(t){let e=[];for(;t.data.length>t.data.currentIndex;){let A=new Ar(t);if(e.length>0){let s=e[e.length-1];s.zonesCount=A.zoneStartIndex-s.zoneStartIndex}e.push(A)}return e.pop(),e}function VA(t){let e=[];for(;t.data.length>t.data.currentIndex;){let A=t.data,s=V(A,2),n=V(A,2),a=ls(A[A.currentIndex++],A[A.currentIndex++]),r=V(A,2),i=V(A,2);e.push(new ue(s,r,n,a,i))}return e.pop(),e}function sr(t,e,A,s,n){let a=t.gen,r=t.mod,i=0,o=0;for(let g of n)for(let l=0;ly.type===c.sampleID)?g.createSoundFontZone(k,I,s):(g.globalZone.addGenerators(...I),g.globalZone.addModulators(...k))}}function IA(t){let e=[],A=[];for(;t.data.length>t.data.currentIndex;)A.push(V(t.data,2)),e.push(V(t.data,2));return{mod:e,gen:A}}var nr=class extends pn{sampleDataStartIndex=0;constructor(t,e=!0){if(super(),e)throw new Error("Using the constructor directly is deprecated. Use SoundBankLoader.fromArrayBuffer() instead.");let A=new ee(t);h.group("%cParsing a SoundFont2 file...",d.info),A||(h.groupEnd(),this.parsingError("No data provided!"));let s=U.read(A,!1);this.verifyHeader(s,"riff");let n=Ee(A,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw h.groupEnd(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let a=n==="sfpk",r=U.read(A);this.verifyHeader(r,"list");let i=Ee(r.data,4);if(i!=="INFO")throw h.groupEnd(),new SyntaxError(`Invalid soundFont! Expected "INFO" got "${i}"`);let o;for(;r.data.length>r.data.currentIndex;){let F=U.read(r.data),u=_e(F.data,F.data.length),x=F.header;switch(x){case"ifil":case"iver":{let P=V(F.data,2),te=V(F.data,2);x==="ifil"?this.soundBankInfo.version={major:P,minor:te}:this.soundBankInfo.romVersion={major:P,minor:te};break}case"DMOD":this.defaultModulators=VA(F),this.customDefaultModulators=!0;break;case"LIST":Ee(F.data,4)==="xdta"&&(h.info("%cExtended SF2 found!",d.recognized),o=F);break;case"ICRD":this.soundBankInfo.creationDate=Es(Ee(F.data,F.data.length));break;case"ISFT":this.soundBankInfo.software=u;break;case"IPRD":this.soundBankInfo.product=u;break;case"IENG":this.soundBankInfo.engineer=u;break;case"ICOP":this.soundBankInfo.copyright=u;break;case"INAM":this.soundBankInfo.name=u;break;case"ICMT":this.soundBankInfo.comment=u;break;case"irom":this.soundBankInfo.romInfo=u;break;case"isng":this.soundBankInfo.soundEngine=u}}this.printInfo();let g={};o!==void 0&&(g.phdr=U.read(o.data),g.pbag=U.read(o.data),g.pmod=U.read(o.data),g.pgen=U.read(o.data),g.inst=U.read(o.data),g.ibag=U.read(o.data),g.imod=U.read(o.data),g.igen=U.read(o.data),g.shdr=U.read(o.data));let l=U.read(A,!1);this.verifyHeader(l,"list"),this.verifyText(Ee(A,4),"sdta"),h.info("%cVerifying smpl chunk...",d.warn);let C=U.read(A,!1);this.verifyHeader(C,"smpl");let B;if(a){h.info("%cSF2Pack detected, attempting to decode the smpl chunk...",d.info);try{B=FA.decode(A.buffer.slice(A.currentIndex,A.currentIndex+l.size-12)).data[0]}catch(F){throw h.groupEnd(),new Error(`SF2Pack Ogg Vorbis decode error: ${F}`,{cause:F})}h.info(`%cDecoded the smpl chunk! Length: %c${B.length}`,d.info,d.value)}else B=A,this.sampleDataStartIndex=A.currentIndex;h.info(`%cSkipping sample chunk, length: %c${l.size-12}`,d.info,d.value),A.currentIndex+=l.size-12,h.info("%cLoading preset data chunk...",d.warn);let I=U.read(A);this.verifyHeader(I,"list"),Ee(I.data,4);let E=U.read(I.data);this.verifyHeader(E,"phdr");let m=U.read(I.data);this.verifyHeader(m,"pbag");let k=U.read(I.data);this.verifyHeader(k,"pmod");let y=U.read(I.data);this.verifyHeader(y,"pgen");let b=U.read(I.data);this.verifyHeader(b,"inst");let R=U.read(I.data);this.verifyHeader(R,"ibag");let M=U.read(I.data);this.verifyHeader(M,"imod");let S=U.read(I.data);this.verifyHeader(S,"igen");let Q=U.read(I.data);this.verifyHeader(Q,"shdr"),h.info("%cParsing samples...",d.info),A.currentIndex=this.sampleDataStartIndex;let p=Ms(Q,B,o===void 0);if(o&&g.shdr){let F=Ms(g.shdr,new Float32Array(1),!1);if(F.length===p.length)for(let[u,x]of p.entries())x.name+=F[u].name,x.linkedSampleIndex|=F[u].linkedSampleIndex<<16}for(let F of p)F.name=F.name.trim();this.samples.push(...p);let D=Ns(S),q=VA(M),K=Ts(b);if(o&&g.inst){let F=Ts(g.inst);if(F.length===K.length){for(let[u,x]of K.entries())x.name+=F[u].name,x.zoneStartIndex|=F[u].zoneStartIndex<<16;for(let[u,x]of K.entries())u-1&&(this.rootKey=a[c.overridingRootKey]),this.targetKey=e,a[c.keyNum]>-1&&(this.targetKey=a[c.keyNum]),this.velocity=A,a[c.velocity]>-1&&(this.velocity=a[c.velocity]),this.exclusiveClass=a[c.exclusiveClass],this.loopStart=n.loopStart,this.loopEnd=n.loopEnd,this.sampleData=n.getAudioData(),this.playbackStep=n.sampleRate/s*Math.pow(2,n.pitchCorrection/1200),this.loopingMode=a[c.sampleModes]}},Us=Math.PI/2,dA=-500,Sn=500,us=Sn-dA,kn=new Float32Array(us+1),Dn=new Float32Array(us+1);for(let t=dA;t<=Sn;t++){let e=(t-dA)/us,A=t-dA;kn[A]=Math.cos(Us*e),Dn[A]=Math.sin(Us*e)}function rr(t,e,A,s,n,a){if(!t.isInRelease&&e>=t.releaseStartTime&&(t.isInRelease=!0,t.volEnv.startRelease(t),t.modEnv.startRelease(t),t.loopingMode===3&&(t.wavetable.isLooping=!1)),t.hasRendered=!0,!t.isActive)return;let r=this.synthCore,i=r.sampleRate,o=t.modulatedGenerators,g=t.targetKey,l=t.pitchOffset+o[c.fineTune]+this.octaveTuning[g]+this.currentTuning,C=o[c.coarseTune],B=r.tunings[this.preset.program*128+t.midiNote];if(B!==-1&&(g=Math.trunc(B),C+=B-g),t.portamentoFromKey>-1){let u=Math.min((e-t.startTime)/t.portamentoDuration,1),x=g-t.portamentoFromKey;C-=x*(1-u)}l+=(g-t.rootKey)*o[c.scaleTuning];let I=0,E=0,m=t.gainModifier*(1+o[c.amplitude]/1e3);if(e>=t.vibLfoStartTime){let u=o[c.vibLfoToPitch],x=o[c.vibLfoToFilterFc],P=o[c.vibLfoAmplitudeDepth];if(u!==0||x!==0||P!==0){let te=Math.max(0,As(o[c.freqVibLFO])+o[c.vibLfoRate]/100)*a/i,W=1-4*Math.abs(t.vibLfoPhase-.5);(t.vibLfoPhase+=te)>=1&&(t.vibLfoPhase-=1),l+=W*u,I+=W*x,m*=1-(W+1)/2*(P/1e3)}}if(e>=t.modLfoStartTime){let u=o[c.modLfoToPitch],x=o[c.modLfoToVolume],P=o[c.modLfoToFilterFc],te=o[c.modLfoAmplitudeDepth];if(u!==0||P!==0||x!==0||te!==0){let W=Math.max(0,As(o[c.freqModLFO])+o[c.modLfoRate]/100)*a/i,_=1-4*Math.abs(t.modLfoPhase-.5);(t.modLfoPhase+=W)>=1&&(t.modLfoPhase-=1),l+=_*u,E+=-_*x,I+=_*P,m*=1-(_+1)/2*(te/1e3)}}let k=o[c.modEnvToPitch],y=o[c.modEnvToFilterFc];if(y!==0||k!==0){let u=t.modEnv.process(t,e);I+=u*y,l+=u*k}E-=t.resonanceOffset;let b=l+C*100,R=b|0;R!==t.tuningCents&&(t.tuningCents=R,t.tuningRatio=Math.pow(2,b/1200));let M=yA(o[c.initialAttenuation])*yA(E);if(t.loopingMode===2&&!t.isInRelease){t.isActive=t.volEnv.process(a,M);return}let S=r.voiceBuffer;t.isActive=t.wavetable.process(a,t.tuningRatio,S);let Q=t.volEnv.outputGain,p=t.volEnv.process(a,M),D=(t.volEnv.outputGain-Q)/a;{let u=t.filter,x=o[c.initialFilterFc];u.initialized?u.currentInitialFc+=(x-u.currentInitialFc)*fs.smoothingConstant:(u.initialized=!0,u.currentInitialFc=x);let P=u.currentInitialFc+I,te=o[c.initialFilterQ];if(u.currentInitialFc>13499&&P>13499&&te===0){u.currentInitialFc=13500;for(let W=0;W1||u.resonanceCb!==te)&&(u.lastTargetCutoff=P,u.resonanceCb=te,u.calculateCoefficients(P));let{a0:W,a1:_,a2:$,a3:ne,a4:ae}=u,{x1:J,x2:ie,y1:pe,y2:ve}=u;for(let Be=0;Be0){let u=K.reverbGain*O*(T/1e3),x=r.reverbInput;for(let P=0;P0){let u=K.chorusGain*(F/1e3)*O,x=r.chorusInput;for(let P=0;P0){let x=O*K.delayGain*((u>>7)/127),P=r.delayInput;for(let te=0;te127||e<0)throw new Error("Invalid MIDI Controller.");if(t>=f.modulationWheelLSB&&t<=f.effectControl2LSB){let s=t-32;if(this.lockedControllers[s])return;this._midiControllers[s]=this._midiControllers[s]&16256|e&127,this.computeModulatorsAll(1,s)}if(!this.lockedControllers[t]){switch(this._midiControllers[t]=e<<7|this._midiControllers[t]&127,t){case f.omniModeOff:case f.omniModeOn:case f.allNotesOff:this.stopAllNotes();break;case f.allSoundOff:this.stopAllNotes(!0);break;case f.polyModeOn:this.stopAllNotes(!0),this.setMIDIParameter("polyMode",!0);break;case f.monoModeOn:this.stopAllNotes(!0),this.setMIDIParameter("polyMode",!1);break;case f.bankSelect:this.setBankMSB(e),this.channel%16===9&&Se.isSystemXG(this.channelSystem)&&this.setBankMSB(127);break;case f.bankSelectLSB:this.setBankLSB(e);break;case f.variationDepth:this.synthCore.delayActive=!0;break;case f.registeredParameterLSB:case f.registeredParameterMSB:this._midiControllers[f.dataEntryMSB]=0,this.lastParameterIsRegistered=!0;break;case f.nonRegisteredParameterMSB:this.sf2NRPNGeneratorLSB=0,this._midiControllers[f.dataEntryMSB]=0,this.lastParameterIsRegistered=!1;break;case f.nonRegisteredParameterLSB:if(this._midiControllers[f.nonRegisteredParameterMSB]>>7===ye.SF2)switch(this.sf2NRPNGeneratorLSB%100!==0&&(this.sf2NRPNGeneratorLSB=0),e){case 100:this.sf2NRPNGeneratorLSB+=100;break;case 101:this.sf2NRPNGeneratorLSB+=1e3;break;case 102:this.sf2NRPNGeneratorLSB+=1e4;break;default:e<100&&(this.sf2NRPNGeneratorLSB+=e)}this._midiControllers[f.dataEntryMSB]=0,this.lastParameterIsRegistered=!1;break;case f.dataEntryMSB:case f.dataEntryLSB:this.dataEntry();break;case f.resetAllControllers:this.resetRP15();break;case f.sustainPedal:if(e<64){let s=0;if(this._voiceCount>0){for(let n of this.synthCore.voices)if(n.channel===this.channel&&n.isActive&&n.isHeld&&(n.isHeld=!1,n.releaseVoice(this.synthCore.currentTime),++s>=this._voiceCount))break}}break;case f.portamentoControl:this.lastNote=e,this.portamentoForce=!0;break;default:this.computeModulatorsAll(1,t);break}A&&this.synthCore.callEvent("controllerChange",{channel:this.channel,controller:t,value:e})}}var or=[c.delayModLFO,c.freqModLFO,c.delayVibLFO,c.freqVibLFO,c.delayModEnv,c.attackModEnv,c.holdModEnv,c.decayModEnv,c.sustainModEnv,c.releaseModEnv,c.delayVolEnv,c.attackVolEnv,c.holdVolEnv,c.decayVolEnv,c.sustainVolEnv,c.releaseVolEnv,c.fineTune,c.modLfoToPitch,c.vibLfoToPitch,c.modEnvToPitch,c.modLfoToVolume,c.initialFilterFc,c.initialFilterQ,c.modLfoToFilterFc,c.modEnvToFilterFc,c.chorusEffectsSend,c.reverbEffectsSend],gt=(t,e,A)=>Math.max(e,Math.min(A,t)),cA=t=>Math.max(-32768,1200*Math.log2(t/1e3)),gr=t=>6900+1200*Math.log2(t/440);function Ir(t,e){let A=e&127;e-=8192;let s=or[t];s||h.unsupported(`AWE32 LSB for ${this.channel}`,[t],"Invalid Generator Number");let n,a,r,i;switch(s){default:break;case c.delayModLFO:case c.delayVibLFO:case c.delayVolEnv:case c.delayModEnv:n=4*gt(e,0,5900),this.setGeneratorOverride(s,cA(n));break;case c.attackVolEnv:case c.attackModEnv:n=gt(e,0,5940),this.setGeneratorOverride(s,cA(n));break;case c.holdVolEnv:case c.holdModEnv:n=gt(e,0,8191),this.setGeneratorOverride(s,cA(n));break;case c.decayModEnv:case c.decayVolEnv:case c.releaseVolEnv:case c.releaseModEnv:n=4*gt(e,0,5940),this.setGeneratorOverride(s,cA(n));break;case c.freqVibLFO:case c.freqModLFO:a=.084*A,this.setGeneratorOverride(s,gr(a),!0);break;case c.sustainVolEnv:case c.sustainModEnv:r=A*7.5,this.setGeneratorOverride(s,r);break;case c.fineTune:this.setGeneratorOverride(s,e,!0);break;case c.modLfoToPitch:case c.vibLfoToPitch:i=gt(e,-127,127)*9.375,this.setGeneratorOverride(s,i,!0);break;case c.modEnvToPitch:i=gt(e,-127,127)*9.375,this.setGeneratorOverride(s,i);break;case c.modLfoToVolume:r=1.875*A,this.setGeneratorOverride(s,r,!0);break;case c.initialFilterFc:{let o=4335+59*A;this.setGeneratorOverride(s,o,!0);break}case c.initialFilterQ:r=215*(A/127),this.setGeneratorOverride(s,r,!0);break;case c.modLfoToFilterFc:i=gt(e,-64,63)*56.25,this.setGeneratorOverride(s,i,!0);break;case c.modEnvToFilterFc:i=gt(e,-64,63)*56.25,this.setGeneratorOverride(s,i);break;case c.chorusEffectsSend:case c.reverbEffectsSend:this.setGeneratorOverride(s,gt(e,0,255)*(1e3/255));break}}function cr(){let t=this._midiControllers[f.dataEntryMSB];if(this.lastParameterIsRegistered){let n=this._midiControllers[f.registeredParameterMSB]|this._midiControllers[f.registeredParameterLSB]>>7;switch(n){default:h.info(`%cUnrecognized RPN for %c${this.channel}%c: %c(0x${n.toString(16)})%c data value: %c${t}`,d.warn,d.recognized,d.warn,d.unrecognized,d.warn,d.value);break;case ut.pitchWheelRange:this.pitchWheelRange(t/128);break;case ut.coarseTuning:{let a=(t>>7)-64;this.keyShift(a);break}case ut.fineTuning:{let a=t-8192;this.fineTune(a/81.92);break}case ut.modulationDepth:this.modulationDepth(t/1.28);break;case ut.resetParameters:break}return}let e=this._midiControllers[f.nonRegisteredParameterMSB]>>7,A=this._midiControllers[f.nonRegisteredParameterLSB]>>7,s=t>>7;if(!(this.synthCore.systemParameters.drumLock&&e>=ye.drumPitch&&e<=ye.drumDelay))switch(e){default:h.info(`%cUnrecognized NRPN for %c${this.channel}%c: %c(0x${e.toString(16).toUpperCase()} 0x${A.toString(16).toUpperCase()})%c data value: %c${s}`,d.warn,d.recognized,d.warn,d.unrecognized,d.warn,d.value);break;case ye.partParameter:{let n=this._systemParameters.nrpnParamLock??this.synthCore.systemParameters.nrpnParamLock;switch(A){default:h.info(`%cUnrecognized NRPN for %c${this.channel}%c: %c(0x${e.toString(16)} 0x${A.toString(16)})%c data value: %c${s}`,d.warn,d.recognized,d.warn,d.unrecognized,d.warn,d.value);break;case Pe.vibratoRate:this.controllerChange(f.vibratoRate,s);break;case Pe.vibratoDepth:this.controllerChange(f.vibratoDepth,s);break;case Pe.vibratoDelay:this.controllerChange(f.vibratoDelay,s);break;case Pe.tvfCutoffFrequency:if(n)return;this.controllerChange(f.brightness,s),h.coolInfo(`Filter cutoff for ${this.channel}`,s.toString(),"");break;case Pe.tvfResonance:if(n)return;this.controllerChange(f.filterResonance,s),h.coolInfo(`Filter resonance for ${this.channel}`,s.toString(),"");break;case Pe.envelopeAttackTime:if(n)return;this.controllerChange(f.attackTime,s),h.coolInfo(`EG attack time for ${this.channel}`,s.toString(),"");break;case Pe.envelopeDecayTime:if(n)return;this.controllerChange(f.decayTime,s),h.coolInfo(`EG decay time for ${this.channel}`,s.toString(),"");break;case Pe.envelopeReleaseTime:if(n)return;this.controllerChange(f.releaseTime,s),h.coolInfo(`EG release time for ${this.channel}`,s.toString(),"");break}break}case ye.drumPitch:{let n=this.channelSystem==="xg"||this.patch.bankLSB===1?(s-64)*100:(s-64)*50;this.drumParams[A].pitch=n,h.coolInfo(`Drum ${A} pitch for ${this.channel}`,n,"cents");break}case ye.drumPitchFine:{let n=s-64;this.drumParams[A].pitch+=n,h.coolInfo(`Drum ${A} pitch fine for ${this.channel}`,this.drumParams[A].pitch,"cents");break}case ye.drumLevel:this.drumParams[A].gain=s/120,h.coolInfo(`Drum ${A} level for ${this.channel}`,s,"");break;case ye.drumPan:this.drumParams[A].pan=s,h.coolInfo(`Drum ${A} pan for ${this.channel}`,s,"");break;case ye.drumReverb:this.drumParams[A].reverbGain=s/127,h.coolInfo(`Drum ${A} reverb level for ${this.channel}`,s,"");break;case ye.drumChorus:this.drumParams[A].chorusGain=s/127,h.coolInfo(`Drum ${A} chorus level for ${this.channel}`,s,"");break;case ye.drumDelay:this.drumParams[A].delayGain=s/127,h.coolInfo(`Drum ${A} delay level for ${this.channel}`,t,"");break;case ye.awe32:Ir.call(this,A,t);break;case ye.SF2:{if(A>100)break;let n=this.sf2NRPNGeneratorLSB,a=t-8192;this.setGeneratorOffset(n,a);break}}}var hr=40;function lr(t){if(t<1)return 0;{let e=[1,2,4,8,16,32,64,80,96,112,120,124],A=[1,.5,.25,.125,.0625,.03125,.0625,.0625,.0625,.125,.25,1/3],s=[-.16653127382501215,.11863875218299408,.029479047361245264,-.005442312089231738,.1451520875973037,-.005056281449558275,-.005095486882876532,.03334009551111544,-.09361368678020432,.14132569702451822,-.15805565301011382,-.09918856955881927],n=[.028212773333433472,-.3388502064992847,-.15839529890929713,-.12398131766775483,-.2874848552685111,.012254866302537692,.005957797193345771,-.03745899330347374,.12911781869810196,-.15867193224162568,.504406322732748,.3786845131875458],a=[.7218950861255283,.5574536226347168,.47133893237025826,.48597095327079914,.44336276333518854,.6076986311801551,.30851975971827794,.30514889345633955,.3302511933827384,.153822885219165,.1302280559047337,.49865530675491687],r=[-2.2218487496163566,-1.6382721639824072,-1.3010299956639813,-.958607314841775,-.6020599913279624,-.3010299956639812,.31386722036915343,.6232492903979004,.9242792860618817,1.290034611362518,1.4265112613645752,1.9030899869919435],i=[2,4,8,16,32,64,80,96,112,120,124],o=-1;for(let l=i.length-1;l>=0;l--)if(i[l]Math.max(e,Math.min(A,t));function Br(t,e){if(e<1){this.noteOff(t);return}e=Jt(e,0,127);let A=this.synthCore.systemParameters.blackMIDIMode;if(A&&this.synthCore.voiceCount>200&&e<40||A&&e<10||this._systemParameters.isMuted||!this.preset)return;let s=t+this.currentKeyShift;if(t>127||t<0)return;let n=this.preset.program,a=this.synthCore.tunings[n*128+t];a>=0&&(s=Math.trunc(a)),((this._systemParameters.monophonicRetrigger??this.synthCore.systemParameters.monophonicRetrigger)||this._midiParameters.assignMode===0)&&this.killNote(t);let r=this.synthCore.keyModifierManager.getVelocity(this.channel,t);r>-1&&(e=r);let i=this.synthCore.keyModifierManager.getGain(this.channel,t),o=this.lastNote,g=this.portamentoForce||this._midiControllers[f.portamentoOnOff]>=8192,l=this._midiControllers[f.portamentoTime]>>7,C=g&&!this._drumChannel&&o>=0&&o!==t&&l>0,B=-1,I=0;if(C){let S=Math.abs(t-o);B=o,I=Cr(l,S),this.portamentoForce=!1}if(this.lastNote=t,!this._midiParameters.polyMode){let S=0;if(this._voiceCount>0){for(let Q of this.synthCore.voices)if(Q.isActive&&Q.channel===this.channel&&(Q.exclusiveRelease(this.synthCore.currentTime,0),++S>=this._voiceCount))break}}let E=this.synthCore.getVoices(this.channel,s,e),m=0,k=0,y=0,b=1,R=1,M=1;if(this._midiParameters.randomPan&&(m=Math.round(Math.random()*1e3-500)),this._drumChannel){let S=this.drumParams[t];if(!S.rxNoteOn)return;let Q=S.pan-64;if(Q!==0)if(Q===-64)m=Math.round(Math.random()*1e3-500);else{let p=(this._midiControllers[f.pan]>>7)-64;m=Math.max(-63,Math.min(Q+p,63))/63*500||1}y=S.pitch,k=S.exclusiveClass,b=S.reverbGain,R=S.chorusGain,M=S.delayGain,i===1&&(i=S.gain)}for(let S of E){let Q=this.synthCore.assignVoice(),p=this.synthCore.currentTime;if(Q.setup(p,this.channel,t),Q.wavetable=Q.oscillators[this._systemParameters.interpolationType??this.synthCore.systemParameters.interpolationType],Q.targetKey=S.targetKey,Q.velocity=S.velocity,Q.generators.set(S.generators),Q.exclusiveClass=k||S.exclusiveClass,Q.rootKey=S.rootKey,Q.loopingMode=S.loopingMode,Q.wavetable.sampleData=S.sampleData,Q.wavetable.playbackStep=S.playbackStep,this.dynamicModulators.active){Q.modulators=[...S.modulators];for(let H of this.dynamicModulators.modulatorList){let Z=Q.modulators.findIndex(T=>ke.isIdentical(T,H.mod));Z===-1?Q.modulators.push(H.mod):Q.modulators[Z]=H.mod}}else Q.modulators=S.modulators;if(Q.modulators.length>Q.modulatorValues.length&&(h.warn(`${Q.modulators.length} modulators! Increasing modulatorValues table.`),Q.modulatorValues=new Int16Array(Q.modulators.length)),this.generators.overridesEnabled){let H=this.generators.overrides;for(let Z=0;Z0){for(let Z of this.synthCore.voices)if(Z.isActive&&Z.channel===this.channel&&Z.exclusiveClass===Q.exclusiveClass&&Z.hasRendered&&(Z.exclusiveRelease(this.synthCore.currentTime),++H>=this._voiceCount))break}}this.computeModulators(Q),Q.volEnv.init(Q),Q.modEnv.init(Q),Q.filter.init(),Q.vibLfoStartTime=p+mA(Q.modulatedGenerators[c.delayVibLFO]),Q.modLfoStartTime=p+mA(Q.modulatedGenerators[c.delayModLFO]);let D=Q.modulatedGenerators[c.startAddrsOffset]+Q.modulatedGenerators[c.startAddrsCoarseOffset]*32768,q=Q.modulatedGenerators[c.endAddrOffset]+Q.modulatedGenerators[c.endAddrsCoarseOffset]*32768,K=Q.modulatedGenerators[c.startloopAddrsOffset]+Q.modulatedGenerators[c.startloopAddrsCoarseOffset]*32768,O=Q.modulatedGenerators[c.endloopAddrsOffset]+Q.modulatedGenerators[c.endloopAddrsCoarseOffset]*32768,Y=S.sampleData.length-1;if(Q.wavetable.cursor=Jt(D,0,Y),Q.wavetable.end=Jt(Y+q,0,Y),Q.wavetable.loopStart=Jt(S.loopStart+K,0,Y),Q.wavetable.loopEnd=Jt(S.loopEnd+O,0,Y),Q.wavetable.loopEnd127||t<0)return;if(this.synthCore.systemParameters.blackMIDIMode&&!this._drumChannel||this._drumChannel&&this.drumParams[t].rxNoteOff){this.killNote(t),this.synthCore.callEvent("noteOff",{midiNote:t,channel:this.channel});return}let e=this._midiControllers[f.sustainPedal]>=8192,A=0;if(this._voiceCount>0){for(let s of this.synthCore.voices)if(s.channel===this.channel&&s.isActive&&s.midiNote===t&&!s.isInRelease&&(e?s.isHeld=!0:s.releaseVoice(this.synthCore.currentTime),++A>=this._voiceCount))break}this.synthCore.callEvent("noteOff",{midiNote:t,channel:this.channel})}function dr(t){if(this._systemParameters.presetLock)return;this.patch.program=t;let e=this.synthCore.soundBankManager.getPreset(this.patch,this.channelSystem);!e&&(e=this.synthCore.missingPresetHandler(this.patch,this.channelSystem),!e)||(this.preset=e,e.isDrum!==this._drumChannel&&this.setDrumFlag(e.isDrum),this.resetDrumParams(),this.synthCore.callEvent("programChange",{channel:this.channel,bankLSB:this.preset.bankLSB,bankMSB:this.preset.bankMSB,program:this.preset.program,name:this.preset.name,isGMGSDrum:this.preset.isGMGSDrum,isDrum:this.preset.isDrum}))}var fr=[kA.fromModulator(new ue(Ze(le.linear,!0,!1,!0,f.vibratoRate),0,c.vibLfoRate,1e3,0))],Qr=class{modulatorList=[];active=!1;channel;constructor(t){this.channel=t}resetModulators(){this.modulatorList=fr.map(t=>({mod:t,id:this.getModulatorID(t.primarySource.toSourceEnum(),t.destination,t.primarySource.isBipolar,t.primarySource.isNegative)})),this.active=!1}setupReceiver(t,e,A,s,n,a=!1){this.active=!0;let r=e-64,i=r/64,o=e/127;switch(t&15){case 0:this.setModulator(A,s,c.fineTune,r*100,a),h.coolInfo(`Channel ${this.channel} ${n} pitch control`,r,"semitones");break;case 1:this.setModulator(A,s,c.initialFilterFc,i*9600,a),h.coolInfo(`Channel ${this.channel} ${n} filter control`,i*9600,"cents");break;case 2:this.setModulator(A,s,c.amplitude,i*1e3,a),h.coolInfo(`Channel ${this.channel} ${n} amplitude control`,i*100,"%");break;case 3:this.setModulator(A,s,c.vibLfoRate,i*1e3,a),h.coolInfo(`Channel ${this.channel} ${n} LFO1 rate control`,i*10,"Hz");break;case 4:this.setModulator(A,s,c.vibLfoToPitch,o*600,a),h.coolInfo(`Channel ${this.channel} ${n} LFO1 pitch depth control`,o*600,"cents");break;case 5:this.setModulator(A,s,c.vibLfoToFilterFc,o*2400,a),h.coolInfo(`Channel ${this.channel} ${n} LFO1 filter depth control`,o*2400,"cents");break;case 6:this.setModulator(A,s,c.vibLfoAmplitudeDepth,o*1e3,a),h.coolInfo(`Channel ${this.channel} ${n} LFO1 amplitude depth control`,o*100,"%");break;case 7:this.setModulator(A,s,c.modLfoRate,i*1e3,a),h.coolInfo(`Channel ${this.channel} ${n} LFO2 rate control`,i*10,"Hz");break;case 8:this.setModulator(A,s,c.modLfoToPitch,o*600,a),h.coolInfo(`Channel ${this.channel} ${n} LFO2 pitch depth control`,o*600,"cents");break;case 9:this.setModulator(A,s,c.modLfoToFilterFc,o*2400,a),h.coolInfo(`Channel ${this.channel} ${n} LFO2 filter depth control`,o*2400,"cents");break;case 10:this.setModulator(A,s,c.modLfoAmplitudeDepth,o*1e3,a),h.coolInfo(`Channel ${this.channel} ${n} LFO2 amplitude depth control`,o*100,"%");break}}setModulator(t,e,A,s,n=!1,a=!1){let r=this.getModulatorID(t,A,n,a);s===0&&this.deleteModulator(r);let i=this.modulatorList.find(o=>o.id===r);if(i)i.mod.transformAmount=s;else{let o=kA.fromData(new st(t,le.linear,e,n),new st,A,s,0);this.modulatorList.push({mod:o,id:r})}}getModulatorID(t,e,A,s){return`${t}-${e}-${A}-${s}`}deleteModulator(t){this.modulatorList=this.modulatorList.filter(e=>e.id!==t)}},ur=1e3/200;function mr(t,e,A){let s=t.modulators[A];if(s.transformAmount===0)return t.modulatorValues[A]=0,0;let n=s.primarySource.getValue(this,e,t),a=s.secondarySource.getValue(this,e,t),r=s.transformAmount;s.isEffectModulator&&r<=1e3&&(r*=ur,r=Math.min(r,1e3));let i=n*a*r;return s.transformType===2&&(i=Math.abs(i)),s.isDefaultResonantModulator&&(t.resonanceOffset=Math.max(0,i/2)),s.isModWheelModulator&&(i*=this._midiParameters.modulationDepth),t.modulatorValues[A]=i,i}function pr(t,e=-1,A=0){let s=t.modulators,n=t.generators;if(this.generators.offsetsEnabled){let o=this.generators.offsets;n=new Int16Array(n);for(let g=0;g({...t})),drumChannel:this._drumChannel,channelNumber:this.channel}}function Sr(t){this.setDrums(t.drumChannel),this._midiControllers.set(t.midiControllers);for(let e=0;e<128;e++)this.lockController(e,t.lockedControllers[e]);this.pitchWheels.set(t.pitchWheels),this.octaveTuning.set(t.octaveTuning),this.perNotePitch=t.perNotePitch,this.generators.offsets.set(t.generators.offsets),this.generators.overrides.set(t.generators.overrides);for(let e=0;e<128;e++)this.drumParams[e]=wn.copyFrom(t.drumParams[e]);this.setSystemParameter("presetLock",!1),t.patch&&this.setPatch(t.patch),this.lockedSystem=t.lockedSystem;for(let[e,A]of Object.entries(this._midiParameters))this.setMIDIParameter(e,A);for(let[e,A]of Object.entries(this._systemParameters))this.setSystemParameter(e,A)}var kr={pitchWheel:8192,pitchWheelRange:2,pressure:0,modulationDepth:1,rxChannel:0,polyMode:!0,keyShift:0,randomPan:!1,assignMode:2,efxAssign:!1,cc1:16,cc2:17,drumMap:0,fineTune:0},Dr={presetLock:!1,isMuted:!1,gain:1,pan:0,keyShift:0,fineTune:0,interpolationType:null,nrpnParamLock:null,monophonicRetrigger:null};function wr(t,e){if(this._systemParameters[t]===e)return;let A=this._systemParameters[t];switch(this._systemParameters[t]=e,this.updateInternalParams(),t){default:break;case"presetLock":e&&(this.lockedSystem=this.synthCore.midiParameters.system);break;case"isMuted":e&&this.stopAllNotes(!0);break;case"keyShift":!this._drumChannel&&A!==e&&this.stopAllNotes(!0)}}var br=class{pitchWheels=new Int16Array(128).fill(8192);lockedControllers=new Array(128).fill(!1);drumParams=[];dynamicModulators;sf2NRPNGeneratorLSB=0;patch={bankMSB:0,bankLSB:0,program:0,isGMGSDrum:!1};preset;lockedSystem="gs";channel;synthCore;setSystemParameter=wr.bind(this);noteOn=Br.bind(this);noteOff=Er.bind(this);programChange=dr.bind(this);controllerChange=ir.bind(this);reset=ma.bind(this);renderVoice=rr.bind(this);_midiControllers=new Int16Array(128);octaveTuning=new Int8Array(128);resetRP15=pa.bind(this);dataEntry=cr.bind(this);_midiParameters={...kr};_systemParameters={...Dr};lastParameterIsRegistered=!0;perNotePitch=!1;currentPan=0;currentTuning=0;currentKeyShift=0;currentGain=0;lastNote=-1;portamentoForce=!1;generators={offsets:new Int16Array(St),offsetsEnabled:!1,overrides:new Int16Array(St),overridesEnabled:!1};computeModulator=mr.bind(this);computeModulators=pr.bind(this);constructor(t,e,A){this.synthCore=t,this.preset=e,this.channel=A,this._midiParameters.rxChannel=A,this.dynamicModulators=new Qr(A),this.resetGeneratorOverrides(),this.resetGeneratorOffsets();for(let s=0;s<128;s++)this.drumParams.push(new wn);this.resetDrumParams()}_voiceCount=0;get voiceCount(){return this._voiceCount}set voiceCount(t){this._voiceCount=t}_drumChannel=!1;get drumChannel(){return this._drumChannel}get midiControllers(){return this._midiControllers}get systemParameters(){return this._systemParameters}get midiParameters(){return this._midiParameters}get channelSystem(){return this._systemParameters.presetLock?this.lockedSystem:this.synthCore.midiParameters.system}lockController(t,e){this.lockedControllers[t]=e}setDrums(t){if(Se.isSystemXG(this.channelSystem))if(t)this.setBankMSB(Se.getDrumBank(this.channelSystem)),this.setBankLSB(0);else{if(this.channel%16===9)throw new Error(`Cannot disable drums on channel ${this.channel} for XG.`);this.setBankMSB(0),this.setBankLSB(0)}else this.setGSDrums(t);this.setDrumFlag(t),this.programChange(this.patch.program)}stopAllNotes(t=!1){if(t){let e=0;if(this._voiceCount>0){for(let A of this.synthCore.voices)if(A.channel===this.channel&&A.isActive&&(A.isActive=!1,++e>=this._voiceCount))break}this.clearVoiceCount()}else{let e=0;if(this._voiceCount>0){for(let A of this.synthCore.voices)if(A.channel===this.channel&&A.isActive&&(A.releaseVoice(this.synthCore.currentTime),++e>=this._voiceCount))break}}this.synthCore.callEvent("stopAll",{channel:this.channel,force:t})}setMIDIParameter(t,e){switch(this._midiParameters[t]=e,t){case"pitchWheel":this.computeModulatorsAll(0,Ie.pitchWheel);break;case"pressure":this.computeModulatorsAll(0,Ie.channelPressure);break}this.updateInternalParams(),this.synthCore.callEvent("channelParamChange",{channel:this.channel,parameter:t,value:e})}clearVoiceCount(){this._voiceCount=0}setOctaveTuning(t){if(t.length!==12)throw new Error("Tuning is not the length of 12.");for(let e=0;e<128;e++)this.octaveTuning[e]=t[e%12]}modulationDepth(t,e=!0){this.setMIDIParameter("modulationDepth",t/50),e&&h.info(`%cChannel ${this.channel} modulation depth. Cents: %c${Math.round(t)}`,d.info,d.value)}keyShift(t,e=!0){this._drumChannel&&(t=0),this._midiParameters.keyShift!==t&&(this.setMIDIParameter("keyShift",t),e&&h.info(`%cKey shift for %c${this.channel}%c is now set to %c${t}.`,d.info,d.recognized,d.info,d.value))}fineTune(t,e=!0){this.setMIDIParameter("fineTune",t),e&&h.info(`%cFine tuning for %c${this.channel}%c is now set to %c${Math.round(t)}%c cents.`,d.info,d.recognized,d.info,d.value,d.info)}pitchWheel(t,e=-1){e===-1?(this.perNotePitch=!1,this.setMIDIParameter("pitchWheel",t)):(this.perNotePitch||this.pitchWheels.fill(this._midiParameters.pitchWheel),this.perNotePitch=!0,this.pitchWheels[e]=t,this.computeModulatorsAll(0,Ie.pitchWheel))}polyPressure(t,e){let A=0;if(this._voiceCount>0){for(let s of this.synthCore.voices)if(s.isActive&&s.channel===this.channel&&s.midiNote===t&&(s.pressure=e,this.computeModulators(s,0,Ie.polyPressure),++A>=this._voiceCount))break}this.synthCore.callEvent("polyPressure",{channel:this.channel,midiNote:t,pressure:e})}pitchWheelRange(t,e=!0){this.setMIDIParameter("pitchWheelRange",t),e&&h.coolInfo(`Pitch Wheel Range for ${this.channel}`,t,"semitones")}updateInternalParams(){let t=this.synthCore.systemParameters,e=this._systemParameters,A=this.synthCore.midiParameters,s=this._midiParameters,n=this._drumChannel?e.keyShift:t.keyShift+A.keyShift+e.keyShift+s.keyShift;this.currentKeyShift=Math.trunc(n),this.currentTuning=this._drumChannel?e.fineTune:t.fineTune+A.fineTune+e.fineTune+s.fineTune;let a=t.pan+A.pan+e.pan;this.currentPan=a*500,this.currentGain=Zn*t.gain*A.gain*e.gain}setPatch(t){this.setBankMSB(t.bankMSB),this.setBankLSB(t.bankLSB),this.setGSDrums(t.isGMGSDrum),this.programChange(t.program)}setGSDrums(t){t!==this.patch.isGMGSDrum&&(this.setBankLSB(0),this.setBankMSB(0),this.patch.isGMGSDrum=t)}killNote(t,e=-12e3){let A=0;if(this._voiceCount>0){for(let s of this.synthCore.voices)if(s.channel===this.channel&&s.isActive&&s.midiNote===t&&(s.overrideReleaseVolEnv=e,s.isInRelease=!1,s.releaseVoice(this.synthCore.currentTime),++A>=this._voiceCount))break}}applySnapshot(t){Sr.call(this,t)}getSnapshot(){return yr.call(this)}setLastNote(t){this.lastNote=t}destroy(){this.preset=void 0,this.lockedControllers=void 0,this._systemParameters=void 0,this._midiControllers=void 0,this._midiParameters=void 0}resetGeneratorOverrides(){this.generators.overrides.fill(Jn),this.generators.overridesEnabled=!1}setGeneratorOverride(t,e,A=!1){if(this.generators.overrides[t]=e,this.generators.overridesEnabled=!0,A){let s=0;if(this._voiceCount>0){for(let n of this.synthCore.voices)if(n.channel===this.channel&&n.isActive&&(n.generators[t]=e,this.computeModulators(n),++s>=this._voiceCount))break}}}resetGeneratorOffsets(){this.generators.offsets.fill(0),this.generators.offsetsEnabled=!1}setGeneratorOffset(t,e){this.generators.offsets[t]=e*Ve[t].nrpn,this.generators.offsetsEnabled=!0;let A=0;if(this._voiceCount>0){for(let s of this.synthCore.voices)if(s.channel===this.channel&&s.isActive&&(this.computeModulators(s),++A>=this._voiceCount))break}}resetDrumParams(){if(!(this.synthCore.systemParameters.drumLock||!this._drumChannel))for(let t=0;t<128;t++){let e=this.drumParams[t];e.pitch=0,e.gain=1,e.exclusiveClass=0,e.pan=64,e.reverbGain=uA[t]/127,e.chorusGain=this.channelSystem==="xg"?uA[t]/127:0,e.delayGain=0,e.rxNoteOn=!0,e.rxNoteOff=!1}}computeModulatorsAll(t,e){let A=0;if(this._voiceCount>0){for(let s of this.synthCore.voices)if(s.channel===this.channel&&s.isActive&&(this.computeModulators(s,t,e),++A>=this._voiceCount))break}}setBankMSB(t){this._systemParameters.presetLock||(this.patch.bankMSB=t)}setBankLSB(t){this._systemParameters.presetLock||(this.patch.bankLSB=t)}setDrumFlag(t){this._systemParameters.presetLock||!this.preset||this._drumChannel===t||(this._drumChannel=t,this.keyShift(this._midiParameters.keyShift,!1))}},Rr=class extends _t{constructor(t,e){super(t.parentSoundBank,t.globalZone),this.bankMSB=Se.addBankOffset(t.bankMSB,e,!0),this.name=t.name,this.bankLSB=t.bankLSB,this.isGMGSDrum=t.isGMGSDrum,this.program=t.program,this.genre=t.genre,this.morphology=t.morphology,this.library=t.library,this.zones=t.zones}},Fr=class{soundBankList=[];presetListChangeCallback;selectablePresetList=[];constructor(t){this.presetListChangeCallback=t}_presetList=[];get presetList(){return[...this._presetList]}get priorityOrder(){return this.soundBankList.map(t=>t.id)}set priorityOrder(t){this.soundBankList.sort((e,A)=>t.indexOf(e.id)-t.indexOf(A.id)),this.generatePresetList()}deleteSoundBank(t){if(this.soundBankList.length===0){h.warn("1 soundbank left. Aborting!");return}let e=this.soundBankList.findIndex(A=>A.id===t);if(e===-1)throw new Error(`No sound bank with id "${t}"`);this.soundBankList.splice(e,1),this.generatePresetList()}addSoundBank(t,e,A=0){let s=this.soundBankList.find(n=>n.id===e);s===void 0?this.soundBankList.push({id:e,soundBank:t,bankOffset:A}):(s.soundBank=t,s.bankOffset=A),this.generatePresetList()}getPreset(t,e){if(!(this.soundBankList.length===0||this.selectablePresetList.length===0))return ze.selectPatch(this.selectablePresetList,t,e)}destroy(){for(let t of this.soundBankList)t.soundBank.destroySoundBank();this.soundBankList=[]}generatePresetList(){let t=new Array,e=new Set;for(let A of this.soundBankList){let s=A.soundBank,n=A.bankOffset;for(let a of s.presets){let r=new Rr(a,n);e.has(r.toMIDIString())||(e.add(r.toMIDIString()),t.push(r))}}t.sort(ze.compare.bind(ze)),this.selectablePresetList=t,this._presetList=t.map(A=>({bankMSB:A.bankMSB,bankLSB:A.bankLSB,program:A.program,isGMGSDrum:A.isGMGSDrum,name:A.name,isDrum:A.isDrum})),this.presetListChangeCallback()}};function xs(t,e,A){let s=t,n=e<<7|A;return t===127&&e===127&&A===127?-1:s+n*61e-6}function Mr(t,e=0){switch(t[2]){case 4:switch(t[3]){default:h.gmFail("Device Control",t);break;case 1:{let A=t[5]<<7|t[4];this.setMIDIParameter("gain",A/16384),h.gmInfo("Master Volume",A);break}case 2:{let A=((t[5]<<7|t[4])-8192)/8192;this.setMIDIParameter("pan",A),h.gmInfo("Master Balance",A);break}case 3:{let A=((t[5]<<7|t[6])-8192)/81.92;this.setMIDIParameter("fineTune",A),h.gmInfo("Master Fine Tuning",A,"cents");break}case 4:{let A=t[5]-64;this.setMIDIParameter("keyShift",A),h.gmInfo("Master Coarse Tuning",A,"keys");break}case 5:if(t[4]!==1||t[5]!==1||t[6]!==1||t[7]!==1){h.gmFail("Global Parameter Control",t);break}switch(t[8]){default:h.gmFail("Global Parameter Control",t);break;case 1:{let A=t[10];switch(t[9]){default:h.gmFail("Reverb Parameter Control",t);break;case 0:{let s=A===8?5:A;this.setReverbMacro(s),h.gmInfo("Reverb Type",s);break}case 1:this.reverbProcessor.time=A,h.gmInfo("Reverb Time",A)}break}case 2:{let A=t[10];switch(t[9]){default:h.gmFail("Chorus Parameter Control",t);break;case 0:this.setChorusMacro(A),h.gmInfo("Chorus Type",A);break;case 1:this.chorusProcessor.rate=A,h.gmInfo("Chorus Mod Rate",A);break;case 2:this.chorusProcessor.depth=A,h.gmInfo("Chorus Mod Depth",A);break;case 3:this.chorusProcessor.feedback=A,h.gmInfo("Chorus Mod Feedback",A);break;case 4:this.chorusProcessor.sendLevelToReverb=A,h.gmInfo("Chorus Send to Reverb",A);break}}}}break;case 9:switch(t[3]){default:h.gmFail("System Exclusive",t);break;case 1:h.coolInfo("MIDI System","General MIDI 1"),this.reset("gm");break;case 2:h.coolInfo("MIDI System","Roland GS"),this.reset("gs");break;case 3:h.coolInfo("MIDI System","General MIDI 2"),this.reset("gm2");break}break;case 8:{let A=4;switch(t[3]){case 1:{let s=t[A++],n=_e(t,16,A);if(A+=16,t.length<384){h.warn(`The Bulk Tuning Dump is too short! (${t.length} bytes, at least 384 are expected)`);return}for(let a=0;a<128;a++)this.tunings[s*128+a]=xs(t[A++],t[A++],t[A++]);h.gmInfo("Bulk Tuning Dump",`${n}, program ${s}`);break}case 2:case 7:{t[3]===7&&A++;let s=t[A++],n=t[A++];for(let a=0;a>1&1)===1&&this.midiChannels[15+e].setOctaveTuning(s);for(let n=0;n<7;n++)(t[5]>>n&1)===1&&this.midiChannels[7+n+e].setOctaveTuning(s);for(let n=0;n<7;n++)(t[6]>>n&1)===1&&this.midiChannels[n+e].setOctaveTuning(s);h.gmInfo("Octave Scale Tuning",s.join(" "));break}default:h.gmFail("MIDI Tuning Standard",t);break}break}default:h.gmFail("Universal System Exclusive",t)}}function vr(t,e=0){if(t[3]===18)switch(t[2]){case 66:{let A=t[4],s=t[5],n=t[6],a=Math.min(t[7],127);if(A===0&&s===0&&n===127&&a===0){h.coolInfo("MIDI System","Roland GS"),this.reset("gs");return}if(A===64){if(s===0){switch(n){case 0:{let r=((a<<12|t[8]<<8|t[9]<<4|t[10])-1024)/10;this.setMIDIParameter("fineTune",r),h.gsInfo("Master Tune",r,"cents");break}case 4:h.gsInfo("Master Volume",a);break;case 5:{let r=a-64;h.gsInfo("Master Key-Shift",r,"keys"),this.setMIDIParameter("keyShift",r);break}case 6:h.gsInfo("Master Pan",a),this.setMIDIParameter("pan",(a-64)/64);break;case 127:a===0?(h.coolInfo("MIDI System","Roland GS"),this.reset("gs")):a===127&&(h.coolInfo("MIDI System","General MIDI 1"),this.reset("gm"));break;default:h.gsFail("System Parameter",t);break}return}if(s===1){let r=n>=48&&n<=55,i=n>=56&&n<=64,o=n>=80&&n<=90;if(r&&this.systemParameters.reverbLock||i&&this.systemParameters.chorusLock||o&&this.systemParameters.delayLock)return;switch(this.delayActive||=n===64||o,n){default:h.gsFail("Patch Common Parameter",[n]);break;case 0:{let g=_e(t,16,7);h.gsInfo("Patch name",g);break}case 48:this.setReverbMacro(a),h.gsInfo("Reverb Macro",a);break;case 49:this.reverbProcessor.character=a,h.gsInfo("Reverb Character",a),this.callEvent("effectChange",{effect:"reverb",parameter:"character",value:a});break;case 50:this.reverbProcessor.preLowpass=a,h.gsInfo("Reverb Pre-LPF",a),this.callEvent("effectChange",{effect:"reverb",parameter:"preLowpass",value:a});break;case 51:this.reverbProcessor.level=a,h.gsInfo("Reverb Level",a),this.callEvent("effectChange",{effect:"reverb",parameter:"level",value:a});break;case 52:this.reverbProcessor.time=a,h.gsInfo("Reverb Time",a),this.callEvent("effectChange",{effect:"reverb",parameter:"time",value:a});break;case 53:this.reverbProcessor.delayFeedback=a,h.gsInfo("Reverb Delay Feedback",a),this.callEvent("effectChange",{effect:"reverb",parameter:"delayFeedback",value:a});break;case 54:break;case 55:this.reverbProcessor.preDelayTime=a,h.gsInfo("Reverb Predelay Time",a),this.callEvent("effectChange",{effect:"reverb",parameter:"preDelayTime",value:a});break;case 56:this.setChorusMacro(a),h.gsInfo("Chorus Macro",a);break;case 57:this.chorusProcessor.preLowpass=a,h.gsInfo("Chorus Pre-LPF",a),this.callEvent("effectChange",{effect:"chorus",parameter:"preLowpass",value:a});break;case 58:this.chorusProcessor.level=a,h.gsInfo("Chorus Level",a),this.callEvent("effectChange",{effect:"chorus",parameter:"level",value:a});break;case 59:this.chorusProcessor.feedback=a,h.gsInfo("Chorus Feedback",a),this.callEvent("effectChange",{effect:"chorus",parameter:"feedback",value:a});break;case 60:this.chorusProcessor.delay=a,h.gsInfo("Chorus Delay",a),this.callEvent("effectChange",{effect:"chorus",parameter:"delay",value:a});break;case 61:this.chorusProcessor.rate=a,h.gsInfo("Chorus Rate",a),this.callEvent("effectChange",{effect:"chorus",parameter:"rate",value:a});break;case 62:this.chorusProcessor.depth=a,h.gsInfo("Chorus Depth",a),this.callEvent("effectChange",{effect:"chorus",parameter:"depth",value:a});break;case 63:this.chorusProcessor.sendLevelToReverb=a,h.gsInfo("Chorus Send Level To Reverb",a),this.callEvent("effectChange",{effect:"chorus",parameter:"sendLevelToReverb",value:a});break;case 64:this.chorusProcessor.sendLevelToDelay=a,h.gsInfo("Chorus Send Level To Delay",a),this.callEvent("effectChange",{effect:"chorus",parameter:"sendLevelToDelay",value:a});break;case 80:this.setDelayMacro(a),h.gsInfo("Delay Macro",a);break;case 81:this.delayProcessor.preLowpass=a,h.gsInfo("Delay Pre-LPF",a),this.callEvent("effectChange",{effect:"delay",parameter:"preLowpass",value:a});break;case 82:this.delayProcessor.timeCenter=a,h.gsInfo("Delay Time Center",a),this.callEvent("effectChange",{effect:"delay",parameter:"timeCenter",value:a});break;case 83:this.delayProcessor.timeRatioLeft=a,h.gsInfo("Delay Time Ratio Left",a),this.callEvent("effectChange",{effect:"delay",parameter:"timeRatioLeft",value:a});break;case 84:this.delayProcessor.timeRatioRight=a,h.gsInfo("Delay Time Ratio Right",a),this.callEvent("effectChange",{effect:"delay",parameter:"timeRatioRight",value:a});break;case 85:this.delayProcessor.levelCenter=a,h.gsInfo("Delay Level Center",a),this.callEvent("effectChange",{effect:"delay",parameter:"levelCenter",value:a});break;case 86:this.delayProcessor.levelLeft=a,h.gsInfo("Delay Level Left",a),this.callEvent("effectChange",{effect:"delay",parameter:"levelLeft",value:a});break;case 87:this.delayProcessor.levelRight=a,h.gsInfo("Delay Level Right",a),this.callEvent("effectChange",{effect:"delay",parameter:"levelRight",value:a});break;case 88:this.delayProcessor.level=a,h.gsInfo("Delay Level",a),this.callEvent("effectChange",{effect:"delay",parameter:"level",value:a});break;case 89:this.delayProcessor.feedback=a,h.gsInfo("Delay Feedback",a),this.callEvent("effectChange",{effect:"delay",parameter:"feedback",value:a});break;case 90:this.delayProcessor.sendLevelToReverb=a,h.gsInfo("Delay Send Level To Reverb",a),this.callEvent("effectChange",{effect:"delay",parameter:"sendLevelToReverb",value:a});break}break}if(s===3){if(this.systemParameters.insertionEffectLock)return;if(n>=3&&n<=25&&(this.insertionParams[n-3]=a),n>=3&&n<=22){this.insertionProcessor.setParameter(n,a),h.gsInfo(`EFX Parameter ${n-2}`,a),this.callEvent("effectChange",{effect:"insertion",parameter:n,value:a});return}switch(n){default:h.gsFail("Insertion Effect",[n]);return;case 0:{let r=a<<8|t[8],i=this.insertionEffects.get(r);i?(h.gsInfo("EFX Type",r.toString(16)),this.insertionProcessor=i):(this.insertionProcessor=this.insertionFallback,h.gsFail("EFX Processor",[r],"Using Thru.")),this.resetInsertionParams(),this.insertionProcessor.reset(),this.callEvent("effectChange",{effect:"insertion",parameter:0,value:r});return}case 23:this.insertionProcessor.sendLevelToReverb=a/127*hA,h.gsInfo("EFX Send Level to Reverb",a),this.callEvent("effectChange",{effect:"insertion",parameter:n,value:a});return;case 24:this.insertionProcessor.sendLevelToChorus=a/127*hA,h.gsInfo("EFX Send Level to Chorus",a),this.callEvent("effectChange",{effect:"insertion",parameter:n,value:a});return;case 25:this.insertionProcessor.sendLevelToDelay=a/127*hA,this.delayActive=!0,h.gsInfo("EFX Send Level to Delay",a),this.callEvent("effectChange",{effect:"insertion",parameter:n,value:a});return}}if(s>>4===1){let r=se.syxToChannel(s&15)+e,i=this.midiChannels[r];switch(n){default:h.gsFail(`Patch Part Parameter for ${r}`,[n]);return;case 0:i.controllerChange(f.bankSelect,a),i.programChange(t[8]);break;case 2:{let o=a===16?-1:a+e;i.setMIDIParameter("rxChannel",o),this.customChannelNumbers||=o!==i.channel,h.gsInfo(`Rx. Channel on ${r}`,o);break}case 19:i.setMIDIParameter("polyMode",a===1),h.gsInfo(`Mono/poly on ${r}`,i.midiParameters.polyMode?"POLY":"MONO");break;case 20:i.setMIDIParameter("assignMode",a),h.gsInfo(`Assign mode on ${r}`,a);break;case 21:{i.setMIDIParameter("drumMap",a);let o=a>0;i.setGSDrums(o),h.gsInfo(`Drums on ${r}`,o.toString());return}case 22:{let o=a-64;i.keyShift(o);return}case 25:i.controllerChange(f.mainVolume,a);return;case 28:{let o=a,g=o===0;i.setMIDIParameter("randomPan",g),g?h.gsInfo(`Random pan on ${r}`,"ON"):i.controllerChange(f.pan,o);break}case 31:i.setMIDIParameter("cc1",a),h.gsInfo("CC1 Controller Number",a);break;case 32:i.setMIDIParameter("cc2",a),h.gsInfo("CC2 Controller Number",a);break;case 33:i.controllerChange(f.chorusDepth,a);break;case 34:i.controllerChange(f.reverbDepth,a);break;case 42:{let o=((a<<7|t[8])-8192)/81.92;i.fineTune(o);break}case 44:i.controllerChange(f.variationDepth,a);break;case 48:i.controllerChange(f.vibratoRate,a);break;case 49:i.controllerChange(f.vibratoDepth,a);break;case 50:i.controllerChange(f.brightness,a);break;case 51:i.controllerChange(f.filterResonance,a);break;case 52:i.controllerChange(f.attackTime,a);break;case 53:i.controllerChange(f.decayTime,a);break;case 54:i.controllerChange(f.releaseTime,a);break;case 55:i.controllerChange(f.vibratoDelay,a);break;case 64:{let o=t.length-9,g=new Int8Array(12);for(let l=0;l>4===2){let r=se.syxToChannel(s&15)+e,i=this.midiChannels[r];switch(n&240){default:h.gsFail(`Patch Parameter Controller for ${r}`,[n&240]);break;case 0:if((n&15)===4){let o=a/127*600;i.modulationDepth(o);break}i.dynamicModulators.setupReceiver(n,a,f.modulationWheel,!0,"mod wheel");break;case 16:if((n&15)===0){let o=a-64;i.pitchWheelRange(o);break}i.dynamicModulators.setupReceiver(n,a,Ie.pitchWheel,!1,"pitch wheel",!0);break;case 32:i.dynamicModulators.setupReceiver(n,a,Ie.channelPressure,!1,"channel pressure");break;case 48:i.dynamicModulators.setupReceiver(n,a,Ie.polyPressure,!1,"poly pressure");break;case 64:i.dynamicModulators.setupReceiver(n,a,i.midiParameters.cc1,!0,"CC1");break;case 80:i.dynamicModulators.setupReceiver(n,a,i.midiParameters.cc2,!0,"CC2")}return}if(s>>4===4){let r=se.syxToChannel(s&15)+e,i=this.midiChannels[r];switch(n){default:h.gsFail("Patch Part Parameter",[n]);break;case 0:case 1:i.controllerChange(f.bankSelectLSB,a);break;case 34:{if(this.systemParameters.insertionEffectLock)return;let o=a===1;i.setMIDIParameter("efxAssign",o),this.insertionActive||=o,h.gsInfo(`EFX assign for ${r}`,o?"EFX":"BYPASS")}}return}h.gsFail("Patch Parameter",t);return}if(A===65){if(this.systemParameters.drumLock)return;let r=(s>>4)+1,i=n,o=s&15;switch(o){default:h.gsFail("Drum Setup",[o]);return;case 0:{let g=_e(t,12,7);h.gsInfo(`Patch Name for MAP${r}`,g);break}case 1:{let g=a-60;for(let l of this.midiChannels)l.midiParameters.drumMap===r&&(l.drumParams[i].pitch=g*(l.patch.bankLSB===1?100:50));h.gsInfo(`Drum Pitch for MAP${r}, key ${i}`,g);break}case 2:for(let g of this.midiChannels)g.midiParameters.drumMap===r&&(g.drumParams[i].gain=a/120);h.gsInfo(`Drum Level for MAP${r}, key ${i}`,a);break;case 3:for(let g of this.midiChannels)g.midiParameters.drumMap===r&&(g.drumParams[i].exclusiveClass=a);h.gsInfo(`Drum Assign Group for MAP${r}, key ${i}`,a);break;case 4:for(let g of this.midiChannels)g.midiParameters.drumMap===r&&(g.drumParams[i].pan=a);h.gsInfo(`Drum Pan for MAP${r}, key ${i}`,a);break;case 5:for(let g of this.midiChannels)g.midiParameters.drumMap===r&&(g.drumParams[i].reverbGain=a/127);h.gsInfo(`Drum Reverb for MAP${r}, key ${i}`,a);break;case 6:for(let g of this.midiChannels)g.midiParameters.drumMap===r&&(g.drumParams[i].chorusGain=a/127);h.gsInfo(`Drum Chorus for MAP${r}, key ${i}`,a);break;case 7:for(let g of this.midiChannels)g.midiParameters.drumMap===r&&(g.drumParams[i].rxNoteOff=a===1);h.gsInfo(`Drum Note Off for MAP${r}, key ${i}`,a===1?"ON":"OFF");break;case 8:for(let g of this.midiChannels)g.midiParameters.drumMap===r&&(g.drumParams[i].rxNoteOn=a===1);h.gsInfo(`Drum Note On for MAP${r}, key ${i}`,a===1?"ON":"OFF");break;case 9:for(let g of this.midiChannels)g.midiParameters.drumMap===r&&(g.drumParams[i].delayGain=a/127);h.gsInfo(`Drum Delay for MAP${r}, key ${i}`,a);break}return}h.gsFail("System Exclusive",t);return}case 69:t[4]===16&&(t[5]===0?this.callEvent("displayMessage",[...t]):t[5]===1?this.callEvent("displayMessage",[...t]):h.gsFail("Display Data",t));return;case 22:if(t[4]===16){this.setMIDIParameter("gain",t[7]/100),h.coolInfo("Roland Master Volume Control",t[7]);return}else h.unsupported("Roland",t)}else{h.unsupported("Roland",t);return}}function Gr(t,e=0){if(t[2]===76){let A=t[3],s=t[4],n=t[5],a=t[6];if(A===0&&s===0){switch(n){case 0:{let r=(((t[6]&15)<<12|(t[7]&15)<<8|(t[8]&15)<<4|t[9]&15)-1024)/10;this.setMIDIParameter("fineTune",r),h.xgInfo("Master Tune",r,"cents")}break;case 4:this.setMIDIParameter("gain",a/127),h.xgInfo("Master Volume",a);break;case 5:{let r=127-a;this.setMIDIParameter("gain",r/127),h.xgInfo("Master Attenuation",a);break}case 6:{let r=a-64;this.setMIDIParameter("keyShift",r),h.xgInfo("Master Transpose",a);break}case 127:case 126:h.coolInfo("MIDI System","Yamaha XG"),this.reset("xg");break}return}if(A===2&&s===1){let r,i=n;i<=21?r="Reverb":i<=53?r="Chorus":r="Variation",h.xgFail(`${r} parameter`,[i]);return}if(A===8){let r=s+e;if(r>=this.midiChannels.length){h.xgFail("Part Setup",t,`Invalid part number: ${r}`);return}let i=this.midiChannels[r];switch(n){default:h.xgFail("Part Setup",[t[5]]);break;case 1:i.controllerChange(f.bankSelect,a);break;case 2:i.controllerChange(f.bankSelectLSB,a);break;case 3:i.programChange(a);break;case 4:{let o=a+e;i.setMIDIParameter("rxChannel",o),this.customChannelNumbers||=o!==i.channel,h.xgInfo(`Rev. Channel on ${r}`,o);break}case 5:{let o=a===1;i.setMIDIParameter("polyMode",o),h.xgInfo(`Mono/poly on ${r}`,o?"POLY":"MONO");break}case 7:{let o=a!==0;i.setDrums(o),h.xgInfo(`Part Mode on ${r}`,o?"DRUM":"MELODIC");break}case 8:{let o=a-64;i.keyShift(o);break}case 11:i.controllerChange(f.mainVolume,a);break;case 14:{let o=a,g=o===0;i.setMIDIParameter("randomPan",g),g?h.xgInfo(`Random Pan for ${r}`,"ON"):i.controllerChange(f.pan,o);break}case 18:i.controllerChange(f.chorusDepth,a);break;case 19:i.controllerChange(f.reverbDepth,a);break;case 21:i.controllerChange(f.vibratoRate,a);break;case 22:i.controllerChange(f.vibratoDepth,a);break;case 23:i.controllerChange(f.vibratoDelay,a);break;case 24:i.controllerChange(f.brightness,a);break;case 25:i.controllerChange(f.filterResonance,a);break;case 26:i.controllerChange(f.attackTime,a);break;case 27:i.controllerChange(f.decayTime,a);break;case 28:i.controllerChange(f.releaseTime,a);break;case 35:{let o=a-64;i.pitchWheelRange(o)}}return}if(A>>4===3){if(this.systemParameters.drumLock)return;let r=s;switch(n){default:h.xgFail("Drum Setup",[n]);return;case 0:{let i=(a-64)*100;for(let o of this.midiChannels)o.drumChannel&&(o.drumParams[r].pitch=i);h.xgInfo(`Drum Pitch for key ${r}`,i,"semitones");break}case 1:{let i=a-64;for(let o of this.midiChannels)o.drumChannel&&(o.drumParams[r].pitch+=i,h.xgInfo(`Drum Pitch for key ${r}`,o.drumParams[r].pitch,"semitones"));break}case 2:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].gain=a/120);h.xgInfo(`Drum Level for key ${r}`,a);break;case 3:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].exclusiveClass=a);h.xgInfo(`Drum Alternate Group for key ${r}`,a);break;case 4:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].pan=a);h.xgInfo(`Drum Pan for key ${r}`,a);break;case 5:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].reverbGain=a/127);h.xgInfo(`Drum Reverb for key ${r}`,a);break;case 6:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].chorusGain=a/127);h.xgInfo(`Drum Chorus for key ${r}`,a);break;case 9:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].rxNoteOff=a===1);h.xgInfo(`Drum Note Off for key ${r}`,a===1?"ON":"OFF");break;case 10:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].rxNoteOn=a===1);h.xgInfo(`Drum Note On for key ${r}`,a===1?"ON":"OFF");break}return}if(A===6||A===7){this.callEvent("displayMessage",[...t]);return}h.xgFail("System Exclusive",t,"Unknown address")}else h.xgFail("System Exclusive",t)}function Lr(t,e=0){e+=this.portSelectChannelOffset;let A=t[0];if(!(this.systemParameters.deviceID!==-1&&t[1]!==127&&this.systemParameters.deviceID!==t[1]))switch(A){default:h.unsupported("System Exclusive",t,`Unknown manufacturer: ${A}`);break;case 126:case 127:Mr.call(this,t,e);break;case 65:vr.call(this,t,e);break;case 67:Gr.call(this,t,e);break;case 245:if(t.length<2)return;for(this.portSelectChannelOffset=(t[1]-1)*16;this.midiChannels.length<=this.portSelectChannelOffset;){h.info(`%cPort select, channel offset %c${this.portSelectChannelOffset}%c. Creating a new port!`,d.info,d.value,d.info);for(let s=0;s<16;s++)this.createMIDIChannel(!0)}break}}var Rn=class{sendLevelToReverb=40/127;sendLevelToChorus=0;sendLevelToDelay=0;type=0;reset(){}process(t,e,A,s,n,a,r,i,o){let{sendLevelToReverb:g,sendLevelToChorus:l,sendLevelToDelay:C}=this;for(let B=0;B=1&&(Z-=1);let W=E+I*(1-O*te),_=Math.tan(Math.PI*W/K),$=Math.max(-.9999,Math.min(.9999,(1-_)/(1+_))),ne=x+F*Y,ae=P+F*H;for(let Be=0;Be1e3?(this.manualOffset=ZA*1.5*Ys,this.manual=t):(this.manualOffset=ZA,this.manual=t*Ys)}clearAllPass(){this.prevR=0,this.prevL=0;for(let t=0;t.5?-1:-Math.cos((p-.75)*Js);break;case 2:Y=Math.sin(Js*p);break;case 3:Y=1-2*p;break;case 4:Y=2*p-1;break}(p+=Q)>=1&&(p-=1),D+=(Y-D)*Or;let H=D*M,Z=(1-H)*.5*S,T=(1+H)*.5*S,F=K*B*Z,u=O*B*T,x=i+q;A[x]+=F,s[x]+=u;let P=(F+u)*.5;n[q]+=P*g,a[q]+=P*l,r[q]+=P*C}this.currentPan=D,this.phase=p}setParameter(t,e){switch(t){default:break;case 3:this.modWave=e;break;case 4:this.modRate=ct.rate1(e);break;case 5:this.modDepth=e;break;case 19:this.lowGain=e-64;break;case 20:this.hiGain=e-64;break;case 22:this.level=e/127;break}this.updateShelves()}updateShelves(){Bt(this.lsCoeffs,this.lowGain,200,this.sampleRate,!0),Bt(this.hsCoeffs,this.hiGain,4e3,this.sampleRate,!1)}},Vs=96,qr=.1,Jr=.1,Kr=27,Vr=28,Xr=-28,Zr=400,_r=.62,Wr=.005,Gn=5,Xs=Gn*.5,Ln=class{sendLevelToReverb=40/127;sendLevelToChorus=0;sendLevelToDelay=0;type=289;filType=1;sens=0;manual=68;peak=62;rate=2.05;depth=72;polarity=1;pan=0;lowGain=0;hiGain=0;level=Vs/127;coeffs={...Oe};state={...we};hpCoeffs={...Oe};hpState={...we};phase=0;lsCoeffs={...Oe};hsCoeffs={...Oe};lsState={...we};hsState={...we};sampleRate;lastFc=this.manual;attackCoeff;releaseCoeff;envelope=0;constructor(t){this.sampleRate=t,this.attackCoeff=Math.exp(-1/(qr*t)),this.releaseCoeff=Math.exp(-1/(Jr*t)),this.reset()}reset(){this.filType=1,this.sens=0,this.setManual(68),this.peak=62,this.rate=2.05,this.depth=72,this.polarity=1,this.lowGain=0,this.hiGain=0,this.pan=0,this.level=Vs/127,this.phase=.2,this.lastFc=this.manual,me(this.hsState),me(this.lsState),me(this.state),me(this.hpState),this.updateShelves()}process(t,e,A,s,n,a,r,i,o){let{sendLevelToReverb:g,sendLevelToChorus:l,sendLevelToDelay:C,level:B,lsCoeffs:I,lsState:E,hsCoeffs:m,hsState:k,coeffs:y,state:b,sampleRate:R,filType:M,manual:S,pan:Q,attackCoeff:p,releaseCoeff:D,hpState:q,hpCoeffs:K}=this,{phase:O,lastFc:Y,envelope:H}=this,Z=this.rate/this.sampleRate,T=Math.pow(10,this.peak/127*Vr/20),F=Math.pow(10,this.peak/127*Xr/20),u=this.polarity===0?-1:Gn,x=this.depth/127*u,P=this.sens/127,te=Q+64|0,W=DA[te],_=wA[te];for(let $=0;$H?p*H+(1-p)*ae:D*H+(1-D)*ae;let J=2*Math.abs(O-.5)*x;(O+=Z)>=1&&(O-=1);let ie=J>=Xs||u<0?1:Math.sin(J*Math.PI/(2*Xs)),pe=S*(1+P*H*Kr),ve=Math.max(20,pe*(1+ie*J));Y+=(Math.max(10,ve)-Y)*Wr,zr(y,Y,T,R);let Be=ne;M===1&&($r(K,Zr,F,R),Be=rt(Be,K,q));let be=rt(Be,y,b)*B,xe=be*W,ht=be*_,lt=i+$;A[lt]+=xe,s[lt]+=ht,n[$]+=be*g,a[$]+=be*l,r[$]+=be*C}this.phase=O,this.lastFc=Y,this.envelope=H}setParameter(t,e){switch(t){default:break;case 3:this.filType=e;break;case 4:this.sens=e;break;case 5:this.setManual(e);break;case 6:this.peak=e;break;case 7:this.rate=ct.rate1(e);break;case 8:this.depth=e;break;case 9:this.polarity=e;break;case 19:this.lowGain=e-64;break;case 20:this.hiGain=e-64;break;case 21:this.pan=e-64;break;case 22:this.level=e/127;break}this.updateShelves()}setManual(t){let e=t*_r,A=ct.manual(Math.floor(e)),s=ct.manual(Math.ceil(e)),n=e-Math.floor(e);this.manual=A+(s-A)*n}updateShelves(){Bt(this.lsCoeffs,this.lowGain,200,this.sampleRate,!0),Bt(this.hsCoeffs,this.hiGain,4e3,this.sampleRate,!1)}};function zr(t,e,A,s){let n=2*Math.PI*e/s,a=Math.cos(n),r=Math.sin(n)/(2*A),i=1-a,o=i/2,g=o,l=1+r,C=-2*a,B=1-r;t.a0=1,t.a1=C/l,t.a2=B/l,t.b0=o/l,t.b1=i/l,t.b2=g/l}function $r(t,e,A,s){let n=2*Math.PI*e/s,a=Math.cos(n),r=Math.sin(n)/(2*A),i=(1+a)/2,o=-(1+a),g=i,l=1+r,C=-2*a,B=1-r;t.a0=1,t.a1=C/l,t.a2=B/l,t.b0=i/l,t.b1=o/l,t.b2=g/l}var Zs=127,jr=class{sendLevelToReverb=40/127;sendLevelToChorus=0;sendLevelToDelay=0;type=4360;phPan=0;awPan=127;level=Zs/127;phaser;autoWah;bufferPh;bufferAw;constructor(t,e){this.phaser=new vn(t),this.autoWah=new Ln(t),this.bufferAw=new Float32Array(e),this.bufferPh=new Float32Array(e),this.phaser.sendLevelToReverb=0,this.phaser.sendLevelToChorus=0,this.phaser.sendLevelToDelay=0,this.autoWah.sendLevelToReverb=0,this.autoWah.sendLevelToChorus=0,this.autoWah.sendLevelToDelay=0,this.reset()}reset(){this.phPan=0,this.awPan=127,this.level=Zs/127,this.phaser.reset(),this.autoWah.reset(),this.phaser.setParameter(22,127),this.autoWah.setParameter(22,127)}process(t,e,A,s,n,a,r,i,o){let{sendLevelToReverb:g,sendLevelToChorus:l,sendLevelToDelay:C,level:B}=this,{bufferPh:I,bufferAw:E}=this;this.bufferPh.fill(0),this.phaser.process(t,t,I,I,I,I,I,0,o),this.bufferAw.fill(0),this.autoWah.process(e,e,E,E,E,E,E,0,o);let m=this.phPan|0,k=DA[m],y=wA[m],b=this.awPan|0,R=DA[b],M=wA[b];for(let S=0;S=3&&t<=7){this.phaser.setParameter(t,e);return}if(t>=8&&t<=14){this.autoWah.setParameter(t-5,e);return}switch(t){default:break;case 18:this.phPan=e;break;case 19:this.phaser.setParameter(22,e);break;case 20:this.awPan=e;break;case 21:this.autoWah.setParameter(22,e);break;case 22:this.level=e/127;break}}},_s=127,Ws=Math.PI*2,ei=.01,ti=class{sendLevelToReverb=40/127;sendLevelToChorus=0;sendLevelToDelay=0;type=293;modWave=1;modRate=3.05;modDepth=96;lowGain=0;hiGain=0;level=_s/127;phase=0;currentGain=1;lsCoeffs={...Oe};hsCoeffs={...Oe};lsStateR={...we};lsStateL={...we};hsStateR={...we};hsStateL={...we};sampleRate;constructor(t){this.sampleRate=t,this.reset()}reset(){this.modWave=1,this.modRate=3.05,this.modDepth=96,this.lowGain=0,this.hiGain=0,this.level=_s/127,this.phase=0,this.currentGain=1,me(this.hsStateR),me(this.hsStateL),me(this.lsStateR),me(this.lsStateL),this.updateShelves()}process(t,e,A,s,n,a,r,i,o){let{sendLevelToReverb:g,sendLevelToChorus:l,sendLevelToDelay:C,level:B,lsCoeffs:I,lsStateL:E,lsStateR:m,hsCoeffs:k,hsStateR:y,hsStateL:b,modDepth:R,modWave:M}=this,S=this.modRate/this.sampleRate,{currentGain:Q,phase:p}=this;for(let D=0;D.5?-1:-Math.cos((p-.75)*Ws);break;case 2:O=Math.sin(Ws*p);break;case 3:O=1-2*p;break;case 4:O=2*p-1;break}(p+=S)>=1&&(p-=1);let Y=1-(O/2+.5)*(R/127);Q+=(Y-Q)*ei;let H=q*B*Q,Z=K*B*Q,T=i+D;A[T]+=H,s[T]+=Z;let F=(H+Z)*.5;n[D]+=F*g,a[D]+=F*l,r[D]+=F*C}this.phase=p,this.currentGain=Q}setParameter(t,e){switch(t){default:break;case 3:this.modWave=e;break;case 4:this.modRate=ct.rate1(e);break;case 5:this.modDepth=e;break;case 19:this.lowGain=e-64;break;case 20:this.hiGain=e-64;break;case 22:this.level=e/127;break}this.updateShelves()}updateShelves(){Bt(this.lsCoeffs,this.lowGain,200,this.sampleRate,!0),Bt(this.hsCoeffs,this.hiGain,4e3,this.sampleRate,!1)}},Ai=[Rn,Nr,vn,Yr,Ln,jr,ti],si=class{preDelay=0;preLPF=.5;inputDiffusion1=.75;inputDiffusion2=.625;decay=.5;decayDiffusion1=.7;decayDiffusion2=.5;damping=.005;excursionRate=.1;excursionDepth=.2;gain=1;sampleRate;lp1=0;lp2=0;lp3=0;excPhase=0;pDWrite=0;taps;pDelay;pDLength;delays=new Array;constructor(t){this.sampleRate=t,this.pDLength=t,this.pDelay=new Float32Array(this.pDLength);for(let e of[.004771345,.003595309,.012734787,.009307483,.022579886,.149625349,.060481839,.1249958,.030509727,.141695508,.089244313,.106280031])this.makeDelayLine(e);this.taps=Int16Array.from([.008937872,.099929438,.064278754,.067067639,.066866033,.006283391,.035818689,.011861161,.121870905,.041262054,.08981553,.070931756,.011256342,.004065724],e=>Math.round(e*this.sampleRate))}process(t,e,A,s,n){let a=this.preDelay|0,r=this.inputDiffusion1,i=this.inputDiffusion2,o=this.decay,g=this.decayDiffusion1,l=this.decayDiffusion2,C=1-this.damping,B=this.excursionRate/this.sampleRate,I=this.excursionDepth*this.sampleRate/1e3,E=this.pDWrite;for(let m=0;m=r&&(s=0)}this.writeIndex=s}},ni=1.5,ai=class{dattorro;delayLeft;delayRight;delayLeftOutput;delayRightOutput;delayLeftInput;delayPreLPF;sampleRate;preLPFfc=8e3;preLPFa=0;preLPFz=0;characterTimeCoefficient=1;characterGainCoefficient=1;characterLPFCoefficient=0;delayGain=1;panDelayFeedback=0;constructor(t,e){this.sampleRate=t,this.delayLeftOutput=new Float32Array(e),this.delayRightOutput=new Float32Array(e),this.delayLeftInput=new Float32Array(e),this.delayPreLPF=new Float32Array(e),this.dattorro=new si(t),this.delayLeft=new Xt(t),this.delayRight=new Xt(t)}_delayFeedback=0;get delayFeedback(){return this._delayFeedback}set delayFeedback(t){this._delayFeedback=t,this.updateFeedback()}_character=0;get character(){return this._character}set character(t){switch(this._character=t,this.dattorro.damping=.005,this.characterTimeCoefficient=1,this.characterGainCoefficient=1,this.characterLPFCoefficient=0,this.dattorro.inputDiffusion1=.75,this.dattorro.inputDiffusion2=.625,this.dattorro.decayDiffusion1=.7,this.dattorro.decayDiffusion2=.5,this.dattorro.excursionRate=.5,this.dattorro.excursionDepth=.7,t){case 0:this.dattorro.damping=.85,this.characterTimeCoefficient=.9,this.characterGainCoefficient=.9,this.characterLPFCoefficient=.2;break;case 1:this.dattorro.damping=.2,this.characterGainCoefficient=.7,this.characterTimeCoefficient=1,this.dattorro.decayDiffusion2=.64,this.dattorro.decayDiffusion1=.6,this.characterLPFCoefficient=.2;break;case 2:this.dattorro.damping=.56,this.characterGainCoefficient=.75,this.characterTimeCoefficient=1,this.dattorro.decayDiffusion2=.64,this.dattorro.decayDiffusion1=.6,this.characterLPFCoefficient=.1;break;case 3:this.dattorro.damping=.3,this.characterGainCoefficient=1.25,this.characterTimeCoefficient=1.3,this.characterLPFCoefficient=0,this.dattorro.decayDiffusion2=.7,this.dattorro.decayDiffusion1=.66;break;case 4:this.characterGainCoefficient=1,this.characterTimeCoefficient=1.2,this.characterLPFCoefficient=.1,this.dattorro.damping=.1,this.dattorro.decayDiffusion2=.69,this.dattorro.decayDiffusion1=.67;break;case 5:this.characterGainCoefficient=.75,this.dattorro.damping=.65,this.characterTimeCoefficient=.5;break}this.updateTime(),this.updateGain(),this.updateLowpass(),this.updateFeedback(),this.delayLeft.clear(),this.delayRight.clear()}_time=0;get time(){return this._time}set time(t){this._time=t,this.updateTime()}_preDelayTime=0;get preDelayTime(){return this._preDelayTime}set preDelayTime(t){this._preDelayTime=t,this.dattorro.preDelay=t/1e3*this.sampleRate}_level=0;get level(){return this._level}set level(t){this._level=t,this.updateGain()}_preLowpass=0;get preLowpass(){return this._preLowpass}set preLowpass(t){this._preLowpass=t,this.preLPFfc=8e3*.63**this._preLowpass;let e=Math.exp(-2*Math.PI*this.preLPFfc/this.sampleRate);this.preLPFa=1-e,this.updateLowpass()}process(t,e,A,s,n){switch(this._character){default:this.dattorro.process(t,e,A,s,n);return;case 6:{let a;if(this._preLowpass>0){let o=this.delayPreLPF,g=this.preLPFz,l=this.preLPFa;for(let C=0;C0){let C=this.delayPreLPF,B=this.preLPFz,I=this.preLPFa;for(let E=0;E0,b=this.phase,R=this.write,M=this.preLPFz,S=this.preLPFa;for(let Q=0;Q=l&&(Y-=l);let H=K-O,Z=i[O]*(1-H)+i[Y]*H;i[R]=p+Z*k;let T=Math.max(1,Math.min(B+(1-D)*C,l)),F=R-T;F<0&&(F+=l),O=F|0,Y=O+1,Y>=l&&(Y-=l),H=F-O;let u=o[O]*(1-H)+o[Y]*H,x=Q+a;e[x]+=Z*I,A[x]+=u*I;let P=(Z+u)/2;s[Q]+=P*E,n[Q]+=P*m,o[R]=p+u*k,++R>=l&&(R=0),(b+=g)>=1&&(b-=1)}this.write=R,this.phase=b,this.preLPFz=M}getSnapshot(){return{preLowpass:this._preLowpass,depth:this._depth,delay:this._delay,sendLevelToDelay:this._sendLevelToDelay,sendLevelToReverb:this._sendLevelToReverb,rate:this._rate,feedback:this._feedback,level:this._level}}},oi=[{start:1,end:20,timeStart:.1,resolution:.1},{start:20,end:35,timeStart:2,resolution:.2},{start:35,end:45,timeStart:5,resolution:.5},{start:45,end:55,timeStart:10,resolution:1},{start:55,end:70,timeStart:20,resolution:2},{start:70,end:80,timeStart:50,resolution:5},{start:80,end:90,timeStart:100,resolution:10},{start:90,end:105,timeStart:200,resolution:20},{start:105,end:116,timeStart:500,resolution:50}],gi=1.66,Ii=class{preLPFfc=8e3;preLPFa=0;preLPFz=0;delayLeft;delayRight;delayCenter;sampleRate;delayCenterOutput;delayPreLPF;delayCenterTime;delayLeftMultiplier=.04;delayRightMultiplier=.04;gain=0;reverbGain=0;constructor(t,e){this.sampleRate=t,this.delayCenterOutput=new Float32Array(e),this.delayPreLPF=new Float32Array(e),this.delayCenterTime=.34*t,this.delayCenter=new Xt(t),this.delayLeft=new Xt(t),this.delayRight=new Xt(t)}_sendLevelToReverb=0;get sendLevelToReverb(){return this._sendLevelToReverb}set sendLevelToReverb(t){this._sendLevelToReverb=t,this.reverbGain=t/127}_preLowpass=0;get preLowpass(){return this._preLowpass}set preLowpass(t){this._preLowpass=t,this.preLPFfc=8e3*.63**this._preLowpass;let e=Math.exp(-2*Math.PI*this.preLPFfc/this.sampleRate);this.preLPFa=1-e}_levelRight=0;get levelRight(){return this._levelRight}set levelRight(t){this._levelRight=t,this.updateGain()}_level=64;get level(){return this._level}set level(t){this._level=t,this.gain=t/127*gi}_levelCenter=127;get levelCenter(){return this._levelCenter}set levelCenter(t){this._levelCenter=t,this.updateGain()}_levelLeft=0;get levelLeft(){return this._levelLeft}set levelLeft(t){this._levelLeft=t,this.updateGain()}_feedback=16;get feedback(){return this._feedback}set feedback(t){this._feedback=t,this.delayLeft.feedback=this.delayRight.feedback=0,this.delayCenter.feedback=(t-64)/66}_timeRatioRight=0;get timeRatioRight(){return this._timeRatioRight}set timeRatioRight(t){this._timeRatioRight=t,this.delayRightMultiplier=t*(100/2400),this.delayRight.time=this.delayCenterTime*this.delayRightMultiplier}_timeRatioLeft=0;get timeRatioLeft(){return this._timeRatioLeft}set timeRatioLeft(t){this._timeRatioLeft=t,this.delayLeftMultiplier=t*(100/2400),this.delayLeft.time=this.delayCenterTime*this.delayLeftMultiplier}_timeCenter=12;get timeCenter(){return this._timeCenter}set timeCenter(t){this._timeCenter=t;let e=.1;for(let A of oi)if(t>=A.start&&t0){let C=this.delayPreLPF,B=this.preLPFz,I=this.preLPFa;for(let E=0;Ethis.currentTime?(this.eventQueue.push({message:t,channelOffset:e,time:s}),this.eventQueue.sort((n,a)=>n.time-a.time)):this.processMessageInternal(t,e)}destroySynthProcessor(){this.voices.length=0;for(let t of this.midiChannels)t.destroy();this.clearCache(),this.midiChannels.length=0,this.soundBankManager.destroy()}getVoices(t,e,A){let s=this.midiChannels[t],n=this.keyModifierManager.hasOverridePatch(t,e),a=s.preset;if(n){let r=this.keyModifierManager.getPatch(t,e);a=this.soundBankManager.getPreset(r,this.midiParameters.system)}return a?this.getVoicesForPreset(a,e,A):[]}createMIDIChannel(t){let e=new br(this,this.defaultPreset,this.midiChannels.length);this.midiChannels.push(e),t&&(this.callEvent("channelAdded",void 0),e.setDrums(!0))}reset(t="gs"){if(this.callEvent("reset",t),this.resetMIDIParameters(t),this.tunings.fill(-1),this.portSelectChannelOffset=0,this.customChannelNumbers=!1,this.setReverbMacro(4),this.setChorusMacro(2),this.setDelayMacro(0),this.systemParameters.delayLock||(this.delayActive=!1),this.resetInsertion(),!(!this.drumPreset||!this.defaultPreset))for(let e of this.midiChannels)e.reset(!1)}process(t,e,A=0,s=0){this.processSplit([[t,e]],t,e,A,s)}processSplit(t,e,A,s=0,n=0){if(this.eventQueue.length>0){let o=this.currentTime;for(;this.eventQueue[0]?.time<=o;){let g=this.eventQueue.shift();g&&this.processMessageInternal(g.message,g.channelOffset)}}s=Math.max(s,0);let a=n||t[0][0].length-s;if(a>this.maxBufferSize)throw new Error(`Requested ${a} samples, but maxBufferSize is ${this.maxBufferSize}`);this.reverbInput.fill(0),this.chorusInput.fill(0),this.delayActive&&this.delayInput.fill(0),this.insertionActive&&(this.insertionInputL.fill(0),this.insertionInputR.fill(0));for(let o of this.midiChannels)o.clearVoiceCount();this._voiceCount=0;let r=this.systemParameters.voiceCap,i=t.length;for(let o=0;ot.midiParameters.efxAssign)}}resetInsertionParams(){this.insertionParams.fill(255),this.insertionParams[20]=40,this.insertionParams[21]=0,this.insertionParams[22]=0}resetInsertion(){this.systemParameters.insertionEffectLock||(this.insertionActive=!1,this.insertionProcessor=this.insertionFallback,this.insertionProcessor.reset(),this.insertionProcessor.sendLevelToReverb=40/127*hA,this.insertionProcessor.sendLevelToChorus=0,this.insertionProcessor.sendLevelToDelay=0,this.resetInsertionParams(),this.callEvent("effectChange",{effect:"insertion",parameter:0,value:this.insertionProcessor.type}))}setReverbMacro(t){if(this.systemParameters.reverbLock)return;let e=this.reverbProcessor;switch(e.level=64,e.preDelayTime=0,e.character=t,t){case 0:e.character=0,e.preLowpass=3,e.time=80,e.delayFeedback=0,e.preDelayTime=0;break;case 1:e.preLowpass=4,e.time=56,e.delayFeedback=0;break;case 2:e.preLowpass=0,e.time=72,e.delayFeedback=0;break;case 3:e.preLowpass=4,e.time=72,e.delayFeedback=0;break;case 4:e.preLowpass=0,e.time=64,e.delayFeedback=0;break;case 5:e.preLowpass=0,e.time=88,e.delayFeedback=0;break;case 6:e.preLowpass=0,e.time=32,e.delayFeedback=40;break;case 7:e.preLowpass=0,e.time=64,e.delayFeedback=32;break;default:h.warn(`Invalid reverb macro: ${t}`);return}this.callEvent("effectChange",{effect:"reverb",parameter:"macro",value:t})}setChorusMacro(t){if(this.systemParameters.chorusLock)return;let e=this.chorusProcessor;switch(e.level=64,e.preLowpass=0,e.delay=127,e.sendLevelToDelay=0,e.sendLevelToReverb=0,t){case 0:e.feedback=0,e.delay=112,e.rate=3,e.depth=5;break;case 1:e.feedback=5,e.delay=80,e.rate=9,e.depth=19;break;case 2:e.feedback=8,e.delay=80,e.rate=3,e.depth=19;break;case 3:e.feedback=16,e.delay=64,e.rate=9,e.depth=16;break;case 4:e.feedback=64,e.delay=127,e.rate=2,e.depth=24;break;case 5:e.feedback=112,e.delay=127,e.rate=1,e.depth=5;break;case 6:e.feedback=0,e.depth=127,e.rate=0,e.depth=127;break;case 7:e.feedback=80,e.depth=127,e.rate=0,e.depth=127;break;default:h.warn(`Invalid chorus macro: ${t}`);return}this.callEvent("effectChange",{effect:"chorus",parameter:"macro",value:t})}setDelayMacro(t){if(this.systemParameters.delayLock)return;let e=this.delayProcessor;switch(e.level=64,e.preLowpass=0,e.sendLevelToReverb=0,e.levelRight=e.levelLeft=0,e.levelCenter=127,t){case 0:e.timeCenter=97,e.timeRatioRight=e.timeRatioLeft=1,e.feedback=80;break;case 1:e.timeCenter=106,e.timeRatioRight=e.timeRatioLeft=1,e.feedback=80;break;case 2:e.timeCenter=115,e.timeRatioRight=e.timeRatioLeft=1,e.feedback=72;break;case 3:e.timeCenter=83,e.timeRatioRight=e.timeRatioLeft=1,e.feedback=72;break;case 4:e.timeCenter=105,e.timeRatioLeft=12,e.timeRatioRight=24,e.levelCenter=0,e.levelLeft=125,e.levelRight=60,e.feedback=74;break;case 5:e.timeCenter=109,e.timeRatioLeft=12,e.timeRatioRight=24,e.levelCenter=0,e.levelLeft=125,e.levelRight=60,e.feedback=71;break;case 6:e.timeCenter=115,e.timeRatioLeft=12,e.timeRatioRight=24,e.levelCenter=0,e.levelLeft=120,e.levelRight=64,e.feedback=73;break;case 7:e.timeCenter=93,e.timeRatioLeft=12,e.timeRatioRight=24,e.levelCenter=0,e.levelLeft=120,e.levelRight=64,e.feedback=72;break;case 8:e.timeCenter=109,e.timeRatioLeft=12,e.timeRatioRight=24,e.levelCenter=0,e.levelLeft=114,e.levelRight=60,e.feedback=61,e.sendLevelToReverb=36;break;case 9:e.timeCenter=110,e.timeRatioLeft=21,e.timeRatioRight=32,e.levelCenter=97,e.levelLeft=127,e.levelRight=67,e.feedback=40;break;default:h.warn(`Invalid delay macro: ${t}`);return}this.callEvent("effectChange",{effect:"delay",parameter:"macro",value:t})}getCachedVoice(t,e,A){return this.cachedVoices.get(this.getCachedVoiceIndex(t,e,A))}setCachedVoice(t,e,A,s){this.cachedVoices.set(this.getCachedVoiceIndex(t,e,A),s)}allocateNewVoices(t){for(let e=0;e=128&&A<240?(s=A&240,n=A&15):s=A,n+=e,s){case G.noteOn:{let a=t[2];a>0?this.noteOn(n,t[1],a):this.noteOff(n,t[1]);break}case G.noteOff:this.noteOff(n,t[1]);break;case G.pitchWheel:this.pitchWheel(n,t[2]<<7|t[1]);break;case G.controllerChange:this.controllerChange(n,t[1],t[2]);break;case G.programChange:this.programChange(n,t[1]);break;case G.polyPressure:this.polyPressure(n,t[1],t[2]);break;case G.channelPressure:this.channelPressure(n,t[1]);break;case G.systemExclusive:this.systemExclusive(new ee(t.slice(1)),e);break;case G.reset:this.stopAllChannels(!1),this.reset();break;default:break}}assignVoicePriorities(){if(this.lastPriorityAssignmentTime===this.currentTime)return;h.info("%cPolyphony exceeded, stealing voices",d.warn),this.lastPriorityAssignmentTime=this.currentTime;let t=this.systemParameters.voiceCap;for(let e=0;e{h.info("%cSpessaSynth is ready!",d.recognized)})}get midiChannels(){return this.synthCore.midiChannels}get midiParameters(){return this.synthCore.midiParameters}get systemParameters(){return this.synthCore.systemParameters}get voiceCount(){return this.synthCore.voiceCount}get currentTime(){return this.synthCore.currentTime}get reverbProcessor(){return this.synthCore.reverbProcessor}get chorusProcessor(){return this.synthCore.chorusProcessor}get delayProcessor(){return this.synthCore.delayProcessor}get soundBankManager(){return this.synthCore.soundBankManager}get keyModifierManager(){return this.synthCore.keyModifierManager}onMissingPreset=(t,e)=>{h.warn(`No preset found for ${ze.toMIDIString(t)}! Did you forget to add a sound bank?`)};setSystemParameter(t,e){this.synthCore.setSystemParameter(t,e)}reset(){this.synthCore.reset()}applySnapshot(t){this.savedSnapshot=t,ba.call(this.synthCore,t),this.reset()}getSnapshot(){return Ra.call(this.synthCore)}setEmbeddedSoundBank(t,e){let A=$t.fromArrayBuffer(t);this.synthCore.soundBankManager.addSoundBank(A,nA,e);let s=this.synthCore.soundBankManager.priorityOrder;s.pop(),s.unshift(nA),this.synthCore.soundBankManager.priorityOrder=s,this.savedSnapshot!==void 0&&this.applySnapshot(this.savedSnapshot),h.info(`%cEmbedded sound bank set at offset %c${e}`,d.recognized,d.value)}clearEmbeddedSoundBank(){this.synthCore.soundBankManager.soundBankList.some(t=>t.id===nA)&&this.synthCore.soundBankManager.deleteSoundBank(nA)}createMIDIChannel(){this.synthCore.createMIDIChannel(!0)}stopAllChannels(t=!1){this.synthCore.stopAllChannels(t)}destroySynthProcessor(){this.synthCore.destroySynthProcessor()}clearCache(){this.synthCore.clearCache()}getVoicesForPreset(t,e,A){return this.synthCore.getVoicesForPreset(t,e,A)}callEvent(t,e){this.onEventCall?.({type:t,data:e})}missingPreset(t,e){return this.onMissingPreset(t,e)}};var vA=tn.ConsoleColors;var Pn="spessasynth-worklet-processor";function Tn(t,e){return{...e,...t}}var Un={skipToFirstNoteOn:!0,initialPlaybackRate:1};var ps=class extends RA{events=[];constructor(e){super(),super.copyFrom(e),this.events=[]}},GA=class t extends Dt{tracks;timeline=[];embeddedSoundBank=void 0;embeddedSoundBankSize;constructor(e){super(),super.copyMetadataFrom(e),this.tracks=e.tracks.map(A=>new ps(A)),this.embeddedSoundBankSize=e instanceof t?e.embeddedSoundBankSize:e?.embeddedSoundBank?.byteLength}};var LA={shuffleOn:1,shuffleOff:2,index:3};var xn=-1;var Hn=1,NA=class{synthesizer;sequencers=new Array;post;lastSequencerSync=0;voiceCounts=new Array(16).fill(0);alive=!1;eventsEnabled;constructor(e,A,s){this.synthesizer=new Nn(e,A),this.eventsEnabled=A.eventsEnabled??!1,this.post=s,this.synthesizer.onEventCall=n=>{if(n.type==="channelAdded"){let a=this.synthesizer.midiChannels.length;for(let r=this.voiceCounts.length;r{if(this.eventsEnabled){if(s.type==="songListChange"){let a=s.data.newSongList.map(r=>new GA(r));this.post({type:"sequencerReturn",data:{type:s.type,data:{newSongList:a,shuffledSongIndexes:e.shuffledSongIndexes},id:A},currentTime:this.synthesizer.currentTime});return}this.post({type:"sequencerReturn",data:{...s,id:A},currentTime:this.synthesizer.currentTime})}}}postReady(e,A,s=[]){this.post({type:"isFullyInitialized",data:{type:e,data:A},currentTime:this.synthesizer.currentTime},s)}postProgress(e,A){this.post({type:"renderingProgress",data:{type:e,data:A},currentTime:this.synthesizer.currentTime})}destroy(){this.synthesizer.destroySynthProcessor(),delete this.synthesizer,delete this.sequencers}handleMessage(e){let A=e.channelNumber,s;if(A>=0&&(s=this.synthesizer.midiChannels[A],s===void 0)){h.warn(`Trying to access channel ${A} which does not exist... ignoring!`);return}switch(e.type){case"midiMessage":{this.synthesizer.processMessage(e.data.messageData,e.data.channelOffset,e.data.options);break}case"ccReset":{this.synthesizer.reset();break}case"stopAll":{A===xn?this.synthesizer.stopAllChannels(e.data===1):s?.stopAllNotes(e.data===1);break}case"addNewChannel":{this.synthesizer.createMIDIChannel();break}case"setGlobalSystemParameter":{this.synthesizer.setSystemParameter(e.data.type,e.data.data);break}case"setChannelSystemParameter":{s?.setSystemParameter(e.data.type,e.data.data);break}case"setDrums":{s?.setDrums(e.data);break}case"lockController":{s?.lockController(e.data.controller,e.data.isLocked);break}case"sequencerSpecific":{let n=this.sequencers[e.data.id];if(!n)return;let a=e.data;switch(a.type){default:break;case"loadNewSongList":{try{let i=a.data.map(o=>"duration"in o?Dt.copyFrom(o):Dt.fromArrayBuffer(o.binary,o.fileName));n.loadNewSongList(i)}catch(r){console.error(r),this.post({type:"sequencerReturn",data:{type:"midiError",data:r,id:e.data.id},currentTime:this.synthesizer.currentTime})}break}case"pause":{n.pause();break}case"play":{n.play();break}case"setTime":{n.currentTime=a.data;break}case"changeMIDIMessageSending":{n.externalMIDIPlayback=a.data;break}case"setPlaybackRate":{n.playbackRate=a.data;break}case"setLoopCount":{n.loopCount=a.data;break}case"changeSong":{switch(a.data.changeType){case LA.shuffleOff:{n.shuffleMode=!1;break}case LA.shuffleOn:{n.shuffleMode=!0;break}case LA.index:{a.data.data!==void 0&&(n.songIndex=a.data.data);break}}break}case"getMIDI":{if(!n.midiData)throw new Error("No MIDI is loaded!");this.post({type:"sequencerReturn",data:{type:"getMIDI",data:n.midiData,id:e.data.id},currentTime:this.synthesizer.currentTime});break}case"setSkipToFirstNote":{n.skipToFirstNoteOn=a.data;break}}break}case"soundBankManager":{try{let n=this.synthesizer.soundBankManager,a=e.data,r;switch(a.type){case"addSoundBank":{r=$t.fromArrayBuffer(a.data.soundBankBuffer),n.addSoundBank(r,a.data.id,a.data.bankOffset),this.postReady("soundBankManager",null);break}case"deleteSoundBank":{n.deleteSoundBank(a.data),this.postReady("soundBankManager",null);break}case"rearrangeSoundBanks":n.priorityOrder=a.data,this.postReady("soundBankManager",null)}}catch(n){this.post({type:"soundBankError",data:n,currentTime:this.synthesizer.currentTime})}break}case"keyModifierManager":{let n=e.data,a=this.synthesizer.keyModifierManager;switch(n.type){default:return;case"addMapping":{a.addMapping(n.data.channel,n.data.midiNote,n.data.mapping);break}case"clearMappings":{a.clearMappings();break}case"deleteMapping":a.deleteMapping(n.data.channel,n.data.midiNote)}break}case"requestSynthesizerSnapshot":{let n=this.synthesizer.getSnapshot();this.postReady("synthesizerSnapshot",n);break}case"requestNewSequencer":{this.createNewSequencer();break}case"setLogLevel":{h.setLogLevel(e.data.enableInfo,e.data.enableWarning,e.data.enableGroup);break}case"destroyWorklet":{this.alive=!1,this.synthesizer.destroySynthProcessor(),this.destroy();break}default:{h.warn("Unrecognized event!",e);break}}}};var PA=class extends NA{alive=!0;oneOutputMode;port;constructor(e,A,s,n){super(e,{effectsEnabled:!n.oneOutput,eventsEnabled:n?.eventsEnabled,initialTime:A},(a,r)=>{s.postMessage(a,r)}),this.port=s,this.oneOutputMode=n.oneOutput,this.synthesizer.processorInitialized.then(()=>{this.port.onmessage=a=>this.handleMessage(a.data),this.postReady("sf3Decoder",null)})}process(e,A){if(!this.alive)return!1;for(let i of this.sequencers)i.processTick();if(this.oneOutputMode){let i=A[0],o=[];for(let g=0;g<32;g+=2)o.push([i[g],i[g+1]]);this.synthesizer.setSystemParameter("effectsEnabled",!1),this.synthesizer.processSplit(o,i[0],i[0])}else this.synthesizer.processSplit(A.slice(1),A[0][0],A[0][1]);let s=this.synthesizer.currentTime;if(this.eventsEnabled&&s-this.lastSequencerSync>Hn){for(let i=0;i import { WorkletSynthesizer } from 'https://esm.sh/spessasynth_lib@4.3.1'; window.SpessaSynthClass = WorkletSynthesizer; - window.__SpessaSynthCDN = 'https://cdn.jsdelivr.net/npm/spessasynth_lib@4.3.1/dist/'; + window.__SpessaSynthCDN = '/static/js/services/'; console.log('[SonicSF] SpessaSynth library loaded via esm.sh.');