diff --git a/package.json b/package.json index 60ef8730..d3724d62 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "SpessaSynth", - "version": "3.16.1", + "version": "3.16.2", "type": "module", "scripts": { "start": "node src/website/server/server.js", diff --git a/src/spessasynth_lib/sequencer/worklet_sequencer/song_control.js b/src/spessasynth_lib/sequencer/worklet_sequencer/song_control.js index 26968098..ef05faab 100644 --- a/src/spessasynth_lib/sequencer/worklet_sequencer/song_control.js +++ b/src/spessasynth_lib/sequencer/worklet_sequencer/song_control.js @@ -68,7 +68,7 @@ export function loadNewSequence(parsedMidi) if(this.synth.overrideSoundfont) { // clean up the embedded soundfont - this.synth.clearSoundFont(); + this.synth.clearSoundFont(true, true); } SpessaSynthGroupCollapsed("%cPreloading samples...", consoleColors.info); // smart preloading: load only samples used in the midi! diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index 4330797c..865d1f2b 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -10,4 +10,4 @@ var Yt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>( `}};function OA(e,A,t,s,n){return e<<10|A<<9|t<<8|s<<7|n}var tt=960,st=fA.concave,ts=[new EA({srcEnum:OA(st,0,1,0,K.noteOnVelocity),dest:B.initialAttenuation,amt:tt,secSrcEnum:0,transform:0}),new EA({srcEnum:129,dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(st,0,1,1,S.mainVolume),dest:B.initialAttenuation,amt:tt,secSrcEnum:0,transform:0}),new EA({srcEnum:13,dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new EA({srcEnum:526,dest:B.fineTune,amt:12700,secSrcEnum:16,transform:0}),new EA({srcEnum:650,dest:B.pan,amt:1e3,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(st,0,1,1,S.expressionController),dest:B.initialAttenuation,amt:tt,secSrcEnum:0,transform:0}),new EA({srcEnum:219,dest:B.reverbEffectsSend,amt:200,secSrcEnum:0,transform:0}),new EA({srcEnum:221,dest:B.chorusEffectsSend,amt:200,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(fA.linear,0,0,0,K.polyPressure),dest:B.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(fA.linear,0,0,1,S.effects2Depth),dest:B.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(fA.linear,1,0,1,S.releaseTime),dest:B.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new EA({srcEnum:OA(fA.linear,1,0,1,S.brightness),dest:B.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0})];function nt(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new EA(e.chunkData));return A}var ot=class{constructor(A,t){this.generatorZoneStartIndex=q(A,2),this.modulatorZoneStartIndex=q(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.zoneID=t,this.keyRange={min:0,max:127},this.velRange={min:0,max:127},this.isGlobal=!0,this.useCount=0,this.generators=[],this.modulators=[]}deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;ts.generatorType===B.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===B.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===B.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ss(e,A,t,s){let n=[],o=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let C=new ot(e.chunkData,o);if(n.length>0){let a=C.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,Q=C.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(a,Q),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(t),n[n.length-1].getSample(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(C),o++}return n.length>1&&n.pop(),n}var It=class{constructor(A,t){this.generatorZoneStartIndex=q(A,2),this.modulatorZoneStartIndex=q(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.zoneID=t,this.keyRange={min:0,max:127},this.velRange={min:0,max:127},this.isGlobal=!0,this.generators=[],this.modulators=[]}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}deleteZone(){this.isGlobal||this.instrument.removeUseCount()}getGenerators(A){for(let t=this.generatorZoneStartIndex;ts.generatorType===B.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===B.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===B.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function ns(e,A,t,s){let n=[],o=0;for(;e.chunkData.length>e.chunkData.currentIndex;){let C=new It(e.chunkData,o);if(n.length>0){let a=C.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,Q=C.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(a,Q),n[n.length-1].getGenerators(A),n[n.length-1].getModulators(t),n[n.length-1].getInstrument(s),n[n.length-1].getKeyRange(),n[n.length-1].getVelRange()}n.push(C),o++}return n.length>1&&n.pop(),n}var rt=class{constructor(A){this.presetName=X(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=q(A.chunkData,2),this.bank=q(A.chunkData,2),this.presetZoneStartIndex=q(A.chunkData,2),this.presetZonesAmount=0,this.presetZones=[],this.sampleIDOffset=0,this.foundSamplesAndGenerators=[];for(let t=0;t<128;t++)this.foundSamplesAndGenerators[t]=[];this.library=q(A.chunkData,4),this.genre=q(A.chunkData,4),this.morphology=q(A.chunkData,4)}getPresetZones(A,t){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;sA.deleteZone()),this.presetZones.length=0}deleteZone(A){this.presetZones[A].deleteZone(),this.presetZones.splice(A,1)}preload(A,t){for(let s=A;s{o.sample.isSampleLoaded||o.sample.getAudioData()})}preloadSpecific(A,t){this.getSamplesAndGenerators(A,t).forEach(s=>{s.sample.isSampleLoaded||s.sample.getAudioData()})}getSamplesAndGenerators(A,t){let s=this.foundSamplesAndGenerators[A][t];if(s)return s;if(this.presetZones.length<1)return[];function n(d,m,l){return l>=d&&l<=m}function o(d,m){return d.modulatorSource===m.modulatorSource&&d.modulatorDestination===m.modulatorDestination&&d.modulationSecondarySrc===m.modulationSecondarySrc&&d.transformType===m.transformType}function C(d,m){d.push(...m.filter(l=>!d.find(H=>H.generatorType===l.generatorType)))}function a(d,m){d.push(...m.filter(l=>!d.find(H=>o(l,H))))}let Q=[],h=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],u=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(d=>n(d.keyRange.min,d.keyRange.max,A)&&n(d.velRange.min,d.velRange.max,t)&&!d.isGlobal).forEach(d=>{if(d.instrument.instrumentZones.length<1)return;let m=d.generators,l=d.modulators,H=d.instrument.instrumentZones[0].isGlobal?[...d.instrument.instrumentZones[0].generators]:[],k=d.instrument.instrumentZones[0].isGlobal?[...d.instrument.instrumentZones[0].modulators]:[];d.instrument.instrumentZones.filter(U=>n(U.keyRange.min,U.keyRange.max,A)&&n(U.velRange.min,U.velRange.max,t)&&!U.isGlobal).forEach(U=>{let b=[...U.generators],_=[...U.modulators];C(m,h),C(b,H),a(l,u),a(_,k),a(_,ts);let Y=[..._];for(let r=0;ro($,O));P!==-1?Y[P]=Y[P].sumTransform($):Y.push($)}Q.push({instrumentGenerators:b,presetGenerators:m,modulators:Y,sample:U.sample,sampleID:U.generators.find(r=>r.generatorType===B.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=Q,Q}};function os(e,A){let t=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let s=new rt(e);if(t.length>0){let n=s.presetZoneStartIndex-t[t.length-1].presetZoneStartIndex;t[t.length-1].getPresetZones(n,A)}t.push(s)}return t.length>1&&t.pop(),t}function Is(){let e=4;for(let s of this.instruments)e+=s.instrumentZones.reduce((n,o)=>(o.generators=o.generators.filter(C=>C.generatorType!==B.sampleID&&C.generatorType!==B.keyRange&&C.generatorType!==B.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:B.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:B.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:B.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+n),0);let A=new N(e),t=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=t;for(let o of n.generators)G(A,o.generatorType),G(A,o.generatorValue),t++}return CA(A,0),W(new V("igen",A.length,A))}function rs(e,A,t,s,n){let o=this.samples.map((h,u)=>{t&&h.compressSample(s,n);let f=h.getRawData();return p(`%cEncoded sample %c${u}. ${h.sampleName}%c of %c${this.samples.length}`,g.info,g.recognized,g.info,g.recognized),f}),C=this.samples.reduce((h,u,f)=>h+o[f].length+46,0),a=new N(C);this.samples.forEach((h,u)=>{let f=o[u],d,m,l=f.length;h.isCompressed?(d=a.currentIndex,m=d+f.length):(d=a.currentIndex/2,m=d+f.length/2,l+=46),e.push(d),a.set(f,a.currentIndex),a.currentIndex+=l,A.push(m)});let Q=W(new V("smpl",a.length,a),new N([115,100,116,97]));return W(new V("LIST",Q.length,Q))}function is(e,A){let s=new N(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{mA(s,n.sampleName,20);let C=e[o];CA(s,C);let a=A[o];CA(s,a);let Q=n.sampleLoopStartIndex/2+C,h=n.sampleLoopEndIndex/2+C;n.isCompressed&&(Q-=C,h-=C),CA(s,Q),CA(s,h),CA(s,n.sampleRate),s[s.currentIndex++]=n.samplePitch,s[s.currentIndex++]=n.samplePitchCorrection,G(s,n.sampleLink),G(s,n.sampleType)}),mA(s,"EOS",46),W(new V("shdr",s.length,s))}function gs(){let e=10;for(let s of this.instruments)e+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new N(e),t=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=t;for(let o of n.modulators)G(A,o.modulatorSource),G(A,o.modulatorDestination),G(A,o.transformAmount),G(A,o.modulationSecondarySrc),G(A,o.transformType),t++}return jA(A,0,10),W(new V("imod",A.length,A))}function as(){let e=this.instruments.reduce((o,C)=>C.instrumentZones.length*4+o,4),A=new N(e),t=0,s=0,n=0;for(let o of this.instruments){o.instrumentZoneIndex=t;for(let C of o.instrumentZones)C.zoneID=t,G(A,s),G(A,n),s+=C.generators.length,n+=C.modulators.length,t++}return G(A,s),G(A,n),W(new V("ibag",A.length,A))}function Cs(){let e=this.instruments.length*22+22,A=new N(e),t=0,s=0;for(let n of this.instruments)mA(A,n.instrumentName,20),G(A,t),t+=n.instrumentZones.length,n.instrumentID=s,s++;return mA(A,"EOI",20),G(A,t),W(new V("inst",A.length,A))}function Es(){let e=4;for(let s of this.presets)e+=s.presetZones.reduce((n,o)=>(o.generators=o.generators.filter(C=>C.generatorType!==B.instrument&&C.generatorType!==B.keyRange&&C.generatorType!==B.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:B.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:B.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:B.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+n),0);let A=new N(e),t=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=t;for(let o of n.generators)G(A,o.generatorType),G(A,o.generatorValue);t+=n.generators.length}return G(A,0),G(A,0),W(new V("pgen",A.length,A))}function Bs(){let e=10;for(let s of this.presets)e+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new N(e),t=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=t;for(let o of n.modulators)G(A,o.modulatorSource),G(A,o.modulatorDestination),G(A,o.transformAmount),G(A,o.modulationSecondarySrc),G(A,o.transformType),t++}return jA(A,0,10),W(new V("pmod",A.length,A))}function Qs(){let e=this.presets.reduce((o,C)=>C.presetZones.length*4+o,4),A=new N(e),t=0,s=0,n=0;for(let o of this.presets){o.presetZoneStartIndex=t;for(let C of o.presetZones)C.zoneID=t,G(A,s),G(A,n),s+=C.generators.length,n+=C.modulators.length,t++}return G(A,s),G(A,n),W(new V("pbag",A.length,A))}function hs(){let e=this.presets.length*38+38,A=new N(e),t=0;for(let s of this.presets)mA(A,s.presetName,20),G(A,s.program),G(A,s.bank),G(A,t),CA(A,s.library),CA(A,s.genre),CA(A,s.morphology),t+=s.presetZones.length;return mA(A,"EOP",20),G(A,0),G(A,0),G(A,t),CA(A,0),CA(A,0),CA(A,0),W(new V("phdr",A.length,A))}var no={compress:!1,compressionQuality:.5,compressionFunction:void 0};function cs(e=no){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");TA("%cSaving soundfont...",g.info),p(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,g.info,g.recognized,g.info,g.recognized),p("%cWriting INFO...",g.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.compress&&(this.soundFontInfo.ifil="3.0");for(let[_,Y]of Object.entries(this.soundFontInfo))if(_==="ifil"||_==="iver"){let r=parseInt(Y.split(".")[0]),$=parseInt(Y.split(".")[1]),P=new N(4);G(P,r),G(P,$),A.push(W(new V(_,4,P)))}else{let r=new N(Y.length);mA(r,Y),A.push(W(new V(_,Y.length,r)))}let t=re([new N([73,78,70,79]),...A]),s=W(new V("LIST",t.length,t));p("%cWriting SDTA...",g.info);let n=[],o=[],C=rs.call(this,n,o,e?.compress,e?.compressionQuality||.5,e.compressionFunction);p("%cWriting PDTA...",g.info),p("%cWriting SHDR...",g.info);let a=is.call(this,n,o);p("%cWriting IGEN...",g.info);let Q=Is.call(this);p("%cWriting IMOD...",g.info);let h=gs.call(this);p("%cWriting IBAG...",g.info);let u=as.call(this);p("%cWriting INST...",g.info);let f=Cs.call(this),d=Es.call(this);p("%cWriting PMOD...",g.info);let m=Bs.call(this);p("%cWriting PBAG...",g.info);let l=Qs.call(this);p("%cWriting PHDR...",g.info);let H=hs.call(this),k=re([new N([112,100,116,97]),H,l,m,d,f,u,h,Q,a]),J=W(new V("LIST",k.length,k));p("%cWriting the output file...",g.info);let U=re([new N([115,102,98,107]),s,C,J]),b=W(new V("RIFF",U.length,U));return p(`%cSaved succesfully! Final file size: %c${b.length}`,g.info,g.recognized),AA(),b}var qA=class e{constructor(A){if(A.presets){this.presets=A.presets,this.soundFontInfo=A.info;return}if(this.dataArray=new N(A),_e("%cParsing SoundFont...",g.info),!this.dataArray)throw AA(),new TypeError("No data!");let t=oA(this.dataArray,!1);this.verifyHeader(t,"riff");let s=X(this.dataArray,4).toLowerCase();if(s!=="sfbk"&&s!=="sfpk")throw AA(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${s}"`);let n=s==="sfpk",o=oA(this.dataArray);for(this.verifyHeader(o,"list"),X(o.chunkData,4),this.soundFontInfo={};o.chunkData.length>o.chunkData.currentIndex;){let O=oA(o.chunkData),sA;switch(O.header.toLowerCase()){case"ifil":case"iver":sA=`${q(O.chunkData,2)}.${q(O.chunkData,2)}`;break;case"icmt":sA=X(O.chunkData,O.chunkData.length,void 0,!1);break;default:sA=X(O.chunkData,O.chunkData.length)}p(`%c"${O.header}": %c"${sA}"`,g.info,g.recognized),this.soundFontInfo[O.header]=sA}let C=oA(this.dataArray,!1);this.verifyHeader(C,"list"),this.verifyText(X(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",g.warn);let a=oA(this.dataArray,!1);this.verifyHeader(a,"smpl");let Q;if(n){p("%cSF2Pack detected, attempting to decode the smpl chunk...",g.info);try{Q=UA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+C.size-12)).data[0]}catch(O){throw AA(),new Error(`SF2Pack Ogg Vorbis decode error: ${O}`)}p(`%cDecoded the smpl chunk! Length: %c${Q.length}`,g.info,g.value)}else Q=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${C.size-12}`,g.info,g.value),this.dataArray.currentIndex+=C.size-12,p("%cLoading preset data chunk...",g.warn);let h=oA(this.dataArray);this.verifyHeader(h,"list"),X(h.chunkData,4);let u=oA(h.chunkData);this.verifyHeader(u,"phdr");let f=oA(h.chunkData);this.verifyHeader(f,"pbag");let d=oA(h.chunkData);this.verifyHeader(d,"pmod");let m=oA(h.chunkData);this.verifyHeader(m,"pgen");let l=oA(h.chunkData);this.verifyHeader(l,"inst");let H=oA(h.chunkData);this.verifyHeader(H,"ibag");let k=oA(h.chunkData);this.verifyHeader(k,"imod");let J=oA(h.chunkData);this.verifyHeader(J,"igen");let U=oA(h.chunkData);this.verifyHeader(U,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples=$t(U,Q,!n);let b=At(J),_=nt(k),Y=ss(H,b,_,this.samples);this.instruments=es(l,Y);let r=At(m),$=nt(d),P=ns(f,r,$,this.instruments);this.presets=os(u,P),this.presets.sort((O,sA)=>O.program-sA.program+(O.bank-sA.bank)),p(`%cParsing finished! %c"${this.soundFontInfo.INAM}"%c has %c${this.presets.length} %cpresets, %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,g.info,g.recognized,g.info,g.recognized,g.info,g.recognized,g.info,g.recognized,g.info),AA(),n&&delete this.dataArray}removeUnusedElements(){this.instruments.forEach(A=>{A.useCount<1&&A.instrumentZones.forEach(t=>{t.isGlobal||t.sample.useCount--})}),this.instruments=this.instruments.filter(A=>A.useCount>0),this.samples=this.samples.filter(A=>A.useCount>0)}deleteInstrument(A){if(A.useCount>0)throw new Error(`Cannot delete an instrument that has ${A.useCount} usages.`);this.instruments.splice(this.instruments.indexOf(A),1),A.deleteInstrument(),this.removeUnusedElements()}deleteSample(A){if(A.useCount>0)throw new Error(`Cannot delete sample that has ${A.useCount} usages.`);this.samples.splice(this.samples.indexOf(A),1),this.removeUnusedElements()}deletePreset(A){A.deletePreset(),this.presets.splice(this.presets.indexOf(A),1),this.removeUnusedElements()}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw AA(),new SyntaxError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw AA(),new SyntaxError(`Invalid soundFont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}getPresetNoFallback(A,t){return this.presets.find(s=>s.bank===A&&s.program===t)}setSampleIDOffset(A){this.presets.forEach(t=>t.sampleIDOffset=A)}getPreset(A,t){let s=this.presets.find(n=>n.bank===A&&n.program===t);return s||(s=this.presets.find(n=>n.program===t&&n.bank!==128),A===128&&(s=this.presets.find(n=>n.bank===128&&n.program===t),s||(s=this.presets.find(n=>n.bank===128))),s&&L(`%cPreset ${A}.${t} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,g.warn,g.recognized)),s||(L(`Preset ${t} not found. Defaulting to`,this.presets[0].presetName),s=this.presets[0]),s}getPresetByName(A){let t=this.presets.find(s=>s.presetName===A);return t||(L("Preset not found. Defaulting to:",this.presets[0].presetName),t=this.presets[0]),t}static mergeSoundfonts(...A){let t=A.shift(),s=t.presets;for(;A.length;)A.shift().presets.forEach(o=>{s.find(C=>C.bank===o.bank&&C.program===o.program)===void 0&&s.push(o)});return new e({presets:s,info:t.soundFontInfo})}};qA.prototype.write=cs;var FA={loadNewSongList:0,pause:1,stop:2,play:3,setTime:4,changeMIDIMessageSending:5,setPlaybackRate:6,setLoop:7,changeSong:8,getMIDI:9,setSkipToFirstNote:10},pA={midiEvent:0,songChange:1,textEvent:2,timeChange:3,pause:4,getMIDI:5,midiError:6};function KA(e,A){let t=0;for(let s=8*(A-1);s>=0;s-=8)t|=e[e.currentIndex++]<>>0}function ls(e,A){if(this.ignoreEvents)return;if(this.sendMIDIMessages&&e.messageStatusByte>=128){this.sendMIDIMessage([e.messageStatusByte,...e.messageData]);return}let t=ie(e.messageStatusByte),s=this.midiPortChannelOffsets[this.midiPorts[A]]||0;switch(t.channel+=s,t.status){case y.noteOn:let n=e.messageData[1];if(n>0)this.synth.noteOn(t.channel,e.messageData[0],n),this.playingNotes.push({midiNote:e.messageData[0],channel:t.channel,velocity:n,startTime:this.currentTime});else{this.synth.noteOff(t.channel,e.messageData[0]);let C=this.playingNotes.findIndex(a=>a.midiNote===e.messageData[0]&&a.channel===t.channel);C!==-1&&this.playingNotes.splice(C,1)}break;case y.noteOff:this.synth.noteOff(t.channel,e.messageData[0]);let o=this.playingNotes.findIndex(C=>C.midiNote===e.messageData[0]&&C.channel===t.channel);o!==-1&&this.playingNotes.splice(o,1);break;case y.pitchBend:this.synth.pitchWheel(t.channel,e.messageData[1],e.messageData[0]);break;case y.controllerChange:this.synth.controllerChange(t.channel,e.messageData[0],e.messageData[1]);break;case y.programChange:this.synth.programChange(t.channel,e.messageData[0]);break;case y.polyPressure:this.synth.polyPressure(t.channel,e.messageData[0],e.messageData[1]);break;case y.channelPressure:this.synth.channelPressure(t.channel,e.messageData[0]);break;case y.systemExclusive:this.synth.systemExclusive(e.messageData,s);break;case y.setTempo:this.oneTickToSeconds=60/(oo(e)*this.midiData.timeDivision),this.oneTickToSeconds===0&&(this.oneTickToSeconds=60/(120*this.midiData.timeDivision),L("invalid tempo! falling back to 120 BPM"));break;case y.timeSignature:case y.endOfTrack:case y.midiChannelPrefix:case y.songPosition:case y.activeSensing:case y.keySignature:break;case y.text:case y.lyric:case y.copyright:case y.trackName:case y.marker:case y.cuePoint:case y.instrumentName:this.post(pA.textEvent,[e.messageData,t.status]);break;case y.midiPort:this.assignMIDIPort(A,e.messageData[0]);break;case y.reset:this.synth.stopAllChannels(),this.synth.resetAllControllers();break;default:L(`%cUnrecognized Event: %c${e.messageStatusByte}%c status byte: %c${Object.keys(y).find(C=>y[C]===t.status)}`,g.warn,g.unrecognized,g.warn,g.value);break}}function fs(){for(let e=0;e<16;e++)this.synth.createWorkletChannel(!0),e===wA&&this.synth.setDrums(this.synth.workletProcessorChannels.length-1,!0)}function oo(e){return e.messageData.currentIndex=0,6e7/KA(e.messageData,3)}function ds(){let e=this.currentTime;for(;this.playedTime1&&this.nextSong();return}let s=this.tracks[A][this.eventIndex[A]];if(this.playedTime+=this.oneTickToSeconds*(s.ticks-t.ticks),this.midiData.loop.end<=t.ticks&&this.loop){this.setTimeTicks(this.midiData.loop.start);return}else if(e>=this.duration){if(this.loop){this.setTimeTicks(this.midiData.loop.start);return}this.eventIndex[A]--,this.pause(!0),this.songs.length>1&&this.nextSong();return}}}function us(){let e=0,A=1/0;return this.tracks.forEach((t,s)=>{this.eventIndex[s]>=t.length||t[this.eventIndex[s]].ticksa===S.dataDecrement||a===S.dataIncrement||a===S.dataEntryMsb||a===S.dataDecrement||a===S.lsbForControl6DataEntry||a===S.RPNLsb||a===S.RPNMsb||a===S.NRPNLsb||a===S.NRPNMsb||a===S.bankSelect||a===S.lsbForControl0BankSelect||a===S.resetAllControllers,C=[];for(let a=0;a=A)break}else if(this.playedTime>=e)break;let h=ie(Q.messageStatusByte),u=h.channel+(this.midiPortChannelOffsets[this.midiPorts[a]]||0);switch(h.status){case y.noteOn:case y.noteOff:case y.keySignature:break;case y.pitchBend:s[u]=Q.messageData[1]<<7|Q.messageData[0];break;case y.programChange:let d=n[u];d.program=Q.messageData[0],d.actualBank=d.bank;break;case y.controllerChange:let m=Q.messageData[0];if(o(m))if(this.sendMIDIMessages)this.sendMIDIMessage([y.controllerChange|u%16,m,Q.messageData[1]]);else{let l=Q.messageData[1];if(m===S.bankSelect){n[u].bank=l;break}this.synth.controllerChange(u,m,l)}else C[u]===void 0&&(C[u]=Array.from(bA)),C[u][m]=Q.messageData[1];break;default:this._processEvent(Q,a);break}this.eventIndex[a]++,a=this._findFirstEventIndex();let f=this.tracks[a][this.eventIndex[a]];if(f===void 0)return this.stop(),!1;this.playedTime+=this.oneTickToSeconds*(f.ticks-Q.ticks)}if(this.sendMIDIMessages){for(let a=0;a>7]),C[a].forEach((Q,h)=>{Q!==bA[h]&&!o(h)&&this.sendMIDIMessage([y.controllerChange|a%16,h,Q])}),n[a].program>=0&&n[a].actualBank>=0){let Q=n[a].actualBank;this.sendMIDIMessage([y.controllerChange|a%16,S.bankSelect,Q]),this.sendMIDIMessage([y.programChange|a%16,n[a].program])}}else for(let a=0;a>7,s[a]&127),C[a]!==void 0&&C[a].forEach((Q,h)=>{Q!==bA[h]&&!o(h)&&this.synth.controllerChange(a,h,Q)}),n[a].program>=0&&n[a].actualBank>=0){let Q=n[a].actualBank;this.synth.controllerChange(a,S.bankSelect,Q),this.synth.programChange(a,n[a].program)}return!0}function ps(e=!1){if(this.midiData!==void 0){if(e){this.currentTime=0;return}if(this.currentTime>=this.duration){this.currentTime=0;return}if(this.paused&&(this._recalculateStartTime(this.pausedTime),this.pausedTime=void 0),!this.sendMIDIMessages){let A=this.currentTime;this.playingNotes.forEach(t=>{let s=t.startTime-A;this.synth.noteOn(t.channel,t.midiNote,t.velocity,!1,!0,currentTime+s)})}this.setProcessHandler()}}function De(e,A,t){if(A<=0)return 0;let s=e.find(o=>o.ticks>7!==1)break}return A}function Ds(e=!1){let A={midiControllers:new Int16Array(it),lockedControllers:Array(it).fill(!1),customControllers:new Float32Array(ks),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:BA.Idle,voices:[],sustainedVoices:[],cachedVoices:[],preset:this.defaultPreset,presetUsesOverride:!1,channelTransposeKeyShift:0,channelOctaveTuning:new Int8Array(12),channelVibrato:{delay:0,depth:0,rate:0},lockVibrato:!1,holdPedal:!1,isMuted:!1,drumChannel:!1,lockPreset:!1};for(let t=0;t<128;t++)A.cachedVoices.push([]);this.workletProcessorChannels.push(A),this.resetControllers(this.workletProcessorChannels.length-1),this.sendChannelProperties(),e&&this.callEvent("newchannel",void 0)}var IA=128,it=147,LA=new Int16Array(it).fill(0);LA[S.mainVolume]=12800;LA[S.expressionController]=16256;LA[S.pan]=8192;LA[S.releaseTime]=8192;LA[S.brightness]=8192;LA[S.effects1Depth]=5120;LA[IA+K.pitchWheel]=8192;LA[IA+K.pitchWheelRange]=256;var BA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},eA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},ks=Object.keys(eA).length,gt=new Float32Array(ks);gt[eA.modulationMultiplier]=1;var Fe={name:"INAM",album:"IPRD",artist:"IART",genre:"IGNR",picture:"IPIC",copyright:"ICOP",creationDate:"ICRD",comment:"ICMT",engineer:"IENG",software:"ISFT",encoding:"IENC",midiEncoding:"MENC",bankOffset:"DBNK"};var Re=class{constructor(A,t=""){TA("%cParsing MIDI File...",g.info);let s=new N(A),n;this.embeddedSoundFont=void 0,this.RMIDInfo=void 0,this.bankOffset=0,this.copyright="";let o=!1;this.midiName="",this.rawMidiName=new Uint8Array(0);let C=!1,a=X(s,4);if(s.currentIndex-=4,a==="RIFF"){s.currentIndex+=8;let l=X(s,4,void 0,!1);if(l!=="RMID")throw AA(),new SyntaxError(`Invalid RMIDI Header! Expected "RMID", got "${l}"`);let H=oA(s);if(H.header!=="data")throw AA(),new SyntaxError(`Invalid RMIDI Chunk header! Expected "data", got "${l}"`);for(n=H.chunkData;s.currentIndex<=s.length;){let k=s.currentIndex,J=oA(s,!0);if(J.header==="RIFF"){let U=X(J.chunkData,4);(U==="sfbk"||U==="sfpk")&&(p("%cFound embedded soundfont!",g.recognized),this.embeddedSoundFont=s.slice(k,k+J.size).buffer)}else if(J.header==="LIST"&&X(J.chunkData,4)==="INFO"){for(p("%cFound RMIDI INFO chunk!",g.recognized),this.RMIDInfo={};J.chunkData.currentIndex<=J.size;){let b=oA(J.chunkData,!0);this.RMIDInfo[b.header]=b.chunkData}this.RMIDInfo.ICOP&&(o=!0,this.copyright=X(this.RMIDInfo.ICOP,this.RMIDInfo.ICOP.length)),this.RMIDInfo.INAM&&(this.rawMidiName=this.RMIDInfo[Fe.name],this.midiName=X(this.rawMidiName,this.rawMidiName.length,void 0,!1),C=!0),this.bankOffset=1,this.RMIDInfo[Fe.bankOffset]&&(this.bankOffset=q(this.RMIDInfo[Fe.bankOffset],2))}}}else n=s;let Q=this.readMIDIChunk(n);if(Q.type!=="MThd")throw AA(),new SyntaxError(`Invalid MIDI Header! Expected "MThd", got "${Q.type}"`);if(Q.size!==6)throw AA(),new RangeError(`Invalid MIDI header chunk size! Expected 6, got ${Q.size}`);this.format=KA(Q.data,2),this.tracksAmount=KA(Q.data,2),this.timeDivision=KA(Q.data,2),this.keyRange={min:127,max:0},this.lyrics=[],this.tempoChanges=[{ticks:0,tempo:120}];let h=null,u=null;this.lastVoiceEventTick=0,this.midiPorts=[];let f=0;this.midiPortChannelOffsets=[],this.usedChannelsOnTrack=[],this.tracks=[];for(let l=0;l0&&(b+=this.tracks[l-1][this.tracks[l-1].length-1].ticks);k.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=b),$=Kt[Y>>4],(Y&240)===y.noteOn){J.add(r);let dA=k.data[k.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,dA),this.keyRange.max=Math.max(this.keyRange.max,dA)}U=Y;break}let P=new N($),O=k.data.slice(k.data.currentIndex,k.data.currentIndex+$);k.data.currentIndex+=$,P.set(O,0);let sA=new _A(b,Y,P);switch(H.push(sA),r){case-2:switch(Y){case y.setTempo:this.tempoChanges.push({ticks:b,tempo:6e7/KA(O,3)});break;case y.marker:switch(X(P,P.length).trim().toLowerCase()){default:break;case"start":case"loopstart":h=b;break;case"loopend":u=b}P.currentIndex=0;break;case y.midiPort:let nA=P[0];this.midiPorts[l]=nA,this.midiPortChannelOffsets[nA]===void 0&&(this.midiPortChannelOffsets[nA]=f,f+=16);break;case y.copyright:o||(this.copyright+=X(P,P.length,void 0,!1)+` `);break;case y.lyric:this.lyrics.push(P)}break;case-3:if(aA(P.slice(0,7)).trim()==="41 10 45 12 10 00 00"){let dA=P.slice(7,O.length-3),nA=X(dA,dA.length)+` -`;this.copyright+=nA,p(`%cDecoded Roland SC message! %c${nA}`,g.recognized,g.value)}break;default:if((Y&240)===y.controllerChange)switch(P[0]){case 2:case 116:h=b;break;case 4:case 117:u===null?u=b:u=0;break}}}this.tracks.push(H),this.usedChannelsOnTrack.push(J),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,g.info,g.value,g.info,g.value)}let d=[];for(let l of this.tracks){let H=l.find(k=>(k.messageStatusByte&240)===y.noteOn);H&&d.push(H.ticks)}this.firstNoteOn=Math.min(...d),p(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}`,g.info,g.recognized),AA(),h!==null&&u===null?(h=this.firstNoteOn,u=this.lastVoiceEventTick):(h===null&&(h=this.firstNoteOn),(u===null||u===0)&&(u=this.lastVoiceEventTick));let m=0;for(let l of this.midiPorts)if(l!==-1){m=l;break}if(this.midiPorts=this.midiPorts.map(l=>l===-1?m:l),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.loop={start:h,end:u},!C)if(this.tracks.length>1){if(this.tracks[0].find(l=>l.messageStatusByte>=y.noteOn&&l.messageStatusByteH.messageStatusByte===y.trackName);l&&(this.rawMidiName=l.messageData,this.midiName=X(l.messageData,l.messageData.length,void 0,!1))}}else{let l=this.tracks[0].find(H=>H.messageStatusByte===y.trackName);l&&(this.rawMidiName=l.messageData,this.midiName=X(l.messageData,l.messageData.length,void 0,!1))}if(this.fileName=t,this.midiName=this.midiName.trim(),this.midiName.length===0){this.midiName=Jt(t),this.rawMidiName=new Uint8Array(this.midiName.length);for(let l=0;ln.ticksd>f?d:f),s=[];for(let f=0;f{C[l]>=m.length||m[C[l]].ticks0;){let f=Q(),d=e.tracks[f];if(C[f]>=d.length){a--;continue}let m=d[C[f]];if(C[f]++,m.messageStatusByte===y.midiPort){h[f]=m.messageData[0];continue}let l=m.messageStatusByte&240;if(l!==y.noteOn&&l!==y.controllerChange&&l!==y.programChange&&l!==y.systemExclusive)continue;let H=(m.messageStatusByte&15)+e.midiPortChannelOffsets[h[f]]||0,k=s[H];switch(l){case y.programChange:k.program=m.messageData[0],n(k);break;case y.controllerChange:if(m.messageData[0]!==S.bankSelect||u==="gs"&&k.drums)continue;let J=m.messageData[1],U=Math.max(0,J-e.bankOffset);if(u==="xg"){let Y=J===120||J===126||J===127;Y!==k.drums?(k.drums=Y,k.bank=k.drums?128:U,n(k)):k.bank=k.drums?128:U;continue}s[H].bank=U;break;case y.noteOn:if(m.messageData[1]===0)continue;n(k),o[k.string].add(`${m.messageData[0]}-${m.messageData[1]}`);break;case y.systemExclusive:if(m.messageData[0]!==65||m.messageData[2]!==66||m.messageData[3]!==18||m.messageData[4]!==64||!(m.messageData[5]&16)||m.messageData[6]!==21){m.messageData[0]===67&&m.messageData[2]===76&&m.messageData[5]===126&&m.messageData[6]===0&&(u="xg");continue}let b=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][m.messageData[5]&15]+e.midiPortChannelOffsets[h[f]],_=!!(m.messageData[7]>0&&m.messageData[5]>>4);k=s[b],k.drums=_,k.bank=_?128:0,n(k);break}}for(let f of Object.keys(o))o[f].size===0&&(p(`%cDetected change but no keys for %c${f}`,g.info,g.value),delete o[f]);return AA(),o}function Fs(e,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.lengthA.getAudioData());else{this.synth.overrideSoundfont&&this.synth.clearSoundFont(),TA("%cPreloading samples...",g.info);let A=ws(this.midiData,this.synth.soundfontManager);for(let[t,s]of Object.entries(A)){let n=parseInt(t.split(":")[0]),o=parseInt(t.split(":")[1]),C=this.synth.getPreset(n,o);p(`%cPreloading used samples on %c${C.presetName}%c...`,g.info,g.recognized,g.info);for(let a of s){let Q=a.split("-");C.preloadSpecific(parseInt(Q[0]),parseInt(Q[1]))}}AA()}this.tracks=this.midiData.tracks,this.midiPorts=this.midiData.midiPorts,this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this.midiData.midiPorts.forEach((A,t)=>{this.assignMIDIPort(t,A)}),this.duration=this.midiData.duration,this.firstNoteTime=De(this.midiData.tempoChanges,this.midiData.firstNoteOn,this.midiData.timeDivision),p(`%cTotal song time: ${We(Math.ceil(this.duration)).time}`,g.recognized),this.post(pA.songChange,[new ke(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(L(`%cVery short song: (${We(Math.round(this.duration)).time}). Disabling loop!`,g.warn),this.loop=!1),this.play(!0)}function Gs(e){this.songs=e.reduce((A,t)=>{if(t.duration)return A.push(t),A;try{A.push(new Re(t.binary,t.altName||""))}catch(s){return this.post(pA.midiError,s.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function xs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Ms(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}function Ns(e,A){switch(e){default:break;case FA.loadNewSongList:this.loadNewSongList(A);break;case FA.pause:this.pause();break;case FA.play:this.play(A);break;case FA.stop:this.stop();break;case FA.setTime:this.currentTime=A;break;case FA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case FA.setPlaybackRate:this.playbackRate=A;break;case FA.setLoop:this.loop=A;break;case FA.changeSong:A?this.nextSong():this.previousSong();break;case FA.getMIDI:this.post(pA.getMIDI,this.midiData);break;case FA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Us(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:lA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function bs(e){this.post(pA.midiEvent,e)}var rA=class{constructor(A){this.synth=A,this.ignoreEvents=!1,this.sendMIDIMessages=!1,this.eventIndex=[],this.songIndex=0,this.playedTime=0,this.pausedTime=void 0,this.absoluteStartTime=currentTime,this._playbackRate=1,this.playingNotes=[],this.loop=!0,this.midiData=void 0,this.midiPorts=[],this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this._skipToFirstNoteOn=!0}set playbackRate(A){let t=this.currentTime;this._playbackRate=A,this.currentTime=t}get currentTime(){return this.pausedTime?this.pausedTime:(currentTime-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&&ALs?440*Math.pow(2,(e-6900)/1200):Ct[~~e-Ge]}var Bt=-1660,Io=1600,Et=new Float32Array((Io-Bt)*100+1);for(let e=0;e.5?1:0,s?t*2-1:t;case fA.concave:return s?(t=t*2-1,t<0?1-$A[~~(t*-tA)]-1:$A[~~t*tA]):$A[~~(t*tA)];case fA.convex:return s?(t=t*2-1,t<0?1-Ae[~~(t*-tA)]-1:Ae[~~(t*tA)]):Ae[~~(t*tA)]}}var Qt=1,ht=new Float32Array(1e3);for(let e=0;e=e.sample.loopEnd;)s-=o;let a=~~s,Q=a+1;for(;Q>=e.sample.loopEnd;)Q-=o;let h=s-a,u=A[Q],f=A[a];t[C]=f+(u-f)*h,s+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=A.length&&(e.sample.end=A.length-1);for(let C=0;C=e.sample.end){e.finished=!0;return}let h=s-a,u=A[Q],f=A[a];t[C]=f+(u-f)*h,s+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=s}function Ys(e,A,t,s,n,o,C,a,Q){if(!isNaN(t[0])){if(C>0){let h=o[0],u=o[1];C=Math.min(C,1e3);let f=C/500,d=e*f,m=A*f;for(let l=0;l0){let h=a[0],u=a[1];Q=Math.min(Q,1e3);let f=Q/500,d=e*f,m=A*f;for(let l=0;l0)for(let h=0;h0)for(let h=0;h=A.length)return;a.state++;case 1:for(;Q=A.length)return}a.state++;case 2:for(;Q=A.length)return}a.state++;case 3:for(;Q=A.length)return}a.state++;case 4:for(;;){let u=a.sustainDb+C;if(a.currentAttenuationDb+=(u-a.currentAttenuationDb)*o,A[h]*=GA(a.currentAttenuationDb),++h>=A.length)return}}}var Vs={a0:0,a1:0,a2:0,a3:0,a4:0,x1:0,x2:0,y1:0,y2:0,reasonanceCb:0,reasonanceGain:1,cutoffCents:13500,cutoffHz:2e4};function Os(e,A,t){if(!(t>13499)){(e.filter.cutoffCents!==t||e.filter.reasonanceCb!==e.modulatedGenerators[B.initialFilterQ])&&(e.filter.cutoffCents=t,e.filter.reasonanceCb=e.modulatedGenerators[B.initialFilterQ],io(e));for(let s=0;s.45*sampleRate&&(e.filter.cutoffHz=.45*sampleRate);let A=e.filter.reasonanceCb/10-3.01;e.filter.reasonanceGain=GA(-1*A);let t=1/Math.sqrt(e.filter.reasonanceGain),s=2*Math.PI*e.filter.cutoffHz/sampleRate,n=Math.cos(s),o=Math.sin(s)/(2*e.filter.reasonanceGain),C=(1-n)*t,a=C/2,Q=a,h=1+o,u=-2*n,f=1-o;e.filter.a0=a/h,e.filter.a1=C/h,e.filter.a2=Q/h,e.filter.a3=u/h,e.filter.a4=f/h}var vs=Math.PI/2,Zs=.01;function Xs(e,A,t,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.releaseStartModEnv=A.currentModEnvValue,A.isInRelease=!0,ZA(A),A.volumeEnvelope.currentReleaseGain=GA(A.volumeEnvelope.currentAttenuationDb)),A.modulatedGenerators[B.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let C=A.targetKey,a=A.modulatedGenerators[B.fineTune]+e.customControllers[eA.channelTuning]+e.customControllers[eA.channelTransposeFine]+e.customControllers[eA.masterTuning]+e.channelOctaveTuning[A.midiNote%12],Q=A.modulatedGenerators[B.coarseTune]+e.customControllers[eA.channelTuningSemitones],h=this.tunings[e.preset.program]?.[C];h?.midiNote>=0&&(C=h.midiNote,a+=h.centTuning),a+=(C-A.sample.rootKey)*A.modulatedGenerators[B.scaleTuning];let u=A.modulatedGenerators[B.vibLfoToPitch];if(u!==0){let sA=A.startTime+QA(A.modulatedGenerators[B.delayVibLFO]),dA=ae(A.modulatedGenerators[B.freqVibLFO]),nA=xe(sA,dA,currentTime);a+=nA*(u*e.customControllers[eA.modulationMultiplier])}let f=A.modulatedGenerators[B.initialFilterFc],d=A.modulatedGenerators[B.modLfoToPitch],m=A.modulatedGenerators[B.modLfoToVolume],l=A.modulatedGenerators[B.modLfoToFilterFc],H=0;if(d+l+m!==0){let sA=A.startTime+QA(A.modulatedGenerators[B.delayModLFO]),dA=ae(A.modulatedGenerators[B.freqModLFO]),nA=xe(sA,dA,currentTime);a+=nA*(d*e.customControllers[eA.modulationMultiplier]),H=nA*m,f+=nA*l}if(e.channelVibrato.depth>0){let sA=xe(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);sA&&(a+=sA*e.channelVibrato.depth)}let k=A.modulatedGenerators[B.modEnvToPitch],J=A.modulatedGenerators[B.modEnvToFilterFc],U=Hs(A,currentTime);f+=U*J,a+=U*k;let b=~~(a+Q*100);b!==A.currentTuningCents&&(A.currentTuningCents=b,A.currentTuningCalculated=Math.pow(2,b/1200));let _=(Math.max(-500,Math.min(500,A.modulatedGenerators[B.pan]))+500)/1e3,Y=new Float32Array(t.length);Ts(A,this.workletDumpedSamplesList[A.sample.sampleID],Y),Os(A,Y,f),Ps(A,Y,currentTime,H,this.sampleTime,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(_-A.currentPan)*this.panSmoothingFactor;let r=Math.cos(vs*A.currentPan)*this.panLeft,$=Math.sin(vs*A.currentPan)*this.panRight,P=this.oneOutputMode?0:A.modulatedGenerators[B.reverbEffectsSend],O=this.oneOutputMode?0:A.modulatedGenerators[B.chorusEffectsSend];Ys(r,$,Y,t,s,n,P,o,O)}function go(e,A){let t=0;return e.drumChannel&&(t+=5),A.isInRelease&&(t-=5),t+=A.velocity/25,t-=A.volumeEnvelope.state,A.isInRelease&&(t-=5),t-=A.volumeEnvelope.currentAttenuationDb/50,t}function Ws(e){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=go(s,n);A.push({channel:s,voice:n,priority:o})}A.sort((s,n)=>s.priority-n.priority);let t=A.slice(0,e);for(let{channel:s,voice:n}of t){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function _s(e){e.releaseStartTime=currentTime,e.releaseStartTime-e.startTime=0&&(s=this.workletProcessorChannels[t]),e.messageType){case v.noteOn:this.noteOn(t,A[0],A[1],A[2]);break;case v.noteOff:this.noteOff(t,A);break;case v.pitchWheel:this.pitchWheel(t,A[0],A[1]);break;case v.ccChange:this.controllerChange(t,A[0],A[1],A[2]);break;case v.customcCcChange:s.customControllers[A[0]]=A[1];break;case v.killNote:this.killNote(t,A);break;case v.programChange:this.programChange(t,A[0],A[1]);break;case v.channelPressure:this.channelPressure(t,A);break;case v.polyPressure:this.polyPressure(t,A[0],A[1]);break;case v.ccReset:t===RA?this.resetAllControllers():this.resetControllers(t);break;case v.systemExclusive:this.systemExclusive(A);break;case v.setChannelVibrato:if(t===RA)for(let C=0;C{let t=(A.midiControllers[IA+K.pitchWheelRange]>>7)+(A.midiControllers[IA+K.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[IA+K.pitchWheel],pitchBendRangeSemitones:t,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:lA.channelProperties,messageData:e})}function ao(e,A,t){let s=e,n=A<<7|t;return e===127&&A===127&&t===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function An(e,A=0){let t=e[0];if(!(this.deviceID!==RA&&e[1]!==127&&this.deviceID!==e[1]))switch(t){default:L(`%cUnrecognized SysEx: %c${aA(e)}`,g.warn,g.unrecognized);break;case 126:case 127:switch(e[2]){case 4:let s;switch(e[3]){case 1:let n=e[5]<<7|e[4];this.setMIDIVolume(n/16384),p(`%cMaster Volume. Volume: %c${n}`,g.info,g.value);break;case 2:let C=((e[5]<<7|e[4])-8192)/8192;this.setMasterPan(C),p(`%cMaster Pan. Pan: %c${C}`,g.info,g.value);break;case 3:let a=(e[5]<<7|e[6])-8192;s=Math.floor(a/81.92),this.setMasterTuning(s),p(`%cMaster Fine Tuning. Cents: %c${s}`,g.info,g.value);break;case 4:s=(e[5]-64)*100,this.setMasterTuning(s),p(`%cMaster Coarse Tuning. Cents: %c${s}`,g.info,g.value);break;default:L(`%cUnrecognized MIDI Device Control Real-time message: %c${aA(e)}`,g.warn,g.unrecognized)}break;case 9:e[3]===1?(p("%cGM system on",g.info),this.system="gm"):e[3]===3?(p("%cGM2 system on",g.info),this.system="gm2"):(p("%cGM system off, defaulting to GS",g.info),this.system="gs");break;case 8:switch(e[3]){case 2:case 7:let n=4;e[3]===7&&n++;let o=e[n++],C=e[n++];for(let Q=0;Q>1&1)===1&&this.setOctaveTuning(15+A,a);for(let Q=0;Q<7;Q++)(e[5]>>Q&1)===1&&this.setOctaveTuning(7+Q+A,a);for(let Q=0;Q<7;Q++)(e[6]>>Q&1)===1&&this.setOctaveTuning(Q+A,a);p(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${a.join(" ")}`,g.info,g.value);break;default:L(`%cUnrecognized MIDI Tuning standard message: %c${aA(e)}`,g.warn,g.unrecognized);break}break;default:L(`%cUnrecognized MIDI Realtime/non realtime message: %c${aA(e)}`,g.warn,g.unrecognized)}break;case 65:if(e[2]===66&&e[3]===18){let s=e[7];if(e[6]===127){s===0?(p("%cGS system on",g.info),this.system="gs"):s===127&&(p("%cGS system off, switching to GM2",g.info),this.system="gm2");return}else if(e[4]===64){if((e[5]&16)>0){let n=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A;switch(e[6]){default:break;case 21:let o=s>0&&e[5]>>4;this.setDrums(n,o),p(`%cChannel %c${n}%c ${o?"is now a drum channel":"now isn't a drum channel"}%c via: %c${aA(e)}`,g.info,g.value,g.recognized,g.info,g.value);return;case 22:let C=s-64;this.transposeChannel(n,C),p(`%cChannel %c${n}%c pitch shift. Semitones %c${C}%c, with %c${aA(e)}`,g.info,g.recognized,g.info,g.value,g.info,g.value);return;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let a=s-64;p(`%cChannel %c${n}%c tuning. Cents %c${a}%c, with %c${aA(e)}`,g.info,g.recognized,g.info,g.value,g.info,g.value),this.setChannelTuning(n,a)}}else if(e[5]===0&&e[6]===6){p(`%cRoland GS Master Pan set to: %c${s}%c with: %c${aA(e)}`,g.info,g.value,g.info,g.value),this.setMasterPan((s-64)/64);return}else if(e[5]===0&&e[6]===5){let n=s-64;p(`%cRoland GS Master Key-Shift set to: %c${n}%c with: %c${aA(e)}`,g.info,g.value,g.info,g.value),this.setMasterTuning(n*100);return}else if(e[5]===0&&e[6]===4){p(`%cRoland GS Master Volume set to: %c${s}%c with: %c${aA(e)}`,g.info,g.value,g.info,g.value),this.setMIDIVolume(s/127);return}}L(`%cUnrecognized Roland %cGS %cSysEx: %c${aA(e)}`,g.warn,g.recognized,g.warn,g.unrecognized);return}else if(e[2]===22&&e[3]===18&&e[4]===16){this.setMIDIVolume(e[7]/100),p(`%cRoland Master Volume control set to: %c${e[7]}%c via: %c${aA(e)}`,g.info,g.value,g.info,g.value);return}else{L(`%cUnrecognized Roland SysEx: %c${aA(e)}`,g.warn,g.unrecognized);return}case 67:if(e[2]===76)if(e[3]===0&&e[4]===0)switch(e[5]){case 4:let s=e[6];this.setMIDIVolume(s/127),p(`%cXG master volume. Volume: %c${s}`,g.info,g.recognized);break;case 6:let n=e[6]-64;this.transposeAllChannels(n),p(`%cXG master transpose. Volume: %c${n}`,g.info,g.recognized);break;case 126:p("%cXG system on",g.info),this.system="xg";break}else if(e[3]===8){if(this.system!=="xg")return;let s=e[4]+A,n=e[6];switch(e[5]){case 1:this.controllerChange(s,S.bankSelect,n);break;case 2:this.controllerChange(s,S.lsbForControl0BankSelect,n);break;case 3:this.programChange(s,n);break;case 11:this.controllerChange(s,S.mainVolume,n);break;case 14:let o=n;o===0&&(o=Math.floor(Math.random()*127)),this.controllerChange(s,S.pan,o);break;case 19:this.controllerChange(s,S.effects1Depth,n);break;case 18:this.controllerChange(s,S.effects3Depth,n);break;default:L(`%cUnrecognized Yamaha XG Part Setup: %c${e[5].toString(16).toUpperCase()}`,g.warn,g.unrecognized)}}else this.system==="xg"&&L(`%cUnrecognized Yamaha XG SysEx: %c${aA(e)}`,g.warn,g.unrecognized);else this.system==="xg"&&L(`%cUnrecognized Yamaha SysEx: %c${aA(e)}`,g.warn,g.unrecognized);break}}var Me=[];function en(){Me=[]}function Co(e,A,t,s){Me[t]=!1,s({channel:e,sampleID:t,sampleData:A.getAudioData()}),Me[t]=!0}function Ce(e){if(e===null||typeof e!="object")return e;if(e instanceof Int16Array)return new Int16Array(e);let A=Array.isArray(e)?[]:{};for(let t in e)e.hasOwnProperty(t)&&(typeof e[t]=="object"&&e[t]!==null?A[t]=Ce(e[t]):e[t]instanceof Int16Array?A[t]=new Int16Array(e[t]):A[t]=e[t]);return A}function tn(e,A,t,s,n,o,C,a,Q=!1){let h,u=a[A][t];return u!==void 0?(h=u.map(Ce),h.forEach(f=>{f.startTime=n})):(h=s.getSamplesAndGenerators(A,t).reduce((f,d)=>{let m=d.sampleID+s.sampleIDOffset;if(Me[m]!==!0&&Co(e,d.sample,m,C),d.sample.sampleData===void 0)return L(`Discarding invalid sample: ${d.sample.sampleName}`),f;let l=new Int16Array(60);for(let r=0;r<60;r++)l[r]=As(r,d.presetGenerators,d.instrumentGenerators);l[B.initialAttenuation]=Math.floor(l[B.initialAttenuation]*.4);let H=d.sample.samplePitch;l[B.overridingRootKey]>-1&&(H=l[B.overridingRootKey]);let k=A;l[B.keyNum]>-1&&(k=l[B.keyNum]);let J=d.sample.sampleLoopStartIndex/2+(l[B.startloopAddrsOffset]+l[B.startloopAddrsCoarseOffset]*32768),U=d.sample.sampleLoopEndIndex/2+(l[B.endloopAddrsOffset]+l[B.endloopAddrsCoarseOffset]*32768),b=l[B.sampleModes],_=d.sample.getAudioData().length;J=Math.min(Math.max(0,J),_),U=Math.min(Math.max(0,U),_),U-J<1&&(b=0);let Y={sampleID:m,playbackStep:d.sample.sampleRate/o*Math.pow(2,d.sample.samplePitchCorrection/1200),cursor:l[B.startAddrsOffset]+l[B.startAddrsCoarseOffset]*32768,rootKey:H,loopStart:J,loopEnd:U,end:Math.floor(d.sample.sampleData.length)-1+(l[B.endAddrOffset]+l[B.endAddrsCoarseOffset]*32768),loopingMode:b};return l[B.velocity]>-1&&(t=l[B.velocity]),Q&&Zt([{Sample:d.sample.sampleName,Generators:l,Modulators:d.modulators.map(r=>r.debugString()),Velocity:t,TargetKey:k,MidiNote:A,WorkletSample:Y}]),f.push({filter:Ce(Vs),generators:l,modulators:d.modulators,modulatedGenerators:new Int16Array(60),sample:Y,velocity:t,midiNote:A,pressure:0,channelNumber:e,startTime:n,targetKey:k,currentTuningCalculated:1,currentTuningCents:0,releaseStartTime:1/0,finished:!1,isInRelease:!1,currentModEnvValue:0,releaseStartModEnv:1,currentPan:.5,volumeEnvelope:Ce(qs)}),f},[]),a[A][t]=h.map(Ce)),h}function sn(e,A,t){if(A.transformAmount===0)return 0;let s;if(A.sourceUsesCC)s=e[A.sourceIndex];else{let Q=A.sourceIndex+IA;switch(A.sourceIndex){case K.noController:s=16383;break;case K.noteOnKeyNum:s=t.midiNote<<7;break;case K.noteOnVelocity:s=t.velocity<<7;break;case K.polyPressure:s=t.pressure<<7;break;default:s=e[Q];break}}let n=hA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let Q=A.secSrcIndex+IA;switch(A.secSrcIndex){case K.noController:o=16383;break;case K.noteOnKeyNum:o=t.midiNote<<7;break;case K.noteOnVelocity:o=t.velocity<<7;break;case K.polyPressure:o=t.pressure<<7;break;default:o=e[Q]}}let C=hA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],a=n*C*A.transformAmount;return A.transformType===2?Math.abs(a):a}function YA(e,A,t=-1,s=0){let{modulators:n,generators:o,modulatedGenerators:C}=e;if(t===-1){C.set(o),n.forEach(h=>{C[h.modulatorDestination]+=sn(A,h,e)}),ZA(e);return}let a=new Set([B.initialAttenuation,B.delayVolEnv,B.attackVolEnv,B.holdVolEnv,B.decayVolEnv,B.sustainVolEnv,B.releaseVolEnv,B.keyNumToVolEnvHold,B.keyNumToVolEnvDecay]),Q=new Set;n.forEach(h=>{if(h.sourceUsesCC===t&&h.sourceIndex===s||h.secSrcUsesCC===t&&h.secSrcIndex===s){let u=h.modulatorDestination;Q.has(u)||(C[u]=o[u],n.forEach(f=>{f.modulatorDestination===u&&(C[u]+=sn(A,f,e))}),Q.add(u))}}),[...Q].some(h=>a.has(h))&&ZA(e)}var hA=[];for(let e=0;e<4;e++){hA[e]=[[new Float32Array(tA),new Float32Array(tA)],[new Float32Array(tA),new Float32Array(tA)]];for(let A=0;A200&&t<40||this.highPerformanceMode&&t<10||C.isMuted)return;let a=A+C.channelTransposeKeyShift;if(A>127||A<0)return;let Q=C.preset.program;this.tunings[Q]?.[A]?.midiNote>=0&&(a=this.tunings[Q]?.[A].midiNote);let h=tn(e,a,t,C.preset,o,sampleRate,f=>this.sampleDump(f.channel,f.sampleID,f.sampleData),C.cachedVoices,s),u=C.voices;h.forEach(f=>{let d=f.generators[B.exclusiveClass];d!==0&&u.forEach(m=>{m.generators[B.exclusiveClass]===d&&(this.releaseVoice(m),m.modulatedGenerators[B.releaseVolEnv]=-7e3,m.modulatedGenerators[B.releaseModEnv]=-7e3,ZA(m))}),YA(f,C.midiControllers),f.currentPan=(Math.max(-500,Math.min(500,f.modulatedGenerators[B.pan]))+500)/1e3}),this.totalVoicesAmount+=h.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(h.length),u.push(...h),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:e,velocity:t}))}function on(e,A){if(A>127||A<0){L("Received a noteOn for note",A,"Ignoring.");return}let t=A+this.workletProcessorChannels[e].channelTransposeKeyShift,s=this.workletProcessorChannels[e].preset.program;if(this.tunings[s]?.[A]?.midiNote>=0&&(t=this.tunings[s]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[e].drumChannel){this.killNote(e,t);return}this.workletProcessorChannels[e].voices.forEach(o=>{o.midiNote!==t||o.isInRelease===!0||(this.workletProcessorChannels[e].holdPedal?this.workletProcessorChannels[e].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:e})}function In(e,A){this.workletProcessorChannels[e].voices.forEach(t=>{t.midiNote===A&&(t.modulatedGenerators[B.releaseVolEnv]=-12e3,this.releaseVoice(t))})}function rn(e,A=!1){let t=this.workletProcessorChannels[e].voices;A?(t.length=0,this.workletProcessorChannels[e].sustainedVoices.length=0,this.sendChannelProperties()):(t.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[e].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function gn(e=!1){p("%cStop all received!",g.info);for(let A=0;AYA(n,this.workletProcessorChannels[e].midiControllers,0,K.pitchWheel)),this.sendChannelProperties()}function ln(e,A){let t=this.workletProcessorChannels[e];t.midiControllers[IA+K.channelPressure]=A<<7,this.workletProcessorChannels[e].voices.forEach(s=>YA(s,t.midiControllers,0,K.channelPressure)),this.callEvent("channelpressure",{channel:e,pressure:A})}function fn(e,A,t){this.workletProcessorChannels[e].voices.forEach(s=>{s.midiNote===A&&(s.pressure=t,YA(s,this.workletProcessorChannels[e].midiControllers,0,K.polyPressure))}),this.callEvent("polypressure",{channel:e,midiNote:A,pressure:t})}function dn(e,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[e].channelOctaveTuning=A}function un(e,A,t,s=!1){let n=this.workletProcessorChannels[e];if(A>=S.lsbForControl1ModulationWheel&&A<=S.lsbForControl13EffectControl2&&A!==S.lsbForControl6DataEntry){let o=A-32;if(n.lockedControllers[o])return;n.midiControllers[o]=n.midiControllers[o]&16256|t&127,n.voices.forEach(C=>YA(C,n.midiControllers,1,o))}switch(A){case S.allNotesOff:this.stopAll(e);break;case S.allSoundOff:this.stopAll(e,!0);break;case S.bankSelect:let o=t;if(!s){switch(this.system){case"gm":p(`%cIgnoring the Bank Select (${t}), as the synth is in GM mode.`,g.info);return;case"xg":o===120||o===126||o===127?this.setDrums(e,!0):this.setDrums(e,!1);break;case"gm2":o===120&&(n.drumChannel=!0,this.callEvent("drumchange",{channel:e,isDrumChannel:!0}))}n.drumChannel&&(o=128),o===128&&!n.drumChannel&&(o=n.midiControllers[S.bankSelect])}n.midiControllers[S.bankSelect]=o;break;case S.lsbForControl0BankSelect:this.system==="xg"?n.drumChannel||t!==127&&(n.midiControllers[S.bankSelect]=t):this.system==="gm2"&&(n.midiControllers[S.bankSelect]=t);break;case S.RPNLsb:n.RPValue=n.RPValue<<7|t,n.dataEntryState=BA.RPFine;break;case S.RPNMsb:n.RPValue=t,n.dataEntryState=BA.RPCoarse;break;case S.NRPNMsb:n.NRPCoarse=t,n.dataEntryState=BA.NRPCoarse;break;case S.NRPNLsb:n.NRPFine=t,n.dataEntryState=BA.NRPFine;break;case S.dataEntryMsb:this.dataEntryCoarse(e,t);break;case S.lsbForControl6DataEntry:this.dataEntryFine(e,t);break;case S.resetAllControllers:this.resetControllers(e);break;case S.sustainPedal:t>=64?n.holdPedal=!0:(n.holdPedal=!1,n.sustainedVoices.forEach(C=>{this.releaseVoice(C)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=t<<7,n.voices.forEach(C=>YA(C,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:e,controllerNumber:A,controllerValue:t});break}}function mn(e){this.midiVolume=e,this.setMasterPan(this.pan)}function pn(e){this.masterGain=e*lt,this.setMasterPan(this.pan)}function Sn(e){this.pan=e,e=e/2+.5,this.panLeft=(1-e)*this.currentGain,this.panRight=e*this.currentGain}function yn(e,A){A&&this.stopAll(e,!0),this.workletProcessorChannels[e].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:e,isMuted:A})}function Dn(e){this.workletProcessorChannels[e].lockVibrato=!0,this.workletProcessorChannels[e].channelVibrato.rate=0,this.workletProcessorChannels[e].channelVibrato.delay=0,this.workletProcessorChannels[e].channelVibrato.depth=0}function kn(e,A,t,s){this.workletProcessorChannels[e].lockVibrato||(this.workletProcessorChannels[e].channelVibrato.rate=t,this.workletProcessorChannels[e].channelVibrato.delay=s,this.workletProcessorChannels[e].channelVibrato.depth=A)}function wn(e,A){let t=this.workletProcessorChannels[e],s=()=>{t.channelVibrato.delay===0&&t.channelVibrato.rate===0&&t.channelVibrato.depth===0&&(t.channelVibrato.depth=50,t.channelVibrato.rate=8,t.channelVibrato.delay=.6)};switch(t.dataEntryState){default:case BA.Idle:break;case BA.NRPFine:if(this.system!=="gs")return;switch(t.NRPCoarse){default:if(A===64)return;L(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16).toUpperCase()} 0x${t.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,g.warn,g.recognized,g.warn,g.unrecognized,g.warn,g.value);break;case 1:switch(t.NRPFine){default:if(A===64)return;L(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16)} 0x${t.NRPFine.toString(16)})%c data value: %c${A}`,g.warn,g.recognized,g.warn,g.unrecognized,g.warn,g.value);break;case 8:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.rate=A/64*8,p(`%cVibrato rate for channel %c${e}%c is now set to %c${t.channelVibrato.rate}%cHz.`,g.info,g.recognized,g.info,g.value,g.info);break;case 9:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.depth=A/2,p(`%cVibrato depth for %c${e}%c is now set to %c${t.channelVibrato.depth}%c cents range of detune.`,g.info,g.recognized,g.info,g.value,g.info);break;case 10:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.delay=A/64/3,p(`%cVibrato delay for %c${e}%c is now set to %c${t.channelVibrato.delay}%c seconds.`,g.info,g.recognized,g.info,g.value,g.info);break;case 32:let o=A;this.controllerChange(e,S.brightness,A),p(`%cFilter cutoff for %c${e}%c is now set to %c${o}`,g.info,g.recognized,g.info,g.value)}break;case 29:if(!t.drumChannel)return;let n=A;this.controllerChange(e,S.effects1Depth,n),p(`%cGS Drum reverb for %c${e}%c: %c${n}`,g.info,g.recognized,g.info,g.value);break}break;case BA.RPCoarse:case BA.RPFine:switch(t.RPValue){default:L(`%cUnrecognized RPN for %c${e}%c: %c(0x${t.RPValue.toString(16)})%c data value: %c${A}`,g.warn,g.recognized,g.warn,g.unrecognized,g.warn,g.value);break;case 0:t.midiControllers[IA+K.pitchWheelRange]=A<<7,p(`%cChannel ${e} bend range. Semitones: %c${A}`,g.info,g.value);break;case 2:this.setChannelTuningSemitones(e,A-64);break;case 1:this.setChannelTuning(e,A-64,!1);break;case 5:this.setModulationDepth(e,A*100);break;case 16383:this.resetParameters(e);break}}}function Fn(e,A){let t=this.workletProcessorChannels[e];switch(t.dataEntryState){default:break;case BA.RPCoarse:case BA.RPFine:switch(t.RPValue){default:break;case 0:if(A===0)break;t.midiControllers[IA+K.pitchWheelRange]|=A;let s=(t.midiControllers[IA+K.pitchWheelRange]>>7)+A/127;p(`%cChannel ${e} bend range. Semitones: %c${s}`,g.info,g.value);break;case 1:let o=t.customControllers[eA.channelTuning]<<7|A;this.setChannelTuning(e,o*.01220703125);break;case 5:let a=t.customControllers[eA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(e,a);break;case 16383:this.resetParameters(e);break}}}function Rn(){p("%cResetting all controllers!",g.info),this.callEvent("allcontrollerreset",void 0);for(let e=0;e{this.workletProcessorChannels[e].lockedControllers[s]&&this.callEvent("controllerchange",{channel:e,controllerNumber:s,controllerValue:this.workletProcessorChannels[e].midiControllers[s]>>7})};if(t(S.mainVolume),t(S.pan),t(S.expressionController),t(S.modulationWheel),t(S.effects3Depth),t(S.effects1Depth),this.workletProcessorChannels[e].lockedControllers[IA+K.pitchWheel]){let s=this.workletProcessorChannels[e].midiControllers[IA+K.pitchWheel],n=s>>7,o=s&127;this.callEvent("pitchwheel",{channel:e,MSB:n,LSB:o})}}this.tunings=[],this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Se}function Gn(e){let A=this.workletProcessorChannels[e],s=A.lockedControllers.reduce((o,C,a)=>(C&&o.push(a),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.midiControllers.set(LA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let n=A.customControllers[eA.channelTransposeFine];A.customControllers.set(gt),A.customControllers[eA.channelTransposeFine]=n,this.resetParameters(e)}function xn(e){let A=this.workletProcessorChannels[e];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=BA.Idle}function Mn(e,A,t=!1){let s=this.workletProcessorChannels[e];if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[S.bankSelect],o,C;if(this.overrideSoundfont){let a=n===128?128:Math.max(0,n-this.soundfontBankOffset),Q=this.overrideSoundfont.presets.find(h=>h.program===A&&h.bank===a);Q?(o=n,C=Q,s.presetUsesOverride=!0):this.soundfontBankOffset===0?(C=this.overrideSoundfont.getPreset(0,A),o=C.bank):(C=this.soundfontManager.getPreset(n,A),o=C.bank,s.presetUsesOverride=!1)}else C=this.soundfontManager.getPreset(n,A),o=C.bank,s.presetUsesOverride=!1;this.setPreset(e,C),this.callEvent("programchange",{channel:e,program:C.program,bank:o,userCalled:t})}function Nn(e,A){if(this.overrideSoundfont){let t=e===128?128:Math.max(0,e-this.soundfontBankOffset),s=this.overrideSoundfont.presets.find(n=>n.program===A&&n.bank===t);if(s)return s;if(this.soundfontBankOffset===0)return this.overrideSoundfont.getPreset(0,A)}return this.soundfontManager.getPreset(e,A)}function Un(e,A){if(!this.workletProcessorChannels[e].lockPreset){delete this.workletProcessorChannels[e].preset,this.workletProcessorChannels[e].preset=A,this.workletProcessorChannels[e].cachedVoices=[];for(let t=0;t<128;t++)this.workletProcessorChannels[e].cachedVoices.push([])}}function bn(e,A){let t=this.workletProcessorChannels[e];t.lockPreset||t.drumChannel!==A&&(A?(t.channelTransposeKeyShift=0,t.drumChannel=!0,this.setPreset(e,this.getPreset(128,t.preset.program))):(t.drumChannel=!1,this.setPreset(e,this.getPreset(t.midiControllers[S.bankSelect],t.preset.program))),t.presetUsesOverride=!1,this.callEvent("drumchange",{channel:e,isDrumChannel:t.drumChannel}),this.sendChannelProperties())}function Ln(){let e=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,s=e.find(n=>n.bank===t&&n.program===A.program);s!==void 0?s.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.callEvent("presetlistchange",e)}function Hn(e=!0,A=!0){this.stopAllChannels(!0),en(),A&&delete this.overrideSoundfont,delete this.workletDumpedSamplesList,this.workletDumpedSamplesList=[],this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let t=0;t{this.programChange(s,t.preset.program)}),this.post({messageType:lA.ready,messageData:void 0}),this.sendPresetList(),p("%cSpessaSynth is ready!",g.recognized)}function Yn(e,A,t){this.workletDumpedSamplesList[A]=t,this.workletProcessorChannels[e].voices.forEach(s=>{if(s.sample.sampleID===A){if(s.sample.end=t.length-1+s.generators[B.endAddrOffset]+s.generators[B.endAddrsCoarseOffset]*32768,s.sample.cursor=s.sample.playbackStep*sampleRate*(currentTime-s.startTime),s.sample.loopingMode===0){if(s.sample.cursor>=s.sample.end){s.finished=!0;return}}else s.sample.cursor>s.sample.loopEnd&&(s.sample.cursor=s.sample.cursor%(s.sample.loopEnd-s.sample.loopStart)+s.sample.loopStart-1);s.startTime=currentTime}})}function Jn(){let A={channelSnapshots:this.workletProcessorChannels.map(t=>({program:t.preset.program,bank:t.preset.bank,lockPreset:t.lockPreset,patchName:t.preset.presetName,midiControllers:t.midiControllers,lockedControllers:t.lockedControllers,customControllers:t.customControllers,channelVibrato:t.channelVibrato,lockVibrato:t.lockVibrato,channelTransposeKeyShift:t.channelTransposeKeyShift,channelOctaveTuning:t.channelOctaveTuning,isMuted:t.isMuted,drumChannel:t.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system};this.post({messageType:lA.synthesizerSnapshot,messageData:A})}function qn(e){for(this.system=e.system,this.setMasterGain(e.mainVolume),this.setMasterPan(e.pan),this.transposeAllChannels(e.transposition);this.workletProcessorChannels.length{let s=this.workletProcessorChannels[t];this.muteChannel(t,A.isMuted),this.setDrums(t,A.drumChannel),s.midiControllers=A.midiControllers,s.lockedControllers=A.lockedControllers,s.customControllers=A.customControllers,s.channelVibrato=A.channelVibrato,s.lockVibrato=A.lockVibrato,s.channelTransposeKeyShift=A.channelTransposeKeyShift,s.channelOctaveTuning=A.channelOctaveTuning,s.lockPreset=!1,s.midiControllers[S.bankSelect]=A.bank,this.programChange(t,A.program),s.lockPreset=A.lockPreset}),p("%cFinished restoring controllers!",g.info)}var Ne=class{constructor(A,t){this.ready=t,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(t=>{t.soundfont.setSampleIDOffset(A),A+=t.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let t=this.soundfontList.length-1;t>=0;t--){let s=this.soundfontList[t];for(let n of s.soundfont.presets){let o=`${n.bank+s.bankOffset}-${n.program}`;A[o]=n.presetName}}this.presetList=[];for(let[t,s]of Object.entries(A)){let n=t.split("-");this.presetList.push({presetName:s,program:parseInt(n[1]),bank:parseInt(n[0])})}}handleMessage(A,t){switch(A){case zA.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case zA.reloadSoundFont:this.reloadManager(t);break;case zA.deleteSoundFont:this.deleteSoundFont(t);break;case zA.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList}reloadManager(A){let t=new qA(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:t}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){L("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(s=>s.id===A);if(t===-1){L(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[t].soundfont.presets,delete this.soundfontList[t].soundfont.instruments,delete this.soundfontList[t].soundfont.samples,this.soundfontList.splice(t,1),this.generatePresetList()}addNewSoundFont(A,t,s){if(this.soundfontList.find(n=>n.id===t)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:t,soundfont:new qA(A),bankOffset:s}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((t,s)=>A.indexOf(t.id)-A.indexOf(s.id)),this.generatePresetList()}getPreset(A,t){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let s of this.soundfontList){let n=s.soundfont.getPresetNoFallback(A-s.bankOffset,t);if(n!==void 0)return n}if(A!==128){for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.program===t);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}else{for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.bank===128);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}}};var ct=.07,lt=1,F=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=RA,this.processTickCallback=void 0,this.sequencer=new rA(this),this.transposition=0,this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=lt,this.midiVolume=1,this.voiceCap=Wt,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new Ne(A.processorOptions.soundfont,this.postReady.bind(this))}catch(t){throw this.post({messageType:lA.soundfontError,messageData:t}),t}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletDumpedSamplesList=[],this.workletProcessorChannels=[];for(let t=0;tthis.handleMessage(t.data),A.processorOptions.startRenderingData&&(A.processorOptions.startRenderingData.snapshot&&(this.applySynthesizerSnapshot(A.processorOptions.startRenderingData.snapshot),this.resetAllControllers()),p("%cRendering enabled! Starting render.",g.info),A.processorOptions.startRenderingData.parsedMIDI&&(this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]),this.sequencer.loop=!1)),UA.isInitialized.then(()=>{this.postReady(),p("%cSpessaSynth is ready!",g.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:lA.ready,messageData:void 0})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){p({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){this.processTickCallback&&this.processTickCallback();let s=0;return this.workletProcessorChannels.forEach((n,o)=>{if(n.voices.length<1||n.isMuted)return;let C,a,Q,h,u;if(this.oneOutputMode){let d=t[0];C=o%16*2,a=d[C],Q=d[C+1]}else C=o%this._outputsAmount+2,a=t[C][0],Q=t[C][1],h=t[0],u=t[1];let f=n.voices;n.voices=[],f.forEach(d=>{this.renderVoice(n,d,a,Q,h,u),d.finished||n.voices.push(d)}),s+=f.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};F.prototype.renderVoice=Xs;F.prototype.releaseVoice=_s;F.prototype.voiceKilling=Ws;F.prototype.handleMessage=zs;F.prototype.sendChannelProperties=$s;F.prototype.callEvent=js;F.prototype.systemExclusive=An;F.prototype.noteOn=nn;F.prototype.noteOff=on;F.prototype.polyPressure=fn;F.prototype.killNote=In;F.prototype.stopAll=rn;F.prototype.stopAllChannels=gn;F.prototype.muteChannel=yn;F.prototype.setVibrato=kn;F.prototype.disableAndLockVibrato=Dn;F.prototype.dataEntryCoarse=wn;F.prototype.dataEntryFine=Fn;F.prototype.createWorkletChannel=Ds;F.prototype.controllerChange=un;F.prototype.channelPressure=ln;F.prototype.resetAllControllers=Rn;F.prototype.resetControllers=Gn;F.prototype.resetParameters=xn;F.prototype.setMasterGain=pn;F.prototype.setMasterPan=Sn;F.prototype.setMIDIVolume=mn;F.prototype.transposeAllChannels=an;F.prototype.transposeChannel=Cn;F.prototype.setChannelTuning=En;F.prototype.setChannelTuningSemitones=Bn;F.prototype.setMasterTuning=Qn;F.prototype.setModulationDepth=hn;F.prototype.pitchWheel=cn;F.prototype.setOctaveTuning=dn;F.prototype.programChange=Mn;F.prototype.getPreset=Nn;F.prototype.setPreset=Un;F.prototype.setDrums=bn;F.prototype.reloadSoundFont=Tn;F.prototype.clearSoundFont=Hn;F.prototype.sampleDump=Yn;F.prototype.sendPresetList=Ln;F.prototype.sendSynthesizerSnapshot=Jn;F.prototype.applySynthesizerSnapshot=qn;registerProcessor(Xt,F);p("%cProcessor succesfully registered!",g.recognized); +`;this.copyright+=nA,p(`%cDecoded Roland SC message! %c${nA}`,g.recognized,g.value)}break;default:if((Y&240)===y.controllerChange)switch(P[0]){case 2:case 116:h=b;break;case 4:case 117:u===null?u=b:u=0;break}}}this.tracks.push(H),this.usedChannelsOnTrack.push(J),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,g.info,g.value,g.info,g.value)}let d=[];for(let l of this.tracks){let H=l.find(k=>(k.messageStatusByte&240)===y.noteOn);H&&d.push(H.ticks)}this.firstNoteOn=Math.min(...d),p(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}`,g.info,g.recognized),AA(),h!==null&&u===null?(h=this.firstNoteOn,u=this.lastVoiceEventTick):(h===null&&(h=this.firstNoteOn),(u===null||u===0)&&(u=this.lastVoiceEventTick));let m=0;for(let l of this.midiPorts)if(l!==-1){m=l;break}if(this.midiPorts=this.midiPorts.map(l=>l===-1?m:l),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.loop={start:h,end:u},!C)if(this.tracks.length>1){if(this.tracks[0].find(l=>l.messageStatusByte>=y.noteOn&&l.messageStatusByteH.messageStatusByte===y.trackName);l&&(this.rawMidiName=l.messageData,this.midiName=X(l.messageData,l.messageData.length,void 0,!1))}}else{let l=this.tracks[0].find(H=>H.messageStatusByte===y.trackName);l&&(this.rawMidiName=l.messageData,this.midiName=X(l.messageData,l.messageData.length,void 0,!1))}if(this.fileName=t,this.midiName=this.midiName.trim(),this.midiName.length===0){this.midiName=Jt(t),this.rawMidiName=new Uint8Array(this.midiName.length);for(let l=0;ln.ticksd>f?d:f),s=[];for(let f=0;f{C[l]>=m.length||m[C[l]].ticks0;){let f=Q(),d=e.tracks[f];if(C[f]>=d.length){a--;continue}let m=d[C[f]];if(C[f]++,m.messageStatusByte===y.midiPort){h[f]=m.messageData[0];continue}let l=m.messageStatusByte&240;if(l!==y.noteOn&&l!==y.controllerChange&&l!==y.programChange&&l!==y.systemExclusive)continue;let H=(m.messageStatusByte&15)+e.midiPortChannelOffsets[h[f]]||0,k=s[H];switch(l){case y.programChange:k.program=m.messageData[0],n(k);break;case y.controllerChange:if(m.messageData[0]!==S.bankSelect||u==="gs"&&k.drums)continue;let J=m.messageData[1],U=Math.max(0,J-e.bankOffset);if(u==="xg"){let Y=J===120||J===126||J===127;Y!==k.drums?(k.drums=Y,k.bank=k.drums?128:U,n(k)):k.bank=k.drums?128:U;continue}s[H].bank=U;break;case y.noteOn:if(m.messageData[1]===0)continue;n(k),o[k.string].add(`${m.messageData[0]}-${m.messageData[1]}`);break;case y.systemExclusive:if(m.messageData[0]!==65||m.messageData[2]!==66||m.messageData[3]!==18||m.messageData[4]!==64||!(m.messageData[5]&16)||m.messageData[6]!==21){m.messageData[0]===67&&m.messageData[2]===76&&m.messageData[5]===126&&m.messageData[6]===0&&(u="xg");continue}let b=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][m.messageData[5]&15]+e.midiPortChannelOffsets[h[f]],_=!!(m.messageData[7]>0&&m.messageData[5]>>4);k=s[b],k.drums=_,k.bank=_?128:0,n(k);break}}for(let f of Object.keys(o))o[f].size===0&&(p(`%cDetected change but no keys for %c${f}`,g.info,g.value),delete o[f]);return AA(),o}function Fs(e,A){this.midiPortChannelOffset===0&&(this.midiPortChannelOffset+=16,this.midiPortChannelOffsets[A]=0),this.midiPortChannelOffsets[A]===void 0&&(this.synth.workletProcessorChannels.lengthA.getAudioData());else{this.synth.overrideSoundfont&&this.synth.clearSoundFont(!0,!0),TA("%cPreloading samples...",g.info);let A=ws(this.midiData,this.synth.soundfontManager);for(let[t,s]of Object.entries(A)){let n=parseInt(t.split(":")[0]),o=parseInt(t.split(":")[1]),C=this.synth.getPreset(n,o);p(`%cPreloading used samples on %c${C.presetName}%c...`,g.info,g.recognized,g.info);for(let a of s){let Q=a.split("-");C.preloadSpecific(parseInt(Q[0]),parseInt(Q[1]))}}AA()}this.tracks=this.midiData.tracks,this.midiPorts=this.midiData.midiPorts,this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this.midiData.midiPorts.forEach((A,t)=>{this.assignMIDIPort(t,A)}),this.duration=this.midiData.duration,this.firstNoteTime=De(this.midiData.tempoChanges,this.midiData.firstNoteOn,this.midiData.timeDivision),p(`%cTotal song time: ${We(Math.ceil(this.duration)).time}`,g.recognized),this.post(pA.songChange,[new ke(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(L(`%cVery short song: (${We(Math.round(this.duration)).time}). Disabling loop!`,g.warn),this.loop=!1),this.play(!0)}function Gs(e){this.songs=e.reduce((A,t)=>{if(t.duration)return A.push(t),A;try{A.push(new Re(t.binary,t.altName||""))}catch(s){return this.post(pA.midiError,s.message),A}return A},[]),!(this.songs.length<1)&&(this.songIndex=0,this.songs.length>1&&(this.loop=!1),this.loadNewSequence(this.songs[this.songIndex]))}function xs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Ms(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex--,this.songIndex<0&&(this.songIndex=this.songs.length-1),this.loadNewSequence(this.songs[this.songIndex])}function Ns(e,A){switch(e){default:break;case FA.loadNewSongList:this.loadNewSongList(A);break;case FA.pause:this.pause();break;case FA.play:this.play(A);break;case FA.stop:this.stop();break;case FA.setTime:this.currentTime=A;break;case FA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case FA.setPlaybackRate:this.playbackRate=A;break;case FA.setLoop:this.loop=A;break;case FA.changeSong:A?this.nextSong():this.previousSong();break;case FA.getMIDI:this.post(pA.getMIDI,this.midiData);break;case FA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Us(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:lA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function bs(e){this.post(pA.midiEvent,e)}var rA=class{constructor(A){this.synth=A,this.ignoreEvents=!1,this.sendMIDIMessages=!1,this.eventIndex=[],this.songIndex=0,this.playedTime=0,this.pausedTime=void 0,this.absoluteStartTime=currentTime,this._playbackRate=1,this.playingNotes=[],this.loop=!0,this.midiData=void 0,this.midiPorts=[],this.midiPortChannelOffset=0,this.midiPortChannelOffsets={},this._skipToFirstNoteOn=!0}set playbackRate(A){let t=this.currentTime;this._playbackRate=A,this.currentTime=t}get currentTime(){return this.pausedTime?this.pausedTime:(currentTime-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&&ALs?440*Math.pow(2,(e-6900)/1200):Ct[~~e-Ge]}var Bt=-1660,Io=1600,Et=new Float32Array((Io-Bt)*100+1);for(let e=0;e.5?1:0,s?t*2-1:t;case fA.concave:return s?(t=t*2-1,t<0?1-$A[~~(t*-tA)]-1:$A[~~t*tA]):$A[~~(t*tA)];case fA.convex:return s?(t=t*2-1,t<0?1-Ae[~~(t*-tA)]-1:Ae[~~(t*tA)]):Ae[~~(t*tA)]}}var Qt=1,ht=new Float32Array(1e3);for(let e=0;e=e.sample.loopEnd;)s-=o;let a=~~s,Q=a+1;for(;Q>=e.sample.loopEnd;)Q-=o;let h=s-a,u=A[Q],f=A[a];t[C]=f+(u-f)*h,s+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=A.length&&(e.sample.end=A.length-1);for(let C=0;C=e.sample.end){e.finished=!0;return}let h=s-a,u=A[Q],f=A[a];t[C]=f+(u-f)*h,s+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=s}function Ys(e,A,t,s,n,o,C,a,Q){if(!isNaN(t[0])){if(C>0){let h=o[0],u=o[1];C=Math.min(C,1e3);let f=C/500,d=e*f,m=A*f;for(let l=0;l0){let h=a[0],u=a[1];Q=Math.min(Q,1e3);let f=Q/500,d=e*f,m=A*f;for(let l=0;l0)for(let h=0;h0)for(let h=0;h=A.length)return;a.state++;case 1:for(;Q=A.length)return}a.state++;case 2:for(;Q=A.length)return}a.state++;case 3:for(;Q=A.length)return}a.state++;case 4:for(;;){let u=a.sustainDb+C;if(a.currentAttenuationDb+=(u-a.currentAttenuationDb)*o,A[h]*=GA(a.currentAttenuationDb),++h>=A.length)return}}}var Vs={a0:0,a1:0,a2:0,a3:0,a4:0,x1:0,x2:0,y1:0,y2:0,reasonanceCb:0,reasonanceGain:1,cutoffCents:13500,cutoffHz:2e4};function Os(e,A,t){if(!(t>13499)){(e.filter.cutoffCents!==t||e.filter.reasonanceCb!==e.modulatedGenerators[B.initialFilterQ])&&(e.filter.cutoffCents=t,e.filter.reasonanceCb=e.modulatedGenerators[B.initialFilterQ],io(e));for(let s=0;s.45*sampleRate&&(e.filter.cutoffHz=.45*sampleRate);let A=e.filter.reasonanceCb/10-3.01;e.filter.reasonanceGain=GA(-1*A);let t=1/Math.sqrt(e.filter.reasonanceGain),s=2*Math.PI*e.filter.cutoffHz/sampleRate,n=Math.cos(s),o=Math.sin(s)/(2*e.filter.reasonanceGain),C=(1-n)*t,a=C/2,Q=a,h=1+o,u=-2*n,f=1-o;e.filter.a0=a/h,e.filter.a1=C/h,e.filter.a2=Q/h,e.filter.a3=u/h,e.filter.a4=f/h}var vs=Math.PI/2,Zs=.01;function Xs(e,A,t,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.releaseStartModEnv=A.currentModEnvValue,A.isInRelease=!0,ZA(A),A.volumeEnvelope.currentReleaseGain=GA(A.volumeEnvelope.currentAttenuationDb)),A.modulatedGenerators[B.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let C=A.targetKey,a=A.modulatedGenerators[B.fineTune]+e.customControllers[eA.channelTuning]+e.customControllers[eA.channelTransposeFine]+e.customControllers[eA.masterTuning]+e.channelOctaveTuning[A.midiNote%12],Q=A.modulatedGenerators[B.coarseTune]+e.customControllers[eA.channelTuningSemitones],h=this.tunings[e.preset.program]?.[C];h?.midiNote>=0&&(C=h.midiNote,a+=h.centTuning),a+=(C-A.sample.rootKey)*A.modulatedGenerators[B.scaleTuning];let u=A.modulatedGenerators[B.vibLfoToPitch];if(u!==0){let sA=A.startTime+QA(A.modulatedGenerators[B.delayVibLFO]),dA=ae(A.modulatedGenerators[B.freqVibLFO]),nA=xe(sA,dA,currentTime);a+=nA*(u*e.customControllers[eA.modulationMultiplier])}let f=A.modulatedGenerators[B.initialFilterFc],d=A.modulatedGenerators[B.modLfoToPitch],m=A.modulatedGenerators[B.modLfoToVolume],l=A.modulatedGenerators[B.modLfoToFilterFc],H=0;if(d+l+m!==0){let sA=A.startTime+QA(A.modulatedGenerators[B.delayModLFO]),dA=ae(A.modulatedGenerators[B.freqModLFO]),nA=xe(sA,dA,currentTime);a+=nA*(d*e.customControllers[eA.modulationMultiplier]),H=nA*m,f+=nA*l}if(e.channelVibrato.depth>0){let sA=xe(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);sA&&(a+=sA*e.channelVibrato.depth)}let k=A.modulatedGenerators[B.modEnvToPitch],J=A.modulatedGenerators[B.modEnvToFilterFc],U=Hs(A,currentTime);f+=U*J,a+=U*k;let b=~~(a+Q*100);b!==A.currentTuningCents&&(A.currentTuningCents=b,A.currentTuningCalculated=Math.pow(2,b/1200));let _=(Math.max(-500,Math.min(500,A.modulatedGenerators[B.pan]))+500)/1e3,Y=new Float32Array(t.length);Ts(A,this.workletDumpedSamplesList[A.sample.sampleID],Y),Os(A,Y,f),Ps(A,Y,currentTime,H,this.sampleTime,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(_-A.currentPan)*this.panSmoothingFactor;let r=Math.cos(vs*A.currentPan)*this.panLeft,$=Math.sin(vs*A.currentPan)*this.panRight,P=this.oneOutputMode?0:A.modulatedGenerators[B.reverbEffectsSend],O=this.oneOutputMode?0:A.modulatedGenerators[B.chorusEffectsSend];Ys(r,$,Y,t,s,n,P,o,O)}function go(e,A){let t=0;return e.drumChannel&&(t+=5),A.isInRelease&&(t-=5),t+=A.velocity/25,t-=A.volumeEnvelope.state,A.isInRelease&&(t-=5),t-=A.volumeEnvelope.currentAttenuationDb/50,t}function Ws(e){let A=[];for(let s of this.workletProcessorChannels)for(let n of s.voices)if(!n.finished){let o=go(s,n);A.push({channel:s,voice:n,priority:o})}A.sort((s,n)=>s.priority-n.priority);let t=A.slice(0,e);for(let{channel:s,voice:n}of t){let o=s.voices.indexOf(n);o>-1&&s.voices.splice(o,1)}}function _s(e){e.releaseStartTime=currentTime,e.releaseStartTime-e.startTime=0&&(s=this.workletProcessorChannels[t]),e.messageType){case v.noteOn:this.noteOn(t,A[0],A[1],A[2]);break;case v.noteOff:this.noteOff(t,A);break;case v.pitchWheel:this.pitchWheel(t,A[0],A[1]);break;case v.ccChange:this.controllerChange(t,A[0],A[1],A[2]);break;case v.customcCcChange:s.customControllers[A[0]]=A[1];break;case v.killNote:this.killNote(t,A);break;case v.programChange:this.programChange(t,A[0],A[1]);break;case v.channelPressure:this.channelPressure(t,A);break;case v.polyPressure:this.polyPressure(t,A[0],A[1]);break;case v.ccReset:t===RA?this.resetAllControllers():this.resetControllers(t);break;case v.systemExclusive:this.systemExclusive(A);break;case v.setChannelVibrato:if(t===RA)for(let C=0;C{let t=(A.midiControllers[IA+K.pitchWheelRange]>>7)+(A.midiControllers[IA+K.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[IA+K.pitchWheel],pitchBendRangeSemitones:t,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:lA.channelProperties,messageData:e})}function ao(e,A,t){let s=e,n=A<<7|t;return e===127&&A===127&&t===127?{midiNote:-1,centTuning:null}:{midiNote:s,centTuning:n*.0061}}function An(e,A=0){let t=e[0];if(!(this.deviceID!==RA&&e[1]!==127&&this.deviceID!==e[1]))switch(t){default:L(`%cUnrecognized SysEx: %c${aA(e)}`,g.warn,g.unrecognized);break;case 126:case 127:switch(e[2]){case 4:let s;switch(e[3]){case 1:let n=e[5]<<7|e[4];this.setMIDIVolume(n/16384),p(`%cMaster Volume. Volume: %c${n}`,g.info,g.value);break;case 2:let C=((e[5]<<7|e[4])-8192)/8192;this.setMasterPan(C),p(`%cMaster Pan. Pan: %c${C}`,g.info,g.value);break;case 3:let a=(e[5]<<7|e[6])-8192;s=Math.floor(a/81.92),this.setMasterTuning(s),p(`%cMaster Fine Tuning. Cents: %c${s}`,g.info,g.value);break;case 4:s=(e[5]-64)*100,this.setMasterTuning(s),p(`%cMaster Coarse Tuning. Cents: %c${s}`,g.info,g.value);break;default:L(`%cUnrecognized MIDI Device Control Real-time message: %c${aA(e)}`,g.warn,g.unrecognized)}break;case 9:e[3]===1?(p("%cGM system on",g.info),this.system="gm"):e[3]===3?(p("%cGM2 system on",g.info),this.system="gm2"):(p("%cGM system off, defaulting to GS",g.info),this.system="gs");break;case 8:switch(e[3]){case 2:case 7:let n=4;e[3]===7&&n++;let o=e[n++],C=e[n++];for(let Q=0;Q>1&1)===1&&this.setOctaveTuning(15+A,a);for(let Q=0;Q<7;Q++)(e[5]>>Q&1)===1&&this.setOctaveTuning(7+Q+A,a);for(let Q=0;Q<7;Q++)(e[6]>>Q&1)===1&&this.setOctaveTuning(Q+A,a);p(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${a.join(" ")}`,g.info,g.value);break;default:L(`%cUnrecognized MIDI Tuning standard message: %c${aA(e)}`,g.warn,g.unrecognized);break}break;default:L(`%cUnrecognized MIDI Realtime/non realtime message: %c${aA(e)}`,g.warn,g.unrecognized)}break;case 65:if(e[2]===66&&e[3]===18){let s=e[7];if(e[6]===127){s===0?(p("%cGS system on",g.info),this.system="gs"):s===127&&(p("%cGS system off, switching to GM2",g.info),this.system="gm2");return}else if(e[4]===64){if((e[5]&16)>0){let n=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][e[5]&15]+A;switch(e[6]){default:break;case 21:let o=s>0&&e[5]>>4;this.setDrums(n,o),p(`%cChannel %c${n}%c ${o?"is now a drum channel":"now isn't a drum channel"}%c via: %c${aA(e)}`,g.info,g.value,g.recognized,g.info,g.value);return;case 22:let C=s-64;this.transposeChannel(n,C),p(`%cChannel %c${n}%c pitch shift. Semitones %c${C}%c, with %c${aA(e)}`,g.info,g.recognized,g.info,g.value,g.info,g.value);return;case 64:case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:let a=s-64;p(`%cChannel %c${n}%c tuning. Cents %c${a}%c, with %c${aA(e)}`,g.info,g.recognized,g.info,g.value,g.info,g.value),this.setChannelTuning(n,a)}}else if(e[5]===0&&e[6]===6){p(`%cRoland GS Master Pan set to: %c${s}%c with: %c${aA(e)}`,g.info,g.value,g.info,g.value),this.setMasterPan((s-64)/64);return}else if(e[5]===0&&e[6]===5){let n=s-64;p(`%cRoland GS Master Key-Shift set to: %c${n}%c with: %c${aA(e)}`,g.info,g.value,g.info,g.value),this.setMasterTuning(n*100);return}else if(e[5]===0&&e[6]===4){p(`%cRoland GS Master Volume set to: %c${s}%c with: %c${aA(e)}`,g.info,g.value,g.info,g.value),this.setMIDIVolume(s/127);return}}L(`%cUnrecognized Roland %cGS %cSysEx: %c${aA(e)}`,g.warn,g.recognized,g.warn,g.unrecognized);return}else if(e[2]===22&&e[3]===18&&e[4]===16){this.setMIDIVolume(e[7]/100),p(`%cRoland Master Volume control set to: %c${e[7]}%c via: %c${aA(e)}`,g.info,g.value,g.info,g.value);return}else{L(`%cUnrecognized Roland SysEx: %c${aA(e)}`,g.warn,g.unrecognized);return}case 67:if(e[2]===76)if(e[3]===0&&e[4]===0)switch(e[5]){case 4:let s=e[6];this.setMIDIVolume(s/127),p(`%cXG master volume. Volume: %c${s}`,g.info,g.recognized);break;case 6:let n=e[6]-64;this.transposeAllChannels(n),p(`%cXG master transpose. Volume: %c${n}`,g.info,g.recognized);break;case 126:p("%cXG system on",g.info),this.system="xg";break}else if(e[3]===8){if(this.system!=="xg")return;let s=e[4]+A,n=e[6];switch(e[5]){case 1:this.controllerChange(s,S.bankSelect,n);break;case 2:this.controllerChange(s,S.lsbForControl0BankSelect,n);break;case 3:this.programChange(s,n);break;case 11:this.controllerChange(s,S.mainVolume,n);break;case 14:let o=n;o===0&&(o=Math.floor(Math.random()*127)),this.controllerChange(s,S.pan,o);break;case 19:this.controllerChange(s,S.effects1Depth,n);break;case 18:this.controllerChange(s,S.effects3Depth,n);break;default:L(`%cUnrecognized Yamaha XG Part Setup: %c${e[5].toString(16).toUpperCase()}`,g.warn,g.unrecognized)}}else this.system==="xg"&&L(`%cUnrecognized Yamaha XG SysEx: %c${aA(e)}`,g.warn,g.unrecognized);else this.system==="xg"&&L(`%cUnrecognized Yamaha SysEx: %c${aA(e)}`,g.warn,g.unrecognized);break}}var Me=[];function en(){Me=[]}function Co(e,A,t,s){Me[t]=!1,s({channel:e,sampleID:t,sampleData:A.getAudioData()}),Me[t]=!0}function Ce(e){if(e===null||typeof e!="object")return e;if(e instanceof Int16Array)return new Int16Array(e);let A=Array.isArray(e)?[]:{};for(let t in e)e.hasOwnProperty(t)&&(typeof e[t]=="object"&&e[t]!==null?A[t]=Ce(e[t]):e[t]instanceof Int16Array?A[t]=new Int16Array(e[t]):A[t]=e[t]);return A}function tn(e,A,t,s,n,o,C,a,Q=!1){let h,u=a[A][t];return u!==void 0?(h=u.map(Ce),h.forEach(f=>{f.startTime=n})):(h=s.getSamplesAndGenerators(A,t).reduce((f,d)=>{let m=d.sampleID+s.sampleIDOffset;if(Me[m]!==!0&&Co(e,d.sample,m,C),d.sample.sampleData===void 0)return L(`Discarding invalid sample: ${d.sample.sampleName}`),f;let l=new Int16Array(60);for(let r=0;r<60;r++)l[r]=As(r,d.presetGenerators,d.instrumentGenerators);l[B.initialAttenuation]=Math.floor(l[B.initialAttenuation]*.4);let H=d.sample.samplePitch;l[B.overridingRootKey]>-1&&(H=l[B.overridingRootKey]);let k=A;l[B.keyNum]>-1&&(k=l[B.keyNum]);let J=d.sample.sampleLoopStartIndex/2+(l[B.startloopAddrsOffset]+l[B.startloopAddrsCoarseOffset]*32768),U=d.sample.sampleLoopEndIndex/2+(l[B.endloopAddrsOffset]+l[B.endloopAddrsCoarseOffset]*32768),b=l[B.sampleModes],_=d.sample.getAudioData().length;J=Math.min(Math.max(0,J),_),U=Math.min(Math.max(0,U),_),U-J<1&&(b=0);let Y={sampleID:m,playbackStep:d.sample.sampleRate/o*Math.pow(2,d.sample.samplePitchCorrection/1200),cursor:l[B.startAddrsOffset]+l[B.startAddrsCoarseOffset]*32768,rootKey:H,loopStart:J,loopEnd:U,end:Math.floor(d.sample.sampleData.length)-1+(l[B.endAddrOffset]+l[B.endAddrsCoarseOffset]*32768),loopingMode:b};return l[B.velocity]>-1&&(t=l[B.velocity]),Q&&Zt([{Sample:d.sample.sampleName,Generators:l,Modulators:d.modulators.map(r=>r.debugString()),Velocity:t,TargetKey:k,MidiNote:A,WorkletSample:Y}]),f.push({filter:Ce(Vs),generators:l,modulators:d.modulators,modulatedGenerators:new Int16Array(60),sample:Y,velocity:t,midiNote:A,pressure:0,channelNumber:e,startTime:n,targetKey:k,currentTuningCalculated:1,currentTuningCents:0,releaseStartTime:1/0,finished:!1,isInRelease:!1,currentModEnvValue:0,releaseStartModEnv:1,currentPan:.5,volumeEnvelope:Ce(qs)}),f},[]),a[A][t]=h.map(Ce)),h}function sn(e,A,t){if(A.transformAmount===0)return 0;let s;if(A.sourceUsesCC)s=e[A.sourceIndex];else{let Q=A.sourceIndex+IA;switch(A.sourceIndex){case K.noController:s=16383;break;case K.noteOnKeyNum:s=t.midiNote<<7;break;case K.noteOnVelocity:s=t.velocity<<7;break;case K.polyPressure:s=t.pressure<<7;break;default:s=e[Q];break}}let n=hA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let Q=A.secSrcIndex+IA;switch(A.secSrcIndex){case K.noController:o=16383;break;case K.noteOnKeyNum:o=t.midiNote<<7;break;case K.noteOnVelocity:o=t.velocity<<7;break;case K.polyPressure:o=t.pressure<<7;break;default:o=e[Q]}}let C=hA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],a=n*C*A.transformAmount;return A.transformType===2?Math.abs(a):a}function YA(e,A,t=-1,s=0){let{modulators:n,generators:o,modulatedGenerators:C}=e;if(t===-1){C.set(o),n.forEach(h=>{C[h.modulatorDestination]+=sn(A,h,e)}),ZA(e);return}let a=new Set([B.initialAttenuation,B.delayVolEnv,B.attackVolEnv,B.holdVolEnv,B.decayVolEnv,B.sustainVolEnv,B.releaseVolEnv,B.keyNumToVolEnvHold,B.keyNumToVolEnvDecay]),Q=new Set;n.forEach(h=>{if(h.sourceUsesCC===t&&h.sourceIndex===s||h.secSrcUsesCC===t&&h.secSrcIndex===s){let u=h.modulatorDestination;Q.has(u)||(C[u]=o[u],n.forEach(f=>{f.modulatorDestination===u&&(C[u]+=sn(A,f,e))}),Q.add(u))}}),[...Q].some(h=>a.has(h))&&ZA(e)}var hA=[];for(let e=0;e<4;e++){hA[e]=[[new Float32Array(tA),new Float32Array(tA)],[new Float32Array(tA),new Float32Array(tA)]];for(let A=0;A200&&t<40||this.highPerformanceMode&&t<10||C.isMuted)return;let a=A+C.channelTransposeKeyShift;if(A>127||A<0)return;let Q=C.preset.program;this.tunings[Q]?.[A]?.midiNote>=0&&(a=this.tunings[Q]?.[A].midiNote);let h=tn(e,a,t,C.preset,o,sampleRate,f=>this.sampleDump(f.channel,f.sampleID,f.sampleData),C.cachedVoices,s),u=C.voices;h.forEach(f=>{let d=f.generators[B.exclusiveClass];d!==0&&u.forEach(m=>{m.generators[B.exclusiveClass]===d&&(this.releaseVoice(m),m.modulatedGenerators[B.releaseVolEnv]=-7e3,m.modulatedGenerators[B.releaseModEnv]=-7e3,ZA(m))}),YA(f,C.midiControllers),f.currentPan=(Math.max(-500,Math.min(500,f.modulatedGenerators[B.pan]))+500)/1e3}),this.totalVoicesAmount+=h.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(h.length),u.push(...h),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:e,velocity:t}))}function on(e,A){if(A>127||A<0){L("Received a noteOn for note",A,"Ignoring.");return}let t=A+this.workletProcessorChannels[e].channelTransposeKeyShift,s=this.workletProcessorChannels[e].preset.program;if(this.tunings[s]?.[A]?.midiNote>=0&&(t=this.tunings[s]?.[A].midiNote),this.highPerformanceMode&&!this.workletProcessorChannels[e].drumChannel){this.killNote(e,t);return}this.workletProcessorChannels[e].voices.forEach(o=>{o.midiNote!==t||o.isInRelease===!0||(this.workletProcessorChannels[e].holdPedal?this.workletProcessorChannels[e].sustainedVoices.push(o):this.releaseVoice(o))}),this.callEvent("noteoff",{midiNote:A,channel:e})}function In(e,A){this.workletProcessorChannels[e].voices.forEach(t=>{t.midiNote===A&&(t.modulatedGenerators[B.releaseVolEnv]=-12e3,this.releaseVoice(t))})}function rn(e,A=!1){let t=this.workletProcessorChannels[e].voices;A?(t.length=0,this.workletProcessorChannels[e].sustainedVoices.length=0,this.sendChannelProperties()):(t.forEach(s=>{s.isInRelease||this.releaseVoice(s)}),this.workletProcessorChannels[e].sustainedVoices.forEach(s=>{this.releaseVoice(s)}))}function gn(e=!1){p("%cStop all received!",g.info);for(let A=0;AYA(n,this.workletProcessorChannels[e].midiControllers,0,K.pitchWheel)),this.sendChannelProperties()}function ln(e,A){let t=this.workletProcessorChannels[e];t.midiControllers[IA+K.channelPressure]=A<<7,this.workletProcessorChannels[e].voices.forEach(s=>YA(s,t.midiControllers,0,K.channelPressure)),this.callEvent("channelpressure",{channel:e,pressure:A})}function fn(e,A,t){this.workletProcessorChannels[e].voices.forEach(s=>{s.midiNote===A&&(s.pressure=t,YA(s,this.workletProcessorChannels[e].midiControllers,0,K.polyPressure))}),this.callEvent("polypressure",{channel:e,midiNote:A,pressure:t})}function dn(e,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[e].channelOctaveTuning=A}function un(e,A,t,s=!1){let n=this.workletProcessorChannels[e];if(A>=S.lsbForControl1ModulationWheel&&A<=S.lsbForControl13EffectControl2&&A!==S.lsbForControl6DataEntry){let o=A-32;if(n.lockedControllers[o])return;n.midiControllers[o]=n.midiControllers[o]&16256|t&127,n.voices.forEach(C=>YA(C,n.midiControllers,1,o))}switch(A){case S.allNotesOff:this.stopAll(e);break;case S.allSoundOff:this.stopAll(e,!0);break;case S.bankSelect:let o=t;if(!s){switch(this.system){case"gm":p(`%cIgnoring the Bank Select (${t}), as the synth is in GM mode.`,g.info);return;case"xg":o===120||o===126||o===127?this.setDrums(e,!0):this.setDrums(e,!1);break;case"gm2":o===120&&(n.drumChannel=!0,this.callEvent("drumchange",{channel:e,isDrumChannel:!0}))}n.drumChannel&&(o=128),o===128&&!n.drumChannel&&(o=n.midiControllers[S.bankSelect])}n.midiControllers[S.bankSelect]=o;break;case S.lsbForControl0BankSelect:this.system==="xg"?n.drumChannel||t!==127&&(n.midiControllers[S.bankSelect]=t):this.system==="gm2"&&(n.midiControllers[S.bankSelect]=t);break;case S.RPNLsb:n.RPValue=n.RPValue<<7|t,n.dataEntryState=BA.RPFine;break;case S.RPNMsb:n.RPValue=t,n.dataEntryState=BA.RPCoarse;break;case S.NRPNMsb:n.NRPCoarse=t,n.dataEntryState=BA.NRPCoarse;break;case S.NRPNLsb:n.NRPFine=t,n.dataEntryState=BA.NRPFine;break;case S.dataEntryMsb:this.dataEntryCoarse(e,t);break;case S.lsbForControl6DataEntry:this.dataEntryFine(e,t);break;case S.resetAllControllers:this.resetControllers(e);break;case S.sustainPedal:t>=64?n.holdPedal=!0:(n.holdPedal=!1,n.sustainedVoices.forEach(C=>{this.releaseVoice(C)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=t<<7,n.voices.forEach(C=>YA(C,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:e,controllerNumber:A,controllerValue:t});break}}function mn(e){this.midiVolume=e,this.setMasterPan(this.pan)}function pn(e){this.masterGain=e*lt,this.setMasterPan(this.pan)}function Sn(e){this.pan=e,e=e/2+.5,this.panLeft=(1-e)*this.currentGain,this.panRight=e*this.currentGain}function yn(e,A){A&&this.stopAll(e,!0),this.workletProcessorChannels[e].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:e,isMuted:A})}function Dn(e){this.workletProcessorChannels[e].lockVibrato=!0,this.workletProcessorChannels[e].channelVibrato.rate=0,this.workletProcessorChannels[e].channelVibrato.delay=0,this.workletProcessorChannels[e].channelVibrato.depth=0}function kn(e,A,t,s){this.workletProcessorChannels[e].lockVibrato||(this.workletProcessorChannels[e].channelVibrato.rate=t,this.workletProcessorChannels[e].channelVibrato.delay=s,this.workletProcessorChannels[e].channelVibrato.depth=A)}function wn(e,A){let t=this.workletProcessorChannels[e],s=()=>{t.channelVibrato.delay===0&&t.channelVibrato.rate===0&&t.channelVibrato.depth===0&&(t.channelVibrato.depth=50,t.channelVibrato.rate=8,t.channelVibrato.delay=.6)};switch(t.dataEntryState){default:case BA.Idle:break;case BA.NRPFine:if(this.system!=="gs")return;switch(t.NRPCoarse){default:if(A===64)return;L(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16).toUpperCase()} 0x${t.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,g.warn,g.recognized,g.warn,g.unrecognized,g.warn,g.value);break;case 1:switch(t.NRPFine){default:if(A===64)return;L(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16)} 0x${t.NRPFine.toString(16)})%c data value: %c${A}`,g.warn,g.recognized,g.warn,g.unrecognized,g.warn,g.value);break;case 8:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.rate=A/64*8,p(`%cVibrato rate for channel %c${e}%c is now set to %c${t.channelVibrato.rate}%cHz.`,g.info,g.recognized,g.info,g.value,g.info);break;case 9:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.depth=A/2,p(`%cVibrato depth for %c${e}%c is now set to %c${t.channelVibrato.depth}%c cents range of detune.`,g.info,g.recognized,g.info,g.value,g.info);break;case 10:if(t.lockVibrato||A===64)return;s(),t.channelVibrato.delay=A/64/3,p(`%cVibrato delay for %c${e}%c is now set to %c${t.channelVibrato.delay}%c seconds.`,g.info,g.recognized,g.info,g.value,g.info);break;case 32:let o=A;this.controllerChange(e,S.brightness,A),p(`%cFilter cutoff for %c${e}%c is now set to %c${o}`,g.info,g.recognized,g.info,g.value)}break;case 29:if(!t.drumChannel)return;let n=A;this.controllerChange(e,S.effects1Depth,n),p(`%cGS Drum reverb for %c${e}%c: %c${n}`,g.info,g.recognized,g.info,g.value);break}break;case BA.RPCoarse:case BA.RPFine:switch(t.RPValue){default:L(`%cUnrecognized RPN for %c${e}%c: %c(0x${t.RPValue.toString(16)})%c data value: %c${A}`,g.warn,g.recognized,g.warn,g.unrecognized,g.warn,g.value);break;case 0:t.midiControllers[IA+K.pitchWheelRange]=A<<7,p(`%cChannel ${e} bend range. Semitones: %c${A}`,g.info,g.value);break;case 2:this.setChannelTuningSemitones(e,A-64);break;case 1:this.setChannelTuning(e,A-64,!1);break;case 5:this.setModulationDepth(e,A*100);break;case 16383:this.resetParameters(e);break}}}function Fn(e,A){let t=this.workletProcessorChannels[e];switch(t.dataEntryState){default:break;case BA.RPCoarse:case BA.RPFine:switch(t.RPValue){default:break;case 0:if(A===0)break;t.midiControllers[IA+K.pitchWheelRange]|=A;let s=(t.midiControllers[IA+K.pitchWheelRange]>>7)+A/127;p(`%cChannel ${e} bend range. Semitones: %c${s}`,g.info,g.value);break;case 1:let o=t.customControllers[eA.channelTuning]<<7|A;this.setChannelTuning(e,o*.01220703125);break;case 5:let a=t.customControllers[eA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(e,a);break;case 16383:this.resetParameters(e);break}}}function Rn(){p("%cResetting all controllers!",g.info),this.callEvent("allcontrollerreset",void 0);for(let e=0;e{this.workletProcessorChannels[e].lockedControllers[s]&&this.callEvent("controllerchange",{channel:e,controllerNumber:s,controllerValue:this.workletProcessorChannels[e].midiControllers[s]>>7})};if(t(S.mainVolume),t(S.pan),t(S.expressionController),t(S.modulationWheel),t(S.effects3Depth),t(S.effects1Depth),this.workletProcessorChannels[e].lockedControllers[IA+K.pitchWheel]){let s=this.workletProcessorChannels[e].midiControllers[IA+K.pitchWheel],n=s>>7,o=s&127;this.callEvent("pitchwheel",{channel:e,MSB:n,LSB:o})}}this.tunings=[],this.tunings=[];for(let e=0;e<127;e++)this.tunings.push([]);this.setMIDIVolume(1),this.system=Se}function Gn(e){let A=this.workletProcessorChannels[e],s=A.lockedControllers.reduce((o,C,a)=>(C&&o.push(a),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.midiControllers.set(LA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let n=A.customControllers[eA.channelTransposeFine];A.customControllers.set(gt),A.customControllers[eA.channelTransposeFine]=n,this.resetParameters(e)}function xn(e){let A=this.workletProcessorChannels[e];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=BA.Idle}function Mn(e,A,t=!1){let s=this.workletProcessorChannels[e];if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[S.bankSelect],o,C;if(this.overrideSoundfont){let a=n===128?128:Math.max(0,n-this.soundfontBankOffset),Q=this.overrideSoundfont.presets.find(h=>h.program===A&&h.bank===a);Q?(o=n,C=Q,s.presetUsesOverride=!0):this.soundfontBankOffset===0?(C=this.overrideSoundfont.getPreset(0,A),o=C.bank):(C=this.soundfontManager.getPreset(n,A),o=C.bank,s.presetUsesOverride=!1)}else C=this.soundfontManager.getPreset(n,A),o=C.bank,s.presetUsesOverride=!1;this.setPreset(e,C),this.callEvent("programchange",{channel:e,program:C.program,bank:o,userCalled:t})}function Nn(e,A){if(this.overrideSoundfont){let t=e===128?128:Math.max(0,e-this.soundfontBankOffset),s=this.overrideSoundfont.presets.find(n=>n.program===A&&n.bank===t);if(s)return s;if(this.soundfontBankOffset===0)return this.overrideSoundfont.getPreset(0,A)}return this.soundfontManager.getPreset(e,A)}function Un(e,A){if(!this.workletProcessorChannels[e].lockPreset){delete this.workletProcessorChannels[e].preset,this.workletProcessorChannels[e].preset=A,this.workletProcessorChannels[e].cachedVoices=[];for(let t=0;t<128;t++)this.workletProcessorChannels[e].cachedVoices.push([])}}function bn(e,A){let t=this.workletProcessorChannels[e];t.lockPreset||t.drumChannel!==A&&(A?(t.channelTransposeKeyShift=0,t.drumChannel=!0,this.setPreset(e,this.getPreset(128,t.preset.program))):(t.drumChannel=!1,this.setPreset(e,this.getPreset(t.midiControllers[S.bankSelect],t.preset.program))),t.presetUsesOverride=!1,this.callEvent("drumchange",{channel:e,isDrumChannel:t.drumChannel}),this.sendChannelProperties())}function Ln(){let e=this.soundfontManager.getPresetList();this.overrideSoundfont!==void 0&&this.overrideSoundfont.presets.forEach(A=>{let t=A.bank===128?128:A.bank+this.soundfontBankOffset,s=e.find(n=>n.bank===t&&n.program===A.program);s!==void 0?s.presetName=A.presetName:e.push({presetName:A.presetName,bank:t,program:A.program})}),this.callEvent("presetlistchange",e)}function Hn(e=!0,A=!0){this.stopAllChannels(!0),en(),A&&delete this.overrideSoundfont,delete this.workletDumpedSamplesList,this.workletDumpedSamplesList=[],this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0);for(let t=0;t{this.programChange(s,t.preset.program)}),this.post({messageType:lA.ready,messageData:void 0}),this.sendPresetList(),p("%cSpessaSynth is ready!",g.recognized)}function Yn(e,A,t){this.workletDumpedSamplesList[A]=t,this.workletProcessorChannels[e].voices.forEach(s=>{if(s.sample.sampleID===A){if(s.sample.end=t.length-1+s.generators[B.endAddrOffset]+s.generators[B.endAddrsCoarseOffset]*32768,s.sample.cursor=s.sample.playbackStep*sampleRate*(currentTime-s.startTime),s.sample.loopingMode===0){if(s.sample.cursor>=s.sample.end){s.finished=!0;return}}else s.sample.cursor>s.sample.loopEnd&&(s.sample.cursor=s.sample.cursor%(s.sample.loopEnd-s.sample.loopStart)+s.sample.loopStart-1);s.startTime=currentTime}})}function Jn(){let A={channelSnapshots:this.workletProcessorChannels.map(t=>({program:t.preset.program,bank:t.preset.bank,lockPreset:t.lockPreset,patchName:t.preset.presetName,midiControllers:t.midiControllers,lockedControllers:t.lockedControllers,customControllers:t.customControllers,channelVibrato:t.channelVibrato,lockVibrato:t.lockVibrato,channelTransposeKeyShift:t.channelTransposeKeyShift,channelOctaveTuning:t.channelOctaveTuning,isMuted:t.isMuted,drumChannel:t.drumChannel})),mainVolume:this.midiVolume,pan:this.pan,transposition:this.transposition,system:this.system};this.post({messageType:lA.synthesizerSnapshot,messageData:A})}function qn(e){for(this.system=e.system,this.setMasterGain(e.mainVolume),this.setMasterPan(e.pan),this.transposeAllChannels(e.transposition);this.workletProcessorChannels.length{let s=this.workletProcessorChannels[t];this.muteChannel(t,A.isMuted),this.setDrums(t,A.drumChannel),s.midiControllers=A.midiControllers,s.lockedControllers=A.lockedControllers,s.customControllers=A.customControllers,s.channelVibrato=A.channelVibrato,s.lockVibrato=A.lockVibrato,s.channelTransposeKeyShift=A.channelTransposeKeyShift,s.channelOctaveTuning=A.channelOctaveTuning,s.lockPreset=!1,s.midiControllers[S.bankSelect]=A.bank,this.programChange(t,A.program),s.lockPreset=A.lockPreset}),p("%cFinished restoring controllers!",g.info)}var Ne=class{constructor(A,t){this.ready=t,this.totalSoundfontOffset=0,this.reloadManager(A)}_assingSampleOffsets(){let A=0;this.soundfontList.forEach(t=>{t.soundfont.setSampleIDOffset(A),A+=t.soundfont.samples.length}),this.totalSoundfontOffset=A}generatePresetList(){this._assingSampleOffsets();let A={};for(let t=this.soundfontList.length-1;t>=0;t--){let s=this.soundfontList[t];for(let n of s.soundfont.presets){let o=`${n.bank+s.bankOffset}-${n.program}`;A[o]=n.presetName}}this.presetList=[];for(let[t,s]of Object.entries(A)){let n=t.split("-");this.presetList.push({presetName:s,program:parseInt(n[1]),bank:parseInt(n[0])})}}handleMessage(A,t){switch(A){case zA.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case zA.reloadSoundFont:this.reloadManager(t);break;case zA.deleteSoundFont:this.deleteSoundFont(t);break;case zA.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let t=new qA(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:t}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){L("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(s=>s.id===A);if(t===-1){L(`No soundfont with id of "${A}" found. Aborting!`);return}delete this.soundfontList[t].soundfont.presets,delete this.soundfontList[t].soundfont.instruments,delete this.soundfontList[t].soundfont.samples,this.soundfontList.splice(t,1),this.generatePresetList()}addNewSoundFont(A,t,s){if(this.soundfontList.find(n=>n.id===t)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this.soundfontList.push({id:t,soundfont:new qA(A),bankOffset:s}),this.generatePresetList(),this.ready()}rearrangeSoundFonts(A){this.soundfontList.sort((t,s)=>A.indexOf(t.id)-A.indexOf(s.id)),this.generatePresetList()}getPreset(A,t){if(this.soundfontList.length<1)throw new Error("No soundfonts! This should never happen.");for(let s of this.soundfontList){let n=s.soundfont.getPresetNoFallback(A-s.bankOffset,t);if(n!==void 0)return n}if(A!==128){for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.program===t);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}else{for(let s of this.soundfontList){let n=s.soundfont.presets.find(o=>o.bank===128);if(n)return n}return this.soundfontList[0].soundfont.presets[0]}}};var ct=.07,lt=1,F=class extends AudioWorkletProcessor{constructor(A){super(),this.oneOutputMode=A.processorOptions?.startRenderingData?.oneOutput===!0,this._outputsAmount=this.oneOutputMode?1:A.processorOptions.midiChannels,this.enableEventSystem=A.processorOptions.enableEventSystem,this.deviceID=RA,this.processTickCallback=void 0,this.sequencer=new rA(this),this.transposition=0,this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=lt,this.midiVolume=1,this.voiceCap=Wt,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new Ne(A.processorOptions.soundfont,this.postReady.bind(this))}catch(t){throw this.post({messageType:lA.soundfontError,messageData:t}),t}this.sendPresetList(),this.defaultPreset=this.getPreset(0,0),this.drumPreset=this.getPreset(128,0),this.workletDumpedSamplesList=[],this.workletProcessorChannels=[];for(let t=0;tthis.handleMessage(t.data),A.processorOptions.startRenderingData&&(A.processorOptions.startRenderingData.snapshot&&(this.applySynthesizerSnapshot(A.processorOptions.startRenderingData.snapshot),this.resetAllControllers()),p("%cRendering enabled! Starting render.",g.info),A.processorOptions.startRenderingData.parsedMIDI&&(this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]),this.sequencer.loop=!1)),UA.isInitialized.then(()=>{this.postReady(),p("%cSpessaSynth is ready!",g.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:lA.ready,messageData:void 0})}get currentGain(){return this.masterGain*this.midiVolume}debugMessage(){p({channels:this.workletProcessorChannels,voicesAmount:this.totalVoicesAmount,outputAmount:this._outputsAmount,dumpedSamples:this.workletDumpedSamplesList})}process(A,t){this.processTickCallback&&this.processTickCallback();let s=0;return this.workletProcessorChannels.forEach((n,o)=>{if(n.voices.length<1||n.isMuted)return;let C,a,Q,h,u;if(this.oneOutputMode){let d=t[0];C=o%16*2,a=d[C],Q=d[C+1]}else C=o%this._outputsAmount+2,a=t[C][0],Q=t[C][1],h=t[0],u=t[1];let f=n.voices;n.voices=[],f.forEach(d=>{this.renderVoice(n,d,a,Q,h,u),d.finished||n.voices.push(d)}),s+=f.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};F.prototype.renderVoice=Xs;F.prototype.releaseVoice=_s;F.prototype.voiceKilling=Ws;F.prototype.handleMessage=zs;F.prototype.sendChannelProperties=$s;F.prototype.callEvent=js;F.prototype.systemExclusive=An;F.prototype.noteOn=nn;F.prototype.noteOff=on;F.prototype.polyPressure=fn;F.prototype.killNote=In;F.prototype.stopAll=rn;F.prototype.stopAllChannels=gn;F.prototype.muteChannel=yn;F.prototype.setVibrato=kn;F.prototype.disableAndLockVibrato=Dn;F.prototype.dataEntryCoarse=wn;F.prototype.dataEntryFine=Fn;F.prototype.createWorkletChannel=Ds;F.prototype.controllerChange=un;F.prototype.channelPressure=ln;F.prototype.resetAllControllers=Rn;F.prototype.resetControllers=Gn;F.prototype.resetParameters=xn;F.prototype.setMasterGain=pn;F.prototype.setMasterPan=Sn;F.prototype.setMIDIVolume=mn;F.prototype.transposeAllChannels=an;F.prototype.transposeChannel=Cn;F.prototype.setChannelTuning=En;F.prototype.setChannelTuningSemitones=Bn;F.prototype.setMasterTuning=Qn;F.prototype.setModulationDepth=hn;F.prototype.pitchWheel=cn;F.prototype.setOctaveTuning=dn;F.prototype.programChange=Mn;F.prototype.getPreset=Nn;F.prototype.setPreset=Un;F.prototype.setDrums=bn;F.prototype.reloadSoundFont=Tn;F.prototype.clearSoundFont=Hn;F.prototype.sampleDump=Yn;F.prototype.sendPresetList=Ln;F.prototype.sendSynthesizerSnapshot=Jn;F.prototype.applySynthesizerSnapshot=qn;registerProcessor(Xt,F);p("%cProcessor succesfully registered!",g.recognized); diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/worklet_soundfont_manager/worklet_soundfont_manager.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/worklet_soundfont_manager/worklet_soundfont_manager.js index 9d1bbd68..19584374 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/worklet_soundfont_manager/worklet_soundfont_manager.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/worklet_soundfont_manager/worklet_soundfont_manager.js @@ -101,7 +101,7 @@ export class WorkletSoundfontManager */ getPresetList() { - return this.presetList; + return this.presetList.slice(); } /**