spessasynth_lib 3.26.15 → 3.26.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -101,7 +101,7 @@ export class Sequencer
|
|
|
101
101
|
|
|
102
102
|
/**
|
|
103
103
|
* Fires on meta-event
|
|
104
|
-
* @type {Object<string, function([
|
|
104
|
+
* @type {Object<string, function([MIDIMessage, number])>}
|
|
105
105
|
*/
|
|
106
106
|
onMetaEvent = {};
|
|
107
107
|
|
|
@@ -445,8 +445,7 @@ export class Sequencer
|
|
|
445
445
|
|
|
446
446
|
/**
|
|
447
447
|
* Adds a new event that gets called when a meta-event occurs
|
|
448
|
-
* @param callback {function([
|
|
449
|
-
* its data, the track number and MIDI ticks
|
|
448
|
+
* @param callback {function([MIDIMessage, number])} the meta-event type and the track number
|
|
450
449
|
* @param id {string} must be unique
|
|
451
450
|
*/
|
|
452
451
|
addOnMetaEvent(callback, id)
|
|
@@ -14,7 +14,7 @@ Converted from SF2 to DLS using SpessaSynth`,this.soundFontInfo.ISFT="SpessaSynt
|
|
|
14
14
|
`+this.soundFontInfo.ISBJ,delete this.soundFontInfo.ISBJ),this.soundFontInfo.ICMT+=`
|
|
15
15
|
Converted from DLS to SF2 with SpessaSynth`;for(let[i,E]of Object.entries(this.soundFontInfo))y(`%c"${i}": %c"${E}"`,I.info,I.recognized);let o=n.find(i=>i.header==="colh");o||(q(),this.parsingError("No colh chunk!")),this.instrumentAmount=N(o.chunkData,4),y(`%cInstruments amount: %c${this.instrumentAmount}`,I.info,I.recognized);let r=XA(n,"wvpl");r||(q(),this.parsingError("No wvpl chunk!")),this.readDLSSamples(r);let g=XA(n,"lins");g||(q(),this.parsingError("No lins chunk!")),this.readDLSInstrumentList(g),this.presets.sort((i,E)=>i.program-E.program+(i.bank-E.bank)),this._parseInternal(),y(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets,
|
|
16
16
|
%c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),q()}verifyHeader(A,...t){for(let n of t)if(A.header.toLowerCase()===n.toLowerCase())return;q(),this.parsingError(`Invalid DLS chunk header! Expected "${t.toString()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(q(),this.parsingError(`FourCC error: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`))}parsingError(A){throw new Error(`DLS parse error: ${A} The file may be corrupted.`)}destroySoundBank(){super.destroySoundBank(),delete this.dataArray}};be.prototype.readDLSInstrumentList=Po;be.prototype.readDLSInstrument=Zo;be.prototype.readRegion=zo;be.prototype.readLart=_o;be.prototype.readDLSSamples=$o;var hs=class extends Ge{constructor(A,t,n,s,o,r,g,i,E,l,c,h,B){super(A,r,g,i,E,l,s-t/2,o-t/2),this.sampleName=A,this.sampleStartIndex=t,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=h,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=c,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=B}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let t=A.currentIndex;return A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t)}else{this.isDataRaw||super.getRawData();let t=A.currentIndex;return A.slice(t+this.sampleStartIndex,t+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,t=A.currentIndex,n=A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t);this.sampleData=new Float32Array(0);try{let s=me.decode(n.buffer);this.sampleData=s.data[0],this.sampleData===void 0&&Y(`Error decoding sample ${this.sampleName}: Vorbis decode returned undefined.`)}catch(s){Y(`Error decoding sample ${this.sampleName}: ${s}`),this.sampleData=new Float32Array(this.sampleLoopEndIndex+1)}}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?(Y(`Invalid sample ${this.sampleName}! Invalid length: ${this.sampleLength}`),new Float32Array(1)):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return Y("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),t=this.sampleDataArray.currentIndex,n=new Int16Array(this.sampleDataArray.slice(t+this.sampleStartIndex,t+this.sampleEndIndex).buffer);for(let s=0;s<n.length;s++)A[s]=n[s]/32768;return this.sampleData=A,this.isSampleLoaded=!0,A}getUncompressedReadyData(){let A=this.sampleDataArray.slice(this.sampleStartIndex/2,this.sampleEndIndex/2);return this.sampleData=A,this.isSampleLoaded=!0,A}};function Ar(e,A,t=!0){let n=[],s=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let o=Li(s,e.chunkData,A,t);n.push(o),s++}return n.length>1&&n.pop(),n}function Li(e,A,t,n){let s=AA(A,20),o=N(A,4)*2,r=N(A,4)*2,g=N(A,4),i=N(A,4),E=N(A,4),l=A[A.currentIndex++];l===255&&(l=60);let c=mo(A[A.currentIndex++]),h=N(A,2),B=N(A,2);return new hs(s,o,r,g,i,E,l,c,h,B,t,e,n)}var ls=class extends v{constructor(A){super();let t=A.currentIndex;this.generatorType=A[t+1]<<8|A[t],this.generatorValue=Ke(A[t+2],A[t+3]),A.currentIndex+=4}};function Bs(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new ls(e.chunkData));return A.length>1&&A.pop(),A}var Qs=class extends JA{constructor(A){super(),this.generatorZoneStartIndex=N(A,2),this.modulatorZoneStartIndex=N(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;t<this.generatorZoneStartIndex+this.generatorZoneSize;t++)this.generators.push(A[t])}getModulators(A){for(let t=this.modulatorZoneStartIndex;t<this.modulatorZoneStartIndex+this.modulatorZoneSize;t++)this.modulators.push(A[t])}getSample(A){let t=this.generators.find(n=>n.generatorType===a.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function er(e,A,t,n){let s=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Qs(e.chunkData);if(s.length>0){let r=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(r,g),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(t),s[s.length-1].getSample(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var ds=class extends Re{constructor(A){super(),this.generatorZoneStartIndex=N(A,2),this.modulatorZoneStartIndex=N(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;t<this.generatorZoneStartIndex+this.generatorZoneSize;t++)this.generators.push(A[t])}getModulators(A){for(let t=this.modulatorZoneStartIndex;t<this.modulatorZoneStartIndex+this.modulatorZoneSize;t++)this.modulators.push(A[t])}getInstrument(A){let t=this.generators.find(n=>n.generatorType===a.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function tr(e,A,t,n){let s=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new ds(e.chunkData);if(s.length>0){let r=o.modulatorZoneStartIndex-s[s.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-s[s.length-1].generatorZoneStartIndex;s[s.length-1].setZoneSize(r,g),s[s.length-1].getGenerators(A),s[s.length-1].getModulators(t),s[s.length-1].getInstrument(n),s[s.length-1].getKeyRange(),s[s.length-1].getVelRange()}s.push(o)}return s.length>1&&s.pop(),s}var fs=class extends xe{constructor(A,t){super(t),this.presetName=AA(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=N(A.chunkData,2),this.bank=N(A.chunkData,2),this.presetZoneStartIndex=N(A.chunkData,2),this.library=N(A.chunkData,4),this.genre=N(A.chunkData,4),this.morphology=N(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,t){this.presetZonesAmount=A;for(let n=this.presetZoneStartIndex;n<this.presetZonesAmount+this.presetZoneStartIndex;n++)this.presetZones.push(t[n])}};function nr(e,A,t){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let s=new fs(e,t);if(n.length>0){let o=s.presetZoneStartIndex-n[n.length-1].presetZoneStartIndex;n[n.length-1].getPresetZones(o,A)}n.push(s)}return n.length>1&&n.pop(),n}var us=class extends Me{constructor(A){super(),this.instrumentName=AA(A.chunkData,20).trim(),this.instrumentZoneIndex=N(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,t){this.instrumentZonesAmount=A;for(let n=this.instrumentZoneIndex;n<this.instrumentZonesAmount+this.instrumentZoneIndex;n++)this.instrumentZones.push(t[n])}};function sr(e,A){let t=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let n=new us(e);if(t.length>0){let s=n.instrumentZoneIndex-t[t.length-1].instrumentZoneIndex;t[t.length-1].getInstrumentZones(s,A)}t.push(n)}return t.length>1&&t.pop(),t}var ms=class extends X{constructor(A){let t=N(A,2),n=N(A,2),s=Ke(A[A.currentIndex++],A[A.currentIndex++]),o=N(A,2),r=N(A,2);super(t,o,n,s,r)}};function yn(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new ms(e.chunkData));return A}var Sn=class extends Ne{constructor(A,t=!0){super(),t&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new x(A),ge("%cParsing SoundFont...",I.info),this.dataArray||(q(),this.parsingError("No data provided!"));let n=IA(this.dataArray,!1);this.verifyHeader(n,"riff");let s=AA(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw q(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let o=s==="sfpk",r=IA(this.dataArray);for(this.verifyHeader(r,"list"),AA(r.chunkData,4);r.chunkData.length>r.chunkData.currentIndex;){let $=IA(r.chunkData),U;switch($.header.toLowerCase()){case"ifil":case"iver":U=`${N($.chunkData,2)}.${N($.chunkData,2)}`,this.soundFontInfo[$.header]=U;break;case"icmt":U=AA($.chunkData,$.chunkData.length,void 0,!1),this.soundFontInfo[$.header]=U;break;case"dmod":let tA=yn($);tA.pop(),U=`Modulators: ${tA.length}`;let hA=this.defaultModulators;this.defaultModulators=tA,this.defaultModulators.push(...hA.filter(oA=>!this.defaultModulators.find(rA=>X.isIdentical(oA,rA)))),this.soundFontInfo[$.header]=$.chunkData;break;default:U=AA($.chunkData,$.chunkData.length),this.soundFontInfo[$.header]=U}y(`%c"${$.header}": %c"${U}"`,I.info,I.recognized)}let g=IA(this.dataArray,!1);this.verifyHeader(g,"list"),this.verifyText(AA(this.dataArray,4),"sdta"),y("%cVerifying smpl chunk...",I.warn);let i=IA(this.dataArray,!1);this.verifyHeader(i,"smpl");let E;if(o){y("%cSF2Pack detected, attempting to decode the smpl chunk...",I.info);try{E=me.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+g.size-12)).data[0]}catch($){throw q(),new Error(`SF2Pack Ogg Vorbis decode error: ${$}`)}y(`%cDecoded the smpl chunk! Length: %c${E.length}`,I.info,I.value)}else E=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;y(`%cSkipping sample chunk, length: %c${g.size-12}`,I.info,I.value),this.dataArray.currentIndex+=g.size-12,y("%cLoading preset data chunk...",I.warn);let l=IA(this.dataArray);this.verifyHeader(l,"list"),AA(l.chunkData,4);let c=IA(l.chunkData);this.verifyHeader(c,"phdr");let h=IA(l.chunkData);this.verifyHeader(h,"pbag");let B=IA(l.chunkData);this.verifyHeader(B,"pmod");let m=IA(l.chunkData);this.verifyHeader(m,"pgen");let f=IA(l.chunkData);this.verifyHeader(f,"inst");let S=IA(l.chunkData);this.verifyHeader(S,"ibag");let G=IA(l.chunkData);this.verifyHeader(G,"imod");let D=IA(l.chunkData);this.verifyHeader(D,"igen");let M=IA(l.chunkData);this.verifyHeader(M,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...Ar(M,E,!o));let T=Bs(D),R=yn(G),C=er(S,T,R,this.samples);this.instruments=sr(f,C);let b=Bs(m),L=yn(B),nA=tr(h,b,L,this.instruments);this.presets.push(...nr(c,nA,this)),this.presets.sort(($,U)=>$.program-U.program+($.bank-U.bank)),this._parseInternal(),y(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets,
|
|
17
|
-
%c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),q(),o&&delete this.dataArray}verifyHeader(A,t){A.header.toLowerCase()!==t.toLowerCase()&&(q(),this.parsingError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(q(),this.parsingError(`Invalid FourCC: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"\``))}destroySoundBank(){super.destroySoundBank(),delete this.dataArray}};function At(e){let A=e.slice(8,12),t=new x(A);return AA(t,4,void 0,!1).toLowerCase()==="dls "?new be(e):new Sn(e,!1)}function or(){this.soundfontManager.soundfontList.some(e=>e.id===We)&&this.soundfontManager.deleteSoundFont(We)}function rr(e,A){this.soundfontBankOffset=A;let t=At(e);this.soundfontManager.addNewSoundFont(t,We,A);let n=this.soundfontManager.getCurrentSoundFontOrder();n.pop(),n.unshift(We),this.soundfontManager.rearrangeSoundFonts(n),this._snapshot!==void 0&&this.applySynthesizerSnapshot(this._snapshot),y(`%cEmbedded sound bank set at offset %c${A}`,I.recognized,I.value)}function ir(){let e=this.soundfontManager.getPresetList();this.clearCache(),this.callEvent("presetlistchange",e),this.getDefaultPresets(),this.midiAudioChannels.forEach(A=>{A.setPresetLock(!1)}),this.resetAllControllers(!1)}function ar(e,A=!1){this.transposition=0;for(let t=0;t<this.midiAudioChannels.length;t++)this.midiAudioChannels[t].transposeChannel(e,A);this.transposition=e}function gr(e){e=Math.round(e);for(let A=0;A<this.midiAudioChannels.length;A++)this.midiAudioChannels[A].setCustomController(CA.masterTuning,e)}var dt=class e{program;bank;isBankLSB;patchName;lockPreset;lockedSystem;midiControllers;lockedControllers;customControllers;lockVibrato;channelVibrato;channelTransposeKeyShift;channelOctaveTuning;isMuted;velocityOverride;drumChannel;static getChannelSnapshot(A,t){let n=A.midiAudioChannels[t],s=new e;return s.program=n.preset.program,s.bank=n.getBankSelect(),s.isBankLSB=s.bank!==n.bank,s.lockPreset=n.lockPreset,s.lockedSystem=n.lockedSystem,s.patchName=n.preset.presetName,s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.channelVibrato=n.channelVibrato,s.lockVibrato=n.lockGSNRPNParams,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.isMuted=n.isMuted,s.velocityOverride=n.velocityOverride,s.drumChannel=n.drumChannel,s}static applyChannelSnapshot(A,t,n){let s=A.midiAudioChannels[t];s.muteChannel(n.isMuted),s.setDrums(n.drumChannel),s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.updateChannelTuning(),s.channelVibrato=n.channelVibrato,s.lockGSNRPNParams=n.lockVibrato,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.velocityOverride=n.velocityOverride,s.setPresetLock(!1),s.setBankSelect(n.bank,n.isBankLSB),s.programChange(n.program),s.setPresetLock(n.lockPreset),s.lockedSystem=n.lockedSystem}};var et=class e{channelSnapshots;keyMappings;mainVolume;pan;interpolation;system;transposition;static createSynthesizerSnapshot(A){let t=new e;return t.channelSnapshots=A.midiAudioChannels.map((n,s)=>dt.getChannelSnapshot(A,s)),t.keyMappings=A.keyModifierManager.getMappings(),t.mainVolume=A.midiVolume,t.pan=A.pan,t.system=A.system,t.interpolation=A.interpolationType,t.transposition=A.transposition,t.effectsConfig={},t}static applySnapshot(A,t){for(A.setSystem(t.system),A.setMasterParameter(OA.mainVolume,t.mainVolume),A.setMasterParameter(OA.masterPan,t.pan),A.transposeAllChannels(t.transposition),A.interpolationType=t.interpolation,A.keyModifierManager.setMappings(t.keyMappings);A.midiAudioChannels.length<t.channelSnapshots.length;)A.createMidiChannel();t.channelSnapshots.forEach((n,s)=>{dt.applyChannelSnapshot(A,s,n)}),y("%cFinished restoring controllers!",I.info)}};function Ir(e){this._snapshot=e,et.applySnapshot(this,e),y("%cFinished applying snapshot!",I.info),this.resetAllControllers()}function Dn(e,A,t){if(t<e)return 0;let n=(t-e)/(1/A)+.25;return Math.abs(n-~~(n+.5))*4-1}var ft=class{static getSampleLinear(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=r;let i=~~s,E=i+1;for(;E>=n.loopEnd;)E-=r;let l=s-i,c=o[E],h=o[i];t[g]=h+(c-h)*l,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r<t.length;r++){let g=~~s,i=g+1;if(i>=n.end){A.finished=!0;return}let E=s-g,l=o[i],c=o[g];t[r]=c+(l-c)*E,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}static getSampleNearest(A,t){let n=A.sample,s=n.cursor,o=n.loopEnd-n.loopStart,r=n.sampleData;if(A.sample.isLooping)for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=o;let i=~~s+1;for(;i>=n.loopEnd;)i-=o;t[g]=r[i],s+=n.playbackStep*A.currentTuningCalculated}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let g=0;g<t.length;g++){let i=~~s+1;if(i>=n.end){A.finished=!0;return}t[g]=r[i],s+=n.playbackStep*A.currentTuningCalculated}}n.cursor=s}static getSampleCubic(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=r;let i=~~s,E=i+1,l=E+1,c=l+1,h=s-i;E>=n.loopEnd&&(E-=r),l>=n.loopEnd&&(l-=r),c>=n.loopEnd&&(c-=r);let B=o[i],m=o[E],f=o[l],S=o[c],G=.5*(f-B),D=B-2.5*m+2*f-.5*S,M=.5*(S-B)+1.5*(m-f);t[g]=((M*h+D)*h+G)*h+m,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r<t.length;r++){let g=~~s,i=g+1,E=i+1,l=E+1,c=s-g;if(i>=n.end||E>=n.end||l>=n.end){A.finished=!0;return}let h=o[g],B=o[i],m=o[E],f=o[l],S=.5*(m-h),G=h-2.5*B+2*m-.5*f,D=.5*(f-h)+1.5*(B-m);t[r]=((D*c+G)*c+S)*c+B,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}};function Er(e,A,t,n,s,o,r,g){if(e.isInRelease||A>=e.releaseStartTime&&(e.isInRelease=!0,ce.startRelease(e),he.startRelease(e),e.sample.loopingMode===3&&(e.sample.isLooping=!1)),e.modulatedGenerators[a.initialAttenuation]>2500)return e.isInRelease&&(e.finished=!0),e.finished;let i=e.targetKey,E=e.modulatedGenerators[a.fineTune]+this.channelOctaveTuning[e.midiNote]+this.channelTuningCents,l=e.modulatedGenerators[a.coarseTune],c=this.synth.tunings[this.preset.program]?.[e.realKey];if(c!==void 0&&c?.midiNote>=0&&(i=c.midiNote,E+=c.centTuning),e.portamentoFromKey>-1){let L=Math.min((A-e.startTime)/e.portamentoDuration,1),nA=i-e.portamentoFromKey;l-=nA*(1-L)}E+=(i-e.sample.rootKey)*e.modulatedGenerators[a.scaleTuning];let h=0,B=0,m=e.modulatedGenerators[a.vibLfoToPitch],f=e.modulatedGenerators[a.vibLfoToVolume],S=e.modulatedGenerators[a.vibLfoToFilterFc];if(m!==0||f!==0||S!==0){let L=e.startTime+Ce(e.modulatedGenerators[a.delayVibLFO]),nA=Ut(e.modulatedGenerators[a.freqVibLFO]),$=Dn(L,nA,A);E+=$*(m*this.customControllers[CA.modulationMultiplier]),B+=-$*f,h+=$*S}let G=e.modulatedGenerators[a.modLfoToPitch],D=e.modulatedGenerators[a.modLfoToVolume],M=e.modulatedGenerators[a.modLfoToFilterFc];if(G!==0||M!==0||D!==0){let L=e.startTime+Ce(e.modulatedGenerators[a.delayModLFO]),nA=Ut(e.modulatedGenerators[a.freqModLFO]),$=Dn(L,nA,A);E+=$*(G*this.customControllers[CA.modulationMultiplier]),B+=-$*D,h+=$*M}if(this.channelVibrato.depth>0){let L=Dn(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,A);L&&(E+=L*this.channelVibrato.depth)}let T=e.modulatedGenerators[a.modEnvToPitch],R=e.modulatedGenerators[a.modEnvToFilterFc];if(R!==0||T!==0){let L=he.getValue(e,A);h+=L*R,E+=L*T}let C=~~(E+l*100);C!==e.currentTuningCents&&(e.currentTuningCents=C,e.currentTuningCalculated=Math.pow(2,C/1200));let b=new Float32Array(t.length);switch(this.synth.interpolationType){case ze.fourthOrder:ft.getSampleCubic(e,b);break;case ze.linear:default:ft.getSampleLinear(e,b);break;case ze.nearestNeighbor:ft.getSampleNearest(e,b);break}return Oe.apply(e,b,h,this.synth.filterSmoothingFactor),ce.apply(e,b,B,this.synth.volumeEnvelopeSmoothingFactor),this.panVoice(e,b,t,n,s,o,r,g),e.finished}function Cr(e,A=-12e3){e+=this.customControllers[CA.channelKeyShift],this.voices.forEach(t=>{t.realKey===e&&(t.modulatedGenerators[a.releaseVolEnv]=A,t.release(this.synth.currentSynthTime))})}function cr(e,A=!0){e=Math.round(e),this.setCustomController(CA.channelTuning,e),A&&y(`%cFine tuning for %c${this.channelNumber}%c is now set to %c${e}%c cents.`,I.info,I.recognized,I.info,I.value,I.info)}function hr(e){e=Math.round(e),y(`%cChannel ${this.channelNumber} modulation depth. Cents: %c${e}`,I.info,I.value),this.setCustomController(CA.modulationMultiplier,e/50)}var Le={pitchBendRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},kn={partParameter:1,awe32:127},ut={vibratoRate:8,vibratoDepth:9,vibratoDelay:10,TVFFilterCutoff:32,TVFFilterResonance:33,EGAttackTime:99,EGReleaseTime:102};function lr(e){this.midiControllers[p.dataEntryMsb]=e<<7;let A=()=>{this.channelVibrato.delay===0&&this.channelVibrato.rate===0&&this.channelVibrato.depth===0&&(this.channelVibrato.depth=50,this.channelVibrato.rate=8,this.channelVibrato.delay=.6)},t=(n,s,o)=>{o.length>0&&(o=" "+o),y(`%c${n} for %c${this.channelNumber}%c is now set to %c${s}%c${o}.`,I.info,I.recognized,I.info,I.value,I.info)};switch(this.dataEntryState){default:case UA.Idle:break;case UA.NRPFine:if(this.lockGSNRPNParams)return;let n=this.midiControllers[p.NRPNMsb]>>7,s=this.midiControllers[p.NRPNLsb]>>7;switch(n){default:if(e===64)return;Y(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${s.toString(16).toUpperCase()} 0x${s.toString(16).toUpperCase()})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case kn.partParameter:switch(s){default:if(e===64)return;Y(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${n.toString(16)} 0x${s.toString(16)})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case ut.vibratoRate:if(e===64)return;A(),this.channelVibrato.rate=e/64*8,t("Vibrato rate",`${e} = ${this.channelVibrato.rate}`,"Hz");break;case ut.vibratoDepth:if(e===64)return;A(),this.channelVibrato.depth=e/2,t("Vibrato depth",`${e} = ${this.channelVibrato.depth}`,"cents of detune");break;case ut.vibratoDelay:if(e===64)return;A(),this.channelVibrato.delay=e/64/3,t("Vibrato delay",`${e} = ${this.channelVibrato.delay}`,"seconds");break;case ut.TVFFilterCutoff:this.controllerChange(p.brightness,e),t("Filter cutoff",e.toString(),"");break;case ut.EGAttackTime:this.controllerChange(p.attackTime,e),t("EG attack time",e.toString(),"");break;case ut.EGReleaseTime:this.controllerChange(p.releaseTime,e),t("EG release time",e.toString(),"");break}break;case kn.awe32:break}break;case UA.RPCoarse:case UA.RPFine:let o=this.midiControllers[p.RPNMsb]|this.midiControllers[p.RPNLsb]>>7;switch(o){default:Y(`%cUnrecognized RPN for %c${this.channelNumber}%c: %c(0x${o.toString(16)})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Le.pitchBendRange:this.midiControllers[BA+_.pitchWheelRange]=e<<7,t("Pitch bend range",e.toString(),"semitones");break;case Le.coarseTuning:let r=e-64;this.setCustomController(CA.channelTuningSemitones,r),t("Coarse tuning",r.toString(),"semitones");break;case Le.fineTuning:this.setTuning(e-64,!1);break;case Le.modulationDepth:this.setModulationDepth(e*100);break;case Le.resetParameters:this.resetParameters();break}}}var Ti=[a.delayModLFO,a.freqModLFO,a.delayVibLFO,a.freqVibLFO,a.delayModEnv,a.attackModEnv,a.holdModEnv,a.decayModEnv,a.sustainModEnv,a.releaseModEnv,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.fineTune,a.modLfoToPitch,a.vibLfoToPitch,a.modEnvToPitch,a.modLfoToVolume,a.initialFilterFc,a.initialFilterQ,a.modLfoToFilterFc,a.modEnvToFilterFc,a.chorusEffectsSend,a.reverbEffectsSend];function Br(e,A,t){let n=(h,B,m)=>Math.max(B,Math.min(m,h)),s=h=>Math.max(-32768,1200*Math.log2(h/1e3)),o=h=>6900+1200*Math.log2(h/440),r=t<<7|A;r-=8192;let g=Ti[e];g||Y(`Invalid AWE32 LSB: %c${e}`,I.unrecognized);let i,E,l,c;switch(g){default:break;case a.delayModLFO:case a.delayVibLFO:case a.delayVolEnv:case a.delayModEnv:i=4*n(r,0,5900),this.setGeneratorOverride(g,s(i));break;case a.attackVolEnv:case a.attackModEnv:i=n(r,0,5940),this.setGeneratorOverride(g,s(i));break;case a.holdVolEnv:case a.holdModEnv:i=n(r,0,8191),this.setGeneratorOverride(g,s(i));break;case a.decayModEnv:case a.decayVolEnv:case a.releaseVolEnv:case a.releaseModEnv:i=4*n(r,0,5940),this.setGeneratorOverride(g,s(i));break;case a.freqVibLFO:case a.freqModLFO:E=.084*A,this.setGeneratorOverride(g,o(E),!0);break;case a.sustainVolEnv:case a.sustainModEnv:l=A*7.5,this.setGeneratorOverride(g,l);break;case a.fineTune:this.setGeneratorOverride(g,r,!0);break;case a.modLfoToPitch:case a.vibLfoToPitch:c=n(r,-127,127)*9.375,this.setGeneratorOverride(g,c,!0);break;case a.modEnvToPitch:c=n(r,-127,127)*9.375,this.setGeneratorOverride(g,c);break;case a.modLfoToVolume:l=1.875*A,this.setGeneratorOverride(g,l,!0);break;case a.initialFilterFc:let h=4335+59*A;this.setGeneratorOverride(g,h,!0);break;case a.initialFilterQ:l=215*(A/127),this.setGeneratorOverride(g,l,!0);break;case a.modLfoToFilterFc:c=n(r,-64,63)*56.25,this.setGeneratorOverride(g,c,!0);break;case a.modEnvToFilterFc:c=n(r,-64,63)*56.25,this.setGeneratorOverride(g,c);break;case a.chorusEffectsSend:case a.reverbEffectsSend:this.setGeneratorOverride(g,n(r,0,255)*(1e3/255));break}}function Qr(e){switch(this.midiControllers[p.lsbForControl6DataEntry]=e<<7,this.dataEntryState){default:break;case UA.RPCoarse:case UA.RPFine:switch(this.midiControllers[p.RPNMsb]|this.midiControllers[p.RPNLsb]>>7){default:break;case Le.pitchBendRange:if(e===0)break;this.midiControllers[BA+_.pitchWheelRange]|=e;let s=(this.midiControllers[BA+_.pitchWheelRange]>>7)+e/128;y(`%cChannel ${this.channelNumber} bend range. Semitones: %c${s}`,I.info,I.value);break;case Le.fineTuning:let r=this.customControllers[CA.channelTuning]<<7|e;this.setTuning(r*.01220703125);break;case Le.modulationDepth:let i=this.customControllers[CA.modulationMultiplier]*50+e/128*100;this.setModulationDepth(i);break;case 16383:this.resetParameters();break}break;case UA.NRPFine:let t=this.midiControllers[p.NRPNMsb]>>7,n=this.midiControllers[p.NRPNLsb]>>7;switch(t){default:Y(`%cUnrecognized NRPN LSB for %c${this.channelNumber}%c: %c(0x${n.toString(16).toUpperCase()} 0x${n.toString(16).toUpperCase()})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case kn.awe32:Br.call(this,n,e,this.midiControllers[p.dataEntryMsb]>>7);break}}}var Ui=1e3/200;function dr(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=e[A.sourceIndex];else{let E=A.sourceIndex+BA;switch(A.sourceIndex){case _.noController:n=16383;break;case _.noteOnKeyNum:n=t.midiNote<<7;break;case _.noteOnVelocity:n=t.velocity<<7;break;case _.polyPressure:n=t.pressure<<7;break;default:n=e[E];break}}let s=tt[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let E=A.secSrcIndex+BA;switch(A.secSrcIndex){case _.noController:o=16383;break;case _.noteOnKeyNum:o=t.midiNote<<7;break;case _.noteOnVelocity:o=t.velocity<<7;break;case _.polyPressure:o=t.pressure<<7;break;default:o=e[E]}}let r=tt[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=A.transformAmount;A.isEffectModulator&&g<=1e3&&(g*=Ui,g=Math.min(g,1e3));let i=s*r*g;return A.transformType===2&&(i=Math.abs(i)),A.currentValue=i,i}function te(e,A,t=-1,n=0){let s=e.modulators,o=e.generators,r=e.modulatedGenerators;if(t===-1){r.set(o),s.forEach(E=>{let l=Z[E.modulatorDestination],c=r[E.modulatorDestination]+dr(A,E,e);r[E.modulatorDestination]=Math.max(l.min,Math.min(c,l.max))}),ce.recalculate(e),he.recalculate(e);return}let g=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),i=new Set;s.forEach(E=>{if(E.sourceUsesCC===t&&E.sourceIndex===n||E.secSrcUsesCC===t&&E.secSrcIndex===n){let l=E.modulatorDestination;i.has(l)||(r[l]=o[l],dr(A,E,e),s.forEach(c=>{if(c.modulatorDestination===l){let h=Z[E.modulatorDestination],B=r[E.modulatorDestination]+c.currentValue;r[E.modulatorDestination]=Math.max(h.min,Math.min(B,h.max))}}),i.add(l))}}),[...i].some(E=>g.has(E))&&ce.recalculate(e),he.recalculate(e)}var tt=[];for(let e=0;e<4;e++){tt[e]=[[new Float32Array(bA),new Float32Array(bA)],[new Float32Array(bA),new Float32Array(bA)]];for(let A=0;A<bA;A++)tt[e][0][0][A]=$e(0,e,A/bA,0),tt[e][1][0][A]=$e(0,e,A/bA,1),tt[e][0][1][A]=$e(1,e,A/bA,0),tt[e][1][1][A]=$e(1,e,A/bA,1)}function fr(e,A,t=!1){if(e>127){if(!t)return;switch(e){default:return;case is.velocityOverride:this.velocityOverride=A}}if(e>=p.lsbForControl1ModulationWheel&&e<=p.lsbForControl13EffectControl2&&e!==p.lsbForControl6DataEntry){let n=e-32;if(this.lockedControllers[n])return;this.midiControllers[n]=this.midiControllers[n]&16256|A&127,this.voices.forEach(s=>te(s,this.midiControllers,1,n))}if(!this.lockedControllers[e]){switch(this.midiControllers[e]=A<<7,e){case p.allNotesOff:this.stopAllNotes();break;case p.allSoundOff:this.stopAllNotes(!0);break;case p.bankSelect:this.setBankSelect(A);break;case p.lsbForControl0BankSelect:this.setBankSelect(A,!0);break;case p.RPNLsb:this.dataEntryState=UA.RPFine;break;case p.RPNMsb:this.dataEntryState=UA.RPCoarse;break;case p.NRPNMsb:this.dataEntryState=UA.NRPCoarse;break;case p.NRPNLsb:this.dataEntryState=UA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(A);break;case p.lsbForControl6DataEntry:this.dataEntryFine(A);break;case p.resetAllControllers:this.resetControllersRP15Compliant();break;case p.sustainPedal:A>=64?this.holdPedal=!0:(this.holdPedal=!1,this.sustainedVoices.forEach(n=>{n.release(this.synth.currentSynthTime)}),this.sustainedVoices=[]);break;default:this.voices.forEach(n=>te(n,this.midiControllers,1,e));break}this.synth.callEvent("controllerchange",{channel:this.channelNumber,controllerNumber:e,controllerValue:A})}}function ur(e=!1){e?(this.voices.length=0,this.sustainedVoices.length=0,this.sendChannelProperty()):(this.voices.forEach(A=>{A.isInRelease||A.release(this.synth.currentSynthTime)}),this.sustainedVoices.forEach(A=>{A.release(this.synth.currentSynthTime)}))}function mr(e){e&&this.stopAllNotes(!0),this.isMuted=e,this.sendChannelProperty(),this.synth.callEvent("mutechannel",{channel:this.channelNumber,isMuted:e})}function pr(e,A=!1){this.drumChannel||(e+=this.synth.transposition);let t=Math.trunc(e),n=this.channelTransposeKeyShift+this.customControllers[CA.channelTransposeFine]/100;this.drumChannel&&!A||e===n||(t!==this.channelTransposeKeyShift&&this.controllerChange(p.allNotesOff,127),this.channelTransposeKeyShift=t,this.setCustomController(CA.channelTransposeFine,(e-t)*100),this.sendChannelProperty())}var Jt={0:0,1:.006,2:.023,4:.05,8:.11,16:.25,32:.5,64:2.06,80:4.2,96:8.4,112:19.5,116:26.7,120:40,124:80,127:480};function vi(e){if(Jt[e]!==void 0)return Jt[e];let A=null,t=null;for(let n of Object.keys(Jt))n=parseInt(n),n<e&&(A===null||n>A)&&(A=n),n>e&&(t===null||n<t)&&(t=n);if(A!==null&&t!==null){let n=Jt[A],s=Jt[t];return n+(e-A)*(s-n)/(t-A)}return 0}function yr(e,A){return vi(e)*(A/30)}function Sr(e,A){if(A<1){this.noteOff(e);return}if(A=Math.min(127,A),this.synth.highPerformanceMode&&this.synth.totalVoicesAmount>200&&A<40||this.synth.highPerformanceMode&&A<10||this.isMuted)return;let t=e+this.channelTransposeKeyShift+this.customControllers[CA.channelKeyShift],n=t;if(t>127||t<0)return;let s=this.preset.program,o=this.synth.tunings[s]?.[t]?.midiNote;o>=0&&(n=o),this.velocityOverride>0&&(A=this.velocityOverride);let r=this.synth.keyModifierManager.getVelocity(this.channelNumber,t);r>-1&&(A=r);let g=this.synth.keyModifierManager.getGain(this.channelNumber,t),i=-1,E=0,l=this.midiControllers[p.portamentoTime]>>7,c=this.midiControllers[p.portamentoControl],h=c>>7;if(!this.drumChannel&&h!==n&&this.midiControllers[p.portamentoOnOff]>=8192&&l>0){if(c!==1){let S=Math.abs(n-h);E=yr(l,S),i=h}this.controllerChange(p.portamentoControl,n)}let B=this.synth.getVoices(this.channelNumber,n,A,t),m=0;this.randomPan&&(m=Math.round(Math.random()*1e3-500));let f=this.voices;B.forEach(S=>{S.portamentoFromKey=i,S.portamentoDuration=E,S.overridePan=m,S.gain=g,this.sysExModulators.modulatorList.forEach(L=>{let nA=L.mod,$=S.modulators.findIndex(U=>X.isIdentical(U,nA));$!==-1?S.modulators[$]=X.copy(nA):S.modulators.push(X.copy(nA))}),this.generatorOverridesEnabled&&this.generatorOverrides.forEach((L,nA)=>{L!==nn&&(S.generators[nA]=L)});let G=S.exclusiveClass;G!==0&&f.forEach(L=>{L.exclusiveClass===G&&L.exclusiveRelease(this.synth.currentSynthTime)}),te(S,this.midiControllers);let D=S.modulatedGenerators[a.startAddrsOffset]+S.modulatedGenerators[a.startAddrsCoarseOffset]*32768,M=S.modulatedGenerators[a.endAddrOffset]+S.modulatedGenerators[a.endAddrsCoarseOffset]*32768,T=S.modulatedGenerators[a.startloopAddrsOffset]+S.modulatedGenerators[a.startloopAddrsCoarseOffset]*32768,R=S.modulatedGenerators[a.endloopAddrsOffset]+S.modulatedGenerators[a.endloopAddrsCoarseOffset]*32768,C=S.sample,b=L=>Math.max(0,Math.min(C.sampleData.length-1,L));if(C.cursor=b(C.cursor+D),C.end=b(C.end+M),C.loopStart=b(C.loopStart+T),C.loopEnd=b(C.loopEnd+R),C.loopEnd<C.loopStart){let L=C.loopStart;C.loopStart=C.loopEnd,C.loopEnd=L}C.loopEnd-C.loopStart<1&&(C.loopingMode=0,C.isLooping=!1),S.volumeEnvelope.attenuation=S.volumeEnvelope.attenuationTargetGain,S.currentPan=Math.max(-500,Math.min(500,S.modulatedGenerators[a.pan]))}),this.synth.totalVoicesAmount+=B.length,this.synth.totalVoicesAmount>this.synth.voiceCap&&this.synth.voiceKilling(B.length),f.push(...B),this.sendChannelProperty(),this.synth.callEvent("noteon",{midiNote:e,channel:this.channelNumber,velocity:A})}function Dr(e){if(e>127||e<0){Y("Received a noteOn for note",e,"Ignoring.");return}let A=e+this.channelTransposeKeyShift+this.customControllers[CA.channelKeyShift];if(this.synth.highPerformanceMode&&!this.drumChannel){this.killNote(A,-6950),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber});return}this.voices.forEach(n=>{n.realKey!==A||n.isInRelease===!0||(this.holdPedal?this.sustainedVoices.push(n):n.release(this.synth.currentSynthTime))}),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber})}function kr(e,A){this.voices.forEach(t=>{t.midiNote===e&&(t.pressure=A,te(t,this.midiControllers,0,_.polyPressure))}),this.synth.callEvent("polypressure",{channel:this.channelNumber,midiNote:e,pressure:A})}function Fr(e){this.midiControllers[BA+_.channelPressure]=e<<7,this.updateChannelTuning(),this.voices.forEach(A=>te(A,this.midiControllers,0,_.channelPressure)),this.synth.callEvent("channelpressure",{channel:this.channelNumber,pressure:e})}function wr(e,A){if(this.lockedControllers[BA+_.pitchWheel])return;let t=A|e<<7;this.synth.callEvent("pitchwheel",{channel:this.channelNumber,MSB:e,LSB:A}),this.midiControllers[BA+_.pitchWheel]=t,this.voices.forEach(n=>te(n,this.midiControllers,0,_.pitchWheel)),this.sendChannelProperty()}function Rr(e){if(e.length!==12)throw new Error("Tuning is not the length of 12.");this.channelOctaveTuning=new Int8Array(128);for(let A=0;A<128;A++)this.channelOctaveTuning[A]=e[A%12]}function Gr(e){if(this.lockPreset)return;let A=this.getBankSelect(),t=this.isXGChannel,n=this.synth.soundfontManager.getPreset(A,e,t),s=n.preset;this.setPreset(s),this.sentBank=Math.min(128,s.bank+n.bankOffset),this.synth.callEvent("programchange",{channel:this.channelNumber,program:s.program,bank:this.sentBank}),this.sendChannelProperty()}var Fn=class{modulatorList=[];resetModulators(){this.modulatorList=[]}_getModulatorId(A,t,n,s){return`${A}-${t}-${n}-${s}`}_deleteModulator(A){this.modulatorList=this.modulatorList.filter(t=>t.id!==A)}setModulator(A,t,n,s=!1,o=!1){let r=this._getModulatorId(A,t,s,o);n===0&&this._deleteModulator(r);let g=this.modulatorList.find(i=>i.id===r);if(g)g.mod.transformAmount=n;else{let i,E;A>=BA?(i=A-BA,E=!1):(i=A,E=!0);let l=new X(ZA(FA.linear,s,0,E,i),0,t,n,0);this.modulatorList.push({mod:l,id:r})}}};var DA=class{midiControllers=new Int16Array(gn);lockedControllers=Array(gn).fill(!1);customControllers=new Float32Array(os);channelTransposeKeyShift=0;channelOctaveTuning=new Int8Array(128);channelTuningCents=0;sysExModulators=new Fn;generatorOverrides=new Int16Array(on);generatorOverridesEnabled=!1;holdPedal=!1;drumChannel=!1;velocityOverride=0;randomPan=!1;dataEntryState=UA.Idle;bank=0;sentBank=0;bankLSB=0;preset=void 0;lockPreset=!1;lockedSystem="gs";lockGSNRPNParams=!1;channelVibrato={delay:0,depth:0,rate:0};isMuted=!1;voices=[];sustainedVoices=[];channelNumber;synth;constructor(A,t,n){this.synth=A,this.preset=t,this.channelNumber=n,this.resetGeneratorOverrides()}get isXGChannel(){return GA(this.synth.system)||this.lockPreset&&GA(this.lockedSystem)}setCustomController(A,t){this.customControllers[A]=t,this.updateChannelTuning()}updateChannelTuning(){this.channelTuningCents=this.customControllers[CA.channelTuning]+this.customControllers[CA.channelTransposeFine]+this.customControllers[CA.masterTuning]+this.customControllers[CA.channelTuningSemitones]*100}renderAudio(A,t,n,s,o,r){this.voices=this.voices.filter(g=>!this.renderVoice(g,this.synth.currentSynthTime,A,t,n,s,o,r))}setPresetLock(A){this.lockPreset=A,A&&(this.lockedSystem=this.synth.system)}setBankSelect(A,t=!1){if(!this.lockPreset)if(t)this.bankLSB=A;else switch(this.bank=A,lt(this.getBankSelect(),A,this.synth.system,!1,this.drumChannel,this.channelNumber).drumsStatus){default:case 0:break;case 1:this.channelNumber%16===9&&(this.bank=127);break;case 2:this.setDrums(!0);break}}getBankSelect(){return Bt(this.bank,this.bankLSB,this.drumChannel,this.isXGChannel)}setPreset(A){this.lockPreset||(delete this.preset,this.preset=A)}setDrums(A){this.lockPreset||this.drumChannel!==A&&(A?(this.channelTransposeKeyShift=0,this.drumChannel=!0):this.drumChannel=!1,this.synth.callEvent("drumchange",{channel:this.channelNumber,isDrumChannel:this.drumChannel}),this.programChange(this.preset.program),this.sendChannelProperty())}setVibrato(A,t,n){this.lockGSNRPNParams||(this.channelVibrato.rate=t,this.channelVibrato.delay=n,this.channelVibrato.depth=A)}disableAndLockGSNRPN(){this.lockGSNRPNParams=!0,this.channelVibrato.rate=0,this.channelVibrato.delay=0,this.channelVibrato.depth=0}sendChannelProperty(){if(!this.synth.enableEventSystem)return;let A={voicesAmount:this.voices.length,pitchBend:this.midiControllers[BA+_.pitchWheel],pitchBendRangeSemitones:this.midiControllers[BA+_.pitchWheelRange]/128,isMuted:this.isMuted,isDrum:this.drumChannel,transposition:this.channelTransposeKeyShift+this.customControllers[CA.channelTransposeFine]/100,bank:this.sentBank,program:this.preset.program};this.synth?.onChannelPropertyChange?.(A,this.channelNumber)}resetGeneratorOverrides(){this.generatorOverrides.fill(nn),this.generatorOverridesEnabled=!1}setGeneratorOverride(A,t,n=!1){this.generatorOverrides[A]=t,this.generatorOverridesEnabled=!0,n&&this.voices.forEach(s=>{s.generators[A]=t,te(s,this.midiControllers)})}};DA.prototype.renderVoice=Er;DA.prototype.panVoice=fo;DA.prototype.killNote=Cr;DA.prototype.stopAllNotes=ur;DA.prototype.muteChannel=mr;DA.prototype.noteOn=Sr;DA.prototype.noteOff=Dr;DA.prototype.polyPressure=kr;DA.prototype.channelPressure=Fr;DA.prototype.pitchWheel=wr;DA.prototype.programChange=Gr;DA.prototype.setTuning=cr;DA.prototype.setOctaveTuning=Rr;DA.prototype.setModulationDepth=hr;DA.prototype.transposeChannel=pr;DA.prototype.controllerChange=fr;DA.prototype.resetControllers=oo;DA.prototype.resetControllersRP15Compliant=ro;DA.prototype.resetParameters=io;DA.prototype.dataEntryFine=Qr;DA.prototype.dataEntryCoarse=lr;function Mr(e=!1){let A=new DA(this,this.defaultPreset,this.midiAudioChannels.length);this.midiAudioChannels.push(A),e&&(this.callEvent("newchannel",void 0),A.sendChannelProperty(),this.midiAudioChannels[this.midiAudioChannels.length-1].setDrums(!0))}var ps={enableEventSystem:!0,initialTime:0,effectsEnabled:!0,midiChannels:16};function xr(e,A){e===void 0&&(e={});for(let t in A)A.hasOwnProperty(t)&&!(t in e)&&(e[t]=A[t]);return e}var Hi={time:0},Eo=.03,Co=.07,ts=1,LA=class{cachedVoices=[];deviceID=-1;eventQueue=[];interpolationType=ze.fourthOrder;transposition=0;tunings=[];soundfontBankOffset=0;masterGain=ts;midiVolume=1;reverbGain=1;chorusGain=1;reverbSend=1;chorusSend=1;voiceCap=350;pan=0;panLeft=.5;panRight=.5;highPerformanceMode=!1;keyModifierManager=new En;midiAudioChannels=[];system=Tt;totalVoicesAmount=0;defaultPreset;drumPreset;processorInitialized=me.isInitialized;currentSynthTime=0;sampleRate;sampleTime;effectsEnabled;_snapshot;onEventCall;onChannelPropertyChange;onMasterParameterChange;constructor(A,t=ps){t=xr(t,ps),this.midiOutputsCount=t.midiChannels,this.effectsEnabled=t.effectsEnabled,this.enableEventSystem=t.enableEventSystem,this.currentSynthTime=t.initialTime,this.sampleTime=1/A,this.sampleRate=A,this.volumeEnvelopeSmoothingFactor=Ws*(44100/A),this.panSmoothingFactor=ho*(44100/A),this.filterSmoothingFactor=ao*(44100/A);for(let n=0;n<128;n++)this.tunings.push([]);this.soundfontManager=new Qt(this.updatePresetList.bind(this));for(let n=0;n<this.midiOutputsCount;n++)this.createMidiChannel(!1);this.processorInitialized.then(()=>{y("%cSpessaSynth is ready!",I.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}getDefaultPresets(){let A=this.system;this.system="xg",this.defaultPreset=this.getPreset(0,0),this.system=A,this.drumPreset=this.getPreset(128,0)}setSystem(A){this.system=A,this?.onMasterParameterChange?.(OA.midiSystem,this.system)}getCachedVoice(A,t,n,s){return this.cachedVoices?.[A]?.[t]?.[n]?.[s]}setCachedVoice(A,t,n,s,o){this.cachedVoices[A]||(this.cachedVoices[A]=[]),this.cachedVoices[A][t]||(this.cachedVoices[A][t]=[]),this.cachedVoices[A][t][n]||(this.cachedVoices[A][t][n]=[]),this.cachedVoices[A][t][n][s]=o}renderAudio(A,t,n){this.renderAudioSplit(t,n,Array(16).fill(A))}renderAudioSplit(A,t,n){let s=this.currentSynthTime;for(;this.eventQueue[0]?.time<=s;)this.eventQueue.shift().callback();let o=A[0],r=A[1],g=t[0],i=t[1];this.totalVoicesAmount=0,this.midiAudioChannels.forEach((E,l)=>{if(E.voices.length<1||E.isMuted)return;let c=E.voices.length,h=l%16;E.renderAudio(n[h][0],n[h][1],o,r,g,i),this.totalVoicesAmount+=E.voices.length,E.voices.length!==c&&E.sendChannelProperty()}),this.currentSynthTime+=n[0][0].length*this.sampleTime}destroySynthProcessor(){this.midiAudioChannels.forEach(A=>{delete A.midiControllers,delete A.voices,delete A.sustainedVoices,delete A.lockedControllers,delete A.preset,delete A.customControllers}),delete this.cachedVoices,delete this.midiAudioChannels,this.soundfontManager.destroyManager(),delete this.soundfontManager}controllerChange(A,t,n,s=!1){this.midiAudioChannels[A].controllerChange(t,n,s)}noteOn(A,t,n){this.midiAudioChannels[A].noteOn(t,n)}noteOff(A,t){this.midiAudioChannels[A].noteOff(t)}polyPressure(A,t,n){this.midiAudioChannels[A].polyPressure(t,n)}channelPressure(A,t){this.midiAudioChannels[A].channelPressure(t)}pitchWheel(A,t,n){this.midiAudioChannels[A].pitchWheel(t,n)}programChange(A,t){this.midiAudioChannels[A].programChange(t)}processMessage(A,t=0,n=!1,s=Hi){let o=()=>{let g=ht(A[0]),i=g.channel+t;switch(g.status){case F.noteOn:let E=A[2];E>0?this.noteOn(i,A[1],E):this.noteOff(i,A[1]);break;case F.noteOff:n?this.midiAudioChannels[i].killNote(A[1]):this.noteOff(i,A[1]);break;case F.pitchBend:this.pitchWheel(i,A[2],A[1]);break;case F.controllerChange:this.controllerChange(i,A[1],A[2],n);break;case F.programChange:this.programChange(i,A[1]);break;case F.polyPressure:this.polyPressure(i,A[0],A[1]);break;case F.channelPressure:this.channelPressure(i,A[1]);break;case F.systemExclusive:this.systemExclusive(new x(A.slice(1)),t);break;case F.reset:this.stopAllChannels(!0),this.resetAllControllers();break;default:break}},r=s.time;r>this.currentSynthTime?(this.eventQueue.push({callback:o.bind(this),time:r}),this.eventQueue.sort((g,i)=>g.time-i.time)):o()}setMIDIVolume(A){this.midiVolume=Math.pow(A,Math.E),this.setMasterParameter(OA.masterPan,this.pan)}callEvent(A,t){this?.onEventCall?.(A,t)}clearCache(){this.cachedVoices=[]}getPreset(A,t){return this.soundfontManager.getPreset(A,t,GA(this.system)).preset}};LA.prototype.voiceKilling=qs;LA.prototype.getVoicesForPreset=go;LA.prototype.getVoices=Io;LA.prototype.systemExclusive=no;LA.prototype.stopAllChannels=uo;LA.prototype.createMidiChannel=Mr;LA.prototype.resetAllControllers=so;LA.prototype.setMasterParameter=Ao;LA.prototype.transposeAllChannels=ar;LA.prototype.setMasterTuning=gr;LA.prototype.clearEmbeddedBank=or;LA.prototype.setEmbeddedSoundFont=rr;LA.prototype.updatePresetList=ir;LA.prototype.applySynthesizerSnapshot=Ir;function KA(e,A){let t=0;for(let n=8*(A-1);n>=0;n-=8)t|=e[e.currentIndex++]<<n;return t>>>0}function Kt(e,A){let t=new Array(A).fill(0);for(let n=A-1;n>=0;n--)t[n]=e&255,e>>=8;return t}function br(e,A){if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=ht(e.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=n,t.status){case F.noteOn:let s=e.messageData[1];if(s>0)this.synth.noteOn(t.channel,e.messageData[0],s),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:s});else{this.synth.noteOff(t.channel,e.messageData[0]);let g=this.playingNotes.findIndex(i=>i.midiNote===e.messageData[0]&&i.channel===t.channel);g!==-1&&this.playingNotes.splice(g,1)}break;case F.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let o=this.playingNotes.findIndex(g=>g.midiNote===e.messageData[0]&&g.channel===t.channel);o!==-1&&this.playingNotes.splice(o,1);break;case F.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case F.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case F.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.programChange(t.channel,e.messageData[0]);break;case F.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case F.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case F.systemExclusive:this.synth.systemExclusive(e.messageData,n);break;case F.setTempo:e.messageData.currentIndex=0;let r=6e7/KA(e.messageData,3);this.oneTickToSeconds=60/(r*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),Y("invalid tempo! falling back to 120 BPM"),r=120);break;case F.timeSignature:case F.endOfTrack:case F.midiChannelPrefix:case F.songPosition:case F.activeSensing:case F.keySignature:case F.sequenceNumber:case F.sequenceSpecific:case F.text:case F.lyric:case F.copyright:case F.trackName:case F.marker:case F.cuePoint:case F.instrumentName:case F.programName:break;case F.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case F.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:Y(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(F).find(g=>F[g]===t.status)}`,I.warn,I.unrecognized,I.warn,I.value);break}t.status>=0&&t.status<128&&this?.onMetaEvent?.(e,A)}function Lr(){for(let e=0;e<16;e++)this.synth.createMidiChannel(!0)}function Tr(){if(!this.isActive)return;let e=this.currentTime;for(;this.playedTime<e;){let A=this._findFirstEventIndex(),t=this.tracks[A][this.eventIndex[A]];if(this._processEvent(t,A),this.eventIndex[A]++,A=this._findFirstEventIndex(),this.tracks[A].length<=this.eventIndex[A]){if(this.loop){this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];this.playedTime+=this.oneTickToSeconds*(n.ticks-t.ticks);let s=this.loop&&(this.loopCount>0||this.loopCount===-1);if(this.midiData.loop.end<=t.ticks&&s){this.loopCount!==1/0&&(this.loopCount--,this?.onLoopCountChange?.(this.loopCount)),this.setTimeTicks(this.midiData.loop.start);return}else if(e>=this.duration){if(s){this.loopCount!==1/0&&(this.loopCount--,this?.onLoopCountChange?.(this.loopCount)),this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function Ur(){let e=0,A=1/0;return this.tracks.forEach((t,n)=>{this.eventIndex[n]>=t.length||t[this.eventIndex[n]].ticks<A&&(e=n,A=t[this.eventIndex[n]].ticks)}),e}var nt=class{timeDivision=0;duration=0;tempoChanges=[{ticks:0,tempo:120}];copyright="";tracksAmount=0;trackNames=[];lyrics=[];lyricsTicks=[];firstNoteOn=0;keyRange={min:0,max:127};lastVoiceEventTick=0;midiPorts=[0];midiPortChannelOffsets=[0];usedChannelsOnTrack=[];loop={start:0,end:0};midiName="";midiNameUsesFileName=!1;fileName="";rawMidiName;format=0;RMIDInfo={};bankOffset=0;isKaraokeFile=!1;isMultiPort=!1;MIDIticksToSeconds(A){let t=0;for(;A>0;){let n=this.tempoChanges.find(o=>o.ticks<A),s=A-n.ticks;t+=s*60/(n.tempo*this.timeDivision),A-=s}return t}_copyFromSequence(A){this.midiName=A.midiName,this.midiNameUsesFileName=A.midiNameUsesFileName,this.fileName=A.fileName,this.timeDivision=A.timeDivision,this.duration=A.duration,this.copyright=A.copyright,this.tracksAmount=A.tracksAmount,this.firstNoteOn=A.firstNoteOn,this.lastVoiceEventTick=A.lastVoiceEventTick,this.format=A.format,this.bankOffset=A.bankOffset,this.isKaraokeFile=A.isKaraokeFile,this.isMultiPort=A.isMultiPort,this.tempoChanges=[...A.tempoChanges],this.lyrics=A.lyrics.map(t=>new Uint8Array(t)),this.lyricsTicks=[...A.lyricsTicks],this.midiPorts=[...A.midiPorts],this.trackNames=[...A.trackNames],this.midiPortChannelOffsets=[...A.midiPortChannelOffsets],this.usedChannelsOnTrack=A.usedChannelsOnTrack.map(t=>new Set(t)),this.rawMidiName=A.rawMidiName?new Uint8Array(A.rawMidiName):void 0,this.loop={...A.loop},this.keyRange={...A.keyRange},this.RMIDInfo={...A.RMIDInfo}}};function mA(e){let A=0;for(;e;){let t=e[e.currentIndex++];if(A=A<<7|t&127,t>>7!==1)break}return A}function wn(e){let A=[e&127];for(e>>=7;e>0;)A.unshift(e&127|128),e>>=7;return A}function vr(){let e=this;if(!e.tracks)throw new Error("MIDI has no tracks!");let A=[];for(let s of e.tracks){let o=[],r=0,g;for(let i of s){let E=i.ticks-r,l;i.messageStatusByte<=F.sequenceSpecific?l=[255,i.messageStatusByte,...wn(i.messageData.length),...i.messageData]:i.messageStatusByte===F.systemExclusive?l=[240,...wn(i.messageData.length),...i.messageData]:(l=[],g!==i.messageStatusByte&&(g=i.messageStatusByte,l.push(i.messageStatusByte)),l.push(...i.messageData)),o.push(...wn(E)),o.push(...l),r+=E}A.push(new Uint8Array(o))}function t(s,o){for(let r=0;r<s.length;r++)o.push(s.charCodeAt(r))}let n=[];t("MThd",n),n.push(...Kt(6,4)),n.push(0,e.format),n.push(...Kt(e.tracksAmount,2)),n.push(...Kt(e.timeDivision,2));for(let s of A)t("MTrk",n),n.push(...Kt(s.length,4)),n.push(...s);return new Uint8Array(n)}function mt(e){return e.messageData[0]===67&&e.messageData[2]===76&&e.messageData[5]===126&&e.messageData[6]===0}function Rn(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[3]===18&&e.messageData[4]===64&&(e.messageData[5]&16)!==0&&e.messageData[6]===21}function Gn(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[6]===127}function Mn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===1}function xn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===3}function ys(e){return new YA(e,F.systemExclusive,new x([65,16,66,18,64,0,127,0,65,247]))}function pt(e,A,t,n){return new YA(n,F.controllerChange|e%16,new x([A,t]))}function Yi(e,A){let t=16|[1,2,3,4,5,6,7,8,0,9,10,11,12,13,14,15][e%16],n=[65,16,66,18,64,t,21,1],o=128-(64+t+21+1)%128;return new YA(A,F.systemExclusive,new x([...n,o,247]))}function Hr(e=[],A=[],t=[],n=[]){let s=this;uA("%cApplying changes to the MIDI file...",I.info),y("Desired program changes:",e),y("Desired CC changes:",A),y("Desired channels to clear:",t),y("Desired channels to transpose:",n);let o=new Set;e.forEach(M=>{o.add(M.channel)});let r="gs",g=!1,i=Array(s.tracks.length).fill(0),E=s.tracks.length;function l(){let M=0,T=1/0;return s.tracks.forEach((R,C)=>{i[C]>=R.length||R[i[C]].ticks<T&&(M=C,T=R[i[C]].ticks)}),M}let c=s.midiPorts.slice(),h={},B=0;function m(M,T){s.usedChannelsOnTrack[M].size!==0&&(B===0&&(B+=16,h[T]=0),h[T]===void 0&&(h[T]=B,B+=16),c[M]=T)}s.midiPorts.forEach((M,T)=>{m(T,M)});let f=B,S=Array(f).fill(!0),G=Array(f).fill(0),D=Array(f).fill(0);for(n.forEach(M=>{let T=Math.trunc(M.keyShift),R=M.keyShift-T;G[M.channel]=T,D[M.channel]=R});E>0;){let M=l(),T=s.tracks[M];if(i[M]>=T.length){E--;continue}let R=i[M]++,C=T[R],b=()=>{T.splice(R,1),i[M]--},L=(hA,oA=0)=>{T.splice(R+oA,0,hA),i[M]++},nA=h[c[M]]||0;if(C.messageStatusByte===F.midiPort){m(M,C.messageData[0]);continue}if(C.messageStatusByte<=F.sequenceSpecific&&C.messageStatusByte>=F.sequenceNumber)continue;let $=C.messageStatusByte&240,U=C.messageStatusByte&15,tA=U+nA;if(t.indexOf(tA)!==-1){b();continue}switch($){case F.noteOn:if(S[tA]){S[tA]=!1,A.filter(cA=>cA.channel===tA).forEach(cA=>{let H=pt(U,cA.controllerNumber,cA.controllerValue,C.ticks);L(H)});let rA=D[tA];if(rA!==0){let cA=rA*64+64,H=pt(U,p.RPNMsb,0,C.ticks),J=pt(U,p.RPNLsb,1,C.ticks),z=pt(tA,p.dataEntryMsb,cA,C.ticks),V=pt(U,p.lsbForControl6DataEntry,0,C.ticks);L(V),L(z),L(J),L(H)}if(o.has(tA)){let cA=e.find(iA=>iA.channel===tA),H=Math.max(0,Math.min(cA.bank,127)),J=cA.program;y(`%cSetting %c${cA.channel}%c to %c${H}:${J}%c. Track num: %c${M}`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized);let z=new YA(C.ticks,F.programChange|U,new x([J]));L(z);let V=(iA,qA)=>{let Ee=pt(U,iA?p.lsbForControl0BankSelect:p.bankSelect,qA,C.ticks);L(Ee)};GA(r)?cA.isDrum?(y(`%cAdding XG Drum change on track %c${M}`,I.recognized,I.value),V(!1,Ae(H)?H:127),V(!0,0)):H===an?(V(!1,an),V(!0,0)):(V(!1,0),V(!0,H)):(V(!1,H),cA.isDrum&&U!==9&&(y(`%cAdding GS Drum change on track %c${M}`,I.recognized,I.value),L(Yi(U,C.ticks))))}}C.messageData[0]+=G[tA];break;case F.noteOff:C.messageData[0]+=G[tA];break;case F.programChange:if(o.has(tA)){b();continue}break;case F.controllerChange:let hA=C.messageData[0];if(A.find(rA=>rA.channel===tA&&hA===rA.controllerNumber)!==void 0){b();continue}if((hA===p.bankSelect||hA===p.lsbForControl0BankSelect)&&o.has(tA)){b();continue}break;case F.systemExclusive:if(mt(C))y("%cXG system on detected",I.info),r="xg",g=!0;else if(C.messageData[0]===67&&C.messageData[2]===76&&C.messageData[3]===8&&C.messageData[5]===3)o.has(C.messageData[4]+nA)&&b();else if(Gn(C)){g=!0,y("%cGS on detected!",I.recognized);break}else(Mn(C)||xn(C))&&(y("%cGM/2 on detected, removing!",I.info),b(),g=!1)}}if(!g&&e.length>0){let M=0;s.tracks[0][0].messageStatusByte===F.trackName&&M++,s.tracks[0].splice(M,0,ys(0)),y("%cGS on not detected. Adding it.",I.info)}this.flush(),q()}function Yr(e){let A=[],t=[],n=[],s=[];e.channelSnapshots.forEach((o,r)=>{if(o.isMuted){t.push(r);return}let g=o.channelTransposeKeyShift+o.customControllers[CA.channelTransposeFine]/100;g!==0&&A.push({channel:r,keyShift:g}),o.lockPreset&&n.push({channel:r,program:o.program,bank:o.bank,isDrum:o.drumChannel}),o.lockedControllers.forEach((i,E)=>{if(!i||E>127||E===p.bankSelect)return;let l=o.midiControllers[E]>>7;s.push({channel:r,controllerNumber:E,controllerValue:l})})}),this.modifyMIDI(n,s,t,A)}var pA={name:"INAM",album:"IPRD",album2:"IALB",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"},qe="utf-8",Oi="Created using SpessaSynth";function Or(e,A,t=0,n="Shift_JIS",s={},o=!0){let r=this;if(ge("%cWriting the RMIDI File...",I.info),y(`%cConfiguration: Bank offset: %c${t}%c, encoding: %c${n}`,I.info,I.value,I.info,I.value),y("metadata",s),y("Initial bank offset",r.bankOffset),o){let G=function(){let R=0,C=1/0;return r.tracks.forEach((b,L)=>{f[L]>=b.length||b[f[L]].ticks<C&&(R=L,C=b[f[L]].ticks)}),R},B="gm",m=[],f=Array(r.tracks.length).fill(0),S=r.tracks.length,D=Array(r.tracks.length).fill(0),M=16+r.midiPortChannelOffsets.reduce((R,C)=>C>R?C:R),T=[];for(let R=0;R<M;R++)T.push({program:0,drums:R%16===9,lastBank:void 0,lastBankLSB:void 0,hasBankSelect:!1});for(;S>0;){let R=G(),C=r.tracks[R];if(f[R]>=C.length){S--;continue}let b=C[f[R]];f[R]++;let L=r.midiPortChannelOffsets[D[R]];if(b.messageStatusByte===F.midiPort){D[R]=b.messageData[0];continue}let nA=b.messageStatusByte&240;if(nA!==F.controllerChange&&nA!==F.programChange&&nA!==F.systemExclusive)continue;if(nA===F.systemExclusive){if(!Rn(b)){mt(b)?B="xg":Gn(b)?B="gs":Mn(b)?(B="gm",m.push({tNum:R,e:b})):xn(b)&&(B="gm2");continue}let rA=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][b.messageData[5]&15]+L;T[rA].drums=!!(b.messageData[7]>0&&b.messageData[5]>>4);continue}let $=(b.messageStatusByte&15)+L,U=T[$];if(nA===F.programChange){let rA=GA(B),cA=b.messageData[0];U.drums?A.presets.findIndex(V=>V.program===cA&&V.isDrumPreset(rA,!0))===-1&&(b.messageData[0]=A.presets.find(V=>V.isDrumPreset(rA))?.program||0,y(`%cNo drum preset %c${cA}%c. Channel %c${$}%c. Changing program to ${b.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)):A.presets.findIndex(V=>V.program===cA&&!V.isDrumPreset(rA))===-1&&(b.messageData[0]=A.presets.find(V=>!V.isDrumPreset(rA))?.program||0,y(`%cNo preset %c${cA}%c. Channel %c${$}%c. Changing program to ${b.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)),U.program=b.messageData[0];let H=Math.max(0,U.lastBank?.messageData[1]-r.bankOffset),J=U?.lastBankLSB?.messageData[1]-r.bankOffset||0;if(U.lastBank===void 0)continue;let z=Bt(H,J,U.drums,rA);if(A.presets.findIndex(V=>V.bank===z&&V.program===b.messageData[0])===-1){let V=A.presets.find(iA=>iA.program===b.messageData[0])?.bank+t||t;U.lastBank.messageData[1]=V,U?.lastBankLSB?.messageData&&(U.lastBankLSB.messageData[1]=V),y(`%cNo preset %c${z}:${b.messageData[0]}%c. Channel %c${$}%c. Changing bank to ${V}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)}else{let V=z;GA(B)&&z===128&&(z=127);let iA=(z===128?128:V)+t;U.lastBank.messageData[1]=iA,U?.lastBankLSB?.messageData&&!U.drums&&(U.lastBankLSB.messageData[1]=U.lastBankLSB.messageData[1]-r.bankOffset+t),y(`%cPreset %c${z}:${b.messageData[0]}%c exists. Channel %c${$}%c. Changing bank to ${iA}.`,I.info,I.recognized,I.info,I.recognized,I.info)}continue}let tA=b.messageData[0]===p.lsbForControl0BankSelect;if(b.messageData[0]!==p.bankSelect&&!tA)continue;U.hasBankSelect=!0;let hA=b.messageData[1],oA=lt(U?.lastBank?.messageData[1]||0,hA,B,tA,U.drums,$);oA.drumsStatus===2?U.drums=!0:oA.drumsStatus===1&&(U.drums=!1),tA?U.lastBankLSB=b:U.lastBank=b}if(T.forEach((R,C)=>{if(R.hasBankSelect===!0)return;let b=C%16,L=F.programChange|b,nA=Math.floor(C/16)*16,$=r.midiPortChannelOffsets.indexOf(nA),U=r.tracks.find((rA,cA)=>r.midiPorts[cA]===$&&r.usedChannelsOnTrack[cA].has(b));if(U===void 0)return;let tA=U.findIndex(rA=>rA.messageStatusByte===L);if(tA===-1){let rA=U.findIndex(J=>J.messageStatusByte>128&&J.messageStatusByte<240&&(J.messageStatusByte&15)===b);if(rA===-1)return;let cA=U[rA].ticks,H=A.getPreset(0,0).program;U.splice(rA,0,new YA(cA,F.programChange|b,new x([H]))),tA=rA}y(`%cAdding bank select for %c${C}`,I.info,I.recognized);let hA=U[tA].ticks,oA=A.getPreset(0,R.program,GA(B))?.bank+t||t;U.splice(tA,0,new YA(hA,F.controllerChange|b,new x([p.bankSelect,oA])))}),B!=="gs"&&!GA(B)){for(let C of m)r.tracks[C.tNum].splice(r.tracks[C.tNum].indexOf(C.e),1);let R=0;r.tracks[0][0].messageStatusByte===F.trackName&&R++,r.tracks[0].splice(R,0,ys(0))}}let g=new x(r.writeMIDI().buffer),i=[_e("INFO")],E=new TextEncoder;if(i.push(j(pA.software,E.encode("SpessaSynth"),!0)),s.name!==void 0?(i.push(j(pA.name,E.encode(s.name),!0)),n=qe):i.push(j(pA.name,r.rawMidiName,!0)),s.creationDate!==void 0)n=qe,i.push(j(pA.creationDate,E.encode(s.creationDate),!0));else{let B=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});i.push(j(pA.creationDate,pe(B),!0))}if(s.comment!==void 0&&(n=qe,i.push(j(pA.comment,E.encode(s.comment)))),s.engineer!==void 0&&i.push(j(pA.engineer,E.encode(s.engineer),!0)),s.album!==void 0&&(n=qe,i.push(j(pA.album,E.encode(s.album),!0)),i.push(j(pA.album2,E.encode(s.album),!0))),s.artist!==void 0&&(n=qe,i.push(j(pA.artist,E.encode(s.artist),!0))),s.genre!==void 0&&(n=qe,i.push(j(pA.genre,E.encode(s.genre),!0))),s.picture!==void 0&&i.push(j(pA.picture,new Uint8Array(s.picture))),s.copyright!==void 0)n=qe,i.push(j(pA.copyright,E.encode(s.copyright),!0));else{let B=r.copyright.length>0?r.copyright:Oi;i.push(j(pA.copyright,pe(B)))}let l=new x(2);Je(l,t,2),i.push(j(pA.bankOffset,l)),s.midiEncoding!==void 0&&(i.push(j(pA.midiEncoding,E.encode(s.midiEncoding))),n=qe),i.push(j(pA.encoding,pe(n)));let c=kA(i),h=kA([_e("RMID"),j("data",g),j("LIST",c),e]);return y("%cFinished!",I.info),q(),j("RIFF",h)}function Jr(e){let A=this;uA("%cSearching for all used programs and keys...",I.info);let t=16+A.midiPortChannelOffsets.reduce((c,h)=>h>c?h:c),n=[];for(let c=0;c<t;c++){let h=c%16===9?128:0;n.push({program:0,bank:h,bankLSB:0,actualBank:h,drums:c%16===9,string:`${h}:0`})}let s="gs";function o(c){let h=Bt(c.bank,c.bankLSB,c.drums,GA(s)),B,m;if(e instanceof Qt){let f=e.getPreset(h,c.program,GA(s));B=f.preset.bank+f.bankOffset,m=f.preset.program}else{let f=e.getPreset(h,c.program,GA(s));B=f.bank,m=f.program}c.actualBank=B,c.program=m,c.string=c.actualBank+":"+c.program,r[c.string]||(y(`%cDetected a new preset: %c${c.string}`,I.info,I.recognized),r[c.string]=new Set)}let r={},g=Array(A.tracks.length).fill(0),i=A.tracks.length;function E(){let c=0,h=1/0;return A.tracks.forEach((B,m)=>{g[m]>=B.length||B[g[m]].ticks<h&&(c=m,h=B[g[m]].ticks)}),c}let l=A.midiPorts.slice();for(n.forEach(c=>{o(c)});i>0;){let c=E(),h=A.tracks[c];if(g[c]>=h.length){i--;continue}let B=h[g[c]];if(g[c]++,B.messageStatusByte===F.midiPort){l[c]=B.messageData[0];continue}let m=B.messageStatusByte&240;if(m!==F.noteOn&&m!==F.controllerChange&&m!==F.programChange&&m!==F.systemExclusive)continue;let f=(B.messageStatusByte&15)+A.midiPortChannelOffsets[l[c]]||0,S=n[f];switch(m){case F.programChange:S.program=B.messageData[0],o(S);break;case F.controllerChange:let G=B.messageData[0]===p.lsbForControl0BankSelect;if(B.messageData[0]!==p.bankSelect&&!G||s==="gs"&&S.drums)continue;let D=B.messageData[1];switch(G?S.bankLSB=D:S.bank=D,lt(S.bank,D,s,G,S.drums,f).drumsStatus){case 0:break;case 1:S.drums=!1,o(S);break;case 2:S.drums=!0,o(S);break}break;case F.noteOn:if(B.messageData[1]===0)continue;r[S.string].add(`${B.messageData[0]}-${B.messageData[1]}`);break;case F.systemExclusive:if(!Rn(B)){mt(B)&&(s="xg",y("%cXG on detected!",I.recognized));continue}let T=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][B.messageData[5]&15]+A.midiPortChannelOffsets[l[c]],R=!!(B.messageData[7]>0&&B.messageData[5]>>4);S=n[T],S.drums=R,o(S);break}}for(let c of Object.keys(r))r[c].size===0&&(y(`%cDetected change but no keys for %c${c}`,I.info,I.value),delete r[c]);return q(),r}function Kr(e=0){function A(c){return c.messageData=new x(c.messageData.buffer),c.messageData.currentIndex=0,6e7/KA(c.messageData,3)}let t=[],s=this.tracks.flat();s.sort((c,h)=>c.ticks-h.ticks);for(let c=0;c<16;c++)t.push([]);let o=0,r=60/(120*this.timeDivision),g=0,i=0,E=[];for(let c=0;c<16;c++)E.push([]);let l=(c,h)=>{let B=E[h].findIndex(f=>f.midiNote===c),m=E[h][B];if(m){let f=o-m.start;m.length=f,h===9&&(m.length=f<e?e:f),E[h].splice(B,1)}i--};for(;g<s.length;){let c=s[g],h=c.messageStatusByte>>4,B=c.messageStatusByte&15;if(h===8)l(c.messageData[0],B);else if(h===9)if(c.messageData[1]===0)l(c.messageData[0],B);else{l(c.messageData[0],B);let m={midiNote:c.messageData[0],start:o,length:-1,velocity:c.messageData[1]/127};t[B].push(m),E[B].push(m),i++}else c.messageStatusByte===81&&(r=60/(A(c)*this.timeDivision));if(++g>=s.length)break;o+=r*(s[g].ticks-c.ticks)}return i>0&&E.forEach((c,h)=>{c.forEach(B=>{let m=o-B.start;B.length=m,h===9&&(B.length=m<e?e:m)})}),t}var WA=class e extends nt{embeddedSoundFont=void 0;tracks=[];isDLSRMIDI=!1;static copyFrom(A){let t=new e;return t._copyFromSequence(A),t.isDLSRMIDI=A.isDLSRMIDI,t.embeddedSoundFont=A.embeddedSoundFont?A.embeddedSoundFont.slice(0):void 0,t.tracks=A.tracks.map(n=>[...n]),t}_parseInternal(){ge("%cInterpreting MIDI events...",I.info);let A=!1;this.keyRange={max:0,min:127};let t=[],n=!1;typeof this.RMIDInfo.ICOP<"u"&&(n=!0);let s=!1;typeof this.RMIDInfo.INAM<"u"&&(s=!0);let o=null,r=null;for(let l=0;l<this.tracks.length;l++){let c=this.tracks[l],h=new Set,B=!1;for(let f of c){if(f.messageStatusByte>=128&&f.messageStatusByte<240){B=!0;for(let G=0;G<f.messageData.length;G++)f.messageData[G]=Math.min(127,f.messageData[G]);switch(f.ticks>this.lastVoiceEventTick&&(this.lastVoiceEventTick=f.ticks),f.messageStatusByte&240){case F.controllerChange:switch(f.messageData[0]){case 2:case 116:o=f.ticks;break;case 4:case 117:r===null?r=f.ticks:r=0;break;case 0:this.isDLSRMIDI&&f.messageData[1]!==0&&f.messageData[1]!==127&&(y("%cDLS RMIDI with offset 1 detected!",I.recognized),this.bankOffset=1)}break;case F.noteOn:h.add(f.messageStatusByte&15);let G=f.messageData[0];this.keyRange.min=Math.min(this.keyRange.min,G),this.keyRange.max=Math.max(this.keyRange.max,G);break}}f.messageData.currentIndex=0;let S=AA(f.messageData,f.messageData.length);switch(f.messageData.currentIndex=0,f.messageStatusByte){case F.setTempo:f.messageData.currentIndex=0,this.tempoChanges.push({ticks:f.ticks,tempo:6e7/KA(f.messageData,3)}),f.messageData.currentIndex=0;break;case F.marker:switch(S.trim().toLowerCase()){default:break;case"start":case"loopstart":o=f.ticks;break;case"loopend":r=f.ticks}f.messageData.currentIndex=0;break;case F.copyright:n||(f.messageData.currentIndex=0,t.push(AA(f.messageData,f.messageData.length,void 0,!1)),f.messageData.currentIndex=0);break;case F.lyric:if(S.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,y("%cKaraoke MIDI detected!",I.recognized)),this.isKaraokeFile)f.messageStatusByte=F.text;else{this.lyrics.push(f.messageData),this.lyricsTicks.push(f.ticks);break}case F.text:let D=S.trim();D.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,y("%cKaraoke MIDI detected!",I.recognized)):this.isKaraokeFile&&(D.startsWith("@T")||D.startsWith("@A")?A?t.push(D.substring(2).trim()):(this.midiName=D.substring(2).trim(),A=!0,s=!0,this.rawMidiName=_e(this.midiName)):D[0]!=="@"&&(this.lyrics.push(Ks(f.messageData)),this.lyricsTicks.push(f.ticks)));break;case F.trackName:break}}this.usedChannelsOnTrack.push(h),this.trackNames[l]="";let m=c.find(f=>f.messageStatusByte===F.trackName);if(m){m.messageData.currentIndex=0;let f=AA(m.messageData,m.messageData.length);this.trackNames[l]=f,B||t.push(f)}}this.tempoChanges.reverse(),y("%cCorrecting loops, ports and detecting notes...",I.info);let g=[];for(let l of this.tracks){let c=l.find(h=>(h.messageStatusByte&240)===F.noteOn);c&&g.push(c.ticks)}this.firstNoteOn=Math.min(...g),y(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,I.info,I.recognized,I.info),o!==null&&r===null?(o=this.firstNoteOn,r=this.lastVoiceEventTick):(o===null&&(o=this.firstNoteOn),(r===null||r===0)&&(r=this.lastVoiceEventTick)),this.loop={start:o,end:r},y(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,I.info,I.recognized,I.info,I.recognized);let i=0;this.midiPorts=[],this.midiPortChannelOffsets=[];for(let l=0;l<this.tracks.length;l++)if(this.midiPorts.push(-1),this.usedChannelsOnTrack[l].size!==0)for(let c of this.tracks[l]){if(c.messageStatusByte!==F.midiPort)continue;let h=c.messageData[0];this.midiPorts[l]=h,this.midiPortChannelOffsets[h]===void 0&&(this.midiPortChannelOffsets[h]=i,i+=16)}this.midiPortChannelOffsets=[...this.midiPortChannelOffsets].map(l=>l??0);let E=1/0;for(let l of this.midiPorts)l!==-1&&E>l&&(E=l);if(E===1/0&&(E=0),this.midiPorts=this.midiPorts.map(l=>l===-1||l===void 0?E:l),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?y("%cNo additional MIDI Ports detected.",I.info):(this.isMultiPort=!0,y("%cMIDI Ports detected!",I.recognized)),!s)if(this.tracks.length>1){if(this.tracks[0].find(l=>l.messageStatusByte>=F.noteOn&&l.messageStatusByte<F.polyPressure)===void 0){let l=this.tracks[0].find(c=>c.messageStatusByte===F.trackName);l&&(this.rawMidiName=l.messageData,l.messageData.currentIndex=0,this.midiName=AA(l.messageData,l.messageData.length,void 0,!1))}}else{let l=this.tracks[0].find(c=>c.messageStatusByte===F.trackName);l&&(this.rawMidiName=l.messageData,l.messageData.currentIndex=0,this.midiName=AA(l.messageData,l.messageData.length,void 0,!1))}if(n||(this.copyright=t.map(l=>l.trim().replace(/(\r?\n)+/g,`
|
|
17
|
+
%c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),q(),o&&delete this.dataArray}verifyHeader(A,t){A.header.toLowerCase()!==t.toLowerCase()&&(q(),this.parsingError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,t){A.toLowerCase()!==t.toLowerCase()&&(q(),this.parsingError(`Invalid FourCC: Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"\``))}destroySoundBank(){super.destroySoundBank(),delete this.dataArray}};function At(e){let A=e.slice(8,12),t=new x(A);return AA(t,4,void 0,!1).toLowerCase()==="dls "?new be(e):new Sn(e,!1)}function or(){this.soundfontManager.soundfontList.some(e=>e.id===We)&&this.soundfontManager.deleteSoundFont(We)}function rr(e,A){this.soundfontBankOffset=A;let t=At(e);this.soundfontManager.addNewSoundFont(t,We,A);let n=this.soundfontManager.getCurrentSoundFontOrder();n.pop(),n.unshift(We),this.soundfontManager.rearrangeSoundFonts(n),this._snapshot!==void 0&&this.applySynthesizerSnapshot(this._snapshot),y(`%cEmbedded sound bank set at offset %c${A}`,I.recognized,I.value)}function ir(){let e=this.soundfontManager.getPresetList();this.clearCache(),this.callEvent("presetlistchange",e),this.getDefaultPresets(),this.midiAudioChannels.forEach(A=>{A.setPresetLock(!1)}),this.resetAllControllers(!1)}function ar(e,A=!1){this.transposition=0;for(let t=0;t<this.midiAudioChannels.length;t++)this.midiAudioChannels[t].transposeChannel(e,A);this.transposition=e}function gr(e){e=Math.round(e);for(let A=0;A<this.midiAudioChannels.length;A++)this.midiAudioChannels[A].setCustomController(CA.masterTuning,e)}var dt=class e{program;bank;isBankLSB;patchName;lockPreset;lockedSystem;midiControllers;lockedControllers;customControllers;lockVibrato;channelVibrato;channelTransposeKeyShift;channelOctaveTuning;isMuted;velocityOverride;drumChannel;static getChannelSnapshot(A,t){let n=A.midiAudioChannels[t],s=new e;return s.program=n.preset.program,s.bank=n.getBankSelect(),s.isBankLSB=s.bank!==n.bank,s.lockPreset=n.lockPreset,s.lockedSystem=n.lockedSystem,s.patchName=n.preset.presetName,s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.channelVibrato=n.channelVibrato,s.lockVibrato=n.lockGSNRPNParams,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.isMuted=n.isMuted,s.velocityOverride=n.velocityOverride,s.drumChannel=n.drumChannel,s}static applyChannelSnapshot(A,t,n){let s=A.midiAudioChannels[t];s.muteChannel(n.isMuted),s.setDrums(n.drumChannel),s.midiControllers=n.midiControllers,s.lockedControllers=n.lockedControllers,s.customControllers=n.customControllers,s.updateChannelTuning(),s.channelVibrato=n.channelVibrato,s.lockGSNRPNParams=n.lockVibrato,s.channelTransposeKeyShift=n.channelTransposeKeyShift,s.channelOctaveTuning=n.channelOctaveTuning,s.velocityOverride=n.velocityOverride,s.setPresetLock(!1),s.setBankSelect(n.bank,n.isBankLSB),s.programChange(n.program),s.setPresetLock(n.lockPreset),s.lockedSystem=n.lockedSystem}};var et=class e{channelSnapshots;keyMappings;mainVolume;pan;interpolation;system;transposition;static createSynthesizerSnapshot(A){let t=new e;return t.channelSnapshots=A.midiAudioChannels.map((n,s)=>dt.getChannelSnapshot(A,s)),t.keyMappings=A.keyModifierManager.getMappings(),t.mainVolume=A.midiVolume,t.pan=A.pan,t.system=A.system,t.interpolation=A.interpolationType,t.transposition=A.transposition,t.effectsConfig={},t}static applySnapshot(A,t){for(A.setSystem(t.system),A.setMasterParameter(OA.mainVolume,t.mainVolume),A.setMasterParameter(OA.masterPan,t.pan),A.transposeAllChannels(t.transposition),A.interpolationType=t.interpolation,A.keyModifierManager.setMappings(t.keyMappings);A.midiAudioChannels.length<t.channelSnapshots.length;)A.createMidiChannel();t.channelSnapshots.forEach((n,s)=>{dt.applyChannelSnapshot(A,s,n)}),y("%cFinished restoring controllers!",I.info)}};function Ir(e){this._snapshot=e,et.applySnapshot(this,e),y("%cFinished applying snapshot!",I.info),this.resetAllControllers()}function Dn(e,A,t){if(t<e)return 0;let n=(t-e)/(1/A)+.25;return Math.abs(n-~~(n+.5))*4-1}var ft=class{static getSampleLinear(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=r;let i=~~s,E=i+1;for(;E>=n.loopEnd;)E-=r;let l=s-i,c=o[E],h=o[i];t[g]=h+(c-h)*l,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r<t.length;r++){let g=~~s,i=g+1;if(i>=n.end){A.finished=!0;return}let E=s-g,l=o[i],c=o[g];t[r]=c+(l-c)*E,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}static getSampleNearest(A,t){let n=A.sample,s=n.cursor,o=n.loopEnd-n.loopStart,r=n.sampleData;if(A.sample.isLooping)for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=o;let i=~~s+1;for(;i>=n.loopEnd;)i-=o;t[g]=r[i],s+=n.playbackStep*A.currentTuningCalculated}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let g=0;g<t.length;g++){let i=~~s+1;if(i>=n.end){A.finished=!0;return}t[g]=r[i],s+=n.playbackStep*A.currentTuningCalculated}}n.cursor=s}static getSampleCubic(A,t){let n=A.sample,s=n.cursor,o=n.sampleData;if(n.isLooping){let r=n.loopEnd-n.loopStart;for(let g=0;g<t.length;g++){for(;s>=n.loopEnd;)s-=r;let i=~~s,E=i+1,l=E+1,c=l+1,h=s-i;E>=n.loopEnd&&(E-=r),l>=n.loopEnd&&(l-=r),c>=n.loopEnd&&(c-=r);let B=o[i],m=o[E],f=o[l],S=o[c],G=.5*(f-B),D=B-2.5*m+2*f-.5*S,M=.5*(S-B)+1.5*(m-f);t[g]=((M*h+D)*h+G)*h+m,s+=n.playbackStep*A.currentTuningCalculated}}else{if(n.loopingMode===2&&!A.isInRelease)return;for(let r=0;r<t.length;r++){let g=~~s,i=g+1,E=i+1,l=E+1,c=s-g;if(i>=n.end||E>=n.end||l>=n.end){A.finished=!0;return}let h=o[g],B=o[i],m=o[E],f=o[l],S=.5*(m-h),G=h-2.5*B+2*m-.5*f,D=.5*(f-h)+1.5*(B-m);t[r]=((D*c+G)*c+S)*c+B,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}};function Er(e,A,t,n,s,o,r,g){if(e.isInRelease||A>=e.releaseStartTime&&(e.isInRelease=!0,ce.startRelease(e),he.startRelease(e),e.sample.loopingMode===3&&(e.sample.isLooping=!1)),e.modulatedGenerators[a.initialAttenuation]>2500)return e.isInRelease&&(e.finished=!0),e.finished;let i=e.targetKey,E=e.modulatedGenerators[a.fineTune]+this.channelOctaveTuning[e.midiNote]+this.channelTuningCents,l=e.modulatedGenerators[a.coarseTune],c=this.synth.tunings[this.preset.program]?.[e.realKey];if(c!==void 0&&c?.midiNote>=0&&(i=c.midiNote,E+=c.centTuning),e.portamentoFromKey>-1){let L=Math.min((A-e.startTime)/e.portamentoDuration,1),nA=i-e.portamentoFromKey;l-=nA*(1-L)}E+=(i-e.sample.rootKey)*e.modulatedGenerators[a.scaleTuning];let h=0,B=0,m=e.modulatedGenerators[a.vibLfoToPitch],f=e.modulatedGenerators[a.vibLfoToVolume],S=e.modulatedGenerators[a.vibLfoToFilterFc];if(m!==0||f!==0||S!==0){let L=e.startTime+Ce(e.modulatedGenerators[a.delayVibLFO]),nA=Ut(e.modulatedGenerators[a.freqVibLFO]),$=Dn(L,nA,A);E+=$*(m*this.customControllers[CA.modulationMultiplier]),B+=-$*f,h+=$*S}let G=e.modulatedGenerators[a.modLfoToPitch],D=e.modulatedGenerators[a.modLfoToVolume],M=e.modulatedGenerators[a.modLfoToFilterFc];if(G!==0||M!==0||D!==0){let L=e.startTime+Ce(e.modulatedGenerators[a.delayModLFO]),nA=Ut(e.modulatedGenerators[a.freqModLFO]),$=Dn(L,nA,A);E+=$*(G*this.customControllers[CA.modulationMultiplier]),B+=-$*D,h+=$*M}if(this.channelVibrato.depth>0){let L=Dn(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,A);L&&(E+=L*this.channelVibrato.depth)}let T=e.modulatedGenerators[a.modEnvToPitch],R=e.modulatedGenerators[a.modEnvToFilterFc];if(R!==0||T!==0){let L=he.getValue(e,A);h+=L*R,E+=L*T}let C=~~(E+l*100);C!==e.currentTuningCents&&(e.currentTuningCents=C,e.currentTuningCalculated=Math.pow(2,C/1200));let b=new Float32Array(t.length);switch(this.synth.interpolationType){case ze.fourthOrder:ft.getSampleCubic(e,b);break;case ze.linear:default:ft.getSampleLinear(e,b);break;case ze.nearestNeighbor:ft.getSampleNearest(e,b);break}return Oe.apply(e,b,h,this.synth.filterSmoothingFactor),ce.apply(e,b,B,this.synth.volumeEnvelopeSmoothingFactor),this.panVoice(e,b,t,n,s,o,r,g),e.finished}function Cr(e,A=-12e3){e+=this.customControllers[CA.channelKeyShift],this.voices.forEach(t=>{t.realKey===e&&(t.modulatedGenerators[a.releaseVolEnv]=A,t.release(this.synth.currentSynthTime))})}function cr(e,A=!0){e=Math.round(e),this.setCustomController(CA.channelTuning,e),A&&y(`%cFine tuning for %c${this.channelNumber}%c is now set to %c${e}%c cents.`,I.info,I.recognized,I.info,I.value,I.info)}function hr(e){e=Math.round(e),y(`%cChannel ${this.channelNumber} modulation depth. Cents: %c${e}`,I.info,I.value),this.setCustomController(CA.modulationMultiplier,e/50)}var Le={pitchBendRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},kn={partParameter:1,awe32:127},ut={vibratoRate:8,vibratoDepth:9,vibratoDelay:10,TVFFilterCutoff:32,TVFFilterResonance:33,EGAttackTime:99,EGReleaseTime:102};function lr(e){this.midiControllers[p.dataEntryMsb]=e<<7;let A=()=>{this.channelVibrato.delay===0&&this.channelVibrato.rate===0&&this.channelVibrato.depth===0&&(this.channelVibrato.depth=50,this.channelVibrato.rate=8,this.channelVibrato.delay=.6)},t=(n,s,o)=>{o.length>0&&(o=" "+o),y(`%c${n} for %c${this.channelNumber}%c is now set to %c${s}%c${o}.`,I.info,I.recognized,I.info,I.value,I.info)};switch(this.dataEntryState){default:case UA.Idle:break;case UA.NRPFine:if(this.lockGSNRPNParams)return;let n=this.midiControllers[p.NRPNMsb]>>7,s=this.midiControllers[p.NRPNLsb]>>7;switch(n){default:if(e===64)return;Y(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${s.toString(16).toUpperCase()} 0x${s.toString(16).toUpperCase()})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case kn.partParameter:switch(s){default:if(e===64)return;Y(`%cUnrecognized NRPN for %c${this.channelNumber}%c: %c(0x${n.toString(16)} 0x${s.toString(16)})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case ut.vibratoRate:if(e===64)return;A(),this.channelVibrato.rate=e/64*8,t("Vibrato rate",`${e} = ${this.channelVibrato.rate}`,"Hz");break;case ut.vibratoDepth:if(e===64)return;A(),this.channelVibrato.depth=e/2,t("Vibrato depth",`${e} = ${this.channelVibrato.depth}`,"cents of detune");break;case ut.vibratoDelay:if(e===64)return;A(),this.channelVibrato.delay=e/64/3,t("Vibrato delay",`${e} = ${this.channelVibrato.delay}`,"seconds");break;case ut.TVFFilterCutoff:this.controllerChange(p.brightness,e),t("Filter cutoff",e.toString(),"");break;case ut.EGAttackTime:this.controllerChange(p.attackTime,e),t("EG attack time",e.toString(),"");break;case ut.EGReleaseTime:this.controllerChange(p.releaseTime,e),t("EG release time",e.toString(),"");break}break;case kn.awe32:break}break;case UA.RPCoarse:case UA.RPFine:let o=this.midiControllers[p.RPNMsb]|this.midiControllers[p.RPNLsb]>>7;switch(o){default:Y(`%cUnrecognized RPN for %c${this.channelNumber}%c: %c(0x${o.toString(16)})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case Le.pitchBendRange:this.midiControllers[BA+_.pitchWheelRange]=e<<7,t("Pitch bend range",e.toString(),"semitones");break;case Le.coarseTuning:let r=e-64;this.setCustomController(CA.channelTuningSemitones,r),t("Coarse tuning",r.toString(),"semitones");break;case Le.fineTuning:this.setTuning(e-64,!1);break;case Le.modulationDepth:this.setModulationDepth(e*100);break;case Le.resetParameters:this.resetParameters();break}}}var Ti=[a.delayModLFO,a.freqModLFO,a.delayVibLFO,a.freqVibLFO,a.delayModEnv,a.attackModEnv,a.holdModEnv,a.decayModEnv,a.sustainModEnv,a.releaseModEnv,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.fineTune,a.modLfoToPitch,a.vibLfoToPitch,a.modEnvToPitch,a.modLfoToVolume,a.initialFilterFc,a.initialFilterQ,a.modLfoToFilterFc,a.modEnvToFilterFc,a.chorusEffectsSend,a.reverbEffectsSend];function Br(e,A,t){let n=(h,B,m)=>Math.max(B,Math.min(m,h)),s=h=>Math.max(-32768,1200*Math.log2(h/1e3)),o=h=>6900+1200*Math.log2(h/440),r=t<<7|A;r-=8192;let g=Ti[e];g||Y(`Invalid AWE32 LSB: %c${e}`,I.unrecognized);let i,E,l,c;switch(g){default:break;case a.delayModLFO:case a.delayVibLFO:case a.delayVolEnv:case a.delayModEnv:i=4*n(r,0,5900),this.setGeneratorOverride(g,s(i));break;case a.attackVolEnv:case a.attackModEnv:i=n(r,0,5940),this.setGeneratorOverride(g,s(i));break;case a.holdVolEnv:case a.holdModEnv:i=n(r,0,8191),this.setGeneratorOverride(g,s(i));break;case a.decayModEnv:case a.decayVolEnv:case a.releaseVolEnv:case a.releaseModEnv:i=4*n(r,0,5940),this.setGeneratorOverride(g,s(i));break;case a.freqVibLFO:case a.freqModLFO:E=.084*A,this.setGeneratorOverride(g,o(E),!0);break;case a.sustainVolEnv:case a.sustainModEnv:l=A*7.5,this.setGeneratorOverride(g,l);break;case a.fineTune:this.setGeneratorOverride(g,r,!0);break;case a.modLfoToPitch:case a.vibLfoToPitch:c=n(r,-127,127)*9.375,this.setGeneratorOverride(g,c,!0);break;case a.modEnvToPitch:c=n(r,-127,127)*9.375,this.setGeneratorOverride(g,c);break;case a.modLfoToVolume:l=1.875*A,this.setGeneratorOverride(g,l,!0);break;case a.initialFilterFc:let h=4335+59*A;this.setGeneratorOverride(g,h,!0);break;case a.initialFilterQ:l=215*(A/127),this.setGeneratorOverride(g,l,!0);break;case a.modLfoToFilterFc:c=n(r,-64,63)*56.25,this.setGeneratorOverride(g,c,!0);break;case a.modEnvToFilterFc:c=n(r,-64,63)*56.25,this.setGeneratorOverride(g,c);break;case a.chorusEffectsSend:case a.reverbEffectsSend:this.setGeneratorOverride(g,n(r,0,255)*(1e3/255));break}}function Qr(e){switch(this.midiControllers[p.lsbForControl6DataEntry]=e<<7,this.dataEntryState){default:break;case UA.RPCoarse:case UA.RPFine:switch(this.midiControllers[p.RPNMsb]|this.midiControllers[p.RPNLsb]>>7){default:break;case Le.pitchBendRange:if(e===0)break;this.midiControllers[BA+_.pitchWheelRange]|=e;let s=(this.midiControllers[BA+_.pitchWheelRange]>>7)+e/128;y(`%cChannel ${this.channelNumber} bend range. Semitones: %c${s}`,I.info,I.value);break;case Le.fineTuning:let r=this.customControllers[CA.channelTuning]<<7|e;this.setTuning(r*.01220703125);break;case Le.modulationDepth:let i=this.customControllers[CA.modulationMultiplier]*50+e/128*100;this.setModulationDepth(i);break;case 16383:this.resetParameters();break}break;case UA.NRPFine:let t=this.midiControllers[p.NRPNMsb]>>7,n=this.midiControllers[p.NRPNLsb]>>7;switch(t){default:Y(`%cUnrecognized NRPN LSB for %c${this.channelNumber}%c: %c(0x${n.toString(16).toUpperCase()} 0x${n.toString(16).toUpperCase()})%c data value: %c${e}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case kn.awe32:Br.call(this,n,e,this.midiControllers[p.dataEntryMsb]>>7);break}}}var Ui=1e3/200;function dr(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=e[A.sourceIndex];else{let E=A.sourceIndex+BA;switch(A.sourceIndex){case _.noController:n=16383;break;case _.noteOnKeyNum:n=t.midiNote<<7;break;case _.noteOnVelocity:n=t.velocity<<7;break;case _.polyPressure:n=t.pressure<<7;break;default:n=e[E];break}}let s=tt[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let E=A.secSrcIndex+BA;switch(A.secSrcIndex){case _.noController:o=16383;break;case _.noteOnKeyNum:o=t.midiNote<<7;break;case _.noteOnVelocity:o=t.velocity<<7;break;case _.polyPressure:o=t.pressure<<7;break;default:o=e[E]}}let r=tt[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=A.transformAmount;A.isEffectModulator&&g<=1e3&&(g*=Ui,g=Math.min(g,1e3));let i=s*r*g;return A.transformType===2&&(i=Math.abs(i)),A.currentValue=i,i}function te(e,A,t=-1,n=0){let s=e.modulators,o=e.generators,r=e.modulatedGenerators;if(t===-1){r.set(o),s.forEach(E=>{let l=Z[E.modulatorDestination],c=r[E.modulatorDestination]+dr(A,E,e);r[E.modulatorDestination]=Math.max(l.min,Math.min(c,l.max))}),ce.recalculate(e),he.recalculate(e);return}let g=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),i=new Set;s.forEach(E=>{if(E.sourceUsesCC===t&&E.sourceIndex===n||E.secSrcUsesCC===t&&E.secSrcIndex===n){let l=E.modulatorDestination;i.has(l)||(r[l]=o[l],dr(A,E,e),s.forEach(c=>{if(c.modulatorDestination===l){let h=Z[E.modulatorDestination],B=r[E.modulatorDestination]+c.currentValue;r[E.modulatorDestination]=Math.max(h.min,Math.min(B,h.max))}}),i.add(l))}}),[...i].some(E=>g.has(E))&&ce.recalculate(e),he.recalculate(e)}var tt=[];for(let e=0;e<4;e++){tt[e]=[[new Float32Array(bA),new Float32Array(bA)],[new Float32Array(bA),new Float32Array(bA)]];for(let A=0;A<bA;A++)tt[e][0][0][A]=$e(0,e,A/bA,0),tt[e][1][0][A]=$e(0,e,A/bA,1),tt[e][0][1][A]=$e(1,e,A/bA,0),tt[e][1][1][A]=$e(1,e,A/bA,1)}function fr(e,A,t=!1){if(e>127){if(!t)return;switch(e){default:return;case is.velocityOverride:this.velocityOverride=A}}if(e>=p.lsbForControl1ModulationWheel&&e<=p.lsbForControl13EffectControl2&&e!==p.lsbForControl6DataEntry){let n=e-32;if(this.lockedControllers[n])return;this.midiControllers[n]=this.midiControllers[n]&16256|A&127,this.voices.forEach(s=>te(s,this.midiControllers,1,n))}if(!this.lockedControllers[e]){switch(this.midiControllers[e]=A<<7,e){case p.allNotesOff:this.stopAllNotes();break;case p.allSoundOff:this.stopAllNotes(!0);break;case p.bankSelect:this.setBankSelect(A);break;case p.lsbForControl0BankSelect:this.setBankSelect(A,!0);break;case p.RPNLsb:this.dataEntryState=UA.RPFine;break;case p.RPNMsb:this.dataEntryState=UA.RPCoarse;break;case p.NRPNMsb:this.dataEntryState=UA.NRPCoarse;break;case p.NRPNLsb:this.dataEntryState=UA.NRPFine;break;case p.dataEntryMsb:this.dataEntryCoarse(A);break;case p.lsbForControl6DataEntry:this.dataEntryFine(A);break;case p.resetAllControllers:this.resetControllersRP15Compliant();break;case p.sustainPedal:A>=64?this.holdPedal=!0:(this.holdPedal=!1,this.sustainedVoices.forEach(n=>{n.release(this.synth.currentSynthTime)}),this.sustainedVoices=[]);break;default:this.voices.forEach(n=>te(n,this.midiControllers,1,e));break}this.synth.callEvent("controllerchange",{channel:this.channelNumber,controllerNumber:e,controllerValue:A})}}function ur(e=!1){e?(this.voices.length=0,this.sustainedVoices.length=0,this.sendChannelProperty()):(this.voices.forEach(A=>{A.isInRelease||A.release(this.synth.currentSynthTime)}),this.sustainedVoices.forEach(A=>{A.release(this.synth.currentSynthTime)}))}function mr(e){e&&this.stopAllNotes(!0),this.isMuted=e,this.sendChannelProperty(),this.synth.callEvent("mutechannel",{channel:this.channelNumber,isMuted:e})}function pr(e,A=!1){this.drumChannel||(e+=this.synth.transposition);let t=Math.trunc(e),n=this.channelTransposeKeyShift+this.customControllers[CA.channelTransposeFine]/100;this.drumChannel&&!A||e===n||(t!==this.channelTransposeKeyShift&&this.controllerChange(p.allNotesOff,127),this.channelTransposeKeyShift=t,this.setCustomController(CA.channelTransposeFine,(e-t)*100),this.sendChannelProperty())}var Jt={0:0,1:.006,2:.023,4:.05,8:.11,16:.25,32:.5,64:2.06,80:4.2,96:8.4,112:19.5,116:26.7,120:40,124:80,127:480};function vi(e){if(Jt[e]!==void 0)return Jt[e];let A=null,t=null;for(let n of Object.keys(Jt))n=parseInt(n),n<e&&(A===null||n>A)&&(A=n),n>e&&(t===null||n<t)&&(t=n);if(A!==null&&t!==null){let n=Jt[A],s=Jt[t];return n+(e-A)*(s-n)/(t-A)}return 0}function yr(e,A){return vi(e)*(A/30)}function Sr(e,A){if(A<1){this.noteOff(e);return}if(A=Math.min(127,A),this.synth.highPerformanceMode&&this.synth.totalVoicesAmount>200&&A<40||this.synth.highPerformanceMode&&A<10||this.isMuted)return;let t=e+this.channelTransposeKeyShift+this.customControllers[CA.channelKeyShift],n=t;if(t>127||t<0)return;let s=this.preset.program,o=this.synth.tunings[s]?.[t]?.midiNote;o>=0&&(n=o),this.velocityOverride>0&&(A=this.velocityOverride);let r=this.synth.keyModifierManager.getVelocity(this.channelNumber,t);r>-1&&(A=r);let g=this.synth.keyModifierManager.getGain(this.channelNumber,t),i=-1,E=0,l=this.midiControllers[p.portamentoTime]>>7,c=this.midiControllers[p.portamentoControl],h=c>>7;if(!this.drumChannel&&h!==n&&this.midiControllers[p.portamentoOnOff]>=8192&&l>0){if(c!==1){let S=Math.abs(n-h);E=yr(l,S),i=h}this.controllerChange(p.portamentoControl,n)}let B=this.synth.getVoices(this.channelNumber,n,A,t),m=0;this.randomPan&&(m=Math.round(Math.random()*1e3-500));let f=this.voices;B.forEach(S=>{S.portamentoFromKey=i,S.portamentoDuration=E,S.overridePan=m,S.gain=g,this.sysExModulators.modulatorList.forEach(L=>{let nA=L.mod,$=S.modulators.findIndex(U=>X.isIdentical(U,nA));$!==-1?S.modulators[$]=X.copy(nA):S.modulators.push(X.copy(nA))}),this.generatorOverridesEnabled&&this.generatorOverrides.forEach((L,nA)=>{L!==nn&&(S.generators[nA]=L)});let G=S.exclusiveClass;G!==0&&f.forEach(L=>{L.exclusiveClass===G&&L.exclusiveRelease(this.synth.currentSynthTime)}),te(S,this.midiControllers);let D=S.modulatedGenerators[a.startAddrsOffset]+S.modulatedGenerators[a.startAddrsCoarseOffset]*32768,M=S.modulatedGenerators[a.endAddrOffset]+S.modulatedGenerators[a.endAddrsCoarseOffset]*32768,T=S.modulatedGenerators[a.startloopAddrsOffset]+S.modulatedGenerators[a.startloopAddrsCoarseOffset]*32768,R=S.modulatedGenerators[a.endloopAddrsOffset]+S.modulatedGenerators[a.endloopAddrsCoarseOffset]*32768,C=S.sample,b=L=>Math.max(0,Math.min(C.sampleData.length-1,L));if(C.cursor=b(C.cursor+D),C.end=b(C.end+M),C.loopStart=b(C.loopStart+T),C.loopEnd=b(C.loopEnd+R),C.loopEnd<C.loopStart){let L=C.loopStart;C.loopStart=C.loopEnd,C.loopEnd=L}C.loopEnd-C.loopStart<1&&(C.loopingMode=0,C.isLooping=!1),S.volumeEnvelope.attenuation=S.volumeEnvelope.attenuationTargetGain,S.currentPan=Math.max(-500,Math.min(500,S.modulatedGenerators[a.pan]))}),this.synth.totalVoicesAmount+=B.length,this.synth.totalVoicesAmount>this.synth.voiceCap&&this.synth.voiceKilling(B.length),f.push(...B),this.sendChannelProperty(),this.synth.callEvent("noteon",{midiNote:e,channel:this.channelNumber,velocity:A})}function Dr(e){if(e>127||e<0){Y("Received a noteOn for note",e,"Ignoring.");return}let A=e+this.channelTransposeKeyShift+this.customControllers[CA.channelKeyShift];if(this.synth.highPerformanceMode&&!this.drumChannel){this.killNote(A,-6950),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber});return}this.voices.forEach(n=>{n.realKey!==A||n.isInRelease===!0||(this.holdPedal?this.sustainedVoices.push(n):n.release(this.synth.currentSynthTime))}),this.synth.callEvent("noteoff",{midiNote:e,channel:this.channelNumber})}function kr(e,A){this.voices.forEach(t=>{t.midiNote===e&&(t.pressure=A,te(t,this.midiControllers,0,_.polyPressure))}),this.synth.callEvent("polypressure",{channel:this.channelNumber,midiNote:e,pressure:A})}function Fr(e){this.midiControllers[BA+_.channelPressure]=e<<7,this.updateChannelTuning(),this.voices.forEach(A=>te(A,this.midiControllers,0,_.channelPressure)),this.synth.callEvent("channelpressure",{channel:this.channelNumber,pressure:e})}function wr(e,A){if(this.lockedControllers[BA+_.pitchWheel])return;let t=A|e<<7;this.synth.callEvent("pitchwheel",{channel:this.channelNumber,MSB:e,LSB:A}),this.midiControllers[BA+_.pitchWheel]=t,this.voices.forEach(n=>te(n,this.midiControllers,0,_.pitchWheel)),this.sendChannelProperty()}function Rr(e){if(e.length!==12)throw new Error("Tuning is not the length of 12.");this.channelOctaveTuning=new Int8Array(128);for(let A=0;A<128;A++)this.channelOctaveTuning[A]=e[A%12]}function Gr(e){if(this.lockPreset)return;let A=this.getBankSelect(),t=this.isXGChannel,n=this.synth.soundfontManager.getPreset(A,e,t),s=n.preset;this.setPreset(s),this.sentBank=Math.min(128,s.bank+n.bankOffset),this.synth.callEvent("programchange",{channel:this.channelNumber,program:s.program,bank:this.sentBank}),this.sendChannelProperty()}var Fn=class{modulatorList=[];resetModulators(){this.modulatorList=[]}_getModulatorId(A,t,n,s){return`${A}-${t}-${n}-${s}`}_deleteModulator(A){this.modulatorList=this.modulatorList.filter(t=>t.id!==A)}setModulator(A,t,n,s=!1,o=!1){let r=this._getModulatorId(A,t,s,o);n===0&&this._deleteModulator(r);let g=this.modulatorList.find(i=>i.id===r);if(g)g.mod.transformAmount=n;else{let i,E;A>=BA?(i=A-BA,E=!1):(i=A,E=!0);let l=new X(ZA(FA.linear,s,0,E,i),0,t,n,0);this.modulatorList.push({mod:l,id:r})}}};var DA=class{midiControllers=new Int16Array(gn);lockedControllers=Array(gn).fill(!1);customControllers=new Float32Array(os);channelTransposeKeyShift=0;channelOctaveTuning=new Int8Array(128);channelTuningCents=0;sysExModulators=new Fn;generatorOverrides=new Int16Array(on);generatorOverridesEnabled=!1;holdPedal=!1;drumChannel=!1;velocityOverride=0;randomPan=!1;dataEntryState=UA.Idle;bank=0;sentBank=0;bankLSB=0;preset=void 0;lockPreset=!1;lockedSystem="gs";lockGSNRPNParams=!1;channelVibrato={delay:0,depth:0,rate:0};isMuted=!1;voices=[];sustainedVoices=[];channelNumber;synth;constructor(A,t,n){this.synth=A,this.preset=t,this.channelNumber=n,this.resetGeneratorOverrides()}get isXGChannel(){return GA(this.synth.system)||this.lockPreset&&GA(this.lockedSystem)}setCustomController(A,t){this.customControllers[A]=t,this.updateChannelTuning()}updateChannelTuning(){this.channelTuningCents=this.customControllers[CA.channelTuning]+this.customControllers[CA.channelTransposeFine]+this.customControllers[CA.masterTuning]+this.customControllers[CA.channelTuningSemitones]*100}renderAudio(A,t,n,s,o,r){this.voices=this.voices.filter(g=>!this.renderVoice(g,this.synth.currentSynthTime,A,t,n,s,o,r))}setPresetLock(A){this.lockPreset=A,A&&(this.lockedSystem=this.synth.system)}setBankSelect(A,t=!1){if(!this.lockPreset)if(t)this.bankLSB=A;else switch(this.bank=A,lt(this.getBankSelect(),A,this.synth.system,!1,this.drumChannel,this.channelNumber).drumsStatus){default:case 0:break;case 1:this.channelNumber%16===9&&(this.bank=127);break;case 2:this.setDrums(!0);break}}getBankSelect(){return Bt(this.bank,this.bankLSB,this.drumChannel,this.isXGChannel)}setPreset(A){this.lockPreset||(delete this.preset,this.preset=A)}setDrums(A){this.lockPreset||this.drumChannel!==A&&(A?(this.channelTransposeKeyShift=0,this.drumChannel=!0):this.drumChannel=!1,this.synth.callEvent("drumchange",{channel:this.channelNumber,isDrumChannel:this.drumChannel}),this.programChange(this.preset.program),this.sendChannelProperty())}setVibrato(A,t,n){this.lockGSNRPNParams||(this.channelVibrato.rate=t,this.channelVibrato.delay=n,this.channelVibrato.depth=A)}disableAndLockGSNRPN(){this.lockGSNRPNParams=!0,this.channelVibrato.rate=0,this.channelVibrato.delay=0,this.channelVibrato.depth=0}sendChannelProperty(){if(!this.synth.enableEventSystem)return;let A={voicesAmount:this.voices.length,pitchBend:this.midiControllers[BA+_.pitchWheel],pitchBendRangeSemitones:this.midiControllers[BA+_.pitchWheelRange]/128,isMuted:this.isMuted,isDrum:this.drumChannel,transposition:this.channelTransposeKeyShift+this.customControllers[CA.channelTransposeFine]/100,bank:this.sentBank,program:this.preset.program};this.synth?.onChannelPropertyChange?.(A,this.channelNumber)}resetGeneratorOverrides(){this.generatorOverrides.fill(nn),this.generatorOverridesEnabled=!1}setGeneratorOverride(A,t,n=!1){this.generatorOverrides[A]=t,this.generatorOverridesEnabled=!0,n&&this.voices.forEach(s=>{s.generators[A]=t,te(s,this.midiControllers)})}};DA.prototype.renderVoice=Er;DA.prototype.panVoice=fo;DA.prototype.killNote=Cr;DA.prototype.stopAllNotes=ur;DA.prototype.muteChannel=mr;DA.prototype.noteOn=Sr;DA.prototype.noteOff=Dr;DA.prototype.polyPressure=kr;DA.prototype.channelPressure=Fr;DA.prototype.pitchWheel=wr;DA.prototype.programChange=Gr;DA.prototype.setTuning=cr;DA.prototype.setOctaveTuning=Rr;DA.prototype.setModulationDepth=hr;DA.prototype.transposeChannel=pr;DA.prototype.controllerChange=fr;DA.prototype.resetControllers=oo;DA.prototype.resetControllersRP15Compliant=ro;DA.prototype.resetParameters=io;DA.prototype.dataEntryFine=Qr;DA.prototype.dataEntryCoarse=lr;function Mr(e=!1){let A=new DA(this,this.defaultPreset,this.midiAudioChannels.length);this.midiAudioChannels.push(A),e&&(this.callEvent("newchannel",void 0),A.sendChannelProperty(),this.midiAudioChannels[this.midiAudioChannels.length-1].setDrums(!0))}var ps={enableEventSystem:!0,initialTime:0,effectsEnabled:!0,midiChannels:16};function xr(e,A){e===void 0&&(e={});for(let t in A)A.hasOwnProperty(t)&&!(t in e)&&(e[t]=A[t]);return e}var Hi={time:0},Eo=.03,Co=.07,ts=1,LA=class{cachedVoices=[];deviceID=-1;eventQueue=[];interpolationType=ze.fourthOrder;transposition=0;tunings=[];soundfontBankOffset=0;masterGain=ts;midiVolume=1;reverbGain=1;chorusGain=1;reverbSend=1;chorusSend=1;voiceCap=350;pan=0;panLeft=.5;panRight=.5;highPerformanceMode=!1;keyModifierManager=new En;midiAudioChannels=[];system=Tt;totalVoicesAmount=0;defaultPreset;drumPreset;processorInitialized=me.isInitialized;currentSynthTime=0;sampleRate;sampleTime;effectsEnabled;_snapshot;onEventCall;onChannelPropertyChange;onMasterParameterChange;constructor(A,t=ps){t=xr(t,ps),this.midiOutputsCount=t.midiChannels,this.effectsEnabled=t.effectsEnabled,this.enableEventSystem=t.enableEventSystem,this.currentSynthTime=t.initialTime,this.sampleTime=1/A,this.sampleRate=A,this.volumeEnvelopeSmoothingFactor=Ws*(44100/A),this.panSmoothingFactor=ho*(44100/A),this.filterSmoothingFactor=ao*(44100/A);for(let n=0;n<128;n++)this.tunings.push([]);this.soundfontManager=new Qt(this.updatePresetList.bind(this));for(let n=0;n<this.midiOutputsCount;n++)this.createMidiChannel(!1);this.processorInitialized.then(()=>{y("%cSpessaSynth is ready!",I.recognized)})}get currentGain(){return this.masterGain*this.midiVolume}getDefaultPresets(){let A=this.system;this.system="xg",this.defaultPreset=this.getPreset(0,0),this.system=A,this.drumPreset=this.getPreset(128,0)}setSystem(A){this.system=A,this?.onMasterParameterChange?.(OA.midiSystem,this.system)}getCachedVoice(A,t,n,s){return this.cachedVoices?.[A]?.[t]?.[n]?.[s]}setCachedVoice(A,t,n,s,o){this.cachedVoices[A]||(this.cachedVoices[A]=[]),this.cachedVoices[A][t]||(this.cachedVoices[A][t]=[]),this.cachedVoices[A][t][n]||(this.cachedVoices[A][t][n]=[]),this.cachedVoices[A][t][n][s]=o}renderAudio(A,t,n){this.renderAudioSplit(t,n,Array(16).fill(A))}renderAudioSplit(A,t,n){let s=this.currentSynthTime;for(;this.eventQueue[0]?.time<=s;)this.eventQueue.shift().callback();let o=A[0],r=A[1],g=t[0],i=t[1];this.totalVoicesAmount=0,this.midiAudioChannels.forEach((E,l)=>{if(E.voices.length<1||E.isMuted)return;let c=E.voices.length,h=l%16;E.renderAudio(n[h][0],n[h][1],o,r,g,i),this.totalVoicesAmount+=E.voices.length,E.voices.length!==c&&E.sendChannelProperty()}),this.currentSynthTime+=n[0][0].length*this.sampleTime}destroySynthProcessor(){this.midiAudioChannels.forEach(A=>{delete A.midiControllers,delete A.voices,delete A.sustainedVoices,delete A.lockedControllers,delete A.preset,delete A.customControllers}),delete this.cachedVoices,delete this.midiAudioChannels,this.soundfontManager.destroyManager(),delete this.soundfontManager}controllerChange(A,t,n,s=!1){this.midiAudioChannels[A].controllerChange(t,n,s)}noteOn(A,t,n){this.midiAudioChannels[A].noteOn(t,n)}noteOff(A,t){this.midiAudioChannels[A].noteOff(t)}polyPressure(A,t,n){this.midiAudioChannels[A].polyPressure(t,n)}channelPressure(A,t){this.midiAudioChannels[A].channelPressure(t)}pitchWheel(A,t,n){this.midiAudioChannels[A].pitchWheel(t,n)}programChange(A,t){this.midiAudioChannels[A].programChange(t)}processMessage(A,t=0,n=!1,s=Hi){let o=()=>{let g=ht(A[0]),i=g.channel+t;switch(g.status){case F.noteOn:let E=A[2];E>0?this.noteOn(i,A[1],E):this.noteOff(i,A[1]);break;case F.noteOff:n?this.midiAudioChannels[i].killNote(A[1]):this.noteOff(i,A[1]);break;case F.pitchBend:this.pitchWheel(i,A[2],A[1]);break;case F.controllerChange:this.controllerChange(i,A[1],A[2],n);break;case F.programChange:this.programChange(i,A[1]);break;case F.polyPressure:this.polyPressure(i,A[0],A[1]);break;case F.channelPressure:this.channelPressure(i,A[1]);break;case F.systemExclusive:this.systemExclusive(new x(A.slice(1)),t);break;case F.reset:this.stopAllChannels(!0),this.resetAllControllers();break;default:break}},r=s.time;r>this.currentSynthTime?(this.eventQueue.push({callback:o.bind(this),time:r}),this.eventQueue.sort((g,i)=>g.time-i.time)):o()}setMIDIVolume(A){this.midiVolume=Math.pow(A,Math.E),this.setMasterParameter(OA.masterPan,this.pan)}callEvent(A,t){this?.onEventCall?.(A,t)}clearCache(){this.cachedVoices=[]}getPreset(A,t){return this.soundfontManager.getPreset(A,t,GA(this.system)).preset}};LA.prototype.voiceKilling=qs;LA.prototype.getVoicesForPreset=go;LA.prototype.getVoices=Io;LA.prototype.systemExclusive=no;LA.prototype.stopAllChannels=uo;LA.prototype.createMidiChannel=Mr;LA.prototype.resetAllControllers=so;LA.prototype.setMasterParameter=Ao;LA.prototype.transposeAllChannels=ar;LA.prototype.setMasterTuning=gr;LA.prototype.clearEmbeddedBank=or;LA.prototype.setEmbeddedSoundFont=rr;LA.prototype.updatePresetList=ir;LA.prototype.applySynthesizerSnapshot=Ir;function KA(e,A){let t=0;for(let n=8*(A-1);n>=0;n-=8)t|=e[e.currentIndex++]<<n;return t>>>0}function Kt(e,A){let t=new Array(A).fill(0);for(let n=A-1;n>=0;n--)t[n]=e&255,e>>=8;return t}function br(e,A){if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=ht(e.messageStatusByte),n=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=n,t.status){case F.noteOn:let s=e.messageData[1];if(s>0)this.synth.noteOn(t.channel,e.messageData[0],s),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:s});else{this.synth.noteOff(t.channel,e.messageData[0]);let g=this.playingNotes.findIndex(i=>i.midiNote===e.messageData[0]&&i.channel===t.channel);g!==-1&&this.playingNotes.splice(g,1)}break;case F.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let o=this.playingNotes.findIndex(g=>g.midiNote===e.messageData[0]&&g.channel===t.channel);o!==-1&&this.playingNotes.splice(o,1);break;case F.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case F.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case F.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.programChange(t.channel,e.messageData[0]);break;case F.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case F.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case F.systemExclusive:this.synth.systemExclusive(e.messageData,n);break;case F.setTempo:e.messageData.currentIndex=0;let r=6e7/KA(e.messageData,3);this.oneTickToSeconds=60/(r*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),Y("invalid tempo! falling back to 120 BPM"),r=120);break;case F.timeSignature:case F.endOfTrack:case F.midiChannelPrefix:case F.songPosition:case F.activeSensing:case F.keySignature:case F.sequenceNumber:case F.sequenceSpecific:case F.text:case F.lyric:case F.copyright:case F.trackName:case F.marker:case F.cuePoint:case F.instrumentName:case F.programName:break;case F.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case F.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:Y(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(F).find(g=>F[g]===t.status)}`,I.warn,I.unrecognized,I.warn,I.value);break}t.status>=0&&t.status<128&&this?.onMetaEvent?.(e,A)}function Lr(){for(let e=0;e<16;e++)this.synth.createMidiChannel(!0)}function Tr(){if(!this.isActive)return;let e=this.currentTime;for(;this.playedTime<e;){let A=this._findFirstEventIndex(),t=this.tracks[A][this.eventIndex[A]];if(this._processEvent(t,A),this.eventIndex[A]++,A=this._findFirstEventIndex(),this.tracks[A].length<=this.eventIndex[A]){if(this.loop){this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}let n=this.tracks[A][this.eventIndex[A]];this.playedTime+=this.oneTickToSeconds*(n.ticks-t.ticks);let s=this.loop&&(this.loopCount>0||this.loopCount===-1);if(this.midiData.loop.end<=t.ticks&&s){this.loopCount!==1/0&&(this.loopCount--,this?.onLoopCountChange?.(this.loopCount)),this.setTimeTicks(this.midiData.loop.start);return}else if(e>=this.duration){if(s){this.loopCount!==1/0&&(this.loopCount--,this?.onLoopCountChange?.(this.loopCount)),this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function Ur(){let e=0,A=1/0;return this.tracks.forEach((t,n)=>{this.eventIndex[n]>=t.length||t[this.eventIndex[n]].ticks<A&&(e=n,A=t[this.eventIndex[n]].ticks)}),e}var nt=class{timeDivision=0;duration=0;tempoChanges=[{ticks:0,tempo:120}];copyright="";tracksAmount=0;trackNames=[];lyrics=[];lyricsTicks=[];firstNoteOn=0;keyRange={min:0,max:127};lastVoiceEventTick=0;midiPorts=[0];midiPortChannelOffsets=[0];usedChannelsOnTrack=[];loop={start:0,end:0};midiName="";midiNameUsesFileName=!1;fileName="";rawMidiName;format=0;RMIDInfo={};bankOffset=0;isKaraokeFile=!1;isMultiPort=!1;MIDIticksToSeconds(A){let t=0;for(;A>0;){let n=this.tempoChanges.find(o=>o.ticks<A),s=A-n.ticks;t+=s*60/(n.tempo*this.timeDivision),A-=s}return t}_copyFromSequence(A){this.midiName=A.midiName,this.midiNameUsesFileName=A.midiNameUsesFileName,this.fileName=A.fileName,this.timeDivision=A.timeDivision,this.duration=A.duration,this.copyright=A.copyright,this.tracksAmount=A.tracksAmount,this.firstNoteOn=A.firstNoteOn,this.lastVoiceEventTick=A.lastVoiceEventTick,this.format=A.format,this.bankOffset=A.bankOffset,this.isKaraokeFile=A.isKaraokeFile,this.isMultiPort=A.isMultiPort,this.tempoChanges=[...A.tempoChanges],this.lyrics=A.lyrics.map(t=>new Uint8Array(t)),this.lyricsTicks=[...A.lyricsTicks],this.midiPorts=[...A.midiPorts],this.trackNames=[...A.trackNames],this.midiPortChannelOffsets=[...A.midiPortChannelOffsets],this.usedChannelsOnTrack=A.usedChannelsOnTrack.map(t=>new Set(t)),this.rawMidiName=A.rawMidiName?new Uint8Array(A.rawMidiName):void 0,this.loop={...A.loop},this.keyRange={...A.keyRange},this.RMIDInfo={...A.RMIDInfo}}};function mA(e){let A=0;for(;e;){let t=e[e.currentIndex++];if(A=A<<7|t&127,t>>7!==1)break}return A}function wn(e){let A=[e&127];for(e>>=7;e>0;)A.unshift(e&127|128),e>>=7;return A}function vr(){let e=this;if(!e.tracks)throw new Error("MIDI has no tracks!");let A=[];for(let s of e.tracks){let o=[],r=0,g;for(let i of s){let E=i.ticks-r,l;i.messageStatusByte<=F.sequenceSpecific?(l=[255,i.messageStatusByte,...wn(i.messageData.length),...i.messageData],g=void 0):i.messageStatusByte===F.systemExclusive?(l=[240,...wn(i.messageData.length),...i.messageData],g=void 0):(l=[],g!==i.messageStatusByte&&(g=i.messageStatusByte,l.push(i.messageStatusByte)),l.push(...i.messageData)),o.push(...wn(E)),o.push(...l),r+=E}A.push(new Uint8Array(o))}function t(s,o){for(let r=0;r<s.length;r++)o.push(s.charCodeAt(r))}let n=[];t("MThd",n),n.push(...Kt(6,4)),n.push(0,e.format),n.push(...Kt(e.tracksAmount,2)),n.push(...Kt(e.timeDivision,2));for(let s of A)t("MTrk",n),n.push(...Kt(s.length,4)),n.push(...s);return new Uint8Array(n)}function mt(e){return e.messageData[0]===67&&e.messageData[2]===76&&e.messageData[5]===126&&e.messageData[6]===0}function Rn(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[3]===18&&e.messageData[4]===64&&(e.messageData[5]&16)!==0&&e.messageData[6]===21}function Gn(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[6]===127}function Mn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===1}function xn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===3}function ys(e){return new YA(e,F.systemExclusive,new x([65,16,66,18,64,0,127,0,65,247]))}function pt(e,A,t,n){return new YA(n,F.controllerChange|e%16,new x([A,t]))}function Yi(e,A){let t=16|[1,2,3,4,5,6,7,8,0,9,10,11,12,13,14,15][e%16],n=[65,16,66,18,64,t,21,1],o=128-(64+t+21+1)%128;return new YA(A,F.systemExclusive,new x([...n,o,247]))}function Hr(e=[],A=[],t=[],n=[]){let s=this;uA("%cApplying changes to the MIDI file...",I.info),y("Desired program changes:",e),y("Desired CC changes:",A),y("Desired channels to clear:",t),y("Desired channels to transpose:",n);let o=new Set;e.forEach(M=>{o.add(M.channel)});let r="gs",g=!1,i=Array(s.tracks.length).fill(0),E=s.tracks.length;function l(){let M=0,T=1/0;return s.tracks.forEach((R,C)=>{i[C]>=R.length||R[i[C]].ticks<T&&(M=C,T=R[i[C]].ticks)}),M}let c=s.midiPorts.slice(),h={},B=0;function m(M,T){s.usedChannelsOnTrack[M].size!==0&&(B===0&&(B+=16,h[T]=0),h[T]===void 0&&(h[T]=B,B+=16),c[M]=T)}s.midiPorts.forEach((M,T)=>{m(T,M)});let f=B,S=Array(f).fill(!0),G=Array(f).fill(0),D=Array(f).fill(0);for(n.forEach(M=>{let T=Math.trunc(M.keyShift),R=M.keyShift-T;G[M.channel]=T,D[M.channel]=R});E>0;){let M=l(),T=s.tracks[M];if(i[M]>=T.length){E--;continue}let R=i[M]++,C=T[R],b=()=>{T.splice(R,1),i[M]--},L=(hA,oA=0)=>{T.splice(R+oA,0,hA),i[M]++},nA=h[c[M]]||0;if(C.messageStatusByte===F.midiPort){m(M,C.messageData[0]);continue}if(C.messageStatusByte<=F.sequenceSpecific&&C.messageStatusByte>=F.sequenceNumber)continue;let $=C.messageStatusByte&240,U=C.messageStatusByte&15,tA=U+nA;if(t.indexOf(tA)!==-1){b();continue}switch($){case F.noteOn:if(S[tA]){S[tA]=!1,A.filter(cA=>cA.channel===tA).forEach(cA=>{let H=pt(U,cA.controllerNumber,cA.controllerValue,C.ticks);L(H)});let rA=D[tA];if(rA!==0){let cA=rA*64+64,H=pt(U,p.RPNMsb,0,C.ticks),J=pt(U,p.RPNLsb,1,C.ticks),z=pt(tA,p.dataEntryMsb,cA,C.ticks),V=pt(U,p.lsbForControl6DataEntry,0,C.ticks);L(V),L(z),L(J),L(H)}if(o.has(tA)){let cA=e.find(iA=>iA.channel===tA),H=Math.max(0,Math.min(cA.bank,127)),J=cA.program;y(`%cSetting %c${cA.channel}%c to %c${H}:${J}%c. Track num: %c${M}`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized);let z=new YA(C.ticks,F.programChange|U,new x([J]));L(z);let V=(iA,qA)=>{let Ee=pt(U,iA?p.lsbForControl0BankSelect:p.bankSelect,qA,C.ticks);L(Ee)};GA(r)?cA.isDrum?(y(`%cAdding XG Drum change on track %c${M}`,I.recognized,I.value),V(!1,Ae(H)?H:127),V(!0,0)):H===an?(V(!1,an),V(!0,0)):(V(!1,0),V(!0,H)):(V(!1,H),cA.isDrum&&U!==9&&(y(`%cAdding GS Drum change on track %c${M}`,I.recognized,I.value),L(Yi(U,C.ticks))))}}C.messageData[0]+=G[tA];break;case F.noteOff:C.messageData[0]+=G[tA];break;case F.programChange:if(o.has(tA)){b();continue}break;case F.controllerChange:let hA=C.messageData[0];if(A.find(rA=>rA.channel===tA&&hA===rA.controllerNumber)!==void 0){b();continue}if((hA===p.bankSelect||hA===p.lsbForControl0BankSelect)&&o.has(tA)){b();continue}break;case F.systemExclusive:if(mt(C))y("%cXG system on detected",I.info),r="xg",g=!0;else if(C.messageData[0]===67&&C.messageData[2]===76&&C.messageData[3]===8&&C.messageData[5]===3)o.has(C.messageData[4]+nA)&&b();else if(Gn(C)){g=!0,y("%cGS on detected!",I.recognized);break}else(Mn(C)||xn(C))&&(y("%cGM/2 on detected, removing!",I.info),b(),g=!1)}}if(!g&&e.length>0){let M=0;s.tracks[0][0].messageStatusByte===F.trackName&&M++,s.tracks[0].splice(M,0,ys(0)),y("%cGS on not detected. Adding it.",I.info)}this.flush(),q()}function Yr(e){let A=[],t=[],n=[],s=[];e.channelSnapshots.forEach((o,r)=>{if(o.isMuted){t.push(r);return}let g=o.channelTransposeKeyShift+o.customControllers[CA.channelTransposeFine]/100;g!==0&&A.push({channel:r,keyShift:g}),o.lockPreset&&n.push({channel:r,program:o.program,bank:o.bank,isDrum:o.drumChannel}),o.lockedControllers.forEach((i,E)=>{if(!i||E>127||E===p.bankSelect)return;let l=o.midiControllers[E]>>7;s.push({channel:r,controllerNumber:E,controllerValue:l})})}),this.modifyMIDI(n,s,t,A)}var pA={name:"INAM",album:"IPRD",album2:"IALB",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"},qe="utf-8",Oi="Created using SpessaSynth";function Or(e,A,t=0,n="Shift_JIS",s={},o=!0){let r=this;if(ge("%cWriting the RMIDI File...",I.info),y(`%cConfiguration: Bank offset: %c${t}%c, encoding: %c${n}`,I.info,I.value,I.info,I.value),y("metadata",s),y("Initial bank offset",r.bankOffset),o){let G=function(){let R=0,C=1/0;return r.tracks.forEach((b,L)=>{f[L]>=b.length||b[f[L]].ticks<C&&(R=L,C=b[f[L]].ticks)}),R},B="gm",m=[],f=Array(r.tracks.length).fill(0),S=r.tracks.length,D=Array(r.tracks.length).fill(0),M=16+r.midiPortChannelOffsets.reduce((R,C)=>C>R?C:R),T=[];for(let R=0;R<M;R++)T.push({program:0,drums:R%16===9,lastBank:void 0,lastBankLSB:void 0,hasBankSelect:!1});for(;S>0;){let R=G(),C=r.tracks[R];if(f[R]>=C.length){S--;continue}let b=C[f[R]];f[R]++;let L=r.midiPortChannelOffsets[D[R]];if(b.messageStatusByte===F.midiPort){D[R]=b.messageData[0];continue}let nA=b.messageStatusByte&240;if(nA!==F.controllerChange&&nA!==F.programChange&&nA!==F.systemExclusive)continue;if(nA===F.systemExclusive){if(!Rn(b)){mt(b)?B="xg":Gn(b)?B="gs":Mn(b)?(B="gm",m.push({tNum:R,e:b})):xn(b)&&(B="gm2");continue}let rA=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][b.messageData[5]&15]+L;T[rA].drums=!!(b.messageData[7]>0&&b.messageData[5]>>4);continue}let $=(b.messageStatusByte&15)+L,U=T[$];if(nA===F.programChange){let rA=GA(B),cA=b.messageData[0];U.drums?A.presets.findIndex(V=>V.program===cA&&V.isDrumPreset(rA,!0))===-1&&(b.messageData[0]=A.presets.find(V=>V.isDrumPreset(rA))?.program||0,y(`%cNo drum preset %c${cA}%c. Channel %c${$}%c. Changing program to ${b.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)):A.presets.findIndex(V=>V.program===cA&&!V.isDrumPreset(rA))===-1&&(b.messageData[0]=A.presets.find(V=>!V.isDrumPreset(rA))?.program||0,y(`%cNo preset %c${cA}%c. Channel %c${$}%c. Changing program to ${b.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)),U.program=b.messageData[0];let H=Math.max(0,U.lastBank?.messageData[1]-r.bankOffset),J=U?.lastBankLSB?.messageData[1]-r.bankOffset||0;if(U.lastBank===void 0)continue;let z=Bt(H,J,U.drums,rA);if(A.presets.findIndex(V=>V.bank===z&&V.program===b.messageData[0])===-1){let V=A.presets.find(iA=>iA.program===b.messageData[0])?.bank+t||t;U.lastBank.messageData[1]=V,U?.lastBankLSB?.messageData&&(U.lastBankLSB.messageData[1]=V),y(`%cNo preset %c${z}:${b.messageData[0]}%c. Channel %c${$}%c. Changing bank to ${V}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)}else{let V=z;GA(B)&&z===128&&(z=127);let iA=(z===128?128:V)+t;U.lastBank.messageData[1]=iA,U?.lastBankLSB?.messageData&&!U.drums&&(U.lastBankLSB.messageData[1]=U.lastBankLSB.messageData[1]-r.bankOffset+t),y(`%cPreset %c${z}:${b.messageData[0]}%c exists. Channel %c${$}%c. Changing bank to ${iA}.`,I.info,I.recognized,I.info,I.recognized,I.info)}continue}let tA=b.messageData[0]===p.lsbForControl0BankSelect;if(b.messageData[0]!==p.bankSelect&&!tA)continue;U.hasBankSelect=!0;let hA=b.messageData[1],oA=lt(U?.lastBank?.messageData[1]||0,hA,B,tA,U.drums,$);oA.drumsStatus===2?U.drums=!0:oA.drumsStatus===1&&(U.drums=!1),tA?U.lastBankLSB=b:U.lastBank=b}if(T.forEach((R,C)=>{if(R.hasBankSelect===!0)return;let b=C%16,L=F.programChange|b,nA=Math.floor(C/16)*16,$=r.midiPortChannelOffsets.indexOf(nA),U=r.tracks.find((rA,cA)=>r.midiPorts[cA]===$&&r.usedChannelsOnTrack[cA].has(b));if(U===void 0)return;let tA=U.findIndex(rA=>rA.messageStatusByte===L);if(tA===-1){let rA=U.findIndex(J=>J.messageStatusByte>128&&J.messageStatusByte<240&&(J.messageStatusByte&15)===b);if(rA===-1)return;let cA=U[rA].ticks,H=A.getPreset(0,0).program;U.splice(rA,0,new YA(cA,F.programChange|b,new x([H]))),tA=rA}y(`%cAdding bank select for %c${C}`,I.info,I.recognized);let hA=U[tA].ticks,oA=A.getPreset(0,R.program,GA(B))?.bank+t||t;U.splice(tA,0,new YA(hA,F.controllerChange|b,new x([p.bankSelect,oA])))}),B!=="gs"&&!GA(B)){for(let C of m)r.tracks[C.tNum].splice(r.tracks[C.tNum].indexOf(C.e),1);let R=0;r.tracks[0][0].messageStatusByte===F.trackName&&R++,r.tracks[0].splice(R,0,ys(0))}}let g=new x(r.writeMIDI().buffer),i=[_e("INFO")],E=new TextEncoder;if(i.push(j(pA.software,E.encode("SpessaSynth"),!0)),s.name!==void 0?(i.push(j(pA.name,E.encode(s.name),!0)),n=qe):i.push(j(pA.name,r.rawMidiName,!0)),s.creationDate!==void 0)n=qe,i.push(j(pA.creationDate,E.encode(s.creationDate),!0));else{let B=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});i.push(j(pA.creationDate,pe(B),!0))}if(s.comment!==void 0&&(n=qe,i.push(j(pA.comment,E.encode(s.comment)))),s.engineer!==void 0&&i.push(j(pA.engineer,E.encode(s.engineer),!0)),s.album!==void 0&&(n=qe,i.push(j(pA.album,E.encode(s.album),!0)),i.push(j(pA.album2,E.encode(s.album),!0))),s.artist!==void 0&&(n=qe,i.push(j(pA.artist,E.encode(s.artist),!0))),s.genre!==void 0&&(n=qe,i.push(j(pA.genre,E.encode(s.genre),!0))),s.picture!==void 0&&i.push(j(pA.picture,new Uint8Array(s.picture))),s.copyright!==void 0)n=qe,i.push(j(pA.copyright,E.encode(s.copyright),!0));else{let B=r.copyright.length>0?r.copyright:Oi;i.push(j(pA.copyright,pe(B)))}let l=new x(2);Je(l,t,2),i.push(j(pA.bankOffset,l)),s.midiEncoding!==void 0&&(i.push(j(pA.midiEncoding,E.encode(s.midiEncoding))),n=qe),i.push(j(pA.encoding,pe(n)));let c=kA(i),h=kA([_e("RMID"),j("data",g),j("LIST",c),e]);return y("%cFinished!",I.info),q(),j("RIFF",h)}function Jr(e){let A=this;uA("%cSearching for all used programs and keys...",I.info);let t=16+A.midiPortChannelOffsets.reduce((c,h)=>h>c?h:c),n=[];for(let c=0;c<t;c++){let h=c%16===9?128:0;n.push({program:0,bank:h,bankLSB:0,actualBank:h,drums:c%16===9,string:`${h}:0`})}let s="gs";function o(c){let h=Bt(c.bank,c.bankLSB,c.drums,GA(s)),B,m;if(e instanceof Qt){let f=e.getPreset(h,c.program,GA(s));B=f.preset.bank+f.bankOffset,m=f.preset.program}else{let f=e.getPreset(h,c.program,GA(s));B=f.bank,m=f.program}c.actualBank=B,c.program=m,c.string=c.actualBank+":"+c.program,r[c.string]||(y(`%cDetected a new preset: %c${c.string}`,I.info,I.recognized),r[c.string]=new Set)}let r={},g=Array(A.tracks.length).fill(0),i=A.tracks.length;function E(){let c=0,h=1/0;return A.tracks.forEach((B,m)=>{g[m]>=B.length||B[g[m]].ticks<h&&(c=m,h=B[g[m]].ticks)}),c}let l=A.midiPorts.slice();for(n.forEach(c=>{o(c)});i>0;){let c=E(),h=A.tracks[c];if(g[c]>=h.length){i--;continue}let B=h[g[c]];if(g[c]++,B.messageStatusByte===F.midiPort){l[c]=B.messageData[0];continue}let m=B.messageStatusByte&240;if(m!==F.noteOn&&m!==F.controllerChange&&m!==F.programChange&&m!==F.systemExclusive)continue;let f=(B.messageStatusByte&15)+A.midiPortChannelOffsets[l[c]]||0,S=n[f];switch(m){case F.programChange:S.program=B.messageData[0],o(S);break;case F.controllerChange:let G=B.messageData[0]===p.lsbForControl0BankSelect;if(B.messageData[0]!==p.bankSelect&&!G||s==="gs"&&S.drums)continue;let D=B.messageData[1];switch(G?S.bankLSB=D:S.bank=D,lt(S.bank,D,s,G,S.drums,f).drumsStatus){case 0:break;case 1:S.drums=!1,o(S);break;case 2:S.drums=!0,o(S);break}break;case F.noteOn:if(B.messageData[1]===0)continue;r[S.string].add(`${B.messageData[0]}-${B.messageData[1]}`);break;case F.systemExclusive:if(!Rn(B)){mt(B)&&(s="xg",y("%cXG on detected!",I.recognized));continue}let T=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][B.messageData[5]&15]+A.midiPortChannelOffsets[l[c]],R=!!(B.messageData[7]>0&&B.messageData[5]>>4);S=n[T],S.drums=R,o(S);break}}for(let c of Object.keys(r))r[c].size===0&&(y(`%cDetected change but no keys for %c${c}`,I.info,I.value),delete r[c]);return q(),r}function Kr(e=0){function A(c){return c.messageData=new x(c.messageData.buffer),c.messageData.currentIndex=0,6e7/KA(c.messageData,3)}let t=[],s=this.tracks.flat();s.sort((c,h)=>c.ticks-h.ticks);for(let c=0;c<16;c++)t.push([]);let o=0,r=60/(120*this.timeDivision),g=0,i=0,E=[];for(let c=0;c<16;c++)E.push([]);let l=(c,h)=>{let B=E[h].findIndex(f=>f.midiNote===c),m=E[h][B];if(m){let f=o-m.start;m.length=f,h===9&&(m.length=f<e?e:f),E[h].splice(B,1)}i--};for(;g<s.length;){let c=s[g],h=c.messageStatusByte>>4,B=c.messageStatusByte&15;if(h===8)l(c.messageData[0],B);else if(h===9)if(c.messageData[1]===0)l(c.messageData[0],B);else{l(c.messageData[0],B);let m={midiNote:c.messageData[0],start:o,length:-1,velocity:c.messageData[1]/127};t[B].push(m),E[B].push(m),i++}else c.messageStatusByte===81&&(r=60/(A(c)*this.timeDivision));if(++g>=s.length)break;o+=r*(s[g].ticks-c.ticks)}return i>0&&E.forEach((c,h)=>{c.forEach(B=>{let m=o-B.start;B.length=m,h===9&&(B.length=m<e?e:m)})}),t}var WA=class e extends nt{embeddedSoundFont=void 0;tracks=[];isDLSRMIDI=!1;static copyFrom(A){let t=new e;return t._copyFromSequence(A),t.isDLSRMIDI=A.isDLSRMIDI,t.embeddedSoundFont=A.embeddedSoundFont?A.embeddedSoundFont.slice(0):void 0,t.tracks=A.tracks.map(n=>[...n]),t}_parseInternal(){ge("%cInterpreting MIDI events...",I.info);let A=!1;this.keyRange={max:0,min:127};let t=[],n=!1;typeof this.RMIDInfo.ICOP<"u"&&(n=!0);let s=!1;typeof this.RMIDInfo.INAM<"u"&&(s=!0);let o=null,r=null;for(let l=0;l<this.tracks.length;l++){let c=this.tracks[l],h=new Set,B=!1;for(let f of c){if(f.messageStatusByte>=128&&f.messageStatusByte<240){B=!0;for(let G=0;G<f.messageData.length;G++)f.messageData[G]=Math.min(127,f.messageData[G]);switch(f.ticks>this.lastVoiceEventTick&&(this.lastVoiceEventTick=f.ticks),f.messageStatusByte&240){case F.controllerChange:switch(f.messageData[0]){case 2:case 116:o=f.ticks;break;case 4:case 117:r===null?r=f.ticks:r=0;break;case 0:this.isDLSRMIDI&&f.messageData[1]!==0&&f.messageData[1]!==127&&(y("%cDLS RMIDI with offset 1 detected!",I.recognized),this.bankOffset=1)}break;case F.noteOn:h.add(f.messageStatusByte&15);let G=f.messageData[0];this.keyRange.min=Math.min(this.keyRange.min,G),this.keyRange.max=Math.max(this.keyRange.max,G);break}}f.messageData.currentIndex=0;let S=AA(f.messageData,f.messageData.length);switch(f.messageData.currentIndex=0,f.messageStatusByte){case F.setTempo:f.messageData.currentIndex=0,this.tempoChanges.push({ticks:f.ticks,tempo:6e7/KA(f.messageData,3)}),f.messageData.currentIndex=0;break;case F.marker:switch(S.trim().toLowerCase()){default:break;case"start":case"loopstart":o=f.ticks;break;case"loopend":r=f.ticks}f.messageData.currentIndex=0;break;case F.copyright:n||(f.messageData.currentIndex=0,t.push(AA(f.messageData,f.messageData.length,void 0,!1)),f.messageData.currentIndex=0);break;case F.lyric:if(S.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,y("%cKaraoke MIDI detected!",I.recognized)),this.isKaraokeFile)f.messageStatusByte=F.text;else{this.lyrics.push(f.messageData),this.lyricsTicks.push(f.ticks);break}case F.text:let D=S.trim();D.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,y("%cKaraoke MIDI detected!",I.recognized)):this.isKaraokeFile&&(D.startsWith("@T")||D.startsWith("@A")?A?t.push(D.substring(2).trim()):(this.midiName=D.substring(2).trim(),A=!0,s=!0,this.rawMidiName=_e(this.midiName)):D[0]!=="@"&&(this.lyrics.push(Ks(f.messageData)),this.lyricsTicks.push(f.ticks)));break;case F.trackName:break}}this.usedChannelsOnTrack.push(h),this.trackNames[l]="";let m=c.find(f=>f.messageStatusByte===F.trackName);if(m){m.messageData.currentIndex=0;let f=AA(m.messageData,m.messageData.length);this.trackNames[l]=f,B||t.push(f)}}this.tempoChanges.reverse(),y("%cCorrecting loops, ports and detecting notes...",I.info);let g=[];for(let l of this.tracks){let c=l.find(h=>(h.messageStatusByte&240)===F.noteOn);c&&g.push(c.ticks)}this.firstNoteOn=Math.min(...g),y(`%cFirst note-on detected at: %c${this.firstNoteOn}%c ticks!`,I.info,I.recognized,I.info),o!==null&&r===null?(o=this.firstNoteOn,r=this.lastVoiceEventTick):(o===null&&(o=this.firstNoteOn),(r===null||r===0)&&(r=this.lastVoiceEventTick)),this.loop={start:o,end:r},y(`%cLoop points: start: %c${this.loop.start}%c end: %c${this.loop.end}`,I.info,I.recognized,I.info,I.recognized);let i=0;this.midiPorts=[],this.midiPortChannelOffsets=[];for(let l=0;l<this.tracks.length;l++)if(this.midiPorts.push(-1),this.usedChannelsOnTrack[l].size!==0)for(let c of this.tracks[l]){if(c.messageStatusByte!==F.midiPort)continue;let h=c.messageData[0];this.midiPorts[l]=h,this.midiPortChannelOffsets[h]===void 0&&(this.midiPortChannelOffsets[h]=i,i+=16)}this.midiPortChannelOffsets=[...this.midiPortChannelOffsets].map(l=>l??0);let E=1/0;for(let l of this.midiPorts)l!==-1&&E>l&&(E=l);if(E===1/0&&(E=0),this.midiPorts=this.midiPorts.map(l=>l===-1||l===void 0?E:l),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?y("%cNo additional MIDI Ports detected.",I.info):(this.isMultiPort=!0,y("%cMIDI Ports detected!",I.recognized)),!s)if(this.tracks.length>1){if(this.tracks[0].find(l=>l.messageStatusByte>=F.noteOn&&l.messageStatusByte<F.polyPressure)===void 0){let l=this.tracks[0].find(c=>c.messageStatusByte===F.trackName);l&&(this.rawMidiName=l.messageData,l.messageData.currentIndex=0,this.midiName=AA(l.messageData,l.messageData.length,void 0,!1))}}else{let l=this.tracks[0].find(c=>c.messageStatusByte===F.trackName);l&&(this.rawMidiName=l.messageData,l.messageData.currentIndex=0,this.midiName=AA(l.messageData,l.messageData.length,void 0,!1))}if(n||(this.copyright=t.map(l=>l.trim().replace(/(\r?\n)+/g,`
|
|
18
18
|
`)).filter(l=>l.length>0).join(`
|
|
19
19
|
`)||""),this.midiName=this.midiName.trim(),this.midiNameUsesFileName=!1,this.midiName.length===0){y("%cNo name detected. Using the alt name!",I.info),this.midiName=Js(this.fileName),this.midiNameUsesFileName=!0,this.rawMidiName=new Uint8Array(this.midiName.length);for(let l=0;l<this.midiName.length;l++)this.rawMidiName[l]=this.midiName.charCodeAt(l)}else y(`%cMIDI Name detected! %c"${this.midiName}"`,I.info,I.recognized);this.tracks.some(l=>l[0].ticks===0)||this.tracks[0].unshift(new YA(0,F.trackName,new x(this.rawMidiName.buffer))),this.duration=this.MIDIticksToSeconds(this.lastVoiceEventTick),y("%cSuccess!",I.recognized),q()}flush(){for(let A of this.tracks)A.sort((t,n)=>t.ticks-n.ticks);this._parseInternal()}};WA.prototype.writeMIDI=vr;WA.prototype.modifyMIDI=Hr;WA.prototype.applySnapshotToMIDI=Yr;WA.prototype.writeRMIDI=Or;WA.prototype.getUsedProgramsAndKeys=Jr;WA.prototype.getNoteTimes=Kr;function qr(e,A){this.midiData.usedChannelsOnTrack[e].size!==0&&(this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.midiAudioChannels.length<this.midiPortChannelOffset+15&&this._addNewMidiPort(),this.midiPortChannelOffsets[A]=this.midiPortChannelOffset,this.midiPortChannelOffset+=16),this.midiPorts[e]=A)}function Vr(e,A=!0){if(this.stop(),!e.tracks)throw new Error("This MIDI has no tracks!");this.oneTickToSeconds=60/(120*e.timeDivision),this.midiData=e,this.synth.clearEmbeddedBank(),this.midiData.embeddedSoundFont!==void 0&&(y("%cEmbedded soundfont detected! Using it.",I.recognized),this.synth.setEmbeddedSoundFont(this.midiData.embeddedSoundFont,this.midiData.bankOffset)),uA("%cPreloading samples...",I.info);let t=this.midiData.getUsedProgramsAndKeys(this.synth.soundfontManager);for(let[n,s]of Object.entries(t)){let[o,r]=n.split(":").map(Number),g=this.synth.getPreset(o,r);y(`%cPreloading used samples on %c${g.presetName}%c...`,I.info,I.recognized,I.info);for(let i of s){let[E,l]=i.split("-").map(Number);this.synth.getVoicesForPreset(g,o,r,E,l,E)}}if(q(),this.tracks=this.midiData.tracks,this.midiPorts=this.midiData.midiPorts.slice(),this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this.midiData.midiPorts.forEach((n,s)=>{this.assignMIDIPort(s,n)}),this.duration=this.midiData.duration,this.firstNoteTime=this.midiData.MIDIticksToSeconds(this.midiData.firstNoteOn),y(`%cTotal song time: ${_n(Math.ceil(this.duration)).time}`,I.recognized),this?.onSongChange?.(this.songIndex,A),this.duration<=1&&(Y(`%cVery short song: (${_n(Math.round(this.duration)).time}). Disabling loop!`,I.warn),this.loop=!1),A)this.play(!0);else{let n=this.skipToFirstNoteOn?this.midiData.firstNoteOn-1:0;this.setTimeTicks(n),this.pause()}}function Pr(e,A=!0){this.songs=e.map(t=>WA.copyFrom(t)),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.shuffleSongIndexes(),this?.onSongListChange?.(this.songs),this.loadCurrentSong(A))}function Zr(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadCurrentSong()}function Xr(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadCurrentSong()}var st=Ye.slice(0,128);function Wr(e,A=void 0){this.oneTickToSeconds=60/(120*this.midiData.timeDivision),this.synth.resetAllControllers(),this.sendMIDIReset(),this._resetTimers();let t=this.synth.midiAudioChannels.length,n=Array(t).fill(8192),s=[];for(let i=0;i<t;i++)s.push({program:-1,bank:0,actualBank:0});let o=i=>i===p.dataDecrement||i===p.dataIncrement||i===p.dataEntryMsb||i===p.dataDecrement||i===p.lsbForControl6DataEntry||i===p.RPNLsb||i===p.RPNMsb||i===p.NRPNLsb||i===p.NRPNMsb||i===p.bankSelect||i===p.lsbForControl0BankSelect||i===p.resetAllControllers,r=[];for(let i=0;i<t;i++)r.push(Array.from(st));function g(i){if(n[i]=8192,r?.[i]!==void 0)for(let E=0;E<st.length;E++)as.has(E)||(r[i][E]=st[E])}for(;;){let i=this._findFirstEventIndex(),E=this.tracks[i][this.eventIndex[i]];if(A!==void 0){if(E.ticks>=A)break}else if(this.playedTime>=e)break;let l=ht(E.messageStatusByte),c=l.channel+(this.midiPortChannelOffsets[this.midiPorts[i]]||0);switch(l.status){case F.noteOn:r[c]===void 0&&(r[c]=Array.from(st)),r[c][p.portamentoControl]=E.messageData[0];break;case F.noteOff:break;case F.pitchBend:n[c]=E.messageData[1]<<7|E.messageData[0];break;case F.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[i].size===0)break;let B=s[c];B.program=E.messageData[0],B.actualBank=B.bank;break;case F.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[i].size===0)break;let m=E.messageData[0];if(o(m)){let f=E.messageData[1];if(m===p.bankSelect){s[c].bank=f;break}else m===p.resetAllControllers&&g(c);this.sendMIDIMessages?this.sendMIDICC(c,m,f):this.synth.controllerChange(c,m,f)}else r[c]===void 0&&(r[c]=Array.from(st)),r[c][m]=E.messageData[1];break;default:this._processEvent(E,i);break}this.eventIndex[i]++,i=this._findFirstEventIndex();let h=this.tracks[i][this.eventIndex[i]];if(h===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(h.ticks-E.ticks)}if(this.sendMIDIMessages){for(let i=0;i<t;i++)if(n[i]!==void 0&&this.sendMIDIPitchWheel(i,n[i]>>7,n[i]&127),r[i]!==void 0&&r[i].forEach((E,l)=>{E!==st[l]&&!o(l)&&this.sendMIDICC(i,l,E)}),s[i].program>=0&&s[i].actualBank>=0){let E=s[i].actualBank;this.sendMIDICC(i,p.bankSelect,E),this.sendMIDIProgramChange(i,s[i].program)}}else for(let i=0;i<t;i++)if(n[i]!==void 0&&this.synth.pitchWheel(i,n[i]>>7,n[i]&127),r[i]!==void 0&&r[i].forEach((E,l)=>{E!==st[l]&&!o(l)&&this.synth.controllerChange(i,l,E)}),s[i].actualBank>=0){let E=s[i];E.program!==-1?(this.synth.controllerChange(i,p.bankSelect,E.actualBank),this.synth.programChange(i,E.program)):this.synth.controllerChange(i,p.bankSelect,E.bank)}return!0}function _r(e=!1){if(this.midiData!==void 0){if(e){this.pausedTime=void 0,this.currentTime=0;return}if(this.currentTime>=this.duration){this.pausedTime=void 0,this.currentTime=0;return}this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),this.sendMIDIMessages||this.playingNotes.forEach(A=>{this.synth.noteOn(A.channel,A.midiNote,A.velocity)}),this.setProcessHandler()}}function zr(e){if(!this.midiData)return;this.stop(),this.playingNotes=[],this.pausedTime=void 0,this?.onTimeChange?.(this.midiData.MIDIticksToSeconds(e));let A=this._playTo(0,e);this._recalculateStartTime(this.playedTime),A&&this.play()}function jr(e){this.absoluteStartTime=this.synth.currentSynthTime-e/this._playbackRate}function $r(e){this.sendMIDIMessages&&this?.onMIDIMessage?.(e)}function Ai(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.controllerChange|e,A,t])}function ei(e,A){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.programChange|e,A])}function ti(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([F.pitchBend|e,t,A])}function ni(){if(this.sendMIDIMessages){this.sendMIDIMessage([F.reset]);for(let e=0;e<16;e++)this.sendMIDIMessage([F.controllerChange|e,p.allSoundOff,0]),this.sendMIDIMessage([F.controllerChange|e,p.resetAllControllers,0])}}var wA=class{songs=[];songIndex=0;shuffledSongIndexes=[];synth;isActive=!1;sendMIDIMessages=!1;loopCount=1/0;eventIndex=[];playedTime=0;pausedTime=void 0;absoluteStartTime=0;playingNotes=[];loop=!0;shuffleMode=!1;midiData=void 0;midiPorts=[];midiPortChannelOffset=0;midiPortChannelOffsets={};skipToFirstNoteOn=!0;preservePlaybackState=!1;onMIDIMessage;onTimeChange;onPlaybackStop;onSongListChange;onSongChange;onMetaEvent;onLoopCountChange;constructor(A){this.synth=A,this.absoluteStartTime=this.synth.currentSynthTime}_playbackRate=1;set playbackRate(A){let t=this.currentTime;this._playbackRate=A,this.currentTime=t}get currentTime(){return this.pausedTime!==void 0?this.pausedTime:(this.synth.currentSynthTime-this.absoluteStartTime)*this._playbackRate}set currentTime(A){if(!this.midiData)return;if(A>this.duration||A<0){this.skipToFirstNoteOn?this.setTimeTicks(this.midiData.firstNoteOn-1):this.setTimeTicks(0);return}if(this.skipToFirstNoteOn&&A<this.firstNoteTime){this.setTimeTicks(this.midiData.firstNoteOn-1);return}this.stop(),this.playingNotes=[];let t=this.paused&&this.preservePlaybackState;if(this.pausedTime=void 0,this?.onTimeChange?.(A),this.midiData.duration===0){Y("No duration!"),this?.onPlaybackStop?.(!0);return}this._playTo(A),this._recalculateStartTime(A),t?this.pause():this.play()}get paused(){return this.pausedTime!==void 0}pause(A=!1){if(this.paused){Y("Already paused");return}this.pausedTime=this.currentTime,this.stop(),this?.onPlaybackStop?.(A)}stop(){this.clearProcessHandler();for(let A=0;A<16;A++)this.synth.controllerChange(A,p.sustainPedal,0);if(this.synth.stopAllChannels(),this.sendMIDIMessages){for(let A of this.playingNotes)this.sendMIDIMessage([F.noteOff|A.channel%16,A.midiNote]);for(let A=0;A<16;A++)this.sendMIDICC(A,p.allNotesOff,0)}}loadCurrentSong(A=!0){let t=this.songIndex;this.shuffleMode&&(t=this.shuffledSongIndexes[this.songIndex]),this.loadNewSequence(this.songs[t],A)}_resetTimers(){this.playedTime=0,this.eventIndex=Array(this.tracks.length).fill(0)}setProcessHandler(){this.isActive=!0}clearProcessHandler(){this.isActive=!1}shuffleSongIndexes(){let A=this.songs.map((t,n)=>n);for(this.shuffledSongIndexes=[];A.length>0;){let t=A[Math.floor(Math.random()*A.length)];this.shuffledSongIndexes.push(t),A.splice(A.indexOf(t),1)}}};wA.prototype.sendMIDIMessage=$r;wA.prototype.sendMIDIReset=ni;wA.prototype.sendMIDICC=Ai;wA.prototype.sendMIDIProgramChange=ei;wA.prototype.sendMIDIPitchWheel=ti;wA.prototype.assignMIDIPort=qr;wA.prototype._processEvent=br;wA.prototype._addNewMidiPort=Lr;wA.prototype.processTick=Tr;wA.prototype._findFirstEventIndex=Ur;wA.prototype.loadNewSequence=Vr;wA.prototype.loadNewSongList=Pr;wA.prototype.nextSong=Zr;wA.prototype.previousSong=Xr;wA.prototype.play=_r;wA.prototype._playTo=Wr;wA.prototype.setTimeTicks=zr;wA.prototype._recalculateStartTime=jr;var qt;(()=>{var e=Uint8Array,A=Uint16Array,t=Int32Array,n=new e([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]),s=new e([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]),o=new e([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),r=function(H,J){for(var z=new A(31),V=0;V<31;++V)z[V]=J+=1<<H[V-1];for(var iA=new t(z[30]),V=1;V<30;++V)for(var qA=z[V];qA<z[V+1];++qA)iA[qA]=qA-z[V]<<5|V;return{b:z,r:iA}},g=r(n,2),i=g.b,E=g.r;i[28]=258,E[258]=28;var l=r(s,0),c=l.b,h=l.r,B=new A(32768);for(D=0;D<32768;++D)m=(D&43690)>>1|(D&21845)<<1,m=(m&52428)>>2|(m&13107)<<2,m=(m&61680)>>4|(m&3855)<<4,B[D]=((m&65280)>>8|(m&255)<<8)>>1;var m,D,f=function(H,J,z){for(var V=H.length,iA=0,qA=new A(J);iA<V;++iA)H[iA]&&++qA[H[iA]-1];var Ee=new A(J);for(iA=1;iA<J;++iA)Ee[iA]=Ee[iA-1]+qA[iA-1]<<1;var Be;if(z){Be=new A(1<<J);var Qe=15-J;for(iA=0;iA<V;++iA)if(H[iA])for(var rt=iA<<4|H[iA],ye=J-H[iA],gA=Ee[H[iA]-1]++<<ye,QA=gA|(1<<ye)-1;gA<=QA;++gA)Be[B[gA]>>Qe]=rt}else for(Be=new A(V),iA=0;iA<V;++iA)H[iA]&&(Be[iA]=B[Ee[H[iA]-1]++]>>15-H[iA]);return Be},S=new e(288);for(D=0;D<144;++D)S[D]=8;var D;for(D=144;D<256;++D)S[D]=9;var D;for(D=256;D<280;++D)S[D]=7;var D;for(D=280;D<288;++D)S[D]=8;var D,G=new e(32);for(D=0;D<32;++D)G[D]=5;var D,M=f(S,9,1),T=f(G,5,1),R=function(H){for(var J=H[0],z=1;z<H.length;++z)H[z]>J&&(J=H[z]);return J},C=function(H,J,z){var V=J/8|0;return(H[V]|H[V+1]<<8)>>(J&7)&z},b=function(H,J){var z=J/8|0;return(H[z]|H[z+1]<<8|H[z+2]<<16)>>(J&7)},L=function(H){return(H+7)/8|0},nA=function(H,J,z){return(J==null||J<0)&&(J=0),(z==null||z>H.length)&&(z=H.length),new e(H.subarray(J,z))},$=["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"],U=function(H,J,z){var V=new Error(J||$[H]);if(V.code=H,Error.captureStackTrace&&Error.captureStackTrace(V,U),!z)throw V;return V},tA=function(H,J,z,V){var iA=H.length,qA=V?V.length:0;if(!iA||J.f&&!J.l)return z||new e(0);var Ee=!z,Be=Ee||J.i!=2,Qe=J.i;Ee&&(z=new e(iA*3));var rt=function(zt){var He=z.length;if(zt>He){var Mt=new e(Math.max(He*2,zt));Mt.set(z),z=Mt}},ye=J.f||0,gA=J.p||0,QA=J.b||0,de=J.l,_A=J.d,Te=J.m,Ue=J.n,kt=iA*8;do{if(!de){ye=C(H,gA,1);var it=C(H,gA+1,3);if(gA+=3,it)if(it==1)de=M,_A=T,Te=9,Ue=5;else if(it==2){var Ft=C(H,gA,31)+257,Tn=C(H,gA+10,15)+4,Un=Ft+C(H,gA+5,31)+1;gA+=14;for(var at=new e(Un),ve=new e(19),zA=0;zA<Tn;++zA)ve[o[zA]]=C(H,gA+zA*3,7);gA+=Tn*3;for(var vn=R(ve),Zt=(1<<vn)-1,gt=f(ve,vn,1),zA=0;zA<Un;){var wt=gt[C(H,gA,Zt)];gA+=wt&15;var VA=wt>>4;if(VA<16)at[zA++]=VA;else{var Se=0,Rt=0;for(VA==16?(Rt=3+C(H,gA,3),gA+=2,Se=at[zA-1]):VA==17?(Rt=3+C(H,gA,7),gA+=3):VA==18&&(Rt=11+C(H,gA,127),gA+=7);Rt--;)at[zA++]=Se}}var Hn=at.subarray(0,Ft),De=at.subarray(Ft);Te=R(Hn),Ue=R(De),de=f(Hn,Te,1),_A=f(De,Ue,1)}else U(1);else{var VA=L(gA)+4,Xt=H[VA-4]|H[VA-3]<<8,Wt=VA+Xt;if(Wt>iA){Qe&&U(0);break}Be&&rt(QA+Xt),z.set(H.subarray(VA,Wt),QA),J.b=QA+=Xt,J.p=gA=Wt*8,J.f=ye;continue}if(gA>kt){Qe&&U(0);break}}Be&&rt(QA+131072);for(var Rs=(1<<Te)-1,Gs=(1<<Ue)-1,_t=gA;;_t=gA){var Se=de[b(H,gA)&Rs],Ve=Se>>4;if(gA+=Se&15,gA>kt){Qe&&U(0);break}if(Se||U(2),Ve<256)z[QA++]=Ve;else if(Ve==256){_t=gA,de=null;break}else{var Yn=Ve-254;if(Ve>264){var zA=Ve-257,ke=n[zA];Yn=C(H,gA,(1<<ke)-1)+i[zA],gA+=ke}var It=_A[b(H,gA)&Gs],Pe=It>>4;It||U(3),gA+=It&15;var De=c[Pe];if(Pe>3){var ke=s[Pe];De+=b(H,gA)&(1<<ke)-1,gA+=ke}if(gA>kt){Qe&&U(0);break}Be&&rt(QA+131072);var Gt=QA+Yn;if(QA<De){var Et=qA-De,xA=Math.min(De,Gt);for(Et+QA<0&&U(3);QA<xA;++QA)z[QA]=V[Et+QA]}for(;QA<Gt;++QA)z[QA]=z[QA-De]}}J.l=de,J.p=_t,J.b=QA,J.f=ye,de&&(ye=1,J.m=Te,J.d=_A,J.n=Ue)}while(!ye);return QA!=z.length&&Ee?nA(z,0,QA):z.subarray(0,QA)},hA=new e(0);function oA(H,J){return tA(H,{i:2},J&&J.out,J&&J.dictionary)}var rA=typeof TextDecoder<"u"&&new TextDecoder,cA=0;try{rA.decode(hA,{stream:!0}),cA=1}catch{}qt=oA})();var Ss={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},St={inLineResource:1,inFileResource:2,inFileNode:3,externalFile:4,externalXMF:5,XMFFileURIandNodeID:6},Ds={StandardMIDIFile:0,StandardMIDIFileType1:1,DLS1:2,DLS2:3,DLS22:4,mobileDLS:5},Ji={standard:0,MMA:1,registered:2,nonRegistered:3},Nn={none:0,MMAUnpacker:1,registered:2,nonRegistered:3},ks=class e{length;itemCount;metadataLength;metadata={};nodeData;innerNodes=[];packedContent=!1;nodeUnpackers=[];resourceFormat="unknown";constructor(A){let t=A.currentIndex;this.length=mA(A),this.itemCount=mA(A);let n=mA(A),s=A.currentIndex-t,o=n-s,r=A.slice(A.currentIndex,A.currentIndex+o);A.currentIndex+=o,this.metadataLength=mA(r);let g=r.slice(r.currentIndex,r.currentIndex+this.metadataLength);r.currentIndex+=this.metadataLength;let i,E;for(;g.currentIndex<g.length;){if(g[g.currentIndex]===0)g.currentIndex++,i=mA(g),Object.values(Ss).indexOf(i)===-1?(Y(`Unknown field specifier: ${i}`),E=`unknown_${i}`):E=Object.keys(Ss).find(f=>Ss[f]===i);else{let f=mA(g);i=AA(g,f),E=i}let m=mA(g);if(m===0){let f=mA(g),S=g.slice(g.currentIndex,g.currentIndex+f);g.currentIndex+=f,mA(S)<4?this.metadata[E]=AA(S,f-1):this.metadata[E]=S.slice(S.currentIndex)}else Y(`International content: ${m}`),g.currentIndex+=mA(g)}let l=r.currentIndex,c=mA(r),h=r.slice(r.currentIndex,l+c);if(r.currentIndex=l+c,c>0)for(this.packedContent=!0;h.currentIndex<c;){let B={};switch(B.id=mA(h),B.id){case Nn.nonRegistered:case Nn.registered:throw q(),new Error(`Unsupported unpacker ID: ${B.id}`);default:throw q(),new Error(`Unknown unpacker ID: ${B.id}`);case Nn.none:B.standardID=mA(h);break;case Nn.MMAUnpacker:let m=h[h.currentIndex++];m===0&&(m<<=8,m|=h[h.currentIndex++],m<<=8,m|=h[h.currentIndex++]);let f=mA(h);B.manufacturerID=m,B.manufacturerInternalID=f;break}B.decodedSize=mA(h),this.nodeUnpackers.push(B)}switch(A.currentIndex=t+n,this.referenceTypeID=mA(A),this.nodeData=A.slice(A.currentIndex,t+this.length),A.currentIndex=t+this.length,this.referenceTypeID){case St.inLineResource:break;case St.externalXMF:case St.inFileNode:case St.XMFFileURIandNodeID:case St.externalFile:case St.inFileResource:throw q(),new Error(`Unsupported reference type: ${this.referenceTypeID}`);default:throw q(),new Error(`Unknown reference type: ${this.referenceTypeID}`)}if(this.isFile){if(this.packedContent){let m=this.nodeData.slice(2,this.nodeData.length);y(`%cPacked content. Attemting to deflate. Target size: %c${this.nodeUnpackers[0].decodedSize}`,I.warn,I.value);try{this.nodeData=new x(qt(m).buffer)}catch(f){throw q(),new Error(`Error unpacking XMF file contents: ${f.message}.`)}}let B=this.metadata.resourceFormat;if(B===void 0)Y("No resource format for this file node!");else{B[0]!==Ji.standard&&(Y(`Non-standard formatTypeID: ${B}`),this.resourceFormat=B.toString());let f=B[1];Object.values(Ds).indexOf(f)===-1?Y(`Unrecognized resource format: ${f}`):this.resourceFormat=Object.keys(Ds).find(S=>Ds[S]===f)}}else for(this.resourceFormat="folder";this.nodeData.currentIndex<this.nodeData.length;){let B=this.nodeData.currentIndex,m=mA(this.nodeData),f=this.nodeData.slice(B,B+m);this.nodeData.currentIndex=B+m,this.innerNodes.push(new e(f))}}get isFile(){return this.itemCount===0}};function si(e,A){e.bankOffset=0;let t=AA(A,4);if(t!=="XMF_")throw q(),new SyntaxError(`Invalid XMF Header! Expected "_XMF", got "${t}"`);ge("%cParsing XMF file...",I.info);let n=AA(A,4);if(y(`%cXMF version: %c${n}`,I.info,I.recognized),n==="2.00"){let i=KA(A,4),E=KA(A,4);y(`%cFile Type ID: %c${i}%c, File Type Revision ID: %c${E}`,I.info,I.recognized,I.info,I.recognized)}mA(A);let s=mA(A);A.currentIndex+=s,A.currentIndex=mA(A);let o=new ks(A),r,g=i=>{let E=(l,c)=>{i.metadata[l]!==void 0&&typeof i.metadata[l]=="string"&&(e.RMIDInfo[c]=i.metadata[l])};if(E("nodeName",pA.name),E("title",pA.name),E("copyrightNotice",pA.copyright),E("comment",pA.comment),i.isFile)switch(i.resourceFormat){default:return;case"DLS1":case"DLS2":case"DLS22":case"mobileDLS":y("%cFound embedded DLS!",I.recognized),e.embeddedSoundFont=i.nodeData.buffer;break;case"StandardMIDIFile":case"StandardMIDIFileType1":y("%cFound embedded MIDI!",I.recognized),r=i.nodeData;break}else for(let l of i.innerNodes)g(l)};return g(o),q(),r}var Vt=class extends WA{constructor(A,t=""){super(),uA("%cParsing MIDI File...",I.info),this.fileName=t;let n=new x(A),s,o=AA(n,4);if(n.currentIndex-=4,o==="RIFF"){n.currentIndex+=8;let g=AA(n,4,void 0,!1);if(g!=="RMID")throw q(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${g}"`);let i=IA(n);if(i.header!=="data")throw q(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${g}"`);for(s=i.chunkData;n.currentIndex<=n.length;){let E=n.currentIndex,l=IA(n,!0);if(l.header==="RIFF"){let c=AA(l.chunkData,4).toLowerCase();c==="sfbk"||c==="sfpk"||c==="dls "?(y("%cFound embedded soundfont!",I.recognized),this.embeddedSoundFont=n.slice(E,E+l.size).buffer):Y(`Unknown RIFF chunk: "${c}"`),c==="dls "&&(this.isDLSRMIDI=!0)}else if(l.header==="LIST"&&AA(l.chunkData,4)==="INFO"){for(y("%cFound RMIDI INFO chunk!",I.recognized),this.RMIDInfo={};l.chunkData.currentIndex<=l.size;){let h=IA(l.chunkData,!0);this.RMIDInfo[h.header]=h.chunkData}this.RMIDInfo.ICOP&&(this.copyright=AA(this.RMIDInfo.ICOP,this.RMIDInfo.ICOP.length,void 0,!1).replaceAll(`
|
|
20
20
|
`," ")),this.RMIDInfo.INAM&&(this.rawMidiName=this.RMIDInfo[pA.name],this.midiName=AA(this.rawMidiName,this.rawMidiName.length,void 0,!1).replaceAll(`
|