spessasynth_lib 3.26.11 → 3.26.12

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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spessasynth_lib",
3
- "version": "3.26.11",
3
+ "version": "3.26.12",
4
4
  "description": "MIDI and SoundFont2/DLS library for the browsers with no compromises",
5
5
  "browser": "index.js",
6
6
  "type": "module",
@@ -4,5 +4,6 @@
4
4
  export const DEFAULT_SEQUENCER_OPTIONS = {
5
5
  skipToFirstNoteOn: true,
6
6
  autoPlay: true,
7
- preservePlaybackState: false
7
+ preservePlaybackState: false,
8
+ initialPlaybackRate: 1
8
9
  };
@@ -41,6 +41,7 @@ import { DEFAULT_SEQUENCER_OPTIONS } from "./default_sequencer_options.js";
41
41
  * @property {boolean|undefined} autoPlay - if true, the sequencer will automatically start playing the MIDI
42
42
  * @property {boolean|unescape} preservePlaybackState - if true,
43
43
  * the sequencer will stay paused when seeking or changing the playback rate
44
+ * @property {number|undefined} initialPlaybackRate - the initial playback rate, defaults to 1.0 (normal speed)
44
45
  */
45
46
 
46
47
  // noinspection JSUnusedGlobalSymbols
@@ -174,6 +175,11 @@ export class Sequencer
174
175
  */
175
176
  this._preservePlaybackState = options?.preservePlaybackState ?? false;
176
177
 
178
+ if (options?.initialPlaybackRate !== 1)
179
+ {
180
+ this.playbackRate = options?.initialPlaybackRate ?? 1;
181
+ }
182
+
177
183
  if (this._skipToFirstNoteOn === false)
178
184
  {
179
185
  // setter sends message
@@ -200,6 +200,7 @@ class WorkletSpessaProcessor extends AudioWorkletProcessor
200
200
  );
201
201
  this.sequencer.skipToFirstNoteOn = seqOptions.skipToFirstNoteOn;
202
202
  this.sequencer.preservePlaybackState = seqOptions.preservePlaybackState;
203
+ this.sequencer.playbackRate = seqOptions.initialPlaybackRate;
203
204
  // autoplay is ignored
204
205
  try
205
206
  {
@@ -16,7 +16,7 @@ Converted from DLS to SF2 with SpessaSynth`;for(let[i,C]of Object.entries(this.s
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=qo;be.prototype.readDLSInstrument=Vo;be.prototype.readRegion=Wo;be.prototype.readLart=Xo;be.prototype.readDLSSamples=zo;var Cs=class extends Ge{constructor(A,t,n,s,o,r,g,i,C,B,h,c,l){super(A,r,g,i,C,B,s-t/2,o-t/2),this.sampleName=A,this.sampleStartIndex=t,this.sampleEndIndex=n,this.isSampleLoaded=!1,this.sampleID=c,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=h,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex/2,this.sampleLoopEndIndex+=this.sampleStartIndex/2,this.sampleLength=99999999),this.isDataRaw=l}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&&J(`Error decoding sample ${this.sampleName}: Vorbis decode returned undefined.`)}catch(s){J(`Error decoding sample ${this.sampleName}: ${s}`),this.sampleData=new Float32Array(this.sampleLoopEndIndex+1)}}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?(J(`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 J("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 jo(e,A,t=!0){let n=[],s=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let o=xi(s,e.chunkData,A,t);n.push(o),s++}return n.length>1&&n.pop(),n}function xi(e,A,t,n){let s=AA(A,20),o=b(A,4)*2,r=b(A,4)*2,g=b(A,4),i=b(A,4),C=b(A,4),B=A[A.currentIndex++];B===255&&(B=60);let h=fo(A[A.currentIndex++]),c=b(A,2),l=b(A,2);return new Cs(s,o,r,g,i,C,B,h,c,l,t,e,n)}var Es=class extends U{constructor(A){super();let t=A.currentIndex;this.generatorType=A[t+1]<<8|A[t],this.generatorValue=Oe(A[t+2],A[t+3]),A.currentIndex+=4}};function hs(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new Es(e.chunkData));return A.length>1&&A.pop(),A}var cs=class extends OA{constructor(A){super(),this.generatorZoneStartIndex=b(A,2),this.modulatorZoneStartIndex=b(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 $o(e,A,t,n){let s=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new cs(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 Bs=class extends Re{constructor(A){super(),this.generatorZoneStartIndex=b(A,2),this.modulatorZoneStartIndex=b(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 Ar(e,A,t,n){let s=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Bs(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 ls=class extends xe{constructor(A,t){super(t),this.presetName=AA(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=b(A.chunkData,2),this.bank=b(A.chunkData,2),this.presetZoneStartIndex=b(A.chunkData,2),this.library=b(A.chunkData,4),this.genre=b(A.chunkData,4),this.morphology=b(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 er(e,A,t){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let s=new ls(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 Qs=class extends Me{constructor(A){super(),this.instrumentName=AA(A.chunkData,20).trim(),this.instrumentZoneIndex=b(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 tr(e,A){let t=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let n=new Qs(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 ds=class extends X{constructor(A){let t=b(A,2),n=b(A,2),s=Oe(A[A.currentIndex++],A[A.currentIndex++]),o=b(A,2),r=b(A,2);super(t,o,n,s,r)}};function mn(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new ds(e.chunkData));return A}var pn=class extends Ne{constructor(A,t=!0){super(),t&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new N(A),ae("%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),T;switch($.header.toLowerCase()){case"ifil":case"iver":T=`${b($.chunkData,2)}.${b($.chunkData,2)}`,this.soundFontInfo[$.header]=T;break;case"icmt":T=AA($.chunkData,$.chunkData.length,void 0,!1),this.soundFontInfo[$.header]=T;break;case"dmod":let nA=mn($);nA.pop(),T=`Modulators: ${nA.length}`;let cA=this.defaultModulators;this.defaultModulators=nA,this.defaultModulators.push(...cA.filter(oA=>!this.defaultModulators.find(rA=>X.isIdentical(oA,rA)))),this.soundFontInfo[$.header]=$.chunkData;break;default:T=AA($.chunkData,$.chunkData.length),this.soundFontInfo[$.header]=T}p(`%c"${$.header}": %c"${T}"`,I.info,I.recognized)}let g=IA(this.dataArray,!1);this.verifyHeader(g,"list"),this.verifyText(AA(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",I.warn);let i=IA(this.dataArray,!1);this.verifyHeader(i,"smpl");let C;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",I.info);try{C=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: ${$}`)}p(`%cDecoded the smpl chunk! Length: %c${C.length}`,I.info,I.value)}else C=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${g.size-12}`,I.info,I.value),this.dataArray.currentIndex+=g.size-12,p("%cLoading preset data chunk...",I.warn);let B=IA(this.dataArray);this.verifyHeader(B,"list"),AA(B.chunkData,4);let h=IA(B.chunkData);this.verifyHeader(h,"phdr");let c=IA(B.chunkData);this.verifyHeader(c,"pbag");let l=IA(B.chunkData);this.verifyHeader(l,"pmod");let m=IA(B.chunkData);this.verifyHeader(m,"pgen");let f=IA(B.chunkData);this.verifyHeader(f,"inst");let S=IA(B.chunkData);this.verifyHeader(S,"ibag");let F=IA(B.chunkData);this.verifyHeader(F,"imod");let D=IA(B.chunkData);this.verifyHeader(D,"igen");let x=IA(B.chunkData);this.verifyHeader(x,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...jo(x,C,!o));let L=hs(D),G=mn(F),E=$o(S,L,G,this.samples);this.instruments=tr(f,E);let M=hs(m),v=mn(l),eA=Ar(c,M,v,this.instruments);this.presets.push(...er(h,eA,this)),this.presets.sort(($,T)=>$.program-T.program+($.bank-T.bank)),this._parseInternal(),p(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets,
17
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 $e(e){let A=e.slice(8,12),t=new N(A);return AA(t,4,void 0,!1).toLowerCase()==="dls "?new be(e):new pn(e,!1)}function nr(){this.soundfontManager.soundfontList.some(e=>e.id===Xe)&&this.soundfontManager.deleteSoundFont(Xe)}function sr(e,A){this.soundfontBankOffset=A;let t=$e(e);this.soundfontManager.addNewSoundFont(t,Xe,A);let n=this.soundfontManager.getCurrentSoundFontOrder();n.pop(),n.unshift(Xe),this.soundfontManager.rearrangeSoundFonts(n),this._snapshot!==void 0&&this.applySynthesizerSnapshot(this._snapshot),p(`%cEmbedded sound bank set at offset %c${A}`,I.recognized,I.value)}function or(){let e=this.soundfontManager.getPresetList();this.clearCache(),this.callEvent("presetlistchange",e),this.getDefaultPresets(),this.midiAudioChannels.forEach(A=>{A.setPresetLock(!1)}),this.resetAllControllers(!1)}function rr(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 ir(e){e=Math.round(e);for(let A=0;A<this.midiAudioChannels.length;A++)this.midiAudioChannels[A].setCustomController(EA.masterTuning,e)}var Qt=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 At=class e{channelSnapshots;keyMappings;mainVolume;pan;interpolation;system;transposition;static createSynthesizerSnapshot(A){let t=new e;return t.channelSnapshots=A.midiAudioChannels.map((n,s)=>Qt.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(JA.mainVolume,t.mainVolume),A.setMasterParameter(JA.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)=>{Qt.applyChannelSnapshot(A,s,n)}),p("%cFinished restoring controllers!",I.info)}};function ar(e){this._snapshot=e,At.applySnapshot(this,e),p("%cFinished applying snapshot!",I.info),this.resetAllControllers()}function yn(e,A,t){if(t<e)return 0;let n=(t-e)/(1/A)+.25;return Math.abs(n-~~(n+.5))*4-1}var dt=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,C=i+1;for(;C>=n.loopEnd;)C-=r;let B=s-i,h=o[C],c=o[i];t[g]=c+(h-c)*B,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 C=s-g,B=o[i],h=o[g];t[r]=h+(B-h)*C,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,C=i+1,B=C+1,h=B+1,c=s-i;C>=n.loopEnd&&(C-=r),B>=n.loopEnd&&(B-=r),h>=n.loopEnd&&(h-=r);let l=o[i],m=o[C],f=o[B],S=o[h],F=.5*(f-l),D=l-2.5*m+2*f-.5*S,x=.5*(S-l)+1.5*(m-f);t[g]=((x*c+D)*c+F)*c+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,C=i+1,B=C+1,h=s-g;if(i>=n.end||C>=n.end||B>=n.end){A.finished=!0;return}let c=o[g],l=o[i],m=o[C],f=o[B],S=.5*(m-c),F=c-2.5*l+2*m-.5*f,D=.5*(f-c)+1.5*(l-m);t[r]=((D*h+F)*h+S)*h+l,s+=n.playbackStep*A.currentTuningCalculated}}A.sample.cursor=s}};function gr(e,A,t,n,s,o,r,g){if(e.isInRelease||A>=e.releaseStartTime&&(e.isInRelease=!0,Ee.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,C=e.modulatedGenerators[a.fineTune]+this.channelOctaveTuning[e.midiNote]+this.channelTuningCents,B=e.modulatedGenerators[a.coarseTune],h=this.synth.tunings[this.preset.program]?.[e.realKey];if(h!==void 0&&h?.midiNote>=0&&(i=h.midiNote,C+=h.centTuning),e.portamentoFromKey>-1){let v=Math.min((A-e.startTime)/e.portamentoDuration,1),eA=i-e.portamentoFromKey;B-=eA*(1-v)}C+=(i-e.sample.rootKey)*e.modulatedGenerators[a.scaleTuning];let c=0,l=0,m=e.modulatedGenerators[a.vibLfoToPitch],f=e.modulatedGenerators[a.vibLfoToVolume],S=e.modulatedGenerators[a.vibLfoToFilterFc];if(m!==0||f!==0||S!==0){let v=e.startTime+Ce(e.modulatedGenerators[a.delayVibLFO]),eA=Tt(e.modulatedGenerators[a.freqVibLFO]),$=yn(v,eA,A);C+=$*(m*this.customControllers[EA.modulationMultiplier]),l+=-$*f,c+=$*S}let F=e.modulatedGenerators[a.modLfoToPitch],D=e.modulatedGenerators[a.modLfoToVolume],x=e.modulatedGenerators[a.modLfoToFilterFc];if(F!==0||x!==0||D!==0){let v=e.startTime+Ce(e.modulatedGenerators[a.delayModLFO]),eA=Tt(e.modulatedGenerators[a.freqModLFO]),$=yn(v,eA,A);C+=$*(F*this.customControllers[EA.modulationMultiplier]),l+=-$*D,c+=$*x}if(this.channelVibrato.depth>0){let v=yn(e.startTime+this.channelVibrato.delay,this.channelVibrato.rate,A);v&&(C+=v*this.channelVibrato.depth)}let L=e.modulatedGenerators[a.modEnvToPitch],G=e.modulatedGenerators[a.modEnvToFilterFc];if(G!==0||L!==0){let v=he.getValue(e,A);c+=v*G,C+=v*L}let E=~~(C+B*100);E!==e.currentTuningCents&&(e.currentTuningCents=E,e.currentTuningCalculated=Math.pow(2,E/1200));let M=new Float32Array(t.length);switch(this.synth.interpolationType){case _e.fourthOrder:dt.getSampleCubic(e,M);break;case _e.linear:default:dt.getSampleLinear(e,M);break;case _e.nearestNeighbor:dt.getSampleNearest(e,M);break}return Ye.apply(e,M,c,this.synth.filterSmoothingFactor),Ee.apply(e,M,l,this.synth.volumeEnvelopeSmoothingFactor),this.panVoice(e,M,t,n,s,o,r,g),e.finished}function Ir(e,A=-12e3){e+=this.customControllers[EA.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(EA.channelTuning,e),A&&p(`%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 Er(e){e=Math.round(e),p(`%cChannel ${this.channelNumber} modulation depth. Cents: %c${e}`,I.info,I.value),this.setCustomController(EA.modulationMultiplier,e/50)}function hr(e){switch(this.dataEntryState){default:break;case vA.RPCoarse:case vA.RPFine:switch(this.midiControllers[y.RPNMsb]|this.midiControllers[y.RPNLsb]>>7){default:break;case 0:if(e===0)break;this.midiControllers[lA+_.pitchWheelRange]|=e;let t=(this.midiControllers[lA+_.pitchWheelRange]>>7)+e/128;p(`%cChannel ${this.channelNumber} bend range. Semitones: %c${t}`,I.info,I.value);break;case 1:let s=this.customControllers[EA.channelTuning]<<7|e;this.setTuning(s*.01220703125);break;case 5:let r=this.customControllers[EA.modulationMultiplier]*50+e/128*100;this.setModulationDepth(r);break;case 16383:this.resetParameters();break}}}var Ni=1e3/200;function cr(e,A,t){if(A.transformAmount===0)return A.currentValue=0,0;let n;if(A.sourceUsesCC)n=e[A.sourceIndex];else{let C=A.sourceIndex+lA;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[C];break}}let s=et[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][n],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let C=A.secSrcIndex+lA;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[C]}}let r=et[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=A.transformAmount;A.isEffectModulator&&g<=1e3&&(g*=Ni,g=Math.min(g,1e3));let i=s*r*g;return A.transformType===2&&(i=Math.abs(i)),A.currentValue=i,i}function ce(e,A,t=-1,n=0){let s=e.modulators,o=e.generators,r=e.modulatedGenerators;if(t===-1){r.set(o),s.forEach(C=>{let B=Z[C.modulatorDestination],h=r[C.modulatorDestination]+cr(A,C,e);r[C.modulatorDestination]=Math.max(B.min,Math.min(h,B.max))}),Ee.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(C=>{if(C.sourceUsesCC===t&&C.sourceIndex===n||C.secSrcUsesCC===t&&C.secSrcIndex===n){let B=C.modulatorDestination;i.has(B)||(r[B]=o[B],cr(A,C,e),s.forEach(h=>{if(h.modulatorDestination===B){let c=Z[C.modulatorDestination],l=r[C.modulatorDestination]+h.currentValue;r[C.modulatorDestination]=Math.max(c.min,Math.min(l,c.max))}}),i.add(B))}}),[...i].some(C=>g.has(C))&&Ee.recalculate(e),he.recalculate(e)}var et=[];for(let e=0;e<4;e++){et[e]=[[new Float32Array(bA),new Float32Array(bA)],[new Float32Array(bA),new Float32Array(bA)]];for(let A=0;A<bA;A++)et[e][0][0][A]=je(0,e,A/bA,0),et[e][1][0][A]=je(0,e,A/bA,1),et[e][0][1][A]=je(1,e,A/bA,0),et[e][1][1][A]=je(1,e,A/bA,1)}function Br(e,A,t=!1){if(e>127){if(!t)return;switch(e){default:return;case ss.velocityOverride:this.velocityOverride=A}}if(e>=y.lsbForControl1ModulationWheel&&e<=y.lsbForControl13EffectControl2&&e!==y.lsbForControl6DataEntry){let n=e-32;if(this.lockedControllers[n])return;this.midiControllers[n]=this.midiControllers[n]&16256|A&127,this.voices.forEach(s=>ce(s,this.midiControllers,1,n))}if(!this.lockedControllers[e]){switch(this.midiControllers[e]=A<<7,e){case y.allNotesOff:this.stopAllNotes();break;case y.allSoundOff:this.stopAllNotes(!0);break;case y.bankSelect:this.setBankSelect(A);break;case y.lsbForControl0BankSelect:this.setBankSelect(A,!0);break;case y.RPNLsb:this.dataEntryState=vA.RPFine;break;case y.RPNMsb:this.dataEntryState=vA.RPCoarse;break;case y.NRPNMsb:this.dataEntryState=vA.NRPCoarse;break;case y.NRPNLsb:this.dataEntryState=vA.NRPFine;break;case y.dataEntryMsb:this.dataEntryCoarse(A);break;case y.lsbForControl6DataEntry:this.dataEntryFine(A);break;case y.resetAllControllers:this.resetControllersRP15Compliant();break;case y.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=>ce(n,this.midiControllers,1,e));break}this.synth.callEvent("controllerchange",{channel:this.channelNumber,controllerNumber:e,controllerValue:A})}}function lr(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 Qr(e){e&&this.stopAllNotes(!0),this.isMuted=e,this.sendChannelProperty(),this.synth.callEvent("mutechannel",{channel:this.channelNumber,isMuted:e})}function dr(e,A=!1){this.drumChannel||(e+=this.synth.transposition);let t=Math.trunc(e),n=this.channelTransposeKeyShift+this.customControllers[EA.channelTransposeFine]/100;this.drumChannel&&!A||e===n||(t!==this.channelTransposeKeyShift&&this.controllerChange(y.allNotesOff,127),this.channelTransposeKeyShift=t,this.setCustomController(EA.channelTransposeFine,(e-t)*100),this.sendChannelProperty())}var Jt={pitchBendRange:0,fineTuning:1,coarseTuning:2,modulationDepth:5,resetParameters:16383},bi={partParameter:1},ft={vibratoRate:8,vibratoDepth:9,vibratoDelay:10,TVFFilterCutoff:32,TVFFilterResonance:33,EGAttackTime:99,EGReleaseTime:102};function fr(e){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),p(`%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 vA.Idle:break;case vA.NRPFine:if(this.lockGSNRPNParams)return;let n=this.midiControllers[y.NRPNMsb]>>7,s=this.midiControllers[y.NRPNLsb]>>7;switch(n){default:if(e===64)return;J(`%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 bi.partParameter:switch(s){default:if(e===64)return;J(`%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 ft.vibratoRate:if(e===64)return;A(),this.channelVibrato.rate=e/64*8,t("Vibrato rate",`${e} = ${this.channelVibrato.rate}`,"Hz");break;case ft.vibratoDepth:if(e===64)return;A(),this.channelVibrato.depth=e/2,t("Vibrato depth",`${e} = ${this.channelVibrato.depth}`,"cents of detune");break;case ft.vibratoDelay:if(e===64)return;A(),this.channelVibrato.delay=e/64/3,t("Vibrato delay",`${e} = ${this.channelVibrato.delay}`,"seconds");break;case ft.TVFFilterCutoff:this.controllerChange(y.brightness,e),t("Filter cutoff",e.toString(),"");break;case ft.EGAttackTime:this.controllerChange(y.attackTime,e),t("EG attack time",e.toString(),"");break;case ft.EGReleaseTime:this.controllerChange(y.releaseTime,e),t("EG release time",e.toString(),"");break}break}break;case vA.RPCoarse:case vA.RPFine:let o=this.midiControllers[y.RPNMsb]|this.midiControllers[y.RPNLsb]>>7;switch(o){default:J(`%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 Jt.pitchBendRange:this.midiControllers[lA+_.pitchWheelRange]=e<<7,t("Pitch bend range",e.toString(),"semitones");break;case Jt.coarseTuning:let r=e-64;this.setCustomController(EA.channelTuningSemitones,r),t("Coarse tuning",r.toString(),"semitones");break;case Jt.fineTuning:this.setTuning(e-64,!1);break;case Jt.modulationDepth:this.setModulationDepth(e*100);break;case Jt.resetParameters:this.resetParameters();break}}}var Ot={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 Li(e){if(Ot[e]!==void 0)return Ot[e];let A=null,t=null;for(let n of Object.keys(Ot))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=Ot[A],s=Ot[t];return n+(e-A)*(s-n)/(t-A)}return 0}function ur(e,A){return Li(e)*(A/30)}function mr(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[EA.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,C=0,B=this.midiControllers[y.portamentoTime]>>7,h=this.midiControllers[y.portamentoControl],c=h>>7;if(!this.drumChannel&&c!==n&&this.midiControllers[y.portamentoOnOff]>=8192&&B>0){if(h!==1){let F=Math.abs(n-c);C=ur(B,F),i=c}this.controllerChange(y.portamentoControl,n)}let l=this.synth.getVoices(this.channelNumber,n,A,t),m=0;this.randomPan&&(m=Math.round(Math.random()*1e3-500));let f=this.sysExModulators.getModulators(),S=this.voices;l.forEach(F=>{F.portamentoFromKey=i,F.portamentoDuration=C,F.overridePan=m,F.gain=g,f.forEach(eA=>{let $=F.modulators.findIndex(T=>X.isIdentical(T,eA));$!==-1?F.modulators[$]=X.copy(eA):F.modulators.push(X.copy(eA))});let D=F.exclusiveClass;D!==0&&S.forEach(eA=>{eA.exclusiveClass===D&&eA.exclusiveRelease(this.synth.currentSynthTime)}),ce(F,this.midiControllers);let x=F.modulatedGenerators[a.startAddrsOffset]+F.modulatedGenerators[a.startAddrsCoarseOffset]*32768,L=F.modulatedGenerators[a.endAddrOffset]+F.modulatedGenerators[a.endAddrsCoarseOffset]*32768,G=F.modulatedGenerators[a.startloopAddrsOffset]+F.modulatedGenerators[a.startloopAddrsCoarseOffset]*32768,E=F.modulatedGenerators[a.endloopAddrsOffset]+F.modulatedGenerators[a.endloopAddrsCoarseOffset]*32768,M=F.sample,v=eA=>Math.max(0,Math.min(M.sampleData.length-1,eA));if(M.cursor=v(M.cursor+x),M.end=v(M.end+L),M.loopStart=v(M.loopStart+G),M.loopEnd=v(M.loopEnd+E),M.loopEnd<M.loopStart){let eA=M.loopStart;M.loopStart=M.loopEnd,M.loopEnd=eA}M.loopEnd-M.loopStart<1&&(M.loopingMode=0,M.isLooping=!1),F.volumeEnvelope.attenuation=F.volumeEnvelope.attenuationTargetGain,F.currentPan=Math.max(-500,Math.min(500,F.modulatedGenerators[a.pan]))}),this.synth.totalVoicesAmount+=l.length,this.synth.totalVoicesAmount>this.synth.voiceCap&&this.synth.voiceKilling(l.length),S.push(...l),this.sendChannelProperty(),this.synth.callEvent("noteon",{midiNote:e,channel:this.channelNumber,velocity:A})}function pr(e){if(e>127||e<0){J("Received a noteOn for note",e,"Ignoring.");return}let A=e+this.channelTransposeKeyShift+this.customControllers[EA.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 yr(e,A){this.voices.forEach(t=>{t.midiNote===e&&(t.pressure=A,ce(t,this.midiControllers,0,_.polyPressure))}),this.synth.callEvent("polypressure",{channel:this.channelNumber,midiNote:e,pressure:A})}function Sr(e){this.midiControllers[lA+_.channelPressure]=e<<7,this.updateChannelTuning(),this.voices.forEach(A=>ce(A,this.midiControllers,0,_.channelPressure)),this.synth.callEvent("channelpressure",{channel:this.channelNumber,pressure:e})}function Dr(e,A){if(this.lockedControllers[lA+_.pitchWheel])return;let t=A|e<<7;this.synth.callEvent("pitchwheel",{channel:this.channelNumber,MSB:e,LSB:A}),this.midiControllers[lA+_.pitchWheel]=t,this.voices.forEach(n=>ce(n,this.midiControllers,0,_.pitchWheel)),this.sendChannelProperty()}function kr(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 Fr(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 Sn=class{modulatorList=[];resetModulators(){this.modulatorList=[]}getModulators(){return this.modulatorList.map(A=>A.mod)}_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,C;A>=lA?(i=A-lA,C=!1):(i=A,C=!0);let B=new X(ZA(FA.linear,s,0,C,i),0,t,n,0);this.modulatorList.push({mod:B,id:r})}}};var DA=class{midiControllers=new Int16Array(rn);lockedControllers=Array(rn).fill(!1);customControllers=new Float32Array(ts);channelTransposeKeyShift=0;channelOctaveTuning=new Int8Array(128);channelTuningCents=0;sysExModulators=new Sn;holdPedal=!1;drumChannel=!1;velocityOverride=0;randomPan=!1;dataEntryState=vA.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}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[EA.channelTuning]+this.customControllers[EA.channelTransposeFine]+this.customControllers[EA.masterTuning]+this.customControllers[EA.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,ct(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[lA+_.pitchWheel],pitchBendRangeSemitones:this.midiControllers[lA+_.pitchWheelRange]/128,isMuted:this.isMuted,isDrum:this.drumChannel,transposition:this.channelTransposeKeyShift+this.customControllers[EA.channelTransposeFine]/100,bank:this.sentBank,program:this.preset.program};this.synth?.onChannelPropertyChange?.(A,this.channelNumber)}};DA.prototype.renderVoice=gr;DA.prototype.panVoice=lo;DA.prototype.killNote=Ir;DA.prototype.stopAllNotes=lr;DA.prototype.muteChannel=Qr;DA.prototype.noteOn=mr;DA.prototype.noteOff=pr;DA.prototype.polyPressure=yr;DA.prototype.channelPressure=Sr;DA.prototype.pitchWheel=Dr;DA.prototype.programChange=Fr;DA.prototype.setTuning=Cr;DA.prototype.setOctaveTuning=kr;DA.prototype.setModulationDepth=Er;DA.prototype.transposeChannel=dr;DA.prototype.controllerChange=Br;DA.prototype.resetControllers=no;DA.prototype.resetControllersRP15Compliant=so;DA.prototype.resetParameters=oo;DA.prototype.dataEntryFine=hr;DA.prototype.dataEntryCoarse=fr;function wr(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 fs={enableEventSystem:!0,initialTime:0,effectsEnabled:!0,midiChannels:16};function Rr(e,A){e===void 0&&(e={});for(let t in A)A.hasOwnProperty(t)&&!(t in e)&&(e[t]=A[t]);return e}var go=.03,Io=.07,$n=1,LA=class{cachedVoices=[];deviceID=-1;eventQueue=[];interpolationType=_e.fourthOrder;transposition=0;tunings=[];soundfontBankOffset=0;masterGain=$n;midiVolume=1;reverbGain=1;chorusGain=1;reverbSend=1;chorusSend=1;voiceCap=350;pan=0;panLeft=.5;panRight=.5;highPerformanceMode=!1;keyModifierManager=new gn;midiAudioChannels=[];system=Lt;totalVoicesAmount=0;defaultPreset;drumPreset;processorInitialized=me.isInitialized;currentSynthTime=0;sampleRate;sampleTime;effectsEnabled;_snapshot;onEventCall;onChannelPropertyChange;onMasterParameterChange;constructor(A,t=fs){t=Rr(t,fs),this.midiOutputsCount=t.midiChannels,this.effectsEnabled=t.effectsEnabled,this.enableEventSystem=t.enableEventSystem,this.currentSynthTime=t.midiChannels,this.sampleTime=1/A,this.sampleRate=A,this.volumeEnvelopeSmoothingFactor=Zs*(44100/A),this.panSmoothingFactor=Eo*(44100/A),this.filterSmoothingFactor=ro*(44100/A);for(let n=0;n<128;n++)this.tunings.push([]);this.soundfontManager=new lt(this.updatePresetList.bind(this));for(let n=0;n<this.midiOutputsCount;n++)this.createMidiChannel(!1);this.processorInitialized.then(()=>{p("%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?.(JA.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((C,B)=>{if(C.voices.length<1||C.isMuted)return;let h=C.voices.length,c=B%16;C.renderAudio(n[c][0],n[c][1],o,r,g,i),this.totalVoicesAmount+=C.voices.length,C.voices.length!==h&&C.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,n,s){let o=()=>{let g=ht(A[0]),i=g.channel+t;switch(g.status){case w.noteOn:let C=A[2];C>0?this.noteOn(i,A[1],C):this.noteOff(i,A[1]);break;case w.noteOff:n?this.midiAudioChannels[i].killNote(A[1]):this.noteOff(i,A[1]);break;case w.pitchBend:this.pitchWheel(i,A[2],A[1]);break;case w.controllerChange:this.controllerChange(i,A[1],A[2],n);break;case w.programChange:this.programChange(i,A[1]);break;case w.polyPressure:this.polyPressure(i,A[0],A[1]);break;case w.channelPressure:this.channelPressure(i,A[1]);break;case w.systemExclusive:this.systemExclusive(new N(A.slice(1)),t);break;case w.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(JA.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=Js;LA.prototype.getVoicesForPreset=io;LA.prototype.getVoices=ao;LA.prototype.systemExclusive=eo;LA.prototype.stopAllChannels=Qo;LA.prototype.createMidiChannel=wr;LA.prototype.resetAllControllers=to;LA.prototype.setMasterParameter=js;LA.prototype.transposeAllChannels=rr;LA.prototype.setMasterTuning=ir;LA.prototype.clearEmbeddedBank=nr;LA.prototype.setEmbeddedSoundFont=sr;LA.prototype.updatePresetList=or;LA.prototype.applySynthesizerSnapshot=ar;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 Mr(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 w.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 w.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 w.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case w.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 w.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[A].size===0)return;this.synth.programChange(t.channel,e.messageData[0]);break;case w.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case w.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case w.systemExclusive:this.synth.systemExclusive(e.messageData,n);break;case w.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),J("invalid tempo! falling back to 120 BPM"),r=120);break;case w.timeSignature:case w.endOfTrack:case w.midiChannelPrefix:case w.songPosition:case w.activeSensing:case w.keySignature:case w.sequenceNumber:case w.sequenceSpecific:case w.text:case w.lyric:case w.copyright:case w.trackName:case w.marker:case w.cuePoint:case w.instrumentName:case w.programName:break;case w.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case w.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:J(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(w).find(g=>w[g]===t.status)}`,I.warn,I.unrecognized,I.warn,I.value);break}t.status>=0&&t.status<128&&this?.onMetaEvent?.(e,A)}function xr(){for(let e=0;e<16;e++)this.synth.createMidiChannel(!0)}function Nr(){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 br(){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 tt=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 Dn(e){let A=[e&127];for(e>>=7;e>0;)A.unshift(e&127|128),e>>=7;return A}function Lr(){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 C=i.ticks-r,B;i.messageStatusByte<=w.sequenceSpecific?B=[255,i.messageStatusByte,...Dn(i.messageData.length),...i.messageData]:i.messageStatusByte===w.systemExclusive?B=[240,...Dn(i.messageData.length),...i.messageData]:(B=[],g!==i.messageStatusByte&&(g=i.messageStatusByte,B.push(i.messageStatusByte)),B.push(...i.messageData)),o.push(...Dn(C)),o.push(...B),r+=C}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 ut(e){return e.messageData[0]===67&&e.messageData[2]===76&&e.messageData[5]===126&&e.messageData[6]===0}function kn(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 Fn(e){return e.messageData[0]===65&&e.messageData[2]===66&&e.messageData[6]===127}function wn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===1}function Rn(e){return e.messageData[0]===126&&e.messageData[2]===9&&e.messageData[3]===3}function us(e){return new YA(e,w.systemExclusive,new N([65,16,66,18,64,0,127,0,65,247]))}function mt(e,A,t,n){return new YA(n,w.controllerChange|e%16,new N([A,t]))}function Ti(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,w.systemExclusive,new N([...n,o,247]))}function Tr(e=[],A=[],t=[],n=[]){let s=this;uA("%cApplying changes to the MIDI file...",I.info),p("Desired program changes:",e),p("Desired CC changes:",A),p("Desired channels to clear:",t),p("Desired channels to transpose:",n);let o=new Set;e.forEach(x=>{o.add(x.channel)});let r="gs",g=!1,i=Array(s.tracks.length).fill(0),C=s.tracks.length;function B(){let x=0,L=1/0;return s.tracks.forEach((G,E)=>{i[E]>=G.length||G[i[E]].ticks<L&&(x=E,L=G[i[E]].ticks)}),x}let h=s.midiPorts.slice(),c={},l=0;function m(x,L){s.usedChannelsOnTrack[x].size!==0&&(l===0&&(l+=16,c[L]=0),c[L]===void 0&&(c[L]=l,l+=16),h[x]=L)}s.midiPorts.forEach((x,L)=>{m(L,x)});let f=l,S=Array(f).fill(!0),F=Array(f).fill(0),D=Array(f).fill(0);for(n.forEach(x=>{let L=Math.trunc(x.keyShift),G=x.keyShift-L;F[x.channel]=L,D[x.channel]=G});C>0;){let x=B(),L=s.tracks[x];if(i[x]>=L.length){C--;continue}let G=i[x]++,E=L[G],M=()=>{L.splice(G,1),i[x]--},v=(cA,oA=0)=>{L.splice(G+oA,0,cA),i[x]++},eA=c[h[x]]||0;if(E.messageStatusByte===w.midiPort){m(x,E.messageData[0]);continue}if(E.messageStatusByte<=w.sequenceSpecific&&E.messageStatusByte>=w.sequenceNumber)continue;let $=E.messageStatusByte&240,T=E.messageStatusByte&15,nA=T+eA;if(t.indexOf(nA)!==-1){M();continue}switch($){case w.noteOn:if(S[nA]){S[nA]=!1,A.filter(hA=>hA.channel===nA).forEach(hA=>{let H=mt(T,hA.controllerNumber,hA.controllerValue,E.ticks);v(H)});let rA=D[nA];if(rA!==0){let hA=rA*64+64,H=mt(T,y.RPNMsb,0,E.ticks),O=mt(T,y.RPNLsb,1,E.ticks),z=mt(nA,y.dataEntryMsb,hA,E.ticks),V=mt(T,y.lsbForControl6DataEntry,0,E.ticks);v(V),v(z),v(O),v(H)}if(o.has(nA)){let hA=e.find(iA=>iA.channel===nA),H=Math.max(0,Math.min(hA.bank,127)),O=hA.program;p(`%cSetting %c${hA.channel}%c to %c${H}:${O}%c. Track num: %c${x}`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized);let z=new YA(E.ticks,w.programChange|T,new N([O]));v(z);let V=(iA,qA)=>{let Ie=mt(T,iA?y.lsbForControl0BankSelect:y.bankSelect,qA,E.ticks);v(Ie)};GA(r)?hA.isDrum?(p(`%cAdding XG Drum change on track %c${x}`,I.recognized,I.value),V(!1,Ae(H)?H:127),V(!0,0)):H===on?(V(!1,on),V(!0,0)):(V(!1,0),V(!0,H)):(V(!1,H),hA.isDrum&&T!==9&&(p(`%cAdding GS Drum change on track %c${x}`,I.recognized,I.value),v(Ti(T,E.ticks))))}}E.messageData[0]+=F[nA];break;case w.noteOff:E.messageData[0]+=F[nA];break;case w.programChange:if(o.has(nA)){M();continue}break;case w.controllerChange:let cA=E.messageData[0];if(A.find(rA=>rA.channel===nA&&cA===rA.controllerNumber)!==void 0){M();continue}if((cA===y.bankSelect||cA===y.lsbForControl0BankSelect)&&o.has(nA)){M();continue}break;case w.systemExclusive:if(ut(E))p("%cXG system on detected",I.info),r="xg",g=!0;else if(E.messageData[0]===67&&E.messageData[2]===76&&E.messageData[3]===8&&E.messageData[5]===3)o.has(E.messageData[4]+eA)&&M();else if(Fn(E)){g=!0,p("%cGS on detected!",I.recognized);break}else(wn(E)||Rn(E))&&(p("%cGM/2 on detected, removing!",I.info),M(),g=!1)}}if(!g&&e.length>0){let x=0;s.tracks[0][0].messageStatusByte===w.trackName&&x++,s.tracks[0].splice(x,0,us(0)),p("%cGS on not detected. Adding it.",I.info)}this.flush(),q()}function Ur(e){let A=[],t=[],n=[],s=[];e.channelSnapshots.forEach((o,r)=>{if(o.isMuted){t.push(r);return}let g=o.channelTransposeKeyShift+o.customControllers[EA.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,C)=>{if(!i||C>127||C===y.bankSelect)return;let B=o.midiControllers[C]>>7;s.push({channel:r,controllerNumber:C,controllerValue:B})})}),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"},Ke="utf-8",Ui="Created using SpessaSynth";function vr(e,A,t=0,n="Shift_JIS",s={},o=!0){let r=this;if(ae("%cWriting the RMIDI File...",I.info),p(`%cConfiguration: Bank offset: %c${t}%c, encoding: %c${n}`,I.info,I.value,I.info,I.value),p("metadata",s),p("Initial bank offset",r.bankOffset),o){let F=function(){let G=0,E=1/0;return r.tracks.forEach((M,v)=>{f[v]>=M.length||M[f[v]].ticks<E&&(G=v,E=M[f[v]].ticks)}),G},l="gm",m=[],f=Array(r.tracks.length).fill(0),S=r.tracks.length,D=Array(r.tracks.length).fill(0),x=16+r.midiPortChannelOffsets.reduce((G,E)=>E>G?E:G),L=[];for(let G=0;G<x;G++)L.push({program:0,drums:G%16===9,lastBank:void 0,lastBankLSB:void 0,hasBankSelect:!1});for(;S>0;){let G=F(),E=r.tracks[G];if(f[G]>=E.length){S--;continue}let M=E[f[G]];f[G]++;let v=r.midiPortChannelOffsets[D[G]];if(M.messageStatusByte===w.midiPort){D[G]=M.messageData[0];continue}let eA=M.messageStatusByte&240;if(eA!==w.controllerChange&&eA!==w.programChange&&eA!==w.systemExclusive)continue;if(eA===w.systemExclusive){if(!kn(M)){ut(M)?l="xg":Fn(M)?l="gs":wn(M)?(l="gm",m.push({tNum:G,e:M})):Rn(M)&&(l="gm2");continue}let rA=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][M.messageData[5]&15]+v;L[rA].drums=!!(M.messageData[7]>0&&M.messageData[5]>>4);continue}let $=(M.messageStatusByte&15)+v,T=L[$];if(eA===w.programChange){let rA=GA(l),hA=M.messageData[0];T.drums?A.presets.findIndex(V=>V.program===hA&&V.isDrumPreset(rA,!0))===-1&&(M.messageData[0]=A.presets.find(V=>V.isDrumPreset(rA))?.program||0,p(`%cNo drum preset %c${hA}%c. Channel %c${$}%c. Changing program to ${M.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)):A.presets.findIndex(V=>V.program===hA&&!V.isDrumPreset(rA))===-1&&(M.messageData[0]=A.presets.find(V=>!V.isDrumPreset(rA))?.program||0,p(`%cNo preset %c${hA}%c. Channel %c${$}%c. Changing program to ${M.messageData[0]}.`,I.info,I.unrecognized,I.info,I.recognized,I.info)),T.program=M.messageData[0];let H=Math.max(0,T.lastBank?.messageData[1]-r.bankOffset),O=T?.lastBankLSB?.messageData[1]-r.bankOffset||0;if(T.lastBank===void 0)continue;let z=Bt(H,O,T.drums,rA);if(A.presets.findIndex(V=>V.bank===z&&V.program===M.messageData[0])===-1){let V=A.presets.find(iA=>iA.program===M.messageData[0])?.bank+t||t;T.lastBank.messageData[1]=V,T?.lastBankLSB?.messageData&&(T.lastBankLSB.messageData[1]=V),p(`%cNo preset %c${z}:${M.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(l)&&z===128&&(z=127);let iA=(z===128?128:V)+t;T.lastBank.messageData[1]=iA,T?.lastBankLSB?.messageData&&!T.drums&&(T.lastBankLSB.messageData[1]=T.lastBankLSB.messageData[1]-r.bankOffset+t),p(`%cPreset %c${z}:${M.messageData[0]}%c exists. Channel %c${$}%c. Changing bank to ${iA}.`,I.info,I.recognized,I.info,I.recognized,I.info)}continue}let nA=M.messageData[0]===y.lsbForControl0BankSelect;if(M.messageData[0]!==y.bankSelect&&!nA)continue;T.hasBankSelect=!0;let cA=M.messageData[1],oA=ct(T?.lastBank?.messageData[1]||0,cA,l,nA,T.drums,$);oA.drumsStatus===2?T.drums=!0:oA.drumsStatus===1&&(T.drums=!1),nA?T.lastBankLSB=M:T.lastBank=M}if(L.forEach((G,E)=>{if(G.hasBankSelect===!0)return;let M=E%16,v=w.programChange|M,eA=Math.floor(E/16)*16,$=r.midiPortChannelOffsets.indexOf(eA),T=r.tracks.find((rA,hA)=>r.midiPorts[hA]===$&&r.usedChannelsOnTrack[hA].has(M));if(T===void 0)return;let nA=T.findIndex(rA=>rA.messageStatusByte===v);if(nA===-1){let rA=T.findIndex(O=>O.messageStatusByte>128&&O.messageStatusByte<240&&(O.messageStatusByte&15)===M);if(rA===-1)return;let hA=T[rA].ticks,H=A.getPreset(0,0).program;T.splice(rA,0,new YA(hA,w.programChange|M,new N([H]))),nA=rA}p(`%cAdding bank select for %c${E}`,I.info,I.recognized);let cA=T[nA].ticks,oA=A.getPreset(0,G.program,GA(l))?.bank+t||t;T.splice(nA,0,new YA(cA,w.controllerChange|M,new N([y.bankSelect,oA])))}),l!=="gs"&&!GA(l)){for(let E of m)r.tracks[E.tNum].splice(r.tracks[E.tNum].indexOf(E.e),1);let G=0;r.tracks[0][0].messageStatusByte===w.trackName&&G++,r.tracks[0].splice(G,0,us(0))}}let g=new N(r.writeMIDI().buffer),i=[We("INFO")],C=new TextEncoder;if(i.push(j(pA.software,C.encode("SpessaSynth"),!0)),s.name!==void 0?(i.push(j(pA.name,C.encode(s.name),!0)),n=Ke):i.push(j(pA.name,r.rawMidiName,!0)),s.creationDate!==void 0)n=Ke,i.push(j(pA.creationDate,C.encode(s.creationDate),!0));else{let l=new Date().toLocaleString(void 0,{weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"numeric"});i.push(j(pA.creationDate,pe(l),!0))}if(s.comment!==void 0&&(n=Ke,i.push(j(pA.comment,C.encode(s.comment)))),s.engineer!==void 0&&i.push(j(pA.engineer,C.encode(s.engineer),!0)),s.album!==void 0&&(n=Ke,i.push(j(pA.album,C.encode(s.album),!0)),i.push(j(pA.album2,C.encode(s.album),!0))),s.artist!==void 0&&(n=Ke,i.push(j(pA.artist,C.encode(s.artist),!0))),s.genre!==void 0&&(n=Ke,i.push(j(pA.genre,C.encode(s.genre),!0))),s.picture!==void 0&&i.push(j(pA.picture,new Uint8Array(s.picture))),s.copyright!==void 0)n=Ke,i.push(j(pA.copyright,C.encode(s.copyright),!0));else{let l=r.copyright.length>0?r.copyright:Ui;i.push(j(pA.copyright,pe(l)))}let B=new N(2);Je(B,t,2),i.push(j(pA.bankOffset,B)),s.midiEncoding!==void 0&&(i.push(j(pA.midiEncoding,C.encode(s.midiEncoding))),n=Ke),i.push(j(pA.encoding,pe(n)));let h=kA(i),c=kA([We("RMID"),j("data",g),j("LIST",h),e]);return p("%cFinished!",I.info),q(),j("RIFF",c)}function Hr(e){let A=this;uA("%cSearching for all used programs and keys...",I.info);let t=16+A.midiPortChannelOffsets.reduce((h,c)=>c>h?c:h),n=[];for(let h=0;h<t;h++){let c=h%16===9?128:0;n.push({program:0,bank:c,bankLSB:0,actualBank:c,drums:h%16===9,string:`${c}:0`})}let s="gs";function o(h){let c=Bt(h.bank,h.bankLSB,h.drums,GA(s)),l,m;if(e instanceof lt){let f=e.getPreset(c,h.program,GA(s));l=f.preset.bank+f.bankOffset,m=f.preset.program}else{let f=e.getPreset(c,h.program,GA(s));l=f.bank,m=f.program}h.actualBank=l,h.program=m,h.string=h.actualBank+":"+h.program,r[h.string]||(p(`%cDetected a new preset: %c${h.string}`,I.info,I.recognized),r[h.string]=new Set)}let r={},g=Array(A.tracks.length).fill(0),i=A.tracks.length;function C(){let h=0,c=1/0;return A.tracks.forEach((l,m)=>{g[m]>=l.length||l[g[m]].ticks<c&&(h=m,c=l[g[m]].ticks)}),h}let B=A.midiPorts.slice();for(n.forEach(h=>{o(h)});i>0;){let h=C(),c=A.tracks[h];if(g[h]>=c.length){i--;continue}let l=c[g[h]];if(g[h]++,l.messageStatusByte===w.midiPort){B[h]=l.messageData[0];continue}let m=l.messageStatusByte&240;if(m!==w.noteOn&&m!==w.controllerChange&&m!==w.programChange&&m!==w.systemExclusive)continue;let f=(l.messageStatusByte&15)+A.midiPortChannelOffsets[B[h]]||0,S=n[f];switch(m){case w.programChange:S.program=l.messageData[0],o(S);break;case w.controllerChange:let F=l.messageData[0]===y.lsbForControl0BankSelect;if(l.messageData[0]!==y.bankSelect&&!F||s==="gs"&&S.drums)continue;let D=l.messageData[1];switch(F?S.bankLSB=D:S.bank=D,ct(S.bank,D,s,F,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 w.noteOn:if(l.messageData[1]===0)continue;r[S.string].add(`${l.messageData[0]}-${l.messageData[1]}`);break;case w.systemExclusive:if(!kn(l)){ut(l)&&(s="xg",p("%cXG on detected!",I.recognized));continue}let L=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][l.messageData[5]&15]+A.midiPortChannelOffsets[B[h]],G=!!(l.messageData[7]>0&&l.messageData[5]>>4);S=n[L],S.drums=G,o(S);break}}for(let h of Object.keys(r))r[h].size===0&&(p(`%cDetected change but no keys for %c${h}`,I.info,I.value),delete r[h]);return q(),r}function Yr(e=0){function A(h){return h.messageData=new N(h.messageData.buffer),h.messageData.currentIndex=0,6e7/KA(h.messageData,3)}let t=[],s=this.tracks.flat();s.sort((h,c)=>h.ticks-c.ticks);for(let h=0;h<16;h++)t.push([]);let o=0,r=60/(120*this.timeDivision),g=0,i=0,C=[];for(let h=0;h<16;h++)C.push([]);let B=(h,c)=>{let l=C[c].findIndex(f=>f.midiNote===h),m=C[c][l];if(m){let f=o-m.start;m.length=f,c===9&&(m.length=f<e?e:f),C[c].splice(l,1)}i--};for(;g<s.length;){let h=s[g],c=h.messageStatusByte>>4,l=h.messageStatusByte&15;if(c===8)B(h.messageData[0],l);else if(c===9)if(h.messageData[1]===0)B(h.messageData[0],l);else{B(h.messageData[0],l);let m={midiNote:h.messageData[0],start:o,length:-1,velocity:h.messageData[1]/127};t[l].push(m),C[l].push(m),i++}else h.messageStatusByte===81&&(r=60/(A(h)*this.timeDivision));if(++g>=s.length)break;o+=r*(s[g].ticks-h.ticks)}return i>0&&C.forEach((h,c)=>{h.forEach(l=>{let m=o-l.start;l.length=m,c===9&&(l.length=m<e?e:m)})}),t}var WA=class e extends tt{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(){ae("%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 B=0;B<this.tracks.length;B++){let h=this.tracks[B],c=new Set,l=!1;for(let f of h){if(f.messageStatusByte>=128&&f.messageStatusByte<240){l=!0;for(let F=0;F<f.messageData.length;F++)f.messageData[F]=Math.min(127,f.messageData[F]);switch(f.ticks>this.lastVoiceEventTick&&(this.lastVoiceEventTick=f.ticks),f.messageStatusByte&240){case w.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&&(p("%cDLS RMIDI with offset 1 detected!",I.recognized),this.bankOffset=1)}break;case w.noteOn:c.add(f.messageStatusByte&15);let F=f.messageData[0];this.keyRange.min=Math.min(this.keyRange.min,F),this.keyRange.max=Math.max(this.keyRange.max,F);break}}f.messageData.currentIndex=0;let S=AA(f.messageData,f.messageData.length);switch(f.messageData.currentIndex=0,f.messageStatusByte){case w.setTempo:f.messageData.currentIndex=0,this.tempoChanges.push({ticks:f.ticks,tempo:6e7/KA(f.messageData,3)}),f.messageData.currentIndex=0;break;case w.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 w.copyright:n||(f.messageData.currentIndex=0,t.push(AA(f.messageData,f.messageData.length,void 0,!1)),f.messageData.currentIndex=0);break;case w.lyric:if(S.trim().startsWith("@KMIDI KARAOKE FILE")&&(this.isKaraokeFile=!0,p("%cKaraoke MIDI detected!",I.recognized)),this.isKaraokeFile)f.messageStatusByte=w.text;else{this.lyrics.push(f.messageData),this.lyricsTicks.push(f.ticks);break}case w.text:let D=S.trim();D.startsWith("@KMIDI KARAOKE FILE")?(this.isKaraokeFile=!0,p("%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=We(this.midiName)):D[0]!=="@"&&(this.lyrics.push(Ys(f.messageData)),this.lyricsTicks.push(f.ticks)));break;case w.trackName:break}}this.usedChannelsOnTrack.push(c),this.trackNames[B]="";let m=h.find(f=>f.messageStatusByte===w.trackName);if(m){m.messageData.currentIndex=0;let f=AA(m.messageData,m.messageData.length);this.trackNames[B]=f,l||t.push(f)}}this.tempoChanges.reverse(),p("%cCorrecting loops, ports and detecting notes...",I.info);let g=[];for(let B of this.tracks){let h=B.find(c=>(c.messageStatusByte&240)===w.noteOn);h&&g.push(h.ticks)}this.firstNoteOn=Math.min(...g),p(`%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},p(`%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 B=0;B<this.tracks.length;B++)if(this.midiPorts.push(-1),this.usedChannelsOnTrack[B].size!==0)for(let h of this.tracks[B]){if(h.messageStatusByte!==w.midiPort)continue;let c=h.messageData[0];this.midiPorts[B]=c,this.midiPortChannelOffsets[c]===void 0&&(this.midiPortChannelOffsets[c]=i,i+=16)}this.midiPortChannelOffsets=[...this.midiPortChannelOffsets].map(B=>B??0);let C=1/0;for(let B of this.midiPorts)B!==-1&&C>B&&(C=B);if(C===1/0&&(C=0),this.midiPorts=this.midiPorts.map(B=>B===-1||B===void 0?C:B),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.midiPortChannelOffsets.length<2?p("%cNo additional MIDI Ports detected.",I.info):(this.isMultiPort=!0,p("%cMIDI Ports detected!",I.recognized)),!s)if(this.tracks.length>1){if(this.tracks[0].find(B=>B.messageStatusByte>=w.noteOn&&B.messageStatusByte<w.polyPressure)===void 0){let B=this.tracks[0].find(h=>h.messageStatusByte===w.trackName);B&&(this.rawMidiName=B.messageData,B.messageData.currentIndex=0,this.midiName=AA(B.messageData,B.messageData.length,void 0,!1))}}else{let B=this.tracks[0].find(h=>h.messageStatusByte===w.trackName);B&&(this.rawMidiName=B.messageData,B.messageData.currentIndex=0,this.midiName=AA(B.messageData,B.messageData.length,void 0,!1))}if(n||(this.copyright=t.map(B=>B.trim().replace(/(\r?\n)+/g,`
18
18
  `)).filter(B=>B.length>0).join(`
19
- `)||""),this.midiName=this.midiName.trim(),this.midiNameUsesFileName=!1,this.midiName.length===0){p("%cNo name detected. Using the alt name!",I.info),this.midiName=Hs(this.fileName),this.midiNameUsesFileName=!0,this.rawMidiName=new Uint8Array(this.midiName.length);for(let B=0;B<this.midiName.length;B++)this.rawMidiName[B]=this.midiName.charCodeAt(B)}else p(`%cMIDI Name detected! %c"${this.midiName}"`,I.info,I.recognized);this.tracks.some(B=>B[0].ticks===0)||this.tracks[0].unshift(new YA(0,w.trackName,new N(this.rawMidiName.buffer))),this.duration=this.MIDIticksToSeconds(this.lastVoiceEventTick),p("%cSuccess!",I.recognized),q()}flush(){for(let A of this.tracks)A.sort((t,n)=>t.ticks-n.ticks);this._parseInternal()}};WA.prototype.writeMIDI=Lr;WA.prototype.modifyMIDI=Tr;WA.prototype.applySnapshotToMIDI=Ur;WA.prototype.writeRMIDI=vr;WA.prototype.getUsedProgramsAndKeys=Hr;WA.prototype.getNoteTimes=Yr;function Jr(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 Or(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&&(p("%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);p(`%cPreloading used samples on %c${g.presetName}%c...`,I.info,I.recognized,I.info);for(let i of s){let[C,B]=i.split("-").map(Number);this.synth.getVoicesForPreset(g,o,r,C,B,C)}}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),p(`%cTotal song time: ${Zn(Math.ceil(this.duration)).time}`,I.recognized),this?.onSongChange?.(this.songIndex,A),this.duration<=1&&(J(`%cVery short song: (${Zn(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 Kr(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 qr(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadCurrentSong()}function Vr(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadCurrentSong()}var nt=He.slice(0,128);function Pr(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===y.dataDecrement||i===y.dataIncrement||i===y.dataEntryMsb||i===y.dataDecrement||i===y.lsbForControl6DataEntry||i===y.RPNLsb||i===y.RPNMsb||i===y.NRPNLsb||i===y.NRPNMsb||i===y.bankSelect||i===y.lsbForControl0BankSelect||i===y.resetAllControllers,r=[];for(let i=0;i<t;i++)r.push(Array.from(nt));function g(i){if(n[i]=8192,r?.[i]!==void 0)for(let C=0;C<nt.length;C++)os.has(C)||(r[i][C]=nt[C])}for(;;){let i=this._findFirstEventIndex(),C=this.tracks[i][this.eventIndex[i]];if(A!==void 0){if(C.ticks>=A)break}else if(this.playedTime>=e)break;let B=ht(C.messageStatusByte),h=B.channel+(this.midiPortChannelOffsets[this.midiPorts[i]]||0);switch(B.status){case w.noteOn:r[h]===void 0&&(r[h]=Array.from(nt)),r[h][y.portamentoControl]=C.messageData[0];break;case w.noteOff:break;case w.pitchBend:n[h]=C.messageData[1]<<7|C.messageData[0];break;case w.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[i].size===0)break;let l=s[h];l.program=C.messageData[0],l.actualBank=l.bank;break;case w.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[i].size===0)break;let m=C.messageData[0];if(o(m)){let f=C.messageData[1];if(m===y.bankSelect){s[h].bank=f;break}else m===y.resetAllControllers&&g(h);this.sendMIDIMessages?this.sendMIDICC(h,m,f):this.synth.controllerChange(h,m,f)}else r[h]===void 0&&(r[h]=Array.from(nt)),r[h][m]=C.messageData[1];break;default:this._processEvent(C,i);break}this.eventIndex[i]++,i=this._findFirstEventIndex();let c=this.tracks[i][this.eventIndex[i]];if(c===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(c.ticks-C.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((C,B)=>{C!==nt[B]&&!o(B)&&this.sendMIDICC(i,B,C)}),s[i].program>=0&&s[i].actualBank>=0){let C=s[i].actualBank;this.sendMIDICC(i,y.bankSelect,C),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((C,B)=>{C!==nt[B]&&!o(B)&&this.synth.controllerChange(i,B,C)}),s[i].actualBank>=0){let C=s[i];C.program!==-1?(this.synth.controllerChange(i,y.bankSelect,C.actualBank),this.synth.programChange(i,C.program)):this.synth.controllerChange(i,y.bankSelect,C.bank)}return!0}function Zr(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 Xr(e){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 Wr(e){this.absoluteStartTime=this.synth.currentSynthTime-e/this._playbackRate}function _r(e){this.sendMIDIMessages&&this?.onMIDIMessage?.(e)}function zr(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.controllerChange|e,A,t])}function jr(e,A){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.programChange|e,A])}function $r(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.pitchBend|e,t,A])}function Ai(){if(this.sendMIDIMessages){this.sendMIDIMessage([w.reset]);for(let e=0;e<16;e++)this.sendMIDIMessage([w.controllerChange|e,y.allSoundOff,0]),this.sendMIDIMessage([w.controllerChange|e,y.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(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){J("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){J("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,y.sustainPedal,0);if(this.synth.stopAllChannels(),this.sendMIDIMessages){for(let A of this.playingNotes)this.sendMIDIMessage([w.noteOff|A.channel%16,A.midiNote]);for(let A=0;A<16;A++)this.sendMIDICC(A,y.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=Ai;wA.prototype.sendMIDICC=zr;wA.prototype.sendMIDIProgramChange=jr;wA.prototype.sendMIDIPitchWheel=$r;wA.prototype.assignMIDIPort=Jr;wA.prototype._processEvent=Mr;wA.prototype._addNewMidiPort=xr;wA.prototype.processTick=Nr;wA.prototype._findFirstEventIndex=br;wA.prototype.loadNewSequence=Or;wA.prototype.loadNewSongList=Kr;wA.prototype.nextSong=qr;wA.prototype.previousSong=Vr;wA.prototype.play=Zr;wA.prototype._playTo=Pr;wA.prototype.setTimeTicks=Xr;wA.prototype._recalculateStartTime=Wr;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,O){for(var z=new A(31),V=0;V<31;++V)z[V]=O+=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,C=g.r;i[28]=258,C[258]=28;var B=r(s,0),h=B.b,c=B.r,l=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,l[D]=((m&65280)>>8|(m&255)<<8)>>1;var m,D,f=function(H,O,z){for(var V=H.length,iA=0,qA=new A(O);iA<V;++iA)H[iA]&&++qA[H[iA]-1];var Ie=new A(O);for(iA=1;iA<O;++iA)Ie[iA]=Ie[iA-1]+qA[iA-1]<<1;var le;if(z){le=new A(1<<O);var Qe=15-O;for(iA=0;iA<V;++iA)if(H[iA])for(var ot=iA<<4|H[iA],ye=O-H[iA],gA=Ie[H[iA]-1]++<<ye,QA=gA|(1<<ye)-1;gA<=QA;++gA)le[l[gA]>>Qe]=ot}else for(le=new A(V),iA=0;iA<V;++iA)H[iA]&&(le[iA]=l[Ie[H[iA]-1]++]>>15-H[iA]);return le},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,F=new e(32);for(D=0;D<32;++D)F[D]=5;var D,x=f(S,9,1),L=f(F,5,1),G=function(H){for(var O=H[0],z=1;z<H.length;++z)H[z]>O&&(O=H[z]);return O},E=function(H,O,z){var V=O/8|0;return(H[V]|H[V+1]<<8)>>(O&7)&z},M=function(H,O){var z=O/8|0;return(H[z]|H[z+1]<<8|H[z+2]<<16)>>(O&7)},v=function(H){return(H+7)/8|0},eA=function(H,O,z){return(O==null||O<0)&&(O=0),(z==null||z>H.length)&&(z=H.length),new e(H.subarray(O,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"],T=function(H,O,z){var V=new Error(O||$[H]);if(V.code=H,Error.captureStackTrace&&Error.captureStackTrace(V,T),!z)throw V;return V},nA=function(H,O,z,V){var iA=H.length,qA=V?V.length:0;if(!iA||O.f&&!O.l)return z||new e(0);var Ie=!z,le=Ie||O.i!=2,Qe=O.i;Ie&&(z=new e(iA*3));var ot=function(zt){var ve=z.length;if(zt>ve){var Gt=new e(Math.max(ve*2,zt));Gt.set(z),z=Gt}},ye=O.f||0,gA=O.p||0,QA=O.b||0,de=O.l,_A=O.d,Le=O.m,Te=O.n,Dt=iA*8;do{if(!de){ye=E(H,gA,1);var rt=E(H,gA+1,3);if(gA+=3,rt)if(rt==1)de=x,_A=L,Le=9,Te=5;else if(rt==2){var kt=E(H,gA,31)+257,Nn=E(H,gA+10,15)+4,bn=kt+E(H,gA+5,31)+1;gA+=14;for(var it=new e(bn),Ue=new e(19),zA=0;zA<Nn;++zA)Ue[o[zA]]=E(H,gA+zA*3,7);gA+=Nn*3;for(var Ln=G(Ue),Zt=(1<<Ln)-1,at=f(Ue,Ln,1),zA=0;zA<bn;){var Ft=at[E(H,gA,Zt)];gA+=Ft&15;var VA=Ft>>4;if(VA<16)it[zA++]=VA;else{var Se=0,wt=0;for(VA==16?(wt=3+E(H,gA,3),gA+=2,Se=it[zA-1]):VA==17?(wt=3+E(H,gA,7),gA+=3):VA==18&&(wt=11+E(H,gA,127),gA+=7);wt--;)it[zA++]=Se}}var Tn=it.subarray(0,kt),De=it.subarray(kt);Le=G(Tn),Te=G(De),de=f(Tn,Le,1),_A=f(De,Te,1)}else T(1);else{var VA=v(gA)+4,Xt=H[VA-4]|H[VA-3]<<8,Wt=VA+Xt;if(Wt>iA){Qe&&T(0);break}le&&ot(QA+Xt),z.set(H.subarray(VA,Wt),QA),O.b=QA+=Xt,O.p=gA=Wt*8,O.f=ye;continue}if(gA>Dt){Qe&&T(0);break}}le&&ot(QA+131072);for(var ks=(1<<Le)-1,Fs=(1<<Te)-1,_t=gA;;_t=gA){var Se=de[M(H,gA)&ks],qe=Se>>4;if(gA+=Se&15,gA>Dt){Qe&&T(0);break}if(Se||T(2),qe<256)z[QA++]=qe;else if(qe==256){_t=gA,de=null;break}else{var Un=qe-254;if(qe>264){var zA=qe-257,ke=n[zA];Un=E(H,gA,(1<<ke)-1)+i[zA],gA+=ke}var gt=_A[M(H,gA)&Fs],Ve=gt>>4;gt||T(3),gA+=gt&15;var De=h[Ve];if(Ve>3){var ke=s[Ve];De+=M(H,gA)&(1<<ke)-1,gA+=ke}if(gA>Dt){Qe&&T(0);break}le&&ot(QA+131072);var Rt=QA+Un;if(QA<De){var It=qA-De,xA=Math.min(De,Rt);for(It+QA<0&&T(3);QA<xA;++QA)z[QA]=V[It+QA]}for(;QA<Rt;++QA)z[QA]=z[QA-De]}}O.l=de,O.p=_t,O.b=QA,O.f=ye,de&&(ye=1,O.m=Le,O.d=_A,O.n=Te)}while(!ye);return QA!=z.length&&Ie?eA(z,0,QA):z.subarray(0,QA)},cA=new e(0);function oA(H,O){return nA(H,{i:2},O&&O.out,O&&O.dictionary)}var rA=typeof TextDecoder<"u"&&new TextDecoder,hA=0;try{rA.decode(cA,{stream:!0}),hA=1}catch{}qt=oA})();var ms={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},yt={inLineResource:1,inFileResource:2,inFileNode:3,externalFile:4,externalXMF:5,XMFFileURIandNodeID:6},ps={StandardMIDIFile:0,StandardMIDIFileType1:1,DLS1:2,DLS2:3,DLS22:4,mobileDLS:5},vi={standard:0,MMA:1,registered:2,nonRegistered:3},Gn={none:0,MMAUnpacker:1,registered:2,nonRegistered:3},ys=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,C;for(;g.currentIndex<g.length;){if(g[g.currentIndex]===0)g.currentIndex++,i=mA(g),Object.values(ms).indexOf(i)===-1?(J(`Unknown field specifier: ${i}`),C=`unknown_${i}`):C=Object.keys(ms).find(f=>ms[f]===i);else{let f=mA(g);i=AA(g,f),C=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[C]=AA(S,f-1):this.metadata[C]=S.slice(S.currentIndex)}else J(`International content: ${m}`),g.currentIndex+=mA(g)}let B=r.currentIndex,h=mA(r),c=r.slice(r.currentIndex,B+h);if(r.currentIndex=B+h,h>0)for(this.packedContent=!0;c.currentIndex<h;){let l={};switch(l.id=mA(c),l.id){case Gn.nonRegistered:case Gn.registered:throw q(),new Error(`Unsupported unpacker ID: ${l.id}`);default:throw q(),new Error(`Unknown unpacker ID: ${l.id}`);case Gn.none:l.standardID=mA(c);break;case Gn.MMAUnpacker:let m=c[c.currentIndex++];m===0&&(m<<=8,m|=c[c.currentIndex++],m<<=8,m|=c[c.currentIndex++]);let f=mA(c);l.manufacturerID=m,l.manufacturerInternalID=f;break}l.decodedSize=mA(c),this.nodeUnpackers.push(l)}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 yt.inLineResource:break;case yt.externalXMF:case yt.inFileNode:case yt.XMFFileURIandNodeID:case yt.externalFile:case yt.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);p(`%cPacked content. Attemting to deflate. Target size: %c${this.nodeUnpackers[0].decodedSize}`,I.warn,I.value);try{this.nodeData=new N(qt(m).buffer)}catch(f){throw q(),new Error(`Error unpacking XMF file contents: ${f.message}.`)}}let l=this.metadata.resourceFormat;if(l===void 0)J("No resource format for this file node!");else{l[0]!==vi.standard&&(J(`Non-standard formatTypeID: ${l}`),this.resourceFormat=l.toString());let f=l[1];Object.values(ps).indexOf(f)===-1?J(`Unrecognized resource format: ${f}`):this.resourceFormat=Object.keys(ps).find(S=>ps[S]===f)}}else for(this.resourceFormat="folder";this.nodeData.currentIndex<this.nodeData.length;){let l=this.nodeData.currentIndex,m=mA(this.nodeData),f=this.nodeData.slice(l,l+m);this.nodeData.currentIndex=l+m,this.innerNodes.push(new e(f))}}get isFile(){return this.itemCount===0}};function ei(e,A){e.bankOffset=0;let t=AA(A,4);if(t!=="XMF_")throw q(),new SyntaxError(`Invalid XMF Header! Expected "_XMF", got "${t}"`);ae("%cParsing XMF file...",I.info);let n=AA(A,4);if(p(`%cXMF version: %c${n}`,I.info,I.recognized),n==="2.00"){let i=KA(A,4),C=KA(A,4);p(`%cFile Type ID: %c${i}%c, File Type Revision ID: %c${C}`,I.info,I.recognized,I.info,I.recognized)}mA(A);let s=mA(A);A.currentIndex+=s,A.currentIndex=mA(A);let o=new ys(A),r,g=i=>{let C=(B,h)=>{i.metadata[B]!==void 0&&typeof i.metadata[B]=="string"&&(e.RMIDInfo[h]=i.metadata[B])};if(C("nodeName",pA.name),C("title",pA.name),C("copyrightNotice",pA.copyright),C("comment",pA.comment),i.isFile)switch(i.resourceFormat){default:return;case"DLS1":case"DLS2":case"DLS22":case"mobileDLS":p("%cFound embedded DLS!",I.recognized),e.embeddedSoundFont=i.nodeData.buffer;break;case"StandardMIDIFile":case"StandardMIDIFileType1":p("%cFound embedded MIDI!",I.recognized),r=i.nodeData;break}else for(let B of i.innerNodes)g(B)};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 N(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 C=n.currentIndex,B=IA(n,!0);if(B.header==="RIFF"){let h=AA(B.chunkData,4).toLowerCase();h==="sfbk"||h==="sfpk"||h==="dls "?(p("%cFound embedded soundfont!",I.recognized),this.embeddedSoundFont=n.slice(C,C+B.size).buffer):J(`Unknown RIFF chunk: "${h}"`),h==="dls "&&(this.isDLSRMIDI=!0)}else if(B.header==="LIST"&&AA(B.chunkData,4)==="INFO"){for(p("%cFound RMIDI INFO chunk!",I.recognized),this.RMIDInfo={};B.chunkData.currentIndex<=B.size;){let c=IA(B.chunkData,!0);this.RMIDInfo[c.header]=c.chunkData}this.RMIDInfo.ICOP&&(this.copyright=AA(this.RMIDInfo.ICOP,this.RMIDInfo.ICOP.length,void 0,!1).replaceAll(`
19
+ `)||""),this.midiName=this.midiName.trim(),this.midiNameUsesFileName=!1,this.midiName.length===0){p("%cNo name detected. Using the alt name!",I.info),this.midiName=Hs(this.fileName),this.midiNameUsesFileName=!0,this.rawMidiName=new Uint8Array(this.midiName.length);for(let B=0;B<this.midiName.length;B++)this.rawMidiName[B]=this.midiName.charCodeAt(B)}else p(`%cMIDI Name detected! %c"${this.midiName}"`,I.info,I.recognized);this.tracks.some(B=>B[0].ticks===0)||this.tracks[0].unshift(new YA(0,w.trackName,new N(this.rawMidiName.buffer))),this.duration=this.MIDIticksToSeconds(this.lastVoiceEventTick),p("%cSuccess!",I.recognized),q()}flush(){for(let A of this.tracks)A.sort((t,n)=>t.ticks-n.ticks);this._parseInternal()}};WA.prototype.writeMIDI=Lr;WA.prototype.modifyMIDI=Tr;WA.prototype.applySnapshotToMIDI=Ur;WA.prototype.writeRMIDI=vr;WA.prototype.getUsedProgramsAndKeys=Hr;WA.prototype.getNoteTimes=Yr;function Jr(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 Or(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&&(p("%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);p(`%cPreloading used samples on %c${g.presetName}%c...`,I.info,I.recognized,I.info);for(let i of s){let[C,B]=i.split("-").map(Number);this.synth.getVoicesForPreset(g,o,r,C,B,C)}}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),p(`%cTotal song time: ${Zn(Math.ceil(this.duration)).time}`,I.recognized),this?.onSongChange?.(this.songIndex,A),this.duration<=1&&(J(`%cVery short song: (${Zn(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 Kr(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 qr(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadCurrentSong()}function Vr(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadCurrentSong()}var nt=He.slice(0,128);function Pr(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===y.dataDecrement||i===y.dataIncrement||i===y.dataEntryMsb||i===y.dataDecrement||i===y.lsbForControl6DataEntry||i===y.RPNLsb||i===y.RPNMsb||i===y.NRPNLsb||i===y.NRPNMsb||i===y.bankSelect||i===y.lsbForControl0BankSelect||i===y.resetAllControllers,r=[];for(let i=0;i<t;i++)r.push(Array.from(nt));function g(i){if(n[i]=8192,r?.[i]!==void 0)for(let C=0;C<nt.length;C++)os.has(C)||(r[i][C]=nt[C])}for(;;){let i=this._findFirstEventIndex(),C=this.tracks[i][this.eventIndex[i]];if(A!==void 0){if(C.ticks>=A)break}else if(this.playedTime>=e)break;let B=ht(C.messageStatusByte),h=B.channel+(this.midiPortChannelOffsets[this.midiPorts[i]]||0);switch(B.status){case w.noteOn:r[h]===void 0&&(r[h]=Array.from(nt)),r[h][y.portamentoControl]=C.messageData[0];break;case w.noteOff:break;case w.pitchBend:n[h]=C.messageData[1]<<7|C.messageData[0];break;case w.programChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[i].size===0)break;let l=s[h];l.program=C.messageData[0],l.actualBank=l.bank;break;case w.controllerChange:if(this.midiData.isMultiPort&&this.midiData.usedChannelsOnTrack[i].size===0)break;let m=C.messageData[0];if(o(m)){let f=C.messageData[1];if(m===y.bankSelect){s[h].bank=f;break}else m===y.resetAllControllers&&g(h);this.sendMIDIMessages?this.sendMIDICC(h,m,f):this.synth.controllerChange(h,m,f)}else r[h]===void 0&&(r[h]=Array.from(nt)),r[h][m]=C.messageData[1];break;default:this._processEvent(C,i);break}this.eventIndex[i]++,i=this._findFirstEventIndex();let c=this.tracks[i][this.eventIndex[i]];if(c===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(c.ticks-C.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((C,B)=>{C!==nt[B]&&!o(B)&&this.sendMIDICC(i,B,C)}),s[i].program>=0&&s[i].actualBank>=0){let C=s[i].actualBank;this.sendMIDICC(i,y.bankSelect,C),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((C,B)=>{C!==nt[B]&&!o(B)&&this.synth.controllerChange(i,B,C)}),s[i].actualBank>=0){let C=s[i];C.program!==-1?(this.synth.controllerChange(i,y.bankSelect,C.actualBank),this.synth.programChange(i,C.program)):this.synth.controllerChange(i,y.bankSelect,C.bank)}return!0}function Zr(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 Xr(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 Wr(e){this.absoluteStartTime=this.synth.currentSynthTime-e/this._playbackRate}function _r(e){this.sendMIDIMessages&&this?.onMIDIMessage?.(e)}function zr(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.controllerChange|e,A,t])}function jr(e,A){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.programChange|e,A])}function $r(e,A,t){e%=16,this.sendMIDIMessages&&this.sendMIDIMessage([w.pitchBend|e,t,A])}function Ai(){if(this.sendMIDIMessages){this.sendMIDIMessage([w.reset]);for(let e=0;e<16;e++)this.sendMIDIMessage([w.controllerChange|e,y.allSoundOff,0]),this.sendMIDIMessage([w.controllerChange|e,y.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){J("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){J("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,y.sustainPedal,0);if(this.synth.stopAllChannels(),this.sendMIDIMessages){for(let A of this.playingNotes)this.sendMIDIMessage([w.noteOff|A.channel%16,A.midiNote]);for(let A=0;A<16;A++)this.sendMIDICC(A,y.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=Ai;wA.prototype.sendMIDICC=zr;wA.prototype.sendMIDIProgramChange=jr;wA.prototype.sendMIDIPitchWheel=$r;wA.prototype.assignMIDIPort=Jr;wA.prototype._processEvent=Mr;wA.prototype._addNewMidiPort=xr;wA.prototype.processTick=Nr;wA.prototype._findFirstEventIndex=br;wA.prototype.loadNewSequence=Or;wA.prototype.loadNewSongList=Kr;wA.prototype.nextSong=qr;wA.prototype.previousSong=Vr;wA.prototype.play=Zr;wA.prototype._playTo=Pr;wA.prototype.setTimeTicks=Xr;wA.prototype._recalculateStartTime=Wr;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,O){for(var z=new A(31),V=0;V<31;++V)z[V]=O+=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,C=g.r;i[28]=258,C[258]=28;var B=r(s,0),h=B.b,c=B.r,l=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,l[D]=((m&65280)>>8|(m&255)<<8)>>1;var m,D,f=function(H,O,z){for(var V=H.length,iA=0,qA=new A(O);iA<V;++iA)H[iA]&&++qA[H[iA]-1];var Ie=new A(O);for(iA=1;iA<O;++iA)Ie[iA]=Ie[iA-1]+qA[iA-1]<<1;var le;if(z){le=new A(1<<O);var Qe=15-O;for(iA=0;iA<V;++iA)if(H[iA])for(var ot=iA<<4|H[iA],ye=O-H[iA],gA=Ie[H[iA]-1]++<<ye,QA=gA|(1<<ye)-1;gA<=QA;++gA)le[l[gA]>>Qe]=ot}else for(le=new A(V),iA=0;iA<V;++iA)H[iA]&&(le[iA]=l[Ie[H[iA]-1]++]>>15-H[iA]);return le},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,F=new e(32);for(D=0;D<32;++D)F[D]=5;var D,x=f(S,9,1),L=f(F,5,1),G=function(H){for(var O=H[0],z=1;z<H.length;++z)H[z]>O&&(O=H[z]);return O},E=function(H,O,z){var V=O/8|0;return(H[V]|H[V+1]<<8)>>(O&7)&z},M=function(H,O){var z=O/8|0;return(H[z]|H[z+1]<<8|H[z+2]<<16)>>(O&7)},v=function(H){return(H+7)/8|0},eA=function(H,O,z){return(O==null||O<0)&&(O=0),(z==null||z>H.length)&&(z=H.length),new e(H.subarray(O,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"],T=function(H,O,z){var V=new Error(O||$[H]);if(V.code=H,Error.captureStackTrace&&Error.captureStackTrace(V,T),!z)throw V;return V},nA=function(H,O,z,V){var iA=H.length,qA=V?V.length:0;if(!iA||O.f&&!O.l)return z||new e(0);var Ie=!z,le=Ie||O.i!=2,Qe=O.i;Ie&&(z=new e(iA*3));var ot=function(zt){var ve=z.length;if(zt>ve){var Gt=new e(Math.max(ve*2,zt));Gt.set(z),z=Gt}},ye=O.f||0,gA=O.p||0,QA=O.b||0,de=O.l,_A=O.d,Le=O.m,Te=O.n,Dt=iA*8;do{if(!de){ye=E(H,gA,1);var rt=E(H,gA+1,3);if(gA+=3,rt)if(rt==1)de=x,_A=L,Le=9,Te=5;else if(rt==2){var kt=E(H,gA,31)+257,Nn=E(H,gA+10,15)+4,bn=kt+E(H,gA+5,31)+1;gA+=14;for(var it=new e(bn),Ue=new e(19),zA=0;zA<Nn;++zA)Ue[o[zA]]=E(H,gA+zA*3,7);gA+=Nn*3;for(var Ln=G(Ue),Zt=(1<<Ln)-1,at=f(Ue,Ln,1),zA=0;zA<bn;){var Ft=at[E(H,gA,Zt)];gA+=Ft&15;var VA=Ft>>4;if(VA<16)it[zA++]=VA;else{var Se=0,wt=0;for(VA==16?(wt=3+E(H,gA,3),gA+=2,Se=it[zA-1]):VA==17?(wt=3+E(H,gA,7),gA+=3):VA==18&&(wt=11+E(H,gA,127),gA+=7);wt--;)it[zA++]=Se}}var Tn=it.subarray(0,kt),De=it.subarray(kt);Le=G(Tn),Te=G(De),de=f(Tn,Le,1),_A=f(De,Te,1)}else T(1);else{var VA=v(gA)+4,Xt=H[VA-4]|H[VA-3]<<8,Wt=VA+Xt;if(Wt>iA){Qe&&T(0);break}le&&ot(QA+Xt),z.set(H.subarray(VA,Wt),QA),O.b=QA+=Xt,O.p=gA=Wt*8,O.f=ye;continue}if(gA>Dt){Qe&&T(0);break}}le&&ot(QA+131072);for(var ks=(1<<Le)-1,Fs=(1<<Te)-1,_t=gA;;_t=gA){var Se=de[M(H,gA)&ks],qe=Se>>4;if(gA+=Se&15,gA>Dt){Qe&&T(0);break}if(Se||T(2),qe<256)z[QA++]=qe;else if(qe==256){_t=gA,de=null;break}else{var Un=qe-254;if(qe>264){var zA=qe-257,ke=n[zA];Un=E(H,gA,(1<<ke)-1)+i[zA],gA+=ke}var gt=_A[M(H,gA)&Fs],Ve=gt>>4;gt||T(3),gA+=gt&15;var De=h[Ve];if(Ve>3){var ke=s[Ve];De+=M(H,gA)&(1<<ke)-1,gA+=ke}if(gA>Dt){Qe&&T(0);break}le&&ot(QA+131072);var Rt=QA+Un;if(QA<De){var It=qA-De,xA=Math.min(De,Rt);for(It+QA<0&&T(3);QA<xA;++QA)z[QA]=V[It+QA]}for(;QA<Rt;++QA)z[QA]=z[QA-De]}}O.l=de,O.p=_t,O.b=QA,O.f=ye,de&&(ye=1,O.m=Le,O.d=_A,O.n=Te)}while(!ye);return QA!=z.length&&Ie?eA(z,0,QA):z.subarray(0,QA)},cA=new e(0);function oA(H,O){return nA(H,{i:2},O&&O.out,O&&O.dictionary)}var rA=typeof TextDecoder<"u"&&new TextDecoder,hA=0;try{rA.decode(cA,{stream:!0}),hA=1}catch{}qt=oA})();var ms={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},yt={inLineResource:1,inFileResource:2,inFileNode:3,externalFile:4,externalXMF:5,XMFFileURIandNodeID:6},ps={StandardMIDIFile:0,StandardMIDIFileType1:1,DLS1:2,DLS2:3,DLS22:4,mobileDLS:5},vi={standard:0,MMA:1,registered:2,nonRegistered:3},Gn={none:0,MMAUnpacker:1,registered:2,nonRegistered:3},ys=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,C;for(;g.currentIndex<g.length;){if(g[g.currentIndex]===0)g.currentIndex++,i=mA(g),Object.values(ms).indexOf(i)===-1?(J(`Unknown field specifier: ${i}`),C=`unknown_${i}`):C=Object.keys(ms).find(f=>ms[f]===i);else{let f=mA(g);i=AA(g,f),C=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[C]=AA(S,f-1):this.metadata[C]=S.slice(S.currentIndex)}else J(`International content: ${m}`),g.currentIndex+=mA(g)}let B=r.currentIndex,h=mA(r),c=r.slice(r.currentIndex,B+h);if(r.currentIndex=B+h,h>0)for(this.packedContent=!0;c.currentIndex<h;){let l={};switch(l.id=mA(c),l.id){case Gn.nonRegistered:case Gn.registered:throw q(),new Error(`Unsupported unpacker ID: ${l.id}`);default:throw q(),new Error(`Unknown unpacker ID: ${l.id}`);case Gn.none:l.standardID=mA(c);break;case Gn.MMAUnpacker:let m=c[c.currentIndex++];m===0&&(m<<=8,m|=c[c.currentIndex++],m<<=8,m|=c[c.currentIndex++]);let f=mA(c);l.manufacturerID=m,l.manufacturerInternalID=f;break}l.decodedSize=mA(c),this.nodeUnpackers.push(l)}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 yt.inLineResource:break;case yt.externalXMF:case yt.inFileNode:case yt.XMFFileURIandNodeID:case yt.externalFile:case yt.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);p(`%cPacked content. Attemting to deflate. Target size: %c${this.nodeUnpackers[0].decodedSize}`,I.warn,I.value);try{this.nodeData=new N(qt(m).buffer)}catch(f){throw q(),new Error(`Error unpacking XMF file contents: ${f.message}.`)}}let l=this.metadata.resourceFormat;if(l===void 0)J("No resource format for this file node!");else{l[0]!==vi.standard&&(J(`Non-standard formatTypeID: ${l}`),this.resourceFormat=l.toString());let f=l[1];Object.values(ps).indexOf(f)===-1?J(`Unrecognized resource format: ${f}`):this.resourceFormat=Object.keys(ps).find(S=>ps[S]===f)}}else for(this.resourceFormat="folder";this.nodeData.currentIndex<this.nodeData.length;){let l=this.nodeData.currentIndex,m=mA(this.nodeData),f=this.nodeData.slice(l,l+m);this.nodeData.currentIndex=l+m,this.innerNodes.push(new e(f))}}get isFile(){return this.itemCount===0}};function ei(e,A){e.bankOffset=0;let t=AA(A,4);if(t!=="XMF_")throw q(),new SyntaxError(`Invalid XMF Header! Expected "_XMF", got "${t}"`);ae("%cParsing XMF file...",I.info);let n=AA(A,4);if(p(`%cXMF version: %c${n}`,I.info,I.recognized),n==="2.00"){let i=KA(A,4),C=KA(A,4);p(`%cFile Type ID: %c${i}%c, File Type Revision ID: %c${C}`,I.info,I.recognized,I.info,I.recognized)}mA(A);let s=mA(A);A.currentIndex+=s,A.currentIndex=mA(A);let o=new ys(A),r,g=i=>{let C=(B,h)=>{i.metadata[B]!==void 0&&typeof i.metadata[B]=="string"&&(e.RMIDInfo[h]=i.metadata[B])};if(C("nodeName",pA.name),C("title",pA.name),C("copyrightNotice",pA.copyright),C("comment",pA.comment),i.isFile)switch(i.resourceFormat){default:return;case"DLS1":case"DLS2":case"DLS22":case"mobileDLS":p("%cFound embedded DLS!",I.recognized),e.embeddedSoundFont=i.nodeData.buffer;break;case"StandardMIDIFile":case"StandardMIDIFileType1":p("%cFound embedded MIDI!",I.recognized),r=i.nodeData;break}else for(let B of i.innerNodes)g(B)};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 N(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 C=n.currentIndex,B=IA(n,!0);if(B.header==="RIFF"){let h=AA(B.chunkData,4).toLowerCase();h==="sfbk"||h==="sfpk"||h==="dls "?(p("%cFound embedded soundfont!",I.recognized),this.embeddedSoundFont=n.slice(C,C+B.size).buffer):J(`Unknown RIFF chunk: "${h}"`),h==="dls "&&(this.isDLSRMIDI=!0)}else if(B.header==="LIST"&&AA(B.chunkData,4)==="INFO"){for(p("%cFound RMIDI INFO chunk!",I.recognized),this.RMIDInfo={};B.chunkData.currentIndex<=B.size;){let c=IA(B.chunkData,!0);this.RMIDInfo[c.header]=c.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(`
21
- `," ")),this.RMIDInfo.IALB&&!this.RMIDInfo.IPRD&&(this.RMIDInfo.IPRD=this.RMIDInfo.IALB),this.RMIDInfo.IPRD&&!this.RMIDInfo.IALB&&(this.RMIDInfo.IALB=this.RMIDInfo.IPRD),this.bankOffset=1,this.RMIDInfo[pA.bankOffset]&&(this.bankOffset=b(this.RMIDInfo[pA.bankOffset],2))}}this.isDLSRMIDI&&(this.bankOffset=0),this.embeddedSoundFont===void 0&&(this.bankOffset=0)}else o==="XMF_"?s=ei(this,n):s=n;let r=this._readMIDIChunk(s);if(r.type!=="MThd")throw q(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${r.type}"`);if(r.size!==6)throw q(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${r.size}`);this.format=KA(r.data,2),this.tracksAmount=KA(r.data,2),this.timeDivision=KA(r.data,2);for(let g=0;g<this.tracksAmount;g++){let i=[],C=this._readMIDIChunk(s);if(C.type!=="MTrk")throw q(),new SyntaxError(`Invalid track header! Expected "MTrk" got "${C.type}"`);let B,h=0;for(this.format===2&&g>0&&(h+=this.tracks[g-1][this.tracks[g-1].length-1].ticks);C.data.currentIndex<C.size;){h+=mA(C.data);let c=C.data[C.data.currentIndex],l;if(B!==void 0&&c<128)l=B;else{if(B===void 0&&c<128)throw q(),new SyntaxError(`Unexpected byte with no running byte. (${c})`);l=C.data[C.data.currentIndex++]}let m=Xs(l),f;switch(m){case-1:f=0;break;case-2:l=C.data[C.data.currentIndex++],f=mA(C.data);break;case-3:f=mA(C.data);break;default:f=Ws[l>>4],B=l;break}let S=new N(f);S.set(C.data.slice(C.data.currentIndex,C.data.currentIndex+f),0);let F=new YA(h,l,S);i.push(F),C.data.currentIndex+=f}this.tracks.push(i),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,I.info,I.value,I.info,I.value)}p("%cAll tracks parsed correctly!",I.recognized),this._parseInternal(),q(),p(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}%c, total seconds time: %c${this.duration}`,I.info,I.recognized,I.info,I.recognized)}_readMIDIChunk(A){let t={};t.type=AA(A,4),t.size=KA(A,4),t.data=new N(t.size);let n=A.slice(A.currentIndex,A.currentIndex+t.size);return t.data.set(n,0),A.currentIndex+=t.size,t}};var st={consoleColors:I,SpessaSynthInfo:p,SpessaSynthWarn:J,SpessaSynthGroupCollapsed:uA,SpessaSynthGroupEnd:q,readBytesAsUintBigEndian:KA,readLittleEndian:b,readBytesAsString:AA,readVariableLengthQuantity:mA,inflateSync:qt};var Ss=st.consoleColors;var RA={midiMessage:0,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customCcChange:14,debugMessage:15,setMasterParameter:17,setDrums:18,transpose:19,highPerformanceMode:20,lockController:21,sequencerSpecific:22,requestSynthesizerSnapshot:23,setLogLevel:24,keyModifierManager:25,setEffectsGain:26,destroyWorklet:27},te={channelPropertyChange:0,eventCall:1,masterParameterChange:2,sequencerSpecific:3,synthesizerSnapshot:4,isFullyInitialized:5,soundfontError:6};var ti="spessasynth-worklet-processor";var Mn={addMapping:0,deleteMapping:1,clearMappings:2};var Pt={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var St={backwards:0,forwards:1,shuffleOn:2,shuffleOff:3,index:4},ne={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10,setPreservePlaybackState:11},Be={midiEvent:0,songChange:1,timeChange:2,pause:3,getMIDI:4,midiError:5,metaEvent:6,loopCountChange:7,songListChange:8};function ni(e,A){e===void 0&&(e={});for(let t in A)A.hasOwnProperty(t)&&!(t in e)&&(e[t]=A[t]);return e}var si={skipToFirstNoteOn:!0,autoPlay:!0,preservePlaybackState:!1};var xn=class extends tt{isEmbedded=!1;constructor(A){super(),this._copyFromSequence(A),this.isEmbedded=A.embeddedSoundFont!==void 0}},im={duration:99999,firstNoteOn:0,loop:{start:0,end:123456},lastVoiceEventTick:123456,lyrics:[],copyright:"",midiPorts:[],midiPortChannelOffsets:[],tracksAmount:0,tempoChanges:[{ticks:0,tempo:120}],fileName:"NOT_LOADED.mid",midiName:"Loading...",rawMidiName:new Uint8Array([76,111,97,100,105,110,103,46,46,46]),usedChannelsOnTrack:[],timeDivision:0,keyRange:{min:0,max:127},isEmbedded:!1,RMIDInfo:{},bankOffset:0,midiNameUsesFileName:!1,format:0};var Ds=class extends AudioWorkletProcessor{alive=!0;oneOutputMode=!1;constructor(A){super();let t=A.processorOptions;this.oneOutputMode=t.midiChannels===1;let n=(g,i)=>{this.postMessageToMainThread({messageType:g,messageData:i})},s=t?.startRenderingData,o=s?.snapshot;this.synthesizer=new LA(sampleRate,{effectsEnabled:!this.oneOutputMode,enableEventSystem:t?.enableEventSystem,midiChannels:16,initialTime:currentTime}),this.synthesizer.onEventCall=(g,i)=>{n(te.eventCall,{eventName:g,eventData:i})},this.synthesizer.onChannelPropertyChange=(g,i)=>n(te.channelPropertyChange,[i,g]),this.synthesizer.onMasterParameterChange=(g,i)=>n(te.masterParameterChange,[g,i]);let r=$e(t.soundfont);this.synthesizer.soundfontManager.reloadManager(r),this.synthesizer.processorInitialized.then(()=>{this.sequencer=new wA(this.synthesizer);let g=(i,C)=>{this.postMessageToMainThread({messageType:te.sequencerSpecific,messageData:{messageType:i,messageData:C}})};if(this.port.onmessage=i=>this.handleMessage(i.data),this.sequencer.onMIDIMessage=i=>{g(Be.midiEvent,i)},this.sequencer.onTimeChange=i=>{g(Be.timeChange,i)},this.sequencer.onPlaybackStop=i=>{g(Be.pause,i)},this.sequencer.onSongChange=(i,C)=>{g(Be.songChange,[i,C])},this.sequencer.onMetaEvent=(i,C)=>{g(Be.metaEvent,[i,C])},this.sequencer.onLoopCountChange=i=>{g(Be.loopCountChange,i)},this.sequencer.onSongListChange=i=>{let C=i.map(B=>new xn(B));this.postMessageToMainThread({messageType:te.sequencerSpecific,messageData:{messageType:Be.songListChange,messageData:C}})},o!==void 0&&this.synthesizer.applySynthesizerSnapshot(o),s&&(st.SpessaSynthInfo("%cRendering enabled! Starting render.",Ss.info),s.parsedMIDI)){s?.loopCount!==void 0?(this.sequencer.loopCount=s?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.synthesizer.voiceCap=1/0;let i=ni(s.sequencerOptions,si);this.sequencer.skipToFirstNoteOn=i.skipToFirstNoteOn,this.sequencer.preservePlaybackState=i.preservePlaybackState;try{this.sequencer.loadNewSongList([s.parsedMIDI])}catch(C){console.error(C),g(Be.midiError,C)}}this.postReady()})}postReady(){this.postMessageToMainThread({messageType:te.isFullyInitialized,messageData:void 0})}postMessageToMainThread(A){this.port.postMessage(A)}handleMessage(A){let t=A.messageData,n=A.channelNumber,s;if(n>=0&&(s=this.synthesizer.midiAudioChannels[n],s===void 0)){st.SpessaSynthWarn(`Trying to access channel ${n} which does not exist... ignoring!`);return}switch(A.messageType){case RA.midiMessage:this.synthesizer.processMessage(...t);break;case RA.customCcChange:s.setCustomController(t[0],t[1]);break;case RA.ccReset:n===-1?this.synthesizer.resetAllControllers():s.resetControllers();break;case RA.setChannelVibrato:if(n===-1)for(let m=0;m<this.synthesizer.midiAudioChannels.length;m++){let f=this.synthesizer.midiAudioChannels[m];t.rate===-1?f.disableAndLockGSNRPN():f.setVibrato(t.depth,t.rate,t.delay)}else t.rate===-1?s.disableAndLockGSNRPN():s.setVibrato(t.depth,t.rate,t.delay);break;case RA.stopAll:n===-1?this.synthesizer.stopAllChannels(t===1):s.stopAllNotes(t===1);break;case RA.killNotes:this.synthesizer.voiceKilling(t);break;case RA.muteChannel:s.muteChannel(t);break;case RA.addNewChannel:this.synthesizer.createMidiChannel(!0);break;case RA.debugMessage:console.debug(this.synthesizer);break;case RA.setMasterParameter:let o=t[0],r=t[1];this.synthesizer.setMasterParameter(o,r);break;case RA.setDrums:s.setDrums(t);break;case RA.transpose:n===-1?this.synthesizer.transposeAllChannels(t[0],t[1]):s.transposeChannel(t[0],t[1]);break;case RA.highPerformanceMode:this.synthesizer.highPerformanceMode=t;break;case RA.lockController:t[0]===-1?s.setPresetLock(t[1]):s.lockedControllers[t[0]]=t[1];break;case RA.sequencerSpecific:let g=this.sequencer,i=t.messageData;switch(t.messageType){default:break;case ne.loadNewSongList:try{let F=i[0].map(D=>D.duration?D:new Vt(D.binary,D.altName));g.loadNewSongList(F,i[1])}catch(S){console.error(S),this.postMessageToMainThread({messageType:te.sequencerSpecific,messageData:{messageType:Be.midiError,messageData:S}})}break;case ne.pause:g.pause();break;case ne.play:g.play(i);break;case ne.stop:g.stop();break;case ne.setTime:g.currentTime=i;break;case ne.changeMIDIMessageSending:g.sendMIDIMessages=i;break;case ne.setPlaybackRate:g.playbackRate=i;break;case ne.setLoop:let[m,f]=i;g.loop=m,f===-1?g.loopCount=1/0:g.loopCount=f;break;case ne.changeSong:switch(i[0]){case St.forwards:g.nextSong();break;case St.backwards:g.previousSong();break;case St.shuffleOff:g.shuffleMode=!1,g.songIndex=g.shuffledSongIndexes[g.songIndex];break;case St.shuffleOn:g.shuffleMode=!0,g.shuffleSongIndexes(),g.songIndex=0,g.loadCurrentSong();break;case St.index:g.songIndex=i[1],g.loadCurrentSong();break}break;case ne.getMIDI:this.postMessageToMainThread({messageType:te.sequencerSpecific,messageData:{messageType:Be.getMIDI,messageData:g.midiData}});break;case ne.setSkipToFirstNote:g.skipToFirstNoteOn=i;break;case ne.setPreservePlaybackState:g.preservePlaybackState=i}break;case RA.soundFontManager:try{let m=this.synthesizer.soundfontManager,f=t[0],S=t[1],F;switch(f){case Pt.addNewSoundFont:F=$e(S[0]),m.addNewSoundFont(F,S[1],S[2]),this.postMessageToMainThread({messageType:te.isFullyInitialized,messageData:void 0});break;case Pt.reloadSoundFont:F=$e(S),m.reloadManager(F),this.postMessageToMainThread({messageType:te.isFullyInitialized,messageData:void 0});break;case Pt.deleteSoundFont:m.deleteSoundFont(S);break;case Pt.rearrangeSoundFonts:m.rearrangeSoundFonts(S)}}catch(m){this.postMessageToMainThread({messageType:te.soundfontError,messageData:m})}break;case RA.keyModifierManager:let B=t[0],h=this.synthesizer.keyModifierManager,c=t[1];switch(B){default:return;case Mn.addMapping:h.addMapping(...c);break;case Mn.clearMappings:h.clearMappings();break;case Mn.deleteMapping:h.deleteMapping(...c)}break;case RA.requestSynthesizerSnapshot:let l=At.createSynthesizerSnapshot(this.synthesizer);this.postMessageToMainThread({messageType:te.synthesizerSnapshot,messageData:l});break;case RA.setLogLevel:Pn(t[0],t[1],t[2],t[3]);break;case RA.setEffectsGain:this.synthesizer.reverbGain=t[0],this.synthesizer.chorusGain=t[1];break;case RA.destroyWorklet:this.alive=!1,this.synthesizer.destroySynthProcessor(),delete this.synthesizer,delete this.sequencer.midiData,delete this.sequencer;break;default:st.SpessaSynthWarn("Unrecognized event:",t);break}}process(A,t){if(!this.alive)return!1;if(this.sequencer.processTick(),this.oneOutputMode){let n=t[0],s=[];for(let o=0;o<32;o+=2)s.push([n[o],n[o+1]]);this.synthesizer.renderAudioSplit([],[],s)}else this.synthesizer.renderAudioSplit(t[0],t[1],t.slice(2));return!0}};registerProcessor(ti,Ds);st.SpessaSynthInfo("%cProcessor successfully registered!",Ss.recognized);
21
+ `," ")),this.RMIDInfo.IALB&&!this.RMIDInfo.IPRD&&(this.RMIDInfo.IPRD=this.RMIDInfo.IALB),this.RMIDInfo.IPRD&&!this.RMIDInfo.IALB&&(this.RMIDInfo.IALB=this.RMIDInfo.IPRD),this.bankOffset=1,this.RMIDInfo[pA.bankOffset]&&(this.bankOffset=b(this.RMIDInfo[pA.bankOffset],2))}}this.isDLSRMIDI&&(this.bankOffset=0),this.embeddedSoundFont===void 0&&(this.bankOffset=0)}else o==="XMF_"?s=ei(this,n):s=n;let r=this._readMIDIChunk(s);if(r.type!=="MThd")throw q(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${r.type}"`);if(r.size!==6)throw q(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${r.size}`);this.format=KA(r.data,2),this.tracksAmount=KA(r.data,2),this.timeDivision=KA(r.data,2);for(let g=0;g<this.tracksAmount;g++){let i=[],C=this._readMIDIChunk(s);if(C.type!=="MTrk")throw q(),new SyntaxError(`Invalid track header! Expected "MTrk" got "${C.type}"`);let B,h=0;for(this.format===2&&g>0&&(h+=this.tracks[g-1][this.tracks[g-1].length-1].ticks);C.data.currentIndex<C.size;){h+=mA(C.data);let c=C.data[C.data.currentIndex],l;if(B!==void 0&&c<128)l=B;else{if(B===void 0&&c<128)throw q(),new SyntaxError(`Unexpected byte with no running byte. (${c})`);l=C.data[C.data.currentIndex++]}let m=Xs(l),f;switch(m){case-1:f=0;break;case-2:l=C.data[C.data.currentIndex++],f=mA(C.data);break;case-3:f=mA(C.data);break;default:f=Ws[l>>4],B=l;break}let S=new N(f);S.set(C.data.slice(C.data.currentIndex,C.data.currentIndex+f),0);let F=new YA(h,l,S);i.push(F),C.data.currentIndex+=f}this.tracks.push(i),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,I.info,I.value,I.info,I.value)}p("%cAll tracks parsed correctly!",I.recognized),this._parseInternal(),q(),p(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}%c, total seconds time: %c${this.duration}`,I.info,I.recognized,I.info,I.recognized)}_readMIDIChunk(A){let t={};t.type=AA(A,4),t.size=KA(A,4),t.data=new N(t.size);let n=A.slice(A.currentIndex,A.currentIndex+t.size);return t.data.set(n,0),A.currentIndex+=t.size,t}};var st={consoleColors:I,SpessaSynthInfo:p,SpessaSynthWarn:J,SpessaSynthGroupCollapsed:uA,SpessaSynthGroupEnd:q,readBytesAsUintBigEndian:KA,readLittleEndian:b,readBytesAsString:AA,readVariableLengthQuantity:mA,inflateSync:qt};var Ss=st.consoleColors;var RA={midiMessage:0,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customCcChange:14,debugMessage:15,setMasterParameter:17,setDrums:18,transpose:19,highPerformanceMode:20,lockController:21,sequencerSpecific:22,requestSynthesizerSnapshot:23,setLogLevel:24,keyModifierManager:25,setEffectsGain:26,destroyWorklet:27},te={channelPropertyChange:0,eventCall:1,masterParameterChange:2,sequencerSpecific:3,synthesizerSnapshot:4,isFullyInitialized:5,soundfontError:6};var ti="spessasynth-worklet-processor";var Mn={addMapping:0,deleteMapping:1,clearMappings:2};var Pt={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var St={backwards:0,forwards:1,shuffleOn:2,shuffleOff:3,index:4},ne={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10,setPreservePlaybackState:11},Be={midiEvent:0,songChange:1,timeChange:2,pause:3,getMIDI:4,midiError:5,metaEvent:6,loopCountChange:7,songListChange:8};function ni(e,A){e===void 0&&(e={});for(let t in A)A.hasOwnProperty(t)&&!(t in e)&&(e[t]=A[t]);return e}var si={skipToFirstNoteOn:!0,autoPlay:!0,preservePlaybackState:!1,initialPlaybackRate:1};var xn=class extends tt{isEmbedded=!1;constructor(A){super(),this._copyFromSequence(A),this.isEmbedded=A.embeddedSoundFont!==void 0}},im={duration:99999,firstNoteOn:0,loop:{start:0,end:123456},lastVoiceEventTick:123456,lyrics:[],copyright:"",midiPorts:[],midiPortChannelOffsets:[],tracksAmount:0,tempoChanges:[{ticks:0,tempo:120}],fileName:"NOT_LOADED.mid",midiName:"Loading...",rawMidiName:new Uint8Array([76,111,97,100,105,110,103,46,46,46]),usedChannelsOnTrack:[],timeDivision:0,keyRange:{min:0,max:127},isEmbedded:!1,RMIDInfo:{},bankOffset:0,midiNameUsesFileName:!1,format:0};var Ds=class extends AudioWorkletProcessor{alive=!0;oneOutputMode=!1;constructor(A){super();let t=A.processorOptions;this.oneOutputMode=t.midiChannels===1;let n=(g,i)=>{this.postMessageToMainThread({messageType:g,messageData:i})},s=t?.startRenderingData,o=s?.snapshot;this.synthesizer=new LA(sampleRate,{effectsEnabled:!this.oneOutputMode,enableEventSystem:t?.enableEventSystem,midiChannels:16,initialTime:currentTime}),this.synthesizer.onEventCall=(g,i)=>{n(te.eventCall,{eventName:g,eventData:i})},this.synthesizer.onChannelPropertyChange=(g,i)=>n(te.channelPropertyChange,[i,g]),this.synthesizer.onMasterParameterChange=(g,i)=>n(te.masterParameterChange,[g,i]);let r=$e(t.soundfont);this.synthesizer.soundfontManager.reloadManager(r),this.synthesizer.processorInitialized.then(()=>{this.sequencer=new wA(this.synthesizer);let g=(i,C)=>{this.postMessageToMainThread({messageType:te.sequencerSpecific,messageData:{messageType:i,messageData:C}})};if(this.port.onmessage=i=>this.handleMessage(i.data),this.sequencer.onMIDIMessage=i=>{g(Be.midiEvent,i)},this.sequencer.onTimeChange=i=>{g(Be.timeChange,i)},this.sequencer.onPlaybackStop=i=>{g(Be.pause,i)},this.sequencer.onSongChange=(i,C)=>{g(Be.songChange,[i,C])},this.sequencer.onMetaEvent=(i,C)=>{g(Be.metaEvent,[i,C])},this.sequencer.onLoopCountChange=i=>{g(Be.loopCountChange,i)},this.sequencer.onSongListChange=i=>{let C=i.map(B=>new xn(B));this.postMessageToMainThread({messageType:te.sequencerSpecific,messageData:{messageType:Be.songListChange,messageData:C}})},o!==void 0&&this.synthesizer.applySynthesizerSnapshot(o),s&&(st.SpessaSynthInfo("%cRendering enabled! Starting render.",Ss.info),s.parsedMIDI)){s?.loopCount!==void 0?(this.sequencer.loopCount=s?.loopCount,this.sequencer.loop=!0):this.sequencer.loop=!1,this.synthesizer.voiceCap=1/0;let i=ni(s.sequencerOptions,si);this.sequencer.skipToFirstNoteOn=i.skipToFirstNoteOn,this.sequencer.preservePlaybackState=i.preservePlaybackState,this.sequencer.playbackRate=i.initialPlaybackRate;try{this.sequencer.loadNewSongList([s.parsedMIDI])}catch(C){console.error(C),g(Be.midiError,C)}}this.postReady()})}postReady(){this.postMessageToMainThread({messageType:te.isFullyInitialized,messageData:void 0})}postMessageToMainThread(A){this.port.postMessage(A)}handleMessage(A){let t=A.messageData,n=A.channelNumber,s;if(n>=0&&(s=this.synthesizer.midiAudioChannels[n],s===void 0)){st.SpessaSynthWarn(`Trying to access channel ${n} which does not exist... ignoring!`);return}switch(A.messageType){case RA.midiMessage:this.synthesizer.processMessage(...t);break;case RA.customCcChange:s.setCustomController(t[0],t[1]);break;case RA.ccReset:n===-1?this.synthesizer.resetAllControllers():s.resetControllers();break;case RA.setChannelVibrato:if(n===-1)for(let m=0;m<this.synthesizer.midiAudioChannels.length;m++){let f=this.synthesizer.midiAudioChannels[m];t.rate===-1?f.disableAndLockGSNRPN():f.setVibrato(t.depth,t.rate,t.delay)}else t.rate===-1?s.disableAndLockGSNRPN():s.setVibrato(t.depth,t.rate,t.delay);break;case RA.stopAll:n===-1?this.synthesizer.stopAllChannels(t===1):s.stopAllNotes(t===1);break;case RA.killNotes:this.synthesizer.voiceKilling(t);break;case RA.muteChannel:s.muteChannel(t);break;case RA.addNewChannel:this.synthesizer.createMidiChannel(!0);break;case RA.debugMessage:console.debug(this.synthesizer);break;case RA.setMasterParameter:let o=t[0],r=t[1];this.synthesizer.setMasterParameter(o,r);break;case RA.setDrums:s.setDrums(t);break;case RA.transpose:n===-1?this.synthesizer.transposeAllChannels(t[0],t[1]):s.transposeChannel(t[0],t[1]);break;case RA.highPerformanceMode:this.synthesizer.highPerformanceMode=t;break;case RA.lockController:t[0]===-1?s.setPresetLock(t[1]):s.lockedControllers[t[0]]=t[1];break;case RA.sequencerSpecific:let g=this.sequencer,i=t.messageData;switch(t.messageType){default:break;case ne.loadNewSongList:try{let F=i[0].map(D=>D.duration?D:new Vt(D.binary,D.altName));g.loadNewSongList(F,i[1])}catch(S){console.error(S),this.postMessageToMainThread({messageType:te.sequencerSpecific,messageData:{messageType:Be.midiError,messageData:S}})}break;case ne.pause:g.pause();break;case ne.play:g.play(i);break;case ne.stop:g.stop();break;case ne.setTime:g.currentTime=i;break;case ne.changeMIDIMessageSending:g.sendMIDIMessages=i;break;case ne.setPlaybackRate:g.playbackRate=i;break;case ne.setLoop:let[m,f]=i;g.loop=m,f===-1?g.loopCount=1/0:g.loopCount=f;break;case ne.changeSong:switch(i[0]){case St.forwards:g.nextSong();break;case St.backwards:g.previousSong();break;case St.shuffleOff:g.shuffleMode=!1,g.songIndex=g.shuffledSongIndexes[g.songIndex];break;case St.shuffleOn:g.shuffleMode=!0,g.shuffleSongIndexes(),g.songIndex=0,g.loadCurrentSong();break;case St.index:g.songIndex=i[1],g.loadCurrentSong();break}break;case ne.getMIDI:this.postMessageToMainThread({messageType:te.sequencerSpecific,messageData:{messageType:Be.getMIDI,messageData:g.midiData}});break;case ne.setSkipToFirstNote:g.skipToFirstNoteOn=i;break;case ne.setPreservePlaybackState:g.preservePlaybackState=i}break;case RA.soundFontManager:try{let m=this.synthesizer.soundfontManager,f=t[0],S=t[1],F;switch(f){case Pt.addNewSoundFont:F=$e(S[0]),m.addNewSoundFont(F,S[1],S[2]),this.postMessageToMainThread({messageType:te.isFullyInitialized,messageData:void 0});break;case Pt.reloadSoundFont:F=$e(S),m.reloadManager(F),this.postMessageToMainThread({messageType:te.isFullyInitialized,messageData:void 0});break;case Pt.deleteSoundFont:m.deleteSoundFont(S);break;case Pt.rearrangeSoundFonts:m.rearrangeSoundFonts(S)}}catch(m){this.postMessageToMainThread({messageType:te.soundfontError,messageData:m})}break;case RA.keyModifierManager:let B=t[0],h=this.synthesizer.keyModifierManager,c=t[1];switch(B){default:return;case Mn.addMapping:h.addMapping(...c);break;case Mn.clearMappings:h.clearMappings();break;case Mn.deleteMapping:h.deleteMapping(...c)}break;case RA.requestSynthesizerSnapshot:let l=At.createSynthesizerSnapshot(this.synthesizer);this.postMessageToMainThread({messageType:te.synthesizerSnapshot,messageData:l});break;case RA.setLogLevel:Pn(t[0],t[1],t[2],t[3]);break;case RA.setEffectsGain:this.synthesizer.reverbGain=t[0],this.synthesizer.chorusGain=t[1];break;case RA.destroyWorklet:this.alive=!1,this.synthesizer.destroySynthProcessor(),delete this.synthesizer,delete this.sequencer.midiData,delete this.sequencer;break;default:st.SpessaSynthWarn("Unrecognized event:",t);break}}process(A,t){if(!this.alive)return!1;if(this.sequencer.processTick(),this.oneOutputMode){let n=t[0],s=[];for(let o=0;o<32;o+=2)s.push([n[o],n[o+1]]);this.synthesizer.renderAudioSplit([],[],s)}else this.synthesizer.renderAudioSplit(t[0],t[1],t.slice(2));return!0}};registerProcessor(ti,Ds);st.SpessaSynthInfo("%cProcessor successfully registered!",Ss.recognized);
22
22
  //# sourceMappingURL=worklet_processor.min.js.map