0?Math.round(0|s.volume):Math.max(0,Math.min(f,Math.round((0|s.volume)*f/100))),c>e.beatsPerBar*d.partsPerBeat||(0==h.pins.length&&(h.start=c,l=r),h.pins.push(Ft(r-l,c-h.start,p)))}if(h.pins.length<2)continue;h.end=h.pins[h.pins.length-1].time+h.start;const c=s?d.drumCount-1:d.maxPitch;let p=c,m=0;for(let t=0;tc)&&(h.pitches.splice(t,1),t--),h.pitches[t]m&&(m=h.pitches[t]);if(!(h.pitches.length<1)){for(let t=0;tc&&(e.interval=c-m),t>=2&&e.interval==h.pins[t-1].interval&&e.interval==h.pins[t-2].interval&&e.size==h.pins[t-1].size&&e.size==h.pins[t-2].size&&(h.pins.splice(t-1,1),t--)}0==h.start?h.continuesLastPattern=!0===a.continuesLastPattern:h.continuesLastPattern=!1,this.notes.push(h)}}}}}class Et{constructor(t){this.frequency=4,this.amplitude=0,this.waveform=0,this.pulseWidth=.5,this.reset(t)}reset(t){this.frequency=4,this.amplitude=t<=1?d.operatorAmplitudeMax:0,this.waveform=0,this.pulseWidth=5}copy(t){this.frequency=t.frequency,this.amplitude=t.amplitude,this.waveform=t.waveform,this.pulseWidth=t.pulseWidth}}class Tt{constructor(){this.name="",this.carrierCount=0,this.modulatedBy=[[],[],[],[],[],[]],this.associatedCarrier=[],this.fromPreset(1)}set(t,e){this.reset(),this.carrierCount=t;for(let n=0;nt-1&&(this.associatedCarrier[e[n][i]-1]=n+1),this.name+=",";this.name+=n=25;this.spectrum[e]=t?Math.max(0,Math.round(d.spectrumMax*(1-e/30))):0}this.markCustomWaveDirty()}markCustomWaveDirty(){const t=jt.fittingPowerOfTwo(d.spectrumMax+2)-1;let e=0;for(const n of this.spectrum)e=e*t+n>>>0;this.hash=e}}class Bt{constructor(){this.wave=null,this.ft=-1}getCustomWave(t,e){if(this.ft==t.hash)return this.wave;this.ft=t.hash;const n=d.spectrumNoiseLength;null!=this.wave&&this.wave.length==n+1||(this.wave=new Float32Array(n+1));const i=this.wave;for(let t=0;t=d.spectrumControlPoints?t.spectrum[d.spectrumControlPoints-1]:t.spectrum[e],h=o(e-1);let l=o(e);e>=d.spectrumControlPoints&&(l=14+.25*(l-14)),0==s&&0==r||(a+=.02*y(i,n,h,l,s/d.spectrumMax,r/d.spectrumMax,-.5))}return t.spectrum[d.spectrumControlPoints-1]>0&&(a+=.02*y(i,n,14+.25*(o(d.spectrumControlPoints)-14),14,t.spectrum[d.spectrumControlPoints-1]/d.spectrumMax,0,-.5)),at(i,n),st(i,5/(Math.sqrt(n)*Math.pow(a,.75))),i[n]=i[0],i}}class It{constructor(){this.harmonics=[],this.hash=-1,this.reset()}reset(){for(let t=0;t>>0;this.hash=e}}class Lt{constructor(){this.wave=null,this.ft=-1}getCustomWave(t,e){if(this.ft==t.hash&&this.yt==e)return this.wave;this.ft=t.hash,this.yt=e;const n=7==e?d.harmonicsRenderedForPickedString:d.harmonicsRendered,i=d.harmonicsWavelength,s=f(0,null,null);null!=this.wave&&this.wave.length==i+1||(this.wave=new Float32Array(i+1));const o=this.wave;for(let t=0;t=d.harmonicsControlPoints&&(h*=1-(e-d.harmonicsControlPoints)/(n-d.harmonicsControlPoints));const l=h/d.harmonicsMax;let c=Math.pow(2,h-d.harmonicsMax+1)*Math.sqrt(l);e=1?e:t}convertLegacySettings(t,e,n){this.reset();const i=2*Math.asin(.475),s=e>1,o=0==e,a=10==t,r=3==n.type||4==n.type||8==n.type||0==n.type,h=48e3,l=8e3*Math.pow(2,.5*(t-10)),c=Math.min(i,2*Math.PI*l/h);if(1==n.type&&!s&&a);else if(o){const t=3.5,e=c*Math.pow(2,t),n=h*(e/(1+e/Math.PI))/(2*Math.PI),i=qt.getRoundedSettingValueFromHz(n),s=qt.getHzFromSettingValue(i),o=2*Math.PI*s/h,a=new lt;a.lowPass1stOrderSimplified(c);const l=new ct;l.analyze(a,o);const d=l.magnitude();let p=Math.log2(d);p=.82*(p+t)-t,r&&(p=Math.min(p,-1));const m=Math.pow(2,p),u=qt.getRoundedSettingValueFromLinearGain(m);this.addPoint(0,i,u)}else{const t=.5/(1-.95*Math.sqrt(Math.max(0,e-1)/6)),n=.5/t,i=c+(c*(c/(2*Math.PI*8e3/h)*Math.pow(n,.9)+1)-c)*n;let o;o=r?h*Math.min(i,c*Math.pow(2,.25))/(2*Math.PI):h*i/(2*Math.PI);const a=qt.getRoundedSettingValueFromHz(o);let l;if(r)l=t;else{const e=new lt;e.lowPass2ndOrderSimplified(c,t);const n=new ct;n.analyze(e,i),l=n.magnitude()}s||(l=Math.min(l,Math.sqrt(.5)));const d=qt.getRoundedSettingValueFromLinearGain(l);this.addPoint(0,a,d)}this.controlPoints.length=this.controlPointCount}convertLegacySettingsForSynth(t,e,n=!1){this.reset();const i=2*Math.asin(.475),s=0==e&&n,o=48e3,a=8e3*Math.pow(2,.5*(t-10)),r=Math.min(i,2*Math.PI*a/o);if(s){const t=3.5,e=r*Math.pow(2,t),n=o*(e/(1+e/Math.PI))/(2*Math.PI),i=qt.getRoundedSettingValueFromHz(n),s=qt.getHzFromSettingValue(i),a=2*Math.PI*s/o,h=new lt;h.lowPass1stOrderSimplified(r);const l=new ct;l.analyze(h,a);const c=l.magnitude();let d=Math.log2(c);d=.82*(d+t)-t;const p=Math.pow(2,d),m=qt.getRoundedSettingValueFromLinearGain(p);this.addPoint(0,i,m)}else{const t=.5/(1-.95*Math.sqrt(Math.max(0,e-1)/6)),n=.5/t,i=r+(r*(r/(2*Math.PI*8e3/o)*Math.pow(n,.9)+1)-r)*n;let s;s=o*i/(2*Math.PI);const a=qt.getSettingValueFromHz(s);let h;const l=new lt;l.lowPass2ndOrderSimplified(r,t);const c=new ct;c.analyze(l,i),h=c.magnitude();const d=qt.getRoundedSettingValueFromLinearGain(h);this.addPoint(0,a,d)}}}class Nt{constructor(){this.target=0,this.index=0,this.envelope=0,this.reset()}reset(){this.target=0,this.index=0,this.envelope=0}toJsonObject(){const t={target:d.instrumentAutomationTargets[this.target].name,envelope:d.envelopes[this.envelope].name};return d.instrumentAutomationTargets[this.target].maxCount>1&&(t.index=this.index),t}fromJsonObject(t){this.reset();let e=d.instrumentAutomationTargets.dictionary[t.target];null==e&&(e=d.instrumentAutomationTargets.dictionary.noteVolume),this.target=e.index;let n=d.envelopes.dictionary[t.envelope];null==n&&(n=d.envelopes.dictionary.none),this.envelope=n.index,null!=t.index?this.index=mt(0,d.instrumentAutomationTargets[this.target].maxCount,0|t.index):this.index=0}}class Rt{constructor(t,e){if(this.type=0,this.preset=0,this.chipWave=2,this.isUsingAdvancedLoopControls=!1,this.chipWaveLoopStart=0,this.chipWaveLoopEnd=d.rawRawChipWaves[this.chipWave].samples.length-1,this.chipWaveLoopMode=0,this.chipWavePlayBackwards=!1,this.chipWaveStartOffset=0,this.chipNoise=1,this.eqFilter=new zt,this.eqFilterType=!1,this.eqFilterSimpleCut=d.filterSimpleCutRange-1,this.eqFilterSimplePeak=0,this.noteFilter=new zt,this.noteFilterType=!1,this.noteFilterSimpleCut=d.filterSimpleCutRange-1,this.noteFilterSimplePeak=0,this.eqSubFilters=[],this.noteSubFilters=[],this.envelopes=[],this.fadeIn=0,this.fadeOut=d.fadeOutNeutral,this.envelopeCount=0,this.transition=d.transitions.dictionary.normal.index,this.pitchShift=0,this.detune=0,this.vibrato=0,this.interval=0,this.vibratoDepth=0,this.vibratoSpeed=10,this.vibratoDelay=0,this.vibratoType=0,this.unison=0,this.unisonVoices=1,this.unisonSpread=0,this.unisonOffset=0,this.unisonExpression=1.4,this.unisonSign=1,this.effects=0,this.chord=1,this.volume=0,this.pan=d.panCenter,this.panDelay=10,this.arpeggioSpeed=12,this.fastTwoNoteArp=!1,this.legacyTieOver=!1,this.clicklessTransition=!1,this.aliases=!1,this.pulseWidth=d.pulseWidthRange,this.decimalOffset=0,this.stringSustain=10,this.distortion=0,this.bitcrusherFreq=0,this.bitcrusherQuantization=0,this.chorus=0,this.reverb=0,this.echoSustain=0,this.echoDelay=0,this.algorithm=0,this.feedbackType=0,this.algorithm6Op=1,this.feedbackType6Op=1,this.customAlgorithm=new Tt,this.customFeedbackType=new Pt,this.feedbackAmplitude=0,this.LFOtime=0,this.nextLFOtime=0,this.arpTime=0,this.customChipWave=new Float32Array(64),this.customChipWaveIntegral=new Float32Array(65),this.operators=[],this.harmonicsWave=new It,this.drumsetEnvelopes=[],this.drumsetSpectrumWaves=[],this.modChannels=[],this.modInstruments=[],this.modulators=[],this.modFilterTypes=[],this.invalidModulators=[],e)for(let t=0;t>>0),null!=t.volume?this.volume=mt(-d.volumeRange/2,d.volumeRange/2+1,0|t.volume):this.volume=0,Array.isArray(t.effects)){let e=0;for(let n=0;ne.name==t.wave)),"pink noise"==t.wave&&(this.chipNoise=d.chipNoises.findIndex((t=>"pink"==t.name))),"brownian noise"==t.wave&&(this.chipNoise=d.chipNoises.findIndex((t=>"brownian"==t.name))),-1==this.chipNoise&&(this.chipNoise=1));const c={custom:"note size",steady:"none","pluck 1":"twang 1","pluck 2":"twang 2","pluck 3":"twang 3"},p=t=>null!=c[t]?d.envelopes.dictionary[c[t]]:d.envelopes.dictionary[t];if(4==this.type&&null!=t.drums)for(let e=0;et.name==r));-1!=t&&(this.chipWave=t)}-1==this.chipWave&&(this.chipWave=1)}if(1==this.type||10==this.type){1==this.type?(this.algorithm=d.algorithms.findIndex((e=>e.name==t.algorithm)),-1==this.algorithm&&(this.algorithm=0),this.feedbackType=d.feedbacks.findIndex((e=>e.name==t.feedbackType)),-1==this.feedbackType&&(this.feedbackType=0)):(this.algorithm6Op=d.algorithms6Op.findIndex((e=>e.name==t.algorithm)),-1==this.algorithm6Op&&(this.algorithm6Op=1),0==this.algorithm6Op?this.customAlgorithm.set(t.customAlgorithm.carrierCount,t.customAlgorithm.mods):this.customAlgorithm.fromPreset(this.algorithm6Op),this.feedbackType6Op=d.feedbacks6Op.findIndex((e=>e.name==t.feedbackType)),-1==this.feedbackType6Op&&(this.feedbackType6Op=1),0==this.feedbackType6Op?this.customFeedbackType.set(t.customFeedback.mods):this.customFeedbackType.fromPreset(this.feedbackType6Op)),null!=t.feedbackAmplitude?this.feedbackAmplitude=mt(0,d.operatorAmplitudeMax+1,0|t.feedbackAmplitude):this.feedbackAmplitude=0;for(let e=0;et.name==i.frequency)),-1==n.frequency&&(n.frequency=0),null!=i.amplitude?n.amplitude=mt(0,d.operatorAmplitudeMax+1,0|i.amplitude):n.amplitude=0,null!=i.waveform?(n.waveform=d.operatorWaves.findIndex((t=>t.name==i.waveform)),-1==n.waveform&&("square"==i.waveform?(n.waveform=d.operatorWaves.dictionary["pulse width"].index,n.pulseWidth=5):n.waveform=0)):n.waveform=0,null!=i.pulseWidth?n.pulseWidth=0|i.pulseWidth:n.pulseWidth=5}}else if(8==this.type){if(t.customChipWave){for(let e=0;e<64;e++)this.customChipWave[e]=t.customChipWave[e];let e=0;for(let t=0;t=d.maxEnvelopeCount);t++){const n=new Nt;n.fromJsonObject(e[t]),this.addEnvelope(n.target,n.index,n.envelope)}}}0===a&&(null!=t.isUsingAdvancedLoopControls?(this.isUsingAdvancedLoopControls=t.isUsingAdvancedLoopControls,this.chipWaveLoopStart=t.chipWaveLoopStart,this.chipWaveLoopEnd=t.chipWaveLoopEnd,this.chipWaveLoopMode=t.chipWaveLoopMode,this.chipWavePlayBackwards=t.chipWavePlayBackwards,this.chipWaveStartOffset=t.chipWaveStartOffset):(this.isUsingAdvancedLoopControls=!1,this.chipWaveLoopStart=0,this.chipWaveLoopEnd=d.rawRawChipWaves[this.chipWave].samples.length-1,this.chipWaveLoopMode=0,this.chipWavePlayBackwards=!1,this.chipWaveStartOffset=0))}static frequencyFromPitch(t){return 440*Math.pow(2,(t-69)/12)}addEnvelope(t,e,n){let i=!1;if(this.supportsEnvelopeTarget(t,e)||(i=!0),this.envelopeCount>=d.maxEnvelopeCount)throw new Error;for(;this.envelopes.length<=this.envelopeCount;)this.envelopes[this.envelopes.length]=new Nt;const s=this.envelopes[this.envelopeCount];s.target=i?d.instrumentAutomationTargets.dictionary.none.index:t,s.index=i?0:e,s.envelope=n,this.envelopeCount++}supportsEnvelopeTarget(t,e){const n=d.instrumentAutomationTargets[t];if(e>=n.maxCount)return!1;if(null!=n.compatibleInstruments&&-1==n.compatibleInstruments.indexOf(this.type))return!1;if(null!=n.effect&&0==(this.effects&1<=t)return!1}return!0}clearInvalidEnvelopeTargets(){for(let t=0;t{if(t&&null!=e&&null!=n&&null!=i){i=d.modCount-i-1;let t=d.modulators[this.channels[e].instruments[n].modulators[i]].newNoteVol,s=d.modulators.dictionary.tempo.index;return this.channels[e].instruments[n].modulators[i]==s&&(t=this.tempo-d.modulators[s].convertRealFactor),null!=t?t:6}return 6},this.getVolumeCap=(t,e,n,i)=>{if(t&&null!=e&&null!=n&&null!=i){i=d.modCount-i-1;let t=this.channels[e].instruments[n],s=d.modulators[t.modulators[i]],o=s.maxRawVol;return null!=o?("eq filter"!=s.name&&"note filter"!=s.name||(o=d.filterMorphCount-1,t.modFilterTypes[i]>0&&t.modFilterTypes[i]%2?o=d.filterFreqRange:t.modFilterTypes[i]>0&&(o=d.filterGainRange)),o):6}return 6},this.getVolumeCapForSetting=(t,e,n)=>{if(t){let t=d.modulators[e].maxRawVol;return null!=t?(null==n||"eq filter"!=d.modulators[e].name&&"note filter"!=d.modulators[e].name||(t=d.filterMorphCount-1,n>0&&n%2?t=d.filterFreqRange:n>0&&(t=d.filterGainRange)),t):d.noteSizeMax}return d.noteSizeMax},null!=t?this.fromBase64String(t):this.initToDefault(!0)}getChannelCount(){return this.pitchChannelCount+this.noiseChannelCount+this.modChannelCount}getMaxInstrumentsPerChannel(){return Math.max(this.layeredInstruments?d.layeredInstrumentCountMax:d.instrumentCountMin,this.patternInstruments?d.patternInstrumentCountMax:d.instrumentCountMin)}getMaxInstrumentsPerPattern(t){return this.getMaxInstrumentsPerPatternForChannel(this.channels[t])}getMaxInstrumentsPerPatternForChannel(t){return this.layeredInstruments?Math.min(d.layeredInstrumentCountMax,t.instruments.length):1}getChannelIsNoise(t){return t>=this.pitchChannelCount&&t=this.pitchChannelCount+this.noiseChannelCount}initToDefault(t=!0){if(this.scale=0,this.scaleCustom=[!0,!1,!1,!1,!1,!1,!1,!1,!1,!1,!1,!1],this.key=0,this.octave=0,this.loopStart=0,this.loopLength=4,this.tempo=120,this.reverb=0,this.beatsPerBar=8,this.barCount=16,this.patternsPerChannel=8,this.rhythm=3,this.layeredInstruments=!1,this.patternInstruments=!1,this.title="Untitled",document.title=q.versionDisplayName,t){this.pitchChannelCount=3,this.noiseChannelCount=1,this.modChannelCount=0;for(let t=0;t=this.pitchChannelCount&&t=this.pitchChannelCount+this.noiseChannelCount;this.channels.length<=t&&(this.channels[t]=new Ot);const i=this.channels[t];i.octave=Math.max(3-t,0);for(let t=0;t>6],xt[63&n.length]);for(let t=0;t>6],xt[63&this.loopStart]),e.push(101,xt[this.loopLength-1>>6],xt[this.loopLength-1&63]),e.push(116,xt[this.tempo>>6],xt[63&this.tempo]),e.push(97,xt[this.beatsPerBar-1]),e.push(103,xt[this.barCount-1>>6],xt[this.barCount-1&63]),e.push(106,xt[this.patternsPerChannel-1>>6],xt[this.patternsPerChannel-1&63]),e.push(114,xt[this.rhythm]),e.push(79),1!=this.compressionRatio||1!=this.limitRatio||4e3!=this.limitRise||4!=this.limitDecay||1!=this.limitThreshold||1!=this.compressionThreshold||1!=this.masterGain?(e.push(xt[Math.round(this.compressionRatio<1?10*this.compressionRatio:10+60*(this.compressionRatio-1))]),e.push(xt[Math.round(this.limitRatio<1?10*this.limitRatio:9+this.limitRatio)]),e.push(xt[this.limitDecay]),e.push(xt[Math.round((this.limitRise-2e3)/250)]),e.push(xt[Math.round(20*this.compressionThreshold)]),e.push(xt[Math.round(20*this.limitThreshold)]),e.push(xt[Math.round(50*this.masterGain)>>6],xt[63&Math.round(50*this.masterGain)])):e.push(xt[63]),e.push(85);for(let t=0;t>6],xt[63&s.length]);for(let t=0;t>6],xt[i.volume+d.volumeRange/2&63]),e.push(117,xt[i.preset>>6],xt[63&i.preset]),e.push(102),e.push(xt[+i.eqFilterType]),i.eqFilterType)e.push(xt[i.eqFilterSimpleCut]),e.push(xt[i.eqFilterSimplePeak]);else{if(null==i.eqFilter)e.push(xt[0]),console.log("Null EQ filter settings detected in toBase64String for channelIndex "+t+", instrumentIndex "+n);else{e.push(xt[i.eqFilter.controlPointCount]);for(let t=0;t>6],xt[63&s]);for(let t=0;t>6],xt[63&i.effects]),C(i.effects))if(e.push(xt[+i.noteFilterType]),i.noteFilterType)e.push(xt[i.noteFilterSimpleCut]),e.push(xt[i.noteFilterSimplePeak]);else{if(null==i.noteFilter)e.push(xt[0]),console.log("Null note filter settings detected in toBase64String for channelIndex "+t+", instrumentIndex "+n);else{e.push(xt[i.noteFilter.controlPointCount]);for(let t=0;t>6],xt[63&s]);for(let t=0;t>6],xt[i.detune-d.detuneMin&63]),F(i.effects)&&(e.push(xt[i.vibrato]),i.vibrato==d.vibratos.length&&(e.push(xt[Math.round(25*i.vibratoDepth)]),e.push(xt[i.vibratoSpeed]),e.push(xt[Math.round(i.vibratoDelay)]),e.push(xt[i.vibratoType]))),A(i.effects)&&(e.push(xt[i.distortion]),e.push(xt[+i.aliases])),E(i.effects)&&e.push(xt[i.bitcrusherFreq],xt[i.bitcrusherQuantization]),T(i.effects)&&(e.push(xt[i.pan>>6],xt[63&i.pan]),e.push(xt[i.panDelay])),P(i.effects)&&e.push(xt[i.chorus]),D(i.effects)&&e.push(xt[i.echoSustain],xt[i.echoDelay]),B(i.effects)&&e.push(xt[i.reverb]),4!=i.type&&(e.push(100,xt[i.fadeIn],xt[i.fadeOut]),e.push(xt[+i.clicklessTransition])),5==i.type||7==i.type){e.push(72);const t=new St;for(let e=0;e186?(e.push(119,xt[i.chipWave-186]),e.push(xt[3])):i.chipWave>124?(e.push(119,xt[i.chipWave-124]),e.push(xt[2])):i.chipWave>62?(e.push(119,xt[i.chipWave-62]),e.push(xt[1])):(e.push(119,xt[i.chipWave]),e.push(xt[0])),e.push(104,xt[i.unison]),i.unison==d.unisons.length&&wt(e,i.unisonVoices,i.unisonSpread,i.unisonOffset,i.unisonExpression,i.unisonSign),e.push(121);const t=mt(0,32,i.chipWaveLoopMode)<<1|(i.isUsingAdvancedLoopControls?1:0);e.push(xt[t]);const n=mt(0,32,0)<<1|(i.chipWavePlayBackwards?1:0);e.push(xt[n]),bt(e,i.chipWaveLoopStart),bt(e,i.chipWaveLoopEnd),bt(e,i.chipWaveStartOffset)}else if(1==i.type||10==i.type){if(1==i.type)e.push(65,xt[i.algorithm]),e.push(70,xt[i.feedbackType]);else{if(e.push(65,xt[i.algorithm6Op]),0==i.algorithm6Op){e.push(67,xt[i.customAlgorithm.carrierCount]),e.push(113);for(let t=0;t186?(e.push(119,xt[i.chipWave-186]),e.push(xt[3])):i.chipWave>124?(e.push(119,xt[i.chipWave-124]),e.push(xt[2])):i.chipWave>62?(e.push(119,xt[i.chipWave-62]),e.push(xt[1])):(e.push(119,xt[i.chipWave]),e.push(xt[0])),e.push(104,xt[i.unison]),i.unison==d.unisons.length&&wt(e,i.unisonVoices,i.unisonSpread,i.unisonOffset,i.unisonExpression,i.unisonSign),e.push(77);for(let t=0;t<64;t++)e.push(xt[i.customChipWave[t]+24])}else if(2==i.type)e.push(119,xt[i.chipNoise]);else if(3==i.type){e.push(83);const t=new St;for(let e=0;e>6],xt[63&i.decimalOffset]);else if(7==i.type)e.push(104,xt[i.unison]),i.unison==d.unisons.length&&wt(e,i.unisonVoices,i.unisonSpread,i.unisonOffset,i.unisonExpression,i.unisonSign),e.push(73,xt[i.stringSustain]);else if(9!=i.type)throw new Error("Unknown instrument type.");e.push(69,xt[i.envelopeCount]);for(let t=0;t1&&e.push(xt[i.envelopes[t].index]),e.push(xt[i.envelopes[t].envelope])}e.push(98),t=new St;let o=0;for(;1<0){t.write(1,1);let n=0;for(const i of e.notes){i.startn&&(t.write(2,0),o&&t.write(1,0),t.writePartDuration(i.start-n)),a.clear(),1==i.pitches.length?a.write(1,0):(a.write(1,1),a.write(3,i.pitches.length-2)),a.writePinCount(i.pins.length-1),o?a.write(9,i.pins[0].size):a.write(r,i.pins[0].size);let e=0,s=i.pitches[0],h=s;const l=[];for(let t=1;t10&&u.pop();const f=i.pitches.concat(l);for(let e=0;e16&&m.pop(),p=e==i.pitches.length-1?i.pitches[0]:n}0==i.start&&t.write(1,i.continuesLastPattern?1:0),n=i.end}n0;)l.unshift(xt[63&h]),h>>=6;e.push(xt[l.length]),Array.prototype.push.apply(e,l),t.encodeBase64(e);const c=64e3;let p="";if(null!=q.customSamples&&q.customSamples.length>0&&(p="|"+q.customSamples.join("|")),e.length$t.xt||p<$t.kt))return;if(r&&(-1==p||p>$t.Mt||p<$t.St))return;if(h&&(-1==p||p>$t.Ft||p<$t.Ct))return;if(l&&(-1==p||p>$t.gt||p<$t.At))return;const m=p<2,u=p<3,f=p<4,y=p<5,b=p<6,g=p<7,w=p<8,I=p<9;this.initToDefault(o&&I||r&&y||f&&h);const L=o&&I||r&&y;let z=!1;if(l||h){var N=(t=t.replaceAll("%7C","|")).split("|");if(t=N.shift(),null==q.customSamples||q.customSamples.join(", ")!=N.join(", ")){$t.Et();let t=!1,e=!1,n=!1;const o=[],r=[];i.statusTable={},i.urlTable={},i.totalSamples=0,i.samplesLoaded=0,a.dispatchEvent(new s(i.totalSamples,i.samplesLoaded));for(const s of N)if("legacysamples"===s.toLowerCase())t||(t=!0,o.push(s),c(0));else if("nintariboxsamples"===s.toLowerCase())e||(e=!0,o.push(s),c(1));else if("mariopaintboxsamples"===s.toLowerCase())n||(n=!0,o.push(s),c(2));else{const t=u;if(!$t.Tt(s,o,r,i,t))continue}if(o.length>0&&(q.customSamples=o),r.length>0){const t=v(r);q.presetCategories[q.presetCategories.length]={name:"Custom Sample Presets",presets:t,index:q.presetCategories.length}}}}if(u&&o){for(const t of this.channels)t.instruments[0].transition=d.transitions.dictionary.interrupt.index,t.instruments[0].effects|=1024;this.channels[3].instruments[0].chipNoise=0}let R=null;if(o&&I||r&&y||f&&h){R=[];for(let t=R.length;t1;for(let t=0;t=this.pitchChannelCount&&t=this.pitchChannelCount+this.noiseChannelCount;for(let s=this.channels[t].instruments.length;s=2&&(_=!0))}break;case 111:if(u&&o){const n=kt[t.charCodeAt(e++)];this.channels[n].octave=mt(0,d.pitchOctaves,kt[t.charCodeAt(e++)]+1),n>=this.pitchChannelCount&&(this.channels[n].octave=0)}else if(I&&o||r&&y||f&&h)for(let n=0;n=this.pitchChannelCount&&(this.channels[n].octave=0);else{for(let n=0;n=this.channels[H].instruments.length&&(H++,V=0),ut(0,this.channels.length-1,H);const n=this.channels[H].instruments[V];let i=ut(0,10,kt[t.charCodeAt(e++)]);(r&&y||f&&h)&&(7==i?i=8:8==i&&(i=9)),n.setTypeAndReset(i,H>=this.pitchChannelCount&&H=this.pitchChannelCount+this.noiseChannelCount),!(g&&o||m&&r)||0!=i&&8!=i&&6!=i||(n.aliases=!0,n.distortion=0,n.effects|=8),G&&(n.arpeggioSpeed=9),_&&(n.fastTwoNoteArp=!0),g&&o&&(n.effects=0,n.chord!=d.chords.dictionary.simultaneous.index&&(n.effects|=2048))}break;case 117:{const n=kt[t.charCodeAt(e++)]<<6|kt[t.charCodeAt(e++)];this.channels[H].instruments[V].preset=n,(r&&y||f&&h)&&7==this.channels[H].instruments[V].preset&&(this.channels[H].instruments[V].preset=8)}break;case 119:if(u&&o){const n=[1,2,3,4,5,6,7,8,0],i=kt[t.charCodeAt(e++)],s=this.channels[i].instruments[0];s.chipWave=mt(0,d.chipWaves.length,0|n[kt[t.charCodeAt(e++)]]),s.convertLegacySettings(R[i][0],L)}else if(b&&o){const n=[1,2,3,4,5,6,7,8,0];for(let i=0;i=this.pitchChannelCount?s.chipNoise=mt(0,d.chipNoises.length,kt[t.charCodeAt(e++)]):s.chipWave=mt(0,d.chipWaves.length,0|n[kt[t.charCodeAt(e++)]])}else if(g&&o){const n=[1,2,3,4,5,6,7,8,0];H>=this.pitchChannelCount?this.channels[H].instruments[V].chipNoise=mt(0,d.chipNoises.length,kt[t.charCodeAt(e++)]):this.channels[H].instruments[V].chipWave=mt(0,d.chipWaves.length,0|n[kt[t.charCodeAt(e++)]])}else if(2==this.channels[H].instruments[V].type)this.channels[H].instruments[V].chipNoise=mt(0,d.chipNoises.length,kt[t.charCodeAt(e++)]);else if(l){const n=kt[t.charCodeAt(e++)],i=kt[t.charCodeAt(e++)];this.channels[H].instruments[V].chipWave=mt(0,d.chipWaves.length,3==i?n+186:2==i?n+124:1==i?n+62:n)}else this.channels[H].instruments[V].chipWave=mt(0,d.chipWaves.length,kt[t.charCodeAt(e++)]);break;case 120:if(h&&!f&&b){const n=kt[t.charCodeAt(e++)];n+62>85&&"legacysamples"!=document.URL.substring(document.URL.length-13).toLowerCase()&&(z||(z=!0,d.willReloadForCustomSamples=!0,q.customSamples=["legacySamples"],c(0))),this.channels[H].instruments[V].chipWave=n+62>78?mt(0,d.chipWaves.length,n+63):n+62>67?mt(0,d.chipWaves.length,n+61):n+62==67?40:mt(0,d.chipWaves.length,n+62)}break;case 102:if(I&&o||y&&r||f&&h)if(g&&o){const n=[10,6,3,0,8,5,2],i=["none","none","none","none","decay 1","decay 2","decay 3"];if(u&&o){const s=kt[t.charCodeAt(e++)],o=this.channels[s].instruments[0],a=R[s][0],r=[1,3,4,5][mt(0,n.length,kt[t.charCodeAt(e++)])];a.filterCutoff=n[r],a.filterResonance=0,a.filterEnvelope=d.envelopes.dictionary[i[r]],o.convertLegacySettings(a,L)}else if(b&&o)for(let s=0;s>1,o=kt[t.charCodeAt(e++)],a=Boolean(1&o),r=gt(t,e);e+=6;const h=gt(t,e);e+=6;const l=gt(t,e);e+=6;const c=this.channels[H].instruments[V];c.isUsingAdvancedLoopControls=i,c.chipWaveLoopStart=r,c.chipWaveLoopEnd=h,c.chipWaveLoopMode=s,c.chipWavePlayBackwards=a,c.chipWaveStartOffset=l}else if(h&&!f&&b)"legacysamples"!=document.URL.substring(document.URL.length-13).toLowerCase()&&(z||(z=!0,d.willReloadForCustomSamples=!0,q.customSamples=["legacySamples"],c(0))),this.channels[H].instruments[V].chipWave=mt(0,d.chipWaves.length,kt[t.charCodeAt(e++)]+125);else if(I&&o||r&&y||f&&h){const n=8,i=this.channels[H].instruments[V],s=R[H][V];s.filterResonance=mt(0,n,kt[t.charCodeAt(e++)]),i.convertLegacySettings(s,L)}break;case 122:{const n=this.channels[H].instruments[V],i=[0,1,2,4,5,6,8,9,10,12,13,14,16,17,18,19,20,21,23,24,25,27,28,29,32,33,34,31,11];if(I&&o||y&&r||f&&h)if(4==n.type)for(let s=0;s0&&(s.legacyTieOver=!0),s.clicklessTransition=!!kt[t.charCodeAt(e++)],(s.transition!=d.transitions.dictionary.normal.index||s.clicklessTransition)&&(s.effects|=1024)}}else{const n=this.channels[H].instruments[V];n.fadeIn=mt(0,d.fadeInRange,kt[t.charCodeAt(e++)]),n.fadeOut=mt(0,d.fadeOutTicks.length,kt[t.charCodeAt(e++)]),(r||h||l)&&(n.clicklessTransition=!!kt[t.charCodeAt(e++)])}break;case 99:if(I&&o||r&&y||f&&h)if(g&&o)if(u&&o){const n=[0,3,2,0],i=["none","none","none","tremolo2"],s=kt[t.charCodeAt(e++)],o=mt(0,n.length,kt[t.charCodeAt(e++)]),a=this.channels[s].instruments[0],r=R[s][0];a.vibrato=n[o],null!=r.filterEnvelope&&1!=r.filterEnvelope.type||(r.filterEnvelope=d.envelopes.dictionary[i[o]],a.convertLegacySettings(r,L)),a.vibrato!=d.vibratos.dictionary.none.index&&(a.effects|=512)}else if(b&&o){const n=[0,1,2,3,0,0],i=["none","none","none","none","tremolo5","tremolo2"];for(let s=0;s1&&(o=mt(0,a,kt[t.charCodeAt(e++)]));let r=kt[t.charCodeAt(e++)];(m&&h||!h&&!l)&&(r=n[r]);const c=mt(0,d.envelopes.length,r);i.addEnvelope(s,o,c)}}}break;case 82:{const n=this.channels[H].instruments[V];if(u&&h)for(let i=0;i0;)i<<=6,i+=kt[t.charCodeAt(e++)],s--}const p=new Mt(t,e,e+i);e+=i;const m=$t.getNeededBits(d.noteSizeMax);let b=-1,w=-1,v=-1;for(;;){const t=this.channels[n],e=this.getChannelIsNoise(n),i=this.getChannelIsMod(n),x=this.getMaxInstrumentsPerPattern(n),k=$t.getNeededBits(x-d.instrumentCountMin),M=$t.getNeededBits(t.instruments.length-1);if(i){let e=y&&r||f&&h;const i=e?M:$t.getNeededBits(this.getMaxInstrumentsPerChannel()+2);for(let s=0;s=0){let e=C(this.channels[o.modChannels[t]].instruments[o.modInstruments[t]].effects);7==o.modulators[t]?(o.modulators[t]=e?d.modulators.dictionary["note filt cut"].index:d.modulators.dictionary["eq filt cut"].index,o.modFilterTypes[t]=1):8==o.modulators[t]&&(o.modulators[t]=e?d.modulators.dictionary["note filt peak"].index:d.modulators.dictionary["eq filt peak"].index,o.modFilterTypes[t]=2)}else e&&o.modulators[t]==d.modulators.dictionary["song reverb"].index&&(b=n,w=s,v=t);e&&12!=d.modulators[o.modulators[t]].associatedEffect&&(this.channels[o.modChannels[t]].instruments[o.modInstruments[t]].effects|=1<10&&T.pop(),w.length<=v?(k=new Ct(0,b,b+u.length,u.initialSize),w[v++]=k):(k=w[v++],k.start=b,k.end=b+u.length,k.pins[0].size=u.initialSize);let F=0;const C=[];for(let t=0;t0;){for(M++;-1!=E.indexOf(M);)M++;t--}for(;t<0;){for(M--;-1!=E.indexOf(M);)M--;t++}}E.unshift(M),E.length>c&&E.pop(),t=this.getChannelCount())break}if((r&&y||f&&h)&&v>=0)for(let t=0;t0){const n=this.channels[t].patterns[e-1];let i=6;for(const t of n.notes)t.pitches[0]==d.modCount-1-v&&(i=Math.min(i,t.start));i>0&&n.notes.push(new Ct(d.modCount-1-v,0,i,$))}else if(this.channels[t].patterns.lengththis.patternsPerChannel){for(let t=0;t{location.reload()}),50))}static Pt(t){try{return Boolean(new URL(t))}catch(t){return!1}}static Tt(t,e,n,i,s){const o=d.chipWaves[0].samples,a=d.rawRawChipWaves[0].samples,h=e.length;e.push(t);const l=d.chipWaves.length;let c=t,p=44100,m=!1,u=60,f=!1,y=null,b=null,g=null,w=null,v=!1,x=!1,k=t.indexOf("!"),M=-1;if(0===k&&(M=t.indexOf("!",k+1),-1!==M)){const F=t.slice(k+1,M).split(",");for(const C of F){const A=C.charAt(0),E=C.slice(1,C.length);"s"===A?p=mt(8e3,96001,ft(E,44100)):"r"===A?u=ft(E,60):"p"===A?m=!0:"a"===A?(y=yt(E,null),null!=y&&(f=!0)):"b"===A?(b=yt(E,null),null!=b&&(f=!0)):"c"===A?(g=yt(E,null),null!=g&&(f=!0)):"d"===A?(w=yt(E,null),null!=w&&(w=mt(0,4,w),f=!0)):"e"===A&&(v=!0,f=!0)}c=t.slice(M+1,t.length),x=!0}let S=null;if(!$t.Pt(c))return alert(t+" is not a valid url"),!1;if(S=new URL(c),s&&!x&&null!=S){function T(){c=t.slice(0,t.indexOf(",")),S=new URL(c),p=mt(8e3,96001,ft(t.slice(t.indexOf(",")+1),44100))}function P(){c=t.slice(0,t.indexOf("!")),S=new URL(c),u=ft(t.slice(t.indexOf("!")+1),60)}-1!=t.indexOf("@")&&(c=t.replaceAll("@",""),S=new URL(c),m=!0),-1!=t.indexOf(",")&&-1!=t.indexOf("!")?t.indexOf(",")0&&(D="!"+B.join(",")+"!"+c),e[h]=D;const I=decodeURIComponent(S.pathname.replace(/^([^\/]*\/)+/,"")),L=1;d.chipWaves[l]={name:I,expression:L,isCustomSampled:!0,isPercussion:m,rootKey:u,sampleRate:p,samples:o,index:l},d.rawChipWaves[l]={name:I,expression:L,isCustomSampled:!0,isPercussion:m,rootKey:u,sampleRate:p,samples:a,index:l},d.rawRawChipWaves[l]={name:I,expression:L,isCustomSampled:!0,isPercussion:m,rootKey:u,sampleRate:p,samples:a,index:l};const q={type:"chip",eqFilter:[],effects:[],transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"harmony",wave:I,unison:"none",envelopes:[]};f&&(q.isUsingAdvancedLoopControls=!0,q.chipWaveLoopStart=null!=y?y:0,q.chipWaveLoopEnd=null!=b?b:2,q.chipWaveLoopMode=null!=w?w:0,q.chipWavePlayBackwards=v,q.chipWaveStartOffset=null!=g?g:0);const z={index:0,name:I,midiProgram:80,settings:q};if(n.push(z),!d.willReloadForCustomSamples){r(c,l,q,{isUsingAdvancedLoopControls:f,chipWaveLoopStart:y,chipWaveLoopEnd:b,chipWaveLoopMode:w,chipWavePlayBackwards:v,chipWaveStartOffset:g},p)}i.statusTable[l]=0,i.urlTable[l]=c,i.totalSamples++}return!0}static Et(){d.chipWaves=v(d.chipWaves.slice(0,d.firstIndexForSamplesInChipWaveList)),d.rawChipWaves=v(d.rawChipWaves.slice(0,d.firstIndexForSamplesInChipWaveList)),d.rawRawChipWaves=v(d.rawRawChipWaves.slice(0,d.firstIndexForSamplesInChipWaveList))}static vt(){q.customSamples=null,$t.Et(),i.statusTable={},i.urlTable={},i.totalSamples=0,i.samplesLoaded=0,a.dispatchEvent(new s(i.totalSamples,i.samplesLoaded))}toJsonObject(t=!0,e=1,n=!0){const i=[];for(let s=0;s0&&(s.customSamples=q.customSamples),s}fromJsonObject(t){if(this.initToDefault(!0),!t)return;if(null!=t.name&&(this.title=t.name),null!=t.customSamples){const e=t.customSamples;if(null==q.customSamples||q.customSamples.join(", ")!=e.join(", ")){d.willReloadForCustomSamples=!0,$t.Et();let t=!1,n=!1,s=!1;const o=[],a=[];for(const r of e)if("legacysamples"===r.toLowerCase())t||(t=!0,o.push(r),c(0));else if("nintariboxsamples"===r.toLowerCase())n||(n=!0,o.push(r),c(1));else if("mariopaintboxsamples"===r.toLowerCase())s||(s=!0,o.push(r),c(2));else{const t=!1;$t.Tt(r,o,a,i,t)}if(o.length>0&&(q.customSamples=o),a.length>0){const t=v(a);q.presetCategories[q.presetCategories.length]={name:"Custom Sample Presets",presets:t,index:q.presetCategories.length}}}}else{let e=!1;if(null!=t.channels)for(let n=0;nt===s))]):r.includes(s)&&("trumpet"===s||"flute"===s||(e=!0,i.wave=o[r.findIndex((t=>t===s))]))}}}e?(d.willReloadForCustomSamples=!0,$t.Et(),c(0),q.customSamples=["legacySamples"]):null!=q.customSamples&&q.customSamples.length>0&&(d.willReloadForCustomSamples=!0,$t.vt())}if(this.scale=0,null!=t.scale){const n={"romani :)":"dbl harmonic :)","romani :(":"dbl harmonic :(",enigma:"strange"},i=null!=n[t.scale]?n[t.scale]:t.scale,s=d.scales.findIndex((t=>t.name==i));if(-1!=s&&(this.scale=s),this.scale==d.scales.dictionary.Custom.index&&null!=t.customScale)for(var e of t.customScale.keys())this.scaleCustom[e]=t.customScale[e]}if(null!=t.key)if("number"==typeof t.key)this.key=(t.key+1200>>>0)%d.keys.length;else if("string"==typeof t.key){const e=t.key;if("C+"===e)this.key=0,this.octave=1;else if("G- (actually F#-)"===e)this.key=6,this.octave=-1;else if("C-"===e)this.key=0,this.octave=-1;else if("oh no (F-)"===e)this.key=5,this.octave=-1;else{const t=e.charAt(0).toUpperCase(),n=e.charAt(1).toLowerCase();let i={C:0,D:2,E:4,F:5,G:7,A:9,B:11}[t];const s={"#":1,"♯":1,b:-1,"♭":-1}[n];null!=i&&(null!=s&&(i+=s),i<0&&(i+=12),i%=12,this.key=i)}}null!=t.beatsPerMinute&&(this.tempo=mt(d.tempoMin,d.tempoMax+1,0|t.beatsPerMinute)),null!=t.keyOctave&&(this.octave=mt(d.octaveMin,d.octaveMax+1,0|t.keyOctave));let n=0;null!=t.reverb&&(n=mt(0,32,0|t.reverb)),null!=t.beatsPerBar&&(this.beatsPerBar=Math.max(d.beatsPerBarMin,Math.min(d.beatsPerBarMax,0|t.beatsPerBar)));let s=4;null!=t.ticksPerBeat&&(s=0|t.ticksPerBeat||4,this.rhythm=d.rhythms.findIndex((t=>t.stepsPerBeat==s)),-1==this.rhythm&&(this.rhythm=1)),null!=t.masterGain?this.masterGain=Math.max(0,Math.min(5,t.masterGain||0)):this.masterGain=1,null!=t.limitThreshold?this.limitThreshold=Math.max(0,Math.min(2,t.limitThreshold||0)):this.limitThreshold=1,null!=t.compressionThreshold?this.compressionThreshold=Math.max(0,Math.min(1.1,t.compressionThreshold||0)):this.compressionThreshold=1,null!=t.limitRise?this.limitRise=Math.max(2e3,Math.min(1e4,t.limitRise||0)):this.limitRise=4e3,null!=t.limitDecay?this.limitDecay=Math.max(1,Math.min(30,t.limitDecay||0)):this.limitDecay=4,null!=t.limitRatio?this.limitRatio=Math.max(0,Math.min(11,t.limitRatio||0)):this.limitRatio=1,null!=t.compressionRatio?this.compressionRatio=Math.max(0,Math.min(1.168,t.compressionRatio||0)):this.compressionRatio=1;let o=1,a=1,r=1;if(null!=t.channels)for(const e of t.channels)e.instruments&&(o=Math.max(o,0|e.instruments.length)),e.patterns&&(a=Math.max(a,0|e.patterns.length)),e.sequence&&(r=Math.max(r,0|e.sequence.length));null!=t.layeredInstruments?this.layeredInstruments=!!t.layeredInstruments:this.layeredInstruments=!1,null!=t.patternInstruments?this.patternInstruments=!!t.patternInstruments:this.patternInstruments=o>1,this.patternsPerChannel=Math.min(a,d.barCountMax),this.barCount=Math.min(r,d.barCountMax),null!=t.introBars&&(this.loopStart=mt(0,this.barCount,0|t.introBars)),null!=t.loopBars&&(this.loopLength=mt(1,this.barCount-this.loopStart+1,0|t.loopBars));const h=[],l=[],p=[];if(null!=t.channels)for(let e=0;e=3,a?l.push(o):r?p.push(o):h.push(o),null!=i.octaveScrollBar&&(o.octave=mt(0,d.pitchOctaves,1+(0|i.octaveScrollBar)),a&&(o.octave=0)),null!=i.name?o.name=i.name:o.name="",Array.isArray(i.instruments)){const t=i.instruments;for(let e=0;e=this.getMaxInstrumentsPerChannel());e++){const i=new Rt(a,r);o.instruments[e]=i,i.fromJsonObject(t[e],a,r,!1,!1,n)}}for(let t=0;t>>0):0;o.bars.length=this.barCount}h.length>d.pitchChannelCountMax&&(h.length=d.pitchChannelCountMax),l.length>d.noiseChannelCountMax&&(l.length=d.noiseChannelCountMax),p.length>d.modChannelCountMax&&(p.length=d.modChannelCountMax),this.pitchChannelCount=h.length,this.noiseChannelCount=l.length,this.modChannelCount=p.length,this.channels.length=0,Array.prototype.push.apply(this.channels,h),Array.prototype.push.apply(this.channels,l),Array.prototype.push.apply(this.channels,p),d.willReloadForCustomSamples&&(window.location.hash=this.toBase64String(),setTimeout((()=>{location.reload()}),50))}getPattern(t,e){if(e<0||e>=this.barCount)return null;const n=this.channels[t].bars[e];return 0==n?null:this.channels[t].patterns[n-1]}getBeatsPerMinute(){return this.tempo}static getNeededBits(t){return 32-Math.clz32(Math.ceil(t+1)-1)}restoreLimiterDefaults(){this.compressionRatio=1,this.limitRatio=1,this.limitRise=4e3,this.limitDecay=4,this.limitThreshold=1,this.compressionThreshold=1,this.masterGain=1}}$t.Dt="UltraBox",$t.kt=2,$t.xt=9,$t.St=1,$t.Mt=5,$t.Ct=1,$t.Ft=4,$t.At=1,$t.gt=4,$t.bt=117;class Ht{constructor(){this.delayLine=null,this.allPassG=0,this.allPassGDelta=0,this.shelfA1=0,this.shelfA1Delta=0,this.shelfB0=0,this.shelfB0Delta=0,this.shelfB1=0,this.shelfB1Delta=0,this.reset()}reset(){this.delayIndex=-1,this.allPassSample=0,this.allPassPrevInput=0,this.shelfSample=0,this.shelfPrevInput=0,this.fractionalDelaySample=0,this.prevDelayLength=-1,this.delayResetOffset=0}update(t,e,n,i,s,o,a){const r=2*Math.PI*d.pickedStringDispersionCenterFreq/t.samplesPerSecond,h=2*Math.PI*d.pickedStringShelfHz/t.samplesPerSecond,l=(Math.pow(100,o)-1)/99,c=(Math.pow(100,a)-1)/99,p=this.prevDelayLength,m=n.phaseDeltas[i],u=n.phaseDeltaScales[i],f=m*Math.pow(u,s),y=2*Math.PI*m,b=2*Math.PI*f,g=2*y,w=2*b,v=Math.min(Math.PI,y*d.pickedStringDispersionFreqMult*Math.pow(r/y,d.pickedStringDispersionFreqScale)),x=Math.min(Math.PI,b*d.pickedStringDispersionFreqMult*Math.pow(r/b,d.pickedStringDispersionFreqScale)),k=Math.pow(.5,l*h/y),M=Math.pow(.5,c*h/b),S=Math.pow(k,d.stringDecayRate),F=Math.pow(M,d.stringDecayRate),C=Math.pow(k,.002),A=Math.pow(M,.002);jt.tempFilterStartCoefficients.allPass1stOrderInvertPhaseAbove(v),t.tempFrequencyResponse.analyze(jt.tempFilterStartCoefficients,g);const E=jt.tempFilterStartCoefficients.b[0],T=-t.tempFrequencyResponse.angle()/g;jt.tempFilterEndCoefficients.allPass1stOrderInvertPhaseAbove(x),t.tempFrequencyResponse.analyze(jt.tempFilterEndCoefficients,w);const P=jt.tempFilterEndCoefficients.b[0],D=-t.tempFrequencyResponse.angle()/w;jt.tempFilterStartCoefficients.highShelf1stOrder(h,S),t.tempFrequencyResponse.analyze(jt.tempFilterStartCoefficients,g);const B=jt.tempFilterStartCoefficients.a[1],I=jt.tempFilterStartCoefficients.b[0]*C,L=jt.tempFilterStartCoefficients.b[1]*C,q=-t.tempFrequencyResponse.angle()/g;jt.tempFilterEndCoefficients.highShelf1stOrder(h,F),t.tempFrequencyResponse.analyze(jt.tempFilterEndCoefficients,w);const z=jt.tempFilterEndCoefficients.a[1],N=jt.tempFilterEndCoefficients.b[0]*A,R=jt.tempFilterEndCoefficients.b[1]*A,O=-t.tempFrequencyResponse.angle()/w,$=1/m,H=1/f,V=Math.ceil(2*Math.max($,H)),G=$-T-q,_=H-D-O;this.prevDelayLength=G,this.delayLengthDelta=(_-G)/s,this.allPassG=E,this.shelfA1=B,this.shelfB0=I,this.shelfB1=L,this.allPassGDelta=(P-E)/s,this.shelfA1Delta=(z-B)/s,this.shelfB0Delta=(N-I)/s,this.shelfB1Delta=(R-L)/s;const W=Math.abs(Math.log2(G/p))>.01,j=-1==this.delayIndex||W;if(null==this.delayLine||this.delayLine.length<=V){const e=Math.ceil(2*t.samplesPerSecond/Rt.frequencyFromPitch(12)),n=new Float32Array(jt.fittingPowerOfTwo(Math.max(e,V)));if(!j&&null!=this.delayLine){const t=this.delayLine.length-1>>0,e=this.delayIndex+this.delayResetOffset;this.delayIndex=this.delayLine.length-this.delayResetOffset;for(let i=0;i>0;if(j){this.delayIndex=0,this.allPassSample=0,this.allPassPrevInput=0,this.shelfSample=0,this.shelfPrevInput=0,this.fractionalDelaySample=0;const n=-G,i=Math.floor(n-$/2),s=Math.ceil(i+2*$);this.delayResetOffset=s;for(let t=i;t<=s;t++)U[t&K]=0;const o=e.wave,a=o.length-1,r=a/$,h=Math.min(.2*$,.003*t.samplesPerSecond),l=Math.ceil(n),c=n+$+h,d=c;let p=(l-n)*r,m=0;for(let t=l;t<=d;t++){const e=0|p,i=e%a;let s=o[i];const l=p-e;s+=(o[i+1]-s)*l;const d=(s-m)/r,u=Math.min(1,(t-n)/h)*Math.min(1,(c-t)/h),f=u*u*(3-2*u);U[t&K]+=d*f,m=s,p+=r}}}}class Vt{constructor(){this.noteSecondsStart=0,this.noteSecondsEnd=0,this.noteTicksStart=0,this.noteTicksEnd=0,this.noteSizeStart=d.noteSizeMax,this.noteSizeEnd=d.noteSizeMax,this.prevNoteSize=d.noteSizeMax,this.nextNoteSize=d.noteSizeMax,this.Bt=d.noteSizeMax,this.prevNoteSecondsStart=0,this.prevNoteSecondsEnd=0,this.prevNoteTicksStart=0,this.prevNoteTicksEnd=0,this.It=d.noteSizeMax,this.prevSlideStart=!1,this.prevSlideEnd=!1,this.nextSlideStart=!1,this.nextSlideEnd=!1,this.prevSlideRatioStart=0,this.prevSlideRatioEnd=0,this.nextSlideRatioStart=0,this.nextSlideRatioEnd=0,this.envelopeStarts=[],this.envelopeEnds=[],this.Lt=[],this.qt=0,this.lowpassCutoffDecayVolumeCompensation=1;for(let t=0;t<38;t++)this.envelopeStarts[t]=1,this.envelopeEnds[t]=1;this.reset()}reset(){this.noteSecondsEnd=0,this.noteTicksEnd=0,this.Bt=d.noteSizeMax,this.prevNoteSecondsEnd=0,this.prevNoteTicksEnd=0,this.It=d.noteSizeMax,this.qt=0}computeEnvelopes(t,e,n,i,s){const o=t.getTransition();null==s||!s.atNoteStart||o.continues||s.forceContinueAtStart||(this.prevNoteSecondsEnd=this.noteSecondsEnd,this.prevNoteTicksEnd=this.noteTicksEnd,this.It=this.Bt,this.noteSecondsEnd=0,this.noteTicksEnd=0),null!=s&&(null!=s.note?this.Bt=s.note.pins[s.note.pins.length-1].size:this.Bt=d.noteSizeMax);const a=n+1,r=this.noteSecondsEnd,h=r+i,l=this.noteTicksEnd,c=l+1,p=this.prevNoteSecondsEnd,m=p+i,u=this.prevNoteTicksEnd,f=u+1,y=1/(d.ticksPerPart*d.partsPerBeat),b=y*n,g=y*a;let w=this.Bt,v=this.Bt,x=this.It,k=0,M=!1,S=!1,F=!1,C=!1,A=0,E=0,T=0,P=0;if(null!=s&&null!=s.note&&!s.passedEndOfNote){const t=s.note.getEndPinIndex(e),i=s.note.pins[t-1],r=s.note.pins[t],h=(s.note.start+i.time)*d.ticksPerPart,l=(s.note.start+r.time)*d.ticksPerPart,c=(n-h)/(l-h),p=(a-h)/(l-h);if(w=i.size+(r.size-i.size)*c,v=i.size+(r.size-i.size)*p,o.slides){const t=s.noteStartPart*d.ticksPerPart,e=s.noteEndPart*d.ticksPerPart,i=.5*(e-t),r=Math.min(i,o.slideTicks);null==s.prevNote||s.forceContinueAtStart||(n-ti&&0==e.controlPoints[i].type&&(D=Math.max(D,Vt.getLowpassCutoffDecayVolumeCompensation(s)))}}}this.noteSecondsStart=r,this.noteSecondsEnd=h,this.noteTicksStart=l,this.noteTicksEnd=c,this.prevNoteSecondsStart=p,this.prevNoteSecondsEnd=m,this.prevNoteTicksStart=u,this.prevNoteTicksEnd=f,this.prevNoteSize=x,this.nextNoteSize=k,this.noteSizeStart=w,this.noteSizeEnd=v,this.prevSlideStart=M,this.prevSlideEnd=S,this.nextSlideStart=F,this.nextSlideEnd=C,this.prevSlideRatioStart=A,this.prevSlideRatioEnd=E,this.nextSlideRatioStart=T,this.nextSlideRatioEnd=P,this.lowpassCutoffDecayVolumeCompensation=D}clearEnvelopes(){for(let t=0;t0?o:0,o;case 11:{let n=1-e/(16/t.speed);return n=n>0?n:0,n}case 12:{let n=e/(16/t.speed);return n=n<1?n:1,n}default:throw new Error("Unrecognized operator envelope type.")}}static getLowpassCutoffDecayVolumeCompensation(t){return 8==t.type?1.25+.025*t.speed:4==t.type?1+.02*t.speed:1}}class Gt{constructor(){this.pitches=Array(d.maxChordSize+2).fill(0),this.pitchCount=0,this.chordSize=0,this.drumsetPitch=null,this.note=null,this.prevNote=null,this.nextNote=null,this.prevNotePitchIndex=0,this.nextNotePitchIndex=0,this.freshlyAllocated=!0,this.atNoteStart=!1,this.isOnLastTick=!1,this.passedEndOfNote=!1,this.forceContinueAtStart=!1,this.forceContinueAtEnd=!1,this.noteStartPart=0,this.noteEndPart=0,this.ticksSinceReleased=0,this.liveInputSamplesHeld=0,this.lastInterval=0,this.noiseSample=0,this.stringSustainStart=0,this.stringSustainEnd=0,this.phases=[],this.operatorWaves=[],this.phaseDeltas=[],this.directions=[],this.chipWaveCompletions=[],this.chipWavePrevWaves=[],this.chipWaveCompletionsLastWave=[],this.phaseDeltaScales=[],this.expression=0,this.expressionDelta=0,this.operatorExpressions=[],this.operatorExpressionDeltas=[],this.prevPitchExpressions=Array(d.maxPitchOrOperatorCount).fill(null),this.prevVibrato=null,this.prevStringDecay=null,this.pulseWidth=0,this.pulseWidthDelta=0,this.decimalOffset=0,this.pickedStrings=[],this.noteFilters=[],this.noteFilterCount=0,this.initialNoteFilterInput1=0,this.initialNoteFilterInput2=0,this.specialIntervalExpressionMult=1,this.feedbackOutputs=[],this.feedbackMult=0,this.feedbackDelta=0,this.stereoVolumeLStart=0,this.stereoVolumeRStart=0,this.stereoVolumeLDelta=0,this.stereoVolumeRDelta=0,this.stereoDelayStart=0,this.stereoDelayEnd=0,this.stereoDelayDelta=0,this.customVolumeStart=0,this.customVolumeEnd=0,this.filterResonanceStart=0,this.filterResonanceDelta=0,this.isFirstOrder=!1,this.envelopeComputer=new Vt,this.reset()}reset(){this.noiseSample=0;for(let t=0;t>1,e.echoDelay+1),i=2*jt.fittingPowerOfTwo(t*d.echoDelayStepTicks*n);if(null==this.echoDelayLineL||null==this.echoDelayLineR)this.echoDelayLineL=new Float32Array(i),this.echoDelayLineR=new Float32Array(i);else if(this.echoDelayLineL.length=e&&(this.deactivateAfterThisTick=!0)}else{0==this.attentuationProgress||(g=0),w=0;const t=1/256,e=-Math.log2(t);let i=0;if(p&&(i+=d.chorusMaxDelay),m){const t=Math.pow(k,1/M);i+=-1/Math.log2(t)*e}if(u){const t=2*S,n=d.reverbDelayBufferSize/4/r,s=Math.pow(t,1/n);i+=-1/Math.log2(s)*e}const s=n/r/i,o=this.attentuationProgress+s;o>=1&&(x=0),this.attentuationProgress=o,this.attentuationProgress>=1&&(this.flushingDelayLines=!0)}this.eqFilterVolume=g,this.eqFilterVolumeDelta=(w-g)/i,this.delayInputMult=v,this.delayInputMultDelta=(x-v)/i}updateWaves(t,e){if(this.volumeScale=1,0==t.type)this.wave=this.aliases?d.rawChipWaves[t.chipWave].samples:d.chipWaves[t.chipWave].samples,this.isUsingAdvancedLoopControls=t.isUsingAdvancedLoopControls,this.chipWaveLoopStart=t.chipWaveLoopStart,this.chipWaveLoopEnd=t.chipWaveLoopEnd,this.chipWaveLoopMode=t.chipWaveLoopMode,this.chipWavePlayBackwards=t.chipWavePlayBackwards,this.chipWaveStartOffset=t.chipWaveStartOffset,this.unisonVoices=t.unisonVoices,this.unisonSpread=t.unisonSpread,this.unisonOffset=t.unisonOffset,this.unisonExpression=t.unisonExpression,this.unisonSign=t.unisonSign;else if(8==t.type)this.wave=this.aliases?t.customChipWave:t.customChipWaveIntegral,this.volumeScale=.05,this.unisonVoices=t.unisonVoices,this.unisonSpread=t.unisonSpread,this.unisonOffset=t.unisonOffset,this.unisonExpression=t.unisonExpression,this.unisonSign=t.unisonSign;else if(2==t.type)this.wave=f(t.chipNoise,at,st);else if(5==t.type)this.wave=this.harmonicsWave.getCustomWave(t.harmonicsWave,t.type),this.unisonVoices=t.unisonVoices,this.unisonSpread=t.unisonSpread,this.unisonOffset=t.unisonOffset,this.unisonExpression=t.unisonExpression,this.unisonSign=t.unisonSign;else if(7==t.type)this.wave=this.harmonicsWave.getCustomWave(t.harmonicsWave,t.type),this.unisonVoices=t.unisonVoices,this.unisonSpread=t.unisonSpread,this.unisonOffset=t.unisonOffset,this.unisonExpression=t.unisonExpression,this.unisonSign=t.unisonSign;else if(3==t.type)this.wave=this.spectrumWave.getCustomWave(t.spectrumWave,8);else if(4==t.type){for(let e=0;e0){let t=[],e=[];this.modValues=[],this.nextModValues=[],this.modInsValues=[],this.nextModInsValues=[];for(let t=0;t=0;o--)if(s=this.song.getPattern(i,o),null!=s){let a=s.instruments[0],r=this.song.channels[i].instruments[a],h=[],l=[],c=o==this.bar?n:this.findPartsInBar(o);for(const t of s.notes)if(t.starth[d.modCount-1-t.pitches[0]]))if(t.end<=c)h[d.modCount-1-t.pitches[0]]=t.end,l[d.modCount-1-t.pitches[0]]=t.pins[t.pins.length-1].size;else{h[d.modCount-1-t.pitches[0]]=c;for(let e=0;ec){const n=t.pins[e].time-t.pins[e-1].time,i=c-t.start-t.pins[e-1].time,s=t.pins[e].size-t.pins[e-1].size;l[d.modCount-1-t.pitches[0]]=Math.round(t.pins[e-1].size+s*i/n),e=t.pins.length}}for(let n=0;nt[r.modulators[n]])&&(this.setModValue(l[n],l[n],n,r.modChannels[n],r.modInstruments[n],r.modulators[n]),t[r.modulators[n]]=o*d.partsPerBeat*this.song.beatsPerBar+h[n]);else{let t=[];if(r.modInstruments[n]==this.song.channels[r.modChannels[n]].instruments.length)for(let e=0;ethis.song.channels[r.modChannels[n]].instruments.length){const e=this.song.getPattern(r.modChannels[n],o);null!=e&&(t=e.instruments)}else t.push(r.modInstruments[n]);for(let i=0;ie[r.modChannels[n]][t[i]][c]){if(s){let e=this.song.channels[r.modChannels[n]].instruments[t[i]];if(0==r.modFilterTypes[n])e.tmpEqFilterStart=e.eqSubFilters[l[n]];else{for(let t=0;t=n.instruments.length?n.instruments:[n.instruments[t.modInstruments[e]]];for(let n=0;ns.eqFilter.controlPointCount||s.noteFilterType&&"note filter"==o||!s.noteFilterType&&("note filt cut"==o||"note filt peak"==o)||"note filter"==o&&Math.floor((t.modFilterTypes[e]+1)/2)>s.noteFilter.controlPointCount||(t.invalidModulators[e]=!1,n=i.length)}}}static operatorAmplitudeCurve(t){return(Math.pow(16,t/15)-1)/15}get playing(){return this.isPlayingSong}get recording(){return this.isRecording}get playhead(){return this.playheadInternal}set playhead(t){if(null!=this.song){this.playheadInternal=Math.max(0,Math.min(this.song.barCount,t));let e=this.playheadInternal;this.bar=Math.floor(e),e=this.song.beatsPerBar*(e-this.bar),this.beat=Math.floor(e),e=d.partsPerBeat*(e-this.beat),this.part=Math.floor(e),e=d.ticksPerPart*(e-this.part),this.tick=Math.floor(e),this.tickSampleCountdown=0,this.isAtStartOfTick=!0,this.prevBar=null}}getSamplesPerBar(){if(null==this.song)throw new Error;return this.getSamplesPerTick()*d.ticksPerPart*d.partsPerBeat*this.song.beatsPerBar}getTicksIntoBar(){return(this.beat*d.partsPerBeat+this.part)*d.ticksPerPart+this.tick}getCurrentPart(){return this.beat*d.partsPerBeat+this.part}findPartsInBar(t){if(null==this.song)return 0;let e=d.partsPerBeat*this.song.beatsPerBar;for(let n=this.song.pitchChannelCount+this.song.noiseChannelCount;nt.start&&(e=t.start)}}return e}getTotalSamples(t,e,n){if(null==this.song)return-1;let i=t?0:this.song.loopStart,s=e?this.song.barCount:this.song.loopStart+this.song.loopLength,o=!1,a=!1,r=this.song.tempo;for(let t=this.song.pitchChannelCount+this.song.noiseChannelCount;t0){let t=null,e=0;for(let n=i-1;n>=0;n--){for(let i=this.song.pitchChannelCount+this.song.noiseChannelCount;it))if(n.end<=r)t=n.end,e=n.pins[n.pins.length-1].size;else{t=r;for(let t=0;tr){const i=n.pins[t].time-n.pins[t-1].time,s=r-n.start-n.pins[t-1].time,o=n.pins[t].size-n.pins[t-1].size;e=Math.round(n.pins[t-1].size+o*s/i),t=n.pins.length}}}}null!=t&&(r=e+d.modulators.dictionary.tempo.convertRealFactor,n=-1)}}if(o||a){let t=i,e=!1,h=0;for(;!e;){let i=d.partsPerBeat*this.song.beatsPerBar,l=0;if(a&&(i=this.findPartsInBar(t)),o){let e=!1;for(let n=this.song.pitchChannelCount+this.song.noiseChannelCount;nt.pitches[0]==d.modCount-1-n))){e=!0,s.notes.sort((function(t,e){return t.start==e.start?t.pitches[0]-e.pitches[0]:t.start-e.start}));for(const t of s.notes)if(t.pitches[0]==d.modCount-1-n&&(h+=Math.min(i-l,t.start-l)*d.ticksPerPart*this.getSamplesPerTickSpecificBPM(r),t.starti&&(o=t.pins[e-1].size+(t.pins[e].size-t.pins[e-1].size)*(i-(t.start+t.pins[e-1].time))/(t.pins[e].time-t.pins[e-1].time)+d.modulators.dictionary.tempo.convertRealFactor);let a=d.partsPerBeat*d.ticksPerPart/60;h+=o!=s?-this.samplesPerSecond*n*(Math.log(a*o*n)-Math.log(a*s*n))/(a*(s-o)):n*this.getSamplesPerTickSpecificBPM(o),r=o}l=Math.min(t.start+t.pins[e].time,i)}}}}}h+=(i-l)*d.ticksPerPart*this.getSamplesPerTickSpecificBPM(r),t++,0!=n&&t==this.song.loopStart+this.song.loopLength&&(t=this.song.loopStart,n>0&&n--),t>=s&&(e=!0)}return Math.ceil(h)}return this.getSamplesPerBar()*this.getTotalBars(t,e,n)}getTotalBars(t,e,n=this.loopRepeatCount){if(null==this.song)throw new Error;let i=this.song.loopLength*(n+1);return t&&(i+=this.song.loopStart),e&&(i+=this.song.barCount-(this.song.loopStart+this.song.loopLength)),i}constructor(t=null){this.samplesPerSecond=44100,this.song=null,this.preferLowerLatency=!1,this.anticipatePoorPerformance=!1,this.liveInputDuration=0,this.liveInputStarted=!1,this.liveInputPitches=[],this.liveInputChannel=0,this.liveInputInstruments=[],this.loopRepeatCount=-1,this.volume=1,this.oscRefreshEventTimer=0,this.oscEnabled=!0,this.enableMetronome=!1,this.countInMetronome=!1,this.renderingSong=!1,this.wantToSkip=!1,this.playheadInternal=0,this.bar=0,this.prevBar=null,this.nextBar=null,this.beat=0,this.part=0,this.tick=0,this.isAtStartOfTick=!0,this.isAtEndOfTick=!0,this.tickSampleCountdown=0,this.modValues=[],this.modInsValues=[],this.nextModValues=[],this.nextModInsValues=[],this.isPlayingSong=!1,this.isRecording=!1,this.liveInputEndTime=0,this.browserAutomaticallyClearsAudioBuffer=!0,this.tempDrumSetControlPoint=new qt,this.tempFrequencyResponse=new ct,this.channels=[],this.tonePool=new rt,this.tempMatchedPitchTones=Array(d.maxChordSize).fill(null),this.startedMetronome=!1,this.metronomeSamplesRemaining=-1,this.metronomeAmplitude=0,this.metronomePrevAmplitude=0,this.metronomeFilter=0,this.limit=0,this.tempMonoInstrumentSampleBuffer=null,this.audioCtx=null,this.scriptNode=null,this.audioProcessCallback=t=>{const e=t.outputBuffer,n=e.getChannelData(0),i=e.getChannelData(1);if(!this.browserAutomaticallyClearsAudioBuffer||0==n[0]&&0==i[0]&&0==n[e.length-1]&&0==i[e.length-1]||(this.browserAutomaticallyClearsAudioBuffer=!1),!this.browserAutomaticallyClearsAudioBuffer){const t=e.length;for(let e=0;e=this.liveInputEndTime?this.deactivateAudio():(this.synthesize(n,i,e.length,this.isPlayingSong),this.oscEnabled&&(this.oscRefreshEventTimer<=0?(ht.raise("oscillascopeUpdate",n,i),this.oscRefreshEventTimer=2):this.oscRefreshEventTimer--))},this.computeDelayBufferSizes(),null!=t&&this.setSong(t)}setSong(t){"string"==typeof t?this.song=new $t(t):t instanceof $t&&(this.song=t),this.prevBar=null}computeDelayBufferSizes(){this.panningDelayBufferSize=jt.fittingPowerOfTwo(this.samplesPerSecond*d.panDelaySecondsMax),this.panningDelayBufferMask=this.panningDelayBufferSize-1,this.chorusDelayBufferSize=jt.fittingPowerOfTwo(this.samplesPerSecond*d.chorusMaxDelay),this.chorusDelayBufferMask=this.chorusDelayBufferSize-1}activateAudio(){const t=this.anticipatePoorPerformance?this.preferLowerLatency?2048:4096:this.preferLowerLatency?512:2048;if(null==this.audioCtx||null==this.scriptNode||this.scriptNode.bufferSize!=t){null!=this.scriptNode&&this.deactivateAudio();const e=this.anticipatePoorPerformance?this.preferLowerLatency?"balanced":"playback":this.preferLowerLatency?"interactive":"balanced";this.audioCtx=this.audioCtx||new(window.AudioContext||window.webkitAudioContext)({latencyHint:e}),this.samplesPerSecond=this.audioCtx.sampleRate,this.scriptNode=this.audioCtx.createScriptProcessor?this.audioCtx.createScriptProcessor(t,0,2):this.audioCtx.createJavaScriptNode(t,0,2),this.scriptNode.onaudioprocess=this.audioProcessCallback,this.scriptNode.channelCountMode="explicit",this.scriptNode.channelInterpretation="speakers",this.scriptNode.connect(this.audioCtx.destination),this.computeDelayBufferSizes()}this.audioCtx.resume()}deactivateAudio(){null!=this.audioCtx&&null!=this.scriptNode&&(this.scriptNode.disconnect(this.audioCtx.destination),this.scriptNode=null,this.audioCtx.close&&this.audioCtx.close(),this.audioCtx=null)}maintainLiveInput(){this.activateAudio(),this.liveInputEndTime=performance.now()+1e4}play(){this.isPlayingSong||(this.computeLatestModValues(),this.warmUpSynthesizer(this.song),this.isPlayingSong=!0,this.activateAudio())}pause(){if(this.isPlayingSong&&(this.isPlayingSong=!1,this.isRecording=!1,this.modValues=[],this.nextModValues=[],null!=this.song)){this.song.inVolumeCap=0,this.song.outVolumeCap=0;for(let t=0;t=this.song.loopStart+this.song.loopLength)){const t=this.bar;this.bar=this.song.loopStart,this.playheadInternal+=this.bar-t,this.playing&&this.computeLatestModValues()}}goToNextBar(){if(!this.song)return;this.prevBar=this.bar;const t=this.bar;this.bar++,this.bar>=this.song.barCount&&(this.bar=0),this.playheadInternal+=this.bar-t,this.playing&&this.computeLatestModValues()}goToPrevBar(){if(!this.song)return;this.prevBar=null;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,this.playing&&this.computeLatestModValues()}getNextBar(){let t=this.bar+1;return this.isRecording?t>=this.song.barCount&&(t=this.song.barCount-1):0!=this.loopRepeatCount&&t==this.song.loopStart+this.song.loopLength&&(t=this.song.loopStart),t}skipBar(){if(!this.song)return;const t=this.getSamplesPerTick();this.bar++,this.beat=0,this.part=0,this.tick=0,this.tickSampleCountdown=t,this.isAtStartOfTick=!0,0!=this.loopRepeatCount&&this.bar==this.song.loopStart+this.song.loopLength&&(this.bar=this.song.loopStart,this.loopRepeatCount>0&&this.loopRepeatCount--)}synthesize(t,e,n,i=!0){if(null==this.song){for(let i=0;io)&&(this.tickSampleCountdown=o,this.isAtStartOfTick=!0),i&&(this.beat>=s.beatsPerBar&&(this.beat=0,this.part=0,this.tick=0,this.tickSampleCountdown=o,this.isAtStartOfTick=!0,this.prevBar=this.bar,this.bar=this.getNextBar(),this.bar<=this.prevBar&&this.loopRepeatCount>0&&this.loopRepeatCount--),this.bar>=s.barCount&&(this.bar=0,-1!=this.loopRepeatCount&&(a=!0,this.pause()))),this.syncSongState(),(null==this.tempMonoInstrumentSampleBuffer||this.tempMonoInstrumentSampleBuffer.length=s.barCount&&(this.nextBar=null);const f=n-u,y=Math.ceil(this.tickSampleCountdown),b=Math.min(y,f),g=u+b;if(this.isPlayingSong||this.renderingSong)for(let t=s.pitchChannelCount+s.noiseChannelCount;t=Math.abs(h.getFadeOutTicks())){this.freeReleasedTone(l,e),e--;continue}const a=t>=d.maximumTonesPerChannel;this.computeTone(s,n,o,i,!0,a),t++}l.awake&&(l.computed||l.compute(this,h,o,Math.ceil(o),null,n,i),l.computed=!1)}for(let t=0;t4&&s.beatsPerBar%2==0&&this.beat==s.beatsPerBar/2,e=0==this.beat?8:t?6:4,n=0==this.beat?1600:t?1200:800,i=0==this.beat?.06:t?.05:.04,o=this.samplesPerSecond/n,a=2*Math.PI/o;this.metronomeSamplesRemaining=Math.floor(o*e),this.metronomeFilter=2*Math.cos(a),this.metronomeAmplitude=i*Math.sin(a),this.metronomePrevAmplitude=0,this.startedMetronome=!0}if(this.metronomeSamplesRemaining>0){const n=Math.min(g,u+this.metronomeSamplesRemaining);this.metronomeSamplesRemaining-=n-u;for(let i=u;id?a:d;this.song.inVolumeCap=this.song.inVolumeCap>p?this.song.inVolumeCap:p;const m=+(p>s.compressionThreshold)+ +(p>s.limitThreshold),u=+(0==m)*((.8*(p+1-s.compressionThreshold)+.25)*s.compressionRatio+1.05*(1-s.compressionRatio))+1.05*+(1==m)+ +(2==m)*(1.05*((p+1-s.limitThreshold)*s.limitRatio+(1-s.limitThreshold)));c+=(u-c)*(c=1?1.05*c:.8*c+.25);t[n]=i*f,e[n]=o*f,this.song.outVolumeCap=this.song.outVolumeCap>p*f?this.song.outVolumeCap:p*f}if(u+=b,this.isAtStartOfTick=!1,this.tickSampleCountdown-=b,this.tickSampleCountdown<=0){this.isAtStartOfTick=!0;for(const t of this.channels)for(const e of t.instruments){for(let t=0;t0&&this.loopRepeatCount--,this.bar>=s.barCount&&(this.bar=0,-1!=this.loopRepeatCount&&(a=!0,this.resetEffects(),this.pause())))))))}for(let t=0;t0){const t=this.tonePool.popBack();return t.freshlyAllocated=!0,t}return new Gt}releaseTone(t,e){t.releasedTones.pushFront(e),e.atNoteStart=!1,e.passedEndOfNote=!0}freeReleasedTone(t,e){this.freeTone(t.releasedTones.get(e)),t.releasedTones.remove(e)}freeAllTones(){for(const t of this.channels)for(const e of t.instruments){for(;e.activeTones.count()>0;)this.freeTone(e.activeTones.popBack());for(;e.activeModTones.count()>0;)this.freeTone(e.activeModTones.popBack());for(;e.releasedTones.count()>0;)this.freeTone(e.releasedTones.popBack());for(;e.liveInputTones.count()>0;)this.freeTone(e.liveInputTones.popBack())}}determineLiveInputTones(t,e,n){const i=t.channels[e],s=this.channels[e],o=this.liveInputPitches;for(let a=0;a0&&e==this.liveInputChannel&&o.length>0&&-1!=this.liveInputInstruments.indexOf(a)){const s=i.instruments[a];if(s.getChord().singleTone){let i;h.count()<=l?(i=this.newTone(),h.pushBack(i)):!s.getTransition().isSeamless&&this.liveInputStarted?(this.releaseTone(r,h.get(l)),i=this.newTone(),h.set(l,i)):i=h.get(l),l++;for(let t=0;tl;)this.releaseTone(r,h.popBack());this.clearTempMatchedPitchTones(l,r)}this.liveInputStarted=!1}adjacentPatternHasCompatibleInstrumentTransition(t,e,n,i,s,o,a,r,h,l){if(t.patternInstruments&&-1==i.instruments.indexOf(s)){if(n.instruments.length>1||i.instruments.length>1)return null;const t=e.instruments[i.instruments[0]];if(l)return t.getChord();const s=t.getTransition();return o.includeAdjacentPatterns&&s.includeAdjacentPatterns&&s.slides==o.slides?t.getChord():null}return l||o.includeAdjacentPatterns?a:null}static adjacentNotesHaveMatchingPitches(t,e){if(t.pitches.length!=e.pitches.length)return!1;const n=t.pins[t.pins.length-1].interval;for(const i of t.pitches)if(-1==e.pitches.indexOf(i+n))return!1;return!0}moveTonesIntoOrderedTempMatchedList(t,e){for(let n=0;n0;){const e=t.popFront();for(let t=0;ti[a.notes[t].pitches[0]].start)&&(i[a.notes[t].pitches[0]]=a.notes[t]):a.notes[t].start<=r&&a.notes[t].end>r?n[a.notes[t].pitches[0]]=a.notes[t]:a.notes[t].start>r&&(null==l[a.notes[t].pitches[0]]||a.notes[t].start0;)e.activeModTones.pushFront(t.activeModTones.popBack())}if(o.singleSeamlessInstrument=m,null!=n[t]){let e=i[t],s=l[t],o=!1,a=!1;const r=d.ticksPerPart*n[t].start==h&&this.isAtStartOfTick;let c;if(f.count()<=p)c=this.newTone(),f.pushBack(c);else if(r&&null==e){const t=f.get(p);t.isOnLastTick?this.freeTone(t):this.releaseTone(u,t),c=this.newTone(),f.set(p,c)}else c=f.get(p);p++;for(let e=0;ep;){const n=f.popBack(),i=t.channels[e];if(n.instrumentIndexr)l=a.notes[t];else if(a.notes[t].start>r){p=a.notes[t];break}null!=l&&(null!=c&&c.end!=l.start&&(c=null),null!=p&&p.start!=l.end&&(p=null))}if(null!=a&&(!t.layeredInstruments||1==s.instruments.length||t.patternInstruments&&1==a.instruments.length)){const e=t.patternInstruments?a.instruments[0]:0;if(null!=o.singleSeamlessInstrument&&o.singleSeamlessInstrument!=e&&o.singleSeamlessInstrument0;)n.activeTones.pushFront(t.activeTones.popBack())}o.singleSeamlessInstrument=e}else o.singleSeamlessInstrument=null;for(let i=0;io?y:null,p=l,g=S>o?b:null,w=p.start+a,F=!1;if(w>r){if(!(u.count()>o&&(s.isSeamless||x)&&null!=c))break;g=p,p=c,c=null,w=p.start+a,F=!0}let C=p.end;(s.isSeamless||x)&&null!=g&&(C=Math.min(d.partsPerBeat*this.song.beatsPerBar,C+a)),(s.continues||x)&&null!=c||(a+=v.strumParts);const A=d.ticksPerPart*w==h;let E;if(null!=this.tempMatchedPitchTones[f])E=this.tempMatchedPitchTones[f],this.tempMatchedPitchTones[f]=null,u.pushBack(E);else if(u.count()<=f)E=this.newTone(),u.pushBack(E);else if(!A||(s.isSeamless||x)&&null!=c)E=u.get(f);else{const t=u.get(f);t.isOnLastTick?this.freeTone(t):this.releaseTone(m,t),E=this.newTone(),u.set(f,E)}f++,E.pitches[0]=p.pitches[o],E.pitchCount=1,E.chordSize=p.pitches.length,E.instrumentIndex=i,E.note=p,E.noteStartPart=w,E.noteEndPart=C,E.prevNote=c,E.nextNote=g,E.prevNotePitchIndex=o,E.nextNotePitchIndex=o,E.atNoteStart=A,E.passedEndOfNote=F,E.forceContinueAtStart=x&&null!=c,E.forceContinueAtEnd=k&&null!=g,this.computeTone(t,e,n,E,!1,!1)}}}for(;u.count()>f;){const n=u.popBack(),i=t.channels[e];if(n.instrumentIndex=n&&(P=!0)}else if(null==i.note)I=L=1,i.lastInterval=0,i.ticksSinceReleased=0,i.liveInputSamplesHeld+=a;else{const t=i.note,e=i.nextNote,n=i.noteStartPart,s=i.noteEndPart,o=t.getEndPinIndex(E),a=t.pins[o-1],r=t.pins[o],h=n*d.ticksPerPart,c=s*d.ticksPerPart,m=(t.start+a.time)*d.ticksPerPart,u=(t.start+r.time)*d.ticksPerPart;i.ticksSinceReleased=0;const f=E*d.ticksPerPart+this.tick,y=f+1,b=f-h,g=y-h,w=Math.min(1,(f-m)/(u-m)),v=Math.min(1,(y-m)/(u-m));if(I=1,L=1,D=a.interval+(r.interval-a.interval)*w,B=a.interval+(r.interval-a.interval)*v,i.lastInterval=B,!p.isSeamless&&!i.forceContinueAtEnd||null==e){const t=-l.getFadeOutTicks();if(t>0){const e=c-h;I*=Math.min(1,(e-b)/t),L*=Math.min(1,(e-g)/t),y>=h+e&&(P=!0)}}}i.isOnLastTick=P;let H,V,G=l.noteFilter;if(l.noteFilterType){const t=l.noteFilter;null==l.noteSubFilters[1]&&(l.noteSubFilters[1]=new zt);const n=l.noteSubFilters[1];let s=l.noteFilterSimpleCut,o=l.noteFilterSimplePeak,a=l.noteFilterSimpleCut,r=l.noteFilterSimplePeak,h=!1;this.isModActive(d.modulators.dictionary["note filt cut"].index,e,i.instrumentIndex)&&(s=this.getModValue(d.modulators.dictionary["note filt cut"].index,e,i.instrumentIndex,!1),a=this.getModValue(d.modulators.dictionary["note filt cut"].index,e,i.instrumentIndex,!0),h=!0),this.isModActive(d.modulators.dictionary["note filt peak"].index,e,i.instrumentIndex)&&(o=this.getModValue(d.modulators.dictionary["note filt peak"].index,e,i.instrumentIndex,!1),r=this.getModValue(d.modulators.dictionary["note filt peak"].index,e,i.instrumentIndex,!0),h=!0),t.convertLegacySettingsForSynth(s,o,!h),n.convertLegacySettingsForSynth(a,r,!h),H=t.controlPoints[0],V=n.controlPoints[0],l.noteFilter=t,l.tmpNoteFilterStart=t}const _=i.envelopeComputer;_.computeEnvelopes(l,E,d.ticksPerPart*k,n/this.samplesPerSecond,i);const W=i.envelopeComputer.envelopeStarts,j=i.envelopeComputer.envelopeEnds;if(l.noteFilter=G,null!=i.note&&p.slides){const t=i.prevNote,e=i.nextNote;if(null!=t){const e=t.pitches[i.prevNotePitchIndex]+t.pins[t.pins.length-1].interval-i.pitches[0];if(_.prevSlideStart&&(D+=e*_.prevSlideRatioStart),_.prevSlideEnd&&(B+=e*_.prevSlideRatioEnd),!m.singleTone){const e=t.pitches.length-i.chordSize;_.prevSlideStart&&(q=jt.computeChordExpression(i.chordSize+e*_.prevSlideRatioStart)),_.prevSlideEnd&&(z=jt.computeChordExpression(i.chordSize+e*_.prevSlideRatioEnd))}}if(null!=e){const t=e.pitches[i.nextNotePitchIndex]-(i.pitches[0]+i.note.pins[i.note.pins.length-1].interval);if(_.nextSlideStart&&(D+=t*_.nextSlideRatioStart),_.nextSlideEnd&&(B+=t*_.nextSlideRatioEnd),!m.singleTone){const t=e.pitches.length-i.chordSize;_.nextSlideStart&&(q=jt.computeChordExpression(i.chordSize+t*_.nextSlideRatioStart)),_.nextSlideEnd&&(z=jt.computeChordExpression(i.chordSize+t*_.nextSlideRatioEnd))}}}if(M(l.effects)){let t=d.justIntonationSemitones[l.pitchShift]/y,n=1,s=1;this.isModActive(d.modulators.dictionary["pitch shift"].index,e,i.instrumentIndex)&&(t=d.justIntonationSemitones[d.justIntonationSemitones.length-1],n=this.getModValue(d.modulators.dictionary["pitch shift"].index,e,i.instrumentIndex,!1)/d.pitchShiftCenter,s=this.getModValue(d.modulators.dictionary["pitch shift"].index,e,i.instrumentIndex,!0)/d.pitchShiftCenter);D+=t*W[18]*n,B+=t*j[18]*s}if(S(l.effects)||this.isModActive(d.modulators.dictionary["song detune"].index,e,i.instrumentIndex)){const t=W[19],n=j[19];let s=l.detune,o=l.detune;this.isModActive(d.modulators.dictionary.detune.index,e,i.instrumentIndex)&&(s=this.getModValue(d.modulators.dictionary.detune.index,e,i.instrumentIndex,!1)+d.detuneCenter,o=this.getModValue(d.modulators.dictionary.detune.index,e,i.instrumentIndex,!0)+d.detuneCenter),this.isModActive(d.modulators.dictionary["song detune"].index,e,i.instrumentIndex)&&(s+=4*this.getModValue(d.modulators.dictionary["song detune"].index,e,i.instrumentIndex,!1),o+=4*this.getModValue(d.modulators.dictionary["song detune"].index,e,i.instrumentIndex,!0)),D+=jt.detuneToCents(s*t)*d.pitchesPerOctave/1200,B+=jt.detuneToCents(o*n)*d.pitchesPerOctave/1200}if(F(l.effects)){let t,n,s,o;if(l.vibrato==d.vibratos.length?(t=2*l.vibratoDelay,l.vibratoDelay==d.modulators.dictionary["vibrato delay"].maxRawVol&&(t=Number.POSITIVE_INFINITY),n=l.vibratoDepth,s=n):(t=d.vibratos[l.vibrato].delayTicks,n=d.vibratos[l.vibrato].amplitude,s=n),this.isModActive(d.modulators.dictionary["vibrato delay"].index,e,i.instrumentIndex)&&(t=2*this.getModValue(d.modulators.dictionary["vibrato delay"].index,e,i.instrumentIndex,!1),t==2*d.modulators.dictionary["vibrato delay"].maxRawVol&&(t=Number.POSITIVE_INFINITY)),this.isModActive(d.modulators.dictionary["vibrato depth"].index,e,i.instrumentIndex)&&(n=this.getModValue(d.modulators.dictionary["vibrato depth"].index,e,i.instrumentIndex,!1)/25,s=this.getModValue(d.modulators.dictionary["vibrato depth"].index,e,i.instrumentIndex,!0)/25),null!=i.prevVibrato)o=i.prevVibrato;else{if(o=n*jt.getLFOAmplitude(l,b*l.LFOtime)*W[20],t>0){const e=t-_.noteTicksStart;o*=Math.max(0,Math.min(1,1-e/2))}}let a=jt.getLFOAmplitude(l,b*l.nextLFOtime);const r=j[20];if(9!=l.type){let e=s*a*r;if(t>0){const n=t-_.noteTicksEnd;e*=Math.max(0,Math.min(1,1-n/2))}i.prevVibrato=e,D+=o,B+=e}}if(!p.isSeamless&&!i.forceContinueAtStart||null==i.prevNote){const t=l.getFadeInSeconds();t>0&&(I*=Math.min(1,_.noteSecondsStart/t),L*=Math.min(1,_.noteSecondsEnd/t))}4==l.type&&null==i.drumsetPitch&&(i.drumsetPitch=i.pitches[0],null!=i.note&&(i.drumsetPitch+=i.note.pickMainInterval()),i.drumsetPitch=Math.max(0,Math.min(d.drumCount-1,i.drumsetPitch)));let U=_.lowpassCutoffDecayVolumeCompensation;if(C(l.effects)){const t=W[1],e=j[1];if(l.noteFilterType){const n=W[21],s=j[21],o=W[29],r=j[29];H.toCoefficients(jt.tempFilterStartCoefficients,this.samplesPerSecond,t*n,o),V.toCoefficients(jt.tempFilterEndCoefficients,this.samplesPerSecond,e*s,r),i.noteFilters.length<1&&(i.noteFilters[0]=new dt),i.noteFilters[0].loadCoefficientsWithGradient(jt.tempFilterStartCoefficients,jt.tempFilterEndCoefficients,1/a,0==H.type),U*=H.getVolumeCompensationMult(),i.noteFilterCount=1}else{const n=null!=l.tmpNoteFilterStart?l.tmpNoteFilterStart:l.noteFilter;for(let s=0;s1&&o){const t=Math.floor(l.arpTime/d.ticksPerArpeggio);s=i.pitches[w(i.pitchCount,l.fastTwoNoteArp,t)]-i.pitches[0]}const r=10==l.type?l.customAlgorithm.carrierCount:d.algorithms[l.algorithm].carrierCount;for(let h=0;h<(10==l.type?6:d.operatorCount);h++){const c=10==l.type?l.customAlgorithm.associatedCarrier[h]-1:d.algorithms[l.algorithm].associatedCarrier[h]-1,p=i.pitches[o?0:h1&&(m.arpeggiates||m.customInterval)){const t=Math.floor(l.arpTime/d.ticksPerArpeggio);if(m.customInterval){const e=i.pitches[1+w(i.pitchCount-1,l.fastTwoNoteArp,t)]-i.pitches[0];T=Math.pow(2,e/12),i.specialIntervalExpressionMult=Math.pow(2,-e/$)}else n=i.pitches[w(i.pitchCount,l.fastTwoNoteArp,t)]}const s=R+(n+D)*y,o=R+(n+B)*y;let r;r=null!=i.prevPitchExpressions[0]?i.prevPitchExpressions[0]:Math.pow(2,-(s-N)/$);const h=Math.pow(2,-(o-N)/$);i.prevPitchExpressions[0]=h;let u=O*U;if(2==l.type&&(u*=d.chipNoises[l.chipNoise].expression),0==l.type&&(u*=d.chipWaves[l.chipWave].expression),6==l.type){const t=l.pulseWidth/(2*d.pulseWidthRange);let n=t,s=t;this.isModActive(d.modulators.dictionary["pulse width"].index,e,i.instrumentIndex)&&(n=this.getModValue(d.modulators.dictionary["pulse width"].index,e,i.instrumentIndex,!1)/(2*d.pulseWidthRange),s=this.getModValue(d.modulators.dictionary["pulse width"].index,e,i.instrumentIndex,!0)/(2*d.pulseWidthRange));const o=n*W[2],r=s*j[2];i.pulseWidth=o,i.pulseWidthDelta=(r-o)/a;let h=l.decimalOffset;this.isModActive(d.modulators.dictionary["decimal offset"].index,e,i.instrumentIndex)&&(h=this.getModValue(d.modulators.dictionary["decimal offset"].index,e,i.instrumentIndex,!1));const c=h*W[37];i.decimalOffset=c,i.pulseWidth-=i.decimalOffset/1e4}if(7==l.type){let t=l.stringSustain,n=l.stringSustain;this.isModActive(d.modulators.dictionary.sustain.index,e,i.instrumentIndex)&&(t=this.getModValue(d.modulators.dictionary.sustain.index,e,i.instrumentIndex,!1),n=this.getModValue(d.modulators.dictionary.sustain.index,e,i.instrumentIndex,!0)),i.stringSustainStart=t,i.stringSustainEnd=n,u*=Math.pow(2,.7*(1-t/(d.stringSustainRange-1)))}const f=Rt.frequencyFromPitch(s);if(0==l.type||8==l.type||5==l.type||7==l.type){const e=l.unisonVoices,n=l.unisonSpread,s=l.unisonOffset;u*=l.unisonExpression*(7==l.type?1:e/2);const o=W[4],r=j[4],h=Math.pow(2,(s+n)*o/12),c=Math.pow(2,(s+n)*r/12),d=Math.pow(2,(s-n)*o/12)*T,p=Math.pow(2,(s-n)*r/12)*T;i.phaseDeltas[0]=f*g*h,i.phaseDeltas[1]=f*g*d,i.phaseDeltaScales[0]=t*Math.pow(c/h,1/a),i.phaseDeltaScales[1]=t*Math.pow(p/d,1/a)}else i.phaseDeltas[0]=f*g,i.phaseDeltaScales[0]=t;let b=u*I*q*r*W[0],v=u*L*z*h*j[0];if(this.isModActive(d.modulators.dictionary["note volume"].index,e,i.instrumentIndex)){const t=this.getModValue(d.modulators.dictionary["note volume"].index,e,i.instrumentIndex,!1),n=this.getModValue(d.modulators.dictionary["note volume"].index,e,i.instrumentIndex,!0);b*=t<=0?(t+d.volumeRange/2)/(d.volumeRange/2):jt.instrumentVolumeToVolumeMult(t),v*=n<=0?(n+d.volumeRange/2)/(d.volumeRange/2):jt.instrumentVolumeToVolumeMult(n)}if(i.expression=b,i.expressionDelta=(v-b)/a,7==l.type){let t;if(null!=i.prevStringDecay)t=i.prevStringDecay;else{const e=i.envelopeComputer.envelopeStarts[3];t=1-Math.min(1,e*i.stringSustainStart/(d.stringSustainRange-1))}const e=i.envelopeComputer.envelopeEnds[3];let n=1-Math.min(1,e*i.stringSustainEnd/(d.stringSustainRange-1));i.prevStringDecay=n;const s=l.unisonVoices;for(let t=i.pickedStrings.length;t=0;e--)for(const i of jt.operatorSourceTemplate)if(-1!=i.indexOf("/* + operator@Scaled*/")){let s="";for(const n of d.algorithms[t.algorithm].modulatedBy[e])s+=" + operator"+(n-1)+"Scaled";const o=d.feedbacks[t.feedbackType].indices[e];if(o.length>0){s+=" + feedbackMult * (";const t=[];for(const e of o)t.push("operator"+(e-1)+"Output");s+=t.join(" + ")+")"}n.push(i.replace(/\#/g,e+"").replace("/* + operator@Scaled*/",s))}else n.push(i.replace(/\#/g,e+""));else if(-1!=e.indexOf("#"))for(let t=0;t=0;e--)for(const i of jt.operatorSourceTemplate)if(-1!=i.indexOf("/* + operator@Scaled*/")){let s="";for(const n of t.customAlgorithm.modulatedBy[e])s+=" + operator"+(n-1)+"Scaled";const o=t.customFeedbackType.indices[e];if(o.length>0){s+=" + feedbackMult * (";const t=[];for(const e of o)t.push("operator"+(e-1)+"Output");s+=t.join(" + ")+")"}n.push(i.replace(/\#/g,e+"").replace("/* + operator@Scaled*/",s))}else n.push(i.replace(/\#/g,e+""));else if(-1!=e.indexOf("#"))for(let t=0;t0&&v0&&xl&&(v<=0&&(k=$,v++),e=1):-1===g&&P<0&&(v<=0&&(k=$,v++),e=1),1===w?D>l&&(x<=0&&(M=H,x++),e=1):-1===g&&D<0&&(x<=0&&(M=H,x++),e=1)):3===m?(1===g?P>c&&(v<=0&&(k=$,v++),e=1):-1===g&&Pc&&(x<=0&&(M=H,x++),e=1):-1===g&&Dc&&(P=d+jt.wrap(P-c,p),e=1):-1===g&&Pc&&(D=d+jt.wrap(D-c,p),e=1):-1===w&&Dc&&(P=c-jt.wrap(P-c,p),g=-1,e=1):-1===g&&Pc&&(D=c-jt.wrap(D-c,p),w=-1,e=1):-1===w&&D0?(S-Math.min(v,S))/S:1,e=x>0?(S-Math.min(x,S))/S:1;s=0,s+=v>0?k*t:n,s+=x>0?M*e:i}else{const t=Math.floor(P),o=Math.floor(D),a=jt.wrap(t,l),h=jt.wrap(o,l);let p=r[a],u=r[h];const F=P-t,C=D-o;if(p+=(r[jt.wrap(a+1,l)]-p)*F,u+=(r[jt.wrap(h+1,l)]-u)*C,(0!==m||0!==d||c!==l)&&0!==e){let t=0,e=0;const n=Math.max(0,P-y*g),i=Math.max(0,D-b*w),s=Math.floor(n),o=Math.floor(i),a=jt.wrap(s,l),h=jt.wrap(o,l);t=r[a],e=r[h],t+=(r[jt.wrap(a+1,l)]-t)*(n-s)*g,e+=(r[jt.wrap(h+1,l)]-e)*(i-o)*w,B=t,I=e}1===m&&0!==e?(n=$,i=H):(n=(p-B)/(y*g),i=(u-I)/(b*w)),$=n,H=i,B=p,I=u;const A=v>0?(S-Math.min(v,S))/S:1,E=x>0?(S-Math.min(x,S))/S:1;s+=v>0?k*A:n,s+=x>0?M*E:i*f}const u=R(s*h,z,N,q,L);N=z,z=s*h,y*=F,b*=C;const A=u*E;E+=T,a[t]+=A}i.phases[0]=P/l,i.phases[1]=D/l,i.phaseDeltas[0]=y/l,i.phaseDeltas[1]=b/l,i.directions[0]=g,i.directions[1]=w,i.chipWaveCompletions[0]=v,i.chipWaveCompletions[1]=x,i.chipWavePrevWaves[0]=$,i.chipWavePrevWaves[1]=H,i.chipWaveCompletionsLastWave[0]=k,i.chipWaveCompletionsLastWave[1]=M,i.expression=E,t.sanitizeFilters(L),i.initialNoteFilterInput1=z,i.initialNoteFilterInput2=N}static chipSynth(t,e,n,i,s){const o=A(s.effects)&&s.aliases,a=t.tempMonoInstrumentSampleBuffer,r=s.wave,h=s.volumeScale,l=o&&8==s.type?r.length:r.length-1,c=i.specialIntervalExpressionMult*s.unisonSign;1!=s.unisonVoices||s.chord.customInterval||(i.phases[1]=i.phases[0]);let d=i.phaseDeltas[0]*l,p=i.phaseDeltas[1]*l;const m=+i.phaseDeltaScales[0],u=+i.phaseDeltaScales[1];let f=+i.expression;const y=+i.expressionDelta;let b=i.phases[0]%1*l,g=i.phases[1]%1*l;const w=i.noteFilters,v=0|i.noteFilterCount;let x=+i.initialNoteFilterInput1,k=+i.initialNoteFilterInput2;const M=jt.applyFilters;let S=0,F=0;if(!o){const t=0|b,e=0|g,n=t%l,i=e%l,s=b-t,o=g-e;S=+r[n],F=+r[i],S+=(r[n+1]-S)*s,F+=(r[i+1]-F)*o}const C=e+n;for(let t=e;t> 0;\n\t\t\t\tlet delayIndex# = pickedString#.delayIndex|0;\n\t\t\t\tdelayIndex# = (delayIndex# & delayBufferMask#) + delayLine#.length;\n\t\t\t\tlet delayLength# = +pickedString#.prevDelayLength;\n\t\t\t\tconst delayLengthDelta# = +pickedString#.delayLengthDelta;\n\t\t\t\tlet allPassG# = +pickedString#.allPassG;\n\t\t\t\tlet shelfA1# = +pickedString#.shelfA1;\n\t\t\t\tlet shelfB0# = +pickedString#.shelfB0;\n\t\t\t\tlet shelfB1# = +pickedString#.shelfB1;\n\t\t\t\tconst allPassGDelta# = +pickedString#.allPassGDelta;\n\t\t\t\tconst shelfA1Delta# = +pickedString#.shelfA1Delta;\n\t\t\t\tconst shelfB0Delta# = +pickedString#.shelfB0Delta;\n\t\t\t\tconst shelfB1Delta# = +pickedString#.shelfB1Delta;\n\t\t\t\t\n\t\t\t\tlet expression = +tone.expression;\n\t\t\t\tconst expressionDelta = +tone.expressionDelta;\n\t\t\t\t\n\t\t\t\tconst unisonSign = tone.specialIntervalExpressionMult * instrumentState.unisonSign;\n\t\t\t\tconst delayResetOffset# = pickedString#.delayResetOffset|0;\n\t\t\t\t\n\t\t\t\tconst filters = tone.noteFilters;\n\t\t\t\tconst filterCount = tone.noteFilterCount|0;\n\t\t\t\tlet initialFilterInput1 = +tone.initialNoteFilterInput1;\n\t\t\t\tlet initialFilterInput2 = +tone.initialNoteFilterInput2;\n\t\t\t\tconst applyFilters = Synth.applyFilters;\n\t\t\t\t\n\t\t\t\tconst stopIndex = bufferIndex + runLength;\n\t\t\t\tfor (let sampleIndex = bufferIndex; sampleIndex < stopIndex; sampleIndex++) {\n\t\t\t\t\tconst targetSampleTime# = delayIndex# - delayLength#;\n\t\t\t\t\tconst lowerIndex# = (targetSampleTime# + 0.125) | 0; // Offset to improve stability of all-pass filter.\n\t\t\t\t\tconst upperIndex# = lowerIndex# + 1;\n\t\t\t\t\tconst fractionalDelay# = upperIndex# - targetSampleTime#;\n\t\t\t\t\tconst fractionalDelayG# = (1.0 - fractionalDelay#) / (1.0 + fractionalDelay#); // Inlined version of FilterCoefficients.prototype.allPass1stOrderFractionalDelay\n\t\t\t\t\tconst prevInput# = delayLine#[lowerIndex# & delayBufferMask#];\n\t\t\t\t\tconst input# = delayLine#[upperIndex# & delayBufferMask#];\n\t\t\t\t\tfractionalDelaySample# = fractionalDelayG# * input# + prevInput# - fractionalDelayG# * fractionalDelaySample#;\n\t\t\t\t\t\n\t\t\t\t\tallPassSample# = fractionalDelaySample# * allPassG# + allPassPrevInput# - allPassG# * allPassSample#;\n\t\t\t\t\tallPassPrevInput# = fractionalDelaySample#;\n\t\t\t\t\t\n\t\t\t\t\tshelfSample# = shelfB0# * allPassSample# + shelfB1# * shelfPrevInput# - shelfA1# * shelfSample#;\n\t\t\t\t\tshelfPrevInput# = allPassSample#;\n\t\t\t\t\t\n\t\t\t\t\tdelayLine#[delayIndex# & delayBufferMask#] += shelfSample#;\n\t\t\t\t\tdelayLine#[(delayIndex# + delayResetOffset#) & delayBufferMask#] = 0.0;\n\t\t\t\t\tdelayIndex#++;\n\t\t\t\t\t\n\t\t\t\t\tconst inputSample = (";const e=[];for(let t=0;t{const e=[];for(let n=0;n0,l=T(o.effects),c=P(o.effects),d=D(o.effects),p=B(o.effects);let m=0;a&&(m|=1),m<<=1,r&&(m|=1),m<<=1,h&&(m|=1),m<<=1,l&&(m|=1),m<<=1,c&&(m|=1),m<<=1,d&&(m|=1),m<<=1,p&&(m|=1);let u=jt.effectsFunctionCache[m];if(null==u){let t="";const e=c||p||d;t+="\n\t\t\t\tconst Config = beepbox.Config;\n\t\t\t\tconst tempMonoInstrumentSampleBuffer = synth.tempMonoInstrumentSampleBuffer;\n\t\t\t\t\n\t\t\t\tlet mixVolume = +instrumentState.mixVolume;\n\t\t\t\tconst mixVolumeDelta = +instrumentState.mixVolumeDelta;",e&&(t+="\n\t\t\t\t\n\t\t\t\tlet delayInputMult = +instrumentState.delayInputMult;\n\t\t\t\tconst delayInputMultDelta = +instrumentState.delayInputMultDelta;"),a&&(t+="\n\t\t\t\t\n\t\t\t\tconst distortionBaseVolume = +Config.distortionBaseVolume;\n\t\t\t\tlet distortion = instrumentState.distortion;\n\t\t\t\tconst distortionDelta = instrumentState.distortionDelta;\n\t\t\t\tlet distortionDrive = instrumentState.distortionDrive;\n\t\t\t\tconst distortionDriveDelta = instrumentState.distortionDriveDelta;\n\t\t\t\tconst distortionFractionalResolution = 4.0;\n\t\t\t\tconst distortionOversampleCompensation = distortionBaseVolume / distortionFractionalResolution;\n\t\t\t\tconst distortionFractionalDelay1 = 1.0 / distortionFractionalResolution;\n\t\t\t\tconst distortionFractionalDelay2 = 2.0 / distortionFractionalResolution;\n\t\t\t\tconst distortionFractionalDelay3 = 3.0 / distortionFractionalResolution;\n\t\t\t\tconst distortionFractionalDelayG1 = (1.0 - distortionFractionalDelay1) / (1.0 + distortionFractionalDelay1); // Inlined version of FilterCoefficients.prototype.allPass1stOrderFractionalDelay\n\t\t\t\tconst distortionFractionalDelayG2 = (1.0 - distortionFractionalDelay2) / (1.0 + distortionFractionalDelay2); // Inlined version of FilterCoefficients.prototype.allPass1stOrderFractionalDelay\n\t\t\t\tconst distortionFractionalDelayG3 = (1.0 - distortionFractionalDelay3) / (1.0 + distortionFractionalDelay3); // Inlined version of FilterCoefficients.prototype.allPass1stOrderFractionalDelay\n\t\t\t\tconst distortionNextOutputWeight1 = Math.cos(Math.PI * distortionFractionalDelay1) * 0.5 + 0.5;\n\t\t\t\tconst distortionNextOutputWeight2 = Math.cos(Math.PI * distortionFractionalDelay2) * 0.5 + 0.5;\n\t\t\t\tconst distortionNextOutputWeight3 = Math.cos(Math.PI * distortionFractionalDelay3) * 0.5 + 0.5;\n\t\t\t\tconst distortionPrevOutputWeight1 = 1.0 - distortionNextOutputWeight1;\n\t\t\t\tconst distortionPrevOutputWeight2 = 1.0 - distortionNextOutputWeight2;\n\t\t\t\tconst distortionPrevOutputWeight3 = 1.0 - distortionNextOutputWeight3;\n\t\t\t\t\n\t\t\t\tlet distortionFractionalInput1 = +instrumentState.distortionFractionalInput1;\n\t\t\t\tlet distortionFractionalInput2 = +instrumentState.distortionFractionalInput2;\n\t\t\t\tlet distortionFractionalInput3 = +instrumentState.distortionFractionalInput3;\n\t\t\t\tlet distortionPrevInput = +instrumentState.distortionPrevInput;\n\t\t\t\tlet distortionNextOutput = +instrumentState.distortionNextOutput;"),r&&(t+="\n\t\t\t\t\n\t\t\t\tlet bitcrusherPrevInput = +instrumentState.bitcrusherPrevInput;\n\t\t\t\tlet bitcrusherCurrentOutput = +instrumentState.bitcrusherCurrentOutput;\n\t\t\t\tlet bitcrusherPhase = +instrumentState.bitcrusherPhase;\n\t\t\t\tlet bitcrusherPhaseDelta = +instrumentState.bitcrusherPhaseDelta;\n\t\t\t\tconst bitcrusherPhaseDeltaScale = +instrumentState.bitcrusherPhaseDeltaScale;\n\t\t\t\tlet bitcrusherScale = +instrumentState.bitcrusherScale;\n\t\t\t\tconst bitcrusherScaleScale = +instrumentState.bitcrusherScaleScale;\n\t\t\t\tlet bitcrusherFoldLevel = +instrumentState.bitcrusherFoldLevel;\n\t\t\t\tconst bitcrusherFoldLevelScale = +instrumentState.bitcrusherFoldLevelScale;"),h&&(t+="\n\t\t\t\t\n\t\t\t\tlet filters = instrumentState.eqFilters;\n\t\t\t\tconst filterCount = instrumentState.eqFilterCount|0;\n\t\t\t\tlet initialFilterInput1 = +instrumentState.initialEqFilterInput1;\n\t\t\t\tlet initialFilterInput2 = +instrumentState.initialEqFilterInput2;\n\t\t\t\tconst applyFilters = beepbox.Synth.applyFilters;"),t+="\n\t\t\t\t\n\t\t\t\tlet eqFilterVolume = +instrumentState.eqFilterVolume;\n\t\t\t\tconst eqFilterVolumeDelta = +instrumentState.eqFilterVolumeDelta;",l&&(t+="\n\t\t\t\t\n\t\t\t\tconst panningMask = synth.panningDelayBufferMask >>> 0;\n\t\t\t\tconst panningDelayLine = instrumentState.panningDelayLine;\n\t\t\t\tlet panningDelayPos = instrumentState.panningDelayPos & panningMask;\n\t\t\t\tlet panningVolumeL = +instrumentState.panningVolumeL;\n\t\t\t\tlet panningVolumeR = +instrumentState.panningVolumeR;\n\t\t\t\tconst panningVolumeDeltaL = +instrumentState.panningVolumeDeltaL;\n\t\t\t\tconst panningVolumeDeltaR = +instrumentState.panningVolumeDeltaR;\n\t\t\t\tlet panningOffsetL = +instrumentState.panningOffsetL;\n\t\t\t\tlet panningOffsetR = +instrumentState.panningOffsetR;\n\t\t\t\tconst panningOffsetDeltaL = 1.0 - instrumentState.panningOffsetDeltaL;\n\t\t\t\tconst panningOffsetDeltaR = 1.0 - instrumentState.panningOffsetDeltaR;"),c&&(t+="\n\t\t\t\t\n\t\t\t\tconst chorusMask = synth.chorusDelayBufferMask >>> 0;\n\t\t\t\tconst chorusDelayLineL = instrumentState.chorusDelayLineL;\n\t\t\t\tconst chorusDelayLineR = instrumentState.chorusDelayLineR;\n\t\t\t\tinstrumentState.chorusDelayLineDirty = true;\n\t\t\t\tlet chorusDelayPos = instrumentState.chorusDelayPos & chorusMask;\n\t\t\t\t\n\t\t\t\tlet chorusVoiceMult = +instrumentState.chorusVoiceMult;\n\t\t\t\tconst chorusVoiceMultDelta = +instrumentState.chorusVoiceMultDelta;\n\t\t\t\tlet chorusCombinedMult = +instrumentState.chorusCombinedMult;\n\t\t\t\tconst chorusCombinedMultDelta = +instrumentState.chorusCombinedMultDelta;\n\t\t\t\t\n\t\t\t\tconst chorusDuration = +beepbox.Config.chorusPeriodSeconds;\n\t\t\t\tconst chorusAngle = Math.PI * 2.0 / (chorusDuration * synth.samplesPerSecond);\n\t\t\t\tconst chorusRange = synth.samplesPerSecond * beepbox.Config.chorusDelayRange;\n\t\t\t\tconst chorusOffset0 = synth.chorusDelayBufferSize - beepbox.Config.chorusDelayOffsets[0][0] * chorusRange;\n\t\t\t\tconst chorusOffset1 = synth.chorusDelayBufferSize - beepbox.Config.chorusDelayOffsets[0][1] * chorusRange;\n\t\t\t\tconst chorusOffset2 = synth.chorusDelayBufferSize - beepbox.Config.chorusDelayOffsets[0][2] * chorusRange;\n\t\t\t\tconst chorusOffset3 = synth.chorusDelayBufferSize - beepbox.Config.chorusDelayOffsets[1][0] * chorusRange;\n\t\t\t\tconst chorusOffset4 = synth.chorusDelayBufferSize - beepbox.Config.chorusDelayOffsets[1][1] * chorusRange;\n\t\t\t\tconst chorusOffset5 = synth.chorusDelayBufferSize - beepbox.Config.chorusDelayOffsets[1][2] * chorusRange;\n\t\t\t\tlet chorusPhase = instrumentState.chorusPhase % (Math.PI * 2.0);\n\t\t\t\tlet chorusTap0Index = chorusDelayPos + chorusOffset0 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[0][0]);\n\t\t\t\tlet chorusTap1Index = chorusDelayPos + chorusOffset1 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[0][1]);\n\t\t\t\tlet chorusTap2Index = chorusDelayPos + chorusOffset2 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[0][2]);\n\t\t\t\tlet chorusTap3Index = chorusDelayPos + chorusOffset3 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[1][0]);\n\t\t\t\tlet chorusTap4Index = chorusDelayPos + chorusOffset4 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[1][1]);\n\t\t\t\tlet chorusTap5Index = chorusDelayPos + chorusOffset5 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[1][2]);\n\t\t\t\tchorusPhase += chorusAngle * runLength;\n\t\t\t\tconst chorusTap0End = chorusDelayPos + chorusOffset0 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[0][0]) + runLength;\n\t\t\t\tconst chorusTap1End = chorusDelayPos + chorusOffset1 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[0][1]) + runLength;\n\t\t\t\tconst chorusTap2End = chorusDelayPos + chorusOffset2 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[0][2]) + runLength;\n\t\t\t\tconst chorusTap3End = chorusDelayPos + chorusOffset3 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[1][0]) + runLength;\n\t\t\t\tconst chorusTap4End = chorusDelayPos + chorusOffset4 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[1][1]) + runLength;\n\t\t\t\tconst chorusTap5End = chorusDelayPos + chorusOffset5 - chorusRange * Math.sin(chorusPhase + beepbox.Config.chorusPhaseOffsets[1][2]) + runLength;\n\t\t\t\tconst chorusTap0Delta = (chorusTap0End - chorusTap0Index) / runLength;\n\t\t\t\tconst chorusTap1Delta = (chorusTap1End - chorusTap1Index) / runLength;\n\t\t\t\tconst chorusTap2Delta = (chorusTap2End - chorusTap2Index) / runLength;\n\t\t\t\tconst chorusTap3Delta = (chorusTap3End - chorusTap3Index) / runLength;\n\t\t\t\tconst chorusTap4Delta = (chorusTap4End - chorusTap4Index) / runLength;\n\t\t\t\tconst chorusTap5Delta = (chorusTap5End - chorusTap5Index) / runLength;"),d&&(t+="\n\t\t\t\t\n\t\t\t\tlet echoMult = +instrumentState.echoMult;\n\t\t\t\tconst echoMultDelta = +instrumentState.echoMultDelta;\n\t\t\t\t\n\t\t\t\tconst echoDelayLineL = instrumentState.echoDelayLineL;\n\t\t\t\tconst echoDelayLineR = instrumentState.echoDelayLineR;\n\t\t\t\tconst echoMask = (echoDelayLineL.length - 1) >>> 0;\n\t\t\t\tinstrumentState.echoDelayLineDirty = true;\n\t\t\t\t\n\t\t\t\tlet echoDelayPos = instrumentState.echoDelayPos & echoMask;\n\t\t\t\tconst echoDelayOffsetStart = (echoDelayLineL.length - instrumentState.echoDelayOffsetStart) & echoMask;\n\t\t\t\tconst echoDelayOffsetEnd = (echoDelayLineL.length - instrumentState.echoDelayOffsetEnd) & echoMask;\n\t\t\t\tlet echoDelayOffsetRatio = +instrumentState.echoDelayOffsetRatio;\n\t\t\t\tconst echoDelayOffsetRatioDelta = +instrumentState.echoDelayOffsetRatioDelta;\n\t\t\t\t\n\t\t\t\tconst echoShelfA1 = +instrumentState.echoShelfA1;\n\t\t\t\tconst echoShelfB0 = +instrumentState.echoShelfB0;\n\t\t\t\tconst echoShelfB1 = +instrumentState.echoShelfB1;\n\t\t\t\tlet echoShelfSampleL = +instrumentState.echoShelfSampleL;\n\t\t\t\tlet echoShelfSampleR = +instrumentState.echoShelfSampleR;\n\t\t\t\tlet echoShelfPrevInputL = +instrumentState.echoShelfPrevInputL;\n\t\t\t\tlet echoShelfPrevInputR = +instrumentState.echoShelfPrevInputR;"),p&&(t+="\n\t\t\t\t\n\t\t\t\tconst reverbMask = Config.reverbDelayBufferMask >>> 0; //TODO: Dynamic reverb buffer size.\n\t\t\t\tconst reverbDelayLine = instrumentState.reverbDelayLine;\n\t\t\t\tinstrumentState.reverbDelayLineDirty = true;\n\t\t\t\tlet reverbDelayPos = instrumentState.reverbDelayPos & reverbMask;\n\t\t\t\t\n\t\t\t\tlet reverb = +instrumentState.reverbMult;\n\t\t\t\tconst reverbDelta = +instrumentState.reverbMultDelta;\n\t\t\t\t\n\t\t\t\tconst reverbShelfA1 = +instrumentState.reverbShelfA1;\n\t\t\t\tconst reverbShelfB0 = +instrumentState.reverbShelfB0;\n\t\t\t\tconst reverbShelfB1 = +instrumentState.reverbShelfB1;\n\t\t\t\tlet reverbShelfSample0 = +instrumentState.reverbShelfSample0;\n\t\t\t\tlet reverbShelfSample1 = +instrumentState.reverbShelfSample1;\n\t\t\t\tlet reverbShelfSample2 = +instrumentState.reverbShelfSample2;\n\t\t\t\tlet reverbShelfSample3 = +instrumentState.reverbShelfSample3;\n\t\t\t\tlet reverbShelfPrevInput0 = +instrumentState.reverbShelfPrevInput0;\n\t\t\t\tlet reverbShelfPrevInput1 = +instrumentState.reverbShelfPrevInput1;\n\t\t\t\tlet reverbShelfPrevInput2 = +instrumentState.reverbShelfPrevInput2;\n\t\t\t\tlet reverbShelfPrevInput3 = +instrumentState.reverbShelfPrevInput3;"),t+="\n\t\t\t\t\n\t\t\t\tconst stopIndex = bufferIndex + runLength;\n\t\t\t\tfor (let sampleIndex = bufferIndex; sampleIndex < stopIndex; sampleIndex++) {\n\t\t\t\t\tlet sample = tempMonoInstrumentSampleBuffer[sampleIndex];\n\t\t\t\t\ttempMonoInstrumentSampleBuffer[sampleIndex] = 0.0;",a&&(t+="\n\t\t\t\t\t\n\t\t\t\t\tconst distortionReverse = 1.0 - distortion;\n\t\t\t\t\tconst distortionNextInput = sample * distortionDrive;\n\t\t\t\t\tsample = distortionNextOutput;\n\t\t\t\t\tdistortionNextOutput = distortionNextInput / (distortionReverse * Math.abs(distortionNextInput) + distortion);\n\t\t\t\t\tdistortionFractionalInput1 = distortionFractionalDelayG1 * distortionNextInput + distortionPrevInput - distortionFractionalDelayG1 * distortionFractionalInput1;\n\t\t\t\t\tdistortionFractionalInput2 = distortionFractionalDelayG2 * distortionNextInput + distortionPrevInput - distortionFractionalDelayG2 * distortionFractionalInput2;\n\t\t\t\t\tdistortionFractionalInput3 = distortionFractionalDelayG3 * distortionNextInput + distortionPrevInput - distortionFractionalDelayG3 * distortionFractionalInput3;\n\t\t\t\t\tconst distortionOutput1 = distortionFractionalInput1 / (distortionReverse * Math.abs(distortionFractionalInput1) + distortion);\n\t\t\t\t\tconst distortionOutput2 = distortionFractionalInput2 / (distortionReverse * Math.abs(distortionFractionalInput2) + distortion);\n\t\t\t\t\tconst distortionOutput3 = distortionFractionalInput3 / (distortionReverse * Math.abs(distortionFractionalInput3) + distortion);\n\t\t\t\t\tdistortionNextOutput += distortionOutput1 * distortionNextOutputWeight1 + distortionOutput2 * distortionNextOutputWeight2 + distortionOutput3 * distortionNextOutputWeight3;\n\t\t\t\t\tsample += distortionOutput1 * distortionPrevOutputWeight1 + distortionOutput2 * distortionPrevOutputWeight2 + distortionOutput3 * distortionPrevOutputWeight3;\n\t\t\t\t\tsample *= distortionOversampleCompensation;\n\t\t\t\t\tdistortionPrevInput = distortionNextInput;\n\t\t\t\t\tdistortion += distortionDelta;\n\t\t\t\t\tdistortionDrive += distortionDriveDelta;"),r&&(t+="\n\t\t\t\t\t\n\t\t\t\t\tbitcrusherPhase += bitcrusherPhaseDelta;\n\t\t\t\t\tif (bitcrusherPhase < 1.0) {\n\t\t\t\t\t\tbitcrusherPrevInput = sample;\n\t\t\t\t\t\tsample = bitcrusherCurrentOutput;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbitcrusherPhase = bitcrusherPhase % 1.0;\n\t\t\t\t\t\tconst ratio = bitcrusherPhase / bitcrusherPhaseDelta;\n\t\t\t\t\t\t\n\t\t\t\t\t\tconst lerpedInput = sample + (bitcrusherPrevInput - sample) * ratio;\n\t\t\t\t\t\tbitcrusherPrevInput = sample;\n\t\t\t\t\t\t\n\t\t\t\t\t\tconst bitcrusherWrapLevel = bitcrusherFoldLevel * 4.0;\n\t\t\t\t\t\tconst wrappedSample = (((lerpedInput + bitcrusherFoldLevel) % bitcrusherWrapLevel) + bitcrusherWrapLevel) % bitcrusherWrapLevel;\n\t\t\t\t\t\tconst foldedSample = bitcrusherFoldLevel - Math.abs(bitcrusherFoldLevel * 2.0 - wrappedSample);\n\t\t\t\t\t\tconst scaledSample = foldedSample / bitcrusherScale;\n\t\t\t\t\t\tconst oldValue = bitcrusherCurrentOutput;\n\t\t\t\t\t\tconst newValue = (((scaledSample > 0 ? scaledSample + 1 : scaledSample)|0)-.5) * bitcrusherScale;\n\t\t\t\t\t\t\n\t\t\t\t\t\tsample = oldValue + (newValue - oldValue) * ratio;\n\t\t\t\t\t\tbitcrusherCurrentOutput = newValue;\n\t\t\t\t\t}\n\t\t\t\t\tbitcrusherPhaseDelta *= bitcrusherPhaseDeltaScale;\n\t\t\t\t\tbitcrusherScale *= bitcrusherScaleScale;\n\t\t\t\t\tbitcrusherFoldLevel *= bitcrusherFoldLevelScale;"),h&&(t+="\n\t\t\t\t\t\n\t\t\t\t\tconst inputSample = sample;\n\t\t\t\t\tsample = applyFilters(inputSample, initialFilterInput1, initialFilterInput2, filterCount, filters);\n\t\t\t\t\tinitialFilterInput2 = initialFilterInput1;\n\t\t\t\t\tinitialFilterInput1 = inputSample;"),t+="\n\t\t\t\t\t\n\t\t\t\t\tsample *= eqFilterVolume;\n\t\t\t\t\teqFilterVolume += eqFilterVolumeDelta;",t+=l?"\n\t\t\t\t\t\n\t\t\t\t\tpanningDelayLine[panningDelayPos] = sample;\n\t\t\t\t\tconst panningRatioL = panningOffsetL % 1;\n\t\t\t\t\tconst panningRatioR = panningOffsetR % 1;\n\t\t\t\t\tconst panningTapLA = panningDelayLine[(panningOffsetL) & panningMask];\n\t\t\t\t\tconst panningTapLB = panningDelayLine[(panningOffsetL + 1) & panningMask];\n\t\t\t\t\tconst panningTapRA = panningDelayLine[(panningOffsetR) & panningMask];\n\t\t\t\t\tconst panningTapRB = panningDelayLine[(panningOffsetR + 1) & panningMask];\n\t\t\t\t\tconst panningTapL = panningTapLA + (panningTapLB - panningTapLA) * panningRatioL;\n\t\t\t\t\tconst panningTapR = panningTapRA + (panningTapRB - panningTapRA) * panningRatioR;\n\t\t\t\t\tlet sampleL = panningTapL * panningVolumeL;\n\t\t\t\t\tlet sampleR = panningTapR * panningVolumeR;\n\t\t\t\t\tpanningDelayPos = (panningDelayPos + 1) & panningMask;\n\t\t\t\t\tpanningVolumeL += panningVolumeDeltaL;\n\t\t\t\t\tpanningVolumeR += panningVolumeDeltaR;\n\t\t\t\t\tpanningOffsetL += panningOffsetDeltaL;\n\t\t\t\t\tpanningOffsetR += panningOffsetDeltaR;":"\n\t\t\t\t\t\n\t\t\t\t\tlet sampleL = sample;\n\t\t\t\t\tlet sampleR = sample;",c&&(t+="\n\t\t\t\t\t\n\t\t\t\t\tconst chorusTap0Ratio = chorusTap0Index % 1;\n\t\t\t\t\tconst chorusTap1Ratio = chorusTap1Index % 1;\n\t\t\t\t\tconst chorusTap2Ratio = chorusTap2Index % 1;\n\t\t\t\t\tconst chorusTap3Ratio = chorusTap3Index % 1;\n\t\t\t\t\tconst chorusTap4Ratio = chorusTap4Index % 1;\n\t\t\t\t\tconst chorusTap5Ratio = chorusTap5Index % 1;\n\t\t\t\t\tconst chorusTap0A = chorusDelayLineL[(chorusTap0Index) & chorusMask];\n\t\t\t\t\tconst chorusTap0B = chorusDelayLineL[(chorusTap0Index + 1) & chorusMask];\n\t\t\t\t\tconst chorusTap1A = chorusDelayLineL[(chorusTap1Index) & chorusMask];\n\t\t\t\t\tconst chorusTap1B = chorusDelayLineL[(chorusTap1Index + 1) & chorusMask];\n\t\t\t\t\tconst chorusTap2A = chorusDelayLineL[(chorusTap2Index) & chorusMask];\n\t\t\t\t\tconst chorusTap2B = chorusDelayLineL[(chorusTap2Index + 1) & chorusMask];\n\t\t\t\t\tconst chorusTap3A = chorusDelayLineR[(chorusTap3Index) & chorusMask];\n\t\t\t\t\tconst chorusTap3B = chorusDelayLineR[(chorusTap3Index + 1) & chorusMask];\n\t\t\t\t\tconst chorusTap4A = chorusDelayLineR[(chorusTap4Index) & chorusMask];\n\t\t\t\t\tconst chorusTap4B = chorusDelayLineR[(chorusTap4Index + 1) & chorusMask];\n\t\t\t\t\tconst chorusTap5A = chorusDelayLineR[(chorusTap5Index) & chorusMask];\n\t\t\t\t\tconst chorusTap5B = chorusDelayLineR[(chorusTap5Index + 1) & chorusMask];\n\t\t\t\t\tconst chorusTap0 = chorusTap0A + (chorusTap0B - chorusTap0A) * chorusTap0Ratio;\n\t\t\t\t\tconst chorusTap1 = chorusTap1A + (chorusTap1B - chorusTap1A) * chorusTap1Ratio;\n\t\t\t\t\tconst chorusTap2 = chorusTap2A + (chorusTap2B - chorusTap2A) * chorusTap2Ratio;\n\t\t\t\t\tconst chorusTap3 = chorusTap3A + (chorusTap3B - chorusTap3A) * chorusTap3Ratio;\n\t\t\t\t\tconst chorusTap4 = chorusTap4A + (chorusTap4B - chorusTap4A) * chorusTap4Ratio;\n\t\t\t\t\tconst chorusTap5 = chorusTap5A + (chorusTap5B - chorusTap5A) * chorusTap5Ratio;\n\t\t\t\t\tchorusDelayLineL[chorusDelayPos] = sampleL * delayInputMult;\n\t\t\t\t\tchorusDelayLineR[chorusDelayPos] = sampleR * delayInputMult;\n\t\t\t\t\tsampleL = chorusCombinedMult * (sampleL + chorusVoiceMult * (chorusTap1 - chorusTap0 - chorusTap2));\n\t\t\t\t\tsampleR = chorusCombinedMult * (sampleR + chorusVoiceMult * (chorusTap4 - chorusTap3 - chorusTap5));\n\t\t\t\t\tchorusDelayPos = (chorusDelayPos + 1) & chorusMask;\n\t\t\t\t\tchorusTap0Index += chorusTap0Delta;\n\t\t\t\t\tchorusTap1Index += chorusTap1Delta;\n\t\t\t\t\tchorusTap2Index += chorusTap2Delta;\n\t\t\t\t\tchorusTap3Index += chorusTap3Delta;\n\t\t\t\t\tchorusTap4Index += chorusTap4Delta;\n\t\t\t\t\tchorusTap5Index += chorusTap5Delta;\n\t\t\t\t\tchorusVoiceMult += chorusVoiceMultDelta;\n\t\t\t\t\tchorusCombinedMult += chorusCombinedMultDelta;"),d&&(t+="\n\t\t\t\t\t\n\t\t\t\t\tconst echoTapStartIndex = (echoDelayPos + echoDelayOffsetStart) & echoMask;\n\t\t\t\t\tconst echoTapEndIndex = (echoDelayPos + echoDelayOffsetEnd ) & echoMask;\n\t\t\t\t\tconst echoTapStartL = echoDelayLineL[echoTapStartIndex];\n\t\t\t\t\tconst echoTapEndL = echoDelayLineL[echoTapEndIndex];\n\t\t\t\t\tconst echoTapStartR = echoDelayLineR[echoTapStartIndex];\n\t\t\t\t\tconst echoTapEndR = echoDelayLineR[echoTapEndIndex];\n\t\t\t\t\tconst echoTapL = (echoTapStartL + (echoTapEndL - echoTapStartL) * echoDelayOffsetRatio) * echoMult;\n\t\t\t\t\tconst echoTapR = (echoTapStartR + (echoTapEndR - echoTapStartR) * echoDelayOffsetRatio) * echoMult;\n\t\t\t\t\t\n\t\t\t\t\techoShelfSampleL = echoShelfB0 * echoTapL + echoShelfB1 * echoShelfPrevInputL - echoShelfA1 * echoShelfSampleL;\n\t\t\t\t\techoShelfSampleR = echoShelfB0 * echoTapR + echoShelfB1 * echoShelfPrevInputR - echoShelfA1 * echoShelfSampleR;\n\t\t\t\t\techoShelfPrevInputL = echoTapL;\n\t\t\t\t\techoShelfPrevInputR = echoTapR;\n\t\t\t\t\tsampleL += echoShelfSampleL;\n\t\t\t\t\tsampleR += echoShelfSampleR;\n\t\t\t\t\t\n\t\t\t\t\techoDelayLineL[echoDelayPos] = sampleL * delayInputMult;\n\t\t\t\t\techoDelayLineR[echoDelayPos] = sampleR * delayInputMult;\n\t\t\t\t\techoDelayPos = (echoDelayPos + 1) & echoMask;\n\t\t\t\t\techoDelayOffsetRatio += echoDelayOffsetRatioDelta;\n\t\t\t\t\techoMult += echoMultDelta;\n "),p&&(t+="\n\t\t\t\t\t\n\t\t\t\t\t// Reverb, implemented using a feedback delay network with a Hadamard matrix and lowpass filters.\n\t\t\t\t\t// good ratios: 0.555235 + 0.618033 + 0.818 + 1.0 = 2.991268\n\t\t\t\t\t// Delay lengths: 3041 + 3385 + 4481 + 5477 = 16384 = 2^14\n\t\t\t\t\t// Buffer offsets: 3041 -> 6426 -> 10907 -> 16384\n\t\t\t\t\tconst reverbDelayPos1 = (reverbDelayPos + 3041) & reverbMask;\n\t\t\t\t\tconst reverbDelayPos2 = (reverbDelayPos + 6426) & reverbMask;\n\t\t\t\t\tconst reverbDelayPos3 = (reverbDelayPos + 10907) & reverbMask;\n\t\t\t\t\tconst reverbSample0 = (reverbDelayLine[reverbDelayPos]);\n\t\t\t\t\tconst reverbSample1 = reverbDelayLine[reverbDelayPos1];\n\t\t\t\t\tconst reverbSample2 = reverbDelayLine[reverbDelayPos2];\n\t\t\t\t\tconst reverbSample3 = reverbDelayLine[reverbDelayPos3];\n\t\t\t\t\tconst reverbTemp0 = -(reverbSample0 + sampleL) + reverbSample1;\n\t\t\t\t\tconst reverbTemp1 = -(reverbSample0 + sampleR) - reverbSample1;\n\t\t\t\t\tconst reverbTemp2 = -reverbSample2 + reverbSample3;\n\t\t\t\t\tconst reverbTemp3 = -reverbSample2 - reverbSample3;\n\t\t\t\t\tconst reverbShelfInput0 = (reverbTemp0 + reverbTemp2) * reverb;\n\t\t\t\t\tconst reverbShelfInput1 = (reverbTemp1 + reverbTemp3) * reverb;\n\t\t\t\t\tconst reverbShelfInput2 = (reverbTemp0 - reverbTemp2) * reverb;\n\t\t\t\t\tconst reverbShelfInput3 = (reverbTemp1 - reverbTemp3) * reverb;\n\t\t\t\t\treverbShelfSample0 = reverbShelfB0 * reverbShelfInput0 + reverbShelfB1 * reverbShelfPrevInput0 - reverbShelfA1 * reverbShelfSample0;\n\t\t\t\t\treverbShelfSample1 = reverbShelfB0 * reverbShelfInput1 + reverbShelfB1 * reverbShelfPrevInput1 - reverbShelfA1 * reverbShelfSample1;\n\t\t\t\t\treverbShelfSample2 = reverbShelfB0 * reverbShelfInput2 + reverbShelfB1 * reverbShelfPrevInput2 - reverbShelfA1 * reverbShelfSample2;\n\t\t\t\t\treverbShelfSample3 = reverbShelfB0 * reverbShelfInput3 + reverbShelfB1 * reverbShelfPrevInput3 - reverbShelfA1 * reverbShelfSample3;\n\t\t\t\t\treverbShelfPrevInput0 = reverbShelfInput0;\n\t\t\t\t\treverbShelfPrevInput1 = reverbShelfInput1;\n\t\t\t\t\treverbShelfPrevInput2 = reverbShelfInput2;\n\t\t\t\t\treverbShelfPrevInput3 = reverbShelfInput3;\n\t\t\t\t\treverbDelayLine[reverbDelayPos1] = reverbShelfSample0 * delayInputMult;\n\t\t\t\t\treverbDelayLine[reverbDelayPos2] = reverbShelfSample1 * delayInputMult;\n\t\t\t\t\treverbDelayLine[reverbDelayPos3] = reverbShelfSample2 * delayInputMult;\n\t\t\t\t\treverbDelayLine[reverbDelayPos ] = reverbShelfSample3 * delayInputMult;\n\t\t\t\t\treverbDelayPos = (reverbDelayPos + 1) & reverbMask;\n\t\t\t\t\tsampleL += reverbSample1 + reverbSample2 + reverbSample3;\n\t\t\t\t\tsampleR += reverbSample0 + reverbSample2 - reverbSample3;\n\t\t\t\t\treverb += reverbDelta;"),t+="\n\t\t\t\t\t\n\t\t\t\t\toutputDataL[sampleIndex] += sampleL * mixVolume;\n\t\t\t\t\toutputDataR[sampleIndex] += sampleR * mixVolume;\n\t\t\t\t\tmixVolume += mixVolumeDelta;",e&&(t+="\n\t\t\t\t\t\n\t\t\t\t\tdelayInputMult += delayInputMultDelta;"),t+="\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tinstrumentState.mixVolume = mixVolume;\n\t\t\t\tinstrumentState.eqFilterVolume = eqFilterVolume;\n\t\t\t\t\n\t\t\t\t// Avoid persistent denormal or NaN values in the delay buffers and filter history.\n\t\t\t\tconst epsilon = (1.0e-24);",e&&(t+="\n\t\t\t\t\n\t\t\t\tinstrumentState.delayInputMult = delayInputMult;"),a&&(t+="\n\t\t\t\t\n\t\t\t\tinstrumentState.distortion = distortion;\n\t\t\t\tinstrumentState.distortionDrive = distortionDrive;\n\t\t\t\t\n\t\t\t\tif (!Number.isFinite(distortionFractionalInput1) || Math.abs(distortionFractionalInput1) < epsilon) distortionFractionalInput1 = 0.0;\n\t\t\t\tif (!Number.isFinite(distortionFractionalInput2) || Math.abs(distortionFractionalInput2) < epsilon) distortionFractionalInput2 = 0.0;\n\t\t\t\tif (!Number.isFinite(distortionFractionalInput3) || Math.abs(distortionFractionalInput3) < epsilon) distortionFractionalInput3 = 0.0;\n\t\t\t\tif (!Number.isFinite(distortionPrevInput) || Math.abs(distortionPrevInput) < epsilon) distortionPrevInput = 0.0;\n\t\t\t\tif (!Number.isFinite(distortionNextOutput) || Math.abs(distortionNextOutput) < epsilon) distortionNextOutput = 0.0;\n\t\t\t\t\n\t\t\t\tinstrumentState.distortionFractionalInput1 = distortionFractionalInput1;\n\t\t\t\tinstrumentState.distortionFractionalInput2 = distortionFractionalInput2;\n\t\t\t\tinstrumentState.distortionFractionalInput3 = distortionFractionalInput3;\n\t\t\t\tinstrumentState.distortionPrevInput = distortionPrevInput;\n\t\t\t\tinstrumentState.distortionNextOutput = distortionNextOutput;"),r&&(t+="\n\t\t\t\t\t\n\t\t\t\tif (Math.abs(bitcrusherPrevInput) < epsilon) bitcrusherPrevInput = 0.0;\n\t\t\t\tif (Math.abs(bitcrusherCurrentOutput) < epsilon) bitcrusherCurrentOutput = 0.0;\n\t\t\t\tinstrumentState.bitcrusherPrevInput = bitcrusherPrevInput;\n\t\t\t\tinstrumentState.bitcrusherCurrentOutput = bitcrusherCurrentOutput;\n\t\t\t\tinstrumentState.bitcrusherPhase = bitcrusherPhase;\n\t\t\t\tinstrumentState.bitcrusherPhaseDelta = bitcrusherPhaseDelta;\n\t\t\t\tinstrumentState.bitcrusherScale = bitcrusherScale;\n\t\t\t\tinstrumentState.bitcrusherFoldLevel = bitcrusherFoldLevel;"),h&&(t+="\n\t\t\t\t\t\n\t\t\t\tsynth.sanitizeFilters(filters);\n\t\t\t\t// The filter input here is downstream from another filter so we\n\t\t\t\t// better make sure it's safe too.\n\t\t\t\tif (!(initialFilterInput1 < 100) || !(initialFilterInput2 < 100)) {\n\t\t\t\t\tinitialFilterInput1 = 0.0;\n\t\t\t\t\tinitialFilterInput2 = 0.0;\n\t\t\t\t}\n\t\t\t\tif (Math.abs(initialFilterInput1) < epsilon) initialFilterInput1 = 0.0;\n\t\t\t\tif (Math.abs(initialFilterInput2) < epsilon) initialFilterInput2 = 0.0;\n\t\t\t\tinstrumentState.initialEqFilterInput1 = initialFilterInput1;\n\t\t\t\tinstrumentState.initialEqFilterInput2 = initialFilterInput2;"),l&&(t+="\n\t\t\t\t\n\t\t\t\tbeepbox.Synth.sanitizeDelayLine(panningDelayLine, panningDelayPos, panningMask);\n\t\t\t\tinstrumentState.panningDelayPos = panningDelayPos;\n\t\t\t\tinstrumentState.panningVolumeL = panningVolumeL;\n\t\t\t\tinstrumentState.panningVolumeR = panningVolumeR;\n\t\t\t\tinstrumentState.panningOffsetL = panningOffsetL;\n\t\t\t\tinstrumentState.panningOffsetR = panningOffsetR;"),c&&(t+="\n\t\t\t\t\n\t\t\t\tbeepbox.Synth.sanitizeDelayLine(chorusDelayLineL, chorusDelayPos, chorusMask);\n\t\t\t\tbeepbox.Synth.sanitizeDelayLine(chorusDelayLineR, chorusDelayPos, chorusMask);\n\t\t\t\tinstrumentState.chorusPhase = chorusPhase;\n\t\t\t\tinstrumentState.chorusDelayPos = chorusDelayPos;\n\t\t\t\tinstrumentState.chorusVoiceMult = chorusVoiceMult;\n\t\t\t\tinstrumentState.chorusCombinedMult = chorusCombinedMult;"),d&&(t+="\n\t\t\t\t\n\t\t\t\tbeepbox.Synth.sanitizeDelayLine(echoDelayLineL, echoDelayPos, echoMask);\n\t\t\t\tbeepbox.Synth.sanitizeDelayLine(echoDelayLineR, echoDelayPos, echoMask);\n\t\t\t\tinstrumentState.echoDelayPos = echoDelayPos;\n\t\t\t\tinstrumentState.echoMult = echoMult;\n\t\t\t\tinstrumentState.echoDelayOffsetRatio = echoDelayOffsetRatio;\n\t\t\t\t\n\t\t\t\tif (!Number.isFinite(echoShelfSampleL) || Math.abs(echoShelfSampleL) < epsilon) echoShelfSampleL = 0.0;\n\t\t\t\tif (!Number.isFinite(echoShelfSampleR) || Math.abs(echoShelfSampleR) < epsilon) echoShelfSampleR = 0.0;\n\t\t\t\tif (!Number.isFinite(echoShelfPrevInputL) || Math.abs(echoShelfPrevInputL) < epsilon) echoShelfPrevInputL = 0.0;\n\t\t\t\tif (!Number.isFinite(echoShelfPrevInputR) || Math.abs(echoShelfPrevInputR) < epsilon) echoShelfPrevInputR = 0.0;\n\t\t\t\tinstrumentState.echoShelfSampleL = echoShelfSampleL;\n\t\t\t\tinstrumentState.echoShelfSampleR = echoShelfSampleR;\n\t\t\t\tinstrumentState.echoShelfPrevInputL = echoShelfPrevInputL;\n\t\t\t\tinstrumentState.echoShelfPrevInputR = echoShelfPrevInputR;"),p&&(t+="\n\t\t\t\t\n\t\t\t\tbeepbox.Synth.sanitizeDelayLine(reverbDelayLine, reverbDelayPos , reverbMask);\n\t\t\t\tbeepbox.Synth.sanitizeDelayLine(reverbDelayLine, reverbDelayPos + 3041, reverbMask);\n\t\t\t\tbeepbox.Synth.sanitizeDelayLine(reverbDelayLine, reverbDelayPos + 6426, reverbMask);\n\t\t\t\tbeepbox.Synth.sanitizeDelayLine(reverbDelayLine, reverbDelayPos + 10907, reverbMask);\n\t\t\t\tinstrumentState.reverbDelayPos = reverbDelayPos;\n\t\t\t\tinstrumentState.reverbMult = reverb;\n\t\t\t\t\n\t\t\t\tif (!Number.isFinite(reverbShelfSample0) || Math.abs(reverbShelfSample0) < epsilon) reverbShelfSample0 = 0.0;\n\t\t\t\tif (!Number.isFinite(reverbShelfSample1) || Math.abs(reverbShelfSample1) < epsilon) reverbShelfSample1 = 0.0;\n\t\t\t\tif (!Number.isFinite(reverbShelfSample2) || Math.abs(reverbShelfSample2) < epsilon) reverbShelfSample2 = 0.0;\n\t\t\t\tif (!Number.isFinite(reverbShelfSample3) || Math.abs(reverbShelfSample3) < epsilon) reverbShelfSample3 = 0.0;\n\t\t\t\tif (!Number.isFinite(reverbShelfPrevInput0) || Math.abs(reverbShelfPrevInput0) < epsilon) reverbShelfPrevInput0 = 0.0;\n\t\t\t\tif (!Number.isFinite(reverbShelfPrevInput1) || Math.abs(reverbShelfPrevInput1) < epsilon) reverbShelfPrevInput1 = 0.0;\n\t\t\t\tif (!Number.isFinite(reverbShelfPrevInput2) || Math.abs(reverbShelfPrevInput2) < epsilon) reverbShelfPrevInput2 = 0.0;\n\t\t\t\tif (!Number.isFinite(reverbShelfPrevInput3) || Math.abs(reverbShelfPrevInput3) < epsilon) reverbShelfPrevInput3 = 0.0;\n\t\t\t\tinstrumentState.reverbShelfSample0 = reverbShelfSample0;\n\t\t\t\tinstrumentState.reverbShelfSample1 = reverbShelfSample1;\n\t\t\t\tinstrumentState.reverbShelfSample2 = reverbShelfSample2;\n\t\t\t\tinstrumentState.reverbShelfSample3 = reverbShelfSample3;\n\t\t\t\tinstrumentState.reverbShelfPrevInput0 = reverbShelfPrevInput0;\n\t\t\t\tinstrumentState.reverbShelfPrevInput1 = reverbShelfPrevInput1;\n\t\t\t\tinstrumentState.reverbShelfPrevInput2 = reverbShelfPrevInput2;\n\t\t\t\tinstrumentState.reverbShelfPrevInput3 = reverbShelfPrevInput3;"),u=new Function("synth","outputDataL","outputDataR","bufferIndex","runLength","instrumentState",t),jt.effectsFunctionCache[m]=u}u(t,e,n,i,s,o)}static pulseWidthSynth(t,e,n,i,s){const o=t.tempMonoInstrumentSampleBuffer;let a=i.phaseDeltas[0];const r=+i.phaseDeltaScales[0];let h=+i.expression;const l=+i.expressionDelta;let c=i.phases[0]%1,d=i.pulseWidth;const p=i.pulseWidthDelta,m=i.noteFilters,u=0|i.noteFilterCount;let f=+i.initialNoteFilterInput1,y=+i.initialNoteFilterInput2;const b=jt.applyFilters,g=e+n;for(let t=e;t1-a){i+=.5*((w=(e-1)/a)+w+w*w+1)}if(n1-a){var w;i-=.5*((w=(n-1)/a)+w+w*w+1)}}const g=i,v=b(g,f,y,u,m);y=f,f=g,c+=a,a*=r,d+=p;const x=v*h;h+=l,o[t]+=x}i.phases[0]=c,i.phaseDeltas[0]=a,i.expression=h,i.pulseWidth=d,t.sanitizeFilters(m),i.initialNoteFilterInput1=f,i.initialNoteFilterInput2=y}static noiseSynth(t,e,n,i,s){const o=t.tempMonoInstrumentSampleBuffer,a=s.wave;let r=+i.phaseDeltas[0];const h=+i.phaseDeltaScales[0];let l=+i.expression;const c=+i.expressionDelta;let p=i.phases[0]%1*d.chipNoiseLength;0==i.phases[0]&&(p=Math.random()*d.chipNoiseLength);const m=d.chipNoiseLength-1;let u=+i.noiseSample;const f=i.noteFilters,y=0|i.noteFilterCount;let b=+i.initialNoteFilterInput1,g=+i.initialNoteFilterInput2;const w=jt.applyFilters,v=Math.min(1,r*s.noisePitchFilterMult),x=e+n;for(let t=e;tt.song.channels[s.modChannels[o]].instruments.length?null!=t.song.getPattern(s.modChannels[o],t.bar)&&(r=t.song.getPattern(s.modChannels[o],t.bar).instruments):r.push(s.modInstruments[o]);for(let e=0;eMath.floor((e-1)/2)&&(e%2?a.tmpEqFilterEnd.controlPoints[Math.floor((e-1)/2)].freq=i.expression+i.expressionDelta:a.tmpEqFilterEnd.controlPoints[Math.floor((e-1)/2)].gain=i.expression+i.expressionDelta)}}}else if(a==d.modulators.dictionary["note filter"].index){const a=t.song.channels[s.modChannels[o]].instruments[r[e]];if(!a.noteFilterType){let e=0|s.modFilterTypes[o];if(0==e){let e=0;const s=t.getTicksIntoBar()/d.ticksPerPart;for(;i.note.start+i.note.pins[e].time<=s;)e++;let o=(s-i.note.start+n/(t.getSamplesPerTick()*d.ticksPerPart)*d.ticksPerPart-i.note.pins[e-1].time)/(i.note.pins[e].time-i.note.pins[e-1].time);null!=a.noteSubFilters[i.note.pins[e-1].size]||null!=a.noteSubFilters[i.note.pins[e].size]?a.tmpNoteFilterEnd=zt.lerpFilters(a.noteSubFilters[i.note.pins[e-1].size],a.noteSubFilters[i.note.pins[e].size],o):a.tmpNoteFilterEnd=a.noteFilter}else{for(let t=0;tMath.floor((e-1)/2)&&(e%2?a.tmpNoteFilterEnd.controlPoints[Math.floor((e-1)/2)].freq=i.expression+i.expressionDelta:a.tmpNoteFilterEnd.controlPoints[Math.floor((e-1)/2)].gain=i.expression+i.expressionDelta)}}}}static findRandomZeroCrossing(t,e){let n=Math.random()*e;const i=e-1;let s=n&i,o=t[s];for(let a=128;a>0;a--){const a=s+16&i,r=t[a];if(o*r<=0){for(let a=0;a<16;a++){const a=s+1&i,r=t[a];if(o*r<=0){const t=r-o;n=s,Math.abs(t)>1e-8&&(n+=-o/t),n=Math.max(0,n)%e;break}s=a,o=r}break}s=a,o=r}return n}static instrumentVolumeToVolumeMult(t){return t==-d.volumeRange/2?0:Math.pow(2,d.volumeLogScale*t)}static volumeMultToInstrumentVolume(t){return t<=0?-d.volumeRange/2:Math.min(d.volumeRange,Math.log(t)/Math.LN2/d.volumeLogScale)}static noteSizeToVolumeMult(t){return Math.pow(Math.max(0,t)/d.noteSizeMax,1.5)}static volumeMultToNoteSize(t){return Math.pow(Math.max(0,t),1/1.5)*d.noteSizeMax}static fadeInSettingToSeconds(t){return.0125*(.95*t+.05*t*t)}static secondsToFadeInSetting(t){return mt(0,d.fadeInRange,Math.round((-.95+Math.sqrt(.9025+.2*t/.0125))/.1))}static fadeOutSettingToTicks(t){return d.fadeOutTicks[t]}static ticksToFadeOutSetting(t){let e=d.fadeOutTicks[0];if(t<=e)return 0;for(let n=1;n=pt))break;t[i]=0}}static applyFilters(t,e,n,i,s){for(let o=0;o=0;t--)this._t[t].undo()}}function Qt(t,e){const n=t.every((t=>-1!=e.indexOf(t))),i=e.every((e=>-1!=t.indexOf(e)));return n&&i&&e.length==t.length}function Xt(t,e,n){const i=new Set(t);t.length=0,t.push(...i);for(let i=0;i=e.channels[n].instruments.length&&(t.splice(i,1),i--);t.length>e.getMaxInstrumentsPerPattern(n)&&(t.length=e.getMaxInstrumentsPerPattern(n)),t.length<=0&&(t[0]=0)}function Zt(t,e){for(const n of t.notes)for(const t of n.pitches)for(const i of n.pins){const n=(t+i.interval)%12;e[n]||(e[n]=!0)}}function te(t){for(let e=1;e=t.pins.length)throw new Error("Error converting pins in note overflow.");const a=t.pins[n+1],r=a.time+e;if(r>0){const t=-s/(r-s);o.pins.push(Ft(Math.round(i.interval+t*(a.interval-i.interval)),0,Math.round(i.size+t*(a.size-i.size))))}}else if(s<=a)o.pins.push(Ft(i.interval,s,i.size));else{if(n<1)throw new Error("Error converting pins in note overflow.");const r=t.pins[n-1],h=r.time+e;if(h0&&t.continuesLastPattern){const t=s[s.length-1];if(t.end==o.start&&jt.adjacentNotesHaveMatchingPitches(t,o)){h=!0;const e=t.pins[t.pins.length-1].interval,n=t.end-t.start;for(let i=1;i=this.Qt[t+1].time?this.Qt.splice(t,1):t++;te(this.Qt);const e=this.Qt[0].interval,n=this.Qt[0].time;for(let t=0;t=2),n.volume=e,n.pan=i,n.panDelay=o,n.effects=4|n.effects}n.preset=e,t.notifier.changed(),this.Rt()}}}class re extends Ut{constructor(t){function e(t){let e=0;for(const n of t)e+=n.weight;let n=Math.random()*e;for(const e of t)if(n-=e.weight,n<=0)return e.item;return t[Math.random()*t.length|0].item}function n(t,n,i,s){const o=[];for(let e=t;e<=n;e++)o.push({item:e,weight:1/(Math.pow((e-i)/s,2)+1)});return e(o)}super();class i{constructor(t,e,n,i,s,o){this.chance=t,this.type=e,this.minFreq=n,this.maxFreq=i,this.centerHz=s,this.centerGain=o}}function s(t,e){t.reset();const i=[];for(const s of e){if(Math.random()>s.chance)continue;const e=new qt;e.type=s.type,e.freq=n(s.minFreq,s.maxFreq,qt.getRoundedSettingValueFromHz(s.centerHz),1/d.filterFreqStep),e.gain=n(0,d.filterGainRange-1,d.filterGainCenter+s.centerGain,2/d.filterGainStep),2==e.type&&e.gain==d.filterGainCenter||(i.includes(e.freq)||(i.push(e.freq),t.controlPoints[t.controlPointCount]=e,t.controlPointCount++))}}const o=t.song.getChannelIsNoise(t.channel),a=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];a.effects&=4,a.envelopeCount=0;const r=qt.getRoundedSettingValueFromHz(700),h=d.filterFreqRange-1;if(s(a.eqFilter,[new i(.8,0,r,h,4e3,-1),new i(.4,1,0,r-1,250,-1),new i(.5,2,0,h,2e3,0),new i(.4,2,0,h,1400,0),new i(.3,2,0,h,1e3,0),new i(.2,2,0,h,500,0)]),o){const l=e([{item:2,weight:1},{item:3,weight:3}]);function c(t){let e=0;for(const n of t)n>e&&(e=n);for(let n=0;n>1,2),a.vibrato=d.vibratos.dictionary[e([{item:"light",weight:2},{item:"delayed",weight:2},{item:"heavy",weight:1},{item:"shaky",weight:2}])].index),Math.random()<.8&&(a.effects|=32,s(a.noteFilter,[new i(1,0,r,h,8e3,-1)]),a.addEnvelope(d.instrumentAutomationTargets.dictionary.noteFilterAllFreqs.index,0,d.envelopes.dictionary[e([{item:"punch",weight:4},{item:"flare 1",weight:2},{item:"flare 2",weight:2},{item:"flare 3",weight:2},{item:"twang 1",weight:8},{item:"twang 2",weight:8},{item:"twang 3",weight:8},{item:"swell 1",weight:2},{item:"swell 2",weight:2},{item:"swell 3",weight:1},{item:"tremolo1",weight:1},{item:"tremolo2",weight:1},{item:"tremolo3",weight:1},{item:"tremolo4",weight:1},{item:"tremolo5",weight:1},{item:"tremolo6",weight:1},{item:"decay 1",weight:4},{item:"decay 2",weight:4},{item:"decay 3",weight:4},{item:"wibble 1",weight:2},{item:"wibble 2",weight:2},{item:"wibble 3",weight:2},{item:"linear 1",weight:2},{item:"linear 2",weight:2},{item:"linear 3",weight:2},{item:"linear-1",weight:1}])].index)),Math.random()<.1&&(a.effects|=8,a.distortion=n(1,d.distortionRange-1,d.distortionRange-1,2)),Math.random()<.1&&(a.effects|=16,a.bitcrusherFreq=n(0,d.bitcrusherFreqRange-1,d.bitcrusherFreqRange>>1,2),a.bitcrusherQuantization=n(0,d.bitcrusherQuantizationRange-1,d.bitcrusherQuantizationRange>>1,2)),Math.random()<.1&&(a.effects|=2,a.chorus=n(1,d.chorusRange-1,d.chorusRange-1,1)),Math.random()<.1&&(a.echoSustain=n(0,d.echoSustainRange-1,d.echoSustainRange>>1,2),a.echoDelay=n(0,d.echoDelayRange-1,d.echoDelayRange>>1,2),0==a.echoSustain&&0==a.echoDelay||(a.effects|=64)),Math.random()<.5&&(a.effects|=1,a.reverb=n(1,d.reverbRange-1,1,1)),l){case 2:a.chipNoise=Math.random()*d.chipNoises.length|0;break;case 3:{const p=[()=>{const t=[];for(let e=0;e{let t=1;const e=[t];for(let n=1;n{let t=1;const e=[t];for(let n=1;ne&&(e=n);for(let n=0;n>1,2),a.vibrato=d.vibratos.dictionary[e([{item:"light",weight:2},{item:"delayed",weight:2},{item:"heavy",weight:1},{item:"shaky",weight:2}])].index),Math.random()<.1&&(a.effects|=8,a.distortion=n(1,d.distortionRange-1,d.distortionRange-1,2)),A(a.effects)&&Math.random()<.8?(a.effects|=32,s(a.noteFilter,[new i(1,0,r,h,2e3,-1),new i(.9,1,0,r-1,500,-1),new i(.4,2,0,h,1400,0)])):Math.random()<.5&&(a.effects|=32,s(a.noteFilter,[new i(1,0,r,h,8e3,-1)]),a.addEnvelope(d.instrumentAutomationTargets.dictionary.noteFilterAllFreqs.index,0,d.envelopes.dictionary[e([{item:"punch",weight:6},{item:"flare -1",weight:1},{item:"flare 1",weight:2},{item:"flare 2",weight:4},{item:"flare 3",weight:2},{item:"twang -1",weight:1},{item:"twang 1",weight:2},{item:"twang 2",weight:4},{item:"twang 3",weight:4},{item:"swell -1",weight:4},{item:"swell 1",weight:4},{item:"swell 2",weight:2},{item:"swell 3",weight:1},{item:"tremolo0",weight:1},{item:"tremolo1",weight:1},{item:"tremolo2",weight:1},{item:"tremolo3",weight:1},{item:"tremolo4",weight:1},{item:"tremolo5",weight:1},{item:"tremolo6",weight:1},{item:"decay -1",weight:1},{item:"decay 1",weight:1},{item:"decay 2",weight:2},{item:"decay 3",weight:2},{item:"wibble-1",weight:2},{item:"wibble 1",weight:4},{item:"wibble 2",weight:4},{item:"wibble 3",weight:4},{item:"linear-2",weight:1},{item:"linear-1",weight:1},{item:"linear 1",weight:2},{item:"linear 2",weight:3},{item:"linear 3",weight:2},{item:"rise -2",weight:4},{item:"rise -1",weight:4},{item:"rise 1",weight:3},{item:"rise 2",weight:2},{item:"rise 3",weight:1}])].index)),Math.random()<.1&&(a.effects|=16,a.bitcrusherFreq=n(0,d.bitcrusherFreqRange-1,0,2),a.bitcrusherQuantization=n(0,d.bitcrusherQuantizationRange-1,d.bitcrusherQuantizationRange>>1,2)),Math.random()<.1&&(a.effects|=2,a.chorus=n(1,d.chorusRange-1,d.chorusRange-1,1)),Math.random()<.1&&(a.echoSustain=n(0,d.echoSustainRange-1,d.echoSustainRange>>1,2),a.echoDelay=n(0,d.echoDelayRange-1,d.echoDelayRange>>1,2),0==a.echoSustain&&0==a.echoDelay||(a.effects|=64)),Math.random()<.5&&(a.effects|=1,a.reverb=n(1,d.reverbRange-1,1,1)),f){case 0:a.chipWave=Math.random()*d.chipWaves.length|0,a.isUsingAdvancedLoopControls=!1,a.chipWaveLoopStart=0,a.chipWaveLoopEnd=d.rawRawChipWaves[a.chipWave].samples.length-1,a.chipWaveLoopMode=0,a.chipWavePlayBackwards=!1,a.chipWaveStartOffset=0;break;case 6:a.pulseWidth=n(0,d.pulseWidthRange-1,d.pulseWidthRange-1,2),a.decimalOffset=0,Math.random()<.6&&a.addEnvelope(d.instrumentAutomationTargets.dictionary.pulseWidth.index,0,d.envelopes.dictionary[e([{item:"punch",weight:6},{item:"flare -1",weight:1},{item:"flare 1",weight:2},{item:"flare 2",weight:4},{item:"flare 3",weight:2},{item:"twang -1",weight:1},{item:"twang 1",weight:2},{item:"twang 2",weight:4},{item:"twang 3",weight:4},{item:"swell -1",weight:4},{item:"swell 1",weight:4},{item:"swell 2",weight:2},{item:"swell 3",weight:1},{item:"tremolo0",weight:1},{item:"tremolo1",weight:1},{item:"tremolo2",weight:1},{item:"tremolo3",weight:1},{item:"tremolo4",weight:1},{item:"tremolo5",weight:1},{item:"tremolo6",weight:1},{item:"decay -1",weight:1},{item:"decay 1",weight:1},{item:"decay 2",weight:2},{item:"decay 3",weight:2},{item:"wibble-1",weight:2},{item:"wibble 1",weight:4},{item:"wibble 2",weight:4},{item:"wibble 3",weight:4},{item:"linear-2",weight:1},{item:"linear-1",weight:1},{item:"linear 1",weight:2},{item:"linear 2",weight:3},{item:"linear 3",weight:2},{item:"rise -2",weight:4},{item:"rise -1",weight:4},{item:"rise 1",weight:3},{item:"rise 2",weight:2},{item:"rise 3",weight:1}])].index);break;case 7:case 5:{7==f&&(a.stringSustain=Math.random()*d.stringSustainRange|0);const b=[()=>{const t=[];for(let e=0;e{let t=1;const e=[t];for(let n=1;n{let t=1;const e=[t];for(let n=1;nt.song.patternsPerChannel)throw new Error("invalid pattern");for(let a=n;a=t.song.pitchChannelCount+t.song.noiseChannelCount){const e=t.getCurrentPattern();t.viewedInstrument[i]=null!=e?e.instruments[0]:0}t.notifier.changed()}}class de extends Ut{constructor(t,e,n){if(super(),t.song.barCount!=e){for(const i of t.song.channels)if(n){for(;i.bars.lengthe&&i.bars.splice(0,t.song.barCount-e)}else{for(;i.bars.length0)&&(t.barScrollPos=Math.max(0,t.barScrollPos+n)),t.song.loopStart=Math.max(0,t.song.loopStart+n)}t.bar=Math.min(t.bar,e-1),t.song.loopLength=Math.min(e,t.song.loopLength),t.song.loopStart=Math.min(e-t.song.loopLength,t.song.loopStart),t.song.barCount=e,t.notifier.changed(),this.Rt()}}}class pe extends Ut{constructor(t,e,n){super();const i=Math.min(d.barCountMax,t.song.barCount+n);if(0!=(n=i-t.song.barCount)){for(const n of t.song.channels)for(;n.bars.length=e?t.song.loopStart+=n:t.song.loopStart+t.song.loopLength>=e&&(t.song.loopLength+=n),t.notifier.changed(),this.Rt()}}}class me extends Ut{constructor(t,e,n){super();for(const i of t.song.channels)i.bars.splice(e,n),0==i.bars.length&&i.bars.push(0);t.song.barCount=Math.max(1,t.song.barCount-n),t.bar=Math.max(0,t.bar-n),t.barScrollPos=Math.max(0,t.barScrollPos-n),t.song.loopStart>=e?t.song.loopStart=Math.max(0,t.song.loopStart-n):t.song.loopStart+t.song.loopLength>e&&(t.song.loopLength-=n),t.song.loopLength=Math.max(1,Math.min(t.song.barCount-t.song.loopStart,t.song.loopLength)),t.notifier.changed(),this.Rt()}}class ue extends Ut{constructor(t,e,n,i,s,o,a,r){super(),t.song.limitRatio=e,t.song.compressionRatio=n,t.song.limitThreshold=i,t.song.compressionThreshold=s,t.song.limitRise=o,t.song.limitDecay=a,t.song.masterGain=r,t.notifier.changed(),this.Rt()}}class fe extends Ut{constructor(t,e,n,i){super(),t.song.channels.splice(e+i,0,...t.song.channels.splice(e,n-e+1)),n=Math.max(n,e);for(let s=t.song.pitchChannelCount+t.song.noiseChannelCount;s=e&&a.modChannels[t]<=n?a.modChannels[t]+=i:a.modChannels[t]>=e+i&&a.modChannels[t]<=n+i&&(a.modChannels[t]-=i*(n-e+1))}t.notifier.changed(),this.Rt()}}class ye extends Ut{constructor(t,e){super();for(let n=0;n=2),i.preset=e}s[e].instruments[n]=i}for(let n=0;n=t.song.pitchChannelCount&&m=t.song.pitchChannelCount+t.song.noiseChannelCount)&&(p.modulators[c]=d.modulators.dictionary.none.index),m>=a&&a=e&&this.append(new fe(t,e,i-1,1)),t.synth.computeLatestModValues(),t.recalcChannelNames=!0}}}class we extends Jt{constructor(t,e,n){super();const i=n;for(let n=t.song.pitchChannelCount+t.song.noiseChannelCount;n=e&&o.modChannels[n]<=i?this.append(new An(t,n,0,o)):o.modChannels[n]>i&&this.append(new An(t,n,o.modChannels[n]-(i-e+1)+2,o))}for(;n>=e;){const e=t.song.getChannelIsNoise(n),i=t.song.getChannelIsMod(n);t.song.channels.splice(n,1),e?t.song.noiseChannelCount--:i?t.song.modChannelCount--:t.song.pitchChannelCount--,n--}t.song.pitchChannelCounti&&a--:e.controlPointCount<=1&&(n=d.instrumentAutomationTargets.dictionary.none.index,a=0))}this.ae.push(n),this.re.push(a)}this.Rt(),this.redo()}Ht(){this.ce.controlPoints.splice(this.ut,0,this.de),this.ce.controlPointCount++,this.ce.controlPoints.length=this.ce.controlPointCount,this.ie.preset=this.he;for(let t=0;t=s)return;const o=Hn(n),a=q.valueToPreset(o),r=new Rt(n,i);r.fromJsonObject(a.settings,n,i,!1,!1,1),r.preset=o,r.volume=0,e.instruments.push(r),i||(t.viewedInstrument[t.channel]=e.instruments.length-1);for(let e=t.song.pitchChannelCount+t.song.noiseChannelCount;e=t.song.channels[a].instruments.length-1&&s.modInstruments[i]++}t.synth.computeLatestModValues(),t.notifier.changed(),this.Rt()}}class yn extends Ut{constructor(t){super();const e=t.song.channels[t.channel];if(e.instruments.length<=d.instrumentCountMin)return;const n=t.viewedInstrument[t.channel];if(e.instruments.splice(n,1),t.song.patternInstruments)for(const t of e.patterns){for(let e=0;en&&t.instruments[e]--;t.instruments.length<=0&&(t.instruments[0]=0)}for(let e=t.song.pitchChannelCount+t.song.noiseChannelCount;en?o.modInstruments[s]--:a==n&&(o.modInstruments[s]=0,o.modulators[s]=0))}t.notifier.changed(),this.Rt()}}class bn extends Ut{constructor(t,e){super(),t.viewedInstrument[t.channel]!=e&&(t.viewedInstrument[t.channel]=e,t.notifier.changed(),this.Rt())}}class gn extends Ut{constructor(t,e,n){super();const i=t.song.layeredInstruments,s=t.song.patternInstruments;if(i!=e||s!=n){t.song.layeredInstruments=e,t.song.patternInstruments=n;for(let e=0;et.song.getMaxInstrumentsPerChannel()&&(i.instruments.length=t.song.getMaxInstrumentsPerChannel());for(let o=0;oi)throw new Error;a=t+1}else if(e.notes[t].start=s)break;const h=new Ct(o.pitches[0],n,r,o.pins[0].size,!1);h.pitches.length=0;for(const t of o.pitches)h.pitches.push(t);h.pins.length=0;for(const t of o.pins)h.pins.push(Ft(t.interval,t.time,t.size));h.continuesLastPattern=!0===o.continuesLastPattern&&0==h.start,e.notes.splice(a++,0,h),h.end>s&&this.append(new ei(t,h,h.start,s))}i+=o}null!=e&&t.song.getChannelIsMod(t.channel)&&e.notes.sort((function(t,e){return t.start==e.start?t.pitches[0]-e.pitches[0]:t.start-e.start})),t.notifier.changed(),this.Rt()}}class Fn extends Jt{constructor(t,e,n){super(),e.fromJsonObject(n,n.isDrum,n.isMod,!1,!1),t.notifier.changed(),this.Rt()}}class Cn extends Ut{constructor(t,e,n,i){super(),Qt(n,i.instruments)||(i.instruments.length=0,i.instruments.push(...n),Xt(i.instruments,t.song,e),this.Rt(),t.notifier.changed())}}class An extends Ut{constructor(t,e,n,i){super();let s=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];null!=i&&(s=i),(0==n||d.modulators[s.modulators[e]].forSong&&n>=2||!d.modulators[s.modulators[e]].forSong&&n<2)&&(s.modulators[e]=d.modulators.dictionary.none.index),s.modChannels[e]=n-2,t.notifier.changed(),this.Rt()}}class En extends Ut{constructor(t,e,n){super();let i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.modInstruments[e]!=n&&(i.modInstruments[e]=n,t.notifier.changed(),this.Rt())}}class Tn extends Ut{constructor(t,e,n){super();let i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()],s=i.modChannels[e],o=[];if(s>=0)if(i.modInstruments[e]==t.song.channels[s].instruments.length)o=o.concat(t.song.channels[s].instruments);else if(i.modInstruments[e]>t.song.channels[s].instruments.length){let e=t.song.getPattern(s,t.bar);if(null!=e)for(let n=0;nn&&(e.size=n)}}}t.notifier.changed(),this.Rt()}}}class Pn extends Ut{constructor(t,e,n){super();let i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];if(i.modFilterTypes[e]!=n){i.modFilterTypes[e]=n;let s=t.song.getVolumeCapForSetting(!0,i.modulators[e],i.modFilterTypes[e]);for(let n=0;ns&&(e.size=s)}}}t.notifier.changed(),this.Rt()}}}class Dn extends Ut{constructor(t,e){if(super(),t.song.patternsPerChannel!=e){for(let n=0;ne&&(i[t]=0);for(let t=s.length;tr&&(h||(this.Qt.length>0&&(s=e.continuesLastPattern),this.Qt.push(Ft(this.Yt[n].interval,i,this.Yt[n].size)),h=!0),this.Qt.push(Ft(o.interval,l,o.size)))}h||(s=e.continuesLastPattern,this.Qt.push(Ft(this.Yt[n].interval,i,this.Yt[n].size))),this.ne(s)}}class Ln extends ie{constructor(t,e,n,i,s,o){super(t,e),n-=this.jt,i-=this.jt,s-=e.pitches[o];let a,r,h,l,c=!1,p=!1,m=0,u=d.noteSizeMax,f=!0;for(i>n?(a=0,r=1,h=e.pins.length,l=t=>{this.Qt.push(t)}):(a=e.pins.length-1,r=-1,h=-1,l=t=>{this.Qt.unshift(t)});a!=h;a+=r){const t=e.pins[a],o=t.time;for(;;)if(c){if(p){if(o*r==i*r)break;t.interval!=m&&(f=!1),l(Ft(f?s:t.interval,o,t.size));break}if(o*r<=i*r&&(m=t.interval,u=t.size),o*r=t))break;o+=n}return o}return Math.round(e/n)*n};let s=0;for(;s=i(n.end)?this.append(new ti(t,e,n,s,!0)):(this.append(new zn(t,n,i)),s++)}}}class zn extends ie{constructor(t,e,n){super(t,e);for(const t of this.Yt)this.Qt.push(Ft(t.interval,n(t.time+this.jt)-this.jt,t.size));this.ne()}}class Nn extends Jt{constructor(t,e,n){super();let i=Math.round(e%t.song.beatsPerBar*d.partsPerBeat);if(i<0&&(i+=t.song.beatsPerBar*d.partsPerBeat),0!=i){switch(n){case"wrapAround":{const e=d.partsPerBeat*t.song.beatsPerBar;for(const n of t.song.channels)for(const t of n.patterns){const n=[];for(let s=1;s>=0;s--){const o=s*e;for(const s of t.notes){const t=s.start+i,a=s.end+i,r=Math.max(0,t-o),h=Math.min(e,a-o);re){const n=new Yt;for(let i=0;i=n(e.end)?this.append(new ti(t,s,e,o,!0)):(this.append(new zn(t,e,n)),o++)}}this.append(new Jn(t,t.song.tempo,t.song.tempo*e/t.song.beatsPerBar))}break;case"overflow":this.append(new ne(t,e,0)),t.song.loopStart=0,t.song.loopLength=t.song.barCount;break;default:throw new Error("Unrecognized beats-per-bar conversion strategy.")}t.song.beatsPerBar=e,t.notifier.changed(),this.Rt()}}}class On extends Jt{constructor(t,e){super(),t.song.scale!=e&&(t.song.scale=e,t.notifier.changed(),this.Rt())}}class $n extends Jt{constructor(t){super();const e=t.song,n=d.keys[e.key].basePitch,i=[0,0,0,0,0,0,0,0,0,0,0,0];for(let t=0;t0,!0));e.key=s,t.notifier.changed(),this.Rt()}}}function Hn(t){const e=[];for(let n=0;n.5?"chip noise":"standard drumset"):Hn(i),a=q.valueToPreset(o);n.fromJsonObject(a.settings,i,s,0==t.rhythm||2==t.rhythm,t.rhythm>=2,1),n.preset=o}}class Gn extends Jt{constructor(t,e){super();let n=t.song.pitchChannelCount,i=t.song.noiseChannelCount,s=t.song.modChannelCount;if(t.song.fromBase64String(e),n==t.song.pitchChannelCount&&i==t.song.noiseChannelCount&&s==t.song.modChannelCount||et.resetColors(),""==e){this.append(new ri(t,0,0)),t.selection.resetBoxSelection(),Vn(t.song),t.song.scale=t.prefs.defaultScale;for(let e=0;e<=t.song.channels.length;e++)t.viewedInstrument[e]=0,t.recentPatternInstruments[e]=[0];t.viewedInstrument.length=t.song.channels.length}else this.append(new _n(t));t.synth.computeLatestModValues(),t.notifier.changed(),this.Rt()}}class _n extends Ut{constructor(t){super();const e=Math.min(t.channel,t.song.getChannelCount()-1),n=Math.max(0,Math.min(t.song.barCount-1,t.bar));t.channel==e&&t.bar==n||(t.bar=n,t.channel=e,this.Rt()),t.selection.scrollToSelectedPattern(),t.notifier.changed()}}class Wn extends Jt{constructor(t,e,n,i){super();const s=t.song;function o(t,e){for(;t.length>e;){let e=t.length-1,n=0;for(let i=0;i=n&&(e=i,n=s)}t.splice(e,1)}}for(o(e,d.pitchChannelCountMax),o(n,d.noiseChannelCountMax),o(i,d.modChannelCountMax);e.lengths.patternsPerChannel||e.bars[t]<0)&&(e.bars[t]=0);for(;e.bars.lengths.getMaxInstrumentsPerChannel()&&(e.instruments.length=s.getMaxInstrumentsPerChannel());for(const n of e.patterns)Xt(n.instruments,s,t);for(;e.patterns.lengthn&&!a&&(this.Qt.push(Ft(h,n,r)),a=!0),!(t.time<=i))break;if(this.Qt.push(Ft(t.interval,t.time,t.size)),t.time==i){l=!1;break}}}l&&this.Qt.push(Ft(this.Yt[o].interval,i,this.Yt[o].size)),this.ne(s)}}class ni extends Yt{constructor(t,e,n,i,s=null,o=!1){super();let a=0;for(;a=i){if(!t.song.getChannelIsMod(t.channel))break;a++}else if(r.starti){if(!t.song.getChannelIsMod(t.channel)||o||null!=s&&r.pitches[0]==s.pitches[0]){const s=r.clone();this.append(new ei(t,r,r.start,n)),a++,this.append(new ti(t,e,s,a,!1)),this.append(new ei(t,s,i,s.end))}a++}else r.starti?((!t.song.getChannelIsMod(t.channel)||o||null!=s&&r.pitches[0]==s.pitches[0])&&this.append(new ei(t,r,i,r.end)),a++):!t.song.getChannelIsMod(t.channel)||o||null!=s&&r.pitches[0]==s.pitches[0]?this.append(new ti(t,e,r,a,!0)):a++}}}class ii extends Yt{constructor(t,e){super();let n=0;for(;n=0;t--)if(a||s||e[t%12]){n=t;break}}let h=!1;for(let t=0;te+r&&(l=e+r)}for(const e of this.Yt){let n=e.interval+this.Xt[0];if(nl&&(n=l),o&&!a)n=i?Math.min(l,n+12):Math.max(h,n-12);else{let e=t.song.scale==d.scales.dictionary.Custom.index?t.song.scaleCustom:d.scales[t.song.scale].flags;if(i){for(let t=n+1;t<=l;t++)if(a||s||e[t%12]){n=t;break}}else for(let t=n-1;t>=h;t--)if(a||s||e[t%12]){n=t;break}}n-=this.Zt[0],this.Qt.push(Ft(n,e.time,e.size))}if(0!=this.Qt[0].interval)throw new Error("wrong pin start interval");for(let t=1;t=t.selection.patternSelectionEnd)||this.append(new si(t,e,a,i,s,o))}}class ai extends Ut{constructor(t,e,n,i,s){super(),t.selection.boxSelectionX0=e,t.selection.boxSelectionX1=n,t.selection.boxSelectionY0=i,t.selection.boxSelectionY1=s,t.notifier.changed(),this.Rt()}}class ri extends Kt{constructor(t,e,n){super(!1),this.l=t,this.jt=t.selection.patternSelectionStart,this.Ut=t.selection.patternSelectionEnd,this.Le=t.selection.patternSelectionActive,this.Kt=e,this.Jt=n,this.qe=e=a?(p++,e.end<=r&&(c=p)):(l.push(e.clone()),this.append(new ti(t,n,e,p,!0)))}for(const o of l)if(o.start+=i,o.end+=i,!(o.end<=r||o.start>=h)){this.append(new ti(t,n,o,c++,!1)),this.append(new ei(t,o,Math.max(o.start,r),Math.min(h,o.end)));for(let n=0;n0,t.prefs.notesOutsideScale))}}}class li extends Jt{constructor(t,e,n,i,s){super();for(let o=i;o=e+n)&&t.song.channels[o].bars[i]==a){r=!0;break}if(r){const e=t.song.getPattern(o,s);this.append(new ce(t,0,s,o,1,1)),this.append(new Bn(t,o,s));const n=t.song.getPattern(o,s);if(null==n)throw new Error;this.append(new Sn(t,n,e.notes,0,d.partsPerBeat*t.song.beatsPerBar,d.partsPerBeat*t.song.beatsPerBar)),n.instruments.length=0,n.instruments.push(...e.instruments),i[String(a)]=t.song.channels[o].bars[s]}else i[String(a)]=a}this.append(new ce(t,i[String(a)],s,o,1,1))}}}}}class ci extends Ut{constructor(t,e,n){super(),t.selection.patternSelectionActive&&new ii(t,e);const i=d.maxPitch;for(const s of e.notes){if(t.selection.patternSelectionActive&&(s.end<=t.selection.patternSelectionStart||s.start>=t.selection.patternSelectionEnd))continue;const e=[],o=[];for(let t=0;tn+i&&(r=n+i)}for(const t of s.pins){let i=t.interval+s.pitches[0];ir&&(i=r);const h=n[i%12]+(i-i%12);o.push(Ft(h-e[0],t.time,t.size))}if(0!=o[0].interval)throw new Error("wrong pin start interval");for(let t=1;t30&&(n=n.substring(0,30)),t.song.title=n,document.title=n+" - "+q.versionDisplayName,t.notifier.changed(),e!=n&&this.Rt()}}class mi extends Ut{constructor(t,e,n){super(),n.length>15&&(n=n.substring(0,15)),t.song.channels[t.muteEditorChannel].name=n,t.recalcChannelNames=!0,t.notifier.changed(),e!=n&&this.Rt()}}class ui extends Ut{constructor(t,e,n){super(),t.song.channels[t.channel].instruments[t.getCurrentInstrument()].pan=n,t.synth.unsetMod(d.modulators.dictionary.pan.index,t.channel,t.getCurrentInstrument()),t.notifier.changed(),e!=n&&this.Rt()}}class fi extends Ut{constructor(t,e,n){super(),t.song.channels[t.channel].instruments[t.getCurrentInstrument()].panDelay=n,t.notifier.changed(),e!=n&&this.Rt()}}class yi extends Kt{constructor(t,e,n,i,s,o){super(!1),this.l=t,this.Wt=e,this.Yt=e.pins,this.Qt=[];let a=!1;for(const t of e.pins)t.time{this.l.undo()},this.cleanUp=()=>{this.Oe.removeEventListener("click",this.He),this.Re.removeEventListener("click",this.$e),this.ze.removeEventListener("keypress",Ni.Ve),this.ze.removeEventListener("blur",Ni.Ge),this.container.removeEventListener("keydown",this._e)},this._e=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.He()},this.He=()=>{window.localStorage.setItem("beatCountStrategy",this.Ne.value),this.l.prompt=null,this.l.record(new Rn(this.l,Ni.We(this.ze),this.Ne.value),!0)},this.ze.value=this.l.song.beatsPerBar+"",this.ze.min=d.beatsPerBarMin+"",this.ze.max=d.beatsPerBarMax+"";const e=window.localStorage.getItem("beatCountStrategy");null!=e&&(this.Ne.value=e),this.ze.select(),setTimeout((()=>this.ze.focus())),this.Oe.addEventListener("click",this.He),this.Re.addEventListener("click",this.$e),this.ze.addEventListener("keypress",Ni.Ve),this.ze.addEventListener("blur",Ni.Ge),this.container.addEventListener("keydown",this._e)}static Ve(t){const e=t.which?t.which:t.keyCode;return 46!=e&&e>31&&(e<48||e>57)&&(t.preventDefault(),!0)}static Ge(t){const e=t.target;e.value=String(Ni.We(e))}static We(t){return Math.floor(Math.max(Number(t.min),Math.min(Number(t.max),Number(t.value))))}}const{button:Ri,div:Oi,label:$i,br:Hi,h2:Vi,input:Gi}=U;class _i{constructor(t){this.l=t,this.je=Gi({style:"width: 3em; margin-left: 1em;",type:"number",step:"1"}),this.Ue=Gi({style:"width: 3em; margin-left: 1em;",type:"number",step:"1"}),this.Ke=Gi({style:"width: 3em; margin-left: 1em;",type:"number",step:"1"}),this.Je=Gi({style:"width: 3em; margin-left: 1em;",type:"number",step:"1"}),this.Ye=Gi({style:"width: 3em; margin-left: 1em;",type:"checkbox"}),this.Qe=Gi({style:"width: 3em; margin-left: 1em;",type:"checkbox"}),this.Re=Ri({class:"cancelButton"}),this.Oe=Ri({class:"okayButton",style:"width:45%;"},"Okay"),this.container=Oi({class:"prompt noSelection",style:"width: 250px; text-align: right;"},Vi("Channel Settings"),$i({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Pitch channels:",this.Ue),$i({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Drum channels:",this.Ke),Oi({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Mod channels:",this.Je),$i({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Available patterns per channel:",this.je),$i({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Simultaneous instruments",Hi(),"per channel:",this.Ye),$i({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Different instruments",Hi(),"per pattern:",this.Qe),$i({style:"display: flex; flex-direction: row-reverse; justify-content: space-between;"},this.Oe),this.Re),this.$e=()=>{this.l.undo()},this.cleanUp=()=>{this.Oe.removeEventListener("click",this.He),this.Re.removeEventListener("click",this.$e),this.je.removeEventListener("keypress",_i.Ve),this.Ue.removeEventListener("keypress",_i.Ve),this.Ke.removeEventListener("keypress",_i.Ve),this.Je.removeEventListener("keypress",_i.Ve),this.je.removeEventListener("blur",this.Ge),this.Ue.removeEventListener("blur",this.Ge),this.Ke.removeEventListener("blur",this.Ge),this.Je.removeEventListener("blur",this.Ge),this.container.removeEventListener("keydown",this._e)},this._e=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.He()},this.Ge=t=>{const e=t.target;e.value=String(_i.We(e))},this.He=()=>{const t=new Jt;t.append(new gn(this.l,this.Ye.checked,this.Qe.checked)),t.append(new Dn(this.l,_i.We(this.je))),t.append(new be(this.l,_i.We(this.Ue),_i.We(this.Ke),_i.We(this.Je))),this.l.prompt=null,this.l.record(t,!0)},this.je.value=this.l.song.patternsPerChannel+"",this.je.min="1",this.je.max=d.barCountMax+"",this.Ue.value=this.l.song.pitchChannelCount+"",this.Ue.min=d.pitchChannelCountMin+"",this.Ue.max=d.pitchChannelCountMax+"",this.Ke.value=this.l.song.noiseChannelCount+"",this.Ke.min=d.noiseChannelCountMin+"",this.Ke.max=d.noiseChannelCountMax+"",this.Je.value=this.l.song.modChannelCount+"",this.Je.min=d.modChannelCountMin+"",this.Je.max=d.modChannelCountMax+"",this.Ye.checked=this.l.song.layeredInstruments,this.Qe.checked=this.l.song.patternInstruments,this.Ue.select(),setTimeout((()=>this.Ue.focus())),this.Oe.addEventListener("click",this.He),this.Re.addEventListener("click",this.$e),this.je.addEventListener("keypress",_i.Ve),this.Ue.addEventListener("keypress",_i.Ve),this.Ke.addEventListener("keypress",_i.Ve),this.Je.addEventListener("keypress",_i.Ve),this.je.addEventListener("blur",this.Ge),this.Ue.addEventListener("blur",this.Ge),this.Ke.addEventListener("blur",this.Ge),this.Je.addEventListener("blur",this.Ge),this.container.addEventListener("keydown",this._e)}static Ve(t){const e=t.which?t.which:t.keyCode;return 46!=e&&e>31&&(e<48||e>57)&&(t.preventDefault(),!0)}static We(t){return Math.floor(Math.max(Number(t.min),Math.min(Number(t.max),Number(t.value))))}}const{button:Wi,div:ji,h2:Ui}=U;class Ki{constructor(t){this.N=0,this.Xe=0,this.Ze=0,this.tn=0,this.R=!1,this.chipData=new Float32Array(64),this.startingChipData=new Float32Array(64),this.en=0,this.nn=[],this.u=768,this.v=294,this.sn=K.path({fill:et.uiWidgetBackground,"pointer-events":"none"}),this.an=K.svg({"pointer-events":"none"}),this.rn=K.svg({"pointer-events":"none"}),this.hn=K.svg({"pointer-events":"none"}),this.q=K.svg({style:`background-color: ${et.editorBackground}; touch-action: none; overflow: visible;`,width:"100%",height:"100%",viewBox:"0 0 "+this.u+" "+this.v,preserveAspectRatio:"none"},this.sn,this.an,this.rn,this.hn),this.container=U.div({class:"",style:"height: 294px; width: 768px; padding-bottom: 1.5em;"},this.q),this.ln=()=>{var t=!0;if(this.nn.length>0)for(var e=0;e<64;e++)this.nn[this.en][e]!=this.chipData[e]&&(t=!1,e=64);0!=t&&0!=this.nn.length||(this.nn.splice(0,this.en),this.en=0,this.nn.unshift(this.chipData.slice()),this.nn.length>32&&this.nn.pop())},this.undo=()=>{this.en{this.en>0&&(this.en--,this.chipData=this.nn[this.en].slice(),new se(this.l,this.chipData),this.render())},this._e=t=>{90==t.keyCode?(this.undo(),t.stopPropagation()):89==t.keyCode&&(this.redo(),t.stopPropagation())},this.J=t=>{t.preventDefault(),this.R=!0;const e=this.q.getBoundingClientRect();this.N=((t.clientX||t.pageX)-e.left)*this.u/(e.right-e.left),this.Xe=((t.clientY||t.pageY)-e.top)*this.v/(e.bottom-e.top),isNaN(this.N)&&(this.N=0),isNaN(this.Xe)&&(this.Xe=0),this.Ze=-1,this.tt()},this.X=t=>{t.preventDefault(),this.R=!0;const e=this.q.getBoundingClientRect();this.N=(t.touches[0].clientX-e.left)*this.u/(e.right-e.left),this.Xe=(t.touches[0].clientY-e.top)*this.v/(e.bottom-e.top),isNaN(this.N)&&(this.N=0),isNaN(this.Xe)&&(this.Xe=0),this.Ze=-1,this.tt()},this.Z=t=>{if(null==this.container.offsetParent)return;const e=this.q.getBoundingClientRect();this.N=((t.clientX||t.pageX)-e.left)*this.u/(e.right-e.left),this.Xe=((t.clientY||t.pageY)-e.top)*this.v/(e.bottom-e.top),isNaN(this.N)&&(this.N=0),isNaN(this.Xe)&&(this.Xe=0),this.tt()},this.et=t=>{if(null==this.container.offsetParent)return;if(!this.R)return;t.preventDefault();const e=this.q.getBoundingClientRect();this.N=(t.touches[0].clientX-e.left)*this.u/(e.right-e.left),this.Xe=(t.touches[0].clientY-e.top)*this.v/(e.bottom-e.top),isNaN(this.N)&&(this.N=0),isNaN(this.Xe)&&(this.Xe=0),this.tt()},this.nt=t=>{this.ln(),this.R=!1},this.l=t;for(let t=0;t<=4;t+=2)this.an.appendChild(K.rect({fill:et.tonic,x:t*this.u/4-1,y:0,width:2,height:this.v}));for(let t=1;t<=8;t++)this.rn.appendChild(K.rect({fill:et.fifthNote,x:t*this.u/8-1,y:0,width:1,height:this.v}));this.an.appendChild(K.rect({fill:et.tonic,x:0,y:this.v/2-1,width:this.u,height:2}));for(let t=0;t<3;t++)this.rn.appendChild(K.rect({fill:et.fifthNote,x:0,y:8*t*(this.v/49),width:this.u,height:1})),this.rn.appendChild(K.rect({fill:et.fifthNote,x:0,y:this.v-1-8*t*(this.v/49),width:this.u,height:1}));let e=et.getChannelColor(this.l.song,this.l.channel).primaryNote;for(let t=0;t<=64;t++){let n=this.l.song.channels[this.l.channel].instruments[this.l.getCurrentInstrument()].customChipWave[t];this.chipData[t]=n,this.startingChipData[t]=n,this.hn.appendChild(K.rect({fill:e,x:t*this.u/64,y:(n+24)*(this.v/49),width:this.u/64,height:this.v/49}))}this.ln(),this.container.addEventListener("mousedown",this.J),document.addEventListener("mousemove",this.Z),document.addEventListener("mouseup",this.nt),this.container.addEventListener("touchstart",this.X),this.container.addEventListener("touchmove",this.et),this.container.addEventListener("touchend",this.nt),this.container.addEventListener("touchcancel",this.nt),this.q.addEventListener("keydown",this._e),this.container.addEventListener("keydown",this._e)}tt(){if(this.R){const o=Math.min(63,Math.max(0,Math.floor(64*this.N/this.u))),a=Math.min(48,Math.max(0,Math.floor(49*this.Xe/this.v)));if(-1!=this.Ze&&this.Ze!=o){var t=o,e=this.Ze,n=a,i=this.tn;this.Ze{this.cn.togglePlay(),this.updatePlayButton()},this.$e=()=>{this.l.prompt=null,this.l.undo()},this.cleanUp=()=>{this.Oe.removeEventListener("click",this.He),this.Re.removeEventListener("click",this.$e),this.container.removeEventListener("keydown",this.whenKeyPressed),this.dn.removeEventListener("click",this.pn)},this.whenKeyPressed=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode?this.He():32==t.keyCode?(this.pn(),t.preventDefault()):90==t.keyCode?(this.customChipCanvas.undo(),t.stopPropagation()):89==t.keyCode?(this.customChipCanvas.redo(),t.stopPropagation()):219==t.keyCode?this.l.synth.goToPrevBar():221==t.keyCode&&this.l.synth.goToNextBar()},this.He=()=>{this.l.prompt=null,new se(this.l,this.customChipCanvas.startingChipData),this.l.record(new se(this.l,this.customChipCanvas.chipData),!0)},this.Oe.addEventListener("click",this.He),this.Re.addEventListener("click",this.$e),this.container.addEventListener("keydown",this.whenKeyPressed),this.dn.addEventListener("click",this.pn),this.updatePlayButton(),setTimeout((()=>this.dn.focus())),this.customChipCanvas.render()}updatePlayButton(){this.l.synth.playing?(this.dn.classList.remove("playButton"),this.dn.classList.add("pauseButton"),this.dn.title="Pause (Space)",this.dn.innerText="Pause"):(this.dn.classList.remove("pauseButton"),this.dn.classList.add("playButton"),this.dn.title="Play (Space)",this.dn.innerText="Play")}}class Yi{constructor(t,e=!1,n=!1){if(this.l=t,this.u=120,this.v=26,this.mn=K.path({fill:et.uiWidgetBackground,"pointer-events":"none"}),this.un=[],this.ge=[],this.fn=K.path({fill:"currentColor","pointer-events":"none"}),this.yn=K.path({fill:"none",stroke:"currentColor","stroke-width":1,"stroke-dasharray":"3, 2","pointer-events":"none"}),this.bn=K.circle({fill:"white",stroke:"none","pointer-events":"none",r:4}),this.q=K.svg({style:`background-color: ${et.editorBackground}; touch-action: none;`,width:"100%",height:"100%",viewBox:"0 0 "+this.u+" "+this.v,preserveAspectRatio:"none"},this.mn,this.yn,this.bn,this.fn),this.selfUndoSettings=[],this.selfUndoHistoryPos=0,this.gn=U.div({style:"position: absolute; bottom: 0; left: 2px; font-size: 8px; line-height: 1; pointer-events: none;"}),this.coordText=null,this.container=U.div({class:"filterEditor",style:"height: 100%; position: relative;"},this.q,this.gn),this.wn=2,this.be=!1,this.vn=!1,this.xn=!1,this.N=0,this.Xe=0,this.O=!1,this.R=!1,this.kn=!1,this.Mn=!1,this.Sn=!1,this.Fn=2,this.Cn=0,this.An=0,this.En=0,this.Tn=null,this.Pn=0,this.Dn=-1,this.Bn=-1,this.In=-1,this.Ln=-1,this.qn=-1,this._e=t=>{90==t.keyCode&&(this.undo(),t.stopPropagation()),89==t.keyCode&&(this.redo(),t.stopPropagation())},this.j=t=>{this.O=!0,this.vn||this.fn.style.setProperty("fill","currentColor")},this.K=t=>{this.O=!1,this.zn(),null!=this.coordText&&(this.coordText.innerText="")},this.J=t=>{t.preventDefault(),this.xn=!1;const e=this.q.getBoundingClientRect();this.N=((t.clientX||t.pageX)-e.left)*this.u/(e.right-e.left),this.Xe=((t.clientY||t.pageY)-e.top)*this.v/(e.bottom-e.top),isNaN(this.N)&&(this.N=0),isNaN(this.Xe)&&(this.Xe=0),this.Nn()},this.X=t=>{t.preventDefault(),this.xn=!0;const e=this.q.getBoundingClientRect();this.N=(t.touches[0].clientX-e.left)*this.u/(e.right-e.left),this.Xe=(t.touches[0].clientY-e.top)*this.v/(e.bottom-e.top),isNaN(this.N)&&(this.N=0),isNaN(this.Xe)&&(this.Xe=0),this.Nn()},this.Z=t=>{if(null==this.container.offsetParent)return;const e=this.q.getBoundingClientRect();this.N=((t.clientX||t.pageX)-e.left)*this.u/(e.right-e.left),this.Xe=((t.clientY||t.pageY)-e.top)*this.v/(e.bottom-e.top),isNaN(this.N)&&(this.N=0),isNaN(this.Xe)&&(this.Xe=0),this.R||this.Rn(),this.tt()},this.et=t=>{if(null==this.container.offsetParent)return;this.R&&t.preventDefault();const e=this.q.getBoundingClientRect();this.N=(t.touches[0].clientX-e.left)*this.u/(e.right-e.left),this.Xe=(t.touches[0].clientY-e.top)*this.v/(e.bottom-e.top),isNaN(this.N)&&(this.N=0),isNaN(this.Xe)&&(this.Xe=0),this.R||this.Rn(),this.tt()},this.nt=t=>{if(null!=this.container.offsetParent){if(this.R&&this.l.lastChangeWas(this.Tn)&&null!=this.Tn){if(this.Mn||this.kn||this.xn)this.vn||this.l.record(this.Tn);else if(this.Cn=d.filterMaxPoints)&&i=0&&e=0&&t=0&&n=this.ce.controlPointCount||-1==this.Cn)this.Tn=null,this.R=!1;else{const e=this.On(this.N)-this.An,n=this.Hn(this.Xe)-this.En,i=this.ce.controlPoints[this.Cn],s=Math.max(0,Math.min(d.filterGainRange-1,Math.round(i.gain+n))),o=this.Gn(this.ce,i.freq+e,this.Cn);0==Math.round(e)&&0==Math.round(n)&&o==i.freq&&s==i.gain||(this.kn=!0),o>=0&&o0){if(this.selfUndoHistoryPos--,null!=this.selfUndoSettings[this.selfUndoHistoryPos+1]&&this.selfUndoSettings[this.selfUndoHistoryPos+1].startsWith("jmp")){let t=this.selfUndoSettings[this.selfUndoHistoryPos+1],e=+t.substring(3,t.indexOf("|"));return this.swapToSubfilter(this.Pn,e),e}if(this.selfUndoSettings[this.selfUndoHistoryPos].startsWith("jmp")){let t=new zt,e=this.selfUndoSettings[this.selfUndoHistoryPos];t.fromJsonObject(JSON.parse(e.substring(e.indexOf(":")+1))),this.swapToSettings(t,!1)}else{let t=new zt;t.fromJsonObject(JSON.parse(String(this.selfUndoSettings[this.selfUndoHistoryPos]))),this.swapToSettings(t,!1)}}return-1}redo(){if(this.selfUndoHistoryPos=this.ce.controlPointCount)return;let e=this.ce.controlPoints[this.Cn];this.ce.controlPoints[this.Cn]=this.ce.controlPoints[t],this.ce.controlPoints[t]=e,this.render()}swapToSubfilter(t,e,n=!1){if(t!=e){let i=new zt;if(i.fromJsonObject(this.ce.toJsonObject()),this.ge[t]=i,null==this.ge[e]){let t=new zt;t.fromJsonObject(this.ge[0].toJsonObject()),this.ge[e]=t}n&&(this.selfUndoSettings.length=this.selfUndoHistoryPos+1,this.selfUndoSettings.push("jmp"+t+"|"+e+":"+JSON.stringify(this.ge[e].toJsonObject())),this.selfUndoHistoryPos++),this.Pn=e,this.swapToSettings(this.ge[e],!1)}}render(t=!1){const e=this.l.song.channels[this.l.channel].instruments[this.l.getCurrentInstrument()],n=this.be?e.noteFilter:e.eqFilter;let i=t&&!this.vn&&!this.O&&!this.kn&&!this.R&&this.l.synth.playing;i?this.fn.style.setProperty("fill",`${et.overwritingModSlider}`):this.vn||this.fn.style.setProperty("fill","currentColor"),this.ce!=n&&(this.Tn=null,this.R=!1),this.ce=n;let s=n;this.R||this.Rn(),i&&(s=this.be?e.tmpNoteFilterStart:e.tmpEqFilterStart,null==s&&(s=this.be?e.noteFilter:e.eqFilter),this.ce=s);let o=0,a=0,r=0;for(let t=0;t{this.Wn[this.Pn].classList.remove("selected-instrument"),n&&this.filterEditor.swapToSubfilter(this.Pn,t,e),this.Pn=t,this.Wn[t].classList.add("selected-instrument")},this.ti=()=>{const t=this.be?this.l.song.channels[this.l.channel].instruments[this.l.getCurrentInstrument()].noteFilter.toJsonObject():this.l.song.channels[this.l.channel].instruments[this.l.getCurrentInstrument()].eqFilter.toJsonObject();window.localStorage.setItem("filterCopy",JSON.stringify(t))},this.ei=()=>{let t=new zt;t.fromJsonObject(JSON.parse(String(window.localStorage.getItem("filterCopy")))),null!=t&&this.filterEditor.swapToSettings(t,!0)},this._e=t=>{if(90==t.keyCode){let e=this.filterEditor.undo();e>=0&&this.Zn(e,!1,!1),t.stopPropagation()}if(89==t.keyCode){let e=this.filterEditor.redo();e>=0&&this.Zn(e,!1,!1),t.stopPropagation()}t.keyCode>=49&&t.keyCode<=57&&(t.shiftKey||(this.filterEditor.swapSubfilterIndices(t.keyCode-49),t.stopPropagation()))},this.pn=()=>{this.cn.togglePlay(),this.updatePlayButton()},this.$e=()=>{this.l.prompt=null,this.filterEditor.resetToInitial(),this.l.undo()},this.cleanUp=()=>{this.Oe.removeEventListener("click",this.He),this.Re.removeEventListener("click",this.$e),this.container.removeEventListener("keydown",this.whenKeyPressed),this.dn.removeEventListener("click",this.pn)},this.whenKeyPressed=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode?this.He():32==t.keyCode?(this.pn(),t.preventDefault()):90==t.keyCode?(this.filterEditor.undo(),t.stopPropagation()):89==t.keyCode?(this.filterEditor.redo(),t.stopPropagation()):219==t.keyCode?this.l.synth.goToPrevBar():221==t.keyCode?this.l.synth.goToNextBar():t.keyCode>=48&&t.keyCode<=57&&t.shiftKey&&this.Zn(t.keyCode-48)},this.He=()=>{this.l.prompt=null,this.filterEditor.saveSettings()},this.Oe.addEventListener("click",this.He),this.Re.addEventListener("click",this.$e),this.dn.addEventListener("click",this.pn),this.Jn.addEventListener("click",this.ti),this.Yn.addEventListener("click",this.ei),this.updatePlayButton();let i=et.getChannelColor(this.l.song,this.l.channel);this.filterEditor=new Yi(t,n,!0),this.Un.appendChild(this.filterEditor.container),this.filterEditor.container.insertBefore(this.Xn,this.filterEditor.container.firstChild),this.filterEditor.coordText=this.Xn,this.Kn.children[0].innerHTML=n?"Edit Note Filter":"Edit EQ Filter";let s=Qi({class:"no-underline",style:"max-width: 5em;"},"Main");this.jn.appendChild(s),this.Wn.push(s),s.addEventListener("click",(()=>{this.Zn(0)}));for(let t=1;t{this.Zn(t)}))}this.Wn[d.filterMorphCount-1].classList.add("last-button"),this.Wn[0].classList.add("selected-instrument"),this.jn.style.setProperty("--text-color-lit",i.primaryNote),this.jn.style.setProperty("--text-color-dim",i.secondaryNote),this.jn.style.setProperty("--background-color-lit",i.primaryChannel),this.jn.style.setProperty("--background-color-dim",i.secondaryChannel),this.Un.addEventListener("keydown",this._e),this.filterEditor.container.addEventListener("keydown",this._e),this.container.addEventListener("keydown",this._e),setTimeout((()=>this.dn.focus())),this.filterEditor.render()}updatePlayButton(){this.l.synth.playing?(this.dn.classList.remove("playButton"),this.dn.classList.add("pauseButton"),this.dn.title="Pause (Space)",this.dn.innerText="Pause"):(this.dn.classList.remove("pauseButton"),this.dn.classList.add("playButton"),this.dn.title="Play (Space)",this.dn.innerText="Play")}}const{button:ns,div:is,h2:ss,input:os}=U;function as(t,e){for(;0!==e;){const n=t%e;t=e,e=n}return t}function rs(t,e){let n=t,i=e;const s=as(n,i);return s>1&&(n=Math.floor(n/s),i=Math.floor(i/s)),[n,i]}function hs(t,e){const n=t[0],i=t[1],s=e[0],o=e[1];return rs(function(t,e){return Math.floor(Math.abs(t*e)/as(t,e))}(n,s),as(i,o))}class ls{constructor(t){var e,n,i,s,o,a,r,h,l;this.l=t,this.ni=2,this.ii=64,this.si=14,this.oi=d.pitchChannelCountMax+d.noiseChannelCountMax-1,this.ai="euclidGenMemory",this.ri=0,this.hi=0,this.ci=-1,this.di=0,this.pi=1,this.mi=d.barCountMax,this.ui=0,this.fi=400,this.yi=10,this.bi=100,this.gi=100,this.wi=this.bi/this.ii,this.vi=this.bi/16,this.xi=this.bi/this.ii,this.ki=this.bi/2-this.vi-this.xi,this.Mi=[],this.Si=ns({class:"no-underline",style:"flex-grow: 0; flex-basis: 30px;"},K.svg({width:"26",height:"26",viewBox:"-13 -13 26 26","pointer-events":"none"},K.path({d:"M -7.07 -5.66 L -5.66 -7.07 L 0 -1.4 L 5.66 -7.07 L 7.07 -5.66 L 1.4 0 L 7.07 5.66 L 5.66 7.07 L 0 1.4 L -5.66 7.07 L -7.07 5.66 L -1.4 0 z",fill:et.primaryText}))),this.Fi=ns({class:"no-underline last-button",style:"flex-grow: 0; flex-basis: 30px;"},K.svg({width:"26",height:"26",viewBox:"-13 -13 26 26","pointer-events":"none"},K.path({d:"M -8 -1 L -1 -1 L -1 -8 L 1 -8 L 1 -1 L 8 -1 L 8 1 L 1 1 L 1 8 L -1 8 L -1 1 L -8 1 z",fill:et.primaryText}))),this.Ci=is({class:"instrument-bar",style:"justify-content: center; width: 100%;"},this.Si,this.Fi),this.Ai=K.svg({"pointer-events":"none"}),this.Ei=K.svg({"pointer-events":"none"}),this.Ti=is({style:`flex-grow: 1; color: ${et.secondaryText}`}),this.Pi=ns({style:"height: auto; min-height: var(--button-size);"},K.svg({width:"26",height:"26",viewBox:"-13 -14 26 26","pointer-events":"none"},K.rect({x:"-6",y:"-6",width:"2",height:"12",fill:et.primaryText}),K.path({d:"M 6 -6 L 6 6 L -3 0 z",fill:et.primaryText}))),this.Di=ns({style:"height: auto; min-height: var(--button-size); margin-left: 1em;"},K.svg({width:"24",height:"26",viewBox:"-10 -14 24 26","pointer-events":"none"},K.path({d:"M 6 -6 L 6 6 L -3 0 z",fill:et.primaryText}))),this.Bi=ns({style:"height: auto; min-height: var(--button-size);"},K.svg({width:"24",height:"26",viewBox:"-14 -14 24 26","pointer-events":"none"},K.path({d:"M -6 -6 L -6 6 L 3 0 z",fill:et.primaryText}))),this.Ii=ns({style:"height: auto; min-height: var(--button-size); margin-left: 1em;"},K.svg({width:"26",height:"26",viewBox:"-13 -14 26 26","pointer-events":"none"},K.rect({x:"4",y:"-6",width:"2",height:"12",fill:et.primaryText}),K.path({d:"M -6 -6 L -6 6 L 3 0 z",fill:et.primaryText}))),this.Li=K.circle({cx:this.bi/2,cy:this.gi/2,r:this.ki,stroke:et.primaryText,"stroke-width":"0.5",fill:"none"}),this.qi=K.svg({"pointer-events":"none"}),this.zi=os({style:"width: 3em; margin-left: 1em;",type:"number",min:this.ni,max:this.ii,value:"8",step:"1"}),this.Ni=os({style:"width: 3em; margin-left: 1em;",type:"number",min:"0",max:"8",value:"5",step:"1"}),this.Ri=os({style:"width: 3em; margin-left: 1em;",type:"number",min:"0",max:this.ii,value:"0",step:"1"}),this.Oi=os({style:"width: 3em; margin-left: 1em;",type:"number",min:"1",max:d.partsPerBeat,value:"1",step:"1"}),this.$i=os({style:"width: 3em; margin-left: 1em;",type:"number",min:"1",max:d.partsPerBeat,value:"4",step:"1"}),this.Hi=os({style:"width: 3em; margin-left: 1em;",type:"number",min:"1",max:this.oi+1,value:"1",step:"1"}),this.Vi=os({style:"width: 3em; margin-left: 1em;",type:"number",min:"0",max:d.maxPitch,value:"0",step:"1"}),this.Gi=os({style:"width: 3em; margin-left: 1em;",type:"number",min:"1",max:d.barCountMax,value:"1",step:"1"}),this._i=ns({style:"height: auto; min-height: var(--button-size); margin-left: 1em;"},"Extend until loop"),this.Wi=os({type:"checkbox",style:"width: 1em; padding: 0; margin-left: 1em;"}),this.ji=os({type:"checkbox",style:"width: 1em; padding: 0; margin-left: 1em;"}),this.Oe=ns({class:"okayButton",style:"width: 45%;"},"Okay"),this.Re=ns({class:"cancelButton"}),this.container=is({class:"prompt noSelection",style:"width: 600px;"},ss("Generate Euclidean Rhythm"),is({style:"display: flex; flex-direction: row; align-items: center;"},this.Ci),is({style:"display: flex; flex-direction: row; align-items: center; justify-content: space-between;"},is({style:"flex-grow: 0; flex-shrink: 0;"},this.Pi,this.Di),this.Ti,is({style:"flex-grow: 0; flex-shrink: 0;"},this.Bi,this.Ii)),is({style:"display: flex; flex-direction: row; align-items: center; justify-content: center;"},K.svg({"pointer-events":"none",style:"touch-action: none; overflow: hidden;",width:"100%",height:"20px",viewBox:`0 0 ${this.fi} ${this.yi}`,preserveAspectRatio:"none"},this.Ai,this.Ei)),is({style:"display: flex; flex-direction: row; align-items: center; justify-content: space-evenly;"},is({style:"max-width: 150px; height: 100%;"},K.svg({"pointer-events":"none",width:"100%",height:"100%",style:"touch-action: none; overflow: hidden; margin-right: 1.5em; max-width: 150px; height: 100%;",viewBox:`0 0 ${this.bi} ${this.gi}`,preserveAspectRatio:"none"},this.Li,this.qi)),is({style:"display: flex; height: 100%;"},is({style:"flex-grow: 1; "},is({style:"display: flex; flex-direction: row; align-items: center; height: 3em; justify-content: flex-end;"},is({style:`text-align: right; flex-grow: 1; color: ${et.primaryText};`},"Steps"),this.zi),is({style:"display: flex; flex-direction: row; align-items: center; height: 3em; justify-content: flex-end; margin-top: 0.5em;"},is({style:`text-align: right; flex-grow: 1; color: ${et.primaryText};`},"Pulses"),this.Ni),is({style:"display: flex; flex-direction: row; align-items: center; height: 3em; justify-content: flex-end; margin-top: 0.5em;"},is({style:`text-align: right; flex-grow: 1; color: ${et.primaryText};`},"Rotation"),this.Ri)),is({style:"flex-grow: 1; margin-left: 1em;"},is({style:"display: flex; flex-direction: row; align-items: center; height: 3em; justify-content: flex-end; margin-bottom: 1em;"},is({style:`text-align: right; flex-grow: 1; color: ${et.primaryText};`},"Size"),is({style:"display: flex; flex-direction: column;"},this.Oi,this.$i)),is({style:"display: flex; flex-direction: row; align-items: center; height: 3em; justify-content: flex-end; margin-top: 0.5em;"},is({style:`text-align: right; flex-grow: 1; color: ${et.primaryText};`},"Channel"),this.Hi),is({style:"display: flex; flex-direction: row; align-items: center; height: 3em; justify-content: flex-end; margin-top: 0.5em;"},is({style:`text-align: right; flex-grow: 1; color: ${et.primaryText};`},"Pitch"),this.Vi)))),is({style:"display: flex; flex-direction: row; align-items: center; justify-content: flex-end;"},is({style:`text-align: right; color: ${et.primaryText};`},"Generate fading notes"),this.Wi,is({style:`text-align: right; color: ${et.primaryText}; margin-left: 1em;`},"Invert"),this.ji),is({style:"display: flex; flex-direction: row; align-items: center; justify-content: flex-end;"},is({style:`text-align: right; color: ${et.primaryText};`},"Length (in bars)"),this.Gi,this._i),is({style:"display: flex; flex-direction: row-reverse; justify-content: space-between;"},this.Oe),this.Re),this.cleanUp=()=>{this.Oe.removeEventListener("click",this.He),this.Re.removeEventListener("click",this.$e),this.container.removeEventListener("keydown",this._e),this.Ci.removeEventListener("click",this.Ui),this.Pi.removeEventListener("click",this.Ki),this.Di.removeEventListener("click",this.Ji),this.Bi.removeEventListener("click",this.Yi),this.Ii.removeEventListener("click",this.Qi),this.zi.removeEventListener("change",this.Xi),this.Ni.removeEventListener("change",this.Zi),this.Ri.removeEventListener("change",this.ts),this.Oi.removeEventListener("change",this.es),this.$i.removeEventListener("change",this.es),this.Hi.removeEventListener("change",this.ns),this.Vi.removeEventListener("change",this.ss),this.Gi.removeEventListener("change",this.os),this.ji.removeEventListener("change",this.rs),this.Wi.removeEventListener("change",this.hs),this._i.removeEventListener("click",this.ls)},this.$e=()=>{this.l.undo()},this.He=()=>{this.l.prompt=null;const t=new Jt,e=this.l.song.beatsPerBar,n=d.partsPerBeat,i=n*e,s=this.di,o=s+this.pi;if(o>this.l.song.barCount){const e=this.l.song.barCount-s,n=this.pi-e;t.append(new pe(this.l,this.l.song.barCount,n))}let a=new Map,r=new Map;for(let t=s;t0))continue;const c=s.steps;if(l.length!==c){console.error("The size of the generated sequence and the specified number of steps it should take have diverged: generated",l.length,"steps but expected",c);continue}const p=s.stepSizeNumerator/s.stepSizeDenominator,m=s.pitch,u=s.channel,f=s.invert?0:1,y=s.generateFadingNotes;r.set(m,!0);let b=a.get(u);if(null==b){b=[];for(let t=0;ti)&&(s=!0);const r=Math.max(0,Math.min(i,o)),u=Math.max(0,Math.min(i,a));if(l[t%c]===f){const t=new Ct(m,r,u,d.noteSizeMax,y);if(e&&(t.continuesLastPattern=!0),s&&y){const e=(r-o)/(a-o),n=Math.round(d.noteSizeMax+(0-d.noteSizeMax)*e);t.pins[0].size=n;const i=(u-o)/(a-o),s=Math.round(d.noteSizeMax+(0-d.noteSizeMax)*i);t.pins[1].size=s}g.push(t)}}}}for(const[e,n]of a.entries())for(let i=0;i=0;t--){const e=h[t];let n=[];for(const t of e.pitches)r.has(t)||n.push(t);e.pitches=n,e.pitches.length<1&&h.splice(t,1)}let m=[];for(const t of h)m.push({noteType:"old",eventType:"start",part:t.start,note:t}),m.push({noteType:"old",eventType:"end",part:t.end,note:t});for(const t of o)for(const e of t)m.push({noteType:"new",eventType:"start",part:e.start,note:e}),m.push({noteType:"new",eventType:"end",part:e.end,note:e});m.sort(((t,e)=>t.part-e.part));let u=[],f=null;for(let t of m)null==f?f={part:t.part,events:[t]}:t.part!==f.part?(u.push(f),f={part:t.part,events:[t]}):f.events.push(t);null!=f&&u.push(f);let y=[],b=0,g=0,w=new Set,v=[],x=new Set;for(const t of u)if(0===y.length){for(const e of t.events){if("end"===e.eventType)throw new Error("Got note end earlier than expected");if("start"!==e.eventType)throw new Error("Unknown mergeable event type");y.push({noteType:e.noteType,note:e.note})}b=t.part}else{for(const e of t.events)if("end"===e.eventType)w.add(e.note);else{if("start"!==e.eventType)throw new Error("Unknown mergeable event type");v.push({noteType:e.noteType,note:e.note})}g=t.part;const e=new Ct(0,b,g,d.noteSizeMax,!1);let n=!1,i=null,s=null;for(const t of y){const e=t.note;for(const t of e.pitches)x.add(t);if(e.continuesLastPattern&&(n=!0),"new"===t.noteType)(null==i||t.note.start>i.start||t.note.endt-e));if(e.pitches=o,e.continuesLastPattern=n,null!=i){const t=i.start,n=i.end,s=i.pins[0].size,o=i.pins[1].size,a=(b-t)/(n-t),r=Math.round(s+(o-s)*a);e.pins[0].size=r;const h=(g-t)/(n-t),l=Math.round(s+(o-s)*h);e.pins[1].size=l}else if(null!=s){const t=g-b,n=b-s.start,i=g-s.start;let o=[],a=-1,r=-1,h=0,l=s.pins.length-1;for(let t=0;t=n&&e.time<=i)-1===a&&(a=t),r=t;else if(e.time>i){l=t;break}}if(-1!==a){for(let t=a;t<=r;t++){const e=s.pins[t],i=e.time-n;o.push(Ft(0,i,e.size))}const e=o[0],c=o[o.length-1];if(0!==e.time){const t=s.pins[h],i=n-t.time,a=i/(i+e.time),r=Math.round(t.size+(e.size-t.size)*a);o.unshift(Ft(0,0,r))}if(c.time!==t){const e=s.pins[l],a=i-(c.time+n),r=a/(a+(e.time-i)),h=Math.round(c.size+(e.size-c.size)*r);o.push(Ft(0,t,h))}}else{const e=s.pins[h],a=s.pins[l],r=n-e.time,c=i-e.time,d=a.time-e.time,p=r/d,m=c/d,u=Math.round(e.size+(a.size-e.size)*p),f=Math.round(e.size+(a.size-e.size)*m);o.push(Ft(0,0,u)),o.push(Ft(0,t,f))}e.pins=o}if(e.pins.length<2)throw new Error("Ended up generating note with less than two pins");if(e.pitches.length<1)throw new Error("Ended up generating note with no pitches");p.push(e);for(let t of w)for(let e=y.length-1;e>=0;e--){t===y[e].note&&y.splice(e,1)}for(let t of v)y.push(t);for(x.clear(),w.clear();v.length>0;)v.pop();b=g}c.notes=[];for(let e=0;e{this.ds=[];for(let t=0;t{const e=this.cs[t];this.ds[t]=function(t,e,n){t=Math.max(0,t),e=Math.max(0,Math.min(t,e));let i=[];for(let n=0;n=e?0:1]);let s=t,o=t-e;if(s>0&&o>0)for(;s!==o;){s>o?s-=o:o-=s;const t=Math.min(s,o);if(!(t<=1))for(let e=0;e{this.us(this.ri)},this._e=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.He()},this.Ui=t=>{if(t.target==this.Fi){const t=this.cs[this.ri];this.cs.push({steps:t.steps,pulses:t.pulses,rotation:t.rotation,stepSizeNumerator:t.stepSizeNumerator,stepSizeDenominator:t.stepSizeDenominator,channel:t.channel,pitch:t.pitch,invert:t.invert,generateFadingNotes:t.generateFadingNotes}),this.ri=this.cs.length-1,this.fs(),this.ys(),this.bs(),this.gs(),this.ws()}else if(t.target==this.Si)this.cs.splice(this.ri,1),this.ds.splice(this.ri,1),this.ri=Math.max(0,Math.min(this.cs.length-1,this.ri)),this.ys(),this.bs(),this.gs(),this.ws();else{const e=this.Mi.indexOf(t.target);-1!=e&&(this.ri=e,this.ys(),this.bs(),this.gs(),this.ws())}},this.Ki=t=>{this.ui=this.di,this.vs(),this.xs()},this.Ji=t=>{this.ui=this.ui-1,this.ui{this.ui=this.ui+1;const e=this.di+this.pi;this.ui>=e&&(this.ui-=this.pi),this.vs(),this.xs()},this.Qi=t=>{const e=this.di+this.pi;this.ui=e-1,this.vs(),this.xs()},this.rs=t=>{const e=this.cs[this.ri],n=this.ji.checked;e.invert=n,this.ks(),this.vs()},this.hs=t=>{const e=this.cs[this.ri],n=this.Wi.checked;e.generateFadingNotes=n,this.vs()},this.ls=t=>{const e=[this.l.song.beatsPerBar,1],n=function(t,e){const n=t[0],i=t[1],s=e[0];return rs(n*e[1],i*s)}(this.cs.reduce(((t,n)=>{const i=function(t,e){const n=t[0],i=t[1];return rs(n*e[0],i*e[1])}([n.steps,1],rs(n.stepSizeNumerator,n.stepSizeDenominator));return hs(t,hs(i,e))}),[1,1]),e),i=n[0];this.pi=Math.max(1,Math.min(this.mi,i));const s=this.di,o=this.di+this.pi;this.ui=Math.max(s,Math.min(o-1,this.ui)),this.Gi.value=this.pi+"",this.vs(),this.xs()},this.Xi=t=>{const e=Math.max(this.ni,Math.min(this.ii,+this.zi.value));this.cs[this.ri].steps=e,this.zi.value=e+"",this.bs(),this.fs(),this.ws()},this.Zi=t=>{const e=this.cs[this.ri],n=Math.max(0,Math.min(e.steps,+this.Ni.value));e.pulses=n,this.Ni.value=n+"",this.fs(),this.ws()},this.ts=t=>{const e=Math.max(0,Math.min(this.ii,+this.Ri.value));this.cs[this.ri].rotation=e,this.Ri.value=e+"",this.fs(),this.ws()},this.es=t=>{const e=Math.max(1,Math.min(d.partsPerBeat,+this.Oi.value)),n=Math.max(1,Math.min(d.partsPerBeat,+this.$i.value)),i=this.cs[this.ri];i.stepSizeNumerator=e,i.stepSizeDenominator=n,this.Oi.value=e+"",this.$i.value=n+"",this.vs()},this.ss=t=>{const e=this.cs[this.ri],n=this.l.song.getChannelIsNoise(e.channel)?d.drumCount-1:d.maxPitch,i=Math.max(0,Math.min(n,+this.Vi.value));e.pitch=i,this.Vi.value=i+"",this.xs()},this.ns=t=>{const e=Math.max(0,Math.min(this.oi,+this.Hi.value-1));this.cs[this.ri].channel=e,this.Hi.value=e+1+"",this.gs(),this.ws()},this.os=t=>{const e=Math.max(1,Math.min(this.mi,+this.Gi.value));this.pi=e;const n=this.di,i=this.di+this.pi;this.ui=Math.max(n,Math.min(i-1,this.ui)),this.Gi.value=e+"",this.vs(),this.xs()},this.Ms=()=>{const t=this.l.song.beatsPerBar,e=et.pitchBackground,n=this.Ai,i=this.fi/t,s=this.yi;for(let o=0;o{const t=this.cs[this.ri];this.zi.value=t.steps+"",this.Ni.value=t.pulses+"",this.Ri.value=t.rotation+"",this.Oi.value=t.stepSizeNumerator+"",this.$i.value=t.stepSizeDenominator+"",this.Hi.value=t.channel+1+"",this.Vi.value=t.pitch+"",this.ji.checked=t.invert,this.Wi.checked=t.generateFadingNotes,this.Gi.value=this.pi+""},this.gs=()=>{const t=this.cs[this.ri],e=t.channel,n=this.l.song.getChannelIsNoise(e)?d.drumCount-1:d.maxPitch;this.Vi.value=Math.max(0,Math.min(n,+this.Vi.value))+"",this.Vi.max=n+"",t.pitch=+this.Vi.value},this.bs=()=>{const t=this.cs[this.ri],e=t.steps;this.Ni.value=Math.max(0,Math.min(e,+this.Ni.value))+"",this.Ni.max=e+"",t.pulses=+this.Ni.value},this.ws=()=>{this.ks(),this.vs(),this.xs(),this.Ss()},this.Ss=()=>{const t=this.Ci;for(;this.Mi.lengththis.si;)t.removeChild(this.Mi.pop());if(this.Si.style.display=this.cs.length>1?"":"none",this.Fi.style.display=this.cs.length{const t=this.cs[this.ri].pitch,e=(t+d.keys[this.l.song.key].basePitch)%d.pitchesPerOctave;let n="";if(d.keys[e].isWhiteKey)n=d.keys[e].name;else{const i=d.blackKeyNameParents[t%d.pitchesPerOctave];n=d.keys[(e+d.pitchesPerOctave+i)%d.pitchesPerOctave].name,1==i?n+="♭":-1==i&&(n+="♯")}n+=Math.floor(t/d.pitchesPerOctave),this.Ti.innerText=`Bar ${this.ui+1}, ${n}`},this.ks=()=>{const t=this.cs[this.ri],e=t.steps,n=t.channel,i=this.ds[this.ri],s=i.length>0,o=t.invert?0:1,a=et.getChannelColor(this.l.song,n).primaryNote,r=et.editorBackground;this.Li.setAttribute("stroke",a);const h=this.qi;for(;null!==h.firstChild;)h.removeChild(h.firstChild);const l=this.bi/2,c=this.gi/2,d=this.ki,p=Math.max(this.wi,Math.min(this.vi,this.bi/e));for(let t=0;t{const t=this.l.song.beatsPerBar,e=d.partsPerBeat,n=e*t,i=this.cs[this.ri],s=i.steps,o=i.channel,a=i.stepSizeNumerator/i.stepSizeDenominator,r=this.ds[this.ri],h=r.length>0,l=i.invert?0:1,c=i.generateFadingNotes,p=et.getChannelColor(this.l.song,o),m=p.primaryNote,u=p.secondaryNote,f=this.ui-this.di,y=f*n,b=this.Ei;for(;null!==b.firstChild;)b.removeChild(b.firstChild);let g=[];const w=this.fi/t/e,v=this.yi,x=.2,k=Math.floor(t*f/a),M=Math.ceil(t*(f+1)/a),S=x,F=v-.4;for(let t=k;tn)&&(o=!0);const v=Math.max(0,Math.min(n,p)),k=Math.max(0,Math.min(n,f)),M=x+v*w,C=(k-v)*w-.4;if(h&&r[t%s]===l){if(c){const t=K.rect({x:M,y:S,width:C,height:F,style:`fill: ${u};`});b.appendChild(t);let e=d.noteSizeMax,n=0;if(o){const t=(v-p)/(f-p);e=Math.round(d.noteSizeMax+(0-d.noteSizeMax)*t);const i=(k-p)/(f-p);n=Math.round(d.noteSizeMax+(0-d.noteSizeMax)*i)}e/=d.noteSizeMax,n/=d.noteSizeMax;const i=M,s=S+F/2*(1-e),a=M+C,r=S+F/2*(1-n),h=M+C,l=S+F-F/2*(1-n),c=M,y=S+F-F/2*(1-e),g=K.path({d:`M ${i} ${s} L ${a} ${r} L ${h} ${l} L ${c} ${y} z`,style:`fill: ${m};`});b.appendChild(g)}else{const t=K.rect({x:M,y:S,width:C,height:F,style:`fill: ${m};`});b.appendChild(t)}if(i){let t=2.2;const e=Math.min(F,20),n=S+F/2;let i;i="M "+L(w*v+t)+" "+L(n-.1*e),i+="L "+L(w*v+t)+" "+L(n+.1*e),i+="L "+L(w*v+t+4)+" "+L(n+.1*e),i+="L "+L(w*v+t+4)+" "+L(n+.3*e),i+="L "+L(w*v+t+12)+" "+L(n),i+="L "+L(w*v+t+4)+" "+L(n-.3*e),i+="L "+L(w*v+t+4)+" "+L(n-.1*e);const s=K.path();s.setAttribute("d",i),s.setAttribute("fill",et.invertedText),g.push(s)}}}for(let t of g)b.appendChild(t)},this.di=this.l.bar,this.ui=this.di,this.mi=d.barCountMax-this.di,this.Gi.max=this.mi+"",this.oi=this.l.song.pitchChannelCount+this.l.song.noiseChannelCount-1,this.Hi.max=this.oi+1+"";const c=Math.max(this.ni,Math.min(this.ii,this.l.song.beatsPerBar)),p=Math.max(0,Math.min(c,5));if(this.cs=[{steps:c,pulses:p,rotation:0,stepSizeNumerator:1,stepSizeDenominator:4,channel:Math.max(0,Math.min(this.oi,this.l.channel)),pitch:0,invert:!1,generateFadingNotes:!1}],this.l.selection.boxSelectionActive){this.di=this.l.selection.boxSelectionBar,this.ui=this.di,this.pi=Math.max(1,Math.min(this.mi,this.l.selection.boxSelectionWidth)),this.cs[0].channel=Math.max(0,Math.min(this.oi,this.l.selection.boxSelectionChannel));for(let t=1;t=e){const o=a(e,t,n,i,s);i=o.nextOffset,s=o.leftBytes}return n;function a(t,e,n,i,s){let o=Uint8Array;switch(t){case 8:o=Float64Array;break;case 4:o=Float32Array;break;case 2:o=Uint16Array;break;default:o=Uint8Array}const a=new o(e,i,s/t|0),r=new o(n,i,s/t|0);for(let t=0;tthis.As.byteLength&&(this.As=cs(this.As,Math.max(2*this.As.byteLength,this.Cs)),this.Es=new DataView(this.As))}getWriteIndex(){return this.Fs}rewriteUint32(t,e){this.Es.setUint32(t,e>>>0,!1)}writeUint32(t){t>>>=0,this.Ts(4),this.Es.setUint32(this.Fs,t,!1),this.Fs=this.Cs}writeUint24(t){t>>>=0,this.Ts(3),this.Es.setUint8(this.Fs,t>>16&255),this.Es.setUint8(this.Fs+1,t>>8&255),this.Es.setUint8(this.Fs+2,255&t),this.Fs=this.Cs}writeUint16(t){t>>>=0,this.Ts(2),this.Es.setUint16(this.Fs,t,!1),this.Fs=this.Cs}writeUint8(t){t>>>=0,this.Ts(1),this.Es.setUint8(this.Fs,t),this.Fs=this.Cs}writeInt8(t){t|=0,this.Ts(1),this.Es.setInt8(this.Fs,t),this.Fs=this.Cs}writeMidi7Bits(t){if((t>>>=0)>=128)throw new Error("7 bit value contained 8th bit!");this.Ts(1),this.Es.setUint8(this.Fs,t),this.Fs=this.Cs}writeMidiVariableLength(t){if((t>>>=0)>268435455)throw new Error("writeVariableLength value too big.");let e=!1;for(let n=0;n<4;n++){const i=t>>>21-7*n&127;0==i&&3!=n||(e=!0),e&&this.writeUint8((3==n?0:128)|i)}}writeMidiAscii(t){this.writeMidiVariableLength(t.length);for(let e=0;e127)throw new Error("Trying to write unicode character as ascii.");this.writeUint8(n)}}toCompactArrayBuffer(){return cs(this.As,this.Cs)}}const ps=8192,ms={35:{frequency:0,duration:2,volume:3},36:{frequency:0,duration:2,volume:3},37:{frequency:5,duration:1,volume:3},38:{frequency:4,duration:2,volume:3},39:{frequency:5,duration:2,volume:3},40:{frequency:4,duration:2,volume:3},41:{frequency:1,duration:2,volume:3},42:{frequency:8,duration:1,volume:3},43:{frequency:1,duration:2,volume:3},44:{frequency:8,duration:1,volume:2},45:{frequency:2,duration:2,volume:3},46:{frequency:8,duration:4,volume:3},47:{frequency:2,duration:2,volume:3},48:{frequency:3,duration:2,volume:3},49:{frequency:7,duration:4,volume:3},50:{frequency:3,duration:2,volume:3},51:{frequency:6,duration:4,volume:2},52:{frequency:7,duration:4,volume:3},53:{frequency:6,duration:2,volume:3},54:{frequency:11,duration:2,volume:3},55:{frequency:9,duration:4,volume:3},56:{frequency:7,duration:1,volume:2},57:{frequency:7,duration:4,volume:3},58:{frequency:10,duration:2,volume:2},59:{frequency:6,duration:4,volume:3},69:{frequency:10,duration:2,volume:3},70:{frequency:10,duration:2,volume:3},73:{frequency:10,duration:1,volume:2},74:{frequency:10,duration:2,volume:2}};function us(t){return Math.pow(t/127,4)/.3844015376046128}const{button:fs,div:ys,h2:bs,input:gs,select:ws,option:vs}=U;function xs(t,e,n){return t+n*(e-t)}function ks(t,e){if(navigator.msSaveOrOpenBlob)return void navigator.msSaveOrOpenBlob(t,e);const n=document.createElement("a");if(null!=n.download){const i=URL.createObjectURL(t);setTimeout((function(){URL.revokeObjectURL(i)}),6e4),n.href=i,n.download=e,setTimeout((function(){n.dispatchEvent(new MouseEvent("click"))}),0)}else{const e=URL.createObjectURL(t);setTimeout((function(){URL.revokeObjectURL(e)}),6e4),window.open(e,"_blank")||(window.location.href=e)}}class Ms{constructor(t){this.l=t,this.outputStarted=!1,this.Ps=gs({type:"text",style:"width: 10em;",value:"BeepBox-Song",maxlength:250,autofocus:"autofocus"}),this.Ds=ys({style:"width: 10em;"},new Text("0:00")),this.Bs=gs({type:"checkbox"}),this.Is=gs({style:"width: 2em;",type:"number",min:"1",max:"4",step:"1"}),this.Ls=gs({type:"checkbox"}),this.qs=ws({style:"width: 100%;"},vs({value:"wav"},"Export to .wav file."),vs({value:"mp3"},"Export to .mp3 file."),vs({value:"midi"},"Export to .mid file."),vs({value:"json"},"Export to .json file."),vs({value:"html"},"Export to .html file.")),this.Re=fs({class:"cancelButton"}),this.zs=fs({class:"exportButton",style:"width:45%;"},"Export"),this.Ns=ys({style:`width: 0%; background: ${et.loopAccent}; height: 100%; position: absolute; z-index: 2;`}),this.Rs=ys({style:"position: relative; top: -1px; z-index: 3;"},"0%"),this.Os=ys({style:`height: 12px; background: ${et.uiWidgetBackground}; display: block; position: relative; z-index: 1;`},this.Ns,this.Rs),this.container=ys({class:"prompt noSelection",style:"width: 200px;"},bs("Export Options"),ys({style:"display: flex; flex-direction: row; align-items: center; justify-content: space-between;"},"File name:",this.Ps),ys({style:"display: flex; flex-direction: row; align-items: center; justify-content: space-between;"},"Length:",this.Ds),ys({style:"display: table; width: 100%;"},ys({style:"display: table-row;"},ys({style:"display: table-cell;"},"Intro:"),ys({style:"display: table-cell;"},"Loop Count:"),ys({style:"display: table-cell;"},"Outro:")),ys({style:"display: table-row;"},ys({style:"display: table-cell; vertical-align: middle;"},this.Bs),ys({style:"display: table-cell; vertical-align: middle;"},this.Is),ys({style:"display: table-cell; vertical-align: middle;"},this.Ls))),ys({class:"selectContainer",style:"width: 100%;"},this.qs),ys({style:"text-align: left;"},"Exporting can be slow. Reloading the page or clicking the X will cancel it. Please be patient."),this.Os,ys({style:"display: flex; flex-direction: row-reverse; justify-content: space-between;"},this.zs),this.Re),this.$e=()=>{null!=this.synth&&(this.synth.renderingSong=!1),this.outputStarted=!1,this.l.undo()},this.cleanUp=()=>{this.Ps.removeEventListener("input",Ms.$s),this.Is.removeEventListener("blur",Ms.Ge),this.zs.removeEventListener("click",this.Hs),this.Re.removeEventListener("click",this.$e),this.container.removeEventListener("keydown",this._e)},this._e=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.Hs()},this.Hs=()=>{if(1!=this.outputStarted)switch(window.localStorage.setItem("exportFormat",this.qs.value),this.qs.value){case"wav":this.outputStarted=!0,this.Vs("wav");break;case"mp3":this.outputStarted=!0,this.Vs("mp3");break;case"midi":this.outputStarted=!0,this.Gs();break;case"json":this.outputStarted=!0,this._s();break;case"html":this.Ws();break;default:throw new Error("Unhandled file export type.")}},this.Is.value="1",0==this.l.song.loopStart?(this.Bs.checked=!1,this.Bs.disabled=!0):(this.Bs.checked=!0,this.Bs.disabled=!1),this.l.song.loopStart+this.l.song.loopLength==this.l.song.barCount?(this.Ls.checked=!1,this.Ls.disabled=!0):(this.Ls.checked=!0,this.Ls.disabled=!1);const e=window.localStorage.getItem("exportFormat");null!=e&&(this.qs.value=e),this.Ps.select(),setTimeout((()=>this.Ps.focus())),this.Ps.addEventListener("input",Ms.$s),this.Is.addEventListener("blur",Ms.Ge),this.zs.addEventListener("click",this.Hs),this.Re.addEventListener("click",this.$e),this.Ls.addEventListener("click",(()=>{this.Ds.firstChild.textContent=this.samplesToTime(this.l.synth.getTotalSamples(this.Bs.checked,this.Ls.checked,+this.Is.value-1))})),this.Bs.addEventListener("click",(()=>{this.Ds.firstChild.textContent=this.samplesToTime(this.l.synth.getTotalSamples(this.Bs.checked,this.Ls.checked,+this.Is.value-1))})),this.Is.addEventListener("change",(()=>{this.Ds.firstChild.textContent=this.samplesToTime(this.l.synth.getTotalSamples(this.Bs.checked,this.Ls.checked,+this.Is.value-1))})),this.container.addEventListener("keydown",this._e),this.Ps.value=t.song.title,Ms.$s(null,this.Ps),this.Ds.firstChild.textContent=this.samplesToTime(this.l.synth.getTotalSamples(this.Bs.checked,this.Ls.checked,+this.Is.value-1))}samplesToTime(t){const e=Math.round(t/this.l.synth.samplesPerSecond),n=e%60;return Math.floor(e/60)+":"+(n<10?"0":"")+n}changeFileName(t){this.Ps.value=t}static $s(t,e){let n;if(null!=t)n=t.target;else{if(null==e)return;n=e}const i=/[\+\*\$\?\|\{\}\\\/<>#%!`&'"=:@]/gi;if(i.test(n.value)){let t=n.selectionStart;n.value=n.value.replace(i,""),t--,n.setSelectionRange(t,t)}}static Ge(t){const e=t.target;e.value=Math.floor(Math.max(Number(e.min),Math.min(Number(e.max),Number(e.value))))+""}js(){if(0==this.outputStarted)return;const t=5*this.synth.samplesPerSecond,e=this.currentChunk*t,n=Math.min(t,this.sampleFrames-e),i=new Float32Array(n),s=new Float32Array(n);if(this.synth.renderingSong=!0,this.synth.synthesize(i,s,n),this.recordedSamplesL.set(i,e),this.recordedSamplesR.set(s,e),this.Ns.style.setProperty("width",Math.round((this.currentChunk+1)/this.totalChunks*100)+"%"),this.Rs.innerText=Math.round((this.currentChunk+1)/this.totalChunks*100)+"%",this.currentChunk++,this.currentChunk>=this.totalChunks)if(this.synth.renderingSong=!1,this.Rs.innerText="Encoding...","wav"==this.thenExportTo)this.Us();else{if("mp3"!=this.thenExportTo)throw new Error("Unrecognized file export type chosen!");this.Ks()}else setTimeout((()=>{this.js()}))}Vs(t){if(this.thenExportTo=t,this.currentChunk=0,this.synth=new jt(this.l.song),"wav"==t)this.synth.samplesPerSecond=48e3;else{if("mp3"!=t)throw new Error("Unrecognized file export type chosen!");this.synth.samplesPerSecond=44100}if(this.Ns.style.setProperty("width","0%"),this.Rs.innerText="0%",this.synth.loopRepeatCount=Number(this.Is.value)-1,!this.Bs.checked)for(let t=0;t{this.js()}))}Us(){const t=this.recordedSamplesL.length,e=this.synth.samplesPerSecond,n=2*t;let i=0;const s=new ArrayBuffer(44+2*n),o=new DataView(s);o.setUint32(i,1380533830,!1),i+=4,o.setUint32(i,36+2*n,!0),i+=4,o.setUint32(i,1463899717,!1),i+=4,o.setUint32(i,1718449184,!1),i+=4,o.setUint32(i,16,!0),i+=4,o.setUint16(i,1,!0),i+=2,o.setUint16(i,2,!0),i+=2,o.setUint32(i,e,!0),i+=4,o.setUint32(i,2*e*2,!0),i+=4,o.setUint16(i,4,!0),i+=2,o.setUint16(i,16,!0),i+=2,o.setUint32(i,1684108385,!1),i+=4,o.setUint32(i,2*n,!0),i+=4;{const e=32767;for(let n=0;n{const t=1152,e=new window.lamejs.Mp3Encoder(2,this.synth.samplesPerSecond,192),n=[],i=new Int16Array(this.recordedSamplesL.length),s=new Int16Array(this.recordedSamplesR.length);for(let t=0;t0&&n.push(h)}const o=e.flush();o.length>0&&n.push(o);ks(new Blob(n,{type:"audio/mp3"}),this.Ps.value.trim()+".mp3"),this.$e()};if("lamejs"in window)t();else{var e=document.createElement("script");e.src="https://cdn.jsdelivr.net/npm/lamejs@1.2.0/lame.min.js",e.onload=t,document.head.appendChild(e)}}Gs(){const t=this.l.song,e=2*d.ticksPerPart*d.partsPerBeat,n=2*d.ticksPerPart,i=t.getBeatsPerMinute(),s=Math.round(6e7/i),o=e*t.beatsPerBar,a=24,r=[];if(this.Bs.checked)for(let u=0;u=16)continue;h.push({isMeta:!1,channel:g,midiChannel:l++,isNoise:this.l.song.getChannelIsNoise(g),isDrumset:!1}),9==l&&l++}else h.push({isMeta:!1,channel:g,midiChannel:9,isNoise:!0,isDrumset:!0}),c=!0;const p=new ds(1024);p.writeUint32(1297377380),p.writeUint32(6),p.writeUint16(1),p.writeUint16(h.length),p.writeUint16(e);for(const v of h){p.writeUint32(1297379947);const{isMeta:x,channel:k,midiChannel:M,isNoise:S,isDrumset:F}=v,C=p.getWriteIndex();p.writeUint32(0);let A=0,E=0;const T=function(t){if(t=0&&e<=127))throw new Error("Midi control event value out of range: "+e);p.writeUint8(176|M),p.writeMidi7Bits(t),p.writeMidi7Bits(0|e)};if(x){T(0),p.writeUint8(255),p.writeMidi7Bits(1),p.writeMidiAscii("Composed with jummbus.bitbucket.io"),T(0),p.writeUint8(255),p.writeMidi7Bits(81),p.writeMidiVariableLength(3),p.writeUint24(s),T(0),p.writeUint8(255),p.writeMidi7Bits(88),p.writeMidiVariableLength(4),p.writeUint8(t.beatsPerBar),p.writeUint8(2),p.writeUint8(24),p.writeUint8(8);let D=t.scale==d.scales.dictionary.Custom.index?t.scaleCustom:d.scales[t.scale].flags;const B=D[3]&&!D[4],I=t.key;let L=I;for(1==(1&I)&&(L+=6),B&&(L+=9);L>6;)L-=12;T(0),p.writeUint8(255),p.writeMidi7Bits(89),p.writeMidiVariableLength(2),p.writeInt8(L),p.writeUint8(B?1:0),this.Bs.checked&&(E+=o*t.loopStart),T(E),p.writeUint8(255),p.writeMidi7Bits(6),p.writeMidiAscii("Loop Start");for(let z=0;zn.chipWave&&(t=Ms.midiChipInstruments[n.chipWave]);else if(6==n.type||1==n.type||10==n.type||5==n.type)t=81;else if(7==n.type)t=25;else{if(8!=n.type)throw new Error("Unrecognized instrument type.");t=81}T(E),p.writeUint8(192|M),p.writeMidi7Bits(t)}T(E);let t=(s=jt.instrumentVolumeToVolumeMult(n.volume),127*Math.pow(.3844015376046128*s,.25));P(7,Math.min(127,Math.round(t))),T(E);let o=63*(n.pan/d.panCenter-1)+64;P(10,Math.min(127,Math.round(o)))}var s}null==t.getPattern(k,0)&&O(0);let $=ps,H=127,V=!1;const G=S?d.spectrumBasePitch:d.keys[t.key].basePitch,_=S?d.noiseInterval:1;for(const W of r){const j=t.getPattern(k,W);if(null!=j){const U=j.instruments[0],K=t.channels[k].instruments[U],J=q.valueToPreset(K.preset);O(U);let Y=K.getChord().arpeggiates,Q=Y?1:d.maxChordSize;K.getChord().customInterval&&(0==K.type||5==K.type?(Q=2,Y=!0):1==K.type?Q=d.operatorCount:console.error("Unrecognized instrument type for harmonizing arpeggio: "+K.type));for(let X=0;X