This repository was archived by the owner on Aug 8, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbeepbox_synth.min.js
More file actions
1 lines (1 loc) · 89.8 KB
/
Copy pathbeepbox_synth.min.js
File metadata and controls
1 lines (1 loc) · 89.8 KB
1
var beepbox;!function(t){class s{}function e(t){let s=0;for(let e=0;e<t.length;e++)s+=t[e];const e=s/t.length;let i=0,h=0;for(let s=0;s<t.length;s++)i+=h,h=t[s]-e,t[s]=i;return t.push(0),new Float64Array(t)}function i(e){let i=s.chipNoises[e].samples;if(null==i){if(i=new Float32Array(s.chipNoiseLength+1),s.chipNoises[e].samples=i,0==e){let t=1;for(let e=0;e<s.chipNoiseLength;e++){i[e]=2*(1&t)-1;let s=t>>1;1==(t+s&1)&&(s+=16384),t=s}}else if(1==e)for(let t=0;t<s.chipNoiseLength;t++)i[t]=2*Math.random()-1;else if(2==e){let t=1;for(let e=0;e<s.chipNoiseLength;e++){i[e]=2*(1&t)-1;let s=t>>1;1==(t+s&1)&&(s+=32768),t=s}}else if(3==e){let t=1;for(let e=0;e<s.chipNoiseLength;e++){i[e]=2*(1&t)-1;let s=t>>1;1==(t+s&1)&&(s+=40),t=s}}else{if(4!=e)throw new Error("Unrecognized drum index: "+e);h(i,10,11,1,1,0),h(i,11,14,.6578,.6578,0),t.inverseRealFourierTransform(i,s.chipNoiseLength),t.scaleElementsByFactor(i,1/Math.sqrt(s.chipNoiseLength))}i[s.chipNoiseLength]=i[0]}return i}function h(t,e,h,n,o,r){const a=0|Math.pow(2,e),l=Math.min(s.chipNoiseLength>>1,0|Math.pow(2,h)),f=i(0);let c=0;for(let i=a;i<l;i++){let a=n+(o-n)*(Math.log(i)/Math.LN2-e)/(h-e),l=Math.pow(2,(a-1)*s.spectrumMax+1)*a;c+=l*=Math.pow(i/2048,r),l*=f[i];const u=.61803398875*i*i*Math.PI*2;t[i]=Math.cos(u)*l,t[s.chipNoiseLength-i]=Math.sin(u)*l}return c}function n(t){const s={};for(let e=0;e<t.length;e++){const i=t[e];i.index=e,s[i.name]=i}const e=t;return e.dictionary=s,e}s.scales=n([{name:"easy :)",flags:[!0,!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!1]},{name:"easy :(",flags:[!0,!1,!1,!0,!1,!0,!1,!0,!1,!1,!0,!1]},{name:"island :)",flags:[!0,!1,!1,!1,!0,!0,!1,!0,!1,!1,!1,!0]},{name:"island :(",flags:[!0,!0,!1,!0,!1,!1,!1,!0,!0,!1,!1,!1]},{name:"blues :)",flags:[!0,!1,!0,!0,!0,!1,!1,!0,!1,!0,!1,!1]},{name:"blues :(",flags:[!0,!1,!1,!0,!1,!0,!0,!0,!1,!1,!0,!1]},{name:"normal :)",flags:[!0,!1,!0,!1,!0,!0,!1,!0,!1,!0,!1,!0]},{name:"normal :(",flags:[!0,!1,!0,!0,!1,!0,!1,!0,!0,!1,!0,!1]},{name:"dbl harmonic :)",flags:[!0,!0,!1,!1,!0,!0,!1,!0,!0,!1,!1,!0]},{name:"dbl harmonic :(",flags:[!0,!1,!0,!0,!1,!1,!0,!0,!0,!1,!1,!0]},{name:"enigma",flags:[!0,!1,!0,!1,!0,!1,!0,!1,!0,!1,!0,!1]},{name:"expert",flags:[!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0]}]),s.keys=n([{name:"C",isWhiteKey:!0,basePitch:12},{name:"C♯",isWhiteKey:!1,basePitch:13},{name:"D",isWhiteKey:!0,basePitch:14},{name:"D♯",isWhiteKey:!1,basePitch:15},{name:"E",isWhiteKey:!0,basePitch:16},{name:"F",isWhiteKey:!0,basePitch:17},{name:"F♯",isWhiteKey:!1,basePitch:18},{name:"G",isWhiteKey:!0,basePitch:19},{name:"G♯",isWhiteKey:!1,basePitch:20},{name:"A",isWhiteKey:!0,basePitch:21},{name:"A♯",isWhiteKey:!1,basePitch:22},{name:"B",isWhiteKey:!0,basePitch:23}]),s.blackKeyNameParents=[-1,1,-1,1,-1,1,-1,-1,1,-1,1,-1],s.tempoMin=30,s.tempoMax=300,s.reverbRange=4,s.beatsPerBarMin=3,s.beatsPerBarMax=16,s.barCountMin=1,s.barCountMax=128,s.instrumentsPerChannelMin=1,s.instrumentsPerChannelMax=10,s.partsPerBeat=24,s.ticksPerPart=2,s.rhythms=n([{name:"÷3 (triplets)",stepsPerBeat:3,ticksPerArpeggio:4,arpeggioPatterns:[[0],[0,0,1,1],[0,1,2,1],[0,1,2,3]],roundUpThresholds:[5,12,18]},{name:"÷4 (standard)",stepsPerBeat:4,ticksPerArpeggio:3,arpeggioPatterns:[[0],[0,0,1,1],[0,1,2,1],[0,1,2,3]],roundUpThresholds:[3,9,17,21]},{name:"÷6",stepsPerBeat:6,ticksPerArpeggio:4,arpeggioPatterns:[[0],[0,1],[0,1,2,1],[0,1,2,3]],roundUpThresholds:null},{name:"÷8",stepsPerBeat:8,ticksPerArpeggio:3,arpeggioPatterns:[[0],[0,1],[0,1,2,1],[0,1,2,3]],roundUpThresholds:null},{name:"freehand",stepsPerBeat:24,ticksPerArpeggio:3,arpeggioPatterns:[[0],[0,1],[0,1,2,1],[0,1,2,3]],roundUpThresholds:null}]),s.instrumentTypeNames=["chip","FM","noise","spectrum","drumset","harmonics","PWM"],s.instrumentTypeHasSpecialInterval=[!0,!0,!1,!1,!1,!0,!1],s.instrumentTypeHasChorus=[!0,!0,!0,!1,!1,!0,!0],s.chipWaves=n([{name:"rounded",volume:.94,samples:e([0,.2,.4,.5,.6,.7,.8,.85,.9,.95,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.95,.9,.85,.8,.7,.6,.5,.4,.2,0,-.2,-.4,-.5,-.6,-.7,-.8,-.85,-.9,-.95,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-.95,-.9,-.85,-.8,-.7,-.6,-.5,-.4,-.2])},{name:"triangle",volume:1,samples:e([1/15,.2,5/15,7/15,.6,11/15,13/15,1,1,13/15,11/15,.6,7/15,5/15,.2,1/15,-1/15,-.2,-5/15,-7/15,-.6,-11/15,-13/15,-1,-1,-13/15,-11/15,-.6,-7/15,-5/15,-.2,-1/15])},{name:"square",volume:.5,samples:e([1,-1])},{name:"1/4 pulse",volume:.5,samples:e([1,-1,-1,-1])},{name:"1/8 pulse",volume:.5,samples:e([1,-1,-1,-1,-1,-1,-1,-1])},{name:"sawtooth",volume:.65,samples:e([1/31,3/31,5/31,7/31,9/31,11/31,13/31,15/31,17/31,19/31,21/31,23/31,25/31,27/31,29/31,1,-1,-29/31,-27/31,-25/31,-23/31,-21/31,-19/31,-17/31,-15/31,-13/31,-11/31,-9/31,-7/31,-5/31,-3/31,-1/31])},{name:"double saw",volume:.5,samples:e([0,-.2,-.4,-.6,-.8,-1,1,-.8,-.6,-.4,-.2,1,.8,.6,.4,.2])},{name:"double pulse",volume:.4,samples:e([1,1,1,1,1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1])},{name:"spiky",volume:.4,samples:e([1,-1,1,-1,1,0])}]),s.chipNoises=n([{name:"retro",volume:.25,basePitch:69,pitchFilterMult:1024,isSoft:!1,samples:null},{name:"white",volume:1,basePitch:69,pitchFilterMult:8,isSoft:!0,samples:null},{name:"clang",volume:.4,basePitch:69,pitchFilterMult:1024,isSoft:!1,samples:null},{name:"buzz",volume:.3,basePitch:69,pitchFilterMult:1024,isSoft:!1,samples:null},{name:"hollow",volume:1.5,basePitch:96,pitchFilterMult:1,isSoft:!0,samples:null}]),s.filterCutoffMaxHz=8e3,s.filterCutoffMinHz=1,s.filterMax=.95,s.filterMaxResonance=.95,s.filterCutoffRange=11,s.filterResonanceRange=8,s.transitions=n([{name:"seamless",isSeamless:!0,attackSeconds:0,releases:!1,releaseTicks:1,slides:!1,slideTicks:3},{name:"hard",isSeamless:!1,attackSeconds:0,releases:!1,releaseTicks:3,slides:!1,slideTicks:3},{name:"soft",isSeamless:!1,attackSeconds:.025,releases:!1,releaseTicks:3,slides:!1,slideTicks:3},{name:"slide",isSeamless:!0,attackSeconds:.025,releases:!1,releaseTicks:3,slides:!0,slideTicks:3},{name:"cross fade",isSeamless:!1,attackSeconds:.04,releases:!0,releaseTicks:6,slides:!1,slideTicks:3},{name:"hard fade",isSeamless:!1,attackSeconds:0,releases:!0,releaseTicks:48,slides:!1,slideTicks:3},{name:"medium fade",isSeamless:!1,attackSeconds:.0125,releases:!0,releaseTicks:72,slides:!1,slideTicks:3},{name:"soft fade",isSeamless:!1,attackSeconds:.06,releases:!0,releaseTicks:96,slides:!1,slideTicks:6}]),s.vibratos=n([{name:"none",amplitude:0,periodsSeconds:[.14],delayParts:0},{name:"light",amplitude:.15,periodsSeconds:[.14],delayParts:0},{name:"delayed",amplitude:.3,periodsSeconds:[.14],delayParts:18},{name:"heavy",amplitude:.45,periodsSeconds:[.14],delayParts:0},{name:"shaky",amplitude:.1,periodsSeconds:[.11,.17798,.33],delayParts:0}]),s.intervals=n([{name:"union",spread:0,offset:0,volume:.7,sign:1},{name:"shimmer",spread:.016,offset:0,volume:.8,sign:1},{name:"hum",spread:.045,offset:0,volume:1,sign:1},{name:"honky tonk",spread:.09,offset:0,volume:1,sign:1},{name:"dissonant",spread:.25,offset:0,volume:.9,sign:1},{name:"fifth",spread:3.5,offset:3.5,volume:.9,sign:1},{name:"octave",spread:6,offset:6,volume:.8,sign:1},{name:"bowed",spread:.02,offset:0,volume:1,sign:-1}]),s.effectsNames=["none","reverb","chorus","chorus & reverb"],s.volumeRange=8,s.volumeLogScale=-.5,s.chords=n([{name:"harmony",harmonizes:!0,customInterval:!1,arpeggiates:!1,isCustomInterval:!1,strumParts:0},{name:"strum",harmonizes:!0,customInterval:!1,arpeggiates:!1,isCustomInterval:!1,strumParts:1},{name:"arpeggio",harmonizes:!1,customInterval:!1,arpeggiates:!0,isCustomInterval:!1,strumParts:0},{name:"custom interval",harmonizes:!0,customInterval:!0,arpeggiates:!0,isCustomInterval:!0,strumParts:0}]),s.operatorCount=4,s.algorithms=n([{name:"1←(2 3 4)",carrierCount:1,associatedCarrier:[1,1,1,1],modulatedBy:[[2,3,4],[],[],[]]},{name:"1←(2 3←4)",carrierCount:1,associatedCarrier:[1,1,1,1],modulatedBy:[[2,3],[],[4],[]]},{name:"1←2←(3 4)",carrierCount:1,associatedCarrier:[1,1,1,1],modulatedBy:[[2],[3,4],[],[]]},{name:"1←(2 3)←4",carrierCount:1,associatedCarrier:[1,1,1,1],modulatedBy:[[2,3],[4],[4],[]]},{name:"1←2←3←4",carrierCount:1,associatedCarrier:[1,1,1,1],modulatedBy:[[2],[3],[4],[]]},{name:"1←3 2←4",carrierCount:2,associatedCarrier:[1,2,1,2],modulatedBy:[[3],[4],[],[]]},{name:"1 2←(3 4)",carrierCount:2,associatedCarrier:[1,2,2,2],modulatedBy:[[],[3,4],[],[]]},{name:"1 2←3←4",carrierCount:2,associatedCarrier:[1,2,2,2],modulatedBy:[[],[3],[4],[]]},{name:"(1 2)←3←4",carrierCount:2,associatedCarrier:[1,2,2,2],modulatedBy:[[3],[3],[4],[]]},{name:"(1 2)←(3 4)",carrierCount:2,associatedCarrier:[1,2,2,2],modulatedBy:[[3,4],[3,4],[],[]]},{name:"1 2 3←4",carrierCount:3,associatedCarrier:[1,2,3,3],modulatedBy:[[],[],[4],[]]},{name:"(1 2 3)←4",carrierCount:3,associatedCarrier:[1,2,3,3],modulatedBy:[[4],[4],[4],[]]},{name:"1 2 3 4",carrierCount:4,associatedCarrier:[1,2,3,4],modulatedBy:[[],[],[],[]]}]),s.operatorCarrierInterval=[0,.04,-.073,.091],s.operatorAmplitudeMax=15,s.operatorFrequencies=n([{name:"1×",mult:1,hzOffset:0,amplitudeSign:1},{name:"~1×",mult:1,hzOffset:1.5,amplitudeSign:-1},{name:"2×",mult:2,hzOffset:0,amplitudeSign:1},{name:"~2×",mult:2,hzOffset:-1.3,amplitudeSign:-1},{name:"3×",mult:3,hzOffset:0,amplitudeSign:1},{name:"4×",mult:4,hzOffset:0,amplitudeSign:1},{name:"5×",mult:5,hzOffset:0,amplitudeSign:1},{name:"6×",mult:6,hzOffset:0,amplitudeSign:1},{name:"7×",mult:7,hzOffset:0,amplitudeSign:1},{name:"8×",mult:8,hzOffset:0,amplitudeSign:1},{name:"9×",mult:9,hzOffset:0,amplitudeSign:1},{name:"11×",mult:11,hzOffset:0,amplitudeSign:1},{name:"13×",mult:13,hzOffset:0,amplitudeSign:1},{name:"16×",mult:16,hzOffset:0,amplitudeSign:1},{name:"20×",mult:20,hzOffset:0,amplitudeSign:1}]),s.envelopes=n([{name:"custom",type:0,speed:0},{name:"steady",type:1,speed:0},{name:"punch",type:2,speed:0},{name:"flare 1",type:3,speed:32},{name:"flare 2",type:3,speed:8},{name:"flare 3",type:3,speed:2},{name:"twang 1",type:4,speed:32},{name:"twang 2",type:4,speed:8},{name:"twang 3",type:4,speed:2},{name:"swell 1",type:5,speed:32},{name:"swell 2",type:5,speed:8},{name:"swell 3",type:5,speed:2},{name:"tremolo1",type:6,speed:4},{name:"tremolo2",type:6,speed:2},{name:"tremolo3",type:6,speed:1},{name:"tremolo4",type:7,speed:4},{name:"tremolo5",type:7,speed:2},{name:"tremolo6",type:7,speed:1},{name:"decay 1",type:8,speed:10},{name:"decay 2",type:8,speed:7},{name:"decay 3",type:8,speed:4}]),s.feedbacks=n([{name:"1⟲",indices:[[1],[],[],[]]},{name:"2⟲",indices:[[],[2],[],[]]},{name:"3⟲",indices:[[],[],[3],[]]},{name:"4⟲",indices:[[],[],[],[4]]},{name:"1⟲ 2⟲",indices:[[1],[2],[],[]]},{name:"3⟲ 4⟲",indices:[[],[],[3],[4]]},{name:"1⟲ 2⟲ 3⟲",indices:[[1],[2],[3],[]]},{name:"2⟲ 3⟲ 4⟲",indices:[[],[2],[3],[4]]},{name:"1⟲ 2⟲ 3⟲ 4⟲",indices:[[1],[2],[3],[4]]},{name:"1→2",indices:[[],[1],[],[]]},{name:"1→3",indices:[[],[],[1],[]]},{name:"1→4",indices:[[],[],[],[1]]},{name:"2→3",indices:[[],[],[2],[]]},{name:"2→4",indices:[[],[],[],[2]]},{name:"3→4",indices:[[],[],[],[3]]},{name:"1→3 2→4",indices:[[],[],[1],[2]]},{name:"1→4 2→3",indices:[[],[],[2],[1]]},{name:"1→2→3→4",indices:[[],[1],[2],[3]]}]),s.chipNoiseLength=32768,s.spectrumBasePitch=24,s.spectrumControlPoints=30,s.spectrumControlPointsPerOctave=7,s.spectrumControlPointBits=3,s.spectrumMax=(1<<s.spectrumControlPointBits)-1,s.harmonicsControlPoints=28,s.harmonicsRendered=64,s.harmonicsControlPointBits=3,s.harmonicsMax=(1<<s.harmonicsControlPointBits)-1,s.harmonicsWavelength=2048,s.pulseWidthRange=8,s.pitchChannelCountMin=1,s.pitchChannelCountMax=6,s.noiseChannelCountMin=0,s.noiseChannelCountMax=3,s.noiseInterval=6,s.drumCount=12,s.pitchOctaves=7,s.windowOctaves=3,s.scrollableOctaves=s.pitchOctaves-s.windowOctaves,s.windowPitchCount=12*s.windowOctaves+1,s.maxPitch=12*s.pitchOctaves,s.maximumTonesPerChannel=8,s.sineWaveLength=256,s.sineWaveMask=s.sineWaveLength-1,s.sineWave=function(){const t=new Float64Array(s.sineWaveLength+1);for(let e=0;e<s.sineWaveLength+1;e++)t[e]=Math.sin(e*Math.PI*2/s.sineWaveLength);return t}(),t.Config=s,t.getDrumWave=i,t.drawNoiseSpectrum=h,t.toNameMap=n}(beepbox||(beepbox={})),function(t){function s(t){if(!function(t){return!(!t||t&t-1)}(t))throw new Error("FFT array length must be a power of 2.");return Math.round(Math.log(t)/Math.log(2))}t.scaleElementsByFactor=function(t,s){for(let e=0;e<t.length;e++)t[e]*=s},t.inverseRealFourierTransform=function(t,e){const i=s(e);if(e<4)throw new Error("FFT array length must be at least 4.");for(let s=i-1;s>=2;s--){const i=1<<s,h=i>>1,n=i<<1,o=2*Math.PI/n,r=Math.cos(o),a=Math.sin(o),l=2*r;for(let s=0;s<e;s+=n){const e=s,n=e+h,o=e+i,f=o+h,c=o+i,u=t[e],m=t[o];t[e]=u+m,t[n]*=2,t[o]=u-m,t[f]*=2;let d=r,p=-a,M=1,v=0;for(let s=1;s<h;s++){const i=e+s,h=o-s,n=o+s,r=c-s,a=t[i],f=t[h],u=t[n],m=t[r],g=a-f,w=u+m;t[i]=a+f,t[h]=m-u,t[n]=g*d-w*p,t[r]=w*d+g*p;const y=l*d-M,b=l*p-v;M=d,v=p,d=y,p=b}}}for(let s=0;s<e;s+=4){const e=s+1,i=s+2,h=s+3,n=t[s],o=2*t[e],r=t[i],a=2*t[h],l=n+r,f=n-r;t[s]=l+o,t[e]=l-o,t[i]=f+a,t[h]=f-a}!function(t,e){const i=s(e);if(i>16)throw new Error("FFT array length must not be greater than 2^16.");const h=16-i;for(let s=0;s<e;s++){let e;if((e=((e=(61680&(e=(52428&(e=(43690&s)>>1|(21845&s)<<1))>>2|(13107&e)<<2))>>4|(3855&e)<<4)>>8|(255&e)<<8)>>h)>s){let i=t[s];t[s]=t[e],t[e]=i}}}(t,e)}}(beepbox||(beepbox={})),function(t){t.Deque=class{constructor(){this.t=1,this.s=[void 0],this.i=0,this.h=0,this.o=0}pushFront(t){this.o>=this.t&&this.l(),this.h=this.h-1&this.i,this.s[this.h]=t,this.o++}pushBack(t){this.o>=this.t&&this.l(),this.s[this.h+this.o&this.i]=t,this.o++}popFront(){if(this.o<=0)throw new Error("No elements left to pop.");const t=this.s[this.h];return this.s[this.h]=void 0,this.h=this.h+1&this.i,this.o--,t}popBack(){if(this.o<=0)throw new Error("No elements left to pop.");this.o--;const t=this.h+this.o&this.i,s=this.s[t];return this.s[t]=void 0,s}peakFront(){if(this.o<=0)throw new Error("No elements left to pop.");return this.s[this.h]}peakBack(){if(this.o<=0)throw new Error("No elements left to pop.");return this.s[this.h+this.o-1&this.i]}count(){return this.o}set(t,s){if(t<0||t>=this.o)throw new Error("Invalid index");this.s[this.h+t&this.i]=s}get(t){if(t<0||t>=this.o)throw new Error("Invalid index");return this.s[this.h+t&this.i]}remove(t){if(t<0||t>=this.o)throw new Error("Invalid index");if(t<=this.o>>1){for(;t>0;)this.set(t,this.get(t-1)),t--;this.popFront()}else{for(t++;t<this.o;)this.set(t-1,this.get(t)),t++;this.popBack()}}l(){if(this.t>=1073741824)throw new Error("Capacity too big.");this.t=this.t<<1;const t=this.s,s=new Array(this.t),e=0|this.o,i=0|this.h;for(let h=0;h<e;h++)s[h]=t[i+h&this.i];for(let t=e;t<this.t;t++)s[t]=void 0;this.h=0,this.s=s,this.i=this.t-1}}}(beepbox||(beepbox={})),function(t){const s=[48,49,50,51,52,53,54,55,56,57,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,45,95],e=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,62,62,0,0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,0,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,0,0,0,0,63,0,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,0,0,0,0,0];class i{constructor(t,s,i){this.u=[],this.m=0;for(let h=s;h<i;h++){const s=e[t.charCodeAt(h)];this.u.push(s>>5&1),this.u.push(s>>4&1),this.u.push(s>>3&1),this.u.push(s>>2&1),this.u.push(s>>1&1),this.u.push(1&s)}}read(t){let s=0;for(;t>0;)s<<=1,s+=this.u[this.m++],t--;return s}readLongTail(t,s){let e=t,i=s;for(;this.u[this.m++];)e+=1<<i,i++;for(;i>0;)i--,this.u[this.m++]&&(e+=1<<i);return e}readPartDuration(){return this.readLongTail(1,3)}readLegacyPartDuration(){return this.readLongTail(1,2)}readPinCount(){return this.readLongTail(1,0)}readPitchInterval(){return this.read(1)?-this.readLongTail(1,3):this.readLongTail(1,3)}}class h{constructor(){this.u=[]}write(t,s){for(t--;t>=0;)this.u.push(s>>>t&1),t--}writeLongTail(t,s,e){if(e<t)throw new Error("value out of bounds");e-=t;let i=s;for(;e>=1<<i;)this.u.push(1),e-=1<<i,i++;for(this.u.push(0);i>0;)i--,this.u.push(e>>>i&1)}writePartDuration(t){this.writeLongTail(1,3,t)}writePinCount(t){this.writeLongTail(1,0,t)}writePitchInterval(t){t<0?(this.write(1,1),this.writeLongTail(1,3,-t)):(this.write(1,0),this.writeLongTail(1,3,t))}concat(t){this.u=this.u.concat(t.u)}encodeBase64(t){for(let e=0;e<this.u.length;e+=6){const i=this.u[e]<<5|this.u[e+1]<<4|this.u[e+2]<<3|this.u[e+3]<<2|this.u[e+4]<<1|this.u[e+5];t.push(s[i])}return t}lengthBase64(){return Math.ceil(this.u.length/6)}}function n(t,s,e){return{interval:t,time:s,volume:e}}function o(t,s,e){return e<=(s-=1)?e>=t?e:t:s}t.makeNotePin=n;class r{constructor(t,s,e,i,h=!1){this.pitches=[t],this.pins=[n(0,0,i),n(0,e-s,h?0:i)],this.start=s,this.end=e}pickMainInterval(){let t=0,s=0;for(let e=1;e<this.pins.length;e++){const i=this.pins[e-1],h=this.pins[e];if(i.interval==h.interval){const e=h.time-i.time;t<e&&(t=e,s=i.interval)}}if(0==t){let t=0;for(let e=0;e<this.pins.length;e++){const i=this.pins[e];t<i.volume&&(t=i.volume,s=i.interval)}}return s}}t.Note=r;class a{constructor(){this.notes=[],this.instrument=0}cloneNotes(){const t=[];for(const s of this.notes){const e=new r(-1,s.start,s.end,3);e.pitches=s.pitches.concat(),e.pins=[];for(const t of s.pins)e.pins.push(n(t.interval,t.time,t.volume));t.push(e)}return t}reset(){this.notes.length=0,this.instrument=0}}t.Pattern=a;class l{constructor(t){this.frequency=0,this.amplitude=0,this.envelope=0,this.reset(t)}reset(s){this.frequency=0,this.amplitude=s<=1?t.Config.operatorAmplitudeMax:0,this.envelope=0==s?0:1}}t.Operator=l;class f{constructor(t){this.spectrum=[],this.p=null,this.M=!1,this.reset(t)}reset(s){for(let e=0;e<t.Config.spectrumControlPoints;e++)if(s)this.spectrum[e]=Math.round(t.Config.spectrumMax*(1/Math.sqrt(1+e/3)));else{const s=0==e||7==e||11==e||14==e||16==e||18==e||21==e||23==e||e>=25;this.spectrum[e]=s?Math.max(0,Math.round(t.Config.spectrumMax*(1-e/30))):0}this.M=!1}markCustomWaveDirty(){this.M=!1}getCustomWave(s){if(!this.M||null==this.p){let i=t.Config.chipNoiseLength;null!=this.p&&this.p.length==i+1||(this.p=new Float32Array(i+1));const h=this.p;for(let t=0;t<i;t++)h[t]=0;const n=14,o=.25,r=[0,1/7,Math.log(5/4)/Math.LN2,3/7,Math.log(1.5)/Math.LN2,5/7,6/7];function e(e){return s+Math.floor(e/t.Config.spectrumControlPointsPerOctave)+r[(e+t.Config.spectrumControlPointsPerOctave)%t.Config.spectrumControlPointsPerOctave]}let a=1;for(let s=0;s<t.Config.spectrumControlPoints+1;s++){const i=s<=0?0:this.spectrum[s-1],r=s>=t.Config.spectrumControlPoints?this.spectrum[t.Config.spectrumControlPoints-1]:this.spectrum[s],l=e(s-1);let f=e(s);s>=t.Config.spectrumControlPoints&&(f=n+(f-n)*o),0==i&&0==r||(a+=.02*t.drawNoiseSpectrum(h,l,f,i/t.Config.spectrumMax,r/t.Config.spectrumMax,-.5))}this.spectrum[t.Config.spectrumControlPoints-1]>0&&(a+=.02*t.drawNoiseSpectrum(h,n+(e(t.Config.spectrumControlPoints)-n)*o,n,this.spectrum[t.Config.spectrumControlPoints-1]/t.Config.spectrumMax,0,-.5)),t.inverseRealFourierTransform(h,i),t.scaleElementsByFactor(h,5/(Math.sqrt(i)*Math.pow(a,.75))),h[i]=h[0],this.M=!0}return this.p}}t.SpectrumWave=f;class c{constructor(){this.harmonics=[],this.p=null,this.M=!1,this.reset()}reset(){for(let s=0;s<t.Config.harmonicsControlPoints;s++)this.harmonics[s]=0;this.harmonics[0]=t.Config.harmonicsMax,this.harmonics[3]=t.Config.harmonicsMax,this.harmonics[6]=t.Config.harmonicsMax,this.M=!1}markCustomWaveDirty(){this.M=!1}getCustomWave(){if(!this.M||null==this.p){let s=t.Config.harmonicsWavelength;const e=t.getDrumWave(0);null!=this.p&&this.p.length==s+1||(this.p=new Float32Array(s+1));const i=this.p;for(let t=0;t<s;t++)i[t]=0;const h=-.25;let n=1;for(let o=0;o<t.Config.harmonicsRendered;o++){const r=o+1;let a=o<t.Config.harmonicsControlPoints?this.harmonics[o]:this.harmonics[t.Config.harmonicsControlPoints-1];o>=t.Config.harmonicsControlPoints&&(a*=1-(o-t.Config.harmonicsControlPoints)/(t.Config.harmonicsRendered-t.Config.harmonicsControlPoints));const l=a/t.Config.harmonicsMax;let f=Math.pow(2,a-t.Config.harmonicsMax+1)*Math.sqrt(l);o<t.Config.harmonicsControlPoints&&(n+=f),f*=Math.pow(r,h),f*=e[o+589],i[s-r]=f}t.inverseRealFourierTransform(i,s);const o=1/Math.pow(n,.7);let r=0,a=0;for(let t=0;t<i.length;t++)r+=a,a=i[t]*o,i[t]=r;i[s]=i[0],this.M=!0}return this.p}}t.HarmonicsWave=c;class u{constructor(s){this.type=0,this.preset=0,this.chipWave=2,this.chipNoise=1,this.filterCutoff=6,this.filterResonance=0,this.filterEnvelope=1,this.transition=1,this.vibrato=0,this.interval=0,this.effects=0,this.chord=1,this.volume=0,this.pulseWidth=t.Config.pulseWidthRange-1,this.pulseEnvelope=1,this.algorithm=0,this.feedbackType=0,this.feedbackAmplitude=0,this.feedbackEnvelope=1,this.operators=[],this.harmonicsWave=new c,this.drumsetEnvelopes=[],this.drumsetSpectrumWaves=[],this.spectrumWave=new f(s);for(let s=0;s<t.Config.operatorCount;s++)this.operators[s]=new l(s);for(let s=0;s<t.Config.drumCount;s++)this.drumsetEnvelopes[s]=t.Config.envelopes.dictionary["twang 2"].index,this.drumsetSpectrumWaves[s]=new f(!0)}setTypeAndReset(s,e){switch(this.type=s,this.preset=s,this.volume=0,s){case 0:this.chipWave=2,this.filterCutoff=6,this.filterResonance=0,this.filterEnvelope=t.Config.envelopes.dictionary.steady.index,this.transition=1,this.vibrato=0,this.interval=0,this.effects=1,this.chord=2;break;case 1:this.transition=1,this.vibrato=0,this.effects=1,this.chord=3,this.filterCutoff=10,this.filterResonance=0,this.filterEnvelope=1,this.algorithm=0,this.feedbackType=0,this.feedbackAmplitude=0,this.feedbackEnvelope=t.Config.envelopes.dictionary.steady.index;for(let t=0;t<this.operators.length;t++)this.operators[t].reset(t);break;case 2:this.chipNoise=1,this.transition=1,this.effects=0,this.chord=2,this.filterCutoff=10,this.filterResonance=0,this.filterEnvelope=t.Config.envelopes.dictionary.steady.index;break;case 3:this.transition=1,this.effects=1,this.chord=0,this.filterCutoff=10,this.filterResonance=0,this.filterEnvelope=t.Config.envelopes.dictionary.steady.index,this.spectrumWave.reset(e);break;case 4:this.effects=0;for(let s=0;s<t.Config.drumCount;s++)this.drumsetEnvelopes[s]=t.Config.envelopes.dictionary["twang 2"].index,this.drumsetSpectrumWaves[s].reset(e);break;case 5:this.filterCutoff=10,this.filterResonance=0,this.filterEnvelope=t.Config.envelopes.dictionary.steady.index,this.transition=1,this.vibrato=0,this.interval=0,this.effects=1,this.chord=0,this.harmonicsWave.reset();break;case 6:this.filterCutoff=10,this.filterResonance=0,this.filterEnvelope=t.Config.envelopes.dictionary.steady.index,this.transition=1,this.vibrato=0,this.interval=0,this.effects=1,this.chord=2,this.pulseWidth=t.Config.pulseWidthRange-1,this.pulseEnvelope=t.Config.envelopes.dictionary["twang 2"].index;break;default:throw new Error("Unrecognized instrument type: "+s)}}toJsonObject(){const s={type:t.Config.instrumentTypeNames[this.type],volume:20*(5-this.volume),effects:t.Config.effectsNames[this.effects]};if(this.preset!=this.type&&(s.preset=this.preset),4!=this.type&&(s.transition=t.Config.transitions[this.transition].name,s.chord=this.getChord().name,s.filterCutoffHz=Math.round(t.Config.filterCutoffMaxHz*Math.pow(2,this.getFilterCutoffOctaves())),s.filterResonance=Math.round(100*this.filterResonance/(t.Config.filterResonanceRange-1)),s.filterEnvelope=this.getFilterEnvelope().name),2==this.type)s.wave=t.Config.chipNoises[this.chipNoise].name;else if(3==this.type){s.spectrum=[];for(let e=0;e<t.Config.spectrumControlPoints;e++)s.spectrum[e]=Math.round(100*this.spectrumWave.spectrum[e]/t.Config.spectrumMax)}else if(4==this.type){s.drums=[];for(let e=0;e<t.Config.drumCount;e++){const i=[];for(let s=0;s<t.Config.spectrumControlPoints;s++)i[s]=Math.round(100*this.drumsetSpectrumWaves[e].spectrum[s]/t.Config.spectrumMax);s.drums[e]={filterEnvelope:this.getDrumsetEnvelope(e).name,spectrum:i}}}else if(0==this.type)s.wave=t.Config.chipWaves[this.chipWave].name,s.interval=t.Config.intervals[this.interval].name,s.vibrato=t.Config.vibratos[this.vibrato].name;else if(6==this.type)s.pulseWidth=Math.round(50*Math.pow(.5,.5*(t.Config.pulseWidthRange-this.pulseWidth-1))*32)/32,s.pulseEnvelope=t.Config.envelopes[this.pulseEnvelope].name,s.vibrato=t.Config.vibratos[this.vibrato].name;else if(5==this.type){s.interval=t.Config.intervals[this.interval].name,s.vibrato=t.Config.vibratos[this.vibrato].name,s.harmonics=[];for(let e=0;e<t.Config.harmonicsControlPoints;e++)s.harmonics[e]=Math.round(100*this.harmonicsWave.harmonics[e]/t.Config.harmonicsMax)}else{if(1!=this.type)throw new Error("Unrecognized instrument type");{const e=[];for(const s of this.operators)e.push({frequency:t.Config.operatorFrequencies[s.frequency].name,amplitude:s.amplitude,envelope:t.Config.envelopes[s.envelope].name});s.vibrato=t.Config.vibratos[this.vibrato].name,s.algorithm=t.Config.algorithms[this.algorithm].name,s.feedbackType=t.Config.feedbacks[this.feedbackType].name,s.feedbackAmplitude=this.feedbackAmplitude,s.feedbackEnvelope=t.Config.envelopes[this.feedbackEnvelope].name,s.operators=e}}return s}fromJsonObject(s,e){void 0==s&&(s={});let i=t.Config.instrumentTypeNames.indexOf(s.type);-1==i&&(i=e?2:0),this.setTypeAndReset(i,e),void 0!=s.preset&&(this.preset=s.preset>>>0),void 0!=s.volume?this.volume=o(0,t.Config.volumeRange,Math.round(5-(0|s.volume)/20)):this.volume=0;const h={binary:0,sudden:1,smooth:2},n=s.transition||s.envelope;if(this.transition=void 0!=h[n]?h[n]:t.Config.transitions.findIndex(t=>t.name==n),-1==this.transition&&(this.transition=1),this.effects=t.Config.effectsNames.indexOf(s.effects),-1==this.effects&&(this.effects=2==this.type?0:1),void 0!=s.filterCutoffHz?this.filterCutoff=o(0,t.Config.filterCutoffRange,Math.round(t.Config.filterCutoffRange-1+2*Math.log((0|s.filterCutoffHz)/t.Config.filterCutoffMaxHz)/Math.LN2)):this.filterCutoff=0==this.type?6:10,void 0!=s.filterResonance?this.filterResonance=o(0,t.Config.filterResonanceRange,Math.round((t.Config.filterResonanceRange-1)*(0|s.filterResonance)/100)):this.filterResonance=0,this.filterEnvelope=t.Config.envelopes.findIndex(t=>t.name==s.filterEnvelope),-1==this.filterEnvelope&&(this.filterEnvelope=t.Config.envelopes.dictionary.steady.index),void 0!=s.filter){const t=[10,6,3,0,8,5,2],e=[1,1,1,1,18,19,20],i=["none","bright","medium","soft","decay bright","decay medium","decay soft"],h={"sustain sharp":1,"sustain medium":2,"sustain soft":3,"decay sharp":4};let n=void 0!=h[s.filter]?h[s.filter]:i.indexOf(s.filter);-1==n&&(n=0),this.filterCutoff=t[n],this.filterEnvelope=e[n],this.filterResonance=0}const r=["none","vibrato light","vibrato delayed","vibrato heavy"];if(2==this.type)this.chipNoise=t.Config.chipNoises.findIndex(t=>t.name==s.wave),-1==this.chipNoise&&(this.chipNoise=1),this.chord=t.Config.chords.findIndex(t=>t.name==s.chord),-1==this.chord&&(this.chord=2);else if(3==this.type){if(void 0!=s.spectrum)for(let e=0;e<t.Config.spectrumControlPoints;e++)this.spectrumWave.spectrum[e]=Math.max(0,Math.min(t.Config.spectrumMax,Math.round(t.Config.spectrumMax*+s.spectrum[e]/100)));this.chord=t.Config.chords.findIndex(t=>t.name==s.chord),-1==this.chord&&(this.chord=0)}else if(4==this.type){if(void 0!=s.drums)for(let e=0;e<t.Config.drumCount;e++){const i=s.drums[e];if(void 0!=i&&(void 0!=i.filterEnvelope&&(this.drumsetEnvelopes[e]=t.Config.envelopes.findIndex(t=>t.name==i.filterEnvelope),-1==this.drumsetEnvelopes[e]&&(this.drumsetEnvelopes[e]=t.Config.envelopes.dictionary["twang 2"].index)),void 0!=i.spectrum))for(let s=0;s<t.Config.spectrumControlPoints;s++)this.drumsetSpectrumWaves[e].spectrum[s]=Math.max(0,Math.min(t.Config.spectrumMax,Math.round(t.Config.spectrumMax*+i.spectrum[s]/100)))}}else if(5==this.type){if(void 0!=s.harmonics)for(let e=0;e<t.Config.harmonicsControlPoints;e++)this.harmonicsWave.harmonics[e]=Math.max(0,Math.min(t.Config.harmonicsMax,Math.round(t.Config.harmonicsMax*+s.harmonics[e]/100)));void 0!=s.interval&&(this.interval=t.Config.intervals.findIndex(t=>t.name==s.interval),-1==this.interval&&(this.interval=0)),void 0!=s.vibrato&&(this.vibrato=t.Config.vibratos.findIndex(t=>t.name==s.vibrato),-1==this.vibrato&&(this.vibrato=0)),this.chord=t.Config.chords.findIndex(t=>t.name==s.chord),-1==this.chord&&(this.chord=0)}else if(6==this.type)void 0!=s.pulseWidth?this.pulseWidth=o(0,t.Config.pulseWidthRange,Math.round(Math.log(+s.pulseWidth/50)/Math.LN2/.5-1+8)):this.pulseWidth=t.Config.pulseWidthRange-1,void 0!=s.pulseEnvelope&&(this.pulseEnvelope=t.Config.envelopes.findIndex(t=>t.name==s.pulseEnvelope),-1==this.pulseEnvelope&&(this.pulseEnvelope=t.Config.envelopes.dictionary.steady.index)),void 0!=s.vibrato&&(this.vibrato=t.Config.vibratos.findIndex(t=>t.name==s.vibrato),-1==this.vibrato&&(this.vibrato=0)),this.chord=t.Config.chords.findIndex(t=>t.name==s.chord),-1==this.chord&&(this.chord=0);else if(0==this.type){const e={triangle:1,square:2,"pulse wide":3,"pulse narrow":4,sawtooth:5,"double saw":6,"double pulse":7,spiky:8,plateau:0};if(this.chipWave=void 0!=e[s.wave]?e[s.wave]:t.Config.chipWaves.findIndex(t=>t.name==s.wave),-1==this.chipWave&&(this.chipWave=1),void 0!=s.interval)this.interval=t.Config.intervals.findIndex(t=>t.name==s.interval),-1==this.interval&&(this.interval=0);else if(void 0!=s.chorus){const e={fifths:5,octaves:6};this.interval=void 0!=e[s.chorus]?e[s.chorus]:t.Config.intervals.findIndex(t=>t.name==s.chorus),-1==this.interval&&(this.interval=0)}void 0!=s.vibrato?(this.vibrato=t.Config.vibratos.findIndex(t=>t.name==s.vibrato),-1==this.vibrato&&(this.vibrato=0)):void 0!=s.effect&&(this.vibrato=r.indexOf(s.effect),-1==this.vibrato&&(this.vibrato=0)),this.chord=t.Config.chords.findIndex(t=>t.name==s.chord),-1==this.chord&&(this.chord=2),"custom harmony"==s.chorus&&(this.interval=2,this.chord=3)}else{if(1!=this.type)throw new Error("Unrecognized instrument type.");{void 0!=s.vibrato?(this.vibrato=t.Config.vibratos.findIndex(t=>t.name==s.vibrato),-1==this.vibrato&&(this.vibrato=0)):void 0!=s.effect&&(this.vibrato=r.indexOf(s.effect),-1==this.vibrato&&(this.vibrato=0)),this.chord=t.Config.chords.findIndex(t=>t.name==s.chord),-1==this.chord&&(this.chord=3),this.algorithm=t.Config.algorithms.findIndex(t=>t.name==s.algorithm),-1==this.algorithm&&(this.algorithm=0),this.feedbackType=t.Config.feedbacks.findIndex(t=>t.name==s.feedbackType),-1==this.feedbackType&&(this.feedbackType=0),void 0!=s.feedbackAmplitude?this.feedbackAmplitude=o(0,t.Config.operatorAmplitudeMax+1,0|s.feedbackAmplitude):this.feedbackAmplitude=0;const e={"pluck 1":6,"pluck 2":7,"pluck 3":8};this.feedbackEnvelope=void 0!=e[s.feedbackEnvelope]?e[s.feedbackEnvelope]:t.Config.envelopes.findIndex(t=>t.name==s.feedbackEnvelope),-1==this.feedbackEnvelope&&(this.feedbackEnvelope=0);for(let i=0;i<t.Config.operatorCount;i++){const h=this.operators[i];let n=void 0;s.operators&&(n=s.operators[i]),void 0==n&&(n={}),h.frequency=t.Config.operatorFrequencies.findIndex(t=>t.name==n.frequency),-1==h.frequency&&(h.frequency=0),void 0!=n.amplitude?h.amplitude=o(0,t.Config.operatorAmplitudeMax+1,0|n.amplitude):h.amplitude=0,h.envelope=void 0!=e[n.envelope]?e[n.envelope]:t.Config.envelopes.findIndex(t=>t.name==n.envelope),-1==h.envelope&&(h.envelope=0)}}}}static frequencyFromPitch(t){return 440*Math.pow(2,(t-69)/12)}static drumsetIndexReferenceDelta(s){return u.frequencyFromPitch(t.Config.spectrumBasePitch+6*s)/44100}static v(t){return 15+Math.log(u.drumsetIndexReferenceDelta(t))/Math.LN2}warmUp(){if(2==this.type)t.getDrumWave(this.chipNoise);else if(5==this.type)this.harmonicsWave.getCustomWave();else if(3==this.type)this.spectrumWave.getCustomWave(8);else if(4==this.type)for(let s=0;s<t.Config.drumCount;s++)this.drumsetSpectrumWaves[s].getCustomWave(u.v(s))}getDrumWave(){if(2==this.type)return t.getDrumWave(this.chipNoise);if(3==this.type)return this.spectrumWave.getCustomWave(8);throw new Error("Unhandled instrument type in getDrumWave")}getDrumsetWave(t){if(4==this.type)return this.drumsetSpectrumWaves[t].getCustomWave(u.v(t));throw new Error("Unhandled instrument type in getDrumWave")}getTransition(){return 4==this.type?t.Config.transitions.dictionary["hard fade"]:t.Config.transitions[this.transition]}getChord(){return 4==this.type?t.Config.chords.dictionary.harmony:t.Config.chords[this.chord]}getFilterCutoffOctaves(){return 4==this.type?0:.5*(this.filterCutoff-(t.Config.filterCutoffRange-1))}getFilterIsFirstOrder(){return 4!=this.type&&0==this.filterResonance}getFilterResonance(){return 4==this.type?1:this.filterResonance}getFilterEnvelope(){if(4==this.type)throw new Error("Can't getFilterEnvelope() for drumset.");return t.Config.envelopes[this.filterEnvelope]}getDrumsetEnvelope(s){if(4!=this.type)throw new Error("Can't getDrumsetEnvelope() for non-drumset.");return t.Config.envelopes[this.drumsetEnvelopes[s]]}}t.Instrument=u;class m{constructor(){this.octave=0,this.instruments=[],this.patterns=[],this.bars=[]}}t.Channel=m;class d{constructor(t){this.channels=[],void 0!=t?this.fromBase64String(t):this.initToDefault(!0)}getChannelCount(){return this.pitchChannelCount+this.noiseChannelCount}getChannelIsNoise(t){return t>=this.pitchChannelCount}initToDefault(t=!0){if(this.scale=0,this.key=0,this.loopStart=0,this.loopLength=4,this.tempo=150,this.reverb=0,this.beatsPerBar=8,this.barCount=16,this.patternsPerChannel=8,this.rhythm=1,this.instrumentsPerChannel=1,t){this.pitchChannelCount=3,this.noiseChannelCount=1;for(let t=0;t<this.getChannelCount();t++){this.channels.length<=t&&(this.channels[t]=new m);const s=this.channels[t];s.octave=3-t;for(let t=0;t<this.patternsPerChannel;t++)s.patterns.length<=t?s.patterns[t]=new a:s.patterns[t].reset();s.patterns.length=this.patternsPerChannel;const e=t>=this.pitchChannelCount;for(let t=0;t<this.instrumentsPerChannel;t++)s.instruments.length<=t&&(s.instruments[t]=new u(e)),s.instruments[t].setTypeAndReset(e?2:0,e);s.instruments.length=this.instrumentsPerChannel;for(let t=0;t<this.barCount;t++)s.bars[t]=t<4?1:0;s.bars.length=this.barCount}this.channels.length=this.getChannelCount()}}toBase64String(){let e,i=[];i.push(s[d.g]),i.push(110,s[this.pitchChannelCount],s[this.noiseChannelCount]),i.push(115,s[this.scale]),i.push(107,s[this.key]),i.push(108,s[this.loopStart>>6],s[63&this.loopStart]),i.push(101,s[this.loopLength-1>>6],s[this.loopLength-1&63]),i.push(116,s[this.tempo>>6],s[63&this.tempo]),i.push(109,s[this.reverb]),i.push(97,s[this.beatsPerBar-1]),i.push(103,s[this.barCount-1>>6],s[this.barCount-1&63]),i.push(106,s[this.patternsPerChannel-1>>6],s[this.patternsPerChannel-1&63]),i.push(105,s[this.instrumentsPerChannel-1]),i.push(114,s[this.rhythm]),i.push(111);for(let t=0;t<this.getChannelCount();t++)i.push(s[this.channels[t].octave]);for(let e=0;e<this.getChannelCount();e++)for(let n=0;n<this.instrumentsPerChannel;n++){const o=this.channels[e].instruments[n];if(i.push(84,s[o.type]),i.push(118,s[o.volume]),i.push(117,s[o.preset>>6],s[63&o.preset]),i.push(113,s[o.effects]),4!=o.type&&(i.push(100,s[o.transition]),i.push(102,s[o.filterCutoff]),i.push(121,s[o.filterResonance]),i.push(122,s[o.filterEnvelope]),i.push(67,s[o.chord])),0==o.type)i.push(119,s[o.chipWave]),i.push(99,s[o.vibrato]),i.push(104,s[o.interval]);else if(1==o.type){i.push(99,s[o.vibrato]),i.push(65,s[o.algorithm]),i.push(70,s[o.feedbackType]),i.push(66,s[o.feedbackAmplitude]),i.push(86,s[o.feedbackEnvelope]),i.push(81);for(let e=0;e<t.Config.operatorCount;e++)i.push(s[o.operators[e].frequency]);i.push(80);for(let e=0;e<t.Config.operatorCount;e++)i.push(s[o.operators[e].amplitude]);i.push(69);for(let e=0;e<t.Config.operatorCount;e++)i.push(s[o.operators[e].envelope])}else if(2==o.type)i.push(119,s[o.chipNoise]);else if(3==o.type){i.push(83);const s=new h;for(let e=0;e<t.Config.spectrumControlPoints;e++)s.write(t.Config.spectrumControlPointBits,o.spectrumWave.spectrum[e]);s.encodeBase64(i)}else if(4==o.type){i.push(122);for(let e=0;e<t.Config.drumCount;e++)i.push(s[o.drumsetEnvelopes[e]]);i.push(83);const e=new h;for(let s=0;s<t.Config.drumCount;s++)for(let i=0;i<t.Config.spectrumControlPoints;i++)e.write(t.Config.spectrumControlPointBits,o.drumsetSpectrumWaves[s].spectrum[i]);e.encodeBase64(i)}else if(5==o.type){i.push(99,s[o.vibrato]),i.push(104,s[o.interval]),i.push(72);const e=new h;for(let s=0;s<t.Config.harmonicsControlPoints;s++)e.write(t.Config.harmonicsControlPointBits,o.harmonicsWave.harmonics[s]);e.encodeBase64(i)}else{if(6!=o.type)throw new Error("Unknown instrument type.");i.push(99,s[o.vibrato]),i.push(87,s[o.pulseWidth],s[o.pulseEnvelope])}}i.push(98),e=new h;let n=0;for(;1<<n<this.patternsPerChannel+1;)n++;for(let t=0;t<this.getChannelCount();t++)for(let s=0;s<this.barCount;s++)e.write(n,this.channels[t].bars[s]);e.encodeBase64(i),i.push(112),e=new h;let o=0;for(;1<<o<this.instrumentsPerChannel;)o++;for(let s=0;s<this.getChannelCount();s++){const i=this.getChannelIsNoise(s),n=i?0:12*this.channels[s].octave;let r=(i?4:12)+n;const a=i?[4,6,7,2,3,8,0,10]:[12,19,24,31,36,7,0],l=[];for(let t=0;t<a.length;t++)a[t]+=n;for(const i of this.channels[s].patterns)if(e.write(o,i.instrument),i.notes.length>0){e.write(1,1);let s=0;for(const t of i.notes){t.start>s&&(e.write(2,0),e.writePartDuration(t.start-s));const i=new h;for(let s=1;s<t.pitches.length;s++)i.write(1,1);t.pitches.length<4&&i.write(1,0),i.writePinCount(t.pins.length-1),i.write(2,t.pins[0].volume);let n=0,o=t.pitches[0],f=o;const c=[];for(let s=1;s<t.pins.length;s++){const e=t.pins[s],h=o+e.interval;f!=h?(i.write(1,1),c.push(h),f=h):i.write(1,0),i.writePartDuration(e.time-n),n=e.time,i.write(2,e.volume)}const u=String.fromCharCode.apply(null,i.encodeBase64([])),m=l.indexOf(u);-1==m?(e.write(2,1),e.concat(i)):(e.write(1,1),e.writeLongTail(0,0,m),l.splice(m,1)),l.unshift(u),l.length>10&&l.pop();const d=t.pitches.concat(c);for(let s=0;s<d.length;s++){const i=d[s],h=a.indexOf(i);if(-1==h){let t=0,s=r;if(s<i)for(;s!=i;)s++,-1==a.indexOf(s)&&t++;else for(;s!=i;)s--,-1==a.indexOf(s)&&t--;e.write(1,0),e.writePitchInterval(t)}else e.write(1,1),e.write(3,h),a.splice(h,1);a.unshift(i),a.length>8&&a.pop(),r=s==t.pitches.length-1?t.pitches[0]:i}s=t.end}s<this.beatsPerBar*t.Config.partsPerBeat&&(e.write(2,0),e.writePartDuration(this.beatsPerBar*t.Config.partsPerBeat-s))}else e.write(1,0)}let r=e.lengthBase64(),a=[];for(;r>0;)a.unshift(s[63&r]),r>>=6;i.push(s[a.length]),Array.prototype.push.apply(i,a),e.encodeBase64(i);if(i.length<64e3)return String.fromCharCode.apply(null,i);{let t="";for(let s=0;s<i.length;s+=64e3)t+=String.fromCharCode.apply(null,i.slice(s,s+64e3));return t}}fromBase64String(s){if(null==s||""==s)return void this.initToDefault(!0);let h=0;for(;s.charCodeAt(h)<=32;)h++;if(35==s.charCodeAt(h)&&h++,123==s.charCodeAt(h))return void this.fromJsonObject(JSON.parse(0==h?s:s.substring(h)));const l=e[s.charCodeAt(h++)];if(-1==l||l>d.g||l<d.S)return;const f=l<3,c=l<4,p=l<5,M=l<6,v=l<7,g=l<8;if(this.initToDefault(M),f){for(const t of this.channels)t.instruments[0].transition=0;this.channels[3].instruments[0].chipNoise=0}let w=0,y=-1;for(;h<s.length;){const l=s.charCodeAt(h++);let d;if(110==l){this.pitchChannelCount=e[s.charCodeAt(h++)],this.noiseChannelCount=e[s.charCodeAt(h++)],this.pitchChannelCount=o(t.Config.pitchChannelCountMin,t.Config.pitchChannelCountMax+1,this.pitchChannelCount),this.noiseChannelCount=o(t.Config.noiseChannelCountMin,t.Config.noiseChannelCountMax+1,this.noiseChannelCount);for(let t=this.channels.length;t<this.getChannelCount();t++)this.channels[t]=new m;this.channels.length=this.getChannelCount()}else if(115==l)this.scale=e[s.charCodeAt(h++)],f&&10==this.scale&&(this.scale=11);else if(107==l)this.key=o(0,t.Config.keys.length,v?11-e[s.charCodeAt(h++)]:e[s.charCodeAt(h++)]);else if(108==l)this.loopStart=p?e[s.charCodeAt(h++)]:(e[s.charCodeAt(h++)]<<6)+e[s.charCodeAt(h++)];else if(101==l)this.loopLength=p?e[s.charCodeAt(h++)]:(e[s.charCodeAt(h++)]<<6)+e[s.charCodeAt(h++)]+1;else if(116==l)this.tempo=c?[95,120,151,190][e[s.charCodeAt(h++)]]:v?[88,95,103,111,120,130,140,151,163,176,190,206,222,240,259][e[s.charCodeAt(h++)]]:e[s.charCodeAt(h++)]<<6|e[s.charCodeAt(h++)],this.tempo=o(t.Config.tempoMin,t.Config.tempoMax+1,this.tempo);else if(109==l)this.reverb=e[s.charCodeAt(h++)],this.reverb=o(0,t.Config.reverbRange,this.reverb);else if(97==l)this.beatsPerBar=f?[6,7,8,9,10][e[s.charCodeAt(h++)]]:e[s.charCodeAt(h++)]+1,this.beatsPerBar=Math.max(t.Config.beatsPerBarMin,Math.min(t.Config.beatsPerBarMax,this.beatsPerBar));else if(103==l){this.barCount=(e[s.charCodeAt(h++)]<<6)+e[s.charCodeAt(h++)]+1,this.barCount=Math.max(t.Config.barCountMin,Math.min(t.Config.barCountMax,this.barCount));for(let t=0;t<this.getChannelCount();t++){for(let s=this.channels[t].bars.length;s<this.barCount;s++)this.channels[t].bars[s]=1;this.channels[t].bars.length=this.barCount}}else if(106==l){this.patternsPerChannel=g?e[s.charCodeAt(h++)]+1:(e[s.charCodeAt(h++)]<<6)+e[s.charCodeAt(h++)]+1,this.patternsPerChannel=Math.max(1,Math.min(t.Config.barCountMax,this.patternsPerChannel));for(let t=0;t<this.getChannelCount();t++){for(let s=this.channels[t].patterns.length;s<this.patternsPerChannel;s++)this.channels[t].patterns[s]=new a;this.channels[t].patterns.length=this.patternsPerChannel}}else if(105==l){this.instrumentsPerChannel=e[s.charCodeAt(h++)]+1,this.instrumentsPerChannel=Math.max(t.Config.instrumentsPerChannelMin,Math.min(t.Config.instrumentsPerChannelMax,this.instrumentsPerChannel));for(let t=0;t<this.getChannelCount();t++){const s=t>=this.pitchChannelCount;for(let e=this.channels[t].instruments.length;e<this.instrumentsPerChannel;e++)this.channels[t].instruments[e]=new u(s);if(this.channels[t].instruments.length=this.instrumentsPerChannel,M)for(let e=0;e<this.instrumentsPerChannel;e++)this.channels[t].instruments[e].setTypeAndReset(s?2:0,s)}}else if(114==l)this.rhythm=e[s.charCodeAt(h++)];else if(111==l)if(f)d=e[s.charCodeAt(h++)],this.channels[d].octave=o(0,t.Config.scrollableOctaves+1,e[s.charCodeAt(h++)]);else for(d=0;d<this.getChannelCount();d++)this.channels[d].octave=o(0,t.Config.scrollableOctaves+1,e[s.charCodeAt(h++)]);else if(84==l){++y>=this.instrumentsPerChannel&&(w++,y=0);const t=this.channels[w].instruments[y],i=o(0,7,e[s.charCodeAt(h++)]);t.setTypeAndReset(i,w>=this.pitchChannelCount)}else if(117==l){const t=e[s.charCodeAt(h++)]<<6|e[s.charCodeAt(h++)];this.channels[w].instruments[y].preset=t}else if(119==l)if(f){const i=[1,2,3,4,5,6,7,8,0];d=e[s.charCodeAt(h++)],this.channels[d].instruments[0].chipWave=o(0,t.Config.chipWaves.length,0|i[e[s.charCodeAt(h++)]])}else if(M){const i=[1,2,3,4,5,6,7,8,0];for(d=0;d<this.getChannelCount();d++)for(let n=0;n<this.instrumentsPerChannel;n++)d>=this.pitchChannelCount?this.channels[d].instruments[n].chipNoise=o(0,t.Config.chipNoises.length,e[s.charCodeAt(h++)]):this.channels[d].instruments[n].chipWave=o(0,t.Config.chipWaves.length,0|i[e[s.charCodeAt(h++)]])}else if(v){const i=[1,2,3,4,5,6,7,8,0];w>=this.pitchChannelCount?this.channels[w].instruments[y].chipNoise=o(0,t.Config.chipNoises.length,e[s.charCodeAt(h++)]):this.channels[w].instruments[y].chipWave=o(0,t.Config.chipWaves.length,0|i[e[s.charCodeAt(h++)]])}else w>=this.pitchChannelCount?this.channels[w].instruments[y].chipNoise=o(0,t.Config.chipNoises.length,e[s.charCodeAt(h++)]):this.channels[w].instruments[y].chipWave=o(0,t.Config.chipWaves.length,e[s.charCodeAt(h++)]);else if(102==l)if(v){const t=[10,6,3,0,8,5,2],i=[1,1,1,1,18,19,20],n=["none","bright","medium","soft","decay bright","decay medium","decay soft"];if(f){d=e[s.charCodeAt(h++)];const r=this.channels[d].instruments[0],a=[1,3,4,5][o(0,n.length,e[s.charCodeAt(h++)])];r.filterCutoff=t[a],r.filterEnvelope=i[a],r.filterResonance=0}else if(M)for(d=0;d<this.getChannelCount();d++)for(let r=0;r<this.instrumentsPerChannel;r++){const a=this.channels[d].instruments[r];if(d<this.pitchChannelCount){const r=o(0,n.length,e[s.charCodeAt(h++)]+1);a.filterCutoff=t[r],a.filterEnvelope=i[r],a.filterResonance=0}else a.filterCutoff=10,a.filterEnvelope=1,a.filterResonance=0}else{const r=o(0,n.length,e[s.charCodeAt(h++)]),a=this.channels[w].instruments[y];a.filterCutoff=t[r],a.filterEnvelope=i[r],a.filterResonance=0}}else{this.channels[w].instruments[y].filterCutoff=o(0,t.Config.filterCutoffRange,e[s.charCodeAt(h++)])}else if(121==l)this.channels[w].instruments[y].filterResonance=o(0,t.Config.filterResonanceRange,e[s.charCodeAt(h++)]);else if(122==l){const i=this.channels[w].instruments[y];if(4==i.type)for(let n=0;n<t.Config.drumCount;n++)i.drumsetEnvelopes[n]=o(0,t.Config.envelopes.length,e[s.charCodeAt(h++)]);else i.filterEnvelope=o(0,t.Config.envelopes.length,e[s.charCodeAt(h++)])}else if(87==l){const i=this.channels[w].instruments[y];i.pulseWidth=o(0,t.Config.pulseWidthRange,e[s.charCodeAt(h++)]),i.pulseEnvelope=o(0,t.Config.envelopes.length,e[s.charCodeAt(h++)])}else if(100==l)if(f)d=e[s.charCodeAt(h++)],this.channels[d].instruments[0].transition=o(0,t.Config.transitions.length,e[s.charCodeAt(h++)]);else if(M)for(d=0;d<this.getChannelCount();d++)for(let i=0;i<this.instrumentsPerChannel;i++)this.channels[d].instruments[i].transition=o(0,t.Config.transitions.length,e[s.charCodeAt(h++)]);else this.channels[w].instruments[y].transition=o(0,t.Config.transitions.length,e[s.charCodeAt(h++)]);else if(99==l)if(f){const t=[0,3,2,0],i=[1,1,1,13];d=e[s.charCodeAt(h++)];const n=o(0,t.length,e[s.charCodeAt(h++)]),r=this.channels[d].instruments[0];r.vibrato=t[n],r.filterEnvelope=1==r.filterEnvelope?i[n]:r.filterEnvelope}else if(M){const t=[0,1,2,3,0,0],i=[1,1,1,1,16,13];for(d=0;d<this.getChannelCount();d++)for(let n=0;n<this.instrumentsPerChannel;n++){const r=o(0,t.length,e[s.charCodeAt(h++)]),a=this.channels[d].instruments[n];a.vibrato=t[r],a.filterEnvelope=1==a.filterEnvelope?i[r]:a.filterEnvelope}}else if(v){const t=[0,1,2,3,0,0],i=[1,1,1,1,16,13],n=o(0,t.length,e[s.charCodeAt(h++)]),r=this.channels[w].instruments[y];r.vibrato=t[n],r.filterEnvelope=1==r.filterEnvelope?i[n]:r.filterEnvelope}else{const i=o(0,t.Config.vibratos.length,e[s.charCodeAt(h++)]);this.channels[w].instruments[y].vibrato=i}else if(104==l)if(f)d=e[s.charCodeAt(h++)],this.channels[d].instruments[0].interval=o(0,t.Config.intervals.length,e[s.charCodeAt(h++)]);else if(M)for(d=0;d<this.getChannelCount();d++)for(let i=0;i<this.instrumentsPerChannel;i++){const n=e[s.charCodeAt(h++)];let r=o(0,t.Config.intervals.length,n);8==n&&(r=2,this.channels[d].instruments[i].chord=3),this.channels[d].instruments[i].interval=r}else if(v){const i=e[s.charCodeAt(h++)];let n=o(0,t.Config.intervals.length,i);8==i&&(n=2,this.channels[w].instruments[y].chord=3),this.channels[w].instruments[y].interval=n}else this.channels[w].instruments[y].interval=o(0,t.Config.intervals.length,e[s.charCodeAt(h++)]);else if(67==l)this.channels[w].instruments[y].chord=o(0,t.Config.chords.length,e[s.charCodeAt(h++)]);else if(113==l)this.channels[w].instruments[y].effects=o(0,t.Config.effectsNames.length,e[s.charCodeAt(h++)]);else if(118==l)if(f){d=e[s.charCodeAt(h++)];const i=this.channels[d].instruments[0];i.volume=o(0,t.Config.volumeRange,e[s.charCodeAt(h++)]),5==i.volume&&(i.volume=t.Config.volumeRange-1)}else if(M)for(d=0;d<this.getChannelCount();d++)for(let i=0;i<this.instrumentsPerChannel;i++){const n=this.channels[d].instruments[i];n.volume=o(0,t.Config.volumeRange,e[s.charCodeAt(h++)]),5==n.volume&&(n.volume=t.Config.volumeRange-1)}else if(v){const i=this.channels[w].instruments[y];i.volume=o(0,t.Config.volumeRange,e[s.charCodeAt(h++)]),5==i.volume&&(i.volume=t.Config.volumeRange-1)}else{this.channels[w].instruments[y].volume=o(0,t.Config.volumeRange,e[s.charCodeAt(h++)])}else if(65==l)this.channels[w].instruments[y].algorithm=o(0,t.Config.algorithms.length,e[s.charCodeAt(h++)]);else if(70==l)this.channels[w].instruments[y].feedbackType=o(0,t.Config.feedbacks.length,e[s.charCodeAt(h++)]);else if(66==l)this.channels[w].instruments[y].feedbackAmplitude=o(0,t.Config.operatorAmplitudeMax+1,e[s.charCodeAt(h++)]);else if(86==l)this.channels[w].instruments[y].feedbackEnvelope=o(0,t.Config.envelopes.length,e[s.charCodeAt(h++)]);else if(81==l)for(let i=0;i<t.Config.operatorCount;i++)this.channels[w].instruments[y].operators[i].frequency=o(0,t.Config.operatorFrequencies.length,e[s.charCodeAt(h++)]);else if(80==l)for(let i=0;i<t.Config.operatorCount;i++)this.channels[w].instruments[y].operators[i].amplitude=o(0,t.Config.operatorAmplitudeMax+1,e[s.charCodeAt(h++)]);else if(69==l)for(let i=0;i<t.Config.operatorCount;i++)this.channels[w].instruments[y].operators[i].envelope=o(0,t.Config.envelopes.length,e[s.charCodeAt(h++)]);else if(83==l){const e=this.channels[w].instruments[y];if(3==e.type){const n=Math.ceil(t.Config.spectrumControlPoints*t.Config.spectrumControlPointBits/6),o=new i(s,h,h+n);for(let s=0;s<t.Config.spectrumControlPoints;s++)e.spectrumWave.spectrum[s]=o.read(t.Config.spectrumControlPointBits);e.spectrumWave.markCustomWaveDirty(),h+=n}else{if(4!=e.type)throw new Error("Unhandled instrument type for spectrum song tag code.");{const n=Math.ceil(t.Config.drumCount*t.Config.spectrumControlPoints*t.Config.spectrumControlPointBits/6),o=new i(s,h,h+n);for(let s=0;s<t.Config.drumCount;s++){for(let i=0;i<t.Config.spectrumControlPoints;i++)e.drumsetSpectrumWaves[s].spectrum[i]=o.read(t.Config.spectrumControlPointBits);e.drumsetSpectrumWaves[s].markCustomWaveDirty()}h+=n}}}else if(72==l){const e=this.channels[w].instruments[y],n=Math.ceil(t.Config.harmonicsControlPoints*t.Config.harmonicsControlPointBits/6),o=new i(s,h,h+n);for(let s=0;s<t.Config.harmonicsControlPoints;s++)e.harmonicsWave.harmonics[s]=o.read(t.Config.harmonicsControlPointBits);e.harmonicsWave.markCustomWaveDirty(),h+=n}else if(98==l){let t;if(f){d=e[s.charCodeAt(h++)];const n=e[s.charCodeAt(h++)];t=Math.ceil(.5*n);const o=new i(s,h,h+t);for(let t=0;t<n;t++)this.channels[d].bars[t]=o.read(3)+1}else if(p){let e=0;for(;1<<e<this.patternsPerChannel;)e++;t=Math.ceil(this.getChannelCount()*this.barCount*e/6);const n=new i(s,h,h+t);for(d=0;d<this.getChannelCount();d++)for(let t=0;t<this.barCount;t++)this.channels[d].bars[t]=n.read(e)+1}else{let e=0;for(;1<<e<this.patternsPerChannel+1;)e++;t=Math.ceil(this.getChannelCount()*this.barCount*e/6);const n=new i(s,h,h+t);for(d=0;d<this.getChannelCount();d++)for(let t=0;t<this.barCount;t++)this.channels[d].bars[t]=n.read(e)}h+=t}else if(112==l){let o=0;if(f)d=e[s.charCodeAt(h++)],h++,o=e[s.charCodeAt(h++)],o<<=6,o+=e[s.charCodeAt(h++)];else{d=0;let t=e[s.charCodeAt(h++)];for(;t>0;)o<<=6,o+=e[s.charCodeAt(h++)],t--}const a=new i(s,h,h+o);h+=o;let l=0;for(;1<<l<this.instrumentsPerChannel;)l++;for(;;){const s=this.getChannelIsNoise(d),e=s?0:12*this.channels[d].octave;let i=null,h=null,o=(s?4:12)+e;const c=s?[4,6,7,2,3,8,0,10]:[12,19,24,31,36,7,0],u=[];for(let t=0;t<c.length;t++)c[t]+=e;for(let s=0;s<this.patternsPerChannel;s++){const e=this.channels[d].patterns[s];if(e.reset(),e.instrument=a.read(l),!f&&0==a.read(1))continue;let m=0;const p=e.notes;for(;m<this.beatsPerBar*t.Config.partsPerBeat;){const s=1==a.read(1);let e=!1,l=0;if(s?l=a.readLongTail(0,0):e=1==a.read(1),s||e){let e,f,d;if(s)e=u[l],u.splice(l,1);else{for((e={}).pitchCount=1;e.pitchCount<4&&1==a.read(1);)e.pitchCount++;e.pinCount=a.readPinCount(),e.initialVolume=a.read(2),e.pins=[],e.length=0,e.bendCount=0;for(let s=0;s<e.pinCount;s++)(f={}).pitchBend=1==a.read(1),f.pitchBend&&e.bendCount++,e.length+=v?a.readLegacyPartDuration()*t.Config.partsPerBeat/t.Config.rhythms[this.rhythm].stepsPerBeat:a.readPartDuration(),f.time=e.length,f.volume=a.read(2),e.pins.push(f)}u.unshift(e),u.length>10&&u.pop(),(i=new r(0,m,m+e.length,e.initialVolume)).pitches=[],i.pins.length=1;const M=[];for(let t=0;t<e.pitchCount+e.bendCount;t++){if(1==a.read(1)){const t=a.read(3);d=c[t],c.splice(t,1)}else{const t=a.readPitchInterval();d=o;let s=t;for(;s>0;){for(d++;-1!=c.indexOf(d);)d++;s--}for(;s<0;){for(d--;-1!=c.indexOf(d);)d--;s++}}c.unshift(d),c.length>8&&c.pop(),t<e.pitchCount?i.pitches.push(d):M.push(d),o=t==e.pitchCount-1?i.pitches[0]:d}M.unshift(i.pitches[0]);for(const t of e.pins)t.pitchBend&&M.shift(),h=n(M[0]-i.pitches[0],t.time,t.volume),i.pins.push(h);m=i.end,p.push(i)}else{m+=v?a.readLegacyPartDuration()*t.Config.partsPerBeat/t.Config.rhythms[this.rhythm].stepsPerBeat:a.readPartDuration()}}}if(f)break;if(++d>=this.getChannelCount())break}}}}toJsonObject(s=!0,e=1,i=!0){const h=[];for(let n=0;n<this.getChannelCount();n++){const o=[],r=this.getChannelIsNoise(n);for(let t=0;t<this.instrumentsPerChannel;t++)o.push(this.channels[n].instruments[t].toJsonObject());const a=[];for(const s of this.channels[n].patterns){const e=[];for(const i of s.notes){const s=[];for(const e of i.pins)s.push({tick:(e.time+i.start)*t.Config.rhythms[this.rhythm].stepsPerBeat/t.Config.partsPerBeat,pitchBend:e.interval,volume:Math.round(100*e.volume/3)});e.push({pitches:i.pitches,points:s})}a.push({instrument:s.instrument+1,notes:e})}const l=[];if(s)for(let t=0;t<this.loopStart;t++)l.push(this.channels[n].bars[t]);for(let t=0;t<e;t++)for(let t=this.loopStart;t<this.loopStart+this.loopLength;t++)l.push(this.channels[n].bars[t]);if(i)for(let t=this.loopStart+this.loopLength;t<this.barCount;t++)l.push(this.channels[n].bars[t]);h.push({type:r?"drum":"pitch",octaveScrollBar:this.channels[n].octave,instruments:o,patterns:a,sequence:l})}return{format:d.k,version:d.g,scale:t.Config.scales[this.scale].name,key:t.Config.keys[this.key].name,introBars:this.loopStart,loopBars:this.loopLength,beatsPerBar:this.beatsPerBar,ticksPerBeat:t.Config.rhythms[this.rhythm].stepsPerBeat,beatsPerMinute:this.tempo,reverb:this.reverb,channels:h}}fromJsonObject(s){if(this.initToDefault(!0),!s)return;if(this.scale=11,void 0!=s.scale){const e={"romani :)":8,"romani :(":9},i=void 0!=e[s.scale]?e[s.scale]:t.Config.scales.findIndex(t=>t.name==s.scale);-1!=i&&(this.scale=i)}if(void 0!=s.key)if("number"==typeof s.key)this.key=(s.key+1200>>>0)%t.Config.keys.length;else if("string"==typeof s.key){const t=s.key,e=t.charAt(0).toUpperCase(),i=t.charAt(1).toLowerCase();let h={C:0,D:2,E:4,F:5,G:7,A:9,B:11}[e];const n={"#":1,"♯":1,b:-1,"♭":-1}[i];void 0!=h&&(void 0!=n&&(h+=n),h<0&&(h+=12),h%=12,this.key=h)}void 0!=s.beatsPerMinute&&(this.tempo=o(t.Config.tempoMin,t.Config.tempoMax+1,0|s.beatsPerMinute)),void 0!=s.reverb&&(this.reverb=o(0,t.Config.reverbRange,0|s.reverb)),void 0!=s.beatsPerBar&&(this.beatsPerBar=Math.max(t.Config.beatsPerBarMin,Math.min(t.Config.beatsPerBarMax,0|s.beatsPerBar)));let e=4;void 0!=s.ticksPerBeat&&(e=0|s.ticksPerBeat||4,this.rhythm=t.Config.rhythms.findIndex(t=>t.stepsPerBeat==e),-1==this.rhythm&&(this.rhythm=1));let i=1,h=1,l=1;if(s.channels)for(const t of s.channels)t.instruments&&(i=Math.max(i,0|t.instruments.length)),t.patterns&&(h=Math.max(h,0|t.patterns.length)),t.sequence&&(l=Math.max(l,0|t.sequence.length));this.instrumentsPerChannel=i,this.patternsPerChannel=h,this.barCount=l,void 0!=s.introBars&&(this.loopStart=o(0,this.barCount,0|s.introBars)),void 0!=s.loopBars&&(this.loopLength=o(1,this.barCount-this.loopStart+1,0|s.loopBars));const f=[],c=[];if(s.channels)for(let i=0;i<s.channels.length;i++){let h=s.channels[i];const l=new m;let d=!1;(d=void 0!=h.type?"drum"==h.type:i>=3)?c.push(l):f.push(l),void 0!=h.octaveScrollBar&&(l.octave=o(0,t.Config.scrollableOctaves+1,0|h.octaveScrollBar));for(let t=l.instruments.length;t<this.instrumentsPerChannel;t++)l.instruments[t]=new u(d);l.instruments.length=this.instrumentsPerChannel;for(let t=l.patterns.length;t<this.patternsPerChannel;t++)l.patterns[t]=new a;l.patterns.length=this.patternsPerChannel;for(let t=0;t<this.barCount;t++)l.bars[t]=1;l.bars.length=this.barCount;for(let t=0;t<this.instrumentsPerChannel;t++){l.instruments[t].fromJsonObject(h.instruments[t],d)}for(let s=0;s<this.patternsPerChannel;s++){const i=l.patterns[s];let a=void 0;if(h.patterns&&(a=h.patterns[s]),void 0!=a&&(i.instrument=o(0,this.instrumentsPerChannel,(0|a.instrument)-1),a.notes&&a.notes.length>0)){const s=Math.min(this.beatsPerBar*t.Config.partsPerBeat,a.notes.length>>>0);let h=0;for(let o=0;o<a.notes.length&&!(o>=s);o++){const s=a.notes[o];if(!(s&&s.pitches&&s.pitches.length>=1&&s.points&&s.points.length>=2))continue;const l=new r(0,0,0,0);l.pitches=[],l.pins=[];for(let t=0;t<s.pitches.length;t++){const e=0|s.pitches[t];if(-1==l.pitches.indexOf(e)&&(l.pitches.push(e),l.pitches.length>=4))break}if(l.pitches.length<1)continue;let f=h,c=0;for(let i=0;i<s.points.length;i++){const h=s.points[i];if(void 0==h||void 0==h.tick)continue;const o=void 0==h.pitchBend?0:0|h.pitchBend,r=Math.round(+h.tick*t.Config.partsPerBeat/e),a=void 0==h.volume?3:Math.max(0,Math.min(3,Math.round(3*(0|h.volume)/100)));if(!(r>this.beatsPerBar*t.Config.partsPerBeat)){if(0==l.pins.length){if(r<f)continue;l.start=r,c=o}else if(r<=f)continue;f=r,l.pins.push(n(o-c,r-l.start,a))}}if(l.pins.length<2)continue;l.end=l.pins[l.pins.length-1].time+l.start;const u=d?t.Config.drumCount-1:t.Config.maxPitch;let m=u,p=0;for(let t=0;t<l.pitches.length;t++)l.pitches[t]+=c,(l.pitches[t]<0||l.pitches[t]>u)&&(l.pitches.splice(t,1),t--),l.pitches[t]<m&&(m=l.pitches[t]),l.pitches[t]>p&&(p=l.pitches[t]);if(!(l.pitches.length<1)){for(let t=0;t<l.pins.length;t++){const s=l.pins[t];s.interval+m<0&&(s.interval=-m),s.interval+p>u&&(s.interval=u-p),t>=2&&s.interval==l.pins[t-1].interval&&s.interval==l.pins[t-2].interval&&s.volume==l.pins[t-1].volume&&s.volume==l.pins[t-2].volume&&(l.pins.splice(t-1,1),t--)}i.notes.push(l),h=l.end}}}}for(let t=0;t<this.barCount;t++)l.bars[t]=h.sequence?Math.min(this.patternsPerChannel,h.sequence[t]>>>0):0}f.length>t.Config.pitchChannelCountMax&&(f.length=t.Config.pitchChannelCountMax),c.length>t.Config.noiseChannelCountMax&&(c.length=t.Config.noiseChannelCountMax),this.pitchChannelCount=f.length,this.noiseChannelCount=c.length,this.channels.length=0,Array.prototype.push.apply(this.channels,f),Array.prototype.push.apply(this.channels,c)}getPattern(t,s){const e=this.channels[t].bars[s];return 0==e?null:this.channels[t].patterns[e-1]}getPatternInstrument(t,s){const e=this.getPattern(t,s);return null==e?0:e.instrument}getBeatsPerMinute(){return this.tempo}}d.k="BeepBox",d.S=2,d.g=8,t.Song=d;class p{constructor(){this.pitches=[0,0,0,0],this.pitchCount=0,this.chordSize=0,this.drumsetPitch=0,this.note=null,this.prevNote=null,this.nextNote=null,this.prevNotePitchIndex=0,this.nextNotePitchIndex=0,this.active=!1,this.noteStart=0,this.noteEnd=0,this.noteLengthTicks=0,this.ticksSinceReleased=0,this.liveInputSamplesHeld=0,this.lastInterval=0,this.lastVolume=0,this.sample=0,this.phases=[],this.phaseDeltas=[],this.volumeStarts=[],this.volumeDeltas=[],this.volumeStart=0,this.volumeDelta=0,this.phaseDeltaScale=0,this.pulseWidth=0,this.pulseWidthDelta=0,this.filter=0,this.filterScale=0,this.filterSample0=0,this.filterSample1=0,this.vibratoScale=0,this.intervalMult=0,this.intervalVolumeMult=1,this.feedbackOutputs=[],this.feedbackMult=0,this.feedbackDelta=0,this.reset()}reset(){for(let s=0;s<t.Config.operatorCount;s++)this.phases[s]=0,this.feedbackOutputs[s]=0;this.sample=0,this.filterSample0=0,this.filterSample1=0,this.liveInputSamplesHeld=0}}class M{constructor(s=null){this.samplesPerSecond=44100,this.song=null,this.liveInputPressed=!1,this.liveInputPitches=[0],this.liveInputChannel=0,this.loopRepeatCount=-1,this.volume=1,this.playheadInternal=0,this.bar=0,this.beat=0,this.part=0,this.tick=0,this.tickSampleCountdown=0,this.paused=!0,this.tonePool=new t.Deque,this.activeTones=[],this.releasedTones=[],this.liveInputTones=new t.Deque,this.limit=0,this.samplesForChorus=null,this.samplesForChorusReverb=null,this.samplesForReverb=null,this.chorusDelayLine=new Float32Array(1024),this.chorusDelayPos=0,this.chorusPhase=0,this.reverbDelayLine=new Float32Array(16384),this.reverbDelayPos=0,this.reverbFeedback0=0,this.reverbFeedback1=0,this.reverbFeedback2=0,this.reverbFeedback3=0,this.audioCtx=null,this.scriptNode=null,this.audioProcessCallback=(t=>{const s=t.outputBuffer,e=s.getChannelData(0);if(this.paused)for(let t=0;t<s.length;t++)e[t]=0;else this.synthesize(e,s.length)}),null!=s&&this.setSong(s)}static warmUpSynthesizer(t){if(null!=t)for(let s=0;s<t.getChannelCount();s++)for(let e=0;e<t.instrumentsPerChannel;e++)M.getInstrumentSynthFunction(t.channels[s].instruments[e]),t.channels[s].instruments[e].warmUp()}static operatorAmplitudeCurve(t){return(Math.pow(16,t/15)-1)/15}get playing(){return!this.paused}get playhead(){return this.playheadInternal}set playhead(s){if(null!=this.song){this.playheadInternal=Math.max(0,Math.min(this.song.barCount,s));let e=this.playheadInternal;this.bar=Math.floor(e),e=this.song.beatsPerBar*(e-this.bar),this.beat=Math.floor(e),e=t.Config.partsPerBeat*(e-this.beat),this.part=Math.floor(e),e=t.Config.ticksPerPart*(e-this.part),this.tick=Math.floor(e);const i=this.getSamplesPerTick();e=i*(e-this.tick),this.tickSampleCountdown=Math.floor(i-e)}}getSamplesPerBar(){if(null==this.song)throw new Error;return this.getSamplesPerTick()*t.Config.ticksPerPart*t.Config.partsPerBeat*this.song.beatsPerBar}getTotalBars(t,s){if(null==this.song)throw new Error;let e=this.song.loopLength*(this.loopRepeatCount+1);return t&&(e+=this.song.loopStart),s&&(e+=this.song.barCount-(this.song.loopStart+this.song.loopLength)),e}setSong(t){"string"==typeof t?this.song=new d(t):t instanceof d&&(this.song=t)}play(){if(!this.paused)return;this.paused=!1,M.warmUpSynthesizer(this.song);const t=window.AudioContext||window.webkitAudioContext;this.audioCtx=this.audioCtx||new t,this.scriptNode=this.audioCtx.createScriptProcessor?this.audioCtx.createScriptProcessor(2048,0,1):this.audioCtx.createJavaScriptNode(2048,0,1),this.scriptNode.onaudioprocess=this.audioProcessCallback,this.scriptNode.channelCountMode="explicit",this.scriptNode.channelInterpretation="speakers",this.scriptNode.connect(this.audioCtx.destination),this.samplesPerSecond=this.audioCtx.sampleRate}pause(){this.paused||(this.paused=!0,this.scriptNode.disconnect(this.audioCtx.destination),this.audioCtx.close&&this.audioCtx.close(),this.audioCtx=null,this.scriptNode=null)}snapToStart(){this.bar=0,this.snapToBar()}snapToBar(t){void 0!==t&&(this.bar=t),this.playheadInternal=this.bar,this.beat=0,this.part=0,this.tick=0,this.tickSampleCountdown=0,this.reverbDelayPos=0,this.reverbFeedback0=0,this.reverbFeedback1=0,this.reverbFeedback2=0,this.reverbFeedback3=0,this.freeAllTones();for(let t=0;t<this.reverbDelayLine.length;t++)this.reverbDelayLine[t]=0;for(let t=0;t<this.chorusDelayLine.length;t++)this.chorusDelayLine[t]=0}jumpIntoLoop(){if(this.song&&(this.bar<this.song.loopStart||this.bar>=this.song.loopStart+this.song.loopLength)){const t=this.bar;this.bar=this.song.loopStart,this.playheadInternal+=this.bar-t}}nextBar(){if(!this.song)return;const t=this.bar;this.bar++,this.bar>=this.song.barCount&&(this.bar=0),this.playheadInternal+=this.bar-t}prevBar(){if(!this.song)return;const t=this.bar;this.bar--,(this.bar<0||this.bar>=this.song.barCount)&&(this.bar=this.song.barCount-1),this.playheadInternal+=this.bar-t}synthesize(s,e){if(null==this.song){for(let t=0;t<e;t++)s[t]=0;return}const i=this.song.getChannelCount();for(let s=this.activeTones.length;s<i;s++)this.activeTones[s]=new t.Deque,this.releasedTones[s]=new t.Deque;this.activeTones.length=i,this.releasedTones.length=i;const h=this.getSamplesPerTick();let n=0,o=!1;(0==this.tickSampleCountdown||this.tickSampleCountdown>h)&&(this.tickSampleCountdown=h),this.beat>=this.song.beatsPerBar&&(this.bar++,this.beat=0,this.part=0,this.tick=0,this.tickSampleCountdown=h,0!=this.loopRepeatCount&&this.bar==this.song.loopStart+this.song.loopLength&&(this.bar=this.song.loopStart,this.loopRepeatCount>0&&this.loopRepeatCount--)),this.bar>=this.song.barCount&&(this.bar=0,-1!=this.loopRepeatCount&&(o=!0,this.pause())),(null==this.samplesForChorus||this.samplesForChorus.length<e)&&(this.samplesForChorus=new Float32Array(e)),(null==this.samplesForChorusReverb||this.samplesForChorusReverb.length<e)&&(this.samplesForChorusReverb=new Float32Array(e)),(null==this.samplesForReverb||this.samplesForReverb.length<e)&&(this.samplesForReverb=new Float32Array(e));const r=this.samplesForChorus,a=this.samplesForChorusReverb,l=this.samplesForReverb;for(let t=0;t<e;)s[t++]=0,s[t++]=0,s[t++]=0,s[t++]=0,s[t++]=0,s[t++]=0,s[t++]=0,s[t++]=0;const f=+this.volume,c=this.chorusDelayLine,u=this.reverbDelayLine,m=2*Math.PI/(2*this.samplesPerSecond),d=150*this.samplesPerSecond/44100,p=1024-1.51*d,M=1024-2.1*d,v=1024-3.35*d;let g=this.chorusPhase%(2*Math.PI),w=1023&this.chorusDelayPos,y=16383&this.reverbDelayPos,b=+this.reverbFeedback0,S=+this.reverbFeedback1,k=+this.reverbFeedback2,P=+this.reverbFeedback3;const T=.425*Math.pow(this.song.reverb/t.Config.reverbRange,.667),C=1-Math.pow(.5,4/this.samplesPerSecond),O=1-Math.pow(.5,4e3/this.samplesPerSecond);let E=+this.limit;const I=[s,l,r,a];for(;n<e&&!o;){const i=e-n,F=this.tickSampleCountdown<=i?this.tickSampleCountdown:i;for(let s=0;s<this.song.getChannelCount();s++){if(s==this.liveInputChannel){this.determineLiveInputTones(this.song);for(let t=0;t<this.liveInputTones.count();t++){const e=this.liveInputTones.get(t);this.playTone(this.song,n,I,s,h,F,e,!1,!1)}}this.determineCurrentActiveTones(this.song,s);for(let t=0;t<this.activeTones[s].count();t++){const e=this.activeTones[s].get(t);this.playTone(this.song,n,I,s,h,F,e,!1,!1)}for(let e=0;e<this.releasedTones[s].count();e++){const i=this.releasedTones[s].get(e);if(i.ticksSinceReleased>=i.instrument.getTransition().releaseTicks){this.freeReleasedTone(s,e),e--;continue}const o=e+this.activeTones[s].count()>=t.Config.maximumTonesPerChannel;this.playTone(this.song,n,I,s,h,F,i,!0,o)}}let x=w+p-d*Math.sin(g+0),B=w+M-d*Math.sin(g+2.1),A=w+v-d*Math.sin(g+4.2);g+=m*F;const D=(w+F+p-d*Math.sin(g+0)-x)/F,z=(w+F+M-d*Math.sin(g+2.1)-B)/F,W=(w+F+v-d*Math.sin(g+4.2)-A)/F,R=n+F;for(let t=n;t<R;t++){const e=r[t];r[t]=0;const i=a[t];a[t]=0;const h=l[t];l[t]=0;const n=e+i,o=x%1,m=B%1,d=A%1,p=c[1023&x],M=c[x+1&1023],v=c[1023&B],g=c[B+1&1023],I=c[1023&A],F=.5*(n-(p+(M-p)*o)+(v+(g-v)*m)-(I+(c[A+1&1023]-I)*d));c[w]=n,w=w+1&1023,x+=D,B+=z,A+=W;const R=y+3041&16383,U=y+6426&16383,K=y+10907&16383,N=u[y]+h,L=u[R],j=u[U],q=u[K],J=N+i,V=-J+L,G=-J-L,_=-j+q,H=-j-q;b+=.5*((V+_)*T-b),S+=.5*((G+H)*T-S),k+=.5*((V-_)*T-k),P+=.5*((G-H)*T-P),u[R]=b,u[U]=S,u[K]=k,u[y]=P,y=y+1&16383;const Z=s[t]+F+N+L+j+q,Q=Z<0?-Z:Z;E+=(Q-E)*(E<Q?O:C),s[t]=Z/(E>=1?1.05*E:.8*E+.25)*f}if(n+=F,this.tickSampleCountdown-=F,this.tickSampleCountdown<=0){for(let s=0;s<this.song.getChannelCount();s++)for(let e=0;e<this.releasedTones[s].count();e++){this.releasedTones[s].get(e).ticksSinceReleased++,e+this.activeTones[s].count()>=t.Config.maximumTonesPerChannel&&(this.freeReleasedTone(s,e),e--)}if(this.tick++,this.tickSampleCountdown=h,this.tick==t.Config.ticksPerPart){this.tick=0,this.part++;for(let s=0;s<this.song.getChannelCount();s++)for(let e=0;e<this.activeTones[s].count();e++){const i=this.activeTones[s].get(e),h=i.instrument.getTransition();h.isSeamless||null==i.note||i.note.end!=this.part+this.beat*t.Config.partsPerBeat||(h.releases?this.releaseTone(s,i):this.freeTone(i),this.activeTones[s].remove(e),e--)}this.part==t.Config.partsPerBeat&&(this.part=0,this.beat++,this.beat==this.song.beatsPerBar&&(this.beat=0,this.bar++,0!=this.loopRepeatCount&&this.bar==this.song.loopStart+this.song.loopLength&&(this.bar=this.song.loopStart,this.loopRepeatCount>0&&this.loopRepeatCount--),this.bar>=this.song.barCount&&(this.bar=0,-1!=this.loopRepeatCount&&(o=!0,this.pause()))))}}}-1e-24<b&&b<1e-24&&(b=0),-1e-24<S&&S<1e-24&&(S=0),-1e-24<k&&k<1e-24&&(k=0),-1e-24<P&&P<1e-24&&(P=0),-1e-24<E&&E<1e-24&&(E=0),this.chorusPhase=g,this.chorusDelayPos=w,this.reverbDelayPos=y,this.reverbFeedback0=b,this.reverbFeedback1=S,this.reverbFeedback2=k,this.reverbFeedback3=P,this.limit=E,this.playheadInternal=(((this.tick+1-this.tickSampleCountdown/h)/2+this.part)/t.Config.partsPerBeat+this.beat)/this.song.beatsPerBar+this.bar}freeTone(t){this.tonePool.pushBack(t)}newTone(){if(this.tonePool.count()>0){const t=this.tonePool.popBack();return t.reset(),t.active=!1,t}return new p}releaseTone(t,s){this.releasedTones[t].pushFront(s)}freeReleasedTone(t,s){this.freeTone(this.releasedTones[t].get(s)),this.releasedTones[t].remove(s)}freeAllTones(){for(;this.liveInputTones.count()>0;)this.freeTone(this.liveInputTones.popBack());for(let t=0;t<this.activeTones.length;t++)for(;this.activeTones[t].count()>0;)this.freeTone(this.activeTones[t].popBack());for(let t=0;t<this.releasedTones.length;t++)for(;this.releasedTones[t].count()>0;)this.freeTone(this.releasedTones[t].popBack())}determineLiveInputTones(t){if(this.liveInputPressed){const s=t.channels[this.liveInputChannel].instruments[t.getPatternInstrument(this.liveInputChannel,this.bar)];let e;0==this.liveInputTones.count()?(e=this.newTone(),this.liveInputTones.pushBack(e)):s.getTransition().isSeamless||this.liveInputTones.peakFront().pitches[0]==this.liveInputPitches[0]?e=this.liveInputTones.get(0):(this.releaseTone(this.liveInputChannel,this.liveInputTones.popFront()),e=this.newTone(),this.liveInputTones.pushBack(e));for(let t=0;t<this.liveInputPitches.length;t++)e.pitches[t]=this.liveInputPitches[t];e.pitchCount=this.liveInputPitches.length,e.chordSize=1,e.instrument=s,e.note=e.prevNote=e.nextNote=null}else for(;this.liveInputTones.count()>0;)this.releaseTone(this.liveInputChannel,this.liveInputTones.popBack())}determineCurrentActiveTones(s,e){const i=s.channels[e].instruments[s.getPatternInstrument(e,this.bar)],h=s.getPattern(e,this.bar),n=this.part+this.beat*t.Config.partsPerBeat;let o=null,r=null,a=null;if(null!=h)for(let t=0;t<h.notes.length;t++)if(h.notes[t].end<=n)r=h.notes[t];else if(h.notes[t].start<=n&&h.notes[t].end>n)o=h.notes[t];else if(h.notes[t].start>n){a=h.notes[t];break}const l=this.activeTones[e];if(null!=o)null!=r&&r.end!=o.start&&(r=null),null!=a&&a.start!=o.end&&(a=null),this.syncTones(e,l,i,o.pitches,o,r,a,n);else for(;l.count()>0;)l.peakBack().instrument.getTransition().releases?this.releaseTone(e,l.popBack()):this.freeTone(l.popBack())}syncTones(s,e,i,h,n,o,r,a){let l=0;if(i.getChord().arpeggiates){let t;0==e.count()?(t=this.newTone(),e.pushBack(t)):t=e.get(0),l=1;for(let s=0;s<h.length;s++)t.pitches[s]=h[s];t.pitchCount=h.length,t.chordSize=1,t.instrument=i,t.note=n,t.noteStart=n.start,t.noteEnd=n.end,t.prevNote=o,t.nextNote=r,t.prevNotePitchIndex=0,t.nextNotePitchIndex=0}else{const s=i.getTransition();for(let f=0;f<h.length;f++){const h=f*i.getChord().strumParts;let c=o&&o.pitches.length>f?o:null,u=n,m=r&&r.pitches.length>f?r:null,d=u.start+h;if(d>a){if(!(e.count()>f&&s.isSeamless&&null!=c))break;m=u,u=c,c=null,d=u.start+h}let p,M=u.end;s.isSeamless&&null!=m&&(M=Math.min(t.Config.partsPerBeat*this.song.beatsPerBar,M+h)),e.count()>f?p=e.get(f):(p=this.newTone(),e.pushBack(p)),l++,p.pitches[0]=u.pitches[f],p.pitchCount=1,p.chordSize=u.pitches.length,p.instrument=i,p.note=u,p.noteStart=d,p.noteEnd=M,p.prevNote=c,p.nextNote=m,p.prevNotePitchIndex=f,p.nextNotePitchIndex=f}}for(;e.count()>l;)e.peakBack().instrument.getTransition().releases?this.releaseTone(s,e.popBack()):this.freeTone(e.popBack())}playTone(t,s,e,i,h,n,o,r,a){M.computeTone(this,t,i,h,n,o,r,a);const l=e[o.instrument.effects];M.getInstrumentSynthFunction(o.instrument)(this,l,s,n,o,o.instrument)}static computeEnvelope(t,s,e,i){switch(t.type){case 0:return i;case 1:return 1;case 4:return 1/(1+s*t.speed);case 5:return 1-1/(1+s*t.speed);case 6:return.5-.5*Math.cos(2*e*Math.PI*t.speed);case 7:return.75-.25*Math.cos(2*e*Math.PI*t.speed);case 2:return Math.max(1,2-10*s);case 3:const h=t.speed,n=.25/Math.sqrt(h);return s<n?s/n:1/(1+(s-n)*h);case 8:return Math.pow(2,-t.speed*s);default:throw new Error("Unrecognized operator envelope type.")}}static computeChordVolume(t){return 1/(.25*(t-1)+1)}static computeTone(s,e,i,h,n,o,r,a){const l=o.instrument,f=l.getTransition(),c=l.getChord(),m=c.arpeggiates?1:M.computeChordVolume(o.chordSize),d=e.getChannelIsNoise(i),p=d?t.Config.noiseInterval:1,v=t.Config.ticksPerPart*h/s.samplesPerSecond,g=1/t.Config.partsPerBeat,w=o.active,y=s.tickSampleCountdown,b=1-y/h,S=1-(y-n)/h,k=(s.beat*t.Config.partsPerBeat+s.part)*t.Config.ticksPerPart+s.tick,P=k/t.Config.ticksPerPart,T=(k+1)/t.Config.ticksPerPart,C=P+(T-P)*b,O=P+(T-P)*S;o.phaseDeltaScale=0,o.filter=1,o.filterScale=1,o.vibratoScale=0,o.intervalMult=1,o.intervalVolumeMult=1,o.active=!1;let E,I,F,x,B=!0,A=0,D=0,z=0,W=1,R=1,U=m,K=m,N=0,L=0,j=0,q=0;if(3==l.type)d?(I=t.Config.spectrumBasePitch,F=.6):(I=t.Config.keys[e.key].basePitch,F=.3),E=t.Config.spectrumBasePitch,x=28;else if(4==l.type)F=.45,E=I=t.Config.spectrumBasePitch,x=48;else if(2==l.type)F=.19,E=I=t.Config.chipNoises[l.chipNoise].basePitch,x=t.Config.chipNoises[l.chipNoise].isSoft?24:60;else if(1==l.type)I=t.Config.keys[e.key].basePitch,F=.03,E=16,x=48;else if(0==l.type)I=t.Config.keys[e.key].basePitch,F=.03375,E=16,x=48;else if(5==l.type)I=t.Config.keys[e.key].basePitch,F=.025,E=16,x=48;else{if(6!=l.type)throw new Error("Unknown instrument type in computeTone.");I=t.Config.keys[e.key].basePitch,F=.04725,E=16,x=48}for(let s=0;s<t.Config.operatorCount;s++)o.phaseDeltas[s]=0,o.volumeStarts[s]=0,o.volumeDeltas[s]=0;if(r){const s=o.noteLengthTicks+o.ticksSinceReleased,e=o.ticksSinceReleased+b,i=o.ticksSinceReleased+S,h=o.noteLengthTicks+e,n=o.noteLengthTicks+i,r=o.instrument.getTransition();B=!1,A=Math.floor(s/t.Config.ticksPerPart),D=z=o.lastInterval,N=L=M.expressionToVolumeMult(o.lastVolume),W=M.expressionToVolumeMult(3*(1-e/r.releaseTicks)),R=M.expressionToVolumeMult(3*(1-i/r.releaseTicks)),j=h/t.Config.ticksPerPart,q=n/t.Config.ticksPerPart,a&&(W*=1-b,R*=1-S)}else if(null==o.note){W=R=1,N=L=1,o.lastInterval=0,o.lastVolume=3,o.ticksSinceReleased=0,B=!1;const s=o.liveInputSamplesHeld/h;o.liveInputSamplesHeld+=n;const e=o.liveInputSamplesHeld/h;o.noteLengthTicks=e;const i=s/t.Config.ticksPerPart,r=e/t.Config.ticksPerPart;A=Math.floor(i),j=i,q=r}else{const i=o.note,h=o.prevNote,n=o.nextNote,r=s.part+s.beat*t.Config.partsPerBeat,a=t.Config.partsPerBeat*e.beatsPerBar,l=o.noteStart,u=o.noteEnd;let d;for(A=r-l,d=1;d<i.pins.length-1&&!(i.pins[d].time+i.start>r);d++);const p=i.pins[d-1],v=i.pins[d],g=l*t.Config.ticksPerPart,y=u*t.Config.ticksPerPart-g,k=(i.start+p.time)*t.Config.ticksPerPart,C=(i.start+v.time)*t.Config.ticksPerPart;o.lastInterval=i.pins[i.pins.length-1].interval,o.lastVolume=i.pins[i.pins.length-1].volume,o.ticksSinceReleased=0,o.noteLengthTicks=y;const O=r*t.Config.ticksPerPart+s.tick,E=r*t.Config.ticksPerPart+s.tick+1,I=O-g,F=E-g,x=Math.min(1,(O-k)/(C-k)),J=Math.min(1,(E-k)/(C-k));let V=p.volume+(v.volume-p.volume)*x,G=p.volume+(v.volume-p.volume)*J,_=1,H=1,Z=m,Q=m,X=p.interval+(v.interval-p.interval)*x,Y=p.interval+(v.interval-p.interval)*J,$=P-l,tt=T-l;B=O+b-g==0||!w;const st=.5*y;if(f.isSeamless&&!f.slides&&0==i.start)B=!w;else if(f.isSeamless&&null!=h&&(B=!w,f.slides)){const t=Math.min(st,f.slideTicks),s=Math.max(0,1-I/t),e=Math.max(0,1-F/t),n=.5*(h.pitches[o.prevNotePitchIndex]+h.pins[h.pins.length-1].interval-o.pitches[0]),r=.5*(h.pins[h.pins.length-1].volume-i.pins[0].volume),a=.5*(h.end-h.start);if(X+=s*n,Y+=e*n,V+=s*r,G+=e*r,$+=s*a,tt+=e*a,!c.arpeggiates){const t=.5*(h.pitches.length-o.chordSize);Z=M.computeChordVolume(o.chordSize+s*t),Q=M.computeChordVolume(o.chordSize+e*t)}}if(f.isSeamless&&!f.slides&&i.end==a);else if(f.isSeamless&&null!=n){if(f.slides){const t=Math.min(st,f.slideTicks),s=Math.max(0,1-(y-I)/t),e=Math.max(0,1-(y-F)/t),h=.5*(n.pitches[o.nextNotePitchIndex]-(o.pitches[0]+i.pins[i.pins.length-1].interval)),r=.5*(n.pins[0].volume-i.pins[i.pins.length-1].volume),a=.5*-(u-l);if(X+=s*h,Y+=e*h,V+=s*r,G+=e*r,$+=s*a,tt+=e*a,!c.arpeggiates){const t=.5*(n.pitches.length-o.chordSize);Z=M.computeChordVolume(o.chordSize+s*t),Q=M.computeChordVolume(o.chordSize+e*t)}}}else if(!f.releases){const t=f.releaseTicks;t>0&&(_*=Math.min(1,(y-I)/t),H*=Math.min(1,(y-F)/t))}D=X+(Y-X)*b,z=X+(Y-X)*S,N=M.expressionToVolumeMult(V+(G-V)*b),L=M.expressionToVolumeMult(V+(G-V)*S),W=_+(H-_)*b,R=_+(H-_)*S,U=Z+(Q-Z)*b,K=Z+(Q-Z)*S,j=$+(tt-$)*b,q=$+(tt-$)*S}const J=1/s.samplesPerSecond;if(o.active=!0,0==l.type||1==l.type||5==l.type||6==l.type){const s=M.getLFOAmplitude(l,v*C),e=M.getLFOAmplitude(l,v*O),i=A<t.Config.vibratos[l.vibrato].delayParts?0:t.Config.vibratos[l.vibrato].amplitude;D+=i*s,z+=i*e}if(!f.isSeamless||(f.slides||null==o.note||0!=o.note.start)&&null==o.prevNote){const t=f.attackSeconds;t>0&&(W*=Math.min(1,v*j/t),R*=Math.min(1,v*q/t))}const V=M.instrumentVolumeToVolumeMult(l.volume);4==l.type&&(o.drumsetPitch=o.pitches[0],null!=o.note&&(o.drumsetPitch+=o.note.pickMainInterval()),o.drumsetPitch=Math.max(0,Math.min(t.Config.drumCount-1,o.drumsetPitch)));const G=l.getFilterCutoffOctaves(),_=4==l.type?l.getDrumsetEnvelope(o.drumsetPitch):l.getFilterEnvelope(),H=t.Config.filterCutoffMaxHz*Math.pow(2,G),Z=2*Math.sin(Math.PI*H/s.samplesPerSecond),Q=2*Math.sin(Math.PI*t.Config.filterCutoffMinHz/s.samplesPerSecond);o.filter=Z*M.computeEnvelope(_,v*j,g*C,N);let X=Z*M.computeEnvelope(_,v*q,g*O,L);o.filter=Math.min(t.Config.filterMax,Math.max(Q,o.filter)),X=Math.min(t.Config.filterMax,Math.max(Q,X)),o.filterScale=Math.pow(X/o.filter,1/n);let Y=Math.pow(.5,.35*G);if(l.filterResonance>0&&(Y=Math.pow(Y,1.7)*Math.pow(.5,.125*(l.filterResonance-1))),8==_.type?Y*=1.25+.025*_.speed:4==_.type&&(Y*=1+.02*_.speed),B&&o.reset(),1==l.type){let i=1,h=0,r=0;if(o.pitchCount>1&&!c.harmonizes){const i=Math.floor((s.tick+s.part*t.Config.ticksPerPart)/t.Config.rhythms[e.rhythm].ticksPerArpeggio),h=t.Config.rhythms[e.rhythm].arpeggioPatterns[o.pitchCount-1];r=o.pitches[h[i%h.length]]-o.pitches[0]}const a=t.Config.algorithms[l.algorithm].carrierCount;for(let s=0;s<t.Config.operatorCount;s++){const e=t.Config.algorithms[l.algorithm].associatedCarrier[s]-1,f=o.pitches[c.harmonizes?s<o.pitchCount?s:e<o.pitchCount?e:0:0],m=t.Config.operatorFrequencies[l.operators[s].frequency].mult,d=t.Config.operatorCarrierInterval[e]+r,w=I+(f+D)*p+d,y=m*u.frequencyFromPitch(w)+t.Config.operatorFrequencies[l.operators[s].frequency].hzOffset;o.phaseDeltas[s]=y*J*t.Config.sineWaveLength;const b=M.operatorAmplitudeCurve(l.operators[s].amplitude),S=b*t.Config.operatorFrequencies[l.operators[s].frequency].amplitudeSign;let k=S,P=S;if(s<a){const t=I+(f+z)*p+d,s=Math.pow(2,-(w-E)/x),e=Math.pow(2,-(t-E)/x);k*=s,P*=e,h+=b}else k*=1.5*t.Config.sineWaveLength,P*=1.5*t.Config.sineWaveLength,i*=1-Math.min(1,l.operators[s].amplitude/15);const T=t.Config.envelopes[l.operators[s].envelope];k*=M.computeEnvelope(T,v*j,g*C,N),P*=M.computeEnvelope(T,v*q,g*O,L),o.volumeStarts[s]=k,o.volumeDeltas[s]=(P-k)/n}const f=.3*t.Config.sineWaveLength*l.feedbackAmplitude/15,m=t.Config.envelopes[l.feedbackEnvelope];let d=f*M.computeEnvelope(m,v*j,g*C,N),w=f*M.computeEnvelope(m,v*q,g*O,L);o.feedbackMult=d,o.feedbackDelta=(w-o.feedbackMult)/n;const y=F*V;o.volumeStart=Y*y*W*U;const b=Y*y*R*K;o.volumeDelta=(b-o.volumeStart)/n,i*=(Math.pow(2,2-1.4*l.feedbackAmplitude/15)-1)/3,i*=1-Math.min(1,Math.max(0,h-1)/2),o.volumeStart*=1+3*i,o.volumeDelta*=1+3*i}else{let i=o.pitches[0];if(o.pitchCount>1){const h=Math.floor((s.tick+s.part*t.Config.ticksPerPart)/t.Config.rhythms[e.rhythm].ticksPerArpeggio);if(c.harmonizes){const s=t.Config.rhythms[e.rhythm].arpeggioPatterns[o.pitchCount-2],i=o.pitches[1+s[h%s.length]]-o.pitches[0];o.intervalMult=Math.pow(2,i/12),o.intervalVolumeMult=Math.pow(2,-i/x)}else{const s=t.Config.rhythms[e.rhythm].arpeggioPatterns[o.pitchCount-1];i=o.pitches[s[h%s.length]]}}const h=I+(i+D)*p,r=I+(i+z)*p,a=u.frequencyFromPitch(h),f=Math.pow(2,-(h-E)/x),m=Math.pow(2,-(r-E)/x);let d=F*Y;if(2==l.type&&(d*=t.Config.chipNoises[l.chipNoise].volume),0==l.type&&(d*=t.Config.chipWaves[l.chipWave].volume),0!=l.type&&5!=l.type||(d*=t.Config.intervals[l.interval].volume),6==l.type){const s=t.Config.envelopes[l.pulseEnvelope],e=.5*Math.pow(.5,.5*(t.Config.pulseWidthRange-l.pulseWidth-1)),i=e*M.computeEnvelope(s,v*j,g*C,N),h=e*M.computeEnvelope(s,v*q,g*O,L);o.pulseWidth=i,o.pulseWidthDelta=(h-i)/n}o.phaseDeltas[0]=a*J,o.volumeStart=W*U*f*d*V;let w=R*K*m*d*V;0==_.type||6==l.type&&0==t.Config.envelopes[l.pulseEnvelope].type||(o.volumeStart*=N,w*=L),o.volumeDelta=(w-o.volumeStart)/n}o.phaseDeltaScale=Math.pow(2,(z-D)*p/12/n)}static getLFOAmplitude(s,e){let i=0;for(const h of t.Config.vibratos[s.vibrato].periodsSeconds)i+=Math.sin(2*Math.PI*e/h);return i}static getInstrumentSynthFunction(s){if(1==s.type){const e=s.algorithm+"_"+s.feedbackType;if(void 0==M.fmSynthFunctionCache[e]){const i=[];for(const e of M.fmSourceTemplate)if(-1!=e.indexOf("// CARRIER OUTPUTS")){const h=[];for(let e=0;e<t.Config.algorithms[s.algorithm].carrierCount;e++)h.push("operator"+e+"Scaled");i.push(e.replace("/*operator#Scaled*/",h.join(" + ")))}else if(-1!=e.indexOf("// INSERT OPERATOR COMPUTATION HERE"))for(let e=t.Config.operatorCount-1;e>=0;e--)for(const h of M.operatorSourceTemplate)if(-1!=h.indexOf("/* + operator@Scaled*/")){let n="";for(const i of t.Config.algorithms[s.algorithm].modulatedBy[e])n+=" + operator"+(i-1)+"Scaled";const o=t.Config.feedbacks[s.feedbackType].indices[e];if(o.length>0){n+=" + feedbackMult * (";const t=[];for(const s of o)t.push("operator"+(s-1)+"Output");n+=t.join(" + ")+")"}i.push(h.replace(/\#/g,e+"").replace("/* + operator@Scaled*/",n))}else i.push(h.replace(/\#/g,e+""));else if(-1!=e.indexOf("#"))for(let s=0;s<t.Config.operatorCount;s++)i.push(e.replace(/\#/g,s+""));else i.push(e);M.fmSynthFunctionCache[e]=new Function("synth","data","bufferIndex","runLength","tone","instrument",i.join("\n"))}return M.fmSynthFunctionCache[e]}if(0==s.type)return M.chipSynth;if(5==s.type)return M.harmonicsSynth;if(6==s.type)return M.pulseWidthSynth;if(2==s.type)return M.noiseSynth;if(3==s.type)return M.spectrumSynth;if(4==s.type)return M.drumsetSynth;throw new Error("Unrecognized instrument type: "+s.type)}static chipSynth(s,e,i,h,n,o){const r=t.Config.chipWaves[o.chipWave].samples,a=+r.length-1,l=+Math.pow(2,(t.Config.intervals[o.interval].offset+t.Config.intervals[o.interval].spread)/12),f=Math.pow(2,(t.Config.intervals[o.interval].offset-t.Config.intervals[o.interval].spread)/12)*n.intervalMult,c=n.intervalVolumeMult*t.Config.intervals[o.interval].sign;0!=o.interval||o.getChord().customInterval||(n.phases[1]=n.phases[0]);const u=f/l;let m=n.phaseDeltas[0]*l*a,d=m*u;const p=+n.phaseDeltaScale;let M=+n.volumeStart;const v=+n.volumeDelta;let g=n.phases[0]%1*a,w=n.phases[1]%1*a,y=+n.filter,b=o.getFilterIsFirstOrder()?1:y;const S=+n.filterScale,k=o.getFilterIsFirstOrder()?1:S,P=t.Config.filterMaxResonance*Math.pow(Math.max(0,o.getFilterResonance()-1)/(t.Config.filterResonanceRange-2),.5);let T=+n.filterSample0,C=+n.filterSample1;const O=0|g,E=0|w,I=O%a,F=E%a,x=g-O,B=w-E;let A=r[I],D=r[F];A+=(r[I+1]-A)*x,D+=(r[F+1]-D)*B;const z=i+h;for(;i<z;){const t=0|(g+=m),s=0|(w+=d),h=t%a,n=s%a;let o=r[h],l=r[n];const f=g-t,u=w-s;let O=((o+=(r[h+1]-o)*f)-A)/m,E=((l+=(r[n+1]-l)*u)-D)/d;A=o,D=l,C+=b*((T+=y*(O+E*c-T+(P+P/(1-y))*(T-C)))-C),y*=S,b*=k,m*=p,d*=p,e[i]+=C*M,M+=v,i++}n.phases[0]=g/a,n.phases[1]=w/a;-1e-24<T&&T<1e-24&&(T=0),-1e-24<C&&C<1e-24&&(C=0),n.filterSample0=T,n.filterSample1=C}static harmonicsSynth(s,e,i,h,n,o){const r=o.harmonicsWave.getCustomWave(),a=+r.length-1,l=+Math.pow(2,(t.Config.intervals[o.interval].offset+t.Config.intervals[o.interval].spread)/12),f=Math.pow(2,(t.Config.intervals[o.interval].offset-t.Config.intervals[o.interval].spread)/12)*n.intervalMult,c=n.intervalVolumeMult*t.Config.intervals[o.interval].sign;0!=o.interval||o.getChord().customInterval||(n.phases[1]=n.phases[0]);const u=f/l;let m=n.phaseDeltas[0]*l*a,d=m*u;const p=+n.phaseDeltaScale;let M=+n.volumeStart;const v=+n.volumeDelta;let g=n.phases[0]%1*a,w=n.phases[1]%1*a,y=+n.filter,b=o.getFilterIsFirstOrder()?1:y;const S=+n.filterScale,k=o.getFilterIsFirstOrder()?1:S,P=t.Config.filterMaxResonance*Math.pow(Math.max(0,o.getFilterResonance()-1)/(t.Config.filterResonanceRange-2),.5);let T=+n.filterSample0,C=+n.filterSample1;const O=0|g,E=0|w,I=O%a,F=E%a,x=g-O,B=w-E;let A=r[I],D=r[F];A+=(r[I+1]-A)*x,D+=(r[F+1]-D)*B;const z=i+h;for(;i<z;){const t=0|(g+=m),s=0|(w+=d),h=t%a,n=s%a;let o=r[h],l=r[n];const f=g-t,u=w-s;let O=((o+=(r[h+1]-o)*f)-A)/m,E=((l+=(r[n+1]-l)*u)-D)/d;A=o,D=l,C+=b*((T+=y*(O+E*c-T+(P+P/(1-y))*(T-C)))-C),y*=S,b*=k,m*=p,d*=p,e[i]+=C*M,M+=v,i++}n.phases[0]=g/a,n.phases[1]=w/a;-1e-24<T&&T<1e-24&&(T=0),-1e-24<C&&C<1e-24&&(C=0),n.filterSample0=T,n.filterSample1=C}static pulseWidthSynth(s,e,i,h,n,o){let r=n.phaseDeltas[0];const a=+n.phaseDeltaScale;let l=+n.volumeStart;const f=+n.volumeDelta;let c=n.phases[0]%1,u=n.pulseWidth;const m=n.pulseWidthDelta;let d=+n.filter,p=o.getFilterIsFirstOrder()?1:d;const M=+n.filterScale,v=o.getFilterIsFirstOrder()?1:M,g=t.Config.filterMaxResonance*Math.pow(Math.max(0,o.getFilterResonance()-1)/(t.Config.filterResonanceRange-2),.5);let w=+n.filterSample0,y=+n.filterSample1;const b=i+h;for(;i<b;){const t=c%1,s=(c+u)%1;let h=s-t;if(t<r)h+=.5*((S=t/r)+S-S*S-1);else if(t>1-r){h+=.5*((S=(t-1)/r)+S+S*S+1)}if(s<r)h-=.5*((S=s/r)+S-S*S-1);else if(s>1-r){var S;h-=.5*((S=(s-1)/r)+S+S*S+1)}y+=p*((w+=d*(h-w+(g+g/(1-d))*(w-y)))-y),d*=M,p*=v,c+=r,r*=a,u+=m,e[i]+=y*l,l+=f,i++}n.phases[0]=c;-1e-24<w&&w<1e-24&&(w=0),-1e-24<y&&y<1e-24&&(y=0),n.filterSample0=w,n.filterSample1=y}static noiseSynth(s,e,i,h,n,o){let r=o.getDrumWave(),a=+n.phaseDeltas[0];const l=+n.phaseDeltaScale;let f=+n.volumeStart;const c=+n.volumeDelta;let u=n.phases[0]%1*t.Config.chipNoiseLength;0==n.phases[0]&&(u=Math.random()*t.Config.chipNoiseLength);let m=+n.sample,d=+n.filter,p=o.getFilterIsFirstOrder()?1:d;const M=+n.filterScale,v=o.getFilterIsFirstOrder()?1:M,g=t.Config.filterMaxResonance*Math.pow(Math.max(0,o.getFilterResonance()-1)/(t.Config.filterResonanceRange-2),.5);let w=+n.filterSample0,y=+n.filterSample1;const b=Math.min(1,n.phaseDeltas[0]*t.Config.chipNoises[o.chipNoise].pitchFilterMult),S=i+h;for(;i<S;){y+=p*((w+=d*((m+=(r[32767&u]-m)*b)-w+(g+g/(1-d))*(w-y)))-y),u+=a,d*=M,p*=v,a*=l,e[i]+=y*f,f+=c,i++}n.phases[0]=u/t.Config.chipNoiseLength,n.sample=m;-1e-24<w&&w<1e-24&&(w=0),-1e-24<y&&y<1e-24&&(y=0),n.filterSample0=w,n.filterSample1=y}static spectrumSynth(s,e,i,h,n,o){let r=o.getDrumWave(),a=128*n.phaseDeltas[0];const l=+n.phaseDeltaScale;let f=+n.volumeStart;const c=+n.volumeDelta;let u=+n.sample,m=+n.filter,d=o.getFilterIsFirstOrder()?1:m;const p=+n.filterScale,v=o.getFilterIsFirstOrder()?1:p,g=t.Config.filterMaxResonance*Math.pow(Math.max(0,o.getFilterResonance()-1)/(t.Config.filterResonanceRange-2),.5);let w=+n.filterSample0,y=+n.filterSample1,b=n.phases[0]%1*t.Config.chipNoiseLength;0==n.phases[0]&&(b=M.findRandomZeroCrossing(r)+a);const S=Math.min(1,a),k=i+h;for(;i<k;){const t=0|b,s=32767&t;let h=r[s];const n=b-t;y+=d*((w+=m*((u+=((h+=(r[s+1]-h)*n)-u)*S)-w+(g+g/(1-m))*(w-y)))-y),b+=a,m*=p,d*=v,a*=l,e[i]+=y*f,f+=c,i++}n.phases[0]=b/t.Config.chipNoiseLength,n.sample=u;-1e-24<w&&w<1e-24&&(w=0),-1e-24<y&&y<1e-24&&(y=0),n.filterSample0=w,n.filterSample1=y}static drumsetSynth(s,e,i,h,n,o){let r=o.getDrumsetWave(n.drumsetPitch),a=n.phaseDeltas[0]/u.drumsetIndexReferenceDelta(n.drumsetPitch);const l=+n.phaseDeltaScale;let f=+n.volumeStart;const c=+n.volumeDelta;let m=+n.sample,d=+n.filter,p=o.getFilterIsFirstOrder()?1:d;const v=+n.filterScale,g=o.getFilterIsFirstOrder()?1:v,w=t.Config.filterMaxResonance*Math.pow(Math.max(0,o.getFilterResonance()-1)/(t.Config.filterResonanceRange-2),.5);let y=+n.filterSample0,b=+n.filterSample1,S=n.phases[0]%1*t.Config.chipNoiseLength;0==n.phases[0]&&(S=M.findRandomZeroCrossing(r)+a);const k=i+h;for(;i<k;){const t=0|S,s=32767&t;m=r[s];const h=S-t;b+=p*((y+=d*((m+=(r[s+1]-m)*h)-y+(w+w/(1-d))*(y-b)))-b),S+=a,d*=v,p*=g,a*=l,e[i]+=b*f,f+=c,i++}n.phases[0]=S/t.Config.chipNoiseLength,n.sample=m;-1e-24<y&&y<1e-24&&(y=0),-1e-24<b&&b<1e-24&&(b=0),n.filterSample0=y,n.filterSample1=b}static findRandomZeroCrossing(s){let e=Math.random()*t.Config.chipNoiseLength,i=32767&e,h=s[i];for(let n=128;n>0;n--){const n=i+16&32767,o=s[n];if(h*o<=0){for(let n=0;n<16;n++){const n=i+1&32767,o=s[n];if(h*o<=0){const s=o-h;e=i,Math.abs(s)>1e-8&&(e+=-h/s),e=Math.max(0,e)%t.Config.chipNoiseLength;break}i=n,h=o}break}i=n,h=o}return e}static instrumentVolumeToVolumeMult(s){return s==t.Config.volumeRange-1?0:Math.pow(2,t.Config.volumeLogScale*s)}static volumeMultToInstrumentVolume(s){return s<=0?t.Config.volumeRange-1:Math.min(t.Config.volumeRange-2,Math.log(s)/Math.LN2/t.Config.volumeLogScale)}static expressionToVolumeMult(t){return Math.pow(Math.max(0,t)/3,1.5)}static volumeMultToExpression(t){return 3*Math.pow(Math.max(0,t),1/1.5)}getSamplesPerTick(){if(null==this.song)return 0;const s=this.song.getBeatsPerMinute()/60*t.Config.partsPerBeat*t.Config.ticksPerPart;return Math.floor(this.samplesPerSecond/s)}}M.fmSynthFunctionCache={},M.fmSourceTemplate=("\n\t\t\tvar sineWave = beepbox.Config.sineWave;\n\t\t\t\n\t\t\tvar phaseDeltaScale = +tone.phaseDeltaScale;\n\t\t\t// I'm adding 1000 to the phase to ensure that it's never negative even when modulated by other waves because negative numbers don't work with the modulus operator very well.\n\t\t\tvar operator#Phase = +((tone.phases[#] % 1) + 1000) * beepbox.Config.sineWaveLength;\n\t\t\tvar operator#PhaseDelta = +tone.phaseDeltas[#];\n\t\t\tvar operator#OutputMult = +tone.volumeStarts[#];\n\t\t\tvar operator#OutputDelta = +tone.volumeDeltas[#];\n\t\t\tvar operator#Output = +tone.feedbackOutputs[#];\n\t\t\tvar feedbackMult = +tone.feedbackMult;\n\t\t\tvar feedbackDelta = +tone.feedbackDelta;\n\t\t\tvar volume = +tone.volumeStart;\n\t\t\tvar volumeDelta = +tone.volumeDelta;\n\t\t\t\n\t\t\tvar filter1 = +tone.filter;\n\t\t\tvar filter2 = instrument.getFilterIsFirstOrder() ? 1.0 : filter1;\n\t\t\tvar filterScale1 = +tone.filterScale;\n\t\t\tvar filterScale2 = instrument.getFilterIsFirstOrder() ? 1.0 : filterScale1;\n\t\t\tvar filterResonance = beepbox.Config.filterMaxResonance * Math.pow(Math.max(0, instrument.getFilterResonance() - 1) / (beepbox.Config.filterResonanceRange - 2), 0.5);\n\t\t\tvar filterSample0 = +tone.filterSample0;\n\t\t\tvar filterSample1 = +tone.filterSample1;\n\t\t\t\n\t\t\tvar stopIndex = bufferIndex + runLength;\n\t\t\twhile (bufferIndex < stopIndex) {\n\t\t\t\t// INSERT OPERATOR COMPUTATION HERE\n\t\t\t\tvar fmOutput = (/*operator#Scaled*/); // CARRIER OUTPUTS\n\t\t\t\t\n\t\t\t\tvar feedback = filterResonance + filterResonance / (1.0 - filter1);\n\t\t\t\tfilterSample0 += filter1 * (fmOutput - filterSample0 + feedback * (filterSample0 - filterSample1));\n\t\t\t\tfilterSample1 += filter2 * (filterSample0 - filterSample1);\n\t\t\t\t\n\t\t\t\tfeedbackMult += feedbackDelta;\n\t\t\t\toperator#OutputMult += operator#OutputDelta;\n\t\t\t\toperator#Phase += operator#PhaseDelta;\n\t\t\t\toperator#PhaseDelta *= phaseDeltaScale;\n\t\t\t\tfilter1 *= filterScale1;\n\t\t\t\tfilter2 *= filterScale2;\n\t\t\t\t\n\t\t\t\tdata[bufferIndex] += filterSample1 * volume;\n\t\t\t\tvolume += volumeDelta;\n\t\t\t\tbufferIndex++;\n\t\t\t}\n\t\t\t\n\t\t\ttone.phases[#] = operator#Phase / "+t.Config.sineWaveLength+";\n\t\t\ttone.feedbackOutputs[#] = operator#Output;\n\t\t\t\n\t\t\tvar epsilon = (1.0e-24);\n\t\t\tif (-epsilon < filterSample0 && filterSample0 < epsilon) filterSample0 = 0.0;\n\t\t\tif (-epsilon < filterSample1 && filterSample1 < epsilon) filterSample1 = 0.0;\n\t\t\ttone.filterSample0 = filterSample0;\n\t\t\ttone.filterSample1 = filterSample1;\n\t\t").split("\n"),M.operatorSourceTemplate=("\n\t\t\t\tvar operator#PhaseMix = operator#Phase/* + operator@Scaled*/;\n\t\t\t\tvar operator#PhaseInt = operator#PhaseMix|0;\n\t\t\t\tvar operator#Index = operator#PhaseInt & "+t.Config.sineWaveMask+";\n\t\t\t\tvar operator#Sample = sineWave[operator#Index];\n\t\t\t\toperator#Output = operator#Sample + (sineWave[operator#Index + 1] - operator#Sample) * (operator#PhaseMix - operator#PhaseInt);\n\t\t\t\tvar operator#Scaled = operator#OutputMult * operator#Output;\n\t\t").split("\n"),t.Synth=M}(beepbox||(beepbox={}));