(()=>{function ts(A,e,t=0){let s=0;for(let a=0;a>>0}function As(A,e){let t=ss(A,e,A.currentIndex);return A.currentIndex+=e,t}function ss(A,e,t=0){let s=0n;for(let a=0;a>>0}function mA(A,e,t){for(let s=0;s>s*8&255}function G(A,e){A[A.currentIndex++]=e&255,A[A.currentIndex++]=e>>8}function Y(A,e){mA(A,e,4)}function Nt(A,e){let t=BigInt(e);for(let s=0n;s<8n;s++)A[A.currentIndex++]=Number(t>>s*8n&255n)}function as(A,e){let t=e<<8|A;return t>32767?t-65536:t}var K=class extends Uint8Array{currentIndex=0;slice(A,e){let t=super.slice(A,e);return t.currentIndex=0,t}};function zt(A,e=A.length,t=0){let s="";for(let a=0;a0&&e.length>t&&(e=e.slice(0,t));for(let s=0;se.length)for(let s=0;s>7!==1)break}return e}function rs(A){let e="";for(let t=0;t{var A=Uint8Array,e=Uint16Array,t=Int32Array,s=new A([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]),a=new A([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]),i=new A([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o=function(k,v){for(var L=new e(31),J=0;J<31;++J)L[J]=v+=1<>1|(y&21845)<<1,r=(r&52428)>>2|(r&13107)<<2,r=(r&61680)>>4|(r&3855)<<4,p[y]=((r&65280)>>8|(r&255)<<8)>>1;var r,y,B=function(k,v,L){for(var J=k.length,H=0,ve=new e(v);H>Pe]=We}else for(Se=new e(J),H=0;H>15-k[H]);return Se},M=new A(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,T=new A(32);for(y=0;y<32;++y)T[y]=5;var y,$=B(M,9,1),F=B(T,5,1),Z=function(k){for(var v=k[0],L=1;Lv&&(v=k[L]);return v},N=function(k,v,L){var J=v/8|0;return(k[J]|k[J+1]<<8)>>(v&7)&L},q=function(k,v){var L=v/8|0;return(k[L]|k[L+1]<<8|k[L+2]<<16)>>(v&7)},ce=function(k){return(k+7)/8|0},j=function(k,v,L){return(v==null||v<0)&&(v=0),(L==null||L>k.length)&&(L=k.length),new A(k.subarray(v,L))},ee=["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"],V=function(k,v,L){var J=new Error(v||ee[k]);if(J.code=k,Error.captureStackTrace&&Error.captureStackTrace(J,V),!L)throw J;return J},ae=function(k,v,L,J){var H=k.length,ve=J?J.length:0;if(!H||v.f&&!v.l)return L||new A(0);var ye=!L,Se=ye||v.i!=2,Pe=v.i;ye&&(L=new A(H*3));var We=function(_){var W=L.length;if(_>W){var Ee=new A(Math.max(W*2,_));Ee.set(L),L=Ee}},ke=v.f||0,b=v.p||0,te=v.b||0,De=v.l,Ze=v.d,Je=v.m,_e=v.n,at=H*8;do{if(!De){ke=N(k,b,1);var nt=N(k,b+1,3);if(b+=3,nt)if(nt==1)De=$,Ze=F,Je=9,_e=5;else if(nt==2){var Ct=N(k,b,31)+257,mt=N(k,b+10,15)+4,pt=Ct+N(k,b+5,31)+1;b+=14;for(var ue=new A(pt),ze=new A(19),ge=0;ge>4;if(we<16)ue[ge++]=we;else{var Ue=0,Ke=0;for(we==16?(Ke=3+N(k,b,3),b+=2,Ue=ue[ge-1]):we==17?(Ke=3+N(k,b,7),b+=3):we==18&&(Ke=11+N(k,b,127),b+=7);Ke--;)ue[ge++]=Ue}}var it=ue.subarray(0,Ct),Qe=ue.subarray(Ct);Je=Z(it),_e=Z(Qe),De=B(it,Je,1),Ze=B(Qe,_e,1)}else V(1);else{var we=ce(b)+4,$e=k[we-4]|k[we-3]<<8,Me=we+$e;if(Me>H){Pe&&V(0);break}Se&&We(te+$e),L.set(k.subarray(we,Me),te),v.b=te+=$e,v.p=b=Me*8,v.f=ke;continue}if(b>at){Pe&&V(0);break}}Se&&We(te+131072);for(var C=(1<>4;if(b+=Ue&15,b>at){Pe&&V(0);break}if(Ue||V(2),w<256)L[te++]=w;else if(w==256){E=b,De=null;break}else{var x=w-254;if(w>264){var ge=w-257,X=s[ge];x=N(k,b,(1<>4;Ae||V(3),b+=Ae&15;var Qe=Q[R];if(R>3){var X=a[R];Qe+=q(k,b)&(1<at){Pe&&V(0);break}Se&&We(te+131072);var Ce=te+x;if(tel.length+f,0);a&&(o+=4,i="LIST");let h;s?(h=new K(8),Nt(h,o)):(h=new K(4),Y(h,o));let g=[Xe(i),h];return a&&g.push(Xe(e)),g.push(...t),o%2!==0&&g.push(new Uint8Array(1)),g}static writeParts(e,t,s=!1,a=!1){let i=s?12:8,o=e,h=t.reduce((Q,p)=>p.length+Q,0),g=h;a&&(i+=4,g+=4,o="LIST");let f=i+h;f%2!==0&&f++;let l=new K(f);le(l,o),s?Nt(l,g):Y(l,g),a&&le(l,e);for(let Q of t)l.set(Q,i),i+=Q.length;return l}static findListType(e,t){return e.find(s=>s.header!=="LIST"?!1:(s.data.currentIndex=4,zt(s.data,4)===t))}};function $t(A,e){return{...e,...A}}var u=class Ot{static infoEnabled=!1;static warnEnabled=!0;static groupEnabled=!1;static setLogLevel(e,t,s){this.infoEnabled=e,this.warnEnabled=t,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,t,s=""){this.infoEnabled&&this.info(`%cUnsupported %c${e}%c message: %c${rs(t)}%c. ${s}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn)}static gmInfo(e,t,s=""){this.infoEnabled&&this.coolInfo(`General MIDI ${e}`,t,s)}static gmFail(e,t){this.infoEnabled&&this.unsupported(`General MIDI ${e}`,t)}static gsInfo(e,t,s=""){this.infoEnabled&&this.coolInfo(`Roland GS ${e}`,t,s)}static gsFail(e,t,s=""){this.infoEnabled&&this.unsupported(`Roland GS ${e}`,t,s)}static xgInfo(e,t,s=""){this.infoEnabled&&this.coolInfo(`Yamaha XG ${e}`,t,s)}static xgFail(e,t,s=""){this.infoEnabled&&this.unsupported(`Yamaha XG ${e}`,t,s)}static coolInfo(e,t,s=""){this.infoEnabled&&(s?Ot.info(`%c${e}%c is now set to %c${t}%c ${s}.`,I.recognized,I.info,I.value,I.info):Ot.info(`%c${e}%c is now set to %c${t}%c.`,I.recognized,I.info,I.value,I.info))}},SA={ConsoleColors:I,readBigEndian:ts,readLittleEndian:QA,readLittleEndianIndexed:P,readBinaryString:zt,readBinaryStringIndexed:Ve,readVariableLengthQuantity:ns,inflateSync:is},qe={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},m={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};var js=`SPESSASYNTH_EMBEDDED_BANK_${Math.random()}_DO_NOT_DELETE`;var ea=1/Math.cos(Math.PI/4)**2;var gA=121,tt=class{static getDefaultBank(A){return A==="gm2"?gA:0}static getDrumBank(A){switch(A){default:throw new Error(`${A} doesn't have a bank MSB for drums.`);case"gm2":return 120;case"xg":return 127}}static isXGDrum(A){return A===120||A===127}static isValidXGMSB(A){return this.isXGDrum(A)||A===64||A===gA}static isSystemXG(A){return A==="gm2"||A==="xg"}static addBankOffset(A,e,t){return this.isXGDrum(A)&&t?A:Math.min(A+e,127)}static subtractBankOffset(A,e,t){return this.isXGDrum(A)&&t?A:Math.max(0,A-e)}},It=class Yt{static toMIDIString(e){return e.isGMGSDrum?`DRUM:${e.program}`:`${e.bankLSB}:${e.bankMSB}:${e.program}`}static fromMIDIString(e){let t=e.split(":");if(t.length>3||t.length<2)throw new Error(`Invalid MIDI string: ${e}`);return e.startsWith("DRUM")?{bankMSB:0,bankLSB:0,program:Number.parseInt(t[1]),isGMGSDrum:!0}:{bankLSB:Number.parseInt(t[0]),bankMSB:Number.parseInt(t[1]),program:Number.parseInt(t[2]),isGMGSDrum:!1}}static toFullMIDIString(e){return`${this.toMIDIString(e)} ${e.isDrum?"D":"M"} ${e.name}`}static fromFullMIDIString(e){let t=e.indexOf(" "),s=e.indexOf(" ",t+1);if(t===-1||s===-1)throw new Error(`Invalid named MIDI string: ${e}`);let a=e.slice(0,Math.max(0,t)),i=e.slice(t+1,s),o=e.slice(Math.max(0,s+1));return{...Yt.fromMIDIString(a),isDrum:i==="D",name:o}}static matches(e,t){return e.isGMGSDrum||t.isGMGSDrum?e.isGMGSDrum===t.isGMGSDrum&&e.program===t.program:e.program===t.program&&e.bankLSB===t.bankLSB&&e.bankMSB===t.bankMSB}static compare(e,t){return e.isGMGSDrum&&!t.isGMGSDrum?1:!e.isGMGSDrum&&t.isGMGSDrum?-1:e.program!==t.program?e.program-t.program:e.bankMSB!==t.bankMSB?e.bankMSB-t.bankMSB:e.bankLSB-t.bankLSB}static isXGDrum(e){return e.isDrum&&!e.isGMGSDrum}static selectPatch(e,t,s){if(e.length===0)throw new Error("No presets!");t.isGMGSDrum&&tt.isSystemXG(s)&&(t={...t,isGMGSDrum:!1,bankLSB:0,bankMSB:tt.getDrumBank(s)});let{isGMGSDrum:a,bankLSB:i,bankMSB:o,program:h}=t,g=tt.isSystemXG(s),f=tt.isXGDrum(o)&&g,l=e.find(r=>this.matches(r,t));if(l&&(!f||f&&this.isXGDrum(l)))return l;let Q=r=>{u.info(`%cPreset %c${Yt.toMIDIString(t)}%c not found. (${s}) Replaced with %c${this.toFullMIDIString(r)}`,I.warn,I.unrecognized,I.warn,I.value)};if(a){let r=e.find(B=>B.isGMGSDrum&&B.program===h);return r||(r=e.find(B=>B.isDrum&&B.program===h),r)?(Q(r),r):(r=this.getAnyDrums(e,!1),Q(r),r)}if(f){let r=e.find(B=>B.program===h&&B.isDrum&&!B.isGMGSDrum);return r||(r=e.find(B=>B.isDrum&&B.program===h),r&&r.program<49)?(Q(r),r):(r=this.getAnyDrums(e,!0),Q(r),r)}let p=e.filter(r=>r.program===h&&!r.isDrum);if(p.length===0)return Q(e[0]),e[0];if(l=g?p.find(r=>r.bankLSB===i):p.find(r=>r.bankMSB===o),l)return Q(l),l;if(i!==64||!g){let r=Math.max(o,i);if(l=p.find(B=>B.bankLSB===r||B.bankMSB===r),l)return Q(l),l}return Q(p[0]),p[0]}static getAnyDrums(e,t){let s=t?e.find(a=>this.isXGDrum(a)):e.find(a=>a.isGMGSDrum);return s||(e.find(a=>a.isDrum)??e[0])}},ta=Object.freeze({type:"Other"});function kA(A){return A.toISOString().split(".")[0]+"Z"}var os=[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 gs(A){for(let e of os){let t=A;for(let[a,i]of e.entries()){let o=new RegExp(a,"gi");t=t.replace(o,i)}let s=new Date(t);if(!Number.isNaN(s.getTime()))return s}}function hs(A){let e=/^(\d{2})\.(\d{2})\.(\d{4})$/.exec(A);if(e){let t=Number.parseInt(e[1]),s=Number.parseInt(e[2])-1,a=Number.parseInt(e[3]),i=new Date(a,s,t);if(!Number.isNaN(i.getTime()))return i}}function Is(A){let e=/^(\d{1,2})\s{1,2}(\d{1,2})\s{1,2}(\d{2})$/.exec(A);if(e){let t=e[1],s=(Number.parseInt(e[2])+1).toString(),a=e[3],i=new Date(`${s}/${t}/${a}`);if(!Number.isNaN(i.getTime()))return i}}function ls(A){let e=/\b\d{4}\b/.exec(A);return e?new Date(e[0]):void 0}function cs(A){if(A=A.trim(),A.length===0)return new Date;let e=A.replaceAll(/\b(\d+)(st|nd|rd|th)\b/g,"$1").replace(/\s+at\s+/i," "),t=new Date(e);if(Number.isNaN(t.getTime())){let s=gs(A);if(s)return s;let a=hs(A);if(a)return a;let i=Is(A);if(i)return i;let o=ls(A);return o||(u.warn(`Invalid date: "${A}". Replacing with the current date!`),new Date)}return t}var Cs=new Int16Array(128).fill(0),Ie=(A,e)=>Cs[A]=e<<7;Ie(m.mainVolume,100);Ie(m.balance,64);Ie(m.expression,127);Ie(m.pan,64);Ie(m.filterResonance,64);Ie(m.releaseTime,64);Ie(m.attackTime,64);Ie(m.brightness,64);Ie(m.decayTime,64);Ie(m.vibratoRate,64);Ie(m.vibratoDepth,64);Ie(m.vibratoDelay,64);Ie(m.generalPurposeController6,64);Ie(m.generalPurposeController8,64);Ie(m.registeredParameterLSB,127);Ie(m.registeredParameterMSB,127);Ie(m.nonRegisteredParameterLSB,0);Ie(m.nonRegisteredParameterMSB,0);var DA=new Int8Array(128).fill(127);DA[35]=0;DA[36]=0;var Aa=[m.modulationWheel,m.expression,m.sustainPedal,m.portamentoOnOff,m.sostenutoPedal,m.softPedal,m.registeredParameterMSB,m.registeredParameterLSB];var sa=new Set([m.dataDecrement,m.dataIncrement,m.dataEntryMSB,m.dataEntryLSB,m.registeredParameterLSB,m.registeredParameterMSB,m.nonRegisteredParameterLSB,m.nonRegisteredParameterMSB,m.bankSelect,m.bankSelectLSB,m.resetAllControllers,m.monoModeOn,m.polyModeOn]);var Bs={linear:0,nearestNeighbor:1,hermite:2},ut=ut!==void 0?ut:{},hA=!1,wA;ut.isInitialized=new Promise(A=>wA=A);var Es=function(A){var e,t,s,a,i,o,h,g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",f="",l=0;A=A.replace(/[^A-Za-z0-9\+\/\=]/g,"");do a=g.indexOf(A.charAt(l++)),i=g.indexOf(A.charAt(l++)),o=g.indexOf(A.charAt(l++)),h=g.indexOf(A.charAt(l++)),e=a<<2|i>>4,t=(15&i)<<4|o>>2,s=(3&o)<<6|h,f+=String.fromCharCode(e),o!==64&&(f+=String.fromCharCode(t)),h!==64&&(f+=String.fromCharCode(s));while(l1&&(r.thisProgram=process.argv[1].replace(/\\/g,"/")),r.arguments=process.argv.slice(2),process.on("uncaughtException",function(C){if(!(C instanceof Qe))throw C}),process.on("unhandledRejection",function(C,c){process.exit(1)}),r.quit=function(C){process.exit(C)},r.inspect=function(){return"[Emscripten Module object]"}):$?(typeof read<"u"&&(r.read=function(c){return read(c)}),r.readBinary=function(c){var E;return typeof readbuffer=="function"?new Uint8Array(readbuffer(c)):(ne(typeof(E=read(c,"binary"))=="object"),E)},typeof scriptArgs<"u"?r.arguments=scriptArgs:typeof arguments<"u"&&(r.arguments=arguments),typeof quit=="function"&&(r.quit=function(C){quit(C)})):(M||T)&&(M?document.currentScript&&(F=document.currentScript.src):F=self.location.href,F=F.indexOf("blob:")!==0?F.split("/").slice(0,-1).join("/")+"/":"",r.read=function(c){var E=new XMLHttpRequest;return E.open("GET",c,!1),E.send(null),E.responseText},T&&(r.readBinary=function(c){var E=new XMLHttpRequest;return E.open("GET",c,!1),E.responseType="arraybuffer",E.send(null),new Uint8Array(E.response)}),r.readAsync=function(c,E,w){var x=new XMLHttpRequest;x.open("GET",c,!0),x.responseType="arraybuffer",x.onload=function(){if(x.status==200||x.status==0&&x.response){E(x.response);return}w()},x.onerror=w,x.send(null)},r.setWindowTitle=function(C){document.title=C});var N=r.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),q=r.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||N);for(A in B)B.hasOwnProperty(A)&&(r[A]=B[A]);function ce(C){var c=g;return g=g+C+15&-16,c}function j(C,c){return c||(c=16),C=Math.ceil(C/c)*c}function ee(C){ee.shown||(ee.shown={}),ee.shown[C]||(ee.shown[C]=1,q(C))}B=void 0;var V={"f64-rem":function(C,c){return C%c},debugger:function(){}},ae=0;function ne(C,c){C||Me("Assertion failed: "+c)}function U(C){var c=r["_"+C];return ne(c,"Cannot call unknown function "+C+", make sure it is exported"),c}var pe={stackSave:function(){it()},stackRestore:function(){Ke()},arrayToC:function(C){var c,E,w=Ue(C.length);return c=C,E=w,a.set(c,E),w},stringToC:function(C){var c=0;if(C!=null&&C!==0){var E=(C.length<<2)+1;c=Ue(E),ve(C,c,E)}return c}},k={string:pe.stringToC,array:pe.arrayToC};function v(C,c,E,w,x){var X=U(C),Ae=[],R=0;if(w)for(var Ce=0;Ce>0],(w!=0||c)&&(Ae++,!c||Ae!=c););c||(c=Ae);var R="";if(X<128){for(;c>0;)x=String.fromCharCode.apply(String,i.subarray(C,C+Math.min(c,1024))),R=R?R+x:x,C+=1024,c-=1024;return R}return E=C,function(ie,O){for(var _=O;ie[_];)++_;if(_-O>16&&ie.subarray&&J)return J.decode(ie.subarray(O,_));for(var W,Ee,de,Re,je,He="";;){if(!(W=ie[O++]))return He;if(!(128&W)){He+=String.fromCharCode(W);continue}if(Ee=63&ie[O++],(224&W)==192){He+=String.fromCharCode((31&W)<<6|Ee);continue}if(de=63&ie[O++],(240&W)==224?W=(15&W)<<12|Ee<<6|de:(Re=63&ie[O++],(248&W)==240?W=(7&W)<<18|Ee<<12|de<<6|Re:(je=63&ie[O++],W=(252&W)==248?(3&W)<<24|Ee<<18|de<<12|Re<<6|je:(1&W)<<30|Ee<<24|de<<18|Re<<12|je<<6|63&ie[O++])),W<65536)He+=String.fromCharCode(W);else{var Fe=W-65536;He+=String.fromCharCode(55296|Fe>>10,56320|1023&Fe)}}}(i,E)}var J=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function H(C,c,E,w){if(!(w>0))return 0;for(var x=E,X=E+w-1,Ae=0;Ae=55296&&R<=57343&&(R=65536+((1023&R)<<10)|1023&C.charCodeAt(++Ae)),R<=127){if(E>=X)break;c[E++]=R}else if(R<=2047){if(E+1>=X)break;c[E++]=192|R>>6,c[E++]=128|63&R}else if(R<=65535){if(E+2>=X)break;c[E++]=224|R>>12,c[E++]=128|R>>6&63,c[E++]=128|63&R}else if(R<=2097151){if(E+3>=X)break;c[E++]=240|R>>18,c[E++]=128|R>>12&63,c[E++]=128|R>>6&63,c[E++]=128|63&R}else if(R<=67108863){if(E+4>=X)break;c[E++]=248|R>>24,c[E++]=128|R>>18&63,c[E++]=128|R>>12&63,c[E++]=128|R>>6&63,c[E++]=128|63&R}else{if(E+5>=X)break;c[E++]=252|R>>30,c[E++]=128|R>>24&63,c[E++]=128|R>>18&63,c[E++]=128|R>>12&63,c[E++]=128|R>>6&63,c[E++]=128|63&R}}return c[E]=0,E-x}function ve(C,c,E){return H(C,i,c,E)}typeof TextDecoder<"u"&&new TextDecoder("utf-16le");function ye(C,c){return C%c>0&&(C+=c-C%c),C}function Se(C){r.buffer=s=C}function Pe(){r.HEAP8=a=new Int8Array(s),r.HEAP16=new Int16Array(s),r.HEAP32=o=new Int32Array(s),r.HEAPU8=i=new Uint8Array(s),r.HEAPU16=new Uint16Array(s),r.HEAPU32=new Uint32Array(s),r.HEAPF32=new Float32Array(s),r.HEAPF64=new Float64Array(s)}function We(){var C=r.usingWasm?65536:16777216,c=2147483648-C;if(o[p>>2]>c)return!1;var E=b;for(b=Math.max(b,16777216);b>2];)b=b<=536870912?ye(2*b,C):Math.min(ye((3*b+2147483648)/4,C),c);var w=r.reallocBuffer(b);return w&&w.byteLength==b?(Se(w),Pe(),!0):(b=E,!1)}h=g=f=l=Q=p=0,r.reallocBuffer||(r.reallocBuffer=function(C){try{if(ArrayBuffer.transfer)c=ArrayBuffer.transfer(s,C);else{var c,E=a;c=new ArrayBuffer(C),new Int8Array(c).set(E)}}catch{return!1}return!!we(c)&&c});try{Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get)(new ArrayBuffer(4))}catch{}var ke=r.TOTAL_STACK||5242880,b=r.TOTAL_MEMORY||16777216;function te(){return b}function De(C){for(;C.length>0;){var c=C.shift();if(typeof c=="function"){c();continue}var E=c.func;typeof E=="number"?c.arg===void 0?r.dynCall_v(E):r.dynCall_vi(E,c.arg):E(c.arg===void 0?null:c.arg)}}b>2]=Q,r.wasmTableSize=4,r.wasmMaxTableSize=4,r.asmGlobalArg={},r.asmLibraryArg={abort:Me,assert:ne,enlargeMemory:We,getTotalMemory:te,abortOnCannotGrowMemory:function(){Me("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+b+", (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(c,E,w){var x=it();try{return r.dynCall_iii(c,E,w)}catch(X){if(Ke(x),typeof X!="number"&&X!=="longjmp")throw X;r.setThrew(1,0)}},___assert_fail:function(c,E,w,x){Me("Assertion failed: "+L(c)+", at: "+[E?L(E):"unknown filename",w,x?L(x):"unknown function"])},___setErrNo:function(c){return r.___errno_location&&(o[r.___errno_location()>>2]=c),c},_abort:function(){r.abort()},_emscripten_memcpy_big:function(c,E,w){return i.set(i.subarray(E,E+w),c),c},_llvm_floor_f64:pt,DYNAMICTOP_PTR:p,tempDoublePtr:Pt,ABORT:ae,STACKTOP:f,STACK_MAX:l};var Et=r.asm(r.asmGlobalArg,r.asmLibraryArg,s);r.asm=Et,r.___errno_location=function(){return r.asm.___errno_location.apply(null,arguments)};var we=r._emscripten_replace_memory=function(){return r.asm._emscripten_replace_memory.apply(null,arguments)};r._free=function(){return r.asm._free.apply(null,arguments)},r._malloc=function(){return r.asm._malloc.apply(null,arguments)},r._memcpy=function(){return r.asm._memcpy.apply(null,arguments)},r._memset=function(){return r.asm._memset.apply(null,arguments)},r._sbrk=function(){return r.asm._sbrk.apply(null,arguments)},r._stb_vorbis_js_channels=function(){return r.asm._stb_vorbis_js_channels.apply(null,arguments)},r._stb_vorbis_js_close=function(){return r.asm._stb_vorbis_js_close.apply(null,arguments)},r._stb_vorbis_js_decode=function(){return r.asm._stb_vorbis_js_decode.apply(null,arguments)},r._stb_vorbis_js_open=function(){return r.asm._stb_vorbis_js_open.apply(null,arguments)},r._stb_vorbis_js_sample_rate=function(){return r.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},r.establishStackSpace=function(){return r.asm.establishStackSpace.apply(null,arguments)},r.getTempRet0=function(){return r.asm.getTempRet0.apply(null,arguments)},r.runPostSets=function(){return r.asm.runPostSets.apply(null,arguments)},r.setTempRet0=function(){return r.asm.setTempRet0.apply(null,arguments)},r.setThrew=function(){return r.asm.setThrew.apply(null,arguments)};var Ue=r.stackAlloc=function(){return r.asm.stackAlloc.apply(null,arguments)},Ke=r.stackRestore=function(){return r.asm.stackRestore.apply(null,arguments)},it=r.stackSave=function(){return r.asm.stackSave.apply(null,arguments)};function Qe(C){this.name="ExitStatus",this.message="Program terminated with exit("+C+")",this.status=C}function $e(C){C=C||r.arguments,!(ue>0)&&(function(){if(r.preRun)for(typeof r.preRun=="function"&&(r.preRun=[r.preRun]);r.preRun.length;)Ct(r.preRun.shift());De(Ze)}(),!(ue>0)&&(r.calledRun||(r.setStatus?(r.setStatus("Running..."),setTimeout(function(){setTimeout(function(){r.setStatus("")},1),c()},1)):c())));function c(){!r.calledRun&&(r.calledRun=!0,ae||(nt||(nt=!0,De(Je)),De(_e),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for(typeof r.postRun=="function"&&(r.postRun=[r.postRun]);r.postRun.length;)mt(r.postRun.shift());De(at)}()))}}function Me(C){throw r.onAbort&&r.onAbort(C),C!==void 0?(N(C),q(C),C=JSON.stringify(C)):C="",ae=!0,"abort("+C+"). Build with -s ASSERTIONS=1 for more info."}if(r.dynCall_iii=function(){return r.asm.dynCall_iii.apply(null,arguments)},r.asm=Et,r.ccall=v,r.cwrap=function(c,E,w,x){var X=(w=w||[]).every(function(Ae){return Ae==="number"});return E!=="string"&&X&&!x?U(c):function(){return v(c,E,w,arguments,x)}},Qe.prototype=Error(),Qe.prototype.constructor=Qe,ge=function C(){r.calledRun||$e(),r.calledRun||(ge=C)},r.run=$e,r.abort=Me,r.preInit)for(typeof r.preInit=="function"&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();r.noExitRuntime=!0,$e(),r.onRuntimeInitialized=()=>{hA=!0,wA()},ut.decode=function(C){return function(E){if(!hA)throw Error("SF3 decoder has not been initialized yet. Did you await synth.isReady?");var w={};function x(ot){return new Int32Array(r.HEAPU8.buffer,ot,1)[0]}function X(ot,gt){var yt=new ArrayBuffer(gt*Float32Array.BYTES_PER_ELEMENT),me=new Float32Array(yt);return me.set(new Float32Array(r.HEAPU8.buffer,ot,gt)),me}w.open=r.cwrap("stb_vorbis_js_open","number",[]),w.close=r.cwrap("stb_vorbis_js_close","void",["number"]),w.channels=r.cwrap("stb_vorbis_js_channels","number",["number"]),w.sampleRate=r.cwrap("stb_vorbis_js_sample_rate","number",["number"]),w.decode=r.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var Ae,R,Ce,ie,O=w.open(),_=(Ae=E,R=E.byteLength,Ce=r._malloc(R),(ie=new Uint8Array(r.HEAPU8.buffer,Ce,R)).set(new Uint8Array(Ae,0,R)),ie),W=r._malloc(4),Ee=r._malloc(4),de=w.decode(O,_.byteOffset,_.byteLength,W,Ee);if(r._free(_.byteOffset),de<0)throw w.close(O),r._free(W),Error("stbvorbis decode failed: "+de);for(var Re=w.channels(O),je=Array(Re),He=new Int32Array(r.HEAPU32.buffer,x(W),Re),Fe=0;Fe.5?1:0,s?t*2-1:t;case z.concave:return s?(t=t*2-1,t<0?-Ye[Math.trunc(t*-fe)]:Ye[Math.trunc(t*fe)]):Ye[Math.trunc(t*fe)];case z.convex:return s?(t=t*2-1,t<0?-st[Math.trunc(t*-fe)]:st[Math.trunc(t*fe)]):st[Math.trunc(t*fe)]}}var CA=new Float32Array(1e3);for(let A=0;A>e&1)>0}function Tt(A){return A?1:0}var Oe=class qt{isBipolar;isNegative;index;isCC;curveType;constructor(e=se.noController,t=z.linear,s=!1,a=!1,i=!1){this.isBipolar=a,this.isNegative=i,this.index=e,this.isCC=s,this.curveType=t}get sourceName(){return this.isCC?Object.keys(m).find(e=>m[e]===this.index)??this.index.toString():Object.keys(se).find(e=>se[e]===this.index)??this.index.toString()}get curveTypeName(){return Object.keys(z).find(e=>z[e]===this.curveType)??this.curveType.toString()}static fromSourceEnum(e){let t=At(e,9),s=At(e,8),a=At(e,7);return new qt(e&127,e>>10&3,a,t,s)}static copyFrom(e){return new qt(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|Tt(this.isBipolar)<<9|Tt(this.isNegative)<<8|Tt(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,t,s){let a;if(this.isCC)a=e.midiControllers[this.index];else switch(this.index){default:case se.noController:a=16383;break;case se.noteOnVelocity:a=s.velocity<<7;break;case se.noteOnKeyNum:a=s.targetKey<<7;break;case se.polyPressure:a=s.pressure<<7;break;case se.channelPressure:a=e.midiParameters.pressure<<7;break;case se.pitchWheel:a=t;break;case se.pitchWheelRange:a=Math.floor(e.midiParameters.pitchWheelRange*128)}let i=(this.isBipolar?2:0)|(this.isNegative?1:0);return TA[fe*(this.curveType*Gt+i)+a]}},TA=new Float32Array(fe*4*Gt);for(let A=0;An[e]===this.destination)}static isIdentical(e,t,s=!1){return e.primarySource.isIdentical(t.primarySource)&&e.secondarySource.isIdentical(t.secondarySource)&&e.destination===t.destination&&e.transformType===t.transformType&&(!s||e.transformAmount===t.transformAmount)}static copyFrom(e){return new Jt(Oe.copyFrom(e.primarySource),Oe.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,t){G(e,this.primarySource.toSourceEnum()),G(e,this.destination),G(e,this.transformAmount),G(e,this.secondarySource.toSourceEnum()),G(e,this.transformType),t&&t.mod++}sumTransform(e){let t=Jt.copyFrom(this);return t.transformAmount+=e.transformAmount,t}},re=class extends oe{constructor(A,e,t,s,a){super(Oe.fromSourceEnum(A),Oe.fromSourceEnum(e),t,s,a),this.destination>LA&&(this.destination=n.invalid)}},fs=[new re(be(z.concave,!1,!0,!1,se.noteOnVelocity),0,n.initialAttenuation,960,0),new re(129,0,n.vibLfoToPitch,50,0),new re(be(z.concave,!1,!0,!0,m.mainVolume),0,n.initialAttenuation,960,0),new re(13,0,n.vibLfoToPitch,50,0),new re(526,16,n.fineTune,12700,0),new re(650,0,n.pan,500,0),new re(be(z.concave,!1,!0,!0,m.expression),0,n.initialAttenuation,960,0),new re(219,0,n.reverbEffectsSend,200,0),new re(221,0,n.chorusEffectsSend,200,0)],us=[new re(be(z.convex,!0,!1,!0,m.attackTime),0,n.attackVolEnv,6e3,0),new re(be(z.linear,!0,!1,!0,m.releaseTime),0,n.releaseVolEnv,3600,0),new re(be(z.linear,!0,!1,!0,m.decayTime),0,n.decayVolEnv,3600,0),new re(be(z.linear,!0,!1,!0,m.brightness),0,n.initialFilterFc,9600,0),new re(xA,0,n.initialFilterQ,250,0),new re(be(z.switch,!1,!1,!0,m.softPedal),0,n.initialAttenuation,50,0),new re(be(z.switch,!1,!1,!0,m.softPedal),0,n.initialFilterFc,-2400,0),new re(be(z.linear,!0,!1,!0,m.balance),0,n.pan,500,0)],UA=[...fs,...us],Be=class{type;value=0;constructor(A,e,t=!0){if(this.type=A,e===void 0)throw new Error("No value provided.");if(this.value=Math.round(e),t){let s=xe[A];s!==void 0&&(this.value=Math.max(s.min,Math.min(s.max,this.value)))}}write(A){G(A,this.type),G(A,this.value)}toString(){return`${Object.keys(n).find(A=>n[A]===this.type)}: ${this.value}`}},Qt=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 A=this.getGenerator(n.coarseTune,0),e=this.getGenerator(n.fineTune,0);return A*100+e}set fineTuning(A){let e=Math.trunc(A/100),t=A%100;this.setGenerator(n.coarseTune,e),this.setGenerator(n.fineTune,t)}addToGenerator(A,e,t=!0){let s=this.getGenerator(A,xe[A].def);this.setGenerator(A,e+s,t)}setGenerator(A,e,t=!0){switch(A){case n.sampleID:throw new Error("Use setSample()");case n.instrument:throw new Error("Use setInstrument()");case n.velRange:case n.keyRange:throw new Error("Set the range manually")}if(e===null){this.generators=this.generators.filter(a=>a.type!==A);return}let s=this.generators.findIndex(a=>a.type===A);s===-1?this.addGenerators(new Be(A,e,t)):this.generators[s]=new Be(A,e,t)}addGenerators(...A){for(let e of A)switch(e.type){default:this.generators.push(e);break;case n.sampleID:case n.instrument:break;case n.velRange:this.velRange.min=e.value&127,this.velRange.max=e.value>>8&127;break;case n.keyRange:this.keyRange.min=e.value&127,this.keyRange.max=e.value>>8&127}}addModulators(...A){this.modulators.push(...A)}getGenerator(A,e){return this.generators.find(t=>t.type===A)?.value??e}copyFrom(A){this.generators=A.generators.map(e=>new Be(e.type,e.value,!1)),this.modulators=A.modulators.map(oe.copyFrom.bind(oe)),this.velRange={...A.velRange},this.keyRange={...A.keyRange}}getWriteGenerators(A){let e=this.generators.filter(t=>t.type!==n.sampleID&&t.type!==n.instrument&&t.type!==n.keyRange&&t.type!==n.velRange);if(!A)throw new Error("No bank provided! ");return this.hasVelRange&&e.unshift(new Be(n.velRange,this.velRange.max<<8|Math.max(this.velRange.min,0),!1)),this.hasKeyRange&&e.unshift(new Be(n.keyRange,this.keyRange.max<<8|Math.max(this.keyRange.min,0),!1)),e}},Qs=48e3,jt=class{name;sampleRate;originalKey;pitchCorrection;linkedSample;sampleType;loopStart;loopEnd;linkedTo=[];dataOverridden=!0;compressedData;audioData;constructor(A,e,t,s,a,i,o){this.name=A,this.sampleRate=e,this.originalKey=t,this.pitchCorrection=s,this.loopStart=i,this.loopEnd=o,this.sampleType=a}get isCompressed(){return this.compressedData!==void 0}get isLinked(){return this.sampleType===he.rightSample||this.sampleType===he.leftSample||this.sampleType===he.linkedSample}get useCount(){return this.linkedTo.length}getRawData(A){return this.compressedData&&A&&!this.dataOverridden?this.compressedData:this.encodeS16LE()}resampleData(A){let e=this.getAudioData(),t=A/this.sampleRate,s=new Float32Array(Math.floor(e.length*t));for(let a=0;a96e3)&&(this.resampleData(Qs),e=this.getAudioData());let t=await A(e,this.sampleRate);this.setCompressedData(t)}catch(e){u.warn(`Failed to compress ${this.name}. Leaving as uncompressed!`,e),this.compressedData=void 0}}setSampleType(A){if(this.sampleType=A,this.isLinked||(this.linkedSample&&(this.linkedSample.linkedSample=void 0,this.linkedSample.sampleType=A),this.linkedSample=void 0),(A&32768)>0)throw new Error("ROM samples are not supported.")}unlinkSample(){this.setSampleType(he.monoSample)}setLinkedSample(A,e){if(A.linkedSample)throw new Error(`${A.name} is linked tp ${A.linkedSample.name}. Unlink it first.`);switch(this.linkedSample=A,A.linkedSample=this,e){case he.leftSample:this.setSampleType(he.leftSample),A.setSampleType(he.rightSample);break;case he.rightSample:this.setSampleType(he.rightSample),A.setSampleType(he.leftSample);break;case he.linkedSample:this.setSampleType(he.linkedSample),A.setSampleType(he.linkedSample);break;default:throw new Error("Invalid sample type: "+e)}}linkTo(A){this.linkedTo.push(A)}unlinkFrom(A){let e=this.linkedTo.indexOf(A);if(e===-1){u.warn(`Cannot unlink ${A.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(A,e){this.audioData=A,this.sampleRate=e,this.dataOverridden=!0,this.compressedData=void 0}setCompressedData(A){this.audioData=void 0,this.compressedData=A,this.dataOverridden=!1}encodeS16LE(){let A=this.getAudioData(),e=new Int16Array(A.length),t=A.length;for(let s=0;s32767?a=32767:a<-32768&&(a=-32768),e[s]=a}return new K(e.buffer)}decodeVorbis(){if(this.audioData)return this.audioData;if(!this.compressedData)throw new Error("Compressed data is missing.");try{let A=bA.decode(this.compressedData).data[0];if(A===void 0)return u.warn(`Error decoding sample ${this.name}: Vorbis decode returned undefined.`),new Float32Array(0);for(let e=0;e=e.min&&t<=e.max}static addUniqueModulators(e,t){for(let s of t)e.some(a=>oe.isIdentical(s,a))||e.push(s)}static subtractRanges(e,t){return{min:Math.max(e.min,t.min),max:Math.min(e.max,t.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 t=new ys(this,e);return this.zones.push(t),t}preload(e,t){for(let s=e;soe.isIdentical(Q,r));p===-1?f.push(Q):f[p]=f[p].sumTransform(Q)}let l=new Int16Array(Kt);for(let Q of i.globalZone.generators)l[Q.type]=Q.value;for(let Q of g.generators)l[Q.type]=Q.value;for(let Q=0;Q{f.push(...l.filter(Q=>!f.some(p=>p.type===Q.type)))},t=(f,l)=>{f.push(...l.filter(Q=>!f.some(p=>oe.isIdentical(Q,p))))},s=new Lt;s.name=this.name;let a=[],i=[],o=this.globalZone;a.push(...o.generators),i.push(...o.modulators);let h=o.keyRange,g=o.velRange;for(let f of this.zones){if(!f.instrument)throw new Error("No instrument in a preset zone.");let l=f.keyRange;f.hasKeyRange||(l=h);let Q=f.velRange;f.hasVelRange||(Q=g);let p=f.generators.map(N=>new Be(N.type,N.value));e(p,a);let r=[...f.modulators];t(r,i);let B=f.instrument,M=B.zones,T=[],y=[],$=B.globalZone;T.push(...$.generators),y.push(...$.modulators);let F=$.keyRange,Z=$.velRange;for(let N of M){if(!N.sample)throw new Error("No sample in an instrument zone.");let q=N.keyRange;N.hasKeyRange||(q=F);let ce=N.velRange;if(N.hasVelRange||(ce=Z),q=Te.subtractRanges(q,l),ce=Te.subtractRanges(ce,Q),q.maxnew Be(U.type,U.value));e(j,T);let ee=[...N.modulators];t(ee,y);let V=[...ee];for(let U of r){let pe=V.findIndex(k=>oe.isIdentical(U,k));pe===-1?V.push(U):V[pe]=V[pe].sumTransform(U)}let ae=j.map(U=>new Be(U.type,U.value));for(let U of p){if(U.type===n.velRange||U.type===n.keyRange||U.type===n.instrument||U.type===n.endOper||U.type===n.sampleModes)continue;let pe=j.findIndex(k=>k.type===U.type);if(pe===-1){let k=xe[U.type].def+U.value;ae.push(new Be(U.type,k))}else{let k=ae[pe].value+U.value;ae[pe]=new Be(U.type,k)}}ae=ae.filter(U=>U.type!==n.sampleID&&U.type!==n.keyRange&&U.type!==n.velRange&&U.type!==n.endOper&&U.type!==n.instrument&&(!(U.type in xe)||U.value!==xe[U.type].def));let ne=s.createZone(N.sample);ne.keyRange=q,ne.velRange=ce,ne.keyRange.min===0&&ne.keyRange.max===127&&(ne.keyRange.min=-1),ne.velRange.min===0&&ne.velRange.max===127&&(ne.velRange.min=-1),ne.addGenerators(...ae),ne.addModulators(...V)}}return s}write(e,t,s){u.info(`%cWriting ${this.name}...`,I.info),le(e.pdta,this.name.slice(0,20),20),le(e.xdta,this.name.slice(20),20),G(e.pdta,this.program);let a=this.bankMSB;s?(a=this.bankMSB&127|(this.bankLSB&127)<<8,this.isGMGSDrum&&(a|=128)):this.isGMGSDrum?a=128:this.bankMSB===0&&(a=this.bankLSB),G(e.pdta,a),e.xdta.currentIndex+=4,G(e.pdta,t&65535),G(e.xdta,t>>16),Y(e.pdta,this.library),Y(e.pdta,this.genre),Y(e.pdta,this.morphology),e.xdta.currentIndex+=12}},Ss=new Set([n.velRange,n.keyRange,n.instrument,n.sampleID,n.exclusiveClass,n.endOper,n.sampleModes,n.startloopAddrsOffset,n.startloopAddrsCoarseOffset,n.endloopAddrsOffset,n.endloopAddrsCoarseOffset,n.startAddrsOffset,n.startAddrsCoarseOffset,n.endAddrOffset,n.endAddrsCoarseOffset,n.initialAttenuation,n.fineTune,n.coarseTune,n.keyNumToVolEnvHold,n.keyNumToVolEnvDecay,n.keyNumToModEnvHold,n.keyNumToModEnvDecay]),Lt=class{name="";zones=[];globalZone=new Qt;linkedTo=[];get useCount(){return this.linkedTo.length}createZone(A){let e=new ps(this,A);return this.zones.push(e),e}linkTo(A){this.linkedTo.push(A);for(let e of this.zones)e.useCount++}unlinkFrom(A){let e=this.linkedTo.indexOf(A);if(e===-1){u.warn(`Cannot unlink ${A.name} from ${this.name}: not linked.`);return}this.linkedTo.splice(e,1);for(let t of this.zones)t.useCount--}deleteUnusedZones(){this.zones=this.zones.filter(A=>{let e=A.useCount>0;return e||A.sample.unlinkFrom(this),e})}delete(){if(this.useCount>0)throw new Error(`Cannot delete an instrument that is used by: ${this.linkedTo.map(A=>A.name).toString()}.`);for(let A of this.zones)A.sample.unlinkFrom(this)}deleteZone(A,e=!1){let t=this.zones[A];return t.useCount-=1,t.useCount<1||e?(t.sample.unlinkFrom(this),this.zones.splice(A,1),!0):!1}globalize(){let A=this.globalZone;for(let t=0;t<58;t++){if(Ss.has(t))continue;t=t;let s={},a=xe[t]?.def||0;s[a]=0;for(let i of this.zones){let o=i.getGenerator(t,void 0);o===void 0?s[a]++:s[o]===void 0?s[o]=1:s[o]++;let h;switch(t){default:continue;case n.decayVolEnv:h=n.keyNumToVolEnvDecay;break;case n.holdVolEnv:h=n.keyNumToVolEnvHold;break;case n.decayModEnv:h=n.keyNumToModEnvDecay;break;case n.holdModEnv:h=n.keyNumToModEnvHold}if(i.getGenerator(h,void 0)!==void 0){s={};break}}if(Object.keys(s).length>0){let i=["0",0];for(let[h,g]of Object.entries(s))g>i[1]&&(i=[h,g]);let o=Number.parseInt(i[0]);o!==a&&A.setGenerator(t,o,!1);for(let h of this.zones){let g=h.getGenerator(t,void 0);g===void 0?o!==a&&h.setGenerator(t,a):g===o&&h.setGenerator(t,null)}}}let e=this.zones.length===0?[]:this.zones[0].modulators.map(t=>oe.copyFrom(t));for(let t of e){let s=!0;for(let a of this.zones)s&&(a.modulators.find(i=>oe.isIdentical(i,t))||(s=!1));if(s){A.addModulators(oe.copyFrom(t));for(let a of this.zones){let i=a.modulators.find(o=>oe.isIdentical(o,t));i&&i.transformAmount===t.transformAmount&&a.modulators.splice(a.modulators.indexOf(i),1)}}}}write(A,e){u.info(`%cWriting ${this.name}...`,I.info),le(A.pdta,this.name.slice(0,20),20),le(A.xdta,this.name.slice(20),20),G(A.pdta,e&65535),G(A.xdta,e>>>16)}};function ks(A,e,t,s,a){let i=0,o=[],h=[];for(let Q of A.samples){let p=Q.getRawData(!0);i++,a?.(i/A.samples.length),u.info(`%cWrote sample %c${i}. ${Q.name}%c of %c${A.samples.length}.`,I.info,I.recognized,I.info,I.recognized),o.push(p),h.push(p.length),Q.isCompressed||o.push(new Uint8Array(92))}let g=D.getParts("smpl",o,s),f=D.getParts("sdta",g,s,!0),l=0;for(let[Q,p]of A.samples.entries()){let r=h[Q],B,M;p.isCompressed?(B=l,M=B+r):(B=l/2,M=B+r/2,l+=92),l+=r,e.push(B),t.push(M)}return f}function Ds(A,e,t,s){let i=46*(A.samples.length+1),o=new K(i),h=new K(i),g=0;for(let[f,l]of A.samples.entries()){le(o,l.name.slice(0,20),20),le(h,l.name.slice(20),20);let Q=e[f];Y(o,Q),h.currentIndex+=4;let p=t[f];Y(o,p),h.currentIndex+=4;let r=l.loopStart+Q,B=l.loopEnd+Q;l.isCompressed&&(r-=Q,B-=Q),Y(o,r),Y(o,B),Y(o,l.sampleRate),o[o.currentIndex++]=l.originalKey,o[o.currentIndex++]=l.pitchCorrection,h.currentIndex+=14;let M=l.linkedSample?A.samples.indexOf(l.linkedSample):0;G(o,Math.max(0,M)&65535),G(h,Math.max(0,M)>>16),g=Math.max(g,M);let T=l.sampleType;l.isCompressed&&(T|=16),G(o,T),h.currentIndex+=2}return le(o,"EOS",46),le(h,"EOS",46),{pdta:D.write("shdr",o,s),xdta:D.write("shdr",h,s)}}function BA(A,e,t,s=!1){let a=t?A.presets:A.instruments,i=t?"pgen":"igen",o=t?"pmod":"imod",h=t?"pbag":"ibag",g=t?"phdr":"inst",f=t?38:22,l=0,Q=new Array,p=0,r=new Array,B=new Array,M=new Array,T=0,y=new Array,$=ee=>{Q.push(l);let V=ee.getWriteGenerators(A);l+=V.length,B.push(...V),r.push(p);let ae=ee.modulators;p+=ae.length,M.push(...ae)};for(let ee of a){y.push(T),$(ee.globalZone);for(let V of ee.zones)$(V);T+=ee.zones.length+1}B.push(new Be(0,0,!1)),M.push(new re(0,0,0,0,0)),Q.push(l),r.push(p),y.push(T);let F=new K(B.length*4);for(let ee of B)ee.write(F);let Z=new K(M.length*10);for(let ee of M)ee.write(Z);let N=r.length*4,q={pdta:new K(N),xdta:new K(N)};for(let[ee,V]of r.entries()){let ae=Q[ee];G(q.pdta,ae&65535),G(q.pdta,V&65535),G(q.xdta,ae>>16),G(q.xdta,V>>16)}let ce=(a.length+1)*f,j={pdta:new K(ce),xdta:new K(ce)};for(let[ee,V]of a.entries())V.write(j,y[ee],s);return t?(le(j.pdta,"EOP",20),j.pdta.currentIndex+=4,G(j.pdta,T&65535),j.pdta.currentIndex+=12,le(j.xdta,"",20),j.xdta.currentIndex+=4,G(j.xdta,T>>16),j.xdta.currentIndex+=12):(le(j.pdta,"EOI",20),G(j.pdta,T&65535),le(j.xdta,"",20),G(j.xdta,T>>16)),{writeXdta:Math.max(l,p,T)>65535,gen:{pdta:D.write(i,F,e),xdta:D.write(o,new K(4),e)},mod:{pdta:D.write(o,Z,e),xdta:D.write(o,new K(10),e)},bag:{pdta:D.write(h,q.pdta,e),xdta:D.write(h,q.xdta,e)},hdr:{pdta:D.write(g,j.pdta,e),xdta:D.write(g,j.xdta,e)}}}var HA={writeDefaultModulators:!0,writeExtendedLimits:!0,software:"SpessaSynth"},OA={rf64:!0,software:"SpessaSynth"};function ws(A,e){let t=$t(e,HA);return YA(A,t.software,t.writeDefaultModulators,t.writeExtendedLimits,!1,!1)}function bs(A,e){return YA(A,$t(e,OA).software,!0,!0,!0,!0)}function YA(A,e,t,s,a,i){u.groupCollapsed("%cSaving soundbank...",I.info),u.group("%cWriting INFO...",I.info);let o=[],h=(F,Z)=>{Z&&o.push(...D.getParts(F,[Xe(Z,!0,!0)],i))},g=A.soundBankInfo;{let F=new K(4);G(F,g.version.major),G(F,g.version.minor),o.push(D.write("ifil",F,i))}if(h("isng",g.soundEngine),h("INAM",g.name),h("irom",g.romInfo),g.romVersion){let F=new K(4);G(F,g.romVersion.major),G(F,g.romVersion.minor),o.push(D.write("iver",F,i))}if(h("ICRD",kA(g.creationDate)),h("IENG",g.engineer),h("IPRD",g.product),h("ICOP",g.copyright),h("ICMT",g?.subject?(g?.comment?g.comment+` `:"")+g.subject:g?.comment),h("ISFT",e),A.defaultModulators.some(F=>!UA.some(Z=>oe.isIdentical(Z,F,!0)))&&t){let F=A.defaultModulators;u.info(`%cWriting %c${F.length}%c default modulators...`,I.info,I.recognized,I.info);let Z=new K(10+F.length*10);for(let N of F)N.write(Z);mA(Z,0,10),o.push(...D.getParts("DMOD",[Z],i))}u.groupEnd(),u.info("%cWriting SDTA...",I.info);let f=[],l=[],Q=ks(A,f,l,i);u.info("%cWriting PDTA...",I.info),u.info("%cWriting SHDR...",I.info);let p=Ds(A,f,l,i);u.group("%cWriting instruments...",I.info);let r=BA(A,i,!1);u.groupEnd(),u.group("%cWriting presets...",I.info);let B=BA(A,i,!0,a);u.groupEnd();let M=[B.hdr,B.bag,B.mod,B.gen,r.hdr,r.bag,r.mod,r.gen,p],T=D.getParts("pdta",M.map(F=>F.pdta),i,!0);s&&(r.writeXdta||B.writeXdta||A.presets.some(F=>F.name.length>20)||A.instruments.some(F=>F.name.length>20)||A.samples.some(F=>F.name.length>20))&&(u.info("%cWriting the xdta chunk as writeExtendedLimits is enabled and at least one condition was met.",I.info,I.value),o.push(...D.getParts("xdta",M.map(F=>F.xdta),i,!0)));let y=D.getParts("INFO",o,i,!0);u.info("%cWriting the output file...",I.info);let $=D.writeParts(i?"RIFS":"RIFF",[Xe(a?"sfen":"sfbk"),...y,...Q,...T],i);return u.info(`%cSaved successfully! Final file size: %c${$.length}`,I.info,I.recognized),u.groupEnd(),$.buffer}var ct=class{static verifyHeader(A,...e){for(let t of e)if(A.header.toLowerCase()===t.toLowerCase())return;this.parsingError(`Invalid DLS chunk header! Expected "${e.join(", or ")}" got "${A.header.toLowerCase()}"`)}static verifyText(A,...e){for(let t of e)if(A.toLowerCase()===t.toLowerCase())return;this.parsingError(`FourCC error: Expected "${e.join(", or ")}" got "${A.toLowerCase()}"`)}static parsingError(A){throw u.groupEnd(),new Error(`DLS parse error: ${A} The file may be corrupted.`)}static verifyAndReadList(A,...e){this.verifyHeader(A,"LIST"),A.data.currentIndex=0,this.verifyText(Ve(A.data,4),...e);let t=[];for(;A.data.length>A.data.currentIndex;)t.push(D.read(A.data));return t}},S={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},d={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},EA={forward:0,loopAndRelease:1},kt=20,Dt=16,lt=class ft extends ct{gain=0;unityNote=60;fineTune=0;loops=new Array;fulOptions=2;static copyFrom(e){let t=new ft;return t.unityNote=e.unityNote,t.gain=e.gain,t.fineTune=e.fineTune,t.loops=e.loops.map(s=>({...s})),t.fulOptions=e.fulOptions,t}static read(e){this.verifyHeader(e,"wsmp");let t=new ft,s=P(e.data,4);if(s!==kt&&u.warn(`Wsmp cbSize mismatch: got ${s}, expected ${kt}.`),t.unityNote=P(e.data,2),t.fineTune=as(e.data[e.data.currentIndex++],e.data[e.data.currentIndex++]),t.gain=P(e.data,4)|0,t.fulOptions=P(e.data,4),P(e.data,4)!==0){let a=P(e.data,4);a!==Dt&&u.warn(`CbSize for loop in wsmp mismatch. Expected ${Dt}, got ${a}.`);let i=P(e.data,4),o=P(e.data,4),h=P(e.data,4);t.loops.push({loopStart:o,loopLength:h,loopType:i})}return t}static fromSFSample(e){let t=new ft;return t.unityNote=e.originalKey,t.fineTune=e.pitchCorrection,(e.loopEnd!==0||e.loopStart!==0)&&t.loops.push({loopStart:e.loopStart,loopLength:e.loopEnd-e.loopStart,loopType:EA.forward}),t}static fromSFZone(e){let t=new ft;t.unityNote=e.getGenerator(n.overridingRootKey,e.sample.originalKey),e.getGenerator(n.scaleTuning,100)===0&&e.keyRange.max-e.keyRange.min===0&&(t.unityNote=e.keyRange.min),t.fineTune=e.fineTuning+e.sample.pitchCorrection,t.gain=-(e.getGenerator(n.initialAttenuation,0)*.4)<<16;let s=e.getGenerator(n.sampleModes,0);if(s!==0){let a=e.sample.loopStart+e.getGenerator(n.startloopAddrsOffset,0)+e.getGenerator(n.startloopAddrsCoarseOffset,0)*32768,i=e.sample.loopEnd+e.getGenerator(n.endloopAddrsOffset,0)+e.getGenerator(n.endloopAddrsCoarseOffset,0)*32768,o;switch(s){case 1:default:o=0;break;case 3:o=1}t.loops.push({loopType:o,loopStart:a,loopLength:i-a})}return t}toSFZone(e,t){let s=0,a=this.loops[0];a&&(s=a.loopType===EA.loopAndRelease?3:1),s!==0&&e.setGenerator(n.sampleModes,s);let i=-(this.gain>>16)/.4;if(i!==0&&e.setGenerator(n.initialAttenuation,i),e.fineTuning=this.fineTune-t.pitchCorrection,this.unityNote!==t.originalKey&&e.setGenerator(n.overridingRootKey,this.unityNote),a){let o=a.loopStart-t.loopStart,h=a.loopStart+a.loopLength-t.loopEnd;if(o!==0){let g=o%32768;e.setGenerator(n.startloopAddrsOffset,g);let f=Math.trunc(o/32768);f!==0&&e.setGenerator(n.startloopAddrsCoarseOffset,f)}if(h!==0){let g=h%32768;e.setGenerator(n.endloopAddrsOffset,g);let f=Math.trunc(h/32768);f!==0&&e.setGenerator(n.endloopAddrsCoarseOffset,f)}}}write(){let e=new K(kt+this.loops.length*Dt);Y(e,kt),G(e,this.unityNote),G(e,this.fineTune),Y(e,this.gain),Y(e,this.fulOptions),Y(e,this.loops.length);for(let t of this.loops)Y(e,Dt),Y(e,t.loopType),Y(e,t.loopStart),Y(e,t.loopLength);return D.write("wsmp",e)}},xt={PCM:1,ALAW:6};function vs(A,e){let t=Math.pow(2,e*8-1),s=Math.pow(2,e*8),a,i=!1;e===1?(a=255,i=!0):a=t;let o=A.length/e,h=new Float32Array(o);if(e===2){let g=new Int16Array(A.buffer),f=g.length;for(let l=0;l=t&&(f-=s),h[g]=f/a)}return h}function Ms(A,e){let t=A.length/e,s=new Float32Array(t);for(let a=0;a>4,g=o&15;h>0&&(g+=16),g=(g<<4)+8,h>1&&(g=g<127?g:-g)/32768}return s}var Rs=class extends jt{wFormatTag;bytesPerSample;rawData;constructor(A,e,t,s,a,i,o,h,g){super(A,e,t,s,he.monoSample,a,i),this.dataOverridden=!1,this.rawData=o.data,this.wFormatTag=h,this.bytesPerSample=g}getAudioData(){if(!this.rawData)return new Float32Array(0);if(!this.audioData){let A;switch(this.wFormatTag){default:u.warn(`Failed to decode sample. Unknown wFormatTag: ${this.wFormatTag}`),A=new Float32Array(this.rawData.length/this.bytesPerSample);break;case xt.PCM:A=vs(this.rawData,this.bytesPerSample);break;case xt.ALAW:A=Ms(this.rawData,this.bytesPerSample);break}this.setAudioData(A,this.sampleRate)}return this.audioData??new Float32Array(0)}getRawData(A){return this.dataOverridden||this.isCompressed?super.getRawData(A):this.wFormatTag===xt.PCM&&this.bytesPerSample===2?this.rawData:this.encodeS16LE()}},dA=class Xt extends ct{waveSample=new lt;wFormatTag;bytesPerSample;sampleRate;dataChunk;name="Unnamed sample";constructor(e,t,s,a){super(),this.wFormatTag=e,this.bytesPerSample=t,this.sampleRate=s,this.dataChunk=a}static read(e){let t=this.verifyAndReadList(e,"wave"),s=t.find(p=>p.header==="fmt ");if(!s)throw new Error("No fmt chunk in the wave file!");let a=P(s.data,2),i=P(s.data,2);if(i!==1)throw new Error(`Only mono samples are supported. Fmt reports ${i} channels.`);let o=P(s.data,4);P(s.data,4),P(s.data,2);let h=P(s.data,2)/8,g=t.find(p=>p.header==="data");if(!g)throw new Error("No data chunk in the WAVE chunk!");let f=new Xt(a,h,o,g),l=D.findListType(t,"INFO");if(l){let p=D.read(l.data);for(;p.header!=="INAM"&&l.data.currentIndexp.header==="wsmp");return Q&&(f.waveSample=lt.read(Q)),f}static fromSFSample(e){let t=e.getRawData(!1),s=new Xt(1,2,e.sampleRate,new D("data",t.length,new K(t.buffer)));return s.name=e.name,s.waveSample=lt.fromSFSample(e),s}toSFSample(e){let t=this.waveSample.unityNote,s=this.waveSample.fineTune,a=Math.trunc(s/100);t+=a,s-=a*100;let i=0,o=0,h=this.waveSample.loops?.[0];h&&(i=h.loopStart,o=h.loopStart+h.loopLength);let g=new Rs(this.name,this.sampleRate,t,s,i,o,this.dataChunk,this.wFormatTag,this.bytesPerSample);e.addSamples(g)}write(){let e=this.writeFmt(),t=this.waveSample.write(),s=D.getParts("data",[this.dataChunk.data]),a=D.write("INAM",Xe(this.name,!0)),i=D.write("INFO",a,!1,!0);return u.info(`%cSaved %c${this.name}%c successfully!`,I.recognized,I.value,I.recognized),D.getParts("wave",[e,t,...s,i],!1,!0)}writeFmt(){let e=new K(18);return G(e,this.wFormatTag),G(e,1),Y(e,this.sampleRate),Y(e,this.sampleRate*2),G(e,2),G(e,this.bytesPerSample*8),D.write("fmt ",e)}},Ge=class Wt{source;transform;bipolar;invert;constructor(e=S.none,t=z.linear,s=!1,a=!1){this.source=e,this.transform=t,this.bipolar=s,this.invert=a}get sourceName(){return Object.keys(S).find(e=>S[e]===this.source)??this.source.toString()}get transformName(){return Object.keys(z).find(e=>z[e]===this.transform)??this.transform.toString()}static copyFrom(e){return new Wt(e.source,e.transform,e.bipolar,e.invert)}static fromSFSource(e){let t;if(e.isCC)switch(e.index){case m.modulationWheel:t=S.modulationWheel;break;case m.mainVolume:t=S.volume;break;case m.pan:t=S.pan;break;case m.expression:t=S.expression;break;case m.chorusDepth:t=S.chorus;break;case m.reverbDepth:t=S.reverb;break}else switch(e.index){case se.noController:t=S.none;break;case se.noteOnKeyNum:t=S.keyNum;break;case se.noteOnVelocity:t=S.velocity;break;case se.pitchWheel:t=S.pitchWheel;break;case se.pitchWheelRange:t=S.pitchWheelRange;break;case se.polyPressure:t=S.polyPressure;break;case se.channelPressure:t=S.channelPressure}if(t!==void 0)return new Wt(t,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,t=!1;switch(this.source){default:case S.modLfo:case S.vibratoLfo:case S.coarseTune:case S.fineTune:case S.modEnv:return;case S.keyNum:e=se.noteOnKeyNum;break;case S.none:e=se.noController;break;case S.modulationWheel:e=m.modulationWheel,t=!0;break;case S.pan:e=m.pan,t=!0;break;case S.reverb:e=m.reverbDepth,t=!0;break;case S.chorus:e=m.chorusDepth,t=!0;break;case S.expression:e=m.expression,t=!0;break;case S.volume:e=m.mainVolume,t=!0;break;case S.velocity:e=se.noteOnVelocity;break;case S.polyPressure:e=se.polyPressure;break;case S.channelPressure:e=se.channelPressure;break;case S.pitchWheel:e=se.pitchWheel;break;case S.pitchWheelRange:e=se.pitchWheelRange;break}if(e!==void 0)return new Oe(e,this.transform,t,this.bipolar,this.invert)}},qA=new re(219,0,n.reverbEffectsSend,1e3,0),JA=new re(221,0,n.chorusEffectsSend,1e3,0);new re(129,0,n.vibLfoToPitch,0,0);new re(13,0,n.vibLfoToPitch,0,0);var Fs=new Set([n.sampleModes,n.initialAttenuation,n.keyRange,n.velRange,n.sampleID,n.fineTune,n.coarseTune,n.startAddrsOffset,n.startAddrsCoarseOffset,n.endAddrOffset,n.endAddrsCoarseOffset,n.startloopAddrsOffset,n.startloopAddrsCoarseOffset,n.endloopAddrsOffset,n.endloopAddrsCoarseOffset,n.overridingRootKey,n.exclusiveClass]),dt=class et{source;control;destination;scale;transform;constructor(e=new Ge,t=new Ge,s,a,i){this.source=e,this.control=t,this.destination=s,this.transform=a,this.scale=i}get isStaticParameter(){return this.source.source===S.none&&this.control.source===S.none}get shortScale(){return this.scale>>16}get transformName(){return Object.keys(z).find(e=>z[e]===this.transform)??this.transform.toString()}get destinationName(){return Object.keys(d).find(e=>d[e]===this.destination)??this.destination.toString()}static read(e){let t=P(e,2),s=P(e,2),a=P(e,2),i=P(e,2),o=P(e,4)|0,h=i&15,g=new Ge(s,i>>4&15,At(i,8),At(i,9));return new et(new Ge(t,i>>10&15,At(i,14),At(i,15)),g,a,h,o)}static fromSFModulator(e,t){let s=l=>{u.warn(`Failed converting SF modulator into DLS: ${e.toString()} (${l})`)};if(e.transformType!==0){s("Absolute transform type is not supported");return}if(oe.isIdentical(e,JA,!0)||oe.isIdentical(e,qA,!0))return;let a=Ge.fromSFSource(e.primarySource);if(!a){s("Invalid primary source");return}let i=Ge.fromSFSource(e.secondarySource);if(!i){s("Invalid secondary source");return}let o=et.fromSFDestination(e.destination,e.transformAmount);if(o===void 0){s("Invalid destination");return}let h=e.transformAmount,g;if(typeof o=="number")g=o;else if(g=o.destination,h=o.amount,o.source!==S.none){if(i.source!==S.none&&a.source!==S.none){s("Articulation generators with secondary source are not supported");return}a.source!==S.none&&(i=a),a=new Ge(o.source,z.linear,o.isBipolar)}let f=new et(a,i,g,0,h<<16);t.connectionBlocks.push(f)}static copyFrom(e){return new et(Ge.copyFrom(e.source),Ge.copyFrom(e.control),e.destination,e.transform,e.scale)}static fromSFGenerator(e,t){if(Fs.has(e.type))return;let s=g=>{u.warn(`Failed converting SF2 generator into DLS: ${e.toString()} (${g})`)},a=et.fromSFDestination(e.type,e.value);if(a===void 0){s("Invalid type");return}let i=new Ge,o,h=e.value;typeof a=="number"?o=a:(o=a.destination,h=a.amount,i.source=a.source,i.bipolar=a.isBipolar),t.connectionBlocks.push(new et(i,new Ge,o,0,h<<16))}static fromSFDestination(e,t){switch(e){default:return;case n.initialAttenuation:return{destination:d.gain,amount:-t,isBipolar:!1,source:S.none};case n.fineTune:return d.pitch;case n.pan:return d.pan;case n.keyNum:return d.keyNum;case n.reverbEffectsSend:return d.reverbSend;case n.chorusEffectsSend:return d.chorusSend;case n.freqModLFO:return d.modLfoFreq;case n.delayModLFO:return d.modLfoDelay;case n.delayVibLFO:return d.vibLfoDelay;case n.freqVibLFO:return d.vibLfoFreq;case n.delayVolEnv:return d.volEnvDelay;case n.attackVolEnv:return d.volEnvAttack;case n.holdVolEnv:return d.volEnvHold;case n.decayVolEnv:return d.volEnvDecay;case n.sustainVolEnv:return{destination:d.volEnvSustain,amount:1e3-t,isBipolar:!1,source:S.none};case n.releaseVolEnv:return d.volEnvRelease;case n.delayModEnv:return d.modEnvDelay;case n.attackModEnv:return d.modEnvAttack;case n.holdModEnv:return d.modEnvHold;case n.decayModEnv:return d.modEnvDecay;case n.sustainModEnv:return{destination:d.modEnvSustain,amount:1e3-t,isBipolar:!1,source:S.none};case n.releaseModEnv:return d.modEnvRelease;case n.initialFilterFc:return d.filterCutoff;case n.initialFilterQ:return d.filterQ;case n.modEnvToFilterFc:return{source:S.modEnv,destination:d.filterCutoff,amount:t,isBipolar:!1};case n.modEnvToPitch:return{source:S.modEnv,destination:d.pitch,amount:t,isBipolar:!1};case n.modLfoToFilterFc:return{source:S.modLfo,destination:d.filterCutoff,amount:t,isBipolar:!0};case n.modLfoToVolume:return{source:S.modLfo,destination:d.gain,amount:t,isBipolar:!0};case n.modLfoToPitch:return{source:S.modLfo,destination:d.pitch,amount:t,isBipolar:!0};case n.vibLfoToPitch:return{source:S.vibratoLfo,destination:d.pitch,amount:t,isBipolar:!0};case n.keyNumToVolEnvHold:return{source:S.keyNum,destination:d.volEnvHold,amount:t,isBipolar:!0};case n.keyNumToVolEnvDecay:return{source:S.keyNum,destination:d.volEnvDecay,amount:t,isBipolar:!0};case n.keyNumToModEnvHold:return{source:S.keyNum,destination:d.modEnvHold,amount:t,isBipolar:!0};case n.keyNumToModEnvDecay:return{source:S.keyNum,destination:d.modEnvDecay,amount:t,isBipolar:!0};case n.scaleTuning:return{source:S.keyNum,destination:d.pitch,amount:t*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 K(12);return G(e,this.source.source),G(e,this.control.source),G(e,this.destination),G(e,this.transform|this.control.toTransformFlag()<<4|this.source.toTransformFlag()<<10),Y(e,this.scale),e}toSFGenerator(e){let t=this.destination,s=this.shortScale;switch(t){default:u.info(`%cFailed converting DLS articulator into SF generator: %c${this.toString()}%c (invalid destination)`,I.warn,I.value,I.unrecognized);return;case d.pan:e.setGenerator(n.pan,s);break;case d.gain:e.addToGenerator(n.initialAttenuation,-s/.4);break;case d.filterCutoff:e.setGenerator(n.initialFilterFc,s);break;case d.filterQ:e.setGenerator(n.initialFilterQ,s);break;case d.modLfoFreq:e.setGenerator(n.freqModLFO,s);break;case d.modLfoDelay:e.setGenerator(n.delayModLFO,s);break;case d.vibLfoFreq:e.setGenerator(n.freqVibLFO,s);break;case d.vibLfoDelay:e.setGenerator(n.delayVibLFO,s);break;case d.volEnvDelay:e.setGenerator(n.delayVolEnv,s);break;case d.volEnvAttack:e.setGenerator(n.attackVolEnv,s);break;case d.volEnvHold:e.setGenerator(n.holdVolEnv,s);break;case d.volEnvDecay:e.setGenerator(n.decayVolEnv,s);break;case d.volEnvRelease:e.setGenerator(n.releaseVolEnv,s);break;case d.volEnvSustain:e.setGenerator(n.sustainVolEnv,1e3-s);break;case d.modEnvDelay:e.setGenerator(n.delayModEnv,s);break;case d.modEnvAttack:e.setGenerator(n.attackModEnv,s);break;case d.modEnvHold:e.setGenerator(n.holdModEnv,s);break;case d.modEnvDecay:e.setGenerator(n.decayModEnv,s);break;case d.modEnvRelease:e.setGenerator(n.releaseModEnv,s);break;case d.modEnvSustain:e.setGenerator(n.sustainModEnv,1e3-s);break;case d.reverbSend:e.setGenerator(n.reverbEffectsSend,s);break;case d.chorusSend:e.setGenerator(n.chorusEffectsSend,s);break;case d.pitch:e.fineTuning+=s;break}}toSFModulator(e){let t=this.shortScale,s,a,i=new Oe,o=this.toCombinedSFDestination();if(o){s=o;let g=this.control.toSFSource();if(!g){this.failedConversion("Invalid control");return}a=g}else{let g=this.toSFDestination();if(!g){this.failedConversion("Invalid destination");return}typeof g=="object"?(t=g.newAmount,s=g.gen):s=g;let f=this.source.toSFSource();if(!f){this.failedConversion("Invalid source");return}a=f;let l=this.control.toSFSource();if(!l){this.failedConversion("Invalid control");return}i=l}this.transform!==z.linear&&a.curveType===z.linear&&(a.curveType=this.transform),s===n.initialAttenuation&&((this.source.source===S.velocity||this.source.source===S.volume||this.source.source===S.expression)&&(a.isNegative=!0),t=Math.min(960,Math.max(0,t)));let h=new oe(a,i,s,t,0);e.addModulators(h)}toCombinedSFDestination(){let e=this.source.source,t=this.destination;return e===S.vibratoLfo&&t===d.pitch?n.vibLfoToPitch:e===S.modLfo&&t===d.pitch?n.modLfoToPitch:e===S.modLfo&&t===d.filterCutoff?n.modLfoToFilterFc:e===S.modLfo&&t===d.gain?n.modLfoToVolume:e===S.modEnv&&t===d.filterCutoff?n.modEnvToFilterFc:e===S.modEnv&&t===d.pitch?n.modEnvToPitch:void 0}failedConversion(e){u.info(`%cFailed converting DLS articulator into SF2: %c${this.toString()}%c (${e})`,I.warn,I.value,I.unrecognized)}toSFDestination(){let e=this.shortScale;switch(this.destination){default:case d.none:return;case d.pan:return n.pan;case d.gain:return{gen:n.initialAttenuation,newAmount:-e};case d.pitch:return n.fineTune;case d.keyNum:return n.overridingRootKey;case d.volEnvDelay:return n.delayVolEnv;case d.volEnvAttack:return n.attackVolEnv;case d.volEnvHold:return n.holdVolEnv;case d.volEnvDecay:return n.decayVolEnv;case d.volEnvSustain:return{gen:n.sustainVolEnv,newAmount:1e3-e};case d.volEnvRelease:return n.releaseVolEnv;case d.modEnvDelay:return n.delayModEnv;case d.modEnvAttack:return n.attackModEnv;case d.modEnvHold:return n.holdModEnv;case d.modEnvDecay:return n.decayModEnv;case d.modEnvSustain:return{gen:n.sustainModEnv,newAmount:1e3-e};case d.modEnvRelease:return n.releaseModEnv;case d.filterCutoff:return n.initialFilterFc;case d.filterQ:return n.initialFilterQ;case d.chorusSend:return n.chorusEffectsSend;case d.reverbSend:return n.reverbEffectsSend;case d.modLfoFreq:return n.freqModLFO;case d.modLfoDelay:return n.delayModLFO;case d.vibLfoFreq:return n.freqVibLFO;case d.vibLfoDelay:return n.delayVibLFO}}},KA=class extends ct{connectionBlocks=new Array;mode="dls2";get length(){return this.connectionBlocks.length}copyFrom(A){this.mode=A.mode;for(let e of A.connectionBlocks)this.connectionBlocks.push(dt.copyFrom(e))}fromSFZone(A){this.mode="dls2";let e=new Qt;e.copyFrom(A);for(let t of e.generators){let s;switch(t.type){default:continue;case n.keyNumToVolEnvDecay:s=n.decayVolEnv;break;case n.keyNumToVolEnvHold:s=n.holdVolEnv;break;case n.keyNumToModEnvDecay:s=n.decayModEnv;break;case n.keyNumToModEnvHold:s=n.holdModEnv}let a=e.getGenerator(s,void 0),i=t.value*-128;if(a===void 0)continue;let o=a-60/128*i;e.setGenerator(t.type,i,!1),e.setGenerator(s,o,!1)}for(let t of e.generators)dt.fromSFGenerator(t,this);for(let t of e.modulators)dt.fromSFModulator(t,this)}read(A){let e=D.findListType(A,"lart"),t=D.findListType(A,"lar2");if(e)for(this.mode="dls1";e.data.currentIndexs.write()),t=D.getParts(this.mode==="dls2"?"art2":"art1",[A,...e]);return D.getParts(this.mode==="dls2"?"lar2":"lart",t,!0)}toSFZone(A){let e=(t,s,a,i)=>{let o=t/-128;if(A.setGenerator(s,o),o<=120){let h=Math.round(.46875*t),g=this.connectionBlocks.find(f=>f.isStaticParameter&&f.destination===i);g&&A.setGenerator(a,h+g.shortScale)}};for(let t of this.connectionBlocks){let s=t.shortScale,a=t.source.source,i=t.control.source,o=t.destination;if(t.isStaticParameter){t.toSFGenerator(A);continue}if(i===S.none)if(a===S.keyNum){if(o===d.pitch){A.setGenerator(n.scaleTuning,s/128);continue}if(o===d.modEnvHold||o===d.modEnvDecay||o===d.volEnvHold||o===d.volEnvDecay)continue}else{let h=t.toCombinedSFDestination();if(h){A.setGenerator(h,s);continue}}t.toSFModulator(A)}for(let t of this.connectionBlocks){if(t.source.source!==S.keyNum)continue;let s=t.shortScale;switch(t.destination){default:case d.volEnvHold:e(s,n.keyNumToVolEnvHold,n.holdVolEnv,d.volEnvHold);break;case d.volEnvDecay:e(s,n.keyNumToVolEnvDecay,n.decayVolEnv,d.volEnvDecay);break;case d.modEnvHold:e(s,n.keyNumToModEnvHold,n.holdModEnv,d.modEnvHold);break;case d.modEnvDecay:e(s,n.keyNumToModEnvDecay,n.decayModEnv,d.modEnvDecay);break}}if(this.mode==="dls1"){A.setGenerator(n.delayVibLFO,A.getGenerator(n.delayModLFO,null)),A.setGenerator(n.freqVibLFO,A.getGenerator(n.freqModLFO,null)),A.setGenerator(n.vibLfoToPitch,A.getGenerator(n.modLfoToPitch,null)),A.setGenerator(n.modLfoToPitch,null);for(let t of A.modulators)t.destination===n.modLfoToPitch&&(t.destination=n.vibLfoToPitch)}}},Ut=class wt{channel=1;tableIndex;fusOptions=0;phaseGroup=0;constructor(e){this.tableIndex=e}static copyFrom(e){let t=new wt(e.tableIndex);return t.channel=e.channel,t.phaseGroup=e.phaseGroup,t.fusOptions=e.fusOptions,t}static read(e){let t=P(e.data,2),s=P(e.data,2),a=P(e.data,4),i=new wt(P(e.data,4));return i.channel=a,i.fusOptions=t,i.phaseGroup=s,i}static fromSFZone(e,t){let s=e.indexOf(t.sample);if(s===-1)throw new Error(`Wave link error: Sample ${t.sample.name} does not exist in the sample list.`);let a=new wt(s);switch(t.sample.sampleType){default:case he.leftSample:case he.monoSample:a.channel=Math.trunc(1);break;case he.rightSample:a.channel=2}return a}write(){let e=new K(12);return G(e,this.fusOptions),G(e,this.phaseGroup),Y(e,this.channel),Y(e,this.tableIndex),D.write("wlnk",e)}},bt=class ht extends ct{articulation=new KA;keyRange={min:0,max:127};velRange={min:0,max:127};keyGroup=0;fusOptions=0;usLayer=0;waveSample;waveLink;constructor(e,t){super(),this.waveSample=t,this.waveLink=e}static copyFrom(e){let t=new ht(Ut.copyFrom(e.waveLink),lt.copyFrom(e.waveSample));return t.keyGroup=e.keyGroup,t.keyRange={...e.keyRange},t.velRange={...e.velRange},t.usLayer=e.usLayer,t.fusOptions=e.fusOptions,t.articulation.copyFrom(e.articulation),t}static read(e,t){let s=this.verifyAndReadList(t,"rgn ","rgn2"),a=s.find(M=>M.header==="wsmp"),i=a?lt.read(a):void 0,o=s.find(M=>M.header==="wlnk");if(!o){u.warn("Invalid DLS region: missing 'wlnk' chunk! Discarding...");return}let h=Ut.read(o),g=s.find(M=>M.header==="rgnh");if(!g){u.warn("Invalid DLS region: missing 'rgnh' chunk! Discarding...");return}let f=e[h.tableIndex];f||ht.parsingError(`Invalid sample index: ${h.tableIndex}. Samples available: ${e.length}`),i??=f.waveSample;let l=new ht(h,i),Q=P(g.data,2),p=P(g.data,2),r=P(g.data,2),B=P(g.data,2);return r===0&&B===0&&(B=127,r=0),l.keyRange.max=p,l.keyRange.min=Q,l.velRange.max=B,l.velRange.min=r,l.fusOptions=P(g.data,2),l.keyGroup=P(g.data,2),g.data.length-g.data.currentIndex>=2&&(l.usLayer=P(g.data,2)),l.articulation.read(s),l}static fromSFZone(e,t){let s=lt.fromSFZone(e),a=new ht(Ut.fromSFZone(t,e),s);return a.keyRange.min=Math.max(e.keyRange.min,0),a.keyRange.max=e.keyRange.max,a.velRange.min=Math.max(e.velRange.min,0),a.velRange.max=e.velRange.max,a.keyGroup=e.getGenerator(n.exclusiveClass,0),a.articulation.fromSFZone(e),a}write(){let e=[this.writeHeader(),this.waveSample.write(),this.waveLink.write(),...this.articulation.write()];return D.getParts("rgn2",e,!1,!0)}toSFZone(e,t){let s=t[this.waveLink.tableIndex];s||ht.parsingError(`Invalid sample index: ${this.waveLink.tableIndex}`);let a=e.createZone(s);return a.keyRange=this.keyRange,a.velRange=this.velRange,this.keyRange.max===127&&this.keyRange.min===0&&(a.keyRange.min=-1),this.velRange.max===127&&this.velRange.min===0&&(a.velRange.min=-1),this.keyGroup!==0&&a.setGenerator(n.exclusiveClass,this.keyGroup),this.waveSample.toSFZone(a,s),this.articulation.toSFZone(a),a.generators=a.generators.filter(i=>i.value!==xe[i.type].def),a}writeHeader(){let e=new K(14);return G(e,Math.max(this.keyRange.min,0)),G(e,this.keyRange.max),G(e,Math.max(this.velRange.min,0)),G(e,this.velRange.max),G(e,this.fusOptions),G(e,this.keyGroup),G(e,this.usLayer),D.write("rgnh",e)}},Ht=class vt extends ct{articulation=new KA;regions=new Array;name="Unnamed";bankLSB=0;bankMSB=0;isGMGSDrum=!1;program=0;static copyFrom(e){let t=new vt;t.name=e.name,t.isGMGSDrum=e.isGMGSDrum,t.bankMSB=e.bankMSB,t.bankLSB=e.bankLSB,t.program=e.program,t.articulation.copyFrom(e.articulation);for(let s of e.regions)t.regions.push(bt.copyFrom(s));return t}static read(e,t){let s=this.verifyAndReadList(t,"ins "),a=s.find(Q=>Q.header==="insh");if(!a)throw u.groupEnd(),new Error("No instrument header!");let i="",o=D.findListType(s,"INFO");if(o){let Q=D.read(o.data);for(;Q.header!=="INAM";)Q=D.read(o.data);i=Ve(Q.data,Q.data.length).trim()}i.length===0&&(i="Unnamed Instrument");let h=new vt;h.name=i;let g=P(a.data,4),f=P(a.data,4);h.program=P(a.data,4)&127,h.bankMSB=f>>>8&127,h.bankLSB=f&127,h.isGMGSDrum=f>>>31>0,u.groupCollapsed(`%cParsing %c"${i}"%c...`,I.info,I.recognized,I.info);let l=D.findListType(s,"lrgn");if(!l)throw u.groupEnd(),new Error("No region list!");h.articulation.read(s);for(let Q=0;Qa.write());e.push(...D.getParts("lrgn",t,!1,!0)),this.articulation.length>0&&e.push(...this.articulation.write());let s=D.write("INAM",Xe(this.name,!0));return e.push(D.write("INFO",s,!1,!0)),u.groupEnd(),D.writeParts("ins ",e,!1,!0)}toSFPreset(e){let t=new Vt(e);t.name=this.name,t.bankMSB=this.bankMSB,t.bankLSB=this.bankLSB,t.isGMGSDrum=this.isGMGSDrum,t.program=this.program;let s=new Lt;s.name=this.name,t.createZone(s),this.articulation.toSFZone(s.globalZone);for(let a of this.regions)a.toSFZone(s,e.samples);s.globalize(),s.globalZone.modulators.some(a=>a.destination===n.reverbEffectsSend)||s.globalZone.addModulators(oe.copyFrom(qA)),s.globalZone.modulators.some(a=>a.destination===n.chorusEffectsSend)||s.globalZone.addModulators(oe.copyFrom(JA)),s.globalZone.generators=s.globalZone.generators.filter(a=>a.value!==xe[a.type].def),e.addPresets(t),e.addInstruments(s)}writeHeader(){let e=new K(12);Y(e,this.regions.length);let t=(this.bankMSB&127)<<8|this.bankLSB&127;return this.isGMGSDrum&&(t|=1<<31),Y(e,t),Y(e,this.program&127),D.write("insh",e)}},Zt={software:"SpessaSynth"},Gs=class _t extends ct{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 t=new K(e);u.group("%cParsing DLS file...",I.info);let s=D.read(t,!1,!1);this.verifyHeader(s,"RIFF"),this.verifyText(Ve(t,4).toLowerCase(),"dls ");let a=[];for(;t.currentIndexB.header==="colh");if(!h)return this.parsingError("No colh chunk!"),5;let g=P(h.data,4);u.info(`%cInstruments amount: %c${g}`,I.info,I.recognized);let f=D.findListType(a,"wvpl");if(!f)return this.parsingError("No wvpl chunk!"),5;let l=this.verifyAndReadList(f,"wvpl");for(let B of l)i.samples.push(dA.read(B));let Q=D.findListType(a,"lins");if(!Q)return this.parsingError("No lins chunk!"),5;let p=this.verifyAndReadList(Q,"lins");u.groupCollapsed("%cLoading instruments...",I.info),p.length!==g&&u.warn(`Colh reported invalid amount of instruments. Detected ${p.length}, expected ${g}`);for(let B of p)i.instruments.push(Ht.read(i.samples,B));u.groupEnd();let r=a.find(B=>B.header==="pgal");if(r){u.info("%cFound the instrument aliasing chunk!",I.recognized);let B=r.data;(B[0]!==0||B[1]!==1||B[2]!==2||B[3]!==3)&&(B.currentIndex+=4);let M=i.instruments.find(y=>tt.isXGDrum(y.bankMSB)||y.isGMGSDrum);if(!M)return u.warn("MobileBAE aliasing chunk without a drum preset. Aborting!"),i;let T=B.slice(B.currentIndex,B.currentIndex+128);B.currentIndex+=128;for(let y=0;y<128;y++){let $=T[y];if($===y)continue;let F=M.regions.find(N=>N.keyRange.max===$&&N.keyRange.min===$);if(!F){u.warn(`Invalid drum alias ${y} to ${$}: region does not exist.`);continue}let Z=bt.copyFrom(F);Z.keyRange.max=y,Z.keyRange.min=y,M.regions.push(Z)}for(B.currentIndex+=4;B.currentIndex>7&127,Z=B[B.currentIndex++],N=B[B.currentIndex++];N!==0&&u.warn(`Invalid alias byte. Expected 0, got ${N}`);let q=P(B,2),ce=q&127,j=q>>7&127,ee=B[B.currentIndex++];N=B[B.currentIndex++],N!==0&&u.warn(`Invalid alias header. Expected 0, got ${N}`);let V=i.instruments.find(ne=>ne.bankLSB===ce&&ne.bankMSB===j&&ne.program===ee&&!ne.isGMGSDrum);if(!V){u.warn(`Invalid alias. Missing instrument: ${ce}:${j}:${ee}`);continue}let ae=Ht.copyFrom(V);ae.bankMSB=F,ae.bankLSB=$,ae.program=Z,i.instruments.push(ae)}}return u.info(`%cParsing finished! %c"${i.soundBankInfo.name||"UNNAMED"}"%c has %c${i.instruments.length}%c instruments and %c${i.samples.length}%c samples.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),u.groupEnd(),i}static fromSF(e,t){u.groupCollapsed("%cSaving SF2 to DLS level 2...",I.info);let s=new _t;s.soundBankInfo={...e.soundBankInfo};for(let a=0;ay.write()),!1,!0);u.info("%cSuccess!",I.recognized),u.groupEnd(),u.groupCollapsed("%cWriting WAVE samples...",I.info);let o=0,h=[],g=[],f=0;for(let y of this.samples){let $=y.write();t.progressFunction?.(f/this.samples.length),u.info(`%cWrote sample %c${f}. ${y.name}%c of %c${this.samples.length}.`,I.info,I.recognized,I.info,I.recognized),h.push(o),o+=$.reduce((F,Z)=>F+Z.length,0),g.push(...$),f++}let l=D.getParts("wvpl",g,!1,!0);u.info("%cSucceeded!",I.recognized);let Q=new K(8+4*h.length);Y(Q,8),Y(Q,h.length);for(let y of h)Y(Q,y);let p=D.write("ptbl",Q);this.soundBankInfo.software=t.software;let r=[],B=this.soundBankInfo,M=(y,$)=>{$&&r.push(...D.getParts(y,[Xe($,!0)]))};M("INAM",B.name),M("ICMT",B.comment),M("ICOP",B.copyright),M("ICRD",kA(B.creationDate)),M("IENG",B.engineer),M("IPRD",B.product),M("ISFT",t.software),M("ISBJ",B.subject),u.info("%cCombining everything...");let T=D.writeParts("RIFF",[Xe("DLS "),a,...i,p,...l,...D.getParts("INFO",r,!1,!0)]);return u.info("%cSaved successfully!",I.recognized),u.groupEnd(),T.buffer}toSF(){u.group("%cConverting DLS to SF2...",I.info);let e=new VA("dls");e.soundBankInfo.version.minor=4,e.soundBankInfo.version.major=2,e.soundBankInfo={...this.soundBankInfo};for(let t of this.samples)t.toSFSample(e);for(let t of this.instruments)t.toSFPreset(e);return e.flush(),u.info("%cConversion complete!",I.recognized),u.groupEnd(),e}},VA=class Mt{static isSF3DecoderReady=bA.isInitialized;type;soundBankInfo={name:"Unnamed",creationDate:new Date,software:"SpessaSynth",soundEngine:"E-mu 10K2",version:{major:2,minor:4}};presets=[];samples=[];instruments=[];defaultModulators=UA.map(oe.copyFrom.bind(oe));customDefaultModulators=!1;constructor(e="sf2"){this.type=e}_isXGBank=!1;get isXGBank(){return this._isXGBank}static mergeSoundBanks(...e){let t=e.shift();if(!t)throw new Error("No sound banks provided!");let s=t.presets;for(;e.length>0;){let i=e?.shift()?.presets;if(i)for(let o of i)s.some(h=>o.matches(h))||s.push(o)}let a=new Mt;return a.addCompletePresets(s),a.soundBankInfo={...t.soundBankInfo},a}static getSampleSoundBankFile(){let e=new Mt,t=new Float32Array(128);for(let o=0;o<128;o++)t[o]=o/128*2-1;let s=new ms;s.name="Saw",s.originalKey=65,s.pitchCorrection=20,s.loopEnd=128,s.setAudioData(t,44100),e.addSamples(s);let a=new Lt;a.name="Saw Wave",a.globalZone.addGenerators(new Be(n.initialAttenuation,375),new Be(n.releaseVolEnv,-1e3),new Be(n.sampleModes,1)),a.createZone(s),a.createZone(s).setGenerator(n.fineTune,-9),e.addInstruments(a);let i=new Vt(e);return i.name="Saw Wave",i.createZone(a),e.addPresets(i),e.soundBankInfo.name="SpessaSynth Sample Sound Bank",e.flush(),e.writeSF2()}static copyFrom(e){let t=new Mt;for(let s of e.presets)t.clonePreset(s);return t.soundBankInfo={...e.soundBankInfo},t}addCompletePresets(e){this.addPresets(...e);let t=[];for(let a of e)for(let i of a.zones)i.instrument&&!t.includes(i.instrument)&&t.push(i.instrument);this.addInstruments(...t);let s=[];for(let a of t)for(let i of a.zones)i.sample&&!s.includes(i.sample)&&s.push(i.sample);this.addSamples(...s)}async setSampleFormat(e){let t=0,s=e.format,a=e.progressFunction;for(let i of this.samples){switch(s){default:case"pcm":i.setAudioData(i.getAudioData(),i.sampleRate);break;case"compressed":{let o=e.compressionFunction;if(!o)throw new Error(`No compression function supplied but '${s}' was requested.`);await i.compressSample(o)}}t++,a?.(t/this.samples.length),u.info(`%cEncoded sample %c${t}. ${i.name}%c of %c${this.samples.length}%c. Compressed: %c${i.isCompressed}%c.`,I.info,I.recognized,I.info,I.recognized,I.info,i.isCompressed?I.recognized:I.unrecognized,I.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=Zt){let t=e.progressFunction;return Gs.fromSF(this,t?s=>t(s/2):void 0).write({...e,progressFunction:t?s=>t(.5+s/2):void 0})}writeSF2(e=HA){return ws(this,e)}writeSFE(e=OA){return bs(this,e)}addPresets(...e){this.presets.push(...e)}addInstruments(...e){this.instruments.push(...e)}addSamples(...e){this.samples.push(...e)}cloneSample(e){let t=this.samples.find(a=>a.name===e.name);if(t)return t;let s=new jt(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 a=this.cloneSample(e.linkedSample);a.linkedSample||s.setLinkedSample(a,s.sampleType)}return s}cloneInstrument(e){let t=this.instruments.find(a=>a.name===e.name);if(t)return t;let s=new Lt;s.name=e.name,s.globalZone.copyFrom(e.globalZone);for(let a of e.zones)s.createZone(this.cloneSample(a.sample)).copyFrom(a);return this.addInstruments(s),s}clonePreset(e){let t=this.presets.find(a=>a.name===e.name);if(t)return t;let s=new Vt(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 a of e.zones)s.createZone(this.cloneInstrument(a.instrument)).copyFrom(a);return this.addPresets(s),s}flush(){this.presets.sort(It.compare.bind(It)),this.parseInternal()}trim(e){let t=(s,a)=>{let i=0;for(let o=0;o=g.min&&Q<=g.max&&[...p].some(r=>r>=f.min&&r<=f.max)){l=!0;break}l||(u.info(`%c${h.sample.name}%c removed from %c${s.name}%c.`,I.recognized,I.info,I.recognized,I.info),s.deleteZone(o)&&(i++,o--,u.info(`%c${h.sample.name}%c deleted`,I.recognized,I.info)),h.sample.useCount<1&&this.deleteSample(h.sample))}return i};u.groupCollapsed("%cTrimming sound bank...",I.info),u.info("Combinations to trim for:",e);for(let s=0;s=f.min&&p<=f.max&&[...r].some(B=>B>=l.min&&B<=l.max)){Q=!0;let B=t(g.instrument,i);u.info(`%cTrimmed off %c${B}%c instrument zones from %c${g.instrument.name}`,I.info,I.recognized,I.info,I.recognized);break}Q||(o++,a.deleteZone(h),g.instrument.useCount<1&&this.deleteInstrument(g.instrument),h--)}u.info(`%cTrimmed off %c${o}%c preset zones from %c${a.name}`,I.info,I.recognized,I.info,I.recognized),u.groupEnd()}}this.removeUnusedElements(),u.info("%cSound bank modified!",I.recognized),u.groupEnd()}removeUnusedElements(){this.instruments=this.instruments.filter(e=>{e.deleteUnusedZones();let t=e.useCount<1;return t&&e.delete(),!t}),this.samples=this.samples.filter(e=>{let t=e.useCount<1;return t&&e.unlinkSample(),!t})}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,t){return It.selectPatch(this.presets,e,t)}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 t of this.presets)if(tt.isXGDrum(t.bankMSB)&&(this._isXGBank=!0,!e.has(t.program))){this._isXGBank=!1,u.info(`%cThis bank is not valid XG. Preset %c${t.toString()}%c is not a valid XG drum. XG mode will use presets on bank 128.`,I.info,I.value,I.info);break}}printInfo(){for(let[e,t]of Object.entries(this.soundBankInfo))if(typeof t=="object"&&"major"in t){let s=t;u.info(`%c${e}: %c"${s.major}.${s.minor}"`,I.info,I.recognized)}else u.info(`%c${e}: %c${t.toLocaleString()}`,I.info,I.recognized)}};var Ls=class XA extends oe{isEffectModulator;isDefaultResonantModulator;isModWheelModulator;constructor(e,t,s,a,i,o,h,g){super(e,t,s,a,i),this.isEffectModulator=o,this.isDefaultResonantModulator=h,this.isModWheelModulator=g}static fromData(e,t,s,a,i){let o=e.toSourceEnum(),h=t.toSourceEnum();return new XA(e,t,s,a,i,(o===219||o===221)&&h===0&&(s===n.reverbEffectsSend||s===n.chorusEffectsSend),o===xA&&h===0&&s===n.initialFilterQ,(e.isCC&&e.index===m.modulationWheel||t.isCC&&t.index===m.modulationWheel)&&(s===n.modLfoToPitch||s===n.vibLfoToPitch))}static fromModulator(e){return this.fromData(e.primarySource,e.secondarySource,e.destination,e.transformAmount,e.transformType)}};var fA=Math.PI/2,Rt=-500,WA=500,eA=WA-Rt,Ps=new Float32Array(eA+1),Ns=new Float32Array(eA+1);for(let A=Rt;A<=WA;A++){let e=(A-Rt)/eA,t=A-Rt;Ps[t]=Math.cos(fA*e),Ns[t]=Math.sin(fA*e)}var aa=[n.delayModLFO,n.freqModLFO,n.delayVibLFO,n.freqVibLFO,n.delayModEnv,n.attackModEnv,n.holdModEnv,n.decayModEnv,n.sustainModEnv,n.releaseModEnv,n.delayVolEnv,n.attackVolEnv,n.holdVolEnv,n.decayVolEnv,n.sustainVolEnv,n.releaseVolEnv,n.fineTune,n.modLfoToPitch,n.vibLfoToPitch,n.modEnvToPitch,n.modLfoToVolume,n.initialFilterFc,n.initialFilterQ,n.modLfoToFilterFc,n.modEnvToFilterFc,n.chorusEffectsSend,n.reverbEffectsSend];var na=[Ls.fromModulator(new re(be(z.linear,!0,!1,!0,m.vibratoRate),0,n.vibLfoRate,1e3,0))];var ra=1e3/200;var tA={pitchWheel:8192,pitchWheelRange:2,pressure:0,modulationDepth:50,rxChannel:0,polyMode:!0,keyShift:0,fineTune:0,randomPan:!1,assignMode:2,efxAssign:!1,cc1:16,cc2:17,drumMap:0,velocitySenseDepth:64,velocitySenseOffset:64};var ZA={presetLock:!1,isMuted:!1,gain:1,pan:0,keyShift:0,fineTune:0,interpolationType:null,nrpnParamLock:null,monophonicRetrigger:null};var uA=Math.PI/2,Ft=-64,_A=63,AA=_A-Ft,Ts=new Float32Array(AA+1),xs=new Float32Array(AA+1);for(let A=Ft;A<=_A;A++){let e=(A-Ft)/AA,t=A-Ft;Ts[t]=Math.cos(uA*e),xs[t]=Math.sin(uA*e)}var ia=Math.PI*2;var Us=5,oa=Us*.5;var ga=Math.PI*2;var sA={volume:1,pan:0,keyShift:0,fineTune:0,system:"gs"};var zA={eventsEnabled:!0,oneOutput:!1,audioNodeCreators:void 0},Hs="spessasynth-worklet-processor";function aA(A,e){return{...e,...A}}var Os=class{keyModifiers=[];synth;constructor(A){this.synth=A}addModifier(A,e,t){let s=new vA;s.gain=t?.gain??1,s.velocity=t?.velocity??-1,s.patch=aA(t.patch??{},{isGMGSDrum:!1,bankLSB:-1,bankMSB:-1,program:-1}),this.keyModifiers[A]??=[],this.keyModifiers[A][e]=s,this.sendToWorklet("addMapping",{channel:A,midiNote:e,mapping:s})}getModifier(A,e){return this.keyModifiers?.[A]?.[e]}deleteModifier(A,e){this.sendToWorklet("deleteMapping",{channel:A,midiNote:e}),this.keyModifiers[A]?.[e]!==void 0&&(this.keyModifiers[A][e]=void 0)}clearModifiers(){this.sendToWorklet("clearMappings",null),this.keyModifiers=[]}sendToWorklet(A,e){let t={type:A,data:e};this.synth.post({type:"keyModifierManager",channelNumber:-1,data:t})}},Ys=class{soundBankList;synth;constructor(A){this.soundBankList=[],this.synth=A}get priorityOrder(){return this.soundBankList.map(A=>A.id)}set priorityOrder(A){this.sendToWorklet("rearrangeSoundBanks",A),this.soundBankList.sort((e,t)=>A.indexOf(e.id)-A.indexOf(t.id))}async addSoundBank(A,e,t=0){this.sendToWorklet("addSoundBank",{soundBankBuffer:A,bankOffset:t,id:e},[A]),await this.awaitResponse();let s=this.soundBankList.find(a=>a.id===e);s===void 0?this.soundBankList.push({id:e,bankOffset:t}):s.bankOffset=t}async deleteSoundBank(A){if(this.soundBankList.length<2){u.warn("1 sound bank left. Aborting!");return}if(!this.soundBankList.some(e=>e.id===A)){u.warn(`No sound banks with id of "${A}" found. Aborting!`);return}this.sendToWorklet("deleteSoundBank",A),this.soundBankList=this.soundBankList.filter(e=>e.id!==A),await this.awaitResponse()}async awaitResponse(){return new Promise(A=>this.synth.awaitWorkerResponse("soundBankManager",A))}sendToWorklet(A,e,t=[]){let s={type:"soundBankManager",channelNumber:-1,data:{type:A,data:e}};this.synth.post(s,t)}},qs=class{timeDelay=0;events={noteOff:new Map,noteOn:new Map,controllerChange:new Map,programChange:new Map,polyPressure:new Map,stopAll:new Map,channelAdded:new Map,presetListChange:new Map,reset:new Map,soundBankError:new Map,displayMessage:new Map,globalParamChange:new Map,channelParamChange:new Map,effectChange:new Map};addEvent(A,e,t){this.events[A].set(e,t)}removeEvent(A,e){this.events[A].delete(e)}callEventInternal(A,e){let t=this.events[A],s=()=>{for(let a of t.values())try{a(e)}catch(i){console.error(`Error while executing an event callback for ${A}:`,i)}};this.timeDelay>0?setTimeout(s.bind(this),this.timeDelay*1e3):s()}},Js=SA.ConsoleColors,Ks=class{channel;synth;_systemParameters={...ZA};constructor(A,e){this.channel=A,this.synth=e}_patch={bankMSB:0,bankLSB:0,program:0,isDrum:!1,isGMGSDrum:!1,name:""};get patch(){return this._patch}set patch(A){this._patch=A}_midiParameters={...tA};get midiParameters(){return this._midiParameters}get systemParameters(){return this._systemParameters}_voiceCount=0;get voiceCount(){return this._voiceCount}set voiceCount(A){this._voiceCount=A}lockMIDIParameter(A,e){this.synth.post({type:"lockChannelMIDIParameter",channelNumber:this.channel,data:{parameter:A,isLocked:e}})}setSystemParameter(A,e){this._systemParameters[A]=e,this.synth.post({type:"setChannelSystemParameter",channelNumber:this.channel,data:{parameter:A,value:e}})}lockController(A,e){this.synth.post({channelNumber:this.channel,type:"lockController",data:{controller:A,isLocked:e}})}setDrums(A){this.synth.post({channelNumber:this.channel,type:"setDrums",data:A})}setMIDIParameter(A,e){this._midiParameters[A]=e}reset(){this._midiParameters={...tA}}},Le={time:0},Vs=A=>`SPESSASYNTH_LIB_HANDLE_${A}_${Math.random()}`,Xs=class{soundBankManager=new Ys(this);keyModifierManager=new Os(this);eventHandler=new qs;context;midiChannels=[];presetList=[];sequencers=new Array;isReady;post;worklet;_outputCount=16;_systemParameters={...MA};resolveMap=new Map;renderingProgressTracker=new Map;constructor(A,e,t){u.info("%cInitializing SpessaSynth synthesizer...",Js.info),this.context=A.context,this.worklet=A,this.post=e,this.isReady=new Promise(s=>this.awaitWorkerResponse("sf3Decoder",s)),this.worklet.port.onmessage=s=>this.handleMessage(s.data);for(let s=0;s<16;s++)this.addNewChannelInternal(!1);this.registerInternalEvent("channelAdded",()=>{this.addNewChannelInternal(!1)}),this.registerInternalEvent("presetListChange",s=>this.presetList=[...s]),this.registerInternalEvent("globalParamChange",s=>this._midiParameters[s.parameter]=s.value),this.registerInternalEvent("channelParamChange",s=>this.midiChannels[s.channel].setMIDIParameter(s.parameter,s.value)),this.registerInternalEvent("programChange",s=>this.midiChannels[s.channel].patch={...s}),this.registerInternalEvent("reset",()=>{for(let s of this.midiChannels)s.reset();this._midiParameters={...sA}})}_midiParameters={...sA};get midiParameters(){return this._midiParameters}get channelCount(){return this.midiChannels.length}_voiceCount=0;get voiceCount(){return this._voiceCount}get currentTime(){return this.context.currentTime}get systemParameters(){return this._systemParameters}connect(A){for(let e=0;e<17;e++)this.worklet.connect(A,e);return A}disconnect(A){if(!A){this.worklet.disconnect();return}for(let e=0;e<17;e++)this.worklet.disconnect(A,e);return A}setLogLevel(A,e,t){this.post({channelNumber:-1,type:"setLogLevel",data:{enableInfo:A,enableWarning:e,enableGroup:t}})}lockMIDIParameter(A,e){this.post({type:"lockGlobalMIDIParameter",data:{parameter:A,isLocked:e},channelNumber:-1})}setSystemParameter(A,e){this._systemParameters[A]=e,this.post({type:"setGlobalSystemParameter",channelNumber:-1,data:{parameter:A,value:e}})}async getSnapshot(){return new Promise(A=>{this.awaitWorkerResponse("synthesizerSnapshot",e=>{A(e)}),this.post({type:"requestSynthesizerSnapshot",data:null,channelNumber:-1})})}addNewChannel(){this.addNewChannelInternal(!0)}connectChannel(A,e){return this.worklet.connect(A,e%16+1),A}disconnectChannel(A,e){this.worklet.disconnect(A,e%16+1)}connectIndividualOutputs(A){if(A.length!==this._outputCount)throw new Error(`input nodes amount differs from the system's outputs amount! Expected ${this._outputCount} got ${A.length}`);for(let e=0;e127||e<0)throw new Error(`Invalid controller number: ${e}`);t=Math.floor(t)%128,e=Math.floor(e)%128;let a=A%16,i=A-a;this._sendInternal([qe.controllerChange|a,e,t],i,s)}reset(){this.post({channelNumber:-1,type:"ccReset",data:null})}channelPressure(A,e,t=Le){let s=A%16,a=A-s;e%=128,this.sendMessage([qe.channelPressure|s,e],a,t)}polyPressure(A,e,t,s=Le){let a=A%16,i=A-a;e%=128,t%=128,this.sendMessage([qe.polyPressure|a,e,t],i,s)}pitchWheel(A,e,t=Le){let s=A%16,a=A-s;this.sendMessage([qe.pitchWheel|s,e&127,e>>7],a,t)}pitchWheelRange(A,e,t=Le){this.controllerChange(A,m.registeredParameterMSB,0,t),this.controllerChange(A,m.registeredParameterLSB,0,t),this.controllerChange(A,m.dataEntryMSB,e),this.controllerChange(A,m.registeredParameterMSB,127,t),this.controllerChange(A,m.registeredParameterLSB,127,t),this.controllerChange(A,m.dataEntryMSB,0,t)}programChange(A,e,t=Le){let s=A%16,a=A-s;e%=128,this.sendMessage([qe.programChange|s,e],a,t)}systemExclusive(A,e=0,t=Le){this._sendInternal([qe.systemExclusive,...Array.from(A)],e,t)}tuneKeys(A,e){if(e.length>127)throw new Error("Too many tunings. Maximum allowed is 127.");let t=[127,16,8,2,A,e.length];for(let s of e)if(t.push(s.sourceKey),s.targetPitch===-1)t.push(127,127,127);else{let a=Math.floor(s.targetPitch),i=Math.floor((s.targetPitch-a)/61e-6);t.push(a,i>>7&127,i&127)}t.push(247),this.systemExclusive(t)}reverbateEverythingBecauseWhyNot(){for(let A=0;At+s,0);break;case"isFullyInitialized":this.workletResponds(A.data.type,A.data.data);break;case"soundBankError":u.warn(A.data),this.eventHandler.callEventInternal("soundBankError",A.data);break;case"renderingProgress":this.renderingProgressTracker.get(A.data.type)?.(A.data.data)}}addNewChannelInternal(A){this.midiChannels.push(new Ks(this.midiChannels.length,this)),A&&this.post({channelNumber:0,type:"addNewChannel",data:null})}workletResponds(A,e){this.resolveMap.get(A)?.(e),this.resolveMap.delete(A)}registerInternalEvent(A,e){this.eventHandler.addEvent(A,Vs(A),e)}},$A=class extends Xs{constructor(A,e=zA){let t=aA(e,zA),s=new Array(17).fill(2),a=17;t.oneOutput&&(s=[34],a=1);let i;try{i=(t?.audioNodeCreators?.worklet??((o,h,g)=>new AudioWorkletNode(o,h,g)))(A,Hs,{outputChannelCount:s,numberOfOutputs:a,processorOptions:{oneOutput:t.oneOutput,eventsEnabled:t.eventsEnabled}})}catch(o){throw console.error(o),new Error("Could not create the AudioWorkletNode. Did you forget to addModule()?",{cause:o})}super(i,(o,h=[])=>{i.port.postMessage(o,h)},t)}async startOfflineRender(A){this.post({type:"startOfflineRender",data:A,channelNumber:-1},A.soundBankList.map(e=>e.soundBankBuffer)),await new Promise(e=>this.awaitWorkerResponse("startOfflineRender",e))}destroy(){this.post({channelNumber:0,type:"destroyWorklet",data:null}),this.worklet.disconnect(),delete this.worklet}};var nA={trim:!0,bankID:"",writeEmbeddedSoundBank:!0,sequencerID:0},Ws={...nA,writeDefaultModulators:!0,writeExtendedLimits:!0,compressionAction:"keep",compressionQuality:1,software:"SpessaSynth"},Ga={...nA,applySnapshot:!1,bankOffset:0,correctBankOffset:!0,metadata:{},format:"sf2",...Ws},La={...nA,software:"SpessaSynth"};var jA='function Ht(t,e,A=0){let s=0;for(let a=0;a>>0}function Nt(t,e){let A=Ht(t,e,t.currentIndex);return t.currentIndex+=e,A}function aA(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 Xn(t,e){let A=Zn(t,e,t.currentIndex);return t.currentIndex+=e,A}function Zn(t,e,A=0){let s=0n;for(let a=0;a>>0}function ls(t,e,A){for(let s=0;s>s*8&255}function se(t,e){t[t.currentIndex++]=e&255,t[t.currentIndex++]=e>>8}function ge(t,e){ls(t,e,4)}function xA(t,e){let A=BigInt(e);for(let s=0n;s<8n;s++)t[t.currentIndex++]=Number(A>>s*8n&255n)}function Cs(t,e){let A=e<<8|t;return A>32767?A-65536:A}function Wn(t){return t>127?t-256:t}var te=class extends Uint8Array{currentIndex=0;slice(t,e){let A=super.slice(t,e);return A.currentIndex=0,A}};function We(t,e=t.length,A=0){let s="";for(let a=0;a0&&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 HA(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 en(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]),a=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]),n=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),r=function(U,T){for(var Q=new e(31),b=0;b<31;++b)Q[b]=T+=1<>1|(D&21845)<<1,g=(g&52428)>>2|(g&13107)<<2,g=(g&61680)>>4|(g&3855)<<4,B[D]=((g&65280)>>8|(g&255)<<8)>>1;var g,D,E=function(U,T,Q){for(var b=U.length,L=0,z=new e(T);L>V]=ee}else for(W=new e(b),L=0;L>15-U[L]);return W},p=new t(288);for(D=0;D<144;++D)p[D]=8;var D;for(D=144;D<256;++D)p[D]=9;var D;for(D=256;D<280;++D)p[D]=7;var D;for(D=280;D<288;++D)p[D]=8;var D,y=new t(32);for(D=0;D<32;++D)y[D]=5;var D,R=E(p,9,1),S=E(y,5,1),w=function(U){for(var T=U[0],Q=1;QT&&(T=U[Q]);return T},F=function(U,T,Q){var b=T/8|0;return(U[b]|U[b+1]<<8)>>(T&7)&Q},H=function(U,T){var Q=T/8|0;return(U[Q]|U[Q+1]<<8|U[Q+2]<<16)>>(T&7)},k=function(U){return(U+7)/8|0},u=function(U,T,Q){return(T==null||T<0)&&(T=0),(Q==null||Q>U.length)&&(Q=U.length),new t(U.subarray(T,Q))},m=["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"],J=function(U,T,Q){var b=new Error(T||m[U]);if(b.code=U,Error.captureStackTrace&&Error.captureStackTrace(b,J),!Q)throw b;return b},O=function(U,T,Q,b){var L=U.length,z=b?b.length:0;if(!L||T.f&&!T.l)return Q||new t(0);var $=!Q,W=$||T.i!=2,V=T.i;$&&(Q=new t(L*3));var ee=function(Be){var he=Q.length;if(Be>he){var xe=new t(Math.max(he*2,Be));xe.set(Q),Q=xe}},Ae=T.f||0,Y=T.p||0,re=T.b||0,ue=T.l,Le=T.d,Ee=T.m,Re=T.n,Oe=L*8;do{if(!ue){Ae=F(U,Y,1);var Bt=F(U,Y+1,3);if(Y+=3,Bt)if(Bt==1)ue=R,Le=S,Ee=9,Re=5;else if(Bt==2){var Et=F(U,Y,31)+257,tA=F(U,Y+10,15)+4,AA=Et+F(U,Y+5,31)+1;Y+=14;for(var Je=new t(AA),Qt=new t(19),Fe=0;Fe>4;if(_e<16)Je[Fe++]=_e;else{var It=0,dt=0;for(_e==16?(dt=3+F(U,Y,3),Y+=2,It=Je[Fe-1]):_e==17?(dt=3+F(U,Y,7),Y+=3):_e==18&&(dt=11+F(U,Y,127),Y+=7);dt--;)Je[Fe++]=It}}var Rt=Je.subarray(0,Et),Ke=Je.subarray(Et);Ee=w(Rt),Re=w(Ke),ue=E(Rt,Ee,1),Le=E(Ke,Re,1)}else J(1);else{var _e=k(Y)+4,ut=U[_e-4]|U[_e-3]<<8,tt=_e+ut;if(tt>L){V&&J(0);break}W&&ee(re+ut),Q.set(U.subarray(_e,tt),re),T.b=re+=ut,T.p=Y=tt*8,T.f=Ae;continue}if(Y>Oe){V&&J(0);break}}W&&ee(re+131072);for(var v=(1<>4;if(Y+=It&15,Y>Oe){V&&J(0);break}if(It||J(2),_<256)Q[re++]=_;else if(_==256){P=Y,ue=null;break}else{var ie=_-254;if(_>264){var Fe=_-257,ce=s[Fe];ie=F(U,Y,(1<>4;fe||J(3),Y+=fe&15;var Ke=C[j];if(j>3){var ce=a[j];Ke+=H(U,Y)&(1<Oe){V&&J(0);break}W&&ee(re+131072);var Te=re+ie;if(reh.length+I,0);a&&(r+=4,n="LIST");let i;s?(i=new te(8),xA(i,r)):(i=new te(4),ge(i,r));let o=[et(n),i];return a&&o.push(et(e)),o.push(...A),r%2!==0&&o.push(new Uint8Array(1)),o}static writeParts(e,A,s=!1,a=!1){let n=s?12:8,r=e,i=A.reduce((C,B)=>B.length+C,0),o=i;a&&(n+=4,o+=4,r="LIST");let I=n+i;I%2!==0&&I++;let h=new te(I);Ne(h,r),s?xA(h,o):ge(h,o),a&&Ne(h,e);for(let C of A)h.set(C,n),n+=C.length;return h}static findListType(e,A){return e.find(s=>s.header!=="LIST"?!1:(s.data.currentIndex=4,We(s.data,4)===A))}};function $t(t,e){return{...e,...t}}var l=class $A{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${en(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?$A.info(`%c${e}%c is now set to %c${A}%c ${s}.`,d.recognized,d.info,d.value,d.info):$A.info(`%c${e}%c is now set to %c${A}%c.`,d.recognized,d.info,d.value,d.info))}},nn={ConsoleColors:d,readBigEndian:Ht,readLittleEndian:hs,readLittleEndianIndexed:X,readBinaryString:We,readBinaryStringIndexed:de,readVariableLengthQuantity:pe,inflateSync:An},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},Ze={pitchWheelRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},ke={partParameter:1,drumPitch:24,drumPitchFine:25,drumLevel:26,drumPan:28,drumReverb:29,drumChorus:30,drumDelay:31,awe32:127,SF2:120},Ue={vibratoRate:8,vibratoDepth:9,vibratoDelay:10,tvfCutoffFrequency:32,tvfResonance:33,envelopeAttackTime:99,envelopeDecayTime:100,envelopeReleaseTime:102},Qe=class it{ticks;statusByte;data;constructor(e,A,s){this.ticks=e,this.statusByte=A,this.data=s}static pitchWheel(e,A,s){return new it(e,G.pitchWheel|A%16,new Uint8Array([s&127,s>>7&127]))}static channelPressure(e,A,s){return new it(e,G.channelPressure|A%16,new Uint8Array([s]))}static programChange(e,A,s){return new it(e,G.programChange|A%16,new Uint8Array([s]))}static controllerChange(e,A,s,a){return new it(e,G.controllerChange|A%16,new Uint8Array([s,a]))}static systemExclusive(e,A){return new it(e,G.systemExclusive,new Uint8Array(A))}static registeredParameter(e,A,s,a){if(s>16383||s<0||a>16383||a<0)throw new Error("Parameter and value must be between 0 and 16383.");return[it.controllerChange(e,A,f.registeredParameterMSB,s>>7),it.controllerChange(e,A,f.registeredParameterLSB,s&127),it.controllerChange(e,A,f.dataEntryMSB,a>>7),it.controllerChange(e,A,f.dataEntryLSB,a&127)]}},Ms=(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 a=e.slice(0,Math.max(0,A)),n=e.slice(A+1,s),r=e.slice(Math.max(0,s+1));return{...jA.fromMIDIString(a),isDrum:n==="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&&De.isSystemXG(s)&&(A={...A,isGMGSDrum:!1,bankLSB:0,bankMSB:De.getDrumBank(s)});let{isGMGSDrum:a,bankLSB:n,bankMSB:r,program:i}=A,o=De.isSystemXG(s),I=De.isXGDrum(r)&&o,h=e.find(g=>this.matches(g,A));if(h&&(!I||I&&this.isXGDrum(h)))return h;let C=g=>{l.info(`%cPreset %c${jA.toMIDIString(A)}%c not found. (${s}) Replaced with %c${this.toFullMIDIString(g)}`,d.warn,d.unrecognized,d.warn,d.value)};if(a){let g=e.find(E=>E.isGMGSDrum&&E.program===i);return g||(g=e.find(E=>E.isDrum&&E.program===i),g)?(C(g),g):(g=this.getAnyDrums(e,!1),C(g),g)}if(I){let g=e.find(E=>E.program===i&&E.isDrum&&!E.isGMGSDrum);return g||(g=e.find(E=>E.isDrum&&E.program===i),g&&g.program<49)?(C(g),g):(g=this.getAnyDrums(e,!0),C(g),g)}let B=e.filter(g=>g.program===i&&!g.isDrum);if(B.length===0)return C(e[0]),e[0];if(h=o?B.find(g=>g.bankLSB===n):B.find(g=>g.bankMSB===r),h)return C(h),h;if(n!==64||!o){let g=Math.max(r,n);if(h=B.find(E=>E.bankLSB===g||E.bankMSB===g),h)return C(h),h}return C(B[0]),B[0]}static getAnyDrums(e,A){let s=A?e.find(a=>this.isXGDrum(a)):e.find(a=>a.isGMGSDrum);return s||(e.find(a=>a.isDrum)??e[0])}},me=Object.freeze({type:"Other"}),ne=class le{static analyzeSysEx(e){if(e.length<3)return me;switch(e[0]){default:return me;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 me;case Ze.pitchWheelRange:return{type:"Channel MIDI Param",channel:e,parameter:"pitchWheelRange",value:s/128};case Ze.fineTuning:return{type:"Channel MIDI Param",channel:e,parameter:"fineTune",value:(s-8192)/81.92};case Ze.coarseTuning:return{type:"Channel MIDI Param",channel:e,parameter:"keyShift",value:(s>>7)-64};case Ze.modulationDepth:return{type:"Channel MIDI Param",channel:e,parameter:"modulationDepth",value:s/1.28}}}static analyzeNRPN(e,A,s){let a=A>>7,n=A&127;switch(a){default:return me;case ke.partParameter:switch(n){default:return me;case Ue.vibratoRate:return{type:"Controller Change",channel:e,controller:f.vibratoRate,value:s>>7};case Ue.vibratoDepth:return{type:"Controller Change",channel:e,controller:f.vibratoDepth,value:s>>7};case Ue.vibratoDelay:return{type:"Controller Change",channel:e,controller:f.vibratoDelay,value:s>>7};case Ue.tvfCutoffFrequency:return{type:"Controller Change",channel:e,controller:f.brightness,value:s>>7};case Ue.tvfResonance:return{type:"Controller Change",channel:e,controller:f.filterResonance,value:s>>7};case Ue.envelopeAttackTime:return{type:"Controller Change",channel:e,controller:f.attackTime,value:s>>7};case Ue.envelopeDecayTime:return{type:"Controller Change",channel:e,controller:f.decayTime,value:s>>7};case Ue.envelopeReleaseTime:return{type:"Controller Change",channel:e,controller:f.releaseTime,value:s>>7}}case ke.drumPitch:case ke.drumPitchFine:case ke.drumLevel:case ke.drumPan:case ke.drumReverb:case ke.drumChorus:case ke.drumDelay:return{type:"Drum Setup"}}}static setGlobalMIDIParameter(e,A,s,a){switch(s){case"system":return[le.reset(e,a)];case"keyShift":switch(A){default:return[le.deviceControlMessage(e,4,[0,a+64])];case"xg":return[le.xgMessage(e,0,0,6,[a+64])];case"gs":return[le.gsMessage(e,64,0,5,[a+64])]}case"fineTune":switch(A){default:{let n=Math.floor(a*81.92+8192);return[le.deviceControlMessage(e,3,[n&127,n>>7&127])]}case"xg":{let n=Math.floor(a*10+1024);return[le.xgMessage(e,0,0,0,[n>>12&15,n>>8&15,n>>4&15,n&15])]}case"gs":{let n=Math.floor(a*10+1024);return[le.gsMessage(e,64,0,0,[n>>12&15,n>>8&15,n>>4&15,n&15])]}}case"volume":switch(A){default:{let n=Math.floor(a*16383);return[le.deviceControlMessage(e,1,[n&127,n>>7&127])]}case"xg":{let n=Math.floor(a*127);return[le.xgMessage(e,0,0,4,[n])]}case"gs":{let n=Math.floor(a*127);return[le.gsMessage(e,64,0,4,[n])]}}case"pan":if(A==="gs"){let n=Math.floor(a*63)+64;return[le.gsMessage(e,64,0,6,[n])]}else{let n=Math.floor(a*8192)+8192;return[le.deviceControlMessage(e,2,[n&127,n>>7&127])]}}}static setChannelMIDIParameter(e,A,s,a,n){A%=16;let r=le.channelToSyx(A);switch(a){case"pressure":return[Qe.channelPressure(e,A,n)];case"pitchWheel":return[Qe.pitchWheel(e,A,n)];case"pitchWheelRange":return Qe.registeredParameter(e,A,Ze.pitchWheelRange,Math.floor(n*128));case"modulationDepth":return Qe.registeredParameter(e,A,Ze.modulationDepth,Math.floor(n*1.28));case"rxChannel":return s==="xg"?[le.xgMessage(e,8,A,4,[n])]:[le.gsMessage(e,64,16|r,2,[n])];case"polyMode":return n?[Qe.controllerChange(e,A,f.polyModeOn,0)]:[Qe.controllerChange(e,A,f.monoModeOn,0)];case"keyShift":return Qe.registeredParameter(e,A,Ze.coarseTuning,n+64<<7);case"fineTune":return Qe.registeredParameter(e,A,Ze.fineTuning,Math.floor(n*81.92+8192));case"randomPan":return s==="xg"?[le.xgMessage(e,8,A,14,[0])]:[le.gsMessage(e,64,16|r,28,[0])];case"assignMode":switch(s){default:case"gs":return[le.gsMessage(e,64,16|r,20,[n])];case"xg":return[le.xgMessage(e,8,A,6,[n])]}case"efxAssign":return[le.gsMessage(e,64,16|r,34,[n])];case"cc1":return[le.gsMessage(e,64,16|r,31,[n])];case"cc2":return[le.gsMessage(e,64,16|r,32,[n])];case"drumMap":return[le.gsMessage(e,64,16|r,21,[n])];case"velocitySenseDepth":return s==="xg"?[le.xgMessage(e,8,A,12,[n])]:[le.gsMessage(e,64,16|r,26,[n])];case"velocitySenseOffset":return s==="xg"?[le.xgMessage(e,8,A,13,[n])]:[le.gsMessage(e,64,16|r,27,[n])]}}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 gs(e,A,s,a){let n=128-(e+A+s+a.reduce((r,i)=>r+i,0))%128&127;return[65,16,66,18,e,A,s,...a,n,247]}static gsMessage(e,A,s,a,n){return Qe.systemExclusive(e,this.gs(A,s,a,n))}static xg(e,A,s,a){return[67,16,76,e,A,s,...a,247]}static xgMessage(e,A,s,a,n){return Qe.systemExclusive(e,this.xg(A,s,a,n))}static deviceControl(e,A){return[127,127,4,e,...A,247]}static deviceControlMessage(e,A,s){return Qe.systemExclusive(e,this.deviceControl(A,s))}static reset(e,A){switch(A){case"gs":return this.gsMessage(e,64,0,127,[0]);case"xg":return this.xgMessage(e,0,0,126,[0]);case"gm":return Qe.systemExclusive(e,[126,127,9,1,127]);case"gm2":return Qe.systemExclusive(e,[126,127,9,3,127])}}static analyzeGM(e){if(e.length<4)return me;if(e[2]===4)switch(e[3]){default:return me;case 1:{let A=(e[5]<<7|e[4])/16383;return{type:"Global MIDI Param",parameter:"volume",value:Math.pow(A,2)}}case 2:return{type:"Global MIDI Param",parameter:"pan",value:((e[5]<<7|e[4])-8192)/8192};case 3:return{type:"Global MIDI Param",parameter:"fineTune",value:((e[5]<<7|e[4])-8192)/81.92};case 4:return{type:"Global MIDI Param",parameter:"keyShift",value:e[5]-64};case 5:if(e[4]!==1||e[5]!==1||e[6]!==1||e[7]!==1)return me;switch(e[8]){default:return me;case 1:switch(e[9]){default:return me;case 0:case 1:return{type:"Reverb Param"}}case 2:switch(e[9]){default:return me;case 0:case 1:case 2:case 3:case 4:return{type:"Chorus Param"}}}}if(e[2]!==9)return me;switch(e[3]){default:return me;case 1:return{type:"Global MIDI Param",parameter:"system",value:"gm"};case 2:return{type:"Global MIDI Param",parameter:"system",value:"gm"};case 3:return{type:"Global MIDI Param",parameter:"system",value:"gm2"}}}static analyzeXG(e){if(e[2]!==76||e.length<7)return me;let A=e[3],s=e[4],a=e[5],n=e[6];if(A===6||A===7)return{type:"Display Data"};if(A===0&&s===0)switch(a){default:return me;case 0:return{type:"Global MIDI Param",parameter:"fineTune",value:(((e[6]&15)<<12|(e[7]&15)<<8|(e[8]&15)<<4|e[9]&15)-1024)/10};case 6:return{type:"Global MIDI Param",parameter:"keyShift",value:n-64};case 126:case 127:return{type:"Global MIDI Param",parameter:"system",value:"xg"}}if(A===2&&s===1)return a<=21?{type:"Reverb Param"}:a<=53?{type:"Chorus Param"}:{type:"Variation Param"};if(A===3&&s===0)return{type:"Variation Param"};if(A===8){let r=s;switch(a){default:return me;case 1:return{type:"Controller Change",channel:r,controller:f.bankSelect,value:n};case 2:return{type:"Controller Change",channel:r,controller:f.bankSelectLSB,value:n};case 3:return{type:"Program Change",channel:r,value:n};case 5:return{type:"Controller Change",channel:r,controller:n===1?f.polyModeOn:f.monoModeOn,value:0};case 6:return{type:"Channel MIDI Param",channel:r,parameter:"assignMode",value:n};case 7:return{type:"Drums On",channel:r,isDrum:n>0};case 8:return{type:"Channel MIDI Param",channel:r,parameter:"keyShift",value:n-64};case 11:return{type:"Controller Change",channel:r,controller:f.mainVolume,value:n};case 14:return{type:"Controller Change",channel:r,controller:f.pan,value:n};case 18:return{type:"Controller Change",channel:r,controller:f.chorusDepth,value:n};case 19:return{type:"Controller Change",channel:r,controller:f.reverbDepth,value:n};case 21:return{type:"Controller Change",channel:r,controller:f.vibratoRate,value:n};case 22:return{type:"Controller Change",channel:r,controller:f.vibratoDepth,value:n};case 23:return{type:"Controller Change",channel:r,controller:f.vibratoDelay,value:n};case 24:return{type:"Controller Change",channel:r,controller:f.brightness,value:n};case 25:return{type:"Controller Change",channel:r,controller:f.filterResonance,value:n};case 26:return{type:"Controller Change",channel:r,controller:f.attackTime,value:n};case 27:return{type:"Controller Change",channel:r,controller:f.decayTime,value:n};case 12:return{type:"Controller Change",channel:r,controller:f.releaseTime,value:n}}}return A>>4===3?{type:"Drum Setup"}:me}static analyzeGS(e){if(e.length<10||e[3]!==18)return me;if(e[2]===69)return{type:"Display Data"};if(e[2]!==66)return me;let A=e[4],s=e[5],a=e[6],n=e[7];if((A===0||A===64)&&s===0)switch(a){case 0:return{type:"Global MIDI Param",parameter:"fineTune",value:((n<<12|e[8]<<8|e[9]<<4|e[10])-1024)/10};case 4:return{type:"Global MIDI Param",parameter:"volume",value:n/127};case 5:return{type:"Global MIDI Param",parameter:"keyShift",value:n-64};case 6:return{type:"Global MIDI Param",parameter:"pan",value:(n-64)/63};case 127:switch(n){case 0:case 1:return{type:"Global MIDI Param",parameter:"system",value:"gs"};case 127:return{type:"Global MIDI Param",parameter:"system",value:"gm"}}return me}if(A===65)return{type:"Drum Setup"};if(A!==64&&A!==80)return me;let r=A===80?16:0;if(s===1){if(a>=48&&a<=55)return{type:"Reverb Param"};if(a>=56&&a<=64)return{type:"Chorus Param"};if(a>=80&&a<=90)return{type:"Delay Param"}}if(s===3&&a>=0&&a<=127)return{type:"Insertion Param"};if(s>>4===1){let i=le.syxToChannel(s&15)+r;switch(a){default:return me;case 0:return{type:"Program Change",channel:i,value:n};case 19:return{type:"Channel MIDI Param",channel:i,parameter:"polyMode",value:n===1};case 20:return{type:"Channel MIDI Param",channel:i,parameter:"assignMode",value:n};case 21:return{type:"Drums On",channel:i,isDrum:n>0};case 22:return{type:"Channel MIDI Param",channel:i,parameter:"keyShift",value:n-64};case 25:return{type:"Controller Change",channel:i,controller:f.mainVolume,value:n};case 26:return{type:"Channel MIDI Param",channel:i,parameter:"velocitySenseDepth",value:n};case 27:return{type:"Channel MIDI Param",channel:i,parameter:"velocitySenseOffset",value:n};case 28:return{type:"Controller Change",channel:i,controller:f.pan,value:n};case 31:return{type:"Channel MIDI Param",channel:i,parameter:"cc1",value:n};case 32:return{type:"Channel MIDI Param",channel:i,parameter:"cc2",value:n};case 33:return{type:"Controller Change",channel:i,controller:f.chorusDepth,value:n};case 34:return{type:"Controller Change",channel:i,controller:f.reverbDepth,value:n};case 42:return{type:"Channel MIDI Param",channel:i,parameter:"fineTune",value:((n<<7|e[8])-8192)/81.92};case 44:return{type:"Controller Change",channel:i,controller:f.variationDepth,value:n};case 48:return{type:"Controller Change",channel:i,controller:f.vibratoRate,value:n};case 49:return{type:"Controller Change",channel:i,controller:f.vibratoDepth,value:n};case 50:return{type:"Controller Change",channel:i,controller:f.brightness,value:n};case 51:return{type:"Controller Change",channel:i,controller:f.filterResonance,value:n};case 52:return{type:"Controller Change",channel:i,controller:f.attackTime,value:n};case 53:return{type:"Controller Change",channel:i,controller:f.decayTime,value:n};case 54:return{type:"Controller Change",channel:i,controller:f.releaseTime,value:n};case 55:return{type:"Controller Change",channel:i,controller:f.vibratoDelay,value:n}}}if(s>>4===4){let i=le.syxToChannel(s&15)+r;switch(a){default:return me;case 0:case 1:return{type:"Controller Change",channel:i,controller:f.bankSelectLSB,value:n};case 34:return{type:"Channel MIDI Param",channel:i,parameter:"efxAssign",value:n===1}}}return me}},Aa="Created using SpessaSynth";function sa(t,e,A){let s="gm",a=[],n=new Array(t.tracks.length).fill(0),r=16+Math.max(...t.portChannelOffsetMap),i=[];for(let o=0;o{let C=t.portChannelOffsetMap[n[I]];if(o.statusByte===G.midiPort){n[I]=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 y=ne.analyzeSysEx(o.data);switch(y.type){default:return;case"Drums On":{let D=y.channel+C;if(!i[D])return;i[D].isDrum=y.isDrum;return}case"Global MIDI Param":y.parameter==="system"&&(s=y.value,y.value==="gm"&&a.push({tNum:I,e:o}));break;case"Controller Change":{let D=t.tracks[I];if(y.channel>=16)return;let R=Qe.controllerChange(o.ticks,y.channel,y.controller,y.value);D.events[h[I]]=R,o=R,l.info("%cReplaced a system exclusive with controller change!",d.info);break}case"Program Change":{if(y.channel>=16)return;let D=t.tracks[I],R=Qe.programChange(o.ticks,y.channel,y.value);D.events[h[I]]=R,o=R,l.info("%cReplaced a system exclusive with program change!",d.info);break}}}let g=(o.statusByte&15)+C,E=i[g];if(B===G.programChange){let y={program:o.data[0],bankLSB:E.lastBankLSB?.data?.[1]??0,bankMSB:De.subtractBankOffset(E.lastBank?.data?.[1]??0,t.bankOffset,s==="xg"),isGMGSDrum:E.isDrum},D=A.getPreset(y,s);if(l.info(`%cInput patch: %c${je.toMIDIString(y)}%c. Channel %c${g}%c. Changing patch to ${D.toString()}.`,d.info,d.unrecognized,d.info,d.recognized,d.info),o.data[0]=D.program,D.isGMGSDrum&&De.isSystemXG(s)||E.lastBank===void 0||(E.lastBank.data[1]=De.addBankOffset(D.bankMSB,e,s==="xg"),E.lastBankLSB===void 0))return;E.lastBankLSB.data[1]=D.bankLSB;return}let p=o.data[0]===f.bankSelectLSB;o.data[0]!==f.bankSelect&&!p||(E.hasBankSelect=!0,p?E.lastBankLSB=o:E.lastBank=o)});for(let o=0;oS.port===g&&S.channels.has(h));if(E===void 0)continue;let p=E.events.findIndex(S=>S.statusByte===C);if(p===-1){let S=E.events.findIndex(H=>H.statusByte>128&&H.statusByte<240&&(H.statusByte&15)===h);if(S===-1)continue;let w=E.events[S].ticks,F=A.getPreset({bankMSB:0,bankLSB:0,program:0,isGMGSDrum:!1},s).program;E.addEvents(S,Qe.programChange(w,h,F)),p=S}l.info(`%cAdding bank select for %c${o}`,d.info,d.recognized);let y=E.events[p].ticks,D=A.getPreset({bankLSB:0,bankMSB:0,program:I.program,isGMGSDrum:I.isDrum},s),R=De.addBankOffset(D.bankMSB,e,s==="xg");E.addEvents(p,Qe.controllerChange(y,h,f.bankSelect,R))}if(s==="gm"&&!De.isSystemXG(s)){for(let I of a){let h=t.tracks[I.tNum];h.deleteEvent(h.events.indexOf(I.e))}let o=0;t.tracks[0].events[0].statusByte===G.trackName&&o++,t.tracks[0].addEvents(o,ne.reset(0,"gs"))}t.flush()}var Rs={bankOffset:0,metadata:{},correctBankOffset:!0,soundBank:void 0};function na(t,e,A){let s=A.metadata;if(l.group("%cWriting the RMIDI File...",d.info),l.info("metadata",s),l.info("Initial bank offset",t.bankOffset),A.correctBankOffset){if(!A.soundBank)throw new Error("Sound bank must be provided if correcting bank offset.");sa(t,A.bankOffset,A.soundBank)}let a=new te(t.writeMIDI());s.name??=t.getName(),s.creationDate??=new Date,s.copyright??=Aa,s.software??="SpessaSynth",Object.entries(s).forEach(o=>{let I=o;I[1]&&t.setRMIDInfo(I[0],I[1])});let n=[],r=(o,I)=>{n.push(x.write(o,I))};for(let o of Object.entries(t.rmidiInfo)){let I=o[0],h=o[1];switch(I){case"album":r("IALB",h),r("IPRD",h);break;case"software":r("ISFT",h);break;case"infoEncoding":r("IENC",h);break;case"creationDate":r("ICRD",h);break;case"picture":r("IPIC",h);break;case"name":r("INAM",h);break;case"artist":r("IART",h);break;case"genre":r("IGNR",h);break;case"copyright":r("ICOP",h);break;case"comment":r("ICMT",h);break;case"engineer":r("IENG",h);break;case"subject":r("ISBJ",h);break;case"midiEncoding":r("MENC",h);break}}let i=new te(2);return ls(i,A.bankOffset,2),n.push(x.write("DBNK",i)),l.info("%cFinished!",d.info),l.groupEnd(),x.writeParts("RIFF",[et("RMID"),x.write("data",a),x.writeParts("INFO",n,!1,!0),new te(e)]).buffer}var mA=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?ne.analyzeRPN(this.channel,this.rpnMSB.v<<7|this.rpnLSB.v,t):ne.analyzeNRPN(this.channel,this.nrpnMSB.v<<7|this.nrpnLSB.v,t)}};function aa(t,e){l.groupCollapsed("%cSearching for all used programs and keys...",d.info);let A=16+Math.max(...t.portChannelOffsetMap),s=[],a="gs",n=0,r=B=>{a=B,n=0;for(let g=0;gB.port),I=t.portChannelOffsetMap,{timeline:h,tracks:C}=t;for(let B of h){let g=B.tr,E=B.ev,p=C[g].events[E];if(p.statusByte===G.midiPort&&t.tracks[g].channels.size>0){let R=p.data[0];I[R]===void 0&&(l.warn(`Invalid port ${R} on track ${g}. (No offset found in the MIDI map.`),R=0),o[g]=R;continue}let y=p.statusByte&240;if(y!==G.noteOn&&y!==G.controllerChange&&y!==G.programChange&&y!==G.systemExclusive)continue;let D=I[o[g]]||0;switch(y){case G.programChange:{let R=s[(p.statusByte&15)+D];R.preset=e.getPreset({bankMSB:R.bankMSB,bankLSB:R.bankLSB,program:p.data[0],isGMGSDrum:R.isDrum},a);break}case G.controllerChange:{let R=s[(p.statusByte&15)+D],S=p.data[0],w=p.data[1];switch(S){case f.registeredParameterMSB:case f.registeredParameterLSB:case f.nonRegisteredParameterLSB:case f.nonRegisteredParameterMSB:R.param.controllerChange(S,w,g,E);break;case f.dataEntryMSB:case f.dataEntryLSB:{let F=R.param.controllerChange(S,w,g,E);F?.type==="Channel MIDI Param"&&F.parameter==="keyShift"&&(R.keyShift=R.isDrum?0:F.value);break}case f.resetAllControllers:R.param.reset();break;case f.bankSelect:R.bankMSB=w;break;case f.bankSelectLSB:R.bankLSB=w;break}break}case G.noteOn:{let R=s[(p.statusByte&15)+D];if(p.data[1]===0||!R.preset)continue;let S=i.get(R.preset);S||(S=new Map,i.set(R.preset,S));let w=p.data[0]+(R.isDrum?0:n)+R.keyShift,F=S.get(w);F||(F=new Set,S.set(w,F)),F.add(p.data[1]);break}case G.systemExclusive:{let R=ne.analyzeSysEx(p.data);switch(R.type){default:break;case"Global MIDI Param":R.parameter==="keyShift"?n=R.value:R.parameter==="system"&&(r(R.value),l.info(`%c${R.value.toUpperCase()} on detected!`,d.recognized));break;case"Channel MIDI Param":if(R.parameter==="keyShift"){let S=s[R.channel];if(!S)break;S.keyShift=S.isDrum?0:R.value}break;case"Drums On":{let S=R.channel+D;if(!s[S])break;s[S].isDrum=R.isDrum;break}case"Program Change":{let S=s[R.channel+D];if(!S)break;S.preset=e.getPreset({bankMSB:S.bankMSB,bankLSB:S.bankLSB,program:R.value,isGMGSDrum:S.isDrum},a);break}case"Controller Change":{let S=s[R.channel+D];if(!S)break;R.controller===f.bankSelectLSB?S.bankLSB=R.value:R.controller===f.bankSelect&&(S.bankMSB=R.value)}}}}}for(let[B,g]of i.entries())g.size===0&&(l.info(`%cDetected change but no keys for %c${B.name}`,d.info,d.value),i.delete(B));return l.groupEnd(),i}var ra=t=>(t.data=new te(t.data.buffer),6e7/Ht(t.data,3));function ia(t,e=0){let A=[];for(let C=0;C<16;C++)A.push([]);let s=0,a=60/(120*t.timeDivision),n=0,r=0,i=[];for(let C=0;C<16;C++)i.push(new Map);let o=(C,B)=>{let g=i[B].get(C);if(g===void 0)return;let E=g.shift();if(E===void 0)return;let p=A[B][E],y=s-p.start;p.length=B===9?Math.max(y,e):y,r--},{timeline:I,tracks:h}=t;for(;n>4,E=B.statusByte&15;if(g===8)o(B.data[0],E);else if(g===9){let y=B.data[0],D=B.data[1];if(D===0)o(y,E);else{let R={midiNote:y,start:s,length:-1,velocity:D},S=A[E];S.push(R);let w=i[E];w.has(y)||w.set(y,[]),i[E].get(y)?.push(S.length-1),r++}}else B.statusByte===81&&(a=60/(ra(B)*t.timeDivision));if(++n>=I.length)break;let p=I[n];s+=a*(h[p.tr].events[p.ev].ticks-B.ticks)}if(r>0)for(let C=0;Ck.port),p={},y=0,D=(k,u)=>{t.tracks[k].channels.size!==0&&(y===0&&(y+=16,p[u]=0),p[u]===void 0&&(p[u]=y,y+=16),E[k]=u)};for(let[k,u]of t.tracks.entries())D(k,u.port);let R=y,S=[];for(let k=0;k{let J=t.tracks[u],O=m[u],q=()=>{J.deleteEvent(O),m[u]--},K=W=>{let V=S[W],ee=V.param,Ae=ee.paramMSB,Y=ee.paramLSB;l.info(`%cClearing Non/Registered Parameter on ${W}. Clear MSB: %c${V.clearedParams.pMSB}%c, clear LSB: %c${V.clearedParams.pLSB}%c, clear data: %c${V.clearedParams.data}.`,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized),V.clearedParams.data||(q(),u===Ae.track&&O{J.addEvents(O,W),m[u]++},U=(...W)=>{for(let V=W.length-1;V>=0;V--)ae(W[V])},T=p[E[u]]||0;if(k.statusByte===G.midiPort){D(u,k.data[0]);return}if(k.statusByteG.systemExclusive)return;let Q=k.statusByte&240,b=k.statusByte&15,L=b+T;if(k.statusByte!==G.systemExclusive&&o.has(L)){q();return}let z=S[L],$=I.get(L);switch(Q){case G.noteOn:if(!$)break;if(z.isFirstNoteOn){if(z.isFirstNoteOn=!1,$.controllers)for(let[V,ee]of $.controllers)ee!=="clear"&&ae(Qe.controllerChange(k.ticks,b,V,ee));if($.midiParams?.fineTune!==void 0&&$.midiParams.fineTune!=="clear"){let V=z.fineTune+$.midiParams.fineTune;z.currentKeyShift=Math.trunc(V/100),$.midiParams.fineTune=V%100}else{let V=z.fineTune+z.currentFineTune;z.currentKeyShift=Math.trunc(V/100),$.midiParams??={},$.midiParams.fineTune=V%100}let W=$.patch;if(W&&W!=="clear"){l.info(`%cSetting %c${L}%c to %c${je.toMIDIString(W)}%c. Track num: %c${u}`,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized);let V=W.bankMSB,ee=W.bankLSB,Ae=W.program;ae(Qe.programChange(k.ticks,b,Ae));let Y=(re,ue)=>{ae(Qe.controllerChange(k.ticks,b,re?f.bankSelectLSB:f.bankSelect,ue))};if(De.isSystemXG(h)&&W.isGMGSDrum&&(l.info(`%cAdding XG Drum change on track %c${u}`,d.recognized,d.value),V=De.getDrumBank(h),ee=0),Y(!1,V),Y(!0,ee),W.isGMGSDrum&&!De.isSystemXG(h)&&b!==9){l.info(`%cAdding GS Drum change on track %c${u}`,d.recognized,d.value);let re=16|ne.channelToSyx(b);ae(ne.gsMessage(k.ticks,40,re,21,[1]))}}if($.midiParams)for(let[V,ee]of Object.entries($.midiParams))ee!=="clear"&&U(...ne.setChannelMIDIParameter(k.ticks,b,h,V,ee))}k.data[0]+=z.keyShift+z.currentKeyShift;break;case G.noteOff:if(!$)break;k.data[0]+=z.keyShift+z.currentKeyShift;break;case G.programChange:if($?.patch){q();return}break;case G.pitchWheel:$?.midiParams?.pitchWheel&&q();break;case G.channelPressure:$?.midiParams?.pressure&&q();break;case G.controllerChange:{let W=k.data[0],V=k.data[1];if($?.controllers?.get(W)){q();return}switch(W){case f.bankSelect:case f.bankSelectLSB:$?.patch&&q();return;case f.registeredParameterLSB:case f.registeredParameterMSB:case f.nonRegisteredParameterMSB:case f.nonRegisteredParameterLSB:W===f.nonRegisteredParameterLSB||W===f.registeredParameterLSB?z.clearedParams.pLSB=!1:z.clearedParams.pMSB=!1,z.param.controllerChange(W,V,u,O);return;case f.dataEntryMSB:case f.dataEntryLSB:{z.clearedParams.data=!1;let ee=z.param.controllerChange(W,V,u,O);if(!ee)return;switch(ee.type){case"Drum Setup":i&&K(L);return;case"Controller Change":{let Ae=ee.controller,Y=ee.channel;if($?.controllers?.get(Ae)){K(Y);return}(Ae===f.bankSelect||Ae===f.bankSelectLSB)&&$?.patch&&K(Y);break}case"Channel MIDI Param":if(ee.parameter==="fineTune"&&z.fineTune){z.currentFineTune=ee.value;let Ae=z.fineTune+ee.value;z.currentKeyShift=Math.trunc(Ae/100);let Y=Ae%100;l.info(`%cFine tuning already present on ${L}%c (${ee.value})%c, new relative tune: %c${Ae}%c cents. Key shift: %c${z.currentKeyShift}%c semitones. Actual RPN value to set: %c${Y} cents.`,d.info,d.recognized,d.info,d.value,d.info,d.value,d.info,d.value);let re=Math.floor(Y*81.92)+8192;k.data[1]=W===f.dataEntryMSB?re>>7:re&127}else $?.midiParams?.[ee.parameter]&&K(L);break}z.clearedParams.pLSB=!0,z.clearedParams.pMSB=!0;return}default:return}}case G.systemExclusive:{let W=ne.analyzeSysEx(k.data);switch(W.type){default:return;case"Drum Setup":i&&q();return;case"Reverb Param":s&&q();return;case"Chorus Param":a&&q();return;case"Delay Param":n&&q();return;case"Insertion Param":r&&q();return;case"Program Change":I.get(W.channel+T)?.patch&&q();return;case"Global MIDI Param":if(e.midiParams?.[W.parameter]){q();return}if(W.parameter==="system")switch(W.value){case"xg":l.info("%cXG system on detected",d.info),h="xg",C=!0,B=u,g=O;for(let V of S)V.param.reset(),V.clearedParams={pLSB:!0,pMSB:!0,data:!0};return;case"gm2":l.info("%cGM2 system on detected",d.info),h="gm2",C=!0,B=u,g=O;for(let V of S)V.param.reset(),V.clearedParams={pLSB:!0,pMSB:!0,data:!0};return;case"gs":l.info("%cGS on detected!",d.recognized),C=!0,B=u,g=O;for(let V of S)V.param.reset(),V.clearedParams={pLSB:!0,pMSB:!0,data:!0};return;case"gm":l.info("%cGM on detected, removing!",d.info),q(),C=!1;return}break;case"Channel MIDI Param":{let V=I.get(W.channel+T);if(V?.midiParams?.[W.parameter]){q();return}if(W.parameter==="fineTune"){let ee=S[W.channel+T];if(ee&&ee.isFirstNoteOn&&V){let Ae=ee.fineTune+W.value;ee.currentKeyShift=Math.trunc(Ae/100),ee.fineTune=Ae%100,l.info(`%cFine tuning already present on ${W.channel+T}, new relative tune: %c${Ae} cents`,d.info,d.recognized),q()}break}break}case"Controller Change":{let V=W.controller,ee=I.get(W.channel+T);if(ee?.controllers?.get(V)!==void 0){q();return}(V===f.bankSelect||V===f.bankSelectLSB)&&ee?.patch&&q();return}}}}}),!C&&[...I.values()].some(k=>k.patch&&k.patch!=="clear")){let k=0;t.tracks[0].events[0].statusByte===G.trackName&&k++;let u=(e.midiParams?.system==="clear"?void 0:e.midiParams?.system)??"gs";t.tracks[0].addEvents(k,ne.reset(0,u)),B=0,g=k,h=u,l.info(`%c${u} reset on not detected. Adding it.`,d.info)}let w=Math.max(0,t.firstNoteOn),F=t.tracks[B],H=g+1;for(let k of Object.keys(e.midiParams??{})){if(k==="system")continue;let u=e.midiParams?.[k];!u||u==="clear"||F.addEvents(H,...ne.setGlobalMIDIParameter(w,h,k,u))}if(s&&s!=="clear"){let k=oa,u=s;F.addEvents(H,ne.gsMessage(w,64,1,k.level,[u.level]),ne.gsMessage(w,64,1,k.preLowpass,[u.preLowpass]),ne.gsMessage(w,64,1,k.character,[u.character]),ne.gsMessage(w,64,1,k.time,[u.time]),ne.gsMessage(w,64,1,k.delayFeedback,[u.delayFeedback]),ne.gsMessage(w,64,1,k.preDelayTime,[u.preDelayTime]))}if(a&&a!=="clear"){let k=ga,u=a;F.addEvents(H,ne.gsMessage(w,64,1,k.level,[u.level]),ne.gsMessage(w,64,1,k.preLowpass,[u.preLowpass]),ne.gsMessage(w,64,1,k.feedback,[u.feedback]),ne.gsMessage(w,64,1,k.delay,[u.delay]),ne.gsMessage(w,64,1,k.rate,[u.rate]),ne.gsMessage(w,64,1,k.depth,[u.depth]),ne.gsMessage(w,64,1,k.sendLevelToReverb,[u.sendLevelToReverb]),ne.gsMessage(w,64,1,k.sendLevelToDelay,[u.sendLevelToDelay]))}if(n&&n!=="clear"){let k=Ia,u=n;F.addEvents(H,ne.gsMessage(w,64,1,k.level,[u.level]),ne.gsMessage(w,64,1,k.preLowpass,[u.preLowpass]),ne.gsMessage(w,64,1,k.timeCenter,[u.timeCenter]),ne.gsMessage(w,64,1,k.timeRatioLeft,[u.timeRatioLeft]),ne.gsMessage(w,64,1,k.timeRatioRight,[u.timeRatioRight]),ne.gsMessage(w,64,1,k.levelCenter,[u.levelCenter]),ne.gsMessage(w,64,1,k.levelLeft,[u.levelLeft]),ne.gsMessage(w,64,1,k.levelRight,[u.levelRight]),ne.gsMessage(w,64,1,k.feedback,[u.feedback]),ne.gsMessage(w,64,1,k.sendLevelToReverb,[u.sendLevelToReverb]))}if(r&&r!=="clear"){let k=r;for(let u=0;u>8,k.type&127]))}t.flush(),l.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 Qe(A.ticks,A.statusByte,new te(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)}},ha={8:2,9:2,10:2,11:2,12:1,13:1,14:2};function Bs(t,e,A){l.groupCollapsed("%cParsing MIDI File...",d.info),t.fileName=A;let s=r=>{let i=de(r,4),o=Nt(r,4),I={type:i,size:o,data:new te(o)},h=r.slice(r.currentIndex,r.currentIndex+I.size);return I.data.set(h,0),r.currentIndex+=I.size,I},a=s(e);if(a.type!=="MThd")throw l.groupEnd(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${a.type}"`);if(a.size!==6)throw l.groupEnd(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${a.size}`);t.format=Nt(a.data,2);let n=Nt(a.data,2);t.timeDivision=Nt(a.data,2);for(let r=0;r0&&(h+=t.tracks[r-1].events[t.tracks[r-1].events.length-1].ticks);let C=o.data;for(;C.currentIndex=G.noteOff&&g>4],I=g):g===G.systemExclusive?E=pe(C):g===255?(g=C[C.currentIndex++],E=pe(C)):E=0;let p=new te(E);p.set(C.slice(C.currentIndex,C.currentIndex+E)),i.pushEvent(new Qe(h,g,p)),C.currentIndex+=E}t.tracks.push(i),l.info(`%cParsed %c${t.tracks.length}%c / %c${t.tracks.length}`,d.info,d.value,d.info,d.value)}l.info("%cAll tracks parsed correctly!",d.recognized),t.flush(!1),l.groupEnd()}function Es(t){return t.toISOString().split(".")[0]+"Z"}var la=[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 Ca(t){for(let e of la){let A=t;for(let[a,n]of e.entries()){let r=new RegExp(a,"gi");A=A.replace(r,n)}let s=new Date(A);if(!Number.isNaN(s.getTime()))return s}}function Ba(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,a=Number.parseInt(e[3]),n=new Date(a,s,A);if(!Number.isNaN(n.getTime()))return n}}function Ea(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(),a=e[3],n=new Date(`${s}/${A}/${a}`);if(!Number.isNaN(n.getTime()))return n}}function da(t){let e=/\\b\\d{4}\\b/.exec(t);return e?new Date(e[0]):void 0}function ds(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=Ca(t);if(s)return s;let a=Ba(t);if(a)return a;let n=Ea(t);if(n)return n;let r=da(t);return r||(l.warn(`Invalid date: "${t}". Replacing with the current date!`),new Date)}return A}function fa(t,e,A){e.currentIndex+=8;let s=de(e,4);if(s!=="RMID")throw l.groupEnd(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${s}"`);let a=x.read(e);if(a.header!=="data")throw l.groupEnd(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${a.header}"`);let n=a.data,r=!1,i=!1;for(;e.currentIndexOA[g]===i)??"":(l.info(`Unknown field specifier: ${i}`),o=`unknown_${i}`)):(i=de(r,pe(r)),o=i);let B=pe(r);if(B===0){let g=pe(r),E=r.slice(r.currentIndex,r.currentIndex+g);r.currentIndex+=g;let p=pe(E);this.metadata[o]=p<4?de(E,g-1):E.slice(E.currentIndex)}else l.info(`International content: ${B}`),r.currentIndex+=pe(r)}let I=n.currentIndex,h=pe(n),C=n.slice(n.currentIndex,I+h);if(n.currentIndex=I+h,h>0)for(this.packedContent=!0;C.currentIndexYA[E]===g):l.info(`Unrecognized resource format: ${g}`)}}else for(this.resourceFormat="folder";this.nodeData.currentIndex{let h=(C,B)=>{I.metadata[C]!==void 0&&typeof I.metadata[C]=="string"&&(t.rmidiInfo[B]=et(I.metadata[C]))};if(h("nodeName","name"),h("title","name"),h("copyrightNotice","copyright"),h("comment","comment"),I.isFile)switch(I.resourceFormat){default:return;case"DLS1":case"DLS2":case"DLS22":case"mobileDLS":l.info("%cFound embedded DLS!",d.recognized),t.embeddedSoundBank=I.nodeData.buffer;break;case"StandardMIDIFile":case"StandardMIDIFileType1":l.info("%cFound embedded MIDI!",d.recognized),i=I.nodeData;break}else for(let C of I.innerNodes)o(C)};if(o(r),l.groupEnd(),!i)throw new Error("No MIDI data in the XMF file!");Bs(t,i,A)}function pa(t,e){let A=new Map,s=e.systemParameters.keyShift,a=e.systemParameters.fineTune;for(let r=0;r>7;C.set(g,E)}let B={};for(let[g,E]of Object.entries(i.midiParameters))i.lockedMIDIParameters[g]&&(B[g]=E);A.set(r,{keyShift:o,fineTune:I,patch:h,controllers:C,midiParams:B})}let n={};for(let[r,i]of Object.entries(e.midiParameters))e.lockedMIDIParameters[r]&&(n[r]=i);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,midiParams:n})}var Mt=class es{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--,We(e,A)}static fromArrayBuffer(e,A=""){let s=new es,a=new te(e);switch(We(a,4)){case"RIFF":fa(s,a,A);break;case"XMF_":ma(s,a,A);break;default:Bs(s,a,A);break}return s}static async fromFile(e){return this.fromArrayBuffer(await e.arrayBuffer(),e.name)}static copyFrom(e){let A=new es;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(a=>a.ticks<=e),s=0;for(;A=0;a--){let n=this.tempoChanges[a],r=this.tempoChanges[a-1],i=r?r.ticks-n.ticks:1/0,o=60/(n.tempo*this.timeDivision),I=i*o;if(A<=I)return s+=Math.round(A/o),s;s+=i,A-=I}return s}getUsedProgramsAndKeys(e){return aa(this,e)}preloadSynth(e){l.groupCollapsed("%cPreloading samples...",d.info);let A=this.getUsedProgramsAndKeys(e.soundBankManager);for(let[s,a]of A.entries()){l.info(`%cPreloading used samples on %c${s.name}%c...`,d.info,d.recognized,d.info);for(let[n,r]of a.entries())for(let i of r)e.getVoicesForPreset(s,n,i)}l.groupEnd()}flush(e=!0){if(e)for(let A of this.tracks)A.events.sort((s,a)=>s.ticks-a.ticks);this.parseInternal()}getNoteTimes(e=0){return ia(this,e)}writeMIDI(){return zn(this)}writeRMIDI(e,A=Rs){return na(this,e,$t(A,Rs))}modify(e){ca(this,e)}applySnapshot(e){pa(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(a){l.warn(`Failed to decode MIDI name: ${a}`)}}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=et("utf-8",!0),e==="picture")this.rmidiInfo.picture=new Uint8Array(A);else if(e==="creationDate")this.rmidiInfo.creationDate=et(Es(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 ds(We(this.rmidiInfo[e]));try{let s=new TextDecoder(A),a=this.rmidiInfo[e];return a[a.length-1]===0&&(a=a?.slice(0,-1)),s.decode(a.buffer).trim()}catch(s){l.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 a=0,n=1/0;for(let o=0;o=I.length||I[A[o]].ticks=r.length){s--;continue}let i=A[a];e(r[i],a,A),A[a]++}}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 Qe(A.ticks,A.statusByte,new te(A.data))),this.lyrics=e.lyrics.map(A=>new Qe(A.ticks,A.statusByte,new te(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],a=A[1];this.rmidiInfo[s]=new Uint8Array(a)}}parseInternal(){l.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,a=null,n="hard";for(let I of this.tracks){let h=new Set,C=!1;for(let g=0;g=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 f.breathController:case f.undefinedCC111LSB:E.data[1]===0&&(s=E.ticks);break;case f.undefinedCC116LSB:s=E.ticks;break;case f.footController:case f.undefinedCC117LSB:a===null&&(E.data[0]!==4||E.data[0]===4&&E.data[1]===0)?(n="soft",a=E.ticks):(a=0,n="hard");break;case f.bankSelect:this.isDLSRMIDI&&E.data[1]!==0&&E.data[1]!==127&&(l.info("%cDLS RMIDI with offset 1 detected!",d.recognized),this.bankOffset=1)}break;case G.noteOn:{h.add(E.statusByte&15);let y=E.data[0];this.keyRange.min=Math.min(this.keyRange.min,y),this.keyRange.max=Math.max(this.keyRange.max,y);break}}let p=We(E.data);switch(E.statusByte){case G.endOfTrack:g!==I.events.length-1&&(I.deleteEvent(g),g--,l.warn("Unexpected EndOfTrack. Removing!"));break;case G.setTempo:this.tempoChanges.push({ticks:E.ticks,tempo:6e7/Ht(E.data,3)});break;case G.marker:switch(p.trim().toLowerCase()){default:break;case"start":case"loopstart":s=E.ticks;break;case"loopend":a=E.ticks}break;case G.copyright:this.extraMetadata.push(E);break;case G.lyric:p.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,l.info("%cKaraoke MIDI detected!",d.recognized)),this.isKaraokeFile?E.statusByte=G.text:this.lyrics.push(E);case G.text:{let y=p.trim();y.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,l.info("%cKaraoke MIDI detected!",d.recognized)):this.isKaraokeFile&&(y.startsWith("@T")||y.startsWith("@A")?e?this.extraMetadata.push(E):(this.binaryName=E.data.slice(2),e=!0,A=!0):y.startsWith("@")||this.lyrics.push(E));break}}}I.channels=h,I.name="";let B=I.events.find(g=>g.statusByte===G.trackName);B&&this.tracks.indexOf(I)>0&&(I.name=We(B.data),!C&&!I.name.toLowerCase().includes("setup")&&this.extraMetadata.push(B))}this.tempoChanges.reverse(),l.info("%cCorrecting loops, ports and detecting notes...",d.info);let r=[];for(let I of this.tracks){let h=I.events.find(C=>(C.statusByte&240)===G.noteOn);h&&r.push(h.ticks)}this.firstNoteOn=Math.min(...r),l.info(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,d.info,d.recognized,d.info),s??=this.firstNoteOn,(a===null||a===0)&&(a=this.lastVoiceEventTick),this.loop={start:s,end:a,type:n},this.lastVoiceEventTick=Math.max(this.lastVoiceEventTick,this.loop.end),l.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 I of this.tracks)if(I.port=-1,I.channels.size!==0)for(let h of I.events){if(h.statusByte!==G.midiPort)continue;let C=h.data[0];I.port=C,this.portChannelOffsetMap[C]===void 0&&(this.portChannelOffsetMap[C]=i,i+=16)}this.portChannelOffsetMap=[...this.portChannelOffsetMap].map(I=>I??0);let o=1/0;for(let I of this.tracks)I.port!==-1&&o>I.port&&(o=I.port);o===1/0&&(o=0);for(let I of this.tracks)(I.port===-1||I.port===void 0)&&(I.port=o);if(this.portChannelOffsetMap.length===0&&(this.portChannelOffsetMap=[0]),this.portChannelOffsetMap.length<2?l.info("%cNo additional MIDI Ports detected.",d.info):(this.isMultiPort=!0,l.info("%cMIDI Ports detected!",d.recognized)),!A)if(this.tracks.length>1){if(!this.tracks[0].events.some(I=>I.statusByte>=G.noteOn&&I.statusByteh.statusByte===G.trackName);I&&(this.binaryName=I.data)}}else{let I=this.tracks[0].events.find(h=>h.statusByte===G.trackName);I&&(this.binaryName=I.data)}if(this.extraMetadata=this.extraMetadata.filter(I=>I.data.length>0),this.lyrics.sort((I,h)=>I.ticks-h.ticks),!this.tracks.some(I=>I.events[0].ticks===0)){let I=this.tracks[0],h=this?.binaryName?.buffer;h||(h=new Uint8Array(0).buffer),I.addEvents(0,new Qe(0,G.trackName,new te(h)))}this.duration=this.midiTicksToSeconds(this.lastVoiceEventTick),this.timeline.length=0,this.iterate((I,h,C)=>{this.timeline.push(Object.freeze({ev:C[h],tr:h}))}),this.binaryName?.length===0&&(this.binaryName=void 0),l.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),l.groupEnd()}};function ya(t,e){if(this.externalMIDIPlayback&&t.statusByte>=128){this.sendMIDIMessage([t.statusByte,...t.data]);return}let A=this._midiData.tracks[e],s,a=0;t.statusByte>=128&&t.statusByte<240?(s=t.statusByte&240,a=t.statusByte&15):s=t.statusByte;let n=this.midiPortChannelOffsets[this.currentMIDIPorts[e]]||0;switch(a+=n,s){case G.noteOn:{let r=this.playingNotes[a];if(!r){for(;this.playingNotes.length<=a;)this.playingNotes.push(new Map);r=this.playingNotes[a]}let i=t.data[1];i>0?(this.synth.noteOn(a,t.data[0],i),r.set(t.data[0],i)):(this.synth.noteOff(a,t.data[0]),r.delete(t.data[0]));break}case G.noteOff:{let r=this.playingNotes[a];if(!r){for(;this.playingNotes.length<=a;)this.playingNotes.push(new Map);r=this.playingNotes[a]}this.synth.noteOff(a,t.data[0]),r.delete(t.data[0]);break}case G.pitchWheel:this.synth.pitchWheel(a,t.data[1]<<7|t.data[0]);break;case G.controllerChange:if(this._midiData.isMultiPort&&A.channels.size===0)return;this.synth.controllerChange(a,t.data[0],t.data[1]);break;case G.programChange:if(this._midiData.isMultiPort&&A.channels.size===0)return;this.synth.programChange(a,t.data[0]);break;case G.polyPressure:this.synth.polyPressure(a,t.data[0],t.data[1]);break;case G.channelPressure:this.synth.channelPressure(a,t.data[0]);break;case G.systemExclusive:this.synth.systemExclusive(t.data,n);break;case G.setTempo:{let r=6e7/Ht(t.data,3);this.oneTickToSeconds=60/(r*this._midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this._midiData.timeDivision),l.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:l.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 Sa(){if(this.paused||!this._midiData)return;let t=this.currentTime;for(;this.playedTime0&&a.end<=r.ticks){this.loopCount!==1/0&&(this.loopCount--,this.callEvent("loopCountChange",{newCount:this.loopCount})),a.type==="soft"?this.jumpToTick(a.start):this.setTimeTicks(a.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 ka(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),l.info(`%cTotal song time: ${_A(Math.ceil(this._midiData.duration)).time}`,d.recognized),this.callEvent("songChange",{songIndex:this._songIndex}),this._midiData.duration<=.2&&(l.warn(`%cVery short song: (${_A(Math.round(this._midiData.duration)).time}). Disabling loop!`,d.warn),this.loopCount=0),this.currentTime=0}var yt=new Int16Array(128).fill(0),Ge=(t,e)=>yt[t]=e<<7;Ge(f.mainVolume,100);Ge(f.balance,64);Ge(f.expression,127);Ge(f.pan,64);Ge(f.filterResonance,64);Ge(f.releaseTime,64);Ge(f.attackTime,64);Ge(f.brightness,64);Ge(f.decayTime,64);Ge(f.vibratoRate,64);Ge(f.vibratoDepth,64);Ge(f.vibratoDelay,64);Ge(f.generalPurposeController6,64);Ge(f.generalPurposeController8,64);Ge(f.registeredParameterLSB,127);Ge(f.registeredParameterMSB,127);Ge(f.nonRegisteredParameterLSB,0);Ge(f.nonRegisteredParameterMSB,0);var pA=new Int8Array(128).fill(127);pA[35]=0;pA[36]=0;function wa(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=yt[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.setMIDIParameter("pressure",0),this.setMIDIParameter("pitchWheelRange",2),this.setMIDIParameter("modulationDepth",50),this.setMIDIParameter("rxChannel",this.channel),this.setMIDIParameter("efxAssign",!1),this.setMIDIParameter("polyMode",!0),this.setMIDIParameter("keyShift",0),this.setMIDIParameter("fineTune",0),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.setMIDIParameter("velocitySenseOffset",64),this.setMIDIParameter("velocitySenseDepth",64),this.pitchWheel(8192),this.octaveTuning.fill(0),this.lastPortamentoNote=this.channelSystem==="xg"?60:-1,this.resetDrumParams(),this.resetGeneratorOverrides(),this.resetGeneratorOffsets(),this.dynamicModulators.resetModulators(),this.sf2NRPNGeneratorLSB=0,this.playingNotes.fill(!1),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(De.getDefaultBank(this.channelSystem)),this.setBankLSB(0),this.setGSDrums(!1),this.setDrums(this.channel%16===9),this.programChange(0)}var on=[f.modulationWheel,f.expression,f.sustainPedal,f.portamentoOnOff,f.sostenutoPedal,f.softPedal,f.registeredParameterMSB,f.registeredParameterLSB];function Ma(){this.pitchWheel(8192),this.setMIDIParameter("pressure",0);for(let t of on){let e=yt[t];e!==this._midiControllers[t]&&this.controllerChange(t,e>>7)}}var oA=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 ba(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 I=0;I=t)break}else if(B.ticks>=e)break;let g,E=0;B.statusByte>=128&&B.statusByte<240?(g=B.statusByte&240,E=B.statusByte&15):g=B.statusByte;let p=E+(this.midiPortChannelOffsets[C.port]||0);s[p]??={pitchWheel:8192,controllers:new Int16Array(yt),param:new mA(p),portamentoNote:-1};let y=s[p];switch(g){case G.noteOn:y.portamentoNote=B.data[0];break;case G.noteOff:break;case G.pitchWheel:y.pitchWheel=B.data[1]<<7|B.data[0];break;case G.systemExclusive:{let S=ne.analyzeSysEx(B.data);switch(S.type){default:this.processEvent(B,h);break;case"Controller Change":{let{controller:w,value:F,channel:H}=S;if(H>=A||this._midiData.isMultiPort&&C.channels.size===0)break;if(w===f.resetAllControllers){r(H);break}oA.has(w)?this.sendMIDICC(H,w,F):s[H].controllers[w]=F<<7}}break}case G.controllerChange:{if(this._midiData.isMultiPort&&C.channels.size===0)break;let S=B.data[0],w=B.data[1];switch(S){default:if(S===f.resetAllControllers){r(p);break}oA.has(S)?this.sendMIDICC(p,S,w):y.controllers[S]=w<<7;break;case f.registeredParameterMSB:case f.registeredParameterLSB:case f.nonRegisteredParameterLSB:case f.nonRegisteredParameterMSB:y.param.controllerChange(S,w,0,0),this.sendMIDICC(p,S,w);break;case f.dataEntryMSB:case f.dataEntryLSB:{let F=y.param.controllerChange(S,w,0,0);this.sendMIDICC(p,S,w),F.type==="Controller Change"&&(oA.has(F.controller)?this.sendMIDICC(p,F.controller,F.value):y.controllers[F.controller]=F.value<<7);break}}break}case G.setTempo:{let S=6e7/Ht(B.data,3);this.oneTickToSeconds=60/(S*this._midiData.timeDivision),a=B,n=h;break}default:this.processEvent(B,h);break}let D=i[++this.index],R=o[D.tr].events[D.ev];if(R===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(R.ticks-B.ticks)}for(let I=0;I=0&&(this.externalMIDIPlayback?this.sendMIDICC(I,f.portamentoControl,h.portamentoNote):this.synth.midiChannels[I].setLastNote(h.portamentoNote));for(let C=0;C<128;C++){let B=h.controllers[C]>>7;B!==yt[C]&&!oA.has(C)&&this.sendMIDICC(I,C,B)}}return a&&this.callEvent("metaEvent",{event:a,trackIndex:n}),this.paused&&(this.pausedTime=this.playedTime),!0}var gn=class{songs=[];shuffledSongIndexes=[];synth;externalMIDIPlayback=!1;retriggerPausedNotes=!0;loopCount=0;skipToFirstNoteOn=!0;isFinished=!1;preload=!0;onEventCall;processTick=Sa.bind(this);firstNoteTime=0;oneTickToSeconds=0;index=0;playedTime=0;pausedTime=-1;absoluteStartTime=0;playingNotes=[];currentMIDIPorts=[];midiPortChannelOffset=0;midiPortChannelOffsets={};assignMIDIPort=ka.bind(this);loadNewSequence=Da.bind(this);processEvent=ya.bind(this);setTimeTo=ba.bind(this);constructor(t){this.synth=t,this.absoluteStartTime=this.synth.currentTime,this.playingNotes=this.synth.midiChannels.map(()=>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(n=>e.tracks[n.tr].events[n.ev].ticks>=t);this.index=s===-1?e.timeline.length:s;let a=e.tempoChanges.find(n=>n.ticks<=t);this.oneTickToSeconds=60/(a.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])}},Ra={linear:0,nearestNeighbor:1,hermite:2},Wt=Wt!==void 0?Wt:{},Fs=!1,In;Wt.isInitialized=new Promise(t=>In=t);var Fa=function(t){var e,A,s,a,n,r,i,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",I="",h=0;t=t.replace(/[^A-Za-z0-9\\+\\/\\=]/g,"");do a=o.indexOf(t.charAt(h++)),n=o.indexOf(t.charAt(h++)),r=o.indexOf(t.charAt(h++)),i=o.indexOf(t.charAt(h++)),e=a<<2|n>>4,A=(15&n)<<4|r>>2,s=(3&r)<<6|i,I+=String.fromCharCode(e),r!==64&&(I+=String.fromCharCode(A)),i!==64&&(I+=String.fromCharCode(s));while(h1&&(g.thisProgram=process.argv[1].replace(/\\\\/g,"/")),g.arguments=process.argv.slice(2),process.on("uncaughtException",function(v){if(!(v instanceof Ke))throw v}),process.on("unhandledRejection",function(v,M){process.exit(1)}),g.quit=function(v){process.exit(v)},g.inspect=function(){return"[Emscripten Module object]"}):R?(typeof read<"u"&&(g.read=function(M){return read(M)}),g.readBinary=function(M){var P;return typeof readbuffer=="function"?new Uint8Array(readbuffer(M)):(q(typeof(P=read(M,"binary"))=="object"),P)},typeof scriptArgs<"u"?g.arguments=scriptArgs:typeof arguments<"u"&&(g.arguments=arguments),typeof quit=="function"&&(g.quit=function(v){quit(v)})):(p||y)&&(p?document.currentScript&&(S=document.currentScript.src):S=self.location.href,S=S.indexOf("blob:")!==0?S.split("/").slice(0,-1).join("/")+"/":"",g.read=function(M){var P=new XMLHttpRequest;return P.open("GET",M,!1),P.send(null),P.responseText},y&&(g.readBinary=function(M){var P=new XMLHttpRequest;return P.open("GET",M,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),g.readAsync=function(M,P,_){var ie=new XMLHttpRequest;ie.open("GET",M,!0),ie.responseType="arraybuffer",ie.onload=function(){if(ie.status==200||ie.status==0&&ie.response){P(ie.response);return}_()},ie.onerror=_,ie.send(null)},g.setWindowTitle=function(v){document.title=v});var F=g.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),H=g.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||F);for(t in E)E.hasOwnProperty(t)&&(g[t]=E[t]);function k(v){var M=o;return o=o+v+15&-16,M}function u(v,M){return M||(M=16),v=Math.ceil(v/M)*M}function m(v){m.shown||(m.shown={}),m.shown[v]||(m.shown[v]=1,H(v))}E=void 0;var J={"f64-rem":function(v,M){return v%M},debugger:function(){}},O=0;function q(v,M){v||tt("Assertion failed: "+M)}function K(v){var M=g["_"+v];return q(M,"Cannot call unknown function "+v+", make sure it is exported"),M}var ae={stackSave:function(){Rt()},stackRestore:function(){dt()},arrayToC:function(v){var M,P,_=It(v.length);return M=v,P=_,a.set(M,P),_},stringToC:function(v){var M=0;if(v!=null&&v!==0){var P=(v.length<<2)+1;M=It(P),z(v,M,P)}return M}},U={string:ae.stringToC,array:ae.arrayToC};function T(v,M,P,_,ie){var ce=K(v),fe=[],j=0;if(_)for(var Te=0;Te<_.length;Te++){var Me=U[P[Te]];Me?(j===0&&(j=Rt()),fe[Te]=Me(_[Te])):fe[Te]=_[Te]}var oe,Be=ce.apply(null,fe);return Be=(oe=Be,M==="string"?Q(oe):M==="boolean"?!!oe:oe),j!==0&&dt(j),Be}function Q(v,M){if(M===0||!v)return"";for(var P,_,ie,ce=0,fe=0;ce|=_=n[v+fe>>0],(_!=0||M)&&(fe++,!M||fe!=M););M||(M=fe);var j="";if(ce<128){for(;M>0;)ie=String.fromCharCode.apply(String,n.subarray(v,v+Math.min(M,1024))),j=j?j+ie:ie,v+=1024,M-=1024;return j}return P=v,(function(Me,oe){for(var Be=oe;Me[Be];)++Be;if(Be-oe>16&&Me.subarray&&b)return b.decode(Me.subarray(oe,Be));for(var he,xe,He,At,mt,ct="";;){if(!(he=Me[oe++]))return ct;if(!(128&he)){ct+=String.fromCharCode(he);continue}if(xe=63&Me[oe++],(224&he)==192){ct+=String.fromCharCode((31&he)<<6|xe);continue}if(He=63&Me[oe++],(240&he)==224?he=(15&he)<<12|xe<<6|He:(At=63&Me[oe++],(248&he)==240?he=(7&he)<<18|xe<<12|He<<6|At:(mt=63&Me[oe++],he=(252&he)==248?(3&he)<<24|xe<<18|He<<12|At<<6|mt:(1&he)<<30|xe<<24|He<<18|At<<12|mt<<6|63&Me[oe++])),he<65536)ct+=String.fromCharCode(he);else{var st=he-65536;ct+=String.fromCharCode(55296|st>>10,56320|1023&st)}}})(n,P)}var b=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function L(v,M,P,_){if(!(_>0))return 0;for(var ie=P,ce=P+_-1,fe=0;fe=55296&&j<=57343&&(j=65536+((1023&j)<<10)|1023&v.charCodeAt(++fe)),j<=127){if(P>=ce)break;M[P++]=j}else if(j<=2047){if(P+1>=ce)break;M[P++]=192|j>>6,M[P++]=128|63&j}else if(j<=65535){if(P+2>=ce)break;M[P++]=224|j>>12,M[P++]=128|j>>6&63,M[P++]=128|63&j}else if(j<=2097151){if(P+3>=ce)break;M[P++]=240|j>>18,M[P++]=128|j>>12&63,M[P++]=128|j>>6&63,M[P++]=128|63&j}else if(j<=67108863){if(P+4>=ce)break;M[P++]=248|j>>24,M[P++]=128|j>>18&63,M[P++]=128|j>>12&63,M[P++]=128|j>>6&63,M[P++]=128|63&j}else{if(P+5>=ce)break;M[P++]=252|j>>30,M[P++]=128|j>>24&63,M[P++]=128|j>>18&63,M[P++]=128|j>>12&63,M[P++]=128|j>>6&63,M[P++]=128|63&j}}return M[P]=0,P-ie}function z(v,M,P){return L(v,n,M,P)}typeof TextDecoder<"u"&&new TextDecoder("utf-16le");function $(v,M){return v%M>0&&(v+=M-v%M),v}function W(v){g.buffer=s=v}function V(){g.HEAP8=a=new Int8Array(s),g.HEAP16=new Int16Array(s),g.HEAP32=r=new Int32Array(s),g.HEAPU8=n=new Uint8Array(s),g.HEAPU16=new Uint16Array(s),g.HEAPU32=new Uint32Array(s),g.HEAPF32=new Float32Array(s),g.HEAPF64=new Float64Array(s)}function ee(){var v=g.usingWasm?65536:16777216,M=2147483648-v;if(r[B>>2]>M)return!1;var P=Y;for(Y=Math.max(Y,16777216);Y>2];)Y=Y<=536870912?$(2*Y,v):Math.min($((3*Y+2147483648)/4,v),M);var _=g.reallocBuffer(Y);return _&&_.byteLength==Y?(W(_),V(),!0):(Y=P,!1)}i=o=I=h=C=B=0,g.reallocBuffer||(g.reallocBuffer=function(v){try{if(ArrayBuffer.transfer)M=ArrayBuffer.transfer(s,v);else{var M,P=a;M=new ArrayBuffer(v),new Int8Array(M).set(P)}}catch{return!1}return!!_e(M)&&M});try{Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get)(new ArrayBuffer(4))}catch{}var Ae=g.TOTAL_STACK||5242880,Y=g.TOTAL_MEMORY||16777216;function re(){return Y}function ue(v){for(;v.length>0;){var M=v.shift();if(typeof M=="function"){M();continue}var P=M.func;typeof P=="number"?M.arg===void 0?g.dynCall_v(P):g.dynCall_vi(P,M.arg):P(M.arg===void 0?null:M.arg)}}Y>2]=C,g.wasmTableSize=4,g.wasmMaxTableSize=4,g.asmGlobalArg={},g.asmLibraryArg={abort:tt,assert:q,enlargeMemory:ee,getTotalMemory:re,abortOnCannotGrowMemory:function(){tt("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+Y+", (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(M,P,_){var ie=Rt();try{return g.dynCall_iii(M,P,_)}catch(ce){if(dt(ie),typeof ce!="number"&&ce!=="longjmp")throw ce;g.setThrew(1,0)}},___assert_fail:function(M,P,_,ie){tt("Assertion failed: "+Q(M)+", at: "+[P?Q(P):"unknown filename",_,ie?Q(ie):"unknown function"])},___setErrNo:function(M){return g.___errno_location&&(r[g.___errno_location()>>2]=M),M},_abort:function(){g.abort()},_emscripten_memcpy_big:function(M,P,_){return n.set(n.subarray(P,P+_),M),M},_llvm_floor_f64:AA,DYNAMICTOP_PTR:B,tempDoublePtr:UA,ABORT:O,STACKTOP:I,STACK_MAX:h};var qt=g.asm(g.asmGlobalArg,g.asmLibraryArg,s);g.asm=qt,g.___errno_location=function(){return g.asm.___errno_location.apply(null,arguments)};var _e=g._emscripten_replace_memory=function(){return g.asm._emscripten_replace_memory.apply(null,arguments)};g._free=function(){return g.asm._free.apply(null,arguments)},g._malloc=function(){return g.asm._malloc.apply(null,arguments)},g._memcpy=function(){return g.asm._memcpy.apply(null,arguments)},g._memset=function(){return g.asm._memset.apply(null,arguments)},g._sbrk=function(){return g.asm._sbrk.apply(null,arguments)},g._stb_vorbis_js_channels=function(){return g.asm._stb_vorbis_js_channels.apply(null,arguments)},g._stb_vorbis_js_close=function(){return g.asm._stb_vorbis_js_close.apply(null,arguments)},g._stb_vorbis_js_decode=function(){return g.asm._stb_vorbis_js_decode.apply(null,arguments)},g._stb_vorbis_js_open=function(){return g.asm._stb_vorbis_js_open.apply(null,arguments)},g._stb_vorbis_js_sample_rate=function(){return g.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},g.establishStackSpace=function(){return g.asm.establishStackSpace.apply(null,arguments)},g.getTempRet0=function(){return g.asm.getTempRet0.apply(null,arguments)},g.runPostSets=function(){return g.asm.runPostSets.apply(null,arguments)},g.setTempRet0=function(){return g.asm.setTempRet0.apply(null,arguments)},g.setThrew=function(){return g.asm.setThrew.apply(null,arguments)};var It=g.stackAlloc=function(){return g.asm.stackAlloc.apply(null,arguments)},dt=g.stackRestore=function(){return g.asm.stackRestore.apply(null,arguments)},Rt=g.stackSave=function(){return g.asm.stackSave.apply(null,arguments)};function Ke(v){this.name="ExitStatus",this.message="Program terminated with exit("+v+")",this.status=v}function ut(v){v=v||g.arguments,!(Je>0)&&((function(){if(g.preRun)for(typeof g.preRun=="function"&&(g.preRun=[g.preRun]);g.preRun.length;)Et(g.preRun.shift());ue(Le)})(),!(Je>0)&&(g.calledRun||(g.setStatus?(g.setStatus("Running..."),setTimeout(function(){setTimeout(function(){g.setStatus("")},1),M()},1)):M())));function M(){!g.calledRun&&(g.calledRun=!0,O||(Bt||(Bt=!0,ue(Ee)),ue(Re),g.onRuntimeInitialized&&g.onRuntimeInitialized(),(function(){if(g.postRun)for(typeof g.postRun=="function"&&(g.postRun=[g.postRun]);g.postRun.length;)tA(g.postRun.shift());ue(Oe)})()))}}function tt(v){throw g.onAbort&&g.onAbort(v),v!==void 0?(F(v),H(v),v=JSON.stringify(v)):v="",O=!0,"abort("+v+"). Build with -s ASSERTIONS=1 for more info."}if(g.dynCall_iii=function(){return g.asm.dynCall_iii.apply(null,arguments)},g.asm=qt,g.ccall=T,g.cwrap=function(M,P,_,ie){var ce=(_=_||[]).every(function(fe){return fe==="number"});return P!=="string"&&ce&&!ie?K(M):function(){return T(M,P,_,arguments,ie)}},Ke.prototype=Error(),Ke.prototype.constructor=Ke,Fe=function v(){g.calledRun||ut(),g.calledRun||(Fe=v)},g.run=ut,g.abort=tt,g.preInit)for(typeof g.preInit=="function"&&(g.preInit=[g.preInit]);g.preInit.length>0;)g.preInit.pop()();g.noExitRuntime=!0,ut(),g.onRuntimeInitialized=()=>{Fs=!0,In()},Wt.decode=function(v){return(function(P){if(!Fs)throw Error("SF3 decoder has not been initialized yet. Did you await synth.isReady?");var _={};function ie(Ft){return new Int32Array(g.HEAPU8.buffer,Ft,1)[0]}function ce(Ft,vt){var sA=new ArrayBuffer(vt*Float32Array.BYTES_PER_ELEMENT),Ve=new Float32Array(sA);return Ve.set(new Float32Array(g.HEAPU8.buffer,Ft,vt)),Ve}_.open=g.cwrap("stb_vorbis_js_open","number",[]),_.close=g.cwrap("stb_vorbis_js_close","void",["number"]),_.channels=g.cwrap("stb_vorbis_js_channels","number",["number"]),_.sampleRate=g.cwrap("stb_vorbis_js_sample_rate","number",["number"]),_.decode=g.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var fe,j,Te,Me,oe=_.open(),Be=(fe=P,j=P.byteLength,Te=g._malloc(j),(Me=new Uint8Array(g.HEAPU8.buffer,Te,j)).set(new Uint8Array(fe,0,j)),Me),he=g._malloc(4),xe=g._malloc(4),He=_.decode(oe,Be.byteOffset,Be.byteLength,he,xe);if(g._free(Be.byteOffset),He<0)throw _.close(oe),g._free(he),Error("stbvorbis decode failed: "+He);for(var At=_.channels(oe),mt=Array(At),ct=new Int32Array(g.HEAPU32.buffer,ie(he),At),st=0;st=0}getPatch(t,e){let A=this.keyMappings[t]?.[e];if(A)return A.patch;throw new Error("No modifier.")}};function La(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 cn={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:Ra.hermite,nrpnParamLock:!1,monophonicRetrigger:!1};function Na(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 a=s;athis.voices.length&&(l.warn(`Allocating ${s-this.voices.length} new voices!`),this.allocateNewVoices(s-this.voices.length));break}case"keyShift":A!==e&&this.stopAllChannels(!0)}}var fs=-15e3,ts=new Float32Array(15e3-fs+1);for(let t=0;thn?440*Math.pow(2,(t-6900)/1200):As[t-SA|0]}var Tt=-16600,Ut=new Float32Array(16e3-Tt+1);for(let t=0;t=gA&&(t.isActive=!1)}init(t){this.enteredRelease=!1,this.state=0,this.sampleTime=0,this.outputGain=0,this.canEndOnSilentSustain=t.modulatedGenerators[c.sustainVolEnv]>=gA,this.sustainCb=Math.min(Xe,t.modulatedGenerators[c.sustainVolEnv]),this.attackDuration=this.timecentsToSamples(t.modulatedGenerators[c.attackVolEnv]);let e=(60-t.targetKey)*t.modulatedGenerators[c.keyNumToVolEnvDecay],A=this.sustainCb/Xe;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:a,delayEnd:n,attackEnd:r,attackDuration:i,holdEnd:o,decayEnd:I,decayDuration:h,sustainCb:C}=this,B=this.sampleTime+=t;if(this.enteredRelease){let g=B-A,E=Xe-s;return this.attenuationCb=g/a*E+s,this.outputGain=Ut[this.attenuationCb-Tt|0]*e,this.attenuationCb=gA?(this.attenuationCb=Xe,this.outputGain=0,!1):(this.attenuationCb=C,this.outputGain=e*Ut[C-Tt|0],!0)}}timecentsToSamples(t){return Math.max(0,Math.floor(yA(t)*this.sampleRate))}},ve={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},Ce={linear:0,concave:1,convex:2,switch:3};var Ye=16384,DA=Object.keys(Ce).length,lt=new Float32Array(Ye+1),kt=new Float32Array(Ye+1);lt[0]=0;lt[lt.length-1]=1;kt[0]=0;kt[kt.length-1]=1;for(let t=1;t.5?1:0,s?A*2-1:A;case Ce.concave:return s?(A=A*2-1,A<0?-lt[Math.trunc(A*-Ye)]:lt[Math.trunc(A*Ye)]):lt[Math.trunc(A*Ye)];case Ce.convex:return s?(A=A*2-1,A<0?-kt[Math.trunc(A*-Ye)]:kt[Math.trunc(A*Ye)]):kt[Math.trunc(A*Ye)]}}var qA=1,ns=new Float32Array(1e3);for(let t=0;t=n;)o-=r;let h=o|0,C=h+1;C>=n&&(C-=r);let B=o-h,g=a[C],E=a[h];A[I]=E+(g-E)*B,o+=s}else for(let I=0;I=i)return A.fill(0,I,t),!1;let B=o-h,g=a[C],E=a[h];A[I]=E+(g-E)*B,o+=s}return this.cursor=o,!0}},Oa=class extends us{process(t,e,A){let s=e*this.playbackStep,a=this.sampleData,{loopEnd:n,loopLength:r,end:i}=this,o=this.cursor;if(this.isLooping)for(let I=0;I=n;)o-=r;A[I]=a[o|0],o+=s}else for(let I=0;I=i)return A.fill(0,I,t),!1;A[I]=a[o|0],o+=s}return this.cursor=o,!0}},Ya=class extends us{process(t,e,A){let s=e*this.playbackStep,a=this.sampleData,{loopEnd:n,loopLength:r,end:i}=this,o=this.cursor;if(this.isLooping)for(let I=0;I=n;)o-=r;let h=o|0,C=h+1,B=h+2,g=h+3,E=o-h;C>=n&&(C-=r),B>=n&&(B-=r),g>=n&&(g-=r);let p=a[h],y=a[C],D=a[B],R=a[g],S=(D-p)*.5,w=y-D,F=S+w,H=F+w+(R-y)*.5,k=F+H;A[I]=((H*E-k)*E+S)*E+y,o+=s}else for(let I=0;I=i)return A.fill(0,I,t),!1;let p=a[h],y=a[C],D=a[B],R=a[g],S=(D-p)*.5,w=y-D,F=S+w,H=F+w+(R-y)*.5,k=F+H;A[I]=((H*E-k)*E+S)*E+y,o+=s}return this.cursor=o,!0}},qa=-2320,Ja=class{oscillators=[new Ha,new Oa,new Ya];wavetable=this.oscillators[cn.interpolationType];filter;generators=new Int16Array(Dt);modulatedGenerators=new Int16Array(Dt);modulators=new Array;modulatorValues=new Int16Array(64);modEnv=new xa;volEnv;resonanceOffset=0;priority=0;isActive=!1;hasRendered=!1;isInRelease=!1;isHeld=!1;channel=0;noteID=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 Ua(t,e),this.filter=new Qs(t)}exclusiveRelease(t,e=ea){this.overrideReleaseVolEnv=qa,this.isInRelease=!1,this.releaseVoice(t,e)}releaseVoice(t,e=jn){this.releaseStartTime=t,this.releaseStartTime-this.startTime>e&1)>0}function JA(t){return t?1:0}var at=class as{isBipolar;isNegative;index;isCC;curveType;constructor(e=Ie.noController,A=Ce.linear,s=!1,a=!1,n=!1){this.isBipolar=a,this.isNegative=n,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(Ce).find(e=>Ce[e]===this.curveType)??this.curveType.toString()}static fromSourceEnum(e){let A=St(e,9),s=St(e,8),a=St(e,7);return new as(e&127,e>>10&3,a,A,s)}static copyFrom(e){return new as(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|JA(this.isBipolar)<<9|JA(this.isNegative)<<8|JA(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 a;if(this.isCC)a=e.midiControllers[this.index];else switch(this.index){default:case Ie.noController:a=16383;break;case Ie.noteOnVelocity:a=s.velocity<<7;break;case Ie.noteOnKeyNum:a=s.targetKey<<7;break;case Ie.polyPressure:a=s.pressure<<7;break;case Ie.channelPressure:a=e.midiParameters.pressure<<7;break;case Ie.pitchWheel:a=A;break;case Ie.pitchWheelRange:a=Math.floor(e.midiParameters.pitchWheelRange*128)}let n=(this.isBipolar?2:0)|(this.isNegative?1:0);return Bn[Ye*(this.curveType*DA+n)+a]}},Bn=new Float32Array(Ye*4*DA);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 rs(at.copyFrom(e.primarySource),at.copyFrom(e.secondarySource),e.destination,e.transformAmount,e.transformType)}toString(){return`Source: ${this.primarySource.toString()}\nSecondary source: ${this.secondarySource.toString()}\nto: ${this.destinationName}\namount: ${this.transformAmount}`+(this.transformType===2?"absolute value":"")}write(e,A){se(e,this.primarySource.toSourceEnum()),se(e,this.destination),se(e,this.transformAmount),se(e,this.secondarySource.toSourceEnum()),se(e,this.transformType),A&&A.mod++}sumTransform(e){let A=rs.copyFrom(this);return A.transformAmount+=e.transformAmount,A}},ye=class extends we{constructor(t,e,A,s,a){super(at.fromSourceEnum(t),at.fromSourceEnum(e),A,s,a),this.destination>ln&&(this.destination=c.invalid)}},Ka=[new ye($e(Ce.concave,!1,!0,!1,Ie.noteOnVelocity),0,c.initialAttenuation,960,0),new ye(129,0,c.vibLfoToPitch,50,0),new ye($e(Ce.concave,!1,!0,!0,f.mainVolume),0,c.initialAttenuation,960,0),new ye(13,0,c.vibLfoToPitch,50,0),new ye(526,16,c.fineTune,12700,0),new ye(650,0,c.pan,500,0),new ye($e(Ce.concave,!1,!0,!0,f.expression),0,c.initialAttenuation,960,0),new ye(219,0,c.reverbEffectsSend,200,0),new ye(221,0,c.chorusEffectsSend,200,0)],Va=[new ye($e(Ce.convex,!0,!1,!0,f.attackTime),0,c.attackVolEnv,6e3,0),new ye($e(Ce.linear,!0,!1,!0,f.releaseTime),0,c.releaseVolEnv,3600,0),new ye($e(Ce.linear,!0,!1,!0,f.decayTime),0,c.decayVolEnv,3600,0),new ye($e(Ce.linear,!0,!1,!0,f.brightness),0,c.initialFilterFc,9600,0),new ye(En,0,c.initialFilterQ,250,0),new ye($e(Ce.switch,!1,!1,!0,f.softPedal),0,c.initialAttenuation,50,0),new ye($e(Ce.switch,!1,!1,!0,f.softPedal),0,c.initialFilterFc,-2400,0),new ye($e(Ce.linear,!0,!1,!0,f.balance),0,c.pan,500,0)],dn=[...Ka,...Va],Pe=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=ze[t];s!==void 0&&(this.value=Math.max(s.min,Math.min(s.max,this.value)))}}write(t){se(t,this.type),se(t,this.value)}toString(){return`${Object.keys(c).find(t=>c[t]===this.type)}: ${this.value}`}},jt=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,ze[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(a=>a.type!==t);return}let s=this.generators.findIndex(a=>a.type===t);s===-1?this.addGenerators(new Pe(t,e,A)):this.generators[s]=new Pe(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 Pe(e.type,e.value,!1)),this.modulators=t.modulators.map(we.copyFrom.bind(we)),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 Pe(c.velRange,this.velRange.max<<8|Math.max(this.velRange.min,0),!1)),this.hasKeyRange&&e.unshift(new Pe(c.keyRange,this.keyRange.max<<8|Math.max(this.keyRange.min,0),!1)),e}},Xa=48e3,vA=class{name;sampleRate;originalKey;pitchCorrection;linkedSample;sampleType;loopStart;loopEnd;linkedTo=[];dataOverridden=!0;compressedData;audioData;constructor(t,e,A,s,a,n,r){this.name=t,this.sampleRate=e,this.originalKey=A,this.pitchCorrection=s,this.loopStart=n,this.loopEnd=r,this.sampleType=a}get isCompressed(){return this.compressedData!==void 0}get isLinked(){return this.sampleType===ve.rightSample||this.sampleType===ve.leftSample||this.sampleType===ve.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 a=0;a96e3)&&(this.resampleData(Xa),e=this.getAudioData());let A=await t(e,this.sampleRate);this.setCompressedData(A)}catch(e){l.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(ve.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 ve.leftSample:this.setSampleType(ve.leftSample),t.setSampleType(ve.rightSample);break;case ve.rightSample:this.setSampleType(ve.rightSample),t.setSampleType(ve.leftSample);break;case ve.linkedSample:this.setSampleType(ve.linkedSample),t.setSampleType(ve.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){l.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?a=32767:a<-32768&&(a=-32768),e[s]=a}return new te(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 l.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(a=>we.isIdentical(s,a))||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 Qn(this,e);return this.zones.push(A),A}preload(e,A){for(let s=e;swe.isIdentical(C,g));B===-1?I.push(C):I[B]=I[B].sumTransform(C)}let h=new Int16Array(is);for(let C of n.globalZone.generators)h[C.type]=C.value;for(let C of o.generators)h[C.type]=C.value;for(let C=0;C{I.push(...h.filter(C=>!I.some(B=>B.type===C.type)))},A=(I,h)=>{I.push(...h.filter(C=>!I.some(B=>we.isIdentical(C,B))))},s=new _t;s.name=this.name;let a=[],n=[],r=this.globalZone;a.push(...r.generators),n.push(...r.modulators);let i=r.keyRange,o=r.velRange;for(let I of this.zones){if(!I.instrument)throw new Error("No instrument in a preset zone.");let h=I.keyRange;I.hasKeyRange||(h=i);let C=I.velRange;I.hasVelRange||(C=o);let B=I.generators.map(F=>new Pe(F.type,F.value));e(B,a);let g=[...I.modulators];A(g,n);let E=I.instrument,p=E.zones,y=[],D=[],R=E.globalZone;y.push(...R.generators),D.push(...R.modulators);let S=R.keyRange,w=R.velRange;for(let F of p){if(!F.sample)throw new Error("No sample in an instrument zone.");let H=F.keyRange;F.hasKeyRange||(H=S);let k=F.velRange;if(F.hasVelRange||(k=w),H=ot.subtractRanges(H,h),k=ot.subtractRanges(k,C),H.maxnew Pe(K.type,K.value));e(u,y);let m=[...F.modulators];A(m,D);let J=[...m];for(let K of g){let ae=J.findIndex(U=>we.isIdentical(K,U));ae===-1?J.push(K):J[ae]=J[ae].sumTransform(K)}let O=u.map(K=>new Pe(K.type,K.value));for(let K of B){if(K.type===c.velRange||K.type===c.keyRange||K.type===c.instrument||K.type===c.endOper||K.type===c.sampleModes)continue;let ae=u.findIndex(U=>U.type===K.type);if(ae===-1){let U=ze[K.type].def+K.value;O.push(new Pe(K.type,U))}else{let U=O[ae].value+K.value;O[ae]=new Pe(K.type,U)}}O=O.filter(K=>K.type!==c.sampleID&&K.type!==c.keyRange&&K.type!==c.velRange&&K.type!==c.endOper&&K.type!==c.instrument&&(!(K.type in ze)||K.value!==ze[K.type].def));let q=s.createZone(F.sample);q.keyRange=H,q.velRange=k,q.keyRange.min===0&&q.keyRange.max===127&&(q.keyRange.min=-1),q.velRange.min===0&&q.velRange.max===127&&(q.velRange.min=-1),q.addGenerators(...O),q.addModulators(...J)}}return s}write(e,A,s){l.info(`%cWriting ${this.name}...`,d.info),Ne(e.pdta,this.name.slice(0,20),20),Ne(e.xdta,this.name.slice(20),20),se(e.pdta,this.program);let a=this.bankMSB;s?(a=this.bankMSB&127|(this.bankLSB&127)<<8,this.isGMGSDrum&&(a|=128)):this.isGMGSDrum?a=128:this.bankMSB===0&&(a=this.bankLSB),se(e.pdta,a),e.xdta.currentIndex+=4,se(e.pdta,A&65535),se(e.xdta,A>>16),ge(e.pdta,this.library),ge(e.pdta,this.genre),ge(e.pdta,this.morphology),e.xdta.currentIndex+=12}},Wa=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]),_t=class{name="";zones=[];globalZone=new jt;linkedTo=[];get useCount(){return this.linkedTo.length}createZone(t){let e=new fn(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){l.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(Wa.has(A))continue;A=A;let s={},a=ze[A]?.def||0;s[a]=0;for(let n of this.zones){let r=n.getGenerator(A,void 0);r===void 0?s[a]++: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(n.getGenerator(i,void 0)!==void 0){s={};break}}if(Object.keys(s).length>0){let n=["0",0];for(let[i,o]of Object.entries(s))o>n[1]&&(n=[i,o]);let r=Number.parseInt(n[0]);r!==a&&t.setGenerator(A,r,!1);for(let i of this.zones){let o=i.getGenerator(A,void 0);o===void 0?r!==a&&i.setGenerator(A,a):o===r&&i.setGenerator(A,null)}}}let e=this.zones.length===0?[]:this.zones[0].modulators.map(A=>we.copyFrom(A));for(let A of e){let s=!0;for(let a of this.zones)s&&(a.modulators.find(n=>we.isIdentical(n,A))||(s=!1));if(s){t.addModulators(we.copyFrom(A));for(let a of this.zones){let n=a.modulators.find(r=>we.isIdentical(r,A));n&&n.transformAmount===A.transformAmount&&a.modulators.splice(a.modulators.indexOf(n),1)}}}}write(t,e){l.info(`%cWriting ${this.name}...`,d.info),Ne(t.pdta,this.name.slice(0,20),20),Ne(t.xdta,this.name.slice(20),20),se(t.pdta,e&65535),se(t.xdta,e>>>16)}};function za(t,e,A,s,a){let n=0,r=[],i=[];for(let C of t.samples){let B=C.getRawData(!0);n++,a?.(n/t.samples.length),l.info(`%cWrote sample %c${n}. ${C.name}%c of %c${t.samples.length}.`,d.info,d.recognized,d.info,d.recognized),r.push(B),i.push(B.length),C.isCompressed||r.push(new Uint8Array(92))}let o=x.getParts("smpl",r,s),I=x.getParts("sdta",o,s,!0),h=0;for(let[C,B]of t.samples.entries()){let g=i[C],E,p;B.isCompressed?(E=h,p=E+g):(E=h/2,p=E+g/2,h+=92),h+=g,e.push(E),A.push(p)}return I}var _a=class extends vA{linkedSampleIndex;s16leData;startByteOffset;endByteOffset;sampleID;constructor(t,e,A,s,a,n,r,i,o,I,h,C){let B=(I&16)>0;I&=-17,super(t,n,r,i,I,s-e/2,a-e/2),this.dataOverridden=!1,this.name=t,this.startByteOffset=e,this.endByteOffset=A,this.sampleID=C;let g=h instanceof te?h.currentIndex:0;h instanceof te?B?(this.loopStart+=this.startByteOffset/2,this.loopEnd+=this.startByteOffset/2,this.setCompressedData(h.slice(this.startByteOffset/2+g,this.endByteOffset/2+g))):this.s16leData=h.slice(g+this.startByteOffset,g+this.endByteOffset):this.setAudioData(h.slice(this.startByteOffset/2,this.endByteOffset/2),n),this.linkedSampleIndex=o}getLinkedSample(t){if(this.linkedSample||!this.isLinked)return;let e=t[this.linkedSampleIndex];e?e.linkedSample?(l.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):(l.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 l.warn(`Invalid sample ${this.name}! Invalid length: ${t}`),new Float32Array(1);let e=new Float32Array(t/2),A=new Int16Array(this.s16leData.buffer),s=A.length;for(let a=0;at.data.currentIndex;){let n=$a(a,t.data,e);s.push(n),a++}if(s.pop(),A)for(let n of s)n.getLinkedSample(s);return s}function $a(t,e,A){let s=de(e,20),a=X(e,4)*2,n=X(e,4)*2,r=X(e,4),i=X(e,4),o=X(e,4),I=e[e.currentIndex++];I>127&&(I=60);let h=Wn(e[e.currentIndex++]),C=X(e,2),B=X(e,2);return new _a(s,a,n,r,i,o,I,h,C,B,A,t)}function ja(t,e,A,s){let n=46*(t.samples.length+1),r=new te(n),i=new te(n),o=0;for(let[I,h]of t.samples.entries()){Ne(r,h.name.slice(0,20),20),Ne(i,h.name.slice(20),20);let C=e[I];ge(r,C),i.currentIndex+=4;let B=A[I];ge(r,B),i.currentIndex+=4;let g=h.loopStart+C,E=h.loopEnd+C;h.isCompressed&&(g-=C,E-=C),ge(r,g),ge(r,E),ge(r,h.sampleRate),r[r.currentIndex++]=h.originalKey,r[r.currentIndex++]=h.pitchCorrection,i.currentIndex+=14;let p=h.linkedSample?t.samples.indexOf(h.linkedSample):0;se(r,Math.max(0,p)&65535),se(i,Math.max(0,p)>>16),o=Math.max(o,p);let y=h.sampleType;h.isCompressed&&(y|=16),se(r,y),i.currentIndex+=2}return Ne(r,"EOS",46),Ne(i,"EOS",46),{pdta:x.write("shdr",r,s),xdta:x.write("shdr",i,s)}}function Gs(t,e,A,s=!1){let a=A?t.presets:t.instruments,n=A?"pgen":"igen",r=A?"pmod":"imod",i=A?"pbag":"ibag",o=A?"phdr":"inst",I=A?38:22,h=0,C=new Array,B=0,g=new Array,E=new Array,p=new Array,y=0,D=new Array,R=m=>{C.push(h);let J=m.getWriteGenerators(t);h+=J.length,E.push(...J),g.push(B);let O=m.modulators;B+=O.length,p.push(...O)};for(let m of a){D.push(y),R(m.globalZone);for(let J of m.zones)R(J);y+=m.zones.length+1}E.push(new Pe(0,0,!1)),p.push(new ye(0,0,0,0,0)),C.push(h),g.push(B),D.push(y);let S=new te(E.length*4);for(let m of E)m.write(S);let w=new te(p.length*10);for(let m of p)m.write(w);let F=g.length*4,H={pdta:new te(F),xdta:new te(F)};for(let[m,J]of g.entries()){let O=C[m];se(H.pdta,O&65535),se(H.pdta,J&65535),se(H.xdta,O>>16),se(H.xdta,J>>16)}let k=(a.length+1)*I,u={pdta:new te(k),xdta:new te(k)};for(let[m,J]of a.entries())J.write(u,D[m],s);return A?(Ne(u.pdta,"EOP",20),u.pdta.currentIndex+=4,se(u.pdta,y&65535),u.pdta.currentIndex+=12,Ne(u.xdta,"",20),u.xdta.currentIndex+=4,se(u.xdta,y>>16),u.xdta.currentIndex+=12):(Ne(u.pdta,"EOI",20),se(u.pdta,y&65535),Ne(u.xdta,"",20),se(u.xdta,y>>16)),{writeXdta:Math.max(h,B,y)>65535,gen:{pdta:x.write(n,S,e),xdta:x.write(r,new te(4),e)},mod:{pdta:x.write(r,w,e),xdta:x.write(r,new te(10),e)},bag:{pdta:x.write(i,H.pdta,e),xdta:x.write(i,H.xdta,e)},hdr:{pdta:x.write(o,u.pdta,e),xdta:x.write(o,u.xdta,e)}}}var un={writeDefaultModulators:!0,writeExtendedLimits:!0,software:"SpessaSynth"},mn={rf64:!0,software:"SpessaSynth"};function er(t,e){let A=$t(e,un);return pn(t,A.software,A.writeDefaultModulators,A.writeExtendedLimits,!1,!1)}function tr(t,e){return pn(t,$t(e,mn).software,!0,!0,!0,!0)}function pn(t,e,A,s,a,n){l.groupCollapsed("%cSaving soundbank...",d.info),l.group("%cWriting INFO...",d.info);let r=[],i=(S,w)=>{w&&r.push(...x.getParts(S,[et(w,!0,!0)],n))},o=t.soundBankInfo;{let S=new te(4);se(S,o.version.major),se(S,o.version.minor),r.push(x.write("ifil",S,n))}if(i("isng",o.soundEngine),i("INAM",o.name),i("irom",o.romInfo),o.romVersion){let S=new te(4);se(S,o.romVersion.major),se(S,o.romVersion.minor),r.push(x.write("iver",S,n))}if(i("ICRD",Es(o.creationDate)),i("IENG",o.engineer),i("IPRD",o.product),i("ICOP",o.copyright),i("ICMT",o?.subject?(o?.comment?o.comment+`\n`:"")+o.subject:o?.comment),i("ISFT",e),t.defaultModulators.some(S=>!dn.some(w=>we.isIdentical(w,S,!0)))&&A){let S=t.defaultModulators;l.info(`%cWriting %c${S.length}%c default modulators...`,d.info,d.recognized,d.info);let w=new te(10+S.length*10);for(let F of S)F.write(w);ls(w,0,10),r.push(...x.getParts("DMOD",[w],n))}l.groupEnd(),l.info("%cWriting SDTA...",d.info);let I=[],h=[],C=za(t,I,h,n);l.info("%cWriting PDTA...",d.info),l.info("%cWriting SHDR...",d.info);let B=ja(t,I,h,n);l.group("%cWriting instruments...",d.info);let g=Gs(t,n,!1);l.groupEnd(),l.group("%cWriting presets...",d.info);let E=Gs(t,n,!0,a);l.groupEnd();let p=[E.hdr,E.bag,E.mod,E.gen,g.hdr,g.bag,g.mod,g.gen,B],y=x.getParts("pdta",p.map(S=>S.pdta),n,!0);s&&(g.writeXdta||E.writeXdta||t.presets.some(S=>S.name.length>20)||t.instruments.some(S=>S.name.length>20)||t.samples.some(S=>S.name.length>20))&&(l.info("%cWriting the xdta chunk as writeExtendedLimits is enabled and at least one condition was met.",d.info,d.value),r.push(...x.getParts("xdta",p.map(S=>S.xdta),n,!0)));let D=x.getParts("INFO",r,n,!0);l.info("%cWriting the output file...",d.info);let R=x.writeParts(n?"RIFS":"RIFF",[et(a?"sfen":"sfbk"),...D,...C,...y],n);return l.info(`%cSaved successfully! Final file size: %c${R.length}`,d.info,d.recognized),l.groupEnd(),R.buffer}var Ot=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 l.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(de(t.data,4),...e);let A=[];for(;t.data.length>t.data.currentIndex;)A.push(x.read(t.data));return A}},Z={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},Ls={forward:0,loopAndRelease:1},IA=20,cA=16,xt=class Xt extends Ot{gain=0;unityNote=60;fineTune=0;loops=new Array;fulOptions=2;static copyFrom(e){let A=new Xt;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 Xt,s=X(e.data,4);if(s!==IA&&l.warn(`Wsmp cbSize mismatch: got ${s}, expected ${IA}.`),A.unityNote=X(e.data,2),A.fineTune=Cs(e.data[e.data.currentIndex++],e.data[e.data.currentIndex++]),A.gain=X(e.data,4)|0,A.fulOptions=X(e.data,4),X(e.data,4)!==0){let a=X(e.data,4);a!==cA&&l.warn(`CbSize for loop in wsmp mismatch. Expected ${cA}, got ${a}.`);let n=X(e.data,4),r=X(e.data,4),i=X(e.data,4);A.loops.push({loopStart:r,loopLength:i,loopType:n})}return A}static fromSFSample(e){let A=new Xt;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:Ls.forward}),A}static fromSFZone(e){let A=new Xt;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 a=e.sample.loopStart+e.getGenerator(c.startloopAddrsOffset,0)+e.getGenerator(c.startloopAddrsCoarseOffset,0)*32768,n=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:a,loopLength:n-a})}return A}toSFZone(e,A){let s=0,a=this.loops[0];a&&(s=a.loopType===Ls.loopAndRelease?3:1),s!==0&&e.setGenerator(c.sampleModes,s);let n=-(this.gain>>16)/.4;if(n!==0&&e.setGenerator(c.initialAttenuation,n),e.fineTuning=this.fineTune-A.pitchCorrection,this.unityNote!==A.originalKey&&e.setGenerator(c.overridingRootKey,this.unityNote),a){let r=a.loopStart-A.loopStart,i=a.loopStart+a.loopLength-A.loopEnd;if(r!==0){let o=r%32768;e.setGenerator(c.startloopAddrsOffset,o);let I=Math.trunc(r/32768);I!==0&&e.setGenerator(c.startloopAddrsCoarseOffset,I)}if(i!==0){let o=i%32768;e.setGenerator(c.endloopAddrsOffset,o);let I=Math.trunc(i/32768);I!==0&&e.setGenerator(c.endloopAddrsCoarseOffset,I)}}}write(){let e=new te(IA+this.loops.length*cA);ge(e,IA),se(e,this.unityNote),se(e,this.fineTune),ge(e,this.gain),ge(e,this.fulOptions),ge(e,this.loops.length);for(let A of this.loops)ge(e,cA),ge(e,A.loopType),ge(e,A.loopStart),ge(e,A.loopLength);return x.write("wsmp",e)}},KA={PCM:1,ALAW:6};function Ar(t,e){let A=Math.pow(2,e*8-1),s=Math.pow(2,e*8),a,n=!1;e===1?(a=255,n=!0):a=A;let r=t.length/e,i=new Float32Array(r);if(e===2){let o=new Int16Array(t.buffer),I=o.length;for(let h=0;h=A&&(I-=s),i[o]=I/a)}return i}function sr(t,e){let A=t.length/e,s=new Float32Array(A);for(let a=0;a>4,o=r&15;i>0&&(o+=16),o=(o<<4)+8,i>1&&(o=o<127?o:-o)/32768}return s}var nr=class extends vA{wFormatTag;bytesPerSample;rawData;constructor(t,e,A,s,a,n,r,i,o){super(t,e,A,s,ve.monoSample,a,n),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:l.warn(`Failed to decode sample. Unknown wFormatTag: ${this.wFormatTag}`),t=new Float32Array(this.rawData.length/this.bytesPerSample);break;case KA.PCM:t=Ar(this.rawData,this.bytesPerSample);break;case KA.ALAW:t=sr(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===KA.PCM&&this.bytesPerSample===2?this.rawData:this.encodeS16LE()}},Ps=class os extends Ot{waveSample=new xt;wFormatTag;bytesPerSample;sampleRate;dataChunk;name="Unnamed sample";constructor(e,A,s,a){super(),this.wFormatTag=e,this.bytesPerSample=A,this.sampleRate=s,this.dataChunk=a}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 a=X(s.data,2),n=X(s.data,2);if(n!==1)throw new Error(`Only mono samples are supported. Fmt reports ${n} channels.`);let r=X(s.data,4);X(s.data,4),X(s.data,2);let i=X(s.data,2)/8,o=A.find(B=>B.header==="data");if(!o)throw new Error("No data chunk in the WAVE chunk!");let I=new os(a,i,r,o),h=x.findListType(A,"INFO");if(h){let B=x.read(h.data);for(;B.header!=="INAM"&&h.data.currentIndexB.header==="wsmp");return C&&(I.waveSample=xt.read(C)),I}static fromSFSample(e){let A=e.getRawData(!1),s=new os(1,2,e.sampleRate,new x("data",A.length,new te(A.buffer)));return s.name=e.name,s.waveSample=xt.fromSFSample(e),s}toSFSample(e){let A=this.waveSample.unityNote,s=this.waveSample.fineTune,a=Math.trunc(s/100);A+=a,s-=a*100;let n=0,r=0,i=this.waveSample.loops?.[0];i&&(n=i.loopStart,r=i.loopStart+i.loopLength);let o=new nr(this.name,this.sampleRate,A,s,n,r,this.dataChunk,this.wFormatTag,this.bytesPerSample);e.addSamples(o)}write(){let e=this.writeFmt(),A=this.waveSample.write(),s=x.getParts("data",[this.dataChunk.data]),a=x.write("INAM",et(this.name,!0)),n=x.write("INFO",a,!1,!0);return l.info(`%cSaved %c${this.name}%c successfully!`,d.recognized,d.value,d.recognized),x.getParts("wave",[e,A,...s,n],!1,!0)}writeFmt(){let e=new te(18);return se(e,this.wFormatTag),se(e,1),ge(e,this.sampleRate),ge(e,this.sampleRate*2),se(e,2),se(e,this.bytesPerSample*8),x.write("fmt ",e)}},nt=class gs{source;transform;bipolar;invert;constructor(e=Z.none,A=Ce.linear,s=!1,a=!1){this.source=e,this.transform=A,this.bipolar=s,this.invert=a}get sourceName(){return Object.keys(Z).find(e=>Z[e]===this.source)??this.source.toString()}get transformName(){return Object.keys(Ce).find(e=>Ce[e]===this.transform)??this.transform.toString()}static copyFrom(e){return new gs(e.source,e.transform,e.bipolar,e.invert)}static fromSFSource(e){let A;if(e.isCC)switch(e.index){case f.modulationWheel:A=Z.modulationWheel;break;case f.mainVolume:A=Z.volume;break;case f.pan:A=Z.pan;break;case f.expression:A=Z.expression;break;case f.chorusDepth:A=Z.chorus;break;case f.reverbDepth:A=Z.reverb;break}else switch(e.index){case Ie.noController:A=Z.none;break;case Ie.noteOnKeyNum:A=Z.keyNum;break;case Ie.noteOnVelocity:A=Z.velocity;break;case Ie.pitchWheel:A=Z.pitchWheel;break;case Ie.pitchWheelRange:A=Z.pitchWheelRange;break;case Ie.polyPressure:A=Z.polyPressure;break;case Ie.channelPressure:A=Z.channelPressure}if(A!==void 0)return new gs(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 Z.modLfo:case Z.vibratoLfo:case Z.coarseTune:case Z.fineTune:case Z.modEnv:return;case Z.keyNum:e=Ie.noteOnKeyNum;break;case Z.none:e=Ie.noController;break;case Z.modulationWheel:e=f.modulationWheel,A=!0;break;case Z.pan:e=f.pan,A=!0;break;case Z.reverb:e=f.reverbDepth,A=!0;break;case Z.chorus:e=f.chorusDepth,A=!0;break;case Z.expression:e=f.expression,A=!0;break;case Z.volume:e=f.mainVolume,A=!0;break;case Z.velocity:e=Ie.noteOnVelocity;break;case Z.polyPressure:e=Ie.polyPressure;break;case Z.channelPressure:e=Ie.channelPressure;break;case Z.pitchWheel:e=Ie.pitchWheel;break;case Z.pitchWheelRange:e=Ie.pitchWheelRange;break}if(e!==void 0)return new at(e,this.transform,A,this.bipolar,this.invert)}},yn=new ye(219,0,c.reverbEffectsSend,1e3,0),Sn=new ye(221,0,c.chorusEffectsSend,1e3,0);new ye(129,0,c.vibLfoToPitch,0,0);new ye(13,0,c.vibLfoToPitch,0,0);var ar=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]),Jt=class pt{source;control;destination;scale;transform;constructor(e=new nt,A=new nt,s,a,n){this.source=e,this.control=A,this.destination=s,this.transform=a,this.scale=n}get isStaticParameter(){return this.source.source===Z.none&&this.control.source===Z.none}get shortScale(){return this.scale>>16}get transformName(){return Object.keys(Ce).find(e=>Ce[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=X(e,2),s=X(e,2),a=X(e,2),n=X(e,2),r=X(e,4)|0,i=n&15,o=new nt(s,n>>4&15,St(n,8),St(n,9));return new pt(new nt(A,n>>10&15,St(n,14),St(n,15)),o,a,i,r)}static fromSFModulator(e,A){let s=h=>{l.warn(`Failed converting SF modulator into DLS:\n ${e.toString()} \n(${h})`)};if(e.transformType!==0){s("Absolute transform type is not supported");return}if(we.isIdentical(e,Sn,!0)||we.isIdentical(e,yn,!0))return;let a=nt.fromSFSource(e.primarySource);if(!a){s("Invalid primary source");return}let n=nt.fromSFSource(e.secondarySource);if(!n){s("Invalid secondary source");return}let r=pt.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!==Z.none){if(n.source!==Z.none&&a.source!==Z.none){s("Articulation generators with secondary source are not supported");return}a.source!==Z.none&&(n=a),a=new nt(r.source,Ce.linear,r.isBipolar)}let I=new pt(a,n,o,0,i<<16);A.connectionBlocks.push(I)}static copyFrom(e){return new pt(nt.copyFrom(e.source),nt.copyFrom(e.control),e.destination,e.transform,e.scale)}static fromSFGenerator(e,A){if(ar.has(e.type))return;let s=o=>{l.warn(`Failed converting SF2 generator into DLS:\n ${e.toString()} \n(${o})`)},a=pt.fromSFDestination(e.type,e.value);if(a===void 0){s("Invalid type");return}let n=new nt,r,i=e.value;typeof a=="number"?r=a:(r=a.destination,i=a.amount,n.source=a.source,n.bipolar=a.isBipolar),A.connectionBlocks.push(new pt(n,new nt,r,0,i<<16))}static fromSFDestination(e,A){switch(e){default:return;case c.initialAttenuation:return{destination:N.gain,amount:-A,isBipolar:!1,source:Z.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:Z.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:Z.none};case c.releaseModEnv:return N.modEnvRelease;case c.initialFilterFc:return N.filterCutoff;case c.initialFilterQ:return N.filterQ;case c.modEnvToFilterFc:return{source:Z.modEnv,destination:N.filterCutoff,amount:A,isBipolar:!1};case c.modEnvToPitch:return{source:Z.modEnv,destination:N.pitch,amount:A,isBipolar:!1};case c.modLfoToFilterFc:return{source:Z.modLfo,destination:N.filterCutoff,amount:A,isBipolar:!0};case c.modLfoToVolume:return{source:Z.modLfo,destination:N.gain,amount:A,isBipolar:!0};case c.modLfoToPitch:return{source:Z.modLfo,destination:N.pitch,amount:A,isBipolar:!0};case c.vibLfoToPitch:return{source:Z.vibratoLfo,destination:N.pitch,amount:A,isBipolar:!0};case c.keyNumToVolEnvHold:return{source:Z.keyNum,destination:N.volEnvHold,amount:A,isBipolar:!0};case c.keyNumToVolEnvDecay:return{source:Z.keyNum,destination:N.volEnvDecay,amount:A,isBipolar:!0};case c.keyNumToModEnvHold:return{source:Z.keyNum,destination:N.modEnvHold,amount:A,isBipolar:!0};case c.keyNumToModEnvDecay:return{source:Z.keyNum,destination:N.modEnvDecay,amount:A,isBipolar:!0};case c.scaleTuning:return{source:Z.keyNum,destination:N.pitch,amount:A*128,isBipolar:!1}}}toString(){return`Source: ${this.source.toString()},\nControl: ${this.control.toString()},\nScale: ${this.scale} >> 16 = ${this.shortScale},\nOutput transform: ${this.transformName}\nDestination: ${this.destinationName}`}write(){let e=new te(12);return se(e,this.source.source),se(e,this.control.source),se(e,this.destination),se(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:l.info(`%cFailed converting DLS articulator into SF generator: %c${this.toString()}%c\n(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,a,n=new at,r=this.toCombinedSFDestination();if(r){s=r;let o=this.control.toSFSource();if(!o){this.failedConversion("Invalid control");return}a=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 I=this.source.toSFSource();if(!I){this.failedConversion("Invalid source");return}a=I;let h=this.control.toSFSource();if(!h){this.failedConversion("Invalid control");return}n=h}this.transform!==Ce.linear&&a.curveType===Ce.linear&&(a.curveType=this.transform),s===c.initialAttenuation&&((this.source.source===Z.velocity||this.source.source===Z.volume||this.source.source===Z.expression)&&(a.isNegative=!0),A=Math.min(960,Math.max(0,A)));let i=new we(a,n,s,A,0);e.addModulators(i)}toCombinedSFDestination(){let e=this.source.source,A=this.destination;return e===Z.vibratoLfo&&A===N.pitch?c.vibLfoToPitch:e===Z.modLfo&&A===N.pitch?c.modLfoToPitch:e===Z.modLfo&&A===N.filterCutoff?c.modLfoToFilterFc:e===Z.modLfo&&A===N.gain?c.modLfoToVolume:e===Z.modEnv&&A===N.filterCutoff?c.modEnvToFilterFc:e===Z.modEnv&&A===N.pitch?c.modEnvToPitch:void 0}failedConversion(e){l.info(`%cFailed converting DLS articulator into SF2:\n %c${this.toString()}%c\n(${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}}},kn=class extends Ot{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(Jt.copyFrom(e))}fromSFZone(t){this.mode="dls2";let e=new jt;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 a=e.getGenerator(s,void 0),n=A.value*-128;if(a===void 0)continue;let r=a-60/128*n;e.setGenerator(A.type,n,!1),e.setGenerator(s,r,!1)}for(let A of e.generators)Jt.fromSFGenerator(A,this);for(let A of e.modulators)Jt.fromSFModulator(A,this)}read(t){let e=x.findListType(t,"lart"),A=x.findListType(t,"lar2");if(e)for(this.mode="dls1";e.data.currentIndexs.write()),A=x.getParts(this.mode==="dls2"?"art2":"art1",[t,...e]);return x.getParts(this.mode==="dls2"?"lar2":"lart",A,!0)}toSFZone(t){let e=(A,s,a,n)=>{let r=A/-128;if(t.setGenerator(s,r),r<=120){let i=Math.round(.46875*A),o=this.connectionBlocks.find(I=>I.isStaticParameter&&I.destination===n);o&&t.setGenerator(a,i+o.shortScale)}};for(let A of this.connectionBlocks){let s=A.shortScale,a=A.source.source,n=A.control.source,r=A.destination;if(A.isStaticParameter){A.toSFGenerator(t);continue}if(n===Z.none)if(a===Z.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!==Z.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)}}},VA=class BA{channel=1;tableIndex;fusOptions=0;phaseGroup=0;constructor(e){this.tableIndex=e}static copyFrom(e){let A=new BA(e.tableIndex);return A.channel=e.channel,A.phaseGroup=e.phaseGroup,A.fusOptions=e.fusOptions,A}static read(e){let A=X(e.data,2),s=X(e.data,2),a=X(e.data,4),n=new BA(X(e.data,4));return n.channel=a,n.fusOptions=A,n.phaseGroup=s,n}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 a=new BA(s);switch(A.sample.sampleType){default:case ve.leftSample:case ve.monoSample:a.channel=Math.trunc(1);break;case ve.rightSample:a.channel=2}return a}write(){let e=new te(12);return se(e,this.fusOptions),se(e,this.phaseGroup),ge(e,this.channel),ge(e,this.tableIndex),x.write("wlnk",e)}},EA=class Pt extends Ot{articulation=new kn;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 Pt(VA.copyFrom(e.waveLink),xt.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"),a=s.find(p=>p.header==="wsmp"),n=a?xt.read(a):void 0,r=s.find(p=>p.header==="wlnk");if(!r){l.warn("Invalid DLS region: missing \'wlnk\' chunk! Discarding...");return}let i=VA.read(r),o=s.find(p=>p.header==="rgnh");if(!o){l.warn("Invalid DLS region: missing \'rgnh\' chunk! Discarding...");return}let I=e[i.tableIndex];I||Pt.parsingError(`Invalid sample index: ${i.tableIndex}. Samples available: ${e.length}`),n??=I.waveSample;let h=new Pt(i,n),C=X(o.data,2),B=X(o.data,2),g=X(o.data,2),E=X(o.data,2);return g===0&&E===0&&(E=127,g=0),h.keyRange.max=B,h.keyRange.min=C,h.velRange.max=E,h.velRange.min=g,h.fusOptions=X(o.data,2),h.keyGroup=X(o.data,2),o.data.length-o.data.currentIndex>=2&&(h.usLayer=X(o.data,2)),h.articulation.read(s),h}static fromSFZone(e,A){let s=xt.fromSFZone(e),a=new Pt(VA.fromSFZone(A,e),s);return a.keyRange.min=Math.max(e.keyRange.min,0),a.keyRange.max=e.keyRange.max,a.velRange.min=Math.max(e.velRange.min,0),a.velRange.max=e.velRange.max,a.keyGroup=e.getGenerator(c.exclusiveClass,0),a.articulation.fromSFZone(e),a}write(){let e=[this.writeHeader(),this.waveSample.write(),this.waveLink.write(),...this.articulation.write()];return x.getParts("rgn2",e,!1,!0)}toSFZone(e,A){let s=A[this.waveLink.tableIndex];s||Pt.parsingError(`Invalid sample index: ${this.waveLink.tableIndex}`);let a=e.createZone(s);return a.keyRange=this.keyRange,a.velRange=this.velRange,this.keyRange.max===127&&this.keyRange.min===0&&(a.keyRange.min=-1),this.velRange.max===127&&this.velRange.min===0&&(a.velRange.min=-1),this.keyGroup!==0&&a.setGenerator(c.exclusiveClass,this.keyGroup),this.waveSample.toSFZone(a,s),this.articulation.toSFZone(a),a.generators=a.generators.filter(n=>n.value!==ze[n.type].def),a}writeHeader(){let e=new te(14);return se(e,Math.max(this.keyRange.min,0)),se(e,this.keyRange.max),se(e,Math.max(this.velRange.min,0)),se(e,this.velRange.max),se(e,this.fusOptions),se(e,this.keyGroup),se(e,this.usLayer),x.write("rgnh",e)}},XA=class dA extends Ot{articulation=new kn;regions=new Array;name="Unnamed";bankLSB=0;bankMSB=0;isGMGSDrum=!1;program=0;static copyFrom(e){let A=new dA;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(EA.copyFrom(s));return A}static read(e,A){let s=this.verifyAndReadList(A,"ins "),a=s.find(C=>C.header==="insh");if(!a)throw l.groupEnd(),new Error("No instrument header!");let n="",r=x.findListType(s,"INFO");if(r){let C=x.read(r.data);for(;C.header!=="INAM";)C=x.read(r.data);n=de(C.data,C.data.length).trim()}n.length===0&&(n="Unnamed Instrument");let i=new dA;i.name=n;let o=X(a.data,4),I=X(a.data,4);i.program=X(a.data,4)&127,i.bankMSB=I>>>8&127,i.bankLSB=I&127,i.isGMGSDrum=I>>>31>0,l.groupCollapsed(`%cParsing %c"${n}"%c...`,d.info,d.recognized,d.info);let h=x.findListType(s,"lrgn");if(!h)throw l.groupEnd(),new Error("No region list!");i.articulation.read(s);for(let C=0;Ca.write());e.push(...x.getParts("lrgn",A,!1,!0)),this.articulation.length>0&&e.push(...this.articulation.write());let s=x.write("INAM",et(this.name,!0));return e.push(x.write("INFO",s,!1,!0)),l.groupEnd(),x.writeParts("ins ",e,!1,!0)}toSFPreset(e){let A=new zt(e);A.name=this.name,A.bankMSB=this.bankMSB,A.bankLSB=this.bankLSB,A.isGMGSDrum=this.isGMGSDrum,A.program=this.program;let s=new _t;s.name=this.name,A.createZone(s),this.articulation.toSFZone(s.globalZone);for(let a of this.regions)a.toSFZone(s,e.samples);s.globalize(),s.globalZone.modulators.some(a=>a.destination===c.reverbEffectsSend)||s.globalZone.addModulators(we.copyFrom(yn)),s.globalZone.modulators.some(a=>a.destination===c.chorusEffectsSend)||s.globalZone.addModulators(we.copyFrom(Sn)),s.globalZone.generators=s.globalZone.generators.filter(a=>a.value!==ze[a.type].def),e.addPresets(A),e.addInstruments(s)}writeHeader(){let e=new te(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),x.write("insh",e)}},Is={software:"SpessaSynth"},Dn=class cs extends Ot{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 te(e);l.group("%cParsing DLS file...",d.info);let s=x.read(A,!1,!1);this.verifyHeader(s,"RIFF"),this.verifyText(de(A,4).toLowerCase(),"dls ");let a=[];for(;A.currentIndexE.header==="colh");if(!i)return this.parsingError("No colh chunk!"),5;let o=X(i.data,4);l.info(`%cInstruments amount: %c${o}`,d.info,d.recognized);let I=x.findListType(a,"wvpl");if(!I)return this.parsingError("No wvpl chunk!"),5;let h=this.verifyAndReadList(I,"wvpl");for(let E of h)n.samples.push(Ps.read(E));let C=x.findListType(a,"lins");if(!C)return this.parsingError("No lins chunk!"),5;let B=this.verifyAndReadList(C,"lins");l.groupCollapsed("%cLoading instruments...",d.info),B.length!==o&&l.warn(`Colh reported invalid amount of instruments. Detected ${B.length}, expected ${o}`);for(let E of B)n.instruments.push(XA.read(n.samples,E));l.groupEnd();let g=a.find(E=>E.header==="pgal");if(g){l.info("%cFound the instrument aliasing chunk!",d.recognized);let E=g.data;(E[0]!==0||E[1]!==1||E[2]!==2||E[3]!==3)&&(E.currentIndex+=4);let p=n.instruments.find(D=>De.isXGDrum(D.bankMSB)||D.isGMGSDrum);if(!p)return l.warn("MobileBAE aliasing chunk without a drum preset. Aborting!"),n;let y=E.slice(E.currentIndex,E.currentIndex+128);E.currentIndex+=128;for(let D=0;D<128;D++){let R=y[D];if(R===D)continue;let S=p.regions.find(F=>F.keyRange.max===R&&F.keyRange.min===R);if(!S){l.warn(`Invalid drum alias ${D} to ${R}: region does not exist.`);continue}let w=EA.copyFrom(S);w.keyRange.max=D,w.keyRange.min=D,p.regions.push(w)}for(E.currentIndex+=4;E.currentIndex>7&127,w=E[E.currentIndex++],F=E[E.currentIndex++];F!==0&&l.warn(`Invalid alias byte. Expected 0, got ${F}`);let H=X(E,2),k=H&127,u=H>>7&127,m=E[E.currentIndex++];F=E[E.currentIndex++],F!==0&&l.warn(`Invalid alias header. Expected 0, got ${F}`);let J=n.instruments.find(q=>q.bankLSB===k&&q.bankMSB===u&&q.program===m&&!q.isGMGSDrum);if(!J){l.warn(`Invalid alias. Missing instrument: ${k}:${u}:${m}`);continue}let O=XA.copyFrom(J);O.bankMSB=S,O.bankLSB=R,O.program=w,n.instruments.push(O)}}return l.info(`%cParsing finished! %c"${n.soundBankInfo.name||"UNNAMED"}"%c has %c${n.instruments.length}%c instruments and %c${n.samples.length}%c samples.`,d.info,d.recognized,d.info,d.recognized,d.info,d.recognized,d.info),l.groupEnd(),n}static fromSF(e,A){l.groupCollapsed("%cSaving SF2 to DLS level 2...",d.info);let s=new cs;s.soundBankInfo={...e.soundBankInfo};for(let a=0;aD.write()),!1,!0);l.info("%cSuccess!",d.recognized),l.groupEnd(),l.groupCollapsed("%cWriting WAVE samples...",d.info);let r=0,i=[],o=[],I=0;for(let D of this.samples){let R=D.write();A.progressFunction?.(I/this.samples.length),l.info(`%cWrote sample %c${I}. ${D.name}%c of %c${this.samples.length}.`,d.info,d.recognized,d.info,d.recognized),i.push(r),r+=R.reduce((S,w)=>S+w.length,0),o.push(...R),I++}let h=x.getParts("wvpl",o,!1,!0);l.info("%cSucceeded!",d.recognized);let C=new te(8+4*i.length);ge(C,8),ge(C,i.length);for(let D of i)ge(C,D);let B=x.write("ptbl",C);this.soundBankInfo.software=A.software;let g=[],E=this.soundBankInfo,p=(D,R)=>{R&&g.push(...x.getParts(D,[et(R,!0)]))};p("INAM",E.name),p("ICMT",E.comment),p("ICOP",E.copyright),p("ICRD",Es(E.creationDate)),p("IENG",E.engineer),p("IPRD",E.product),p("ISFT",A.software),p("ISBJ",E.subject),l.info("%cCombining everything...");let y=x.writeParts("RIFF",[et("DLS "),a,...n,B,...h,...x.getParts("INFO",g,!1,!0)]);return l.info("%cSaved successfully!",d.recognized),l.groupEnd(),y.buffer}toSF(){l.group("%cConverting DLS to SF2...",d.info);let e=new wn("dls");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(),l.info("%cConversion complete!",d.recognized),l.groupEnd(),e}},wn=class fA{static isSF3DecoderReady=FA.isInitialized;type;soundBankInfo={name:"Unnamed",creationDate:new Date,software:"SpessaSynth",soundEngine:"E-mu 10K2",version:{major:2,minor:4}};presets=[];samples=[];instruments=[];defaultModulators=dn.map(we.copyFrom.bind(we));customDefaultModulators=!1;constructor(e="sf2"){this.type=e}_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 n=e?.shift()?.presets;if(n)for(let r of n)s.some(i=>r.matches(i))||s.push(r)}let a=new fA;return a.addCompletePresets(s),a.soundBankInfo={...A.soundBankInfo},a}static getSampleSoundBankFile(){let e=new fA,A=new Float32Array(128);for(let r=0;r<128;r++)A[r]=r/128*2-1;let s=new Za;s.name="Saw",s.originalKey=65,s.pitchCorrection=20,s.loopEnd=128,s.setAudioData(A,44100),e.addSamples(s);let a=new _t;a.name="Saw Wave",a.globalZone.addGenerators(new Pe(c.initialAttenuation,375),new Pe(c.releaseVolEnv,-1e3),new Pe(c.sampleModes,1)),a.createZone(s),a.createZone(s).setGenerator(c.fineTune,-9),e.addInstruments(a);let n=new zt(e);return n.name="Saw Wave",n.createZone(a),e.addPresets(n),e.soundBankInfo.name="SpessaSynth Sample Sound Bank",e.flush(),e.writeSF2()}static copyFrom(e){let A=new fA;for(let s of e.presets)A.clonePreset(s);return A.soundBankInfo={...e.soundBankInfo},A}addCompletePresets(e){this.addPresets(...e);let A=[];for(let a of e)for(let n of a.zones)n.instrument&&!A.includes(n.instrument)&&A.push(n.instrument);this.addInstruments(...A);let s=[];for(let a of A)for(let n of a.zones)n.sample&&!s.includes(n.sample)&&s.push(n.sample);this.addSamples(...s)}async setSampleFormat(e){let A=0,s=e.format,a=e.progressFunction;for(let n of this.samples){switch(s){default:case"pcm":n.setAudioData(n.getAudioData(),n.sampleRate);break;case"compressed":{let r=e.compressionFunction;if(!r)throw new Error(`No compression function supplied but \'${s}\' was requested.`);await n.compressSample(r)}}A++,a?.(A/this.samples.length),l.info(`%cEncoded sample %c${A}. ${n.name}%c of %c${this.samples.length}%c. Compressed: %c${n.isCompressed}%c.`,d.info,d.recognized,d.info,d.recognized,d.info,n.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=Is){let A=e.progressFunction;return Dn.fromSF(this,A?s=>A(s/2):void 0).write({...e,progressFunction:A?s=>A(.5+s/2):void 0})}writeSF2(e=un){return er(this,e)}writeSFE(e=mn){return tr(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(a=>a.name===e.name);if(A)return A;let s=new vA(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 a=this.cloneSample(e.linkedSample);a.linkedSample||s.setLinkedSample(a,s.sampleType)}return s}cloneInstrument(e){let A=this.instruments.find(a=>a.name===e.name);if(A)return A;let s=new _t;s.name=e.name,s.globalZone.copyFrom(e.globalZone);for(let a of e.zones)s.createZone(this.cloneSample(a.sample)).copyFrom(a);return this.addInstruments(s),s}clonePreset(e){let A=this.presets.find(a=>a.name===e.name);if(A)return A;let s=new zt(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 a of e.zones)s.createZone(this.cloneInstrument(a.instrument)).copyFrom(a);return this.addPresets(s),s}flush(){this.presets.sort(je.compare.bind(je)),this.parseInternal()}trim(e){let A=(s,a)=>{let n=0;for(let r=0;r=o.min&&C<=o.max&&[...B].some(g=>g>=I.min&&g<=I.max)){h=!0;break}h||(l.info(`%c${i.sample.name}%c removed from %c${s.name}%c.`,d.recognized,d.info,d.recognized,d.info),s.deleteZone(r)&&(n++,r--,l.info(`%c${i.sample.name}%c deleted`,d.recognized,d.info)),i.sample.useCount<1&&this.deleteSample(i.sample))}return n};l.groupCollapsed("%cTrimming sound bank...",d.info),l.info("Combinations to trim for:",e);for(let s=0;s=I.min&&B<=I.max&&[...g].some(E=>E>=h.min&&E<=h.max)){C=!0;let E=A(o.instrument,n);l.info(`%cTrimmed off %c${E}%c instrument zones from %c${o.instrument.name}`,d.info,d.recognized,d.info,d.recognized);break}C||(r++,a.deleteZone(i),o.instrument.useCount<1&&this.deleteInstrument(o.instrument),i--)}l.info(`%cTrimmed off %c${r}%c preset zones from %c${a.name}`,d.info,d.recognized,d.info,d.recognized),l.groupEnd()}}this.removeUnusedElements(),l.info("%cSound bank modified!",d.recognized),l.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 je.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(De.isXGDrum(A.bankMSB)&&(this._isXGBank=!0,!e.has(A.program))){this._isXGBank=!1,l.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;l.info(`%c${e}: %c"${s.major}.${s.minor}"`,d.info,d.recognized)}else l.info(`%c${e}: %c${A.toLocaleString()}`,d.info,d.recognized)}},rr=class extends Pe{constructor(t){let e=t.currentIndex,A=t[e+1]<<8|t[e],s=Cs(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 rr(t.data));return e.pop(),e}function ir(t,e,A,s,a){let n=t.gen,r=t.mod,i=0,o=0;for(let I of a)for(let h=0;hD.type===c.instrument)?I.createSoundFontZone(y,g,s):(I.globalZone.addGenerators(...g),I.globalZone.addModulators(...y))}}var or=class extends zt{zoneStartIndex;zonesCount=0;constructor(t,e){super(e),this.name=de(t.data,20),this.program=X(t.data,2);let A=X(t.data,2);this.bankMSB=A&127,this.isGMGSDrum=(A&128)>0,this.bankLSB=A>>8,this.zoneStartIndex=X(t.data,2),this.library=X(t.data,4),this.genre=X(t.data,4),this.morphology=X(t.data,4)}createSoundFontZone(t,e,A){let s=e.find(r=>r.type===c.instrument),a;if(s)a=A[s.value];else throw new Error("No instrument ID found in preset zone.");if(!a)throw new Error(`Invalid instrument ID: ${s.value}, available instruments: ${A.length}`);let n=new Qn(this,a);return n.addGenerators(...e),n.addModulators(...t),this.zones.push(n),n}};function Ts(t,e){let A=[];for(;t.data.length>t.data.currentIndex;){let s=new or(t,e);if(A.length>0){let a=A[A.length-1];a.zonesCount=s.zoneStartIndex-a.zoneStartIndex}A.push(s)}return A.pop(),A}var gr=class extends _t{zoneStartIndex;zonesCount=0;constructor(t){super(),this.name=de(t.data,20),this.zoneStartIndex=X(t.data,2)}createSoundFontZone(t,e,A){let s=e.find(r=>r.type===c.sampleID),a;if(s)a=A[s.value];else throw new Error("No sample ID found in instrument zone.");if(!a)throw new Error(`Invalid sample ID: ${s.value}, available samples: ${A.length}`);let n=new fn(this,a);return n.addGenerators(...e),n.addModulators(...t),this.zones.push(n),n}};function Us(t){let e=[];for(;t.data.length>t.data.currentIndex;){let A=new gr(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 ZA(t){let e=[];for(;t.data.length>t.data.currentIndex;){let A=t.data,s=X(A,2),a=X(A,2),n=Cs(A[A.currentIndex++],A[A.currentIndex++]),r=X(A,2),i=X(A,2);e.push(new ye(s,r,a,n,i))}return e.pop(),e}function Ir(t,e,A,s,a){let n=t.gen,r=t.mod,i=0,o=0;for(let I of a)for(let h=0;hD.type===c.sampleID)?I.createSoundFontZone(y,g,s):(I.globalZone.addGenerators(...g),I.globalZone.addModulators(...y))}}function hA(t){let e=[],A=[];for(;t.data.length>t.data.currentIndex;)A.push(X(t.data,2)),e.push(X(t.data,2));return{mod:e,gen:A}}var cr=class extends wn{sampleDataStartIndex=0;constructor(t,e){super(e?"sfe":"sf2");let A=new te(t);l.group("%cParsing a SoundFont2 file...",d.info);let s=We(A,4).toLowerCase();this.verifyTexts(s,["riff","rifs"]);let a=s==="rifs";a&&l.info("%cRIFF64 Detected!",d.recognized),x.read(A,a,!1);let n=de(A,4).toLowerCase();this.verifyTexts(n,["sfbk","sfpk","sfen"]);let r=n==="sfpk",i=x.read(A,a);this.verifyHeader(i,"list");let o=de(i.data,4);this.verifyText(o,"info");let I;for(;i.data.length>i.data.currentIndex;){let Q=x.read(i.data,a),b=We(Q.data,Q.data.length),L=Q.header;switch(L){case"ifil":case"iver":{let z=X(Q.data,2),$=X(Q.data,2);L==="ifil"?this.soundBankInfo.version={major:z,minor:$}:this.soundBankInfo.romVersion={major:z,minor:$};break}case"DMOD":this.defaultModulators=ZA(Q),this.customDefaultModulators=!0;break;case"LIST":de(Q.data,4)==="xdta"&&(l.info("%cExtended SF2 found!",d.recognized),I=Q);break;case"ICRD":this.soundBankInfo.creationDate=ds(de(Q.data,Q.data.length));break;case"ISFT":this.soundBankInfo.software=b;break;case"IPRD":this.soundBankInfo.product=b;break;case"IENG":this.soundBankInfo.engineer=b;break;case"ICOP":this.soundBankInfo.copyright=b;break;case"INAM":this.soundBankInfo.name=b;break;case"ICMT":this.soundBankInfo.comment=b;break;case"irom":this.soundBankInfo.romInfo=b;break;case"isng":this.soundBankInfo.soundEngine=b}}this.printInfo();let h={};I!==void 0&&(h.phdr=x.read(I.data,a),h.pbag=x.read(I.data,a),h.pmod=x.read(I.data,a),h.pgen=x.read(I.data,a),h.inst=x.read(I.data,a),h.ibag=x.read(I.data,a),h.imod=x.read(I.data,a),h.igen=x.read(I.data,a),h.shdr=x.read(I.data,a));let C=x.read(A,a,!1);this.verifyHeader(C,"list"),this.verifyText(de(A,4),"sdta"),l.info("%cVerifying smpl chunk...",d.warn);let B=x.read(A,a,!1);this.verifyHeader(B,"smpl");let g;if(r){l.info("%cSF2Pack detected, attempting to decode the smpl chunk...",d.info);try{g=FA.decode(A.buffer.slice(A.currentIndex,A.currentIndex+C.size-4-C.headerSize)).data[0]}catch(Q){throw l.groupEnd(),new Error(`SF2Pack Ogg Vorbis decode error: ${Q}`,{cause:Q})}l.info(`%cDecoded the smpl chunk! Length: %c${g.length}`,d.info,d.value)}else g=A,this.sampleDataStartIndex=A.currentIndex;l.info(`%cSkipping sample chunk, length: %c${C.size-4-C.headerSize}`,d.info,d.value),A.currentIndex+=C.size-4-C.headerSize,l.info("%cLoading preset data chunk...",d.warn);let E=x.read(A,a);this.verifyHeader(E,"list"),de(E.data,4);let p=x.read(E.data,a);this.verifyHeader(p,"phdr");let y=x.read(E.data,a);this.verifyHeader(y,"pbag");let D=x.read(E.data,a);this.verifyHeader(D,"pmod");let R=x.read(E.data,a);this.verifyHeader(R,"pgen");let S=x.read(E.data,a);this.verifyHeader(S,"inst");let w=x.read(E.data,a);this.verifyHeader(w,"ibag");let F=x.read(E.data,a);this.verifyHeader(F,"imod");let H=x.read(E.data,a);this.verifyHeader(H,"igen");let k=x.read(E.data,a);this.verifyHeader(k,"shdr"),l.info("%cParsing samples...",d.info),A.currentIndex=this.sampleDataStartIndex;let u=vs(k,g,I===void 0);if(I&&h.shdr){let Q=vs(h.shdr,new Float32Array(1),!1);if(Q.length===u.length)for(let[b,L]of u.entries())L.name+=Q[b].name,L.linkedSampleIndex|=Q[b].linkedSampleIndex<<16}for(let Q of u)Q.name=Q.name.trim();this.samples.push(...u);let m=Ns(H),J=ZA(F),O=Us(S);if(I&&h.inst){let Q=Us(h.inst);if(Q.length===O.length){for(let[b,L]of O.entries())L.name+=Q[b].name,L.zoneStartIndex|=Q[b].zoneStartIndex<<16;for(let[b,L]of O.entries())b`"${A}"`).join(", ")} but got "${t.toLowerCase()}"`))}},eA=class{static fromArrayBuffer(t){let e=de(new te(t.slice(0,4)),4);if(e!=="RIFF"&&e!=="RIFS")throw new Error(`Expected \'RIFF\' or \'RIFS\' header, got \'${e}\'`);let A=de(new te(e==="RIFS"?t.slice(12,16):t.slice(8,12)),4).toLowerCase();return A==="dls "?this.loadDLS(t):new cr(t,A==="sfen")}static loadDLS(t){return Dn.read(t).toSF()}},wA=class Mn extends we{isEffectModulator;isDefaultResonantModulator;isModWheelModulator;constructor(e,A,s,a,n,r,i,o){super(e,A,s,a,n),this.isEffectModulator=r,this.isDefaultResonantModulator=i,this.isModWheelModulator=o}static fromData(e,A,s,a,n){let r=e.toSourceEnum(),i=A.toSourceEnum();return new Mn(e,A,s,a,n,(r===219||r===221)&&i===0&&(s===c.reverbEffectsSend||s===c.chorusEffectsSend),r===En&&i===0&&s===c.initialFilterQ,(e.isCC&&e.index===f.modulationWheel||A.isCC&&A.index===f.modulationWheel)&&(s===c.modLfoToPitch||s===c.vibLfoToPitch))}static fromModulator(e){return this.fromData(e.primarySource,e.secondarySource,e.destination,e.transformAmount,e.transformType)}},hr=class{sampleData;generators;modulators;exclusiveClass;targetKey;velocity;rootKey;loopStart;loopEnd;playbackStep;loopingMode;constructor(t,e,A,s){let a=t.sample,n=t.generators;this.modulators=t.modulators.map(wA.fromModulator.bind(wA)),this.generators=n,this.rootKey=a.originalKey,n[c.overridingRootKey]>-1&&(this.rootKey=n[c.overridingRootKey]),this.targetKey=e,n[c.keyNum]>-1&&(this.targetKey=n[c.keyNum]),this.velocity=A,n[c.velocity]>-1&&(this.velocity=n[c.velocity]),this.exclusiveClass=n[c.exclusiveClass],this.loopStart=a.loopStart,this.loopEnd=a.loopEnd,this.sampleData=a.getAudioData(),this.playbackStep=a.sampleRate/s*Math.pow(2,a.pitchCorrection/1200),this.loopingMode=n[c.sampleModes]}},xs=Math.PI/2,QA=-500,bn=500,ms=bn-QA,Rn=new Float32Array(ms+1),Fn=new Float32Array(ms+1);for(let t=QA;t<=bn;t++){let e=(t-QA)/ms,A=t-QA;Rn[A]=Math.cos(xs*e),Fn[A]=Math.sin(xs*e)}function lr(t,e,A,s,a,n){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,I=t.targetKey,h=t.pitchOffset+o[c.fineTune]+this.octaveTuning[I]+this.currentTuning,C=o[c.coarseTune],B=r.tunings[this.preset.program*128+t.midiNote];if(B!==-1&&(I=Math.trunc(B),C+=B-I),t.portamentoFromKey>-1){let Q=Math.min((e-t.startTime)/t.portamentoDuration,1),b=I-t.portamentoFromKey;C-=b*(1-Q)}h+=(I-t.rootKey)*o[c.scaleTuning];let g=0,E=0,p=t.gainModifier*(1+o[c.amplitude]/1e3);if(e>=t.vibLfoStartTime){let Q=o[c.vibLfoToPitch],b=o[c.vibLfoToFilterFc],L=o[c.vibLfoAmplitudeDepth];if(Q!==0||b!==0||L!==0){let z=Math.max(0,ss(o[c.freqVibLFO])+o[c.vibLfoRate]/100)*n/i,$=1-4*Math.abs(t.vibLfoPhase-.5);(t.vibLfoPhase+=z)>=1&&(t.vibLfoPhase-=1),h+=$*Q,g+=$*b,p*=1-($+1)/2*(L/1e3)}}if(e>=t.modLfoStartTime){let Q=o[c.modLfoToPitch],b=o[c.modLfoToVolume],L=o[c.modLfoToFilterFc],z=o[c.modLfoAmplitudeDepth];if(Q!==0||L!==0||b!==0||z!==0){let $=Math.max(0,ss(o[c.freqModLFO])+o[c.modLfoRate]/100)*n/i,W=1-4*Math.abs(t.modLfoPhase-.5);(t.modLfoPhase+=$)>=1&&(t.modLfoPhase-=1),h+=W*Q,E+=-W*b,g+=W*L,p*=1-(W+1)/2*(z/1e3)}}let y=o[c.modEnvToPitch],D=o[c.modEnvToFilterFc];if(D!==0||y!==0){let Q=t.modEnv.process(t,e);g+=Q*D,h+=Q*y}E-=t.resonanceOffset;let R=h+C*100,S=R|0;S!==t.tuningCents&&(t.tuningCents=S,t.tuningRatio=Math.pow(2,R/1200));let w=kA(o[c.initialAttenuation])*kA(E);if(t.loopingMode===2&&!t.isInRelease){t.isActive=t.volEnv.process(n,w);return}let F=r.voiceBuffer;t.isActive=t.wavetable.process(n,t.tuningRatio,F);let H=t.volEnv.outputGain,k=t.volEnv.process(n,w),u=(t.volEnv.outputGain-H)/n;{let Q=t.filter,b=o[c.initialFilterFc];Q.initialized?Q.currentInitialFc+=(b-Q.currentInitialFc)*Qs.smoothingConstant:(Q.initialized=!0,Q.currentInitialFc=b);let L=Q.currentInitialFc+g,z=o[c.initialFilterQ];if(Q.currentInitialFc>13499&&L>13499&&z===0){Q.currentInitialFc=13500;for(let $=0;$1||Q.resonanceCb!==z)&&(Q.lastTargetCutoff=L,Q.resonanceCb=z,Q.calculateCoefficients(L));let{a0:$,a1:W,a2:V,a3:ee,a4:Ae}=Q,{x1:Y,x2:re,y1:ue,y2:Le}=Q;for(let Ee=0;Ee0){let Q=J.reverbGain*O*(U/1e3),b=r.reverbInput;for(let L=0;L0){let Q=J.chorusGain*(T/1e3)*O,b=r.chorusInput;for(let L=0;L0){let b=O*J.delayGain*((Q>>7)/127),L=r.delayInput;for(let z=0;z127||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&&De.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===ke.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 a of this.synthCore.voices)if(a.channel===this.channel&&a.isActive&&a.isHeld&&(a.isHeld=!1,a.releaseVoice(this.synthCore.currentTime),++s>=this._voiceCount))break}}break;case f.portamentoControl:this.lastPortamentoNote=e,this.portamentoForce=!0;break;default:this.computeModulatorsAll(1,t);break}A&&this.synthCore.callEvent("controllerChange",{channel:this.channel,controller:t,value:e})}}var Br=[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],ht=(t,e,A)=>Math.max(e,Math.min(A,t)),lA=t=>Math.max(-32768,1200*Math.log2(t/1e3)),Er=t=>6900+1200*Math.log2(t/440);function dr(t,e){let A=e&127;e-=8192;let s=Br[t];s||l.unsupported(`AWE32 LSB for ${this.channel}`,[t],"Invalid Generator Number");let a,n,r,i;switch(s){default:break;case c.delayModLFO:case c.delayVibLFO:case c.delayVolEnv:case c.delayModEnv:a=4*ht(e,0,5900),this.setGeneratorOverride(s,lA(a));break;case c.attackVolEnv:case c.attackModEnv:a=ht(e,0,5940),this.setGeneratorOverride(s,lA(a));break;case c.holdVolEnv:case c.holdModEnv:a=ht(e,0,8191),this.setGeneratorOverride(s,lA(a));break;case c.decayModEnv:case c.decayVolEnv:case c.releaseVolEnv:case c.releaseModEnv:a=4*ht(e,0,5940),this.setGeneratorOverride(s,lA(a));break;case c.freqVibLFO:case c.freqModLFO:n=.084*A,this.setGeneratorOverride(s,Er(n),!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=ht(e,-127,127)*9.375,this.setGeneratorOverride(s,i,!0);break;case c.modEnvToPitch:i=ht(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=ht(e,-64,63)*56.25,this.setGeneratorOverride(s,i,!0);break;case c.modEnvToFilterFc:i=ht(e,-64,63)*56.25,this.setGeneratorOverride(s,i);break;case c.chorusEffectsSend:case c.reverbEffectsSend:this.setGeneratorOverride(s,ht(e,0,255)*(1e3/255));break}}function fr(){let t=this._midiControllers[f.dataEntryMSB];if(this.lastParameterIsRegistered){let a=this._midiControllers[f.registeredParameterMSB]|this._midiControllers[f.registeredParameterLSB]>>7;switch(a){default:l.info(`%cUnrecognized RPN for %c${this.channel}%c: %c(0x${a.toString(16)})%c data value: %c${t}`,d.warn,d.recognized,d.warn,d.unrecognized,d.warn,d.value);break;case Ze.pitchWheelRange:{let n=t/128;this.setMIDIParameter("pitchWheelRange",n),l.coolInfo(`Pitch Wheel Range for ${this.channel}`,n,"semitones");break}case Ze.coarseTuning:{let n=(t>>7)-64;this.setMIDIParameter("keyShift",n),l.coolInfo(`Key shift for ${this.channel}`,n);break}case Ze.fineTuning:{let n=(t-8192)/81.92;this.setMIDIParameter("fineTune",n),l.coolInfo(`Fine tuning for ${this.channel}`,Math.round(n),"cents");break}case Ze.modulationDepth:{let n=t/1.28;this.setMIDIParameter("modulationDepth",n),l.coolInfo(`Modulation depth for ${this.channel}`,Math.round(n),"cents");break}case Ze.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>=ke.drumPitch&&e<=ke.drumDelay))switch(e){default:l.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 ke.partParameter:{let a=this._systemParameters.nrpnParamLock??this.synthCore.systemParameters.nrpnParamLock;switch(A){default:l.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 Ue.vibratoRate:this.controllerChange(f.vibratoRate,s);break;case Ue.vibratoDepth:this.controllerChange(f.vibratoDepth,s);break;case Ue.vibratoDelay:this.controllerChange(f.vibratoDelay,s);break;case Ue.tvfCutoffFrequency:if(a)return;this.controllerChange(f.brightness,s),l.coolInfo(`Filter cutoff for ${this.channel}`,s.toString(),"");break;case Ue.tvfResonance:if(a)return;this.controllerChange(f.filterResonance,s),l.coolInfo(`Filter resonance for ${this.channel}`,s.toString(),"");break;case Ue.envelopeAttackTime:if(a)return;this.controllerChange(f.attackTime,s),l.coolInfo(`EG attack time for ${this.channel}`,s.toString(),"");break;case Ue.envelopeDecayTime:if(a)return;this.controllerChange(f.decayTime,s),l.coolInfo(`EG decay time for ${this.channel}`,s.toString(),"");break;case Ue.envelopeReleaseTime:if(a)return;this.controllerChange(f.releaseTime,s),l.coolInfo(`EG release time for ${this.channel}`,s.toString(),"");break}break}case ke.drumPitch:{let a=this.channelSystem==="xg"||this.patch.bankLSB===1?(s-64)*100:(s-64)*50;this.drumParams[A].pitch=a,l.coolInfo(`Drum ${A} pitch for ${this.channel}`,a,"cents");break}case ke.drumPitchFine:{let a=s-64;this.drumParams[A].pitch+=a,l.coolInfo(`Drum ${A} pitch fine for ${this.channel}`,this.drumParams[A].pitch,"cents");break}case ke.drumLevel:this.drumParams[A].gain=s/120,l.coolInfo(`Drum ${A} level for ${this.channel}`,s,"");break;case ke.drumPan:this.drumParams[A].pan=s,l.coolInfo(`Drum ${A} pan for ${this.channel}`,s,"");break;case ke.drumReverb:this.drumParams[A].reverbGain=s/127,l.coolInfo(`Drum ${A} reverb level for ${this.channel}`,s,"");break;case ke.drumChorus:this.drumParams[A].chorusGain=s/127,l.coolInfo(`Drum ${A} chorus level for ${this.channel}`,s,"");break;case ke.drumDelay:this.drumParams[A].delayGain=s/127,l.coolInfo(`Drum ${A} delay level for ${this.channel}`,t,"");break;case ke.awe32:dr.call(this,A,t);break;case ke.SF2:{if(A>100)break;let a=this.sf2NRPNGeneratorLSB,n=t-8192;this.setGeneratorOffset(a,n);break}}}var Qr=40;function ur(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],a=[.028212773333433472,-.3388502064992847,-.15839529890929713,-.12398131766775483,-.2874848552685111,.012254866302537692,.005957797193345771,-.03745899330347374,.12911781869810196,-.15867193224162568,.504406322732748,.3786845131875458],n=[.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 h=i.length-1;h>=0;h--)if(i[h]Math.max(e,Math.min(A,t));function pr(t,e,A=!0){if(e<1){this.noteOff(t);return}let s=this.synthCore.systemParameters.blackMIDIMode;if(s&&this.synthCore.voiceCount>200&&e<40||s&&e<10||this._systemParameters.isMuted||!this.preset)return;let a=Kt(Math.floor(e*(this._midiParameters.velocitySenseDepth/64)+(this._midiParameters.velocitySenseOffset-64)*2),0,127),n=t+this.currentKeyShift;if(t>127||t<0)return;let r=this.preset.program,i=this.synthCore.tunings[r*128+t];i>=0&&(n=Math.trunc(i)),((this._systemParameters.monophonicRetrigger??this.synthCore.systemParameters.monophonicRetrigger)||this._midiParameters.assignMode===0)&&this.killNote(t);let o=this.synthCore.keyModifierManager.getVelocity(this.channel,t);o>-1&&(a=o);let I=this.synthCore.keyModifierManager.getGain(this.channel,t),h=this.lastPortamentoNote,C=this.portamentoForce||this._midiControllers[f.portamentoOnOff]>=8192,B=this._midiControllers[f.portamentoTime]>>7,g=C&&!this._drumChannel&&h>=0&&h!==t&&B>0,E=-1,p=0;if(g){let u=Math.abs(t-h);E=h,p=mr(B,u),this.portamentoForce=!1}this.lastPortamentoNote=t,this.playingNotes[t]=!0,this._midiParameters.polyMode||(this.lastMonoNote>=0&&this.lastMonoNote!==t&&this.killNote(this.lastMonoNote),this.lastMonoNote=t,this.lastMonoVelocity=e);let y=this.synthCore.getVoices(this.channel,n,a),D=0,R=0,S=0,w=1,F=1,H=1;if(this._midiParameters.randomPan&&(D=Math.round(Math.random()*1e3-500)),this._drumChannel){let u=this.drumParams[t];if(!u.rxNoteOn)return;let m=u.pan-64;if(m!==0)if(m===-64)D=Math.round(Math.random()*1e3-500);else{let J=(this._midiControllers[f.pan]>>7)-64;D=Math.max(-63,Math.min(m+J,63))/63*500||1}S=u.pitch,R=u.exclusiveClass,w=u.reverbGain,F=u.chorusGain,H=u.delayGain,I===1&&(I=u.gain)}let k=A?this.noteOnID[t]++:this.noteOnID[t];for(let u of y){let m=this.synthCore.assignVoice(),J=this.synthCore.currentTime;if(m.setup(J,this.channel,t,k),m.wavetable=m.oscillators[this._systemParameters.interpolationType??this.synthCore.systemParameters.interpolationType],m.targetKey=u.targetKey,m.velocity=u.velocity,m.generators.set(u.generators),m.exclusiveClass=R||u.exclusiveClass,m.rootKey=u.rootKey,m.loopingMode=u.loopingMode,m.wavetable.sampleData=u.sampleData,m.wavetable.playbackStep=u.playbackStep,this.dynamicModulators.active){m.modulators=[...u.modulators];for(let T of this.dynamicModulators.modulatorList){let Q=m.modulators.findIndex(b=>we.isIdentical(b,T.mod));Q===-1?m.modulators.push(T.mod):m.modulators[Q]=T.mod}}else m.modulators=u.modulators;if(m.modulators.length>m.modulatorValues.length&&(l.warn(`${m.modulators.length} modulators! Increasing modulatorValues table.`),m.modulatorValues=new Int16Array(m.modulators.length)),this.generators.overridesEnabled){let T=this.generators.overrides;for(let Q=0;Q0){for(let Q of this.synthCore.voices)if(Q.isActive&&Q.channel===this.channel&&Q.exclusiveClass===m.exclusiveClass&&Q.hasRendered&&(Q.exclusiveRelease(this.synthCore.currentTime),++T>=this._voiceCount))break}}this.computeModulators(m),m.volEnv.init(m),m.modEnv.init(m),m.filter.init(),m.vibLfoStartTime=J+yA(m.modulatedGenerators[c.delayVibLFO]),m.modLfoStartTime=J+yA(m.modulatedGenerators[c.delayModLFO]);let O=m.modulatedGenerators[c.startAddrsOffset]+m.modulatedGenerators[c.startAddrsCoarseOffset]*32768,q=m.modulatedGenerators[c.endAddrOffset]+m.modulatedGenerators[c.endAddrsCoarseOffset]*32768,K=m.modulatedGenerators[c.startloopAddrsOffset]+m.modulatedGenerators[c.startloopAddrsCoarseOffset]*32768,ae=m.modulatedGenerators[c.endloopAddrsOffset]+m.modulatedGenerators[c.endloopAddrsCoarseOffset]*32768,U=u.sampleData.length;if(m.wavetable.cursor=Kt(O,0,U-1),m.wavetable.end=Kt(U+q,0,U),m.wavetable.loopStart=Kt(u.loopStart+K,0,U),m.wavetable.loopEnd=Kt(u.loopEnd+ae,0,U),m.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}this.playingNotes[t]=!1;let e=!this._midiParameters.polyMode,A=this._midiControllers[f.sustainPedal]>=8192&&!e,s=0,a=this.noteOffID[t];if(a0){for(let n of this.synthCore.voices)if(n.channel===this.channel&&n.isActive&&n.midiNote===t&&n.noteID===a&&!n.isInRelease&&(A?n.isHeld=!0:n.releaseVoice(this.synthCore.currentTime),++s>=this._voiceCount))break}if(this.synthCore.callEvent("noteOff",{midiNote:t,channel:this.channel}),e){let n=this.playingNotes.lastIndexOf(!0);n===-1?this.lastMonoNote=-1:this.lastMonoNote===t&&this.noteOn(n,this.lastMonoVelocity,!1)}}function Sr(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 kr=[wA.fromModulator(new ye($e(Ce.linear,!0,!1,!0,f.vibratoRate),0,c.vibLfoRate,1e3,0))],Dr=class{modulatorList=[];active=!1;channel;constructor(t){this.channel=t}resetModulators(){this.modulatorList=kr.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,a,n=!1){this.active=!0;let r=e-64,i=r/64,o=e/127;switch(t&15){case 0:{let I=Math.min(24,Math.max(-24,r));this.setModulator(A,s,c.fineTune,I*100,n),l.coolInfo(`Channel ${this.channel} ${a} pitch control`,I,"semitones");break}case 1:this.setModulator(A,s,c.initialFilterFc,i*9600,n),l.coolInfo(`Channel ${this.channel} ${a} filter control`,i*9600,"cents");break;case 2:this.setModulator(A,s,c.amplitude,i*1e3,n),l.coolInfo(`Channel ${this.channel} ${a} amplitude control`,i*100,"%");break;case 3:this.setModulator(A,s,c.vibLfoRate,i*1e3,n),l.coolInfo(`Channel ${this.channel} ${a} LFO1 rate control`,i*10,"Hz");break;case 4:this.setModulator(A,s,c.vibLfoToPitch,o*600,n),l.coolInfo(`Channel ${this.channel} ${a} LFO1 pitch depth control`,o*600,"cents");break;case 5:this.setModulator(A,s,c.vibLfoToFilterFc,o*2400,n),l.coolInfo(`Channel ${this.channel} ${a} LFO1 filter depth control`,o*2400,"cents");break;case 6:this.setModulator(A,s,c.vibLfoAmplitudeDepth,o*1e3,n),l.coolInfo(`Channel ${this.channel} ${a} LFO1 amplitude depth control`,o*100,"%");break;case 7:this.setModulator(A,s,c.modLfoRate,i*1e3,n),l.coolInfo(`Channel ${this.channel} ${a} LFO2 rate control`,i*10,"Hz");break;case 8:this.setModulator(A,s,c.modLfoToPitch,o*600,n),l.coolInfo(`Channel ${this.channel} ${a} LFO2 pitch depth control`,o*600,"cents");break;case 9:this.setModulator(A,s,c.modLfoToFilterFc,o*2400,n),l.coolInfo(`Channel ${this.channel} ${a} LFO2 filter depth control`,o*2400,"cents");break;case 10:this.setModulator(A,s,c.modLfoAmplitudeDepth,o*1e3,n),l.coolInfo(`Channel ${this.channel} ${a} LFO2 amplitude depth control`,o*100,"%");break}}setModulator(t,e,A,s,a=!1,n=!1){let r=this.getModulatorID(t,A,a,n);s===0&&this.deleteModulator(r);let i=this.modulatorList.find(o=>o.id===r);if(i)i.mod.transformAmount=s;else{let o=wA.fromData(new at(t,Ce.linear,e,a),new at,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)}},wr=1e3/200;function Mr(t,e,A){let s=t.modulators[A];if(s.transformAmount===0)return t.modulatorValues[A]=0,0;let a=s.primarySource.getValue(this,e,t),n=s.secondarySource.getValue(this,e,t),r=s.transformAmount;s.isEffectModulator&&r<=1e3&&(r*=wr,r=Math.min(r,1e3));let i=a*n*r;return s.transformType===2&&(i=Math.abs(i)),s.isDefaultResonantModulator&&(t.resonanceOffset=Math.max(0,i/2)),s.isModWheelModulator&&(i*=this._midiParameters.modulationDepth/50),t.modulatorValues[A]=i,i}function br(t,e=-1,A=0){let s=t.modulators,a=t.generators;if(this.generators.offsetsEnabled){let o=this.generators.offsets;a=new Int16Array(a);for(let I=0;I({...t})),drumChannel:this._drumChannel,channel:this.channel}}function Fr(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),this.generators.offsetsEnabled=t.generators.offsetsEnabled,this.generators.overridesEnabled=t.generators.overridesEnabled;for(let e=0;e<128;e++)this.drumParams[e]=vn.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(t.midiParameters))this.setMIDIParameter(e,A);for(let[e,A]of Object.entries(t.lockedMIDIParameters))this.lockMIDIParameter(e,A);for(let[e,A]of Object.entries(t.systemParameters))this.setSystemParameter(e,A)}var Hs={pitchWheel:8192,pitchWheelRange:2,pressure:0,modulationDepth:50,rxChannel:0,polyMode:!0,keyShift:0,fineTune:0,randomPan:!1,assignMode:2,efxAssign:!1,cc1:16,cc2:17,drumMap:0,velocitySenseDepth:64,velocitySenseOffset:64};function vr(t,e){if(!this.lockedMIDIParameters[t]){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})}}function Gr(t,e){this.lockedMIDIParameters[t]=e}var Lr={presetLock:!1,isMuted:!1,gain:1,pan:0,keyShift:0,fineTune:0,interpolationType:null,nrpnParamLock:null,monophonicRetrigger:null};function Pr(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 Nr=class{pitchWheels=new Int16Array(128).fill(8192);drumParams=[];dynamicModulators;sf2NRPNGeneratorLSB=0;patch={bankMSB:0,bankLSB:0,program:0,isGMGSDrum:!1};preset;lockedSystem="gs";channel;synthCore;setSystemParameter=Pr.bind(this);lockMIDIParameter=Gr.bind(this);noteOn=pr.bind(this);noteOff=yr.bind(this);programChange=Sr.bind(this);controllerChange=Cr.bind(this);reset=wa.bind(this);renderVoice=lr.bind(this);setMIDIParameter=vr.bind(this);lockedControllers=new Array(128).fill(!1);_midiControllers=new Int16Array(128);octaveTuning=new Int8Array(128);resetRP15=Ma.bind(this);dataEntry=fr.bind(this);lockedMIDIParameters=Object.fromEntries(Object.keys(Hs).map(t=>[t,!1]));_midiParameters={...Hs};_systemParameters={...Lr};noteOnID=new Array(128).fill(0);noteOffID=new Array(128).fill(0);lastParameterIsRegistered=!0;perNotePitch=!1;currentPan=0;currentTuning=0;currentKeyShift=0;currentGain=0;lastPortamentoNote=-1;portamentoForce=!1;lastMonoNote=-1;lastMonoVelocity=0;playingNotes=new Array(128).fill(!1);generators={offsets:new Int16Array(Dt),offsetsEnabled:!1,overrides:new Int16Array(Dt),overridesEnabled:!1};computeModulator=Mr.bind(this);computeModulators=br.bind(this);constructor(t,e,A){this.synthCore=t,this.preset=e,this.channel=A,this._midiParameters.rxChannel=A,this.dynamicModulators=new Dr(A),this.resetGeneratorOverrides(),this.resetGeneratorOffsets();for(let s=0;s<128;s++)this.drumParams.push(new vn);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(De.isSystemXG(this.channelSystem))if(t)this.setBankMSB(De.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(this.noteOnID.fill(0),this.noteOffID.fill(0),this.playingNotes.fill(!1),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})}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]}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})}updateInternalParams(){let t=this.synthCore.systemParameters,e=this._systemParameters,A=this.synthCore.midiParameters,s=this._midiParameters,a=this._drumChannel?e.keyShift:t.keyShift+A.keyShift+e.keyShift+s.keyShift;this.currentKeyShift=Math.trunc(a),this.currentTuning=this._drumChannel?e.fineTune:t.fineTune+A.fineTune+e.fineTune+s.fineTune;let n=t.pan+A.pan+e.pan;this.currentPan=n*500,this.currentGain=ta*t.gain*Math.pow(A.volume,2)*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.noteOffID[t]=0,this.noteOnID[t]=0,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){Fr.call(this,t)}getSnapshot(){return Rr.call(this)}setLastNote(t){this.lastPortamentoNote=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(_n),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 a of this.synthCore.voices)if(a.channel===this.channel&&a.isActive&&(a.generators[t]=e,this.computeModulators(a),++s>=this._voiceCount))break}}}resetGeneratorOffsets(){this.generators.offsets.fill(0),this.generators.offsetsEnabled=!1}setGeneratorOffset(t,e){this.generators.offsets[t]=e*ze[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=pA[t]/127,e.chorusGain=this.channelSystem==="xg"?pA[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.updateInternalParams())}},Tr=class extends zt{constructor(t,e){super(t.parentSoundBank,t.globalZone),this.bankMSB=De.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}},Ur=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){l.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(a=>a.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 je.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,a=A.bankOffset;for(let n of s.presets){let r=new Tr(n,a);e.has(r.toMIDIString())||(e.add(r.toMIDIString()),t.push(r))}}t.sort(je.compare.bind(je)),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 Os(t,e,A){let s=t,a=e<<7|A;return t===127&&e===127&&A===127?-1:s+a*61e-6}function xr(t,e=0){switch(t[2]){case 4:switch(t[3]){default:l.gmFail("Device Control",t);break;case 1:{let A=t[5]<<7|t[4];this.setMIDIParameter("volume",A/16383),l.gmInfo("Master Volume",A);break}case 2:{let A=((t[5]<<7|t[4])-8192)/8192;this.setMIDIParameter("pan",A),l.gmInfo("Master Balance",A);break}case 3:{let A=((t[5]<<7|t[4])-8192)/81.92;this.setMIDIParameter("fineTune",A),l.gmInfo("Master Fine Tuning",A,"cents");break}case 4:{let A=t[5]-64;this.setMIDIParameter("keyShift",A),l.gmInfo("Master Coarse Tuning",A,"keys");break}case 5:if(t[4]!==1||t[5]!==1||t[6]!==1||t[7]!==1){l.gmFail("Global Parameter Control",t);break}switch(t[8]){default:l.gmFail("Global Parameter Control",t);break;case 1:{let A=t[10];switch(t[9]){default:l.gmFail("Reverb Parameter Control",t);break;case 0:{let s=A===8?5:A;this.setReverbMacro(s),l.gmInfo("Reverb Type",s);break}case 1:this.reverbProcessor.time=A,l.gmInfo("Reverb Time",A)}break}case 2:{let A=t[10];switch(t[9]){default:l.gmFail("Chorus Parameter Control",t);break;case 0:this.setChorusMacro(A),l.gmInfo("Chorus Type",A);break;case 1:this.chorusProcessor.rate=A,l.gmInfo("Chorus Mod Rate",A);break;case 2:this.chorusProcessor.depth=A,l.gmInfo("Chorus Mod Depth",A);break;case 3:this.chorusProcessor.feedback=A,l.gmInfo("Chorus Mod Feedback",A);break;case 4:this.chorusProcessor.sendLevelToReverb=A,l.gmInfo("Chorus Send to Reverb",A);break}}}}break;case 9:switch(t[3]){default:l.gmFail("System Exclusive",t);break;case 1:l.coolInfo("MIDI System","General MIDI 1"),this.reset("gm");break;case 2:l.coolInfo("MIDI System","Roland GS"),this.reset("gs");break;case 3:l.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++],a=We(t,16,A);if(A+=16,t.length<384){l.warn(`The Bulk Tuning Dump is too short! (${t.length} bytes, at least 384 are expected)`);return}for(let n=0;n<128;n++)this.tunings[s*128+n]=Os(t[A++],t[A++],t[A++]);l.gmInfo("Bulk Tuning Dump",`${a}, program ${s}`);break}case 2:case 7:{t[3]===7&&A++;let s=t[A++],a=t[A++];for(let n=0;n>1&1)===1&&this.midiChannels[15+e].setOctaveTuning(s);for(let a=0;a<7;a++)(t[5]>>a&1)===1&&this.midiChannels[7+a+e].setOctaveTuning(s);for(let a=0;a<7;a++)(t[6]>>a&1)===1&&this.midiChannels[a+e].setOctaveTuning(s);l.gmInfo("Octave Scale Tuning",s.join(" "));break}default:l.gmFail("MIDI Tuning Standard",t);break}break}default:l.gmFail("Universal System Exclusive",t)}}function Hr(t,e=0){if(t[3]===18)switch(t[2]){case 66:{let A=t[4],s=t[5],a=t[6],n=Math.min(t[7],127);if(A===0&&s===0&&a===127&&(n===0||n===1)){if(n===1)for(l.gsInfo("Mode","Double Module");this.midiChannels.length<32;)this.createMIDIChannel(!0);l.coolInfo("MIDI System","Roland GS"),this.reset("gs");return}if(A===64||A===80){if(A===80&&(e+=16),s===0){switch(a){case 0:{let r=((n<<12|t[8]<<8|t[9]<<4|t[10])-1024)/10;this.setMIDIParameter("fineTune",r),l.gsInfo("Master Tune",r,"cents");break}case 4:l.gsInfo("Master Volume",n),this.setMIDIParameter("volume",n/127);break;case 5:{let r=n-64;l.gsInfo("Master Key-Shift",r,"keys"),this.setMIDIParameter("keyShift",r);break}case 6:{let r=(n-64)/63;l.gsInfo("Master Pan",r),this.setMIDIParameter("pan",r);break}case 127:n===0?(l.coolInfo("MIDI System","Roland GS"),this.reset("gs")):n===127&&(l.coolInfo("MIDI System","General MIDI 1"),this.reset("gm"));break;default:l.gsFail("System Parameter",t);break}return}if(s===1){let r=a>=48&&a<=55,i=a>=56&&a<=64,o=a>=80&&a<=90;if(r&&this.systemParameters.reverbLock||i&&this.systemParameters.chorusLock||o&&this.systemParameters.delayLock)return;switch(this.delayActive||=a===64||o,a){default:l.gsFail("Patch Common Parameter",[a]);break;case 0:{let I=We(t,16,7);l.gsInfo("Patch name",I),this.callEvent("displayMessage",[...t]);break}case 48:this.setReverbMacro(n),l.gsInfo("Reverb Macro",n);break;case 49:this.reverbProcessor.character=n,l.gsInfo("Reverb Character",n),this.callEvent("effectChange",{effect:"reverb",parameter:"character",value:n});break;case 50:this.reverbProcessor.preLowpass=n,l.gsInfo("Reverb Pre-LPF",n),this.callEvent("effectChange",{effect:"reverb",parameter:"preLowpass",value:n});break;case 51:this.reverbProcessor.level=n,l.gsInfo("Reverb Level",n),this.callEvent("effectChange",{effect:"reverb",parameter:"level",value:n});break;case 52:this.reverbProcessor.time=n,l.gsInfo("Reverb Time",n),this.callEvent("effectChange",{effect:"reverb",parameter:"time",value:n});break;case 53:this.reverbProcessor.delayFeedback=n,l.gsInfo("Reverb Delay Feedback",n),this.callEvent("effectChange",{effect:"reverb",parameter:"delayFeedback",value:n});break;case 54:break;case 55:this.reverbProcessor.preDelayTime=n,l.gsInfo("Reverb Predelay Time",n),this.callEvent("effectChange",{effect:"reverb",parameter:"preDelayTime",value:n});break;case 56:this.setChorusMacro(n),l.gsInfo("Chorus Macro",n);break;case 57:this.chorusProcessor.preLowpass=n,l.gsInfo("Chorus Pre-LPF",n),this.callEvent("effectChange",{effect:"chorus",parameter:"preLowpass",value:n});break;case 58:this.chorusProcessor.level=n,l.gsInfo("Chorus Level",n),this.callEvent("effectChange",{effect:"chorus",parameter:"level",value:n});break;case 59:this.chorusProcessor.feedback=n,l.gsInfo("Chorus Feedback",n),this.callEvent("effectChange",{effect:"chorus",parameter:"feedback",value:n});break;case 60:this.chorusProcessor.delay=n,l.gsInfo("Chorus Delay",n),this.callEvent("effectChange",{effect:"chorus",parameter:"delay",value:n});break;case 61:this.chorusProcessor.rate=n,l.gsInfo("Chorus Rate",n),this.callEvent("effectChange",{effect:"chorus",parameter:"rate",value:n});break;case 62:this.chorusProcessor.depth=n,l.gsInfo("Chorus Depth",n),this.callEvent("effectChange",{effect:"chorus",parameter:"depth",value:n});break;case 63:this.chorusProcessor.sendLevelToReverb=n,l.gsInfo("Chorus Send Level To Reverb",n),this.callEvent("effectChange",{effect:"chorus",parameter:"sendLevelToReverb",value:n});break;case 64:this.chorusProcessor.sendLevelToDelay=n,l.gsInfo("Chorus Send Level To Delay",n),this.callEvent("effectChange",{effect:"chorus",parameter:"sendLevelToDelay",value:n});break;case 80:this.setDelayMacro(n),l.gsInfo("Delay Macro",n);break;case 81:this.delayProcessor.preLowpass=n,l.gsInfo("Delay Pre-LPF",n),this.callEvent("effectChange",{effect:"delay",parameter:"preLowpass",value:n});break;case 82:this.delayProcessor.timeCenter=n,l.gsInfo("Delay Time Center",n),this.callEvent("effectChange",{effect:"delay",parameter:"timeCenter",value:n});break;case 83:this.delayProcessor.timeRatioLeft=n,l.gsInfo("Delay Time Ratio Left",n),this.callEvent("effectChange",{effect:"delay",parameter:"timeRatioLeft",value:n});break;case 84:this.delayProcessor.timeRatioRight=n,l.gsInfo("Delay Time Ratio Right",n),this.callEvent("effectChange",{effect:"delay",parameter:"timeRatioRight",value:n});break;case 85:this.delayProcessor.levelCenter=n,l.gsInfo("Delay Level Center",n),this.callEvent("effectChange",{effect:"delay",parameter:"levelCenter",value:n});break;case 86:this.delayProcessor.levelLeft=n,l.gsInfo("Delay Level Left",n),this.callEvent("effectChange",{effect:"delay",parameter:"levelLeft",value:n});break;case 87:this.delayProcessor.levelRight=n,l.gsInfo("Delay Level Right",n),this.callEvent("effectChange",{effect:"delay",parameter:"levelRight",value:n});break;case 88:this.delayProcessor.level=n,l.gsInfo("Delay Level",n),this.callEvent("effectChange",{effect:"delay",parameter:"level",value:n});break;case 89:this.delayProcessor.feedback=n,l.gsInfo("Delay Feedback",n),this.callEvent("effectChange",{effect:"delay",parameter:"feedback",value:n});break;case 90:this.delayProcessor.sendLevelToReverb=n,l.gsInfo("Delay Send Level To Reverb",n),this.callEvent("effectChange",{effect:"delay",parameter:"sendLevelToReverb",value:n});break}break}if(s===3){if(this.systemParameters.insertionEffectLock)return;if(a>=3&&a<=25&&(this.insertionParams[a-3]=n),a>=3&&a<=22){this.insertionProcessor.setParameter(a,n),l.gsInfo(`EFX Parameter ${a-2}`,n),this.callEvent("effectChange",{effect:"insertion",parameter:a,value:n});return}switch(a){default:l.gsFail("Insertion Effect",[a]);return;case 0:{let r=n<<8|t[8],i=this.insertionEffects.get(r);i?(l.gsInfo("EFX Type",r.toString(16)),this.insertionProcessor=i):(this.insertionProcessor=this.insertionFallback,l.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=n/127*CA,l.gsInfo("EFX Send Level to Reverb",n),this.callEvent("effectChange",{effect:"insertion",parameter:a,value:n});return;case 24:this.insertionProcessor.sendLevelToChorus=n/127*CA,l.gsInfo("EFX Send Level to Chorus",n),this.callEvent("effectChange",{effect:"insertion",parameter:a,value:n});return;case 25:this.insertionProcessor.sendLevelToDelay=n/127*CA,this.delayActive=!0,l.gsInfo("EFX Send Level to Delay",n),this.callEvent("effectChange",{effect:"insertion",parameter:a,value:n});return}}if(s>>4===1){let r=ne.syxToChannel(s&15)+e,i=this.midiChannels[r];switch(i||l.gsFail(`Patch Parameter for ${r}`,t,"Invalid channel number"),a){default:l.gsFail(`Patch Part Parameter for ${r}`,[a]);return;case 0:i.controllerChange(f.bankSelect,n),i.programChange(t[8]);break;case 2:{let o=n===16?-1:n+e;i.setMIDIParameter("rxChannel",o),this.customChannelNumbers||=o!==i.channel,l.gsInfo(`Rx. Channel on ${r}`,o);break}case 19:i.setMIDIParameter("polyMode",n===1),l.gsInfo(`Mono/poly on ${r}`,i.midiParameters.polyMode?"POLY":"MONO");break;case 20:i.setMIDIParameter("assignMode",n),l.gsInfo(`Assign mode on ${r}`,n);break;case 21:{i.setMIDIParameter("drumMap",n);let o=n>0;i.setGSDrums(o),l.gsInfo(`Drums on ${r}`,o.toString());return}case 22:{let o=n-64;i.setMIDIParameter("keyShift",o),l.gsInfo(`Key Shift for ${r}`,o);return}case 25:i.controllerChange(f.mainVolume,n);return;case 26:i.setMIDIParameter("velocitySenseDepth",n),l.gsInfo(`Velocity Sense Depth for ${r}`,n);return;case 27:i.setMIDIParameter("velocitySenseOffset",n),l.gsInfo(`Velocity Sense Offset for ${r}`,n);return;case 28:{let o=n,I=o===0;i.setMIDIParameter("randomPan",I),I?l.gsInfo(`Random pan on ${r}`,"ON"):i.controllerChange(f.pan,o);break}case 31:i.setMIDIParameter("cc1",n),l.gsInfo(`CC1 Controller Number for ${r}`,n);break;case 32:i.setMIDIParameter("cc2",n),l.gsInfo(`CC2 Controller Number for ${r}`,n);break;case 33:i.controllerChange(f.chorusDepth,n);break;case 34:i.controllerChange(f.reverbDepth,n);break;case 42:{let o=((n<<7|t[8])-8192)/81.92;i.setMIDIParameter("fineTune",o),l.gsInfo(`Fine tuning for ${r}`,Math.round(o),"cents");break}case 44:i.controllerChange(f.variationDepth,n);break;case 48:i.controllerChange(f.vibratoRate,n);break;case 49:i.controllerChange(f.vibratoDepth,n);break;case 50:i.controllerChange(f.brightness,n);break;case 51:i.controllerChange(f.filterResonance,n);break;case 52:i.controllerChange(f.attackTime,n);break;case 53:i.controllerChange(f.decayTime,n);break;case 54:i.controllerChange(f.releaseTime,n);break;case 55:i.controllerChange(f.vibratoDelay,n);break;case 64:{let o=t.length-9,I=new Int8Array(12);for(let h=0;h>4===2){let r=ne.syxToChannel(s&15)+e,i=this.midiChannels[r];switch(a&240){default:l.gsFail(`Patch Parameter Controller for ${r}`,[a&240]);break;case 0:if((a&15)===4){let o=n/127*600;i.setMIDIParameter("modulationDepth",o),l.gsInfo(`Modulation depth for ${r}`,Math.round(o),"cents");break}i.dynamicModulators.setupReceiver(a,n,f.modulationWheel,!0,"mod wheel");break;case 16:if((a&15)===0){let o=n-64;i.setMIDIParameter("pitchWheelRange",o),l.gsInfo(`Pitch Wheel Range for ${r}`,o,"semitones");break}i.dynamicModulators.setupReceiver(a,n,Ie.pitchWheel,!1,"pitch wheel",!0);break;case 32:i.dynamicModulators.setupReceiver(a,n,Ie.channelPressure,!1,"channel pressure");break;case 48:i.dynamicModulators.setupReceiver(a,n,Ie.polyPressure,!1,"poly pressure");break;case 64:i.dynamicModulators.setupReceiver(a,n,i.midiParameters.cc1,!0,"CC1");break;case 80:i.dynamicModulators.setupReceiver(a,n,i.midiParameters.cc2,!0,"CC2")}return}if(s>>4===4){let r=ne.syxToChannel(s&15)+e,i=this.midiChannels[r];switch(a){default:l.gsFail("Patch Part Parameter",[a]);break;case 0:case 1:i.controllerChange(f.bankSelectLSB,n);break;case 34:{let o=n===1;i.setMIDIParameter("efxAssign",o),this.insertionActive||=o,l.gsInfo(`EFX assign for ${r}`,o?"EFX":"BYPASS")}}return}l.gsFail("Patch Parameter",t);return}if(A===65||A===81){if(this.systemParameters.drumLock)return;let r=(s>>4)+1,i=a,o=s&15;switch(o){default:l.gsFail("Drum Setup",[o]);return;case 0:{let I=We(t,12,7);l.gsInfo(`Drum Map Name for MAP${r}`,I),this.callEvent("displayMessage",[...t]);break}case 1:{let I=n-60;for(let h of this.midiChannels)h.midiParameters.drumMap===r&&(h.drumParams[i].pitch=I*(h.patch.bankLSB===1?100:50));l.gsInfo(`Drum Pitch for MAP${r}, key ${i}`,I);break}case 2:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].gain=n/120);l.gsInfo(`Drum Level for MAP${r}, key ${i}`,n);break;case 3:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].exclusiveClass=n);l.gsInfo(`Drum Assign Group for MAP${r}, key ${i}`,n);break;case 4:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].pan=n);l.gsInfo(`Drum Pan for MAP${r}, key ${i}`,n);break;case 5:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].reverbGain=n/127);l.gsInfo(`Drum Reverb for MAP${r}, key ${i}`,n);break;case 6:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].chorusGain=n/127);l.gsInfo(`Drum Chorus for MAP${r}, key ${i}`,n);break;case 7:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].rxNoteOff=n===1);l.gsInfo(`Drum Note Off for MAP${r}, key ${i}`,n===1?"ON":"OFF");break;case 8:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].rxNoteOn=n===1);l.gsInfo(`Drum Note On for MAP${r}, key ${i}`,n===1?"ON":"OFF");break;case 9:for(let I of this.midiChannels)I.midiParameters.drumMap===r&&(I.drumParams[i].delayGain=n/127);l.gsInfo(`Drum Delay for MAP${r}, key ${i}`,n);break}return}l.gsFail("System Exclusive",t);return}case 69:t[4]===16&&this.callEvent("displayMessage",[...t]);return;case 22:if(t[4]===16){this.setMIDIParameter("volume",t[7]/100),l.coolInfo("Roland Master Volume Control",t[7]);return}else l.unsupported("Roland",t)}else{l.unsupported("Roland",t);return}}function Or(t,e=0){if(t[2]===76){let A=t[3],s=t[4],a=t[5],n=t[6];if(A===0&&s===0){switch(a){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),l.xgInfo("Master Tune",r,"cents")}break;case 4:this.setMIDIParameter("volume",n/127),l.xgInfo("Master Volume",n);break;case 5:{let r=127-n;this.setMIDIParameter("volume",r/127),l.xgInfo("Master Attenuation",n);break}case 6:{let r=n-64;this.setMIDIParameter("keyShift",r),l.xgInfo("Master Transpose",n);break}case 127:case 126:l.coolInfo("MIDI System","Yamaha XG"),this.reset("xg");break}return}if(A===2&&s===1){let r,i=a;i<=21?r="Reverb":i<=53?r="Chorus":r="Variation",l.xgFail(`${r} parameter`,[i]);return}if(A===8){let r=s+e;if(r>=this.midiChannels.length){l.xgFail("Part Setup",t,`Invalid part number: ${r}`);return}let i=this.midiChannels[r];switch(a){default:l.xgFail("Part Setup",[t[5]]);break;case 1:i.controllerChange(f.bankSelect,n);break;case 2:i.controllerChange(f.bankSelectLSB,n);break;case 3:i.programChange(n);break;case 4:{let o=n+e;i.setMIDIParameter("rxChannel",o),this.customChannelNumbers||=o!==i.channel,l.xgInfo(`Rev. Channel on ${r}`,o);break}case 5:{let o=n===1;i.setMIDIParameter("polyMode",o),l.xgInfo(`Mono/poly on ${r}`,o?"POLY":"MONO");break}case 6:i.setMIDIParameter("assignMode",n),l.xgInfo(`Same Note Number Key On Assign on ${r}`,n);break;case 7:{let o=n!==0;i.setDrums(o),l.xgInfo(`Part Mode on ${r}`,o?"DRUM":"MELODIC");break}case 8:{let o=n-64;i.setMIDIParameter("keyShift",o),l.xgInfo(`Key Shift on ${r}`,o);break}case 11:i.controllerChange(f.mainVolume,n);break;case 12:i.setMIDIParameter("velocitySenseDepth",n),l.xgInfo(`Velocity Sense Depth on ${r}`,n);return;case 13:i.setMIDIParameter("velocitySenseOffset",n),l.xgInfo(`Velocity Sense Offset on ${r}`,n);return;case 14:{let o=n,I=o===0;i.setMIDIParameter("randomPan",I),I?l.xgInfo(`Random Pan for ${r}`,"ON"):i.controllerChange(f.pan,o);break}case 18:i.controllerChange(f.chorusDepth,n);break;case 19:i.controllerChange(f.reverbDepth,n);break;case 21:i.controllerChange(f.vibratoRate,n);break;case 22:i.controllerChange(f.vibratoDepth,n);break;case 23:i.controllerChange(f.vibratoDelay,n);break;case 24:i.controllerChange(f.brightness,n);break;case 25:i.controllerChange(f.filterResonance,n);break;case 26:i.controllerChange(f.attackTime,n);break;case 27:i.controllerChange(f.decayTime,n);break;case 28:i.controllerChange(f.releaseTime,n);break;case 35:{let o=n-64;i.setMIDIParameter("pitchWheelRange",o),l.xgInfo(`Pitch Wheel Range for ${r}`,o,"semitones")}}return}if(A>>4===3){if(this.systemParameters.drumLock)return;let r=s;switch(a){default:l.xgFail("Drum Setup",[a]);return;case 0:{let i=(n-64)*100;for(let o of this.midiChannels)o.drumChannel&&(o.drumParams[r].pitch=i);l.xgInfo(`Drum Pitch for key ${r}`,i,"semitones");break}case 1:{let i=n-64;for(let o of this.midiChannels)o.drumChannel&&(o.drumParams[r].pitch+=i,l.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=n/120);l.xgInfo(`Drum Level for key ${r}`,n);break;case 3:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].exclusiveClass=n);l.xgInfo(`Drum Alternate Group for key ${r}`,n);break;case 4:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].pan=n);l.xgInfo(`Drum Pan for key ${r}`,n);break;case 5:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].reverbGain=n/127);l.xgInfo(`Drum Reverb for key ${r}`,n);break;case 6:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].chorusGain=n/127);l.xgInfo(`Drum Chorus for key ${r}`,n);break;case 9:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].rxNoteOff=n===1);l.xgInfo(`Drum Note Off for key ${r}`,n===1?"ON":"OFF");break;case 10:for(let i of this.midiChannels)i.drumChannel&&(i.drumParams[r].rxNoteOn=n===1);l.xgInfo(`Drum Note On for key ${r}`,n===1?"ON":"OFF");break}return}if(A===6||A===7){this.callEvent("displayMessage",[...t]);return}l.xgFail("System Exclusive",t,"Unknown address")}else l.xgFail("System Exclusive",t)}function Yr(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:l.unsupported("System Exclusive",t,`Unknown manufacturer: ${A}`);break;case 126:case 127:xr.call(this,t,e);break;case 65:Hr.call(this,t,e);break;case 67:Or.call(this,t,e);break;case 245:if(t.length<2)return;for(this.portSelectChannelOffset=(t[1]-1)*16;this.midiChannels.length<=this.portSelectChannelOffset;){l.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 Ln=class{sendLevelToReverb=40/127;sendLevelToChorus=0;sendLevelToDelay=0;type=0;reset(){}process(t,e,A,s,a,n,r,i,o){let{sendLevelToReverb:I,sendLevelToChorus:h,sendLevelToDelay:C}=this;for(let B=0;B=1&&(ae-=1);let $=E+g*(1-O*z),W=Math.tan(Math.PI*$/J),V=Math.max(-.9999,Math.min(.9999,(1-W)/(1+W))),ee=b+T*q,Ae=L+T*K;for(let Ee=0;Ee1e3?(this.manualOffset=zA*1.5*Js,this.manual=t):(this.manualOffset=zA,this.manual=t*Js)}clearAllPass(){this.prevR=0,this.prevL=0;for(let t=0;t.5?-1:-Math.cos((k-.75)*Vs);break;case 2:q=Math.sin(Vs*k);break;case 3:q=1-2*k;break;case 4:q=2*k-1;break}(k+=H)>=1&&(k-=1),u+=(q-u)*Wr;let K=u*w,ae=(1-K)*.5*F,U=(1+K)*.5*F,T=J*B*ae,Q=O*B*U,b=i+m;A[b]+=T,s[b]+=Q;let L=(T+Q)*.5;a[m]+=L*I,n[m]+=L*h,r[m]+=L*C}this.currentPan=u,this.phase=k}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(){ft(this.lsCoeffs,this.lowGain,200,this.sampleRate,!0),ft(this.hsCoeffs,this.hiGain,4e3,this.sampleRate,!1)}},Zs=96,_r=.1,$r=.1,jr=27,ei=28,ti=-28,Ai=400,si=.62,ni=.005,Un=5,Ws=Un*.5,xn=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=Zs/127;coeffs={...qe};state={...be};hpCoeffs={...qe};hpState={...be};phase=0;lsCoeffs={...qe};hsCoeffs={...qe};lsState={...be};hsState={...be};sampleRate;lastFc=this.manual;attackCoeff;releaseCoeff;envelope=0;constructor(t){this.sampleRate=t,this.attackCoeff=Math.exp(-1/(_r*t)),this.releaseCoeff=Math.exp(-1/($r*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=Zs/127,this.phase=.2,this.lastFc=this.manual,Se(this.hsState),Se(this.lsState),Se(this.state),Se(this.hpState),this.updateShelves()}process(t,e,A,s,a,n,r,i,o){let{sendLevelToReverb:I,sendLevelToChorus:h,sendLevelToDelay:C,level:B,lsCoeffs:g,lsState:E,hsCoeffs:p,hsState:y,coeffs:D,state:R,sampleRate:S,filType:w,manual:F,pan:H,attackCoeff:k,releaseCoeff:u,hpState:m,hpCoeffs:J}=this,{phase:O,lastFc:q,envelope:K}=this,ae=this.rate/this.sampleRate,U=Math.pow(10,this.peak/127*ei/20),T=Math.pow(10,this.peak/127*ti/20),Q=this.polarity===0?-1:Un,b=this.depth/127*Q,L=this.sens/127,z=H+64|0,$=MA[z],W=bA[z];for(let V=0;VK?k*K+(1-k)*Ae:u*K+(1-u)*Ae;let Y=2*Math.abs(O-.5)*b;(O+=ae)>=1&&(O-=1);let re=Y>=Ws||Q<0?1:Math.sin(Y*Math.PI/(2*Ws)),ue=F*(1+L*K*jr),Le=Math.max(20,ue*(1+re*Y));q+=(Math.max(10,Le)-q)*ni,ai(D,q,U,S);let Ee=ee;w===1&&(ri(J,Ai,T,S),Ee=gt(Ee,J,m));let Re=gt(Ee,D,R)*B,Oe=Re*$,Bt=Re*W,Et=i+V;A[Et]+=Oe,s[Et]+=Bt,a[V]+=Re*I,n[V]+=Re*h,r[V]+=Re*C}this.phase=O,this.lastFc=q,this.envelope=K}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*si,A=Ct.manual(Math.floor(e)),s=Ct.manual(Math.ceil(e)),a=e-Math.floor(e);this.manual=A+(s-A)*a}updateShelves(){ft(this.lsCoeffs,this.lowGain,200,this.sampleRate,!0),ft(this.hsCoeffs,this.hiGain,4e3,this.sampleRate,!1)}};function ai(t,e,A,s){let a=2*Math.PI*e/s,n=Math.cos(a),r=Math.sin(a)/(2*A),i=1-n,o=i/2,I=o,h=1+r,C=-2*n,B=1-r;t.a0=1,t.a1=C/h,t.a2=B/h,t.b0=o/h,t.b1=i/h,t.b2=I/h}function ri(t,e,A,s){let a=2*Math.PI*e/s,n=Math.cos(a),r=Math.sin(a)/(2*A),i=(1+n)/2,o=-(1+n),I=i,h=1+r,C=-2*n,B=1-r;t.a0=1,t.a1=C/h,t.a2=B/h,t.b0=i/h,t.b1=o/h,t.b2=I/h}var zs=127,ii=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 Tn(t),this.autoWah=new xn(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,a,n,r,i,o){let{sendLevelToReverb:I,sendLevelToChorus:h,sendLevelToDelay:C,level:B}=this,{bufferPh:g,bufferAw:E}=this;this.bufferPh.fill(0),this.phaser.process(t,t,g,g,g,g,g,0,o),this.bufferAw.fill(0),this.autoWah.process(e,e,E,E,E,E,E,0,o);let p=this.phPan|0,y=MA[p],D=bA[p],R=this.awPan|0,S=MA[R],w=bA[R];for(let F=0;F=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,$s=Math.PI*2,oi=.01,gi=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={...qe};hsCoeffs={...qe};lsStateR={...be};lsStateL={...be};hsStateR={...be};hsStateL={...be};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,Se(this.hsStateR),Se(this.hsStateL),Se(this.lsStateR),Se(this.lsStateL),this.updateShelves()}process(t,e,A,s,a,n,r,i,o){let{sendLevelToReverb:I,sendLevelToChorus:h,sendLevelToDelay:C,level:B,lsCoeffs:g,lsStateL:E,lsStateR:p,hsCoeffs:y,hsStateR:D,hsStateL:R,modDepth:S,modWave:w}=this,F=this.modRate/this.sampleRate,{currentGain:H,phase:k}=this;for(let u=0;u.5?-1:-Math.cos((k-.75)*$s);break;case 2:O=Math.sin($s*k);break;case 3:O=1-2*k;break;case 4:O=2*k-1;break}(k+=F)>=1&&(k-=1);let q=1-(O/2+.5)*(S/127);H+=(q-H)*oi;let K=m*B*H,ae=J*B*H,U=i+u;A[U]+=K,s[U]+=ae;let T=(K+ae)*.5;a[u]+=T*I,n[u]+=T*h,r[u]+=T*C}this.phase=k,this.currentGain=H}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(){ft(this.lsCoeffs,this.lowGain,200,this.sampleRate,!0),ft(this.hsCoeffs,this.hiGain,4e3,this.sampleRate,!1)}},Ii=[Ln,qr,Tn,zr,xn,ii,gi],ci=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,a){let n=this.preDelay|0,r=this.inputDiffusion1,i=this.inputDiffusion2,o=this.decay,I=this.decayDiffusion1,h=this.decayDiffusion2,C=1-this.damping,B=this.excursionRate/this.sampleRate,g=this.excursionDepth*this.sampleRate/1e3,E=this.pDWrite;for(let p=0;p=r&&(s=0)}this.writeIndex=s}},hi=1.5,li=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 ci(t),this.delayLeft=new Zt(t),this.delayRight=new Zt(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,a){switch(this._character){default:this.dattorro.process(t,e,A,s,a);return;case 6:{let n;if(this._preLowpass>0){let o=this.delayPreLPF,I=this.preLPFz,h=this.preLPFa;for(let C=0;C0){let C=this.delayPreLPF,B=this.preLPFz,g=this.preLPFa;for(let E=0;E0,R=this.phase,S=this.write,w=this.preLPFz,F=this.preLPFa;for(let H=0;H=h&&(q-=h);let K=J-O,ae=i[O]*(1-K)+i[q]*K;i[S]=k+ae*y;let U=Math.max(1,Math.min(B+(1-u)*C,h)),T=S-U;T<0&&(T+=h),O=T|0,q=O+1,q>=h&&(q-=h),K=T-O;let Q=o[O]*(1-K)+o[q]*K,b=H+n;e[b]+=ae*g,A[b]+=Q*g;let L=(ae+Q)/2;s[H]+=L*E,a[H]+=L*p,o[S]=k+Q*y,++S>=h&&(S=0),(R+=I)>=1&&(R-=1)}this.write=S,this.phase=R,this.preLPFz=w}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}}},Ei=[{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}],di=1.66,fi=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 Zt(t),this.delayLeft=new Zt(t),this.delayRight=new Zt(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*di}_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 Ei)if(t>=A.start&&t0){let C=this.delayPreLPF,B=this.preLPFz,g=this.preLPFa;for(let E=0;E[t,!1]));midiParameters={...js};systemParameters={...cn};currentTime=0;defaultPreset;drumPreset;gainSmoothingFactor;panSmoothingFactor;eventCallbackHandler;missingPresetHandler;cachedVoices=new Map;lockMIDIParameter=ui.bind(this);setSystemParameter=Na.bind(this);systemExclusive=Yr.bind(this);reverbProcessor;chorusProcessor;delayProcessor;customChannelNumbers=!1;setMIDIParameter=Qi.bind(this);insertionFallback=new Ln;insertionProcessor=this.insertionFallback;insertionEffects=new Map;insertionActive=!1;portSelectChannelOffset=0;insertionParams=new Uint8Array(23).fill(255);lastPriorityAssignmentTime=0;eventQueue=[];sampleTime;constructor(t,e,A,s){this.eventCallbackHandler=t,this.missingPresetHandler=e,this.sampleRate=A,this.sampleTime=1/A,this.currentTime=s.initialTime,this.setSystemParameter("effectsEnabled",s.effectsEnabled),this.setSystemParameter("eventsEnabled",s.eventsEnabled),this.maxBufferSize=s.maxBufferSize,this.gainSmoothingFactor=mi*(44100/A),this.panSmoothingFactor=pi*(44100/A),Qs.initCache(this.sampleRate);let a=this.maxBufferSize;this.reverbProcessor=s.reverbProcessor??new li(A,a),this.chorusProcessor=s.chorusProcessor??new Bi(A,a),this.delayProcessor=s.delayProcessor??new fi(A,a),this.voiceBuffer=new Float32Array(a),this.insertionInputL=new Float32Array(a),this.insertionInputR=new Float32Array(a),this.reverbInput=new Float32Array(a),this.chorusInput=new Float32Array(a),this.delayInput=new Float32Array(a);for(let n of Ii)this.registerInsertionProcessor(n);this.resetInsertionParams(),this.allocateNewVoices(this.systemParameters.voiceCap)}_voiceCount=0;get voiceCount(){return this._voiceCount}controllerChange(t,e,A){if(this.customChannelNumbers){for(let s of this.midiChannels)s.midiParameters.rxChannel===t&&s.controllerChange(e,A);return}this.midiChannels[t+this.portSelectChannelOffset].controllerChange(e,A)}noteOn(t,e,A){if(this.customChannelNumbers){for(let s of this.midiChannels)s.midiParameters.rxChannel===t&&s.noteOn(e,A);return}this.midiChannels[t+this.portSelectChannelOffset].noteOn(e,A)}noteOff(t,e){if(this.customChannelNumbers){for(let A of this.midiChannels)A.midiParameters.rxChannel===t&&A.noteOff(e);return}this.midiChannels[t+this.portSelectChannelOffset].noteOff(e)}polyPressure(t,e,A){if(this.customChannelNumbers){for(let s of this.midiChannels)s.midiParameters.rxChannel===t&&s.polyPressure(e,A);return}this.midiChannels[t+this.portSelectChannelOffset].polyPressure(e,A)}channelPressure(t,e){if(this.customChannelNumbers){for(let A of this.midiChannels)A.midiParameters.rxChannel===t&&A.setMIDIParameter("pressure",e);return}this.midiChannels[t+this.portSelectChannelOffset].setMIDIParameter("pressure",e)}pitchWheel(t,e,A=-1){if(this.customChannelNumbers){for(let s of this.midiChannels)s.midiParameters.rxChannel===t&&s.pitchWheel(e,A);return}this.midiChannels[t+this.portSelectChannelOffset].pitchWheel(e,A)}programChange(t,e){if(this.customChannelNumbers){for(let A of this.midiChannels)A.midiParameters.rxChannel===t&&A.programChange(e);return}this.midiChannels[t+this.portSelectChannelOffset].programChange(e)}assignVoice(){for(let e=0;ethis.currentTime?(this.eventQueue.push({message:t,channelOffset:e,time:s}),this.eventQueue.sort((a,n)=>a.time-n.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],a=this.keyModifierManager.hasOverridePatch(t,e),n=s.preset;if(a){let r=this.keyModifierManager.getPatch(t,e);n=this.soundBankManager.getPreset(r,this.midiParameters.system)}return n?this.getVoicesForPreset(n,e,A):[]}createMIDIChannel(t){let e=new Nr(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.setMIDIParameter("system",t),this.setMIDIParameter("volume",1),this.setMIDIParameter("pan",0),this.setMIDIParameter("keyShift",0),this.setMIDIParameter("fineTune",0),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,a=0){if(this.eventQueue.length>0){let o=this.currentTime;for(;this.eventQueue[0]?.time<=o;){let I=this.eventQueue.shift();I&&this.processMessageInternal(I.message,I.channelOffset)}}s=Math.max(s,0);let n=a||t[0][0].length-s;if(n>this.maxBufferSize)throw new Error(`Requested ${n} 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;o=128&&A<240?(s=A&240,a=A&15):s=A,a+=e,s){case G.noteOn:{let n=t[2];n>0?this.noteOn(a,t[1],n):this.noteOff(a,t[1]);break}case G.noteOff:this.noteOff(a,t[1]);break;case G.pitchWheel:this.pitchWheel(a,t[2]<<7|t[1]);break;case G.controllerChange:this.controllerChange(a,t[1],t[2]);break;case G.programChange:this.programChange(a,t[1]);break;case G.polyPressure:this.polyPressure(a,t[1],t[2]);break;case G.channelPressure:this.channelPressure(a,t[1]);break;case G.systemExclusive:this.systemExclusive(new te(t.slice(1)),e);break;case G.reset:this.stopAllChannels(!1),this.reset();break;default:break}}assignVoicePriorities(){if(this.lastPriorityAssignmentTime===this.currentTime)return;l.info("%cPolyphony exceeded, stealing voices",d.warn),this.lastPriorityAssignmentTime=this.currentTime;let t=this.systemParameters.voiceCap;for(let e=0;e{l.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)=>{l.warn(`No preset found for ${je.toMIDIString(t)}! Did you forget to add a sound bank?`)};lockMIDIParameter(t,e){this.synthCore.lockMIDIParameter(t,e)}setSystemParameter(t,e){this.synthCore.setSystemParameter(t,e)}reset(){this.synthCore.reset()}applySnapshot(t){this.savedSnapshot=t,La.call(this.synthCore,t)}getSnapshot(){return Pa.call(this.synthCore)}setEmbeddedSoundBank(t,e){let A=eA.fromArrayBuffer(t);this.synthCore.soundBankManager.addSoundBank(A,rA,e);let s=this.synthCore.soundBankManager.priorityOrder;s.pop(),s.unshift(rA),this.synthCore.soundBankManager.priorityOrder=s,this.savedSnapshot!==void 0&&this.applySnapshot(this.savedSnapshot),l.info(`%cEmbedded sound bank set at offset %c${e}`,d.recognized,d.value)}clearEmbeddedSoundBank(){this.synthCore.soundBankManager.soundBankList.some(t=>t.id===rA)&&this.synthCore.soundBankManager.deleteSoundBank(rA)}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 GA=nn.ConsoleColors;var On="spessasynth-worklet-processor";function Yn(t,e){return{...e,...t}}var qn={skipToFirstNoteOn:!0,initialPlaybackRate:1};var ys=class extends RA{events=[];constructor(e){super(),super.copyFrom(e),this.events=[]}},LA=class t extends Mt{tracks;timeline=[];embeddedSoundBank=void 0;embeddedSoundBankSize;constructor(e){super(),super.copyMetadataFrom(e),this.tracks=e.tracks.map(A=>new ys(A)),this.embeddedSoundBankSize=e instanceof t?e.embeddedSoundBankSize:e?.embeddedSoundBank?.byteLength}};var PA={shuffleOn:1,shuffleOff:2,index:3};var Jn=-1;var Kn=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 Hn(e,A),this.eventsEnabled=A.eventsEnabled??!1,this.post=s,this.synthesizer.onEventCall=a=>{if(a.type==="channelAdded"){let n=this.synthesizer.midiChannels.length;for(let r=this.voiceCounts.length;r{if(this.eventsEnabled){if(s.type==="songListChange"){let n=s.data.newSongList.map(r=>new LA(r));this.post({type:"sequencerReturn",data:{type:s.type,data:{newSongList:n,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)){l.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===Jn?this.synthesizer.stopAllChannels(e.data===1):s?.stopAllNotes(e.data===1);break}case"addNewChannel":{this.synthesizer.createMIDIChannel();break}case"lockGlobalMIDIParameter":{this.synthesizer.lockMIDIParameter(e.data.parameter,e.data.isLocked);break}case"setGlobalSystemParameter":{this.synthesizer.setSystemParameter(e.data.parameter,e.data.value);break}case"lockChannelMIDIParameter":{s?.lockMIDIParameter(e.data.parameter,e.data.isLocked);break}case"setChannelSystemParameter":{s?.setSystemParameter(e.data.parameter,e.data.value);break}case"setDrums":{s?.setDrums(e.data);break}case"lockController":{s?.lockController(e.data.controller,e.data.isLocked);break}case"sequencerSpecific":{let a=this.sequencers[e.data.id];if(!a)return;let n=e.data;switch(n.type){default:break;case"loadNewSongList":{try{let i=n.data.map(o=>"duration"in o?Mt.copyFrom(o):Mt.fromArrayBuffer(o.binary,o.fileName));a.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":{a.pause();break}case"play":{a.play();break}case"setTime":{a.currentTime=n.data;break}case"changeMIDIMessageSending":{a.externalMIDIPlayback=n.data;break}case"setPlaybackRate":{a.playbackRate=n.data;break}case"setLoopCount":{a.loopCount=n.data;break}case"changeSong":{switch(n.data.changeType){case PA.shuffleOff:{a.shuffleMode=!1;break}case PA.shuffleOn:{a.shuffleMode=!0;break}case PA.index:{n.data.data!==void 0&&(a.songIndex=n.data.data);break}}break}case"getMIDI":{if(!a.midiData)throw new Error("No MIDI is loaded!");this.post({type:"sequencerReturn",data:{type:"getMIDI",data:a.midiData,id:e.data.id},currentTime:this.synthesizer.currentTime});break}case"setSkipToFirstNote":{a.skipToFirstNoteOn=n.data;break}}break}case"soundBankManager":{try{let a=this.synthesizer.soundBankManager,n=e.data,r;switch(n.type){case"addSoundBank":{r=eA.fromArrayBuffer(n.data.soundBankBuffer),a.addSoundBank(r,n.data.id,n.data.bankOffset),this.postReady("soundBankManager",null);break}case"deleteSoundBank":{a.deleteSoundBank(n.data),this.postReady("soundBankManager",null);break}case"rearrangeSoundBanks":a.priorityOrder=n.data,this.postReady("soundBankManager",null)}}catch(a){this.post({type:"soundBankError",data:a,currentTime:this.synthesizer.currentTime})}break}case"keyModifierManager":{let a=e.data,n=this.synthesizer.keyModifierManager;switch(a.type){default:return;case"addMapping":{n.addMapping(a.data.channel,a.data.midiNote,a.data.mapping);break}case"clearMappings":{n.clearMappings();break}case"deleteMapping":n.deleteMapping(a.data.channel,a.data.midiNote)}break}case"requestSynthesizerSnapshot":{let a=this.synthesizer.getSnapshot();this.postReady("synthesizerSnapshot",a);break}case"requestNewSequencer":{this.createNewSequencer();break}case"setLogLevel":{l.setLogLevel(e.data.enableInfo,e.data.enableWarning,e.data.enableGroup);break}case"destroyWorklet":{this.alive=!1,this.synthesizer.destroySynthProcessor(),this.destroy();break}default:{l.warn("Unrecognized event!",e);break}}}};var TA=class extends NA{alive=!0;oneOutputMode;port;constructor(e,A,s,a){super(e,{effectsEnabled:!a.oneOutput,eventsEnabled:a?.eventsEnabled,initialTime:A},(n,r)=>{s.postMessage(n,r)}),this.port=s,this.oneOutputMode=a.oneOutput,this.synthesizer.processorInitialized.then(()=>{this.port.onmessage=n=>this.handleMessage(n.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 I=0;I<32;I+=2)o.push([i[I],i[I+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>Kn){for(let i=0;i