From 16698c0806bcc9fa694a87edad9cd4ee5cd7893e Mon Sep 17 00:00:00 2001 From: spessasus Date: Wed, 4 Sep 2024 16:47:13 +0200 Subject: [PATCH] Fix ModLfoToVol again and add interpolation type to snapshot and add negative multipliers --- package.json | 2 +- src/spessasynth_lib/synthetizer/worklet_processor.min.js | 4 ++-- .../synthetizer/worklet_system/worklet_methods/snapshot.js | 5 ++++- .../worklet_system/worklet_methods/voice_control.js | 4 ++-- src/website/js/renderer/render_waveforms.js | 2 +- src/website/js/renderer/renderer.js | 1 - src/website/js/settings_ui/settings_html.js | 2 +- src/website/minified/demo_main.min.js | 4 ++-- src/website/minified/local_main.min.js | 4 ++-- 9 files changed, 15 insertions(+), 13 deletions(-) diff --git a/package.json b/package.json index 4ac5f257..5dd9988f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "SpessaSynth", - "version": "3.20.10", + "version": "3.20.11", "type": "module", "scripts": { "start": "node src/website/server/server.js" diff --git a/src/spessasynth_lib/synthetizer/worklet_processor.min.js b/src/spessasynth_lib/synthetizer/worklet_processor.min.js index fd0f571a..ec8ce984 100644 --- a/src/spessasynth_lib/synthetizer/worklet_processor.min.js +++ b/src/spessasynth_lib/synthetizer/worklet_processor.min.js @@ -8,9 +8,9 @@ var rs=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(A,t)=>( `}};function KA(e,A,t,s,n){return e<<10|A<<9|t<<8|s<<7|n}var ft=960,dt=lA.concave,ws=[new rA({srcEnum:KA(dt,0,1,0,v.noteOnVelocity),dest:a.initialAttenuation,amt:ft,secSrcEnum:0,transform:0}),new rA({srcEnum:129,dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(dt,0,1,1,S.mainVolume),dest:a.initialAttenuation,amt:ft,secSrcEnum:0,transform:0}),new rA({srcEnum:13,dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new rA({srcEnum:526,dest:a.fineTune,amt:12700,secSrcEnum:16,transform:0}),new rA({srcEnum:650,dest:a.pan,amt:1e3,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(dt,0,1,1,S.expressionController),dest:a.initialAttenuation,amt:ft,secSrcEnum:0,transform:0}),new rA({srcEnum:219,dest:a.reverbEffectsSend,amt:200,secSrcEnum:0,transform:0}),new rA({srcEnum:221,dest:a.chorusEffectsSend,amt:200,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(lA.linear,0,0,0,v.polyPressure),dest:a.vibLfoToPitch,amt:50,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(lA.linear,0,0,1,S.effects2Depth),dest:a.modLfoToVolume,amt:24,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(lA.linear,1,0,1,S.releaseTime),dest:a.releaseVolEnv,amt:1200,secSrcEnum:0,transform:0}),new rA({srcEnum:KA(lA.linear,1,0,1,S.brightness),dest:a.initialFilterFc,amt:4e3,secSrcEnum:0,transform:0})];function mt(e){let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(new rA(e.chunkData));return A}function Fs(e=!1){let A={midiControllers:new Int16Array(pt),lockedControllers:Array(pt).fill(!1),customControllers:new Float32Array(Rs),NRPCoarse:0,NRPFine:0,RPValue:0,dataEntryState:uA.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 gA=128,pt=147,PA=new Int16Array(pt).fill(0);PA[S.mainVolume]=12800;PA[S.expressionController]=16256;PA[S.pan]=8192;PA[S.releaseTime]=8192;PA[S.brightness]=8192;PA[S.effects1Depth]=5120;PA[gA+v.pitchWheel]=8192;PA[gA+v.pitchWheelRange]=256;var uA={Idle:0,RPCoarse:1,RPFine:2,NRPCoarse:3,NRPFine:4,DataCoarse:5,DataFine:6},iA={channelTuning:0,channelTransposeFine:1,modulationMultiplier:2,masterTuning:3,channelTuningSemitones:4},Rs=Object.keys(iA).length,St=new Float32Array(Rs);St[iA.modulationMultiplier]=1;var Pe={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 ve=class{constructor(){this.timeDivision=0,this.duration=0,this.tempoChanges=[{ticks:0,tempo:120}],this.copyright="",this.tracksAmount=0,this.lyrics=[],this.firstNoteOn=0,this.keyRange={min:0,max:127},this.lastVoiceEventTick=0,this.midiPorts=[0],this.midiPortChannelOffsets=[0],this.usedChannelsOnTrack=[],this.loop={start:0,end:0},this.midiName="",this.fileName="",this.rawMidiName=void 0,this.embeddedSoundFont=void 0,this.format=0,this.RMIDInfo={},this.bankOffset=0,this.tracks=[]}_ticksToSeconds(A){if(A<=0)return 0;let t=this.tempoChanges.find(n=>n.ticks0&&(Z+=this.tracks[y-1][this.tracks[y-1].length-1].ticks);G.data.currentIndexthis.lastVoiceEventTick&&(this.lastVoiceEventTick=Z),K=as[r>>4],(r&240)===w.noteOn){M.add(sA);let aA=G.data[G.data.currentIndex];this.keyRange.min=Math.min(this.keyRange.min,aA),this.keyRange.max=Math.max(this.keyRange.max,aA)}N=r;break}let z=new Y(K),$=G.data.slice(G.data.currentIndex,G.data.currentIndex+K);G.data.currentIndex+=K,z.set($,0);let QA=new oe(Z,r,z);switch(k.push(QA),sA){case-2:switch(r){case w.setTempo:this.tempoChanges.push({ticks:Z,tempo:6e7/WA($,3)});break;case w.marker:switch(V(z,z.length).trim().toLowerCase()){default:break;case"start":case"loopstart":d=Z;break;case"loopend":u=Z}z.currentIndex=0;break;case w.midiPort:let TA=z[0];this.midiPorts[y]=TA,this.midiPortChannelOffsets[TA]===void 0&&(this.midiPortChannelOffsets[TA]=Q,Q+=16);break;case w.copyright:o||(this.copyright+=V(z,z.length,void 0,!1)+` `);break;case w.lyric:this.lyrics.push(z)}break;case-3:if(hA(z.slice(0,7)).trim()==="41 10 45 12 10 00 00"){let aA=z.slice(7,$.length-3),TA=V(aA,aA.length)+` -`;this.copyright+=TA,p(`%cDecoded Roland SC message! %c${TA}`,I.recognized,I.value)}break;default:if((r&240)===w.controllerChange)switch(z[0]){case 2:case 116:d=Z;break;case 4:case 117:u===null?u=Z:u=0;break;case 0:g&&z[1]!==0&&z[1]!==127&&(p("%cDLS RMIDI with offset 1 detected!",I.recognized),this.bankOffset=1)}}}this.tracks.push(k),this.usedChannelsOnTrack.push(M),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,I.info,I.value,I.info,I.value)}let l=[];for(let y of this.tracks){let k=y.find(G=>(G.messageStatusByte&240)===w.noteOn);k&&l.push(k.ticks)}this.firstNoteOn=Math.min(...l),p(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}`,I.info,I.recognized),X(),d!==null&&u===null?(d=this.firstNoteOn,u=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(u===null||u===0)&&(u=this.lastVoiceEventTick));let m=0;for(let y of this.midiPorts)if(y!==-1){m=y;break}if(this.midiPorts=this.midiPorts.map(y=>y===-1?m:y),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.loop={start:d,end:u},!E)if(this.tracks.length>1){if(this.tracks[0].find(y=>y.messageStatusByte>=w.noteOn&&y.messageStatusBytek.messageStatusByte===w.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=V(y.messageData,y.messageData.length,void 0,!1))}}else{let y=this.tracks[0].find(k=>k.messageStatusByte===w.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=V(y.messageData,y.messageData.length,void 0,!1))}if(this.fileName=t,this.midiName=this.midiName.trim(),this.midiName.length===0){this.midiName=is(t),this.rawMidiName=new Uint8Array(this.midiName.length);for(let y=0;yQ>u?Q:u),s=[];for(let u=0;u{E[m]>=l.length||l[E[m]].ticks0;){let u=h(),Q=e.tracks[u];if(E[u]>=Q.length){g--;continue}let l=Q[E[u]];if(E[u]++,l.messageStatusByte===w.midiPort){c[u]=l.messageData[0];continue}let m=l.messageStatusByte&240;if(m!==w.noteOn&&m!==w.controllerChange&&m!==w.programChange&&m!==w.systemExclusive)continue;let y=(l.messageStatusByte&15)+e.midiPortChannelOffsets[c[u]]||0,k=s[y];switch(m){case w.programChange:k.program=l.messageData[0],n(k);break;case w.controllerChange:if(l.messageData[0]!==S.bankSelect||d==="gs"&&k.drums)continue;let G=l.messageData[1],M=Math.max(0,G-e.bankOffset);if(d==="xg"){let H=G===120||G===126||G===127;H!==k.drums?(k.drums=H,k.bank=k.drums?128:M,n(k)):k.bank=k.drums?128:M;continue}s[y].bank=M;break;case w.noteOn:if(l.messageData[1]===0)continue;n(k),o[k.string].add(`${l.messageData[0]}-${l.messageData[1]}`);break;case w.systemExclusive:if(l.messageData[0]!==65||l.messageData[2]!==66||l.messageData[3]!==18||l.messageData[4]!==64||!(l.messageData[5]&16)||l.messageData[6]!==21){l.messageData[0]===67&&l.messageData[2]===76&&l.messageData[5]===126&&l.messageData[6]===0&&(d="xg");continue}let N=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][l.messageData[5]&15]+e.midiPortChannelOffsets[c[u]],Z=!!(l.messageData[7]>0&&l.messageData[5]>>4);k=s[N],k.drums=Z,k.bank=Z?128:0,n(k);break}}for(let u of Object.keys(o))o[u].size===0&&(p(`%cDetected change but no keys for %c${u}`,I.info,I.value),delete o[u]);return X(),o}function xs(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),DA("%cPreloading samples...",I.info);let A=Gs(this.midiData,this.synth.soundfontManager);for(let[t,s]of Object.entries(A)){let n=parseInt(t.split(":")[0]),o=parseInt(t.split(":")[1]),E=this.synth.getPreset(n,o);p(`%cPreloading used samples on %c${E.presetName}%c...`,I.info,I.recognized,I.info);for(let g of s){let h=g.split("-");E.preloadSpecific(parseInt(h[0]),parseInt(h[1]))}}X()}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=Je(this.midiData.tempoChanges,this.midiData.firstNoteOn,this.midiData.timeDivision),p(`%cTotal song time: ${ct(Math.ceil(this.duration)).time}`,I.recognized),this.post(kA.songChange,[new qe(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(b(`%cVery short song: (${ct(Math.round(this.duration)).time}). Disabling loop!`,I.warn),this.loop=!1),this.play(!0)}function Ns(e){this.songs=e.reduce((A,t)=>{if(t.duration)return A.push(t),A;try{A.push(new Ve(t.binary,t.altName||""))}catch(s){return this.post(kA.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 bs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Ls(){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 Us(e,A){switch(e){default:break;case MA.loadNewSongList:this.loadNewSongList(A);break;case MA.pause:this.pause();break;case MA.play:this.play(A);break;case MA.stop:this.stop();break;case MA.setTime:this.currentTime=A;break;case MA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case MA.setPlaybackRate:this.playbackRate=A;break;case MA.setLoop:this.loop=A;break;case MA.changeSong:A?this.nextSong():this.previousSong();break;case MA.getMIDI:this.post(kA.getMIDI,this.midiData);break;case MA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Ts(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:mA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function Hs(e){this.post(kA.midiEvent,e)}var CA=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&&AYs?440*Math.pow(2,(e-6900)/1200):Dt[~~e-Oe]}var wt=-1660,Ro=1600,kt=new Float32Array((Ro-wt)*100+1);for(let e=0;e.5?1:0,s?t*2-1:t;case lA.concave:return s?(t=t*2-1,t<0?1-ge[~~(t*-IA)]-1:ge[~~t*IA]):ge[~~(t*IA)];case lA.convex:return s?(t=t*2-1,t<0?1-Ce[~~(t*-IA)]-1:Ce[~~(t*IA)]):Ce[~~(t*IA)]}}var Ft=1,Rt=new Float32Array(1e3);for(let e=0;e=e.sample.loopEnd;)s-=o;let g=~~s,h=g+1;for(;h>=e.sample.loopEnd;)h-=o;let c=s-g,d=A[h],u=A[g];t[E]=u+(d-u)*c,s+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=A.length&&(e.sample.end=A.length-1);for(let E=0;E=e.sample.end){e.finished=!0;return}let c=s-g,d=A[h],u=A[g];t[E]=u+(d-u)*c,s+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=s}function qs(e,A,t){let s=e.sample.cursor,n=e.sample.loopingMode===1||e.sample.loopingMode===3&&!e.isInRelease,o=e.sample.loopEnd-e.sample.loopStart;if(n)for(let E=0;E=e.sample.loopEnd;)s-=o;let g=~~s+1;for(;g>=e.sample.loopEnd;)g-=o;t[E]=A[g],s+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=A.length&&(e.sample.end=A.length-1);for(let E=0;E=e.sample.end){e.finished=!0;return}t[E]=A[g],s+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=s}function Ks(e,A,t,s,n,o,E,g,h){if(!isNaN(t[0])){if(E>0){let c=o[0],d=o[1];E=Math.min(E,1e3);let u=E/800,Q=e*u,l=A*u;for(let m=0;m0){let c=g[0],d=g[1];h=Math.min(h,1e3);let u=h/800,Q=e*u,l=A*u;for(let m=0;m0)for(let c=0;c0)for(let c=0;c13499)){(e.filter.cutoffCents!==t||e.filter.reasonanceCb!==e.modulatedGenerators[a.initialFilterQ])&&(e.filter.cutoffCents=t,e.filter.reasonanceCb=e.modulatedGenerators[a.initialFilterQ],Go(e));for(let s=0;s.45*sampleRate&&(e.filter.cutoffHz=.45*sampleRate);let A=e.filter.reasonanceCb/10-3.01;e.filter.reasonanceGain=_A(-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),E=(1-n)*t,g=E/2,h=g,c=1+o,d=-2*n,u=1-o;e.filter.a0=g/c,e.filter.a1=E/c,e.filter.a2=h/c,e.filter.a3=d/c,e.filter.a4=u/c}var Vs=.001,De=100,Gt=70,NA=class e{constructor(A){this.sampleRate=A}currentSampleTime=0;sampleRate;currentAttenuationDb=De;state=0;releaseStartDb=100;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;sustainDb=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=_A(A.volumeEnvelope.currentAttenuationDb),e.recalculate(A)}static recalculate(A){let t=A.volumeEnvelope,s=h=>Math.floor(LA(h)*t.sampleRate);t.attenuation=A.modulatedGenerators[a.initialAttenuation]/10,t.sustainDb=Math.min(100,A.volumeEnvelope.attenuation+A.modulatedGenerators[a.sustainVolEnv]/10),t.attackDuration=s(A.modulatedGenerators[a.attackVolEnv]);let n=A.modulatedGenerators[a.decayVolEnv],o=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvDecay],E=(t.sustainDb-t.attenuation)/100;t.decayDuration=s(n+o)*E,t.releaseDuration=s(A.modulatedGenerators[a.releaseVolEnv]),t.delayEnd=s(A.modulatedGenerators[a.delayVolEnv]),t.attackEnd=t.attackDuration+t.delayEnd;let g=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvHold];if(t.holdEnd=s(A.modulatedGenerators[a.holdVolEnv]+g)+t.attackEnd,t.decayEnd=t.decayDuration+t.holdEnd,A.isInRelease){switch(t.state){case 0:t.releaseStartDb=De;break;case 1:let c=(1-(t.attackEnd-t.releaseStartTimeSamples)/t.attackDuration)*_A(t.attenuation);t.releaseStartDb=20*Math.log10(c)*-1;break;case 2:t.releaseStartDb=t.attenuation;break;case 3:t.releaseStartDb=(1-(t.decayEnd-t.releaseStartTimeSamples)/t.decayDuration)*(t.sustainDb-t.attenuation)+t.attenuation;break;case 4:t.releaseStartDb=t.sustainDb;break;default:t.releaseStartDb=t.currentAttenuationDb}t.releaseStartDb=Math.min(t.releaseStartDb,De),t.releaseStartDb>=Gt&&(A.finished=!0)}}static getInterpolatedGain(A,t,s){return A.currentAttenuationDb+=(t-A.currentAttenuationDb)*s,_A(A.currentAttenuationDb)}static apply(A,t,s,n){let o=A.volumeEnvelope,E=s/10;if(A.isInRelease){let h=n*10,c=o.currentSampleTime-o.releaseStartTimeSamples;if(c>=o.releaseDuration){for(let Q=0;Q=Gt&&(A.finished=!0);return}let g=0;switch(o.state){case 0:for(;o.currentSampleTime=t.length)return;o.state++;case 1:for(;o.currentSampleTime=t.length)return}o.state++;case 2:for(;o.currentSampleTime=t.length)return;o.state++;case 3:let h=o.sustainDb-o.attenuation;for(;o.currentSampleTime=t.length)return}o.state++;case 4:if(o.sustainDb>Gt){for(A.finished=!0;g=t.length)return}}};var Os=Math.PI/2,Zs=.01;function Xs(e,A,t,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,NA.startRelease(A),UA.startRelease(A)),A.modulatedGenerators[a.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let E=A.targetKey,g=A.modulatedGenerators[a.fineTune]+e.customControllers[iA.channelTuning]+e.customControllers[iA.channelTransposeFine]+e.customControllers[iA.masterTuning]+e.channelOctaveTuning[A.midiNote%12],h=A.modulatedGenerators[a.coarseTune]+e.customControllers[iA.channelTuningSemitones],c=this.tunings[e.preset.program]?.[E];c?.midiNote>=0&&(E=c.midiNote,g+=c.centTuning),g+=(E-A.sample.rootKey)*A.modulatedGenerators[a.scaleTuning];let d=A.modulatedGenerators[a.vibLfoToPitch];if(d!==0){let $=A.startTime+LA(A.modulatedGenerators[a.delayVibLFO]),QA=ye(A.modulatedGenerators[a.freqVibLFO]),aA=Ze($,QA,currentTime);g+=aA*(d*e.customControllers[iA.modulationMultiplier])}let u=A.modulatedGenerators[a.initialFilterFc],Q=A.modulatedGenerators[a.modLfoToPitch],l=A.modulatedGenerators[a.modLfoToVolume],m=A.modulatedGenerators[a.modLfoToFilterFc],y=0;if(Q+m+l!==0){let $=A.startTime+LA(A.modulatedGenerators[a.delayModLFO]),QA=ye(A.modulatedGenerators[a.freqModLFO]),aA=Ze($,QA,currentTime);g+=aA*(Q*e.customControllers[iA.modulationMultiplier]),y=(aA/2+.5)*l,u+=aA*m}if(e.channelVibrato.depth>0){let $=Ze(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);$&&(g+=$*e.channelVibrato.depth)}let k=A.modulatedGenerators[a.modEnvToPitch],G=A.modulatedGenerators[a.modEnvToFilterFc],M=UA.getValue(A,currentTime);u+=M*G,g+=M*k;let N=~~(g+h*100);N!==A.currentTuningCents&&(A.currentTuningCents=N,A.currentTuningCalculated=Math.pow(2,N/1200));let Z=(Math.max(-500,Math.min(500,A.modulatedGenerators[a.pan]))+500)/1e3,H=new Float32Array(t.length);this.interpolationType===Xe.linear?Js(A,this.workletDumpedSamplesList[A.sample.sampleID],H):qs(A,this.workletDumpedSamplesList[A.sample.sampleID],H),vs(A,H,u),NA.apply(A,H,y,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(Z-A.currentPan)*this.panSmoothingFactor;let r=Math.cos(Os*A.currentPan)*this.panLeft,sA=Math.sin(Os*A.currentPan)*this.panRight,K=this.oneOutputMode?0:A.modulatedGenerators[a.reverbEffectsSend],z=this.oneOutputMode?0:A.modulatedGenerators[a.chorusEffectsSend];Ks(r,sA,H,t,s,n,K,o,z)}function xo(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=xo(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.startTimejs=e);var Mo=function(e){var A,t,s,n,o,E,g,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="",d=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=h.indexOf(e.charAt(d++)),o=h.indexOf(e.charAt(d++)),E=h.indexOf(e.charAt(d++)),g=h.indexOf(e.charAt(d++)),A=n<<2|o>>4,t=(15&o)<<4|E>>2,s=(3&E)<<6|g,c+=String.fromCharCode(A),E!==64&&(c+=String.fromCharCode(t)),g!==64&&(c+=String.fromCharCode(s));while(d1&&(r.thisProgram=process.argv[1].replace(/\\/g,"/")),r.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(i){if(!(i instanceof fe))throw i}),process.on("unhandledRejection",function(i,C){process.exit(1)}),r.quit=function(i){process.exit(i)},r.inspect=function(){return"[Emscripten Module object]"}):QA?(typeof read<"u"&&(r.read=function(C){return read(C)}),r.readBinary=function(C){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(C)):(XA(typeof(B=read(C,"binary"))=="object"),B)},typeof scriptArgs<"u"?r.arguments=scriptArgs:typeof arguments<"u"&&(r.arguments=arguments),typeof quit=="function"&&(r.quit=function(i){quit(i)})):(K||z)&&(K?document.currentScript&&(aA=document.currentScript.src):aA=self.location.href,aA=aA.indexOf("blob:")!==0?aA.split("/").slice(0,-1).join("/")+"/":"",r.read=function(C){var B=new XMLHttpRequest;return B.open("GET",C,!1),B.send(null),B.responseText},z&&(r.readBinary=function(C){var B=new XMLHttpRequest;return B.open("GET",C,!1),B.responseType="arraybuffer",B.send(null),new Uint8Array(B.response)}),r.readAsync=function(C,B,f){var F=new XMLHttpRequest;F.open("GET",C,!0),F.responseType="arraybuffer",F.onload=function(){if(F.status==200||F.status==0&&F.response){B(F.response);return}f()},F.onerror=f,F.send(null)},r.setWindowTitle=function(i){document.title=i});var Yt=r.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),HA=r.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Yt);for(e in sA)sA.hasOwnProperty(e)&&(r[e]=sA[e]);function Fe(i){var C=l;return l=l+i+15&-16,C}function Jt(i){var C=h[N>>2],B=C+i+15&-16;return h[N>>2]=B,B>=EA&&!_t()?(h[N>>2]=C,0):C}function qt(i,C){return C||(C=16),i=Math.ceil(i/C)*C}function Bo(i){switch(i){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(i[i.length-1]==="*")return 4;if(i[0]!=="i")return 0;var C=parseInt(i.substr(1));return XA(C%8==0),C/8}}function ce(i){ce.shown||(ce.shown={}),ce.shown[i]||(ce.shown[i]=1,HA(i))}sA=void 0;var ho={"f64-rem":function(i,C){return i%C},debugger:function(){}},tt=[];function Yo(i,C){for(var B=0,f=B;f>>0)+4294967296*+(C>>>0):+(i>>>0)+4294967296*+(0|C)}function nt(i,C,B){return B&&B.length?r["dynCall_"+i].apply(null,[C].concat(B)):r["dynCall_"+i].call(null,C)}var Re=0,Kt=0;function XA(i,C){i||VA("Assertion failed: "+C)}function Pt(i){var C=r["_"+i];return XA(C,"Cannot call unknown function "+i+", make sure it is exported"),C}var vt={stackSave:function(){Et()},stackRestore:function(){Ct()},arrayToC:function(i){var C,B,f=Le(i.length);return C=i,B=f,n.set(C,B),f},stringToC:function(i){var C=0;if(i!=null&&i!==0){var B=(i.length<<2)+1;C=Le(B),Zt(i,C,B)}return C}},Qo={string:vt.stringToC,array:vt.arrayToC};function Vt(i,C,B,f,F){var P=Pt(i),W=[],x=0;if(f)for(var BA=0;BA>0]=C;break;case"i16":E[i>>1]=C;break;case"i32":h[i>>2]=C;break;case"i64":tempI64=[C>>>0,+po(tempDouble=C)>=1?tempDouble>0?(0|yo(+es(tempDouble/4294967296),4294967295))>>>0:~~+So((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],h[i>>2]=tempI64[0],h[i+4>>2]=tempI64[1];break;case"float":d[i>>2]=C;break;case"double":u[i>>3]=C;break;default:VA("invalid type for setValue: "+B)}}function Po(i,C,B){switch((C=C||"i8").charAt(C.length-1)==="*"&&(C="i32"),C){case"i1":case"i8":return n[i>>0];case"i16":return E[i>>1];case"i32":case"i64":return h[i>>2];case"float":return d[i>>2];case"double":return u[i>>3];default:VA("invalid type for getValue: "+C)}return null}function vo(i,C,B,f){typeof i=="number"?(P=!0,W=i):(P=!1,W=i.length);var F=typeof C=="string"?C:null;if(x=B==4?f:[typeof be=="function"?be:Fe,Le,Fe,Jt][B===void 0?2:B](Math.max(W,F?1:C.length)),P){for(f=x,XA((3&x)==0),BA=x+(-4&W);f>2]=0;for(BA=x+W;f>0]=0;return x}if(F==="i8")return i.subarray||i.slice?o.set(i,x):o.set(new Uint8Array(i),x),x;for(var P,W,x,BA,nA,oA,eA,q=0;q>0],(f!=0||C)&&(W++,!C||W!=C););C||(C=W);var x="";if(P<128){for(;C>0;)F=String.fromCharCode.apply(String,o.subarray(i,i+Math.min(C,1024))),x=x?x+F:F,i+=1024,C-=1024;return x}return B=i,function(nA,oA){for(var eA=oA;nA[eA];)++eA;if(eA-oA>16&&nA.subarray&&Ot)return Ot.decode(nA.subarray(oA,eA));for(var q,dA,FA,RA,GA,$A,xA="";;){if(!(q=nA[oA++]))return xA;if(!(128&q)){xA+=String.fromCharCode(q);continue}if(dA=63&nA[oA++],(224&q)==192){xA+=String.fromCharCode((31&q)<<6|dA);continue}if(FA=63&nA[oA++],(240&q)==224?q=(15&q)<<12|dA<<6|FA:(RA=63&nA[oA++],(248&q)==240?q=(7&q)<<18|dA<<12|FA<<6|RA:(GA=63&nA[oA++],q=(252&q)==248?(3&q)<<24|dA<<18|FA<<12|RA<<6|GA:(1&q)<<30|dA<<24|FA<<18|RA<<12|GA<<6|($A=63&nA[oA++]))),q<65536)xA+=String.fromCharCode(q);else{var de=q-65536;xA+=String.fromCharCode(55296|de>>10,56320|1023&de)}}}(o,B)}function Oo(i){for(var C="";;){var B=n[i++>>0];if(!B)return C;C+=String.fromCharCode(B)}}function Zo(i,C){return function(f,F,P){for(var W=0;W>0]=f.charCodeAt(W);P||(n[F>>0]=0)}(i,C,!1)}var Ot=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function xe(i,C,B,f){if(!(f>0))return 0;for(var F=B,P=B+f-1,W=0;W=55296&&x<=57343&&(x=65536+((1023&x)<<10)|1023&i.charCodeAt(++W)),x<=127){if(B>=P)break;C[B++]=x}else if(x<=2047){if(B+1>=P)break;C[B++]=192|x>>6,C[B++]=128|63&x}else if(x<=65535){if(B+2>=P)break;C[B++]=224|x>>12,C[B++]=128|x>>6&63,C[B++]=128|63&x}else if(x<=2097151){if(B+3>=P)break;C[B++]=240|x>>18,C[B++]=128|x>>12&63,C[B++]=128|x>>6&63,C[B++]=128|63&x}else if(x<=67108863){if(B+4>=P)break;C[B++]=248|x>>24,C[B++]=128|x>>18&63,C[B++]=128|x>>12&63,C[B++]=128|x>>6&63,C[B++]=128|63&x}else{if(B+5>=P)break;C[B++]=252|x>>30,C[B++]=128|x>>24&63,C[B++]=128|x>>18&63,C[B++]=128|x>>12&63,C[B++]=128|x>>6&63,C[B++]=128|63&x}}return C[B]=0,B-F}function Zt(i,C,B){return xe(i,o,C,B)}function Me(i){for(var C=0,B=0;B=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&i.charCodeAt(++B)),f<=127?++C:f<=2047?C+=2:f<=65535?C+=3:f<=2097151?C+=4:f<=67108863?C+=5:C+=6}return C}var Xt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function Xo(i){for(var C=i,B=C>>1;E[B];)++B;if((C=B<<1)-i>32&&Xt)return Xt.decode(o.subarray(i,C));for(var f=0,F="";;){var P=E[i+2*f>>1];if(P==0)return F;++f,F+=String.fromCharCode(P)}}function Wo(i,C,B){if(B===void 0&&(B=2147483647),B<2)return 0;for(var f=C,F=(B-=2)<2*i.length?B/2:i.length,P=0;P>1]=W,C+=2}return E[C>>1]=0,C-f}function _o(i){return 2*i.length}function zo(i){for(var C=0,B="";;){var f=h[i+4*C>>2];if(f==0)return B;if(++C,f>=65536){var F=f-65536;B+=String.fromCharCode(55296|F>>10,56320|1023&F)}else B+=String.fromCharCode(f)}}function jo(i,C,B){if(B===void 0&&(B=2147483647),B<4)return 0;for(var f=C,F=f+B-4,P=0;P=55296&&W<=57343&&(W=65536+((1023&W)<<10)|1023&i.charCodeAt(++P)),h[C>>2]=W,(C+=4)+4>F)break}return h[C>>2]=0,C-f}function $o(i){for(var C=0,B=0;B=55296&&f<=57343&&++B,C+=4}return C}function Ar(i){var C=Me(i)+1,B=be(C);return B&&xe(i,n,B,C),B}function er(i){var C=Me(i)+1,B=Le(C);return xe(i,n,B,C),B}function tr(i){return i}function sr(){var i,C=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(F){f=F}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return r.extraStackTrace&&(C+=` +`;this.copyright+=TA,p(`%cDecoded Roland SC message! %c${TA}`,I.recognized,I.value)}break;default:if((r&240)===w.controllerChange)switch(z[0]){case 2:case 116:d=Z;break;case 4:case 117:u===null?u=Z:u=0;break;case 0:g&&z[1]!==0&&z[1]!==127&&(p("%cDLS RMIDI with offset 1 detected!",I.recognized),this.bankOffset=1)}}}this.tracks.push(k),this.usedChannelsOnTrack.push(M),p(`%cParsed %c${this.tracks.length}%c / %c${this.tracksAmount}`,I.info,I.value,I.info,I.value)}let l=[];for(let y of this.tracks){let k=y.find(G=>(G.messageStatusByte&240)===w.noteOn);k&&l.push(k.ticks)}this.firstNoteOn=Math.min(...l),p(`%cMIDI file parsed. Total tick time: %c${this.lastVoiceEventTick}`,I.info,I.recognized),X(),d!==null&&u===null?(d=this.firstNoteOn,u=this.lastVoiceEventTick):(d===null&&(d=this.firstNoteOn),(u===null||u===0)&&(u=this.lastVoiceEventTick));let m=0;for(let y of this.midiPorts)if(y!==-1){m=y;break}if(this.midiPorts=this.midiPorts.map(y=>y===-1?m:y),this.midiPortChannelOffsets.length===0&&(this.midiPortChannelOffsets=[0]),this.loop={start:d,end:u},!E)if(this.tracks.length>1){if(this.tracks[0].find(y=>y.messageStatusByte>=w.noteOn&&y.messageStatusBytek.messageStatusByte===w.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=V(y.messageData,y.messageData.length,void 0,!1))}}else{let y=this.tracks[0].find(k=>k.messageStatusByte===w.trackName);y&&(this.rawMidiName=y.messageData,this.midiName=V(y.messageData,y.messageData.length,void 0,!1))}if(this.fileName=t,this.midiName=this.midiName.trim(),this.midiName.length===0){this.midiName=is(t),this.rawMidiName=new Uint8Array(this.midiName.length);for(let y=0;yQ>u?Q:u),s=[];for(let u=0;u{E[m]>=l.length||l[E[m]].ticks0;){let u=h(),Q=e.tracks[u];if(E[u]>=Q.length){g--;continue}let l=Q[E[u]];if(E[u]++,l.messageStatusByte===w.midiPort){c[u]=l.messageData[0];continue}let m=l.messageStatusByte&240;if(m!==w.noteOn&&m!==w.controllerChange&&m!==w.programChange&&m!==w.systemExclusive)continue;let y=(l.messageStatusByte&15)+e.midiPortChannelOffsets[c[u]]||0,k=s[y];switch(m){case w.programChange:k.program=l.messageData[0],n(k);break;case w.controllerChange:if(l.messageData[0]!==S.bankSelect||d==="gs"&&k.drums)continue;let G=l.messageData[1],M=Math.max(0,G-e.bankOffset);if(d==="xg"){let H=G===120||G===126||G===127;H!==k.drums?(k.drums=H,k.bank=k.drums?128:M,n(k)):k.bank=k.drums?128:M;continue}s[y].bank=M;break;case w.noteOn:if(l.messageData[1]===0)continue;n(k),o[k.string].add(`${l.messageData[0]}-${l.messageData[1]}`);break;case w.systemExclusive:if(l.messageData[0]!==65||l.messageData[2]!==66||l.messageData[3]!==18||l.messageData[4]!==64||!(l.messageData[5]&16)||l.messageData[6]!==21){l.messageData[0]===67&&l.messageData[2]===76&&l.messageData[5]===126&&l.messageData[6]===0&&(d="xg");continue}let N=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][l.messageData[5]&15]+e.midiPortChannelOffsets[c[u]],Z=!!(l.messageData[7]>0&&l.messageData[5]>>4);k=s[N],k.drums=Z,k.bank=Z?128:0,n(k);break}}for(let u of Object.keys(o))o[u].size===0&&(p(`%cDetected change but no keys for %c${u}`,I.info,I.value),delete o[u]);return X(),o}function xs(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),DA("%cPreloading samples...",I.info);let A=Gs(this.midiData,this.synth.soundfontManager);for(let[t,s]of Object.entries(A)){let n=parseInt(t.split(":")[0]),o=parseInt(t.split(":")[1]),E=this.synth.getPreset(n,o);p(`%cPreloading used samples on %c${E.presetName}%c...`,I.info,I.recognized,I.info);for(let g of s){let h=g.split("-");E.preloadSpecific(parseInt(h[0]),parseInt(h[1]))}}X()}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=Je(this.midiData.tempoChanges,this.midiData.firstNoteOn,this.midiData.timeDivision),p(`%cTotal song time: ${ct(Math.ceil(this.duration)).time}`,I.recognized),this.post(kA.songChange,[new qe(this.midiData),this.songIndex]),this.synth.resetAllControllers(),this.duration<=1&&(b(`%cVery short song: (${ct(Math.round(this.duration)).time}). Disabling loop!`,I.warn),this.loop=!1),this.play(!0)}function Ns(e){this.songs=e.reduce((A,t)=>{if(t.duration)return A.push(t),A;try{A.push(new Ve(t.binary,t.altName||""))}catch(s){return this.post(kA.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 bs(){if(this.songs.length===1){this.currentTime=0;return}this.songIndex++,this.songIndex%=this.songs.length,this.loadNewSequence(this.songs[this.songIndex])}function Ls(){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 Us(e,A){switch(e){default:break;case MA.loadNewSongList:this.loadNewSongList(A);break;case MA.pause:this.pause();break;case MA.play:this.play(A);break;case MA.stop:this.stop();break;case MA.setTime:this.currentTime=A;break;case MA.changeMIDIMessageSending:this.sendMIDIMessages=A;break;case MA.setPlaybackRate:this.playbackRate=A;break;case MA.setLoop:this.loop=A;break;case MA.changeSong:A?this.nextSong():this.previousSong();break;case MA.getMIDI:this.post(kA.getMIDI,this.midiData);break;case MA.setSkipToFirstNote:this._skipToFirstNoteOn=A;break}}function Ts(e,A=void 0){this.synth.enableEventSystem&&this.synth.post({messageType:mA.sequencerSpecific,messageData:{messageType:e,messageData:A}})}function Hs(e){this.post(kA.midiEvent,e)}var CA=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&&AYs?440*Math.pow(2,(e-6900)/1200):Dt[~~e-Oe]}var wt=-1660,Ro=1600,kt=new Float32Array((Ro-wt)*100+1);for(let e=0;e.5?1:0,s?t*2-1:t;case lA.concave:return s?(t=t*2-1,t<0?1-ge[~~(t*-IA)]-1:ge[~~t*IA]):ge[~~(t*IA)];case lA.convex:return s?(t=t*2-1,t<0?1-Ce[~~(t*-IA)]-1:Ce[~~(t*IA)]):Ce[~~(t*IA)]}}var Ft=1,Rt=new Float32Array(1e3);for(let e=0;e=e.sample.loopEnd;)s-=o;let g=~~s,h=g+1;for(;h>=e.sample.loopEnd;)h-=o;let c=s-g,d=A[h],u=A[g];t[E]=u+(d-u)*c,s+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=A.length&&(e.sample.end=A.length-1);for(let E=0;E=e.sample.end){e.finished=!0;return}let c=s-g,d=A[h],u=A[g];t[E]=u+(d-u)*c,s+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=s}function qs(e,A,t){let s=e.sample.cursor,n=e.sample.loopingMode===1||e.sample.loopingMode===3&&!e.isInRelease,o=e.sample.loopEnd-e.sample.loopStart;if(n)for(let E=0;E=e.sample.loopEnd;)s-=o;let g=~~s+1;for(;g>=e.sample.loopEnd;)g-=o;t[E]=A[g],s+=e.sample.playbackStep*e.currentTuningCalculated}else{e.sample.end>=A.length&&(e.sample.end=A.length-1);for(let E=0;E=e.sample.end){e.finished=!0;return}t[E]=A[g],s+=e.sample.playbackStep*e.currentTuningCalculated}}e.sample.cursor=s}function Ks(e,A,t,s,n,o,E,g,h){if(!isNaN(t[0])){if(E>0){let c=o[0],d=o[1];E=Math.min(E,1e3);let u=E/800,Q=e*u,l=A*u;for(let m=0;m0){let c=g[0],d=g[1];h=Math.min(h,1e3);let u=h/800,Q=e*u,l=A*u;for(let m=0;m0)for(let c=0;c0)for(let c=0;c13499)){(e.filter.cutoffCents!==t||e.filter.reasonanceCb!==e.modulatedGenerators[a.initialFilterQ])&&(e.filter.cutoffCents=t,e.filter.reasonanceCb=e.modulatedGenerators[a.initialFilterQ],Go(e));for(let s=0;s.45*sampleRate&&(e.filter.cutoffHz=.45*sampleRate);let A=e.filter.reasonanceCb/10-3.01;e.filter.reasonanceGain=_A(-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),E=(1-n)*t,g=E/2,h=g,c=1+o,d=-2*n,u=1-o;e.filter.a0=g/c,e.filter.a1=E/c,e.filter.a2=h/c,e.filter.a3=d/c,e.filter.a4=u/c}var Vs=.001,De=100,Gt=70,NA=class e{constructor(A){this.sampleRate=A}currentSampleTime=0;sampleRate;currentAttenuationDb=De;state=0;releaseStartDb=100;releaseStartTimeSamples=0;currentReleaseGain=1;attackDuration=0;decayDuration=0;releaseDuration=0;attenuation=0;sustainDb=0;delayEnd=0;attackEnd=0;holdEnd=0;decayEnd=0;static startRelease(A){A.volumeEnvelope.releaseStartTimeSamples=A.volumeEnvelope.currentSampleTime,A.volumeEnvelope.currentReleaseGain=_A(A.volumeEnvelope.currentAttenuationDb),e.recalculate(A)}static recalculate(A){let t=A.volumeEnvelope,s=h=>Math.floor(LA(h)*t.sampleRate);t.attenuation=A.modulatedGenerators[a.initialAttenuation]/10,t.sustainDb=Math.min(100,A.volumeEnvelope.attenuation+A.modulatedGenerators[a.sustainVolEnv]/10),t.attackDuration=s(A.modulatedGenerators[a.attackVolEnv]);let n=A.modulatedGenerators[a.decayVolEnv],o=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvDecay],E=(t.sustainDb-t.attenuation)/100;t.decayDuration=s(n+o)*E,t.releaseDuration=s(A.modulatedGenerators[a.releaseVolEnv]),t.delayEnd=s(A.modulatedGenerators[a.delayVolEnv]),t.attackEnd=t.attackDuration+t.delayEnd;let g=(60-A.targetKey)*A.modulatedGenerators[a.keyNumToVolEnvHold];if(t.holdEnd=s(A.modulatedGenerators[a.holdVolEnv]+g)+t.attackEnd,t.decayEnd=t.decayDuration+t.holdEnd,A.isInRelease){switch(t.state){case 0:t.releaseStartDb=De;break;case 1:let c=(1-(t.attackEnd-t.releaseStartTimeSamples)/t.attackDuration)*_A(t.attenuation);t.releaseStartDb=20*Math.log10(c)*-1;break;case 2:t.releaseStartDb=t.attenuation;break;case 3:t.releaseStartDb=(1-(t.decayEnd-t.releaseStartTimeSamples)/t.decayDuration)*(t.sustainDb-t.attenuation)+t.attenuation;break;case 4:t.releaseStartDb=t.sustainDb;break;default:t.releaseStartDb=t.currentAttenuationDb}t.releaseStartDb=Math.min(t.releaseStartDb,De),t.releaseStartDb>=Gt&&(A.finished=!0)}}static getInterpolatedGain(A,t,s){return A.currentAttenuationDb+=(t-A.currentAttenuationDb)*s,_A(A.currentAttenuationDb)}static apply(A,t,s,n){let o=A.volumeEnvelope,E=s/10;if(A.isInRelease){let h=n*10,c=o.currentSampleTime-o.releaseStartTimeSamples;if(c>=o.releaseDuration){for(let Q=0;Q=Gt&&(A.finished=!0);return}let g=0;switch(o.state){case 0:for(;o.currentSampleTime=t.length)return;o.state++;case 1:for(;o.currentSampleTime=t.length)return}o.state++;case 2:for(;o.currentSampleTime=t.length)return;o.state++;case 3:let h=o.sustainDb-o.attenuation;for(;o.currentSampleTime=t.length)return}o.state++;case 4:if(o.sustainDb>Gt){for(A.finished=!0;g=t.length)return}}};var Os=Math.PI/2,Zs=.01;function Xs(e,A,t,s,n,o){if(A.isInRelease||currentTime>=A.releaseStartTime&&(A.isInRelease=!0,NA.startRelease(A),UA.startRelease(A)),A.modulatedGenerators[a.initialAttenuation]>2500){A.isInRelease&&(A.finished=!0);return}let E=A.targetKey,g=A.modulatedGenerators[a.fineTune]+e.customControllers[iA.channelTuning]+e.customControllers[iA.channelTransposeFine]+e.customControllers[iA.masterTuning]+e.channelOctaveTuning[A.midiNote%12],h=A.modulatedGenerators[a.coarseTune]+e.customControllers[iA.channelTuningSemitones],c=this.tunings[e.preset.program]?.[E];c?.midiNote>=0&&(E=c.midiNote,g+=c.centTuning),g+=(E-A.sample.rootKey)*A.modulatedGenerators[a.scaleTuning];let d=A.modulatedGenerators[a.vibLfoToPitch];if(d!==0){let $=A.startTime+LA(A.modulatedGenerators[a.delayVibLFO]),QA=ye(A.modulatedGenerators[a.freqVibLFO]),aA=Ze($,QA,currentTime);g+=aA*(d*e.customControllers[iA.modulationMultiplier])}let u=A.modulatedGenerators[a.initialFilterFc],Q=A.modulatedGenerators[a.modLfoToPitch],l=A.modulatedGenerators[a.modLfoToVolume],m=A.modulatedGenerators[a.modLfoToFilterFc],y=0;if(Q+m+l!==0){let $=A.startTime+LA(A.modulatedGenerators[a.delayModLFO]),QA=ye(A.modulatedGenerators[a.freqModLFO]),aA=Ze($,QA,currentTime);g+=aA*(Q*e.customControllers[iA.modulationMultiplier]),y=-aA*l,u+=aA*m}if(e.channelVibrato.depth>0){let $=Ze(A.startTime+e.channelVibrato.delay,e.channelVibrato.rate,currentTime);$&&(g+=$*e.channelVibrato.depth)}let k=A.modulatedGenerators[a.modEnvToPitch],G=A.modulatedGenerators[a.modEnvToFilterFc],M=UA.getValue(A,currentTime);u+=M*G,g+=M*k;let N=~~(g+h*100);N!==A.currentTuningCents&&(A.currentTuningCents=N,A.currentTuningCalculated=Math.pow(2,N/1200));let Z=(Math.max(-500,Math.min(500,A.modulatedGenerators[a.pan]))+500)/1e3,H=new Float32Array(t.length);this.interpolationType===Xe.linear?Js(A,this.workletDumpedSamplesList[A.sample.sampleID],H):qs(A,this.workletDumpedSamplesList[A.sample.sampleID],H),vs(A,H,u),NA.apply(A,H,y,this.volumeEnvelopeSmoothingFactor),A.currentPan+=(Z-A.currentPan)*this.panSmoothingFactor;let r=Math.cos(Os*A.currentPan)*this.panLeft,sA=Math.sin(Os*A.currentPan)*this.panRight,K=this.oneOutputMode?0:A.modulatedGenerators[a.reverbEffectsSend],z=this.oneOutputMode?0:A.modulatedGenerators[a.chorusEffectsSend];Ks(r,sA,H,t,s,n,K,o,z)}function xo(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=xo(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.startTimejs=e);var Mo=function(e){var A,t,s,n,o,E,g,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c="",d=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");do n=h.indexOf(e.charAt(d++)),o=h.indexOf(e.charAt(d++)),E=h.indexOf(e.charAt(d++)),g=h.indexOf(e.charAt(d++)),A=n<<2|o>>4,t=(15&o)<<4|E>>2,s=(3&E)<<6|g,c+=String.fromCharCode(A),E!==64&&(c+=String.fromCharCode(t)),g!==64&&(c+=String.fromCharCode(s));while(d1&&(r.thisProgram=process.argv[1].replace(/\\/g,"/")),r.arguments=process.argv.slice(2),typeof module<"u",process.on("uncaughtException",function(i){if(!(i instanceof fe))throw i}),process.on("unhandledRejection",function(i,C){process.exit(1)}),r.quit=function(i){process.exit(i)},r.inspect=function(){return"[Emscripten Module object]"}):QA?(typeof read<"u"&&(r.read=function(C){return read(C)}),r.readBinary=function(C){var B;return typeof readbuffer=="function"?new Uint8Array(readbuffer(C)):(XA(typeof(B=read(C,"binary"))=="object"),B)},typeof scriptArgs<"u"?r.arguments=scriptArgs:typeof arguments<"u"&&(r.arguments=arguments),typeof quit=="function"&&(r.quit=function(i){quit(i)})):(K||z)&&(K?document.currentScript&&(aA=document.currentScript.src):aA=self.location.href,aA=aA.indexOf("blob:")!==0?aA.split("/").slice(0,-1).join("/")+"/":"",r.read=function(C){var B=new XMLHttpRequest;return B.open("GET",C,!1),B.send(null),B.responseText},z&&(r.readBinary=function(C){var B=new XMLHttpRequest;return B.open("GET",C,!1),B.responseType="arraybuffer",B.send(null),new Uint8Array(B.response)}),r.readAsync=function(C,B,f){var F=new XMLHttpRequest;F.open("GET",C,!0),F.responseType="arraybuffer",F.onload=function(){if(F.status==200||F.status==0&&F.response){B(F.response);return}f()},F.onerror=f,F.send(null)},r.setWindowTitle=function(i){document.title=i});var Yt=r.print||(typeof console<"u"?console.log.bind(console):typeof print<"u"?print:null),HA=r.printErr||(typeof printErr<"u"?printErr:typeof console<"u"&&console.warn.bind(console)||Yt);for(e in sA)sA.hasOwnProperty(e)&&(r[e]=sA[e]);function Fe(i){var C=l;return l=l+i+15&-16,C}function Jt(i){var C=h[N>>2],B=C+i+15&-16;return h[N>>2]=B,B>=EA&&!_t()?(h[N>>2]=C,0):C}function qt(i,C){return C||(C=16),i=Math.ceil(i/C)*C}function Bo(i){switch(i){case"i1":case"i8":return 1;case"i16":return 2;case"i32":case"float":return 4;case"i64":case"double":return 8;default:if(i[i.length-1]==="*")return 4;if(i[0]!=="i")return 0;var C=parseInt(i.substr(1));return XA(C%8==0),C/8}}function ce(i){ce.shown||(ce.shown={}),ce.shown[i]||(ce.shown[i]=1,HA(i))}sA=void 0;var ho={"f64-rem":function(i,C){return i%C},debugger:function(){}},tt=[];function Yo(i,C){for(var B=0,f=B;f>>0)+4294967296*+(C>>>0):+(i>>>0)+4294967296*+(0|C)}function nt(i,C,B){return B&&B.length?r["dynCall_"+i].apply(null,[C].concat(B)):r["dynCall_"+i].call(null,C)}var Re=0,Kt=0;function XA(i,C){i||VA("Assertion failed: "+C)}function Pt(i){var C=r["_"+i];return XA(C,"Cannot call unknown function "+i+", make sure it is exported"),C}var vt={stackSave:function(){Et()},stackRestore:function(){Ct()},arrayToC:function(i){var C,B,f=Le(i.length);return C=i,B=f,n.set(C,B),f},stringToC:function(i){var C=0;if(i!=null&&i!==0){var B=(i.length<<2)+1;C=Le(B),Zt(i,C,B)}return C}},Qo={string:vt.stringToC,array:vt.arrayToC};function Vt(i,C,B,f,F){var P=Pt(i),W=[],x=0;if(f)for(var BA=0;BA>0]=C;break;case"i16":E[i>>1]=C;break;case"i32":h[i>>2]=C;break;case"i64":tempI64=[C>>>0,+po(tempDouble=C)>=1?tempDouble>0?(0|yo(+es(tempDouble/4294967296),4294967295))>>>0:~~+So((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0],h[i>>2]=tempI64[0],h[i+4>>2]=tempI64[1];break;case"float":d[i>>2]=C;break;case"double":u[i>>3]=C;break;default:VA("invalid type for setValue: "+B)}}function Po(i,C,B){switch((C=C||"i8").charAt(C.length-1)==="*"&&(C="i32"),C){case"i1":case"i8":return n[i>>0];case"i16":return E[i>>1];case"i32":case"i64":return h[i>>2];case"float":return d[i>>2];case"double":return u[i>>3];default:VA("invalid type for getValue: "+C)}return null}function vo(i,C,B,f){typeof i=="number"?(P=!0,W=i):(P=!1,W=i.length);var F=typeof C=="string"?C:null;if(x=B==4?f:[typeof be=="function"?be:Fe,Le,Fe,Jt][B===void 0?2:B](Math.max(W,F?1:C.length)),P){for(f=x,XA((3&x)==0),BA=x+(-4&W);f>2]=0;for(BA=x+W;f>0]=0;return x}if(F==="i8")return i.subarray||i.slice?o.set(i,x):o.set(new Uint8Array(i),x),x;for(var P,W,x,BA,nA,oA,eA,q=0;q>0],(f!=0||C)&&(W++,!C||W!=C););C||(C=W);var x="";if(P<128){for(;C>0;)F=String.fromCharCode.apply(String,o.subarray(i,i+Math.min(C,1024))),x=x?x+F:F,i+=1024,C-=1024;return x}return B=i,function(nA,oA){for(var eA=oA;nA[eA];)++eA;if(eA-oA>16&&nA.subarray&&Ot)return Ot.decode(nA.subarray(oA,eA));for(var q,dA,FA,RA,GA,$A,xA="";;){if(!(q=nA[oA++]))return xA;if(!(128&q)){xA+=String.fromCharCode(q);continue}if(dA=63&nA[oA++],(224&q)==192){xA+=String.fromCharCode((31&q)<<6|dA);continue}if(FA=63&nA[oA++],(240&q)==224?q=(15&q)<<12|dA<<6|FA:(RA=63&nA[oA++],(248&q)==240?q=(7&q)<<18|dA<<12|FA<<6|RA:(GA=63&nA[oA++],q=(252&q)==248?(3&q)<<24|dA<<18|FA<<12|RA<<6|GA:(1&q)<<30|dA<<24|FA<<18|RA<<12|GA<<6|($A=63&nA[oA++]))),q<65536)xA+=String.fromCharCode(q);else{var de=q-65536;xA+=String.fromCharCode(55296|de>>10,56320|1023&de)}}}(o,B)}function Oo(i){for(var C="";;){var B=n[i++>>0];if(!B)return C;C+=String.fromCharCode(B)}}function Zo(i,C){return function(f,F,P){for(var W=0;W>0]=f.charCodeAt(W);P||(n[F>>0]=0)}(i,C,!1)}var Ot=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function xe(i,C,B,f){if(!(f>0))return 0;for(var F=B,P=B+f-1,W=0;W=55296&&x<=57343&&(x=65536+((1023&x)<<10)|1023&i.charCodeAt(++W)),x<=127){if(B>=P)break;C[B++]=x}else if(x<=2047){if(B+1>=P)break;C[B++]=192|x>>6,C[B++]=128|63&x}else if(x<=65535){if(B+2>=P)break;C[B++]=224|x>>12,C[B++]=128|x>>6&63,C[B++]=128|63&x}else if(x<=2097151){if(B+3>=P)break;C[B++]=240|x>>18,C[B++]=128|x>>12&63,C[B++]=128|x>>6&63,C[B++]=128|63&x}else if(x<=67108863){if(B+4>=P)break;C[B++]=248|x>>24,C[B++]=128|x>>18&63,C[B++]=128|x>>12&63,C[B++]=128|x>>6&63,C[B++]=128|63&x}else{if(B+5>=P)break;C[B++]=252|x>>30,C[B++]=128|x>>24&63,C[B++]=128|x>>18&63,C[B++]=128|x>>12&63,C[B++]=128|x>>6&63,C[B++]=128|63&x}}return C[B]=0,B-F}function Zt(i,C,B){return xe(i,o,C,B)}function Me(i){for(var C=0,B=0;B=55296&&f<=57343&&(f=65536+((1023&f)<<10)|1023&i.charCodeAt(++B)),f<=127?++C:f<=2047?C+=2:f<=65535?C+=3:f<=2097151?C+=4:f<=67108863?C+=5:C+=6}return C}var Xt=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function Xo(i){for(var C=i,B=C>>1;E[B];)++B;if((C=B<<1)-i>32&&Xt)return Xt.decode(o.subarray(i,C));for(var f=0,F="";;){var P=E[i+2*f>>1];if(P==0)return F;++f,F+=String.fromCharCode(P)}}function Wo(i,C,B){if(B===void 0&&(B=2147483647),B<2)return 0;for(var f=C,F=(B-=2)<2*i.length?B/2:i.length,P=0;P>1]=W,C+=2}return E[C>>1]=0,C-f}function _o(i){return 2*i.length}function zo(i){for(var C=0,B="";;){var f=h[i+4*C>>2];if(f==0)return B;if(++C,f>=65536){var F=f-65536;B+=String.fromCharCode(55296|F>>10,56320|1023&F)}else B+=String.fromCharCode(f)}}function jo(i,C,B){if(B===void 0&&(B=2147483647),B<4)return 0;for(var f=C,F=f+B-4,P=0;P=55296&&W<=57343&&(W=65536+((1023&W)<<10)|1023&i.charCodeAt(++P)),h[C>>2]=W,(C+=4)+4>F)break}return h[C>>2]=0,C-f}function $o(i){for(var C=0,B=0;B=55296&&f<=57343&&++B,C+=4}return C}function Ar(i){var C=Me(i)+1,B=be(C);return B&&xe(i,n,B,C),B}function er(i){var C=Me(i)+1,B=Le(C);return xe(i,n,B,C),B}function tr(i){return i}function sr(){var i,C=function(){var f=Error();if(!f.stack){try{throw Error(0)}catch(F){f=F}if(!f.stack)return"(no stack trace available)"}return f.stack.toString()}();return r.extraStackTrace&&(C+=` `+r.extraStackTrace()),(i=C).replace(/__Z[\w\d_]+/g,function(B){var f,F=f=B;return B===F?B:B+" ["+F+"]"})}function ot(i,C){return i%C>0&&(i+=C-i%C),i}function Wt(i){r.buffer=s=i}function rt(){r.HEAP8=n=new Int8Array(s),r.HEAP16=E=new Int16Array(s),r.HEAP32=h=new Int32Array(s),r.HEAPU8=o=new Uint8Array(s),r.HEAPU16=g=new Uint16Array(s),r.HEAPU32=c=new Uint32Array(s),r.HEAPF32=d=new Float32Array(s),r.HEAPF64=u=new Float64Array(s)}function _t(){var i=r.usingWasm?65536:16777216,C=2147483648-i;if(h[N>>2]>C)return!1;var B=EA;for(EA=Math.max(EA,16777216);EA>2];)EA=EA<=536870912?ot(2*EA,i):Math.min(ot((3*EA+2147483648)/4,i),C);var f=r.reallocBuffer(EA);return f&&f.byteLength==EA?(Wt(f),rt(),!0):(EA=B,!1)}Q=l=y=k=G=M=N=0,m=!1,r.reallocBuffer||(r.reallocBuffer=function(i){try{if(ArrayBuffer.transfer)C=ArrayBuffer.transfer(s,i);else{var C,B=n;C=new ArrayBuffer(i),new Int8Array(C).set(B)}}catch{return!1}return!!Do(C)&&C});try{(Z=Function.prototype.call.bind(Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get))(new ArrayBuffer(4))}catch{Z=function(C){return C.byteLength}}var it=r.TOTAL_STACK||5242880,EA=r.TOTAL_MEMORY||16777216;function lo(){return EA}function le(i){for(;i.length>0;){var C=i.shift();if(typeof C=="function"){C();continue}var B=C.func;typeof B=="number"?C.arg===void 0?r.dynCall_v(B):r.dynCall_vi(B,C.arg):B(C.arg===void 0?null:C.arg)}}EA=0?i:C<=32?2*Math.abs(1<=f&&(C<=32||i>f)&&(i=-2*f+i),i}var po=Math.abs,So=Math.ceil,es=Math.floor,yo=Math.min,jA=0,gt=null,ue=null;function gr(i){return i}r.preloadedImages={},r.preloadedAudios={};var ts="data:application/octet-stream;base64,";function Ne(i){return String.prototype.startsWith?i.startsWith(ts):i.indexOf(ts)===0}(function(){var C="main.wast",B="main.wasm",f="main.temp.asm.js";Ne(C)||(C=TA(C)),Ne(B)||(B=TA(B)),Ne(f)||(f=TA(f));var F={global:null,env:null,asm2wasm:ho,parent:r},P=null;function W(eA){return eA}function x(){try{if(r.wasmBinary)return new Uint8Array(r.wasmBinary);if(r.readBinary)return r.readBinary(B);throw"both async and sync fetching of the wasm failed"}catch(eA){VA(eA)}}r.asmPreload=r.asm;var BA=r.reallocBuffer,nA=function(eA){eA=ot(eA,r.usingWasm?65536:16777216);var q=r.buffer.byteLength;if(r.usingWasm)try{var dA=r.wasmMemory.grow((eA-q)/65536);return dA!==-1?r.buffer=r.wasmMemory.buffer:null}catch{return null}};r.reallocBuffer=function(eA){return oA==="asmjs"?BA(eA):nA(eA)};var oA="";r.asm=function(eA,q,dA){var FA;if(!(q=FA=q).table){var RA,GA=r.wasmTableSize;GA===void 0&&(GA=1024);var $A=r.wasmMaxTableSize;typeof WebAssembly=="object"&&typeof WebAssembly.Table=="function"?$A!==void 0?q.table=new WebAssembly.Table({initial:GA,maximum:$A,element:"anyfunc"}):q.table=new WebAssembly.Table({initial:GA,element:"anyfunc"}):q.table=Array(GA),r.wasmTable=q.table}return q.memoryBase||(q.memoryBase=r.STATIC_BASE),q.tableBase||(q.tableBase=0),RA=function(de,se,ht){if(typeof WebAssembly!="object")return HA("no native wasm support detected"),!1;if(!(r.wasmMemory instanceof WebAssembly.Memory))return HA("no native wasm Memory in use"),!1;function Ue(YA,JA){if((P=YA.exports).memory){var me,Qt,os;me=P.memory,Qt=r.buffer,me.byteLength0?B:Me(i)+1,F=Array(f),P=xe(i,F,0,F.length);return C&&(F.length=P),F}function hr(i){for(var C=[],B=0;B255&&(f&=255),C.push(String.fromCharCode(f))}return C.join("")}l+=16,N=Fe(4),G=(y=k=qt(l))+it,M=qt(G),h[N>>2]=M,m=!0,r.wasmTableSize=4,r.wasmMaxTableSize=4,r.asmGlobalArg={},r.asmLibraryArg={abort:VA,assert:XA,enlargeMemory:_t,getTotalMemory:lo,abortOnCannotGrowMemory:function(){VA("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+EA+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which allows increasing the size at runtime, or (3) if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")},invoke_iii:function(C,B,f){var F=Et();try{return r.dynCall_iii(C,B,f)}catch(P){if(Ct(F),typeof P!="number"&&P!=="longjmp")throw P;r.setThrew(1,0)}},___assert_fail:function(C,B,f,F){VA("Assertion failed: "+Ge(C)+", at: "+[B?Ge(B):"unknown filename",f,F?Ge(F):"unknown function"])},___setErrNo:function(C){return r.___errno_location&&(h[r.___errno_location()>>2]=C),C},_abort:function(){r.abort()},_emscripten_memcpy_big:function(C,B,f){return o.set(o.subarray(B,B+f),C),C},_llvm_floor_f64:es,DYNAMICTOP_PTR:N,tempDoublePtr:yA,ABORT:Re,STACKTOP:k,STACK_MAX:G};var ss=r.asm(r.asmGlobalArg,r.asmLibraryArg,s);r.asm=ss,r.___errno_location=function(){return r.asm.___errno_location.apply(null,arguments)};var Do=r._emscripten_replace_memory=function(){return r.asm._emscripten_replace_memory.apply(null,arguments)};r._free=function(){return r.asm._free.apply(null,arguments)};var be=r._malloc=function(){return r.asm._malloc.apply(null,arguments)};r._memcpy=function(){return r.asm._memcpy.apply(null,arguments)},r._memset=function(){return r.asm._memset.apply(null,arguments)},r._sbrk=function(){return r.asm._sbrk.apply(null,arguments)},r._stb_vorbis_js_channels=function(){return r.asm._stb_vorbis_js_channels.apply(null,arguments)},r._stb_vorbis_js_close=function(){return r.asm._stb_vorbis_js_close.apply(null,arguments)},r._stb_vorbis_js_decode=function(){return r.asm._stb_vorbis_js_decode.apply(null,arguments)},r._stb_vorbis_js_open=function(){return r.asm._stb_vorbis_js_open.apply(null,arguments)},r._stb_vorbis_js_sample_rate=function(){return r.asm._stb_vorbis_js_sample_rate.apply(null,arguments)},r.establishStackSpace=function(){return r.asm.establishStackSpace.apply(null,arguments)},r.getTempRet0=function(){return r.asm.getTempRet0.apply(null,arguments)},r.runPostSets=function(){return r.asm.runPostSets.apply(null,arguments)},r.setTempRet0=function(){return r.asm.setTempRet0.apply(null,arguments)},r.setThrew=function(){return r.asm.setThrew.apply(null,arguments)};var Le=r.stackAlloc=function(){return r.asm.stackAlloc.apply(null,arguments)},Ct=r.stackRestore=function(){return r.asm.stackRestore.apply(null,arguments)},Et=r.stackSave=function(){return r.asm.stackSave.apply(null,arguments)};function fe(i){this.name="ExitStatus",this.message="Program terminated with exit("+i+")",this.status=i}function Bt(i){i=i||r.arguments,!(jA>0)&&(function(){if(r.preRun)for(typeof r.preRun=="function"&&(r.preRun=[r.preRun]);r.preRun.length;)fo(r.preRun.shift());le(zt)}(),!(jA>0)&&(r.calledRun||(r.setStatus?(r.setStatus("Running..."),setTimeout(function(){setTimeout(function(){r.setStatus("")},1),C()},1)):C())));function C(){!r.calledRun&&(r.calledRun=!0,Re||(at||(at=!0,le(It)),le(jt),r.onRuntimeInitialized&&r.onRuntimeInitialized(),function(){if(r.postRun)for(typeof r.postRun=="function"&&(r.postRun=[r.postRun]);r.postRun.length;)mo(r.postRun.shift());le(As)}()))}}function Qr(i,C){(!C||!r.noExitRuntime||i!==0)&&(r.noExitRuntime||(Re=!0,Kt=i,k=H,le($t),uo=!0,r.onExit&&r.onExit(i)),r.quit(i,new fe(i)))}function VA(i){throw r.onAbort&&r.onAbort(i),i!==void 0?(Yt(i),HA(i),i=JSON.stringify(i)):i="",Re=!0,Kt=1,"abort("+i+"). Build with -s ASSERTIONS=1 for more info."}if(r.dynCall_iii=function(){return r.asm.dynCall_iii.apply(null,arguments)},r.asm=ss,r.ccall=Vt,r.cwrap=function(C,B,f,F){var P=(f=f||[]).every(function(W){return W==="number"});return B!=="string"&&P&&!F?Pt(C):function(){return Vt(C,B,f,arguments,F)}},fe.prototype=Error(),fe.prototype.constructor=fe,ue=function i(){r.calledRun||Bt(),r.calledRun||(ue=i)},r.run=Bt,r.abort=VA,r.preInit)for(typeof r.preInit=="function"&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();r.noExitRuntime=!0,Bt(),r.onRuntimeInitialized=()=>{zs=!0,js()},vA.decode=function(i){return function(B){if(!zs)throw Error("Not initialized");var f={};function F(se){return new Int32Array(r.HEAPU8.buffer,se,1)[0]}function P(se,ht){var Ue=new ArrayBuffer(ht*Float32Array.BYTES_PER_ELEMENT),ne=new Float32Array(Ue);return ne.set(new Float32Array(r.HEAPU8.buffer,se,ht)),ne}f.open=r.cwrap("stb_vorbis_js_open","number",[]),f.close=r.cwrap("stb_vorbis_js_close","void",["number"]),f.channels=r.cwrap("stb_vorbis_js_channels","number",["number"]),f.sampleRate=r.cwrap("stb_vorbis_js_sample_rate","number",["number"]),f.decode=r.cwrap("stb_vorbis_js_decode","number",["number","number","number","number","number"]);var W,x,BA,nA,oA=f.open(),eA=(W=B,x=B.byteLength,BA=r._malloc(x),(nA=new Uint8Array(r.HEAPU8.buffer,BA,x)).set(new Uint8Array(W,0,x)),nA),q=r._malloc(4),dA=r._malloc(4),FA=f.decode(oA,eA.byteOffset,eA.byteLength,q,dA);if(r._free(eA.byteOffset),FA<0)throw f.close(oA),r._free(q),Error("stbvorbis decode failed: "+FA);for(var RA=f.channels(oA),GA=Array(RA),$A=new Int32Array(r.HEAPU32.buffer,F(q),RA),xA=0;xA=0&&(s=this.workletProcessorChannels[t]),e.messageType){case AA.noteOn:this.noteOn(t,A[0],A[1],A[2]);break;case AA.noteOff:this.noteOff(t,A);break;case AA.pitchWheel:this.pitchWheel(t,A[0],A[1]);break;case AA.ccChange:this.controllerChange(t,A[0],A[1],A[2]);break;case AA.customcCcChange:s.customControllers[A[0]]=A[1];break;case AA.killNote:this.killNote(t,A);break;case AA.programChange:this.programChange(t,A[0],A[1]);break;case AA.channelPressure:this.channelPressure(t,A);break;case AA.polyPressure:this.polyPressure(t,A[0],A[1]);break;case AA.ccReset:t===bA?this.resetAllControllers():this.resetControllers(t);break;case AA.systemExclusive:this.systemExclusive(A);break;case AA.setChannelVibrato:if(t===bA)for(let E=0;E{let t=(A.midiControllers[gA+v.pitchWheelRange]>>7)+(A.midiControllers[gA+v.pitchWheelRange]&127)/127;return{voicesAmount:A.voices.length,pitchBend:A.midiControllers[gA+v.pitchWheel],pitchBendRangeSemitones:t,isMuted:A.isMuted,isDrum:A.drumChannel}});this.post({messageType:mA.channelProperties,messageData:e})}function No(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 tn(e,A=0){let t=e[0];if(!(this.deviceID!==bA&&e[1]!==127&&this.deviceID!==e[1]))switch(t){default:b(`%cUnrecognized SysEx: %c${hA(e)}`,I.warn,I.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}`,I.info,I.value);break;case 2:let E=((e[5]<<7|e[4])-8192)/8192;this.setMasterPan(E),p(`%cMaster Pan. Pan: %c${E}`,I.info,I.value);break;case 3:let g=(e[5]<<7|e[6])-8192;s=Math.floor(g/81.92),this.setMasterTuning(s),p(`%cMaster Fine Tuning. Cents: %c${s}`,I.info,I.value);break;case 4:s=(e[5]-64)*100,this.setMasterTuning(s),p(`%cMaster Coarse Tuning. Cents: %c${s}`,I.info,I.value);break;default:b(`%cUnrecognized MIDI Device Control Real-time message: %c${hA(e)}`,I.warn,I.unrecognized)}break;case 9:e[3]===1?(p("%cGM system on",I.info),this.system="gm"):e[3]===3?(p("%cGM2 system on",I.info),this.system="gm2"):(p("%cGM system off, defaulting to GS",I.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++],E=e[n++];for(let h=0;h>1&1)===1&&this.setOctaveTuning(15+A,g);for(let h=0;h<7;h++)(e[5]>>h&1)===1&&this.setOctaveTuning(7+h+A,g);for(let h=0;h<7;h++)(e[6]>>h&1)===1&&this.setOctaveTuning(h+A,g);p(`%cMIDI Octave Scale ${e[3]===8?"(1 byte)":"(2 bytes)"} tuning via Tuning: %c${g.join(" ")}`,I.info,I.value);break;default:b(`%cUnrecognized MIDI Tuning standard message: %c${hA(e)}`,I.warn,I.unrecognized);break}break;default:b(`%cUnrecognized MIDI Realtime/non realtime message: %c${hA(e)}`,I.warn,I.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",I.info),this.system="gs"):s===127&&(p("%cGS system off, switching to GM2",I.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${hA(e)}`,I.info,I.value,I.recognized,I.info,I.value);return;case 22:let E=s-64;this.transposeChannel(n,E),p(`%cChannel %c${n}%c pitch shift. Semitones %c${E}%c, with %c${hA(e)}`,I.info,I.recognized,I.info,I.value,I.info,I.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 g=s-64;p(`%cChannel %c${n}%c tuning. Cents %c${g}%c, with %c${hA(e)}`,I.info,I.recognized,I.info,I.value,I.info,I.value),this.setChannelTuning(n,g)}}else if(e[5]===0&&e[6]===6){p(`%cRoland GS Master Pan set to: %c${s}%c with: %c${hA(e)}`,I.info,I.value,I.info,I.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${hA(e)}`,I.info,I.value,I.info,I.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${hA(e)}`,I.info,I.value,I.info,I.value),this.setMIDIVolume(s/127);return}}b(`%cUnrecognized Roland %cGS %cSysEx: %c${hA(e)}`,I.warn,I.recognized,I.warn,I.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${hA(e)}`,I.info,I.value,I.info,I.value);return}else{b(`%cUnrecognized Roland SysEx: %c${hA(e)}`,I.warn,I.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}`,I.info,I.recognized);break;case 6:let n=e[6]-64;this.transposeAllChannels(n),p(`%cXG master transpose. Volume: %c${n}`,I.info,I.recognized);break;case 126:p("%cXG system on",I.info),this.system="xg";break}else if(e[3]===8){if(this.system!=="xg")return;let s=e[4]+A;if(s>=this.workletProcessorChannels.length)return;let 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 8:let o=this.workletProcessorChannels[s];if(o.drumChannel)return;let E=n-64;o.channelTransposeKeyShift=E;break;case 11:this.controllerChange(s,S.mainVolume,n);break;case 14:let g=n;g===0&&(g=Math.floor(Math.random()*127)),this.controllerChange(s,S.pan,g);break;case 19:this.controllerChange(s,S.effects1Depth,n);break;case 18:this.controllerChange(s,S.effects3Depth,n);break;default:b(`%cUnrecognized Yamaha XG Part Setup: %c${e[5].toString(16).toUpperCase()}`,I.warn,I.unrecognized)}}else this.system==="xg"&&b(`%cUnrecognized Yamaha XG SysEx: %c${hA(e)}`,I.warn,I.unrecognized);else this.system==="xg"&&b(`%cUnrecognized Yamaha SysEx: %c${hA(e)}`,I.warn,I.unrecognized);break}}var _e=[];function sn(){_e=[]}function bo(e,A,t,s){_e[t]=!1,s({channel:e,sampleID:t,sampleData:A.getAudioData()}),_e[t]=!0}function We(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]=We(e[t]):e[t]instanceof Int16Array?A[t]=new Int16Array(e[t]):A[t]=e[t]);return A}function nn(e,A,t,s,n,o,E,g,h=!1){let c,d=g[A][t];return d!==void 0?(c=d.map(We),c.forEach(u=>{u.startTime=n})):(c=s.getSamplesAndGenerators(A,t).reduce((u,Q)=>{let l=Q.sampleID+s.sampleIDOffset;if(_e[l]!==!0&&bo(e,Q.sample,l,E),Q.sample.sampleData===void 0)return b(`Discarding invalid sample: ${Q.sample.sampleName}`),u;let m=new Int16Array(60);for(let r=0;r<60;r++)m[r]=ks(r,Q.presetGenerators,Q.instrumentGenerators);m[a.initialAttenuation]=Math.floor(m[a.initialAttenuation]*.4);let y=Q.sample.samplePitch;m[a.overridingRootKey]>-1&&(y=m[a.overridingRootKey]);let k=A;m[a.keyNum]>-1&&(k=m[a.keyNum]);let G=Q.sample.sampleLoopStartIndex/2+(m[a.startloopAddrsOffset]+m[a.startloopAddrsCoarseOffset]*32768),M=Q.sample.sampleLoopEndIndex/2+(m[a.endloopAddrsOffset]+m[a.endloopAddrsCoarseOffset]*32768),N=m[a.sampleModes],Z=Q.sample.getAudioData().length;G=Math.min(Math.max(0,G),Z),M=Math.min(Math.max(0,M),Z),M-G<1&&(N=0);let H={sampleID:l,playbackStep:Q.sample.sampleRate/o*Math.pow(2,Q.sample.samplePitchCorrection/1200),cursor:m[a.startAddrsOffset]+m[a.startAddrsCoarseOffset]*32768,rootKey:y,loopStart:G,loopEnd:M,end:Math.floor(Q.sample.sampleData.length)-1+(m[a.endAddrOffset]+m[a.endAddrsCoarseOffset]*32768),loopingMode:N};return m[a.velocity]>-1&&(t=m[a.velocity]),h&&hs([{Sample:Q.sample.sampleName,Generators:m,Modulators:Q.modulators.map(r=>r.debugString()),Velocity:t,TargetKey:k,MidiNote:A,WorkletSample:H}]),u.push({filter:We(Ps),generators:m,modulators:Q.modulators,modulatedGenerators:new Int16Array(m),sample:H,velocity:t,midiNote:A,pressure:0,channelNumber:e,startTime:n,targetKey:k,currentTuningCalculated:1,currentTuningCents:0,releaseStartTime:1/0,finished:!1,isInRelease:!1,currentPan:.5,volumeEnvelope:new NA(o),modulationEnvelope:new UA}),u},[]),g[A][t]=c.map(We)),c}function on(e,A,t){if(A.transformAmount===0)return 0;let s;if(A.sourceUsesCC)s=e[A.sourceIndex];else{let h=A.sourceIndex+gA;switch(A.sourceIndex){case v.noController:s=16383;break;case v.noteOnKeyNum:s=t.midiNote<<7;break;case v.noteOnVelocity:s=t.velocity<<7;break;case v.polyPressure:s=t.pressure<<7;break;default:s=e[h];break}}let n=fA[A.sourceCurveType][A.sourcePolarity][A.sourceDirection][s],o;if(A.secSrcUsesCC)o=e[A.secSrcIndex];else{let h=A.secSrcIndex+gA;switch(A.secSrcIndex){case v.noController:o=16383;break;case v.noteOnKeyNum:o=t.midiNote<<7;break;case v.noteOnVelocity:o=t.velocity<<7;break;case v.polyPressure:o=t.pressure<<7;break;default:o=e[h]}}let E=fA[A.secSrcCurveType][A.secSrcPolarity][A.secSrcDirection][o],g=n*E*A.transformAmount;return A.transformType===2?Math.abs(g):g}function OA(e,A,t=-1,s=0){let{modulators:n,generators:o,modulatedGenerators:E}=e;if(UA.recalculate(e),t===-1){E.set(o),n.forEach(c=>{E[c.modulatorDestination]+=on(A,c,e)}),NA.recalculate(e);return}let g=new Set([a.initialAttenuation,a.delayVolEnv,a.attackVolEnv,a.holdVolEnv,a.decayVolEnv,a.sustainVolEnv,a.releaseVolEnv,a.keyNumToVolEnvHold,a.keyNumToVolEnvDecay]),h=new Set;n.forEach(c=>{if(c.sourceUsesCC===t&&c.sourceIndex===s||c.secSrcUsesCC===t&&c.secSrcIndex===s){let d=c.modulatorDestination;h.has(d)||(E[d]=o[d],n.forEach(u=>{u.modulatorDestination===d&&(E[d]+=on(A,u,e))}),h.add(d))}}),[...h].some(c=>g.has(c))&&NA.recalculate(e)}var fA=[];for(let e=0;e<4;e++){fA[e]=[[new Float32Array(IA),new Float32Array(IA)],[new Float32Array(IA),new Float32Array(IA)]];for(let A=0;A200&&t<40||this.highPerformanceMode&&t<10||E.isMuted)return;let g=A+E.channelTransposeKeyShift;if(A>127||A<0)return;let h=E.preset.program;this.tunings[h]?.[A]?.midiNote>=0&&(g=this.tunings[h]?.[A].midiNote);let c=nn(e,g,t,E.preset,o,sampleRate,u=>this.sampleDump(u.channel,u.sampleID,u.sampleData),E.cachedVoices,s),d=E.voices;c.forEach(u=>{let Q=u.generators[a.exclusiveClass];Q!==0&&d.forEach(l=>{l.generators[a.exclusiveClass]===Q&&(this.releaseVoice(l),l.modulatedGenerators[a.releaseVolEnv]=-7e3,l.modulatedGenerators[a.releaseModEnv]=-7e3,NA.recalculate(l),UA.recalculate(l))}),OA(u,E.midiControllers),u.currentPan=(Math.max(-500,Math.min(500,u.modulatedGenerators[a.pan]))+500)/1e3}),this.totalVoicesAmount+=c.length,this.totalVoicesAmount>this.voiceCap&&this.voiceKilling(c.length),d.push(...c),n&&(this.sendChannelProperties(),this.callEvent("noteon",{midiNote:A,channel:e,velocity:t}))}function In(e,A){if(A>127||A<0){b("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 an(e,A){this.workletProcessorChannels[e].voices.forEach(t=>{t.midiNote===A&&(t.modulatedGenerators[a.releaseVolEnv]=-12e3,this.releaseVoice(t))})}function gn(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 Cn(e=!1){p("%cStop all received!",I.info);for(let A=0;AOA(n,this.workletProcessorChannels[e].midiControllers,0,v.pitchWheel)),this.sendChannelProperties()}function fn(e,A){let t=this.workletProcessorChannels[e];t.midiControllers[gA+v.channelPressure]=A<<7,this.workletProcessorChannels[e].voices.forEach(s=>OA(s,t.midiControllers,0,v.channelPressure)),this.callEvent("channelpressure",{channel:e,pressure:A})}function dn(e,A,t){this.workletProcessorChannels[e].voices.forEach(s=>{s.midiNote===A&&(s.pressure=t,OA(s,this.workletProcessorChannels[e].midiControllers,0,v.polyPressure))}),this.callEvent("polypressure",{channel:e,midiNote:A,pressure:t})}function mn(e,A){if(A.length!==12)throw new Error("Tuning is not the length of 12.");this.workletProcessorChannels[e].channelOctaveTuning=A}function pn(e,A,t,s=!1){let n=this.workletProcessorChannels[e];if(n===void 0){b(`Trying to access channel ${e} which does not exist... ignoring!`);return}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(E=>OA(E,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.`,I.info);return;case"xg":o===120||o===126||o===127?this.setDrums(e,!0):e%16!==pA&&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=uA.RPFine;break;case S.RPNMsb:n.RPValue=t,n.dataEntryState=uA.RPCoarse;break;case S.NRPNMsb:n.NRPCoarse=t,n.dataEntryState=uA.NRPCoarse;break;case S.NRPNLsb:n.NRPFine=t,n.dataEntryState=uA.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(E=>{this.releaseVoice(E)}),n.sustainedVoices=[]);break;default:if(n.lockedControllers[A])return;n.midiControllers[A]=t<<7,n.voices.forEach(E=>OA(E,n.midiControllers,1,A)),this.callEvent("controllerchange",{channel:e,controllerNumber:A,controllerValue:t});break}}function Sn(e){this.midiVolume=e,this.setMasterPan(this.pan)}function yn(e){this.masterGain=e*Mt,this.setMasterPan(this.pan)}function Dn(e){this.pan=e,e=e/2+.5,this.panLeft=(1-e)*this.currentGain,this.panRight=e*this.currentGain}function kn(e,A){A&&this.stopAll(e,!0),this.workletProcessorChannels[e].isMuted=A,this.sendChannelProperties(),this.callEvent("mutechannel",{channel:e,isMuted:A})}function wn(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 Fn(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 Rn(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 uA.Idle:break;case uA.NRPFine:if(this.system!=="gs")return;switch(t.NRPCoarse){default:if(A===64)return;b(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16).toUpperCase()} 0x${t.NRPFine.toString(16).toUpperCase()})%c data value: %c${A}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case 1:switch(t.NRPFine){default:if(A===64)return;b(`%cUnrecognized NRPN for %c${e}%c: %c(0x${t.NRPCoarse.toString(16)} 0x${t.NRPFine.toString(16)})%c data value: %c${A}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.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.`,I.info,I.recognized,I.info,I.value,I.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.`,I.info,I.recognized,I.info,I.value,I.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.`,I.info,I.recognized,I.info,I.value,I.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}`,I.info,I.recognized,I.info,I.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}`,I.info,I.recognized,I.info,I.value);break}break;case uA.RPCoarse:case uA.RPFine:switch(t.RPValue){default:b(`%cUnrecognized RPN for %c${e}%c: %c(0x${t.RPValue.toString(16)})%c data value: %c${A}`,I.warn,I.recognized,I.warn,I.unrecognized,I.warn,I.value);break;case 0:t.midiControllers[gA+v.pitchWheelRange]=A<<7,p(`%cChannel ${e} bend range. Semitones: %c${A}`,I.info,I.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 Gn(e,A){let t=this.workletProcessorChannels[e];switch(t.dataEntryState){default:break;case uA.RPCoarse:case uA.RPFine:switch(t.RPValue){default:break;case 0:if(A===0)break;t.midiControllers[gA+v.pitchWheelRange]|=A;let s=(t.midiControllers[gA+v.pitchWheelRange]>>7)+A/127;p(`%cChannel ${e} bend range. Semitones: %c${s}`,I.info,I.value);break;case 1:let o=t.customControllers[iA.channelTuning]<<7|A;this.setChannelTuning(e,o*.01220703125);break;case 5:let g=t.customControllers[iA.modulationMultiplier]*50+A/128*100;this.setModulationDepth(e,g);break;case 16383:this.resetParameters(e);break}}}function xn(){p("%cResetting all controllers!",I.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[gA+v.pitchWheel]){let s=this.workletProcessorChannels[e].midiControllers[gA+v.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=Ye}function Mn(e){let A=this.workletProcessorChannels[e],s=A.lockedControllers.reduce((o,E,g)=>(E&&o.push(g),o),[]).map(o=>({ccNum:o,ccVal:A.midiControllers[o]}));A.channelOctaveTuning.fill(0),A.midiControllers.set(PA),A.channelVibrato={rate:0,depth:0,delay:0},A.holdPedal=!1,s.forEach(o=>{A.midiControllers[o.ccNum]=o.ccVal});let n=A.customControllers[iA.channelTransposeFine];A.customControllers.set(St),A.customControllers[iA.channelTransposeFine]=n,this.resetParameters(e)}function Nn(e){let A=this.workletProcessorChannels[e];A.NRPCoarse=0,A.NRPFine=0,A.RPValue=0,A.dataEntryState=uA.Idle}function bn(){let e=4;for(let s of this.instruments)e+=s.instrumentZones.reduce((n,o)=>(o.generators=o.generators.filter(E=>E.generatorType!==a.sampleID&&E.generatorType!==a.keyRange&&E.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.sampleID,generatorValue:this.samples.indexOf(o.sample)}),o.generators.length*4+n),0);let A=new Y(e),t=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.generatorZoneStartIndex=t;for(let o of n.generators)J(A,o.generatorType),J(A,o.generatorValue),t++}return cA(A,0),tA(new j("igen",A.length,A))}function Ln(e,A,t,s,n){let o=this.samples.map((c,d)=>{t&&c.compressSample(s,n);let u=c.getRawData();return p(`%cEncoded sample %c${d}. ${c.sampleName}%c of %c${this.samples.length}`,I.info,I.recognized,I.info,I.recognized),u}),E=this.samples.reduce((c,d,u)=>c+o[u].length+46,0),g=new Y(E);this.samples.forEach((c,d)=>{let u=o[d],Q,l,m=u.length;c.isCompressed?(Q=g.currentIndex,l=Q+u.length):(Q=g.currentIndex/2,l=Q+u.length/2,m+=46),e.push(Q),g.set(u,g.currentIndex),g.currentIndex+=m,A.push(l)});let h=tA(new j("smpl",g.length,g),new Y([115,100,116,97]));return tA(new j("LIST",h.length,h))}function Un(e,A){let s=new Y(46*(this.samples.length+1));return this.samples.forEach((n,o)=>{wA(s,n.sampleName,20);let E=e[o];cA(s,E);let g=A[o];cA(s,g);let h=n.sampleLoopStartIndex/2+E,c=n.sampleLoopEndIndex/2+E;n.isCompressed&&(h-=E,c-=E),cA(s,h),cA(s,c),cA(s,n.sampleRate),s[s.currentIndex++]=n.samplePitch,s[s.currentIndex++]=n.samplePitchCorrection,J(s,n.sampleLink),J(s,n.sampleType)}),wA(s,"EOS",46),tA(new j("shdr",s.length,s))}function Tn(){let e=10;for(let s of this.instruments)e+=s.instrumentZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new Y(e),t=0;for(let s of this.instruments)for(let n of s.instrumentZones){n.modulatorZoneStartIndex=t;for(let o of n.modulators)J(A,o.modulatorSource),J(A,o.modulatorDestination),J(A,o.transformAmount),J(A,o.modulationSecondarySrc),J(A,o.transformType),t++}return Ie(A,0,10),tA(new j("imod",A.length,A))}function Hn(){let e=this.instruments.reduce((o,E)=>E.instrumentZones.length*4+o,4),A=new Y(e),t=0,s=0,n=0;for(let o of this.instruments){o.instrumentZoneIndex=t;for(let E of o.instrumentZones)E.zoneID=t,J(A,s),J(A,n),s+=E.generators.length,n+=E.modulators.length,t++}return J(A,s),J(A,n),tA(new j("ibag",A.length,A))}function Yn(){let e=this.instruments.length*22+22,A=new Y(e),t=0,s=0;for(let n of this.instruments)wA(A,n.instrumentName,20),J(A,t),t+=n.instrumentZones.length,n.instrumentID=s,s++;return wA(A,"EOI",20),J(A,t),tA(new j("inst",A.length,A))}function Jn(){let e=4;for(let s of this.presets)e+=s.presetZones.reduce((n,o)=>(o.generators=o.generators.filter(E=>E.generatorType!==a.instrument&&E.generatorType!==a.keyRange&&E.generatorType!==a.velRange),(o.velRange.max!==127||o.velRange.min!==0)&&o.generators.unshift({generatorType:a.velRange,generatorValue:o.velRange.max<<8|o.velRange.min}),(o.keyRange.max!==127||o.keyRange.min!==0)&&o.generators.unshift({generatorType:a.keyRange,generatorValue:o.keyRange.max<<8|o.keyRange.min}),o.isGlobal||o.generators.push({generatorType:a.instrument,generatorValue:this.instruments.indexOf(o.instrument)}),o.generators.length*4+n),0);let A=new Y(e),t=0;for(let s of this.presets)for(let n of s.presetZones){n.generatorZoneStartIndex=t;for(let o of n.generators)J(A,o.generatorType),J(A,o.generatorValue);t+=n.generators.length}return J(A,0),J(A,0),tA(new j("pgen",A.length,A))}function qn(){let e=10;for(let s of this.presets)e+=s.presetZones.reduce((n,o)=>o.modulators.length*10+n,0);let A=new Y(e),t=0;for(let s of this.presets)for(let n of s.presetZones){n.modulatorZoneStartIndex=t;for(let o of n.modulators)J(A,o.modulatorSource),J(A,o.modulatorDestination),J(A,o.transformAmount),J(A,o.modulationSecondarySrc),J(A,o.transformType),t++}return Ie(A,0,10),tA(new j("pmod",A.length,A))}function Kn(){let e=this.presets.reduce((o,E)=>E.presetZones.length*4+o,4),A=new Y(e),t=0,s=0,n=0;for(let o of this.presets){o.presetZoneStartIndex=t;for(let E of o.presetZones)E.zoneID=t,J(A,s),J(A,n),s+=E.generators.length,n+=E.modulators.length,t++}return J(A,s),J(A,n),tA(new j("pbag",A.length,A))}function Pn(){let e=this.presets.length*38+38,A=new Y(e),t=0;for(let s of this.presets)wA(A,s.presetName,20),J(A,s.program),J(A,s.bank),J(A,t),cA(A,s.library),cA(A,s.genre),cA(A,s.morphology),t+=s.presetZones.length;return wA(A,"EOP",20),J(A,0),J(A,0),J(A,t),cA(A,0),cA(A,0),cA(A,0),tA(new j("phdr",A.length,A))}var Lo={compress:!1,compressionQuality:.5,compressionFunction:void 0};function vn(e=Lo){if(e.compress&&typeof e.compressionFunction!="function")throw new TypeError("No compression function supplied but compression enabled.");DA("%cSaving soundfont...",I.info),p(`%cCompression: %c${e?.compress||"false"}%c quality: %c${e?.compressionQuality||"none"}`,I.info,I.recognized,I.info,I.recognized),p("%cWriting INFO...",I.info);let A=[];this.soundFontInfo.ISFT="SpessaSynth",e?.compress&&(this.soundFontInfo.ifil="3.0");for(let[Z,H]of Object.entries(this.soundFontInfo))if(Z==="ifil"||Z==="iver"){let r=parseInt(H.split(".")[0]),sA=parseInt(H.split(".")[1]),K=new Y(4);J(K,r),J(K,sA),A.push(tA(new j(Z,4,K)))}else{let r=new Y(H.length);wA(r,H),A.push(tA(new j(Z,H.length,r)))}let t=pe([new Y([73,78,70,79]),...A]),s=tA(new j("LIST",t.length,t));p("%cWriting SDTA...",I.info);let n=[],o=[],E=Ln.call(this,n,o,e?.compress,e?.compressionQuality||.5,e.compressionFunction);p("%cWriting PDTA...",I.info),p("%cWriting SHDR...",I.info);let g=Un.call(this,n,o);p("%cWriting IGEN...",I.info);let h=bn.call(this);p("%cWriting IMOD...",I.info);let c=Tn.call(this);p("%cWriting IBAG...",I.info);let d=Hn.call(this);p("%cWriting INST...",I.info);let u=Yn.call(this),Q=Jn.call(this);p("%cWriting PMOD...",I.info);let l=qn.call(this);p("%cWriting PBAG...",I.info);let m=Kn.call(this);p("%cWriting PHDR...",I.info);let y=Pn.call(this),k=pe([new Y([112,100,116,97]),y,m,l,Q,u,d,c,h,g]),G=tA(new j("LIST",k.length,k));p("%cWriting the output file...",I.info);let M=pe([new Y([115,102,98,107]),s,E,G]),N=tA(new j("RIFF",M.length,M));return p(`%cSaved succesfully! Final file size: %c${N.length}`,I.info,I.recognized),X(),N}var te=class e{constructor(A=void 0){this.soundFontInfo={},this.presets=[],this.samples=[],this.instruments=[],A?.presets&&(this.presets.push(...A.presets),this.soundFontInfo=A.info)}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()}getPresetNoFallback(A,t,s=!1){let n=this.presets.find(o=>o.bank===A&&o.program===t);if(n)return n;if(s!==!1)return A===128?this.presets.find(o=>o.bank===128):this.presets.find(o=>o.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&&b(`%cPreset ${A}.${t} not found. Replaced with %c${s.presetName} (${s.bank}.${s.program})`,I.warn,I.recognized)),s||(b(`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||(b("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(E=>E.bank===o.bank&&E.program===o.program)===void 0&&s.push(o)});return new e({presets:s,info:t.soundFontInfo})}};te.prototype.write=vn;function Vn(e){DA("%cLoading instruments...",I.info);for(let A=0;AA.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(Q,l,m){return m>=Q&&m<=l}function o(Q,l){return Q.modulatorSource===l.modulatorSource&&Q.modulatorDestination===l.modulatorDestination&&Q.modulationSecondarySrc===l.modulationSecondarySrc&&Q.transformType===l.transformType}function E(Q,l){Q.push(...l.filter(m=>!Q.find(y=>y.generatorType===m.generatorType)))}function g(Q,l){Q.push(...l.filter(m=>!Q.find(y=>o(m,y))))}let h=[],c=this.presetZones[0].isGlobal?[...this.presetZones[0].generators]:[],d=this.presetZones[0].isGlobal?[...this.presetZones[0].modulators]:[];return this.presetZones.filter(Q=>n(Q.keyRange.min,Q.keyRange.max,A)&&n(Q.velRange.min,Q.velRange.max,t)&&!Q.isGlobal).forEach(Q=>{if(Q.instrument.instrumentZones.length<1)return;let l=Q.generators,m=Q.modulators,y=Q.instrument.instrumentZones[0].isGlobal?[...Q.instrument.instrumentZones[0].generators]:[],k=Q.instrument.instrumentZones[0].isGlobal?[...Q.instrument.instrumentZones[0].modulators]:[];Q.instrument.instrumentZones.filter(M=>n(M.keyRange.min,M.keyRange.max,A)&&n(M.velRange.min,M.velRange.max,t)&&!M.isGlobal).forEach(M=>{let N=[...M.generators],Z=[...M.modulators];E(l,c),E(N,y),g(m,d),g(Z,k),g(Z,ws);let H=[...Z];for(let r=0;ro(sA,z));K!==-1?H[K]=H[K].sumTransform(sA):H.push(sA)}h.push({instrumentGenerators:N,presetGenerators:l,modulators:H,sample:M.sample,sampleID:M.generators.find(r=>r.generatorType===a.sampleID).generatorValue})})}),this.foundSamplesAndGenerators[A][t]=h,h}};var ke=class{velRange={min:0,max:127};keyRange={min:0,max:127};isGlobal=!1;generators=[];modulators=[]};var zA=class extends ke{sample=void 0;useCount=0;deleteZone(){this.useCount--,!this.isGlobal&&this.sample.useCount--}},Be=class extends ke{instrument=void 0;deleteZone(){this.isGlobal||this.instrument.removeUseCount()}};var he=class{constructor(){this.instrumentName="",this.instrumentZones=[],this._useCount=0}addUseCount(){this._useCount++,this.instrumentZones.forEach(A=>A.useCount++)}removeUseCount(){this._useCount--;for(let A=0;AA.deleteZone()),this.instrumentZones.length=0}safeDeleteZone(A){return this.instrumentZones[A].useCount--,this.instrumentZones[A].useCount<1?(this.deleteZone(A),!0):!1}deleteZone(A){this.instrumentZones[A].deleteZone(),this.instrumentZones.splice(A,1)}};var ze=class extends Ee{constructor(A,t){super(),this.program=t&127,this.bank=A>>8&127,A>>31&&(this.bank=128),this.DLSInstrument=new he,this.DLSInstrument.addUseCount();let n=new Be;n.instrument=this.DLSInstrument,this.presetZones=[n]}};function On(e){this.verifyHeader(e,"LIST"),this.verifyText(V(e.chunkData,4),"ins ");let A=[];for(;e.chunkData.length>e.chunkData.currentIndex;)A.push(O(e.chunkData));let t=A.find(l=>l.header==="insh");if(!t)throw X(),new Error("No instrument header!");let s=D(t.chunkData,4),n=D(t.chunkData,4),o=D(t.chunkData,4),E=new ze(n,o),g="unnamedPreset",h=SA(A,"INFO");if(h){let l=O(h.chunkData);for(;l.header!=="INAM";)l=O(h.chunkData);g=V(l.chunkData,l.chunkData.length).trim()}E.presetName=g,E.DLSInstrument.instrumentName=g,Ae(`%cParsing %c"${g}"%c...`,I.info,I.recognized,I.info);let c=SA(A,"lrgn");if(!c)throw X(),new Error("No region list!");let d=new zA;d.isGlobal=!0;let u=SA(A,"lart"),Q=SA(A,"lar2");this.readLart(u,Q,d),E.DLSInstrument.instrumentZones.push(d);for(let l=0;l>10&15;G===lA.linear&&k!==lA.linear&&(G=k);let M=s>>14&1,N=s>>15&1;E===a.initialAttenuation&&(N=!N),u=KA(G,M,N,g.isCC,g.enum)}let Q=s>>4&15,l=s>>8&1,m=s>>9&1,y=KA(Q,l,m,d.isCC,d.enum);if(h){let k=y;y=u,u=k}return new rA({srcEnum:u,secSrcEnum:y,dest:E,transform:0,amt:n})}function Nt(e,A){let t=e.chunkData,s=[],n=[];D(t,4);let o=D(t,4);for(let E=0;E>16;if(g===0&&h===0&&d===0){let l;switch(c){case R.pan:l=new L(a.pan,Q);break;case R.gain:l=new L(a.initialAttenuation,-Q*10/.4);break;case R.filterCutoff:l=new L(a.initialFilterFc,Q);break;case R.filterQ:l=new L(a.initialFilterQ,Q);break;case R.modLfoFreq:l=new L(a.freqModLFO,Q);break;case R.modLfoDelay:l=new L(a.delayModLFO,Q);break;case R.vibLfoFreq:l=new L(a.freqVibLFO,Q);break;case R.vibLfoDelay:l=new L(a.delayVibLFO,Q);break;case R.volEnvDelay:l=new L(a.delayVolEnv,Q);break;case R.volEnvAttack:l=new L(a.attackVolEnv,Q);break;case R.volEnvHold:l=new L(a.holdVolEnv,Q);break;case R.volEnvDecay:l=new L(a.decayVolEnv,Q);break;case R.volEnvRelease:l=new L(a.releaseVolEnv,Q);break;case R.volEnvSustain:let m=(1e3-Q)/10;l=new L(a.sustainVolEnv,m*10);break;case R.modEnvDelay:l=new L(a.delayModEnv,Q);break;case R.modEnvAttack:l=new L(a.attackModEnv,Q);break;case R.modEnvHold:l=new L(a.holdModEnv,Q);break;case R.modEnvDecay:l=new L(a.decayModEnv,Q);break;case R.modEnvRelease:l=new L(a.releaseModEnv,Q);break;case R.modEnvSustain:let y=1e3-Q;l=new L(a.sustainModEnv,y);break;case R.reverbSend:l=new L(a.reverbEffectsSend,Q);break;case R.chorusSend:l=new L(a.chorusEffectsSend,Q);break;case R.pitch:let k=Math.floor(Q/100),G=Math.floor(Q-k*100);l=new L(a.fineTune,G),s.push(new L(a.coarseTune,k));break}l&&s.push(l)}else{let l=!0;if(h===_.none)if(g===_.modLfo&&c===R.pitch)s.push(new L(a.modLfoToPitch,Q));else if(g===_.modLfo&&c===R.gain)s.push(new L(a.modLfoToVolume,Q));else if(g===_.modLfo&&c===R.filterCutoff)s.push(new L(a.modLfoToFilterFc,Q));else if(g===_.vibratoLfo&&c===R.pitch)s.push(new L(a.vibLfoToPitch,Q));else if(g===_.modEnv&&c===R.pitch)s.push(new L(a.modEnvToPitch,Q));else if(g===_.modEnv&&c===R.filterCutoff)s.push(new L(a.modEnvToFilterFc,Q));else if(g===_.keyNum&&c===R.volEnvHold){s.push(new L(a.keyNumToVolEnvHold,Q/-128));let m=Math.round(60/128*Q);s.forEach(y=>{y.generatorType===a.holdVolEnv&&(y.generatorValue+=m)})}else if(g===_.keyNum&&c===R.volEnvDecay){s.push(new L(a.keyNumToVolEnvDecay,Q/-128));let m=Math.round(60/128*Q);s.forEach(y=>{y.generatorType===a.decayVolEnv&&(y.generatorValue+=m)})}else if(g===_.keyNum&&c===R.modEnvHold){s.push(new L(a.keyNumToModEnvHold,Q/-128));let m=Math.round(60/128*Q);s.forEach(y=>{y.generatorType===a.holdModEnv&&(y.generatorValue+=m)})}else if(g===_.keyNum&&c===R.modEnvDecay){s.push(new L(a.keyNumToModEnvDecay,Q/-128));let m=Math.round(60/128*Q);s.forEach(y=>{y.generatorType===a.decayModEnv&&(y.generatorValue+=m)})}else l=!1;else l=!1;if(l===!1){let m=Xn(g,h,c,d,Q);m?(n.push(m),p("%cSucceeded converting to SF2 Modulator!",I.recognized)):b("Failed converting to SF2 Modulator!")}}}return n.find(E=>E.modulatorDestination===a.reverbEffectsSend)===void 0&&n.push(new rA({srcEnum:219,dest:a.reverbEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),n.find(E=>E.modulatorDestination===a.chorusEffectsSend)===void 0&&n.push(new rA({srcEnum:221,dest:a.chorusEffectsSend,amt:1e3,secSrcEnum:0,transform:0})),A&&n.push(new rA({srcEnum:129,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0}),new rA({srcEnum:13,dest:a.vibLfoToPitch,amt:0,secSrcEnum:0,transform:0})),{modulators:n,generators:s}}function Wn(e,A,t){if(e)for(;e.chunkData.currentIndexe.chunkData.currentIndex;)A.push(O(e.chunkData));let t=A.find(r=>r.header==="rgnh"),s=D(t.chunkData,2),n=D(t.chunkData,2),o=D(t.chunkData,2),E=D(t.chunkData,2),g=new je({min:s,max:n},{min:o,max:E});D(t.chunkData,2);let h=D(t.chunkData,2);h!==0&&g.generators.push(new L(a.exclusiveClass,h));let c=SA(A,"lart"),d=SA(A,"lar2");this.readLart(c,d,g),g.isGlobal=!1;let u=A.find(r=>r.header==="wsmp");D(u.chunkData,4);let Q=D(u.chunkData,2);D(u.chunkData,2);let y=(D(u.chunkData,4)|0)/-655360*10/.4;D(u.chunkData,4);let k=D(u.chunkData,4),G,M={start:0,end:0};if(k===0)G=0;else{D(u.chunkData,4),D(u.chunkData,4)===0?G=1:G=3,M.start=D(u.chunkData,4);let sA=D(u.chunkData,4);M.end=M.start+sA}let N=A.find(r=>r.header==="wlnk");if(N===void 0)return;D(N.chunkData,2),D(N.chunkData,2),D(N.chunkData,4);let Z=D(N.chunkData,4),H=this.samples[Z];if(H===void 0)throw new Error("Invalid sample ID!");return g.setWavesample(y,G,M,Q,H,Z),g}var Qe=class{constructor(A,t,s,n,o,E,g,h){this.sampleName=A,this.sampleRate=t,this.samplePitch=s,this.samplePitchCorrection=n,this.sampleLink=o,this.sampleType=E,this.sampleLoopStartIndex=g,this.sampleLoopEndIndex=h,this.isCompressed=(E&16)>0,this.compressedData=void 0,this.useCount=0}getRawData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}compressSample(A,t){if(!this.isCompressed)try{this.compressedData=t([this.getAudioData()],1,this.sampleRate,A),this.sampleType|=16,this.isCompressed=!0}catch{b(`Failed to compress ${this.sampleName}. Leaving as uncompressed!`),this.isCompressed=!1,this.compressedData=void 0,this.sampleType&=-17}}getAudioData(){let A=new Error("Not implemented");throw A.name="NotImplementedError",A}};var $e=class extends Qe{constructor(A,t,s,n,o,E,g){super(A,t,s,n,0,1,o*2,(E-1)*2),this.sampleData=g}getAudioData(){return this.sampleData}sampleData;getRawData(){if(this.isCompressed){if(!this.compressedData)throw new Error("Compressed but no data??");return this.compressedData}let A=new Uint8Array(this.sampleData.length*2);for(let t=0;t>8&255}return A}};function zn(e){DA("%cLoading Wave samples...",I.recognized);let A=0;for(;e.chunkData.currentIndexK.header==="fmt ");if(!n)throw new Error("No fmt chunk in the wave file!");if(D(n.chunkData,2)!==1)throw new Error("Only PCM format in WAVE is supported.");if(D(n.chunkData,2)!==1)throw new Error("Only mono samples are supported.");let g=D(n.chunkData,4);D(n.chunkData,4),D(n.chunkData,2);let h=D(n.chunkData,2),c=h/8,d=Math.pow(2,c*8-1),u=Math.pow(2,c*8),Q,l=!1;h===8?(Q=255,l=!0):Q=d;let m=s.find(K=>K.header==="data");if(!m)throw new Error("No data chunk in the wave chunk!");let y=m.size/c,k=new Float32Array(y);for(let K=0;K=d&&(z-=u),k[K]=z/Q)}let G=60,M=0,N=0,Z=k.length-1,H=s.find(K=>K.header==="wsmp");if(H){if(D(H.chunkData,4),G=D(H.chunkData,2),M=ae(H.chunkData[H.chunkData.currentIndex++],H.chunkData[H.chunkData.currentIndex++]),D(H.chunkData,4),D(H.chunkData,4),D(H.chunkData,4)===1){D(H.chunkData,8),N=D(H.chunkData,4);let z=D(H.chunkData,4);Z=N+z}}else b("No wsmp chunk in wave... using sane defaults.");let r=SA(s,"INFO"),sA=`Unnamed ${A}`;if(r){let K=O(r.chunkData);for(;K.header!=="INAM"&&r.chunkData.currentIndexh.header==="colh");if(!o)throw X(),new Error("No colh chunk!");this.instrumentAmount=D(o.chunkData,4),p(`%cInstruments amount: %c${this.instrumentAmount}`,I.info,I.recognized);let E=SA(s,"wvpl");this.readDLSSamples(E);let g=SA(s,"lins");if(!g)throw X(),new Error("No lins chunk!");this.readDLSInstrumentList(g),p(`%cParsing finished! %c"${this.soundFontInfo.INAM||"UNNAMED"}"%c has %c${this.presets.length} %cpresets, %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),X()}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw X(),new SyntaxError(`Invalid DLS chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw X(),new SyntaxError(`Invalid DLS soundfont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}};ZA.prototype.readDLSInstrumentList=Vn;ZA.prototype.readDLSInstrument=On;ZA.prototype.readRegion=_n;ZA.prototype.readLart=Wn;ZA.prototype.readDLSSamples=zn;var bt=class extends Qe{constructor(A,t,s,n,o,E,g,h,c,d,u,Q,l){super(A,E,g,h,c,d,n-t,o-t),this.sampleName=A,this.sampleStartIndex=t,this.sampleEndIndex=s,this.isSampleLoaded=!1,this.sampleID=Q,this.sampleLength=this.sampleEndIndex-this.sampleStartIndex,this.sampleDataArray=u,this.sampleData=new Float32Array(0),this.isCompressed&&(this.sampleLoopStartIndex+=this.sampleStartIndex,this.sampleLoopEndIndex+=this.sampleStartIndex,this.sampleLength=99999999),this.isDataRaw=l}getRawData(){let A=this.sampleDataArray;if(this.isCompressed){if(this.compressedData)return this.compressedData;let t=A.currentIndex;return A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t)}else{if(!this.isDataRaw)throw new Error("Writing SF2Pack samples is not supported.");let t=A.currentIndex;return A.slice(t+this.sampleStartIndex,t+this.sampleEndIndex)}}decodeVorbis(){if(this.sampleLength<1)return;let A=this.sampleDataArray,t=A.currentIndex,s=A.slice(this.sampleStartIndex/2+t,this.sampleEndIndex/2+t);this.sampleData=new Float32Array(0);let n=vA.decode(s.buffer);this.sampleData=n.data[0]}getAudioData(){return this.isSampleLoaded?this.sampleData:this.sampleLength<1?new Float32Array(1):this.isCompressed?(this.decodeVorbis(),this.isSampleLoaded=!0,this.sampleData):this.isDataRaw?this.loadUncompressedData():this.getUncompressedReadyData()}loadUncompressedData(){if(this.isCompressed)return b("Trying to load a compressed sample via loadUncompressedData()... aborting!"),new Float32Array(0);let A=new Float32Array(this.sampleLength/2),t=this.sampleDataArray.currentIndex,s=new Int16Array(this.sampleDataArray.slice(t+this.sampleStartIndex,t+this.sampleEndIndex).buffer);for(let n=0;ne.chunkData.currentIndex;){let o=Ho(n,e.chunkData,A,t);s.push(o),n++}return s.length>1&&s.pop(),s}function Ho(e,A,t,s){let n=V(A,20),o=D(A,4)*2,E=D(A,4)*2,g=D(A,4)*2,h=D(A,4)*2,c=D(A,4),d=A[A.currentIndex++];d===255&&(d=60);let u=Ds(A[A.currentIndex++]),Q=D(A,2),l=D(A,2);return new bt(n,o,E,g,h,c,d,u,Q,l,t,e,s)}var Lt=class extends he{constructor(A){super(),this.instrumentName=V(A.chunkData,20).trim(),this.instrumentZoneIndex=D(A.chunkData,2),this.instrumentZonesAmount=0}getInstrumentZones(A,t){this.instrumentZonesAmount=A;for(let s=this.instrumentZoneIndex;se.chunkData.currentIndex;){let s=new Lt(e);if(t.length>0){let n=s.instrumentZoneIndex-t[t.length-1].instrumentZoneIndex;t[t.length-1].getInstrumentZones(n,A)}t.push(s)}return t.length>1&&t.pop(),t}var Ut=class extends zA{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;ts.generatorType===a.sampleID);t&&(this.sample=A[t.generatorValue],this.isGlobal=!1,this.sample.useCount++)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function Ao(e,A,t,s){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Ut(e.chunkData);if(n.length>0){let E=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(E,g),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(o)}return n.length>1&&n.pop(),n}var Tt=class extends Be{constructor(A){super(),this.generatorZoneStartIndex=D(A,2),this.modulatorZoneStartIndex=D(A,2),this.modulatorZoneSize=0,this.generatorZoneSize=0,this.isGlobal=!0}setZoneSize(A,t){this.modulatorZoneSize=A,this.generatorZoneSize=t}getGenerators(A){for(let t=this.generatorZoneStartIndex;ts.generatorType===a.instrument);t&&(this.instrument=A[t.generatorValue],this.instrument.addUseCount(),this.isGlobal=!1)}getKeyRange(){let A=this.generators.find(t=>t.generatorType===a.keyRange);A&&(this.keyRange.min=A.generatorValue&127,this.keyRange.max=A.generatorValue>>8&127)}getVelRange(){let A=this.generators.find(t=>t.generatorType===a.velRange);A&&(this.velRange.min=A.generatorValue&127,this.velRange.max=A.generatorValue>>8&127)}};function eo(e,A,t,s){let n=[];for(;e.chunkData.length>e.chunkData.currentIndex;){let o=new Tt(e.chunkData);if(n.length>0){let E=o.modulatorZoneStartIndex-n[n.length-1].modulatorZoneStartIndex,g=o.generatorZoneStartIndex-n[n.length-1].generatorZoneStartIndex;n[n.length-1].setZoneSize(E,g),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(o)}return n.length>1&&n.pop(),n}var Ht=class extends Ee{constructor(A){super(),this.presetName=V(A.chunkData,20).trim().replace(/\d{3}:\d{3}/,""),this.program=D(A.chunkData,2),this.bank=D(A.chunkData,2),this.presetZoneStartIndex=D(A.chunkData,2),this.library=D(A.chunkData,4),this.genre=D(A.chunkData,4),this.morphology=D(A.chunkData,4),this.presetZonesAmount=0}getPresetZones(A,t){this.presetZonesAmount=A;for(let s=this.presetZoneStartIndex;se.chunkData.currentIndex;){let s=new Ht(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}var At=class extends te{constructor(A,t=!0){if(super(),t&&console.warn("Using the constructor directly is deprecated. Use loadSoundFont instead."),this.dataArray=new Y(A),Ae("%cParsing SoundFont...",I.info),!this.dataArray)throw X(),new TypeError("No data!");let s=O(this.dataArray,!1);this.verifyHeader(s,"riff");let n=V(this.dataArray,4).toLowerCase();if(n!=="sfbk"&&n!=="sfpk")throw X(),new SyntaxError(`Invalid soundFont! Expected "sfbk" or "sfpk" got "${n}"`);let o=n==="sfpk",E=O(this.dataArray);for(this.verifyHeader(E,"list"),V(E.chunkData,4);E.chunkData.length>E.chunkData.currentIndex;){let $=O(E.chunkData),QA;switch($.header.toLowerCase()){case"ifil":case"iver":QA=`${D($.chunkData,2)}.${D($.chunkData,2)}`;break;case"icmt":QA=V($.chunkData,$.chunkData.length,void 0,!1);break;default:QA=V($.chunkData,$.chunkData.length)}p(`%c"${$.header}": %c"${QA}"`,I.info,I.recognized),this.soundFontInfo[$.header]=QA}let g=O(this.dataArray,!1);this.verifyHeader(g,"list"),this.verifyText(V(this.dataArray,4),"sdta"),p("%cVerifying smpl chunk...",I.warn);let h=O(this.dataArray,!1);this.verifyHeader(h,"smpl");let c;if(o){p("%cSF2Pack detected, attempting to decode the smpl chunk...",I.info);try{c=vA.decode(this.dataArray.buffer.slice(this.dataArray.currentIndex,this.dataArray.currentIndex+g.size-12)).data[0]}catch($){throw X(),new Error(`SF2Pack Ogg Vorbis decode error: ${$}`)}p(`%cDecoded the smpl chunk! Length: %c${c.length}`,I.info,I.value)}else c=this.dataArray,this.sampleDataStartIndex=this.dataArray.currentIndex;p(`%cSkipping sample chunk, length: %c${g.size-12}`,I.info,I.value),this.dataArray.currentIndex+=g.size-12,p("%cLoading preset data chunk...",I.warn);let d=O(this.dataArray);this.verifyHeader(d,"list"),V(d.chunkData,4);let u=O(d.chunkData);this.verifyHeader(u,"phdr");let Q=O(d.chunkData);this.verifyHeader(Q,"pbag");let l=O(d.chunkData);this.verifyHeader(l,"pmod");let m=O(d.chunkData);this.verifyHeader(m,"pgen");let y=O(d.chunkData);this.verifyHeader(y,"inst");let k=O(d.chunkData);this.verifyHeader(k,"ibag");let G=O(d.chunkData);this.verifyHeader(G,"imod");let M=O(d.chunkData);this.verifyHeader(M,"igen");let N=O(d.chunkData);this.verifyHeader(N,"shdr"),this.dataArray.currentIndex=this.sampleDataStartIndex,this.samples.push(...jn(N,c,!o));let Z=ut(M),H=mt(G),r=Ao(k,Z,H,this.samples);this.instruments=$n(y,r);let sA=ut(m),K=mt(l),z=eo(Q,sA,K,this.instruments);this.presets.push(...to(u,z)),this.presets.sort(($,QA)=>$.program-QA.program+($.bank-QA.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.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),X(),o&&delete this.dataArray}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw X(),new SyntaxError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw X(),new SyntaxError(`Invalid soundFont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}};function we(e){let A=e.slice(8,12),t=new Y(A);return V(t,4,void 0,!1).toLowerCase()==="dls "?new ZA(e):new At(e,!1)}function so(e,A,t=!1){let s=this.workletProcessorChannels[e];if(s===void 0){b(`Trying to access channel ${e} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[S.bankSelect],o,E;if(this.overrideSoundfont){let g=n===128?128:n-this.soundfontBankOffset,h=this.overrideSoundfont.getPresetNoFallback(g,A);h?(o=n,E=h,s.presetUsesOverride=!0):(E=this.soundfontManager.getPreset(n,A),o=E.bank,s.presetUsesOverride=!1)}else E=this.soundfontManager.getPreset(n,A),o=E.bank,s.presetUsesOverride=!1;this.setPreset(e,E),this.callEvent("programchange",{channel:e,program:E.program,bank:o,userCalled:t})}function no(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,s=this.overrideSoundfont.getPresetNoFallback(t,A);if(s)return s}return this.soundfontManager.getPreset(e,A)}function oo(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 ro(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 io(){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 Io(e=!0,A=!0){this.stopAllChannels(!0),sn(),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:mA.ready,messageData:void 0}),this.sendPresetList(),p("%cSpessaSynth is ready!",I.recognized)}function go(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[a.endAddrOffset]+s.generators[a.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 Co(){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:mA.synthesizerSnapshot,messageData:A})}function Eo(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!",I.info)}var et=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 ie.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case ie.reloadSoundFont:this.reloadManager(t);break;case ie.deleteSoundFont:this.deleteSoundFont(t);break;case ie.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let t=we(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:t}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){b("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(s=>s.id===A);if(t===-1){b(`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:we(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 xt=.07,Mt=1,T=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=bA,this.interpolationType=Xe.linear,this.processTickCallback=void 0,this.sequencer=new CA(this),this.transposition=0,this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Mt,this.midiVolume=1,this.voiceCap=cs,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new et(A.processorOptions.soundfont,this.postReady.bind(this))}catch(t){throw this.post({messageType:mA.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.",I.info),A.processorOptions.startRenderingData.parsedMIDI&&(this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]),this.sequencer.loop=!1)),vA.isInitialized.then(()=>{this.postReady(),p("%cSpessaSynth is ready!",I.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:mA.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 E,g,h,c,d;if(this.oneOutputMode){let Q=t[0];E=o%16*2,g=Q[E],h=Q[E+1]}else E=o%this._outputsAmount+2,g=t[E][0],h=t[E][1],c=t[0],d=t[1];let u=n.voices;n.voices=[],u.forEach(Q=>{this.renderVoice(n,Q,g,h,c,d),Q.finished||n.voices.push(Q)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};T.prototype.renderVoice=Xs;T.prototype.releaseVoice=_s;T.prototype.voiceKilling=Ws;T.prototype.handleMessage=$s;T.prototype.sendChannelProperties=en;T.prototype.callEvent=An;T.prototype.systemExclusive=tn;T.prototype.noteOn=rn;T.prototype.noteOff=In;T.prototype.polyPressure=dn;T.prototype.killNote=an;T.prototype.stopAll=gn;T.prototype.stopAllChannels=Cn;T.prototype.muteChannel=kn;T.prototype.setVibrato=Fn;T.prototype.disableAndLockVibrato=wn;T.prototype.dataEntryCoarse=Rn;T.prototype.dataEntryFine=Gn;T.prototype.createWorkletChannel=Fs;T.prototype.controllerChange=pn;T.prototype.channelPressure=fn;T.prototype.resetAllControllers=xn;T.prototype.resetControllers=Mn;T.prototype.resetParameters=Nn;T.prototype.setMasterGain=yn;T.prototype.setMasterPan=Dn;T.prototype.setMIDIVolume=Sn;T.prototype.transposeAllChannels=En;T.prototype.transposeChannel=Bn;T.prototype.setChannelTuning=hn;T.prototype.setChannelTuningSemitones=Qn;T.prototype.setMasterTuning=cn;T.prototype.setModulationDepth=ln;T.prototype.pitchWheel=un;T.prototype.setOctaveTuning=mn;T.prototype.programChange=so;T.prototype.getPreset=no;T.prototype.setPreset=oo;T.prototype.setDrums=ro;T.prototype.reloadSoundFont=ao;T.prototype.clearSoundFont=Io;T.prototype.sampleDump=go;T.prototype.sendPresetList=io;T.prototype.sendSynthesizerSnapshot=Co;T.prototype.applySynthesizerSnapshot=Eo;registerProcessor(Qs,T);p("%cProcessor succesfully registered!",I.recognized); + %c${this.instruments.length}%c instruments and %c${this.samples.length}%c samples.`,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info,I.recognized,I.info),X(),o&&delete this.dataArray}verifyHeader(A,t){if(A.header.toLowerCase()!==t.toLowerCase())throw X(),new SyntaxError(`Invalid chunk header! Expected "${t.toLowerCase()}" got "${A.header.toLowerCase()}"`)}verifyText(A,t){if(A.toLowerCase()!==t.toLowerCase())throw X(),new SyntaxError(`Invalid soundFont! Expected "${t.toLowerCase()}" got "${A.toLowerCase()}"`)}};function we(e){let A=e.slice(8,12),t=new Y(A);return V(t,4,void 0,!1).toLowerCase()==="dls "?new ZA(e):new At(e,!1)}function so(e,A,t=!1){let s=this.workletProcessorChannels[e];if(s===void 0){b(`Trying to access channel ${e} which does not exist... ignoring!`);return}if(s.lockPreset)return;let n=s.drumChannel?128:s.midiControllers[S.bankSelect],o,E;if(this.overrideSoundfont){let g=n===128?128:n-this.soundfontBankOffset,h=this.overrideSoundfont.getPresetNoFallback(g,A);h?(o=n,E=h,s.presetUsesOverride=!0):(E=this.soundfontManager.getPreset(n,A),o=E.bank,s.presetUsesOverride=!1)}else E=this.soundfontManager.getPreset(n,A),o=E.bank,s.presetUsesOverride=!1;this.setPreset(e,E),this.callEvent("programchange",{channel:e,program:E.program,bank:o,userCalled:t})}function no(e,A){if(this.overrideSoundfont){let t=e===128?128:e-this.soundfontBankOffset,s=this.overrideSoundfont.getPresetNoFallback(t,A);if(s)return s}return this.soundfontManager.getPreset(e,A)}function oo(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 ro(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 io(){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 Io(e=!0,A=!0){this.stopAllChannels(!0),sn(),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:mA.ready,messageData:void 0}),this.sendPresetList(),p("%cSpessaSynth is ready!",I.recognized)}function go(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[a.endAddrOffset]+s.generators[a.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 Co(){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,interpolation:this.interpolationType};this.post({messageType:mA.synthesizerSnapshot,messageData:A})}function Eo(e){for(this.system=e.system,this.setMasterGain(e.mainVolume),this.setMasterPan(e.pan),this.transposeAllChannels(e.transposition),this.interpolationType=e.interpolation;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!",I.info)}var et=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 ie.addNewSoundFont:this.addNewSoundFont(t[0],t[1],t[2]);break;case ie.reloadSoundFont:this.reloadManager(t);break;case ie.deleteSoundFont:this.deleteSoundFont(t);break;case ie.rearrangeSoundFonts:this.rearrangeSoundFonts(t)}}getPresetList(){return this.presetList.slice()}reloadManager(A){let t=we(A);this.soundfontList=[],this.soundfontList.push({id:"main",bankOffset:0,soundfont:t}),this.generatePresetList(),this.ready()}deleteSoundFont(A){if(this.soundfontList.length===0){b("1 soundfont left. Aborting!");return}let t=this.soundfontList.findIndex(s=>s.id===A);if(t===-1){b(`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:we(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 xt=.07,Mt=1,T=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=bA,this.interpolationType=Xe.linear,this.processTickCallback=void 0,this.sequencer=new CA(this),this.transposition=0,this.tunings=[];for(let t=0;t<127;t++)this.tunings.push([]);this.soundfontBankOffset=0,this.masterGain=Mt,this.midiVolume=1,this.voiceCap=cs,this.pan=0,this.panLeft=.5*this.currentGain,this.highPerformanceMode=!1,this.overrideSoundfont=void 0,this.panRight=.5*this.currentGain;try{this.soundfontManager=new et(A.processorOptions.soundfont,this.postReady.bind(this))}catch(t){throw this.post({messageType:mA.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.",I.info),A.processorOptions.startRenderingData.parsedMIDI&&(this.sequencer.loadNewSongList([A.processorOptions.startRenderingData.parsedMIDI]),this.sequencer.loop=!1)),vA.isInitialized.then(()=>{this.postReady(),p("%cSpessaSynth is ready!",I.recognized)})}post(A){this.enableEventSystem&&this.port.postMessage(A)}postReady(){this.enableEventSystem&&this.port.postMessage({messageType:mA.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 E,g,h,c,d;if(this.oneOutputMode){let Q=t[0];E=o%16*2,g=Q[E],h=Q[E+1]}else E=o%this._outputsAmount+2,g=t[E][0],h=t[E][1],c=t[0],d=t[1];let u=n.voices;n.voices=[],u.forEach(Q=>{this.renderVoice(n,Q,g,h,c,d),Q.finished||n.voices.push(Q)}),s+=n.voices.length}),s!==this.totalVoicesAmount&&(this.totalVoicesAmount=s,this.sendChannelProperties()),!0}};T.prototype.renderVoice=Xs;T.prototype.releaseVoice=_s;T.prototype.voiceKilling=Ws;T.prototype.handleMessage=$s;T.prototype.sendChannelProperties=en;T.prototype.callEvent=An;T.prototype.systemExclusive=tn;T.prototype.noteOn=rn;T.prototype.noteOff=In;T.prototype.polyPressure=dn;T.prototype.killNote=an;T.prototype.stopAll=gn;T.prototype.stopAllChannels=Cn;T.prototype.muteChannel=kn;T.prototype.setVibrato=Fn;T.prototype.disableAndLockVibrato=wn;T.prototype.dataEntryCoarse=Rn;T.prototype.dataEntryFine=Gn;T.prototype.createWorkletChannel=Fs;T.prototype.controllerChange=pn;T.prototype.channelPressure=fn;T.prototype.resetAllControllers=xn;T.prototype.resetControllers=Mn;T.prototype.resetParameters=Nn;T.prototype.setMasterGain=yn;T.prototype.setMasterPan=Dn;T.prototype.setMIDIVolume=Sn;T.prototype.transposeAllChannels=En;T.prototype.transposeChannel=Bn;T.prototype.setChannelTuning=hn;T.prototype.setChannelTuningSemitones=Qn;T.prototype.setMasterTuning=cn;T.prototype.setModulationDepth=ln;T.prototype.pitchWheel=un;T.prototype.setOctaveTuning=mn;T.prototype.programChange=so;T.prototype.getPreset=no;T.prototype.setPreset=oo;T.prototype.setDrums=ro;T.prototype.reloadSoundFont=ao;T.prototype.clearSoundFont=Io;T.prototype.sampleDump=go;T.prototype.sendPresetList=io;T.prototype.sendSynthesizerSnapshot=Co;T.prototype.applySynthesizerSnapshot=Eo;registerProcessor(Qs,T);p("%cProcessor succesfully registered!",I.recognized); diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/snapshot.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/snapshot.js index 5bd9d348..1d46bf6b 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/snapshot.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/snapshot.js @@ -28,6 +28,7 @@ * @property {ChannelSnapshot[]} channelSnapshots - the individual channel snapshots * @property {number} mainVolume - main synth volume (set by MIDI), from 0 to 1 * @property {number} pan - master stereo panning, from -1 to 1 + * @property {interpolationTypes} interpolation - the synth's interpolation type * @property {SynthSystem} system - the synths system. Values can be "gs", "gm", "gm2" or "xg" * @property {number} transposition - the current synth transpositon in semitones. can be a float */ @@ -75,7 +76,8 @@ export function sendSynthesizerSnapshot() mainVolume: this.midiVolume, pan: this.pan, transposition: this.transposition, - system: this.system + system: this.system, + interpolation: this.interpolationType }; this.post({ @@ -98,6 +100,7 @@ export function applySynthesizerSnapshot(snapshot) this.setMasterGain(snapshot.mainVolume); this.setMasterPan(snapshot.pan); this.transposeAllChannels(snapshot.transposition); + this.interpolationType = snapshot.interpolation; // add channels if more needed while(this.workletProcessorChannels.length < snapshot.channelSnapshots.length) diff --git a/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/voice_control.js b/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/voice_control.js index 8f967855..5c3bef1e 100644 --- a/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/voice_control.js +++ b/src/spessasynth_lib/synthetizer/worklet_system/worklet_methods/voice_control.js @@ -108,8 +108,8 @@ export function renderVoice( // use modulation multiplier (RPN modulation depth) cents += modLfoValue * (modPitchDepth * channel.customControllers[customControllers.modulationMultiplier]); // volenv volume offset - // the lfo returns from -1 to 1, we change it to 0-1 here because the volume excursion is only positive - modLfoCentibels = (modLfoValue / 2 + 0.5) * modVolDepth; + // negate the lfo value because audigy starts with increase rather than decrease + modLfoCentibels = -modLfoValue * modVolDepth; // lowpass frequency lowpassCents += modLfoValue * modFilterDepth; } diff --git a/src/website/js/renderer/render_waveforms.js b/src/website/js/renderer/render_waveforms.js index 36f0a9e9..a6e20373 100644 --- a/src/website/js/renderer/render_waveforms.js +++ b/src/website/js/renderer/render_waveforms.js @@ -43,7 +43,7 @@ export function renderWaveforms() const relativeX = waveWidth * x; const relativeY = waveHeight * y + waveHeight / 2; - const multiplier = this.waveMultiplier * waveHeight * this.waveSign; + const multiplier = this.waveMultiplier * waveHeight; // draw this.drawingContext.lineWidth = this.lineThickness; diff --git a/src/website/js/renderer/renderer.js b/src/website/js/renderer/renderer.js index fe3c8a51..c7e35a41 100644 --- a/src/website/js/renderer/renderer.js +++ b/src/website/js/renderer/renderer.js @@ -86,7 +86,6 @@ class Renderer this._normalAnalyserFft = CHANNEL_ANALYSER_FFT; this._drumAnalyserFft = DRUMS_ANALYSER_FFT; this.waveMultiplier = WAVE_MULTIPLIER; - this.waveSign = 1; /** * @type {boolean} diff --git a/src/website/js/settings_ui/settings_html.js b/src/website/js/settings_ui/settings_html.js index 50a350ed..74d23b89 100644 --- a/src/website/js/settings_ui/settings_html.js +++ b/src/website/js/settings_ui/settings_html.js @@ -21,7 +21,7 @@ export const settingsHtml = ` - +
diff --git a/src/website/minified/demo_main.min.js b/src/website/minified/demo_main.min.js index 4ab874bb..c62cd8ea 100644 --- a/src/website/minified/demo_main.min.js +++ b/src/website/minified/demo_main.min.js @@ -1,5 +1,5 @@ var hm=(A=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(A,{get:(r,l)=>(typeof require<"u"?require:r)[l]}):A)(function(A){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+A+'" is not supported')});var l6=class extends Uint8Array{constructor(r){super(r),this.currentIndex=0}currentIndex};function bs(A){let r=A.reduce((I,b)=>I+b.length,0),l=new l6(r),g=0;for(let I of A)l.set(I,g),g+=I.length;return l}function f$(A){A=Math.floor(A);let r=Math.floor(A/60),l=Math.round(A-r*60);return{minutes:r,seconds:l,time:`${r.toString().padStart(2,"0")}:${l.toString().padStart(2,"0")}`}}function wB(A){return A.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}var D1={warn:"color: orange;",unrecognized:"color: red;",info:"color: aqua;",recognized:"color: lime",value:"color: yellow; background-color: black;"};var ui=class{constructor(r,l,g){this.ticks=r,this.messageStatusByte=l,this.messageData=g}};var J3={noteOff:128,noteOn:144,polyPressure:160,controllerChange:176,programChange:192,channelPressure:208,pitchBend:224,systemExclusive:240,timecode:241,songPosition:242,songSelect:243,tuneRequest:246,clock:248,start:250,continue:251,stop:252,activeSensing:254,reset:255,sequenceNumber:0,text:1,copyright:2,trackName:3,instrumentName:4,lyric:5,marker:6,cuePoint:7,midiChannelPrefix:32,midiPort:33,endOfTrack:47,setTempo:81,smpteOffset:84,timeSignature:88,keySignature:89,sequenceSpecific:127};function KQ(A){let r=A&240,l=A&15,g=-1,I=A;return r>=128&&r<=224&&(g=l,I=r),{status:I,channel:g}}var A6={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,effects1Depth:91,effects2Depth:92,effects3Depth:93,effects4Depth:94,effects5Depth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127};var fm=class{constructor(){this.events={noteoff:{},noteon:{},pitchwheel:{},controllerchange:{},programchange:{},channelpressure:{},polypressure:{},drumchange:{},stopall:{},newchannel:{},mutechannel:{},presetlistchange:{},allcontrollerreset:{},soundfonterror:{}}}addEvent(r,l,g){this.events[r][l]=g}removeEvent(r,l){delete this.events[r][l]}callEvent(r,l){this.events[r]&&Object.values(this.events[r]).forEach(g=>g(l))}};var kB={nodesAmount:4,defaultDelay:.03,delayVariation:.01,stereoDifference:.02,oscillatorFrequency:.3,oscillatorFrequencyVariation:.05,oscillatorGain:.003},um=class{constructor(r,l=kB){let g=r.context;this.input=new ChannelSplitterNode(g,{numberOfOutputs:2});let I=new ChannelMergerNode(g,{numberOfInputs:2}),b=[],h0=[],b0=l.oscillatorFrequency,p0=l.defaultDelay;for(let R0=0;R0{let b=await I.arrayBuffer();l.buffer=await A.decodeAudioData(b)})}return l}var B8={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25},mC={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},Hi=-1,u$={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var BD=!0,pD=!0,vB=!0;function Y5(...A){BD&&console.info(...A)}function _4(...A){pD&&console.warn(...A)}function ar(...A){vB&&console.group(...A)}function ei(...A){vB&&console.groupCollapsed(...A)}function t4(){vB&&console.groupEnd()}var zQ={chorusEnabled:!0,chorusConfig:kB,reverbEnabled:!0,reverbImpulseResponse:void 0};var BC={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var Im=class{constructor(r){this.soundfontList=[{id:"main",bankOffset:0}],this._port=r.worklet.port,this.synth=r}_sendToWorklet(r,l){this._port.postMessage({messageType:B8.soundFontManager,messageData:[r,l]})}async addNewSoundFont(r,l,g=0){if(this.soundfontList.find(I=>I.id===l)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this._sendToWorklet(BC.addNewSoundFont,[r,l,g]),await new Promise(I=>this.synth.resolveWhenReady=I),this.soundfontList.push({id:l,bankOffset:g})}deleteSoundFont(r){if(this.soundfontList.length===0){_4("1 soundfont left. Aborting!");return}if(this.soundfontList.findIndex(l=>l.id===r)===-1){_4(`No soundfont with id of "${r}" found. Aborting!`);return}this._sendToWorklet(BC.deleteSoundFont,r)}rearrangeSoundFonts(r){this._sendToWorklet(BC.rearrangeSoundFonts,r),this.soundfontList.sort((l,g)=>r.indexOf(l.id)-r.indexOf(g.id))}async reloadManager(r){this._sendToWorklet(BC.reloadSoundFont,r),await new Promise(l=>this.synth.resolveWhenReady=l)}};var QD="spessasynth-worklet-system",SB=450,ki=9,yD=16;var ah=class{constructor(r,l,g=!0,I=void 0,b=zQ){Y5("%cInitializing SpessaSynth synthesizer...",D1.info),this.context=r.context;let h0=I?.oneOutput===!0;this.eventHandler=new fm,this._voiceCap=SB,this._outputsAmount=yD,this.channelsAmount=this._outputsAmount,this.resolveWhenReady=void 0,this.isReady=new Promise(R0=>this.resolveWhenReady=R0),this.channelProperties=[];for(let R0=0;R0this.handleMessage(R0.data),this.soundfontManager=new Im(this),this._snapshotCallback=void 0,this.sequencerCallbackFunction=void 0,b.reverbEnabled&&!h0&&(this.reverbProcessor=VQ(this.context,b.reverbImpulseResponse),this.reverbProcessor.connect(r),this.worklet.connect(this.reverbProcessor,0)),b.chorusEnabled&&!h0&&(this.chorusProcessor=new um(r,b.chorusConfig),this.worklet.connect(this.chorusProcessor.input,1)),h0)this.worklet.connect(r,0);else for(let R0=2;R0{this.channelsAmount++})}get voiceCap(){return this._voiceCap}set voiceCap(r){this._setMasterParam(mC.voicesCap,r),this._voiceCap=r}set highPerformanceMode(r){this._highPerformanceMode=r}get highPerformanceMode(){return this._highPerformanceMode}setLogLevel(r,l,g,I){this.post({channelNumber:Hi,messageType:B8.setLogLevel,messageData:[r,l,g,I]})}_setMasterParam(r,l){this.post({channelNumber:Hi,messageType:B8.setMasterParameter,messageData:[r,l]})}setInterpolationType(r){this._setMasterParam(mC.interpolationType,r)}handleMessage(r){let l=r.messageData;switch(r.messageType){case u$.channelProperties:this.channelProperties=l,this._voicesAmount=this.channelProperties.reduce((g,I)=>g+I.voicesAmount,0);break;case u$.eventCall:this.eventHandler.callEvent(l.eventName,l.eventData);break;case u$.sequencerSpecific:this.sequencerCallbackFunction&&this.sequencerCallbackFunction(l.messageType,l.messageData);break;case u$.synthesizerSnapshot:this._snapshotCallback&&this._snapshotCallback(l);break;case u$.ready:this.resolveWhenReady();break;case u$.soundfontError:_4(new Error(l)),this.eventHandler.callEvent("soundfonterror",l);break}}async getSynthesizerSnapshot(){return new Promise(r=>{this._snapshotCallback=l=>{this._snapshotCallback=void 0,r(l)},this.post({messageType:B8.requestSynthesizerSnapshot,messageData:void 0,channelNumber:Hi})})}addNewChannel(r=!0){this.channelProperties.push({voicesAmount:0,pitchBend:0,pitchBendRangeSemitones:0,isMuted:!1,isDrum:!1}),r&&this.post({channelNumber:0,messageType:B8.addNewChannel,messageData:null})}setVibrato(r,l){this.post({channelNumber:r,messageType:B8.setChannelVibrato,messageData:l})}connectIndividualOutputs(r){if(r.length!==this._outputsAmount)throw new Error(`input nodes amount differs from the system's outputs amount! - Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case J3.noteOff:this.noteOff(l.channel,r[1]);break;case J3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case J3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case J3.programChange:this.programChange(l.channel,r[1]);break;case J3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case J3.channelPressure:this.channelPressure(l.channel,r[1]);break;case J3.systemExclusive:this.systemExclusive(new l6(r.slice(1)));break;case J3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}get currentTime(){return this.context.currentTime}get voicesAmount(){return this._voicesAmount}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,I)=>{let b;if(Bn)b=127;else{let b0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=I.clientX-b0.left,R0=b0.width;b=Math.floor((R0-p0)/R0*127)}else{let p0=I.clientY-b0.top,R0=b0.height;b=Math.floor(p0/R0*127)}}this.synth.noteOn(this.channel,g,b,this.enableDebugging)},l=g=>{let I=g.touches?Array.from(g.touches):[g],b=new Set;I.forEach(h0=>{let b0=document.elementFromPoint(h0.clientX,h0.clientY),p0=parseInt(b0.id.replace("note",""));b.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,h0))}),this.pressedKeys.forEach(h0=>{b.has(h0)||A(h0)})};Bn||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{A(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{A(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var WQ=20,pC=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,A6.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,A6.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let I=0;I<128;I++)this.releaseNote(I,g.channel)})}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get shown(){return this._shown}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(b=l(r-1)),r<127&&(h0=l(r+1)),h0&&b?g.classList.add("between_sharps"):b?g.classList.add("left_sharp"):h0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let I=900/(r.max-r.min+5),b=document.styleSheets[0].cssRules,h0;for(let b0 of b)if(b0.selectorText==="#keyboard .key"){h0=b0;break}if(h0.style.setProperty("--pressed-transform-skew",`${8e-4/(I/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let b0=getComputedStyle(this.keyboard),p0=parseFloat(b0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),R0=this.keyboard.getBoundingClientRect().height,E1=I/p0,M=R0*E1-R0,K0=(this._keyRange.min+this._keyRange.max)/2,_0=(r.min+r.max)/2;this._keyRange=r;let k1=this.keys.find(_5=>_5.classList.contains("sharp_key")).getBoundingClientRect().width,g2=(K0-_0)*k1,R1=parseFloat(b0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${M}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${E1}) translateX(${g2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${R1/E1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${I}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${I}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let I=this.keys[r-this._keyRange.min];if(I===void 0)return;I.classList.add("pressed");let b=I.classList.contains("sharp_key"),h0=g/127,b0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!b&&this.mode==="light"?p0=`rgba(${b0.slice(0,3).map(E1=>255-(255-E1)*h0).join(", ")}, ${b0[3]})`:p0=`rgba(${b0.slice(0,3).map(E1=>E1*h0).join(", ")}, ${b0[3]})`,I.style.background=p0,this.mode==="dark"){let R0=WQ*h0;I.style.boxShadow=`${p0} 0px 0px ${R0}px ${R0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let I=this.keyColors[r-this._keyRange.min];if(!I)return;let b=I.findLastIndex(h0=>h0===this.channelColors[l]);b!==-1&&(I.splice(b,1),g.style.background=I[I.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${WQ}px ${I[I.length-1]}`),I.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};pC.prototype._handlePointers=ZQ;function I$(A,r){let l=A.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var kD="#000";function jQ(A,r,l){A.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let I=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*I,l){r.fillRect(g.xPos,g.yPos-g.height*I,g.width,g.height*(I*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*I,g.yPos,g.width*(I*2+1),g.height),r.globalAlpha=1}),A.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=kD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var DB=!1;function XQ(A=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(DB){A&&requestAnimationFrame(this.render.bind(this));return}else DB=!0;else DB=!1;if(A&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let b=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||jQ(b,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let I=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${bB}px Verdana`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,bB+5),this.drawingContext.fillText(Math.round(I).toString()+" FPS",this.canvas.width,5),this.onRender&&this.onRender(),A&&requestAnimationFrame(this.render.bind(this))}function ey(A=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,I=r/(g+1),b=I-E$*2,h0=this.noteFallingTimeMs/1e3,b0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,R0=p0-b0,E1=h0+b0,M=R0+E1,K0=iy/E1,_0=[];this.synth.channelProperties.forEach(g2=>{if(this.showVisualPitch){let R1=g2.pitchBend-8192+this.visualPitchBendOffset;_0.push(g2.pitchBendRangeSemitones*(R1/8192*I))}else _0.push(0)});let k1=[];return this.noteTimes.forEach((g2,R1)=>{if(g2.renderStartIndex>=g2.notes.length||!this.renderChannels[R1])return;let _5=g2.renderStartIndex,v2=g2.notes,J2=v2[_5],n3=-1;for(;J2.start<=M&&(_5++,!(this.notesOnScreen>ry));){let U5=J2.start+J2.length;if(U5>R0&&J2.length>0){let a0=J2.length/E1*l-E$*2;if(this.notesOnScreen<1e3||a0>K0){n3===-1&&(n3=_5-1);let J5=(J2.start-R0)/E1*l,n6;if(this._notesFall?n6=l-a0-J5+E$:n6=J5+E$,J2.midiNotethis.keyRange.max){if(_5>=v2.length)break;J2=v2[_5];continue}let c6=J2.midiNote-this.keyRange.min,O6=I*c6+E$,g6,u4,Ke,J4;if(this.sideways?(g6=n6,u4=O6,J4=b,Ke=a0):(u4=n6,g6=O6,Ke=b,J4=a0),this.notesOnScreen++,A)this.drawingContext.fillStyle=this.plainColors[R1],this.drawingContext.fillRect(g6+d$+E$,u4+d$,Ke-d$*2,J4-d$*2);else{let p9;if(J2.start>p0||U5=v2.length)break;J2=v2[_5]}n3>-1&&(g2.renderStartIndex=n3)}),k1.sort((g2,R1)=>R1.height-g2.height),k1}function ny(){let A=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let I=g%4,b=Math.floor(g/4),h0=!1;for(let M=g;M0){h0=!0;break}if(!h0){let M=this.canvas.width/4,K0=this.canvas.height/4,_0=M*I,k1=K0*b+K0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(_0,k1),this.drawingContext.lineTo(_0+M,k1),this.drawingContext.stroke();return}let b0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(b0);let p0=A*I,R0=r*b+r/2,E1=this.waveMultiplier*r*this.waveSign;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let M=b0.length/4,K0=A/M,_0=Math.floor(M/2),k1=b0.length-_0;for(let v2=k1;v2>=1;v2--)if(b0[v2-1]<0&&b0[v2]>=0){k1=v2;break}let g2=p0,R1=k1-_0,_5=k1+_0;for(let v2=R1;v2<_5;v2++)this.drawingContext.lineTo(g2,R0+b0[v2]*E1),g2+=K0}else{let M=A/b0.length,K0=p0;for(let _0=0;_0{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function oy(){for(let A=0;A{this.updateFftSize()})}function $y(){for(let A of this.channelAnalysers)A.disconnect();Y5("%cAnalysers disconnected!",D1.recognized)}function ly(A){this.seq=A,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),I=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${I}), rgba(0, 0, 0, ${I})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function cy(){this.noteTimes&&this.noteTimes.forEach(A=>A.renderStartIndex=0)}function _B(A,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=A[A.currentIndex++]<>>0}function QC(A,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=A&255,A>>=8;return l}var $h=.02;function gy(A){function r(R0){return R0.messageData=new l6(R0.messageData.buffer),R0.messageData.currentIndex=0,6e7/_B(R0.messageData,3)}let l=[],I=A.tracks.flat();I.sort((R0,E1)=>R0.ticks-E1.ticks);for(let R0=0;R0<16;R0++)l.push({renderStartIndex:0,notes:[]});let b=0,h0=60/(120*A.timeDivision),b0=0,p0=0;for(;b0>4,M=R0.messageStatusByte&15;if(E1===8){let K0=l[M].notes.findLast(_0=>_0.midiNote===R0.messageData[0]&&_0.length===-1);if(K0){let _0=b-K0.start;K0.length=_0<$h&&M===ki?$h:_0}p0--}else if(E1===9)if(R0.messageData[1]===0){let K0=l[M].notes.findLast(_0=>_0.midiNote===R0.messageData[0]&&_0.length===-1);if(K0){let _0=b-K0.start;K0.length=_0<$h&&M===ki?$h:_0}p0--}else l[R0.messageStatusByte&15].notes.push({midiNote:R0.messageData[0],start:b,length:-1,velocity:R0.messageData[1]/127}),p0++;else R0.messageStatusByte===81&&(h0=60/(r(R0)*A.timeDivision));if(++b0>=I.length)break;b+=h0*(I[b0].ticks-R0.ticks)}p0>0&&l.forEach((R0,E1)=>R0.notes.filter(M=>M.length===-1).forEach(M=>{let K0=b-M.start;M.length=K0<$h&&E1===ki?$h:K0})),this.noteTimes=l,Y5("%cFinished loading note times and ready to render the sequence!",D1.info)}var vD=1024,SD=4096,DD=2,bD=2,dm=.6,Em=.5,d$=1,E$=1,bB=16,ty=.6,iy=2,ry=81572,vi=class{constructor(r,l,g,I){this.noteFallingTimeMs=1e3,this.noteAfterTriggerTimeMs=0,this._keyRange={min:0,max:127},this.visualPitchBendOffset=0,this.lineThickness=bD,this._normalAnalyserFft=vD,this._drumAnalyserFft=SD,this.waveMultiplier=DD,this.waveSign=1,this._notesFall=!0,this.sideways=!1,this._renderBool=!0,this.renderAnalysers=!0,this.renderNotes=!0,this.drawActiveNotes=!0,this.showVisualPitch=!0,this._stabilizeWaveforms=!0,this.renderChannels=Array(16).fill(!0),this.canvas=g,this.drawingContext=this.canvas.getContext("2d"),this.plainColors=r,this.computeColors(),this.synth=l,this.delayNode=I,this.notesOnScreen=0,this.channelAnalysers=[],this.createChannelAnalysers(l),this.connectChannelAnalysers(l)}get stabilizeWaveforms(){return this._stabilizeWaveforms}set stabilizeWaveforms(r){this._stabilizeWaveforms=r,this.updateFftSize()}set direction(r){this._notesFall=r==="down"}get direction(){return this._notesFall?"down":"up"}computeColors(){this.channelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,I$(r,g=>g*Em)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,I$(r,g=>g*Em*dm)),l.addColorStop(1,I$(r,g=>g*dm)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,I$(r,g=>g*Em)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,I$(r,g=>g*Em*dm)),l.addColorStop(1,I$(r,g=>g*dm)),l})}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}onRender;get normalAnalyserFft(){return this._normalAnalyserFft}set normalAnalyserFft(r){this._normalAnalyserFft=r,this.updateFftSize()}get drumAnalyserFft(){return this._drumAnalyserFft}set drumAnalyserFft(r){this._drumAnalyserFft=r,this.updateFftSize()}get renderBool(){return this._renderBool}set renderBool(r){this._renderBool=r,r===!0?this.connectChannelAnalysers(this.synth):this.disconnectChannelAnalysers()}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}};vi.prototype.render=XQ;vi.prototype.computeNotePositions=ey;vi.prototype.createChannelAnalysers=Ay;vi.prototype.updateFftSize=oy;vi.prototype.connectChannelAnalysers=ay;vi.prototype.disconnectChannelAnalysers=$y;vi.prototype.connectSequencer=ly;vi.prototype.calculateNoteTimes=gy;vi.prototype.resetIndexes=cy;vi.prototype.renderWaveforms=ny;function r3(A,r){let l=0;for(let g=0;g>>0}function C$(A,r,l){for(let g=0;g>g*8&255}function B9(A,r){A[A.currentIndex++]=r&255,A[A.currentIndex++]=r>>8}function at(A,r){C$(A,r,4)}function lh(A,r){let l=r<<8|A;return l>32767?l-65536:l}function hy(A){return A>127?A-256:A}function Fe(A,r,l=void 0,g=!0){if(l){let I=A.slice(A.currentIndex,A.currentIndex+r);return A.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(I.buffer)}else{let I=!1,b="";for(let h0=0;h0127){if(g){I=!0;continue}else if(b0===0){I=!0;continue}}b+=String.fromCharCode(b0)}}return b}}function So(A,r=0){let l=A.length;r>0&&(l=r);let g=new l6(l);return Ii(g,A,r),g}function Ii(A,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,Fe(l.chunkData,4)===r))}function Cm(A){let r=[A&127];for(A>>=7;A>0;)r.unshift(A&127|128),A>>=7;return r}function mm(A){let r=[];for(let I of A.tracks){let b=[],h0=0,b0;for(let p0 of I){let R0=p0.ticks-h0,E1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?E1=[255,p0.messageStatusByte,...Cm(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?E1=[240,...Cm(p0.messageData.length),...p0.messageData]:(E1=[],b0!==p0.messageStatusByte&&(b0=p0.messageStatusByte,E1.push(p0.messageStatusByte)),E1.push(...p0.messageData)),b.push(...Cm(R0)),b.push(...E1),h0+=R0}r.push(new Uint8Array(b))}function l(I,b){for(let h0=0;h0A.chunkData.currentIndex;)r.push(new RB(A.chunkData));return r.length>1&&r.pop(),r}var x7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Qn={linear:0,concave:1,convex:2,switch:3},_D=[];for(let A=0;A<4;A++)_D.push([[],[]]);var o7=class A{constructor(r){r.srcEnum?(this.modulatorSource=r.srcEnum,this.modulatorDestination=r.dest,this.modulationSecondarySrc=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.modulatorSource=r3(r,2),this.modulatorDestination=r3(r,2),this.transformAmount=lh(r[r.currentIndex++],r[r.currentIndex++]),this.modulationSecondarySrc=r3(r,2),this.transformType=r3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=b1.INVALID),this.sourcePolarity=this.modulatorSource>>9&1,this.sourceDirection=this.modulatorSource>>8&1,this.sourceUsesCC=this.modulatorSource>>7&1,this.sourceIndex=this.modulatorSource&127,this.sourceCurveType=this.modulatorSource>>10&3,this.secSrcPolarity=this.modulationSecondarySrc>>9&1,this.secSrcDirection=this.modulationSecondarySrc>>8&1,this.secSrcUsesCC=this.modulationSecondarySrc>>7&1,this.secSrcIndex=this.modulationSecondarySrc&127,this.secSrcCurveType=this.modulationSecondarySrc>>10&3}sumTransform(r){return new A({srcEnum:this.modulatorSource,secSrcEnum:this.modulationSecondarySrc,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(I,b){return Object.keys(I).find(h0=>I[h0]===b)}let l=r(Qn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(A6,this.sourceIndex):l+=r(x7,this.sourceIndex);let g=r(Qn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(A6,this.secSrcIndex):g+=r(x7,this.secSrcIndex),`Modulator: + Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case J3.noteOff:this.noteOff(l.channel,r[1]);break;case J3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case J3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case J3.programChange:this.programChange(l.channel,r[1]);break;case J3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case J3.channelPressure:this.channelPressure(l.channel,r[1]);break;case J3.systemExclusive:this.systemExclusive(new l6(r.slice(1)));break;case J3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}get currentTime(){return this.context.currentTime}get voicesAmount(){return this._voicesAmount}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,I)=>{let b;if(Bn)b=127;else{let b0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=I.clientX-b0.left,R0=b0.width;b=Math.floor((R0-p0)/R0*127)}else{let p0=I.clientY-b0.top,R0=b0.height;b=Math.floor(p0/R0*127)}}this.synth.noteOn(this.channel,g,b,this.enableDebugging)},l=g=>{let I=g.touches?Array.from(g.touches):[g],b=new Set;I.forEach(h0=>{let b0=document.elementFromPoint(h0.clientX,h0.clientY),p0=parseInt(b0.id.replace("note",""));b.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,h0))}),this.pressedKeys.forEach(h0=>{b.has(h0)||A(h0)})};Bn||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{A(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{A(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var WQ=20,pC=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,A6.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,A6.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let I=0;I<128;I++)this.releaseNote(I,g.channel)})}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get shown(){return this._shown}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(b=l(r-1)),r<127&&(h0=l(r+1)),h0&&b?g.classList.add("between_sharps"):b?g.classList.add("left_sharp"):h0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let I=900/(r.max-r.min+5),b=document.styleSheets[0].cssRules,h0;for(let b0 of b)if(b0.selectorText==="#keyboard .key"){h0=b0;break}if(h0.style.setProperty("--pressed-transform-skew",`${8e-4/(I/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let b0=getComputedStyle(this.keyboard),p0=parseFloat(b0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),R0=this.keyboard.getBoundingClientRect().height,E1=I/p0,M=R0*E1-R0,K0=(this._keyRange.min+this._keyRange.max)/2,_0=(r.min+r.max)/2;this._keyRange=r;let k1=this.keys.find(_5=>_5.classList.contains("sharp_key")).getBoundingClientRect().width,g2=(K0-_0)*k1,R1=parseFloat(b0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${M}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${E1}) translateX(${g2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${R1/E1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${I}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${I}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let I=this.keys[r-this._keyRange.min];if(I===void 0)return;I.classList.add("pressed");let b=I.classList.contains("sharp_key"),h0=g/127,b0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!b&&this.mode==="light"?p0=`rgba(${b0.slice(0,3).map(E1=>255-(255-E1)*h0).join(", ")}, ${b0[3]})`:p0=`rgba(${b0.slice(0,3).map(E1=>E1*h0).join(", ")}, ${b0[3]})`,I.style.background=p0,this.mode==="dark"){let R0=WQ*h0;I.style.boxShadow=`${p0} 0px 0px ${R0}px ${R0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let I=this.keyColors[r-this._keyRange.min];if(!I)return;let b=I.findLastIndex(h0=>h0===this.channelColors[l]);b!==-1&&(I.splice(b,1),g.style.background=I[I.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${WQ}px ${I[I.length-1]}`),I.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};pC.prototype._handlePointers=ZQ;function I$(A,r){let l=A.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var kD="#000";function jQ(A,r,l){A.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let I=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*I,l){r.fillRect(g.xPos,g.yPos-g.height*I,g.width,g.height*(I*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*I,g.yPos,g.width*(I*2+1),g.height),r.globalAlpha=1}),A.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=kD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var DB=!1;function XQ(A=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(DB){A&&requestAnimationFrame(this.render.bind(this));return}else DB=!0;else DB=!1;if(A&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let b=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||jQ(b,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let I=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${bB}px Verdana`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,bB+5),this.drawingContext.fillText(Math.round(I).toString()+" FPS",this.canvas.width,5),this.onRender&&this.onRender(),A&&requestAnimationFrame(this.render.bind(this))}function ey(A=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,I=r/(g+1),b=I-E$*2,h0=this.noteFallingTimeMs/1e3,b0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,R0=p0-b0,E1=h0+b0,M=R0+E1,K0=iy/E1,_0=[];this.synth.channelProperties.forEach(g2=>{if(this.showVisualPitch){let R1=g2.pitchBend-8192+this.visualPitchBendOffset;_0.push(g2.pitchBendRangeSemitones*(R1/8192*I))}else _0.push(0)});let k1=[];return this.noteTimes.forEach((g2,R1)=>{if(g2.renderStartIndex>=g2.notes.length||!this.renderChannels[R1])return;let _5=g2.renderStartIndex,v2=g2.notes,J2=v2[_5],n3=-1;for(;J2.start<=M&&(_5++,!(this.notesOnScreen>ry));){let U5=J2.start+J2.length;if(U5>R0&&J2.length>0){let a0=J2.length/E1*l-E$*2;if(this.notesOnScreen<1e3||a0>K0){n3===-1&&(n3=_5-1);let J5=(J2.start-R0)/E1*l,n6;if(this._notesFall?n6=l-a0-J5+E$:n6=J5+E$,J2.midiNotethis.keyRange.max){if(_5>=v2.length)break;J2=v2[_5];continue}let c6=J2.midiNote-this.keyRange.min,O6=I*c6+E$,g6,u4,Ke,J4;if(this.sideways?(g6=n6,u4=O6,J4=b,Ke=a0):(u4=n6,g6=O6,Ke=b,J4=a0),this.notesOnScreen++,A)this.drawingContext.fillStyle=this.plainColors[R1],this.drawingContext.fillRect(g6+d$+E$,u4+d$,Ke-d$*2,J4-d$*2);else{let p9;if(J2.start>p0||U5=v2.length)break;J2=v2[_5]}n3>-1&&(g2.renderStartIndex=n3)}),k1.sort((g2,R1)=>R1.height-g2.height),k1}function ny(){let A=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let I=g%4,b=Math.floor(g/4),h0=!1;for(let M=g;M0){h0=!0;break}if(!h0){let M=this.canvas.width/4,K0=this.canvas.height/4,_0=M*I,k1=K0*b+K0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(_0,k1),this.drawingContext.lineTo(_0+M,k1),this.drawingContext.stroke();return}let b0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(b0);let p0=A*I,R0=r*b+r/2,E1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let M=b0.length/4,K0=A/M,_0=Math.floor(M/2),k1=b0.length-_0;for(let v2=k1;v2>=1;v2--)if(b0[v2-1]<0&&b0[v2]>=0){k1=v2;break}let g2=p0,R1=k1-_0,_5=k1+_0;for(let v2=R1;v2<_5;v2++)this.drawingContext.lineTo(g2,R0+b0[v2]*E1),g2+=K0}else{let M=A/b0.length,K0=p0;for(let _0=0;_0{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function oy(){for(let A=0;A{this.updateFftSize()})}function $y(){for(let A of this.channelAnalysers)A.disconnect();Y5("%cAnalysers disconnected!",D1.recognized)}function ly(A){this.seq=A,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),I=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${I}), rgba(0, 0, 0, ${I})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function cy(){this.noteTimes&&this.noteTimes.forEach(A=>A.renderStartIndex=0)}function _B(A,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=A[A.currentIndex++]<>>0}function QC(A,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=A&255,A>>=8;return l}var $h=.02;function gy(A){function r(R0){return R0.messageData=new l6(R0.messageData.buffer),R0.messageData.currentIndex=0,6e7/_B(R0.messageData,3)}let l=[],I=A.tracks.flat();I.sort((R0,E1)=>R0.ticks-E1.ticks);for(let R0=0;R0<16;R0++)l.push({renderStartIndex:0,notes:[]});let b=0,h0=60/(120*A.timeDivision),b0=0,p0=0;for(;b0>4,M=R0.messageStatusByte&15;if(E1===8){let K0=l[M].notes.findLast(_0=>_0.midiNote===R0.messageData[0]&&_0.length===-1);if(K0){let _0=b-K0.start;K0.length=_0<$h&&M===ki?$h:_0}p0--}else if(E1===9)if(R0.messageData[1]===0){let K0=l[M].notes.findLast(_0=>_0.midiNote===R0.messageData[0]&&_0.length===-1);if(K0){let _0=b-K0.start;K0.length=_0<$h&&M===ki?$h:_0}p0--}else l[R0.messageStatusByte&15].notes.push({midiNote:R0.messageData[0],start:b,length:-1,velocity:R0.messageData[1]/127}),p0++;else R0.messageStatusByte===81&&(h0=60/(r(R0)*A.timeDivision));if(++b0>=I.length)break;b+=h0*(I[b0].ticks-R0.ticks)}p0>0&&l.forEach((R0,E1)=>R0.notes.filter(M=>M.length===-1).forEach(M=>{let K0=b-M.start;M.length=K0<$h&&E1===ki?$h:K0})),this.noteTimes=l,Y5("%cFinished loading note times and ready to render the sequence!",D1.info)}var vD=1024,SD=4096,DD=2,bD=2,dm=.6,Em=.5,d$=1,E$=1,bB=16,ty=.6,iy=2,ry=81572,vi=class{constructor(r,l,g,I){this.noteFallingTimeMs=1e3,this.noteAfterTriggerTimeMs=0,this._keyRange={min:0,max:127},this.visualPitchBendOffset=0,this.lineThickness=bD,this._normalAnalyserFft=vD,this._drumAnalyserFft=SD,this.waveMultiplier=DD,this._notesFall=!0,this.sideways=!1,this._renderBool=!0,this.renderAnalysers=!0,this.renderNotes=!0,this.drawActiveNotes=!0,this.showVisualPitch=!0,this._stabilizeWaveforms=!0,this.renderChannels=Array(16).fill(!0),this.canvas=g,this.drawingContext=this.canvas.getContext("2d"),this.plainColors=r,this.computeColors(),this.synth=l,this.delayNode=I,this.notesOnScreen=0,this.channelAnalysers=[],this.createChannelAnalysers(l),this.connectChannelAnalysers(l)}get stabilizeWaveforms(){return this._stabilizeWaveforms}set stabilizeWaveforms(r){this._stabilizeWaveforms=r,this.updateFftSize()}set direction(r){this._notesFall=r==="down"}get direction(){return this._notesFall?"down":"up"}computeColors(){this.channelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,I$(r,g=>g*Em)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,I$(r,g=>g*Em*dm)),l.addColorStop(1,I$(r,g=>g*dm)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,I$(r,g=>g*Em)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,I$(r,g=>g*Em*dm)),l.addColorStop(1,I$(r,g=>g*dm)),l})}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}onRender;get normalAnalyserFft(){return this._normalAnalyserFft}set normalAnalyserFft(r){this._normalAnalyserFft=r,this.updateFftSize()}get drumAnalyserFft(){return this._drumAnalyserFft}set drumAnalyserFft(r){this._drumAnalyserFft=r,this.updateFftSize()}get renderBool(){return this._renderBool}set renderBool(r){this._renderBool=r,r===!0?this.connectChannelAnalysers(this.synth):this.disconnectChannelAnalysers()}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}};vi.prototype.render=XQ;vi.prototype.computeNotePositions=ey;vi.prototype.createChannelAnalysers=Ay;vi.prototype.updateFftSize=oy;vi.prototype.connectChannelAnalysers=ay;vi.prototype.disconnectChannelAnalysers=$y;vi.prototype.connectSequencer=ly;vi.prototype.calculateNoteTimes=gy;vi.prototype.resetIndexes=cy;vi.prototype.renderWaveforms=ny;function r3(A,r){let l=0;for(let g=0;g>>0}function C$(A,r,l){for(let g=0;g>g*8&255}function B9(A,r){A[A.currentIndex++]=r&255,A[A.currentIndex++]=r>>8}function at(A,r){C$(A,r,4)}function lh(A,r){let l=r<<8|A;return l>32767?l-65536:l}function hy(A){return A>127?A-256:A}function Fe(A,r,l=void 0,g=!0){if(l){let I=A.slice(A.currentIndex,A.currentIndex+r);return A.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(I.buffer)}else{let I=!1,b="";for(let h0=0;h0127){if(g){I=!0;continue}else if(b0===0){I=!0;continue}}b+=String.fromCharCode(b0)}}return b}}function So(A,r=0){let l=A.length;r>0&&(l=r);let g=new l6(l);return Ii(g,A,r),g}function Ii(A,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,Fe(l.chunkData,4)===r))}function Cm(A){let r=[A&127];for(A>>=7;A>0;)r.unshift(A&127|128),A>>=7;return r}function mm(A){let r=[];for(let I of A.tracks){let b=[],h0=0,b0;for(let p0 of I){let R0=p0.ticks-h0,E1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?E1=[255,p0.messageStatusByte,...Cm(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?E1=[240,...Cm(p0.messageData.length),...p0.messageData]:(E1=[],b0!==p0.messageStatusByte&&(b0=p0.messageStatusByte,E1.push(p0.messageStatusByte)),E1.push(...p0.messageData)),b.push(...Cm(R0)),b.push(...E1),h0+=R0}r.push(new Uint8Array(b))}function l(I,b){for(let h0=0;h0A.chunkData.currentIndex;)r.push(new RB(A.chunkData));return r.length>1&&r.pop(),r}var x7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Qn={linear:0,concave:1,convex:2,switch:3},_D=[];for(let A=0;A<4;A++)_D.push([[],[]]);var o7=class A{constructor(r){r.srcEnum?(this.modulatorSource=r.srcEnum,this.modulatorDestination=r.dest,this.modulationSecondarySrc=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.modulatorSource=r3(r,2),this.modulatorDestination=r3(r,2),this.transformAmount=lh(r[r.currentIndex++],r[r.currentIndex++]),this.modulationSecondarySrc=r3(r,2),this.transformType=r3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=b1.INVALID),this.sourcePolarity=this.modulatorSource>>9&1,this.sourceDirection=this.modulatorSource>>8&1,this.sourceUsesCC=this.modulatorSource>>7&1,this.sourceIndex=this.modulatorSource&127,this.sourceCurveType=this.modulatorSource>>10&3,this.secSrcPolarity=this.modulationSecondarySrc>>9&1,this.secSrcDirection=this.modulationSecondarySrc>>8&1,this.secSrcUsesCC=this.modulationSecondarySrc>>7&1,this.secSrcIndex=this.modulationSecondarySrc&127,this.secSrcCurveType=this.modulationSecondarySrc>>10&3}sumTransform(r){return new A({srcEnum:this.modulatorSource,secSrcEnum:this.modulationSecondarySrc,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(I,b){return Object.keys(I).find(h0=>I[h0]===b)}let l=r(Qn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(A6,this.sourceIndex):l+=r(x7,this.sourceIndex);let g=r(Qn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(A6,this.secSrcIndex):g+=r(x7,this.secSrcIndex),`Modulator: Source: ${l} Secondary source: ${g} Destination: ${r(b1,this.modulatorDestination)} @@ -89,7 +89,7 @@ var hm=(A=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(A,{get:(r,l)=>( - +
diff --git a/src/website/minified/local_main.min.js b/src/website/minified/local_main.min.js index 0057c070..1c271c06 100644 --- a/src/website/minified/local_main.min.js +++ b/src/website/minified/local_main.min.js @@ -1,5 +1,5 @@ var am=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(r,l)=>(typeof require<"u"?require:r)[l]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var l6=class extends Uint8Array{constructor(r){super(r),this.currentIndex=0}currentIndex};function DA(o){let r=o.reduce((E,x)=>E+x.length,0),l=new l6(r),g=0;for(let E of o)l.set(E,g),g+=E.length;return l}function h$(o){o=Math.floor(o);let r=Math.floor(o/60),l=Math.round(o-r*60);return{minutes:r,seconds:l,time:`${r.toString().padStart(2,"0")}:${l.toString().padStart(2,"0")}`}}function CB(o){return o.trim().replaceAll(".mid","").replaceAll(".rmi","").replaceAll("_"," ")}var D1={warn:"color: orange;",unrecognized:"color: red;",info:"color: aqua;",recognized:"color: lime",value:"color: yellow; background-color: black;"};var fi=class{constructor(r,l,g){this.ticks=r,this.messageStatusByte=l,this.messageData=g}};var J3={noteOff:128,noteOn:144,polyPressure:160,controllerChange:176,programChange:192,channelPressure:208,pitchBend:224,systemExclusive:240,timecode:241,songPosition:242,songSelect:243,tuneRequest:246,clock:248,start:250,continue:251,stop:252,activeSensing:254,reset:255,sequenceNumber:0,text:1,copyright:2,trackName:3,instrumentName:4,lyric:5,marker:6,cuePoint:7,midiChannelPrefix:32,midiPort:33,endOfTrack:47,setTempo:81,smpteOffset:84,timeSignature:88,keySignature:89,sequenceSpecific:127};function UQ(o){let r=o&240,l=o&15,g=-1,E=o;return r>=128&&r<=224&&(g=l,E=r),{status:E,channel:g}}var s6={bankSelect:0,modulationWheel:1,breathController:2,footController:4,portamentoTime:5,dataEntryMsb:6,mainVolume:7,balance:8,pan:10,expressionController:11,effectControl1:12,effectControl2:13,generalPurposeController1:16,generalPurposeController2:17,generalPurposeController3:18,generalPurposeController4:19,lsbForControl0BankSelect:32,lsbForControl1ModulationWheel:33,lsbForControl2BreathController:34,lsbForControl4FootController:36,lsbForControl5PortamentoTime:37,lsbForControl6DataEntry:38,lsbForControl7MainVolume:39,lsbForControl8Balance:40,lsbForControl10Pan:42,lsbForControl11ExpressionController:43,lsbForControl12EffectControl1:44,lsbForControl13EffectControl2:45,sustainPedal:64,portamentoOnOff:65,sostenutoPedal:66,softPedal:67,legatoFootswitch:68,hold2Pedal:69,soundVariation:70,timbreHarmonicContent:71,releaseTime:72,attackTime:73,brightness:74,soundController6:75,soundController7:76,soundController8:77,soundController9:78,soundController10:79,generalPurposeController5:80,generalPurposeController6:81,generalPurposeController7:82,generalPurposeController8:83,portamentoControl:84,effects1Depth:91,effects2Depth:92,effects3Depth:93,effects4Depth:94,effects5Depth:95,dataIncrement:96,dataDecrement:97,NRPNLsb:98,NRPNMsb:99,RPNLsb:100,RPNMsb:101,allSoundOff:120,resetAllControllers:121,localControlOnOff:122,allNotesOff:123,omniModeOff:124,omniModeOn:125,monoModeOn:126,polyModeOn:127};var $m=class{constructor(){this.events={noteoff:{},noteon:{},pitchwheel:{},controllerchange:{},programchange:{},channelpressure:{},polypressure:{},drumchange:{},stopall:{},newchannel:{},mutechannel:{},presetlistchange:{},allcontrollerreset:{},soundfonterror:{}}}addEvent(r,l,g){this.events[r][l]=g}removeEvent(r,l){delete this.events[r][l]}callEvent(r,l){this.events[r]&&Object.values(this.events[r]).forEach(g=>g(l))}};var mB={nodesAmount:4,defaultDelay:.03,delayVariation:.01,stereoDifference:.02,oscillatorFrequency:.3,oscillatorFrequencyVariation:.05,oscillatorGain:.003},lm=class{constructor(r,l=mB){let g=r.context;this.input=new ChannelSplitterNode(g,{numberOfOutputs:2});let E=new ChannelMergerNode(g,{numberOfInputs:2}),x=[],u0=[],R0=l.oscillatorFrequency,p0=l.defaultDelay;for(let D0=0;D0{let x=await E.arrayBuffer();l.buffer=await o.decodeAudioData(x)})}return l}var B8={noteOff:0,noteOn:1,ccChange:2,programChange:3,channelPressure:4,polyPressure:5,killNote:6,ccReset:7,setChannelVibrato:8,soundFontManager:9,stopAll:10,killNotes:11,muteChannel:12,addNewChannel:13,customcCcChange:14,debugMessage:15,systemExclusive:16,setMasterParameter:17,setDrums:18,pitchWheel:19,transpose:20,highPerformanceMode:21,lockController:22,sequencerSpecific:23,requestSynthesizerSnapshot:24,setLogLevel:25},dC={mainVolume:0,masterPan:1,voicesCap:2,interpolationType:3},Pi=-1,f$={channelProperties:0,eventCall:1,reportedCurrentTime:2,sequencerSpecific:3,synthesizerSnapshot:4,ready:5,soundfontError:6,identify:7};var fD=!0,uD=!0,BB=!0;function j5(...o){fD&&console.info(...o)}function fe(...o){uD&&console.warn(...o)}function or(...o){BB&&console.group(...o)}function Xt(...o){BB&&console.groupCollapsed(...o)}function t4(){BB&&console.groupEnd()}var PQ={chorusEnabled:!0,chorusConfig:mB,reverbEnabled:!0,reverbImpulseResponse:void 0};var EC={reloadSoundFont:0,addNewSoundFont:2,deleteSoundFont:3,rearrangeSoundFonts:4};var cm=class{constructor(r){this.soundfontList=[{id:"main",bankOffset:0}],this._port=r.worklet.port,this.synth=r}_sendToWorklet(r,l){this._port.postMessage({messageType:B8.soundFontManager,messageData:[r,l]})}async addNewSoundFont(r,l,g=0){if(this.soundfontList.find(E=>E.id===l)!==void 0)throw new Error("Cannot overwrite the existing soundfont. Use soundfontManager.delete(id) instead.");this._sendToWorklet(EC.addNewSoundFont,[r,l,g]),await new Promise(E=>this.synth.resolveWhenReady=E),this.soundfontList.push({id:l,bankOffset:g})}deleteSoundFont(r){if(this.soundfontList.length===0){fe("1 soundfont left. Aborting!");return}if(this.soundfontList.findIndex(l=>l.id===r)===-1){fe(`No soundfont with id of "${r}" found. Aborting!`);return}this._sendToWorklet(EC.deleteSoundFont,r)}rearrangeSoundFonts(r){this._sendToWorklet(EC.rearrangeSoundFonts,r),this.soundfontList.sort((l,g)=>r.indexOf(l.id)-r.indexOf(g.id))}async reloadManager(r){this._sendToWorklet(EC.reloadSoundFont,r),await new Promise(l=>this.synth.resolveWhenReady=l)}};var ID="spessasynth-worklet-system",pB=450,ki=9,dD=16;var Ah=class{constructor(r,l,g=!0,E=void 0,x=PQ){j5("%cInitializing SpessaSynth synthesizer...",D1.info),this.context=r.context;let u0=E?.oneOutput===!0;this.eventHandler=new $m,this._voiceCap=pB,this._outputsAmount=dD,this.channelsAmount=this._outputsAmount,this.resolveWhenReady=void 0,this.isReady=new Promise(D0=>this.resolveWhenReady=D0),this.channelProperties=[];for(let D0=0;D0this.handleMessage(D0.data),this.soundfontManager=new cm(this),this._snapshotCallback=void 0,this.sequencerCallbackFunction=void 0,x.reverbEnabled&&!u0&&(this.reverbProcessor=OQ(this.context,x.reverbImpulseResponse),this.reverbProcessor.connect(r),this.worklet.connect(this.reverbProcessor,0)),x.chorusEnabled&&!u0&&(this.chorusProcessor=new lm(r,x.chorusConfig),this.worklet.connect(this.chorusProcessor.input,1)),u0)this.worklet.connect(r,0);else for(let D0=2;D0{this.channelsAmount++})}get voiceCap(){return this._voiceCap}set voiceCap(r){this._setMasterParam(dC.voicesCap,r),this._voiceCap=r}set highPerformanceMode(r){this._highPerformanceMode=r}get highPerformanceMode(){return this._highPerformanceMode}setLogLevel(r,l,g,E){this.post({channelNumber:Pi,messageType:B8.setLogLevel,messageData:[r,l,g,E]})}_setMasterParam(r,l){this.post({channelNumber:Pi,messageType:B8.setMasterParameter,messageData:[r,l]})}setInterpolationType(r){this._setMasterParam(dC.interpolationType,r)}handleMessage(r){let l=r.messageData;switch(r.messageType){case f$.channelProperties:this.channelProperties=l,this._voicesAmount=this.channelProperties.reduce((g,E)=>g+E.voicesAmount,0);break;case f$.eventCall:this.eventHandler.callEvent(l.eventName,l.eventData);break;case f$.sequencerSpecific:this.sequencerCallbackFunction&&this.sequencerCallbackFunction(l.messageType,l.messageData);break;case f$.synthesizerSnapshot:this._snapshotCallback&&this._snapshotCallback(l);break;case f$.ready:this.resolveWhenReady();break;case f$.soundfontError:fe(new Error(l)),this.eventHandler.callEvent("soundfonterror",l);break}}async getSynthesizerSnapshot(){return new Promise(r=>{this._snapshotCallback=l=>{this._snapshotCallback=void 0,r(l)},this.post({messageType:B8.requestSynthesizerSnapshot,messageData:void 0,channelNumber:Pi})})}addNewChannel(r=!0){this.channelProperties.push({voicesAmount:0,pitchBend:0,pitchBendRangeSemitones:0,isMuted:!1,isDrum:!1}),r&&this.post({channelNumber:0,messageType:B8.addNewChannel,messageData:null})}setVibrato(r,l){this.post({channelNumber:r,messageType:B8.setChannelVibrato,messageData:l})}connectIndividualOutputs(r){if(r.length!==this._outputsAmount)throw new Error(`input nodes amount differs from the system's outputs amount! - Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case J3.noteOff:this.noteOff(l.channel,r[1]);break;case J3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case J3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case J3.programChange:this.programChange(l.channel,r[1]);break;case J3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case J3.channelPressure:this.channelPressure(l.channel,r[1]);break;case J3.systemExclusive:this.systemExclusive(new l6(r.slice(1)));break;case J3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}get currentTime(){return this.context.currentTime}get voicesAmount(){return this._voicesAmount}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,E)=>{let x;if(vo)x=127;else{let R0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=E.clientX-R0.left,D0=R0.width;x=Math.floor((D0-p0)/D0*127)}else{let p0=E.clientY-R0.top,D0=R0.height;x=Math.floor(p0/D0*127)}}this.synth.noteOn(this.channel,g,x,this.enableDebugging)},l=g=>{let E=g.touches?Array.from(g.touches):[g],x=new Set;E.forEach(u0=>{let R0=document.elementFromPoint(u0.clientX,u0.clientY),p0=parseInt(R0.id.replace("note",""));x.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,u0))}),this.pressedKeys.forEach(u0=>{x.has(u0)||o(u0)})};vo||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var qQ=20,CC=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,s6.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,s6.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let E=0;E<128;E++)this.releaseNote(E,g.channel)})}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get shown(){return this._shown}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(x=l(r-1)),r<127&&(u0=l(r+1)),u0&&x?g.classList.add("between_sharps"):x?g.classList.add("left_sharp"):u0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let E=900/(r.max-r.min+5),x=document.styleSheets[0].cssRules,u0;for(let R0 of x)if(R0.selectorText==="#keyboard .key"){u0=R0;break}if(u0.style.setProperty("--pressed-transform-skew",`${8e-4/(E/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let R0=getComputedStyle(this.keyboard),p0=parseFloat(R0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),D0=this.keyboard.getBoundingClientRect().height,E1=E/p0,M=D0*E1-D0,K0=(this._keyRange.min+this._keyRange.max)/2,_0=(r.min+r.max)/2;this._keyRange=r;let k1=this.keys.find(_5=>_5.classList.contains("sharp_key")).getBoundingClientRect().width,g2=(K0-_0)*k1,R1=parseFloat(R0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${M}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${E1}) translateX(${g2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${R1/E1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${E}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${E}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let E=this.keys[r-this._keyRange.min];if(E===void 0)return;E.classList.add("pressed");let x=E.classList.contains("sharp_key"),u0=g/127,R0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!x&&this.mode==="light"?p0=`rgba(${R0.slice(0,3).map(E1=>255-(255-E1)*u0).join(", ")}, ${R0[3]})`:p0=`rgba(${R0.slice(0,3).map(E1=>E1*u0).join(", ")}, ${R0[3]})`,E.style.background=p0,this.mode==="dark"){let D0=qQ*u0;E.style.boxShadow=`${p0} 0px 0px ${D0}px ${D0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let E=this.keyColors[r-this._keyRange.min];if(!E)return;let x=E.findLastIndex(u0=>u0===this.channelColors[l]);x!==-1&&(E.splice(x,1),g.style.background=E[E.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${qQ}px ${E[E.length-1]}`),E.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};CC.prototype._handlePointers=HQ;function u$(o,r){let l=o.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var CD="#000";function YQ(o,r,l){o.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let E=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*E,l){r.fillRect(g.xPos,g.yPos-g.height*E,g.width,g.height*(E*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*E,g.yPos,g.width*(E*2+1),g.height),r.globalAlpha=1}),o.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=CD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var QB=!1;function JQ(o=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(QB){o&&requestAnimationFrame(this.render.bind(this));return}else QB=!0;else QB=!1;if(o&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let x=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||YQ(x,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let E=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${yB}px Verdana`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,yB+5),this.drawingContext.fillText(Math.round(E).toString()+" FPS",this.canvas.width,5),this.onRender&&this.onRender(),o&&requestAnimationFrame(this.render.bind(this))}function KQ(o=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,E=r/(g+1),x=E-d$*2,u0=this.noteFallingTimeMs/1e3,R0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,D0=p0-R0,E1=u0+R0,M=D0+E1,K0=zQ/E1,_0=[];this.synth.channelProperties.forEach(g2=>{if(this.showVisualPitch){let R1=g2.pitchBend-8192+this.visualPitchBendOffset;_0.push(g2.pitchBendRangeSemitones*(R1/8192*E))}else _0.push(0)});let k1=[];return this.noteTimes.forEach((g2,R1)=>{if(g2.renderStartIndex>=g2.notes.length||!this.renderChannels[R1])return;let _5=g2.renderStartIndex,v2=g2.notes,J2=v2[_5],n3=-1;for(;J2.start<=M&&(_5++,!(this.notesOnScreen>ZQ));){let U5=J2.start+J2.length;if(U5>D0&&J2.length>0){let a0=J2.length/E1*l-d$*2;if(this.notesOnScreen<1e3||a0>K0){n3===-1&&(n3=_5-1);let Y5=(J2.start-D0)/E1*l,n6;if(this._notesFall?n6=l-a0-Y5+d$:n6=Y5+d$,J2.midiNotethis.keyRange.max){if(_5>=v2.length)break;J2=v2[_5];continue}let c6=J2.midiNote-this.keyRange.min,O6=E*c6+d$,g6,u4,Ke,Y4;if(this.sideways?(g6=n6,u4=O6,Y4=x,Ke=a0):(u4=n6,g6=O6,Ke=x,Y4=a0),this.notesOnScreen++,o)this.drawingContext.fillStyle=this.plainColors[R1],this.drawingContext.fillRect(g6+I$+d$,u4+I$,Ke-I$*2,Y4-I$*2);else{let p9;if(J2.start>p0||U5=v2.length)break;J2=v2[_5]}n3>-1&&(g2.renderStartIndex=n3)}),k1.sort((g2,R1)=>R1.height-g2.height),k1}function WQ(){let o=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let E=g%4,x=Math.floor(g/4),u0=!1;for(let M=g;M0){u0=!0;break}if(!u0){let M=this.canvas.width/4,K0=this.canvas.height/4,_0=M*E,k1=K0*x+K0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(_0,k1),this.drawingContext.lineTo(_0+M,k1),this.drawingContext.stroke();return}let R0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(R0);let p0=o*E,D0=r*x+r/2,E1=this.waveMultiplier*r*this.waveSign;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let M=R0.length/4,K0=o/M,_0=Math.floor(M/2),k1=R0.length-_0;for(let v2=k1;v2>=1;v2--)if(R0[v2-1]<0&&R0[v2]>=0){k1=v2;break}let g2=p0,R1=k1-_0,_5=k1+_0;for(let v2=R1;v2<_5;v2++)this.drawingContext.lineTo(g2,D0+R0[v2]*E1),g2+=K0}else{let M=o/R0.length,K0=p0;for(let _0=0;_0{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function ey(){for(let o=0;o{this.updateFftSize()})}function iy(){for(let o of this.channelAnalysers)o.disconnect();j5("%cAnalysers disconnected!",D1.recognized)}function ry(o){this.seq=o,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),E=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${E}), rgba(0, 0, 0, ${E})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function ny(){this.noteTimes&&this.noteTimes.forEach(o=>o.renderStartIndex=0)}function wB(o,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=o[o.currentIndex++]<>>0}function mC(o,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=o&255,o>>=8;return l}var sh=.02;function Ay(o){function r(D0){return D0.messageData=new l6(D0.messageData.buffer),D0.messageData.currentIndex=0,6e7/wB(D0.messageData,3)}let l=[],E=o.tracks.flat();E.sort((D0,E1)=>D0.ticks-E1.ticks);for(let D0=0;D0<16;D0++)l.push({renderStartIndex:0,notes:[]});let x=0,u0=60/(120*o.timeDivision),R0=0,p0=0;for(;R0>4,M=D0.messageStatusByte&15;if(E1===8){let K0=l[M].notes.findLast(_0=>_0.midiNote===D0.messageData[0]&&_0.length===-1);if(K0){let _0=x-K0.start;K0.length=_0_0.midiNote===D0.messageData[0]&&_0.length===-1);if(K0){let _0=x-K0.start;K0.length=_0=E.length)break;x+=u0*(E[R0].ticks-D0.ticks)}p0>0&&l.forEach((D0,E1)=>D0.notes.filter(M=>M.length===-1).forEach(M=>{let K0=x-M.start;M.length=K0{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,u$(r,g=>g*hm)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,u$(r,g=>g*hm*gm)),l.addColorStop(1,u$(r,g=>g*gm)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,u$(r,g=>g*hm)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,u$(r,g=>g*hm*gm)),l.addColorStop(1,u$(r,g=>g*gm)),l})}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}onRender;get normalAnalyserFft(){return this._normalAnalyserFft}set normalAnalyserFft(r){this._normalAnalyserFft=r,this.updateFftSize()}get drumAnalyserFft(){return this._drumAnalyserFft}set drumAnalyserFft(r){this._drumAnalyserFft=r,this.updateFftSize()}get renderBool(){return this._renderBool}set renderBool(r){this._renderBool=r,r===!0?this.connectChannelAnalysers(this.synth):this.disconnectChannelAnalysers()}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}};vi.prototype.render=JQ;vi.prototype.computeNotePositions=KQ;vi.prototype.createChannelAnalysers=XQ;vi.prototype.updateFftSize=ey;vi.prototype.connectChannelAnalysers=ty;vi.prototype.disconnectChannelAnalysers=iy;vi.prototype.connectSequencer=ry;vi.prototype.calculateNoteTimes=Ay;vi.prototype.resetIndexes=ny;vi.prototype.renderWaveforms=WQ;function r3(o,r){let l=0;for(let g=0;g>>0}function E$(o,r,l){for(let g=0;g>g*8&255}function B9(o,r){o[o.currentIndex++]=r&255,o[o.currentIndex++]=r>>8}function ot(o,r){E$(o,r,4)}function oh(o,r){let l=r<<8|o;return l>32767?l-65536:l}function sy(o){return o>127?o-256:o}function Fe(o,r,l=void 0,g=!0){if(l){let E=o.slice(o.currentIndex,o.currentIndex+r);return o.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(E.buffer)}else{let E=!1,x="";for(let u0=0;u0127){if(g){E=!0;continue}else if(R0===0){E=!0;continue}}x+=String.fromCharCode(R0)}}return x}}function So(o,r=0){let l=o.length;r>0&&(l=r);let g=new l6(l);return ui(g,o,r),g}function ui(o,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,Fe(l.chunkData,4)===r))}function fm(o){let r=[o&127];for(o>>=7;o>0;)r.unshift(o&127|128),o>>=7;return r}function um(o){let r=[];for(let E of o.tracks){let x=[],u0=0,R0;for(let p0 of E){let D0=p0.ticks-u0,E1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?E1=[255,p0.messageStatusByte,...fm(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?E1=[240,...fm(p0.messageData.length),...p0.messageData]:(E1=[],R0!==p0.messageStatusByte&&(R0=p0.messageStatusByte,E1.push(p0.messageStatusByte)),E1.push(...p0.messageData)),x.push(...fm(D0)),x.push(...E1),u0+=D0}r.push(new Uint8Array(x))}function l(E,x){for(let u0=0;u0o.chunkData.currentIndex;)r.push(new kB(o.chunkData));return r.length>1&&r.pop(),r}var R7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Qn={linear:0,concave:1,convex:2,switch:3},yD=[];for(let o=0;o<4;o++)yD.push([[],[]]);var o7=class o{constructor(r){r.srcEnum?(this.modulatorSource=r.srcEnum,this.modulatorDestination=r.dest,this.modulationSecondarySrc=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.modulatorSource=r3(r,2),this.modulatorDestination=r3(r,2),this.transformAmount=oh(r[r.currentIndex++],r[r.currentIndex++]),this.modulationSecondarySrc=r3(r,2),this.transformType=r3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=b1.INVALID),this.sourcePolarity=this.modulatorSource>>9&1,this.sourceDirection=this.modulatorSource>>8&1,this.sourceUsesCC=this.modulatorSource>>7&1,this.sourceIndex=this.modulatorSource&127,this.sourceCurveType=this.modulatorSource>>10&3,this.secSrcPolarity=this.modulationSecondarySrc>>9&1,this.secSrcDirection=this.modulationSecondarySrc>>8&1,this.secSrcUsesCC=this.modulationSecondarySrc>>7&1,this.secSrcIndex=this.modulationSecondarySrc&127,this.secSrcCurveType=this.modulationSecondarySrc>>10&3}sumTransform(r){return new o({srcEnum:this.modulatorSource,secSrcEnum:this.modulationSecondarySrc,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(E,x){return Object.keys(E).find(u0=>E[u0]===x)}let l=r(Qn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(s6,this.sourceIndex):l+=r(R7,this.sourceIndex);let g=r(Qn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(s6,this.secSrcIndex):g+=r(R7,this.secSrcIndex),`Modulator: + Expected ${this._outputsAmount} got ${r.length}`);for(let l=0;l0?this.noteOn(l.channel,r[1],g):this.noteOff(l.channel,r[1]);break;case J3.noteOff:this.noteOff(l.channel,r[1]);break;case J3.pitchBend:this.pitchWheel(l.channel,r[2],r[1]);break;case J3.controllerChange:this.controllerChange(l.channel,r[1],r[2]);break;case J3.programChange:this.programChange(l.channel,r[1]);break;case J3.polyPressure:this.polyPressure(l.channel,r[0],r[1]);break;case J3.channelPressure:this.channelPressure(l.channel,r[1]);break;case J3.systemExclusive:this.systemExclusive(new l6(r.slice(1)));break;case J3.reset:this.stopAll(!0),this.resetControllers();break;default:break}}get currentTime(){return this.context.currentTime}get voicesAmount(){return this._voicesAmount}reverbateEverythingBecauseWhyNot(){for(let r=0;r{this.pressedKeys.delete(g),this.releaseNote(g,this.channel),this.synth.noteOff(this.channel,g)},r=(g,E)=>{let x;if(vo)x=127;else{let R0=this.keys[0].getBoundingClientRect();if(this.keyboard.classList.contains("sideways")){let p0=E.clientX-R0.left,D0=R0.width;x=Math.floor((D0-p0)/D0*127)}else{let p0=E.clientY-R0.top,D0=R0.height;x=Math.floor(p0/D0*127)}}this.synth.noteOn(this.channel,g,x,this.enableDebugging)},l=g=>{let E=g.touches?Array.from(g.touches):[g],x=new Set;E.forEach(u0=>{let R0=document.elementFromPoint(u0.clientX,u0.clientY),p0=parseInt(R0.id.replace("note",""));x.add(p0),!(isNaN(p0)||p0<0||this.pressedKeys.has(p0))&&(this.pressedKeys.add(p0),r(p0,u0))}),this.pressedKeys.forEach(u0=>{x.has(u0)||o(u0)})};vo||(document.addEventListener("mousedown",g=>{this.mouseHeld=!0,l(g)}),document.addEventListener("mouseup",()=>{this.mouseHeld=!1,this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.onmousemove=g=>{this.mouseHeld&&l(g)},this.keyboard.onmouseleave=()=>{this.pressedKeys.forEach(g=>{o(g)})}),this.keyboard.ontouchstart=l.bind(this),this.keyboard.ontouchend=l.bind(this),this.keyboard.ontouchmove=l.bind(this)}var qQ=20,CC=class{constructor(r,l){this.mouseHeld=!1,this.pressedKeys=new Set,this.mode="light",this.enableDebugging=!1,this.sizeChangeAnimationId=-1,this.modeChangeAnimationId=-1,this._keyRange={min:0,max:127},document.addEventListener("keydown",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,s6.sustainPedal,127),this.keyboard.style.filter="brightness(0.5)")}),document.addEventListener("keyup",g=>{g.key==="Shift"&&(this.synth.controllerChange(this.channel,s6.sustainPedal,0),this.keyboard.style.filter="")}),this.synth=l,this.channel=0,this.channelColors=r,this._shown=!0,this._createKeyboard(),this.synth.eventHandler.addEvent("noteon","keyboard-note-on",g=>{this.pressNote(g.midiNote,g.channel,g.velocity)}),this.synth.eventHandler.addEvent("noteoff","keyboard-note-off",g=>{this.releaseNote(g.midiNote,g.channel)}),this.synth.eventHandler.addEvent("stopall","keyboard-stop-all",()=>{this.clearNotes()}),this.synth.eventHandler.addEvent("mutechannel","keyboard-mute-channel",g=>{if(g.isMuted)for(let E=0;E<128;E++)this.releaseNote(E,g.channel)})}set shown(r){r===!0?this.keyboard.style.display="":this.keyboard.style.display="none",this._shown=r}get shown(){return this._shown}_createKeyboard(){this.keyboard=document.getElementById("keyboard"),this.keyboard.innerHTML="",this.keys=[],this.keyColors=[];for(let r=this._keyRange.min;r=0&&(x=l(r-1)),r<127&&(u0=l(r+1)),u0&&x?g.classList.add("between_sharps"):x?g.classList.add("left_sharp"):u0&&g.classList.add("right_sharp")}return g}toggleMode(r=!0){if(this.mode==="light"?this.mode="dark":this.mode="light",!r){this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")});return}this.modeChangeAnimationId&&clearTimeout(this.modeChangeAnimationId),this.keyboard.classList.add("mode_transform"),document.body.scrollHeight<=window.innerHeight&&document.body.classList.add("no_scroll"),this.modeChangeAnimationId=setTimeout(()=>{this.keys.forEach(g=>{g.classList.contains("flat_key")&&g.classList.toggle("flat_dark_key")}),this.keyboard.classList.remove("mode_transform"),setTimeout(()=>document.body.classList.remove("no_scroll"),500)},500)}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this.setKeyRange(r,!0)}setKeyRange(r,l=!0){Math.abs(r.max-r.min)<12&&(r.min-=6,r.max=r.min+12);let E=900/(r.max-r.min+5),x=document.styleSheets[0].cssRules,u0;for(let R0 of x)if(R0.selectorText==="#keyboard .key"){u0=R0;break}if(u0.style.setProperty("--pressed-transform-skew",`${8e-4/(E/7)}`),l){this.sizeChangeAnimationId&&clearTimeout(this.sizeChangeAnimationId);let R0=getComputedStyle(this.keyboard),p0=parseFloat(R0.getPropertyValue("--current-min-height").replace(/[^\d.]+/g,"")),D0=this.keyboard.getBoundingClientRect().height,E1=E/p0,M=D0*E1-D0,K0=(this._keyRange.min+this._keyRange.max)/2,_0=(r.min+r.max)/2;this._keyRange=r;let k1=this.keys.find(_5=>_5.classList.contains("sharp_key")).getBoundingClientRect().width,g2=(K0-_0)*k1,R1=parseFloat(R0.getPropertyValue("--key-border-radius").replace(/[^\d.]+/g,""));this.keyboard.style.marginTop=`${M}px`,this.keyboard.style.transition="",this.keyboard.style.transform=`scale(${E1}) translateX(${g2}px)`,this.keyboard.style.setProperty("--key-border-radius",`${R1/E1}vmin`),this.sizeChangeAnimationId=setTimeout(()=>{this.keyboard.style.setProperty("--current-min-height",`${E}`),this.keyboard.style.transition="none",this.keyboard.style.transform="",this.keyboard.style.marginTop="",this.keyboard.style.setProperty("--key-border-radius",""),this._createKeyboard(),setTimeout(()=>this.keyboard.style.transition="",75)},500)}else this.keyboard.style.setProperty("--current-min-height",`${E}`),this._keyRange=r,this._createKeyboard()}selectChannel(r){this.channel=r}pressNote(r,l,g){let E=this.keys[r-this._keyRange.min];if(E===void 0)return;E.classList.add("pressed");let x=E.classList.contains("sharp_key"),u0=g/127,R0=this.channelColors[l%16].match(/\d+(\.\d+)?/g).map(parseFloat),p0;if(!x&&this.mode==="light"?p0=`rgba(${R0.slice(0,3).map(E1=>255-(255-E1)*u0).join(", ")}, ${R0[3]})`:p0=`rgba(${R0.slice(0,3).map(E1=>E1*u0).join(", ")}, ${R0[3]})`,E.style.background=p0,this.mode==="dark"){let D0=qQ*u0;E.style.boxShadow=`${p0} 0px 0px ${D0}px ${D0/5}px`}this.keyColors[r-this._keyRange.min].push(this.channelColors[l%16])}releaseNote(r,l){let g=this.keys[r-this._keyRange.min];if(g===void 0)return;l%=this.channelColors.length;let E=this.keyColors[r-this._keyRange.min];if(!E)return;let x=E.findLastIndex(u0=>u0===this.channelColors[l]);x!==-1&&(E.splice(x,1),g.style.background=E[E.length-1],this.mode==="dark"&&(g.style.boxShadow=`0px 0px ${qQ}px ${E[E.length-1]}`),E.length<1&&(g.classList.remove("pressed"),g.style.background="",g.style.boxShadow=""))}clearNotes(){this.keys.forEach((r,l)=>{r.classList.remove("pressed"),r.style.background="",r.style.boxShadow="",this.keyColors[l]=[]})}};CC.prototype._handlePointers=HQ;function u$(o,r){let l=o.replace(/[^\d,]/g,"").split(",");return`rgb(${r(parseInt(l[0]))}, ${r(parseInt(l[1]))}, ${r(parseInt(l[2]))})`}var CD="#000";function YQ(o,r,l){o.forEach(g=>{if(g.pressedProgress===0)return;r.fillStyle=g.color;let E=g.pressedProgress*g.velocity;if(r.globalAlpha=.5*E,l){r.fillRect(g.xPos,g.yPos-g.height*E,g.width,g.height*(E*2+1)),r.globalAlpha=1;return}r.fillRect(g.xPos-g.width*E,g.yPos,g.width*(E*2+1),g.height),r.globalAlpha=1}),o.forEach(g=>{r.fillStyle=g.color,r.save(),r.translate(g.xPos,g.yPos),r.fillRect(0,0,g.width,g.height),r.restore(),r.strokeStyle=CD,r.lineWidth=g.stroke,r.strokeRect(g.xPos,g.yPos,g.width,g.height)})}var QB=!1;function JQ(o=!0,r=!1){let l=(this.seq===void 0||this?.seq?.paused===!0)&&this.synth.voicesAmount===0&&!r;if(!this.renderBool||l)if(QB){o&&requestAnimationFrame(this.render.bind(this));return}else QB=!0;else QB=!1;if(o&&this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderAnalysers&&!this.synth.highPerformanceMode&&this.renderWaveforms(),this.renderNotes&&this.noteTimes){let x=this.computeNotePositions(this.synth.highPerformanceMode);this.synth.highPerformanceMode||YQ(x,this.drawingContext,this.sideways)}let g=performance.now()-this.frameTimeStart;this.frameTimeStart=performance.now();let E=1e3/g;this.drawingContext.textBaseline="hanging",this.drawingContext.textAlign="end",this.drawingContext.font=`${yB}px Verdana`,this.drawingContext.fillStyle="white",this.drawingContext.strokeStyle="white",this.drawingContext.fillText(`${this.notesOnScreen} notes`,this.canvas.width,yB+5),this.drawingContext.fillText(Math.round(E).toString()+" FPS",this.canvas.width,5),this.onRender&&this.onRender(),o&&requestAnimationFrame(this.render.bind(this))}function KQ(o=!1){this.notesOnScreen=0;let r=this.sideways?this.canvas.height:this.canvas.width,l=this.sideways?this.canvas.width:this.canvas.height,g=this.keyRange.max-this.keyRange.min,E=r/(g+1),x=E-d$*2,u0=this.noteFallingTimeMs/1e3,R0=this.noteAfterTriggerTimeMs/1e3,p0=this.seq.currentHighResolutionTime,D0=p0-R0,E1=u0+R0,M=D0+E1,K0=zQ/E1,_0=[];this.synth.channelProperties.forEach(g2=>{if(this.showVisualPitch){let R1=g2.pitchBend-8192+this.visualPitchBendOffset;_0.push(g2.pitchBendRangeSemitones*(R1/8192*E))}else _0.push(0)});let k1=[];return this.noteTimes.forEach((g2,R1)=>{if(g2.renderStartIndex>=g2.notes.length||!this.renderChannels[R1])return;let _5=g2.renderStartIndex,v2=g2.notes,J2=v2[_5],n3=-1;for(;J2.start<=M&&(_5++,!(this.notesOnScreen>ZQ));){let U5=J2.start+J2.length;if(U5>D0&&J2.length>0){let a0=J2.length/E1*l-d$*2;if(this.notesOnScreen<1e3||a0>K0){n3===-1&&(n3=_5-1);let Y5=(J2.start-D0)/E1*l,n6;if(this._notesFall?n6=l-a0-Y5+d$:n6=Y5+d$,J2.midiNotethis.keyRange.max){if(_5>=v2.length)break;J2=v2[_5];continue}let c6=J2.midiNote-this.keyRange.min,O6=E*c6+d$,g6,u4,Ke,Y4;if(this.sideways?(g6=n6,u4=O6,Y4=x,Ke=a0):(u4=n6,g6=O6,Ke=x,Y4=a0),this.notesOnScreen++,o)this.drawingContext.fillStyle=this.plainColors[R1],this.drawingContext.fillRect(g6+I$+d$,u4+I$,Ke-I$*2,Y4-I$*2);else{let p9;if(J2.start>p0||U5=v2.length)break;J2=v2[_5]}n3>-1&&(g2.renderStartIndex=n3)}),k1.sort((g2,R1)=>R1.height-g2.height),k1}function WQ(){let o=this.canvas.width/4,r=this.canvas.height/4;this.channelAnalysers.forEach((l,g)=>{let E=g%4,x=Math.floor(g/4),u0=!1;for(let M=g;M0){u0=!0;break}if(!u0){let M=this.canvas.width/4,K0=this.canvas.height/4,_0=M*E,k1=K0*x+K0/2;this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this.drawingContext.moveTo(_0,k1),this.drawingContext.lineTo(_0+M,k1),this.drawingContext.stroke();return}let R0=new Float32Array(l.frequencyBinCount);l.getFloatTimeDomainData(R0);let p0=o*E,D0=r*x+r/2,E1=this.waveMultiplier*r;if(this.drawingContext.lineWidth=this.lineThickness,this.drawingContext.strokeStyle=this.channelColors[g],this.drawingContext.beginPath(),this._stabilizeWaveforms){let M=R0.length/4,K0=o/M,_0=Math.floor(M/2),k1=R0.length-_0;for(let v2=k1;v2>=1;v2--)if(R0[v2-1]<0&&R0[v2]>=0){k1=v2;break}let g2=p0,R1=k1-_0,_5=k1+_0;for(let v2=R1;v2<_5;v2++)this.drawingContext.lineTo(g2,D0+R0[v2]*E1),g2+=K0}else{let M=o/R0.length,K0=p0;for(let _0=0;_0{this.renderChannels[r.channel]=!r.isMuted}),this.updateFftSize()}function ey(){for(let o=0;o{this.updateFftSize()})}function iy(){for(let o of this.channelAnalysers)o.disconnect();j5("%cAnalysers disconnected!",D1.recognized)}function ry(o){this.seq=o,this.seq.addOnTimeChangeEvent(()=>this.resetIndexes(),"renderer-time-change"),this.seq.addOnSongChangeEvent(async r=>{if(this.calculateNoteTimes(await this.seq.getMIDI()),this.resetIndexes(),r.RMIDInfo?.IPIC!==void 0){let l=new Blob([r.RMIDInfo?.IPIC.buffer]),g=URL.createObjectURL(l),E=this.canvas.classList.contains("light_mode")?0:.9;this.canvas.style.background=`linear-gradient(rgba(0, 0, 0, ${E}), rgba(0, 0, 0, ${E})), center center / cover url("${g}")`}else this.canvas.style.background=""},"renderer-song-change")}function ny(){this.noteTimes&&this.noteTimes.forEach(o=>o.renderStartIndex=0)}function wB(o,r){let l=0;for(let g=8*(r-1);g>=0;g-=8)l|=o[o.currentIndex++]<>>0}function mC(o,r){let l=new Array(r).fill(0);for(let g=r-1;g>=0;g--)l[g]=o&255,o>>=8;return l}var sh=.02;function Ay(o){function r(D0){return D0.messageData=new l6(D0.messageData.buffer),D0.messageData.currentIndex=0,6e7/wB(D0.messageData,3)}let l=[],E=o.tracks.flat();E.sort((D0,E1)=>D0.ticks-E1.ticks);for(let D0=0;D0<16;D0++)l.push({renderStartIndex:0,notes:[]});let x=0,u0=60/(120*o.timeDivision),R0=0,p0=0;for(;R0>4,M=D0.messageStatusByte&15;if(E1===8){let K0=l[M].notes.findLast(_0=>_0.midiNote===D0.messageData[0]&&_0.length===-1);if(K0){let _0=x-K0.start;K0.length=_0_0.midiNote===D0.messageData[0]&&_0.length===-1);if(K0){let _0=x-K0.start;K0.length=_0=E.length)break;x+=u0*(E[R0].ticks-D0.ticks)}p0>0&&l.forEach((D0,E1)=>D0.notes.filter(M=>M.length===-1).forEach(M=>{let K0=x-M.start;M.length=K0{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,u$(r,g=>g*hm)),l.addColorStop(1,r),l}),this.darkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,this.canvas.width/128,0);return l.addColorStop(0,u$(r,g=>g*hm*gm)),l.addColorStop(1,u$(r,g=>g*gm)),l}),this.sidewaysChannelColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,u$(r,g=>g*hm)),l.addColorStop(1,r),l}),this.sidewaysDarkerColors=this.plainColors.map(r=>{let l=this.drawingContext.createLinearGradient(0,0,0,this.canvas.width/128);return l.addColorStop(0,u$(r,g=>g*hm*gm)),l.addColorStop(1,u$(r,g=>g*gm)),l})}toggleDarkMode(){this.canvas.classList.toggle("light_mode")}onRender;get normalAnalyserFft(){return this._normalAnalyserFft}set normalAnalyserFft(r){this._normalAnalyserFft=r,this.updateFftSize()}get drumAnalyserFft(){return this._drumAnalyserFft}set drumAnalyserFft(r){this._drumAnalyserFft=r,this.updateFftSize()}get renderBool(){return this._renderBool}set renderBool(r){this._renderBool=r,r===!0?this.connectChannelAnalysers(this.synth):this.disconnectChannelAnalysers()}get keyRange(){return this._keyRange}set keyRange(r){if(r.max===void 0||r.min===void 0)throw new TypeError("No min or max property!");if(r.min>r.max){let l=r.min;r.min=r.max,r.max=l}r.min=Math.max(0,r.min),r.max=Math.min(127,r.max),this._keyRange=r}};vi.prototype.render=JQ;vi.prototype.computeNotePositions=KQ;vi.prototype.createChannelAnalysers=XQ;vi.prototype.updateFftSize=ey;vi.prototype.connectChannelAnalysers=ty;vi.prototype.disconnectChannelAnalysers=iy;vi.prototype.connectSequencer=ry;vi.prototype.calculateNoteTimes=Ay;vi.prototype.resetIndexes=ny;vi.prototype.renderWaveforms=WQ;function r3(o,r){let l=0;for(let g=0;g>>0}function E$(o,r,l){for(let g=0;g>g*8&255}function B9(o,r){o[o.currentIndex++]=r&255,o[o.currentIndex++]=r>>8}function ot(o,r){E$(o,r,4)}function oh(o,r){let l=r<<8|o;return l>32767?l-65536:l}function sy(o){return o>127?o-256:o}function Fe(o,r,l=void 0,g=!0){if(l){let E=o.slice(o.currentIndex,o.currentIndex+r);return o.currentIndex+=r,new TextDecoder(l.replace(/[^\x20-\x7E]/g,"")).decode(E.buffer)}else{let E=!1,x="";for(let u0=0;u0127){if(g){E=!0;continue}else if(R0===0){E=!0;continue}}x+=String.fromCharCode(R0)}}return x}}function So(o,r=0){let l=o.length;r>0&&(l=r);let g=new l6(l);return ui(g,o,r),g}function ui(o,r,l=0){l>0&&r.length>l&&(r=r.slice(0,l));for(let g=0;gr.length)for(let g=0;gl.header!=="LIST"?!1:(l.chunkData.currentIndex=0,Fe(l.chunkData,4)===r))}function fm(o){let r=[o&127];for(o>>=7;o>0;)r.unshift(o&127|128),o>>=7;return r}function um(o){let r=[];for(let E of o.tracks){let x=[],u0=0,R0;for(let p0 of E){let D0=p0.ticks-u0,E1;p0.messageStatusByte<=J3.keySignature||p0.messageStatusByte===J3.sequenceSpecific?E1=[255,p0.messageStatusByte,...fm(p0.messageData.length),...p0.messageData]:p0.messageStatusByte===J3.systemExclusive?E1=[240,...fm(p0.messageData.length),...p0.messageData]:(E1=[],R0!==p0.messageStatusByte&&(R0=p0.messageStatusByte,E1.push(p0.messageStatusByte)),E1.push(...p0.messageData)),x.push(...fm(D0)),x.push(...E1),u0+=D0}r.push(new Uint8Array(x))}function l(E,x){for(let u0=0;u0o.chunkData.currentIndex;)r.push(new kB(o.chunkData));return r.length>1&&r.pop(),r}var R7={noController:0,noteOnVelocity:2,noteOnKeyNum:3,polyPressure:10,channelPressure:13,pitchWheel:14,pitchWheelRange:16,link:127},Qn={linear:0,concave:1,convex:2,switch:3},yD=[];for(let o=0;o<4;o++)yD.push([[],[]]);var o7=class o{constructor(r){r.srcEnum?(this.modulatorSource=r.srcEnum,this.modulatorDestination=r.dest,this.modulationSecondarySrc=r.secSrcEnum,this.transformAmount=r.amt,this.transformType=r.transform):(this.modulatorSource=r3(r,2),this.modulatorDestination=r3(r,2),this.transformAmount=oh(r[r.currentIndex++],r[r.currentIndex++]),this.modulationSecondarySrc=r3(r,2),this.transformType=r3(r,2)),this.modulatorDestination>58&&(this.modulatorDestination=b1.INVALID),this.sourcePolarity=this.modulatorSource>>9&1,this.sourceDirection=this.modulatorSource>>8&1,this.sourceUsesCC=this.modulatorSource>>7&1,this.sourceIndex=this.modulatorSource&127,this.sourceCurveType=this.modulatorSource>>10&3,this.secSrcPolarity=this.modulationSecondarySrc>>9&1,this.secSrcDirection=this.modulationSecondarySrc>>8&1,this.secSrcUsesCC=this.modulationSecondarySrc>>7&1,this.secSrcIndex=this.modulationSecondarySrc&127,this.secSrcCurveType=this.modulationSecondarySrc>>10&3}sumTransform(r){return new o({srcEnum:this.modulatorSource,secSrcEnum:this.modulationSecondarySrc,dest:this.modulatorDestination,transform:this.transformType,amt:this.transformAmount+r.transformAmount})}debugString(){function r(E,x){return Object.keys(E).find(u0=>E[u0]===x)}let l=r(Qn,this.sourceCurveType);l+=this.sourcePolarity===0?" unipolar ":" bipolar ",l+=this.sourceDirection===0?"forwards ":"backwards ",this.sourceUsesCC?l+=r(s6,this.sourceIndex):l+=r(R7,this.sourceIndex);let g=r(Qn,this.secSrcCurveType);return g+=this.secSrcPolarity===0?" unipolar ":" bipolar ",g+=this.secSrcCurveType===0?"forwards ":"backwards ",this.secSrcUsesCC?g+=r(s6,this.secSrcIndex):g+=r(R7,this.secSrcIndex),`Modulator: Source: ${l} Secondary source: ${g} Destination: ${r(b1,this.modulatorDestination)} @@ -82,7 +82,7 @@ var am=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(r,l)=>( - +