spessasynth_lib 4.2.3 → 4.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,5 +18,5 @@ Destination: ${this.destinationName}`}write(){let e=new $(12);te(e,this.source.s
18
18
  (${e})`,E.warn,E.value,E.unrecognized)}toSFDestination(){let e=this.shortScale;switch(this.destination){default:case L.none:return;case L.pan:return g.pan;case L.gain:return{gen:g.initialAttenuation,newAmount:-e};case L.pitch:return g.fineTune;case L.keyNum:return g.overridingRootKey;case L.volEnvDelay:return g.delayVolEnv;case L.volEnvAttack:return g.attackVolEnv;case L.volEnvHold:return g.holdVolEnv;case L.volEnvDecay:return g.decayVolEnv;case L.volEnvSustain:return{gen:g.sustainVolEnv,newAmount:1e3-e};case L.volEnvRelease:return g.releaseVolEnv;case L.modEnvDelay:return g.delayModEnv;case L.modEnvAttack:return g.attackModEnv;case L.modEnvHold:return g.holdModEnv;case L.modEnvDecay:return g.decayModEnv;case L.modEnvSustain:return{gen:g.sustainModEnv,newAmount:1e3-e};case L.modEnvRelease:return g.releaseModEnv;case L.filterCutoff:return g.initialFilterFc;case L.filterQ:return g.initialFilterQ;case L.chorusSend:return g.chorusEffectsSend;case L.reverbSend:return g.reverbEffectsSend;case L.modLfoFreq:return g.freqModLFO;case L.modLfoDelay:return g.delayModLFO;case L.vibLfoFreq:return g.freqVibLFO;case L.vibLfoDelay:return g.delayVibLFO}}},gi=class En extends It{connectionBlocks=new Array;mode="dls2";get length(){return this.connectionBlocks.length}copyFrom(e){this.mode=e.mode;for(let t of e.connectionBlocks)this.connectionBlocks.push(yt.copyFrom(t))}fromSFZone(e){this.mode="dls2";let t=new ls;t.copyFrom(e);for(let s of t.generators){let n;switch(s.generatorType){default:continue;case g.keyNumToVolEnvDecay:{n=g.decayVolEnv;break}case g.keyNumToVolEnvHold:{n=g.holdVolEnv;break}case g.keyNumToModEnvDecay:{n=g.decayModEnv;break}case g.keyNumToModEnvHold:n=g.holdModEnv}let a=t.getGenerator(n,void 0),o=s.generatorValue*-128;if(a===void 0)continue;let i=60/128*o,r=a-i;t.setGenerator(s.generatorType,o,!1),t.setGenerator(n,r,!1)}for(let s of t.generators)yt.fromSFGenerator(s,this);for(let s of t.modulators)yt.fromSFModulator(s,this)}read(e){let t=TA(e,"lart"),s=TA(e,"lar2");if(t)for(this.mode="dls1";t.data.currentIndex<t.data.length;){let n=ge(t.data);En.verifyHeader(n,"art1","art2");let a=n.data,o=V(a,4);o!==8&&se(`CbSize in articulation mismatch. Expected 8, got ${o}`);let i=V(a,4);for(let r=0;r<i;r++)this.connectionBlocks.push(yt.read(a))}else if(s)for(this.mode="dls2";s.data.currentIndex<s.data.length;){let n=ge(s.data);En.verifyHeader(n,"art2","art1");let a=n.data,o=V(a,4);o!==8&&se(`CbSize in articulation mismatch. Expected 8, got ${o}`);let i=V(a,4);for(let r=0;r<i;r++)this.connectionBlocks.push(yt.read(a))}}write(){let e=new $(8);Be(e,8),Be(e,this.connectionBlocks.length);let t=this.connectionBlocks.map(n=>n.write()),s=Ze(this.mode==="dls2"?"art2":"art1",[e,...t]);return de(this.mode==="dls2"?"lar2":"lart",s,!1,!0)}toSFZone(e){let t=(s,n,a,o)=>{let i=s/-128;if(e.setGenerator(n,i),i<=120){let r=Math.round(.46875*s),h=this.connectionBlocks.find(I=>I.isStaticParameter&&I.destination===o);h&&e.setGenerator(a,r+h.shortScale)}};for(let s of this.connectionBlocks){let n=s.shortScale,a=s.source.source,o=s.control.source,i=s.destination;if(s.isStaticParameter){s.toSFGenerator(e);continue}if(o===Z.none)if(a===Z.keyNum){if(i===L.pitch){e.setGenerator(g.scaleTuning,n/128);continue}if(i===L.modEnvHold||i===L.modEnvDecay||i===L.volEnvHold||i==L.volEnvDecay)continue}else{let r=s.toCombinedSFDestination();if(r){e.setGenerator(r,n);continue}}s.toSFModulator(e)}this.mode==="dls1"&&e.addModulators(Re.copyFrom(hh),Re.copyFrom(gh));for(let s of this.connectionBlocks){if(s.source.source!==Z.keyNum)continue;let n=s.shortScale;switch(s.destination){default:case L.volEnvHold:{t(n,g.keyNumToVolEnvHold,g.holdVolEnv,L.volEnvHold);break}case L.volEnvDecay:{t(n,g.keyNumToVolEnvDecay,g.decayVolEnv,L.volEnvDecay);break}case L.modEnvHold:{t(n,g.keyNumToModEnvHold,g.holdModEnv,L.modEnvHold);break}case L.modEnvDecay:{t(n,g.keyNumToModEnvDecay,g.decayModEnv,L.modEnvDecay);break}}}}},Xs=class jt{channel=1;tableIndex;fusOptions=0;phaseGroup=0;constructor(e){this.tableIndex=e}static copyFrom(e){let t=new jt(e.tableIndex);return t.channel=e.channel,t.phaseGroup=e.phaseGroup,t.fusOptions=e.fusOptions,t}static read(e){let t=V(e.data,2),s=V(e.data,2),n=V(e.data,4),a=V(e.data,4),o=new jt(a);return o.channel=n,o.fusOptions=t,o.phaseGroup=s,o}static fromSFZone(e,t){let s=e.indexOf(t.sample);if(s===-1)throw new Error(`Wave link error: Sample ${t.sample.name} does not exist in the sample list.`);let n=new jt(s);switch(t.sample.sampleType){default:case xe.leftSample:case xe.monoSample:{n.channel=Math.trunc(1);break}case xe.rightSample:n.channel=2}return n}write(){let e=new $(12);return te(e,this.fusOptions),te(e,this.phaseGroup),Be(e,this.channel),Be(e,this.tableIndex),de("wlnk",e)}},es=class nt extends It{articulation=new gi;keyRange={min:0,max:127};velRange={min:0,max:127};keyGroup=0;fusOptions=0;usLayer=0;waveSample;waveLink;constructor(e,t){super(),this.waveSample=t,this.waveLink=e}static copyFrom(e){let t=new nt(Xs.copyFrom(e.waveLink),rt.copyFrom(e.waveSample));return t.keyGroup=e.keyGroup,t.keyRange={...e.keyRange},t.velRange={...e.velRange},t.usLayer=e.usLayer,t.fusOptions=e.fusOptions,t.articulation.copyFrom(e.articulation),t}static read(e,t){let s=this.verifyAndReadList(t,"rgn ","rgn2"),n=s.find(p=>p.header==="wsmp"),a=n?rt.read(n):void 0,o=s.find(p=>p.header==="wlnk");if(!o){se("Invalid DLS region: missing 'wlnk' chunk! Discarding...");return}let i=Xs.read(o),r=s.find(p=>p.header==="rgnh");if(!r){se("Invalid DLS region: missing 'rgnh' chunk! Discarding...");return}let h=e[i.tableIndex];h||nt.parsingError(`Invalid sample index: ${i.tableIndex}. Samples available: ${e.length}`),a??=h.waveSample;let I=new nt(i,a),c=V(r.data,2),l=V(r.data,2),B=V(r.data,2),d=V(r.data,2);return B===0&&d===0&&(d=127,B=0),I.keyRange.max=l,I.keyRange.min=c,I.velRange.max=d,I.velRange.min=B,I.fusOptions=V(r.data,2),I.keyGroup=V(r.data,2),r.data.length-r.data.currentIndex>=2&&(I.usLayer=V(r.data,2)),I.articulation.read(s),I}static fromSFZone(e,t){let s=rt.fromSFZone(e),n=Xs.fromSFZone(t,e),a=new nt(n,s);return a.keyRange.min=Math.max(e.keyRange.min,0),a.keyRange.max=e.keyRange.max,a.velRange.min=Math.max(e.velRange.min,0),a.velRange.max=e.velRange.max,a.keyGroup=e.getGenerator(g.exclusiveClass,0),a.articulation.fromSFZone(e),a}write(){let e=[this.writeHeader(),this.waveSample.write(),this.waveLink.write(),this.articulation.write()];return Ze("rgn2",e,!0)}toSFZone(e,t){let s=t[this.waveLink.tableIndex];s||nt.parsingError(`Invalid sample index: ${this.waveLink.tableIndex}`);let n=e.createZone(s);return n.keyRange=this.keyRange,n.velRange=this.velRange,this.keyRange.max===127&&this.keyRange.min===0&&(n.keyRange.min=-1),this.velRange.max===127&&this.velRange.min===0&&(n.velRange.min=-1),this.keyGroup!==0&&n.setGenerator(g.exclusiveClass,this.keyGroup),this.waveSample.toSFZone(n,s),this.articulation.toSFZone(n),n.generators=n.generators.filter(a=>a.generatorValue!==oA[a.generatorType].def),n}writeHeader(){let e=new $(12);return te(e,Math.max(this.keyRange.min,0)),te(e,this.keyRange.max),te(e,Math.max(this.velRange.min,0)),te(e,this.velRange.max),te(e,this.fusOptions),te(e,this.keyGroup),te(e,this.usLayer),de("rgnh",e)}},Zs=class As extends It{articulation=new gi;regions=new Array;name="Unnamed";bankLSB=0;bankMSB=0;isGMGSDrum=!1;program=0;static copyFrom(e){let t=new As;t.name=e.name,t.isGMGSDrum=e.isGMGSDrum,t.bankMSB=e.bankMSB,t.bankLSB=e.bankLSB,t.program=e.program,t.articulation.copyFrom(e.articulation);for(let s of e.regions)t.regions.push(es.copyFrom(s));return t}static read(e,t){let s=this.verifyAndReadList(t,"ins "),n=s.find(l=>l.header==="insh");if(!n)throw j(),new Error("No instrument header!");let a="",o=TA(s,"INFO");if(o){let l=ge(o.data);for(;l.header!=="INAM";)l=ge(o.data);a=pe(l.data,l.data.length).trim()}a.length===0&&(a="Unnamed Instrument");let i=new As;i.name=a;let r=V(n.data,4),h=V(n.data,4),I=V(n.data,4);i.program=I&127,i.bankMSB=h>>>8&127,i.bankLSB=h&127,i.isGMGSDrum=h>>>31>0,Xe(`%cParsing %c"${a}"%c...`,E.info,E.recognized,E.info);let c=TA(s,"lrgn");if(!c)throw j(),new Error("No region list!");i.articulation.read(s);for(let l=0;l<r;l++){let B=ge(c.data);this.verifyHeader(B,"LIST");let d=pe(B.data,4);d!=="rgn "&&d!=="rgn2"&&(j(),this.parsingError(`Invalid DLS region! Expected "rgn " or "rgn2" got "${d}"`));let p=es.read(e,B);p&&i.regions.push(p)}return j(),i}static fromSFPreset(e,t){let s=new As;s.name=e.name,s.bankLSB=e.bankLSB,s.bankMSB=e.bankMSB,s.program=e.program,s.isGMGSDrum=e.isGMGSDrum,tA(`%cConverting %c${e.toString()}%c to DLS...`,E.info,E.value,E.info);let n=e.toFlattenedInstrument();for(let a of n.zones)s.regions.push(es.fromSFZone(a,t));return j(),s}write(){Xe(`%cWriting %c${this.name}%c...`,E.info,E.recognized,E.info);let e=[this.writeHeader()],t=this.regions.map(n=>n.write());e.push(Ze("lrgn",t,!0)),this.articulation.length>0&&e.push(this.articulation.write());let s=de("INAM",fA(this.name,!0));return e.push(de("INFO",s,!1,!0)),j(),Ze("ins ",e,!0)}toSFPreset(e){let t=new Rt(e);t.name=this.name,t.bankMSB=this.bankMSB,t.bankLSB=this.bankLSB,t.isGMGSDrum=this.isGMGSDrum,t.program=this.program;let s=new Ft;s.name=this.name,t.createZone(s),this.articulation.toSFZone(s.globalZone);for(let n of this.regions)n.toSFZone(s,e.samples);s.globalize(),s.globalZone.modulators.some(n=>n.destination===g.reverbEffectsSend)||s.globalZone.addModulators(Re.copyFrom(oi)),s.globalZone.modulators.some(n=>n.destination===g.chorusEffectsSend)||s.globalZone.addModulators(Re.copyFrom(hi)),s.globalZone.generators=s.globalZone.generators.filter(n=>n.generatorValue!==oA[n.generatorType].def),e.addPresets(t),e.addInstruments(s)}writeHeader(){let e=new $(12);Be(e,this.regions.length);let t=(this.bankMSB&127)<<8|this.bankLSB&127;return this.isGMGSDrum&&(t|=1<<31),Be(e,t),Be(e,this.program&127),de("insh",e)}},Ii={progressFunction:void 0},ci=class Bn extends It{samples=new Array;instruments=new Array;soundBankInfo={name:"Unnamed",creationDate:new Date,software:"SpessaSynth",soundEngine:"DLS Level 2.2",version:{major:2,minor:4}};static read(e){if(!e)throw new Error("No data provided!");let t=new $(e);tA("%cParsing DLS file...",E.info);let s=ge(t,!1);this.verifyHeader(s,"RIFF"),this.verifyText(pe(t,4).toLowerCase(),"dls ");let n=[];for(;t.currentIndex<t.length;)n.push(ge(t));let a=new Bn;a.soundBankInfo.name="Unnamed DLS",a.soundBankInfo.product="SpessaSynth DLS",a.soundBankInfo.comment="(no description)";let o=TA(n,"INFO");if(o)for(;o.data.currentIndex<o.data.length;){let d=ge(o.data),p=d.header,w=pe(d.data,d.size);switch(p){case"INAM":{a.soundBankInfo.name=w;break}case"ICRD":{a.soundBankInfo.creationDate=Dn(w);break}case"ICMT":{a.soundBankInfo.comment=w;break}case"ISBJ":{a.soundBankInfo.subject=w;break}case"ICOP":{a.soundBankInfo.copyright=w;break}case"IENG":{a.soundBankInfo.engineer=w;break}case"IPRD":{a.soundBankInfo.product=w;break}case"ISFT":a.soundBankInfo.software=w}}this.printInfo(a);let i=n.find(d=>d.header==="colh");if(!i)return this.parsingError("No colh chunk!"),5;let r=V(i.data,4);D(`%cInstruments amount: %c${r}`,E.info,E.recognized);let h=TA(n,"wvpl");if(!h)return this.parsingError("No wvpl chunk!"),5;let I=this.verifyAndReadList(h,"wvpl");for(let d of I)a.samples.push(fa.read(d));let c=TA(n,"lins");if(!c)return this.parsingError("No lins chunk!"),5;let l=this.verifyAndReadList(c,"lins");Xe("%cLoading instruments...",E.info),l.length!==r&&se(`Colh reported invalid amount of instruments. Detected ${l.length}, expected ${r}`);for(let d of l)a.instruments.push(Zs.read(a.samples,d));j();let B=n.find(d=>d.header==="pgal");if(B){D("%cFound the instrument aliasing chunk!",E.recognized);let d=B.data;(d[0]!==0||d[1]!==1||d[2]!==2||d[3]!==3)&&(d.currentIndex+=4);let p=a.instruments.find(G=>Fe.isXGDrums(G.bankMSB)||G.isGMGSDrum);if(!p)return se("MobileBAE aliasing chunk without a drum preset. Aborting!"),a;let w=d.slice(d.currentIndex,d.currentIndex+128);d.currentIndex+=128;for(let G=0;G<128;G++){let F=w[G];if(F===G)continue;let b=p.regions.find(O=>O.keyRange.max===F&&O.keyRange.min===F);if(!b){se(`Invalid drum alias ${G} to ${F}: region does not exist.`);continue}let k=es.copyFrom(b);k.keyRange.max=G,k.keyRange.min=G,p.regions.push(k)}for(d.currentIndex+=4;d.currentIndex<d.length;){let G=V(d,2),F=G&127,b=G>>7&127,k=d[d.currentIndex++],O=d[d.currentIndex++];O!==0&&se(`Invalid alias byte. Expected 0, got ${O}`);let C=V(d,2),Y=C&127,q=C>>7&127,x=d[d.currentIndex++];O=d[d.currentIndex++],O!==0&&se(`Invalid alias header. Expected 0, got ${O}`);let M=a.instruments.find(K=>K.bankLSB===Y&&K.bankMSB===q&&K.program===x&&!K.isGMGSDrum);if(!M){se(`Invalid alias. Missing instrument: ${Y}:${q}:${x}`);continue}let U=Zs.copyFrom(M);U.bankMSB=b,U.bankLSB=F,U.program=k,a.instruments.push(U)}}return D(`%cParsing finished! %c"${a.soundBankInfo.name||"UNNAMED"}"%c has %c${a.instruments.length}%c instruments and %c${a.samples.length}%c samples.`,E.info,E.recognized,E.info,E.recognized,E.info,E.recognized,E.info),j(),a}static fromSF(e){Xe("%cSaving SF2 to DLS level 2...",E.info);let t=new Bn;t.soundBankInfo={...e.soundBankInfo},t.soundBankInfo.comment=(t.soundBankInfo.comment??"(No description)")+`
19
19
  Converted from SF2 to DLS with SpessaSynth`;for(let s of e.samples)t.samples.push(fa.fromSFSample(s));for(let s of e.presets)t.instruments.push(Zs.fromSFPreset(s,e.samples));return D("%cConversion complete!",E.recognized),j(),t}static printInfo(e){for(let[t,s]of Object.entries(e.soundBankInfo)){if(typeof s=="object"&&"major"in s){let n=s;D(`%c${t}: %c"${n.major}.${n.minor}"`,E.info,E.recognized)}D(`%c${t}: %c${s.toLocaleString()}`,E.info,E.recognized)}}async write(e=Ii){Xe("%cSaving DLS...",E.info);let t=new $(4);Be(t,this.instruments.length);let s=de("colh",t);Xe("%cWriting instruments...",E.info);let n=Ze("lins",this.instruments.map(w=>w.write()),!0);D("%cSuccess!",E.recognized),j(),Xe("%cWriting WAVE samples...",E.info);let a=0,o=[],i=[],r=0;for(let w of this.samples){let G=w.write();await e?.progressFunction?.(w.name,r,this.samples.length),o.push(a),a+=G.length,i.push(G),r++}let h=Ze("wvpl",i,!0);D("%cSucceeded!",E.recognized);let I=new $(8+4*o.length);Be(I,8),Be(I,o.length);for(let w of o)Be(I,w);let c=de("ptbl",I);this.soundBankInfo.software="SpessaSynth";let l=[],B=(w,G)=>{l.push(de(w,fA(G,!0)))};for(let[w,G]of Object.entries(this.soundBankInfo)){let F=w,b=G;if(b)switch(F){case"name":{B("INAM",b);break}case"comment":{B("ICMT",b);break}case"copyright":{B("ICOP",b);break}case"creationDate":{B("ICRD",b.toISOString());break}case"engineer":{B("IENG",b);break}case"product":{B("IPRD",b);break}case"romVersion":case"version":case"soundEngine":case"romInfo":break;case"software":{B("ISFT",b);break}case"subject":B("ISBJ",b)}}let d=Ze("INFO",l,!0);D("%cCombining everything...");let p=Ze("RIFF",[fA("DLS "),s,n,c,h,d]);return D("%cSaved successfully!",E.recognized),j(),p.buffer}toSF(){tA("%cConverting DLS to SF2...",E.info);let e=new li;e.soundBankInfo.version.minor=4,e.soundBankInfo.version.major=2,e.soundBankInfo={...this.soundBankInfo},e.soundBankInfo.comment=(e.soundBankInfo.comment??"(No description)")+`
20
20
  Converted from DLS to SF2 with SpessaSynth`;for(let t of this.samples)t.toSFSample(e);for(let t of this.instruments)t.toSFPreset(e);return e.flush(),D("%cConversion complete!",E.recognized),j(),e}},li=class ts{static isSF3DecoderReady=cs.isInitialized;soundBankInfo={name:"Unnamed",creationDate:new Date,software:"SpessaSynth",soundEngine:"E-mu 10K2",version:{major:2,minor:4}};presets=[];samples=[];instruments=[];defaultModulators=Za.map(Re.copyFrom.bind(Re));customDefaultModulators=!1;_isXGBank=!1;get isXGBank(){return this._isXGBank}static mergeSoundBanks(...e){let t=e.shift();if(!t)throw new Error("No sound banks provided!");let s=t.presets;for(;e.length>0;){let a=e?.shift()?.presets;if(a)for(let o of a)s.some(i=>o.matches(i))||s.push(o)}let n=new ts;return n.addCompletePresets(s),n.soundBankInfo={...t.soundBankInfo},n}static async getSampleSoundBankFile(){let e=new ts,t=new Float32Array(128);for(let i=0;i<128;i++)t[i]=i/128*2-1;let s=new Ah;s.name="Saw",s.originalKey=65,s.pitchCorrection=20,s.loopEnd=127,s.setAudioData(t,44100),e.addSamples(s);let n=new Ft;n.name="Saw Wave",n.globalZone.addGenerators(new He(g.initialAttenuation,375),new He(g.releaseVolEnv,-1e3),new He(g.sampleModes,1)),n.createZone(s),n.createZone(s).addGenerators(new He(g.fineTune,-9)),e.addInstruments(n);let o=new Rt(e);return o.name="Saw Wave",o.createZone(n),e.addPresets(o),e.soundBankInfo.name="Dummy",e.flush(),await e.writeSF2()}static copyFrom(e){let t=new ts;for(let s of e.presets)t.clonePreset(s);return t.soundBankInfo={...e.soundBankInfo},t}addCompletePresets(e){this.addPresets(...e);let t=[];for(let n of e)for(let a of n.zones)a.instrument&&!t.includes(a.instrument)&&t.push(a.instrument);this.addInstruments(...t);let s=[];for(let n of t)for(let a of n.zones)a.sample&&!s.includes(a.sample)&&s.push(a.sample);this.addSamples(...s)}async writeDLS(e=Ii){return ci.fromSF(this).write(e)}async writeSF2(e=cn){return ah(this,e)}addPresets(...e){this.presets.push(...e)}addInstruments(...e){this.instruments.push(...e)}addSamples(...e){this.samples.push(...e)}cloneSample(e){let t=this.samples.find(n=>n.name===e.name);if(t)return t;let s=new Cs(e.name,e.sampleRate,e.originalKey,e.pitchCorrection,e.sampleType,e.loopStart,e.loopEnd);if(e.isCompressed?s.setCompressedData(e.getRawData(!0)):s.setAudioData(e.getAudioData(),e.sampleRate),this.addSamples(s),e.linkedSample){let n=this.cloneSample(e.linkedSample);n.linkedSample||s.setLinkedSample(n,s.sampleType)}return s}cloneInstrument(e){let t=this.instruments.find(n=>n.name===e.name);if(t)return t;let s=new Ft;s.name=e.name,s.globalZone.copyFrom(e.globalZone);for(let n of e.zones)s.createZone(this.cloneSample(n.sample)).copyFrom(n);return this.addInstruments(s),s}clonePreset(e){let t=this.presets.find(n=>n.name===e.name);if(t)return t;let s=new Rt(this);s.name=e.name,s.bankMSB=e.bankMSB,s.bankLSB=e.bankLSB,s.isGMGSDrum=e.isGMGSDrum,s.program=e.program,s.library=e.library,s.genre=e.genre,s.morphology=e.morphology,s.globalZone.copyFrom(e.globalZone);for(let n of e.zones)s.createZone(this.cloneInstrument(n.instrument)).copyFrom(n);return this.addPresets(s),s}flush(){this.presets.sort(CA.sorter.bind(CA)),this.parseInternal()}trimSoundBank(e){let t=(n,a)=>{let o=0;for(let i=0;i<n.zones.length;i++){let r=n.zones[i],h=r.keyRange,I=r.velRange,c=!1;for(let l of a)if(l.key>=h.min&&l.key<=h.max&&l.velocity>=I.min&&l.velocity<=I.max){c=!0;break}!c&&r.sample&&(D(`%c${r.sample.name}%c removed from %c${n.name}%c.`,E.recognized,E.info,E.recognized,E.info),n.deleteZone(i)&&(o++,i--,D(`%c${r.sample.name}%c deleted`,E.recognized,E.info)),r.sample.useCount<1&&this.deleteSample(r.sample))}return o};tA("%cTrimming sound bank...",E.info);let s=e.getUsedProgramsAndKeys(this);Xe("%cModifying sound bank...",E.info),D("Detected keys for midi:",s);for(let n=0;n<this.presets.length;n++){let a=this.presets[n],o=s.get(a);if(o===void 0)D(`%cDeleting preset %c${a.name}%c and its zones`,E.info,E.recognized,E.info),this.deletePreset(a),n--;else{let i=[...o].map(h=>{let I=h.split("-");return{key:Number.parseInt(I[0]),velocity:Number.parseInt(I[1])}});Xe(`%cTrimming %c${a.name}`,E.info,E.recognized),D(`Keys for ${a.name}:`,i);let r=0;for(let h=0;h<a.zones.length;h++){let I=a.zones[h],c=I.keyRange,l=I.velRange,B=!1;for(let d of i)if(d.key>=c.min&&d.key<=c.max&&d.velocity>=l.min&&d.velocity<=l.max&&I.instrument){B=!0;let p=t(I.instrument,i);D(`%cTrimmed off %c${p}%c zones from %c${I.instrument.name}`,E.info,E.recognized,E.info,E.recognized);break}!B&&I.instrument&&(r++,a.deleteZone(h),I.instrument.useCount<1&&this.deleteInstrument(I.instrument),h--)}D(`%cTrimmed off %c${r}%c zones from %c${a.name}`,E.info,E.recognized,E.info,E.recognized),j()}}this.removeUnusedElements(),D("%cSound bank modified!",E.recognized),j(),j()}removeUnusedElements(){this.instruments=this.instruments.filter(e=>{e.deleteUnusedZones();let t=e.useCount<1;return t&&e.delete(),!t}),this.samples=this.samples.filter(e=>{let t=e.useCount<1;return t&&e.unlinkSample(),!t})}deleteInstrument(e){e.delete(),this.instruments.splice(this.instruments.indexOf(e),1)}deletePreset(e){e.delete(),this.presets.splice(this.presets.indexOf(e),1)}deleteSample(e){e.unlinkSample(),this.samples.splice(this.samples.indexOf(e),1)}getPreset(e,t){return Ai(this.presets,e,t)}destroySoundBank(){this.presets.length=0,this.instruments.length=0,this.samples.length=0}parsingError(e){throw new Error(`SF parsing error: ${e} The file may be corrupted.`)}parseInternal(){this._isXGBank=!1;let e=new Set([0,1,2,3,4,5,6,7,8,9,16,17,24,25,26,27,28,29,30,31,32,33,40,41,48,56,57,58,64,65,66,126,127]);for(let t of this.presets)if(Fe.isXGDrums(t.bankMSB)&&(this._isXGBank=!0,!e.has(t.program))){this._isXGBank=!1,D(`%cThis bank is not valid XG. Preset %c${t.toString()}%c is not a valid XG drum. XG mode will use presets on bank 128.`,E.info,E.value,E.info);break}}printInfo(){for(let[e,t]of Object.entries(this.soundBankInfo)){if(typeof t=="object"&&"major"in t){let s=t;D(`%c${e}: %c"${s.major}.${s.minor}"`,E.info,E.recognized)}D(`%c${e}: %c${t.toLocaleString()}`,E.info,E.recognized)}}},ch=class extends He{constructor(A){let e=A.currentIndex,t=A[e+1]<<8|A[e],s=dn(A[e+2],A[e+3]);A.currentIndex+=4,super(t,s,!1)}};function ua(A){let e=[];for(;A.data.length>A.data.currentIndex;)e.push(new ch(A.data));return e.pop(),e}var lh=class extends ja{constructor(A,e,t,s){let n=t.find(o=>o.generatorType===g.instrument),a;if(n)a=s[n.generatorValue];else throw new Error("No instrument ID found in preset zone.");if(!a)throw new Error(`Invalid instrument ID: ${n.generatorValue}, available instruments: ${s.length}`);super(A,a),this.addGenerators(...t),this.addModulators(...e)}};function Ch(A,e,t,s,n){let a=A.gen,o=A.mod,i=0,r=0;for(let h of n)for(let I=0;I<h.zonesCount;I++){let c=a[r++],l=a[r],B=e.slice(c,l),d=o[i++],p=o[i],w=t.slice(d,p);B.some(G=>G.generatorType===g.instrument)?h.createSoundFontZone(w,B,s):(h.globalZone.addGenerators(...B),h.globalZone.addModulators(...w))}}var Eh=class extends Rt{zoneStartIndex;zonesCount=0;constructor(A,e){super(e),this.name=pe(A.data,20).replace(/\d{3}:\d{3}/,""),this.program=V(A.data,2);let t=V(A.data,2);this.bankMSB=t&127,this.isGMGSDrum=(t&128)>0,this.bankLSB=t>>8,this.zoneStartIndex=V(A.data,2),this.library=V(A.data,4),this.genre=V(A.data,4),this.morphology=V(A.data,4)}createSoundFontZone(A,e,t){let s=new lh(this,A,e,t);return this.zones.push(s),s}};function ma(A,e){let t=[];for(;A.data.length>A.data.currentIndex;){let s=new Eh(A,e);if(t.length>0){let n=t[t.length-1];n.zonesCount=s.zoneStartIndex-n.zoneStartIndex}t.push(s)}return t.pop(),t}var Bh=class extends ei{constructor(A,e,t,s){let n=t.find(o=>o.generatorType===g.sampleID),a;if(n)a=s[n.generatorValue];else throw new Error("No sample ID found in instrument zone.");if(!a)throw new Error(`Invalid sample ID: ${n.generatorValue}, available samples: ${s.length}`);super(A,a),this.addGenerators(...t),this.addModulators(...e)}};function dh(A,e,t,s,n){let a=A.gen,o=A.mod,i=0,r=0;for(let h of n)for(let I=0;I<h.zonesCount;I++){let c=a[r++],l=a[r],B=e.slice(c,l),d=o[i++],p=o[i],w=t.slice(d,p);B.some(G=>G.generatorType===g.sampleID)?h.createSoundFontZone(w,B,s):(h.globalZone.addGenerators(...B),h.globalZone.addModulators(...w))}}var Qh=class extends Ft{zoneStartIndex;zonesCount=0;constructor(A){super(),this.name=pe(A.data,20),this.zoneStartIndex=V(A.data,2)}createSoundFontZone(A,e,t){let s=new Bh(this,A,e,t);return this.zones.push(s),s}};function pa(A){let e=[];for(;A.data.length>A.data.currentIndex;){let t=new Qh(A);if(e.length>0){let s=e[e.length-1];s.zonesCount=t.zoneStartIndex-s.zoneStartIndex}e.push(t)}return e.pop(),e}function Ws(A){let e=[];for(;A.data.length>A.data.currentIndex;){let t=A.data,s=V(t,2),n=V(t,2),a=dn(t[t.currentIndex++],t[t.currentIndex++]),o=V(t,2),i=V(t,2);e.push(new be(s,o,n,a,i))}return e.pop(),e}function Zt(A){let e=[],t=[];for(;A.data.length>A.data.currentIndex;)t.push(V(A.data,2)),e.push(V(A.data,2));return{mod:e,gen:t}}var fh=class extends li{sampleDataStartIndex=0;constructor(A,e=!0){if(super(),e)throw new Error("Using the constructor directly is deprecated. Use SoundBankLoader.fromArrayBuffer() instead.");let t=new $(A);tA("%cParsing a SoundFont2 file...",E.info),t||(j(),this.parsingError("No data provided!"));let s=ge(t,!1);this.verifyHeader(s,"riff");let n=pe(t,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw j(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let a=n==="sfpk",o=ge(t);this.verifyHeader(o,"list");let i=pe(o.data,4);if(i!=="INFO")throw j(),new SyntaxError(`Invalid soundFont! Expected "INFO" or "${i}"`);let r;for(;o.data.length>o.data.currentIndex;){let H=ge(o.data),y=IA(H.data,H.data.length),R=H.header;switch(R){case"ifil":case"iver":{let J=V(H.data,2),ee=V(H.data,2);R==="ifil"?this.soundBankInfo.version={major:J,minor:ee}:this.soundBankInfo.romVersion={major:J,minor:ee};break}case"DMOD":{this.defaultModulators=Ws(H),this.customDefaultModulators=!0;break}case"LIST":{pe(H.data,4)==="xdta"&&(D("%cExtended SF2 found!",E.recognized),r=H);break}case"ICRD":{this.soundBankInfo.creationDate=Dn(pe(H.data,H.data.length));break}case"ISFT":{this.soundBankInfo.software=y;break}case"IPRD":{this.soundBankInfo.product=y;break}case"IENG":{this.soundBankInfo.engineer=y;break}case"ICOP":{this.soundBankInfo.copyright=y;break}case"INAM":{this.soundBankInfo.name=y;break}case"ICMT":{this.soundBankInfo.comment=y;break}case"irom":{this.soundBankInfo.romInfo=y;break}case"isng":this.soundBankInfo.soundEngine=y}}this.printInfo();let h={};r!==void 0&&(h.phdr=ge(r.data),h.pbag=ge(r.data),h.pmod=ge(r.data),h.pgen=ge(r.data),h.inst=ge(r.data),h.ibag=ge(r.data),h.imod=ge(r.data),h.igen=ge(r.data),h.shdr=ge(r.data));let I=ge(t,!1);this.verifyHeader(I,"list"),this.verifyText(pe(t,4),"sdta"),D("%cVerifying smpl chunk...",E.warn);let c=ge(t,!1);this.verifyHeader(c,"smpl");let l;if(a){D("%cSF2Pack detected, attempting to decode the smpl chunk...",E.info);try{l=cs.decode(t.buffer.slice(t.currentIndex,t.currentIndex+I.size-12)).data[0]}catch(H){throw j(),new Error(`SF2Pack Ogg Vorbis decode error: ${H}`)}D(`%cDecoded the smpl chunk! Length: %c${l.length}`,E.info,E.value)}else l=t,this.sampleDataStartIndex=t.currentIndex;D(`%cSkipping sample chunk, length: %c${I.size-12}`,E.info,E.value),t.currentIndex+=I.size-12,D("%cLoading preset data chunk...",E.warn);let B=ge(t);this.verifyHeader(B,"list"),pe(B.data,4);let d=ge(B.data);this.verifyHeader(d,"phdr");let p=ge(B.data);this.verifyHeader(p,"pbag");let w=ge(B.data);this.verifyHeader(w,"pmod");let G=ge(B.data);this.verifyHeader(G,"pgen");let F=ge(B.data);this.verifyHeader(F,"inst");let b=ge(B.data);this.verifyHeader(b,"ibag");let k=ge(B.data);this.verifyHeader(k,"imod");let O=ge(B.data);this.verifyHeader(O,"igen");let C=ge(B.data);this.verifyHeader(C,"shdr"),D("%cParsing samples...",E.info),t.currentIndex=this.sampleDataStartIndex;let Y=da(C,l,r===void 0);if(r&&h.shdr){let H=da(h.shdr,new Float32Array(1),!1);if(H.length===Y.length)for(let[y,R]of Y.entries())R.name+=H[y].name,R.linkedSampleIndex|=H[y].linkedSampleIndex<<16}for(let H of Y)H.name=H.name.trim();this.samples.push(...Y);let q=ua(O),x=Ws(k),M=pa(F);if(r&&h.inst){let H=pa(h.inst);if(H.length===M.length){for(let[y,R]of M.entries())R.name+=H[y].name,R.zoneStartIndex|=H[y].zoneStartIndex;for(let[y,R]of M.entries())y<M.length-1&&(R.zonesCount=M[y+1].zoneStartIndex-R.zoneStartIndex)}}for(let H of M)H.name=H.name.trim();this.instruments.push(...M);let U=Zt(b);if(r&&h.ibag){let H=Zt(h.ibag);for(let y=0;y<U.mod.length;y++)U.mod[y]|=H.mod[y]<<16;for(let y=0;y<U.gen.length;y++)U.gen[y]|=H.gen[y]<<16}dh(U,q,x,this.samples,M);let K=ua(G),S=Ws(w),T=ma(d,this);if(r&&h.phdr){let H=ma(h.phdr,this);if(H.length===T.length){for(let[y,R]of T.entries())R.name+=H[y].name,R.zoneStartIndex|=H[y].zoneStartIndex;for(let[y,R]of T.entries())y<T.length-1&&(R.zonesCount=T[y+1].zoneStartIndex-R.zoneStartIndex)}}for(let H of T)H.name=H.name.trim();this.addPresets(...T);let P=Zt(p);if(r&&h.pbag){let H=Zt(h.pbag);for(let y=0;y<P.mod.length;y++)P.mod[y]|=H.mod[y]<<16;for(let y=0;y<P.gen.length;y++)P.gen[y]|=H.gen[y]<<16}Ch(P,K,S,this.instruments,T),this.flush(),D(`%cParsing finished! %c"${this.soundBankInfo.name}"%c has %c${this.presets.length}%c presets,
21
- %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,E.info,E.recognized,E.info,E.recognized,E.info,E.recognized,E.info,E.recognized,E.info),j()}verifyHeader(A,e){A.header.toLowerCase()!==e.toLowerCase()&&(j(),this.parsingError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,e){A.toLowerCase()!==e.toLowerCase()&&(j(),this.parsingError(`Invalid FourCC: Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"\``))}},Gt=class{static fromArrayBuffer(A){let e=A.slice(8,12),t=new $(e);return pe(t,4).toLowerCase()==="dls "?this.loadDLS(A):new fh(A,!1)}static loadDLS(A){return ci.read(A).toSF()}},Ci=class{processorInitialized=cs.isInitialized;sampleRate;onEventCall;process;processSplit;systemExclusive;controllerChange;noteOn;noteOff;polyPressure;channelPressure;pitchWheel;programChange;processMessage;synthCore;savedSnapshot;constructor(A,e={}){let t=Mr(A),s=Qn(e,t);if(this.sampleRate=A,!Number.isFinite(s.initialTime)||!Number.isFinite(A))throw new TypeError(`Initial time or sample rate is invalid! initial time: ${s.initialTime}, sample rate: ${A}`);this.synthCore=new $o(this.callEvent.bind(this),this.missingPreset.bind(this),this.sampleRate,s);let n=this.synthCore;this.process=n.process.bind(n),this.processSplit=n.processSplit.bind(n),this.systemExclusive=n.systemExclusive.bind(n),this.controllerChange=n.controllerChange.bind(n),this.noteOn=n.noteOn.bind(n),this.noteOff=n.noteOff.bind(n),this.polyPressure=n.polyPressure.bind(n),this.channelPressure=n.channelPressure.bind(n),this.pitchWheel=n.pitchWheel.bind(n),this.programChange=n.programChange.bind(n),this.processMessage=n.processMessage.bind(n);for(let a=0;a<Fa;a++)this.synthCore.createMIDIChannel(!1);this.processorInitialized.then(()=>{D("%cSpessaSynth is ready!",E.recognized)})}get enableEffects(){return this.synthCore.enableEffects}set enableEffects(A){this.synthCore.enableEffects=A}get enableEventSystem(){return this.synthCore.enableEventSystem}set enableEventSystem(A){this.synthCore.enableEventSystem=A}get midiChannels(){return this.synthCore.midiChannels}get totalVoicesAmount(){return this.synthCore.voiceCount}get currentSynthTime(){return this.synthCore.currentTime}get reverbProcessor(){return this.synthCore.reverbProcessor}get chorusProcessor(){return this.synthCore.chorusProcessor}get delayProcessor(){return this.synthCore.delayProcessor}get soundBankManager(){return this.synthCore.soundBankManager}get keyModifierManager(){return this.synthCore.keyModifierManager}renderAudio(A,e,t,s=0,n=0){this.synthCore.process(A[0],A[1],s,n)}renderAudioSplit(A,e,t,s=0,n=0){this.synthCore.processSplit(t,A[0],A[1],s,n)}onMissingPreset=(A,e)=>{se(`No preset found for ${CA.toMIDIString(A)}! Did you forget to add a sound bank?`)};setMasterParameter(A,e){this.synthCore.setMasterParameter(A,e)}getMasterParameter(A){return this.synthCore.getMasterParameter(A)}getAllMasterParameters(){return this.synthCore.getAllMasterParameters()}resetAllControllers(A=un){this.synthCore.resetAllControllers(A)}applySynthesizerSnapshot(A){this.savedSnapshot=A,A.apply(this),D("%cFinished applying snapshot!",E.info),this.resetAllControllers()}getSnapshot(){return bn.create(this)}getInsertionSnapshot(){return this.synthCore.getInsertionSnapshot()}setEmbeddedSoundBank(A,e){let t=Gt.fromArrayBuffer(A);this.synthCore.soundBankManager.addSoundBank(t,qt,e);let s=this.synthCore.soundBankManager.priorityOrder;s.pop(),s.unshift(qt),this.synthCore.soundBankManager.priorityOrder=s,this.savedSnapshot!==void 0&&this.applySynthesizerSnapshot(this.savedSnapshot),D(`%cEmbedded sound bank set at offset %c${e}`,E.recognized,E.value)}clearEmbeddedBank(){this.synthCore.soundBankManager.soundBankList.some(A=>A.id===qt)&&this.synthCore.soundBankManager.deleteSoundBank(qt)}createMIDIChannel(){this.synthCore.createMIDIChannel(!0)}stopAllChannels(A=!1){this.synthCore.stopAllChannels(A)}destroySynthProcessor(){this.synthCore.destroySynthProcessor()}killVoices(A){se(`killVoices is deprecated, don't use it! Amount requested: ${A}`)}clearCache(){this.synthCore.clearCache()}getVoicesForPreset(A,e,t){return this.synthCore.getVoicesForPreset(A,e,t)}callEvent(A,e){this.onEventCall?.({type:A,data:e})}missingPreset(A,e){return this.onMissingPreset(A,e)}};var Es=RA.consoleColors;var Ei="spessasynth-worklet-processor";function Bi(A,e){return{...e,...A}}var di={skipToFirstNoteOn:!0,initialPlaybackRate:1};var Nn=class extends gs{events=[];constructor(e){super(),super.copyFrom(e),this.events=[]}},Bs=class A extends ZA{tracks;embeddedSoundBank=void 0;embeddedSoundBankSize;constructor(e){super(),super.copyMetadataFrom(e),this.tracks=e.tracks.map(t=>new Nn(t)),this.embeddedSoundBankSize=e instanceof A?e.embeddedSoundBankSize:e?.embeddedSoundBank?.byteLength}};var ds={shuffleOn:1,shuffleOff:2,index:3};var Qi=1,Qs=class{synthesizer;sequencers=new Array;post;lastSequencerSync=0;alive=!1;constructor(e,t,s){this.synthesizer=new Ci(e,t),this.post=s,this.synthesizer.onEventCall=n=>{this.post({type:"eventCall",data:n,currentTime:this.synthesizer.currentSynthTime})}}createNewSequencer(){let e=new Ha(this.synthesizer),t=this.sequencers.length;this.sequencers.push(e),e.onEventCall=s=>{if(s.type==="songListChange"){let a=s.data.newSongList.map(o=>new Bs(o));this.post({type:"sequencerReturn",data:{type:s.type,data:{newSongList:a,shuffledSongIndexes:e.shuffledSongIndexes},id:t},currentTime:this.synthesizer.currentSynthTime});return}this.post({type:"sequencerReturn",data:{...s,id:t},currentTime:this.synthesizer.currentSynthTime})}}postReady(e,t,s=[]){this.post({type:"isFullyInitialized",data:{type:e,data:t},currentTime:this.synthesizer.currentSynthTime},s)}postProgress(e,t){this.post({type:"renderingProgress",data:{type:e,data:t},currentTime:this.synthesizer.currentSynthTime})}destroy(){this.synthesizer.destroySynthProcessor(),delete this.synthesizer,delete this.sequencers}handleMessage(e){let t=e.channelNumber,s;if(t>=0&&(s=this.synthesizer.midiChannels[t],s===void 0)){RA.SpessaSynthWarn(`Trying to access channel ${t} which does not exist... ignoring!`);return}switch(e.type){case"midiMessage":{this.synthesizer.processMessage(e.data.messageData,e.data.channelOffset,e.data.options);break}case"customCcChange":{s?.setCustomController(e.data.ccNumber,e.data.ccValue);break}case"ccReset":{t===gt?this.synthesizer.resetAllControllers():s?.resetControllers();break}case"stopAll":{t===gt?this.synthesizer.stopAllChannels(e.data===1):s?.stopAllNotes(e.data===1);break}case"muteChannel":{s?.muteChannel(e.data);break}case"addNewChannel":{this.synthesizer.createMIDIChannel();break}case"setMasterParameter":{this.synthesizer.setMasterParameter(e.data.type,e.data.data);break}case"setDrums":{s?.setDrums(e.data);break}case"transposeChannel":{s?.transposeChannel(e.data.semitones,e.data.force);break}case"lockController":{if(e.data.controllerNumber===gt)s?.setPresetLock(e.data.isLocked);else{if(!s)return;s.lockedControllers[e.data.controllerNumber]=e.data.isLocked}break}case"sequencerSpecific":{let n=this.sequencers[e.data.id];if(!n)return;let a=e.data;switch(a.type){default:break;case"loadNewSongList":{try{let i=a.data.map(r=>"duration"in r?ZA.copyFrom(r):ZA.fromArrayBuffer(r.binary,r.fileName));n.loadNewSongList(i)}catch(o){console.error(o),this.post({type:"sequencerReturn",data:{type:"midiError",data:o,id:e.data.id},currentTime:this.synthesizer.currentSynthTime})}break}case"pause":{n.pause();break}case"play":{n.play();break}case"setTime":{n.currentTime=a.data;break}case"changeMIDIMessageSending":{n.externalMIDIPlayback=a.data;break}case"setPlaybackRate":{n.playbackRate=a.data;break}case"setLoopCount":{n.loopCount=a.data;break}case"changeSong":{switch(a.data.changeType){case ds.shuffleOff:{n.shuffleMode=!1;break}case ds.shuffleOn:{n.shuffleMode=!0;break}case ds.index:{a.data.data!==void 0&&(n.songIndex=a.data.data);break}}break}case"getMIDI":{if(!n.midiData)throw new Error("No MIDI is loaded!");this.post({type:"sequencerReturn",data:{type:"getMIDI",data:n.midiData,id:e.data.id},currentTime:this.synthesizer.currentSynthTime});break}case"setSkipToFirstNote":{n.skipToFirstNoteOn=a.data;break}}break}case"soundBankManager":{try{let n=this.synthesizer.soundBankManager,a=e.data,o;switch(a.type){case"addSoundBank":{o=Gt.fromArrayBuffer(a.data.soundBankBuffer),n.addSoundBank(o,a.data.id,a.data.bankOffset),this.postReady("soundBankManager",null);break}case"deleteSoundBank":{n.deleteSoundBank(a.data),this.postReady("soundBankManager",null);break}case"rearrangeSoundBanks":n.priorityOrder=a.data,this.postReady("soundBankManager",null)}}catch(n){this.post({type:"soundBankError",data:n,currentTime:this.synthesizer.currentSynthTime})}break}case"keyModifierManager":{let n=e.data,a=this.synthesizer.keyModifierManager;switch(n.type){default:return;case"addMapping":{a.addMapping(n.data.channel,n.data.midiNote,n.data.mapping);break}case"clearMappings":{a.clearMappings();break}case"deleteMapping":a.deleteMapping(n.data.channel,n.data.midiNote)}break}case"requestSynthesizerSnapshot":{let n=bn.create(this.synthesizer);this.postReady("synthesizerSnapshot",n);break}case"requestNewSequencer":{this.createNewSequencer();break}case"setLogLevel":{ba(e.data.enableInfo,e.data.enableWarning,e.data.enableGroup);break}case"destroyWorklet":{this.alive=!1,this.synthesizer.destroySynthProcessor(),this.destroy();break}default:{RA.SpessaSynthWarn("Unrecognized event!",e);break}}}};var fs=class extends Qs{alive=!0;oneOutputMode;port;constructor(e,t,s,n){super(e,{enableEffects:!n.oneOutput,enableEventSystem:n?.enableEventSystem,initialTime:t},(a,o)=>{s.postMessage(a,o)}),this.port=s,this.oneOutputMode=n.oneOutput,this.synthesizer.processorInitialized.then(()=>{this.port.onmessage=a=>this.handleMessage(a.data),this.postReady("sf3Decoder",null)})}process(e,t){if(!this.alive)return!1;for(let n of this.sequencers)n.processTick();if(this.oneOutputMode){let n=t[0],a=[];for(let o=0;o<32;o+=2)a.push([n[o],n[o+1]]);this.synthesizer.enableEffects=!1,this.synthesizer.processSplit(a,n[0],n[0])}else this.synthesizer.processSplit(t.slice(1),t[0][0],t[0][1]);let s=this.synthesizer.currentSynthTime;if(s-this.lastSequencerSync>Qi){for(let n=0;n<this.sequencers.length;n++)this.post({type:"sequencerReturn",data:{type:"sync",data:this.sequencers[n].currentTime,id:n},currentTime:s});this.lastSequencerSync=s}return!0}handleMessage(e){if(e.type==="startOfflineRender"){this.startOfflineRender(e.data);return}super.handleMessage(e)}startOfflineRender(e){let t=this.sequencers[0];if(!t)return;for(let[n,a]of e.soundBankList.entries())try{this.synthesizer.soundBankManager.addSoundBank(Gt.fromArrayBuffer(a.soundBankBuffer),`bank-${n}`,a.bankOffset)}catch(o){this.post({type:"soundBankError",data:o,currentTime:this.synthesizer.currentSynthTime})}e.snapshot!==void 0&&this.synthesizer.applySynthesizerSnapshot(e.snapshot),RA.SpessaSynthInfo("%cRendering enabled! Starting render.",Es.info),t.loopCount=e.loopCount,this.synthesizer.setMasterParameter("autoAllocateVoices",!0);let s=Bi(e.sequencerOptions,di);t.skipToFirstNoteOn=s.skipToFirstNoteOn,t.playbackRate=s.initialPlaybackRate;try{t.loadNewSongList([ZA.copyFrom(e.midiSequence)]),t.play()}catch(n){console.error(n),this.post({type:"sequencerReturn",data:{type:"midiError",data:n,id:0},currentTime:this.synthesizer.currentSynthTime})}this.postReady("startOfflineRender",null)}};var Tn=class extends AudioWorkletProcessor{process;core;constructor(e){super(),this.core=new fs(sampleRate,currentTime,this.port,e.processorOptions),this.process=this.core.process.bind(this.core)}};registerProcessor(Ei,Tn);RA.SpessaSynthInfo("%cProcessor successfully registered!",Es.recognized);
21
+ %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,E.info,E.recognized,E.info,E.recognized,E.info,E.recognized,E.info,E.recognized,E.info),j()}verifyHeader(A,e){A.header.toLowerCase()!==e.toLowerCase()&&(j(),this.parsingError(`Invalid chunk header! Expected "${e.toLowerCase()}" got "${A.header.toLowerCase()}"`))}verifyText(A,e){A.toLowerCase()!==e.toLowerCase()&&(j(),this.parsingError(`Invalid FourCC: Expected "${e.toLowerCase()}" got "${A.toLowerCase()}"\``))}},Gt=class{static fromArrayBuffer(A){let e=A.slice(8,12),t=new $(e);return pe(t,4).toLowerCase()==="dls "?this.loadDLS(A):new fh(A,!1)}static loadDLS(A){return ci.read(A).toSF()}},Ci=class{processorInitialized=cs.isInitialized;sampleRate;onEventCall;process;processSplit;systemExclusive;controllerChange;noteOn;noteOff;polyPressure;channelPressure;pitchWheel;programChange;processMessage;synthCore;savedSnapshot;constructor(A,e={}){let t=Mr(A),s=Qn(e,t);if(this.sampleRate=A,!Number.isFinite(s.initialTime)||!Number.isFinite(A))throw new TypeError(`Initial time or sample rate is invalid! initial time: ${s.initialTime}, sample rate: ${A}`);this.synthCore=new $o(this.callEvent.bind(this),this.missingPreset.bind(this),this.sampleRate,s);let n=this.synthCore;this.process=n.process.bind(n),this.processSplit=n.processSplit.bind(n),this.systemExclusive=n.systemExclusive.bind(n),this.controllerChange=n.controllerChange.bind(n),this.noteOn=n.noteOn.bind(n),this.noteOff=n.noteOff.bind(n),this.polyPressure=n.polyPressure.bind(n),this.channelPressure=n.channelPressure.bind(n),this.pitchWheel=n.pitchWheel.bind(n),this.programChange=n.programChange.bind(n),this.processMessage=n.processMessage.bind(n);for(let a=0;a<Fa;a++)this.synthCore.createMIDIChannel(!1);this.processorInitialized.then(()=>{D("%cSpessaSynth is ready!",E.recognized)})}get enableEffects(){return this.synthCore.enableEffects}set enableEffects(A){this.synthCore.enableEffects=A}get enableEventSystem(){return this.synthCore.enableEventSystem}set enableEventSystem(A){this.synthCore.enableEventSystem=A}get midiChannels(){return this.synthCore.midiChannels}get totalVoicesAmount(){return this.synthCore.voiceCount}get currentSynthTime(){return this.synthCore.currentTime}get reverbProcessor(){return this.synthCore.reverbProcessor}get chorusProcessor(){return this.synthCore.chorusProcessor}get delayProcessor(){return this.synthCore.delayProcessor}get soundBankManager(){return this.synthCore.soundBankManager}get keyModifierManager(){return this.synthCore.keyModifierManager}renderAudio(A,e,t,s=0,n=0){this.synthCore.process(A[0],A[1],s,n)}renderAudioSplit(A,e,t,s=0,n=0){this.synthCore.processSplit(t,A[0],A[1],s,n)}onMissingPreset=(A,e)=>{se(`No preset found for ${CA.toMIDIString(A)}! Did you forget to add a sound bank?`)};setMasterParameter(A,e){this.synthCore.setMasterParameter(A,e)}getMasterParameter(A){return this.synthCore.getMasterParameter(A)}getAllMasterParameters(){return this.synthCore.getAllMasterParameters()}resetAllControllers(A=un){this.synthCore.resetAllControllers(A)}applySynthesizerSnapshot(A){this.savedSnapshot=A,A.apply(this),D("%cFinished applying snapshot!",E.info),this.resetAllControllers()}getSnapshot(){return bn.create(this)}getInsertionSnapshot(){return this.synthCore.getInsertionSnapshot()}setEmbeddedSoundBank(A,e){let t=Gt.fromArrayBuffer(A);this.synthCore.soundBankManager.addSoundBank(t,qt,e);let s=this.synthCore.soundBankManager.priorityOrder;s.pop(),s.unshift(qt),this.synthCore.soundBankManager.priorityOrder=s,this.savedSnapshot!==void 0&&this.applySynthesizerSnapshot(this.savedSnapshot),D(`%cEmbedded sound bank set at offset %c${e}`,E.recognized,E.value)}clearEmbeddedBank(){this.synthCore.soundBankManager.soundBankList.some(A=>A.id===qt)&&this.synthCore.soundBankManager.deleteSoundBank(qt)}createMIDIChannel(){this.synthCore.createMIDIChannel(!0)}stopAllChannels(A=!1){this.synthCore.stopAllChannels(A)}destroySynthProcessor(){this.synthCore.destroySynthProcessor()}killVoices(A){se(`killVoices is deprecated, don't use it! Amount requested: ${A}`)}clearCache(){this.synthCore.clearCache()}getVoicesForPreset(A,e,t){return this.synthCore.getVoicesForPreset(A,e,t)}callEvent(A,e){this.onEventCall?.({type:A,data:e})}missingPreset(A,e){return this.onMissingPreset(A,e)}};var Es=RA.consoleColors;var Ei="spessasynth-worklet-processor";function Bi(A,e){return{...e,...A}}var di={skipToFirstNoteOn:!0,initialPlaybackRate:1};var Nn=class extends gs{events=[];constructor(e){super(),super.copyFrom(e),this.events=[]}},Bs=class A extends ZA{tracks;embeddedSoundBank=void 0;embeddedSoundBankSize;constructor(e){super(),super.copyMetadataFrom(e),this.tracks=e.tracks.map(t=>new Nn(t)),this.embeddedSoundBankSize=e instanceof A?e.embeddedSoundBankSize:e?.embeddedSoundBank?.byteLength}};var ds={shuffleOn:1,shuffleOff:2,index:3};var Qi=1,Qs=class{synthesizer;sequencers=new Array;post;lastSequencerSync=0;alive=!1;enableEventSystem;constructor(e,t,s){this.synthesizer=new Ci(e,t),this.enableEventSystem=t.enableEventSystem,this.post=s,this.synthesizer.onEventCall=n=>{this.post({type:"eventCall",data:n,currentTime:this.synthesizer.currentSynthTime})}}createNewSequencer(){let e=new Ha(this.synthesizer),t=this.sequencers.length;this.sequencers.push(e),e.onEventCall=s=>{if(this.enableEventSystem){if(s.type==="songListChange"){let a=s.data.newSongList.map(o=>new Bs(o));this.post({type:"sequencerReturn",data:{type:s.type,data:{newSongList:a,shuffledSongIndexes:e.shuffledSongIndexes},id:t},currentTime:this.synthesizer.currentSynthTime});return}this.post({type:"sequencerReturn",data:{...s,id:t},currentTime:this.synthesizer.currentSynthTime})}}}postReady(e,t,s=[]){this.post({type:"isFullyInitialized",data:{type:e,data:t},currentTime:this.synthesizer.currentSynthTime},s)}postProgress(e,t){this.post({type:"renderingProgress",data:{type:e,data:t},currentTime:this.synthesizer.currentSynthTime})}destroy(){this.synthesizer.destroySynthProcessor(),delete this.synthesizer,delete this.sequencers}handleMessage(e){let t=e.channelNumber,s;if(t>=0&&(s=this.synthesizer.midiChannels[t],s===void 0)){RA.SpessaSynthWarn(`Trying to access channel ${t} which does not exist... ignoring!`);return}switch(e.type){case"midiMessage":{this.synthesizer.processMessage(e.data.messageData,e.data.channelOffset,e.data.options);break}case"customCcChange":{s?.setCustomController(e.data.ccNumber,e.data.ccValue);break}case"ccReset":{t===gt?this.synthesizer.resetAllControllers():s?.resetControllers();break}case"stopAll":{t===gt?this.synthesizer.stopAllChannels(e.data===1):s?.stopAllNotes(e.data===1);break}case"muteChannel":{s?.muteChannel(e.data);break}case"addNewChannel":{this.synthesizer.createMIDIChannel();break}case"setMasterParameter":{this.synthesizer.setMasterParameter(e.data.type,e.data.data);break}case"setDrums":{s?.setDrums(e.data);break}case"transposeChannel":{s?.transposeChannel(e.data.semitones,e.data.force);break}case"lockController":{if(e.data.controllerNumber===gt)s?.setPresetLock(e.data.isLocked);else{if(!s)return;s.lockedControllers[e.data.controllerNumber]=e.data.isLocked}break}case"sequencerSpecific":{let n=this.sequencers[e.data.id];if(!n)return;let a=e.data;switch(a.type){default:break;case"loadNewSongList":{try{let i=a.data.map(r=>"duration"in r?ZA.copyFrom(r):ZA.fromArrayBuffer(r.binary,r.fileName));n.loadNewSongList(i)}catch(o){console.error(o),this.post({type:"sequencerReturn",data:{type:"midiError",data:o,id:e.data.id},currentTime:this.synthesizer.currentSynthTime})}break}case"pause":{n.pause();break}case"play":{n.play();break}case"setTime":{n.currentTime=a.data;break}case"changeMIDIMessageSending":{n.externalMIDIPlayback=a.data;break}case"setPlaybackRate":{n.playbackRate=a.data;break}case"setLoopCount":{n.loopCount=a.data;break}case"changeSong":{switch(a.data.changeType){case ds.shuffleOff:{n.shuffleMode=!1;break}case ds.shuffleOn:{n.shuffleMode=!0;break}case ds.index:{a.data.data!==void 0&&(n.songIndex=a.data.data);break}}break}case"getMIDI":{if(!n.midiData)throw new Error("No MIDI is loaded!");this.post({type:"sequencerReturn",data:{type:"getMIDI",data:n.midiData,id:e.data.id},currentTime:this.synthesizer.currentSynthTime});break}case"setSkipToFirstNote":{n.skipToFirstNoteOn=a.data;break}}break}case"soundBankManager":{try{let n=this.synthesizer.soundBankManager,a=e.data,o;switch(a.type){case"addSoundBank":{o=Gt.fromArrayBuffer(a.data.soundBankBuffer),n.addSoundBank(o,a.data.id,a.data.bankOffset),this.postReady("soundBankManager",null);break}case"deleteSoundBank":{n.deleteSoundBank(a.data),this.postReady("soundBankManager",null);break}case"rearrangeSoundBanks":n.priorityOrder=a.data,this.postReady("soundBankManager",null)}}catch(n){this.post({type:"soundBankError",data:n,currentTime:this.synthesizer.currentSynthTime})}break}case"keyModifierManager":{let n=e.data,a=this.synthesizer.keyModifierManager;switch(n.type){default:return;case"addMapping":{a.addMapping(n.data.channel,n.data.midiNote,n.data.mapping);break}case"clearMappings":{a.clearMappings();break}case"deleteMapping":a.deleteMapping(n.data.channel,n.data.midiNote)}break}case"requestSynthesizerSnapshot":{let n=bn.create(this.synthesizer);this.postReady("synthesizerSnapshot",n);break}case"requestNewSequencer":{this.createNewSequencer();break}case"setLogLevel":{ba(e.data.enableInfo,e.data.enableWarning,e.data.enableGroup);break}case"destroyWorklet":{this.alive=!1,this.synthesizer.destroySynthProcessor(),this.destroy();break}default:{RA.SpessaSynthWarn("Unrecognized event!",e);break}}}};var fs=class extends Qs{alive=!0;oneOutputMode;port;constructor(e,t,s,n){super(e,{enableEffects:!n.oneOutput,enableEventSystem:n?.enableEventSystem,initialTime:t},(a,o)=>{s.postMessage(a,o)}),this.port=s,this.oneOutputMode=n.oneOutput,this.synthesizer.processorInitialized.then(()=>{this.port.onmessage=a=>this.handleMessage(a.data),this.postReady("sf3Decoder",null)})}process(e,t){if(!this.alive)return!1;for(let n of this.sequencers)n.processTick();if(this.oneOutputMode){let n=t[0],a=[];for(let o=0;o<32;o+=2)a.push([n[o],n[o+1]]);this.synthesizer.enableEffects=!1,this.synthesizer.processSplit(a,n[0],n[0])}else this.synthesizer.processSplit(t.slice(1),t[0][0],t[0][1]);let s=this.synthesizer.currentSynthTime;if(this.enableEventSystem&&s-this.lastSequencerSync>Qi){for(let n=0;n<this.sequencers.length;n++)this.post({type:"sequencerReturn",data:{type:"sync",data:this.sequencers[n].currentTime,id:n},currentTime:s});this.lastSequencerSync=s}return!0}handleMessage(e){if(e.type==="startOfflineRender"){this.startOfflineRender(e.data);return}super.handleMessage(e)}startOfflineRender(e){this.sequencers.length===0&&this.createNewSequencer();let t=this.sequencers[0];for(let[n,a]of e.soundBankList.entries())try{this.synthesizer.soundBankManager.addSoundBank(Gt.fromArrayBuffer(a.soundBankBuffer),`bank-${n}`,a.bankOffset)}catch(o){this.post({type:"soundBankError",data:o,currentTime:this.synthesizer.currentSynthTime})}e.snapshot!==void 0&&this.synthesizer.applySynthesizerSnapshot(e.snapshot),RA.SpessaSynthInfo("%cRendering enabled! Starting render.",Es.info),t.loopCount=e.loopCount,this.synthesizer.setMasterParameter("autoAllocateVoices",!0);let s=Bi(e.sequencerOptions,di);t.skipToFirstNoteOn=s.skipToFirstNoteOn,t.playbackRate=s.initialPlaybackRate;try{t.loadNewSongList([ZA.copyFrom(e.midiSequence)]),t.play()}catch(n){console.error(n),this.post({type:"sequencerReturn",data:{type:"midiError",data:n,id:0},currentTime:this.synthesizer.currentSynthTime})}this.postReady("startOfflineRender",null)}};var Tn=class extends AudioWorkletProcessor{process;core;constructor(e){super(),this.core=new fs(sampleRate,currentTime,this.port,e.processorOptions),this.process=this.core.process.bind(this.core)}};registerProcessor(Ei,Tn);RA.SpessaSynthInfo("%cProcessor successfully registered!",Es.recognized);
22
22
  //# sourceMappingURL=spessasynth_processor.min.js.map