spessasynth_lib
Version:
MIDI and SoundFont2/DLS library for the browsers with no compromises
1 lines • 378 kB
JavaScript
function zA(A,e,t=0){let s=0;for(let n=0;n<e;n++)s=s<<8|A[t+n];return s>>>0}function JA(A,e){let t=zA(A,e,A.currentIndex);return A.currentIndex+=e,t}function Ct(A,e){let t=new Array(e).fill(0);for(let s=e-1;s>=0;s--)t[s]=A&255,A>>=8;return t}function X(A,e){let t=Dn(A,e,A.currentIndex);return A.currentIndex+=e,t}function Dn(A,e,t=0){let s=0;for(let n=0;n<e;n++)s|=A[t+n]<<n*8;return s>>>0}function at(A,e,t){for(let s=0;s<t;s++)A[A.currentIndex++]=e>>s*8&255}function te(A,e){A[A.currentIndex++]=e&255,A[A.currentIndex++]=e>>8}function ge(A,e){at(A,e,4)}function Rs(A,e){let t=e<<8|A;return t>32767?t-65536:t}function ma(A){return A>127?A-256:A}var _=class extends Uint8Array{currentIndex=0;slice(A,e){let t=super.slice(A,e);return t.currentIndex=0,t}};function oA(A,e=A.length,t=0){let s="";for(let n=0;n<e;n++){let a=A[t+n];if(a===0)return s;s+=String.fromCharCode(a)}return s}function ue(A,e){let t=A.currentIndex;return A.currentIndex+=e,oA(A,e,t)}function BA(A,e=!1,t=!1){let s=A.length;e&&s++,t&&s%2!==0&&s++;let n=new _(s);return Ge(n,A),n}function Ge(A,e,t=0){t>0&&e.length>t&&(e=e.slice(0,t));for(let s=0;s<e.length;s++)A[A.currentIndex++]=e.charCodeAt(s);if(t>e.length)for(let s=0;s<t-e.length;s++)A[A.currentIndex++]=0;return A}function pe(A){let e=0;for(;A;){let t=A[A.currentIndex++];if(e=e<<7|t&127,t>>7!==1)break}return e}function $t(A){let e=[A&127];for(A>>=7;A>0;)e.unshift(A&127|128),A>>=7;return e}function ls(A){A=Math.floor(A);let e=Math.floor(A/60),t=Math.round(A-e*60);return{minutes:e,seconds:t,time:`${e.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}`}}function Pt(A){let e="";for(let t of A){let s=t.toString(16).padStart(2,"0").toUpperCase();e+=s,e+=" "}return e}var C={warn:"color: orange;",unrecognized:"color: red;",info:"color: aqua;",recognized:"color: lime",value:"color: yellow; background-color: black;"},wn;(()=>{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]),n=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]),a=new A([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),r=function(S,k){for(var p=new e(31),P=0;P<31;++P)p[P]=k+=1<<S[P-1];for(var K=new t(p[30]),P=1;P<30;++P)for(var Ce=p[P];Ce<p[P+1];++Ce)K[Ce]=Ce-p[P]<<5|P;return{b:p,r:K}},o=r(s,2),i=o.b,g=o.r;i[28]=258,g[258]=28;var c=r(n,0),l=c.b;c.r;var B=new e(32768);for(f=0;f<32768;++f)h=(f&43690)>>1|(f&21845)<<1,h=(h&52428)>>2|(h&13107)<<2,h=(h&61680)>>4|(h&3855)<<4,B[f]=((h&65280)>>8|(h&255)<<8)>>1;var h,f,E=function(S,k,p){for(var P=S.length,K=0,Ce=new e(k);K<P;++K)S[K]&&++Ce[S[K]-1];var be=new e(k);for(K=1;K<k;++K)be[K]=be[K-1]+Ce[K-1]<<1;var Be;if(p){Be=new e(1<<k);var ae=15-k;for(K=0;K<P;++K)if(S[K])for(var he=K<<4|S[K],j=k-S[K],Y=be[S[K]-1]++<<j,ne=Y|(1<<j)-1;Y<=ne;++Y)Be[B[Y]>>ae]=he}else for(Be=new e(P),K=0;K<P;++K)S[K]&&(Be[K]=B[be[S[K]-1]++]>>15-S[K]);return Be},m=new A(288);for(f=0;f<144;++f)m[f]=8;var f;for(f=144;f<256;++f)m[f]=9;var f;for(f=256;f<280;++f)m[f]=7;var f;for(f=280;f<288;++f)m[f]=8;var f,D=new A(32);for(f=0;f<32;++f)D[f]=5;var f,O=E(m,9,1),R=E(D,5,1),Q=function(S){for(var k=S[0],p=1;p<S.length;++p)S[p]>k&&(k=S[p]);return k},T=function(S,k,p){var P=k/8|0;return(S[P]|S[P+1]<<8)>>(k&7)&p},U=function(S,k){var p=k/8|0;return(S[p]|S[p+1]<<8|S[p+2]<<16)>>(k&7)},x=function(S){return(S+7)/8|0},V=function(S,k,p){return(k==null||k<0)&&(k=0),(p==null||p>S.length)&&(p=S.length),new A(S.subarray(k,p))},J=["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"],L=function(S,k,p){var P=new Error(k||J[S]);if(P.code=S,Error.captureStackTrace&&Error.captureStackTrace(P,L),!p)throw P;return P},H=function(S,k,p,P){var K=S.length,Ce=P?P.length:0;if(!K||k.f&&!k.l)return p||new A(0);var be=!p,Be=be||k.i!=2,ae=k.i;be&&(p=new A(K*3));var he=function(Ee){var le=p.length;if(Ee>le){var Ye=new A(Math.max(le*2,Ee));Ye.set(p),p=Ye}},j=k.f||0,Y=k.p||0,ne=k.b||0,fe=k.l,Me=k.d,Ie=k.m,ve=k.n,sA=K*8;do{if(!fe){j=T(S,Y,1);var pA=T(S,Y+1,3);if(Y+=3,pA)if(pA==1)fe=O,Me=R,Ie=9,ve=5;else if(pA==2){var yA=T(S,Y,31)+257,gt=T(S,Y+10,15)+4,It=yA+T(S,Y+5,31)+1;Y+=14;for(var Ze=new A(It),bA=new A(19),Le=0;Le<gt;++Le)bA[a[Le]]=T(S,Y+Le*3,7);Y+=gt*3;for(var $A=Q(bA),TA=(1<<$A)-1,_t=E(bA,$A,1),Le=0;Le<It;){var jA=_t[T(S,Y,TA)];Y+=jA&15;var eA=jA>>4;if(eA<16)Ze[Le++]=eA;else{var EA=0,SA=0;for(eA==16?(SA=3+T(S,Y,3),Y+=2,EA=Ze[Le-1]):eA==17?(SA=3+T(S,Y,7),Y+=3):eA==18&&(SA=11+T(S,Y,127),Y+=7);SA--;)Ze[Le++]=EA}}var UA=Ze.subarray(0,yA),We=Ze.subarray(yA);Ie=Q(UA),ve=Q(We),fe=E(UA,Ie,1),Me=E(We,ve,1)}else L(1);else{var eA=x(Y)+4,RA=S[eA-4]|S[eA-3]<<8,nA=eA+RA;if(nA>K){ae&&L(0);break}Be&&he(ne+RA),p.set(S.subarray(eA,nA),ne),k.b=ne+=RA,k.p=Y=nA*8,k.f=j;continue}if(Y>sA){ae&&L(0);break}}Be&&he(ne+131072);for(var b=(1<<Ie)-1,w=(1<<ve)-1,F=Y;;F=Y){var EA=fe[U(S,Y)&b],W=EA>>4;if(Y+=EA&15,Y>sA){ae&&L(0);break}if(EA||L(2),W<256)p[ne++]=W;else if(W==256){F=Y,fe=null;break}else{var ie=W-254;if(W>264){var Le=W-257,ce=s[Le];ie=T(S,Y,(1<<ce)-1)+i[Le],Y+=ce}var me=Me[U(S,Y)&w],$=me>>4;me||L(3),Y+=me&15;var We=l[$];if($>3){var ce=n[$];We+=U(S,Y)&(1<<ce)-1,Y+=ce}if(Y>sA){ae&&L(0);break}Be&&he(ne+131072);var He=ne+ie;if(ne<We){var Re=Ce-We,re=Math.min(We,He);for(Re+ne<0&&L(3);ne<re;++ne)p[ne]=P[Re+ne]}for(;ne<He;++ne)p[ne]=p[ne-We]}}k.l=fe,k.p=F,k.b=ne,k.f=j,fe&&(j=1,k.m=Ie,k.d=Me,k.n=ve)}while(!j);return ne!=p.length&&be?V(p,0,ne):p.subarray(0,ne)},q=new A(0);function u(S,k){return H(S,{i:2},k&&k.out,k&&k.dictionary)}var v=typeof TextDecoder<"u"&&new TextDecoder;try{v.decode(q,{stream:!0})}catch{}wn=u})();var bn=wn,Rn=!1,Fn=!0,xt=!1;function Gn(A,e,t){Rn=A,Fn=e,xt=t}function y(...A){Rn&&console.info(...A)}function se(...A){Fn&&console.warn(...A)}function je(...A){xt&&console.group(...A)}function Je(...A){xt&&console.groupCollapsed(...A)}function ee(){xt&&console.groupEnd()}var N=class Mn{header;size;data;constructor(e,t,s){this.header=e,this.size=t,this.data=s}static read(e,t=!0,s=!1){let n=ue(e,4),a=X(e,4);n===""&&(a=0);let r=t?e.slice(e.currentIndex,e.currentIndex+a):new _(0);return(t||s)&&(e.currentIndex+=a,a%2!==0&&e.currentIndex++),new Mn(n,a,r)}static write(e,t,s=!1,n=!1){if(e.length!==4)throw new Error(`Invalid header length: ${e}`);let a=8,r=e,o=t.length;s&&o++;let i=o;n&&(a+=4,i+=4,r="LIST");let g=a+o;g%2!==0&&g++;let c=new _(g);return Ge(c,r),ge(c,i),n&&Ge(c,e),c.set(t,a),c}static writeParts(e,t,s=!1){let n=8,a=e,r=t.reduce((c,l)=>l.length+c,0),o=r;s&&(n+=4,o+=4,a="LIST");let i=n+r;i%2!==0&&i++;let g=new _(i);Ge(g,a),ge(g,o),s&&Ge(g,e);for(let c of t)g.set(c,n),n+=c.length;return g}static findListType(e,t){return e.find(s=>s.header!=="LIST"?!1:(s.data.currentIndex=4,oA(s.data,4)===t))}};function Fs(A,e){return{...e,...A}}var mA={consoleColors:C,SpessaSynthInfo:y,SpessaSynthWarn:se,SpessaSynthGroupCollapsed:Je,SpessaSynthGroup:je,SpessaSynthGroupEnd:ee,readBytesAsUintBigEndian:zA,readLittleEndian:X,readBytesAsString:ue,readVariableLengthQuantity:pe,inflateSync:bn};var M={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},d={bankSelect:0,modulationWheel:1,breathController:2,undefinedCC3:3,footController:4,portamentoTime:5,dataEntryMSB:6,mainVolume:7,balance:8,undefinedCC9:9,pan:10,expressionController: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,expressionControllerLSB: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},gA=class{ticks;statusByte;data;constructor(A,e,t){this.ticks=A,this.statusByte=e,this.data=t}};function pa(A){let e=A&240,t=A&15,s=t;switch(e){case 128:case 144:case 160:case 176:case 192:case 208:case 224:break;case 240:switch(t){case 0:s=-3;break;case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:case 13:case 14:s=-1;break;case 15:s=-2;break}break;default:s=-1}return s}function Gs(A){let e=A&240,t=A&15,s=-1,n=A;return e>=128&&e<=224&&(s=t,n=e),{status:n,channel:s}}var ya={8:2,9:2,10:2,11:2,12:1,13:1,14:2},_s=(A,e)=>{for(let t=0;t<A.length;t++)e.push(A.charCodeAt(t))};function Sa(A){if(!A.tracks)throw new Error("MIDI has no tracks!");let e=[];for(let s of A.tracks){let n=[],a=0,r;for(let o of s.events){let i=Math.max(0,o.ticks-a);if(o.statusByte===M.endOfTrack){a+=i;continue}let g;o.statusByte<=M.sequenceSpecific?(g=[255,o.statusByte,...$t(o.data.length),...o.data],r=void 0):o.statusByte===M.systemExclusive?(g=[240,...$t(o.data.length),...o.data],r=void 0):(g=[],r!==o.statusByte&&(r=o.statusByte,g.push(o.statusByte)),g.push(...o.data)),n.push(...$t(i),...g),a+=i}n.push(0,255,M.endOfTrack,0),e.push(new Uint8Array(n))}let t=[];_s("MThd",t),t.push(...Ct(6,4),0,A.format,...Ct(A.tracks.length,2),...Ct(A.timeDivision,2));for(let s of e)_s("MTrk",t),t.push(...Ct(s.length,4),...s);return new Uint8Array(t).buffer}var Ht=-1,Bt=`SPESSASYNTH_EMBEDDED_BANK_${Math.random()}_DO_NOT_DELETE`,ka=32767,Da={time:0},wa=.03,ba=.07,yt=1/Math.cos(Math.PI/4)**2,$s=121,ke=class{static getDefaultBank(A){return A==="gm2"?$s: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 isXGDrums(A){return A===120||A===127}static isValidXGMSB(A){return this.isXGDrums(A)||A===64||A===$s}static isSystemXG(A){return A==="gm2"||A==="xg"}static addBankOffset(A,e,t=!0){return this.isXGDrums(A)&&t?A:Math.min(A+e,127)}static subtractBankOffset(A,e,t=!0){return this.isXGDrums(A)&&t?A:Math.max(0,A-e)}};function Ms(A){return A.data[0]===67&&A.data[2]===76&&A.data[5]===126&&A.data[6]===0}function vn(A){return A.data[0]===65&&A.data[2]===66&&A.data[3]===18&&A.data[4]===64&&(A.data[5]&16)!==0&&A.data[6]===21}function vs(A){return A.data[0]===65&&A.data[2]===66&&A.data[5]===0&&A.data[6]===127}function Ls(A){return A.data[0]===126&&A.data[2]===9&&A.data[3]===1}function Ns(A){return A.data[0]===126&&A.data[2]===9&&A.data[3]===3}function Ra(A){return A[0]===65&&A[2]===66&&A[3]===18&&A[4]===65||A[0]===67&&A[2]===76&&A[3]>>4===3}function Fa(A){return A[0]===67&&A[2]===76&&A[3]===8&&(A[5]===3||A[5]===1||A[5]===2)?A[4]:A[0]===65&&A[2]===66&&A[3]===18&&A[4]===64&&(A[5]&240)===16&&A[6]===0?KA(A[5]&15):-1}function Ga(A){return A[0]===65&&A[2]===66&&A[3]===18&&A[4]===64&&A[5]===1&&A[6]>=48&&A[6]<=55}function Ma(A){return A[0]===65&&A[2]===66&&A[3]===18&&A[4]===64&&A[5]===1&&A[6]>=56&&A[6]<=64}function va(A){return A[0]===65&&A[2]===66&&A[3]===18&&A[4]===64&&A[5]===1&&A[6]>=80&&A[6]<=90}function La(A){return A[0]===65&&A[2]===66&&A[3]===18&&A[4]===64&&(A[5]===3||A[5]>>4===4&&A[6]===34)}function KA(A){return[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][A%16]}function Ts(A){return[1,2,3,4,5,6,7,8,9,0,10,11,12,13,14,15][A%16]}function Ln(A){return new gA(A,M.systemExclusive,new _([65,16,66,18,64,0,127,0,65,247]))}var IA=class Nn{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:");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 toNamedMIDIString(e){return`${Nn.toMIDIString(e)} ${e.name}`}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 fromNamedMIDIString(e){let t=e.indexOf(" ");if(t===-1)throw new Error(`Invalid named MIDI string: ${e}`);let s=this.fromMIDIString(e.slice(0,Math.max(0,t))),n=e.slice(Math.max(0,t+1));return{...s,name:n}}static sorter(e,t){return e.program!==t.program?e.program-t.program:e.isGMGSDrum&&!t.isGMGSDrum?1:!e.isGMGSDrum&&t.isGMGSDrum?-1:e.bankMSB!==t.bankMSB?e.bankMSB-t.bankMSB:e.bankLSB-t.bankLSB}},Na="Created using SpessaSynth";function Ta(A,e,t){let s="gm",n=[],a=new Array(A.tracks.length).fill(0),r=16+Math.max(...A.portChannelOffsetMap),o=[];for(let i=0;i<r;i++)o.push({program:0,drums:i%16===9,lastBank:void 0,lastBankLSB:void 0,hasBankSelect:!1});A.iterate((i,g)=>{let c=A.portChannelOffsetMap[a[g]];if(i.statusByte===M.midiPort){a[g]=i.data[0];return}let l=i.statusByte&240;if(l!==M.controllerChange&&l!==M.programChange&&l!==M.systemExclusive)return;if(l===M.systemExclusive){if(!vn(i)){Ms(i)?s="xg":vs(i)?s="gs":Ls(i)?(s="gm",n.push({tNum:g,e:i})):Ns(i)&&(s="gm2");return}let m=KA(i.data[5]&15)+c;o[m].drums=!!(i.data[7]>0&&i.data[5]>>4);return}let B=(i.statusByte&15)+c,h=o[B];if(l===M.programChange){let m={program:i.data[0],bankLSB:h.lastBankLSB?.data?.[1]??0,bankMSB:ke.subtractBankOffset(h.lastBank?.data?.[1]??0,A.bankOffset),isGMGSDrum:h.drums},D=t.getPreset(m,s);if(y(`%cInput patch: %c${IA.toMIDIString(m)}%c. Channel %c${B}%c. Changing patch to ${D.toString()}.`,C.info,C.unrecognized,C.info,C.recognized,C.info),i.data[0]=D.program,D.isGMGSDrum&&ke.isSystemXG(s)||h.lastBank===void 0||(h.lastBank.data[1]=ke.addBankOffset(D.bankMSB,e,D.isXGDrums),h.lastBankLSB===void 0))return;h.lastBankLSB.data[1]=D.bankLSB;return}let E=i.data[0]===d.bankSelectLSB;i.data[0]!==d.bankSelect&&!E||(h.hasBankSelect=!0,E?h.lastBankLSB=i:h.lastBank=i)});for(let[i,g]of o.entries()){if(g.hasBankSelect)continue;let c=i%16,l=M.programChange|c,B=Math.floor(i/16)*16,h=A.portChannelOffsetMap.indexOf(B),E=A.tracks.find(R=>R.port===h&&R.channels.has(c));if(E===void 0)continue;let m=E.events.findIndex(R=>R.statusByte===l);if(m===-1){let R=E.events.findIndex(U=>U.statusByte>128&&U.statusByte<240&&(U.statusByte&15)===c);if(R===-1)continue;let Q=E.events[R].ticks,T=t.getPreset({bankMSB:0,bankLSB:0,program:0,isGMGSDrum:!1},s).program;E.addEvents(R,new gA(Q,M.programChange|c,new _([T]))),m=R}y(`%cAdding bank select for %c${i}`,C.info,C.recognized);let D=E.events[m].ticks,f=t.getPreset({bankLSB:0,bankMSB:0,program:g.program,isGMGSDrum:g.drums},s),O=ke.addBankOffset(f.bankMSB,e,f.isXGDrums);E.addEvents(m,new gA(D,M.controllerChange|c,new _([d.bankSelect,O])))}if(s==="gm"&&!ke.isSystemXG(s)){for(let g of n){let c=A.tracks[g.tNum];c.deleteEvent(c.events.indexOf(g.e))}let i=0;A.tracks[0].events[0].statusByte===M.trackName&&i++,A.tracks[0].addEvents(i,Ln(0))}}var js={bankOffset:0,metadata:{},correctBankOffset:!0,soundBank:void 0};function Ua(A,e,t){let s=t.metadata;if(je("%cWriting the RMIDI File...",C.info),y("metadata",s),y("Initial bank offset",A.bankOffset),t.correctBankOffset){if(!t.soundBank)throw new Error("Sound bank must be provided if correcting bank offset.");Ta(A,t.bankOffset,t.soundBank)}let n=new _(A.writeMIDI());s.name??=A.getName(),s.creationDate??=new Date,s.copyright??=Na,s.software??="SpessaSynth",Object.entries(s).forEach(i=>{let g=i;g[1]&&A.setRMIDInfo(g[0],g[1])});let a=[],r=(i,g)=>{a.push(N.write(i,g))};for(let i of Object.entries(A.rmidiInfo)){let g=i[0],c=i[1];switch(g){case"album":r("IALB",c),r("IPRD",c);break;case"software":r("ISFT",c);break;case"infoEncoding":r("IENC",c);break;case"creationDate":r("ICRD",c);break;case"picture":r("IPIC",c);break;case"name":r("INAM",c);break;case"artist":r("IART",c);break;case"genre":r("IGNR",c);break;case"copyright":r("ICOP",c);break;case"comment":r("ICMT",c);break;case"engineer":r("IENG",c);break;case"subject":r("ISBJ",c);break;case"midiEncoding":r("MENC",c);break}}let o=new _(2);return at(o,t.bankOffset,2),a.push(N.write("DBNK",o)),y("%cFinished!",C.info),ee(),N.writeParts("RIFF",[BA("RMID"),N.write("data",n),N.writeParts("INFO",a,!0),new _(e)]).buffer}function Pa(A,e){Je("%cSearching for all used programs and keys...",C.info);let t=16+Math.max(...A.portChannelOffsetMap),s=[],n="gs";for(let o=0;o<t;o++){let i=o%16===9;s.push({preset:e.getPreset({bankLSB:0,bankMSB:0,isGMGSDrum:i,program:0},n),bankMSB:0,bankLSB:0,isDrum:i})}let a=new Map,r=A.tracks.map(o=>o.port);A.iterate((o,i)=>{if(o.statusByte===M.midiPort&&A.tracks[i].channels.size>0){let l=o.data[0];A.portChannelOffsetMap[l]===void 0&&(se(`Invalid port ${l} on track ${i}. (No offset found in the MIDI map.`),l=0),r[i]=l;return}let g=o.statusByte&240;if(g!==M.noteOn&&g!==M.controllerChange&&g!==M.programChange&&g!==M.systemExclusive)return;let c=s[(o.statusByte&15)+A.portChannelOffsetMap[r[i]]||0];switch(g){case M.programChange:c.preset=e.getPreset({bankMSB:c.bankMSB,bankLSB:c.bankLSB,program:o.data[0],isGMGSDrum:c.isDrum},n);break;case M.controllerChange:switch(o.data[0]){default:return;case d.bankSelectLSB:c.bankLSB=o.data[1];break;case d.bankSelect:c.bankMSB=o.data[1]}break;case M.noteOn:{if(o.data[1]===0||!c.preset)return;let l=a.get(c.preset);l||(l=new Set,a.set(c.preset,l)),l.add(`${o.data[0]}-${o.data[1]}`);break}case M.systemExclusive:{if(!vn(o)){Ms(o)?(n="xg",y("%cXG on detected!",C.recognized)):Ns(o)?(n="gm2",y("%cGM2 on detected!",C.recognized)):Ls(o)?(n="gm",y("%cGM on detected!",C.recognized)):vs(o)&&(n="gs",y("%cGS on detected!",C.recognized));return}let l=KA(o.data[5]&15)+A.portChannelOffsetMap[r[i]],B=!!(o.data[7]>0&&o.data[5]>>4);c=s[l],c.isDrum=B}break}});for(let[o,i]of a.entries())i.size===0&&(y(`%cDetected change but no keys for %c${o.name}`,C.info,C.value),a.delete(o));return ee(),a}var xa=A=>(A.data=new _(A.data.buffer),6e7/zA(A.data,3));function Ha(A,e=0){let t=[],s=A.tracks.map(c=>c.events).flat();s.sort((c,l)=>c.ticks-l.ticks);for(let c=0;c<16;c++)t.push([]);let n=0,a=60/(120*A.timeDivision),r=0,o=0,i=[];for(let c=0;c<16;c++)i.push([]);let g=(c,l)=>{let B=i[l].findIndex(E=>E.midiNote===c),h=i[l][B];if(h){let E=n-h.start;h.length=E,l===9&&(h.length=Math.max(E,e)),i[l].splice(B,1)}o--};for(;r<s.length;){let c=s[r],l=c.statusByte>>4,B=c.statusByte&15;if(l===8)g(c.data[0],B);else if(l===9)if(c.data[1]===0)g(c.data[0],B);else{g(c.data[0],B);let h={midiNote:c.data[0],start:n,length:-1,velocity:c.data[1]/127};t[B].push(h),i[B].push(h),o++}else c.statusByte===81&&(a=60/(xa(c)*A.timeDivision));if(++r>=s.length)break;n+=a*(s[r].ticks-c.ticks)}if(o>0)for(let[c,l]of i.entries())for(let B of l){let h=n-B.start;B.length=h,c===9&&(B.length=Math.max(h,e))}return t}var Oa={linear:0,nearestNeighbor:1,hermite:2},Ve={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},oe={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4,channelKeyShift:5,sf2NPRNGeneratorLSB:6},Ya={character:49,preLowpass:50,level:51,time:52,delayFeedback:53,preDelayTime:55},qa={preLowpass:57,level:58,feedback:59,delay:60,rate:61,depth:62,sendLevelToReverb:63,sendLevelToDelay:64},Ja={preLowpass:81,timeCenter:82,timeRatioLeft:83,timeRatioRight:84,levelCenter:85,levelLeft:86,levelRight:87,level:88,feedback:89,sendLevelToReverb:90};function HA(A,e,t,s){return new gA(s,M.controllerChange|A%16,new _([e,t]))}function de(A,e,t,s,n){let a=128-(e+t+s+n.reduce((r,o)=>r+o,0))%128&127;return new gA(A,M.systemExclusive,new Uint8Array([65,16,66,18,e,t,s,...n,a,247]))}function Ka(A,e){return de(e,40,16|Ts(A),21,[1])}function Va(A,{programChanges:e=[],controllerChanges:t=[],channelsToClear:s=[],channelsToTranspose:n=[],clearDrumParams:a=!1,reverbParams:r,chorusParams:o,delayParams:i,insertionParams:g}){Je("%cApplying changes to the MIDI file...",C.info),y("Desired program changes:",e),y("Desired CC changes:",t),y("Desired channels to clear:",s),y("Desired channels to transpose:",n),y("Desired reverb parameters",r),y("Desired chorus parameters",o),y("Desired delay parameters",i),y("Desired insertion parameters",g);let c=new Set;for(let u of e)c.add(u.channel);let l="gs",B=!1,h=A.tracks.map(u=>u.port),E={},m=0,D=(u,v)=>{A.tracks[u].channels.size!==0&&(m===0&&(m+=16,E[v]=0),E[v]===void 0&&(E[v]=m,m+=16),h[u]=v)};for(let[u,v]of A.tracks.entries())D(u,v.port);let f=m,O=new Array(f).fill(!0),R=new Array(f).fill(0),Q=new Array(f).fill(0);for(let u of n){let v=Math.trunc(u.keyShift),S=u.keyShift-v;R[u.channel]=v,Q[u.channel]=S}let T=-1,U=0,x=-1,V=0,J=!1;A.iterate((u,v,S)=>{let k=A.tracks[v],p=S[v],P=()=>{k.deleteEvent(p),S[v]--},K=(he,j=0)=>{k.addEvents(p+j,he),S[v]++},Ce=E[h[v]]||0;if(u.statusByte===M.midiPort){D(v,u.data[0]);return}if(u.statusByte<=M.sequenceSpecific&&u.statusByte>=M.sequenceNumber)return;let be=u.statusByte&240,Be=u.statusByte&15,ae=Be+Ce;if(u.statusByte!==M.systemExclusive&&s.includes(ae)){P();return}switch(be){case M.noteOn:if(O[ae]){O[ae]=!1;for(let j of t.filter(Y=>Y.channel===ae))K(HA(Be,j.controllerNumber,j.controllerValue,u.ticks));let he=Q[ae];if(he!==0){let j=he*64+64,Y=HA(Be,d.registeredParameterMSB,0,u.ticks),ne=HA(Be,d.registeredParameterLSB,1,u.ticks),fe=HA(ae,d.dataEntryMSB,j,u.ticks);K(HA(Be,d.dataEntryLSB,0,u.ticks)),K(fe),K(ne),K(Y)}if(c.has(ae)){let j=e.find(Ie=>Ie.channel===ae);if(!j)return;y(`%cSetting %c${j.channel}%c to %c${IA.toMIDIString(j)}%c. Track num: %c${v}`,C.info,C.recognized,C.info,C.recognized,C.info,C.recognized);let Y=j.bankMSB,ne=j.bankLSB,fe=j.program;K(new gA(u.ticks,M.programChange|Be,new _([fe])));let Me=(Ie,ve)=>{K(HA(Be,Ie?d.bankSelectLSB:d.bankSelect,ve,u.ticks))};ke.isSystemXG(l)&&j.isGMGSDrum&&(y(`%cAdding XG Drum change on track %c${v}`,C.recognized,C.value),Y=ke.getDrumBank(l),ne=0),Me(!1,Y),Me(!0,ne),j.isGMGSDrum&&!ke.isSystemXG(l)&&Be!==9&&(y(`%cAdding GS Drum change on track %c${v}`,C.recognized,C.value),K(Ka(Be,u.ticks)))}}u.data[0]+=R[ae];break;case M.noteOff:u.data[0]+=R[ae];break;case M.programChange:if(c.has(ae)){P();return}break;case M.controllerChange:{let he=u.data[0];if(t.find(j=>j.channel===ae&&he===j.controllerNumber)!==void 0){P();return}switch(he){case d.bankSelect:case d.bankSelectLSB:c.has(ae)&&P();return;case d.registeredParameterLSB:case d.registeredParameterMSB:J=!1;return;case d.nonRegisteredParameterMSB:T=S[v],U=v,J=!0;return;case d.nonRegisteredParameterLSB:x=S[v],V=v,J=!0;return;case d.dataEntryMSB:if(x&&T&&J&&a){let j=A.tracks[U].events[T].data[1];if(j>=24&&j<=31){P();let Y=A.tracks[V],ne=A.tracks[U];Y.deleteEvent(x),S[V]--,ne.deleteEvent(T),S[U]--}}return;default:return}}case M.systemExclusive:{if(Ms(u)){y("%cXG system on detected",C.info),l="xg",B=!0;return}if(Ns(u)){y("%cGM2 system on detected",C.info),l="gm2",B=!0;return}if(vs(u)){B=!0,y("%cGS on detected!",C.recognized);return}if(Ls(u)){y("%cGM on detected, removing!",C.info),P(),B=!1;return}if(a&&Ra(u.data)){P();return}if(r&&Ga(u.data)){P();return}if(o&&Ma(u.data)){P();return}if(i&&va(u.data)){P();return}if(g&&La(u.data)){P();return}let he=Fa(u.data);if(he!==-1){c.has(he+Ce)&&P();return}}}});let L=Math.max(0,A.firstNoteOn-10),H=A.tracks[0],q=Math.max(0,H.events.findIndex(u=>u.ticks>=L)-1);if(r){let u=Ya,v=r;H.addEvents(q,de(L,64,1,u.level,[v.level]),de(L,64,1,u.preLowpass,[v.preLowpass]),de(L,64,1,u.character,[v.character]),de(L,64,1,u.time,[v.time]),de(L,64,1,u.delayFeedback,[v.delayFeedback]),de(L,64,1,u.preDelayTime,[v.preDelayTime]))}if(o){let u=qa,v=o;H.addEvents(q,de(L,64,1,u.level,[v.level]),de(L,64,1,u.preLowpass,[v.preLowpass]),de(L,64,1,u.feedback,[v.feedback]),de(L,64,1,u.delay,[v.delay]),de(L,64,1,u.rate,[v.rate]),de(L,64,1,u.depth,[v.depth]),de(L,64,1,u.sendLevelToReverb,[v.sendLevelToReverb]),de(L,64,1,u.sendLevelToDelay,[v.sendLevelToDelay]))}if(i){let u=Ja,v=i;H.addEvents(q,de(L,64,1,u.level,[v.level]),de(L,64,1,u.preLowpass,[v.preLowpass]),de(L,64,1,u.timeCenter,[v.timeCenter]),de(L,64,1,u.timeRatioLeft,[v.timeRatioLeft]),de(L,64,1,u.timeRatioRight,[v.timeRatioRight]),de(L,64,1,u.levelCenter,[v.levelCenter]),de(L,64,1,u.levelLeft,[v.levelLeft]),de(L,64,1,u.levelRight,[v.levelRight]),de(L,64,1,u.feedback,[v.feedback]),de(L,64,1,u.sendLevelToReverb,[v.sendLevelToReverb]))}if(g){let u=g;for(let v=0;v<u.channels.length;v++)u.channels[v]&&H.addEvents(L,de(L,64,64|Ts(v),34,[1]));for(let v=0;v<u.params.length;v++){let S=u.params[v];S!==255&&H.addEvents(q,de(L,64,3,v+3,[S]))}H.addEvents(q,de(L,64,3,0,[u.type>>8,u.type&127]))}if(!B&&e.length>0){let u=0;A.tracks[0].events[0].statusByte===M.trackName&&u++,A.tracks[0].addEvents(u,Ln(0)),y("%cGS on not detected. Adding it.",C.info)}A.flush(),ee()}function Xa(A,e){let t=[],s=[],n=[],a=[];for(let[r,o]of e.channelSnapshots.entries()){if(o.isMuted){s.push(r);continue}let i=o.keyShift+o.customControllers[oe.channelTransposeFine]/100;i!==0&&t.push({channel:r,keyShift:i}),o.lockPreset&&n.push({channel:r,...o.patch});for(let[g,c]of o.lockedControllers.entries()){if(!c||g>127||g===d.bankSelect)continue;let l=o.midiControllers[g]>>7;a.push({channel:r,controllerNumber:g,controllerValue:l})}}A.modify({programChanges:n,controllerChanges:a,channelsToClear:s,channelsToTranspose:t,clearDrumParams:e.masterParameters.drumLock,reverbParams:e.masterParameters.reverbLock?e.reverbSnapshot:void 0,chorusParams:e.masterParameters.chorusLock?e.chorusSnapshot:void 0,delayParams:e.masterParameters.delayLock?e.delaySnapshot:void 0,insertionParams:e.masterParameters.insertionEffectLock?e.insertionSnapshot:void 0})}var jt={XMFFileType:0,nodeName:1,nodeIDNumber:2,resourceFormat:3,filenameOnDisk:4,filenameExtensionOnDisk:5,macOSFileTypeAndCreator:6,mimeType:7,title:8,copyrightNotice:9,comment:10,autoStart:11,preload:12,contentDescription:13,ID3Metadata:14},OA={inLineResource:1,inFileResource:2,inFileNode:3,externalFile:4,externalXMF:5,XMFFileURIandNodeID:6},es={StandardMIDIFile:0,StandardMIDIFileType1:1,DLS1:2,DLS2:3,DLS22:4,mobileDLS:5,unknown:-1,folder:-2},Za={standard:0,MMA:1,registered:2,nonRegistered:3},Et={none:0,MMAUnpacker:1,registered:2,nonRegistered:3},Wa=class Tn{length;itemCount;metadataLength;metadata={};nodeData;innerNodes=[];packedContent=!1;nodeUnpackers=[];resourceFormat="unknown";referenceTypeID;constructor(e){let t=e.currentIndex;this.length=pe(e),this.itemCount=pe(e);let s=pe(e),n=s-(e.currentIndex-t),a=e.slice(e.currentIndex,e.currentIndex+n);e.currentIndex+=n,this.metadataLength=pe(a);let r=a.slice(a.currentIndex,a.currentIndex+this.metadataLength);a.currentIndex+=this.metadataLength;let o,i;for(;r.currentIndex<r.length;){r[r.currentIndex]===0?(r.currentIndex++,o=pe(r),Object.values(jt).includes(o)?i=Object.keys(jt).find(h=>jt[h]===o)??"":(y(`Unknown field specifier: ${o}`),i=`unknown_${o}`)):(o=ue(r,pe(r)),i=o);let B=pe(r);if(B===0){let h=pe(r),E=r.slice(r.currentIndex,r.currentIndex+h);r.currentIndex+=h;let m=pe(E);this.metadata[i]=m<4?ue(E,h-1):E.slice(E.currentIndex)}else y(`International content: ${B}`),r.currentIndex+=pe(r)}let g=a.currentIndex,c=pe(a),l=a.slice(a.currentIndex,g+c);if(a.currentIndex=g+c,c>0)for(this.packedContent=!0;l.currentIndex<c;){let B={id:pe(l)};switch(B.id){case Et.nonRegistered:case Et.registered:throw ee(),new Error(`Unsupported unpacker ID: ${B.id}`);default:throw ee(),new Error(`Unknown unpacker ID: ${B.id}`);case Et.none:B.standardID=pe(l);break;case Et.MMAUnpacker:{let h=l[l.currentIndex++];h===0&&(h<<=8,h|=l[l.currentIndex++],h<<=8,h|=l[l.currentIndex++]);let E=pe(l);B.manufacturerID=h,B.manufacturerInternalID=E}break}B.decodedSize=pe(l),this.nodeUnpackers.push(B)}switch(e.currentIndex=t+s,this.referenceTypeID=pe(e),this.nodeData=e.slice(e.currentIndex,t+this.length),e.currentIndex=t+this.length,this.referenceTypeID){case OA.inLineResource:break;case OA.externalXMF:case OA.inFileNode:case OA.XMFFileURIandNodeID:case OA.externalFile:case OA.inFileResource:throw ee(),new Error(`Unsupported reference type: ${this.referenceTypeID}`);default:throw ee(),new Error(`Unknown reference type: ${this.referenceTypeID}`)}if(this.isFile){if(this.packedContent){let h=this.nodeData.slice(2);y(`%cPacked content. Attempting to deflate. Target size: %c${this.nodeUnpackers[0].decodedSize}`,C.warn,C.value);try{this.nodeData=new _(bn(h).buffer)}catch(E){if(ee(),E instanceof Error)throw new Error(`Error unpacking XMF file contents: ${E.message}.`,{cause:E})}}let B=this.metadata.resourceFormat;if(B===void 0)se("No resource format for this file node!");else{B[0]!==Za.standard&&(y(`Non-standard formatTypeID: ${B.toString()}`),this.resourceFormat=B.toString());let h=B[1];Object.values(es).includes(h)?this.resourceFormat=Object.keys(es).find(E=>es[E]===h):y(`Unrecognized resource format: ${h}`)}}else for(this.resourceFormat="folder";this.nodeData.currentIndex<this.nodeData.length;){let B=this.nodeData.currentIndex,h=pe(this.nodeData),E=this.nodeData.slice(B,B+h);this.nodeData.currentIndex=B+h,this.innerNodes.push(new Tn(E))}}get isFile(){return this.itemCount===0}};function za(A,e){A.bankOffset=0;let t=ue(e,4);if(t!=="XMF_")throw ee(),new SyntaxError(`Invalid XMF Header! Expected "_XMF", got "${t}"`);je("%cParsing XMF file...",C.info);let s=ue(e,4);y(`%cXMF version: %c${s}`,C.info,C.recognized),s==="2.00"&&y(`%cFile Type ID: %c${JA(e,4)}%c, File Type Revision ID: %c${JA(e,4)}`,C.info,C.recognized,C.info,C.recognized),pe(e);let n=pe(e);e.currentIndex+=n,e.currentIndex=pe(e);let a=new Wa(e),r,o=i=>{let g=(c,l)=>{i.metadata[c]!==void 0&&typeof i.metadata[c]=="string"&&(A.rmidiInfo[l]=BA(i.metadata[c]))};if(g("nodeName","name"),g("title","name"),g("copyrightNotice","copyright"),g("comment","comment"),i.isFile)switch(i.resourceFormat){default:return;case"DLS1":case"DLS2":case"DLS22":case"mobileDLS":y("%cFound embedded DLS!",C.recognized),A.embeddedSoundBank=i.nodeData.buffer;break;case"StandardMIDIFile":case"StandardMIDIFileType1":y("%cFound embedded MIDI!",C.recognized),r=i.nodeData;break}else for(let c of i.innerNodes)o(c)};if(o(a),ee(),!r)throw new Error("No MIDI data in the XMF file!");return r}var Ot=class Un{name="";port=0;channels=new Set;events=[];static copyFrom(e){let t=new Un;return t.copyFrom(e),t}copyFrom(e){this.name=e.name,this.port=e.port,this.channels=new Set(e.channels),this.events=e.events.map(t=>new gA(t.ticks,t.statusByte,new _(t.data)))}addEvent(e,t){this.events.splice(t,0,e)}addEvents(e,...t){this.events.splice(e,0,...t)}deleteEvent(e){this.events.splice(e,1)}pushEvent(e){this.events.push(e)}};function en(A,e,t){Je("%cParsing MIDI File...",C.info),A.fileName=t;let s=new _(e),n,a=g=>{let c=ue(g,4),l=JA(g,4),B={type:c,size:l,data:new _(l)},h=g.slice(g.currentIndex,g.currentIndex+B.size);return B.data.set(h,0),g.currentIndex+=B.size,B},r=oA(s,4);if(r==="RIFF"){s.currentIndex+=8;let g=ue(s,4);if(g!=="RMID")throw ee(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${g}"`);let c=N.read(s);if(c.header!=="data")throw ee(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${c.header}"`);n=c.data;let l=!1,B=!1;for(;s.currentIndex<s.length;){let h=s.currentIndex,E=N.read(s,!0);if(E.header==="RIFF"){let m=ue(E.data,4).toLowerCase();m==="sfbk"||m==="sfpk"||m==="dls "?(y("%cFound embedded soundbank!",C.recognized),A.embeddedSoundBank=s.slice(h,h+E.size).buffer):se(`Unknown RIFF chunk: "${m}"`),m==="dls "?A.isDLSRMIDI=!0:l=!0}else if(E.header==="LIST"&&ue(E.data,4)==="INFO")for(y("%cFound RMIDI INFO chunk!",C.recognized);E.data.currentIndex<E.size;){let m=N.read(E.data,!0),D=m.header,f=m.data;switch(D){default:se(`Unknown RMIDI Info: ${D}`);break;case"INAM":A.rmidiInfo.name=f;break;case"IALB":case"IPRD":A.rmidiInfo.album=f;break;case"ICRT":case"ICRD":A.rmidiInfo.creationDate=f;break;case"IART":A.rmidiInfo.artist=f;break;case"IGNR":A.rmidiInfo.genre=f;break;case"IPIC":A.rmidiInfo.picture=f;break;case"ICOP":A.rmidiInfo.copyright=f;break;case"ICMT":A.rmidiInfo.comment=f;break;case"IENG":A.rmidiInfo.engineer=f;break;case"ISFT":A.rmidiInfo.software=f;break;case"ISBJ":A.rmidiInfo.subject=f;break;case"IENC":A.rmidiInfo.infoEncoding=f;break;case"MENC":A.rmidiInfo.midiEncoding=f;break;case"DBNK":A.bankOffset=Dn(f,2),B=!0;break}}}l&&!B&&(A.bankOffset=1),A.isDLSRMIDI&&(A.bankOffset=0),A.embeddedSoundBank===void 0&&(A.bankOffset=0)}else r==="XMF_"?n=za(A,s):n=s;let o=a(n);if(o.type!=="MThd")throw ee(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${o.type}"`);if(o.size!==6)throw ee(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${o.size}`);A.format=JA(o.data,2);let i=JA(o.data,2);A.timeDivision=JA(o.data,2);for(let g=0;g<i;g++){let c=new Ot,l=a(n);if(l.type!=="MTrk")throw ee(),new SyntaxError(`Invalid track header! Expected "MTrk" got "${l.type}"`);let B,h=0;for(A.format===2&&g>0&&(h+=A.tracks[g-1].events[A.tracks[g-1].events.length-1].ticks);l.data.currentIndex<l.size;){h+=pe(l.data);let E=l.data[l.data.currentIndex],m;if(B!==void 0&&E<128)m=B;else{if(E<128)throw ee(),new SyntaxError(`Unexpected byte with no running byte. (${E})`);m=l.data[l.data.currentIndex++]}let D=pa(m),f;switch(D){case-1:f=0;break;case-2:m=l.data[l.data.currentIndex++],f=pe(l.data);break;case-3:f=pe(l.data);break;default:f=ya[m>>4],B=m;break}let O=new _(f);O.set(l.data.slice(l.data.currentIndex,l.data.currentIndex+f),0);let R=new gA(h,m,O);c.pushEvent(R),l.data.currentIndex+=f}A.tracks.push(c),y(`%cParsed %c${A.tracks.length}%c / %c${A.tracks.length}`,C.info,C.value,C.info,C.value)}y("%cAll tracks parsed correctly!",C.recognized),A.flush(!1),ee()}function Us(A){return A.toISOString().split(".")[0]+"Z"}var _a=[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 $a(A){for(let e of _a){let t=A;for(let[n,a]of e.entries()){let r=new RegExp(n,"gi");t=t.replace(r,a)}let s=new Date(t);if(!Number.isNaN(s.getTime()))return s}}function ja(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,n=Number.parseInt(e[3]),a=new Date(n,s,t);if(!Number.isNaN(a.getTime()))return a}}function ei(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(),n=e[3],a=new Date(`${s}/${t}/${n}`);if(!Number.isNaN(a.getTime()))return a}}function Ai(A){let e=/\b\d{4}\b/.exec(A);return e?new Date(e[0]):void 0}function Ps(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=$a(A);if(s)return s;let n=ja(A);if(n)return n;let a=ei(A);if(a)return a;let r=Ai(A);return r||(se(`Invalid date: "${A}". Replacing with the current date!`),new Date)}return t}var NA=class St{tracks=[];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 t=e.byteLength;return e[e.byteLength-1]===0&&t--,oA(e,t)}static fromArrayBuffer(e,t=""){let s=new St;return en(s,e,t),s}static async fromFile(e){let t=new St;return en(t,await e.arrayBuffer(),e.name),t}static copyFrom(e){let t=new St;return t.copyFrom(e),t}copyFrom(e){this.copyMetadataFrom(e),this.embeddedSoundBank=e?.embeddedSoundBank?.slice(0)??void 0,this.tracks=e.tracks.map(t=>Ot.copyFrom(t))}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 t=this.tempoChanges.findIndex(n=>n.ticks<=e),s=0;for(;t<this.tempoChanges.length;){let n=this.tempoChanges[t++],a=e-n.ticks;s+=a*60/(n.tempo*this.timeDivision),e=n.ticks}return s}secondsToMIDITicks(e){if(e=Math.max(e,0),e===0)return 0;if(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 t=e,s=0;for(let n=this.tempoChanges.length-1;n>=0;n--){let a=this.tempoChanges[n],r=this.tempoChanges[n-1],o=r?r.ticks-a.ticks:1/0,i=60/(a.tempo*this.timeDivision),g=o*i;if(t<=g)return s+=Math.round(t/i),s;s+=o,t-=g}return s}getUsedProgramsAndKeys(e){return Pa(this,e)}preloadSynth(e){Je("%cPreloading samples...",C.info);let t=this.getUsedProgramsAndKeys(e.soundBankManager);for(let[s,n]of t.entries()){y(`%cPreloading used samples on %c${s.name}%c...`,C.info,C.recognized,C.info);for(let a of n){let[r,o]=a.split("-").map(Number);e.getVoicesForPreset(s,r,o)}}ee()}flush(e=!0){if(e)for(let t of this.tracks)t.events.sort((s,n)=>s.ticks-n.ticks);this.parseInternal()}getNoteTimes(e=0){return Ha(this,e)}writeMIDI(){return Sa(this)}writeRMIDI(e,t=js){return Ua(this,e,Fs(t,js))}modify({programChanges:e=[],controllerChanges:t=[],channelsToClear:s=[],channelsToTranspose:n=[],clearDrumParams:a=!1,reverbParams:r,chorusParams:o,delayParams:i,insertionParams:g}){Va(this,{programChanges:e,controllerChanges:t,channelsToClear:s,channelsToTranspose:n,clearDrumParams:a,reverbParams:r,chorusParams:o,delayParams:i,insertionParams:g})}applySnapshot(e){Xa(this,e)}getName(e="Shift_JIS"){let t="",s=this.getRMIDInfo("name");if(s)return s.trim();if(this.binaryName){e=this.getRMIDInfo("midiEncoding")??e;try{t=new TextDecoder(e).decode(this.binaryName).trim()}catch(n){se(`Failed to decode MIDI name: ${n}`)}}return t||this.fileName}getExtraMetadata(e="Shift_JIS"){e=this.infoEncoding??e;let t=new TextDecoder(e);return this.extraMetadata.map(s=>t.decode(s.data).replaceAll(/@T|@A/g,"").trim())}setRMIDInfo(e,t){if(this.rmidiInfo.infoEncoding=BA("utf-8",!0),e==="picture")this.rmidiInfo.picture=new Uint8Array(t);else if(e==="creationDate")this.rmidiInfo.creationDate=BA(Us(t),!0);else{let s=new TextEncoder().encode(t);this.rmidiInfo[e]=new Uint8Array([...s,0])}}getRMIDInfo(e){if(!this.rmidiInfo[e])return;let t=this.infoEncoding??"UTF-8";if(e==="picture")return this.rmidiInfo[e].buffer;if(e==="creationDate")return Ps(oA(this.rmidiInfo[e]));try{let s=new TextDecoder(t),n=this.rmidiInfo[e];return n[n.length-1]===0&&(n=n?.slice(0,-1)),s.decode(n.buffer).trim()}catch(s){se(`Failed to decode ${e} name: ${s}`);return}}iterate(e){let t=new Array(this.tracks.length).fill(0),s=this.tracks.length,n=()=>{let a=0,r=1/0;for(let[o,{events:i}]of this.tracks.entries())t[o]>=i.length||i[t[o]].ticks<r&&(a=o,r=i[t[o]].ticks);return a};for(;s>0;){let a=n(),r=this.tracks[a].events;if(t[a]>=r.length){s--;continue}let o=r[t[a]];e(o,a,t),t[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(t=>new gA(t.ticks,t.statusByte,new _(t.data))),this.lyrics=e.lyrics.map(t=>new gA(t.ticks,t.statusByte,new _(t.data))),this.portChannelOffsetMap=[...e.portChannelOffsetMap],this.binaryName=e?.binaryName?.slice(),this.loop={...e.loop},this.keyRange={...e.keyRange},this.rmidiInfo={};for(let t of Object.entries(e.rmidiInfo)){let s=t[0],n=t[1];this.rmidiInfo[s]=new Uint8Array(n)}}parseInternal(){je("%cInterpreting MIDI events...",C.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 t=!1;this.rmidiInfo.name!==void 0&&(t=!0);let s=null,n=null,a="hard";for(let g of this.tracks){let c=new Set,l=!1;for(let h=0;h<g.events.length;h++){let E=g.events[h];if(E.statusByte>=128&&E.statusByte<240)switch(l=!0,E.ticks>this.lastVoiceEventTick&&(this.lastVoiceEventTick=E.ticks),E.statusByte&240){case M.controllerChange:switch(E.data[0]){case 2:case 111:case 116:s=E.ticks;break;case 4:case 117:n===null?(a="soft",n=E.ticks):n=0;break;case 0:this.isDLSRMIDI&&E.data[1]!==0&&E.data[1]!==127&&(y("%cDLS RMIDI with offset 1 detected!",C.recognized),this.bankOffset=1)}break;case M.noteOn:{c.add(E.statusByte&15);let D=E.data[0];this.keyRange.min=Math.min(this.keyRange.min,D),this.keyRange.max=Math.max(this.keyRange.max,D);break}}let m=oA(E.data);switch(E.statusByte){case M.endOfTrack:h!==g.events.length-1&&(g.deleteEvent(h),h--,se("Unexpected EndOfTrack. Removing!"));break;case M.setTempo:this.tempoChanges.push({ticks:E.ticks,tempo:6e7/zA(E.data,3)});break;case M.marker:switch(m.trim().toLowerCase()){default:break;case"start":case"loopstart":s=E.ticks;break;case"loopend":n=E.ticks}break;case M.copyright:this.extraMetadata.push(E);break;case M.lyric:m.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,y("%cKaraoke MIDI detected!",C.recognized)),this.isKaraokeFile?E.statusByte=M.text:this.lyrics.push(E);case M.text:{let D=m.trim();D.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,y("%cKaraoke MIDI detected!",C.recognized)):this.isKaraokeFile&&(D.startsWith("@T")||D.startsWith("@A")?e?this.extraMetadata.push(E):(this.binaryName=E.data.slice(2),e=!0,t=!0):D.startsWith("@")||this.lyrics.push(E));break}}}g.channels=c,g.name="";let B=g.events.find(h=>h.statusByte===M.trackName);B&&this.tracks.indexOf(g)>0&&(g.name=oA(B.data),!l&&!g.name.toLowerCase().includes("setup")&&this.extraMetadata.push(B))}this.tempoChanges.reverse(),y("%cCorrecting loops, ports and detecting notes...",C.info);let r=[];for(let g of this.tracks){let c=g.events.find(l=>(l.statusByte&240)===M.noteOn);c&&r.push(c.ticks)}this.firstNoteOn=Math.min(...r),y(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,C.info,C.recognized,C.info),s??=this.firstNoteOn,(n===null||n===0)&&(n=this.lastVoiceEventTick),this.loop={start:s,end:n,type:a},this.lastVoiceEventTick=Math.max(this.lastVoiceEventTick,this.loop.end),y(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,C.info,C.recognized,C.info,C.recognized);let o=0;this.portChannelOffsetMap=[];for(let g of this.tracks)if(g.port=-1,g.channels.size!==0)for(let c of g.events){if(c.statusByte!==M.midiPort)continue;let l=c.data[0];g.port=l,this.portChannelOffsetMap[l]===void 0&&(this.portChannelOffsetMap[l]=o,o+=16)}this.portChannelOffsetMap=[...this.portChannelOffsetMap].map(g=>g??0);let i=1/0;for(let g of this.tracks)g.port!==-1&&i>g.port&&(i=g.port);i===1/0&&(i=0);for(let g of this.tracks)(g.port===-1||g.port===void 0)&&(g.port=i);if(this.portChannelOffsetMap.length===0&&(this.portChannelOffsetMap=[0]),this.portChannelOffsetMap.length<2?y("%cNo additional MIDI Ports detected.",C.info):(this.isMultiPort=!0,y("%cMIDI Ports detected!",C.recognized)),!t)if(this.tracks.length>1){if(!this.tracks[0].events.some(g=>g.statusByte>=M.noteOn&&g.statusByte<M.polyPressure)){let g=this.tracks[0].events.find(c=>c.statusByte===M.trackName);g&&(this.binaryName=g.data)}}else{let g=this.tracks[0].events.find(c=>c.statusByte===M.trackName);g&&(this.binaryName=g.data)}if(this.extraMetadata=this.extraMetadata.filter(g=>g.data.length>0),this.lyrics.sort((g,c)=>g.ticks-c.ticks),!this.tracks.some(g=>g.events[0].ticks===0)){let g=this.tracks[0],c=this?.binaryName?.buffer;c||(c=new Uint8Array(0).buffer),g.events.unshift(new gA(0,M.trackName,new _(c)))}this.duration=this.midiTicksToSeconds(this.lastVoiceEventTick),this.binaryName?.length===0&&(this.binaryName=void 0),y(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}%c, total seconds time: %c${ls(Math.ceil(this.duration)).time}`,C.info,C.recognized,C.info,C.recognized),ee()}};function ti(A,e){if(this.externalMIDIPlayback&&A.statusByte>=128){this.sendMIDIMessage([A.statusByte,...A.data]);return}let t=this._midiData.tracks[e],s=Gs(A.statusByte),n=this.midiPortChannelOffsets[this.currentMIDIPorts[e]]||0;switch(s.channel+=n,s.status){case M.noteOn:{let a=A.data[1];if(a>0)this.synth.noteOn(s.channel,A.data[0],a),this.playingNotes.push({midiNote:A.data[0],channel:s.channel,velocity:a});else{this.synth.noteOff(s.channel,A.data[0]);let r=this.playingNotes.findIndex(o=>o.midiNote===A.data[0]&&o.channel===s.channel);r!==-1&&this.playingNotes.splice(r,1)}break}case M.noteOff:{this.synth.noteOff(s.channel,A.data[0]);let a=this.playingNotes.findIndex(r=>r.midiNote===A.data[0]&&r.channel===s.channel);a!==-1&&this.playingNotes.splice(a,1);break}case M.pitchWheel:this.synth.pitchWheel(s.channel,A.data[1]<<7|A.data[0]);break;case M.controllerChange:if(this._midiData.isMultiPort&&t.channels.size===0)return;this.synth.controllerChange(s.channel,A.data[0],A.data[1]);break;case M.programChange:if(this._midiData.isMultiPort&&t.channels.size===0)return;this.synth.programChange(s.channel,A.data[0]);break;case M.polyPressure:this.synth.polyPressure(s.channel,A.data[0],A.data[1]);break;case M.channelPressure:this.synth.channelPressure(s.channel,A.data[0]);break;case M.systemExclusive:this.synth.systemExclusive(A.data,n);break;case M.setTempo:{let a=6e7/zA(A.data,3);this.oneTickToSeconds=60/(a*this._midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this._midiData.timeDivision),y("invalid tempo! falling back to 120 BPM"));break}case M.timeSignature:case M.endOfTrack:case M.midiChannelPrefix:case M.songPosition:case M.activeSensing:case M.keySignature:case M.sequenceNumber:case M.sequenceSpecific:case M.text:case M.lyric:case M.copyright:case M.trackName:case M.marker:case M.cuePoint:case M.instrumentName:case M.programName:break;case M.midiPort:this.assignMIDIPort(e,A.data[0]);break;case M.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:y(`%cUnrecognized Event: %c${A.statusByte}%c status byte: %c${Object.keys(M).find(a=>M[a]===s.status)}`,C.warn,C.unrecognized,C.warn,C.value);break}s.status>=0&&s.status<128&&this.callEvent("metaEvent",{event:A,trackIndex:e})}function si(){if(this.paused||!this._midiData)return;let A=this.currentTime;for(;this.playedTime<A;){let e=this.findFirstEventIndex(),t=this._midiData.tracks[e].events[this.eventIndexes[e]++];this.processEvent(t,e);let s=this.findFirstEventIndex(),n=this._midiData.tracks[s];if(this.loopCount>0&&this._midiData.loop.end<=t.ticks){this.loopCount!==1/0&&(this.loopCount--,this.callEvent("loopCountChange",{newCount:this.loopCount})),this._midiData.loop.type==="soft"?this.jumpToTick(this._midiData.loop.start):this.setTimeTicks(this._midiData.loop.start);return}if(n.events.length<=this.eventIndexes[s]||t.ticks>=this._midiData.lastVoiceEventTick){this.songIsFinished();return}let a=n.events[this.eventIndexes[s]];this.playedTime+=this.oneTickToSeconds*(a.ticks-t.ticks)}}function ni(A,e){this._midiData.tracks[A].channels.size!==0&&(this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[e]=0),this.midiPortChannelOffsets[e]===void 0&&(this.synth.midiChannels.length<this.midiPortChannelOffset+15&&this.addNewMIDIPort(),this.midiPortChannelOffsets[e]=this.midiPortChannelOffset,this.midiPortChannelOffset+=16),this.currentMIDIPorts[A]=e)}function ai(A){if(!A.tracks)throw new Error("This MIDI has no tracks!");if(A.duration===0){se("This MIDI file has a duration of exactly 0 seconds."),this.pausedTime=0,this.isFinished=!0;return}this.oneTickToSeconds=60/(120*A.timeDivision),