-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
278 lines (268 loc) · 624 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>AestheticBox</title>
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="theme-color" content="#444" />
<meta name="format-detection" content="telephone=no" />
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet" rel="stylesheet" media="none" onload="if (this.media != 'all') this.media='all';" /> <!-- this is a trick to load CSS asynchronously. -->
<meta name="robots" content="noindex, nofollow" />
<meta name="application-name" content="AestheticBox" />
<meta name="apple-mobile-web-app-title" content="BeepBox">
<meta name="description" content="AestheticBox is an online tool for sketching and sharing instrumental music." />
<meta name="keywords" content="chiptune, instrumental, music, song, melody, composition, tool, free, BeepBox, AestheticBox" />
<meta name="msapplication-TileColor" content="#603cba" />
<meta name="msapplication-config" content="browserconfig.xml" />
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png" />
<link rel="manifest" href="manifest.webmanifest" />
<style type="text/css">
html {
background: var(--page-margin, black);
overflow-x: hidden;
font-size: large;
font-family: 'Quicksand', sans-serif;
line-height: 1.3;
color: var(--primary-text, white);
}
body {
margin: auto;
overflow-x: hidden;
display: flex;
flex-direction: column;
align-items: center;
align-content: center;
}
#beepboxEditorContainer {
min-height: 645px;
overflow: auto;
background: var(--editor-background, black);
width: 100%;
max-width: 710px;
padding-left: 30px;
padding-right: 30px;
}
#text-content {
overflow: auto;
background: var(--editor-background, black);
width: 100%;
max-width: 710px;
padding-left: 30px;
padding-right: 30px;
}
h1 {
font-size: 1.7rem;
text-align: center;
margin-top: 0.5em;
margin-bottom: 0.5em;
-webkit-text-stroke-width: 0;
}
h2 {
font-size: 1.5rem;
text-align: center;
margin-top: 0.5em;
margin-bottom: 0.5em;
-webkit-text-stroke-width: 0;
}
a {
color: var(--link-accent, #98f);
}
.donation form {
display: inline;
}
.donation input[type="submit"] {
-webkit-appearance: none;
appearance: none;
background: none;
border: none;
font-family: inherit;
font-size: inherit;
color: var(--link-accent, #98f);
text-decoration: underline;
cursor: pointer;
padding: 0;
margin: 0;
}
/* wide screen */
@media (min-width: 711px) {
html {
width: 100%;
}
body {
width: 100%;
}
.column-container {
width: 710px;
display: flex;
gap: 25px;
}
/*.instructions-column {
min-width: 0;
}
.twitter-column {
width: 300px;
flex-shrink: 0;
}*/
}
/* narrow screen */
@media (max-width: 710px) {
body {
width: 100%;
}
p, .donation {
margin: 1em 0.5em;
}
.column-container {
display: flex;
flex-direction: column;
align-items: center;
}
}
</style>
</head>
<body>
<div id="beepboxEditorContainer">
<noscript>
Sorry, AestheticBox requires a JavaScript-enabled browser.
</noscript>
</div>
<div id="text-content">
<section>
<h1>
AestheticBox
</h1>
<p id="introduction">
AestheticBox is an online (and offline!) tool for sketching and sharing instrumental music.
</p>
<p>
All song data is contained in the URL at the top of your browser.
When you make changes to the song, the URL is updated to reflect your changes.
When you are satisfied with your song, just copy and paste the URL to save and share your song!
</p>
<div class="donation">
AestheticBox is enabled by John Nesky's Beepbox!
BeepBox is a passion project, and will always be free to use. If you find it valuable and have the means, any gratuity via
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="cmd" value="_donations" />
<input type="hidden" name="business" value="QZJTX9GRYEV9N" />
<input type="hidden" name="currency_code" value="USD" />
<input type="submit" name="submit" value="Paypal"/>
</form>
would be appreciated!
</div>
</section>
<div class="column-container">
<main class="instructions-column">
<section>
<h2>
Instructions
</h2>
<p>
You can add or remove notes by clicking on the gray rows at the top.
AestheticBox automatically plays the notes out loud for you. Try it!
</p>
<p>
Notes go into patterns, and you can edit one pattern at a time.
Those numbered boxes at the bottom of the editor are the different patterns you can edit.
<span id="bar-editing">
Click the boxes to move to a different part of the song, or click the arrows on the currently selected box to swap which pattern is played during that part of the song.
</span>
</p>
<p>
AestheticBox can play several rows of patterns simultaneously, and each row has its own set of patterns.
Most rows can play melodies or harmonies, but the bottom row is for drums.
</p>
<p>
The purple loop underneath the numbered boxes controls which part of the song is currently repeating.
Move the loop to listen to a different part of the song, or drag the ends to expand the loop to include the whole song.
</p>
<div id="keyboard-instructions">
<p>
When AestheticBox has focus (click on its interface above), you can use these keyboard shortcuts: <br/>
</p>
<ul>
<li><b>Spacebar</b>: play or pause the song</li>
<li><b>Shift Spacebar</b>: play from mouse location</li>
<li><b>Z</b>: undo, <b>Y or Shift Z</b>: redo</li>
<li><b>C/V</b>: copy/paste selected pattern(s)</li>
<li><b>0-9</b>: assign pattern number to selection</li>
<li><b>Arrows</b>: move selection</li>
<li><b>Ctrl + Arrows</b>: rearrange channels</li>
<li><b>[ ]</b>: move playhead backward or forward</li>
<li><b>F/H</b>: move to First or Highlighted pattern </li>
<li><b>Shift & Drag</b>: select part of a pattern (long press on touch screen)</li>
<li>Check AestheticBox's edit menu for more!</li>
</ul>
</div>
<p>
In the note pattern editor, you can click and drag horizontally on a note to adjust its duration.
You can also click above or below an existing note to add more notes to be played simultaneously, which is called a chord.
</p>
<p>
ADVANCED: Drag vertically from an existing note to bend its pitch, or drag vertically from above or below the note to adjust its volume. Drag on the numbered pattern boxes to select multiple patterns to copy and paste parts of your song.
</p>
<p>
AestheticBox has many more features.
Try playing with the buttons and menus on the right side to find out what it can do!
You can also click on the label next to each option for a description of what it does.
</p>
</section>
<section>
<h2>
About
</h2>
<p>
BeepBox is developed by <a href="http://www.johnnesky.com" target="_blank">John Nesky</a>, also known as <a href="https://twitter.com/shaktool" target="_blank">@shaktool</a>.
AestheticBox is based off BeepBox, and is NOT developed in affiliation with BeepBox.
</p>
<p>
AestheticBox and BeepBox do not claim ownership over songs created with it, so original songs belong to their authors.
</p>
<p>
John Nesky, BeepBox, or AestheticBox do not assume responsibility for any copyrighted material played on BeepBox (and its derivatives). No songs are ever received, recorded, or distributed by BeepBox's or AestheticBox's servers. All song data is contained in the URL after the hash (#) mark, and your song data will not leave your device unless you copy and share the URL. BeepBox and AestheticBox do not collect, track, or share any user data.
</p>
<p>
You can find the <a href="https://github.com/johnnesky/beepbox/releases/" target="_blank">release notes for the latest versions of BeepBox here</a>.
</p>
<p>
You can download and use <a href="https://github.com/johnnesky/beepbox" target="_blank">the source code</a> under the MIT license
</p>
<p>
AestheticBox is exactly like BeepBox, just with some extra features. Go support John Nesky, the creator of BeepBox!
</p>
<section>
</main>
</div>
</div>
<script type="text/javascript">
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|android|ipad|playbook|silk/i.test(navigator.userAgent) ) {
document.getElementById("introduction").innerHTML = "AestheticBox is an online tool for sketching and sharing instrumental music. Make sure that your volume is turned up, then press the play button!";
document.getElementById("keyboard-instructions").style.display = "none";
document.getElementById("bar-editing").innerHTML = "Tap the boxes to move to a different part of the song, or tap on the currently selected box to swap which pattern is played during that part of the song.";
}
var beepbox=function(t){"use strict";
/*!
Copyright (c) 2012-2022 John Nesky and contributing authors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/class e{}function i(t){let e=0;for(let i=0;i<t.length;i++)e+=t[i];const i=e/t.length;for(let e=0;e<t.length;e++)t[e]-=i;return s(t),t.push(0),new Float32Array(t)}function s(t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];t[i]=e,e+=s}}function n(t){return.5*Math.pow(.5,(e.pulseWidthRange-1-t)*e.pulseWidthStepPower)}function o(t,i,s){let n=e.chipNoises[t].samples;if(null==n){if(n=new Float32Array(e.chipNoiseLength+1),e.chipNoises[t].samples=n,0==t){let t=1;for(let i=0;i<e.chipNoiseLength;i++){n[i]=2*(1&t)-1;let e=t>>1;1==(t+e&1)&&(e+=16384),t=e}}else if(1==t)for(let t=0;t<e.chipNoiseLength;t++)n[t]=2*Math.random()-1;else if(2==t){let t=1;for(let i=0;i<e.chipNoiseLength;i++){n[i]=2*(1&t)-1;let e=t>>1;1==(t+e&1)&&(e+=32768),t=e}}else if(3==t){let t=1;for(let i=0;i<e.chipNoiseLength;i++){n[i]=2*(1&t)-1;let e=t>>1;1==(t+e&1)&&(e+=40),t=e}}else{if(4!=t)throw new Error("Unrecognized drum index: "+t);r(n,e.chipNoiseLength,10,11,1,1,0),r(n,e.chipNoiseLength,11,14,.6578,.6578,0),i(n,e.chipNoiseLength),s(n,1/Math.sqrt(e.chipNoiseLength))}n[e.chipNoiseLength]=n[0]}return n}function r(t,e,i,s,n,r,h){const a=0|Math.pow(2,i),l=Math.min(e>>1,0|Math.pow(2,s)),c=o(0,null,null);let u=0;for(let o=a;o<l;o++){let a=n+(r-n)*(Math.log2(o)-i)/(s-i),l=Math.pow(2,7*(a-1)+1)*a;l*=Math.pow(o/2048,h),u+=l,l*=c[o];const f=.61803398875*o*o*Math.PI*2;t[o]=Math.cos(f)*l,t[e-o]=Math.sin(f)*l}return u}function h(t,i,s){const n=e.rhythms[i].arpeggioPatterns[t-1];return null!=n?n[s%n.length]:s%t}function a(t){const e={};for(let i=0;i<t.length;i++){const s=t[i];s.index=i,e[s.name]=s}const i=t;return i.dictionary=e,i}function l(t){return 0!=(1024&t)}function c(t){return 0!=(2048&t)}function u(t){return 0!=(128&t)}function f(t){return 0!=(256&t)}function p(t){return 0!=(512&t)}function d(t){return 0!=(32&t)}function m(t){return 0!=(8&t)}function y(t){return 0!=(16&t)}function g(t){return 0!=(4&t)}function b(t){return 0!=(2&t)}function w(t){return 0!=(64&t)}function v(t){return 0!=(1&t)}e.scales=a([{name:"Chromatic",realName:"chromatic",flags:[!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0,!0]},{name:"Pentatonic Major",realName:"pentatonic major",flags:[!0,!1,!0,!1,!0,!1,!1,!0,!1,!0,!1,!1]},{name:"Pentatonic Minor",realName:"pentatonic minor",flags:[!0,!1,!1,!0,!1,!0,!1,!0,!1,!1,!0,!1]},{name:"Ryukyu",realName:"ryukyu",flags:[!0,!1,!1,!1,!0,!0,!1,!0,!1,!1,!1,!0]},{name:"Pelog Selisir",realName:"pelog selisir",flags:[!0,!0,!1,!0,!1,!1,!1,!0,!0,!1,!1,!1]},{name:"Blues Major",realName:"blues major",flags:[!0,!1,!0,!0,!0,!1,!1,!0,!1,!0,!1,!1]},{name:"Blues",realName:"blues",flags:[!0,!1,!1,!0,!1,!0,!0,!0,!1,!1,!0,!1]},{name:"Ionian (major)",realName:"ionian",flags:[!0,!1,!0,!1,!0,!0,!1,!0,!1,!0,!1,!0]},{name:"Aeolian (minor)",realName:"aeolian",flags:[!0,!1,!0,!0,!1,!0,!1,!0,!0,!1,!0,!1]},{name:"Double Harmonic Major",realName:"double harmonic major",flags:[!0,!0,!1,!1,!0,!0,!1,!0,!0,!1,!1,!0]},{name:"Double Harmonic Minor",realName:"double harmonic minor",flags:[!0,!1,!0,!0,!1,!1,!0,!0,!0,!1,!1,!0]},{name:"Whole Tone",realName:"whole tone",flags:[!0,!1,!0,!1,!0,!1,!0,!1,!0,!1,!0,!1]}]),e.keys=a([{name:"C",isWhiteKey:!0,basePitch:12},{name:"C♯",isWhiteKey:!1,basePitch:13},{name:"D",isWhiteKey:!0,basePitch:14},{name:"D♯",isWhiteKey:!1,basePitch:15},{name:"E",isWhiteKey:!0,basePitch:16},{name:"F",isWhiteKey:!0,basePitch:17},{name:"F♯",isWhiteKey:!1,basePitch:18},{name:"G",isWhiteKey:!0,basePitch:19},{name:"G♯",isWhiteKey:!1,basePitch:20},{name:"A",isWhiteKey:!0,basePitch:21},{name:"A♯",isWhiteKey:!1,basePitch:22},{name:"B",isWhiteKey:!0,basePitch:23}]),e.blackKeyNameParents=[-1,1,-1,1,-1,1,-1,-1,1,-1,1,-1],e.tempoMin=30,e.tempoMax=300,e.echoDelayRange=24,e.echoDelayStepTicks=4,e.echoSustainRange=8,e.echoShelfHz=4e3,e.echoShelfGain=Math.pow(2,-.5),e.reverbShelfHz=8e3,e.reverbShelfGain=Math.pow(2,-1.5),e.reverbRange=4,e.reverbDelayBufferSize=16384,e.reverbDelayBufferMask=e.reverbDelayBufferSize-1,e.beatsPerBarMin=3,e.beatsPerBarMax=16,e.barCountMin=1,e.barCountMax=128,e.instrumentCountMin=1,e.layeredInstrumentCountMax=4,e.patternInstrumentCountMax=10,e.partsPerBeat=24,e.ticksPerPart=2,e.rhythms=a([{name:"÷3 (triplets)",stepsPerBeat:3,ticksPerArpeggio:4,arpeggioPatterns:[[0],[0,0,1,1],[0,1,2,1]],roundUpThresholds:[5,12,18]},{name:"÷4 (standard)",stepsPerBeat:4,ticksPerArpeggio:3,arpeggioPatterns:[[0],[0,0,1,1],[0,1,2,1]],roundUpThresholds:[3,9,17,21]},{name:"÷6",stepsPerBeat:6,ticksPerArpeggio:4,arpeggioPatterns:[[0],[0,1],[0,1,2,1]],roundUpThresholds:null},{name:"÷8",stepsPerBeat:8,ticksPerArpeggio:3,arpeggioPatterns:[[0],[0,1],[0,1,2,1]],roundUpThresholds:null},{name:"freehand",stepsPerBeat:24,ticksPerArpeggio:3,arpeggioPatterns:[[0],[0,1],[0,1,2,1]],roundUpThresholds:null}]),e.instrumentTypeNames=["chip","FM","noise","spectrum","drumset","harmonics","PWM","Picked String","supersaw"],e.instrumentTypeHasSpecialInterval=[!0,!0,!1,!1,!1,!0,!1,!1,!1],e.chipBaseExpression=.03375,e.fmBaseExpression=.03,e.noiseBaseExpression=.19,e.spectrumBaseExpression=.3,e.drumsetBaseExpression=.45,e.harmonicsBaseExpression=.025,e.pwmBaseExpression=.04725,e.supersawBaseExpression=.061425,e.pickedStringBaseExpression=.025,e.distortionBaseVolume=.011,e.bitcrusherBaseVolume=.01,e.chipWaves=a([{name:"rounded",expression:.94,samples:i([0,.2,.4,.5,.6,.7,.8,.85,.9,.95,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,.95,.9,.85,.8,.7,.6,.5,.4,.2,0,-.2,-.4,-.5,-.6,-.7,-.8,-.85,-.9,-.95,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-.95,-.9,-.85,-.8,-.7,-.6,-.5,-.4,-.2])},{name:"triangle",expression:1,samples:i([1/15,.2,5/15,7/15,.6,11/15,13/15,1,1,13/15,11/15,.6,7/15,5/15,.2,1/15,-1/15,-.2,-5/15,-7/15,-.6,-11/15,-13/15,-1,-1,-13/15,-11/15,-.6,-7/15,-5/15,-.2,-1/15])},{name:"square",expression:.5,samples:i([1,-1])},{name:"1/4 pulse",expression:.5,samples:i([1,-1,-1,-1])},{name:"1/8 pulse",expression:.5,samples:i([1,-1,-1,-1,-1,-1,-1,-1])},{name:"sawtooth",expression:.65,samples:i([1/31,3/31,5/31,7/31,9/31,11/31,13/31,15/31,17/31,19/31,21/31,23/31,25/31,27/31,29/31,1,-1,-29/31,-27/31,-25/31,-23/31,-21/31,-19/31,-17/31,-15/31,-13/31,-11/31,-9/31,-7/31,-5/31,-3/31,-1/31])},{name:"double saw",expression:.5,samples:i([0,-.2,-.4,-.6,-.8,-1,1,-.8,-.6,-.4,-.2,1,.8,.6,.4,.2])},{name:"double pulse",expression:.4,samples:i([1,1,1,1,1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1])},{name:"spiky",expression:.4,samples:i([1,-1,1,-1,1,0])}]),e.chipNoises=a([{name:"retro",expression:.25,basePitch:69,pitchFilterMult:1024,isSoft:!1,samples:null},{name:"white",expression:1,basePitch:69,pitchFilterMult:8,isSoft:!0,samples:null},{name:"clang",expression:.4,basePitch:69,pitchFilterMult:1024,isSoft:!1,samples:null},{name:"buzz",expression:.3,basePitch:69,pitchFilterMult:1024,isSoft:!1,samples:null},{name:"hollow",expression:1.5,basePitch:96,pitchFilterMult:1,isSoft:!0,samples:null}]),e.filterFreqStep=1/4,e.filterFreqRange=34,e.filterFreqReferenceSetting=28,e.filterFreqReferenceHz=8e3,e.filterFreqMaxHz=e.filterFreqReferenceHz*Math.pow(2,e.filterFreqStep*(e.filterFreqRange-1-e.filterFreqReferenceSetting)),e.filterFreqMinHz=8,e.filterGainRange=15,e.filterGainCenter=7,e.filterGainStep=.5,e.filterMaxPoints=8,e.filterTypeNames=["low-pass","high-pass","peak"],e.fadeInRange=10,e.fadeOutTicks=[-24,-12,-6,-3,-1,6,12,24,48,72,96],e.fadeOutNeutral=4,e.drumsetFadeOutTicks=48,e.transitions=a([{name:"normal",isSeamless:!1,continues:!1,slides:!1,slideTicks:3,includeAdjacentPatterns:!1},{name:"interrupt",isSeamless:!0,continues:!1,slides:!1,slideTicks:3,includeAdjacentPatterns:!0},{name:"continue",isSeamless:!0,continues:!0,slides:!1,slideTicks:3,includeAdjacentPatterns:!0},{name:"slide",isSeamless:!0,continues:!1,slides:!0,slideTicks:3,includeAdjacentPatterns:!0},{name:"slide in pattern",isSeamless:!0,continues:!1,slides:!0,slideTicks:3,includeAdjacentPatterns:!1}]),e.vibratos=a([{name:"none",amplitude:0,periodsSeconds:[.14],delayTicks:0},{name:"light",amplitude:.15,periodsSeconds:[.14],delayTicks:0},{name:"delayed",amplitude:.3,periodsSeconds:[.14],delayTicks:37},{name:"heavy",amplitude:.45,periodsSeconds:[.14],delayTicks:0},{name:"shaky",amplitude:.1,periodsSeconds:[.11,.17798,.33],delayTicks:0}]),e.unisons=a([{name:"none",voices:1,spread:0,offset:0,expression:1.4,sign:1},{name:"shimmer",voices:2,spread:.018,offset:0,expression:.8,sign:1},{name:"hum",voices:2,spread:.045,offset:0,expression:1,sign:1},{name:"honky tonk",voices:2,spread:.09,offset:0,expression:1,sign:1},{name:"dissonant",voices:2,spread:.25,offset:0,expression:.9,sign:1},{name:"fifth",voices:2,spread:3.5,offset:3.5,expression:.9,sign:1},{name:"octave",voices:2,spread:6,offset:6,expression:.8,sign:1},{name:"bowed",voices:2,spread:.02,offset:0,expression:1,sign:-1},{name:"piano",voices:2,spread:.01,offset:0,expression:1,sign:.7}]),e.effectNames=["reverb","chorus","panning","distortion","bitcrusher","note filter","echo","pitch shift","detune","vibrato","transition type","chord type"],e.effectOrder=[10,11,7,8,9,5,3,4,2,1,6,0],e.noteSizeMax=3,e.volumeRange=8,e.volumeLogScale=-.5,e.panCenter=4,e.panMax=2*e.panCenter,e.panDelaySecondsMax=5e-4,e.chorusRange=4,e.chorusPeriodSeconds=2,e.chorusDelayRange=.0034,e.chorusDelayOffsets=[[1.51,2.1,3.35],[1.47,2.15,3.25]],e.chorusPhaseOffsets=[[0,2.1,4.2],[3.2,5.3,1]],e.chorusMaxDelay=e.chorusDelayRange*(1+e.chorusDelayOffsets[0].concat(e.chorusDelayOffsets[1]).reduce(((t,e)=>Math.max(t,e)))),e.chords=a([{name:"simultaneous",customInterval:!1,arpeggiates:!1,strumParts:0,singleTone:!1},{name:"strum",customInterval:!1,arpeggiates:!1,strumParts:1,singleTone:!1},{name:"arpeggio",customInterval:!1,arpeggiates:!0,strumParts:0,singleTone:!0},{name:"custom interval",customInterval:!0,arpeggiates:!1,strumParts:0,singleTone:!0}]),e.maxChordSize=4,e.operatorCount=4,e.maxPitchOrOperatorCount=Math.max(e.maxChordSize,e.operatorCount),e.algorithms=a([{name:"1←(2 3 4)",carrierCount:1,associatedCarrier:[1,1,1,1],modulatedBy:[[2,3,4],[],[],[]]},{name:"1←(2 3←4)",carrierCount:1,associatedCarrier:[1,1,1,1],modulatedBy:[[2,3],[],[4],[]]},{name:"1←2←(3 4)",carrierCount:1,associatedCarrier:[1,1,1,1],modulatedBy:[[2],[3,4],[],[]]},{name:"1←(2 3)←4",carrierCount:1,associatedCarrier:[1,1,1,1],modulatedBy:[[2,3],[4],[4],[]]},{name:"1←2←3←4",carrierCount:1,associatedCarrier:[1,1,1,1],modulatedBy:[[2],[3],[4],[]]},{name:"1←3 2←4",carrierCount:2,associatedCarrier:[1,2,1,2],modulatedBy:[[3],[4],[],[]]},{name:"1 2←(3 4)",carrierCount:2,associatedCarrier:[1,2,2,2],modulatedBy:[[],[3,4],[],[]]},{name:"1 2←3←4",carrierCount:2,associatedCarrier:[1,2,2,2],modulatedBy:[[],[3],[4],[]]},{name:"(1 2)←3←4",carrierCount:2,associatedCarrier:[1,2,2,2],modulatedBy:[[3],[3],[4],[]]},{name:"(1 2)←(3 4)",carrierCount:2,associatedCarrier:[1,2,2,2],modulatedBy:[[3,4],[3,4],[],[]]},{name:"1 2 3←4",carrierCount:3,associatedCarrier:[1,2,3,3],modulatedBy:[[],[],[4],[]]},{name:"(1 2 3)←4",carrierCount:3,associatedCarrier:[1,2,3,3],modulatedBy:[[4],[4],[4],[]]},{name:"1 2 3 4",carrierCount:4,associatedCarrier:[1,2,3,4],modulatedBy:[[],[],[],[]]}]),e.operatorCarrierInterval=[0,.04,-.073,.091],e.operatorAmplitudeMax=15,e.operatorFrequencies=a([{name:"1×",mult:1,hzOffset:0,amplitudeSign:1},{name:"~1×",mult:1,hzOffset:1.5,amplitudeSign:-1},{name:"2×",mult:2,hzOffset:0,amplitudeSign:1},{name:"~2×",mult:2,hzOffset:-1.3,amplitudeSign:-1},{name:"3×",mult:3,hzOffset:0,amplitudeSign:1},{name:"4×",mult:4,hzOffset:0,amplitudeSign:1},{name:"5×",mult:5,hzOffset:0,amplitudeSign:1},{name:"6×",mult:6,hzOffset:0,amplitudeSign:1},{name:"7×",mult:7,hzOffset:0,amplitudeSign:1},{name:"8×",mult:8,hzOffset:0,amplitudeSign:1},{name:"9×",mult:9,hzOffset:0,amplitudeSign:1},{name:"11×",mult:11,hzOffset:0,amplitudeSign:1},{name:"13×",mult:13,hzOffset:0,amplitudeSign:1},{name:"16×",mult:16,hzOffset:0,amplitudeSign:1},{name:"20×",mult:20,hzOffset:0,amplitudeSign:1}]),e.envelopes=a([{name:"none",type:1,speed:0},{name:"note size",type:0,speed:0},{name:"punch",type:2,speed:0},{name:"flare 1",type:3,speed:32},{name:"flare 2",type:3,speed:8},{name:"flare 3",type:3,speed:2},{name:"twang 1",type:4,speed:32},{name:"twang 2",type:4,speed:8},{name:"twang 3",type:4,speed:2},{name:"swell 1",type:5,speed:32},{name:"swell 2",type:5,speed:8},{name:"swell 3",type:5,speed:2},{name:"tremolo1",type:6,speed:4},{name:"tremolo2",type:6,speed:2},{name:"tremolo3",type:6,speed:1},{name:"tremolo4",type:7,speed:4},{name:"tremolo5",type:7,speed:2},{name:"tremolo6",type:7,speed:1},{name:"decay 1",type:8,speed:10},{name:"decay 2",type:8,speed:7},{name:"decay 3",type:8,speed:4}]),e.feedbacks=a([{name:"1⟲",indices:[[1],[],[],[]]},{name:"2⟲",indices:[[],[2],[],[]]},{name:"3⟲",indices:[[],[],[3],[]]},{name:"4⟲",indices:[[],[],[],[4]]},{name:"1⟲ 2⟲",indices:[[1],[2],[],[]]},{name:"3⟲ 4⟲",indices:[[],[],[3],[4]]},{name:"1⟲ 2⟲ 3⟲",indices:[[1],[2],[3],[]]},{name:"2⟲ 3⟲ 4⟲",indices:[[],[2],[3],[4]]},{name:"1⟲ 2⟲ 3⟲ 4⟲",indices:[[1],[2],[3],[4]]},{name:"1→2",indices:[[],[1],[],[]]},{name:"1→3",indices:[[],[],[1],[]]},{name:"1→4",indices:[[],[],[],[1]]},{name:"2→3",indices:[[],[],[2],[]]},{name:"2→4",indices:[[],[],[],[2]]},{name:"3→4",indices:[[],[],[],[3]]},{name:"1→3 2→4",indices:[[],[],[1],[2]]},{name:"1→4 2→3",indices:[[],[],[2],[1]]},{name:"1→2→3→4",indices:[[],[1],[2],[3]]}]),e.chipNoiseLength=32768,e.spectrumNoiseLength=32768,e.spectrumBasePitch=24,e.spectrumControlPoints=30,e.spectrumControlPointsPerOctave=7,e.spectrumControlPointBits=3,e.spectrumMax=(1<<e.spectrumControlPointBits)-1,e.harmonicsControlPoints=28,e.harmonicsRendered=64,e.harmonicsRenderedForPickedString=256,e.harmonicsControlPointBits=3,e.harmonicsMax=(1<<e.harmonicsControlPointBits)-1,e.harmonicsWavelength=2048,e.pulseWidthRange=8,e.pulseWidthStepPower=.5,e.supersawVoiceCount=7,e.supersawDynamismMax=6,e.supersawSpreadMax=12,e.supersawShapeMax=6,e.pitchChannelCountMin=1,e.pitchChannelCountMax=10,e.noiseChannelCountMin=0,e.noiseChannelCountMax=5,e.noiseInterval=6,e.pitchesPerOctave=12,e.drumCount=12,e.pitchOctaves=7,e.maxPitch=e.pitchOctaves*e.pitchesPerOctave,e.maximumTonesPerChannel=2*e.maxChordSize,e.justIntonationSemitones=[.5,8/15,9/16,.6,5/8,2/3,32/45,3/4,.8,5/6,8/9,15/16,1,16/15,9/8,1.2,5/4,4/3,45/32,1.5,1.6,5/3,16/9,15/8,2].map((t=>Math.log2(t)*e.pitchesPerOctave)),e.pitchShiftRange=e.justIntonationSemitones.length,e.pitchShiftCenter=e.pitchShiftRange>>1,e.detuneCenter=9,e.detuneMax=2*e.detuneCenter,e.sineWaveLength=256,e.sineWaveMask=e.sineWaveLength-1,e.sineWave=function(){const t=new Float32Array(e.sineWaveLength+1);for(let i=0;i<e.sineWaveLength+1;i++)t[i]=Math.sin(i*Math.PI*2/e.sineWaveLength);return t}(),e.pickedStringDispersionCenterFreq=6e3,e.pickedStringDispersionFreqScale=.3,e.pickedStringDispersionFreqMult=4,e.pickedStringShelfHz=4e3,e.stringSustainRange=15,e.stringDecayRate=.12,e.enableAcousticSustain=!1,e.sustainTypeNames=["bright","acoustic"],e.distortionRange=8,e.bitcrusherFreqRange=14,e.bitcrusherOctaveStep=.5,e.bitcrusherQuantizationRange=8,e.maxEnvelopeCount=12,e.defaultAutomationRange=13,e.instrumentAutomationTargets=a([{name:"none",computeIndex:null,displayName:"none",interleave:!1,isFilter:!1,maxCount:1,effect:null,compatibleInstruments:null},{name:"noteVolume",computeIndex:0,displayName:"note volume",interleave:!1,isFilter:!1,maxCount:1,effect:null,compatibleInstruments:null},{name:"pulseWidth",computeIndex:2,displayName:"pulse width",interleave:!1,isFilter:!1,maxCount:1,effect:null,compatibleInstruments:[6,8]},{name:"stringSustain",computeIndex:3,displayName:"sustain",interleave:!1,isFilter:!1,maxCount:1,effect:null,compatibleInstruments:[7]},{name:"unison",computeIndex:4,displayName:"unison",interleave:!1,isFilter:!1,maxCount:1,effect:null,compatibleInstruments:[0,5,7]},{name:"operatorFrequency",computeIndex:5,displayName:"fm# freq",interleave:!0,isFilter:!1,maxCount:e.operatorCount,effect:null,compatibleInstruments:[1]},{name:"operatorAmplitude",computeIndex:9,displayName:"fm# volume",interleave:!1,isFilter:!1,maxCount:e.operatorCount,effect:null,compatibleInstruments:[1]},{name:"feedbackAmplitude",computeIndex:13,displayName:"fm feedback",interleave:!1,isFilter:!1,maxCount:1,effect:null,compatibleInstruments:[1]},{name:"pitchShift",computeIndex:14,displayName:"pitch shift",interleave:!1,isFilter:!1,maxCount:1,effect:7,compatibleInstruments:null},{name:"detune",computeIndex:15,displayName:"detune",interleave:!1,isFilter:!1,maxCount:1,effect:8,compatibleInstruments:null},{name:"vibratoDepth",computeIndex:16,displayName:"vibrato range",interleave:!1,isFilter:!1,maxCount:1,effect:9,compatibleInstruments:null},{name:"noteFilterAllFreqs",computeIndex:1,displayName:"n. filter freqs",interleave:!1,isFilter:!0,maxCount:1,effect:5,compatibleInstruments:null},{name:"noteFilterFreq",computeIndex:17,displayName:"n. filter # freq",interleave:!1,isFilter:!0,maxCount:e.filterMaxPoints,effect:5,compatibleInstruments:null},{name:"noteFilterGain",computeIndex:null,displayName:"n. filter # vol",interleave:!1,isFilter:!0,maxCount:e.filterMaxPoints,effect:5,compatibleInstruments:null},{name:"supersawDynamism",computeIndex:33,displayName:"dynamism",interleave:!1,isFilter:!1,maxCount:1,effect:null,compatibleInstruments:[8]},{name:"supersawSpread",computeIndex:34,displayName:"spread",interleave:!1,isFilter:!1,maxCount:1,effect:null,compatibleInstruments:[8]},{name:"supersawShape",computeIndex:35,displayName:"saw↔pulse",interleave:!1,isFilter:!1,maxCount:1,effect:null,compatibleInstruments:[8]}]);const k=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|android|ipad|playbook|silk/i.test(navigator.userAgent);function M(t){return t.toFixed(2).replace(/\.?0*$/,"")}class x{static valueToPreset(t){const e=t>>6,i=63&t;return x.presetCategories[e].presets[i]}static midiProgramToPresetValue(t){for(let e=0;e<x.presetCategories.length;e++){const i=x.presetCategories[e];for(let s=0;s<i.presets.length;s++){const n=i.presets[s];if(n.generalMidi&&n.midiProgram==t)return(e<<6)+s}}return null}static nameToPresetValue(t){for(let e=0;e<x.presetCategories.length;e++){const i=x.presetCategories[e];for(let s=0;s<i.presets.length;s++){if(i.presets[s].name==t)return(e<<6)+s}}return null}}x.version="4.2",x.versionDisplayName="BeepBox",x.releaseNotesURL="https://github.com/johnnesky/beepbox/releases/tag/v"+x.version,x.isOnMac=/^Mac/i.test(navigator.platform)||/Mac OS X/i.test(navigator.userAgent)||/^(iPhone|iPad|iPod)/i.test(navigator.platform)||/(iPhone|iPad|iPod)/i.test(navigator.userAgent),x.ctrlSymbol=x.isOnMac?"⌘":"Ctrl+",x.ctrlName=x.isOnMac?"command":"control",x.presetCategories=a([{name:"Custom Instruments",presets:a([{name:"chip wave",customType:0},{name:"FM (expert)",customType:1},{name:"basic noise",customType:2},{name:"spectrum",customType:3},{name:"drumset",customType:4},{name:"harmonics",customType:5},{name:"pulse width",customType:6},{name:"picked string",customType:7},{name:"supersaw",customType:8}])},{name:"Retro Presets",presets:a([{name:"square wave",midiProgram:80,settings:{type:"chip",eqFilter:[],effects:[],transition:"interrupt",fadeInSeconds:0,fadeOutTicks:-1,chord:"arpeggio",wave:"square",unison:"none",envelopes:[]}},{name:"triangle wave",midiProgram:71,settings:{type:"chip",eqFilter:[],effects:[],transition:"interrupt",fadeInSeconds:0,fadeOutTicks:-1,chord:"arpeggio",wave:"triangle",unison:"none",envelopes:[]}},{name:"square lead",midiProgram:80,generalMidi:!0,settings:{type:"chip",eqFilter:[{type:"low-pass",cutoffHz:8e3,linearGain:.3536}],effects:[],transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"simultaneous",wave:"square",unison:"hum",envelopes:[]}},{name:"sawtooth lead 1",midiProgram:81,generalMidi:!0,settings:{type:"chip",eqFilter:[{type:"low-pass",cutoffHz:4e3,linearGain:.5}],effects:[],transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"simultaneous",wave:"sawtooth",unison:"shimmer",envelopes:[]}},{name:"sawtooth lead 2",midiProgram:81,settings:{type:"chip",eqFilter:[{type:"low-pass",cutoffHz:6727.17,linearGain:1}],effects:["vibrato"],vibrato:"light",transition:"normal",fadeInSeconds:.0125,fadeOutTicks:72,chord:"simultaneous",wave:"sawtooth",unison:"hum",envelopes:[]}},{name:"chip noise",midiProgram:116,isNoise:!0,settings:{type:"noise",transition:"hard",effects:"none",chord:"arpeggio",filterCutoffHz:4e3,filterResonance:0,filterEnvelope:"steady",wave:"retro"}},{name:"FM twang",midiProgram:32,settings:{type:"FM",eqFilter:[],effects:[],transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"simultaneous",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:0,operators:[{frequency:"1×",amplitude:15},{frequency:"1×",amplitude:15},{frequency:"1×",amplitude:0},{frequency:"1×",amplitude:0}],envelopes:[{target:"operatorAmplitude",envelope:"twang 2",index:1}]}},{name:"FM bass",midiProgram:36,settings:{type:"FM",eqFilter:[],effects:[],transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"custom interval",algorithm:"1←(2 3←4)",feedbackType:"1⟲",feedbackAmplitude:0,operators:[{frequency:"2×",amplitude:11},{frequency:"1×",amplitude:7},{frequency:"1×",amplitude:9},{frequency:"20×",amplitude:3}],envelopes:[{target:"operatorAmplitude",envelope:"twang 2",index:1},{target:"operatorAmplitude",envelope:"twang 3",index:2},{target:"operatorAmplitude",envelope:"twang 2",index:3}]}},{name:"FM flute",midiProgram:73,settings:{type:"FM",eqFilter:[],effects:[],transition:"normal",fadeInSeconds:.0263,fadeOutTicks:-3,chord:"simultaneous",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:0,operators:[{frequency:"1×",amplitude:15},{frequency:"1×",amplitude:6},{frequency:"1×",amplitude:0},{frequency:"1×",amplitude:0}],envelopes:[{target:"operatorAmplitude",envelope:"twang 2",index:1}]}},{name:"FM organ",midiProgram:16,settings:{type:"FM",eqFilter:[],effects:["vibrato"],vibrato:"delayed",transition:"normal",fadeInSeconds:.0263,fadeOutTicks:-3,chord:"custom interval",algorithm:"1←3 2←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:0,operators:[{frequency:"1×",amplitude:14},{frequency:"2×",amplitude:14},{frequency:"1×",amplitude:11},{frequency:"2×",amplitude:11}],envelopes:[]}},{name:"supersaw lead",midiProgram:81,settings:{type:"supersaw",eqFilter:[{type:"low-pass",cutoffHz:6727.17,linearGain:2}],effects:["reverb"],reverb:67,fadeInSeconds:0,fadeOutTicks:-6,pulseWidth:50,dynamism:100,spread:58,shape:0,envelopes:[]}}])},{name:"Keyboard Presets",presets:a([{name:"grand piano",midiProgram:0,generalMidi:!0,settings:{type:"Picked String",eqFilter:[{type:"high-pass",cutoffHz:148.65,linearGain:.7071},{type:"peak",cutoffHz:1681.79,linearGain:4},{type:"low-pass",cutoffHz:8e3,linearGain:.1768},{type:"peak",cutoffHz:3363.59,linearGain:4},{type:"peak",cutoffHz:2378.41,linearGain:.25}],effects:["note filter","reverb"],noteFilter:[{type:"low-pass",cutoffHz:4756.83,linearGain:.3536},{type:"high-pass",cutoffHz:125,linearGain:.0884}],reverb:67,fadeInSeconds:0,fadeOutTicks:48,harmonics:[100,100,86,86,86,71,71,71,0,71,71,71,71,57,57,71,57,14,57,57,57,57,57,57,57,57,29,57],unison:"piano",stringSustain:86,stringSustainType:"acoustic",envelopes:[{target:"noteFilterFreq",envelope:"note size",index:0},{target:"noteFilterFreq",envelope:"twang 1",index:1},{target:"noteFilterFreq",envelope:"twang 1",index:1}]}},{name:"bright piano",midiProgram:1,generalMidi:!0,settings:{type:"Picked String",eqFilter:[{type:"low-pass",cutoffHz:1681.79,linearGain:.7071},{type:"high-pass",cutoffHz:148.65,linearGain:.5},{type:"peak",cutoffHz:3363.59,linearGain:1.4142}],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:24,chord:"simultaneous",harmonics:[100,100,86,86,71,71,0,71,71,71,71,71,71,14,57,57,57,57,57,57,29,57,57,57,57,57,57,57],unison:"piano",stringSustain:86,envelopes:[]}},{name:"electric grand",midiProgram:2,generalMidi:!0,settings:{type:"chip",eqFilter:[],effects:["note filter"],noteFilter:[{type:"low-pass",cutoffHz:2378.41,linearGain:.5}],transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"simultaneous",wave:"1/8 pulse",unison:"shimmer",envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 3"}]}},{name:"honky-tonk piano",midiProgram:3,generalMidi:!0,settings:{type:"Picked String",eqFilter:[{type:"low-pass",cutoffHz:5656.85,linearGain:.3536}],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"simultaneous",harmonics:[100,100,86,71,86,71,43,71,43,43,57,57,57,29,57,57,57,57,57,57,43,57,57,57,43,43,43,43],unison:"honky tonk",stringSustain:71,envelopes:[]}},{name:"electric piano 1",midiProgram:4,generalMidi:!0,settings:{type:"harmonics",eqFilter:[],effects:["note filter"],noteFilter:[{type:"low-pass",cutoffHz:3363.59,linearGain:.5}],transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"simultaneous",harmonics:[86,100,100,71,71,57,57,43,43,43,29,29,29,14,14,14,0,0,0,0,0,57,0,0,0,0,0,0],unison:"none",envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 2"}]}},{name:"electric piano 2",midiProgram:5,generalMidi:!0,settings:{type:"FM",eqFilter:[],effects:["note filter"],noteFilter:[{type:"low-pass",cutoffHz:13454.34,linearGain:.25}],transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"simultaneous",algorithm:"1←3 2←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:0,operators:[{frequency:"1×",amplitude:12},{frequency:"1×",amplitude:6},{frequency:"1×",amplitude:9},{frequency:"16×",amplitude:6}],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 3"},{target:"operatorAmplitude",envelope:"twang 3",index:3}]}},{name:"harpsichord",midiProgram:6,generalMidi:!0,settings:{type:"Picked String",eqFilter:[{type:"high-pass",cutoffHz:250,linearGain:.3536},{type:"peak",cutoffHz:11313.71,linearGain:2.8284}],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:24,chord:"simultaneous",harmonics:[100,100,100,86,57,86,86,86,86,57,57,71,71,86,86,71,71,86,86,71,71,71,71,71,71,71,71,71],unison:"none",stringSustain:79,envelopes:[]}},{name:"clavinet",midiProgram:7,generalMidi:!0,settings:{type:"FM",eqFilter:[],effects:["note filter"],noteFilter:[{type:"low-pass",cutoffHz:19027.31,linearGain:.3536}],transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"simultaneous",algorithm:"1←(2 3 4)",feedbackType:"3⟲",feedbackAmplitude:6,operators:[{frequency:"3×",amplitude:15},{frequency:"~1×",amplitude:6},{frequency:"8×",amplitude:4},{frequency:"1×",amplitude:0}],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 2"},{target:"feedbackAmplitude",envelope:"twang 2"}]}},{name:"dulcimer",midiProgram:15,generalMidi:!0,settings:{type:"Picked String",eqFilter:[{type:"low-pass",cutoffHz:8e3,linearGain:.3536}],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"strum",harmonics:[100,100,100,86,100,86,57,100,100,86,100,86,100,86,100,71,57,71,71,100,86,71,86,86,100,86,86,86],unison:"piano",stringSustain:79,envelopes:[]}}])},{name:"Idiophone Presets",presets:a([{name:"celesta",midiProgram:8,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:5657,filterResonance:14,filterEnvelope:"twang 2",vibrato:"none",algorithm:"(1 2)←(3 4)",feedbackType:"1⟲ 2⟲",feedbackAmplitude:0,feedbackEnvelope:"steady",operators:[{frequency:"~1×",amplitude:11,envelope:"custom"},{frequency:"8×",amplitude:6,envelope:"custom"},{frequency:"20×",amplitude:3,envelope:"twang 1"},{frequency:"3×",amplitude:1,envelope:"twang 2"}]}},{name:"glockenspiel",midiProgram:9,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:5657,filterResonance:14,filterEnvelope:"twang 2",vibrato:"none",algorithm:"(1 2 3)←4",feedbackType:"1⟲ 2⟲ 3⟲",feedbackAmplitude:2,feedbackEnvelope:"decay 1",operators:[{frequency:"1×",amplitude:7,envelope:"custom"},{frequency:"5×",amplitude:11,envelope:"custom"},{frequency:"8×",amplitude:7,envelope:"custom"},{frequency:"20×",amplitude:2,envelope:"twang 1"}]}},{name:"music box 1",midiProgram:10,generalMidi:!0,settings:{type:"Picked String",eqFilter:[{type:"low-pass",cutoffHz:4756.83,linearGain:.5}],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"strum",harmonics:[100,0,0,100,0,0,0,0,0,0,100,0,0,0,0,0,0,0,0,86,0,0,0,0,0,0,71,0],unison:"none",stringSustain:64,envelopes:[]}},{name:"music box 2",midiProgram:10,settings:{type:"Picked String",eqFilter:[{type:"low-pass",cutoffHz:2828.43,linearGain:.7071}],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"strum",harmonics:[100,57,57,0,0,0,0,0,0,57,0,0,0,0,0,0,0,0,0,43,0,0,0,0,0,0,0,0],unison:"none",stringSustain:29,envelopes:[]}},{name:"vibraphone",midiProgram:11,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"harmony",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"custom",vibrato:"none",algorithm:"1 2 3 4",feedbackType:"1→2→3→4",feedbackAmplitude:3,feedbackEnvelope:"twang 1",operators:[{frequency:"1×",amplitude:13,envelope:"custom"},{frequency:"~1×",amplitude:13,envelope:"custom"},{frequency:"9×",amplitude:3,envelope:"twang 2"},{frequency:"4×",amplitude:9,envelope:"twang 2"}]}},{name:"marimba",midiProgram:12,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2e3,filterResonance:29,filterEnvelope:"decay 1",vibrato:"none",algorithm:"1 2←(3 4)",feedbackType:"1⟲",feedbackAmplitude:0,feedbackEnvelope:"steady",operators:[{frequency:"1×",amplitude:10,envelope:"custom"},{frequency:"4×",amplitude:6,envelope:"custom"},{frequency:"13×",amplitude:6,envelope:"twang 1"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"kalimba",midiProgram:108,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"decay 1",vibrato:"none",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:0,feedbackEnvelope:"steady",operators:[{frequency:"1×",amplitude:11,envelope:"custom"},{frequency:"5×",amplitude:3,envelope:"twang 2"},{frequency:"20×",amplitude:3,envelope:"twang 1"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"xylophone",midiProgram:13,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard",chord:"strum",filterCutoffHz:2e3,filterResonance:14,filterEnvelope:"twang 1",vibrato:"none",algorithm:"(1 2 3)←4",feedbackType:"1⟲ 2⟲ 3⟲",feedbackAmplitude:0,feedbackEnvelope:"steady",operators:[{frequency:"1×",amplitude:9,envelope:"custom"},{frequency:"6×",amplitude:9,envelope:"custom"},{frequency:"11×",amplitude:9,envelope:"custom"},{frequency:"20×",amplitude:6,envelope:"twang 1"}]}},{name:"tubular bell",midiProgram:14,generalMidi:!0,midiSubharmonicOctaves:1,settings:{type:"Picked String",eqFilter:[{type:"low-pass",cutoffHz:4e3,linearGain:.5},{type:"high-pass",cutoffHz:105.11,linearGain:.3536}],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:96,chord:"strum",harmonics:[43,71,0,100,0,100,0,86,0,0,86,0,14,71,14,14,57,14,14,43,14,14,43,14,14,43,14,14],unison:"shimmer",stringSustain:86,envelopes:[]}},{name:"bell synth",midiProgram:14,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2e3,filterResonance:29,filterEnvelope:"twang 3",vibrato:"none",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:0,feedbackEnvelope:"steady",operators:[{frequency:"~2×",amplitude:10,envelope:"custom"},{frequency:"7×",amplitude:6,envelope:"twang 3"},{frequency:"20×",amplitude:1,envelope:"twang 1"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"rain drop",midiProgram:96,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:4e3,filterResonance:14,filterEnvelope:"twang 1",vibrato:"none",algorithm:"(1 2)←(3 4)",feedbackType:"1⟲ 2⟲",feedbackAmplitude:0,feedbackEnvelope:"steady",operators:[{frequency:"1×",amplitude:12,envelope:"custom"},{frequency:"6×",amplitude:4,envelope:"custom"},{frequency:"20×",amplitude:3,envelope:"twang 1"},{frequency:"1×",amplitude:6,envelope:"tremolo1"}]}},{name:"crystal",midiProgram:98,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"harmony",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"twang 2",vibrato:"delayed",algorithm:"1 2 3 4",feedbackType:"1⟲ 2⟲ 3⟲ 4⟲",feedbackAmplitude:4,feedbackEnvelope:"twang 1",operators:[{frequency:"1×",amplitude:10,envelope:"custom"},{frequency:"3×",amplitude:7,envelope:"custom"},{frequency:"6×",amplitude:4,envelope:"custom"},{frequency:"13×",amplitude:4,envelope:"custom"}]}},{name:"tinkle bell",midiProgram:112,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard",chord:"strum",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"twang 2",vibrato:"none",algorithm:"1 2 3 4",feedbackType:"1→2→3→4",feedbackAmplitude:5,feedbackEnvelope:"twang 3",operators:[{frequency:"~2×",amplitude:7,envelope:"custom"},{frequency:"5×",amplitude:7,envelope:"custom"},{frequency:"7×",amplitude:7,envelope:"custom"},{frequency:"16×",amplitude:7,envelope:"custom"}]}},{name:"agogo",midiProgram:113,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:4e3,filterResonance:14,filterEnvelope:"decay 1",vibrato:"none",algorithm:"1 2 3 4",feedbackType:"1→4",feedbackAmplitude:15,feedbackEnvelope:"decay 1",operators:[{frequency:"2×",amplitude:9,envelope:"custom"},{frequency:"5×",amplitude:6,envelope:"custom"},{frequency:"8×",amplitude:9,envelope:"custom"},{frequency:"13×",amplitude:11,envelope:"custom"}]}}])},{name:"Guitar Presets",presets:a([{name:"nylon guitar",midiProgram:24,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:5657,filterResonance:14,filterEnvelope:"twang 1",vibrato:"none",algorithm:"1←2←3←4",feedbackType:"3⟲",feedbackAmplitude:6,feedbackEnvelope:"twang 1",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"1×",amplitude:6,envelope:"steady"},{frequency:"5×",amplitude:2,envelope:"steady"},{frequency:"7×",amplitude:4,envelope:"steady"}]}},{name:"steel guitar",midiProgram:25,generalMidi:!0,settings:{type:"Picked String",eqFilter:[],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"strum",harmonics:[100,100,86,71,71,71,86,86,71,57,43,43,43,57,57,57,57,57,43,43,43,43,43,43,43,43,43,43],unison:"none",stringSustain:71,envelopes:[]}},{name:"jazz guitar",midiProgram:26,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"hard",chord:"strum",filterCutoffHz:2e3,filterResonance:14,filterEnvelope:"twang 2",interval:"union",vibrato:"none",harmonics:[100,100,86,71,57,71,71,43,57,71,57,43,29,29,29,29,29,29,29,29,14,14,14,14,14,14,14,0]}},{name:"clean guitar",midiProgram:27,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"hard",chord:"strum",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"twang 2",interval:"union",vibrato:"none",harmonics:[86,100,100,100,86,57,86,100,100,100,71,57,43,71,86,71,57,57,71,71,71,71,57,57,57,57,57,43]}},{name:"muted guitar",midiProgram:28,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard",chord:"strum",filterCutoffHz:2e3,filterResonance:14,filterEnvelope:"twang 1",vibrato:"none",algorithm:"1←(2 3←4)",feedbackType:"1⟲",feedbackAmplitude:7,feedbackEnvelope:"twang 2",operators:[{frequency:"1×",amplitude:13,envelope:"custom"},{frequency:"1×",amplitude:4,envelope:"twang 3"},{frequency:"4×",amplitude:4,envelope:"twang 2"},{frequency:"16×",amplitude:4,envelope:"twang 1"}]}}])},{name:"Picked Bass Presets",presets:a([{name:"acoustic bass",midiProgram:32,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:4e3,filterResonance:14,filterEnvelope:"twang 1",interval:"union",vibrato:"none",harmonics:[100,86,71,71,71,71,57,57,57,57,43,43,43,43,43,29,29,29,29,29,29,14,14,14,14,14,14,14]}},{name:"fingered bass",midiProgram:33,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"twang 1",interval:"union",vibrato:"none",harmonics:[100,86,71,57,71,43,57,29,29,29,29,29,29,14,14,14,14,14,14,14,14,14,14,14,14,14,14,0]}},{name:"picked bass",midiProgram:34,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2828,filterResonance:0,filterEnvelope:"twang 1",vibrato:"none",algorithm:"1←(2 3←4)",feedbackType:"3⟲",feedbackAmplitude:4,feedbackEnvelope:"twang 1",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"1×",amplitude:5,envelope:"steady"},{frequency:"11×",amplitude:1,envelope:"twang 3"},{frequency:"1×",amplitude:9,envelope:"steady"}]}},{name:"fretless bass",midiProgram:35,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"hard",chord:"strum",filterCutoffHz:1e3,filterResonance:14,filterEnvelope:"flare 2",interval:"union",vibrato:"none",harmonics:[100,100,86,71,71,57,57,71,71,71,57,57,57,57,57,57,57,43,43,43,43,43,43,43,43,29,29,14]}},{name:"slap bass 1",midiProgram:36,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"hard",chord:"strum",filterCutoffHz:4e3,filterResonance:0,filterEnvelope:"twang 1",interval:"union",vibrato:"none",harmonics:[100,100,100,100,86,71,57,29,29,43,43,57,71,57,29,29,43,57,57,57,43,43,43,57,71,71,71,71]}},{name:"slap bass 2",midiProgram:37,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard",chord:"strum",filterCutoffHz:5657,filterResonance:0,filterEnvelope:"twang 1",vibrato:"none",algorithm:"1←2←3←4",feedbackType:"3⟲",feedbackAmplitude:4,feedbackEnvelope:"steady",operators:[{frequency:"3×",amplitude:13,envelope:"custom"},{frequency:"1×",amplitude:7,envelope:"steady"},{frequency:"13×",amplitude:3,envelope:"steady"},{frequency:"1×",amplitude:11,envelope:"steady"}]}},{name:"bass synth 1",midiProgram:38,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard",chord:"strum",filterCutoffHz:4e3,filterResonance:43,filterEnvelope:"twang 2",vibrato:"none",algorithm:"1←3 2←4",feedbackType:"3⟲ 4⟲",feedbackAmplitude:9,feedbackEnvelope:"twang 2",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"1×",amplitude:10,envelope:"custom"},{frequency:"1×",amplitude:14,envelope:"twang 1"},{frequency:"~1×",amplitude:13,envelope:"twang 2"}]}},{name:"bass synth 2",midiProgram:39,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:1e3,filterResonance:57,filterEnvelope:"punch",vibrato:"none",algorithm:"1←(2 3 4)",feedbackType:"1→2",feedbackAmplitude:4,feedbackEnvelope:"twang 3",operators:[{frequency:"1×",amplitude:9,envelope:"custom"},{frequency:"1×",amplitude:9,envelope:"steady"},{frequency:"3×",amplitude:0,envelope:"steady"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"bass & lead",midiProgram:87,generalMidi:!0,settings:{type:"chip",transition:"hard",effects:"reverb",chord:"harmony",filterCutoffHz:4e3,filterResonance:86,filterEnvelope:"twang 2",wave:"sawtooth",interval:"shimmer",vibrato:"none"}},{name:"dubstep yoi yoi",midiProgram:87,settings:{type:"chip",eqFilter:[{type:"low-pass",cutoffHz:6727.17,linearGain:.7071}],effects:["note filter","bitcrusher"],noteFilter:[{type:"low-pass",cutoffHz:594.6,linearGain:11.3137}],bitcrusherOctave:1.5,bitcrusherQuantization:0,transition:"slide",fadeInSeconds:.0263,fadeOutTicks:-3,chord:"arpeggio",wave:"sawtooth",unison:"none",envelopes:[{target:"noteFilterFreq",envelope:"flare 2",index:0}]}}])},{name:"Picked String Presets",presets:a([{name:"pizzicato strings",midiProgram:45,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"medium fade",chord:"harmony",filterCutoffHz:1e3,filterResonance:14,filterEnvelope:"twang 1",vibrato:"none",algorithm:"(1 2 3)←4",feedbackType:"1⟲ 2⟲ 3⟲ 4⟲",feedbackAmplitude:7,feedbackEnvelope:"punch",operators:[{frequency:"1×",amplitude:14,envelope:"custom"},{frequency:"3×",amplitude:11,envelope:"custom"},{frequency:"6×",amplitude:9,envelope:"custom"},{frequency:"~1×",amplitude:10,envelope:"steady"}]}},{name:"harp",midiProgram:46,generalMidi:!0,settings:{type:"FM",transition:"hard fade",effects:"reverb",chord:"strum",filterCutoffHz:2828,filterResonance:0,filterEnvelope:"twang 1",vibrato:"none",algorithm:"1←3 2←4",feedbackType:"3⟲",feedbackAmplitude:6,feedbackEnvelope:"twang 2",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"4×",amplitude:6,envelope:"custom"},{frequency:"~2×",amplitude:3,envelope:"steady"},{frequency:"1×",amplitude:6,envelope:"steady"}]}},{name:"sitar",midiProgram:104,generalMidi:!0,settings:{type:"FM",transition:"hard fade",effects:"reverb",chord:"strum",filterCutoffHz:8e3,filterResonance:57,filterEnvelope:"twang 2",vibrato:"none",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:0,feedbackEnvelope:"steady",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"1×",amplitude:14,envelope:"twang 3"},{frequency:"9×",amplitude:3,envelope:"twang 3"},{frequency:"16×",amplitude:9,envelope:"swell 3"}]}},{name:"banjo",midiProgram:105,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"twang 2",vibrato:"none",algorithm:"1←(2 3←4)",feedbackType:"2⟲",feedbackAmplitude:4,feedbackEnvelope:"steady",operators:[{frequency:"4×",amplitude:14,envelope:"custom"},{frequency:"1×",amplitude:10,envelope:"steady"},{frequency:"11×",amplitude:3,envelope:"twang 3"},{frequency:"1×",amplitude:11,envelope:"steady"}]}},{name:"ukulele",midiProgram:105,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2e3,filterResonance:0,filterEnvelope:"twang 1",vibrato:"none",algorithm:"1←(2 3←4)",feedbackType:"3⟲",feedbackAmplitude:5,feedbackEnvelope:"twang 1",operators:[{frequency:"2×",amplitude:14,envelope:"custom"},{frequency:"1×",amplitude:6,envelope:"steady"},{frequency:"9×",amplitude:4,envelope:"twang 2"},{frequency:"1×",amplitude:11,envelope:"steady"}]}},{name:"shamisen",midiProgram:106,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"harmony",filterCutoffHz:8e3,filterResonance:14,filterEnvelope:"twang 1",vibrato:"none",algorithm:"1←(2 3←4)",feedbackType:"3⟲",feedbackAmplitude:9,feedbackEnvelope:"twang 3",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"1×",amplitude:12,envelope:"steady"},{frequency:"16×",amplitude:4,envelope:"twang 3"},{frequency:"1×",amplitude:7,envelope:"steady"}]}},{name:"koto",midiProgram:107,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"hard fade",chord:"harmony",filterCutoffHz:4e3,filterResonance:14,filterEnvelope:"twang 2",vibrato:"none",algorithm:"1←3 2←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:5,feedbackEnvelope:"twang 2",operators:[{frequency:"~1×",amplitude:12,envelope:"custom"},{frequency:"6×",amplitude:10,envelope:"custom"},{frequency:"4×",amplitude:8,envelope:"twang 3"},{frequency:"~2×",amplitude:8,envelope:"twang 3"}]}}])},{name:"Distortion Presets",presets:a([{name:"overdrive guitar",midiProgram:29,generalMidi:!0,settings:{type:"Picked String",eqFilter:[{type:"low-pass",cutoffHz:4756.83,linearGain:.7071},{type:"high-pass",cutoffHz:210.22,linearGain:1},{type:"low-pass",cutoffHz:5656.85,linearGain:1},{type:"peak",cutoffHz:840.9,linearGain:.5}],effects:["note filter","distortion"],noteFilter:[{type:"high-pass",cutoffHz:297.3,linearGain:2},{type:"low-pass",cutoffHz:2378.41,linearGain:.7071}],distortion:71,transition:"normal",fadeInSeconds:0,fadeOutTicks:12,chord:"strum",harmonics:[86,100,100,86,86,86,86,71,71,71,71,71,71,71,71,71,71,57,57,57,57,57,57,57,57,57,57,57],unison:"none",stringSustain:71,envelopes:[{target:"noteFilterFreq",envelope:"note size",index:1}]}},{name:"distortion guitar",midiProgram:30,generalMidi:!0,settings:{type:"Picked String",eqFilter:[{type:"low-pass",cutoffHz:4756.83,linearGain:.7071},{type:"high-pass",cutoffHz:210.22,linearGain:1},{type:"low-pass",cutoffHz:5656.85,linearGain:1},{type:"peak",cutoffHz:594.6,linearGain:.3536},{type:"peak",cutoffHz:1e3,linearGain:.25}],effects:["note filter","distortion","reverb"],noteFilter:[{type:"high-pass",cutoffHz:353.55,linearGain:2},{type:"low-pass",cutoffHz:2e3,linearGain:1}],distortion:86,reverb:67,transition:"normal",fadeInSeconds:0,fadeOutTicks:12,chord:"strum",harmonics:[86,100,100,86,86,86,86,71,71,71,71,71,71,71,71,71,71,57,57,57,57,57,57,57,57,57,57,57],unison:"none",stringSustain:71,envelopes:[{target:"noteFilterFreq",envelope:"note size",index:1}]}},{name:"charango synth",midiProgram:84,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:11313.71,linearGain:1}],effects:[],transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"strum",algorithm:"1←(2 3←4)",feedbackType:"1→2→3→4",feedbackAmplitude:8,operators:[{frequency:"3×",amplitude:13},{frequency:"~1×",amplitude:5},{frequency:"4×",amplitude:6},{frequency:"3×",amplitude:7}],envelopes:[{target:"feedbackAmplitude",envelope:"twang 3"}]}},{name:"guitar harmonics",midiProgram:31,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:4e3,linearGain:2}],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"strum",algorithm:"1←(2 3)←4",feedbackType:"1⟲",feedbackAmplitude:2,operators:[{frequency:"4×",amplitude:12},{frequency:"16×",amplitude:5},{frequency:"1×",amplitude:2},{frequency:"~1×",amplitude:12}],envelopes:[{target:"operatorAmplitude",envelope:"swell 1",index:1},{target:"operatorAmplitude",envelope:"punch",index:2},{target:"operatorAmplitude",envelope:"twang 1",index:3}]}},{name:"PWM overdrive",midiProgram:29,settings:{type:"PWM",eqFilter:[{type:"low-pass",cutoffHz:5656.85,linearGain:1.4142}],effects:[],transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"strum",pulseWidth:17.67767,envelopes:[{target:"pulseWidth",envelope:"punch"}]}},{name:"PWM distortion",midiProgram:30,settings:{type:"PWM",eqFilter:[{type:"low-pass",cutoffHz:3363.59,linearGain:2}],effects:["vibrato"],vibrato:"delayed",transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"strum",pulseWidth:50,envelopes:[{target:"pulseWidth",envelope:"swell 1"}]}},{name:"FM overdrive",midiProgram:29,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:4756.83,linearGain:1}],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"strum",algorithm:"1←(2 3←4)",feedbackType:"1→2",feedbackAmplitude:2,operators:[{frequency:"~1×",amplitude:15},{frequency:"1×",amplitude:12},{frequency:"~2×",amplitude:6},{frequency:"1×",amplitude:12}],envelopes:[{target:"operatorAmplitude",envelope:"twang 1",index:2},{target:"operatorAmplitude",envelope:"swell 3",index:3},{target:"feedbackAmplitude",envelope:"punch"}]}},{name:"FM distortion",midiProgram:30,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:4e3,linearGain:2}],effects:["reverb"],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"strum",algorithm:"1←(2 3←4)",feedbackType:"1→2",feedbackAmplitude:4,operators:[{frequency:"~1×",amplitude:15},{frequency:"1×",amplitude:11},{frequency:"1×",amplitude:9},{frequency:"~2×",amplitude:4}],envelopes:[{target:"operatorAmplitude",envelope:"swell 1",index:2},{target:"operatorAmplitude",envelope:"swell 3",index:3}]}}])},{name:"Bellows Presets",presets:a([{name:"drawbar organ 1",midiProgram:16,generalMidi:!0,midiSubharmonicOctaves:1,settings:{type:"harmonics",effects:"reverb",transition:"hard",chord:"harmony",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"steady",interval:"union",vibrato:"none",harmonics:[86,86,0,86,0,0,0,86,0,0,0,0,0,0,0,86,0,0,0,0,0,0,0,0,0,0,0,0]}},{name:"drawbar organ 2",midiProgram:16,midiSubharmonicOctaves:1,settings:{type:"harmonics",effects:"reverb",transition:"hard",chord:"harmony",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"steady",interval:"union",vibrato:"none",harmonics:[86,29,71,86,71,14,0,100,0,0,0,86,0,0,0,71,0,0,0,57,0,0,0,29,0,0,0,0]}},{name:"percussive organ",midiProgram:17,generalMidi:!0,midiSubharmonicOctaves:1,settings:{type:"FM",transition:"hard",effects:"reverb",chord:"harmony",filterCutoffHz:2e3,filterResonance:14,filterEnvelope:"punch",vibrato:"light",algorithm:"1 2 3 4",feedbackType:"1→3 2→4",feedbackAmplitude:7,feedbackEnvelope:"decay 1",operators:[{frequency:"1×",amplitude:7,envelope:"custom"},{frequency:"2×",amplitude:7,envelope:"custom"},{frequency:"3×",amplitude:8,envelope:"custom"},{frequency:"4×",amplitude:8,envelope:"custom"}]}},{name:"rock organ",midiProgram:18,generalMidi:!0,midiSubharmonicOctaves:1,settings:{type:"FM",effects:"chorus & reverb",transition:"hard",chord:"harmony",filterCutoffHz:4e3,filterResonance:14,filterEnvelope:"punch",vibrato:"delayed",algorithm:"(1 2 3)←4",feedbackType:"1⟲ 2⟲ 3⟲",feedbackAmplitude:2,feedbackEnvelope:"flare 1",operators:[{frequency:"1×",amplitude:9,envelope:"custom"},{frequency:"4×",amplitude:9,envelope:"custom"},{frequency:"6×",amplitude:9,envelope:"custom"},{frequency:"2×",amplitude:5,envelope:"steady"}]}},{name:"pipe organ",midiProgram:19,generalMidi:!0,midiSubharmonicOctaves:1,settings:{type:"FM",transition:"cross fade",effects:"reverb",chord:"harmony",filterCutoffHz:5657,filterResonance:43,filterEnvelope:"steady",vibrato:"none",algorithm:"1 2 3 4",feedbackType:"1⟲ 2⟲ 3⟲ 4⟲",feedbackAmplitude:5,feedbackEnvelope:"steady",operators:[{frequency:"1×",amplitude:8,envelope:"custom"},{frequency:"2×",amplitude:9,envelope:"custom"},{frequency:"4×",amplitude:9,envelope:"custom"},{frequency:"8×",amplitude:8,envelope:"custom"}]}},{name:"reed organ",midiProgram:20,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2e3,filterResonance:29,filterEnvelope:"steady",interval:"union",vibrato:"none",harmonics:[71,86,100,86,71,100,57,71,71,71,43,43,43,71,43,71,57,57,57,57,57,57,57,29,43,29,29,14]}},{name:"accordion",midiProgram:21,generalMidi:!0,settings:{type:"chip",effects:"reverb",transition:"cross fade",chord:"harmony",filterCutoffHz:5657,filterResonance:0,filterEnvelope:"swell 1",wave:"double saw",interval:"honky tonk",vibrato:"none"}},{name:"bandoneon",midiProgram:23,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:4e3,filterResonance:29,filterEnvelope:"swell 1",interval:"hum",vibrato:"none",harmonics:[86,86,86,57,71,86,57,71,71,71,57,43,57,43,71,43,71,57,57,43,43,43,57,43,43,29,29,29]}},{name:"bagpipe",midiProgram:109,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"cross fade",chord:"harmony",filterCutoffHz:5657,filterResonance:43,filterEnvelope:"punch",interval:"hum",vibrato:"none",harmonics:[71,86,86,100,100,86,57,100,86,71,71,71,57,57,57,71,57,71,57,71,43,57,57,43,43,43,43,43]}}])},{name:"String Presets",presets:a([{name:"violin",midiProgram:40,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:4e3,linearGain:1.4142},{type:"high-pass",cutoffHz:105.11,linearGain:.3536}],effects:["vibrato","reverb"],vibrato:"delayed",reverb:67,transition:"normal",fadeInSeconds:.0413,fadeOutTicks:6,chord:"simultaneous",algorithm:"(1 2)←(3 4)",feedbackType:"1→2",feedbackAmplitude:5,operators:[{frequency:"4×",amplitude:9},{frequency:"3×",amplitude:9},{frequency:"2×",amplitude:7},{frequency:"7×",amplitude:5}],envelopes:[{target:"operatorAmplitude",envelope:"swell 1",index:3},{target:"feedbackAmplitude",envelope:"twang 3"}]}},{name:"viola",midiProgram:41,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"cross fade",chord:"harmony",filterCutoffHz:2e3,filterResonance:29,filterEnvelope:"steady",vibrato:"delayed",algorithm:"(1 2 3)←4",feedbackType:"1⟲ 2⟲ 3⟲",feedbackAmplitude:8,feedbackEnvelope:"swell 1",operators:[{frequency:"2×",amplitude:11,envelope:"custom"},{frequency:"7×",amplitude:7,envelope:"custom"},{frequency:"13×",amplitude:4,envelope:"custom"},{frequency:"1×",amplitude:5,envelope:"steady"}]}},{name:"cello",midiProgram:42,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:4e3,linearGain:.1768},{type:"high-pass",cutoffHz:297.3,linearGain:.7071},{type:"peak",cutoffHz:4756.83,linearGain:5.6569}],effects:["note filter","reverb"],noteFilter:[{type:"low-pass",cutoffHz:16e3,linearGain:.0884}],reverb:67,transition:"normal",fadeInSeconds:.0125,fadeOutTicks:12,chord:"simultaneous",algorithm:"(1 2)←3←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:3,operators:[{frequency:"16×",amplitude:5},{frequency:"~1×",amplitude:10},{frequency:"1×",amplitude:9},{frequency:"6×",amplitude:3}],envelopes:[{target:"noteFilterAllFreqs",envelope:"swell 1"},{target:"operatorAmplitude",envelope:"swell 1",index:3}]}},{name:"contrabass",midiProgram:43,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"cross fade",chord:"harmony",filterCutoffHz:2e3,filterResonance:29,filterEnvelope:"steady",vibrato:"delayed",algorithm:"(1 2)←3←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:0,feedbackEnvelope:"steady",operators:[{frequency:"16×",amplitude:5,envelope:"custom"},{frequency:"1×",amplitude:10,envelope:"custom"},{frequency:"1×",amplitude:10,envelope:"steady"},{frequency:"6×",amplitude:3,envelope:"swell 1"}]}},{name:"fiddle",midiProgram:110,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2828,filterResonance:29,filterEnvelope:"steady",vibrato:"delayed",algorithm:"(1 2)←(3 4)",feedbackType:"3⟲ 4⟲",feedbackAmplitude:5,feedbackEnvelope:"twang 1",operators:[{frequency:"2×",amplitude:10,envelope:"custom"},{frequency:"8×",amplitude:8,envelope:"custom"},{frequency:"1×",amplitude:8,envelope:"steady"},{frequency:"16×",amplitude:3,envelope:"steady"}]}},{name:"tremolo strings",midiProgram:44,generalMidi:!0,settings:{type:"FM",effects:"chorus & reverb",transition:"medium fade",chord:"harmony",filterCutoffHz:2e3,filterResonance:0,filterEnvelope:"tremolo4",vibrato:"none",algorithm:"1 2 3 4",feedbackType:"1→2→3→4",feedbackAmplitude:12,feedbackEnvelope:"steady",operators:[{frequency:"1×",amplitude:8,envelope:"custom"},{frequency:"~2×",amplitude:8,envelope:"custom"},{frequency:"4×",amplitude:8,envelope:"custom"},{frequency:"7×",amplitude:8,envelope:"custom"}]}},{name:"strings",midiProgram:48,generalMidi:!0,settings:{type:"FM",effects:"chorus & reverb",transition:"cross fade",chord:"harmony",filterCutoffHz:2828,filterResonance:43,filterEnvelope:"steady",vibrato:"none",algorithm:"(1 2)←(3 4)",feedbackType:"4⟲",feedbackAmplitude:5,feedbackEnvelope:"twang 3",operators:[{frequency:"4×",amplitude:9,envelope:"custom"},{frequency:"3×",amplitude:9,envelope:"custom"},{frequency:"2×",amplitude:7,envelope:"steady"},{frequency:"7×",amplitude:3,envelope:"swell 1"}]}},{name:"slow strings",midiProgram:49,generalMidi:!0,settings:{type:"FM",effects:"chorus & reverb",transition:"soft fade",chord:"harmony",filterCutoffHz:1414,filterResonance:0,filterEnvelope:"swell 2",vibrato:"none",algorithm:"(1 2)←(3 4)",feedbackType:"4⟲",feedbackAmplitude:6,feedbackEnvelope:"flare 3",operators:[{frequency:"4×",amplitude:10,envelope:"custom"},{frequency:"3×",amplitude:10,envelope:"custom"},{frequency:"2×",amplitude:7,envelope:"steady"},{frequency:"7×",amplitude:4,envelope:"swell 1"}]}},{name:"strings synth 1",midiProgram:50,generalMidi:!0,settings:{type:"chip",transition:"soft fade",effects:"chorus & reverb",chord:"harmony",filterCutoffHz:1414,filterResonance:43,filterEnvelope:"steady",wave:"sawtooth",interval:"hum",vibrato:"delayed"}},{name:"strings synth 2",midiProgram:51,generalMidi:!0,settings:{type:"FM",effects:"chorus & reverb",transition:"soft fade",chord:"harmony",filterCutoffHz:2e3,filterResonance:43,filterEnvelope:"steady",vibrato:"none",algorithm:"1 2 3 4",feedbackType:"1⟲ 2⟲ 3⟲ 4⟲",feedbackAmplitude:12,feedbackEnvelope:"swell 1",operators:[{frequency:"3×",amplitude:6,envelope:"custom"},{frequency:"2×",amplitude:7,envelope:"custom"},{frequency:"1×",amplitude:8,envelope:"custom"},{frequency:"1×",amplitude:9,envelope:"custom"}]}},{name:"orchestra hit 1",midiProgram:55,generalMidi:!0,midiSubharmonicOctaves:1,settings:{type:"FM",effects:"chorus & reverb",transition:"hard fade",chord:"harmony",filterCutoffHz:8e3,filterResonance:14,filterEnvelope:"custom",vibrato:"none",algorithm:"1 2 3 4",feedbackType:"1⟲ 2⟲ 3⟲ 4⟲",feedbackAmplitude:14,feedbackEnvelope:"twang 3",operators:[{frequency:"1×",amplitude:15,envelope:"twang 3"},{frequency:"2×",amplitude:15,envelope:"flare 3"},{frequency:"4×",amplitude:15,envelope:"flare 2"},{frequency:"8×",amplitude:15,envelope:"flare 1"}]}},{name:"orchestra hit 2",midiProgram:55,midiSubharmonicOctaves:1,settings:{type:"FM",effects:"chorus & reverb",transition:"medium fade",chord:"harmony",filterCutoffHz:8e3,filterResonance:0,filterEnvelope:"decay 1",vibrato:"delayed",algorithm:"1 2 3 4",feedbackType:"1⟲ 2⟲ 3⟲ 4⟲",feedbackAmplitude:14,feedbackEnvelope:"steady",operators:[{frequency:"1×",amplitude:12,envelope:"custom"},{frequency:"2×",amplitude:14,envelope:"custom"},{frequency:"3×",amplitude:12,envelope:"custom"},{frequency:"4×",amplitude:14,envelope:"custom"}]}},{name:"supersaw string",midiProgram:41,settings:{type:"supersaw",eqFilter:[{type:"low-pass",cutoffHz:2828.43,linearGain:1.4142},{type:"low-pass",cutoffHz:3363.59,linearGain:.1768}],effects:["note filter","reverb"],noteFilter:[{type:"high-pass",cutoffHz:500,linearGain:.1768}],reverb:33,fadeInSeconds:.0263,fadeOutTicks:6,pulseWidth:35.35534,dynamism:83,spread:8,shape:50,envelopes:[{target:"noteFilterFreq",envelope:"twang 1",index:0}]}}])},{name:"Vocal Presets",presets:a([{name:"choir soprano",midiProgram:94,generalMidi:!0,settings:{type:"harmonics",eqFilter:[{type:"low-pass",cutoffHz:2828.43,linearGain:2},{type:"peak",cutoffHz:1189.21,linearGain:5.6569},{type:"high-pass",cutoffHz:707.11,linearGain:2.8284},{type:"peak",cutoffHz:2e3,linearGain:.0884},{type:"peak",cutoffHz:840.9,linearGain:.25},{type:"low-pass",cutoffHz:6727.17,linearGain:11.3137}],effects:["vibrato","chorus","reverb"],vibrato:"shaky",chorus:100,reverb:33,fadeInSeconds:.0413,fadeOutTicks:24,harmonics:[100,100,86,57,29,29,57,71,57,29,14,14,14,29,43,57,43,29,14,14,14,14,14,14,0,0,0,0],unison:"none",envelopes:[]}},{name:"choir tenor",midiProgram:52,generalMidi:!0,settings:{type:"harmonics",eqFilter:[{type:"peak",cutoffHz:1e3,linearGain:11.3137},{type:"peak",cutoffHz:707.11,linearGain:5.6569},{type:"peak",cutoffHz:840.9,linearGain:.0884},{type:"peak",cutoffHz:1681.79,linearGain:.0884},{type:"high-pass",cutoffHz:297.3,linearGain:.7071},{type:"low-pass",cutoffHz:2828.43,linearGain:11.3137}],effects:["vibrato","chorus","reverb"],vibrato:"shaky",chorus:100,reverb:67,transition:"normal",fadeInSeconds:.0413,fadeOutTicks:48,chord:"simultaneous",harmonics:[86,100,100,86,71,57,43,29,29,29,29,43,43,43,29,29,29,29,29,29,29,29,29,14,14,14,14,14],unison:"none",envelopes:[]}},{name:"choir bass",midiProgram:52,settings:{type:"harmonics",eqFilter:[{type:"low-pass",cutoffHz:2378.41,linearGain:11.3137},{type:"peak",cutoffHz:594.6,linearGain:5.6569},{type:"peak",cutoffHz:1681.79,linearGain:.0884},{type:"peak",cutoffHz:707.11,linearGain:.0884},{type:"peak",cutoffHz:840.9,linearGain:11.3137}],effects:["vibrato","chorus","reverb"],vibrato:"shaky",chorus:100,reverb:67,transition:"normal",fadeInSeconds:.0413,fadeOutTicks:48,chord:"simultaneous",harmonics:[71,86,100,100,86,86,57,43,29,29,29,29,29,29,43,43,43,43,43,29,29,29,29,14,14,14,14,14],unison:"none",envelopes:[]}},{name:"solo soprano",midiProgram:85,settings:{type:"harmonics",eqFilter:[{type:"low-pass",cutoffHz:2828.43,linearGain:2},{type:"peak",cutoffHz:1189.21,linearGain:5.6569},{type:"high-pass",cutoffHz:707.11,linearGain:2.8284},{type:"peak",cutoffHz:2e3,linearGain:.0884},{type:"peak",cutoffHz:840.9,linearGain:.25}],effects:["vibrato","reverb"],vibrato:"shaky",reverb:33,fadeInSeconds:.0413,fadeOutTicks:12,harmonics:[86,100,86,43,14,14,57,71,57,14,14,14,14,14,43,57,43,14,14,14,14,14,14,14,0,0,0,0],unison:"none",envelopes:[]}},{name:"solo tenor",midiProgram:85,settings:{type:"harmonics",eqFilter:[{type:"peak",cutoffHz:1e3,linearGain:11.3137},{type:"peak",cutoffHz:707.11,linearGain:5.6569},{type:"peak",cutoffHz:840.9,linearGain:.0884},{type:"peak",cutoffHz:1681.79,linearGain:.0884},{type:"high-pass",cutoffHz:297.3,linearGain:.7071},{type:"low-pass",cutoffHz:2828.43,linearGain:11.3137}],effects:["vibrato","reverb"],vibrato:"shaky",reverb:33,fadeInSeconds:.0413,fadeOutTicks:12,harmonics:[86,100,100,86,71,57,43,29,29,29,29,43,43,43,29,29,29,29,29,29,29,29,29,14,14,14,14,14],unison:"none",envelopes:[]}},{name:"solo bass",midiProgram:85,settings:{type:"harmonics",eqFilter:[{type:"low-pass",cutoffHz:2378.41,linearGain:5.6569},{type:"peak",cutoffHz:594.6,linearGain:8},{type:"peak",cutoffHz:1681.79,linearGain:.0884},{type:"peak",cutoffHz:707.11,linearGain:.0884},{type:"peak",cutoffHz:840.9,linearGain:8},{type:"high-pass",cutoffHz:210.22,linearGain:1.4142}],effects:["vibrato","reverb"],vibrato:"shaky",reverb:33,transition:"normal",fadeInSeconds:.0263,fadeOutTicks:12,chord:"simultaneous",harmonics:[71,86,100,100,86,86,57,43,29,29,29,29,29,29,43,43,43,43,43,29,29,29,29,14,14,14,14,14],unison:"none",envelopes:[]}},{name:"voice ooh",midiProgram:53,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:1414,filterResonance:57,filterEnvelope:"steady",interval:"union",vibrato:"shaky",harmonics:[100,57,43,43,14,14,0,0,0,14,29,29,14,0,14,29,29,14,0,0,0,0,0,0,0,0,0,0]}},{name:"voice synth",midiProgram:54,generalMidi:!0,settings:{type:"chip",transition:"medium fade",effects:"chorus & reverb",chord:"harmony",filterCutoffHz:4e3,filterResonance:57,filterEnvelope:"steady",wave:"rounded",interval:"union",vibrato:"light"}},{name:"vox synth lead",midiProgram:85,generalMidi:!0,settings:{type:"FM",effects:"chorus & reverb",transition:"cross fade",chord:"harmony",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"steady",vibrato:"light",algorithm:"(1 2 3)←4",feedbackType:"1→2→3→4",feedbackAmplitude:2,feedbackEnvelope:"punch",operators:[{frequency:"2×",amplitude:10,envelope:"custom"},{frequency:"9×",amplitude:5,envelope:"custom"},{frequency:"20×",amplitude:1,envelope:"custom"},{frequency:"~1×",amplitude:4,envelope:"steady"}]}},{name:"tiny robot",midiProgram:85,settings:{type:"FM",eqFilter:[],effects:["vibrato","reverb"],vibrato:"delayed",reverb:33,transition:"slide",fadeInSeconds:.0263,fadeOutTicks:-3,chord:"simultaneous",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:2,operators:[{frequency:"2×",amplitude:15},{frequency:"1×",amplitude:7},{frequency:"~1×",amplitude:7},{frequency:"1×",amplitude:0}],envelopes:[{target:"operatorAmplitude",envelope:"punch",index:1},{target:"feedbackAmplitude",envelope:"twang 3"}]}},{name:"yowie",midiProgram:85,settings:{type:"FM",effects:"reverb",transition:"cross fade",chord:"harmony",filterCutoffHz:2e3,filterResonance:86,filterEnvelope:"tremolo5",vibrato:"none",algorithm:"1←2←(3 4)",feedbackType:"1⟲",feedbackAmplitude:12,feedbackEnvelope:"tremolo3",operators:[{frequency:"2×",amplitude:12,envelope:"custom"},{frequency:"16×",amplitude:5,envelope:"steady"},{frequency:"1×",amplitude:5,envelope:"steady"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"mouse",midiProgram:85,settings:{type:"FM",eqFilter:[],effects:["vibrato","reverb"],vibrato:"light",reverb:33,transition:"slide in pattern",fadeInSeconds:.0263,fadeOutTicks:-3,chord:"simultaneous",algorithm:"1 2 3 4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:5,operators:[{frequency:"2×",amplitude:13},{frequency:"5×",amplitude:12},{frequency:"1×",amplitude:0},{frequency:"1×",amplitude:0}],envelopes:[{target:"noteVolume",envelope:"note size"},{target:"feedbackAmplitude",envelope:"flare 2"}]}},{name:"gumdrop",midiProgram:85,settings:{type:"FM",effects:"reverb",transition:"hard",chord:"harmony",filterCutoffHz:8e3,filterResonance:0,filterEnvelope:"steady",vibrato:"none",algorithm:"(1 2 3)←4",feedbackType:"1⟲ 2⟲ 3⟲",feedbackAmplitude:0,feedbackEnvelope:"steady",operators:[{frequency:"2×",amplitude:15,envelope:"punch"},{frequency:"4×",amplitude:15,envelope:"punch"},{frequency:"7×",amplitude:15,envelope:"punch"},{frequency:"1×",amplitude:10,envelope:"twang 1"}]}},{name:"echo drop",midiProgram:102,generalMidi:!0,settings:{type:"FM",effects:"chorus & reverb",transition:"hard",chord:"harmony",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"punch",vibrato:"none",algorithm:"1←(2 3←4)",feedbackType:"1⟲",feedbackAmplitude:2,feedbackEnvelope:"steady",operators:[{frequency:"~2×",amplitude:11,envelope:"custom"},{frequency:"~1×",amplitude:5,envelope:"steady"},{frequency:"11×",amplitude:2,envelope:"steady"},{frequency:"16×",amplitude:5,envelope:"swell 3"}]}},{name:"dark choir",midiProgram:85,settings:{type:"spectrum",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:4e3,filterResonance:29,filterEnvelope:"swell 1",spectrum:[43,14,14,14,14,14,14,100,14,14,14,57,14,14,100,14,43,14,43,14,14,43,14,29,14,29,14,14,29,0]}}])},{name:"Brass Presets",presets:a([{name:"trumpet",midiProgram:56,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2828,filterResonance:43,filterEnvelope:"steady",vibrato:"none",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:9,feedbackEnvelope:"swell 1",operators:[{frequency:"1×",amplitude:14,envelope:"custom"},{frequency:"1×",amplitude:8,envelope:"steady"},{frequency:"1×",amplitude:5,envelope:"flare 2"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"trombone",midiProgram:57,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2e3,filterResonance:43,filterEnvelope:"steady",vibrato:"none",algorithm:"1←(2 3 4)",feedbackType:"2⟲",feedbackAmplitude:7,feedbackEnvelope:"swell 1",operators:[{frequency:"1×",amplitude:14,envelope:"custom"},{frequency:"1×",amplitude:8,envelope:"steady"},{frequency:"1×",amplitude:0,envelope:"steady"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"tuba",midiProgram:58,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2e3,filterResonance:43,filterEnvelope:"steady",vibrato:"none",algorithm:"1←(2 3 4)",feedbackType:"2⟲",feedbackAmplitude:8,feedbackEnvelope:"swell 1",operators:[{frequency:"1×",amplitude:14,envelope:"custom"},{frequency:"1×",amplitude:6,envelope:"steady"},{frequency:"1×",amplitude:0,envelope:"steady"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"muted trumpet",midiProgram:59,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:8e3,linearGain:2.8284},{type:"peak",cutoffHz:4e3,linearGain:2.8284}],effects:["note filter","reverb"],noteFilter:[{type:"low-pass",cutoffHz:3363.59,linearGain:1}],reverb:33,fadeInSeconds:.0263,fadeOutTicks:-3,algorithm:"1←(2 3←4)",feedbackType:"1⟲",feedbackAmplitude:5,operators:[{frequency:"1×",amplitude:13},{frequency:"1×",amplitude:5},{frequency:"9×",amplitude:5},{frequency:"13×",amplitude:7}],envelopes:[{target:"noteFilterAllFreqs",envelope:"swell 1"},{target:"operatorAmplitude",envelope:"swell 1",index:3},{target:"feedbackAmplitude",envelope:"flare 2"}]}},{name:"french horn",midiProgram:60,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:4e3,linearGain:1},{type:"peak",cutoffHz:2378.41,linearGain:2.8284}],effects:["reverb"],reverb:33,fadeInSeconds:.0263,fadeOutTicks:-3,algorithm:"1←3 2←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:3,operators:[{frequency:"1×",amplitude:15},{frequency:"1×",amplitude:12},{frequency:"1×",amplitude:10},{frequency:"~1×",amplitude:8}],envelopes:[{target:"operatorAmplitude",envelope:"swell 1",index:2},{target:"operatorAmplitude",envelope:"flare 2",index:3},{target:"feedbackAmplitude",envelope:"swell 1"}]}},{name:"brass section",midiProgram:61,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"punch",vibrato:"none",algorithm:"1←3 2←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:6,feedbackEnvelope:"swell 1",operators:[{frequency:"1×",amplitude:14,envelope:"custom"},{frequency:"1×",amplitude:12,envelope:"custom"},{frequency:"1×",amplitude:10,envelope:"swell 1"},{frequency:"~1×",amplitude:10,envelope:"swell 1"}]}},{name:"brass synth 1",midiProgram:62,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:4e3,filterResonance:29,filterEnvelope:"steady",vibrato:"none",algorithm:"1←3 2←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:11,feedbackEnvelope:"swell 1",operators:[{frequency:"1×",amplitude:14,envelope:"custom"},{frequency:"1×",amplitude:14,envelope:"custom"},{frequency:"1×",amplitude:12,envelope:"flare 1"},{frequency:"~1×",amplitude:8,envelope:"flare 2"}]}},{name:"brass synth 2",midiProgram:63,generalMidi:!0,settings:{type:"FM",transition:"soft",effects:"reverb",chord:"harmony",filterCutoffHz:4e3,filterResonance:43,filterEnvelope:"twang 3",vibrato:"none",algorithm:"1←3 2←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:9,feedbackEnvelope:"swell 1",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"1×",amplitude:10,envelope:"flare 1"},{frequency:"~1×",amplitude:7,envelope:"flare 1"}]}},{name:"pulse brass",midiProgram:62,settings:{type:"PWM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:4e3,filterResonance:29,filterEnvelope:"swell 1",pulseWidth:50,pulseEnvelope:"flare 3",vibrato:"none"}}])},{name:"Reed Presets",presets:a([{name:"soprano sax",midiProgram:64,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2e3,filterResonance:29,filterEnvelope:"steady",vibrato:"none",algorithm:"1←2←3←4",feedbackType:"4⟲",feedbackAmplitude:5,feedbackEnvelope:"swell 1",operators:[{frequency:"1×",amplitude:13,envelope:"custom"},{frequency:"4×",amplitude:4,envelope:"swell 1"},{frequency:"1×",amplitude:7,envelope:"steady"},{frequency:"5×",amplitude:4,envelope:"punch"}]}},{name:"alto sax",midiProgram:65,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2e3,filterResonance:43,filterEnvelope:"steady",vibrato:"none",algorithm:"1←(2 3←4)",feedbackType:"1⟲",feedbackAmplitude:4,feedbackEnvelope:"punch",operators:[{frequency:"1×",amplitude:13,envelope:"custom"},{frequency:"1×",amplitude:6,envelope:"steady"},{frequency:"4×",amplitude:6,envelope:"swell 1"},{frequency:"1×",amplitude:12,envelope:"steady"}]}},{name:"tenor sax",midiProgram:66,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2828,filterResonance:29,filterEnvelope:"steady",vibrato:"none",algorithm:"1←2←3←4",feedbackType:"1⟲",feedbackAmplitude:6,feedbackEnvelope:"swell 1",operators:[{frequency:"2×",amplitude:12,envelope:"custom"},{frequency:"3×",amplitude:7,envelope:"steady"},{frequency:"1×",amplitude:3,envelope:"steady"},{frequency:"8×",amplitude:3,envelope:"steady"}]}},{name:"baritone sax",midiProgram:67,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2828,filterResonance:0,filterEnvelope:"steady",vibrato:"none",algorithm:"1←(2 3←4)",feedbackType:"1⟲",feedbackAmplitude:2,feedbackEnvelope:"swell 2",operators:[{frequency:"1×",amplitude:12,envelope:"custom"},{frequency:"8×",amplitude:4,envelope:"steady"},{frequency:"4×",amplitude:5,envelope:"steady"},{frequency:"1×",amplitude:4,envelope:"punch"}]}},{name:"sax synth",midiProgram:64,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:8e3,filterResonance:0,filterEnvelope:"steady",vibrato:"light",algorithm:"1←(2 3 4)",feedbackType:"1⟲ 2⟲",feedbackAmplitude:4,feedbackEnvelope:"steady",operators:[{frequency:"4×",amplitude:15,envelope:"custom"},{frequency:"1×",amplitude:15,envelope:"steady"},{frequency:"1×",amplitude:0,envelope:"steady"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"shehnai",midiProgram:111,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:8e3,filterResonance:0,filterEnvelope:"steady",vibrato:"light",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:3,feedbackEnvelope:"steady",operators:[{frequency:"4×",amplitude:15,envelope:"custom"},{frequency:"1×",amplitude:8,envelope:"steady"},{frequency:"1×",amplitude:0,envelope:"steady"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"oboe",midiProgram:68,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"cross fade",chord:"harmony",filterCutoffHz:4e3,filterResonance:14,filterEnvelope:"swell 1",vibrato:"none",algorithm:"1 2←(3 4)",feedbackType:"2⟲",feedbackAmplitude:2,feedbackEnvelope:"tremolo5",operators:[{frequency:"1×",amplitude:7,envelope:"custom"},{frequency:"4×",amplitude:12,envelope:"custom"},{frequency:"1×",amplitude:6,envelope:"steady"},{frequency:"6×",amplitude:2,envelope:"steady"}]}},{name:"english horn",midiProgram:69,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"cross fade",chord:"harmony",filterCutoffHz:2e3,filterResonance:14,filterEnvelope:"steady",vibrato:"none",algorithm:"1 2←(3 4)",feedbackType:"2⟲",feedbackAmplitude:2,feedbackEnvelope:"steady",operators:[{frequency:"4×",amplitude:12,envelope:"custom"},{frequency:"2×",amplitude:10,envelope:"custom"},{frequency:"1×",amplitude:8,envelope:"punch"},{frequency:"8×",amplitude:4,envelope:"steady"}]}},{name:"bassoon",midiProgram:70,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:707,filterResonance:57,filterEnvelope:"steady",vibrato:"none",algorithm:"1←(2 3←4)",feedbackType:"1⟲",feedbackAmplitude:2,feedbackEnvelope:"steady",operators:[{frequency:"2×",amplitude:11,envelope:"custom"},{frequency:"1×",amplitude:6,envelope:"steady"},{frequency:"6×",amplitude:6,envelope:"swell 1"},{frequency:"1×",amplitude:0,envelope:"steady"}]}},{name:"clarinet",midiProgram:71,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:1414,filterResonance:14,filterEnvelope:"steady",interval:"union",vibrato:"none",harmonics:[100,43,86,57,86,71,86,71,71,71,71,71,71,43,71,71,57,57,57,57,57,57,43,43,43,29,14,0]}},{name:"harmonica",midiProgram:22,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:5657,filterResonance:29,filterEnvelope:"swell 1",vibrato:"none",algorithm:"1←(2 3←4)",feedbackType:"1⟲",feedbackAmplitude:9,feedbackEnvelope:"tremolo5",operators:[{frequency:"2×",amplitude:14,envelope:"custom"},{frequency:"1×",amplitude:15,envelope:"steady"},{frequency:"~2×",amplitude:2,envelope:"twang 3"},{frequency:"1×",amplitude:0,envelope:"steady"}]}}])},{name:"Flute Presets",presets:a([{name:"flute",midiProgram:73,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:5657,filterResonance:14,filterEnvelope:"steady",vibrato:"none",algorithm:"1←(2 3 4)",feedbackType:"4⟲",feedbackAmplitude:7,feedbackEnvelope:"decay 2",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"2×",amplitude:4,envelope:"steady"},{frequency:"1×",amplitude:3,envelope:"steady"},{frequency:"~1×",amplitude:1,envelope:"punch"}]}},{name:"recorder",midiProgram:74,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:4e3,filterResonance:29,filterEnvelope:"swell 2",interval:"union",vibrato:"none",harmonics:[100,43,57,43,57,43,43,43,43,43,43,43,43,29,29,29,29,29,29,29,14,14,14,14,14,14,14,0]}},{name:"whistle",midiProgram:78,generalMidi:!0,settings:{type:"harmonics",effects:"chorus & reverb",transition:"soft",chord:"harmony",filterCutoffHz:2e3,filterResonance:43,filterEnvelope:"steady",interval:"union",vibrato:"delayed",harmonics:[100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},{name:"ocarina",midiProgram:79,generalMidi:!0,settings:{type:"harmonics",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:2828,filterResonance:43,filterEnvelope:"steady",interval:"union",vibrato:"none",harmonics:[100,14,57,14,29,14,14,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},{name:"piccolo",midiProgram:72,generalMidi:!0,settings:{type:"FM",effects:"reverb",transition:"soft",chord:"harmony",filterCutoffHz:5657,filterResonance:43,filterEnvelope:"steady",vibrato:"none",algorithm:"1←3 2←4",feedbackType:"4⟲",feedbackAmplitude:15,feedbackEnvelope:"twang 1",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"1×",amplitude:10,envelope:"custom"},{frequency:"~2×",amplitude:3,envelope:"punch"},{frequency:"~1×",amplitude:5,envelope:"punch"}]}},{name:"shakuhachi",midiProgram:77,generalMidi:!0,settings:{type:"FM",effects:"chorus & reverb",transition:"soft",chord:"harmony",filterCutoffHz:4e3,filterResonance:14,filterEnvelope:"steady",vibrato:"delayed",algorithm:"1←(2 3←4)",feedbackType:"3→4",feedbackAmplitude:15,feedbackEnvelope:"steady",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"2×",amplitude:3,envelope:"punch"},{frequency:"~1×",amplitude:4,envelope:"twang 1"},{frequency:"20×",amplitude:15,envelope:"steady"}]}},{name:"pan flute",midiProgram:75,generalMidi:!0,settings:{type:"spectrum",eqFilter:[{type:"low-pass",cutoffHz:9513.66,linearGain:5.6569}],effects:["note filter","reverb"],noteFilter:[{type:"high-pass",cutoffHz:4756.83,linearGain:.7071}],reverb:33,fadeInSeconds:.0125,fadeOutTicks:-3,spectrum:[100,0,0,0,0,0,0,14,0,0,0,71,0,0,14,0,57,0,29,14,29,14,14,29,14,29,14,14,29,14],envelopes:[{target:"noteFilterFreq",envelope:"twang 1",index:0},{target:"noteVolume",envelope:"punch"}]}},{name:"blown bottle",midiProgram:76,generalMidi:!0,settings:{type:"FM",effects:"chorus & reverb",transition:"cross fade",chord:"harmony",filterCutoffHz:5657,filterResonance:57,filterEnvelope:"steady",vibrato:"none",algorithm:"1 2 3 4",feedbackType:"1⟲ 2⟲ 3⟲ 4⟲",feedbackAmplitude:7,feedbackEnvelope:"twang 1",operators:[{frequency:"1×",amplitude:15,envelope:"custom"},{frequency:"3×",amplitude:4,envelope:"custom"},{frequency:"6×",amplitude:2,envelope:"custom"},{frequency:"11×",amplitude:2,envelope:"custom"}]}},{name:"calliope",midiProgram:82,generalMidi:!0,settings:{type:"spectrum",transition:"cross fade",effects:"reverb",chord:"harmony",filterCutoffHz:5657,filterResonance:14,filterEnvelope:"steady",spectrum:[100,0,0,0,0,0,0,86,0,0,0,71,0,0,57,0,43,0,29,14,14,29,14,14,14,14,14,14,14,14]}},{name:"chiffer",midiProgram:83,generalMidi:!0,settings:{type:"spectrum",effects:"reverb",transition:"hard",chord:"harmony",filterCutoffHz:2e3,filterResonance:14,filterEnvelope:"punch",spectrum:[86,0,0,0,0,0,0,71,0,0,0,71,0,0,57,0,57,0,43,14,14,43,14,29,14,29,29,29,29,14]}},{name:"breath noise",midiProgram:121,generalMidi:!0,settings:{type:"spectrum",eqFilter:[],effects:["chord type","note filter","reverb"],chord:"strum",noteFilter:[{type:"high-pass",cutoffHz:840.9,linearGain:.3536},{type:"low-pass",cutoffHz:16e3,linearGain:.3536}],reverb:33,fadeInSeconds:.0413,fadeOutTicks:12,spectrum:[71,0,0,0,0,0,0,29,0,0,0,71,0,0,29,0,100,29,14,29,100,29,100,14,14,71,0,29,0,0],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 1"}]}}])},{name:"Pad Presets",presets:a([{name:"new age pad",midiProgram:88,generalMidi:!0,settings:{type:"FM",eqFilter:[],effects:["chorus"],chorus:100,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"simultaneous",algorithm:"1←(2 3←4)",feedbackType:"1⟲ 2⟲",feedbackAmplitude:3,operators:[{frequency:"2×",amplitude:14},{frequency:"~1×",amplitude:4},{frequency:"6×",amplitude:3},{frequency:"13×",amplitude:3}],envelopes:[{target:"operatorAmplitude",envelope:"swell 2",index:1},{target:"operatorAmplitude",envelope:"twang 3",index:2},{target:"feedbackAmplitude",envelope:"swell 3"}]}},{name:"warm pad",midiProgram:89,generalMidi:!0,settings:{type:"FM",eqFilter:[],effects:["note filter","chorus"],noteFilter:[{type:"low-pass",cutoffHz:3363.59,linearGain:1}],chorus:100,transition:"normal",fadeInSeconds:.0575,fadeOutTicks:96,chord:"simultaneous",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:7,operators:[{frequency:"1×",amplitude:14},{frequency:"1×",amplitude:6},{frequency:"1×",amplitude:0},{frequency:"1×",amplitude:0}],envelopes:[{target:"noteFilterAllFreqs",envelope:"swell 3"},{target:"operatorAmplitude",envelope:"swell 1",index:1}]}},{name:"polysynth pad",midiProgram:90,generalMidi:!0,settings:{type:"chip",eqFilter:[],effects:["vibrato","note filter","chorus"],vibrato:"delayed",noteFilter:[{type:"low-pass",cutoffHz:2828.43,linearGain:1}],chorus:100,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"simultaneous",wave:"sawtooth",unison:"honky tonk",envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 3"}]}},{name:"space voice pad",midiProgram:91,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:6727.17,linearGain:5.6569},{type:"peak",cutoffHz:2828.43,linearGain:5.6569},{type:"peak",cutoffHz:1414.21,linearGain:.1768}],effects:["chorus"],chorus:100,transition:"normal",fadeInSeconds:.0125,fadeOutTicks:72,chord:"simultaneous",algorithm:"(1 2 3)←4",feedbackType:"1⟲ 2⟲ 3⟲ 4⟲",feedbackAmplitude:5,operators:[{frequency:"1×",amplitude:10},{frequency:"2×",amplitude:8},{frequency:"3×",amplitude:7},{frequency:"11×",amplitude:2}],envelopes:[{target:"operatorAmplitude",envelope:"punch",index:3},{target:"feedbackAmplitude",envelope:"swell 2"}]}},{name:"bowed glass pad",midiProgram:92,generalMidi:!0,settings:{type:"FM",eqFilter:[],effects:["note filter"],noteFilter:[{type:"low-pass",cutoffHz:4756.83,linearGain:.5}],transition:"normal",fadeInSeconds:.0575,fadeOutTicks:96,chord:"simultaneous",algorithm:"1←3 2←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:0,operators:[{frequency:"1×",amplitude:10},{frequency:"2×",amplitude:12},{frequency:"3×",amplitude:7},{frequency:"7×",amplitude:4}],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 3"},{target:"operatorAmplitude",envelope:"twang 3",index:2},{target:"operatorAmplitude",envelope:"flare 3",index:3}]}},{name:"metallic pad",midiProgram:93,generalMidi:!0,settings:{type:"FM",eqFilter:[],effects:["note filter"],noteFilter:[{type:"low-pass",cutoffHz:6727.17,linearGain:.5}],transition:"normal",fadeInSeconds:.0125,fadeOutTicks:72,chord:"simultaneous",algorithm:"1←3 2←4",feedbackType:"1⟲ 2⟲",feedbackAmplitude:13,operators:[{frequency:"1×",amplitude:15},{frequency:"~1×",amplitude:9},{frequency:"1×",amplitude:7},{frequency:"11×",amplitude:7}],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 3"},{target:"operatorAmplitude",envelope:"swell 2",index:2},{target:"feedbackAmplitude",envelope:"twang 3"}]}},{name:"sweep pad",midiProgram:95,generalMidi:!0,settings:{type:"chip",eqFilter:[],effects:["note filter","chorus"],noteFilter:[{type:"low-pass",cutoffHz:4e3,linearGain:4}],chorus:100,transition:"normal",fadeInSeconds:.0575,fadeOutTicks:96,chord:"simultaneous",wave:"sawtooth",unison:"hum",envelopes:[{target:"noteFilterAllFreqs",envelope:"flare 3"}]}},{name:"atmosphere",midiProgram:99,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:4756.83,linearGain:1}],effects:["chorus","reverb"],chorus:100,reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"strum",algorithm:"1←(2 3 4)",feedbackType:"3⟲ 4⟲",feedbackAmplitude:3,operators:[{frequency:"1×",amplitude:14},{frequency:"~1×",amplitude:10},{frequency:"3×",amplitude:7},{frequency:"1×",amplitude:7}],envelopes:[{target:"operatorAmplitude",envelope:"swell 3",index:1},{target:"operatorAmplitude",envelope:"twang 2",index:2},{target:"operatorAmplitude",envelope:"twang 3",index:3}]}},{name:"brightness",midiProgram:100,generalMidi:!0,settings:{type:"Picked String",eqFilter:[{type:"low-pass",cutoffHz:4756.83,linearGain:2}],effects:["chorus"],chorus:100,transition:"normal",fadeInSeconds:.0125,fadeOutTicks:72,chord:"simultaneous",harmonics:[100,86,86,86,43,57,43,71,43,43,43,57,43,43,57,71,57,43,29,43,57,57,43,29,29,29,29,14],unison:"octave",stringSustain:86,envelopes:[]}},{name:"goblins",midiProgram:101,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"peak",cutoffHz:2828.43,linearGain:11.3137}],effects:["note filter","chorus"],noteFilter:[{type:"low-pass",cutoffHz:1681.79,linearGain:.5}],chorus:100,transition:"normal",fadeInSeconds:.0575,fadeOutTicks:96,chord:"simultaneous",algorithm:"1←2←3←4",feedbackType:"1⟲",feedbackAmplitude:10,operators:[{frequency:"1×",amplitude:15},{frequency:"4×",amplitude:5},{frequency:"1×",amplitude:10},{frequency:"1×",amplitude:0}],envelopes:[{target:"noteFilterAllFreqs",envelope:"swell 2"},{target:"operatorAmplitude",envelope:"swell 3",index:1},{target:"operatorAmplitude",envelope:"tremolo1",index:2},{target:"feedbackAmplitude",envelope:"flare 3"}]}},{name:"sci-fi",midiProgram:103,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"peak",cutoffHz:9513.66,linearGain:2.8284}],effects:["note filter","chorus"],noteFilter:[{type:"low-pass",cutoffHz:6727.17,linearGain:.5}],chorus:100,transition:"normal",fadeInSeconds:.0125,fadeOutTicks:48,chord:"simultaneous",algorithm:"(1 2)←3←4",feedbackType:"1⟲ 2⟲ 3⟲ 4⟲",feedbackAmplitude:8,operators:[{frequency:"~1×",amplitude:13},{frequency:"2×",amplitude:10},{frequency:"5×",amplitude:5},{frequency:"11×",amplitude:8}],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 3"},{target:"operatorAmplitude",envelope:"twang 3",index:2},{target:"operatorAmplitude",envelope:"tremolo5",index:3},{target:"feedbackAmplitude",envelope:"twang 3"}]}},{name:"flutter pad",midiProgram:90,settings:{type:"FM",eqFilter:[],effects:["vibrato","note filter","chorus"],vibrato:"delayed",noteFilter:[{type:"low-pass",cutoffHz:4e3,linearGain:4}],chorus:100,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"simultaneous",algorithm:"(1 2)←(3 4)",feedbackType:"1⟲ 2⟲ 3⟲",feedbackAmplitude:9,operators:[{frequency:"1×",amplitude:13},{frequency:"5×",amplitude:7},{frequency:"7×",amplitude:5},{frequency:"~1×",amplitude:6}],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 3"},{target:"operatorAmplitude",envelope:"tremolo1",index:2},{target:"operatorAmplitude",envelope:"punch",index:3}]}},{name:"feedback pad",midiProgram:89,settings:{type:"FM",eqFilter:[{type:"peak",cutoffHz:2378.41,linearGain:8}],effects:[],transition:"normal",fadeInSeconds:.0575,fadeOutTicks:96,chord:"custom interval",algorithm:"1 2 3 4",feedbackType:"1⟲ 2⟲ 3⟲ 4⟲",feedbackAmplitude:8,operators:[{frequency:"1×",amplitude:15},{frequency:"1×",amplitude:15},{frequency:"1×",amplitude:15},{frequency:"~1×",amplitude:15}],envelopes:[{target:"feedbackAmplitude",envelope:"swell 2"}]}},{name:"supersaw pad",midiProgram:93,settings:{type:"supersaw",eqFilter:[{type:"low-pass",cutoffHz:8e3,linearGain:.1768}],effects:["reverb"],reverb:100,fadeInSeconds:.0263,fadeOutTicks:24,pulseWidth:50,dynamism:100,spread:58,shape:0,envelopes:[]}}])},{name:"Drum Presets",presets:a([{name:"standard drumset",midiProgram:116,isNoise:!0,settings:{type:"drumset",effects:"reverb",drums:[{filterEnvelope:"twang 1",spectrum:[57,71,71,86,86,86,71,71,71,71,57,57,57,57,43,43,43,43,29,29,29,29,29,29,29,29,29,29,29,29]},{filterEnvelope:"twang 1",spectrum:[0,0,0,100,71,71,57,86,57,57,57,71,43,43,57,43,43,43,43,43,43,43,43,43,43,43,43,43,43,43]},{filterEnvelope:"twang 1",spectrum:[0,0,0,0,100,57,43,43,29,57,43,29,71,43,43,43,43,57,43,43,43,43,43,43,43,43,29,43,43,43]},{filterEnvelope:"twang 1",spectrum:[0,0,0,0,0,71,57,43,43,43,57,57,43,29,57,43,43,43,29,43,57,43,43,43,43,43,43,29,43,43]},{filterEnvelope:"decay 2",spectrum:[0,14,29,43,86,71,29,43,43,43,43,29,71,29,71,29,43,43,43,43,57,43,43,57,43,43,43,57,57,57]},{filterEnvelope:"decay 1",spectrum:[0,0,14,14,14,14,29,29,29,43,43,43,57,57,57,71,71,71,71,71,71,71,71,57,57,57,57,43,43,43]},{filterEnvelope:"twang 3",spectrum:[43,43,43,71,29,29,43,43,43,29,43,43,43,29,29,43,43,29,29,29,57,14,57,43,43,57,43,43,57,57]},{filterEnvelope:"decay 3",spectrum:[29,43,43,43,43,29,29,43,29,29,43,29,14,29,43,29,43,29,57,29,43,57,43,71,43,71,57,57,71,71]},{filterEnvelope:"twang 3",spectrum:[43,29,29,43,29,29,29,57,29,29,29,57,43,43,29,29,57,43,43,43,71,43,43,71,57,71,71,71,71,71]},{filterEnvelope:"decay 3",spectrum:[57,57,57,43,57,57,43,43,57,43,43,43,71,57,43,57,86,71,57,86,71,57,86,100,71,86,86,86,86,86]},{filterEnvelope:"flare 1",spectrum:[0,0,14,14,14,14,29,29,29,43,43,43,57,57,71,71,86,86,100,100,100,100,100,100,100,100,86,57,29,0]},{filterEnvelope:"decay 2",spectrum:[14,14,14,14,29,14,14,29,14,43,14,43,57,86,57,57,100,57,43,43,57,100,57,43,29,14,0,0,0,0]}]}},{name:"steel pan",midiProgram:114,generalMidi:!0,settings:{type:"FM",eqFilter:[{type:"high-pass",cutoffHz:62.5,linearGain:.1768}],effects:["note filter","chorus","reverb"],noteFilter:[{type:"low-pass",cutoffHz:13454.34,linearGain:.25}],chorus:67,reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:24,chord:"simultaneous",algorithm:"1←(2 3←4)",feedbackType:"1⟲",feedbackAmplitude:0,operators:[{frequency:"~1×",amplitude:14},{frequency:"7×",amplitude:3},{frequency:"3×",amplitude:5},{frequency:"4×",amplitude:4}],envelopes:[{target:"noteFilterAllFreqs",envelope:"decay 2"},{target:"operatorAmplitude",envelope:"flare 1",index:1},{target:"operatorAmplitude",envelope:"flare 2",index:2},{target:"operatorAmplitude",envelope:"swell 2",index:3}]}},{name:"steel pan synth",midiProgram:114,settings:{type:"FM",eqFilter:[],effects:["note filter"],noteFilter:[{type:"low-pass",cutoffHz:13454.34,linearGain:.25}],transition:"normal",fadeInSeconds:0,fadeOutTicks:-3,chord:"simultaneous",algorithm:"1 2 3←4",feedbackType:"1⟲",feedbackAmplitude:5,operators:[{frequency:"~1×",amplitude:12},{frequency:"2×",amplitude:15},{frequency:"4×",amplitude:14},{frequency:"~1×",amplitude:3}],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 1"},{target:"operatorAmplitude",envelope:"note size",index:0},{target:"operatorAmplitude",envelope:"note size",index:1},{target:"operatorAmplitude",envelope:"flare 1",index:2},{target:"operatorAmplitude",envelope:"flare 2",index:3},{target:"feedbackAmplitude",envelope:"flare 1"}]}},{name:"timpani",midiProgram:47,generalMidi:!0,settings:{type:"spectrum",eqFilter:[{type:"peak",cutoffHz:6727.17,linearGain:5.6569}],effects:["pitch shift","note filter","reverb"],pitchShiftSemitones:15,noteFilter:[{type:"low-pass",cutoffHz:19027.31,linearGain:.5}],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"simultaneous",spectrum:[100,0,0,0,86,0,0,71,0,14,43,14,43,43,0,29,43,29,29,29,43,29,43,29,43,43,43,43,43,43],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 1"},{target:"pitchShift",envelope:"twang 1"}]}},{name:"dark strike",midiProgram:47,settings:{type:"spectrum",eqFilter:[],effects:["note filter","reverb"],noteFilter:[{type:"low-pass",cutoffHz:4756.83,linearGain:.7071}],reverb:33,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"simultaneous",spectrum:[0,0,14,14,14,29,29,43,43,86,43,43,43,29,86,29,29,29,86,29,14,14,14,14,0,0,0,0,0,0],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 2"}]}},{name:"woodblock",midiProgram:115,generalMidi:!0,isNoise:!0,midiSubharmonicOctaves:-2.5,settings:{type:"spectrum",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2828,filterResonance:14,filterEnvelope:"twang 1",spectrum:[0,14,29,43,43,57,86,86,71,57,57,43,43,57,86,86,43,43,71,57,57,57,57,57,86,86,71,71,71,71]}},{name:"taiko drum",midiProgram:116,generalMidi:!0,isNoise:!0,midiSubharmonicOctaves:-.5,settings:{type:"spectrum",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2828,filterResonance:29,filterEnvelope:"twang 1",spectrum:[71,100,100,43,43,71,71,43,43,43,43,43,43,57,29,57,43,57,43,43,57,43,43,43,43,43,43,43,43,43]}},{name:"melodic drum",midiProgram:117,generalMidi:!0,isNoise:!0,midiSubharmonicOctaves:-1.5,settings:{type:"spectrum",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2828,filterResonance:43,filterEnvelope:"twang 1",spectrum:[100,71,71,57,57,43,43,71,43,43,43,57,43,43,57,43,43,43,43,29,29,29,29,29,29,29,29,29,29,29]}},{name:"drum synth",midiProgram:118,generalMidi:!0,isNoise:!0,midiSubharmonicOctaves:-2,settings:{type:"spectrum",effects:"reverb",transition:"hard fade",chord:"harmony",filterCutoffHz:4e3,filterResonance:43,filterEnvelope:"decay 1",spectrum:[100,86,71,57,43,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29]}},{name:"tom-tom",midiProgram:116,isNoise:!0,midiSubharmonicOctaves:-1,settings:{type:"spectrum",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:2e3,filterResonance:14,filterEnvelope:"twang 1",spectrum:[100,29,14,0,0,86,14,43,29,86,29,14,29,57,43,43,43,43,57,43,43,43,29,57,43,43,43,43,43,43]}},{name:"metal pipe",midiProgram:117,isNoise:!0,midiSubharmonicOctaves:-1.5,settings:{type:"spectrum",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:8e3,filterResonance:14,filterEnvelope:"twang 2",spectrum:[29,43,86,43,43,43,43,43,100,29,14,14,100,14,14,0,0,0,0,0,14,29,29,14,0,0,14,29,0,0]}},{name:"synth kick",midiProgram:47,settings:{type:"FM",eqFilter:[],effects:[],transition:"normal",fadeInSeconds:0,fadeOutTicks:-6,chord:"simultaneous",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:0,operators:[{frequency:"8×",amplitude:15},{frequency:"1×",amplitude:0},{frequency:"1×",amplitude:0},{frequency:"1×",amplitude:0}],envelopes:[{target:"operatorFrequency",envelope:"twang 1",index:0},{target:"noteVolume",envelope:"twang 2"}]}}])},{name:"Novelty Presets",presets:a([{name:"guitar fret noise",midiProgram:120,generalMidi:!0,settings:{type:"spectrum",eqFilter:[{type:"high-pass",cutoffHz:1e3,linearGain:.1768}],effects:["note filter"],noteFilter:[{type:"low-pass",cutoffHz:6727.17,linearGain:5.6569}],transition:"normal",fadeInSeconds:.0125,fadeOutTicks:-3,chord:"simultaneous",spectrum:[0,0,0,0,0,0,0,0,0,0,0,0,0,14,0,0,0,29,14,0,0,43,0,43,0,71,43,0,57,0],envelopes:[{target:"noteFilterAllFreqs",envelope:"flare 1"},{target:"noteVolume",envelope:"twang 2"}]}},{name:"fifth saw lead",midiProgram:86,generalMidi:!0,midiSubharmonicOctaves:1,settings:{type:"chip",eqFilter:[],effects:["note filter","chorus"],noteFilter:[{type:"low-pass",cutoffHz:2828.43,linearGain:1.4142}],chorus:67,transition:"normal",fadeInSeconds:0,fadeOutTicks:48,chord:"simultaneous",wave:"sawtooth",unison:"fifth",envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 3"}]}},{name:"fifth swell",midiProgram:86,midiSubharmonicOctaves:1,settings:{type:"chip",eqFilter:[],effects:["note filter","chorus"],noteFilter:[{type:"low-pass",cutoffHz:2e3,linearGain:2}],chorus:100,transition:"normal",fadeInSeconds:.0125,fadeOutTicks:72,chord:"simultaneous",wave:"sawtooth",unison:"fifth",envelopes:[{target:"noteFilterAllFreqs",envelope:"swell 3"}]}},{name:"soundtrack",midiProgram:97,generalMidi:!0,settings:{type:"chip",eqFilter:[],effects:["note filter","chorus"],noteFilter:[{type:"low-pass",cutoffHz:2378.41,linearGain:.5}],chorus:67,transition:"normal",fadeInSeconds:.0413,fadeOutTicks:72,chord:"simultaneous",wave:"sawtooth",unison:"fifth",envelopes:[{target:"noteFilterAllFreqs",envelope:"flare 3"}]}},{name:"reverse cymbal",midiProgram:119,generalMidi:!0,isNoise:!0,midiSubharmonicOctaves:-3,settings:{type:"spectrum",effects:"none",transition:"soft",chord:"harmony",filterCutoffHz:4e3,filterResonance:14,filterEnvelope:"swell 3",spectrum:[29,57,57,29,57,57,29,29,43,29,29,43,29,29,57,57,14,57,14,57,71,71,57,86,57,100,86,86,86,86]}},{name:"seashore",midiProgram:122,generalMidi:!0,isNoise:!0,midiSubharmonicOctaves:-3,settings:{type:"spectrum",transition:"soft fade",effects:"reverb",chord:"harmony",filterCutoffHz:2828,filterResonance:0,filterEnvelope:"swell 3",spectrum:[14,14,29,29,43,43,43,57,57,57,57,57,57,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,71,57]}},{name:"bird tweet",midiProgram:123,generalMidi:!0,settings:{type:"harmonics",eqFilter:[],effects:["chord type","vibrato","reverb"],chord:"strum",vibrato:"heavy",reverb:67,fadeInSeconds:.0575,fadeOutTicks:-6,harmonics:[0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],unison:"hum",envelopes:[{target:"noteVolume",envelope:"decay 1"}]}},{name:"telephone ring",midiProgram:124,generalMidi:!0,settings:{type:"FM",eqFilter:[],effects:["note filter"],noteFilter:[{type:"low-pass",cutoffHz:5656.85,linearGain:1}],transition:"normal",fadeInSeconds:.0125,fadeOutTicks:-3,chord:"arpeggio",algorithm:"1←(2 3 4)",feedbackType:"1⟲",feedbackAmplitude:0,operators:[{frequency:"2×",amplitude:12},{frequency:"1×",amplitude:4},{frequency:"20×",amplitude:1},{frequency:"1×",amplitude:0}],envelopes:[{target:"noteFilterAllFreqs",envelope:"tremolo4"},{target:"operatorAmplitude",envelope:"tremolo1",index:1}]}},{name:"helicopter",midiProgram:125,generalMidi:!0,isNoise:!0,midiSubharmonicOctaves:-.5,settings:{type:"spectrum",effects:"reverb",transition:"seamless",chord:"arpeggio",filterCutoffHz:1414,filterResonance:14,filterEnvelope:"tremolo4",spectrum:[14,43,43,57,57,57,71,71,71,71,86,86,86,86,86,86,86,86,86,86,86,71,71,71,71,71,71,71,57,57]}},{name:"applause",midiProgram:126,generalMidi:!0,isNoise:!0,midiSubharmonicOctaves:-3,settings:{type:"spectrum",effects:"reverb",transition:"soft fade",chord:"harmony",filterCutoffHz:2e3,filterResonance:14,filterEnvelope:"swell 3",spectrum:[14,14,29,29,29,43,43,57,71,71,86,86,86,71,71,57,57,57,71,86,86,86,86,86,71,71,57,57,57,57]}},{name:"gunshot",midiProgram:127,generalMidi:!0,isNoise:!0,midiSubharmonicOctaves:-2,settings:{type:"spectrum",effects:"reverb",transition:"hard fade",chord:"strum",filterCutoffHz:1414,filterResonance:29,filterEnvelope:"twang 1",spectrum:[14,29,43,43,57,57,57,71,71,71,86,86,86,86,86,86,86,86,86,86,86,71,71,71,71,57,57,57,57,43]}},{name:"scoot",midiProgram:92,settings:{type:"chip",eqFilter:[],effects:["note filter"],noteFilter:[{type:"low-pass",cutoffHz:707.11,linearGain:4}],transition:"normal",fadeInSeconds:.0125,fadeOutTicks:-3,chord:"simultaneous",wave:"double saw",unison:"shimmer",envelopes:[{target:"noteFilterAllFreqs",envelope:"flare 1"}]}},{name:"buzz saw",midiProgram:30,settings:{type:"FM",eqFilter:[{type:"low-pass",cutoffHz:9513.66,linearGain:.5}],effects:[],transition:"normal",fadeInSeconds:.0263,fadeOutTicks:-3,chord:"custom interval",algorithm:"1←2←3←4",feedbackType:"1⟲",feedbackAmplitude:4,operators:[{frequency:"5×",amplitude:13},{frequency:"1×",amplitude:10},{frequency:"~1×",amplitude:6},{frequency:"11×",amplitude:12}],envelopes:[]}},{name:"mosquito",midiProgram:93,settings:{type:"PWM",eqFilter:[{type:"low-pass",cutoffHz:2828.43,linearGain:2}],effects:["vibrato"],vibrato:"shaky",transition:"normal",fadeInSeconds:.0575,fadeOutTicks:-6,chord:"simultaneous",pulseWidth:4.41942,envelopes:[{target:"pulseWidth",envelope:"tremolo6"}]}},{name:"breathing",midiProgram:126,isNoise:!0,midiSubharmonicOctaves:-1,settings:{type:"spectrum",effects:"reverb",transition:"hard fade",chord:"harmony",filterCutoffHz:2e3,filterResonance:14,filterEnvelope:"swell 2",spectrum:[14,14,14,29,29,29,29,29,43,29,29,43,43,43,29,29,71,43,86,86,57,100,86,86,86,86,71,86,71,57]}},{name:"klaxon synth",midiProgram:125,isNoise:!0,midiSubharmonicOctaves:-1,settings:{type:"noise",effects:"reverb",transition:"slide",chord:"harmony",filterCutoffHz:2e3,filterResonance:86,filterEnvelope:"steady",wave:"buzz"}},{name:"theremin",midiProgram:40,settings:{type:"harmonics",eqFilter:[{type:"low-pass",cutoffHz:8e3,linearGain:.7071}],effects:["vibrato","reverb"],vibrato:"heavy",reverb:33,transition:"slide in pattern",fadeInSeconds:.0263,fadeOutTicks:-6,chord:"simultaneous",harmonics:[100,71,57,43,29,29,14,14,14,14,14,14,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],unison:"none",envelopes:[]}},{name:"sonar ping",midiProgram:121,settings:{type:"spectrum",eqFilter:[],effects:["note filter","reverb"],noteFilter:[{type:"low-pass",cutoffHz:1681.79,linearGain:.5}],reverb:33,transition:"normal",fadeInSeconds:.0125,fadeOutTicks:72,chord:"simultaneous",spectrum:[100,43,29,29,14,14,14,14,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],envelopes:[{target:"noteFilterAllFreqs",envelope:"twang 2"}]}}])}]);var S=t&&t.t||function(t){var e="function"==typeof Symbol&&Symbol.iterator,i=e&&t[e],s=0;if(i)return i.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&s>=t.length&&(t=void 0),{value:t&&t[s++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},F=t&&t.i||function(t,e){var i="function"==typeof Symbol&&t[Symbol.iterator];if(!i)return t;var s,n,o=i.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(s=o.next()).done;)r.push(s.value)}catch(t){n={error:t}}finally{try{s&&!s.done&&(i=o.return)&&i.call(o)}finally{if(n)throw n.error}}return r},P=t&&t.o||function(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(F(arguments[e]));return t};function I(t,e){var i,s,n,o,r,h;try{for(var a=S(e),l=a.next();!l.done;l=a.next()){var c=l.value;if(c instanceof Node)t.appendChild(c);else if("string"==typeof c)t.appendChild(document.createTextNode(c));else if("function"==typeof c)I(t,[c()]);else if(Array.isArray(c))I(t,c);else if(c&&"undefined"!=typeof Symbol&&"function"==typeof c[Symbol.iterator])I(t,P(c));else if(c&&c.constructor===Object&&t instanceof Element)try{for(var u=(n=void 0,S(Object.keys(c))),f=u.next();!f.done;f=u.next()){var p=f.value,d=c[p];if("class"===p)"string"==typeof d?t.setAttribute("class",d):Array.isArray(c)||d&&"undefined"!=typeof Symbol&&"function"==typeof d[Symbol.iterator]?t.setAttribute("class",P(d).join(" ")):console.warn("Invalid "+p+' value "'+d+'" on '+t.tagName+" element.");else if("style"===p)if(d&&d.constructor===Object)try{for(var m=(r=void 0,S(Object.keys(d))),y=m.next();!y.done;y=m.next()){var g=y.value;g in t.style?t.style[g]=d[g]:t.style.setProperty(g,d[g])}}catch(t){r={error:t}}finally{try{y&&!y.done&&(h=m.return)&&h.call(m)}finally{if(r)throw r.error}}else t.setAttribute(p,d);else"function"==typeof d?t[p]=d:"boolean"==typeof d?d?t.setAttribute(p,""):t.removeAttribute(p):t.setAttribute(p,d)}}catch(t){n={error:t}}finally{try{f&&!f.done&&(o=u.return)&&o.call(u)}finally{if(n)throw n.error}}else t.appendChild(document.createTextNode(c))}}catch(t){i={error:t}}finally{try{l&&!l.done&&(s=a.return)&&s.call(a)}finally{if(i)throw i.error}}return t}var T="http://www.w3.org/2000/svg";var q,E,C,L,z=t&&t.t||function(t){var e="function"==typeof Symbol&&Symbol.iterator,i=e&&t[e],s=0;if(i)return i.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&s>=t.length&&(t=void 0),{value:t&&t[s++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},D=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return document.createRange().createContextualFragment(t.join())},A=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];for(var i=document.createDocumentFragment(),s=(new DOMParser).parseFromString('<svg xmlns="http://www.w3.org/2000/svg">'+t.join()+"</svg>","image/svg+xml").documentElement;null!==s.firstChild;)document.importNode(s.firstChild,!0),i.appendChild(s.firstChild);return i},B=function(t){D[t]=function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];return I(document.createElement(t),e)}};try{for(var O=z("a abbr address area article aside audio b base bdi bdo blockquote br button canvas caption cite code col colgroup datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hr i iframe img input ins kbd label legend li link main map mark menu menuitem meta meter nav noscript object ol optgroup option output p param picture pre progress q rp rt ruby s samp script section select small source span strong style sub summary sup table tbody td template textarea tfoot th thead time title tr track u ul var video wbr".split(" ")),N=O.next();!N.done;N=O.next()){B(N.value)}}catch(t){q={error:t}}finally{try{N&&!N.done&&(E=O.return)&&E.call(O)}finally{if(q)throw q.error}}var R=function(t){if(A[t]=function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];return I(document.createElementNS(T,t),e)},/-/.test(t)){var e=t.replace(/-/g,"_");A[e]=function(){for(var e=[],i=0;i<arguments.length;i++)e[i]=arguments[i];return I(document.createElementNS(T,t),e)}}};try{for(var H=z("a altGlyph altGlyphDef altGlyphItem animate animateMotion animateTransform circle clipPath color-profile cursor defs desc discard ellipse feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence filter font font-face font-face-format font-face-name font-face-src font-face-uri foreignObject g glyph glyphRef hkern image line linearGradient marker mask metadata missing-glyph mpath path pattern polygon polyline radialGradient rect script set stop style svg switch symbol text textPath title tref tspan use view vkern".split(" ")),G=H.next();!G.done;G=H.next()){R(G.value)}}catch(t){C={error:t}}finally{try{G&&!G.done&&(L=H.return)&&L.call(H)}finally{if(C)throw C.error}}class ${static getChannelColor(t,e){return e<t.pitchChannelCount?$.pitchChannels[e%$.pitchChannels.length]:$.noiseChannels[(e-t.pitchChannelCount)%$.noiseChannels.length]}static setTheme(t){let e=this.themes[t];null==e&&(e=this.themes["dark classic"]),this.h.textContent=e;const i=document.querySelector("meta[name='theme-color']");null!=i&&i.setAttribute("content",getComputedStyle(document.documentElement).getPropertyValue("--ui-widget-background"))}}$.themes={"dark classic":"\n\t\t\t:root {\n\t\t\t\t--page-margin: black;\n\t\t\t\t--editor-background: black;\n\t\t\t\t--hover-preview: white;\n\t\t\t\t--playhead: white;\n\t\t\t\t--primary-text: white;\n\t\t\t\t--secondary-text: #999;\n\t\t\t\t--inverted-text: black;\n\t\t\t\t--text-selection: rgba(119,68,255,0.99);\n\t\t\t\t--box-selection-fill: rgba(255,255,255,0.2);\n\t\t\t\t--loop-accent: #74f;\n\t\t\t\t--link-accent: #98f;\n\t\t\t\t--ui-widget-background: #444;\n\t\t\t\t--ui-widget-focus: #777;\n\t\t\t\t--pitch-background: #444;\n\t\t\t\t--tonic: #864;\n\t\t\t\t--fifth-note: #468;\n\t\t\t\t--white-piano-key: #bbb;\n\t\t\t\t--black-piano-key: #444;\n\t\t\t\t--pitch1-secondary-channel: #0099A1;\n\t\t\t\t--pitch1-primary-channel: #25F3FF;\n\t\t\t\t--pitch1-secondary-note: #00BDC7;\n\t\t\t\t--pitch1-primary-note: #92F9FF;\n\t\t\t\t--pitch2-secondary-channel: #A1A100;\n\t\t\t\t--pitch2-primary-channel: #FFFF25;\n\t\t\t\t--pitch2-secondary-note: #C7C700;\n\t\t\t\t--pitch2-primary-note: #FFFF92;\n\t\t\t\t--pitch3-secondary-channel: #C75000;\n\t\t\t\t--pitch3-primary-channel: #FF9752;\n\t\t\t\t--pitch3-secondary-note: #FF771C;\n\t\t\t\t--pitch3-primary-note: #FFCDAB;\n\t\t\t\t--pitch4-secondary-channel: #00A100;\n\t\t\t\t--pitch4-primary-channel: #50FF50;\n\t\t\t\t--pitch4-secondary-note: #00C700;\n\t\t\t\t--pitch4-primary-note: #A0FFA0;\n\t\t\t\t--pitch5-secondary-channel: #D020D0;\n\t\t\t\t--pitch5-primary-channel: #FF90FF;\n\t\t\t\t--pitch5-secondary-note: #E040E0;\n\t\t\t\t--pitch5-primary-note: #FFC0FF;\n\t\t\t\t--pitch6-secondary-channel: #7777B0;\n\t\t\t\t--pitch6-primary-channel: #A0A0FF;\n\t\t\t\t--pitch6-secondary-note: #8888D0;\n\t\t\t\t--pitch6-primary-note: #D0D0FF;\n\t\t\t\t--pitch7-secondary-channel: #8AA100;\n\t\t\t\t--pitch7-primary-channel: #DEFF25;\n\t\t\t\t--pitch7-secondary-note: #AAC700;\n\t\t\t\t--pitch7-primary-note: #E6FF92;\n\t\t\t\t--pitch8-secondary-channel: #DF0019;\n\t\t\t\t--pitch8-primary-channel: #FF98A4;\n\t\t\t\t--pitch8-secondary-note: #FF4E63;\n\t\t\t\t--pitch8-primary-note: #FFB2BB;\n\t\t\t\t--pitch9-secondary-channel: #00A170;\n\t\t\t\t--pitch9-primary-channel: #50FFC9;\n\t\t\t\t--pitch9-secondary-note: #00C78A;\n\t\t\t\t--pitch9-primary-note: #83FFD9;\n\t\t\t\t--pitch10-secondary-channel:#A11FFF;\n\t\t\t\t--pitch10-primary-channel: #CE8BFF;\n\t\t\t\t--pitch10-secondary-note: #B757FF;\n\t\t\t\t--pitch10-primary-note: #DFACFF;\n\t\t\t\t--noise1-secondary-channel: #6F6F6F;\n\t\t\t\t--noise1-primary-channel: #AAAAAA;\n\t\t\t\t--noise1-secondary-note: #A7A7A7;\n\t\t\t\t--noise1-primary-note: #E0E0E0;\n\t\t\t\t--noise2-secondary-channel: #996633;\n\t\t\t\t--noise2-primary-channel: #DDAA77;\n\t\t\t\t--noise2-secondary-note: #CC9966;\n\t\t\t\t--noise2-primary-note: #F0D0BB;\n\t\t\t\t--noise3-secondary-channel: #4A6D8F;\n\t\t\t\t--noise3-primary-channel: #77AADD;\n\t\t\t\t--noise3-secondary-note: #6F9FCF;\n\t\t\t\t--noise3-primary-note: #BBD7FF;\n\t\t\t\t--noise4-secondary-channel: #7A4F9A;\n\t\t\t\t--noise4-primary-channel: #AF82D2;\n\t\t\t\t--noise4-secondary-note: #9E71C1;\n\t\t\t\t--noise4-primary-note: #D4C1EA;\n\t\t\t\t--noise5-secondary-channel: #607837;\n\t\t\t\t--noise5-primary-channel: #A2BB77;\n\t\t\t\t--noise5-secondary-note: #91AA66;\n\t\t\t\t--noise5-primary-note: #C5E2B2;\n\t\t\t}\n\t\t","light classic":"\n\t\t\t:root {\n\t\t\t\t-webkit-text-stroke-width: 0.5px;\n\t\t\t\t--page-margin: #685d88;\n\t\t\t\t--editor-background: white;\n\t\t\t\t--hover-preview: black;\n\t\t\t\t--playhead: rgba(0,0,0,0.5);\n\t\t\t\t--primary-text: black;\n\t\t\t\t--secondary-text: #777;\n\t\t\t\t--inverted-text: white;\n\t\t\t\t--text-selection: rgba(200,170,255,0.99);\n\t\t\t\t--box-selection-fill: rgba(0,0,0,0.1);\n\t\t\t\t--loop-accent: #98f;\n\t\t\t\t--link-accent: #74f;\n\t\t\t\t--ui-widget-background: #ececec;\n\t\t\t\t--ui-widget-focus: #eee;\n\t\t\t\t--pitch-background: #ececec;\n\t\t\t\t--tonic: #f0d6b6;\n\t\t\t\t--fifth-note: #bbddf0;\n\t\t\t\t--white-piano-key: #eee;\n\t\t\t\t--black-piano-key: #666;\n\t\t\t\t--pitch1-secondary-channel: #6CD9ED;\n\t\t\t\t--pitch1-primary-channel: #00A0BD;\n\t\t\t\t--pitch1-secondary-note: #34C2DC;\n\t\t\t\t--pitch1-primary-note: #00758A;\n\t\t\t\t--pitch2-secondary-channel: #E3C941;\n\t\t\t\t--pitch2-primary-channel: #B49700;\n\t\t\t\t--pitch2-secondary-note: #D1B628;\n\t\t\t\t--pitch2-primary-note: #836E00;\n\t\t\t\t--pitch3-secondary-channel: #FF9D61;\n\t\t\t\t--pitch3-primary-channel: #E14E00;\n\t\t\t\t--pitch3-secondary-note: #F67D3C;\n\t\t\t\t--pitch3-primary-note: #B64000;\n\t\t\t\t--pitch4-secondary-channel: #4BE24B;\n\t\t\t\t--pitch4-primary-channel: #00A800;\n\t\t\t\t--pitch4-secondary-note: #2DC82D;\n\t\t\t\t--pitch4-primary-note: #008000;\n\t\t\t\t--pitch5-secondary-channel: #FF90FF;\n\t\t\t\t--pitch5-primary-channel: #E12EDF;\n\t\t\t\t--pitch5-secondary-note: #EC6EEC;\n\t\t\t\t--pitch5-primary-note: #A600A5;\n\t\t\t\t--pitch6-secondary-channel: #B5B5FE;\n\t\t\t\t--pitch6-primary-channel: #6969FD;\n\t\t\t\t--pitch6-secondary-note: #9393FE;\n\t\t\t\t--pitch6-primary-note: #4A4AD7;\n\t\t\t\t--pitch7-secondary-channel: #C2D848;\n\t\t\t\t--pitch7-primary-channel: #8EA800;\n\t\t\t\t--pitch7-secondary-note: #B0C82D;\n\t\t\t\t--pitch7-primary-note: #6C8000;\n\t\t\t\t--pitch8-secondary-channel: #FF90A4;\n\t\t\t\t--pitch8-primary-channel: #E12E4D;\n\t\t\t\t--pitch8-secondary-note: #EC6E85;\n\t\t\t\t--pitch8-primary-note: #A6001D;\n\t\t\t\t--pitch9-secondary-channel: #41E3B5;\n\t\t\t\t--pitch9-primary-channel: #00B481;\n\t\t\t\t--pitch9-secondary-note: #28D1A1;\n\t\t\t\t--pitch9-primary-note: #00835E;\n\t\t\t\t--pitch10-secondary-channel:#CA77FF;\n\t\t\t\t--pitch10-primary-channel: #9609FF;\n\t\t\t\t--pitch10-secondary-note: #B54FFF;\n\t\t\t\t--pitch10-primary-note: #8400E3;\n\t\t\t\t--noise1-secondary-channel: #C1C1C1;\n\t\t\t\t--noise1-primary-channel: #898989;\n\t\t\t\t--noise1-secondary-note: #ADADAD;\n\t\t\t\t--noise1-primary-note: #6C6C6C;\n\t\t\t\t--noise2-secondary-channel: #E8BB8C;\n\t\t\t\t--noise2-primary-channel: #BD7D3A;\n\t\t\t\t--noise2-secondary-note: #D1A374;\n\t\t\t\t--noise2-primary-note: #836342;\n\t\t\t\t--noise3-secondary-channel: #9BC4EB;\n\t\t\t\t--noise3-primary-channel: #4481BE;\n\t\t\t\t--noise3-secondary-note: #7CA7D3;\n\t\t\t\t--noise3-primary-note: #476685;\n\t\t\t\t--noise4-secondary-channel: #C5A5E0;\n\t\t\t\t--noise4-primary-channel: #8553AE;\n\t\t\t\t--noise4-secondary-note: #B290CC;\n\t\t\t\t--noise4-primary-note: #684F7D;\n\t\t\t\t--noise5-secondary-channel: #B8CE93;\n\t\t\t\t--noise5-primary-channel: #87A74F;\n\t\t\t\t--noise5-secondary-note: #ABC183;\n\t\t\t\t--noise5-primary-note: #68784C;\n\t\t\t}\n\t\t\t\n\t\t\t.beepboxEditor button, .beepboxEditor select {\n\t\t\t\tbox-shadow: inset 0 0 0 1px var(--secondary-text);\n\t\t\t}\n\t\t"},$.pageMargin="var(--page-margin)",$.editorBackground="var(--editor-background)",$.hoverPreview="var(--hover-preview)",$.playhead="var(--playhead)",$.primaryText="var(--primary-text)",$.secondaryText="var(--secondary-text)",$.invertedText="var(--inverted-text)",$.textSelection="var(--text-selection)",$.boxSelectionFill="var(--box-selection-fill)",$.loopAccent="var(--loop-accent)",$.linkAccent="var(--link-accent)",$.uiWidgetBackground="var(--ui-widget-background)",$.uiWidgetFocus="var(--ui-widget-focus)",$.pitchBackground="var(--pitch-background)",$.tonic="var(--tonic)",$.fifthNote="var(--fifth-note)",$.whitePianoKey="var(--white-piano-key)",$.blackPianoKey="var(--black-piano-key)",$.pitchChannels=a([{name:"pitch1",secondaryChannel:"var(--pitch1-secondary-channel)",primaryChannel:"var(--pitch1-primary-channel)",secondaryNote:"var(--pitch1-secondary-note)",primaryNote:"var(--pitch1-primary-note)"},{name:"pitch2",secondaryChannel:"var(--pitch2-secondary-channel)",primaryChannel:"var(--pitch2-primary-channel)",secondaryNote:"var(--pitch2-secondary-note)",primaryNote:"var(--pitch2-primary-note)"},{name:"pitch3",secondaryChannel:"var(--pitch3-secondary-channel)",primaryChannel:"var(--pitch3-primary-channel)",secondaryNote:"var(--pitch3-secondary-note)",primaryNote:"var(--pitch3-primary-note)"},{name:"pitch4",secondaryChannel:"var(--pitch4-secondary-channel)",primaryChannel:"var(--pitch4-primary-channel)",secondaryNote:"var(--pitch4-secondary-note)",primaryNote:"var(--pitch4-primary-note)"},{name:"pitch5",secondaryChannel:"var(--pitch5-secondary-channel)",primaryChannel:"var(--pitch5-primary-channel)",secondaryNote:"var(--pitch5-secondary-note)",primaryNote:"var(--pitch5-primary-note)"},{name:"pitch6",secondaryChannel:"var(--pitch6-secondary-channel)",primaryChannel:"var(--pitch6-primary-channel)",secondaryNote:"var(--pitch6-secondary-note)",primaryNote:"var(--pitch6-primary-note)"},{name:"pitch7",secondaryChannel:"var(--pitch7-secondary-channel)",primaryChannel:"var(--pitch7-primary-channel)",secondaryNote:"var(--pitch7-secondary-note)",primaryNote:"var(--pitch7-primary-note)"},{name:"pitch8",secondaryChannel:"var(--pitch8-secondary-channel)",primaryChannel:"var(--pitch8-primary-channel)",secondaryNote:"var(--pitch8-secondary-note)",primaryNote:"var(--pitch8-primary-note)"},{name:"pitch9",secondaryChannel:"var(--pitch9-secondary-channel)",primaryChannel:"var(--pitch9-primary-channel)",secondaryNote:"var(--pitch9-secondary-note)",primaryNote:"var(--pitch9-primary-note)"},{name:"pitch10",secondaryChannel:"var(--pitch10-secondary-channel)",primaryChannel:"var(--pitch10-primary-channel)",secondaryNote:"var(--pitch10-secondary-note)",primaryNote:"var(--pitch10-primary-note)"}]),$.noiseChannels=a([{name:"noise1",secondaryChannel:"var(--noise1-secondary-channel)",primaryChannel:"var(--noise1-primary-channel)",secondaryNote:"var(--noise1-secondary-note)",primaryNote:"var(--noise1-primary-note)"},{name:"noise2",secondaryChannel:"var(--noise2-secondary-channel)",primaryChannel:"var(--noise2-primary-channel)",secondaryNote:"var(--noise2-secondary-note)",primaryNote:"var(--noise2-primary-note)"},{name:"noise3",secondaryChannel:"var(--noise3-secondary-channel)",primaryChannel:"var(--noise3-primary-channel)",secondaryNote:"var(--noise3-secondary-note)",primaryNote:"var(--noise3-primary-note)"},{name:"noise4",secondaryChannel:"var(--noise4-secondary-channel)",primaryChannel:"var(--noise4-primary-channel)",secondaryNote:"var(--noise4-secondary-note)",primaryNote:"var(--noise4-primary-note)"},{name:"noise5",secondaryChannel:"var(--noise5-secondary-channel)",primaryChannel:"var(--noise5-primary-channel)",secondaryNote:"var(--noise5-secondary-note)",primaryNote:"var(--noise5-primary-note)"}]),$.h=document.head.appendChild(D.style({type:"text/css"}));const _=document.body.appendChild(D.div({style:"width:30px; height:30px; overflow: auto;"},D.div({style:"width:100%;height:40px"})));_.firstChild.clientWidth<30&&document.documentElement.classList.add("obtrusive-scrollbars"),document.body.removeChild(_),document.head.appendChild(D.style({type:"text/css"},`\n\n/* Note: "#" symbols need to be encoded as "%23" in SVG data urls, otherwise they are interpreted as fragment identifiers! */\n:root {\n\t--button-size: 26px;\n\t--settings-area-width: 192px;\n\t--play-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><path d="M -5 -8 L -5 8 L 8 0 z" fill="gray"/></svg>');\n\t--pause-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><rect x="-5" y="-7" width="4" height="14" fill="gray"/><rect x="3" y="-7" width="4" height="14" fill="gray"/></svg>');\n\t--record-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><circle cx="0" cy="0" r="6" fill="gray"/></svg>');\n\t--stop-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><rect x="-6" y="-6" width="12" height="12" fill="gray"/></svg>');\n\t--prev-bar-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><rect x="-6" y="-6" width="2" height="12" fill="gray"/><path d="M 6 -6 L 6 6 L -3 0 z" fill="gray"/></svg>');\n\t--next-bar-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><rect x="4" y="-6" width="2" height="12" fill="gray"/><path d="M -6 -6 L -6 6 L 3 0 z" fill="gray"/></svg>');\n\t--volume-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 26 26"><path d="M 4 16 L 4 10 L 8 10 L 13 5 L 13 21 L 8 16 z M 15 11 L 16 10 A 7.2 7.2 0 0 1 16 16 L 15 15 A 5.8 5.8 0 0 0 15 12 z M 18 8 L 19 7 A 11.5 11.5 0 0 1 19 19 L 18 18 A 10.1 10.1 0 0 0 18 8 z" fill="gray"/></svg>');\n\t--unmuted-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="3 3 20 20"><path d="M 4 16 L 4 10 L 8 10 L 13 5 L 13 21 L 8 16 z M 15 11 L 16 10 A 7.2 7.2 0 0 1 16 16 L 15 15 A 5.8 5.8 0 0 0 15 12 z M 18 8 L 19 7 A 11.5 11.5 0 0 1 19 19 L 18 18 A 10.1 10.1 0 0 0 18 8 z" fill="gray"/></svg>');\n\t--muted-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="3 3 20 20"><path d="M 4 16 L 4 10 L 8 10 L 13 5 L 13 21 L 8 16 z" fill="gray"/></svg>');\n\t--menu-down-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><path d="M -4 -2 L 4 -2 L 0 3 z" fill="gray"/></svg>');\n\t--select-arrows-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><path d="M -4 -3 L 4 -3 L 0 -8 z M -4 3 L 4 3 L 0 8 z" fill="gray"/></svg>');\n\t--file-page-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-5 -21 26 26"><path d="M 2 0 L 2 -16 L 10 -16 L 14 -12 L 14 0 z M 3 -1 L 13 -1 L 13 -11 L 9 -11 L 9 -15 L 3 -15 z" fill="gray"/></svg>');\n\t--edit-pencil-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-5 -21 26 26"><path d="M 0 0 L 1 -4 L 4 -1 z M 2 -5 L 10 -13 L 13 -10 L 5 -2 zM 11 -14 L 13 -16 L 14 -16 L 16 -14 L 16 -13 L 14 -11 z" fill="gray"/></svg>');\n\t--preferences-gear-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><path d="M 5.78 -1.6 L 7.93 -0.94 L 7.93 0.94 L 5.78 1.6 L 4.85 3.53 L 5.68 5.61 L 4.21 6.78 L 2.36 5.52 L 0.27 5.99 L -0.85 7.94 L -2.68 7.52 L -2.84 5.28 L -4.52 3.95 L -6.73 4.28 L -7.55 2.59 L -5.9 1.07 L -5.9 -1.07 L -7.55 -2.59 L -6.73 -4.28 L -4.52 -3.95 L -2.84 -5.28 L -2.68 -7.52 L -0.85 -7.94 L 0.27 -5.99 L 2.36 -5.52 L 4.21 -6.78 L 5.68 -5.61 L 4.85 -3.53 M 2.92 0.67 L 2.92 -0.67 L 2.35 -1.87 L 1.3 -2.7 L 0 -3 L -1.3 -2.7 L -2.35 -1.87 L -2.92 -0.67 L -2.92 0.67 L -2.35 1.87 L -1.3 2.7 L -0 3 L 1.3 2.7 L 2.35 1.87 z" fill="gray"/></svg>');\n\t--customize-dial-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"> \t\t\t<g transform="translate(0,1)" fill="gray"> \t\t\t\t<circle cx="0" cy="0" r="6.5" stroke="gray" stroke-width="1" fill="none"/> \t\t\t\t<rect x="-1" y="-5" width="2" height="4" transform="rotate(30)"/> \t\t\t\t<circle cx="-7.79" cy="4.5" r="0.75"/> \t\t\t\t<circle cx="-9" cy="0" r="0.75"/> \t\t\t\t<circle cx="-7.79" cy="-4.5" r="0.75"/> \t\t\t\t<circle cx="-4.5" cy="-7.79" r="0.75"/> \t\t\t\t<circle cx="0" cy="-9" r="0.75"/> \t\t\t\t<circle cx="4.5" cy="-7.79" r="0.75"/> \t\t\t\t<circle cx="7.79" cy="-4.5" r="0.75"/> \t\t\t\t<circle cx="9" cy="0" r="0.75"/> \t\t\t\t<circle cx="7.79" cy="4.5" r="0.75"/> \t\t\t</g> \t\t</svg>');\n\t--instrument-copy-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-5 -21 26 26"><path d="M 0 -15 L 1 -15 L 1 0 L 13 0 L 13 1 L 0 1 L 0 -15 z M 2 -1 L 2 -17 L 10 -17 L 14 -13 L 14 -1 z M 3 -2 L 13 -2 L 13 -12 L 9 -12 L 9 -16 L 3 -16 z" fill="currentColor"></path></svg>');\n\t--instrument-paste-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="0 0 26 26"><path d="M 8 18 L 6 18 L 6 5 L 17 5 L 17 7 M 9 8 L 16 8 L 20 12 L 20 22 L 9 22 z" stroke="currentColor" fill="none"></path><path d="M 9 3 L 14 3 L 14 6 L 9 6 L 9 3 z M 16 8 L 20 12 L 16 12 L 16 8 z" fill="currentColor"></path></svg>');\n\t--export-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><path fill="gray" d="M -8 3 L -8 8 L 8 8 L 8 3 L 6 3 L 6 6 L -6 6 L -6 3 z M 0 2 L -4 -2 L -1 -2 L -1 -8 L 1 -8 L 1 -2 L 4 -2 z"/></svg>');\n\t--close-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><path fill="gray" 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"/></svg>');\n\t--add-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><path fill="gray" 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"/></svg>');\n\t--zoom-in-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="-10 -10 20 20"><circle cx="-1" cy="-1" r="6" stroke-width="2" stroke="gray" fill="none"></circle><path stroke="gray" stroke-width="2" d="M 3 3 L 7 7 M -1 -4 L -1 2 M -4 -1 L 2 -1" fill="none"></path></svg>');\n\t--zoom-out-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="-10 -10 20 20"><circle cx="-1" cy="-1" r="6" stroke-width="2" stroke="gray" fill="none"></circle><path stroke="gray" stroke-width="2" d="M 3 3 L 7 7 M -4 -1 L 2 -1" fill="none"></path></svg>');\n\t--checkmark-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-13 -13 26 26"><path fill="gray" d="M -9 -2 L -8 -3 L -3 2 L 9 -8 L 10 -7 L -3 8 z"/></svg>');\n\t--drum-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="40" viewBox="0 0 32 40"> \t\t\t<defs> \t\t\t\t<linearGradient id="gold1" x1="0%" y1="0%" x2="100%" y2="0%"> \t\t\t\t\t<stop offset="0%" stop-color="%237e3302"/> \t\t\t\t\t<stop offset="40%" stop-color="%23ffec6b"/> \t\t\t\t\t<stop offset="100%" stop-color="%237e3302"/> \t\t\t\t</linearGradient> \t\t\t\t<linearGradient id="gold2" x1="0%" y1="0%" x2="100%" y2="0%"> \t\t\t\t\t<stop offset="0%" stop-color="%23faaf7d"/> \t\t\t\t\t<stop offset="15%" stop-color="%23fffba9"/> \t\t\t\t\t<stop offset="40%" stop-color="%23ffffe3"/> \t\t\t\t\t<stop offset="65%" stop-color="%23fffba9"/> \t\t\t\t\t<stop offset="100%" stop-color="%23faaf7d"/> \t\t\t\t</linearGradient> \t\t\t\t<radialGradient id="gold3" cx="0%" cy="0%" r="100%"> \t\t\t\t\t<stop offset="0%" stop-color="%23ffffe3"/> \t\t\t\t\t<stop offset="50%" stop-color="%23ffec6b"/> \t\t\t\t\t<stop offset="100%" stop-color="%237e3302"/> \t\t\t\t</radialGradient> \t\t\t\t<linearGradient id="red" x1="0%" y1="0%" x2="100%" y2="0%"> \t\t\t\t\t<stop offset="0%" stop-color="%23641919"/> \t\t\t\t\t<stop offset="40%" stop-color="%23cd2c2c"/> \t\t\t\t\t<stop offset="100%" stop-color="%23641919"/> \t\t\t\t</linearGradient> \t\t\t\t<radialGradient id="membrane"> \t\t\t\t\t<stop offset="10%" stop-color="%23cccccc" /> \t\t\t\t\t<stop offset="90%" stop-color="%23f6f6f7" /> \t\t\t\t\t<stop offset="100%" stop-color="%23999" /> \t\t\t\t</radialGradient> \t\t\t</defs> \t\t\t<ellipse cx="16" cy="26" rx="16" ry="14" fill="rgba(0,0,0,0.5)"/> \t\t\t<ellipse cx="16" cy="25" rx="16" ry="14" fill="url(%23gold1)"/> \t\t\t<rect x="0" y="23" width="32" height="2" fill="url(%23gold1)"/> \t\t\t<ellipse cx="16" cy="23" rx="16" ry="14" fill="url(%23gold2)"/> \t\t\t<ellipse cx="16" cy="23" rx="15" ry="13" fill="url(%23red)"/> \t\t\t<rect x="1" y="17" width="30" height="6" fill="url(%23red)"/> \t\t\t<rect x="5" y="27" width="1" height="5" rx="0.5" fill="rgba(0,0,0,0.5)"/> \t\t\t<rect x="15" y="31" width="2" height="5" rx="1" fill="rgba(0,0,0,0.5)"/> \t\t\t<rect x="26" y="27" width="1" height="5" rx="0.5" fill="rgba(0,0,0,0.5)"/> \t\t\t<rect x="5" y="26" width="1" height="5" rx="0.5" fill="url(%23gold3)"/> \t\t\t<rect x="15" y="30" width="2" height="5" rx="1" fill="url(%23gold3)"/> \t\t\t<rect x="26" y="26" width="1" height="5" rx="0.5" fill="url(%23gold3)"/> \t\t\t<ellipse cx="16" cy="18" rx="15" ry="13" fill="rgba(0,0,0,0.5)"/> \t\t\t<ellipse cx="16" cy="16" rx="16" ry="14" fill="url(%23gold1)"/> \t\t\t<rect x="0" y="14" width="32" height="2" fill="url(%23gold1)"/> \t\t\t<ellipse cx="16" cy="14" rx="16" ry="14" fill="url(%23gold2)"/> \t\t\t<ellipse cx="16" cy="14" rx="15" ry="13" fill="url(%23membrane)"/> \t\t</svg>');\n\t--piano-key-symbol: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="15" preserveAspectRatio="none" viewBox="0 -1 32 15"> \t\t\t<defs> \t\t\t\t<linearGradient id="shadow" x1="0%" y1="0%" x2="100%" y2="0%"> \t\t\t\t\t<stop offset="0%" stop-color="rgba(0,0,0,0.5)"/> \t\t\t\t\t<stop offset="100%" stop-color="transparent"/> \t\t\t\t</linearGradient> \t\t\t</defs> \t\t\t<rect x="-1" y="1" width="31" height="1" rx="0.6" fill="rgba(255,255,255,0.4)"/> \t\t\t<path d="M -1 11 L 30 11 L 30 2 L 33 -1 L 33 14 L -1 14 z" fill="rgba(0,0,0,0.7)"/> \t\t\t<rect x="-1" y="-1" width="19" height="15" fill="url(%23shadow)"/> \t\t</svg>');\n}\n\n\n.obtrusive-scrollbars, .obtrusive-scrollbars * {\n\tscrollbar-width: thin;\n\tscrollbar-color: ${$.uiWidgetBackground} ${$.editorBackground};\n}\n.obtrusive-scrollbars::-webkit-scrollbar, .obtrusive-scrollbars *::-webkit-scrollbar {\n\twidth: 12px;\n}\n.obtrusive-scrollbars::-webkit-scrollbar-track, .obtrusive-scrollbars *::-webkit-scrollbar-track {\n\tbackground: ${$.editorBackground};\n}\n.obtrusive-scrollbars::-webkit-scrollbar-thumb, .obtrusive-scrollbars *::-webkit-scrollbar-thumb {\n\tbackground-color: ${$.uiWidgetBackground};\n\tborder: 3px solid ${$.editorBackground};\n}\n\n\n.beepboxEditor {\n\tdisplay: grid;\n grid-template-columns: minmax(0, 1fr) max-content;\n grid-template-rows: max-content 1fr; /* max-content minmax(0, 1fr); Chrome 80 grid layout regression. https://bugs.chromium.org/p/chromium/issues/detail?id=1050307 */\n grid-template-areas: "pattern-area settings-area" "track-area settings-area";\n\tgrid-column-gap: 6px;\n\tgrid-row-gap: 6px;\n\tposition: relative;\n\ttouch-action: manipulation;\n\tcursor: default;\n\tfont-size: 13px;\n\toverflow: hidden;\n\tcolor: ${$.primaryText};\n\tbackground: ${$.editorBackground};\n}\n\n.beepboxEditor .noSelection {\n\t-webkit-touch-callout: none;\n\t-webkit-user-select: none;\n\t-moz-user-select: none;\n\t-ms-user-select: none;\n\tuser-select: none;\n}\n\n.beepboxEditor div {\n\tmargin: 0;\n\tpadding: 0;\n}\n\n.beepboxEditor .pattern-area {\n\tgrid-area: pattern-area;\n\theight: 481px;\n\tdisplay: flex;\n\tflex-direction: row;\n\tposition: relative;\n}\n\n.beepboxEditor .track-area {\n\tgrid-area: track-area;\n}\n\n.beepboxEditor .loopEditor {\n\theight: 20px;\n\tposition: sticky;\n\tbottom: 0;\n\tpadding: 5px 0;\n\tbackground-color: ${$.editorBackground};\n}\n\n.beepboxEditor .settings-area {\n\tgrid-area: settings-area;\n\tdisplay: grid;\n grid-template-columns: auto;\n grid-template-rows: min-content min-content min-content min-content min-content;\n grid-template-areas: "version-area" "play-pause-area" "menu-area" "song-settings-area" "instrument-settings-area";\n\tgrid-column-gap: 6px;\n}\n\n.beepboxEditor .version-area{ grid-area: version-area; }\n.beepboxEditor .play-pause-area{ grid-area: play-pause-area; }\n.beepboxEditor .menu-area{ grid-area: menu-area; }\n.beepboxEditor .song-settings-area{ grid-area: song-settings-area; }\n.beepboxEditor .instrument-settings-area{ grid-area: instrument-settings-area; }\n\n.beepboxEditor .tip {\n\tcursor: help;\n\tcolor: ${$.secondaryText};\n\ttext-decoration: none;\n}\n\n.beepboxEditor .tip:hover {\n\tcolor: ${$.linkAccent};\n\ttext-decoration: underline;\n}\n.beepboxEditor .tip:active {\n\tcolor: ${$.primaryText};\n}\n\n.beepboxEditor .volume-speaker {\n\tflex-shrink: 0;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: ${$.secondaryText};\n\t-webkit-mask-image: var(--volume-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--volume-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor .drum-button {\n\tflex: 1;\n\tbackground-color: transparent;\n\tbackground-image: var(--drum-symbol);\n\tbackground-repeat: no-repeat;\n\tbackground-position: center;\n}\n\n.beepboxEditor .piano-button {\n\tflex: 1;\n\tposition: relative;\n\tdisplay: flex;\n\talign-items: center;\n}\n.beepboxEditor .piano-button::before {\n\tcontent: "";\n\tposition: absolute;\n\tleft: 0;\n\ttop: 0;\n\twidth: 100%;\n\theight: 100%;\n\tpointer-events: none;\n\tbackground-image: var(--piano-key-symbol);\n\tbackground-repeat: no-repeat;\n\tbackground-position: center;\n\tbackground-size: 100% 115.38%;\n}\n.beepboxEditor .piano-button.disabled::after {\n\tcontent: "";\n\tposition: absolute;\n\tright: 0;\n\ttop: 0;\n\twidth: 70%;\n\theight: 100%;\n\tpointer-events: none;\n\tbackground: ${$.editorBackground};\n\t-webkit-mask-image: linear-gradient(90deg, transparent 0%, gray 70%, gray 100%);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: linear-gradient(90deg, transparent 0%, gray 70%, gray 100%);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor .piano-button.pressed, .beepboxEditor .drum-button.pressed {\n\tfilter: brightness(0.5);\n}\n\n.beepboxEditor .customize-instrument {\n\tmargin: 2px 0;\n}\n.beepboxEditor .customize-instrument::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--customize-dial-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--customize-dial-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor .instrumentCopyPasteRow {\n\tgap: 2px;\n}\n\n.beepboxEditor .copy-instrument {\n\tmargin: 2px 0;\n\tflex-grow: 1;\n}\n.beepboxEditor .copy-instrument::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--instrument-copy-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--instrument-copy-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor .paste-instrument {\n\tmargin: 2px 0;\n\tflex-grow: 1;\n}\n.beepboxEditor .paste-instrument::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--instrument-paste-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--instrument-paste-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor .envelopeEditor {\n\tdisplay: flex;\n\tflex-direction: column;\n}\n\n.beepboxEditor .envelope-row {\n\tdisplay: flex;\n\tmargin: 2px 0;\n\tgap: 2px;\n}\n\n.beepboxEditor .add-envelope {\n\twidth: var(--button-size);\n}\n.beepboxEditor .add-envelope::before {\n\tcontent: "";\n\tposition: absolute;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tleft: 0;\n\ttop: 0;\n\tpointer-events: none;\n\tbackground: currentColor;\n\tmask-image: var(--add-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n\t-webkit-mask-image: var(--add-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n}\n.beepboxEditor .add-envelope:disabled {\n\tvisibility: hidden;\n}\n\n.beepboxEditor .effects-menu {\n\twidth: var(--button-size);\n\tposition: relative;\n}\n.beepboxEditor .effects-menu::before {\n\tcontent: "";\n\tposition: absolute;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tleft: 0;\n\ttop: 0;\n\tpointer-events: none;\n\tbackground: currentColor;\n\tmask-image: var(--menu-down-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n\t-webkit-mask-image: var(--menu-down-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n}\n\n.beepboxEditor .zoomInButton, .beepboxEditor .zoomOutButton {\n\twidth: var(--button-size);\n\tposition: absolute;\n\tright: 10px;\n}\n.beepboxEditor .zoomInButton {\n\ttop: 10px;\n}\n.beepboxEditor .zoomOutButton {\n\ttop: 50px;\n}\n.beepboxEditor .zoomInButton::before {\n\tcontent: "";\n\tposition: absolute;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tleft: 0;\n\ttop: 0;\n\tpointer-events: none;\n\tbackground: currentColor;\n\tmask-image: var(--zoom-in-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n\t-webkit-mask-image: var(--zoom-in-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n}\n.beepboxEditor .zoomOutButton::before {\n\tcontent: "";\n\tposition: absolute;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tleft: 0;\n\ttop: 0;\n\tpointer-events: none;\n\tbackground: currentColor;\n\tmask-image: var(--zoom-out-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n\t-webkit-mask-image: var(--zoom-out-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n}\n\n.beepboxEditor .delete-envelope {\n\twidth: var(--button-size);\n\tflex-shrink: 0;\n\tflex-grow: 0;\n}\n.beepboxEditor .delete-envelope::before {\n\tcontent: "";\n\tposition: absolute;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tleft: 0;\n\ttop: 0;\n\tpointer-events: none;\n\tbackground: currentColor;\n\tmask-image: var(--close-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n\t-webkit-mask-image: var(--close-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n}\n.beepboxEditor .delete-envelope:disabled {\n\tvisibility: hidden;\n}\n\n.beepboxEditor .menu.file::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--file-page-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--file-page-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor .menu.edit::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--edit-pencil-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--edit-pencil-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor .menu.preferences::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--preferences-gear-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--preferences-gear-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor .mute-button::before {\n\tcontent: "";\n\tpointer-events: none;\n\twidth: 100%;\n\theight: 100%;\n\tbackground: ${$.primaryText};\n\tdisplay: inline-block;\n\t-webkit-mask-image: var(--unmuted-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\t-webkit-mask-size: contain;\n\tmask-image: var(--unmuted-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n\tmask-size: contain;\n}\n\n.beepboxEditor .mute-button.muted::before {\n\tbackground: ${$.editorBackground};\n\t-webkit-mask-image: var(--muted-symbol);\n\tmask-image: var(--muted-symbol);\n}\n\n.beepboxEditor .promptContainer {\n\tposition: absolute;\n\ttop: 0;\n\tleft: 0;\n\twidth: 100%;\n\theight: 100%;\n\tdisplay: flex;\n\tjustify-content: center;\n\talign-items: center;\n\tz-index: 100;\n}\n\n.beepboxEditor .promptContainer::before {\n\tcontent: "";\n\tposition: absolute;\n\ttop: 0;\n\tleft: 0;\n\twidth: 100%;\n\theight: 100%;\n\tbackground: ${$.editorBackground};\n\topacity: 0.5;\n\tdisplay: flex;\n}\n\n.beepboxEditor .prompt {\n\tmargin: auto;\n\ttext-align: center;\n\tbackground: ${$.editorBackground};\n\tborder-radius: 15px;\n\tborder: 4px solid ${$.uiWidgetBackground};\n\tcolor: ${$.primaryText};\n\tpadding: 20px;\n\tdisplay: flex;\n\tflex-direction: column;\n\tposition: relative;\n\tbox-shadow: 5px 5px 20px 10px rgba(0,0,0,0.5);\n}\n\n.beepboxEditor .prompt > *:not(:first-child):not(.cancelButton) {\n\tmargin-top: 1.5em;\n}\n\n.beepboxEditor .prompt h2 {\n\tfont-size: 2em;\n\tmargin: 0 16px;\n\tfont-weight: normal;\n}\n\n.beepboxEditor .prompt p {\n\ttext-align: left;\n\tmargin: 1em 0;\n}\n\n.beepboxEditor .prompt label {\n\tcursor: pointer;\n}\n\n.beepboxEditor .prompt.recordingSetupPrompt p {\n\tmargin-top: 0.75em;\n\tmargin-bottom: 0;\n}\n\n.beepboxEditor .prompt.recordingSetupPrompt > label:not(:first-child):not(.cancelButton) {\n\tmargin: 2px 0;\n}\n\n.beepboxEditor .layout-option {\n\tdisplay: flex;\n\tflex-direction: column;\n\tflex: 1;\n\tcursor: pointer;\n\tcolor: ${$.secondaryText};\n}\n\n.beepboxEditor .layout-option input {\n\tdisplay: none;\n}\n\n.beepboxEditor .layout-option input:checked ~ * {\n\tcolor: ${$.primaryText};\n}\n\n.beepboxEditor .selectContainer {\n\tposition: relative;\n}\n.beepboxEditor .selectContainer:not(.menu)::after {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tright: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: 14px;\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--select-arrows-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--select-arrows-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n.beepboxEditor .selectContainer.menu::after {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tright: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--menu-down-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--menu-down-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n.beepboxEditor select {\n\tmargin: 0;\n\tpadding: 0 4px;\n\tdisplay: block;\n\theight: var(--button-size);\n\tborder: none;\n\tborder-radius: 5px;\n\tbackground: ${$.uiWidgetBackground};\n\tcolor: inherit;\n\tfont-size: inherit;\n\tcursor: pointer;\n\tfont-family: inherit;\n\tfont-weight: inherit;\n\n\t-webkit-appearance:none;\n\t-moz-appearance: none;\n\tappearance: none;\n}\n.beepboxEditor .menu select {\n\tpadding: 0 var(--button-size);\n}\n.beepboxEditor select:focus {\n\tbackground: ${$.uiWidgetFocus};\n\toutline: none;\n}\n.beepboxEditor .menu select {\n\ttext-align: center;\n\ttext-align-last: center;\n}\n.beepboxEditor .settings-area select {\n width: 100%;\n}\n\n/* This makes it look better in firefox on my computer... What about others?\n@-moz-document url-prefix() {\n\t.beepboxEditor select { padding: 0 2px; }\n}\n*/\n.beepboxEditor button {\n\tmargin: 0;\n\tposition: relative;\n\theight: var(--button-size);\n\tborder: none;\n\tborder-radius: 5px;\n\tbackground: ${$.uiWidgetBackground};\n\tcolor: inherit;\n\tfont-size: inherit;\n\tfont-family: inherit;\n\tfont-weight: inherit;\n\tcursor: pointer;\n}\n.beepboxEditor button:focus {\n\tbackground: ${$.uiWidgetFocus};\n\toutline: none;\n}\n\n.beepboxEditor button.cancelButton {\n\tfloat: right;\n\twidth: var(--button-size);\n\tposition: absolute;\n\ttop: 8px;\n\tright: 8px;\n}\n\n.beepboxEditor .playback-bar-controls {\n\tdisplay: grid;\n\tgrid-template-columns: minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr);\n\tgrid-template-rows: min-content;\n\tgrid-column-gap: 4px;\n}\n\n.beepboxEditor button.playButton::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--play-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--play-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n.beepboxEditor button.pauseButton::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--pause-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--pause-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n.beepboxEditor button.recordButton::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--record-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--record-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n.beepboxEditor button.stopButton::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 0;\n\ttop: 50%;\n\ttransform: translateY(-50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--stop-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--stop-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor button.prevBarButton::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 50%;\n\ttop: 50%;\n\ttransform: translate(-50%, -50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--prev-bar-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--prev-bar-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor button.nextBarButton::before {\n\tcontent: "";\n\tflex-shrink: 0;\n\tposition: absolute;\n\tleft: 50%;\n\ttop: 50%;\n\ttransform: translate(-50%, -50%);\n\tpointer-events: none;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--next-bar-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--next-bar-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor button.playButton, .beepboxEditor button.pauseButton, .beepboxEditor button.recordButton, .beepboxEditor button.stopButton, .beepboxEditor button.okayButton, .beepboxEditor button.exportButton {\n\tpadding-left: var(--button-size);\n}\n.beepboxEditor button.playButton, .beepboxEditor button.pauseButton, .beepboxEditor button.recordButton {\n\tgrid-column-start: 1;\n\tgrid-column-end: 3;\n}\n.beepboxEditor button.stopButton {\n\tgrid-column-start: 1;\n\tgrid-column-end: 5;\n}\n.beepboxEditor button.prevBarButton {\n\tgrid-column-start: 3;\n\tgrid-column-end: 4;\n}\n.beepboxEditor button.nextBarButton {\n\tgrid-column-start: 4;\n\tgrid-column-end: 5;\n}\n\n.beepboxEditor button.playButton.shrunk, .beepboxEditor button.recordButton.shrunk {\n\tpadding: 0;\n}\n.beepboxEditor button.playButton.shrunk::before, .beepboxEditor button.recordButton.shrunk::before {\n\tleft: 50%;\n\ttop: 50%;\n\ttransform: translate(-50%, -50%);\n}\n.beepboxEditor button.playButton.shrunk span, .beepboxEditor button.recordButton.shrunk span {\n\tdisplay: none;\n}\n.beepboxEditor button.playButton.shrunk {\n\tgrid-column-start: 1;\n\tgrid-column-end: 2;\n}\n.beepboxEditor button.recordButton.shrunk {\n\tgrid-column-start: 2;\n\tgrid-column-end: 3;\n}\n\n.beepboxEditor button.cancelButton::before {\n\tcontent: "";\n\tposition: absolute;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tleft: 0;\n\ttop: 0;\n\tpointer-events: none;\n\tbackground: currentColor;\n\tmask-image: var(--close-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n\t-webkit-mask-image: var(--close-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n}\n\n.beepboxEditor button.okayButton::before {\n\tcontent: "";\n\tposition: absolute;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tleft: 0;\n\ttop: 0;\n\tpointer-events: none;\n\tbackground: currentColor;\n\t-webkit-mask-image: var(--checkmark-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n\tmask-image: var(--checkmark-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n}\n\n.beepboxEditor button.exportButton::before {\n\tcontent: "";\n\tposition: absolute;\n\twidth: var(--button-size);\n\theight: var(--button-size);\n\tleft: 0;\n\ttop: 0;\n\tpointer-events: none;\n\tbackground: currentColor;\n\tmask-image: var(--export-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n\t-webkit-mask-image: var(--export-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n}\n\n.beepboxEditor .instrument-bar {\n\tdisplay: flex;\n\tgap: 2px;\n}\n\n.beepboxEditor .instrument-bar button {\n\tflex-grow: 1;\n\tmin-width: 0;\n\tpadding: 0;\n\tflex-basis: 0;\n\tdisplay: flex;\n\talign-items: center;\n\tjustify-content: center;\n\tcolor: var(--text-color-lit);\n}\n\n.beepboxEditor .instrument-bar .remove-instrument, .beepboxEditor .instrument-bar .add-instrument {\n\tmax-width: var(--button-size);\n}\n\n.beepboxEditor .instrument-bar > :not(:first-child) {\n\tborder-top-left-radius: 0;\n\tborder-bottom-left-radius: 0;\n}\n\n.beepboxEditor .instrument-bar > :not(.last-button) {\n\tborder-top-right-radius: 0;\n\tborder-bottom-right-radius: 0;\n}\n\n.beepboxEditor .instrument-bar .selected-instrument {\n\tbackground: var(--background-color-lit);\n\tcolor: ${$.invertedText};\n}\n\n.beepboxEditor .instrument-bar .deactivated {\n\tbackground: ${$.editorBackground};\n\tcolor: var(--text-color-dim);\n}\n\n.beepboxEditor .instrument-bar .deactivated.selected-instrument {\n\tbackground: var(--background-color-dim);\n\tcolor: ${$.invertedText};\n}\n\n.beepboxEditor .instrument-bar .remove-instrument::before {\n\tcontent: "";\n\tposition: absolute;\n\twidth: 100%;\n\theight: var(--button-size);\n\tleft: 0;\n\ttop: 0;\n\tpointer-events: none;\n\tbackground: currentColor;\n\tmask-image: var(--close-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n\t-webkit-mask-image: var(--close-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n}\n\n.beepboxEditor .instrument-bar .add-instrument::before {\n\tcontent: "";\n\tposition: absolute;\n\twidth: 100%;\n\theight: var(--button-size);\n\tleft: 0;\n\ttop: 0;\n\tpointer-events: none;\n\tbackground: currentColor;\n\tmask-image: var(--add-symbol);\n\tmask-repeat: no-repeat;\n\tmask-position: center;\n\t-webkit-mask-image: var(--add-symbol);\n\t-webkit-mask-repeat: no-repeat;\n\t-webkit-mask-position: center;\n}\n\n.beepboxEditor canvas {\n\toverflow: hidden;\n\tposition: absolute;\n\tdisplay: block;\n}\n\n.beepboxEditor .trackContainer {\n\tflex-grow: 1;\n}\n\n.beepboxEditor .trackAndMuteContainer {\n\tdisplay: flex;\n\talign-items: flex-start;\n\twidth: 100%;\n\tmin-height: 0;\n\tflex: 1;\n\toverflow-x: hidden;\n\tposition: relative;\n}\n\n.beepboxEditor .channelRow {\n\tdisplay: flex;\n}\n\n.beepboxEditor .channelBox {\n\tdisplay: flex;\n\ttext-align: center;\n\talign-items: center;\n\tjustify-content: center;\n\tbox-sizing: border-box;\n\tpadding-top: 1px;\n}\n\n.beepboxEditor .channelBoxLabel {\n\tfont-size: 20px;\n\tfont-family: sans-serif;\n\tfont-weight: bold;\n}\n\n.beepboxEditor .muteEditor {\n\twidth: 32px;\n\tflex-shrink: 0;\n\tdisplay: flex;\n\tflex-direction: column;\n\talign-items: stretch;\n\tposition: sticky;\n\tleft: 0;\n\tz-index: 1;\n\tbackground: ${$.editorBackground};\n}\n\n.beepboxEditor .selectRow, .beepboxEditor .instrumentCopyPasteRow {\n\tmargin: 2px 0;\n\theight: var(--button-size);\n\tdisplay: flex;\n\tflex-direction: row;\n\talign-items: center;\n\tjustify-content: space-between;\n}\n\n.beepboxEditor .selectRow > :last-child {\n\twidth: 62.5%;\n\tflex-shrink: 0;\n}\n\n.beepboxEditor .menu-area {\n\tdisplay: flex;\n\tflex-direction: column;\n}\n.beepboxEditor .menu-area > * {\n\tmargin: 2px 0;\n}\n.beepboxEditor .menu-area > button {\n\tpadding: 0 var(--button-size);\n\twhite-space: nowrap;\n}\n\n.beepboxEditor .song-settings-area {\n\tdisplay: flex;\n\tflex-direction: column;\n}\n\n.beepboxEditor .editor-controls {\n\tflex-shrink: 0;\n\tdisplay: flex;\n\tflex-direction: column;\n}\n\n.beepboxEditor .instrument-settings-area {\n\tdisplay: flex;\n\tflex-direction: column;\n}\n\n.beepboxEditor .editor-right-side-top > *, .beepboxEditor .editor-right-side-bottom > * {\n\tflex-shrink: 0;\n}\n\n.beepboxEditor .pitchShiftMarkerContainer {\n\tbox-sizing: border-box;\n\tdisplay: flex;\n\theight: 100%;\n\tleft: 3px;\n\tright: 3px;\n\tposition: absolute;\n\talign-items: center;\n\tpointer-events: none;\n}\n\n.beepboxEditor .pitchShiftMarker {\n\twidth: 0;\n\theight: 0;\n\tposition: absolute;\n}\n\n.beepboxEditor .pitchShiftMarker::before {\n\tcontent: "";\n\twidth: 2px;\n\theight: 20px;\n\ttransform: translate(-50%, -50%);\n\tposition: absolute;\n\tbackground: currentColor;\n\tborder-radius: 3px;\n}\n\n.beepboxEditor input[type=text], .beepboxEditor input[type=number] {\n\tfont-size: inherit;\n\tfont-weight: inherit;\n\tfont-family: inherit;\n\tbackground: transparent;\n\tborder: 1px solid ${$.uiWidgetFocus};\n\tcolor: ${$.primaryText};\n}\n\n.beepboxEditor input[type=text]::selection, .beepboxEditor input[type=number]::selection {\n\tbackground-color: ${$.textSelection};\n\tcolor: ${$.primaryText};\n}\n\n.beepboxEditor input[type=checkbox] {\n transform: scale(1.5);\n}\n\n.beepboxEditor input[type=range] {\n\t-webkit-appearance: none;\n\tcolor: inherit;\n\twidth: 100%;\n\theight: var(--button-size);\n\tfont-size: inherit;\n\tmargin: 0;\n\tcursor: pointer;\n\tbackground: none;\n\ttouch-action: pan-y;\n}\n.beepboxEditor input[type=range]:focus {\n\toutline: none;\n}\n.beepboxEditor input[type=range]::-webkit-slider-runnable-track {\n\twidth: 100%;\n\theight: 6px;\n\tcursor: pointer;\n\tbackground: ${$.uiWidgetBackground};\n}\n.beepboxEditor input[type=range]::-webkit-slider-thumb {\n\theight: var(--button-size);\n\twidth: 6px;\n\tborder-radius: 3px;\n\tbackground: currentColor;\n\tcursor: pointer;\n\t-webkit-appearance: none;\n\tmargin-top: -10px;\n}\n.beepboxEditor input[type=range]:focus::-webkit-slider-runnable-track {\n\tbackground: ${$.uiWidgetFocus};\n}\n.beepboxEditor input[type=range]::-moz-range-track {\n\twidth: 100%;\n\theight: 6px;\n\tcursor: pointer;\n\tbackground: ${$.uiWidgetBackground};\n}\n.beepboxEditor input[type=range]:focus::-moz-range-track {\n\tbackground: ${$.uiWidgetFocus};\n}\n.beepboxEditor input[type=range]::-moz-range-thumb {\n\theight: var(--button-size);\n\twidth: 6px;\n\tborder-radius: 3px;\n\tborder: none;\n\tbackground: currentColor;\n\tcursor: pointer;\n}\n.beepboxEditor input[type=range]::-ms-track {\n\twidth: 100%;\n\theight: 6px;\n\tcursor: pointer;\n\tbackground: ${$.uiWidgetBackground};\n\tborder-color: transparent;\n}\n.beepboxEditor input[type=range]:focus::-ms-track {\n\tbackground: ${$.uiWidgetFocus};\n}\n.beepboxEditor input[type=range]::-ms-thumb {\n\theight: var(--button-size);\n\twidth: 6px;\n\tborder-radius: 3px;\n\tbackground: currentColor;\n\tcursor: pointer;\n}\n\n/* wide screen */\n@media (min-width: 711px) {\n\t#beepboxEditorContainer {\n\t\tdisplay: table;\n\t}\n\t.beepboxEditor {\n\t\tflex-direction: row;\n\t}\n\t.beepboxEditor:focus-within {\n\t\toutline: 3px solid ${$.uiWidgetBackground};\n\t}\n\t.beepboxEditor .trackAndMuteContainer {\n\t\twidth: 512px;\n\t}\n\t.beepboxEditor .play-pause-area {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t}\n\t.beepboxEditor .playback-bar-controls {\n\t\tmargin: 2px 0;\n\t}\n\t.beepboxEditor .playback-volume-controls {\n\t\tdisplay: flex;\n\t\tflex-direction: row;\n\t\tmargin: 2px 0;\n\t\talign-items: center;\n\t}\n\t.beepboxEditor .settings-area {\n\t\twidth: var(--settings-area-width);\n\t}\n}\n\n/* narrow screen */\n@media (max-width: 710px) {\n\t.beepboxEditor {\n\t\tgrid-template-columns: minmax(0, 1fr);\n\t\tgrid-template-rows: min-content 6px min-content min-content;\n\t\tgrid-template-areas: "pattern-area" "." "track-area" "settings-area";\n\t\tgrid-row-gap: 0;\n\t}\n\t.beepboxEditor .settings-area {\n\t\tgrid-template-columns: minmax(0, 1fr) minmax(0, 1fr);\n\t\tgrid-template-rows: min-content min-content 1fr min-content;\n\t\tgrid-template-areas:\n\t\t\t"play-pause-area play-pause-area"\n\t\t\t"menu-area instrument-settings-area"\n\t\t\t"song-settings-area instrument-settings-area"\n\t\t\t"version-area version-area";\n\t\tgrid-column-gap: 8px;\n\t\tmargin: 0 4px;\n\t}\n\t.beepboxEditor:focus-within {\n\t\toutline: none;\n\t}\n\t.beepboxEditor .pattern-area {\n\t\tmax-height: 75vh;\n\t}\n\t.beepboxEditor .trackAndMuteContainer {\n\t\toverflow-x: auto;\n\t}\n\t.beepboxEditor .barScrollBar {\n\t\tdisplay: none;\n\t}\n\t.beepboxEditor .play-pause-area {\n\t\tdisplay: grid;\n\t\tgrid-template-columns: minmax(0, 1fr) minmax(0, 1fr);\n\t\tgrid-column-gap: 8px;\n\t\tmargin: 2px 0;\n\t}\n\t.beepboxEditor .playback-bar-controls {\n\t\tflex-grow: 1;\n\t}\n\t.beepboxEditor .playback-volume-controls {\n\t\tdisplay: flex;\n\t\tflex-direction: row;\n\t\talign-items: center;\n\t\tflex-grow: 1;\n\t}\n}\n\n`));class U{static setLayout(t){this.h.textContent=this.l[t]}}function V(t,e){for(let i=0;i<t.length;i++)t[i]*=e}function j(t){if(!function(t){return!(!t||t&t-1)}(t))throw new Error("FFT array length must be a power of 2.");return Math.round(Math.log(t)/Math.log(2))}function W(t,e){const i=j(e);if(e<4)throw new Error("FFT array length must be at least 4.");for(let s=i-1;s>=2;s--){const i=1<<s,n=i>>1,o=i<<1,r=2*Math.PI/o,h=Math.cos(r),a=Math.sin(r),l=2*h;for(let s=0;s<e;s+=o){const e=s,o=e+n,r=e+i,c=r+n,u=r+i,f=t[e],p=t[r];t[e]=f+p,t[o]*=2,t[r]=f-p,t[c]*=2;let d=h,m=-a,y=1,g=0;for(let i=1;i<n;i++){const s=e+i,n=r-i,o=r+i,h=u-i,a=t[s],c=t[n],f=t[o],p=t[h],b=a-c,w=f+p;t[s]=a+c,t[n]=p-f,t[o]=b*d-w*m,t[h]=w*d+b*m;const v=l*d-y,k=l*m-g;y=d,g=m,d=v,m=k}}}for(let i=0;i<e;i+=4){const e=i+1,s=i+2,n=i+3,o=t[i],r=2*t[e],h=t[s],a=2*t[n],l=o+h,c=o-h;t[i]=l+r,t[e]=l-r,t[s]=c+a,t[n]=c-a}!function(t,e){const i=j(e);if(i>16)throw new Error("FFT array length must not be greater than 2^16.");const s=16-i;for(let i=0;i<e;i++){let e;if(e=(43690&i)>>1|(21845&i)<<1,e=(52428&e)>>2|(13107&e)<<2,e=(61680&e)>>4|(3855&e)<<4,e=(e>>8|(255&e)<<8)>>s,e>i){let s=t[i];t[i]=t[e],t[e]=s}}}(t,e)}U.l={small:"",long:`\t\t\t/* long layout */\n\t\t\t@media (min-width: 711px) {\n\t\t\t\t#beepboxEditorContainer {\n\t\t\t\t\tmax-width: initial;\n\t\t\t\t\theight: 100vh;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor {\n\t\t\t\t\twidth: 100%;\n\t\t\t\t\theight: 100vh;\n\t\t\t\t\tgrid-template-columns: minmax(0, 1fr) 390px; /* minmax(0, 1fr) min-content; Chrome 80 grid layout regression. https://bugs.chromium.org/p/chromium/issues/detail?id=1050307 */\n\t\t\t\t\tgrid-template-rows: minmax(481px, 1fr) minmax(0, min-content);\n\t\t\t\t\tgrid-template-areas: "pattern-area settings-area" "track-area track-area";\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .pattern-area {\n\t\t\t\t\twidth: 100%;\n\t\t\t\t\theight: 100%;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .track-area {\n\t\t\t\t\twidth: 100%;\n\t\t\t\t\tdisplay: flex;\n\t\t\t\t\tflex-direction: column;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer {\n\t\t\t\t\twidth: 100%;\n\t\t\t\t\tmin-height: 0;\n\t\t\t\t\tflex: 1;\n\t\t\t\t\toverflow: auto;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .instrument-settings-area {\n\t\t\t\t\toverflow-y: auto;\n\t\t\t\t\tposition: relative;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .instrument-settings-area > .editor-controls {\n\t\t\t\t\tposition: absolute;\n\t\t\t\t\twidth: 100%;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .song-settings-area {\n\t\t\t\t\toverflow-y: auto;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t.beepboxEditor .settings-area {\n\t\t\t\t\twidth: 390px;\n\t\t\t\t\tgrid-template-columns: minmax(0, 1fr) minmax(0, 1fr);\n\t\t\t\t\tgrid-template-rows: auto auto auto minmax(0, 1fr);\n\t\t\t\t\tgrid-template-areas:\n\t\t\t\t\t\t"instrument-settings-area version-area"\n\t\t\t\t\t\t"instrument-settings-area play-pause-area"\n\t\t\t\t\t\t"instrument-settings-area menu-area"\n\t\t\t\t\t\t"instrument-settings-area song-settings-area";\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t.beepboxEditor .barScrollBar {\n\t\t\t\t\tdisplay: none;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackContainer {\n\t\t\t\t\toverflow: visible;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer {\n\t\t\t\t\tscrollbar-width: auto;\n\t\t\t\t\tscrollbar-color: ${$.uiWidgetBackground} ${$.editorBackground};\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer::-webkit-scrollbar {\n\t\t\t\t\twidth: 20px;\n\t\t\t\t\theight: 20px;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer::-webkit-scrollbar-track {\n\t\t\t\t\tbackground: ${$.editorBackground};\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer::-webkit-scrollbar-thumb {\n\t\t\t\t\tbackground-color: ${$.uiWidgetBackground};\n\t\t\t\t\tborder: 3px solid ${$.editorBackground};\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer::-webkit-scrollbar-corner {\n\t\t\t\t\tbackground-color: ${$.editorBackground};\n\t\t\t\t}\n\t\t\t}\n\t\t`,tall:`\t\t\t/* tall layout */\n\t\t\t@media (min-width: 711px) {\n\t\t\t\t#beepboxEditorContainer {\n\t\t\t\t\tmax-width: initial;\n\t\t\t\t\theight: 100vh;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor {\n\t\t\t\t\twidth: 100%;\n\t\t\t\t\theight: 100vh;\n\t\t\t\t\tgrid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 192px;\n\t\t\t\t\tgrid-template-rows: 1fr;\n\t\t\t\t\tgrid-template-areas: "track-area pattern-area settings-area";\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .pattern-area {\n\t\t\t\t\twidth: 100%;\n\t\t\t\t\theight: 100%;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .track-area {\n\t\t\t\t\twidth: 100%;\n\t\t\t\t\theight: 100%;\n\t\t\t\t\tdisplay: flex;\n\t\t\t\t\tflex-direction: column;\n\t\t\t\t\tjustify-content: center;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer {\n\t\t\t\t\twidth: 100%;\n\t\t\t\t\tmin-height: 0;\n\t\t\t\t\tflex: 0;\n\t\t\t\t\toverflow: auto;\n\t\t\t\t\tflex-basis: initial;\n\t\t\t\t\tflex-grow: 0;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .instrument-settings-area > .editor-controls {\n\t\t\t\t\tposition: absolute;\n\t\t\t\t\twidth: 100%;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t.beepboxEditor .settings-area {\n\t\t\t\t\twidth: 192px;\n\t\t\t\t\tposition: relative;\n\t\t\t\t\toverflow-y: auto;\n\t\t\t\t\tgrid-template-columns: minmax(0, 1fr);\n\t\t\t\t\tgrid-template-rows: auto auto auto auto minmax(0, 1fr);\n\t\t\t\t\tgrid-template-areas:\n\t\t\t\t\t\t"version-area"\n\t\t\t\t\t\t"play-pause-area"\n\t\t\t\t\t\t"menu-area"\n\t\t\t\t\t\t"song-settings-area"\n\t\t\t\t\t\t"instrument-settings-area";\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .version-area {\n\t\t\t\t\tposition: sticky;\n\t\t\t\t\ttop: 0;\n\t\t\t\t\tz-index: 1;\n\t\t\t\t\tbackground: ${$.editorBackground};\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .play-pause-area {\n\t\t\t\t\tposition: sticky;\n\t\t\t\t\ttop: 22px;\n\t\t\t\t\tz-index: 1;\n\t\t\t\t\tbackground: ${$.editorBackground};\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .menu-area {\n\t\t\t\t\tposition: sticky;\n\t\t\t\t\ttop: 82px;\n\t\t\t\t\tz-index: 1;\n\t\t\t\t\tbackground: ${$.editorBackground};\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t.beepboxEditor .barScrollBar {\n\t\t\t\t\tdisplay: none;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackContainer {\n\t\t\t\t\toverflow: visible;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer {\n\t\t\t\t\tscrollbar-width: auto;\n\t\t\t\t\tscrollbar-color: ${$.uiWidgetBackground} ${$.editorBackground};\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer::-webkit-scrollbar {\n\t\t\t\t\twidth: 20px;\n\t\t\t\t\theight: 20px;\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer::-webkit-scrollbar-track {\n\t\t\t\t\tbackground: ${$.editorBackground};\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer::-webkit-scrollbar-thumb {\n\t\t\t\t\tbackground-color: ${$.uiWidgetBackground};\n\t\t\t\t\tborder: 3px solid ${$.editorBackground};\n\t\t\t\t}\n\t\t\t\t.beepboxEditor .trackAndMuteContainer::-webkit-scrollbar-corner {\n\t\t\t\t\tbackground-color: ${$.editorBackground};\n\t\t\t\t}\n\t\t\t}\n\t\t`},U.h=document.head.appendChild(D.style({type:"text/css"}));class K{constructor(){this.u=1,this.m=[void 0],this.g=0,this.v=0,this.k=0}pushFront(t){this.k>=this.u&&this.M(),this.v=this.v-1&this.g,this.m[this.v]=t,this.k++}pushBack(t){this.k>=this.u&&this.M(),this.m[this.v+this.k&this.g]=t,this.k++}popFront(){if(this.k<=0)throw new Error("No elements left to pop.");const t=this.m[this.v];return this.m[this.v]=void 0,this.v=this.v+1&this.g,this.k--,t}popBack(){if(this.k<=0)throw new Error("No elements left to pop.");this.k--;const t=this.v+this.k&this.g,e=this.m[t];return this.m[t]=void 0,e}peakFront(){if(this.k<=0)throw new Error("No elements left to pop.");return this.m[this.v]}peakBack(){if(this.k<=0)throw new Error("No elements left to pop.");return this.m[this.v+this.k-1&this.g]}count(){return this.k}set(t,e){if(t<0||t>=this.k)throw new Error("Invalid index");this.m[this.v+t&this.g]=e}get(t){if(t<0||t>=this.k)throw new Error("Invalid index");return this.m[this.v+t&this.g]}remove(t){if(t<0||t>=this.k)throw new Error("Invalid index");if(t<=this.k>>1){for(;t>0;)this.set(t,this.get(t-1)),t--;this.popFront()}else{for(t++;t<this.k;)this.set(t-1,this.get(t)),t++;this.popBack()}}M(){if(this.u>=1073741824)throw new Error("Capacity too big.");this.u=this.u<<1;const t=this.m,e=new Array(this.u),i=0|this.k,s=0|this.v;for(let n=0;n<i;n++)e[n]=t[s+n&this.g];for(let t=i;t<this.u;t++)e[t]=void 0;this.v=0,this.m=e,this.g=this.u-1}}class Y{constructor(){this.a=[1],this.b=[1],this.order=0}linearGain0thOrder(t){this.b[0]=t,this.order=0}lowPass1stOrderButterworth(t){const e=1/Math.tan(.5*t),i=1+e;this.a[1]=(1-e)/i,this.b[1]=this.b[0]=1/i,this.order=1}lowPass1stOrderSimplified(t){const e=2*Math.sin(.5*t);this.a[1]=e-1,this.b[0]=e,this.b[1]=0,this.order=1}highPass1stOrderButterworth(t){const e=1/Math.tan(.5*t),i=1+e;this.a[1]=(1-e)/i,this.b[0]=e/i,this.b[1]=-e/i,this.order=1}highShelf1stOrder(t,e){const i=Math.tan(.5*t),s=Math.sqrt(e),n=(i*s-1)/(i*s+1);this.a[1]=n/1,this.b[0]=(1+n+e*(1-n))/2,this.b[1]=(1+n-e*(1-n))/2,this.order=1}allPass1stOrderInvertPhaseAbove(t){const e=(Math.sin(t)-1)/Math.cos(t);this.a[1]=e,this.b[0]=e,this.b[1]=1,this.order=1}allPass1stOrderFractionalDelay(t){const e=(1-t)/(1+t);this.a[1]=e,this.b[0]=e,this.b[1]=1,this.order=1}lowPass2ndOrderButterworth(t,e){const i=Math.sin(t)/(2*e),s=Math.cos(t),n=1+i;this.a[1]=-2*s/n,this.a[2]=(1-i)/n,this.b[2]=this.b[0]=(1-s)/(2*n),this.b[1]=(1-s)/n,this.order=2}lowPass2ndOrderSimplified(t,e){const i=2*Math.sin(t/2),s=1-1/(2*e),n=s+s/(1-i);this.a[1]=2*i+(i-1)*i*n-2,this.a[2]=(i-1)*(i-i*n-1),this.b[0]=i*i,this.b[1]=0,this.b[2]=0,this.order=2}highPass2ndOrderButterworth(t,e){const i=Math.sin(t)/(2*e),s=Math.cos(t),n=1+i;this.a[1]=-2*s/n,this.a[2]=(1-i)/n,this.b[2]=this.b[0]=(1+s)/(2*n),this.b[1]=-(1+s)/n,this.order=2}highShelf2ndOrder(t,e,i){const s=Math.sqrt(e),n=Math.cos(t),o=s+1,r=s-1,h=.5*Math.sin(t)*Math.sqrt(o/s*(1/i-1)+2),a=2*Math.sqrt(s)*h,l=o-r*n+a;this.a[1]=2*(r-o*n)/l,this.a[2]=(o-r*n-a)/l,this.b[0]=s*(o+r*n+a)/l,this.b[1]=-2*s*(r+o*n)/l,this.b[2]=s*(o+r*n-a)/l,this.order=2}peak2ndOrder(t,e,i){const s=Math.sqrt(e),n=i*t/(s>=1?s:1/s),o=Math.tan(.5*n),r=1+o/s;this.b[0]=(1+o*s)/r,this.b[1]=this.a[1]=-2*Math.cos(t)/r,this.b[2]=(1-o*s)/r,this.a[2]=(1-o/s)/r,this.order=2}}class J{constructor(){this.real=0,this.imag=0,this.denom=1}analyze(t,e){this.analyzeComplex(t,Math.cos(e),Math.sin(e))}analyzeComplex(t,e,i){const s=t.a,n=t.b,o=e,r=-i;let h=n[0]+n[1]*o,a=n[1]*r,l=1+s[1]*o,c=s[1]*r,u=o,f=r;for(let e=2;e<=t.order;e++){const t=u*r+f*o;u=u*o-f*r,f=t,h+=n[e]*u,a+=n[e]*f,l+=s[e]*u,c+=s[e]*f}this.denom=l*l+c*c,this.real=h*l+a*c,this.imag=a*l-h*c}magnitude(){return Math.sqrt(this.real*this.real+this.imag*this.imag)/this.denom}angle(){return Math.atan2(this.imag,this.real)}}class Q{constructor(){this.a1=0,this.a2=0,this.b0=1,this.b1=0,this.b2=0,this.a1Delta=0,this.a2Delta=0,this.b0Delta=0,this.b1Delta=0,this.b2Delta=0,this.output1=0,this.output2=0,this.useMultiplicativeInputCoefficients=!1}resetOutput(){this.output1=0,this.output2=0}loadCoefficientsWithGradient(t,e,i,s){if(2!=t.order||2!=e.order)throw new Error;this.a1=t.a[1],this.a2=t.a[2],this.b0=t.b[0],this.b1=t.b[1],this.b2=t.b[2],this.a1Delta=(e.a[1]-t.a[1])*i,this.a2Delta=(e.a[2]-t.a[2])*i,s?(this.b0Delta=Math.pow(e.b[0]/t.b[0],i),this.b1Delta=Math.pow(e.b[1]/t.b[1],i),this.b2Delta=Math.pow(e.b[2]/t.b[2],i)):(this.b0Delta=(e.b[0]-t.b[0])*i,this.b1Delta=(e.b[1]-t.b[1])*i,this.b2Delta=(e.b[2]-t.b[2])*i),this.useMultiplicativeInputCoefficients=s}}function X(t){return 2*Math.atan(.5*t)}const Z=1e-24;function tt(t,e,i){return i<=(e-=1)?i>=t?i:t:e}function et(t,e,i){if(t<=i&&i<=e)return i;throw new Error(`Value ${i} not in range [${t}, ${e}]`)}const it=[48,49,50,51,52,53,54,55,56,57,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,45,95],st=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,62,62,0,0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0,0,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,0,0,0,0,63,0,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,0,0,0,0,0];class nt{constructor(t,e,i){this.S=[],this.P=0;for(let s=e;s<i;s++){const e=st[t.charCodeAt(s)];this.S.push(e>>5&1),this.S.push(e>>4&1),this.S.push(e>>3&1),this.S.push(e>>2&1),this.S.push(e>>1&1),this.S.push(1&e)}}read(t){let e=0;for(;t>0;)e<<=1,e+=this.S[this.P++],t--;return e}readLongTail(t,e){let i=t,s=e;for(;this.S[this.P++];)i+=1<<s,s++;for(;s>0;)s--,this.S[this.P++]&&(i+=1<<s);return i}readPartDuration(){return this.readLongTail(1,3)}readLegacyPartDuration(){return this.readLongTail(1,2)}readPinCount(){return this.readLongTail(1,0)}readPitchInterval(){return this.read(1)?-this.readLongTail(1,3):this.readLongTail(1,3)}}class ot{constructor(){this.I=0,this.S=[]}clear(){this.I=0}write(t,e){for(t--;t>=0;)this.S[this.I++]=e>>>t&1,t--}writeLongTail(t,e,i){if(i<t)throw new Error("value out of bounds");i-=t;let s=e;for(;i>=1<<s;)this.S[this.I++]=1,i-=1<<s,s++;for(this.S[this.I++]=0;s>0;)s--,this.S[this.I++]=i>>>s&1}writePartDuration(t){this.writeLongTail(1,3,t)}writePinCount(t){this.writeLongTail(1,0,t)}writePitchInterval(t){t<0?(this.write(1,1),this.writeLongTail(1,3,-t)):(this.write(1,0),this.writeLongTail(1,3,t))}concat(t){for(let e=0;e<t.I;e++)this.S[this.I++]=t.S[e]}encodeBase64(t){for(let e=0;e<this.I;e+=6){const i=this.S[e]<<5|this.S[e+1]<<4|this.S[e+2]<<3|this.S[e+3]<<2|this.S[e+4]<<1|this.S[e+5];t.push(it[i])}return t}lengthBase64(){return Math.ceil(this.I/6)}}function rt(t,e,i){return{interval:t,time:e,size:i}}class ht{constructor(t,e,i,s,n=!1){this.pitches=[t],this.pins=[rt(0,0,s),rt(0,i-e,n?0:s)],this.start=e,this.end=i,this.continuesLastPattern=!1}pickMainInterval(){let t=0,e=0;for(let i=1;i<this.pins.length;i++){const s=this.pins[i-1],n=this.pins[i];if(s.interval==n.interval){const i=n.time-s.time;t<i&&(t=i,e=s.interval)}}if(0==t){let t=0;for(let i=0;i<this.pins.length;i++){const s=this.pins[i];t<s.size&&(t=s.size,e=s.interval)}}return e}clone(){const t=new ht(-1,this.start,this.end,e.noteSizeMax);t.pitches=this.pitches.concat(),t.pins=[];for(const e of this.pins)t.pins.push(rt(e.interval,e.time,e.size));return t.continuesLastPattern=this.continuesLastPattern,t}getEndPinIndex(t){let e;for(e=1;e<this.pins.length-1&&!(this.pins[e].time+this.start>t);e++);return e}}class at{constructor(){this.notes=[],this.instruments=[0]}cloneNotes(){const t=[];for(const e of this.notes)t.push(e.clone());return t}reset(){this.notes.length=0,this.instruments[0]=0,this.instruments.length=1}toJsonObject(t){const i=[];for(const s of this.notes){const n=[];for(const i of s.pins)n.push({tick:(i.time+s.start)*e.rhythms[t.rhythm].stepsPerBeat/e.partsPerBeat,pitchBend:i.interval,volume:Math.round(100*i.size/3)});const o={pitches:s.pitches,points:n};0==s.start&&(o.continuesLastPattern=s.continuesLastPattern),i.push(o)}const s={notes:i};return t.patternInstruments&&(s.instruments=this.instruments.map((t=>t+1))),s}fromJsonObject(t,i,s,n,o){if(i.patternInstruments)if(Array.isArray(t.instruments)){const n=t.instruments,o=tt(e.instrumentCountMin,i.getMaxInstrumentsPerPatternForChannel(s)+1,n.length);for(let t=0;t<o;t++)this.instruments[t]=tt(0,s.instruments.length,(0|n[t])-1);this.instruments.length=o}else this.instruments[0]=tt(0,s.instruments.length,(0|t.instrument)-1),this.instruments.length=1;if(t.notes&&t.notes.length>0){const s=Math.min(i.beatsPerBar*e.partsPerBeat,t.notes.length>>>0);let r=0;for(let h=0;h<t.notes.length&&!(h>=s);h++){const s=t.notes[h];if(!(s&&s.pitches&&s.pitches.length>=1&&s.points&&s.points.length>=2))continue;const a=new ht(0,0,0,0);a.pitches=[],a.pins=[];for(let t=0;t<s.pitches.length;t++){const i=0|s.pitches[t];if(-1==a.pitches.indexOf(i)&&(a.pitches.push(i),a.pitches.length>=e.maxChordSize))break}if(a.pitches.length<1)continue;let l=r,c=0;for(let t=0;t<s.points.length;t++){const o=s.points[t];if(null==o||null==o.tick)continue;const r=null==o.pitchBend?0:0|o.pitchBend,h=Math.round(+o.tick*e.partsPerBeat/n),u=null==o.volume?3:Math.max(0,Math.min(3,Math.round(3*(0|o.volume)/100)));if(!(h>i.beatsPerBar*e.partsPerBeat)){if(0==a.pins.length){if(h<l)continue;a.start=h,c=r}else if(h<=l)continue;l=h,a.pins.push(rt(r-c,h-a.start,u))}}if(a.pins.length<2)continue;a.end=a.pins[a.pins.length-1].time+a.start;const u=o?e.drumCount-1:e.maxPitch;let f=u,p=0;for(let t=0;t<a.pitches.length;t++)a.pitches[t]+=c,(a.pitches[t]<0||a.pitches[t]>u)&&(a.pitches.splice(t,1),t--),a.pitches[t]<f&&(f=a.pitches[t]),a.pitches[t]>p&&(p=a.pitches[t]);if(!(a.pitches.length<1)){for(let t=0;t<a.pins.length;t++){const e=a.pins[t];e.interval+f<0&&(e.interval=-f),e.interval+p>u&&(e.interval=u-p),t>=2&&e.interval==a.pins[t-1].interval&&e.interval==a.pins[t-2].interval&&e.size==a.pins[t-1].size&&e.size==a.pins[t-2].size&&(a.pins.splice(t-1,1),t--)}0==a.start?a.continuesLastPattern=!0===s.continuesLastPattern:a.continuesLastPattern=!1,this.notes.push(a),r=a.end}}}}}class lt{constructor(t){this.frequency=0,this.amplitude=0,this.reset(t)}reset(t){this.frequency=0,this.amplitude=t<=1?e.operatorAmplitudeMax:0}}class ct{constructor(t){this.spectrum=[],this.hash=-1,this.reset(t)}reset(t){for(let i=0;i<e.spectrumControlPoints;i++)if(t)this.spectrum[i]=Math.round(e.spectrumMax*(1/Math.sqrt(1+i/3)));else{const t=0==i||7==i||11==i||14==i||16==i||18==i||21==i||23==i||i>=25;this.spectrum[i]=t?Math.max(0,Math.round(e.spectrumMax*(1-i/30))):0}this.markCustomWaveDirty()}markCustomWaveDirty(){const t=Ft.fittingPowerOfTwo(e.spectrumMax+2)-1;let i=0;for(const e of this.spectrum)i=i*t+e>>>0;this.hash=i}}class ut{constructor(){this.wave=null,this.T=-1}getCustomWave(t,i){if(this.T==t.hash)return this.wave;this.T=t.hash;const s=e.spectrumNoiseLength;null!=this.wave&&this.wave.length==s+1||(this.wave=new Float32Array(s+1));const n=this.wave;for(let t=0;t<s;t++)n[t]=0;const o=[0,1/7,Math.log2(5/4),3/7,Math.log2(1.5),5/7,6/7];function h(t){return i+Math.floor(t/e.spectrumControlPointsPerOctave)+o[(t+e.spectrumControlPointsPerOctave)%e.spectrumControlPointsPerOctave]}let a=1;for(let i=0;i<e.spectrumControlPoints+1;i++){const o=i<=0?0:t.spectrum[i-1],l=i>=e.spectrumControlPoints?t.spectrum[e.spectrumControlPoints-1]:t.spectrum[i],c=h(i-1);let u=h(i);i>=e.spectrumControlPoints&&(u=14+.25*(u-14)),0==o&&0==l||(a+=.02*r(n,s,c,u,o/e.spectrumMax,l/e.spectrumMax,-.5))}return t.spectrum[e.spectrumControlPoints-1]>0&&(a+=.02*r(n,s,14+.25*(h(e.spectrumControlPoints)-14),14,t.spectrum[e.spectrumControlPoints-1]/e.spectrumMax,0,-.5)),W(n,s),V(n,5/(Math.sqrt(s)*Math.pow(a,.75))),n[s]=n[0],n}}class ft{constructor(){this.harmonics=[],this.hash=-1,this.reset()}reset(){for(let t=0;t<e.harmonicsControlPoints;t++)this.harmonics[t]=0;this.harmonics[0]=e.harmonicsMax,this.harmonics[3]=e.harmonicsMax,this.harmonics[6]=e.harmonicsMax,this.markCustomWaveDirty()}markCustomWaveDirty(){const t=Ft.fittingPowerOfTwo(e.harmonicsMax+2)-1;let i=0;for(const e of this.harmonics)i=i*t+e>>>0;this.hash=i}}class pt{constructor(){this.wave=null,this.T=-1}getCustomWave(t,i){if(this.T==t.hash&&this.q==i)return this.wave;this.T=t.hash,this.q=i;const n=7==i?e.harmonicsRenderedForPickedString:e.harmonicsRendered,r=e.harmonicsWavelength,h=o(0,null,null);null!=this.wave&&this.wave.length==r+1||(this.wave=new Float32Array(r+1));const a=this.wave;for(let t=0;t<r;t++)a[t]=0;let l=1;for(let i=0;i<n;i++){const s=i+1;let o=i<e.harmonicsControlPoints?t.harmonics[i]:t.harmonics[e.harmonicsControlPoints-1];i>=e.harmonicsControlPoints&&(o*=1-(i-e.harmonicsControlPoints)/(n-e.harmonicsControlPoints));const c=o/e.harmonicsMax;let u=Math.pow(2,o-e.harmonicsMax+1)*Math.sqrt(c);i<e.harmonicsControlPoints&&(l+=u),u*=Math.pow(s,-.25),u*=h[i+589],a[r-s]=u}W(a,r);const c=1/Math.pow(l,.7);for(let t=0;t<a.length;t++)a[t]*=c;return s(a),a[r]=a[0],a}}class dt{constructor(){this.freq=0,this.gain=e.filterGainCenter,this.type=2}set(t,e){this.freq=t,this.gain=e}getHz(){return dt.getHzFromSettingValue(this.freq)}static getHzFromSettingValue(t){return e.filterFreqReferenceHz*Math.pow(2,(t-e.filterFreqReferenceSetting)*e.filterFreqStep)}static getSettingValueFromHz(t){return Math.log2(t/e.filterFreqReferenceHz)/e.filterFreqStep+e.filterFreqReferenceSetting}static getRoundedSettingValueFromHz(t){return Math.max(0,Math.min(e.filterFreqRange-1,Math.round(dt.getSettingValueFromHz(t))))}getLinearGain(t=1){const i=(this.gain-e.filterGainCenter)*e.filterGainStep,s=2==this.type?0:-.5,n=s+(i-s)*t;return Math.pow(2,n)}static getRoundedSettingValueFromLinearGain(t){return Math.max(0,Math.min(e.filterGainRange-1,Math.round(Math.log2(t)/e.filterGainStep+e.filterGainCenter)))}toCoefficients(t,i,s=1,n=1){const o=2*Math.PI*Math.max(e.filterFreqMinHz,Math.min(e.filterFreqMaxHz,s*this.getHz()))/i,r=this.getLinearGain(n);switch(this.type){case 0:t.lowPass2ndOrderButterworth(o,r);break;case 1:t.highPass2ndOrderButterworth(o,r);break;case 2:t.peak2ndOrder(o,r,1);break;default:throw new Error}}getVolumeCompensationMult(){const t=(this.freq-e.filterFreqReferenceSetting)*e.filterFreqStep,i=(this.gain-e.filterGainCenter)*e.filterGainStep;switch(this.type){case 0:const s=Math.pow(2,t)*e.filterFreqReferenceHz/8e3,n=(Math.sqrt(1+4*s)-1)/2,o=Math.log2(n);return Math.pow(.5,.2*Math.max(0,i+1)+Math.min(0,Math.max(-3,.595*o+.35*Math.min(0,i+1))));case 1:return Math.pow(.5,.125*Math.max(0,i+1)+Math.min(0,.3*(-t-Math.log2(e.filterFreqReferenceHz/125))+.2*Math.min(0,i+1)));case 2:const r=t+Math.log2(e.filterFreqReferenceHz/2e3),h=Math.pow(1/(1+Math.pow(r/3,2)),2);return Math.pow(.5,.125*Math.max(0,i)+.1*h*Math.min(0,i));default:throw new Error}}}class mt{constructor(){this.controlPoints=[],this.controlPointCount=0,this.reset()}reset(){this.controlPointCount=0}addPoint(t,e,i){let s;this.controlPoints.length<=this.controlPointCount?(s=new dt,this.controlPoints[this.controlPointCount]=s):s=this.controlPoints[this.controlPointCount],this.controlPointCount++,s.type=t,s.set(e,i)}toJsonObject(){const t=[];for(let i=0;i<this.controlPointCount;i++){const s=this.controlPoints[i];t.push({type:e.filterTypeNames[s.type],cutoffHz:Math.round(100*s.getHz())/100,linearGain:Math.round(1e4*s.getLinearGain())/1e4})}return t}fromJsonObject(t){if(this.controlPoints.length=0,t)for(const i of t){const t=new dt;t.type=e.filterTypeNames.indexOf(i.type),-1==t.type&&(t.type=2),null!=i.cutoffHz?t.freq=dt.getRoundedSettingValueFromHz(i.cutoffHz):t.freq=0,null!=i.linearGain?t.gain=dt.getRoundedSettingValueFromLinearGain(i.linearGain):t.gain=e.filterGainCenter,this.controlPoints.push(t)}this.controlPointCount=this.controlPoints.length}convertLegacySettings(t,e,i){this.reset();const s=2*Math.asin(.475),n=e>1,o=0==e,r=10==t,h=3==i.type||4==i.type||8==i.type||0==i.type,a=48e3,l=8e3*Math.pow(2,.5*(t-10)),c=Math.min(s,2*Math.PI*l/a);if(1==i.type&&!n&&r);else if(o){const t=3.5,e=c*Math.pow(2,t),i=a*(e/(1+e/Math.PI))/(2*Math.PI),s=dt.getRoundedSettingValueFromHz(i),n=dt.getHzFromSettingValue(s),o=2*Math.PI*n/a,r=new Y;r.lowPass1stOrderSimplified(c);const l=new J;l.analyze(r,o);const u=l.magnitude();let f=Math.log2(u);f=.82*(f+t)-t,h&&(f=Math.min(f,-1));const p=Math.pow(2,f),d=dt.getRoundedSettingValueFromLinearGain(p);this.addPoint(0,s,d)}else{const t=.5/(1-.95*Math.sqrt(Math.max(0,e-1)/6)),i=.5/t,s=c+(c*(c/(2*Math.PI*8e3/a)*Math.pow(i,.9)+1)-c)*i;let o;o=h?a*Math.min(s,c*Math.pow(2,.25))/(2*Math.PI):a*s/(2*Math.PI);const r=dt.getRoundedSettingValueFromHz(o);let l;if(h)l=t;else{const e=new Y;e.lowPass2ndOrderSimplified(c,t);const i=new J;i.analyze(e,s),l=i.magnitude()}n||(l=Math.min(l,Math.sqrt(.5)));const u=dt.getRoundedSettingValueFromLinearGain(l);this.addPoint(0,r,u)}}}class yt{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:e.instrumentAutomationTargets[this.target].name,envelope:e.envelopes[this.envelope].name};return e.instrumentAutomationTargets[this.target].maxCount>1&&(t.index=this.index),t}fromJsonObject(t){this.reset();let i=e.instrumentAutomationTargets.dictionary[t.target];null==i&&(i=e.instrumentAutomationTargets.dictionary.noteVolume),this.target=i.index;let s=e.envelopes.dictionary[t.envelope];null==s&&(s=e.envelopes.dictionary.none),this.envelope=s.index,null!=t.index?this.index=tt(0,e.instrumentAutomationTargets[this.target].maxCount,0|t.index):this.index=0}}class gt{constructor(t){this.type=0,this.preset=0,this.chipWave=2,this.chipNoise=1,this.eqFilter=new mt,this.noteFilter=new mt,this.envelopes=[],this.envelopeCount=0,this.fadeIn=0,this.fadeOut=e.fadeOutNeutral,this.transition=e.transitions.dictionary.normal.index,this.pitchShift=0,this.detune=0,this.vibrato=0,this.unison=0,this.effects=0,this.chord=1,this.volume=0,this.pan=e.panCenter,this.pulseWidth=e.pulseWidthRange-1,this.supersawDynamism=e.supersawDynamismMax,this.supersawSpread=Math.ceil(e.supersawSpreadMax/2),this.supersawShape=0,this.stringSustain=10,this.stringSustainType=1,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.feedbackAmplitude=0,this.operators=[],this.harmonicsWave=new ft,this.drumsetEnvelopes=[],this.drumsetSpectrumWaves=[],this.spectrumWave=new ct(t);for(let t=0;t<e.operatorCount;t++)this.operators[t]=new lt(t);for(let t=0;t<e.drumCount;t++)this.drumsetEnvelopes[t]=e.envelopes.dictionary["twang 2"].index,this.drumsetSpectrumWaves[t]=new ct(!0)}setTypeAndReset(t,i){switch(this.type=t,this.preset=t,this.volume=0,this.effects=0,this.chorus=e.chorusRange-1,this.reverb=2,this.echoSustain=Math.floor(.5*(e.echoSustainRange-1)),this.echoDelay=Math.floor(.5*(e.echoDelayRange-1)),this.eqFilter.reset(),this.noteFilter.reset(),this.distortion=Math.floor(.75*(e.distortionRange-1)),this.bitcrusherFreq=Math.floor(.5*(e.bitcrusherFreqRange-1)),this.bitcrusherQuantization=Math.floor(.5*(e.bitcrusherQuantizationRange-1)),this.pan=e.panCenter,this.pitchShift=e.pitchShiftCenter,this.detune=e.detuneCenter,this.vibrato=0,this.unison=0,this.stringSustain=10,this.stringSustainType=e.enableAcousticSustain?1:0,this.fadeIn=0,this.fadeOut=e.fadeOutNeutral,this.transition=e.transitions.dictionary.normal.index,this.envelopeCount=0,t){case 0:this.chipWave=2,this.chord=e.chords.dictionary.arpeggio.index;break;case 1:this.chord=e.chords.dictionary["custom interval"].index,this.algorithm=0,this.feedbackType=0,this.feedbackAmplitude=0;for(let t=0;t<this.operators.length;t++)this.operators[t].reset(t);break;case 2:this.chipNoise=1,this.chord=e.chords.dictionary.arpeggio.index;break;case 3:this.chord=e.chords.dictionary.simultaneous.index,this.spectrumWave.reset(i);break;case 4:this.chord=e.chords.dictionary.simultaneous.index;for(let t=0;t<e.drumCount;t++)this.drumsetEnvelopes[t]=e.envelopes.dictionary["twang 2"].index,this.drumsetSpectrumWaves[t].reset(i);break;case 5:this.chord=e.chords.dictionary.simultaneous.index,this.harmonicsWave.reset();break;case 6:this.chord=e.chords.dictionary.arpeggio.index,this.pulseWidth=e.pulseWidthRange-1;break;case 7:this.chord=e.chords.dictionary.strum.index,this.harmonicsWave.reset();break;case 8:this.chord=e.chords.dictionary.arpeggio.index,this.supersawDynamism=e.supersawDynamismMax,this.supersawSpread=Math.ceil(e.supersawSpreadMax/2),this.supersawShape=0,this.pulseWidth=e.pulseWidthRange-1;break;default:throw new Error("Unrecognized instrument type: "+t)}this.chord!=e.chords.dictionary.simultaneous.index&&(this.effects=2048|this.effects)}convertLegacySettings(t){let i=t.filterCutoff,s=t.filterResonance,n=t.filterEnvelope,o=t.pulseEnvelope,r=t.operatorEnvelopes,h=t.feedbackEnvelope;null==i&&(i=0==this.type?6:10),null==s&&(s=0),null==n&&(n=e.envelopes.dictionary.none),null==o&&(o=e.envelopes.dictionary[6==this.type?"twang 2":"none"]),null==r&&(r=[e.envelopes.dictionary[1==this.type?"note size":"none"],e.envelopes.dictionary.none,e.envelopes.dictionary.none,e.envelopes.dictionary.none]),null==h&&(h=e.envelopes.dictionary.none);10==i&&2==n.type&&(n=e.envelopes.dictionary.none);const a=e.algorithms[this.algorithm].carrierCount;let l=!0,c=!0,u=0==n.type||0==o.type;if(1==this.type){u=u||0==h.type;for(let t=0;t<r.length;t++)t<a?0!=r[t].type?c=!1:l=!1:u=u||0==r[t].type}this.envelopeCount=0,1==this.type&&(c&&u?this.addEnvelope(e.instrumentAutomationTargets.dictionary.noteVolume.index,0,e.envelopes.dictionary["note size"].index):l&&!u&&this.addEnvelope(e.instrumentAutomationTargets.dictionary.none.index,0,e.envelopes.dictionary["note size"].index)),1==n.type?(this.noteFilter.reset(),this.eqFilter.convertLegacySettings(i,s,n),this.effects&=-33):(this.eqFilter.reset(),this.noteFilter.convertLegacySettings(i,s,n),this.effects|=32,this.addEnvelope(e.instrumentAutomationTargets.dictionary.noteFilterAllFreqs.index,0,n.index)),1!=o.type&&this.addEnvelope(e.instrumentAutomationTargets.dictionary.pulseWidth.index,0,o.index);for(let t=0;t<r.length;t++)t<a&&c||1!=r[t].type&&this.addEnvelope(e.instrumentAutomationTargets.dictionary.operatorAmplitude.index,t,r[t].index);1!=h.type&&this.addEnvelope(e.instrumentAutomationTargets.dictionary.feedbackAmplitude.index,0,h.index)}toJsonObject(){const t={type:e.instrumentTypeNames[this.type],volume:20*(5-this.volume),eqFilter:this.eqFilter.toJsonObject()};this.preset!=this.type&&(t.preset=this.preset);const i=[];for(const t of e.effectOrder)this.effects&1<<t&&i.push(e.effectNames[t]);if(t.effects=i,l(this.effects)&&(t.transition=e.transitions[this.transition].name),c(this.effects)&&(t.chord=this.getChord().name),u(this.effects)&&(t.pitchShiftSemitones=this.pitchShift),f(this.effects)&&(t.detuneCents=Ft.detuneToCents(this.detune-e.detuneCenter)),p(this.effects)&&(t.vibrato=e.vibratos[this.vibrato].name),d(this.effects)&&(t.noteFilter=this.noteFilter.toJsonObject()),m(this.effects)&&(t.distortion=Math.round(100*this.distortion/(e.distortionRange-1))),y(this.effects)&&(t.bitcrusherOctave=(e.bitcrusherFreqRange-1-this.bitcrusherFreq)*e.bitcrusherOctaveStep,t.bitcrusherQuantization=Math.round(100*this.bitcrusherQuantization/(e.bitcrusherQuantizationRange-1))),g(this.effects)&&(t.pan=Math.round(100*(this.pan-e.panCenter)/e.panCenter)),b(this.effects)&&(t.chorus=Math.round(100*this.chorus/(e.chorusRange-1))),w(this.effects)&&(t.echoSustain=Math.round(100*this.echoSustain/(e.echoSustainRange-1)),t.echoDelayBeats=Math.round(1e3*(this.echoDelay+1)*e.echoDelayStepTicks/(e.ticksPerPart*e.partsPerBeat))/1e3),v(this.effects)&&(t.reverb=Math.round(100*this.reverb/(e.reverbRange-1))),4!=this.type&&(t.fadeInSeconds=Math.round(1e4*Ft.fadeInSettingToSeconds(this.fadeIn))/1e4,t.fadeOutTicks=Ft.fadeOutSettingToTicks(this.fadeOut)),5==this.type||7==this.type){t.harmonics=[];for(let i=0;i<e.harmonicsControlPoints;i++)t.harmonics[i]=Math.round(100*this.harmonicsWave.harmonics[i]/e.harmonicsMax)}if(2==this.type)t.wave=e.chipNoises[this.chipNoise].name;else if(3==this.type){t.spectrum=[];for(let i=0;i<e.spectrumControlPoints;i++)t.spectrum[i]=Math.round(100*this.spectrumWave.spectrum[i]/e.spectrumMax)}else if(4==this.type){t.drums=[];for(let i=0;i<e.drumCount;i++){const s=[];for(let t=0;t<e.spectrumControlPoints;t++)s[t]=Math.round(100*this.drumsetSpectrumWaves[i].spectrum[t]/e.spectrumMax);t.drums[i]={filterEnvelope:this.getDrumsetEnvelope(i).name,spectrum:s}}}else if(0==this.type)t.wave=e.chipWaves[this.chipWave].name,t.unison=e.unisons[this.unison].name;else if(6==this.type)t.pulseWidth=Math.round(100*n(this.pulseWidth)*1e5)/1e5;else if(8==this.type)t.pulseWidth=Math.round(100*n(this.pulseWidth)*1e5)/1e5,t.dynamism=Math.round(100*this.supersawDynamism/e.supersawDynamismMax),t.spread=Math.round(100*this.supersawSpread/e.supersawSpreadMax),t.shape=Math.round(100*this.supersawShape/e.supersawShapeMax);else if(7==this.type)t.unison=e.unisons[this.unison].name,t.stringSustain=Math.round(100*this.stringSustain/(e.stringSustainRange-1)),e.enableAcousticSustain&&(t.stringSustainType=e.sustainTypeNames[this.stringSustainType]);else if(5==this.type)t.unison=e.unisons[this.unison].name;else{if(1!=this.type)throw new Error("Unrecognized instrument type");{const i=[];for(const t of this.operators)i.push({frequency:e.operatorFrequencies[t.frequency].name,amplitude:t.amplitude});t.algorithm=e.algorithms[this.algorithm].name,t.feedbackType=e.feedbacks[this.feedbackType].name,t.feedbackAmplitude=this.feedbackAmplitude,t.operators=i}}const s=[];for(let t=0;t<this.envelopeCount;t++)s.push(this.envelopes[t].toJsonObject());return t.envelopes=s,t}fromJsonObject(t,i,s=0){null==t&&(t={});let n=e.instrumentTypeNames.indexOf(t.type);if(-1==n&&(n=i?2:0),this.setTypeAndReset(n,i),null!=t.preset&&(this.preset=t.preset>>>0),null!=t.volume?this.volume=tt(0,e.volumeRange,Math.round(5-(0|t.volume)/20)):this.volume=0,Array.isArray(t.effects)){let i=0;for(let s=0;s<t.effects.length;s++)i|=1<<e.effectNames.indexOf(t.effects[s]);this.effects=4095&i}else{const e=["none","reverb","chorus","chorus & reverb"];this.effects=e.indexOf(t.effects),-1==this.effects&&(this.effects=2==this.type?0:1)}this.transition=e.transitions.dictionary.normal.index;const o=t.transition||t.envelope;if(null!=o){let i=e.transitions.dictionary[o];if(null==t.fadeInSeconds||null==t.fadeOutTicks){const t={binary:{transition:"interrupt",fadeInSeconds:0,fadeOutTicks:-1},seamless:{transition:"interrupt",fadeInSeconds:0,fadeOutTicks:-1},sudden:{transition:"normal",fadeInSeconds:0,fadeOutTicks:-3},hard:{transition:"normal",fadeInSeconds:0,fadeOutTicks:-3},smooth:{transition:"normal",fadeInSeconds:.025,fadeOutTicks:-3},soft:{transition:"normal",fadeInSeconds:.025,fadeOutTicks:-3},slide:{transition:"slide in pattern",fadeInSeconds:.025,fadeOutTicks:-3},"cross fade":{transition:"normal",fadeInSeconds:.04,fadeOutTicks:6},"hard fade":{transition:"normal",fadeInSeconds:0,fadeOutTicks:48},"medium fade":{transition:"normal",fadeInSeconds:.0125,fadeOutTicks:72},"soft fade":{transition:"normal",fadeInSeconds:.06,fadeOutTicks:96}}[o];null!=t&&(i=e.transitions.dictionary[t.transition],this.fadeIn=Ft.secondsToFadeInSetting(t.fadeInSeconds),this.fadeOut=Ft.ticksToFadeOutSetting(t.fadeOutTicks))}null!=i&&(this.transition=i.index),this.transition!=e.transitions.dictionary.normal.index&&(this.effects=1024|this.effects)}null!=t.fadeInSeconds&&(this.fadeIn=Ft.secondsToFadeInSetting(+t.fadeInSeconds)),null!=t.fadeOutTicks&&(this.fadeOut=Ft.ticksToFadeOutSetting(+t.fadeOutTicks));{const i=t.chord,s={harmony:"simultaneous"},n=e.chords.dictionary[s[i]]||e.chords.dictionary[i];null!=n?this.chord=n.index:2==this.type?this.chord=e.chords.dictionary.arpeggio.index:7==this.type?this.chord=e.chords.dictionary.strum.index:0==this.type?this.chord=e.chords.dictionary.arpeggio.index:1==this.type?this.chord=e.chords.dictionary["custom interval"].index:this.chord=e.chords.dictionary.simultaneous.index}this.unison=e.unisons.dictionary.none.index;const r=t.unison||t.interval||t.chorus;if(null!=r){const t={union:"none",fifths:"fifth",octaves:"octave"},i=e.unisons.dictionary[t[r]]||e.unisons.dictionary[r];null!=i&&(this.unison=i.index)}"custom harmony"==t.chorus&&(this.unison=e.unisons.dictionary.hum.index,this.chord=e.chords.dictionary["custom interval"].index),this.chord==e.chords.dictionary.simultaneous.index||Array.isArray(t.effects)||(this.effects=2048|this.effects),null!=t.pitchShiftSemitones&&(this.pitchShift=tt(0,e.pitchShiftRange,Math.round(+t.pitchShiftSemitones))),null!=t.detuneCents&&(this.detune=tt(0,e.detuneMax+1,Math.round(e.detuneCenter+Ft.centsToDetune(+t.detuneCents)))),this.vibrato=e.vibratos.dictionary.none.index;const h=t.vibrato||t.effect;if(null!=h){const t={"vibrato light":"light","vibrato delayed":"delayed","vibrato heavy":"heavy"},i=e.vibratos.dictionary[t[r]]||e.vibratos.dictionary[h];null!=i&&(this.vibrato=i.index),i!=e.vibratos.dictionary.none&&(this.effects=512|this.effects)}if(null!=t.pan?(this.pan=tt(0,e.panMax+1,Math.round(e.panCenter+(0|t.pan)*e.panCenter/100)),this.pan!=e.panCenter&&(this.effects=4|this.effects)):this.pan=e.panCenter,null!=t.distortion&&(this.distortion=tt(0,e.distortionRange,Math.round((e.distortionRange-1)*(0|t.distortion)/100))),null!=t.bitcrusherOctave&&(this.bitcrusherFreq=e.bitcrusherFreqRange-1-+t.bitcrusherOctave/e.bitcrusherOctaveStep),null!=t.bitcrusherQuantization&&(this.bitcrusherQuantization=tt(0,e.bitcrusherQuantizationRange,Math.round((e.bitcrusherQuantizationRange-1)*(0|t.bitcrusherQuantization)/100))),null!=t.echoSustain&&(this.echoSustain=tt(0,e.echoSustainRange,Math.round((e.echoSustainRange-1)*(0|t.echoSustain)/100))),null!=t.echoDelayBeats&&(this.echoDelay=tt(0,e.echoDelayRange,Math.round(+t.echoDelayBeats*(e.ticksPerPart*e.partsPerBeat)/e.echoDelayStepTicks-1))),isNaN(t.chorus)||(this.chorus=tt(0,e.chorusRange,Math.round((e.chorusRange-1)*(0|t.chorus)/100))),null!=t.reverb?this.reverb=tt(0,e.reverbRange,Math.round((e.reverbRange-1)*(0|t.reverb)/100)):0==s?this.effects=-2&this.effects:this.reverb=s,null!=t.pulseWidth?this.pulseWidth=tt(0,e.pulseWidthRange,Math.round(Math.log2(+t.pulseWidth/50)/.5-1+8)):this.pulseWidth=e.pulseWidthRange-1,null!=t.dynamism?this.supersawDynamism=tt(0,e.supersawDynamismMax+1,Math.round(e.supersawDynamismMax*(0|t.dynamism)/100)):this.supersawDynamism=e.supersawDynamismMax,null!=t.spread?this.supersawSpread=tt(0,e.supersawSpreadMax+1,Math.round(e.supersawSpreadMax*(0|t.spread)/100)):this.supersawSpread=Math.ceil(e.supersawSpreadMax/2),null!=t.shape?this.supersawShape=tt(0,e.supersawShapeMax+1,Math.round(e.supersawShapeMax*(0|t.shape)/100)):this.supersawShape=0,null!=t.harmonics){for(let i=0;i<e.harmonicsControlPoints;i++)this.harmonicsWave.harmonics[i]=Math.max(0,Math.min(e.harmonicsMax,Math.round(e.harmonicsMax*+t.harmonics[i]/100)));this.harmonicsWave.markCustomWaveDirty()}else this.harmonicsWave.reset();if(null!=t.spectrum){for(let i=0;i<e.spectrumControlPoints;i++)this.spectrumWave.spectrum[i]=Math.max(0,Math.min(e.spectrumMax,Math.round(e.spectrumMax*+t.spectrum[i]/100)));this.spectrumWave.markCustomWaveDirty()}else this.spectrumWave.reset(i);null!=t.stringSustain?this.stringSustain=tt(0,e.stringSustainRange,Math.round((e.stringSustainRange-1)*(0|t.stringSustain)/100)):this.stringSustain=10,this.stringSustainType=e.enableAcousticSustain?e.sustainTypeNames.indexOf(t.stringSustainType):0,-1==this.stringSustainType&&(this.stringSustainType=0),2==this.type&&(this.chipNoise=e.chipNoises.findIndex((e=>e.name==t.wave)),-1==this.chipNoise&&(this.chipNoise=1));const a={custom:"note size",steady:"none","pluck 1":"twang 1","pluck 2":"twang 2","pluck 3":"twang 3"},l=t=>null!=a[t]?e.envelopes.dictionary[a[t]]:e.envelopes.dictionary[t];if(4==this.type&&null!=t.drums)for(let i=0;i<e.drumCount;i++){const s=t.drums[i];if(null!=s){if(this.drumsetEnvelopes[i]=e.envelopes.dictionary["twang 2"].index,null!=s.filterEnvelope){const t=l(s.filterEnvelope);null!=t&&(this.drumsetEnvelopes[i]=t.index)}if(null!=s.spectrum)for(let t=0;t<e.spectrumControlPoints;t++)this.drumsetSpectrumWaves[i].spectrum[t]=Math.max(0,Math.min(e.spectrumMax,Math.round(e.spectrumMax*+s.spectrum[t]/100)))}}if(0==this.type){const i={triangle:1,square:2,"pulse wide":3,"pulse narrow":4,sawtooth:5,"double saw":6,"double pulse":7,spiky:8,plateau:0};this.chipWave=null!=i[t.wave]?i[t.wave]:e.chipWaves.findIndex((e=>e.name==t.wave)),-1==this.chipWave&&(this.chipWave=1)}if(1==this.type){this.algorithm=e.algorithms.findIndex((e=>e.name==t.algorithm)),-1==this.algorithm&&(this.algorithm=0),this.feedbackType=e.feedbacks.findIndex((e=>e.name==t.feedbackType)),-1==this.feedbackType&&(this.feedbackType=0),null!=t.feedbackAmplitude?this.feedbackAmplitude=tt(0,e.operatorAmplitudeMax+1,0|t.feedbackAmplitude):this.feedbackAmplitude=0;for(let i=0;i<e.operatorCount;i++){const s=this.operators[i];let n;null!=t.operators&&(n=t.operators[i]),null==n&&(n={}),s.frequency=e.operatorFrequencies.findIndex((t=>t.name==n.frequency)),-1==s.frequency&&(s.frequency=0),null!=n.amplitude?s.amplitude=tt(0,e.operatorAmplitudeMax+1,0|n.amplitude):s.amplitude=0}}if(null!=t.noteFilter?this.noteFilter.fromJsonObject(t.noteFilter):this.noteFilter.reset(),Array.isArray(t.eqFilter))this.eqFilter.fromJsonObject(t.eqFilter);else{this.eqFilter.reset();const i={},s=8e3,n=11,o=8;if(null!=t.filterCutoffHz?i.filterCutoff=tt(0,n,Math.round(n-1+2*Math.log((0|t.filterCutoffHz)/s)/Math.LN2)):i.filterCutoff=0==this.type?6:10,null!=t.filterResonance?i.filterResonance=tt(0,o,Math.round((o-1)*(0|t.filterResonance)/100)):i.filterResonance=0,i.filterEnvelope=l(t.filterEnvelope),i.pulseEnvelope=l(t.pulseEnvelope),i.feedbackEnvelope=l(t.feedbackEnvelope),Array.isArray(t.operators)){i.operatorEnvelopes=[];for(let s=0;s<e.operatorCount;s++){let n;null!=t.operators[s]&&(n=l(t.operators[s].envelope)),i.operatorEnvelopes[s]=null!=n?n:e.envelopes.dictionary.none}}if(null!=t.filter){const e=[10,6,3,0,8,5,2],s=["none","none","none","none","decay 1","decay 2","decay 3"],n=["none","bright","medium","soft","decay bright","decay medium","decay soft"],o={"sustain sharp":1,"sustain medium":2,"sustain soft":3,"decay sharp":4};let r=null!=o[t.filter]?o[t.filter]:n.indexOf(t.filter);-1==r&&(r=0),i.filterCutoff=e[r],i.filterEnvelope=l(s[r]),i.filterResonance=0}this.convertLegacySettings(i)}if(Array.isArray(t.envelopes)){const i=t.envelopes;for(let t=0;t<i.length&&!(this.envelopeCount>=e.maxEnvelopeCount);t++){const e=new yt;e.fromJsonObject(i[t]),this.addEnvelope(e.target,e.index,e.envelope)}}}static frequencyFromPitch(t){return 440*Math.pow(2,(t-69)/12)}addEnvelope(t,i,s){if(!this.supportsEnvelopeTarget(t,i))throw new Error;if(this.envelopeCount>=e.maxEnvelopeCount)throw new Error;for(;this.envelopes.length<=this.envelopeCount;)this.envelopes[this.envelopes.length]=new yt;const n=this.envelopes[this.envelopeCount];n.target=t,n.index=i,n.envelope=s,this.envelopeCount++}supportsEnvelopeTarget(t,i){const s=e.instrumentAutomationTargets[t];return(null!=s.computeIndex||"none"==s.name)&&(!(i>=s.maxCount)&&((null==s.compatibleInstruments||-1!=s.compatibleInstruments.indexOf(this.type))&&((null==s.effect||0!=(this.effects&1<<s.effect))&&!(s.isFilter&&i>=this.noteFilter.controlPointCount))))}clearInvalidEnvelopeTargets(){for(let t=0;t<this.envelopeCount;t++){const i=this.envelopes[t].target,s=this.envelopes[t].index;this.supportsEnvelopeTarget(i,s)||(this.envelopes[t].target=e.instrumentAutomationTargets.dictionary.none.index,this.envelopes[t].index=0)}}getTransition(){return l(this.effects)?e.transitions[this.transition]:e.transitions.dictionary.normal}getFadeInSeconds(){return 4==this.type?0:Ft.fadeInSettingToSeconds(this.fadeIn)}getFadeOutTicks(){return 4==this.type?e.drumsetFadeOutTicks:Ft.fadeOutSettingToTicks(this.fadeOut)}getChord(){return c(this.effects)?e.chords[this.chord]:e.chords.dictionary.simultaneous}getDrumsetEnvelope(t){if(4!=this.type)throw new Error("Can't getDrumsetEnvelope() for non-drumset.");return e.envelopes[this.drumsetEnvelopes[t]]}}class bt{constructor(){this.octave=0,this.instruments=[],this.patterns=[],this.bars=[],this.muted=!1}}class wt{constructor(t){this.channels=[],null!=t?this.fromBase64String(t):this.initToDefault(!0)}getChannelCount(){return this.pitchChannelCount+this.noiseChannelCount}getMaxInstrumentsPerChannel(){return Math.max(this.layeredInstruments?e.layeredInstrumentCountMax:e.instrumentCountMin,this.patternInstruments?e.patternInstrumentCountMax:e.instrumentCountMin)}getMaxInstrumentsPerPattern(t){return this.getMaxInstrumentsPerPatternForChannel(this.channels[t])}getMaxInstrumentsPerPatternForChannel(t){return this.layeredInstruments?Math.min(e.layeredInstrumentCountMax,t.instruments.length):1}getChannelIsNoise(t){return t>=this.pitchChannelCount}initToDefault(t=!0){if(this.scale=0,this.key=0,this.loopStart=0,this.loopLength=4,this.tempo=150,this.beatsPerBar=8,this.barCount=16,this.patternsPerChannel=8,this.rhythm=1,this.layeredInstruments=!1,this.patternInstruments=!1,t){this.pitchChannelCount=3,this.noiseChannelCount=1;for(let t=0;t<this.getChannelCount();t++){const i=t>=this.pitchChannelCount;this.channels.length<=t&&(this.channels[t]=new bt);const s=this.channels[t];s.octave=i?0:4-t;for(let t=0;t<this.patternsPerChannel;t++)s.patterns.length<=t?s.patterns[t]=new at:s.patterns[t].reset();s.patterns.length=this.patternsPerChannel;for(let t=0;t<e.instrumentCountMin;t++)s.instruments.length<=t&&(s.instruments[t]=new gt(i)),s.instruments[t].setTypeAndReset(i?2:0,i);s.instruments.length=e.instrumentCountMin;for(let t=0;t<this.barCount;t++)s.bars[t]=t<4?1:0;s.bars.length=this.barCount}this.channels.length=this.getChannelCount()}}toBase64String(){let t,i=[];if(i.push(it[wt.L]),i.push(110,it[this.pitchChannelCount],it[this.noiseChannelCount]),i.push(115,it[this.scale]),i.push(107,it[this.key]),i.push(108,it[this.loopStart>>6],it[63&this.loopStart]),i.push(101,it[this.loopLength-1>>6],it[this.loopLength-1&63]),i.push(116,it[this.tempo>>6],it[63&this.tempo]),i.push(97,it[this.beatsPerBar-1]),i.push(103,it[this.barCount-1>>6],it[this.barCount-1&63]),i.push(106,it[this.patternsPerChannel-1>>6],it[this.patternsPerChannel-1&63]),i.push(114,it[this.rhythm]),i.push(105,it[this.layeredInstruments<<1|this.patternInstruments]),this.layeredInstruments||this.patternInstruments)for(let t=0;t<this.getChannelCount();t++)i.push(it[this.channels[t].instruments.length-e.instrumentCountMin]);i.push(111);for(let t=0;t<this.pitchChannelCount;t++)i.push(it[this.channels[t].octave]);for(let t=0;t<this.getChannelCount();t++)for(let s=0;s<this.channels[t].instruments.length;s++){const n=this.channels[t].instruments[s];i.push(84,it[n.type]),i.push(118,it[n.volume]),i.push(117,it[n.preset>>6],it[63&n.preset]),i.push(102,it[n.eqFilter.controlPointCount]);for(let t=0;t<n.eqFilter.controlPointCount;t++){const e=n.eqFilter.controlPoints[t];i.push(it[e.type],it[e.freq],it[e.gain])}if(i.push(113,it[n.effects>>6],it[63&n.effects]),d(n.effects)){i.push(it[n.noteFilter.controlPointCount]);for(let t=0;t<n.noteFilter.controlPointCount;t++){const e=n.noteFilter.controlPoints[t];i.push(it[e.type],it[e.freq],it[e.gain])}}if(l(n.effects)&&i.push(it[n.transition]),c(n.effects)&&i.push(it[n.chord]),u(n.effects)&&i.push(it[n.pitchShift]),f(n.effects)&&i.push(it[n.detune]),p(n.effects)&&i.push(it[n.vibrato]),m(n.effects)&&i.push(it[n.distortion]),y(n.effects)&&i.push(it[n.bitcrusherFreq],it[n.bitcrusherQuantization]),g(n.effects)&&i.push(it[n.pan]),b(n.effects)&&i.push(it[n.chorus]),w(n.effects)&&i.push(it[n.echoSustain],it[n.echoDelay]),v(n.effects)&&i.push(it[n.reverb]),4!=n.type&&i.push(100,it[n.fadeIn],it[n.fadeOut]),5==n.type||7==n.type){i.push(72);const t=new ot;for(let i=0;i<e.harmonicsControlPoints;i++)t.write(e.harmonicsControlPointBits,n.harmonicsWave.harmonics[i]);t.encodeBase64(i)}if(0==n.type)i.push(119,it[n.chipWave]),i.push(104,it[n.unison]);else if(1==n.type){i.push(65,it[n.algorithm]),i.push(70,it[n.feedbackType]),i.push(66,it[n.feedbackAmplitude]),i.push(81);for(let t=0;t<e.operatorCount;t++)i.push(it[n.operators[t].frequency]);i.push(80);for(let t=0;t<e.operatorCount;t++)i.push(it[n.operators[t].amplitude])}else if(2==n.type)i.push(119,it[n.chipNoise]);else if(3==n.type){i.push(83);const t=new ot;for(let i=0;i<e.spectrumControlPoints;i++)t.write(e.spectrumControlPointBits,n.spectrumWave.spectrum[i]);t.encodeBase64(i)}else if(4==n.type){i.push(122);for(let t=0;t<e.drumCount;t++)i.push(it[n.drumsetEnvelopes[t]]);i.push(83);const t=new ot;for(let i=0;i<e.drumCount;i++)for(let s=0;s<e.spectrumControlPoints;s++)t.write(e.spectrumControlPointBits,n.drumsetSpectrumWaves[i].spectrum[s]);t.encodeBase64(i)}else if(5==n.type)i.push(104,it[n.unison]);else if(6==n.type)i.push(87,it[n.pulseWidth]);else if(8==n.type)i.push(120,it[n.supersawDynamism],it[n.supersawSpread],it[n.supersawShape]),i.push(87,it[n.pulseWidth]);else{if(7!=n.type)throw new Error("Unknown instrument type.");if(i.push(104,it[n.unison]),e.stringSustainRange>32)throw new Error("Not enough bits to represent sustain value and type in same base64 character.");i.push(73,it[n.stringSustain|n.stringSustainType<<5])}i.push(69,it[n.envelopeCount]);for(let t=0;t<n.envelopeCount;t++)i.push(it[n.envelopes[t].target]),e.instrumentAutomationTargets[n.envelopes[t].target].maxCount>1&&i.push(it[n.envelopes[t].index]),i.push(it[n.envelopes[t].envelope])}i.push(98),t=new ot;let s=0;for(;1<<s<this.patternsPerChannel+1;)s++;for(let e=0;e<this.getChannelCount();e++)for(let i=0;i<this.barCount;i++)t.write(s,this.channels[e].bars[i]);t.encodeBase64(i),i.push(112),t=new ot;const n=new ot,o=wt.getNeededBits(e.noteSizeMax);for(let i=0;i<this.getChannelCount();i++){const s=this.channels[i],r=this.getMaxInstrumentsPerPattern(i),h=wt.getNeededBits(r-e.instrumentCountMin),a=wt.getNeededBits(s.instruments.length-1),l=this.getChannelIsNoise(i),c=l?0:s.octave*e.pitchesPerOctave;let u=l?4:c;const f=l?[4,6,7,2,3,8,0,10]:[0,7,12,19,24,-5,-12],p=[];for(let t=0;t<f.length;t++)f[t]+=c;for(const i of s.patterns){if(this.patternInstruments){const s=et(e.instrumentCountMin,r,i.instruments.length);t.write(h,s-e.instrumentCountMin);for(let e=0;e<s;e++)t.write(a,i.instruments[e])}if(i.notes.length>0){t.write(1,1);let s=0;for(const r of i.notes){r.start>s&&(t.write(2,0),t.writePartDuration(r.start-s)),n.clear();for(let t=1;t<r.pitches.length;t++)n.write(1,1);r.pitches.length<e.maxChordSize&&n.write(1,0),n.writePinCount(r.pins.length-1),n.write(o,r.pins[0].size);let i=0,h=r.pitches[0],a=h;const l=[];for(let t=1;t<r.pins.length;t++){const e=r.pins[t],s=h+e.interval;a!=s?(n.write(1,1),l.push(s),a=s):n.write(1,0),n.writePartDuration(e.time-i),i=e.time,n.write(o,e.size)}const c=String.fromCharCode.apply(null,n.encodeBase64([])),d=p.indexOf(c);-1==d?(t.write(2,1),t.concat(n)):(t.write(1,1),t.writeLongTail(0,0,d),p.splice(d,1)),p.unshift(c),p.length>10&&p.pop();const m=r.pitches.concat(l);for(let e=0;e<m.length;e++){const i=m[e],s=f.indexOf(i);if(-1==s){let e=0,s=u;if(s<i)for(;s!=i;)s++,-1==f.indexOf(s)&&e++;else for(;s!=i;)s--,-1==f.indexOf(s)&&e--;t.write(1,0),t.writePitchInterval(e)}else t.write(1,1),t.write(3,s),f.splice(s,1);f.unshift(i),f.length>8&&f.pop(),u=e==r.pitches.length-1?r.pitches[0]:i}0==r.start&&t.write(1,r.continuesLastPattern?1:0),s=r.end}s<this.beatsPerBar*e.partsPerBeat&&(t.write(2,0),t.writePartDuration(this.beatsPerBar*e.partsPerBeat-s))}else t.write(1,0)}}let r=t.lengthBase64(),h=[];for(;r>0;)h.unshift(it[63&r]),r>>=6;i.push(it[h.length]),Array.prototype.push.apply(i,h),t.encodeBase64(i);const a=64e3;if(i.length<a)return String.fromCharCode.apply(null,i);{let t="";for(let e=0;e<i.length;e+=a)t+=String.fromCharCode.apply(null,i.slice(e,e+a));return t}}static O(t){return 0==t?t=1:1==t&&(t=0),e.envelopes[tt(0,e.envelopes.length,t)]}fromBase64String(t){if(null==t||""==t)return void this.initToDefault(!0);let i=0;for(;t.charCodeAt(i)<=32;)i++;if(35==t.charCodeAt(i)&&i++,123==t.charCodeAt(i))return void this.fromJsonObject(JSON.parse(0==i?t:t.substring(i)));const s=st[t.charCodeAt(i++)];if(-1==s||s>wt.L||s<wt.N)return;const n=s<3,o=s<4,r=s<5,h=s<6,a=s<7,k=s<8,M=s<9;if(this.initToDefault(M),n){for(const t of this.channels)t.instruments[0].transition=e.transitions.dictionary.interrupt.index,t.instruments[0].effects|=1024;this.channels[3].instruments[0].chipNoise=0}let x=null;if(M){x=[];for(let t=x.length;t<this.getChannelCount();t++){x[t]=[];for(let i=0;i<e.instrumentCountMin;i++)x[t][i]={}}}let S,F=0,P=0,I=-1;for(;i<t.length;)switch(S=t.charCodeAt(i++)){case 110:this.pitchChannelCount=st[t.charCodeAt(i++)],this.noiseChannelCount=st[t.charCodeAt(i++)],this.pitchChannelCount=et(e.pitchChannelCountMin,e.pitchChannelCountMax,this.pitchChannelCount),this.noiseChannelCount=et(e.noiseChannelCountMin,e.noiseChannelCountMax,this.noiseChannelCount);for(let t=this.channels.length;t<this.getChannelCount();t++)this.channels[t]=new bt;if(this.channels.length=this.getChannelCount(),M)for(let t=x.length;t<this.getChannelCount();t++){x[t]=[];for(let i=0;i<e.instrumentCountMin;i++)x[t][i]={}}break;case 115:this.scale=st[t.charCodeAt(i++)],n&&10==this.scale&&(this.scale=11);break;case 107:this.key=tt(0,e.keys.length,a?11-st[t.charCodeAt(i++)]:st[t.charCodeAt(i++)]);break;case 108:this.loopStart=r?st[t.charCodeAt(i++)]:(st[t.charCodeAt(i++)]<<6)+st[t.charCodeAt(i++)];break;case 101:this.loopLength=r?st[t.charCodeAt(i++)]:(st[t.charCodeAt(i++)]<<6)+st[t.charCodeAt(i++)]+1;break;case 116:this.tempo=o?[95,120,151,190][st[t.charCodeAt(i++)]]:a?[88,95,103,111,120,130,140,151,163,176,190,206,222,240,259][st[t.charCodeAt(i++)]]:st[t.charCodeAt(i++)]<<6|st[t.charCodeAt(i++)],this.tempo=tt(e.tempoMin,e.tempoMax+1,this.tempo);break;case 109:M&&(F=st[t.charCodeAt(i++)],F=tt(0,4,F));break;case 97:this.beatsPerBar=n?[6,7,8,9,10][st[t.charCodeAt(i++)]]:st[t.charCodeAt(i++)]+1,this.beatsPerBar=Math.max(e.beatsPerBarMin,Math.min(e.beatsPerBarMax,this.beatsPerBar));break;case 103:{const s=(st[t.charCodeAt(i++)]<<6)+st[t.charCodeAt(i++)]+1;this.barCount=et(e.barCountMin,e.barCountMax,s);for(let t=0;t<this.getChannelCount();t++){for(let e=this.channels[t].bars.length;e<this.barCount;e++)this.channels[t].bars[e]=1;this.channels[t].bars.length=this.barCount}}break;case 106:{let s;s=k?st[t.charCodeAt(i++)]+1:(st[t.charCodeAt(i++)]<<6)+st[t.charCodeAt(i++)]+1,this.patternsPerChannel=et(1,e.barCountMax,s);const n=this.getChannelCount();for(let t=0;t<n;t++){const e=this.channels[t].patterns;for(let t=e.length;t<this.patternsPerChannel;t++)e[t]=new at;e.length=this.patternsPerChannel}}break;case 105:if(M){const s=et(e.instrumentCountMin,e.patternInstrumentCountMax,st[t.charCodeAt(i++)]+e.instrumentCountMin);this.layeredInstruments=!1,this.patternInstruments=s>1;for(let t=0;t<this.getChannelCount();t++){const e=t>=this.pitchChannelCount;for(let i=this.channels[t].instruments.length;i<s;i++)this.channels[t].instruments[i]=new gt(e);if(this.channels[t].instruments.length=s,h)for(let i=0;i<s;i++)this.channels[t].instruments[i].setTypeAndReset(e?2:0,e);for(let e=x[t].length;e<s;e++)x[t][e]={}}}else{const s=st[t.charCodeAt(i++)];this.layeredInstruments=0!=(2&s),this.patternInstruments=0!=(1&s);for(let s=0;s<this.getChannelCount();s++){let n=1;(this.layeredInstruments||this.patternInstruments)&&(n=et(e.instrumentCountMin,this.getMaxInstrumentsPerChannel(),st[t.charCodeAt(i++)]+e.instrumentCountMin));const o=this.channels[s],r=this.getChannelIsNoise(s);for(let t=o.instruments.length;t<n;t++)o.instruments[t]=new gt(r);o.instruments.length=n}}break;case 114:this.rhythm=st[t.charCodeAt(i++)];break;case 111:if(n){const s=st[t.charCodeAt(i++)];this.channels[s].octave=tt(0,e.pitchOctaves,st[t.charCodeAt(i++)]+1),s>=this.pitchChannelCount&&(this.channels[s].octave=0)}else if(M)for(let s=0;s<this.getChannelCount();s++)this.channels[s].octave=tt(0,e.pitchOctaves,st[t.charCodeAt(i++)]+1),s>=this.pitchChannelCount&&(this.channels[s].octave=0);else{for(let s=0;s<this.pitchChannelCount;s++)this.channels[s].octave=tt(0,e.pitchOctaves,st[t.charCodeAt(i++)]);for(let t=this.pitchChannelCount;t<this.getChannelCount();t++)this.channels[t].octave=0}break;case 84:{I++,I>=this.channels[P].instruments.length&&(P++,I=0),et(0,this.channels.length-1,P);const s=this.channels[P].instruments[I],n=et(0,8,st[t.charCodeAt(i++)]);s.setTypeAndReset(n,P>=this.pitchChannelCount),a&&(s.effects=0,F>0&&!this.getChannelIsNoise(P)&&(s.reverb=F,s.effects|=1),s.chord!=e.chords.dictionary.simultaneous.index&&(s.effects|=2048))}break;case 117:{const e=st[t.charCodeAt(i++)]<<6|st[t.charCodeAt(i++)];this.channels[P].instruments[I].preset=e}break;case 119:if(n){const s=[1,2,3,4,5,6,7,8,0],n=st[t.charCodeAt(i++)],o=this.channels[n].instruments[0];o.chipWave=tt(0,e.chipWaves.length,0|s[st[t.charCodeAt(i++)]]),o.convertLegacySettings(x[n][0])}else if(h){const s=[1,2,3,4,5,6,7,8,0];for(let n=0;n<this.getChannelCount();n++)for(const o of this.channels[n].instruments)n>=this.pitchChannelCount?o.chipNoise=tt(0,e.chipNoises.length,st[t.charCodeAt(i++)]):o.chipWave=tt(0,e.chipWaves.length,0|s[st[t.charCodeAt(i++)]])}else if(a){const s=[1,2,3,4,5,6,7,8,0];P>=this.pitchChannelCount?this.channels[P].instruments[I].chipNoise=tt(0,e.chipNoises.length,st[t.charCodeAt(i++)]):this.channels[P].instruments[I].chipWave=tt(0,e.chipWaves.length,0|s[st[t.charCodeAt(i++)]])}else P>=this.pitchChannelCount?this.channels[P].instruments[I].chipNoise=tt(0,e.chipNoises.length,st[t.charCodeAt(i++)]):this.channels[P].instruments[I].chipWave=tt(0,e.chipWaves.length,st[t.charCodeAt(i++)]);break;case 102:if(M)if(a){const s=[10,6,3,0,8,5,2],o=["none","none","none","none","decay 1","decay 2","decay 3"];if(n){const n=st[t.charCodeAt(i++)],r=this.channels[n].instruments[0],h=x[n][0],a=[1,3,4,5][tt(0,s.length,st[t.charCodeAt(i++)])];h.filterCutoff=s[a],h.filterResonance=0,h.filterEnvelope=e.envelopes.dictionary[o[a]],r.convertLegacySettings(h)}else if(h)for(let n=0;n<this.getChannelCount();n++)for(let r=0;r<this.channels[n].instruments.length;r++){const h=this.channels[n].instruments[r],a=x[n][r],l=tt(0,s.length,st[t.charCodeAt(i++)]+1);n<this.pitchChannelCount?(a.filterCutoff=s[l],a.filterResonance=0,a.filterEnvelope=e.envelopes.dictionary[o[l]]):(a.filterCutoff=10,a.filterResonance=0,a.filterEnvelope=e.envelopes.dictionary.none),h.convertLegacySettings(a)}else{const n=tt(0,s.length,st[t.charCodeAt(i++)]),r=this.channels[P].instruments[I],h=x[P][I];h.filterCutoff=s[n],h.filterResonance=0,h.filterEnvelope=e.envelopes.dictionary[o[n]],r.convertLegacySettings(h)}}else{const e=11,s=this.channels[P].instruments[I],n=x[P][I];n.filterCutoff=tt(0,e,st[t.charCodeAt(i++)]),s.convertLegacySettings(n)}else{const s=this.channels[P].instruments[I],n=st[t.charCodeAt(i++)];s.eqFilter.controlPointCount=tt(0,e.filterMaxPoints+1,n);for(let t=s.eqFilter.controlPoints.length;t<s.eqFilter.controlPointCount;t++)s.eqFilter.controlPoints[t]=new dt;for(let n=0;n<s.eqFilter.controlPointCount;n++){const o=s.eqFilter.controlPoints[n];o.type=tt(0,3,st[t.charCodeAt(i++)]),o.freq=tt(0,e.filterFreqRange,st[t.charCodeAt(i++)]),o.gain=tt(0,e.filterGainRange,st[t.charCodeAt(i++)])}for(let t=s.eqFilter.controlPointCount;t<n;t++)i+=3}break;case 121:if(M){const e=8,s=this.channels[P].instruments[I],n=x[P][I];n.filterResonance=tt(0,e,st[t.charCodeAt(i++)]),s.convertLegacySettings(n)}break;case 122:{const s=this.channels[P].instruments[I];if(M)if(4==s.type)for(let n=0;n<e.drumCount;n++)s.drumsetEnvelopes[n]=wt.O(st[t.charCodeAt(i++)]).index;else{const e=x[P][I];e.filterEnvelope=wt.O(st[t.charCodeAt(i++)]),s.convertLegacySettings(e)}else for(let n=0;n<e.drumCount;n++)s.drumsetEnvelopes[n]=tt(0,e.envelopes.length,st[t.charCodeAt(i++)])}break;case 87:{const s=this.channels[P].instruments[I];if(s.pulseWidth=tt(0,e.pulseWidthRange,st[t.charCodeAt(i++)]),M){const e=x[P][I];e.pulseEnvelope=wt.O(st[t.charCodeAt(i++)]),s.convertLegacySettings(e)}}break;case 120:{const s=this.channels[P].instruments[I];s.supersawDynamism=tt(0,e.supersawDynamismMax+1,st[t.charCodeAt(i++)]),s.supersawSpread=tt(0,e.supersawSpreadMax+1,st[t.charCodeAt(i++)]),s.supersawShape=tt(0,e.supersawShapeMax+1,st[t.charCodeAt(i++)])}break;case 73:{const s=this.channels[P].instruments[I],n=st[t.charCodeAt(i++)];s.stringSustain=tt(0,e.stringSustainRange,31&n),s.stringSustainType=e.enableAcousticSustain?tt(0,2,n>>5):0}break;case 100:if(M){const s=[{transition:"interrupt",fadeInSeconds:0,fadeOutTicks:-1},{transition:"normal",fadeInSeconds:0,fadeOutTicks:-3},{transition:"normal",fadeInSeconds:.025,fadeOutTicks:-3},{transition:"slide in pattern",fadeInSeconds:.025,fadeOutTicks:-3},{transition:"normal",fadeInSeconds:.04,fadeOutTicks:6},{transition:"normal",fadeInSeconds:0,fadeOutTicks:48},{transition:"normal",fadeInSeconds:.0125,fadeOutTicks:72},{transition:"normal",fadeInSeconds:.06,fadeOutTicks:96}];if(n){const n=st[t.charCodeAt(i++)],o=s[tt(0,s.length,st[t.charCodeAt(i++)])],r=this.channels[n].instruments[0];r.fadeIn=Ft.secondsToFadeInSetting(o.fadeInSeconds),r.fadeOut=Ft.ticksToFadeOutSetting(o.fadeOutTicks),r.transition=e.transitions.dictionary[o.transition].index,r.transition!=e.transitions.dictionary.normal.index&&(r.effects|=1024)}else if(h)for(let n=0;n<this.getChannelCount();n++)for(const o of this.channels[n].instruments){const n=s[tt(0,s.length,st[t.charCodeAt(i++)])];o.fadeIn=Ft.secondsToFadeInSetting(n.fadeInSeconds),o.fadeOut=Ft.ticksToFadeOutSetting(n.fadeOutTicks),o.transition=e.transitions.dictionary[n.transition].index,o.transition!=e.transitions.dictionary.normal.index&&(o.effects|=1024)}else{const n=s[tt(0,s.length,st[t.charCodeAt(i++)])],o=this.channels[P].instruments[I];o.fadeIn=Ft.secondsToFadeInSetting(n.fadeInSeconds),o.fadeOut=Ft.ticksToFadeOutSetting(n.fadeOutTicks),o.transition=e.transitions.dictionary[n.transition].index,o.transition!=e.transitions.dictionary.normal.index&&(o.effects|=1024)}}else{const s=this.channels[P].instruments[I];s.fadeIn=tt(0,e.fadeInRange,st[t.charCodeAt(i++)]),s.fadeOut=tt(0,e.fadeOutTicks.length,st[t.charCodeAt(i++)])}break;case 99:if(M)if(a)if(n){const s=[0,3,2,0],n=["none","none","none","tremolo2"],o=st[t.charCodeAt(i++)],r=tt(0,s.length,st[t.charCodeAt(i++)]),h=this.channels[o].instruments[0],a=x[o][0];h.vibrato=s[r],null!=a.filterEnvelope&&1!=a.filterEnvelope.type||(a.filterEnvelope=e.envelopes.dictionary[n[r]],h.convertLegacySettings(a)),h.vibrato!=e.vibratos.dictionary.none.index&&(h.effects|=512)}else if(h){const s=[0,1,2,3,0,0],n=["none","none","none","none","tremolo5","tremolo2"];for(let o=0;o<this.getChannelCount();o++)for(let r=0;r<this.channels[o].instruments.length;r++){const h=tt(0,s.length,st[t.charCodeAt(i++)]),a=this.channels[o].instruments[r],l=x[o][r];a.vibrato=s[h],null!=l.filterEnvelope&&1!=l.filterEnvelope.type||(l.filterEnvelope=e.envelopes.dictionary[n[h]],a.convertLegacySettings(l)),a.vibrato!=e.vibratos.dictionary.none.index&&(a.effects|=512),0==F||this.getChannelIsNoise(o)||(a.effects|=1,a.reverb=F)}}else{const s=[0,1,2,3,0,0],n=["none","none","none","none","tremolo5","tremolo2"],o=tt(0,s.length,st[t.charCodeAt(i++)]),r=this.channels[P].instruments[I],h=x[P][I];r.vibrato=s[o],null!=h.filterEnvelope&&1!=h.filterEnvelope.type||(h.filterEnvelope=e.envelopes.dictionary[n[o]],r.convertLegacySettings(h)),r.vibrato!=e.vibratos.dictionary.none.index&&(r.effects|=512),0!=F&&(r.effects|=1,r.reverb=F)}else{const s=this.channels[P].instruments[I],n=tt(0,e.vibratos.length,st[t.charCodeAt(i++)]);s.vibrato=n,s.vibrato!=e.vibratos.dictionary.none.index&&(s.effects|=512)}break;case 104:if(n){const s=st[t.charCodeAt(i++)];this.channels[s].instruments[0].unison=tt(0,e.unisons.length,st[t.charCodeAt(i++)])}else if(h)for(let s=0;s<this.getChannelCount();s++)for(const n of this.channels[s].instruments){const s=st[t.charCodeAt(i++)];let o=tt(0,e.unisons.length,s);8==s&&(o=2,n.chord=3),n.unison=o}else if(a){const s=st[t.charCodeAt(i++)];let n=tt(0,e.unisons.length,s);8==s&&(n=2,this.channels[P].instruments[I].chord=3),this.channels[P].instruments[I].unison=n}else this.channels[P].instruments[I].unison=tt(0,e.unisons.length,st[t.charCodeAt(i++)]);break;case 67:if(M){const s=this.channels[P].instruments[I];s.chord=tt(0,e.chords.length,st[t.charCodeAt(i++)]),s.chord!=e.chords.dictionary.simultaneous.index&&(s.effects|=2048)}break;case 113:{const s=this.channels[P].instruments[I];if(M){s.effects=4095&st[t.charCodeAt(i++)],0==F?s.effects&=-2:v(s.effects)&&(s.reverb=F),s.pan!=e.panCenter&&(s.effects|=4),s.vibrato!=e.vibratos.dictionary.none.index&&(s.effects|=4);const n=x[P][I];s.convertLegacySettings(n)}else{if(s.effects=st[t.charCodeAt(i++)]<<6|st[t.charCodeAt(i++)],d(s.effects)){const n=st[t.charCodeAt(i++)];s.noteFilter.controlPointCount=tt(0,e.filterMaxPoints+1,n);for(let t=s.noteFilter.controlPoints.length;t<s.noteFilter.controlPointCount;t++)s.noteFilter.controlPoints[t]=new dt;for(let n=0;n<s.noteFilter.controlPointCount;n++){const o=s.noteFilter.controlPoints[n];o.type=tt(0,3,st[t.charCodeAt(i++)]),o.freq=tt(0,e.filterFreqRange,st[t.charCodeAt(i++)]),o.gain=tt(0,e.filterGainRange,st[t.charCodeAt(i++)])}for(let t=s.noteFilter.controlPointCount;t<n;t++)i+=3}l(s.effects)&&(s.transition=tt(0,e.transitions.length,st[t.charCodeAt(i++)])),c(s.effects)&&(s.chord=tt(0,e.chords.length,st[t.charCodeAt(i++)])),u(s.effects)&&(s.pitchShift=tt(0,e.pitchShiftRange,st[t.charCodeAt(i++)])),f(s.effects)&&(s.detune=tt(0,e.detuneMax+1,st[t.charCodeAt(i++)])),p(s.effects)&&(s.vibrato=tt(0,e.vibratos.length,st[t.charCodeAt(i++)])),m(s.effects)&&(s.distortion=tt(0,e.distortionRange,st[t.charCodeAt(i++)])),y(s.effects)&&(s.bitcrusherFreq=tt(0,e.bitcrusherFreqRange,st[t.charCodeAt(i++)]),s.bitcrusherQuantization=tt(0,e.bitcrusherQuantizationRange,st[t.charCodeAt(i++)])),g(s.effects)&&(s.pan=tt(0,e.panMax+1,st[t.charCodeAt(i++)])),b(s.effects)&&(s.chorus=tt(0,e.chorusRange,st[t.charCodeAt(i++)])),w(s.effects)&&(s.echoSustain=tt(0,e.echoSustainRange,st[t.charCodeAt(i++)]),s.echoDelay=tt(0,e.echoDelayRange,st[t.charCodeAt(i++)])),v(s.effects)&&(s.reverb=tt(0,e.reverbRange,st[t.charCodeAt(i++)]))}s.effects&=4095}break;case 118:if(n){const s=st[t.charCodeAt(i++)],n=this.channels[s].instruments[0];n.volume=tt(0,e.volumeRange,st[t.charCodeAt(i++)]),5==n.volume&&(n.volume=e.volumeRange-1)}else if(h)for(let s=0;s<this.getChannelCount();s++)for(const n of this.channels[s].instruments)n.volume=tt(0,e.volumeRange,st[t.charCodeAt(i++)]),5==n.volume&&(n.volume=e.volumeRange-1);else if(a){const s=this.channels[P].instruments[I];s.volume=tt(0,e.volumeRange,st[t.charCodeAt(i++)]),5==s.volume&&(s.volume=e.volumeRange-1)}else{this.channels[P].instruments[I].volume=tt(0,e.volumeRange,st[t.charCodeAt(i++)])}break;case 76:if(M){this.channels[P].instruments[I].pan=tt(0,e.panMax+1,st[t.charCodeAt(i++)])}break;case 65:{const s=this.channels[P].instruments[I];if(s.algorithm=tt(0,e.algorithms.length,st[t.charCodeAt(i++)]),M){const t=x[P][I];s.convertLegacySettings(t)}}break;case 70:this.channels[P].instruments[I].feedbackType=tt(0,e.feedbacks.length,st[t.charCodeAt(i++)]);break;case 66:this.channels[P].instruments[I].feedbackAmplitude=tt(0,e.operatorAmplitudeMax+1,st[t.charCodeAt(i++)]);break;case 86:if(M){const e=this.channels[P].instruments[I],s=x[P][I];s.feedbackEnvelope=wt.O(st[t.charCodeAt(i++)]),e.convertLegacySettings(s)}break;case 81:for(let s=0;s<e.operatorCount;s++)this.channels[P].instruments[I].operators[s].frequency=tt(0,e.operatorFrequencies.length,st[t.charCodeAt(i++)]);break;case 80:for(let s=0;s<e.operatorCount;s++)this.channels[P].instruments[I].operators[s].amplitude=tt(0,e.operatorAmplitudeMax+1,st[t.charCodeAt(i++)]);break;case 69:{const s=this.channels[P].instruments[I];if(M){const n=x[P][I];n.operatorEnvelopes=[];for(let s=0;s<e.operatorCount;s++)n.operatorEnvelopes[s]=wt.O(st[t.charCodeAt(i++)]);s.convertLegacySettings(n)}else{const n=tt(0,e.maxEnvelopeCount+1,st[t.charCodeAt(i++)]);for(let o=0;o<n;o++){const n=tt(0,e.instrumentAutomationTargets.length,st[t.charCodeAt(i++)]);let o=0;const r=e.instrumentAutomationTargets[n].maxCount;r>1&&(o=tt(0,r,st[t.charCodeAt(i++)]));const h=tt(0,e.envelopes.length,st[t.charCodeAt(i++)]);s.addEnvelope(n,o,h)}}}break;case 83:{const s=this.channels[P].instruments[I];if(3==s.type){const n=Math.ceil(e.spectrumControlPoints*e.spectrumControlPointBits/6),o=new nt(t,i,i+n);for(let t=0;t<e.spectrumControlPoints;t++)s.spectrumWave.spectrum[t]=o.read(e.spectrumControlPointBits);s.spectrumWave.markCustomWaveDirty(),i+=n}else{if(4!=s.type)throw new Error("Unhandled instrument type for spectrum song tag code.");{const n=Math.ceil(e.drumCount*e.spectrumControlPoints*e.spectrumControlPointBits/6),o=new nt(t,i,i+n);for(let t=0;t<e.drumCount;t++){for(let i=0;i<e.spectrumControlPoints;i++)s.drumsetSpectrumWaves[t].spectrum[i]=o.read(e.spectrumControlPointBits);s.drumsetSpectrumWaves[t].markCustomWaveDirty()}i+=n}}}break;case 72:{const s=this.channels[P].instruments[I],n=Math.ceil(e.harmonicsControlPoints*e.harmonicsControlPointBits/6),o=new nt(t,i,i+n);for(let t=0;t<e.harmonicsControlPoints;t++)s.harmonicsWave.harmonics[t]=o.read(e.harmonicsControlPointBits);s.harmonicsWave.markCustomWaveDirty(),i+=n}break;case 98:{let e;if(n){const s=st[t.charCodeAt(i++)],n=st[t.charCodeAt(i++)];e=Math.ceil(.5*n);const o=new nt(t,i,i+e);for(let t=0;t<n;t++)this.channels[s].bars[t]=o.read(3)+1}else if(r){let s=0;for(;1<<s<this.patternsPerChannel;)s++;e=Math.ceil(this.getChannelCount()*this.barCount*s/6);const n=new nt(t,i,i+e);for(let t=0;t<this.getChannelCount();t++)for(let e=0;e<this.barCount;e++)this.channels[t].bars[e]=n.read(s)+1}else{let s=0;for(;1<<s<this.patternsPerChannel+1;)s++;e=Math.ceil(this.getChannelCount()*this.barCount*s/6);const n=new nt(t,i,i+e);for(let t=0;t<this.getChannelCount();t++)for(let e=0;e<this.barCount;e++)this.channels[t].bars[e]=n.read(s)}i+=e}break;case 112:{let s,o=0;if(n)s=st[t.charCodeAt(i++)],i++,o=st[t.charCodeAt(i++)],o<<=6,o+=st[t.charCodeAt(i++)];else{s=0;let e=et(1,4,st[t.charCodeAt(i++)]);for(;e>0;)o<<=6,o+=st[t.charCodeAt(i++)],e--}const r=new nt(t,i,i+o);i+=o;const h=wt.getNeededBits(e.noteSizeMax);for(;;){const t=this.channels[s],i=this.getChannelIsNoise(s),o=this.getMaxInstrumentsPerPattern(s),l=wt.getNeededBits(o-e.instrumentCountMin),c=wt.getNeededBits(t.instruments.length-1),u=i?0:12*t.octave;let f=i?4:u;const p=i?[4,6,7,2,3,8,0,10]:[0,7,12,19,24,-5,-12],d=[];for(let t=0;t<p.length;t++)p[t]+=u;for(let i=0;i<this.patternsPerChannel;i++){const s=t.patterns[i];if(M)s.instruments[0]=et(0,t.instruments.length-1,r.read(c)),s.instruments.length=1;else if(this.patternInstruments){const i=et(e.instrumentCountMin,o,r.read(l)+e.instrumentCountMin);for(let e=0;e<i;e++)s.instruments[e]=et(0,t.instruments.length-1,r.read(c));s.instruments.length=i}else s.instruments[0]=0,s.instruments.length=e.instrumentCountMin;if(!n&&0==r.read(1)){s.notes.length=0;continue}let u=0;const m=s.notes;let y=0;for(;u<this.beatsPerBar*e.partsPerBeat;){const t=1==r.read(1);let i=!1,s=0;if(t?s=et(0,d.length-1,r.readLongTail(0,0)):i=1==r.read(1),t||i){let i,n,o;if(t)i=d[s],d.splice(s,1);else{for(i={},i.pitchCount=1;i.pitchCount<e.maxChordSize&&1==r.read(1);)i.pitchCount++;i.pinCount=r.readPinCount(),i.initialSize=r.read(h),i.pins=[],i.length=0,i.bendCount=0;for(let t=0;t<i.pinCount;t++){let t={};t.pitchBend=1==r.read(1),t.pitchBend&&i.bendCount++,i.length+=a?r.readLegacyPartDuration()*e.partsPerBeat/e.rhythms[this.rhythm].stepsPerBeat:r.readPartDuration(),t.time=i.length,t.size=r.read(h),i.pins.push(t)}}d.unshift(i),d.length>10&&d.pop(),m.length<=y?(n=new ht(0,u,u+i.length,i.initialSize),m[y++]=n):(n=m[y++],n.start=u,n.end=u+i.length,n.pins[0].size=i.initialSize);let l=0;const c=[];for(let t=0;t<i.pitchCount+i.bendCount;t++){if(1==r.read(1)){const t=et(0,p.length-1,r.read(3));o=p[t],p.splice(t,1)}else{const t=r.readPitchInterval();o=f;let e=t;for(;e>0;){for(o++;-1!=p.indexOf(o);)o++;e--}for(;e<0;){for(o--;-1!=p.indexOf(o);)o--;e++}}p.unshift(o),p.length>8&&p.pop(),t<i.pitchCount?n.pitches[l++]=o:c.push(o),f=t==i.pitchCount-1?n.pitches[0]:o}n.pitches.length=l,c.unshift(n.pitches[0]);let g=1;for(const t of i.pins){t.pitchBend&&c.shift();const e=c[0]-n.pitches[0];if(n.pins.length<=g)n.pins[g++]=rt(e,t.time,t.size);else{const i=n.pins[g++];i.interval=e,i.time=t.time,i.size=t.size}}n.pins.length=g,0!=n.start||M?n.continuesLastPattern=!1:n.continuesLastPattern=1==r.read(1),u=et(0,this.beatsPerBar*e.partsPerBeat,n.end)}else{u+=a?r.readLegacyPartDuration()*e.partsPerBeat/e.rhythms[this.rhythm].stepsPerBeat:r.readPartDuration()}}m.length=y}if(n)break;if(s++,s>=this.getChannelCount())break}}break;default:throw new Error("Unrecognized song tag code "+String.fromCharCode(S)+" at index "+(i-1))}}toJsonObject(t=!0,i=1,s=!0){const n=[];for(let e=0;e<this.getChannelCount();e++){const o=this.channels[e],r=[],h=this.getChannelIsNoise(e);for(const t of o.instruments)r.push(t.toJsonObject());const a=[];for(const t of o.patterns)a.push(t.toJsonObject(this));const l=[];if(t)for(let t=0;t<this.loopStart;t++)l.push(o.bars[t]);for(let t=0;t<i;t++)for(let t=this.loopStart;t<this.loopStart+this.loopLength;t++)l.push(o.bars[t]);if(s)for(let t=this.loopStart+this.loopLength;t<this.barCount;t++)l.push(o.bars[t]);const c={type:h?"drum":"pitch",instruments:r,patterns:a,sequence:l};h||(c.octaveScrollBar=o.octave-1),n.push(c)}return{format:wt.R,version:wt.L,scale:e.scales[this.scale].name,key:e.keys[this.key].name,introBars:this.loopStart,loopBars:this.loopLength,beatsPerBar:this.beatsPerBar,ticksPerBeat:e.rhythms[this.rhythm].stepsPerBeat,beatsPerMinute:this.tempo,layeredInstruments:this.layeredInstruments,patternInstruments:this.patternInstruments,channels:n}}fromJsonObject(t){if(this.initToDefault(!0),!t)return;if(this.scale=11,null!=t.scale){const i={"romani :)":"double harmonic :)","romani :(":"double harmonic :(","dbl harmonic :)":"double harmonic :)","dbl harmonic :(":"double harmonic :(",enigma:"strange"},s=null!=i[t.scale]?i[t.scale]:t.scale,n=e.scales.findIndex((t=>t.name==s));-1!=n&&(this.scale=n)}if(null!=t.key)if("number"==typeof t.key)this.key=(t.key+1200>>>0)%e.keys.length;else if("string"==typeof t.key){const e=t.key,i=e.charAt(0).toUpperCase(),s=e.charAt(1).toLowerCase();let n={C:0,D:2,E:4,F:5,G:7,A:9,B:11}[i];const o={"#":1,"♯":1,b:-1,"♭":-1}[s];null!=n&&(null!=o&&(n+=o),n<0&&(n+=12),n%=12,this.key=n)}null!=t.beatsPerMinute&&(this.tempo=tt(e.tempoMin,e.tempoMax+1,0|t.beatsPerMinute));let i=0;null!=t.reverb&&(i=tt(0,4,0|t.reverb)),null!=t.beatsPerBar&&(this.beatsPerBar=Math.max(e.beatsPerBarMin,Math.min(e.beatsPerBarMax,0|t.beatsPerBar)));let s=4;null!=t.ticksPerBeat&&(s=0|t.ticksPerBeat||4,this.rhythm=e.rhythms.findIndex((t=>t.stepsPerBeat==s)),-1==this.rhythm&&(this.rhythm=1));let n=1,o=1,r=1;if(null!=t.channels)for(const e of t.channels)e.instruments&&(n=Math.max(n,0|e.instruments.length)),e.patterns&&(o=Math.max(o,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=n>1,this.patternsPerChannel=Math.min(o,e.barCountMax),this.barCount=Math.min(r,e.barCountMax),null!=t.introBars&&(this.loopStart=tt(0,this.barCount,0|t.introBars)),null!=t.loopBars&&(this.loopLength=tt(1,this.barCount-this.loopStart+1,0|t.loopBars));const h=[],a=[];if(null!=t.channels)for(let n=0;n<t.channels.length;n++){let o=t.channels[n];const r=new bt;let l=!1;if(l=null!=o.type?"drum"==o.type:n>=3,l?a.push(r):h.push(r),null!=o.octaveScrollBar&&(r.octave=tt(0,e.pitchOctaves,1+(0|o.octaveScrollBar)),l&&(r.octave=0)),Array.isArray(o.instruments)){const t=o.instruments;for(let e=0;e<t.length&&!(e>=this.getMaxInstrumentsPerChannel());e++){const s=new gt(l);r.instruments[e]=s,s.fromJsonObject(t[e],l,i)}}for(let t=0;t<this.patternsPerChannel;t++){const e=new at;let i;r.patterns[t]=e,o.patterns&&(i=o.patterns[t]),null!=i&&e.fromJsonObject(i,this,r,s,l)}r.patterns.length=this.patternsPerChannel;for(let t=0;t<this.barCount;t++)r.bars[t]=null!=o.sequence?Math.min(this.patternsPerChannel,o.sequence[t]>>>0):0;r.bars.length=this.barCount}h.length>e.pitchChannelCountMax&&(h.length=e.pitchChannelCountMax),a.length>e.noiseChannelCountMax&&(a.length=e.noiseChannelCountMax),this.pitchChannelCount=h.length,this.noiseChannelCount=a.length,this.channels.length=0,Array.prototype.push.apply(this.channels,h),Array.prototype.push.apply(this.channels,a)}getPattern(t,e){if(e<0||e>=this.barCount)return null;const i=this.channels[t].bars[e];return 0==i?null:this.channels[t].patterns[i-1]}getBeatsPerMinute(){return this.tempo}static getNeededBits(t){return 32-Math.clz32(Math.ceil(t+1)-1)}}wt.R="BeepBox",wt.N=2,wt.L=9;class vt{constructor(){this.delayLine=null,this.allPassG=0,this.allPassGDelta=0,this.sustainFilterA1=0,this.sustainFilterA1Delta=0,this.sustainFilterA2=0,this.sustainFilterA2Delta=0,this.sustainFilterB0=0,this.sustainFilterB0Delta=0,this.sustainFilterB1=0,this.sustainFilterB1Delta=0,this.sustainFilterB2=0,this.sustainFilterB2Delta=0,this.reset()}reset(){this.delayIndex=-1,this.allPassSample=0,this.allPassPrevInput=0,this.sustainFilterSample=0,this.sustainFilterPrevOutput2=0,this.sustainFilterPrevInput1=0,this.sustainFilterPrevInput2=0,this.fractionalDelaySample=0,this.prevDelayLength=-1,this.delayResetOffset=0}update(t,i,s,n,o,r,h,a){const l=2*Math.PI*e.pickedStringDispersionCenterFreq/t.samplesPerSecond,c=this.prevDelayLength,u=s.phaseDeltas[n],f=s.phaseDeltaScales[n],p=u*Math.pow(f,o),d=2*Math.PI*u,m=2*Math.PI*p,y=2*d,g=2*m,b=Math.min(Math.PI,d*e.pickedStringDispersionFreqMult*Math.pow(l/d,e.pickedStringDispersionFreqScale)),w=Math.min(Math.PI,m*e.pickedStringDispersionFreqMult*Math.pow(l/m,e.pickedStringDispersionFreqScale)),v=2*Math.PI*e.pickedStringShelfHz/t.samplesPerSecond,k=(Math.pow(100,r)-1)/99,M=(Math.pow(100,h)-1)/99,x=1==a?.25:0,S=15.6,F=3*t.samplesPerSecond/48e3,P=Math.pow(.5,k*Math.pow(v/(d*S),1+2*x)*S),I=Math.pow(.5,M*Math.pow(v/(m*S),1+2*x)*S),T=Math.pow(P,.002),q=Math.pow(I,.002);Ft.tempFilterStartCoefficients.allPass1stOrderInvertPhaseAbove(b),t.tempFrequencyResponse.analyze(Ft.tempFilterStartCoefficients,y);const E=Ft.tempFilterStartCoefficients.b[0],C=-t.tempFrequencyResponse.angle()/y;Ft.tempFilterEndCoefficients.allPass1stOrderInvertPhaseAbove(w),t.tempFrequencyResponse.analyze(Ft.tempFilterEndCoefficients,g);const L=Ft.tempFilterEndCoefficients.b[0],z=-t.tempFrequencyResponse.angle()/g,D=0==a?0:1;if(0==D){const t=Math.pow(P,e.stringDecayRate),i=Math.pow(I,e.stringDecayRate);Ft.tempFilterStartCoefficients.highShelf2ndOrder(v,t,.5),Ft.tempFilterEndCoefficients.highShelf2ndOrder(v,i,.5)}else{const e=Math.pow(1==D?0:1,.25),i=Math.pow(F*F*d*3.3*48e3/t.samplesPerSecond,.5+x)/F/Math.pow(k,.5),s=Math.pow(F*F*m*3.3*48e3/t.samplesPerSecond,.5+x)/F/Math.pow(M,.5),n=i*Math.pow(2,.5-1.75*(1-Math.pow(1-e,.85))),o=s*Math.pow(2,.5-1.75*(1-Math.pow(1-e,.85))),r=Math.pow(2,-Math.pow(2,-Math.pow(e,.9))),h=Math.pow(2,-Math.pow(2,-Math.pow(e,.9)));Ft.tempFilterStartCoefficients.lowPass2ndOrderButterworth(X(n),r),Ft.tempFilterEndCoefficients.lowPass2ndOrderButterworth(X(o),h)}t.tempFrequencyResponse.analyze(Ft.tempFilterStartCoefficients,y);const A=Ft.tempFilterStartCoefficients.a[1],B=Ft.tempFilterStartCoefficients.a[2],O=Ft.tempFilterStartCoefficients.b[0]*T,N=Ft.tempFilterStartCoefficients.b[1]*T,R=Ft.tempFilterStartCoefficients.b[2]*T,H=-t.tempFrequencyResponse.angle()/y;t.tempFrequencyResponse.analyze(Ft.tempFilterEndCoefficients,g);const G=Ft.tempFilterEndCoefficients.a[1],$=Ft.tempFilterEndCoefficients.a[2],_=Ft.tempFilterEndCoefficients.b[0]*q,U=Ft.tempFilterEndCoefficients.b[1]*q,V=Ft.tempFilterEndCoefficients.b[2]*q,j=-t.tempFrequencyResponse.angle()/g,W=1/u,K=1/p,Y=Math.ceil(2*Math.max(W,K)),J=W-C-H,Q=K-z-j;this.prevDelayLength=J,this.delayLengthDelta=(Q-J)/o,this.allPassG=E,this.sustainFilterA1=A,this.sustainFilterA2=B,this.sustainFilterB0=O,this.sustainFilterB1=N,this.sustainFilterB2=R,this.allPassGDelta=(L-E)/o,this.sustainFilterA1Delta=(G-A)/o,this.sustainFilterA2Delta=($-B)/o,this.sustainFilterB0Delta=(_-O)/o,this.sustainFilterB1Delta=(U-N)/o,this.sustainFilterB2Delta=(V-R)/o;const Z=Math.abs(Math.log2(J/c))>.01,tt=-1==this.delayIndex||Z;if(null==this.delayLine||this.delayLine.length<=Y){const e=Math.ceil(2*t.samplesPerSecond/gt.frequencyFromPitch(12)),i=new Float32Array(Ft.fittingPowerOfTwo(Math.max(e,Y)));if(!tt&&null!=this.delayLine){const t=this.delayLine.length-1>>0,e=this.delayIndex+this.delayResetOffset;this.delayIndex=this.delayLine.length-this.delayResetOffset;for(let s=0;s<this.delayLine.length;s++)i[s]=this.delayLine[e+s&t]}this.delayLine=i}const et=this.delayLine,it=et.length-1>>0;if(tt){this.delayIndex=0,this.allPassSample=0,this.allPassPrevInput=0,this.sustainFilterSample=0,this.sustainFilterPrevOutput2=0,this.sustainFilterPrevInput1=0,this.sustainFilterPrevInput2=0,this.fractionalDelaySample=0;const e=-J,s=Math.floor(e-W/2),n=Math.ceil(s+2*W);this.delayResetOffset=n;for(let t=s;t<=n;t++)et[t&it]=0;const o=i.wave,r=o.length-1,h=r/W,a=Math.min(.2*W,.003*t.samplesPerSecond),l=Math.ceil(e),c=e+W+a,u=c;let f=(l-e)*h,p=0;for(let t=l;t<=u;t++){const i=0|f,s=i%r;let n=o[s];const l=f-i;n+=(o[s+1]-n)*l;const u=(n-p)/h,d=Math.min(1,(t-e)/a)*Math.min(1,(c-t)/a),m=d*d*(3-2*d);et[t&it]+=u*m,p=n,f+=h}}}}class kt{constructor(){this.noteSecondsStart=0,this.noteSecondsEnd=0,this.noteTicksStart=0,this.noteTicksEnd=0,this.noteSizeStart=e.noteSizeMax,this.noteSizeEnd=e.noteSizeMax,this.prevNoteSize=e.noteSizeMax,this.nextNoteSize=e.noteSizeMax,this.H=e.noteSizeMax,this.prevNoteSecondsStart=0,this.prevNoteSecondsEnd=0,this.prevNoteTicksStart=0,this.prevNoteTicksEnd=0,this.$=e.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._=[],this.U=0,this.lowpassCutoffDecayVolumeCompensation=1;for(let t=0;t<36;t++)this.envelopeStarts[t]=1,this.envelopeEnds[t]=1;this.reset()}reset(){this.noteSecondsEnd=0,this.noteTicksEnd=0,this.H=e.noteSizeMax,this.prevNoteSecondsEnd=0,this.prevNoteTicksEnd=0,this.$=e.noteSizeMax,this.U=0}computeEnvelopes(t,i,s,n,o){const r=t.getTransition();null==o||!o.atNoteStart||r.continues||o.forceContinueAtStart||(this.prevNoteSecondsEnd=this.noteSecondsEnd,this.prevNoteTicksEnd=this.noteTicksEnd,this.$=this.H,this.noteSecondsEnd=0,this.noteTicksEnd=0),null!=o&&(null!=o.note?this.H=o.note.pins[o.note.pins.length-1].size:this.H=e.noteSizeMax);const h=s+1,a=this.noteSecondsEnd,l=a+n,c=this.noteTicksEnd,u=c+1,f=this.prevNoteSecondsEnd,p=f+n,d=this.prevNoteTicksEnd,m=d+1,y=1/(e.ticksPerPart*e.partsPerBeat),g=y*s,b=y*h;let w=this.H,v=this.H,k=this.$,M=0,x=!1,S=!1,F=!1,P=!1,I=0,T=0,q=0,E=0;if(null!=o&&null!=o.note&&!o.passedEndOfNote){const t=o.note.getEndPinIndex(i),n=o.note.pins[t-1],a=o.note.pins[t],l=(o.note.start+n.time)*e.ticksPerPart,c=(o.note.start+a.time)*e.ticksPerPart,u=(s-l)/(c-l),f=(h-l)/(c-l);if(w=n.size+(a.size-n.size)*u,v=n.size+(a.size-n.size)*f,r.slides){const t=o.noteStartPart*e.ticksPerPart,i=o.noteEndPart*e.ticksPerPart,n=.5*(i-t),a=Math.min(n,r.slideTicks);null==o.prevNote||o.forceContinueAtStart||(s-t<a&&(x=!0,I=.5*(1-(s-t)/a)),h-t<a&&(S=!0,T=.5*(1-(h-t)/a))),null==o.nextNote||o.forceContinueAtEnd||(M=o.nextNote.pins[0].size,i-s<a&&(F=!0,q=.5*(1-(i-s)/a)),i-h<a&&(P=!0,E=.5*(1-(i-h)/a)))}}let C=1,L=!1;for(let i=0;i<=t.envelopeCount;i++){let s,n,o;if(i==t.envelopeCount){if(L)break;s=e.instrumentAutomationTargets.dictionary.noteVolume,n=0,o=e.envelopes.dictionary["note size"]}else{let r=t.envelopes[i];s=e.instrumentAutomationTargets[r.target],n=r.index,o=e.envelopes[r.envelope],0==o.type&&(L=!0)}if(null!=s.computeIndex){const e=s.computeIndex+n;let i=kt.computeEnvelope(o,a,g,w),r=kt.computeEnvelope(o,l,b,v);if(x){i+=(kt.computeEnvelope(o,f,g,k)-i)*I}if(S){r+=(kt.computeEnvelope(o,p,b,k)-r)*T}if(F){i+=(kt.computeEnvelope(o,0,g,M)-i)*q}if(P){r+=(kt.computeEnvelope(o,0,b,M)-r)*E}if(this.envelopeStarts[e]*=i,this.envelopeEnds[e]*=r,this._[this.U++]=e,s.isFilter){const e=t.noteFilter;e.controlPointCount>n&&0==e.controlPoints[n].type&&(C=Math.max(C,kt.getLowpassCutoffDecayVolumeCompensation(o)))}}}this.noteSecondsStart=a,this.noteSecondsEnd=l,this.noteTicksStart=c,this.noteTicksEnd=u,this.prevNoteSecondsStart=f,this.prevNoteSecondsEnd=p,this.prevNoteTicksStart=d,this.prevNoteTicksEnd=m,this.prevNoteSize=k,this.nextNoteSize=M,this.noteSizeStart=w,this.noteSizeEnd=v,this.prevSlideStart=x,this.prevSlideEnd=S,this.nextSlideStart=F,this.nextSlideEnd=P,this.prevSlideRatioStart=I,this.prevSlideRatioEnd=T,this.nextSlideRatioStart=q,this.nextSlideRatioEnd=E,this.lowpassCutoffDecayVolumeCompensation=C}clearEnvelopes(){for(let t=0;t<this.U;t++){const e=this._[t];this.envelopeStarts[e]=1,this.envelopeEnds[e]=1}this.U=0}static computeEnvelope(t,e,i,s){switch(t.type){case 0:return Ft.noteSizeToVolumeMult(s);case 1:return 1;case 4:return 1/(1+e*t.speed);case 5:return 1-1/(1+e*t.speed);case 6:return.5-.5*Math.cos(2*i*Math.PI*t.speed);case 7:return.75-.25*Math.cos(2*i*Math.PI*t.speed);case 2:return Math.max(1,2-10*e);case 3:const n=.25/Math.sqrt(t.speed);return e<n?e/n:1/(1+(e-n)*t.speed);case 8:return Math.pow(2,-t.speed*e);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 Mt{constructor(){this.pitches=Array(e.maxChordSize).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.phases=[],this.phaseDeltas=[],this.phaseDeltaScales=[],this.expression=0,this.expressionDelta=0,this.operatorExpressions=[],this.operatorExpressionDeltas=[],this.prevPitchExpressions=Array(e.maxPitchOrOperatorCount).fill(null),this.prevVibrato=null,this.prevStringDecay=null,this.pulseWidth=0,this.pulseWidthDelta=0,this.supersawDynamism=0,this.supersawDynamismDelta=0,this.supersawUnisonDetunes=[],this.supersawShape=0,this.supersawShapeDelta=0,this.supersawDelayLength=0,this.supersawDelayLengthDelta=0,this.supersawDelayLine=null,this.supersawDelayIndex=-1,this.supersawPrevPhaseDelta=null,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.envelopeComputer=new kt,this.reset()}reset(){this.noiseSample=0;for(let t=0;t<e.maxPitchOrOperatorCount;t++)this.phases[t]=0,this.feedbackOutputs[t]=0,this.prevPitchExpressions[t]=null;for(let t=0;t<this.noteFilterCount;t++)this.noteFilters[t].resetOutput();this.noteFilterCount=0,this.initialNoteFilterInput1=0,this.initialNoteFilterInput2=0,this.liveInputSamplesHeld=0,this.supersawDelayIndex=-1;for(const t of this.pickedStrings)t.reset();this.envelopeComputer.reset(),this.prevVibrato=null,this.prevStringDecay=null,this.supersawPrevPhaseDelta=null,this.drumsetPitch=null}}class xt{constructor(){this.awake=!1,this.computed=!1,this.tonesAddedInThisTick=!1,this.flushingDelayLines=!1,this.deactivateAfterThisTick=!1,this.attentuationProgress=0,this.flushedSamples=0,this.activeTones=new K,this.releasedTones=new K,this.liveInputTones=new K,this.type=0,this.synthesizer=null,this.wave=null,this.noisePitchFilterMult=1,this.unison=null,this.chord=null,this.effects=0,this.eqFilterVolume=1,this.eqFilterVolumeDelta=0,this.mixVolume=1,this.mixVolumeDelta=0,this.delayInputMult=0,this.delayInputMultDelta=0,this.distortion=0,this.distortionDelta=0,this.distortionDrive=0,this.distortionDriveDelta=0,this.distortionFractionalInput1=0,this.distortionFractionalInput2=0,this.distortionFractionalInput3=0,this.distortionPrevInput=0,this.distortionNextOutput=0,this.bitcrusherPrevInput=0,this.bitcrusherCurrentOutput=0,this.bitcrusherPhase=1,this.bitcrusherPhaseDelta=0,this.bitcrusherPhaseDeltaScale=1,this.bitcrusherScale=1,this.bitcrusherScaleScale=1,this.bitcrusherFoldLevel=1,this.bitcrusherFoldLevelScale=1,this.eqFilters=[],this.eqFilterCount=0,this.initialEqFilterInput1=0,this.initialEqFilterInput2=0,this.panningDelayLine=null,this.panningDelayPos=0,this.panningVolumeL=0,this.panningVolumeR=0,this.panningVolumeDeltaL=0,this.panningVolumeDeltaR=0,this.panningOffsetL=0,this.panningOffsetR=0,this.panningOffsetDeltaL=0,this.panningOffsetDeltaR=0,this.chorusDelayLineL=null,this.chorusDelayLineR=null,this.chorusDelayLineDirty=!1,this.chorusDelayPos=0,this.chorusPhase=0,this.chorusVoiceMult=0,this.chorusVoiceMultDelta=0,this.chorusCombinedMult=0,this.chorusCombinedMultDelta=0,this.echoDelayLineL=null,this.echoDelayLineR=null,this.echoDelayLineDirty=!1,this.echoDelayPos=0,this.echoDelayOffsetStart=0,this.echoDelayOffsetEnd=null,this.echoDelayOffsetRatio=0,this.echoDelayOffsetRatioDelta=0,this.echoMult=0,this.echoMultDelta=0,this.echoShelfA1=0,this.echoShelfB0=0,this.echoShelfB1=0,this.echoShelfSampleL=0,this.echoShelfSampleR=0,this.echoShelfPrevInputL=0,this.echoShelfPrevInputR=0,this.reverbDelayLine=null,this.reverbDelayLineDirty=!1,this.reverbDelayPos=0,this.reverbMult=0,this.reverbMultDelta=0,this.reverbShelfA1=0,this.reverbShelfB0=0,this.reverbShelfB1=0,this.reverbShelfSample0=0,this.reverbShelfSample1=0,this.reverbShelfSample2=0,this.reverbShelfSample3=0,this.reverbShelfPrevInput0=0,this.reverbShelfPrevInput1=0,this.reverbShelfPrevInput2=0,this.reverbShelfPrevInput3=0,this.spectrumWave=new ut,this.harmonicsWave=new pt,this.drumsetSpectrumWaves=[];for(let t=0;t<e.drumCount;t++)this.drumsetSpectrumWaves[t]=new ut}allocateNecessaryBuffers(t,i,s){if(g(i.effects)&&(null==this.panningDelayLine||this.panningDelayLine.length<t.panningDelayBufferSize)&&(this.panningDelayLine=new Float32Array(t.panningDelayBufferSize)),b(i.effects)&&((null==this.chorusDelayLineL||this.chorusDelayLineL.length<t.chorusDelayBufferSize)&&(this.chorusDelayLineL=new Float32Array(t.chorusDelayBufferSize)),(null==this.chorusDelayLineR||this.chorusDelayLineR.length<t.chorusDelayBufferSize)&&(this.chorusDelayLineR=new Float32Array(t.chorusDelayBufferSize))),w(i.effects)){const t=Math.max(e.echoDelayRange>>1,i.echoDelay+1),n=2*Ft.fittingPowerOfTwo(t*e.echoDelayStepTicks*s);if(null==this.echoDelayLineL||null==this.echoDelayLineR)this.echoDelayLineL=new Float32Array(n),this.echoDelayLineR=new Float32Array(n);else if(this.echoDelayLineL.length<n||this.echoDelayLineR.length<n){const t=new Float32Array(n),e=new Float32Array(n),i=this.echoDelayLineL.length-1;for(let s=0;s<this.echoDelayLineL.length;s++)t[s]=this.echoDelayLineL[this.echoDelayPos+s&i],e[s]=this.echoDelayLineL[this.echoDelayPos+s&i];this.echoDelayPos=this.echoDelayLineL.length,this.echoDelayLineL=t,this.echoDelayLineR=e}}v(i.effects)&&null==this.reverbDelayLine&&(this.reverbDelayLine=new Float32Array(e.reverbDelayBufferSize))}deactivate(){this.bitcrusherPrevInput=0,this.bitcrusherCurrentOutput=0,this.bitcrusherPhase=1;for(let t=0;t<this.eqFilterCount;t++)this.eqFilters[t].resetOutput();if(this.eqFilterCount=0,this.initialEqFilterInput1=0,this.initialEqFilterInput2=0,this.distortionFractionalInput1=0,this.distortionFractionalInput2=0,this.distortionFractionalInput3=0,this.distortionPrevInput=0,this.distortionNextOutput=0,this.panningDelayPos=0,null!=this.panningDelayLine)for(let t=0;t<this.panningDelayLine.length;t++)this.panningDelayLine[t]=0;this.echoDelayOffsetEnd=null,this.echoShelfSampleL=0,this.echoShelfSampleR=0,this.echoShelfPrevInputL=0,this.echoShelfPrevInputR=0,this.reverbShelfSample0=0,this.reverbShelfSample1=0,this.reverbShelfSample2=0,this.reverbShelfSample3=0,this.reverbShelfPrevInput0=0,this.reverbShelfPrevInput1=0,this.reverbShelfPrevInput2=0,this.reverbShelfPrevInput3=0,this.awake=!1,this.flushingDelayLines=!1,this.deactivateAfterThisTick=!1,this.attentuationProgress=0,this.flushedSamples=0}resetAllEffects(){if(this.deactivate(),this.chorusDelayLineDirty){for(let t=0;t<this.chorusDelayLineL.length;t++)this.chorusDelayLineL[t]=0;for(let t=0;t<this.chorusDelayLineR.length;t++)this.chorusDelayLineR[t]=0}if(this.echoDelayLineDirty){for(let t=0;t<this.echoDelayLineL.length;t++)this.echoDelayLineL[t]=0;for(let t=0;t<this.echoDelayLineR.length;t++)this.echoDelayLineR[t]=0}if(this.reverbDelayLineDirty)for(let t=0;t<this.reverbDelayLine.length;t++)this.reverbDelayLine[t]=0;this.chorusPhase=0}compute(t,i,s,n,o){this.computed=!0,this.type=i.type,this.synthesizer=Ft.getInstrumentSynthFunction(i),this.unison=e.unisons[i.unison],this.chord=i.getChord(),this.noisePitchFilterMult=e.chipNoises[i.chipNoise].pitchFilterMult;let r=i.effects;0==i.distortion&&(r&=-9),i.pan==e.panCenter&&(r&=-5),0==i.chorus&&(r&=-3),0==i.echoSustain&&(r&=-65),0==i.reverb&&(r&=-2),this.effects=r,this.allocateNecessaryBuffers(t,i,s);const h=t.samplesPerSecond;this.updateWaves(i,h);const a=m(r),l=y(r),c=g(r),u=b(r),f=w(r),p=v(r);if(a){const t=Math.min(1,i.distortion/(e.distortionRange-1)),s=Math.min(1,i.distortion/(e.distortionRange-1)),o=Math.pow(1-.895*(Math.pow(20,t)-1)/19,2),r=Math.pow(1-.895*(Math.pow(20,s)-1)/19,2),h=(1+2*t)/e.distortionBaseVolume,a=(1+2*s)/e.distortionBaseVolume;this.distortion=o,this.distortionDelta=(r-o)/n,this.distortionDrive=h,this.distortionDriveDelta=(a-h)/n}if(l){const s=i.bitcrusherFreq,o=i.bitcrusherFreq,r=i.bitcrusherQuantization,a=i.bitcrusherQuantization,l=e.keys[t.song.key].basePitch,c=gt.frequencyFromPitch(l+60)*Math.pow(2,(e.bitcrusherFreqRange-1-s)*e.bitcrusherOctaveStep),u=gt.frequencyFromPitch(l+60)*Math.pow(2,(e.bitcrusherFreqRange-1-o)*e.bitcrusherOctaveStep),f=Math.min(1,c/h),p=Math.min(1,u/h);this.bitcrusherPhaseDelta=f,this.bitcrusherPhaseDeltaScale=Math.pow(p/f,1/n);const d=2*e.bitcrusherBaseVolume*Math.pow(2,1-Math.pow(2,.5*(e.bitcrusherQuantizationRange-1-r))),m=2*e.bitcrusherBaseVolume*Math.pow(2,1-Math.pow(2,.5*(e.bitcrusherQuantizationRange-1-a)));this.bitcrusherScale=d,this.bitcrusherScaleScale=Math.pow(m/d,1/n);const y=2*e.bitcrusherBaseVolume*Math.pow(1.5,e.bitcrusherQuantizationRange-1-r),g=2*e.bitcrusherBaseVolume*Math.pow(1.5,e.bitcrusherQuantizationRange-1-a);this.bitcrusherFoldLevel=y,this.bitcrusherFoldLevelScale=Math.pow(g/y,1/n)}let d=1;const k=i.eqFilter;for(let t=0;t<k.controlPointCount;t++){const e=k.controlPoints[t];e.toCoefficients(Ft.tempFilterStartCoefficients,h,1,1),e.toCoefficients(Ft.tempFilterEndCoefficients,h,1,1),this.eqFilters.length<=t&&(this.eqFilters[t]=new Q),this.eqFilters[t].loadCoefficientsWithGradient(Ft.tempFilterStartCoefficients,Ft.tempFilterEndCoefficients,1/n,0==e.type),d*=e.getVolumeCompensationMult()}this.eqFilterCount=k.controlPointCount,d=Math.min(3,d);const M=Ft.instrumentVolumeToVolumeMult(i.volume);this.mixVolume=M;const x=M;this.mixVolumeDelta=(x-this.mixVolume)/n;let S=d,F=d,P=1,I=1;if(c){const s=(i.pan-e.panCenter)/e.panCenter,o=Math.max(-1,Math.min(1,s)),r=Math.max(-1,Math.min(1,s)),a=1.414*Math.cos((1+o)*Math.PI*.25),l=1.414*Math.cos((1-o)*Math.PI*.25),c=1.414*Math.cos((1+r)*Math.PI*.25),u=1.414*Math.cos((1-r)*Math.PI*.25),f=h*e.panDelaySecondsMax,p=o*f,d=r*f,m=Math.max(0,p),y=Math.max(0,-p),g=Math.max(0,d),b=Math.max(0,-d);this.panningVolumeL=a,this.panningVolumeR=l,this.panningVolumeDeltaL=(c-a)/n,this.panningVolumeDeltaR=(u-l)/n,this.panningOffsetL=this.panningDelayPos-m+t.panningDelayBufferSize,this.panningOffsetR=this.panningDelayPos-y+t.panningDelayBufferSize,this.panningOffsetDeltaL=(g-m)/n,this.panningOffsetDeltaR=(b-y)/n}if(u){let t=Math.min(1,i.chorus/(e.chorusRange-1)),s=Math.min(1,i.chorus/(e.chorusRange-1));t=.6*t+.4*Math.pow(t,6),s=.6*s+.4*Math.pow(s,6);const o=1/Math.sqrt(3*t*t+1),r=1/Math.sqrt(3*s*s+1);this.chorusVoiceMult=t,this.chorusVoiceMultDelta=(s-t)/n,this.chorusCombinedMult=o,this.chorusCombinedMultDelta=(r-o)/n}let T=0,q=0;if(f){const o=.9*Math.min(1,Math.pow(i.echoSustain/e.echoSustainRange,1.1)),r=.9*Math.min(1,Math.pow(i.echoSustain/e.echoSustainRange,1.1));this.echoMult=o,this.echoMultDelta=(r-o)/n,T=Math.max(o,r);const a=Math.round((i.echoDelay+1)*e.echoDelayStepTicks*s);null!=this.echoDelayOffsetEnd?this.echoDelayOffsetStart=this.echoDelayOffsetEnd:this.echoDelayOffsetStart=a,this.echoDelayOffsetEnd=a,q=.5*(this.echoDelayOffsetStart+this.echoDelayOffsetEnd)/h,this.echoDelayOffsetRatio=0,this.echoDelayOffsetRatioDelta=1/n;const l=2*Math.PI*e.echoShelfHz/t.samplesPerSecond;Ft.tempFilterStartCoefficients.highShelf1stOrder(l,e.echoShelfGain),this.echoShelfA1=Ft.tempFilterStartCoefficients.a[1],this.echoShelfB0=Ft.tempFilterStartCoefficients.b[0],this.echoShelfB1=Ft.tempFilterStartCoefficients.b[1]}let E=0;if(p){const s=.425*Math.min(1,Math.pow(i.reverb/e.reverbRange,.667)),o=.425*Math.min(1,Math.pow(i.reverb/e.reverbRange,.667));this.reverbMult=s,this.reverbMultDelta=(o-s)/n,E=Math.max(s,o);const r=2*Math.PI*e.reverbShelfHz/t.samplesPerSecond;Ft.tempFilterStartCoefficients.highShelf1stOrder(r,e.reverbShelfGain),this.reverbShelfA1=Ft.tempFilterStartCoefficients.a[1],this.reverbShelfB0=Ft.tempFilterStartCoefficients.b[0],this.reverbShelfB1=Ft.tempFilterStartCoefficients.b[1]}if(this.tonesAddedInThisTick)this.attentuationProgress=0,this.flushedSamples=0,this.flushingDelayLines=!1;else if(this.flushingDelayLines){S=0,F=0,P=0,I=0;let i=0;u&&(i+=t.chorusDelayBufferSize),f&&(i+=this.echoDelayLineL.length),p&&(i+=e.reverbDelayBufferSize),this.flushedSamples+=n,this.flushedSamples>=i&&(this.deactivateAfterThisTick=!0)}else{0==this.attentuationProgress||(S=0),F=0;const t=1/256,i=-Math.log2(t);let n=0;if(u&&(n+=e.chorusMaxDelay),f){const t=Math.pow(T,1/q);n+=-1/Math.log2(t)*i}if(p){const t=2*E,s=e.reverbDelayBufferSize/4/h,o=Math.pow(t,1/s);n+=-1/Math.log2(o)*i}const o=s/h/n,r=this.attentuationProgress+o;r>=1&&(I=0),this.attentuationProgress=r,this.attentuationProgress>=1&&(this.flushingDelayLines=!0)}this.eqFilterVolume=S,this.eqFilterVolumeDelta=(F-S)/n,this.delayInputMult=P,this.delayInputMultDelta=(I-P)/n}updateWaves(t,i){if(0==t.type)this.wave=e.chipWaves[t.chipWave].samples;else if(2==t.type)this.wave=o(t.chipNoise,W,V);else if(5==t.type)this.wave=this.harmonicsWave.getCustomWave(t.harmonicsWave,t.type);else if(7==t.type)this.wave=this.harmonicsWave.getCustomWave(t.harmonicsWave,t.type);else if(3==t.type)this.wave=this.spectrumWave.getCustomWave(t.spectrumWave,8);else if(4==t.type){for(let i=0;i<e.drumCount;i++)this.drumsetSpectrumWaves[i].getCustomWave(t.drumsetSpectrumWaves[i],xt.V(i));this.wave=null}else this.wave=null}getDrumsetWave(t){if(4==this.type)return this.drumsetSpectrumWaves[t].wave;throw new Error("Unhandled instrument type in getDrumsetWave")}static drumsetIndexReferenceDelta(t){return gt.frequencyFromPitch(e.spectrumBasePitch+6*t)/44100}static V(t){return 15+Math.log2(xt.drumsetIndexReferenceDelta(t))}}class St{constructor(){this.instruments=[],this.muted=!1,this.singleSeamlessInstrument=null}}class Ft{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.enableMetronome=!1,this.countInMetronome=!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.tickSampleCountdown=0,this.isPlayingSong=!1,this.isRecording=!1,this.liveInputEndTime=0,this.browserAutomaticallyClearsAudioBuffer=!0,this.tempDrumSetControlPoint=new dt,this.tempFrequencyResponse=new J,this.channels=[],this.tonePool=new K,this.tempMatchedPitchTones=Array(e.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,i=e.getChannelData(0),s=e.getChannelData(1);if(!this.browserAutomaticallyClearsAudioBuffer||0==i[0]&&0==s[0]&&0==i[e.length-1]&&0==s[e.length-1]||(this.browserAutomaticallyClearsAudioBuffer=!1),!this.browserAutomaticallyClearsAudioBuffer){const t=e.length;for(let e=0;e<t;e++)i[e]=0,s[e]=0}!this.isPlayingSong&&performance.now()>=this.liveInputEndTime?this.deactivateAudio():this.synthesize(i,s,e.length,this.isPlayingSong)},this.computeDelayBufferSizes(),null!=t&&this.setSong(t)}syncSongState(){const t=this.song.getChannelCount();for(let e=this.channels.length;e<t;e++)this.channels[e]=new St;this.channels.length=t;for(let e=0;e<t;e++){const t=this.song.channels[e],i=this.channels[e];for(let e=i.instruments.length;e<t.instruments.length;e++)i.instruments[e]=new xt;if(i.instruments.length=t.instruments.length,i.muted!=t.muted&&(i.muted=t.muted,i.muted))for(const t of i.instruments)t.resetAllEffects()}}warmUpSynthesizer(t){if(null!=t){this.syncSongState();const e=this.getSamplesPerTick();for(let i=0;i<t.getChannelCount();i++)for(let s=0;s<t.channels[i].instruments.length;s++){const n=t.channels[i].instruments[s],o=this.channels[i].instruments[s];Ft.getInstrumentSynthFunction(n),o.updateWaves(n,this.samplesPerSecond),o.allocateNecessaryBuffers(this,n,e)}}}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 i=this.playheadInternal;this.bar=Math.floor(i),i=this.song.beatsPerBar*(i-this.bar),this.beat=Math.floor(i),i=e.partsPerBeat*(i-this.beat),this.part=Math.floor(i),i=e.ticksPerPart*(i-this.part),this.tick=Math.floor(i),this.tickSampleCountdown=0,this.isAtStartOfTick=!0,this.prevBar=null}}getSamplesPerBar(){if(null==this.song)throw new Error;return this.getSamplesPerTick()*e.ticksPerPart*e.partsPerBeat*this.song.beatsPerBar}getTicksIntoBar(){return(this.beat*e.partsPerBeat+this.part)*e.ticksPerPart+this.tick}getCurrentPart(){return this.beat*e.partsPerBeat+this.part}getTotalBars(t,e){if(null==this.song)throw new Error;let i=this.song.loopLength*(this.loopRepeatCount+1);return t&&(i+=this.song.loopStart),e&&(i+=this.song.barCount-(this.song.loopStart+this.song.loopLength)),i}setSong(t){"string"==typeof t?this.song=new wt(t):t instanceof wt&&(this.song=t),this.prevBar=null}computeDelayBufferSizes(){this.panningDelayBufferSize=Ft.fittingPowerOfTwo(this.samplesPerSecond*e.panDelaySecondsMax),this.panningDelayBufferMask=this.panningDelayBufferSize-1,this.chorusDelayBufferSize=Ft.fittingPowerOfTwo(this.samplesPerSecond*e.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.isPlayingSong=!0,this.warmUpSynthesizer(this.song),this.activateAudio())}pause(){this.isPlayingSong&&(this.isPlayingSong=!1,this.isRecording=!1)}startRecording(){this.preferLowerLatency=!0,this.isRecording=!0,this.play()}snapToStart(){this.bar=0,this.snapToBar()}goToBar(t){this.bar=t,this.playheadInternal=this.bar,this.prevBar=null}snapToBar(){this.playheadInternal=this.bar,this.beat=0,this.part=0,this.tick=0,this.tickSampleCountdown=0,this.isAtStartOfTick=!0,this.prevBar=null}resetEffects(){if(this.limit=0,this.freeAllTones(),null!=this.song)for(const t of this.channels)for(const e of t.instruments)e.resetAllEffects()}jumpIntoLoop(){if(this.song&&(this.bar<this.song.loopStart||this.bar>=this.song.loopStart+this.song.loopLength)){const t=this.bar;this.bar=this.song.loopStart,this.playheadInternal+=this.bar-t,this.prevBar=null}}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}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}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}synthesize(t,i,s,n=!0){if(null==this.song){for(let e=0;e<s;e++)t[e]=0,i[e]=0;return void this.deactivateAudio()}const o=this.song,r=this.getSamplesPerTick();let h=!1;(this.tickSampleCountdown<=0||this.tickSampleCountdown>r)&&(this.tickSampleCountdown=r,this.isAtStartOfTick=!0),n&&(this.beat>=o.beatsPerBar&&(this.beat=0,this.part=0,this.tick=0,this.tickSampleCountdown=r,this.isAtStartOfTick=!0,this.prevBar=this.bar,this.bar=this.getNextBar(),this.bar<=this.prevBar&&this.loopRepeatCount>0&&this.loopRepeatCount--),this.bar>=o.barCount&&(this.bar=0,-1!=this.loopRepeatCount&&(h=!0,this.pause()))),this.syncSongState(),(null==this.tempMonoInstrumentSampleBuffer||this.tempMonoInstrumentSampleBuffer.length<s)&&(this.tempMonoInstrumentSampleBuffer=new Float32Array(s));const a=+this.volume,l=1-Math.pow(.5,4/this.samplesPerSecond),c=1-Math.pow(.5,4e3/this.samplesPerSecond);let u=+this.limit,f=0;for(;f<s&&!h;){this.nextBar=this.getNextBar(),this.nextBar>=o.barCount&&(this.nextBar=null);const p=s-f,d=Math.ceil(this.tickSampleCountdown),m=Math.min(d,p),y=f+m;for(let s=0;s<o.getChannelCount();s++){const h=o.channels[s],a=this.channels[s];this.isAtStartOfTick&&(this.determineCurrentActiveTones(o,s,r,n&&!this.countInMetronome),this.determineLiveInputTones(o,s,r));for(let n=0;n<h.instruments.length;n++){const l=h.instruments[n],c=a.instruments[n];if(this.isAtStartOfTick){let t=c.activeTones.count()+c.liveInputTones.count();for(let i=0;i<c.releasedTones.count();i++){const n=c.releasedTones.get(i);if(n.ticksSinceReleased>=Math.abs(l.getFadeOutTicks())){this.freeReleasedTone(c,i),i--;continue}const h=t>=e.maximumTonesPerChannel;this.computeTone(o,s,r,n,!0,h),t++}c.awake&&(c.computed||c.compute(this,l,r,Math.ceil(r),null),c.computed=!1)}for(let t=0;t<c.activeTones.count();t++){const e=c.activeTones.get(t);this.playTone(s,f,m,e)}for(let t=0;t<c.liveInputTones.count();t++){const e=c.liveInputTones.get(t);this.playTone(s,f,m,e)}for(let t=0;t<c.releasedTones.count();t++){const e=c.releasedTones.get(t);this.playTone(s,f,m,e)}c.awake&&Ft.effectsSynth(this,t,i,f,m,c)}}if(this.enableMetronome||this.countInMetronome)if(0==this.part){if(!this.startedMetronome){const t=o.beatsPerBar>4&&o.beatsPerBar%2==0&&this.beat==o.beatsPerBar/2,e=0==this.beat?8:t?6:4,i=0==this.beat?1600:t?1200:800,s=0==this.beat?.06:t?.05:.04,n=this.samplesPerSecond/i,r=2*Math.PI/n;this.metronomeSamplesRemaining=Math.floor(n*e),this.metronomeFilter=2*Math.cos(r),this.metronomeAmplitude=s*Math.sin(r),this.metronomePrevAmplitude=0,this.startedMetronome=!0}if(this.metronomeSamplesRemaining>0){const e=Math.min(y,f+this.metronomeSamplesRemaining);this.metronomeSamplesRemaining-=e-f;for(let s=f;s<e;s++){t[s]+=this.metronomeAmplitude,i[s]+=this.metronomeAmplitude;const e=this.metronomeFilter*this.metronomeAmplitude-this.metronomePrevAmplitude;this.metronomePrevAmplitude=this.metronomeAmplitude,this.metronomeAmplitude=e}}}else this.startedMetronome=!1;for(let e=f;e<y;e++){const s=t[e],n=i[e],o=Math.max(Math.abs(s),Math.abs(n));u+=(o-u)*(u<o?c:l*(1+u));const r=a/(u>=1?1.05*u:.8*u+.25);t[e]=s*r,i[e]=n*r}if(f+=m,this.isAtStartOfTick=!1,this.tickSampleCountdown-=m,this.tickSampleCountdown<=0){this.isAtStartOfTick=!0;for(const t of this.channels)for(const e of t.instruments){for(let t=0;t<e.releasedTones.count();t++){const i=e.releasedTones.get(t);i.isOnLastTick?(this.freeReleasedTone(e,t),t--):i.ticksSinceReleased++}e.deactivateAfterThisTick&&e.deactivate(),e.tonesAddedInThisTick=!1}this.tick++,this.tickSampleCountdown+=r,this.tick==e.ticksPerPart&&(this.tick=0,this.part++,this.liveInputDuration--,this.part==e.partsPerBeat&&(this.part=0,n&&(this.beat++,this.beat==o.beatsPerBar&&(this.beat=0,this.countInMetronome?this.countInMetronome=!1:(this.prevBar=this.bar,this.bar=this.getNextBar(),this.bar<=this.prevBar&&this.loopRepeatCount>0&&this.loopRepeatCount--,this.bar>=o.barCount&&(this.bar=0,-1!=this.loopRepeatCount&&(h=!0,this.resetEffects(),this.pause())))))))}}(!Number.isFinite(u)||Math.abs(u)<Z)&&(u=0),this.limit=u,n&&!this.countInMetronome&&(this.playheadInternal=(((this.tick+1-this.tickSampleCountdown/r)/2+this.part)/e.partsPerBeat+this.beat)/o.beatsPerBar+this.bar)}freeTone(t){this.tonePool.pushBack(t)}newTone(){if(this.tonePool.count()>0){const t=this.tonePool.popBack();return t.freshlyAllocated=!0,t}return new Mt}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.releasedTones.count()>0;)this.freeTone(e.releasedTones.popBack());for(;e.liveInputTones.count()>0;)this.freeTone(e.liveInputTones.popBack())}}determineLiveInputTones(t,e,i){const s=t.channels[e],n=this.channels[e],o=this.liveInputPitches;for(let r=0;r<s.instruments.length;r++){const h=n.instruments[r],a=h.liveInputTones;let l=0;if(this.liveInputDuration>0&&e==this.liveInputChannel&&o.length>0&&-1!=this.liveInputInstruments.indexOf(r)){const n=s.instruments[r];if(n.getChord().singleTone){let s;a.count()<=l?(s=this.newTone(),a.pushBack(s)):!n.getTransition().isSeamless&&this.liveInputStarted?(this.releaseTone(h,a.get(l)),s=this.newTone(),a.set(l,s)):s=a.get(l),l++;for(let t=0;t<o.length;t++)s.pitches[t]=o[t];s.pitchCount=o.length,s.chordSize=1,s.instrumentIndex=r,s.note=s.prevNote=s.nextNote=null,s.atNoteStart=this.liveInputStarted,s.forceContinueAtStart=!1,s.forceContinueAtEnd=!1,this.computeTone(t,e,i,s,!1,!1)}else{this.moveTonesIntoOrderedTempMatchedList(a,o);for(let s=0;s<o.length;s++){let n;null!=this.tempMatchedPitchTones[l]?(n=this.tempMatchedPitchTones[l],this.tempMatchedPitchTones[l]=null,1==n.pitchCount&&n.pitches[0]==o[s]||(this.releaseTone(h,n),n=this.newTone()),a.pushBack(n)):(n=this.newTone(),a.pushBack(n)),l++,n.pitches[0]=o[s],n.pitchCount=1,n.chordSize=o.length,n.instrumentIndex=r,n.note=n.prevNote=n.nextNote=null,n.atNoteStart=this.liveInputStarted,n.forceContinueAtStart=!1,n.forceContinueAtEnd=!1,this.computeTone(t,e,i,n,!1,!1)}}}for(;a.count()>l;)this.releaseTone(h,a.popBack());this.clearTempMatchedPitchTones(l,h)}this.liveInputStarted=!1}adjacentPatternHasCompatibleInstrumentTransition(t,e,i,s,n,o,r,h,a,l){if(t.patternInstruments&&-1==s.instruments.indexOf(n)){if(i.instruments.length>1||s.instruments.length>1)return null;const t=e.instruments[s.instruments[0]];if(l)return t.getChord();const n=t.getTransition();return o.includeAdjacentPatterns&&n.includeAdjacentPatterns&&n.slides==o.slides?t.getChord():null}return l||o.includeAdjacentPatterns?r:null}static adjacentNotesHaveMatchingPitches(t,e){if(t.pitches.length!=e.pitches.length)return!1;const i=t.pins[t.pins.length-1].interval;for(const s of t.pitches)if(-1==e.pitches.indexOf(s+i))return!1;return!0}moveTonesIntoOrderedTempMatchedList(t,e){for(let i=0;i<t.count();i++){const s=t.get(i),n=s.pitches[0]+s.lastInterval;for(let o=0;o<e.length;o++)if(e[o]==n){this.tempMatchedPitchTones[o]=s,t.remove(i),i--;break}}for(;t.count()>0;){const e=t.popFront();for(let t=0;t<this.tempMatchedPitchTones.length;t++)if(null==this.tempMatchedPitchTones[t]){this.tempMatchedPitchTones[t]=e;break}}}determineCurrentActiveTones(t,i,s,n){const o=t.channels[i],r=this.channels[i],h=t.getPattern(i,this.bar),a=this.getCurrentPart(),l=this.tick+e.ticksPerPart*a;let c=null,u=null,f=null;if(n&&null!=h&&!o.muted&&(!this.isRecording||this.liveInputChannel!=i)){for(let t=0;t<h.notes.length;t++)if(h.notes[t].end<=a)u=h.notes[t];else if(h.notes[t].start<=a&&h.notes[t].end>a)c=h.notes[t];else if(h.notes[t].start>a){f=h.notes[t];break}null!=c&&(null!=u&&u.end!=c.start&&(u=null),null!=f&&f.start!=c.end&&(f=null))}if(null!=h&&(!t.layeredInstruments||1==o.instruments.length||t.patternInstruments&&1==h.instruments.length)){const e=t.patternInstruments?h.instruments[0]:0;if(null!=r.singleSeamlessInstrument&&r.singleSeamlessInstrument!=e&&r.singleSeamlessInstrument<r.instruments.length){const t=r.instruments[r.singleSeamlessInstrument],i=r.instruments[e];for(;t.activeTones.count()>0;)i.activeTones.pushFront(t.activeTones.popBack())}r.singleSeamlessInstrument=e}else r.singleSeamlessInstrument=null;for(let n=0;n<o.instruments.length;n++){const p=r.instruments[n],d=p.activeTones;let m=0;if(null!=c&&(!t.patternInstruments||-1!=h.instruments.indexOf(n))){const r=o.instruments[n];let y=u,g=f;const b=e.partsPerBeat*t.beatsPerBar,w=r.getTransition(),v=r.getChord();let k=!1,M=!1,x=0,S=0;if(0==c.start){let e=null==this.prevBar?null:t.getPattern(i,this.prevBar);if(null!=e){const i=e.notes.length<=0?null:e.notes[e.notes.length-1];if(null!=i&&i.end==b){const s=c.continuesLastPattern&&Ft.adjacentNotesHaveMatchingPitches(i,c),r=this.adjacentPatternHasCompatibleInstrumentTransition(t,o,h,e,n,w,v,c,i,s);null!=r&&(y=i,x=r.singleTone?1:y.pitches.length,k=s)}}}else null!=y&&(x=v.singleTone?1:y.pitches.length);if(c.end==b){let e=null==this.nextBar?null:t.getPattern(i,this.nextBar);if(null!=e){const i=e.notes.length<=0?null:e.notes[0];if(null!=i&&0==i.start){const s=i.continuesLastPattern&&Ft.adjacentNotesHaveMatchingPitches(c,i),r=this.adjacentPatternHasCompatibleInstrumentTransition(t,o,h,e,n,w,v,c,i,s);null!=r&&(g=i,S=r.singleTone?1:g.pitches.length,M=s)}}}else null!=g&&(S=v.singleTone?1:g.pitches.length);if(v.singleTone){const o=e.ticksPerPart*c.start==l;let r;if(d.count()<=m)r=this.newTone(),d.pushBack(r);else if(!o||(w.isSeamless||k)&&null!=y)r=d.get(m);else{const t=d.get(m);t.isOnLastTick?this.freeTone(t):this.releaseTone(p,t),r=this.newTone(),d.set(m,r)}m++;for(let t=0;t<c.pitches.length;t++)r.pitches[t]=c.pitches[t];r.pitchCount=c.pitches.length,r.chordSize=1,r.instrumentIndex=n,r.note=c,r.noteStartPart=c.start,r.noteEndPart=c.end,r.prevNote=y,r.nextNote=g,r.prevNotePitchIndex=0,r.nextNotePitchIndex=0,r.atNoteStart=o,r.passedEndOfNote=!1,r.forceContinueAtStart=k,r.forceContinueAtEnd=M,this.computeTone(t,i,s,r,!1,!1)}else{const o=r.getTransition();(o.isSeamless&&!o.slides&&0==v.strumParts||k)&&e.ticksPerPart*c.start==l&&null!=y&&this.moveTonesIntoOrderedTempMatchedList(d,c.pitches);let h=0;for(let r=0;r<c.pitches.length;r++){let u=x>r?y:null,f=c,b=S>r?g:null,w=f.start+h,F=!1;if(w>a){if(!(d.count()>r&&(o.isSeamless||k)&&null!=u))break;b=f,f=u,u=null,w=f.start+h,F=!0}let P=f.end;(o.isSeamless||k)&&null!=b&&(P=Math.min(e.partsPerBeat*this.song.beatsPerBar,P+h)),(o.continues||k)&&null!=u||(h+=v.strumParts);const I=e.ticksPerPart*w==l;let T;if(null!=this.tempMatchedPitchTones[m])T=this.tempMatchedPitchTones[m],this.tempMatchedPitchTones[m]=null,d.pushBack(T);else if(d.count()<=m)T=this.newTone(),d.pushBack(T);else if(!I||(o.isSeamless||k)&&null!=u)T=d.get(m);else{const t=d.get(m);t.isOnLastTick?this.freeTone(t):this.releaseTone(p,t),T=this.newTone(),d.set(m,T)}m++,T.pitches[0]=f.pitches[r],T.pitchCount=1,T.chordSize=f.pitches.length,T.instrumentIndex=n,T.note=f,T.noteStartPart=w,T.noteEndPart=P,T.prevNote=u,T.nextNote=b,T.prevNotePitchIndex=r,T.nextNotePitchIndex=r,T.atNoteStart=I,T.passedEndOfNote=F,T.forceContinueAtStart=k&&null!=u,T.forceContinueAtEnd=M&&null!=b,this.computeTone(t,i,s,T,!1,!1)}}}for(;d.count()>m;){const e=d.popBack(),s=t.channels[i];if(e.instrumentIndex<s.instruments.length&&!e.isOnLastTick){const t=r.instruments[e.instrumentIndex];this.releaseTone(t,e)}else this.freeTone(e)}this.clearTempMatchedPitchTones(m,p)}}clearTempMatchedPitchTones(t,e){for(let i=t;i<this.tempMatchedPitchTones.length;i++){const t=this.tempMatchedPitchTones[i];null!=t&&(t.isOnLastTick?this.freeTone(t):this.releaseTone(e,t),this.tempMatchedPitchTones[i]=null)}}playTone(t,e,i,s){const n=this.channels[t].instruments[s.instrumentIndex];n.synthesizer(this,e,i,s,n),s.envelopeComputer.clearEnvelopes()}static computeChordExpression(t){return 1/(.25*(t-1)+1)}computeTone(t,i,s,o,r,a){const l=Math.ceil(s),c=t.channels[i],m=this.channels[i],y=c.instruments[o.instrumentIndex],g=m.instruments[o.instrumentIndex];g.awake=!0,g.tonesAddedInThisTick=!0,g.computed||g.compute(this,y,s,l,o);const b=t.getChannelIsNoise(i),w=y.getTransition(),v=y.getChord(),k=v.singleTone?1:Ft.computeChordExpression(o.chordSize),M=b?e.noiseInterval:1,x=e.ticksPerPart*s/this.samplesPerSecond,S=1/this.samplesPerSecond,F=1/e.partsPerBeat,P=this.getTicksIntoBar(),I=P/e.ticksPerPart,T=(P+1)/e.ticksPerPart,q=this.getCurrentPart();let E=1;o.specialIntervalExpressionMult=1;let C=a,L=0,z=0,D=1,A=1,B=k,O=k,N=16,R=e.keys[t.key].basePitch,H=1,G=48;if(3==y.type)H=e.spectrumBaseExpression,b&&(R=e.spectrumBasePitch,H*=2),N=e.spectrumBasePitch,G=28;else if(4==y.type)R=e.spectrumBasePitch,H=e.drumsetBaseExpression,N=R;else if(2==y.type)R=e.chipNoises[y.chipNoise].basePitch,H=e.noiseBaseExpression,N=R,G=e.chipNoises[y.chipNoise].isSoft?24:60;else if(1==y.type)H=e.fmBaseExpression;else if(0==y.type)H=e.chipBaseExpression;else if(5==y.type)H=e.harmonicsBaseExpression;else if(6==y.type)H=e.pwmBaseExpression;else if(8==y.type)H=e.supersawBaseExpression;else{if(7!=y.type)throw new Error("Unknown instrument type in computeTone.");H=e.pickedStringBaseExpression}(o.atNoteStart&&!w.isSeamless&&!o.forceContinueAtStart||o.freshlyAllocated)&&o.reset(),o.freshlyAllocated=!1;for(let t=0;t<e.maxPitchOrOperatorCount;t++)o.phaseDeltas[t]=0,o.phaseDeltaScales[t]=0,o.operatorExpressions[t]=0,o.operatorExpressionDeltas[t]=0;if(o.expression=0,o.expressionDelta=0,r){const t=o.ticksSinceReleased,i=o.ticksSinceReleased+1;L=z=o.lastInterval;const s=Math.abs(y.getFadeOutTicks());D=Ft.noteSizeToVolumeMult((1-t/s)*e.noteSizeMax),A=Ft.noteSizeToVolumeMult((1-i/s)*e.noteSizeMax),a&&(A=0),o.ticksSinceReleased+1>=s&&(C=!0)}else if(null==o.note)D=A=1,o.lastInterval=0,o.ticksSinceReleased=0,o.liveInputSamplesHeld+=l;else{const t=o.note,i=o.nextNote,s=o.noteStartPart,n=o.noteEndPart,r=t.getEndPinIndex(q),h=t.pins[r-1],a=t.pins[r],l=s*e.ticksPerPart,c=n*e.ticksPerPart,u=(t.start+h.time)*e.ticksPerPart,f=(t.start+a.time)*e.ticksPerPart;o.ticksSinceReleased=0;const p=q*e.ticksPerPart+this.tick,d=p+1,m=p-l,g=d-l,b=Math.min(1,(p-u)/(f-u)),v=Math.min(1,(d-u)/(f-u));if(D=1,A=1,L=h.interval+(a.interval-h.interval)*b,z=h.interval+(a.interval-h.interval)*v,o.lastInterval=z,!w.isSeamless&&!o.forceContinueAtEnd||null==i){const t=-y.getFadeOutTicks();if(t>0){const e=c-l;D*=Math.min(1,(e-m)/t),A*=Math.min(1,(e-g)/t),d>=l+e&&(C=!0)}}}o.isOnLastTick=C;const $=o.envelopeComputer;$.computeEnvelopes(y,q,e.ticksPerPart*I,s/this.samplesPerSecond,o);const _=o.envelopeComputer.envelopeStarts,U=o.envelopeComputer.envelopeEnds;if(null!=o.note&&w.slides){const t=o.prevNote,e=o.nextNote;if(null!=t){const e=t.pitches[o.prevNotePitchIndex]+t.pins[t.pins.length-1].interval-o.pitches[0];if($.prevSlideStart&&(L+=e*$.prevSlideRatioStart),$.prevSlideEnd&&(z+=e*$.prevSlideRatioEnd),!v.singleTone){const e=t.pitches.length-o.chordSize;$.prevSlideStart&&(B=Ft.computeChordExpression(o.chordSize+e*$.prevSlideRatioStart)),$.prevSlideEnd&&(O=Ft.computeChordExpression(o.chordSize+e*$.prevSlideRatioEnd))}}if(null!=e){const t=e.pitches[o.nextNotePitchIndex]-(o.pitches[0]+o.note.pins[o.note.pins.length-1].interval);if($.nextSlideStart&&(L+=t*$.nextSlideRatioStart),$.nextSlideEnd&&(z+=t*$.nextSlideRatioEnd),!v.singleTone){const t=e.pitches.length-o.chordSize;$.nextSlideStart&&(B=Ft.computeChordExpression(o.chordSize+t*$.nextSlideRatioStart)),$.nextSlideEnd&&(O=Ft.computeChordExpression(o.chordSize+t*$.nextSlideRatioEnd))}}}if(u(y.effects)){const t=e.justIntonationSemitones[y.pitchShift]/M;L+=t*_[14],z+=t*U[14]}if(f(y.effects)){const t=_[15],i=U[15];L+=Ft.detuneToCents((y.detune-e.detuneCenter)*t)*e.pitchesPerOctave/1200,z+=Ft.detuneToCents((y.detune-e.detuneCenter)*i)*e.pitchesPerOctave/1200}if(p(y.effects)){const t=e.vibratos[y.vibrato].delayTicks,i=e.vibratos[y.vibrato].amplitude;let s;if(null!=o.prevVibrato)s=o.prevVibrato;else{if(s=i*Ft.getLFOAmplitude(y,x*I)*_[16],t>0){const e=t-$.noteTicksStart;s*=Math.max(0,Math.min(1,1-e/2))}}let n=i*Ft.getLFOAmplitude(y,x*T)*U[16];if(t>0){const e=t-$.noteTicksEnd;n*=Math.max(0,Math.min(1,1-e/2))}o.prevVibrato=n,L+=s,z+=n}if(!w.isSeamless&&!o.forceContinueAtStart||null==o.prevNote){const t=y.getFadeInSeconds();t>0&&(D*=Math.min(1,$.noteSecondsStart/t),A*=Math.min(1,$.noteSecondsEnd/t))}4==y.type&&null==o.drumsetPitch&&(o.drumsetPitch=o.pitches[0],null!=o.note&&(o.drumsetPitch+=o.note.pickMainInterval()),o.drumsetPitch=Math.max(0,Math.min(e.drumCount-1,o.drumsetPitch)));let V=$.lowpassCutoffDecayVolumeCompensation;if(d(y.effects)){const t=y.noteFilter,e=_[1],i=U[1];for(let s=0;s<t.controlPointCount;s++){const n=_[17+s],r=U[17+s],h=_[25+s],a=U[25+s],c=t.controlPoints[s];c.toCoefficients(Ft.tempFilterStartCoefficients,this.samplesPerSecond,e*n,h),c.toCoefficients(Ft.tempFilterEndCoefficients,this.samplesPerSecond,i*r,a),o.noteFilters.length<=s&&(o.noteFilters[s]=new Q),o.noteFilters[s].loadCoefficientsWithGradient(Ft.tempFilterStartCoefficients,Ft.tempFilterEndCoefficients,1/l,0==c.type),V*=c.getVolumeCompensationMult()}o.noteFilterCount=t.controlPointCount}else o.noteFilterCount=0;if(4==y.type){const t=y.getDrumsetEnvelope(o.drumsetPitch);V*=kt.getLowpassCutoffDecayVolumeCompensation(t);let e=kt.computeEnvelope(t,$.noteSecondsStart,F*I,$.noteSizeStart),i=kt.computeEnvelope(t,$.noteSecondsEnd,F*T,$.noteSizeEnd);if($.prevSlideStart){e+=(kt.computeEnvelope(t,$.prevNoteSecondsStart,F*I,$.prevNoteSize)-e)*$.prevSlideRatioStart}if($.prevSlideEnd){i+=(kt.computeEnvelope(t,$.prevNoteSecondsEnd,F*T,$.prevNoteSize)-i)*$.prevSlideRatioEnd}if($.nextSlideStart){e+=(kt.computeEnvelope(t,0,F*I,$.nextNoteSize)-e)*$.nextSlideRatioStart}if($.nextSlideEnd){i+=(kt.computeEnvelope(t,0,F*T,$.nextNoteSize)-i)*$.nextSlideRatioEnd}const s=this.tempDrumSetControlPoint;s.type=0,s.gain=dt.getRoundedSettingValueFromLinearGain(.5),s.freq=dt.getRoundedSettingValueFromHz(8e3),s.toCoefficients(Ft.tempFilterStartCoefficients,this.samplesPerSecond,e*(1+e),1),s.toCoefficients(Ft.tempFilterEndCoefficients,this.samplesPerSecond,i*(1+i),1),o.noteFilters.length==o.noteFilterCount&&(o.noteFilters[o.noteFilterCount]=new Q),o.noteFilters[o.noteFilterCount].loadCoefficientsWithGradient(Ft.tempFilterStartCoefficients,Ft.tempFilterEndCoefficients,1/l,!0),o.noteFilterCount++}if(V=Math.min(3,V),1==y.type){let i=1,s=0,n=0;const r=v.arpeggiates;if(o.pitchCount>1&&r){const i=Math.floor((this.tick+this.part*e.ticksPerPart)/e.rhythms[t.rhythm].ticksPerArpeggio);n=o.pitches[h(o.pitchCount,t.rhythm,i)]-o.pitches[0]}const a=e.algorithms[y.algorithm].carrierCount;for(let t=0;t<e.operatorCount;t++){const h=e.algorithms[y.algorithm].associatedCarrier[t]-1,c=o.pitches[r?0:t<o.pitchCount?t:h<o.pitchCount?h:0],u=e.operatorFrequencies[y.operators[t].frequency].mult,f=e.operatorCarrierInterval[h]+n,p=R+(c+L)*M+f,d=R+(c+z)*M+f,m=gt.frequencyFromPitch(p),g=gt.frequencyFromPitch(d),b=e.operatorFrequencies[y.operators[t].frequency].hzOffset,w=u*m+b,v=u*g+b,k=_[5+t],x=U[5+t];let F,P;1!=k||1!=x?(F=Math.pow(2,Math.log2(w/m)*k)*m,P=Math.pow(2,Math.log2(v/g)*x)*g):(F=w,P=v),o.phaseDeltas[t]=F*S,o.phaseDeltaScales[t]=Math.pow(P/F,1/l);const I=Ft.operatorAmplitudeCurve(y.operators[t].amplitude),T=I*e.operatorFrequencies[y.operators[t].frequency].amplitudeSign;let q=T,E=T;if(t<a){let e;e=null!=o.prevPitchExpressions[t]?o.prevPitchExpressions[t]:Math.pow(2,-(p-N)/G);const i=Math.pow(2,-(d-N)/G);o.prevPitchExpressions[t]=i,q*=e,E*=i,s+=I}else q*=1.5*e.sineWaveLength,E*=1.5*e.sineWaveLength,i*=1-Math.min(1,y.operators[t].amplitude/15);q*=_[9+t],E*=U[9+t],o.operatorExpressions[t]=q,o.operatorExpressionDeltas[t]=(E-q)/l}i*=(Math.pow(2,2-1.4*y.feedbackAmplitude/15)-1)/3,i*=1-Math.min(1,Math.max(0,s-1)/2),i=1+3*i;const c=H*i*V*D*B*_[0],u=H*i*V*A*O*U[0];o.expression=c,o.expressionDelta=(u-c)/l;const f=.3*e.sineWaveLength*y.feedbackAmplitude/15;let p=f*_[13],d=f*U[13];o.feedbackMult=p,o.feedbackDelta=(d-p)/l}else{const i=Math.pow(2,(z-L)*M/12),s=Math.pow(i,1/l);let r=o.pitches[0];if(o.pitchCount>1&&(v.arpeggiates||v.customInterval)){const i=Math.floor((this.tick+this.part*e.ticksPerPart)/e.rhythms[t.rhythm].ticksPerArpeggio);if(v.customInterval){const e=o.pitches[1+h(o.pitchCount-1,t.rhythm,i)]-o.pitches[0];E=Math.pow(2,e/12),o.specialIntervalExpressionMult=Math.pow(2,-e/G)}else r=o.pitches[h(o.pitchCount,t.rhythm,i)]}const a=R+(r+L)*M,c=R+(r+z)*M;let u;u=null!=o.prevPitchExpressions[0]?o.prevPitchExpressions[0]:Math.pow(2,-(a-N)/G);const f=Math.pow(2,-(c-N)/G);o.prevPitchExpressions[0]=f;let p=H*V;if(2==y.type&&(p*=e.chipNoises[y.chipNoise].expression),0==y.type&&(p*=e.chipWaves[y.chipWave].expression),6==y.type){const t=n(y.pulseWidth),e=t*_[2],i=t*U[2];o.pulseWidth=e,o.pulseWidthDelta=(i-e)/l}7==y.type&&(p*=Math.pow(2,.7*(1-y.stringSustain/(e.stringSustainRange-1))));const d=gt.frequencyFromPitch(a);if(0==y.type||5==y.type||7==y.type){const t=e.unisons[y.unison],i=7==y.type?1:t.voices/2;p*=t.expression*i;const n=_[4],r=U[4],h=Math.pow(2,(t.offset+t.spread)*n/12),a=Math.pow(2,(t.offset+t.spread)*r/12),c=Math.pow(2,(t.offset-t.spread)*n/12)*E,u=Math.pow(2,(t.offset-t.spread)*r/12)*E;o.phaseDeltas[0]=d*S*h,o.phaseDeltas[1]=d*S*c,o.phaseDeltaScales[0]=s*Math.pow(a/h,1/l),o.phaseDeltaScales[1]=s*Math.pow(u/c,1/l)}else o.phaseDeltas[0]=d*S,o.phaseDeltaScales[0]=s;let m=1,b=1;if(8==y.type){const t=1/Math.sqrt(e.supersawVoiceCount),s=y.supersawDynamism/e.supersawDynamismMax,r=1-Math.pow(Math.max(0,1-s*_[33]),.2),h=1-Math.pow(Math.max(0,1-s*U[33]),.2),a=Math.pow(2,Math.log2(t)*r),c=Math.pow(2,Math.log2(t)*h),u=Math.sqrt((1/Math.pow(a,2)-1)/(e.supersawVoiceCount-1)),f=Math.sqrt((1/Math.pow(c,2)-1)/(e.supersawVoiceCount-1));o.supersawDynamism=u,o.supersawDynamismDelta=(f-u)/l;const p=-1==o.supersawDelayIndex;if(p){let t=0;for(let i=0;i<e.supersawVoiceCount;i++)o.phases[i]=t,t+=-Math.log(Math.random());const i=1+(e.supersawVoiceCount-1)*u;let s=0;for(let i=0;i<e.supersawVoiceCount;i++){const e=0==i?1:u,n=o.phases[i]/t;o.phases[i]=n,s+=(n-.5)*e}let n=1,r=0;for(let t=e.supersawVoiceCount-1;t>=0;t--){const e=1-o.phases[t],h=e-r;if(s<0){const t=-s/i;if(t<h){n=r+t;break}}s+=h*i-(0==t?1:u),r=e}for(let t=0;t<e.supersawVoiceCount;t++)o.phases[t]+=n;for(let t=1;t<e.supersawVoiceCount-1;t++){const i=t+Math.floor(Math.random()*(e.supersawVoiceCount-t)),s=o.phases[t];o.phases[t]=o.phases[i],o.phases[i]=s}}const g=y.supersawSpread/e.supersawSpreadMax,w=.5*(g*_[34]+g*U[34]),v=Math.pow(1-Math.sqrt(Math.max(0,1-w)),1.75);for(let t=0;t<e.supersawVoiceCount;t++){const i=0==t?0:Math.pow(((t+1>>1)-.5+.025*((2&t)-1))/(e.supersawVoiceCount>>1),1.1)*(2*(1&t)-1);o.supersawUnisonDetunes[t]=Math.pow(2,v*i/12)}const k=y.supersawShape/e.supersawShapeMax,M=k*_[35],x=k*U[35];o.supersawShape=M,o.supersawShapeDelta=(x-M)/l;const F=n(y.pulseWidth),P=F*_[2],I=F*U[2],T=null!=o.supersawPrevPhaseDelta?o.supersawPrevPhaseDelta:d*S,q=d*S*i;o.supersawPrevPhaseDelta=q;const E=P/T,C=I/q;o.supersawDelayLength=E,o.supersawDelayLengthDelta=(C-E)/l;const L=Math.ceil(Math.max(E,C))+2;if(null==o.supersawDelayLine||o.supersawDelayLine.length<=L){const t=Math.ceil(.5*this.samplesPerSecond/gt.frequencyFromPitch(24)),e=new Float32Array(Ft.fittingPowerOfTwo(Math.max(t,L)));if(!p&&null!=o.supersawDelayLine){const t=o.supersawDelayLine.length-1>>0,i=o.supersawDelayIndex;for(let s=0;s<o.supersawDelayLine.length;s++)e[s]=o.supersawDelayLine[i+s&t]}o.supersawDelayLine=e,o.supersawDelayIndex=o.supersawDelayLine.length}else p&&(o.supersawDelayLine.fill(0),o.supersawDelayIndex=o.supersawDelayLine.length);const z=e.pwmBaseExpression/e.supersawBaseExpression;m*=(1+(z-1)*M)/Math.sqrt(1+(e.supersawVoiceCount-1)*u*u),b*=(1+(z-1)*x)/Math.sqrt(1+(e.supersawVoiceCount-1)*f*f)}const k=p*D*B*u*_[0]*m,x=p*A*O*f*U[0]*b;if(o.expression=k,o.expressionDelta=(x-k)/l,7==y.type){let t;if(null!=o.prevStringDecay)t=o.prevStringDecay;else{const i=o.envelopeComputer.envelopeStarts[3];t=1-Math.min(1,i*y.stringSustain/(e.stringSustainRange-1))}const i=o.envelopeComputer.envelopeEnds[3];let s=1-Math.min(1,i*y.stringSustain/(e.stringSustainRange-1));o.prevStringDecay=s;const n=e.unisons[y.unison];for(let t=o.pickedStrings.length;t<n.voices;t++)o.pickedStrings[t]=new vt;if(o.atNoteStart&&!w.continues&&!o.forceContinueAtStart)for(const t of o.pickedStrings)t.delayIndex=-1;for(let e=0;e<n.voices;e++)o.pickedStrings[e].update(this,g,o,e,l,t,s,y.stringSustainType)}}}static getLFOAmplitude(t,i){let s=0;for(const n of e.vibratos[t.vibrato].periodsSeconds)s+=Math.sin(2*Math.PI*i/n);return s}static getInstrumentSynthFunction(t){if(1==t.type){const i=t.algorithm+"_"+t.feedbackType;if(null==Ft.fmSynthFunctionCache[i]){const s=[];for(const i of Ft.fmSourceTemplate)if(-1!=i.indexOf("// CARRIER OUTPUTS")){const n=[];for(let i=0;i<e.algorithms[t.algorithm].carrierCount;i++)n.push("operator"+i+"Scaled");s.push(i.replace("/*operator#Scaled*/",n.join(" + ")))}else if(-1!=i.indexOf("// INSERT OPERATOR COMPUTATION HERE"))for(let i=e.operatorCount-1;i>=0;i--)for(const n of Ft.operatorSourceTemplate)if(-1!=n.indexOf("/* + operator@Scaled*/")){let o="";for(const s of e.algorithms[t.algorithm].modulatedBy[i])o+=" + operator"+(s-1)+"Scaled";const r=e.feedbacks[t.feedbackType].indices[i];if(r.length>0){o+=" + feedbackMult * (";const t=[];for(const e of r)t.push("operator"+(e-1)+"Output");o+=t.join(" + ")+")"}s.push(n.replace(/\#/g,i+"").replace("/* + operator@Scaled*/",o))}else s.push(n.replace(/\#/g,i+""));else if(-1!=i.indexOf("#"))for(let t=0;t<e.operatorCount;t++)s.push(i.replace(/\#/g,t+""));else s.push(i);const n="return (synth, bufferIndex, runLength, tone, instrument) => {"+s.join("\n")+"}";Ft.fmSynthFunctionCache[i]=new Function("Config","Synth",n)(e,Ft)}return Ft.fmSynthFunctionCache[i]}if(0==t.type)return Ft.chipSynth;if(5==t.type)return Ft.harmonicsSynth;if(6==t.type)return Ft.pulseWidthSynth;if(8==t.type)return Ft.supersawSynth;if(7==t.type)return Ft.pickedStringSynth;if(2==t.type)return Ft.noiseSynth;if(3==t.type)return Ft.spectrumSynth;if(4==t.type)return Ft.drumsetSynth;throw new Error("Unrecognized instrument type: "+t.type)}static chipSynth(t,e,i,s,n){const o=t.tempMonoInstrumentSampleBuffer,r=n.wave,h=r.length-1,a=s.specialIntervalExpressionMult*n.unison.sign;1!=n.unison.voices||n.chord.customInterval||(s.phases[1]=s.phases[0]);let l=s.phaseDeltas[0]*h,c=s.phaseDeltas[1]*h;const u=+s.phaseDeltaScales[0],f=+s.phaseDeltaScales[1];let p=+s.expression;const d=+s.expressionDelta;let m=s.phases[0]%1*h,y=s.phases[1]%1*h;const g=s.noteFilters,b=0|s.noteFilterCount;let w=+s.initialNoteFilterInput1,v=+s.initialNoteFilterInput2;const k=Ft.applyFilters,M=0|m,x=0|y,S=M%h,F=x%h,P=m-M,I=y-x;let T=+r[S],q=+r[F];T+=(r[S+1]-T)*P,q+=(r[F+1]-q)*I;const E=e+i;for(let t=e;t<E;t++){m+=l,y+=c;const e=0|m,i=0|y,s=e%h,n=i%h;let M=r[s],x=r[n];const S=m-e,F=y-i;M+=(r[s+1]-M)*S,x+=(r[n+1]-x)*F;const P=(M-T)/l,I=(x-q)/c;T=M,q=x;const E=P+I*a,C=k(E,w,v,b,g);v=w,w=E,l*=u,c*=f;const L=C*p;p+=d,o[t]+=L}s.phases[0]=m/h,s.phases[1]=y/h,s.phaseDeltas[0]=l/h,s.phaseDeltas[1]=c/h,s.expression=p,t.sanitizeFilters(g),s.initialNoteFilterInput1=w,s.initialNoteFilterInput2=v}static harmonicsSynth(t,e,i,s,n){const o=t.tempMonoInstrumentSampleBuffer,r=n.wave,h=r.length-1,a=s.specialIntervalExpressionMult*n.unison.sign;1!=n.unison.voices||n.chord.customInterval||(s.phases[1]=s.phases[0]);let l=s.phaseDeltas[0]*h,c=s.phaseDeltas[1]*h;const u=+s.phaseDeltaScales[0],f=+s.phaseDeltaScales[1];let p=+s.expression;const d=+s.expressionDelta;let m=s.phases[0]%1*h,y=s.phases[1]%1*h;const g=s.noteFilters,b=0|s.noteFilterCount;let w=+s.initialNoteFilterInput1,v=+s.initialNoteFilterInput2;const k=Ft.applyFilters,M=0|m,x=0|y,S=M%h,F=x%h,P=m-M,I=y-x;let T=+r[S],q=+r[F];T+=(r[S+1]-T)*P,q+=(r[F+1]-q)*I;const E=e+i;for(let t=e;t<E;t++){m+=l,y+=c;const e=0|m,i=0|y,s=e%h,n=i%h;let M=r[s],x=r[n];const S=m-e,F=y-i;M+=(r[s+1]-M)*S,x+=(r[n+1]-x)*F;const P=(M-T)/l,I=(x-q)/c;T=M,q=x;const E=P+I*a,C=k(E,w,v,b,g);v=w,w=E,l*=u,c*=f;const L=C*p;p+=d,o[t]+=L}s.phases[0]=m/h,s.phases[1]=y/h,s.phaseDeltas[0]=l/h,s.phaseDeltas[1]=c/h,s.expression=p,t.sanitizeFilters(g),s.initialNoteFilterInput1=w,s.initialNoteFilterInput2=v}static pickedStringSynth(t,i,s,n,o){const r=o.unison.voices;let h=Ft.pickedStringFunctionCache[r];if(null==h){let t="return (synth, bufferIndex, runLength, tone, instrumentState) => {";t+="\n\t\t\t\tconst data = synth.tempMonoInstrumentSampleBuffer;\n\t\t\t\t\n\t\t\t\tlet pickedString# = tone.pickedStrings[#];\n\t\t\t\tlet allPassSample# = +pickedString#.allPassSample;\n\t\t\t\tlet allPassPrevInput# = +pickedString#.allPassPrevInput;\n\t\t\t\tlet sustainFilterSample# = +pickedString#.sustainFilterSample;\n\t\t\t\tlet sustainFilterPrevOutput2# = +pickedString#.sustainFilterPrevOutput2;\n\t\t\t\tlet sustainFilterPrevInput1# = +pickedString#.sustainFilterPrevInput1;\n\t\t\t\tlet sustainFilterPrevInput2# = +pickedString#.sustainFilterPrevInput2;\n\t\t\t\tlet fractionalDelaySample# = +pickedString#.fractionalDelaySample;\n\t\t\t\tconst delayLine# = pickedString#.delayLine;\n\t\t\t\tconst delayBufferMask# = (delayLine#.length - 1) >> 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 sustainFilterA1# = +pickedString#.sustainFilterA1;\n\t\t\t\tlet sustainFilterA2# = +pickedString#.sustainFilterA2;\n\t\t\t\tlet sustainFilterB0# = +pickedString#.sustainFilterB0;\n\t\t\t\tlet sustainFilterB1# = +pickedString#.sustainFilterB1;\n\t\t\t\tlet sustainFilterB2# = +pickedString#.sustainFilterB2;\n\t\t\t\tconst allPassGDelta# = +pickedString#.allPassGDelta;\n\t\t\t\tconst sustainFilterA1Delta# = +pickedString#.sustainFilterA1Delta;\n\t\t\t\tconst sustainFilterA2Delta# = +pickedString#.sustainFilterA2Delta;\n\t\t\t\tconst sustainFilterB0Delta# = +pickedString#.sustainFilterB0Delta;\n\t\t\t\tconst sustainFilterB1Delta# = +pickedString#.sustainFilterB1Delta;\n\t\t\t\tconst sustainFilterB2Delta# = +pickedString#.sustainFilterB2Delta;\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.unison.sign;\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\tconst sustainFilterPrevOutput1# = sustainFilterSample#;\n\t\t\t\t\tsustainFilterSample# = sustainFilterB0# * allPassSample# + sustainFilterB1# * sustainFilterPrevInput1# + sustainFilterB2# * sustainFilterPrevInput2# - sustainFilterA1# * sustainFilterSample# - sustainFilterA2# * sustainFilterPrevOutput2#;\n\t\t\t\t\tsustainFilterPrevOutput2# = sustainFilterPrevOutput1#;\n\t\t\t\t\tsustainFilterPrevInput2# = sustainFilterPrevInput1#;\n\t\t\t\t\tsustainFilterPrevInput1# = allPassSample#;\n\t\t\t\t\t\n\t\t\t\t\tdelayLine#[delayIndex# & delayBufferMask#] += sustainFilterSample#;\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 i=[];for(let t=0;t<r;t++)i.push("fractionalDelaySample"+t+(1==t?" * unisonSign":""));t+=i.join(" + "),t+=") * expression;\n\t\t\t\t\tconst sample = applyFilters(inputSample, initialFilterInput1, initialFilterInput2, filterCount, filters);\n\t\t\t\t\tinitialFilterInput2 = initialFilterInput1;\n\t\t\t\t\tinitialFilterInput1 = inputSample;\n\t\t\t\t\tdata[sampleIndex] += sample;\n\t\t\t\t\t\n\t\t\t\t\texpression += expressionDelta;\n\t\t\t\t\tdelayLength# += delayLengthDelta#;\n\t\t\t\t\tallPassG# += allPassGDelta#;\n\t\t\t\t\tsustainFilterA1# += sustainFilterA1Delta#;\n\t\t\t\t\tsustainFilterA2# += sustainFilterA2Delta#;\n\t\t\t\t\tsustainFilterB0# += sustainFilterB0Delta#;\n\t\t\t\t\tsustainFilterB1# += sustainFilterB1Delta#;\n\t\t\t\t\tsustainFilterB2# += sustainFilterB2Delta#;\n\t\t\t\t}\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);\n\t\t\t\tif (!Number.isFinite(allPassSample#) || Math.abs(allPassSample#) < epsilon) allPassSample# = 0.0;\n\t\t\t\tif (!Number.isFinite(allPassPrevInput#) || Math.abs(allPassPrevInput#) < epsilon) allPassPrevInput# = 0.0;\n\t\t\t\tif (!Number.isFinite(sustainFilterSample#) || Math.abs(sustainFilterSample#) < epsilon) sustainFilterSample# = 0.0;\n\t\t\t\tif (!Number.isFinite(sustainFilterPrevOutput2#) || Math.abs(sustainFilterPrevOutput2#) < epsilon) sustainFilterPrevOutput2# = 0.0;\n\t\t\t\tif (!Number.isFinite(sustainFilterPrevInput1#) || Math.abs(sustainFilterPrevInput1#) < epsilon) sustainFilterPrevInput1# = 0.0;\n\t\t\t\tif (!Number.isFinite(sustainFilterPrevInput2#) || Math.abs(sustainFilterPrevInput2#) < epsilon) sustainFilterPrevInput2# = 0.0;\n\t\t\t\tif (!Number.isFinite(fractionalDelaySample#) || Math.abs(fractionalDelaySample#) < epsilon) fractionalDelaySample# = 0.0;\n\t\t\t\tpickedString#.allPassSample = allPassSample#;\n\t\t\t\tpickedString#.allPassPrevInput = allPassPrevInput#;\n\t\t\t\tpickedString#.sustainFilterSample = sustainFilterSample#;\n\t\t\t\tpickedString#.sustainFilterPrevOutput2 = sustainFilterPrevOutput2#;\n\t\t\t\tpickedString#.sustainFilterPrevInput1 = sustainFilterPrevInput1#;\n\t\t\t\tpickedString#.sustainFilterPrevInput2 = sustainFilterPrevInput2#;\n\t\t\t\tpickedString#.fractionalDelaySample = fractionalDelaySample#;\n\t\t\t\tpickedString#.delayIndex = delayIndex#;\n\t\t\t\tpickedString#.prevDelayLength = delayLength#;\n\t\t\t\tpickedString#.allPassG = allPassG#;\n\t\t\t\tpickedString#.sustainFilterA1 = sustainFilterA1#;\n\t\t\t\tpickedString#.sustainFilterA2 = sustainFilterA2#;\n\t\t\t\tpickedString#.sustainFilterB0 = sustainFilterB0#;\n\t\t\t\tpickedString#.sustainFilterB1 = sustainFilterB1#;\n\t\t\t\tpickedString#.sustainFilterB2 = sustainFilterB2#;\n\t\t\t\t\n\t\t\t\ttone.expression = expression;\n\t\t\t\t\n\t\t\t\tsynth.sanitizeFilters(filters);\n\t\t\t\ttone.initialNoteFilterInput1 = initialFilterInput1;\n\t\t\t\ttone.initialNoteFilterInput2 = initialFilterInput2;\n\t\t\t}",t=t.replace(/^.*\#.*$/gm,(t=>{const e=[];for(let i=0;i<r;i++)e.push(t.replace(/\#/g,String(i)));return e.join("\n")})),h=new Function("Config","Synth",t)(e,Ft),Ft.pickedStringFunctionCache[r]=h}h(t,i,s,n,o)}static effectsSynth(t,i,s,n,o,r){const h=m(r.effects),a=y(r.effects),l=r.eqFilterCount>0,c=g(r.effects),u=b(r.effects),f=w(r.effects),p=v(r.effects);let d=0;h&&(d|=1),d<<=1,a&&(d|=1),d<<=1,l&&(d|=1),d<<=1,c&&(d|=1),d<<=1,u&&(d|=1),d<<=1,f&&(d|=1),d<<=1,p&&(d|=1);let k=Ft.effectsFunctionCache[d];if(null==k){let t="return (synth, outputDataL, outputDataR, bufferIndex, runLength, instrumentState) => {";const i=u||p||f;t+="\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;",i&&(t+="\n\t\t\t\t\n\t\t\t\tlet delayInputMult = +instrumentState.delayInputMult;\n\t\t\t\tconst delayInputMultDelta = +instrumentState.delayInputMultDelta;"),h&&(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;"),a&&(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;"),l&&(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 = Synth.applyFilters;"),t+="\n\t\t\t\t\n\t\t\t\tlet eqFilterVolume = +instrumentState.eqFilterVolume;\n\t\t\t\tconst eqFilterVolumeDelta = +instrumentState.eqFilterVolumeDelta;",c&&(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;"),u&&(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 = +Config.chorusPeriodSeconds;\n\t\t\t\tconst chorusAngle = Math.PI * 2.0 / (chorusDuration * synth.samplesPerSecond);\n\t\t\t\tconst chorusRange = synth.samplesPerSecond * Config.chorusDelayRange;\n\t\t\t\tconst chorusOffset0 = synth.chorusDelayBufferSize - Config.chorusDelayOffsets[0][0] * chorusRange;\n\t\t\t\tconst chorusOffset1 = synth.chorusDelayBufferSize - Config.chorusDelayOffsets[0][1] * chorusRange;\n\t\t\t\tconst chorusOffset2 = synth.chorusDelayBufferSize - Config.chorusDelayOffsets[0][2] * chorusRange;\n\t\t\t\tconst chorusOffset3 = synth.chorusDelayBufferSize - Config.chorusDelayOffsets[1][0] * chorusRange;\n\t\t\t\tconst chorusOffset4 = synth.chorusDelayBufferSize - Config.chorusDelayOffsets[1][1] * chorusRange;\n\t\t\t\tconst chorusOffset5 = synth.chorusDelayBufferSize - 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 + Config.chorusPhaseOffsets[0][0]);\n\t\t\t\tlet chorusTap1Index = chorusDelayPos + chorusOffset1 - chorusRange * Math.sin(chorusPhase + Config.chorusPhaseOffsets[0][1]);\n\t\t\t\tlet chorusTap2Index = chorusDelayPos + chorusOffset2 - chorusRange * Math.sin(chorusPhase + Config.chorusPhaseOffsets[0][2]);\n\t\t\t\tlet chorusTap3Index = chorusDelayPos + chorusOffset3 - chorusRange * Math.sin(chorusPhase + Config.chorusPhaseOffsets[1][0]);\n\t\t\t\tlet chorusTap4Index = chorusDelayPos + chorusOffset4 - chorusRange * Math.sin(chorusPhase + Config.chorusPhaseOffsets[1][1]);\n\t\t\t\tlet chorusTap5Index = chorusDelayPos + chorusOffset5 - chorusRange * Math.sin(chorusPhase + Config.chorusPhaseOffsets[1][2]);\n\t\t\t\tchorusPhase += chorusAngle * runLength;\n\t\t\t\tconst chorusTap0End = chorusDelayPos + chorusOffset0 - chorusRange * Math.sin(chorusPhase + Config.chorusPhaseOffsets[0][0]) + runLength;\n\t\t\t\tconst chorusTap1End = chorusDelayPos + chorusOffset1 - chorusRange * Math.sin(chorusPhase + Config.chorusPhaseOffsets[0][1]) + runLength;\n\t\t\t\tconst chorusTap2End = chorusDelayPos + chorusOffset2 - chorusRange * Math.sin(chorusPhase + Config.chorusPhaseOffsets[0][2]) + runLength;\n\t\t\t\tconst chorusTap3End = chorusDelayPos + chorusOffset3 - chorusRange * Math.sin(chorusPhase + Config.chorusPhaseOffsets[1][0]) + runLength;\n\t\t\t\tconst chorusTap4End = chorusDelayPos + chorusOffset4 - chorusRange * Math.sin(chorusPhase + Config.chorusPhaseOffsets[1][1]) + runLength;\n\t\t\t\tconst chorusTap5End = chorusDelayPos + chorusOffset5 - chorusRange * Math.sin(chorusPhase + 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;"),f&&(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;",h&&(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;"),a&&(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;"),l&&(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+=c?"\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;",u&&(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;"),f&&(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;"),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;",i&&(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);",i&&(t+="\n\t\t\t\t\n\t\t\t\tinstrumentState.delayInputMult = delayInputMult;"),h&&(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;"),a&&(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;"),l&&(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;"),c&&(t+="\n\t\t\t\t\n\t\t\t\tSynth.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;"),u&&(t+="\n\t\t\t\t\n\t\t\t\tSynth.sanitizeDelayLine(chorusDelayLineL, chorusDelayPos, chorusMask);\n\t\t\t\tSynth.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;"),f&&(t+="\n\t\t\t\t\n\t\t\t\tSynth.sanitizeDelayLine(echoDelayLineL, echoDelayPos, echoMask);\n\t\t\t\tSynth.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\tSynth.sanitizeDelayLine(reverbDelayLine, reverbDelayPos , reverbMask);\n\t\t\t\tSynth.sanitizeDelayLine(reverbDelayLine, reverbDelayPos + 3041, reverbMask);\n\t\t\t\tSynth.sanitizeDelayLine(reverbDelayLine, reverbDelayPos + 6426, reverbMask);\n\t\t\t\tSynth.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;"),t+="}",k=new Function("Config","Synth",t)(e,Ft),Ft.effectsFunctionCache[d]=k}k(t,i,s,n,o,r)}static pulseWidthSynth(t,e,i,s,n){const o=t.tempMonoInstrumentSampleBuffer;let r=s.phaseDeltas[0];const h=+s.phaseDeltaScales[0];let a=+s.expression;const l=+s.expressionDelta;let c=s.phases[0]%1,u=s.pulseWidth;const f=s.pulseWidthDelta,p=s.noteFilters,d=0|s.noteFilterCount;let m=+s.initialNoteFilterInput1,y=+s.initialNoteFilterInput2;const g=Ft.applyFilters,b=e+i;for(let t=e;t<b;t++){const e=c%1,i=(c+u)%1;let s=i-e;if(e<r)s+=.5*((w=e/r)+w-w*w-1);else if(e>1-r){s+=.5*((w=(e-1)/r)+w+w*w+1)}if(i<r)s-=.5*((w=i/r)+w-w*w-1);else if(i>1-r){var w;s-=.5*((w=(i-1)/r)+w+w*w+1)}const n=s,b=g(n,m,y,d,p);y=m,m=n,c+=r,r*=h,u+=f;const v=b*a;a+=l,o[t]+=v}s.phases[0]=c,s.phaseDeltas[0]=r,s.expression=a,s.pulseWidth=u,t.sanitizeFilters(p),s.initialNoteFilterInput1=m,s.initialNoteFilterInput2=y}static supersawSynth(t,i,s,n,o){const r=t.tempMonoInstrumentSampleBuffer,h=0|e.supersawVoiceCount;let a=n.phaseDeltas[0];const l=+n.phaseDeltaScales[0];let c=+n.expression;const u=+n.expressionDelta;let f=n.phases,p=+n.supersawDynamism;const d=+n.supersawDynamismDelta,m=n.supersawUnisonDetunes;let y=+n.supersawShape;const g=+n.supersawShapeDelta;let b=+n.supersawDelayLength;const w=+n.supersawDelayLengthDelta,v=n.supersawDelayLine,k=v.length-1>>0;let M=0|n.supersawDelayIndex;M=(M&k)+v.length;const x=n.noteFilters,S=0|n.noteFilterCount;let F=+n.initialNoteFilterInput1,P=+n.initialNoteFilterInput2;const I=Ft.applyFilters,T=i+s;for(let t=i;t<T;t++){let e=(f[0]+a)%1,i=e-.5*(1+(h-1)*p);if(e<a)i-=.5*((q=e/a)+q-q*q-1);else if(e>1-a){var q;i-=.5*((q=(e-1)/a)+q+q*q+1)}f[0]=e;for(let t=1;t<h;t++){const e=a*m[t];let s=(f[t]+e)%1;if(i+=s*p,s<e){const t=s/e;i-=.5*(t+t-t*t-1)*p}else if(s>1-e){const t=(s-1)/e;i-=.5*(t+t+t*t+1)*p}f[t]=s}v[M&k]=i;const s=M-b,n=0|s,o=n+1,T=s-n,E=v[n&k];M++;const C=i-(E+(v[o&k]-E)*T)*y,L=I(C,F,P,S,x);P=F,F=C,a*=l,p+=d,y+=g,b+=w;const z=L*c;c+=u,r[t]+=z}n.phaseDeltas[0]=a,n.expression=c,n.supersawDynamism=p,n.supersawShape=y,n.supersawDelayLength=b,n.supersawDelayIndex=M,t.sanitizeFilters(x),n.initialNoteFilterInput1=F,n.initialNoteFilterInput2=P}static noiseSynth(t,i,s,n,o){const r=t.tempMonoInstrumentSampleBuffer,h=o.wave;let a=+n.phaseDeltas[0];const l=+n.phaseDeltaScales[0];let c=+n.expression;const u=+n.expressionDelta;let f=n.phases[0]%1*e.chipNoiseLength;0==n.phases[0]&&(f=Math.random()*e.chipNoiseLength);const p=e.chipNoiseLength-1;let d=+n.noiseSample;const m=n.noteFilters,y=0|n.noteFilterCount;let g=+n.initialNoteFilterInput1,b=+n.initialNoteFilterInput2;const w=Ft.applyFilters,v=Math.min(1,a*o.noisePitchFilterMult),k=i+s;for(let t=i;t<k;t++){d+=(h[f&p]-d)*v;const e=d,i=w(e,g,b,y,m);b=g,g=e,f+=a,a*=l;const s=i*c;c+=u,r[t]+=s}n.phases[0]=f/e.chipNoiseLength,n.phaseDeltas[0]=a,n.expression=c,n.noiseSample=d,t.sanitizeFilters(m),n.initialNoteFilterInput1=g,n.initialNoteFilterInput2=b}static spectrumSynth(t,i,s,n,o){const r=t.tempMonoInstrumentSampleBuffer,h=o.wave;let a=128*n.phaseDeltas[0];const l=+n.phaseDeltaScales[0];let c=+n.expression;const u=+n.expressionDelta;let f=+n.noiseSample;const p=n.noteFilters,d=0|n.noteFilterCount;let m=+n.initialNoteFilterInput1,y=+n.initialNoteFilterInput2;const g=Ft.applyFilters;let b=n.phases[0]%1*e.spectrumNoiseLength;0==n.phases[0]&&(b=Ft.findRandomZeroCrossing(h,e.spectrumNoiseLength)+a);const w=e.spectrumNoiseLength-1,v=Math.min(1,a),k=i+s;for(let t=i;t<k;t++){const e=0|b,i=e&w;let s=h[i];const n=b-e;s+=(h[i+1]-s)*n,f+=(s-f)*v;const o=f,k=g(o,m,y,d,p);y=m,m=o,b+=a,a*=l;const M=k*c;c+=u,r[t]+=M}n.phases[0]=b/e.spectrumNoiseLength,n.phaseDeltas[0]=a/128,n.expression=c,n.noiseSample=f,t.sanitizeFilters(p),n.initialNoteFilterInput1=m,n.initialNoteFilterInput2=y}static drumsetSynth(t,i,s,n,o){const r=t.tempMonoInstrumentSampleBuffer;let h=o.getDrumsetWave(n.drumsetPitch);const a=xt.drumsetIndexReferenceDelta(n.drumsetPitch);let l=n.phaseDeltas[0]/a;const c=+n.phaseDeltaScales[0];let u=+n.expression;const f=+n.expressionDelta,p=n.noteFilters,d=0|n.noteFilterCount;let m=+n.initialNoteFilterInput1,y=+n.initialNoteFilterInput2;const g=Ft.applyFilters;let b=n.phases[0]%1*e.spectrumNoiseLength;0==n.phases[0]&&(b=Ft.findRandomZeroCrossing(h,e.spectrumNoiseLength)+l);const w=e.spectrumNoiseLength-1,v=i+s;for(let t=i;t<v;t++){const e=0|b,i=e&w;let s=h[i];const n=b-e;s+=(h[i+1]-s)*n;const o=s,a=g(o,m,y,d,p);y=m,m=o,b+=l,l*=c;const v=a*u;u+=f,r[t]+=v}n.phases[0]=b/e.spectrumNoiseLength,n.phaseDeltas[0]=l*a,n.expression=u,t.sanitizeFilters(p),n.initialNoteFilterInput1=m,n.initialNoteFilterInput2=y}static findRandomZeroCrossing(t,e){let i=Math.random()*e;const s=e-1;let n=i&s,o=t[n];for(let r=128;r>0;r--){const r=n+16&s,h=t[r];if(o*h<=0){for(let r=0;r<16;r++){const r=n+1&s,h=t[r];if(o*h<=0){const t=h-o;i=n,Math.abs(t)>1e-8&&(i+=-o/t),i=Math.max(0,i)%e;break}n=r,o=h}break}n=r,o=h}return i}static instrumentVolumeToVolumeMult(t){return t==e.volumeRange-1?0:Math.pow(2,e.volumeLogScale*t)}static volumeMultToInstrumentVolume(t){return t<=0?e.volumeRange-1:Math.min(e.volumeRange-2,Math.log2(t)/e.volumeLogScale)}static noteSizeToVolumeMult(t){return Math.pow(Math.max(0,t)/e.noteSizeMax,1.5)}static volumeMultToNoteSize(t){return Math.pow(Math.max(0,t),1/1.5)*e.noteSizeMax}static fadeInSettingToSeconds(t){return.0125*(.95*t+.05*t*t)}static secondsToFadeInSetting(t){return tt(0,e.fadeInRange,Math.round((-.95+Math.sqrt(.9025+.2*t/.0125))/.1))}static fadeOutSettingToTicks(t){return e.fadeOutTicks[t]}static ticksToFadeOutSetting(t){let i=e.fadeOutTicks[0];if(t<=i)return 0;for(let s=1;s<e.fadeOutTicks.length;s++){let n=e.fadeOutTicks[s];if(t<=n)return t<(i+n)/2?s-1:s;i=n}return e.fadeOutTicks.length-1}static detuneToCents(t){return t*(Math.abs(t)+1)/2}static centsToDetune(t){return Math.sign(t)*(Math.sqrt(1+8*Math.abs(t))-1)/2}getSamplesPerTick(){if(null==this.song)return 0;const t=this.song.getBeatsPerMinute()/60,i=e.partsPerBeat*t,s=e.ticksPerPart*i;return this.samplesPerSecond/s}static fittingPowerOfTwo(t){return 1<<32-Math.clz32(Math.ceil(t)-1)}sanitizeFilters(t){let e=!1;for(const i of t){const t=Math.abs(i.output1),s=Math.abs(i.output2);if(!(t<100&&s<100)){e=!0;break}t<Z&&(i.output1=0),s<Z&&(i.output2=0)}if(e)for(const e of t)e.output1=0,e.output2=0}static sanitizeDelayLine(t,e,i){for(;;){const s=--e&i,n=Math.abs(t[s]);if(Number.isFinite(n)&&(0==n||n>=Z))break;t[s]=0}}static applyFilters(t,e,i,s,n){for(let o=0;o<s;o++){const s=n[o],r=s.output1,h=s.output2,a=s.a1,l=s.a2,c=s.b0,u=s.b1,f=s.b2;t=c*t+u*e+f*i-a*r-l*h,s.a1=a+s.a1Delta,s.a2=l+s.a2Delta,s.useMultiplicativeInputCoefficients?(s.b0=c*s.b0Delta,s.b1=u*s.b1Delta,s.b2=f*s.b2Delta):(s.b0=c+s.b0Delta,s.b1=u+s.b1Delta,s.b2=f+s.b2Delta),s.output2=r,s.output1=t,i=h,e=r}return t}}Ft.tempFilterStartCoefficients=new Y,Ft.tempFilterEndCoefficients=new Y,Ft.fmSynthFunctionCache={},Ft.effectsFunctionCache=Array(128).fill(void 0),Ft.pickedStringFunctionCache=Array(3).fill(void 0),Ft.fmSourceTemplate=("\n\t\tconst data = synth.tempMonoInstrumentSampleBuffer;\n\t\tconst sineWave = Config.sineWave;\n\t\t\n\t\t// I'm adding 1000 to the phase to ensure that it's never negative even when modulated by other waves because negative numbers don't work with the modulus operator very well.\n\t\tlet operator#Phase = +((tone.phases[#] % 1) + 1000) * "+e.sineWaveLength+";\n\t\tlet operator#PhaseDelta = +tone.phaseDeltas[#] * "+e.sineWaveLength+";\n\t\tlet operator#PhaseDeltaScale = +tone.phaseDeltaScales[#];\n\t\tlet operator#OutputMult = +tone.operatorExpressions[#];\n\t\tconst operator#OutputDelta = +tone.operatorExpressionDeltas[#];\n\t\tlet operator#Output = +tone.feedbackOutputs[#];\n\t\tlet feedbackMult = +tone.feedbackMult;\n\t\tconst feedbackDelta = +tone.feedbackDelta;\n\t\tlet expression = +tone.expression;\n\t\tconst expressionDelta = +tone.expressionDelta;\n\t\t\n\t\tconst filters = tone.noteFilters;\n\t\tconst filterCount = tone.noteFilterCount|0;\n\t\tlet initialFilterInput1 = +tone.initialNoteFilterInput1;\n\t\tlet initialFilterInput2 = +tone.initialNoteFilterInput2;\n\t\tconst applyFilters = Synth.applyFilters;\n\t\t\n\t\tconst stopIndex = bufferIndex + runLength;\n\t\tfor (let sampleIndex = bufferIndex; sampleIndex < stopIndex; sampleIndex++) {\n\t\t\t// INSERT OPERATOR COMPUTATION HERE\n\t\t\tconst fmOutput = (/*operator#Scaled*/); // CARRIER OUTPUTS\n\t\t\t\n\t\t\tconst inputSample = fmOutput;\n\t\t\tconst sample = applyFilters(inputSample, initialFilterInput1, initialFilterInput2, filterCount, filters);\n\t\t\tinitialFilterInput2 = initialFilterInput1;\n\t\t\tinitialFilterInput1 = inputSample;\n\t\t\t\n\t\t\tfeedbackMult += feedbackDelta;\n\t\t\toperator#OutputMult += operator#OutputDelta;\n\t\t\toperator#Phase += operator#PhaseDelta;\n\t\t\toperator#PhaseDelta *= operator#PhaseDeltaScale;\n\t\t\t\n\t\t\tconst output = sample * expression;\n\t\t\texpression += expressionDelta;\n\t\t\t\n\t\t\tdata[sampleIndex] += output;\n\t\t}\n\t\t\n\t\ttone.phases[#] = operator#Phase / "+e.sineWaveLength+";\n\t\ttone.phaseDeltas[#] = operator#PhaseDelta / "+e.sineWaveLength+";\n\t\ttone.operatorExpressions[#] = operator#OutputMult;\n\t\ttone.feedbackOutputs[#] = operator#Output;\n\t\ttone.feedbackMult = feedbackMult;\n\t\ttone.expression = expression;\n\t\t\n\t\tsynth.sanitizeFilters(filters);\n\t\ttone.initialNoteFilterInput1 = initialFilterInput1;\n\t\ttone.initialNoteFilterInput2 = initialFilterInput2;\n\t").split("\n"),Ft.operatorSourceTemplate=("\n\t\t\tconst operator#PhaseMix = operator#Phase/* + operator@Scaled*/;\n\t\t\tconst operator#PhaseInt = operator#PhaseMix|0;\n\t\t\tconst operator#Index = operator#PhaseInt & "+e.sineWaveMask+";\n\t\t\tconst operator#Sample = sineWave[operator#Index];\n\t\t\toperator#Output = operator#Sample + (sineWave[operator#Index + 1] - operator#Sample) * (operator#PhaseMix - operator#PhaseInt);\n\t\t\tconst operator#Scaled = operator#OutputMult * operator#Output;\n\t").split("\n");const{button:Pt,div:It,p:Tt,h2:qt}=D;class Et{constructor(t,e){let i;switch(this.j=t,this.W=Pt({class:"cancelButton"}),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.W.removeEventListener("click",this.K)},e){case"scale":i=It(qt("Scale"),Tt("This setting limits the available pitches for adding notes. You may think that there's no point in limiting your choices, but the set of pitches you use has a strong influence on the mood and feel of your song, and these scales serve as guides to help you choose appropriate pitches. Don't worry, you can change the scale at any time, so you're not locked into it. Try making little melodies using all the available pitches of a scale to get a sense for how it sounds."),Tt('Most of the scales have a major version, and a minor version. Assuming your song uses all pitches in the scale and especially "tonic" pitches (the brown rows in the pattern editor) then major scales tend to sound more playful or optimistic, whereas minor scales sound more serious or sad.'));break;case"key":i=It(qt("Song Key"),Tt('This setting can shift the frequency of every note in your entire song up or down, keeping the "tonic" pitches (the brown rows in the pattern editor) aligned with the selected "key" pitch.'),Tt('If you\'ve already placed some notes but they don\'t emphasize "tonic" pitches then the selected key isn\'t very meaningful. You can select the "Detect Key" option in the key menu to automatically align the most emphasized notes with "tonic" pitches.'));break;case"tempo":i=It(qt("Song Tempo"),Tt('This setting controls the speed of your song, measured in beats-per-minute. A "beat" is the duration of the little gray rectangles in the pattern editor. (In conventional music notation, a "quarter note" is usually equivalent to "beat".)'));break;case"reverb":i=It(qt("Reverb"),Tt('Reverb is like a continuous echo effect. A little bit helps instruments sound more natural. Adding a lot of reverb can add sense of depth or mystery, but too much reverb can kinda "smear" sounds so that it\'s harder to distinguish notes or instruments, especially for lower "bass" notes.'));break;case"rhythm":i=It(qt("Rhythm"),Tt("This setting determines how beats are divided. The pattern editor helps you align notes to fractions of a beat based on this setting."),Tt("If you've already placed some notes but they don't align with the selected rhythm, you can select the \"Snap Notes To Rhythm\" option in the rhythm menu to force the notes in the currently selected pattern(s) to align with the selected rhythm."));break;case"instrumentIndex":i=It(qt("Instrument Number"),Tt('In the "Channel Settings" option from BeepBox\'s "Edit" menu, there are a few ways to enable multiple instruments per channel.'),Tt("First, you could enable multiple simultaneous instruments per channel. All of the channel's instruments will play all of the notes in the channel at the same time, and you can click an instrument number to view and edit its settings."),Tt("Second, you could enable different instruments per pattern. Only one of the instruments will play at any given time, but you can click the instrument number to change which instrument is used for the currently selected pattern(s)."),Tt("Finally, you can enable them both, in which case you can click an instrument number once to view it, and again to toggle whether the instrument is used for the currently selected pattern(s)."),Tt("Either way, you can click the + button to add more instruments to a channel, and you can press shift and a number key on your keyboard to select an instrument as if you had clicked the corresponding button here."));break;case"instrumentVolume":i=It(qt("Instrument Volume"),Tt("This setting controls the volume of the selected instrument without affecting the volume of the other instruments. This allows you to balance the loudness of each instrument relative to each other."));break;case"pan":i=It(qt("Instrument Panning"),Tt("If you're listening through headphones or some other stereo sound system, this controls the position of the instrument and where the sound is coming from, ranging from left to right."),Tt("As a suggestion, composers often put lead melodies, drums, and basses in the center, and spread other instruments toward either side. If too many instruments seem like they're coming from the same place, it can feel crowded and harder to distinguish individual sounds, especially if they cover a similar pitch range."));break;case"instrumentType":i=It(qt("Instrument Type"),Tt("BeepBox comes with many instrument presets, try them out! You can also create your own custom instruments!"),Tt("There are also options for copying and pasting instrument settings and for generating random instruments at the top of the instrument type menu."));break;case"eqFilter":i=It(qt("EQ Filter"),Tt("Filters are a way of emphasizing or diminishing different parts of a sound. Musical notes have a fundamental (base) frequency, but the sound of a musical note also has parts at higher frequencies and filters can adjust the volume of each of these parts based on their frequency."),Tt("Click in the filter editor to insert, delete, or drag a filter control point. The horizontal position of the point determines which frequencies it affects, and the vertical position determines how the volume is affected at that frequency."),Tt('Insert a new point on the left side of the filter editor to add a "high-pass" filter point, which additionally reduces the volume of lower frequencies, or insert a new point on the right side to add a "low-pass" filter point which reduces the volume of higher frequencies.'),Tt('You can also enable a "Note Filter" as an effect. EQ and note filters are mostly the same, but have different purposes. EQ filters are for overall adjustments, whereas note filters are for dynamic control and can be moved with envelopes. Note filters also change how the distortion effect sounds.'));break;case"noteFilter":i=It(qt("Note Filter"),Tt("Note filters are mostly the same as EQ filters, but have a different purpose. EQ filters are for overall adjustments, whereas note filters are for dynamic control and can be moved with envelopes. Note filters also change how the distortion effect sounds."),Tt("Filters are a way of emphasizing or diminishing different parts of a sound. Musical notes have a fundamental (base) frequency, but the sound of a musical note also has parts at higher frequencies and filters can adjust the volume of each of these parts based on their frequency."),Tt("Click in the filter editor to insert, delete, or drag a filter control point. The horizontal position of the point determines which frequencies it affects, and the vertical position determines how the volume is affected at that frequency."),Tt('Insert a new point on the left side of the filter editor to add a "high-pass" filter point, which additionally reduces the volume of lower frequencies, or insert a new point on the right side to add a "low-pass" filter point which reduces the volume of higher frequencies.'));break;case"fadeInOut":i=It(qt("Fade In/Out"),Tt("This setting controls how long it takes for notes to reach full volume at the beginning or decay to silence at the end."),Tt("An instant fade-in sounds like instruments that are played by hitting or plucking, whereas slower fade-ins sound like instruments that are played by blowing air."),Tt("You can also make the fade-out start before the note ends to leave a gap before the next note starts, or after the note ends to allow the sound of the end of the note to overlap with the start of the next note."));break;case"transition":i=It(qt("Transition"),Tt("Usually, when one note ends at the same time another begins, the old note will fade out and the new note will fade in based on the fade in/out settings, but this setting can override that, connecting the end of one note to the beginning of the next."),Tt('The "interrupt" transition makes the wave suddenly change from the old note\'s frequency to the new note\'s frequency without any fading, but still restarts envelopes at the beginning of the new note. The "continue" transition is similar but it doesn\'t even restart envelopes, and can be used to make each of the notes in a chord start or stop at different times!'),Tt('The "slide" transition makes the pitch shift quickly but not instantaneously from the old note\'s frequency to the new note\'s frequency, and softly restarts envelopes. The "slide in pattern" transition is the same except it doesn\'t connect the last note in a pattern to the first note in the next pattern.'));break;case"chipWave":i=It(qt("Chip Wave"),Tt("BeepBox comes with some sound waves based on classic electronic sound chips, as well as several unique waves. This is the basic source of the sound of the instrument, which is modified by the other instrument settings."));break;case"chipNoise":i=It(qt("Noise"),Tt("BeepBox comes with several basic noise sounds. These do not have any distinct musical pitch, and can be used like drums to create beats and emphasize your song's rhythm."));break;case"supersawDynamism":i=It(qt("Supersaw Dynamism"),Tt("A supersaw is a combination of many sawtooth waves, and this setting controls the contribution of extra sawtooth waves."),Tt('At the low end of the slider, only the first wave is contributing to the sound, which sounds like an ordinary static sawtooth wave. At the maximum setting, all of the waves are contributing equally and the resulting tone can randomly shift depending on how the waves line up with each other, similar to the "unison" and "chorus" settings.'));break;case"supersawSpread":i=It(qt("Supersaw Spread"),Tt("A supersaw is a combination of many sawtooth waves, and this setting controls the distance between their frequencies. The dynamism setting must be used for the extra waves to have any effect."),Tt('At the low end of the spread slider, all of the voices have the same frequency but random phase, resulting in a different sound every time a note starts. In the middle, the waves all have slightly different frequencies that shift in and out of phase over time similar to the "unison" and "chorus" settings, creating a classic supersaw sound. At the extreme end, the frequencies are so far apart they sound dissonant.'));break;case"supersawShape":i=It(qt("Supersaw Shape"),Tt("This supersaw instrument includes an option to change the shape of the waves from sawtooth waves to pulse waves. Use this setting to morph between the two shapes."),Tt("When a pulse wave shape is used, you can also control the pulse width with a separate setting."));break;case"pulseWidth":i=It(qt("Pulse Wave Width"),Tt("This setting controls the shape and sound of a pulse wave. At the minimum width, it sounds light and buzzy. At the maximum width, it is shaped like a classic square wave."));break;case"unison":i=It(qt("Unison"),Tt("This instrument can play two identical waves at different frequencies. When two waves play at slightly different frequencies, they move in and out of phase with each other over time as different parts of the waves line up. This creates a dynamic, shifting sound. Pianos are a common example of this kind of sound, because each piano key strikes multiple strings that are tuned to slightly different frequencies."),Tt('The distance between two frequencies is called an "interval", and this setting controls how large it is. If the interval is too wide, then the waves may sound out-of-tune and "dissonant". However, if the interval is even larger, then the two frequencies can even be distinct pitches.'));break;case"chords":i=It(qt("Chords"),Tt("When multiple different notes occur at the same time, this is called a chord. Chords can be created in BeepBox's pattern editor by adding notes above or below another note."),Tt('This setting determines how chords are played. The standard option is "simultaneous" which starts playing all of the pitches in a chord at the same instant. The "strum" option is similar, but plays the notes starting at slightly different times. The "arpeggio" option is used in "chiptune" style music and plays a single tone that rapidly alternates between all of the pitches in the chord.'),Tt('Some BeepBox instruments have an option called "custom interval" which uses the chord notes to control the interval between the waves of a single tone. This can create strange sound effects when combined with FM modulators.'));break;case"vibrato":i=It(qt("Vibrato"),Tt("This setting causes the frequency of a note to wobble slightly. Singers and violinists often use vibrato."));break;case"algorithm":i=It(qt("FM Algorithm"),Tt("FM Synthesis is a mysterious but powerful technique for crafting sounds, popularized by Yamaha keyboards and the Sega Genesis/Mega Drive. It may seem confusing, but try playing around with the options until you get a feel for it, or check out some of the preset examples!"),Tt("This FM synthesizer uses up to four waves, numbered 1, 2, 3, and 4. Each wave may have its own frequency and volume."),Tt('There are two kinds of waves: "carrier" waves play a tone out loud, but "modulator" waves distort other waves instead. Wave 1 is always a carrier and plays a tone, but other waves may distort it. The "Algorithm" setting determines which waves are modulators, and which other waves those modulators distort. For example, "1←2" means that wave 2 modulates wave 1, and wave 1 plays out loud.'));break;case"feedbackType":i=It(qt("Feedback Type"),Tt("Modulators distort in one direction (like 1←2), but you can also use the feedback setting to make any wave distort in the opposite direction (1→2), or even itself (1⟲)."));break;case"feedbackVolume":i=It(qt("Feedback Distortion"),Tt("This setting controls the amount of feedback distortion based on the feedback type setting."));break;case"operatorFrequency":i=It(qt("Operator Frequency"),Tt('This setting controls the frequency of an individual FM wave, relative to the fundamental frequency of the note. The multiplier 1× is the same as the fundamental frequency, whereas 2x would be an octave (12 semitones) above it. The frequencies with a "~" are slightly detuned and shift in and out of phase over time compared to the other frequencies.'),Tt('Try different combinations of a "carrier" wave and a "modulator" wave with different frequencies to get a feel for how they sound together.'));break;case"operatorVolume":i=It(qt("Operator Volume"),Tt('This setting controls the volume of "carrier" waves, or the amount of distortion that "modulator" waves apply to other waves.'));break;case"spectrum":i=It(qt("Spectrum"),Tt("This setting allows you to draw your own noise spectrum! This is good for making drum sounds."),Tt("If you only use certain frequencies and a soft fade in/out, it's also possible to make howling wind sounds or even musical wind instruments."),Tt("The left side of the spectrum editor controls the noise energy at lower frequencies, and the right side controls higher frequencies."));break;case"harmonics":i=It(qt("Harmonics"),Tt("This setting allows you to design your own sound wave! Most musical waves are actually a combination of sine waves at certain frequencies, and this lets you control the volume of each sine wave individually."),Tt("The left side of the harmonics editor controls the sine wave volumes at lower frequencies, and the right side controls higher frequencies."));break;case"effects":i=It(qt("Effects"),Tt("BeepBox has many different kinds of special effects you can add to instruments. You can turn on multiple effects at once, and they can be configured individually. Try them all out!"));break;case"drumsetEnvelope":i=It(qt("Drumset Envelope"),Tt("This drumset comes with a low-pass filter, and this setting can dynamically change the low-pass filter frequency over time. Each row in the pattern editor can have a different envelope shape."));break;case"drumsetSpectrum":i=It(qt("Drumset Spectrum"),Tt("This setting allows you to draw your own noise spectrum! This is good for making drumsets. Each row in the pattern editor gets its own spectrum."),Tt("The left side of the spectrum editor controls the noise energy at lower frequencies, and the right side controls higher frequencies."));break;case"chorus":i=It(qt("Chorus"),Tt("The chorus effect combines multiple copies of the instrument's sound and adds a bit of vibrato to simulate an ensemble of instruments or voices. Drag the slider to control how much chorus is added."));break;case"echoSustain":i=It(qt("Echo Volume"),Tt("The echo effect repeats the instrument's sound after a delay. Each echo is a little bit quieter than the last, and this setting controls how much quieter."));break;case"echoDelay":i=It(qt("Echo Delay"),Tt("The echo effect repeats the instrument's sound after a delay, and this setting controls how long the delay is."));break;case"pitchShift":i=It(qt("Pitch Shift"),Tt("This setting makes instruments play higher or lower pitches than the ones displayed in the pattern editor. Be careful that you don't confuse yourself!"),Tt("You can combine this with envelopes to bend pitch over time, or play multiple simultaneous instruments with different pitch shifts for interesting layered sounds."),Tt('The intervals created by this setting are in "just intonation" which means they stay in phase with the original pitch instead of shifting in and out of phase over time. If you want the shifting, add the detune effect!'));break;case"detune":i=It(qt("Detune"),Tt('This setting slightly adjusts the frequency of notes played by the instrument. You can use a little bit to add a pleasing shifting sound similar to the "unison" feature when combined with other instruments. If you use too much, then the instrument may sound unpleasantly out-of-tune.'));break;case"distortion":i=It(qt("Distortion"),Tt("This is the famous electric guitar effect! However, there are some things to be aware of."),Tt('First, most chords don\'t sound right when combined with heavy distortion. The only chords commonly used with distorted electric guitars are "power chords" which consist of a root note, a "fifth" note above that, and/or any octaves of those two notes.'),Tt("Second, the distortion sound depends a lot on filtering. In particular, I recommend enabling the note filter effect, and adding both high-pass and low-pass points to the note filter. (Note filters are applied first, then distortion which transforms the sound based on that filtering, then the EQ filter is applied last.)"),Tt("Finally, I recommend adjusting the fade-out setting to allow the end of each note to overlap a little bit with the beginning of the next, but not too much!"));break;case"bitcrusherQuantization":i=It(qt("Bitcrusher Quantization"),Tt("This effect makes stuff sounds harsher, artificial, and \"low quality\", which is great if that's what you're going for!"));break;case"bitcrusherFreq":i=It(qt("Frequency Quantization"),Tt("The bitcrusher effect comes with an additional frequency quantization effect! This is a fun one to play with, especially when combined with the note filter effect."),Tt("Every other notch on this slider is aligned with the currently selected key of the song, and the in-between notches are aligned with the tritones of the key."));break;case"envelopes":i=It(qt("Envelopes"),Tt("Envelopes are a way to dynamically adjust various other settings over time, usually based on how long the note lasts. Press the + button to add an envelope, then use the menus below to select which setting to control and the curve of the envelope. Try different combinations to see how they sound!"),Tt('Most envelope curves restart from the beginning every time a new note plays. The "note size" option is based on the note width as drawn in the pattern editor.'),Tt("Envelope curves move in the range from 0 to 1 (or vice versa), where 0 means as quiet as possible and 1 is the same as the corresponding position selected in the instrument settings above. If multiple envelopes are targetting the same setting, they are multiplied before applying to the setting."));break;default:throw new Error("Unhandled TipPrompt type: "+e)}this.container=It({class:"prompt",style:"width: 300px;"},i,this.W),setTimeout((()=>this.W.focus())),this.W.addEventListener("click",this.K)}}class Ct{constructor(){this.Y=!0}J(){this.Y=!1}isNoop(){return this.Y}commit(){}}class Lt extends Ct{constructor(t){super(),this.X=t,this.Z=!t}undo(){this.X?(this.tt(),this.Z=!0):(this.et(),this.Z=!1)}redo(){this.X?(this.et(),this.Z=!1):(this.tt(),this.Z=!0)}it(){return this.Z}tt(){throw new Error("Change.doForwards(): Override me.")}et(){throw new Error("Change.doBackwards(): Override me.")}}class zt extends Ct{constructor(){super()}append(t){t.isNoop()||this.J()}}class Dt extends Lt{constructor(t){super(!1),this.st=null==t?[]:t.concat()}append(t){t.isNoop()||(this.st[this.st.length]=t,this.J())}tt(){for(let t=0;t<this.st.length;t++)this.st[t].redo()}et(){for(let t=this.st.length-1;t>=0;t--)this.st[t].undo()}}function At(t,e){const i=t.every((t=>-1!=e.indexOf(t))),s=e.every((e=>-1!=t.indexOf(e)));return i&&s&&e.length==t.length}function Bt(t,e,i){const s=new Set(t);t.length=0,t.push(...s);for(let s=0;s<t.length;s++)t[s]>=e.channels[i].instruments.length&&(t.splice(s,1),s--);t.length>e.getMaxInstrumentsPerPattern(i)&&(t.length=e.getMaxInstrumentsPerPattern(i)),t.length<=0&&(t[0]=0)}function Ot(t,e){for(const i of t.notes)for(const t of i.pitches)for(const s of i.pins){const i=(t+s.interval)%12;e[i]||(e[i]=!0)}}function Nt(t){for(let e=1;e<t.length-1;){const i=t[e-1],s=t[e],n=t[e+1],o=s.time-i.time,r=n.time-s.time;(s.interval-i.interval)*r==(n.interval-s.interval)*o&&(s.size-i.size)*r==(n.size-s.size)*o?t.splice(e,1):e++}}function Rt(t,i,s,n,o){const r=new ht(-1,s,n,e.noteSizeMax,!1);r.pins.length=0,r.pitches.length=0;const h=n-s;for(const e of t.pitches)r.pitches.push(e);for(let e=0;e<t.pins.length;e++){const s=t.pins[e],n=s.time+i;if(n<0){if(e+1>=t.pins.length)throw new Error("Error converting pins in note overflow.");const o=t.pins[e+1],h=o.time+i;if(h>0){const t=-n/(h-n);r.pins.push(rt(Math.round(s.interval+t*(o.interval-s.interval)),0,Math.round(s.size+t*(o.size-s.size))))}}else if(n<=h)r.pins.push(rt(s.interval,n,s.size));else{if(e<1)throw new Error("Error converting pins in note overflow.");const o=t.pins[e-1],a=o.time+i;if(a<h){const t=(h-a)/(n-a);r.pins.push(rt(Math.round(o.interval+t*(s.interval-o.interval)),h,Math.round(o.size+t*(s.size-o.size))))}}}const a=r.pins[0].interval;for(let t=0;t<r.pitches.length;t++)r.pitches[t]+=a;for(let t=0;t<r.pins.length;t++)r.pins[t].interval-=a;let l=!1;if(0==r.start)r.continuesLastPattern=i<0||t.continuesLastPattern;else if(r.continuesLastPattern=!1,o.length>0&&t.continuesLastPattern){const t=o[o.length-1];if(t.end==r.start&&Ft.adjacentNotesHaveMatchingPitches(t,r)){l=!0;const e=t.pins[t.pins.length-1].interval,i=t.end-t.start;for(let s=1;s<r.pins.length;s++){const n=r.pins[s],o=rt(n.interval+e,n.time+i,n.size);t.pins.push(o),t.end=t.start+o.time}Nt(t.pins)}}l||o.push(r)}class Ht extends zt{constructor(t,i,s){super();const n=[],o=[];for(let r=0;r<t.song.getChannelCount();r++){const h=t.song.channels[r],a=new bt;r<t.song.pitchChannelCount?n.push(a):o.push(a),a.muted=h.muted,a.octave=h.octave;for(const t of h.instruments)a.instruments.push(t);const l=e.partsPerBeat*t.song.beatsPerBar,c=e.partsPerBeat*i;let u=-1,f=null;for(let e=0;e<t.song.barCount;e++){const i=t.song.getPattern(r,e);if(null!=i){const t=e*l;for(const e of i.notes){const n=e.start+t+s,o=e.end+t+s,r=Math.floor(n/c),h=Math.ceil(o/c);for(let t=r;t<h;t++){const s=t*c,r=Math.max(0,n-s),h=Math.min(c,o-s);if(r<h){if(u!=t||null==f){for(u++;u<t;)a.bars[u]=0,u++;f=new at,a.patterns.push(f),a.bars[u]=a.patterns.length,f.instruments.length=0,f.instruments.push(...i.instruments)}Rt(e,n-s-r,r,h,f.notes)}}}}}}ii(n),ii(o),this.append(new ti(t,n,o))}}class Gt extends Lt{constructor(t,e){super(!1),this.j=t,this.nt=e,this.ot=this.nt.start,this.rt=this.nt.end,this.ht=this.nt.start,this.lt=this.nt.end,this.ct=this.nt.pins,this.ut=[],this.ft=this.nt.pitches,this.dt=[],this.yt=this.nt.continuesLastPattern,this.gt=this.nt.continuesLastPattern}bt(t){for(let t=0;t<this.ut.length-1;)this.ut[t].time>=this.ut[t+1].time?this.ut.splice(t,1):t++;Nt(this.ut);const e=this.ut[0].interval,i=this.ut[0].time;for(let t=0;t<this.ft.length;t++)this.dt[t]=this.ft[t]+e;for(let t=0;t<this.ut.length;t++)this.ut[t].interval-=e,this.ut[t].time-=i;this.ht=this.ot+i,this.lt=this.ht+this.ut[this.ut.length-1].time,null!=t&&(this.gt=t),0!=this.ht&&(this.gt=!1),this.tt(),this.J()}tt(){this.nt.pins=this.ut,this.nt.pitches=this.dt,this.nt.start=this.ht,this.nt.end=this.lt,this.nt.continuesLastPattern=this.gt,null!=this.j&&this.j.notifier.changed()}et(){this.nt.pins=this.ct,this.nt.pitches=this.ft,this.nt.start=this.ot,this.nt.end=this.rt,this.nt.continuesLastPattern=this.yt,null!=this.j&&this.j.notifier.changed()}}class $t extends Ct{constructor(t){super();const e=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];e.preset!=e.type&&(e.preset=e.type,t.notifier.changed(),this.J())}}class _t extends Ct{constructor(t,i){super();const s=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];if(s.preset!=i){const n=x.valueToPreset(i);if(null!=n)if(null!=n.customType)s.type=n.customType,!e.instrumentTypeHasSpecialInterval[s.type]&&e.chords[s.chord].customInterval&&(s.chord=0),s.clearInvalidEnvelopeTargets();else if(null!=n.settings){const i=s.volume,o=s.pan,r=g(s.effects);s.fromJsonObject(n.settings,t.song.getChannelIsNoise(t.channel),1),s.volume=i,s.pan=o,r&&s.pan!=e.panCenter&&(s.effects=4|s.effects)}s.preset=i,t.notifier.changed(),this.J()}}}class Ut extends Ct{constructor(t){function i(t){let e=0;for(const i of t)e+=i.weight;let i=Math.random()*e;for(const e of t)if(i-=e.weight,i<=0)return e.item;return t[Math.random()*t.length|0].item}function s(t,e,s,n){const o=[];for(let i=t;i<=e;i++)o.push({item:i,weight:1/(Math.pow((i-s)/n,2)+1)});return i(o)}super();class n{constructor(t,e,i,s,n,o){this.chance=t,this.type=e,this.minFreq=i,this.maxFreq=s,this.centerHz=n,this.centerGain=o}}function o(t,i){t.reset();const n=[];for(const o of i){if(Math.random()>o.chance)continue;const i=new dt;i.type=o.type,i.freq=s(o.minFreq,o.maxFreq,dt.getRoundedSettingValueFromHz(o.centerHz),1/e.filterFreqStep),i.gain=s(0,e.filterGainRange-1,e.filterGainCenter+o.centerGain,2/e.filterGainStep),2==i.type&&i.gain==e.filterGainCenter||(n.includes(i.freq)||(n.push(i.freq),t.controlPoints[t.controlPointCount]=i,t.controlPointCount++))}}const r=t.song.getChannelIsNoise(t.channel),h=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];h.effects&=4,h.envelopeCount=0;const a=dt.getRoundedSettingValueFromHz(700),l=e.filterFreqRange-1;if(o(h.eqFilter,[new n(.8,0,a,l,4e3,-1),new n(.4,1,0,a-1,250,-1),new n(.5,2,0,l,2e3,0),new n(.4,2,0,l,1400,0),new n(.3,2,0,l,1e3,0),new n(.2,2,0,l,500,0)]),r){const t=i([{item:2,weight:1},{item:3,weight:3}]);function r(t){let i=0;for(const e of t)e>i&&(i=e);for(let s=0;s<t.length;s++)t[s]=e.harmonicsMax*t[s]/i}switch(h.preset=h.type=t,h.fadeIn=Math.random()<.8?0:s(0,e.fadeInRange-1,0,2),h.fadeOut=s(0,e.fadeOutTicks.length-1,e.fadeOutNeutral,2),Math.random()<.1&&(h.effects|=1024,h.transition=e.transitions.dictionary[i([{item:"normal",weight:30},{item:"interrupt",weight:1},{item:"slide",weight:2}])].index),Math.random()<.2&&(h.effects|=2048,h.chord=e.chords.dictionary[i([{item:"strum",weight:2},{item:"arpeggio",weight:1}])].index),Math.random()<.1&&(h.pitchShift=s(0,e.pitchShiftRange-1,e.pitchShiftCenter,2),h.pitchShift!=e.pitchShiftCenter&&(h.effects|=128,h.addEnvelope(e.instrumentAutomationTargets.dictionary.pitchShift.index,0,e.envelopes.dictionary[i([{item:"flare 1",weight:2},{item:"flare 2",weight:1},{item:"flare 3",weight:1},{item:"twang 1",weight:16},{item:"twang 2",weight:8},{item:"twang 3",weight:4},{item:"tremolo1",weight:1},{item:"tremolo2",weight:1},{item:"tremolo3",weight:1},{item:"decay 1",weight:4},{item:"decay 2",weight:2},{item:"decay 3",weight:1}])].index))),Math.random()<.1&&(h.effects|=512,h.vibrato=s(0,e.echoSustainRange-1,e.echoSustainRange>>1,2),h.vibrato=e.vibratos.dictionary[i([{item:"light",weight:2},{item:"delayed",weight:2},{item:"heavy",weight:1},{item:"shaky",weight:2}])].index),Math.random()<.8&&(h.effects|=32,o(h.noteFilter,[new n(1,0,a,l,8e3,-1)]),h.addEnvelope(e.instrumentAutomationTargets.dictionary.noteFilterAllFreqs.index,0,e.envelopes.dictionary[i([{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}])].index)),Math.random()<.1&&(h.effects|=8,h.distortion=s(1,e.distortionRange-1,e.distortionRange-1,2)),Math.random()<.1&&(h.effects|=16,h.bitcrusherFreq=s(0,e.bitcrusherFreqRange-1,e.bitcrusherFreqRange>>1,2),h.bitcrusherQuantization=s(0,e.bitcrusherQuantizationRange-1,e.bitcrusherQuantizationRange>>1,2)),Math.random()<.1&&(h.effects|=2,h.chorus=s(1,e.chorusRange-1,e.chorusRange-1,1)),Math.random()<.1&&(h.echoSustain=s(0,e.echoSustainRange-1,e.echoSustainRange>>1,2),h.echoDelay=s(0,e.echoDelayRange-1,e.echoDelayRange>>1,2),0==h.echoSustain&&0==h.echoDelay||(h.effects|=64)),Math.random()<.5&&(h.effects|=1,h.reverb=s(1,e.reverbRange-1,1,1)),t){case 2:h.chipNoise=Math.random()*e.chipNoises.length|0;break;case 3:{const t=[()=>{const t=[];for(let i=0;i<e.spectrumControlPoints;i++)t[i]=Math.random()<.5?Math.random():0;return t},()=>{let t=1;const i=[t];for(let s=1;s<e.spectrumControlPoints;s++)t*=Math.pow(2,Math.random()-.52),i[s]=t;return i},()=>{let t=1;const i=[t];for(let s=1;s<e.spectrumControlPoints;s++)t*=Math.pow(2,Math.random()-.52),i[s]=t*Math.random();return i}],i=(0,t[Math.random()*t.length|0])();r(i);for(let t=0;t<e.spectrumControlPoints;t++)h.spectrumWave.spectrum[t]=Math.round(i[t]);h.spectrumWave.markCustomWaveDirty()}break;default:throw new Error("Unhandled noise instrument type in random generator.")}}else{const t=i([{item:0,weight:4},{item:6,weight:4},{item:8,weight:5},{item:5,weight:5},{item:7,weight:5},{item:3,weight:1},{item:1,weight:5}]);function r(t){let i=0;for(const e of t)e>i&&(i=e);for(let s=0;s<t.length;s++)t[s]=e.harmonicsMax*t[s]/i}switch(h.preset=h.type=t,h.fadeIn=Math.random()<.5?0:s(0,e.fadeInRange-1,0,2),h.fadeOut=s(0,e.fadeOutTicks.length-1,e.fadeOutNeutral,2),0!=t&&5!=t&&7!=t||(h.unison=e.unisons.dictionary[i([{item:"none",weight:10},{item:"shimmer",weight:5},{item:"hum",weight:4},{item:"honky tonk",weight:3},{item:"dissonant",weight:1},{item:"fifth",weight:1},{item:"octave",weight:2},{item:"bowed",weight:2},{item:"piano",weight:5}])].index),Math.random()<.1&&(h.effects|=1024,h.transition=e.transitions.dictionary[i([{item:"interrupt",weight:1},{item:"slide",weight:2}])].index),Math.random()<.2&&(h.effects|=2048,h.chord=e.chords.dictionary[i([{item:"strum",weight:2},{item:"arpeggio",weight:1}])].index),Math.random()<.05&&(h.pitchShift=s(0,e.pitchShiftRange-1,e.pitchShiftCenter,1),h.pitchShift!=e.pitchShiftCenter&&(h.effects|=128,h.addEnvelope(e.instrumentAutomationTargets.dictionary.pitchShift.index,0,e.envelopes.dictionary[i([{item:"flare 1",weight:2},{item:"flare 2",weight:1},{item:"flare 3",weight:1},{item:"twang 1",weight:16},{item:"twang 2",weight:8},{item:"twang 3",weight:4},{item:"decay 1",weight:4},{item:"decay 2",weight:2},{item:"decay 3",weight:1}])].index))),Math.random()<.25&&(h.effects|=512,h.vibrato=s(0,e.echoSustainRange-1,e.echoSustainRange>>1,2),h.vibrato=e.vibratos.dictionary[i([{item:"light",weight:2},{item:"delayed",weight:2},{item:"heavy",weight:1},{item:"shaky",weight:2}])].index),Math.random()<.1&&(h.effects|=8,h.distortion=s(1,e.distortionRange-1,e.distortionRange-1,2)),m(h.effects)&&Math.random()<.8?(h.effects|=32,o(h.noteFilter,[new n(1,0,a,l,2e3,-1),new n(.9,1,0,a-1,500,-1),new n(.4,2,0,l,1400,0)])):Math.random()<.5&&(h.effects|=32,o(h.noteFilter,[new n(1,0,a,l,8e3,-1)]),h.addEnvelope(e.instrumentAutomationTargets.dictionary.noteFilterAllFreqs.index,0,e.envelopes.dictionary[i([{item:"punch",weight:6},{item:"flare 1",weight:2},{item:"flare 2",weight:4},{item:"flare 3",weight:2},{item:"twang 1",weight:2},{item:"twang 2",weight:4},{item:"twang 3",weight:4},{item:"swell 1",weight:4},{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:1},{item:"decay 2",weight:2},{item:"decay 3",weight:2}])].index)),Math.random()<.1&&(h.effects|=16,h.bitcrusherFreq=s(0,e.bitcrusherFreqRange-1,0,2),h.bitcrusherQuantization=s(0,e.bitcrusherQuantizationRange-1,e.bitcrusherQuantizationRange>>1,2)),Math.random()<.1&&(h.effects|=2,h.chorus=s(1,e.chorusRange-1,e.chorusRange-1,1)),Math.random()<.1&&(h.echoSustain=s(0,e.echoSustainRange-1,e.echoSustainRange>>1,2),h.echoDelay=s(0,e.echoDelayRange-1,e.echoDelayRange>>1,2),0==h.echoSustain&&0==h.echoDelay||(h.effects|=64)),Math.random()<.5&&(h.effects|=1,h.reverb=s(1,e.reverbRange-1,1,1)),t){case 0:h.chipWave=Math.random()*e.chipWaves.length|0;break;case 6:case 8:8==t&&(h.supersawDynamism=s(0,e.supersawDynamismMax,e.supersawDynamismMax,2),h.supersawSpread=s(0,e.supersawSpreadMax,Math.ceil(e.supersawSpreadMax/3),4),h.supersawShape=s(0,e.supersawShapeMax,0,4)),h.pulseWidth=s(0,e.pulseWidthRange-1,e.pulseWidthRange-1,2),Math.random()<.6&&h.addEnvelope(e.instrumentAutomationTargets.dictionary.pulseWidth.index,0,e.envelopes.dictionary[i([{item:"punch",weight:6},{item:"flare 1",weight:2},{item:"flare 2",weight:4},{item:"flare 3",weight:2},{item:"twang 1",weight:2},{item:"twang 2",weight:4},{item:"twang 3",weight:4},{item:"swell 1",weight:4},{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:1},{item:"decay 2",weight:2},{item:"decay 3",weight:2}])].index);break;case 7:case 5:{7==t&&(h.stringSustain=Math.random()*e.stringSustainRange|0);const i=[()=>{const t=[];for(let i=0;i<e.harmonicsControlPoints;i++)t[i]=Math.random()<.4?Math.random():0;return t[8*Math.random()|0]=Math.pow(Math.random(),.25),t},()=>{let t=1;const i=[t];for(let s=1;s<e.harmonicsControlPoints;s++)t*=Math.pow(2,Math.random()-.55),i[s]=t;return i},()=>{let t=1;const i=[t];for(let s=1;s<e.harmonicsControlPoints;s++)t*=Math.pow(2,Math.random()-.55),i[s]=t*Math.random();return i}],s=(0,i[Math.random()*i.length|0])();r(s);for(let t=0;t<e.harmonicsControlPoints;t++)h.harmonicsWave.harmonics[t]=Math.round(s[t]);h.harmonicsWave.markCustomWaveDirty()}break;case 3:{const t=[];for(let i=0;i<e.spectrumControlPoints;i++){const e=0==i||7==i||11==i||14==i||16==i||18==i||21==i;t[i]=e?Math.pow(Math.random(),.25):.5*Math.pow(Math.random(),3)}r(t);for(let i=0;i<e.spectrumControlPoints;i++)h.spectrumWave.spectrum[i]=Math.round(t[i]);h.spectrumWave.markCustomWaveDirty()}break;case 1:{h.algorithm=Math.random()*e.algorithms.length|0,h.feedbackType=Math.random()*e.feedbacks.length|0;const t=e.algorithms[h.algorithm];for(let i=0;i<t.carrierCount;i++)h.operators[i].frequency=s(0,e.operatorFrequencies.length-1,0,3),h.operators[i].amplitude=s(0,e.operatorAmplitudeMax,e.operatorAmplitudeMax-1,2);for(let n=t.carrierCount;n<e.operatorCount;n++)h.operators[n].frequency=s(3,e.operatorFrequencies.length-1,0,3),h.operators[n].amplitude=Math.pow(Math.random(),2)*e.operatorAmplitudeMax|0,h.envelopeCount<e.maxEnvelopeCount&&Math.random()<.4&&h.addEnvelope(e.instrumentAutomationTargets.dictionary.operatorAmplitude.index,n,e.envelopes.dictionary[i([{item:"punch",weight:2},{item:"flare 1",weight:2},{item:"flare 2",weight:2},{item:"flare 3",weight:2},{item:"twang 1",weight:2},{item:"twang 2",weight:2},{item:"twang 3",weight:2},{item:"swell 1",weight:2},{item:"swell 2",weight:2},{item:"swell 3",weight:2},{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 2",weight:1},{item:"decay 3",weight:1}])].index),h.envelopeCount<e.maxEnvelopeCount&&Math.random()<.05&&h.addEnvelope(e.instrumentAutomationTargets.dictionary.operatorFrequency.index,n,e.envelopes.dictionary[i([{item:"punch",weight:4},{item:"flare 1",weight:4},{item:"flare 2",weight:2},{item:"flare 3",weight:1},{item:"twang 1",weight:16},{item:"twang 2",weight:2},{item:"twang 3",weight:1},{item:"swell 1",weight:4},{item:"swell 2",weight:2},{item:"swell 3",weight:1},{item:"decay 1",weight:2},{item:"decay 2",weight:1},{item:"decay 3",weight:1}])].index);h.feedbackAmplitude=Math.pow(Math.random(),3)*e.operatorAmplitudeMax|0,h.envelopeCount<e.maxEnvelopeCount&&Math.random()<.4&&h.addEnvelope(e.instrumentAutomationTargets.dictionary.feedbackAmplitude.index,0,e.envelopes.dictionary[i([{item:"punch",weight:2},{item:"flare 1",weight:2},{item:"flare 2",weight:2},{item:"flare 3",weight:2},{item:"twang 1",weight:2},{item:"twang 2",weight:2},{item:"twang 3",weight:2},{item:"swell 1",weight:2},{item:"swell 2",weight:2},{item:"swell 3",weight:2},{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 2",weight:1},{item:"decay 3",weight:1}])].index)}break;default:throw new Error("Unhandled pitched instrument type in random generator.")}}t.notifier.changed(),this.J()}}class Vt extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.transition!=e&&(this.J(),i.transition=e,i.preset=i.type,t.notifier.changed())}}class jt extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()],s=i.effects,n=0!=(s&1<<e),o=n?s&~(1<<e):s|1<<e;i.effects=o,2!=e&&(i.preset=i.type),n&&i.clearInvalidEnvelopeTargets(),this.J(),t.notifier.changed()}}class Wt extends Ct{constructor(t,e,i,s,n,o){if(super(),e>t.song.patternsPerChannel)throw new Error("invalid pattern");for(let r=i;r<i+n;r++)for(let i=s;i<s+o;i++)t.song.channels[i].bars[r]!=e&&(t.song.channels[i].bars[r]=e,this.J());t.notifier.changed()}}class Kt extends Ct{constructor(t,e,i){if(super(),t.song.barCount!=e){for(const s of t.song.channels)if(i){for(;s.bars.length<e;)s.bars.unshift(0);t.song.barCount>e&&s.bars.splice(0,t.song.barCount-e)}else{for(;s.bars.length<e;)s.bars.push(0);s.bars.length=e}if(i){const i=e-t.song.barCount;t.bar=Math.max(0,t.bar+i),(i<0||t.barScrollPos>0)&&(t.barScrollPos=Math.max(0,t.barScrollPos+i)),t.song.loopStart=Math.max(0,t.song.loopStart+i)}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.J()}}}class Yt extends Ct{constructor(t,i,s){super();const n=Math.min(e.barCountMax,t.song.barCount+s);if(0!=(s=n-t.song.barCount)){for(const e of t.song.channels)for(;e.bars.length<n;)e.bars.splice(i,0,0);t.song.barCount=n,t.bar+=s,t.barScrollPos+=s,t.song.loopStart>=i?t.song.loopStart+=s:t.song.loopStart+t.song.loopLength>=i&&(t.song.loopLength+=s),t.notifier.changed(),this.J()}}}class Jt extends Ct{constructor(t,e,i){super();for(const s of t.song.channels)s.bars.splice(e,i),0==s.bars.length&&s.bars.push(0);t.song.barCount=Math.max(1,t.song.barCount-i),t.bar=Math.max(0,t.bar-i),t.barScrollPos=Math.max(0,t.barScrollPos-i),t.song.loopStart>=e?t.song.loopStart=Math.max(0,t.song.loopStart-i):t.song.loopStart+t.song.loopLength>e&&(t.song.loopLength-=i),t.song.loopLength=Math.max(1,Math.min(t.song.barCount-t.song.loopStart,t.song.loopLength)),t.notifier.changed(),this.J()}}class Qt extends Ct{constructor(t,e,i,s){super(),t.song.channels.splice(e+s,0,...t.song.channels.splice(e,i-e+1)),t.notifier.changed(),this.J()}}class Xt extends Ct{constructor(t,i,s){if(super(),t.song.pitchChannelCount!=i||t.song.noiseChannelCount!=s){const n=[];function o(i,s,o,r,h,a){for(let l=0;l<i;l++){const i=l+o,c=l+r;if(l<s)n[i]=t.song.channels[c];else{n[i]=new bt,n[i].octave=h;for(let t=0;t<e.instrumentCountMin;t++){const e=new gt(a),s=Je(a),o=x.valueToPreset(s);e.fromJsonObject(o.settings,a),e.preset=s,e.volume=1,n[i].instruments[t]=e}for(let e=0;e<t.song.patternsPerChannel;e++)n[i].patterns[e]=new at;for(let e=0;e<t.song.barCount;e++)n[i].bars[e]=0}}}o(i,t.song.pitchChannelCount,0,0,3,!1),o(s,t.song.noiseChannelCount,i,t.song.pitchChannelCount,0,!0),t.song.pitchChannelCount=i,t.song.noiseChannelCount=s;for(let e=0;e<t.song.getChannelCount();e++)t.song.channels[e]=n[e];t.song.channels.length=t.song.getChannelCount(),t.channel=Math.min(t.channel,i+s-1),t.notifier.changed(),this.J()}}}class Zt extends zt{constructor(t,i,s){super();const n=t.song.pitchChannelCount+(s?0:1),o=t.song.noiseChannelCount+(s?1:0);if(n<=e.pitchChannelCountMax&&o<=e.noiseChannelCountMax){const e=s?t.song.pitchChannelCount+t.song.noiseChannelCount:t.song.pitchChannelCount;this.append(new Xt(t,n,o)),this.append(new Qt(t,i,e-1,1))}}}class te extends zt{constructor(t,i,s){for(super();s>=i;){const e=t.song.getChannelIsNoise(s);t.song.channels.splice(s,1),e?t.song.noiseChannelCount--:t.song.pitchChannelCount--,s--}t.song.pitchChannelCount<e.pitchChannelCountMin&&this.append(new Xt(t,e.pitchChannelCountMin,t.song.noiseChannelCount)),this.append(new ee(t,Math.max(0,i-1),t.bar)),this.J(),t.notifier.changed()}}class ee extends Ct{constructor(t,e,i,s=!1){super();const n=t.channel,o=t.bar;t.channel=e,t.bar=i,s||t.selection.scrollToSelectedPattern(),t.notifier.changed(),n==e&&o==i||this.J()}}class ie extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.unison!=e&&(this.J(),i.unison=e,i.preset=i.type,t.notifier.changed())}}class se extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.chord!=e&&(this.J(),i.chord=e,i.preset=i.type,t.notifier.changed())}}class ne extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.vibrato!=e&&(i.vibrato=e,i.preset=i.type,t.notifier.changed(),this.J())}}class oe extends Ct{constructor(t,e,i){super(),i.markCustomWaveDirty(),e.preset=e.type,t.notifier.changed(),this.J()}}class re extends Ct{constructor(t,e,i){super(),i.markCustomWaveDirty(),e.preset=e.type,t.notifier.changed(),this.J()}}class he extends Ct{constructor(t,e,i){super();const s=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];s.drumsetEnvelopes[e]!=i&&(s.drumsetEnvelopes[e]=i,s.preset=s.type,t.notifier.changed(),this.J())}}class ae extends Ct{constructor(t){super(),this.j=t,this.wt=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()]}commit(){this.isNoop()||(this.wt.preset=this.wt.type,this.j.notifier.changed())}}class le extends ae{constructor(t,e,i){super(t),this.wt.pulseWidth=i,t.notifier.changed(),e!=i&&this.J()}}class ce extends ae{constructor(t,e,i){super(t),this.wt.supersawDynamism=i,t.notifier.changed(),e!=i&&this.J()}}class ue extends ae{constructor(t,e,i){super(t),this.wt.supersawSpread=i,t.notifier.changed(),e!=i&&this.J()}}class fe extends ae{constructor(t,e,i){super(t),this.wt.supersawShape=i,t.notifier.changed(),e!=i&&this.J()}}class pe extends ae{constructor(t,e,i){super(t),this.wt.pitchShift=i,t.notifier.changed(),e!=i&&this.J()}}class de extends ae{constructor(t,e,i){super(t),this.wt.detune=i,t.notifier.changed(),e!=i&&this.J()}}class me extends ae{constructor(t,e,i){super(t),this.wt.distortion=i,t.notifier.changed(),e!=i&&this.J()}}class ye extends ae{constructor(t,e,i){super(t),this.wt.bitcrusherFreq=i,t.notifier.changed(),e!=i&&this.J()}}class ge extends ae{constructor(t,e,i){super(t),this.wt.bitcrusherQuantization=i,t.notifier.changed(),e!=i&&this.J()}}class be extends ae{constructor(t,e,i){super(t),this.wt.stringSustain=i,t.notifier.changed(),e!=i&&this.J()}}class we extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.stringSustainType!=e&&(i.stringSustainType=e,i.preset=i.type,t.notifier.changed(),this.J())}}class ve extends Lt{constructor(t,i,s,n,o,r=!1){super(r),this.vt=[],this.kt=[],this.Mt=[],this.xt=[],this.j=t,this.wt=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],this.St=r?this.wt.preset:this.wt.type,this.Ft=r?this.wt.type:this.wt.preset,this.Pt=i,this.It=s,this.I=n;for(let t=0;t<this.wt.envelopeCount;t++){let s=this.wt.envelopes[t].target,h=this.wt.envelopes[t].index;if(this.vt.push(s),this.kt.push(h),r){const t=e.instrumentAutomationTargets[s];t.isFilter&&5==t.effect==o&&(t.maxCount==e.filterMaxPoints?h==n?(s=e.instrumentAutomationTargets.dictionary.none.index,h=0):h>n&&h--:i.controlPointCount<=1&&(s=e.instrumentAutomationTargets.dictionary.none.index,h=0))}this.Mt.push(s),this.xt.push(h)}this.J(),this.redo()}tt(){this.Pt.controlPoints.splice(this.I,0,this.It),this.Pt.controlPointCount++,this.Pt.controlPoints.length=this.Pt.controlPointCount,this.wt.preset=this.St;for(let t=0;t<this.wt.envelopeCount;t++)this.wt.envelopes[t].target=this.vt[t],this.wt.envelopes[t].index=this.kt[t];this.j.notifier.changed()}et(){this.Pt.controlPoints.splice(this.I,1),this.Pt.controlPointCount--,this.Pt.controlPoints.length=this.Pt.controlPointCount,this.wt.preset=this.Ft;for(let t=0;t<this.wt.envelopeCount;t++)this.wt.envelopes[t].target=this.Mt[t],this.wt.envelopes[t].index=this.xt[t];this.j.notifier.changed()}}class ke extends Lt{constructor(t,e,i,s,n,o){super(!1),this.j=t,this.wt=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],this.St=this.wt.type,this.Ft=this.wt.preset,this.It=e,this.Tt=i,this.qt=s,this.Et=n,this.Ct=o,this.J(),this.redo()}tt(){this.It.freq=this.qt,this.It.gain=this.Ct,this.wt.preset=this.St,this.j.notifier.changed()}et(){this.It.freq=this.Tt,this.It.gain=this.Et,this.wt.preset=this.Ft,this.j.notifier.changed()}}class Me extends Lt{constructor(t,e,i){super(!1),this.j=t,this.wt=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],this.St=this.wt.type,this.Ft=this.wt.preset,this.Lt=this.wt.fadeIn,this.zt=this.wt.fadeOut,this.Dt=e,this.At=i,this.J(),this.redo()}tt(){this.wt.fadeIn=this.Dt,this.wt.fadeOut=this.At,this.wt.preset=this.St,this.j.notifier.changed()}et(){this.wt.fadeIn=this.Lt,this.wt.fadeOut=this.zt,this.wt.preset=this.Ft,this.j.notifier.changed()}}class xe extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.algorithm!=e&&(i.algorithm=e,i.preset=i.type,t.notifier.changed(),this.J())}}class Se extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.feedbackType!=e&&(i.feedbackType=e,i.preset=i.type,t.notifier.changed(),this.J())}}class Fe extends Ct{constructor(t,e,i){super();const s=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];s.operators[e].frequency!=i&&(s.operators[e].frequency=i,s.preset=s.type,t.notifier.changed(),this.J())}}class Pe extends ae{constructor(t,e,i,s){super(t),this.wt.operators[e].amplitude=s,t.notifier.changed(),i!=s&&this.J()}}class Ie extends ae{constructor(t,e,i){super(t),this.wt.feedbackAmplitude=i,t.notifier.changed(),e!=i&&this.J()}}class Te extends Ct{constructor(t){super();const e=t.song.channels[t.channel],i=t.song.getChannelIsNoise(t.channel),s=t.song.getMaxInstrumentsPerChannel();if(e.instruments.length>=s)return;const n=Je(i),o=x.valueToPreset(n),r=new gt(i);r.fromJsonObject(o.settings,i,1),r.preset=n,r.volume=1,e.instruments.push(r),t.viewedInstrument[t.channel]=e.instruments.length-1,t.notifier.changed(),this.J()}}class qe extends Ct{constructor(t){super();const i=t.song.channels[t.channel];if(i.instruments.length<=e.instrumentCountMin)return;const s=t.viewedInstrument[t.channel];if(i.instruments.splice(s,1),t.song.patternInstruments)for(const t of i.patterns){for(let e=0;e<t.instruments.length;e++)t.instruments[e]==s?(t.instruments.splice(e,1),e--):t.instruments[e]>s&&t.instruments[e]--;t.instruments.length<=0&&(t.instruments[0]=0)}t.notifier.changed(),this.J()}}class Ee extends Ct{constructor(t,e){super(),t.viewedInstrument[t.channel]!=e&&(t.viewedInstrument[t.channel]=e,t.notifier.changed(),this.J())}}class Ce extends Ct{constructor(t,e,i){super();const s=t.song.layeredInstruments,n=t.song.patternInstruments;if(s!=e||n!=i){t.song.layeredInstruments=e,t.song.patternInstruments=i;for(let e=0;e<t.song.getChannelCount();e++){const s=t.song.channels[e];s.instruments.length>t.song.getMaxInstrumentsPerChannel()&&(s.instruments.length=t.song.getMaxInstrumentsPerChannel());for(let o=0;o<t.song.patternsPerChannel;o++){const r=s.patterns[o];if(!n&&i){for(let t=0;t<s.instruments.length;t++)r.instruments[t]=t;r.instruments.length=s.instruments.length}Bt(r.instruments,t.song,e)}}t.notifier.changed(),this.J()}}}class Le extends Ct{constructor(t,e){super(),t.song.key!=e&&(t.song.key=e,t.notifier.changed(),this.J())}}class ze extends Ct{constructor(t,e,i,s,n){super(),this.j=t,this.oldStart=e,this.oldLength=i,this.newStart=s,this.newLength=n,this.j.song.loopStart=this.newStart,this.j.song.loopLength=this.newLength,this.j.notifier.changed(),this.oldStart==this.newStart&&this.oldLength==this.newLength||this.J()}}class De extends Lt{constructor(t,e,i,s,n=!1){super(n),this.j=t,this.nt=e,this.Bt=i,this.I=s,this.J(),this.redo()}tt(){this.nt.pitches.splice(this.I,0,this.Bt),this.j.notifier.changed()}et(){this.nt.pitches.splice(this.I,1),this.j.notifier.changed()}}class Ae extends Ct{constructor(t,e,i){super(),this.oldValue=e,t.song.channels[t.channel].octave=i,t.notifier.changed(),e!=i&&this.J()}}class Be extends zt{constructor(t,e){super(),t.song.rhythm!=e&&(t.song.rhythm=e,t.notifier.changed(),this.J())}}class Oe extends zt{constructor(t,e,i,s,n,o){super(),this.append(new ci(t,e,s,n));let r=0;for(let t=0;t<e.notes.length;t++)if(e.notes[t].start<s){if(e.notes[t].end>s)throw new Error;r=t+1}else if(e.notes[t].start<n)throw new Error;for(;s<n;){for(const o of i){const i=o.start+s,h=o.end+s;if(i>=n)break;const a=new ht(o.pitches[0],i,h,o.pins[0].size,!1);a.pitches.length=0;for(const t of o.pitches)a.pitches.push(t);a.pins.length=0;for(const t of o.pins)a.pins.push(rt(t.interval,t.time,t.size));a.continuesLastPattern=!0===o.continuesLastPattern&&0==a.start,e.notes.splice(r++,0,a),a.end>n&&this.append(new li(t,a,a.start,n))}s+=o}t.notifier.changed(),this.J()}}class Ne extends zt{constructor(t,e,i){super(),e.fromJsonObject(i,i.isDrum),t.notifier.changed(),this.J()}}class Re extends Ct{constructor(t,e,i,s){super(),At(i,s.instruments)||(s.instruments.length=0,s.instruments.push(...i),Bt(s.instruments,t.song,e),this.J(),t.notifier.changed())}}class He extends Ct{constructor(t,e){if(super(),t.song.patternsPerChannel!=e){for(let i=0;i<t.song.getChannelCount();i++){const s=t.song.channels[i].bars,n=t.song.channels[i].patterns;for(let t=0;t<s.length;t++)s[t]>e&&(s[t]=0);for(let t=n.length;t<e;t++)n[t]=new at;n.length=e}t.song.patternsPerChannel=e,t.notifier.changed(),this.J()}}}class Ge extends Lt{constructor(t,e,i){super(!1),this.Ot=null,this.Nt=null;const s=t.song;if(0!=s.channels[e].bars[i])return;this.j=t,this.Rt=i,this.Ht=e,this.Gt=s.patternsPerChannel,this.$t=s.patternsPerChannel,this._t=t.recentPatternInstruments[e].concat();let n=null,o=null;for(let t=1;t<=s.patternsPerChannel;t++){let i=!1;for(let n=0;n<s.barCount;n++)if(s.channels[e].bars[n]==t){i=!0;break}if(i)continue;null==o&&(o=t);if(0==s.channels[e].patterns[t-1].notes.length){n=t;break}}if(null!=n)this.Ut=n,this.Nt=s.channels[e].patterns[n-1].instruments.concat();else if(s.patternsPerChannel<s.barCount)this.$t=s.patternsPerChannel+1,this.Ut=s.patternsPerChannel+1;else{if(null==o)throw new Error;this.Ut=o,this.Ot=s.channels[e].patterns[o-1].notes,this.Nt=s.channels[e].patterns[o-1].instruments.concat()}this.J(),this.tt()}tt(){const t=this.j.song;for(let e=t.patternsPerChannel;e<this.$t;e++)for(let i=0;i<t.getChannelCount();i++)t.channels[i].patterns[e]=new at;t.patternsPerChannel=this.$t;const e=t.channels[this.Ht].patterns[this.Ut-1];e.notes=[],e.instruments.length=0,e.instruments.push(...this._t),t.channels[this.Ht].bars[this.Rt]=this.Ut,this.j.notifier.changed()}et(){const t=this.j.song,e=t.channels[this.Ht].patterns[this.Ut-1];null!=this.Ot&&(e.notes=this.Ot),null!=this.Nt&&(e.instruments.length=0,e.instruments.push(...this.Nt)),t.channels[this.Ht].bars[this.Rt]=0;for(let e=0;e<t.getChannelCount();e++)t.channels[e].patterns.length=this.Gt;t.patternsPerChannel=this.Gt,this.j.notifier.changed()}}class $e extends Gt{constructor(t,e,i,s,n){super(t,e),s-=this.ot;const o=this.ct[i].time,r=Math.min(o,s),h=Math.max(o,s);let a=!1;for(let t=0;t<this.ct.length;t++){const o=e.pins[t],l=o.time;l<r?this.ut.push(rt(o.interval,l,o.size)):l>h&&(a||(this.ut.length>0&&(n=e.continuesLastPattern),this.ut.push(rt(this.ct[i].interval,s,this.ct[i].size)),a=!0),this.ut.push(rt(o.interval,l,o.size)))}a||(n=e.continuesLastPattern,this.ut.push(rt(this.ct[i].interval,s,this.ct[i].size))),this.bt(n)}}class _e extends Gt{constructor(t,i,s,n,o,r){super(t,i),s-=this.ot,n-=this.ot,o-=i.pitches[r];let h,a,l,c,u=!1,f=!1,p=0,d=e.noteSizeMax,m=!0;for(n>s?(h=0,a=1,l=i.pins.length,c=t=>{this.ut.push(t)}):(h=i.pins.length-1,a=-1,l=-1,c=t=>{this.ut.unshift(t)});h!=l;h+=a){const t=i.pins[h],e=t.time;for(;;)if(u){if(f){if(e*a==n*a)break;t.interval!=p&&(m=!1),c(rt(m?o:t.interval,e,t.size));break}if(e*a<=n*a&&(p=t.interval,d=t.size),e*a<n*a)break;c(rt(o,n,d)),f=!0}else{if(e*a<=s*a&&(p=t.interval,d=t.size),e*a<s*a){c(rt(t.interval,e,t.size));break}c(rt(p,s,d)),u=!0}}f||c(rt(o,n,d)),this.bt()}}class Ue extends Dt{constructor(t,i){super();const s=e.partsPerBeat/e.rhythms[t.song.rhythm].stepsPerBeat,n=function(i){let n=e.rhythms[t.song.rhythm].roundUpThresholds;if(null!=n){const t=Math.floor(i/e.partsPerBeat)*e.partsPerBeat,o=i-t;let r=t;for(const t of n){if(!(o>=t))break;r+=s}return r}return Math.round(i/s)*s};let o=0;for(;o<i.notes.length;){const e=i.notes[o];n(e.start)>=n(e.end)?this.append(new ai(t,i,e,o,!0)):(this.append(new Ve(t,e,n)),o++)}}}class Ve extends Gt{constructor(t,e,i){super(t,e);for(const t of this.ct)this.ut.push(rt(t.interval,i(t.time+this.ot)-this.ot,t.size));this.bt()}}class je extends zt{constructor(t,i,s){super();let n=Math.round(i%t.song.beatsPerBar*e.partsPerBeat);if(n<0&&(n+=t.song.beatsPerBar*e.partsPerBeat),0!=n){switch(s){case"wrapAround":{const i=e.partsPerBeat*t.song.beatsPerBar;for(const e of t.song.channels)for(const t of e.patterns){const e=[];for(let s=1;s>=0;s--){const o=s*i;for(const s of t.notes){const t=s.start+n,r=s.end+n,h=Math.max(0,t-o),a=Math.min(i,r-o);h<a&&Rt(s,t-o-h,h,a,e)}}t.notes=e}}break;case"overflow":{let e=t.song.barCount,s=t.song.loopStart,o=t.song.loopLength;if(this.append(new Ht(t,t.song.beatsPerBar,n)),i<0){let i=!0;for(const e of t.song.channels)0!=e.bars[0]&&(i=!1);if(i){for(const e of t.song.channels)e.bars.shift();t.song.barCount--}else e++,s++,t.bar++}for(;t.song.barCount<e;){for(const e of t.song.channels)e.bars.push(0);t.song.barCount++}t.song.loopStart=s,t.song.loopLength=o}break;default:throw new Error("Unrecognized beats-per-bar conversion strategy.")}t.notifier.changed(),this.J()}}}class We extends zt{constructor(t,i,s){if(super(),t.song.beatsPerBar!=i){switch(s){case"splice":if(t.song.beatsPerBar>i){const s=new Dt;for(let n=0;n<t.song.getChannelCount();n++)for(let o=0;o<t.song.channels[n].patterns.length;o++)s.append(new ci(t,t.song.channels[n].patterns[o],i*e.partsPerBeat,t.song.beatsPerBar*e.partsPerBeat))}break;case"stretch":{const e=function(e){return Math.round(e*i/t.song.beatsPerBar)};for(let i=0;i<t.song.getChannelCount();i++)for(let s=0;s<t.song.channels[i].patterns.length;s++){const n=t.song.channels[i].patterns[s];let o=0;for(;o<n.notes.length;){const i=n.notes[o];e(i.start)>=e(i.end)?this.append(new ai(t,n,i,o,!0)):(this.append(new Ve(t,i,e)),o++)}}this.append(new si(t,t.song.tempo,t.song.tempo*i/t.song.beatsPerBar))}break;case"overflow":this.append(new Ht(t,i,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=i,t.notifier.changed(),this.J()}}}class Ke extends zt{constructor(t,e){super(),t.song.scale!=e&&(t.song.scale=e,t.notifier.changed(),this.J())}}class Ye extends zt{constructor(t){super();const i=t.song,s=e.keys[i.key].basePitch,n=[0,0,0,0,0,0,0,0,0,0,0,0];for(let t=0;t<i.pitchChannelCount;t++)for(let o=0;o<i.barCount;o++){const r=i.getPattern(t,o);if(null!=r)for(const t of r.notes){const i=t.pins[0];for(let o=1;o<t.pins.length;o++){const r=t.pins[o];if(i.interval==r.interval){let o=r.time-i.time;o+=Math.max(0,Math.min(e.partsPerBeat,r.time+t.start)-(i.time+t.start)),o*=r.size+i.size;for(const e of t.pitches){n[(s+i.interval+e)%12]+=o}}}}}let o=0,r=0;for(let t=0;t<12;t++){const e=n[t]*(3*n[(t+7)%12]+n[(t+4)%12]+n[(t+3)%12]);r<e&&(r=e,o=t)}if(o!=i.key){const e=i.key-o,s=Math.abs(e);for(let n=0;n<i.pitchChannelCount;n++)for(const o of i.channels[n].patterns)for(let i=0;i<s;i++)this.append(new pi(t,n,o,e>0,!0));i.key=o,t.notifier.changed(),this.J()}}}function Je(t){const e=[];for(let i=0;i<x.presetCategories.length;i++){const s=x.presetCategories[i];if("Novelty Presets"!=s.name)for(let n=0;n<s.presets.length;n++){const o=s.presets[n];null!=o.settings&&1==o.isNoise==t&&e.push((i<<6)+n)}}return e[Math.random()*e.length|0]}function Qe(t){for(let e=0;e<t.channels.length;e++)for(const i of t.channels[e].instruments){const s=t.getChannelIsNoise(e),n=e==t.pitchChannelCount?x.nameToPresetValue(Math.random()>.5?"chip noise":"standard drumset"):Je(s),o=x.valueToPreset(n);i.fromJsonObject(o.settings,s,1),i.preset=n,i.volume=1}}class Xe extends zt{constructor(t,e){if(super(),t.song.fromBase64String(e),""==e){this.append(new mi(t,0,0)),t.selection.resetBoxSelection(),Qe(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 Ze(t));t.notifier.changed(),this.J()}}class Ze extends Ct{constructor(t){super();const e=Math.min(t.channel,t.song.getChannelCount()-1),i=Math.max(0,Math.min(t.song.barCount-1,t.bar));t.channel==e&&t.bar==i||(t.bar=i,t.channel=e,this.J()),t.selection.scrollToSelectedPattern(),t.notifier.changed()}}class ti extends zt{constructor(t,i,s){super();const n=t.song;function o(t,e){for(;t.length>e;){let e=t.length-1,i=0;for(let s=0;s<t.length-1;s++){let n=0;for(const e of t[s].bars)0==e&&n++;n>=i&&(e=s,i=n)}t.splice(e,1)}}for(o(i,e.pitchChannelCountMax),o(s,e.noiseChannelCountMax);i.length<e.pitchChannelCountMin;)i.push(new bt);for(;s.length<e.noiseChannelCountMin;)s.push(new bt);n.barCount=1,n.patternsPerChannel=8;const r=i.concat(s);for(let t=0;t<r.length;t++){const e=r[t];n.barCount=Math.max(n.barCount,e.bars.length),n.patternsPerChannel=Math.max(n.patternsPerChannel,e.patterns.length),n.channels[t]=e}n.channels.length=r.length,n.pitchChannelCount=i.length,n.noiseChannelCount=s.length,n.barCount=Math.min(e.barCountMax,n.barCount),n.patternsPerChannel=Math.min(e.barCountMax,n.patternsPerChannel);for(let t=0;t<n.channels.length;t++){const e=n.channels[t];for(let t=0;t<e.bars.length;t++)(e.bars[t]>n.patternsPerChannel||e.bars[t]<0)&&(e.bars[t]=0);for(;e.bars.length<n.barCount;)e.bars.push(0);e.bars.length=n.barCount,e.instruments.length>n.getMaxInstrumentsPerChannel()&&(e.instruments.length=n.getMaxInstrumentsPerChannel());for(const i of e.patterns)Bt(i.instruments,n,t);for(;e.patterns.length<n.patternsPerChannel;)e.patterns.push(new at);e.patterns.length=n.patternsPerChannel}n.loopStart=Math.max(0,Math.min(n.barCount-1,n.loopStart)),n.loopLength=Math.min(n.barCount-n.loopStart,n.loopLength),this.append(new Ze(t)),t.notifier.changed(),this.J()}}function ei(t,e){if(t.length!=e.length)return!1;for(let i=0;i<t.length;i++){const s=t[i],n=e[i];if(n.start!=s.start||n.end!=s.end||n.pitches.length!=s.pitches.length||n.pins.length!=s.pins.length)return!1;for(let t=0;t<s.pitches.length;t++)if(n.pitches[t]!=s.pitches[t])return!1;for(let t=0;t<s.pins.length;t++)if(n.pins[t].interval!=s.pins[t].interval||n.pins[t].time!=s.pins[t].time||n.pins[t].size!=s.pins[t].size)return!1}return!0}function ii(t){for(const e of t){const t=[];for(let i=0;i<e.bars.length;i++){if(0==e.bars[i])continue;const s=e.patterns[e.bars[i]-1];let n=!1;for(let o=0;o<t.length;o++){const r=t[o];if(At(s.instruments,r.instruments)&&r.notes.length==s.notes.length&&ei(s.notes,r.notes)){n=!0,e.bars[i]=o+1;break}}n||(t.push(s),e.bars[i]=t.length)}for(let i=0;i<t.length;i++)e.patterns[i]=t[i];e.patterns.length=t.length}}class si extends Ct{constructor(t,i,s){super(),t.song.tempo=Math.max(e.tempoMin,Math.min(e.tempoMax,Math.round(s))),t.notifier.changed(),i!=s&&this.J()}}class ni extends ae{constructor(t,e,i){super(t),this.wt.echoDelay=i,t.notifier.changed(),e!=i&&this.J()}}class oi extends ae{constructor(t,e,i){super(t),this.wt.echoSustain=i,t.notifier.changed(),e!=i&&this.J()}}class ri extends ae{constructor(t,e,i){super(t),this.wt.chorus=i,t.notifier.changed(),e!=i&&this.J()}}class hi extends ae{constructor(t,e,i){super(t),this.wt.reverb=i,t.notifier.changed(),e!=i&&this.J()}}class ai extends Lt{constructor(t,e,i,s,n=!1){super(n),this.j=t,this.Vt=e,this.nt=i,this.I=s,this.J(),this.redo()}tt(){this.Vt.notes.splice(this.I,0,this.nt),this.j.notifier.changed()}et(){this.Vt.notes.splice(this.I,1),this.j.notifier.changed()}}class li extends Gt{constructor(t,e,i,s){super(t,e);const n=(this.ot<0||e.continuesLastPattern)&&0==i;i-=this.ot,s-=this.ot;let o,r=!1,h=this.ct[0].size,a=this.ct[0].interval,l=!0;for(o=0;o<this.ct.length;o++){const t=this.ct[o];if(t.time<i)h=t.size,a=t.interval;else{if(t.time>i&&!r&&(this.ut.push(rt(a,i,h)),r=!0),!(t.time<=s))break;if(this.ut.push(rt(t.interval,t.time,t.size)),t.time==s){l=!1;break}}}l&&this.ut.push(rt(this.ct[o].interval,s,this.ct[o].size)),this.bt(n)}}class ci extends Dt{constructor(t,e,i,s,n){super();let o=0;for(;o<e.notes.length;){const r=e.notes[o];if(r==n&&null!=n)o++;else if(r.end<=i)o++;else{if(r.start>=s)break;if(r.start<i&&r.end>s){const n=r.clone();this.append(new li(t,r,r.start,i)),o++,this.append(new ai(t,e,n,o,!1)),this.append(new li(t,n,s,n.end)),o++}else r.start<i?(this.append(new li(t,r,r.start,i)),o++):r.end>s?(this.append(new li(t,r,s,r.end)),o++):this.append(new ai(t,e,r,o,!0))}}}}class ui extends Dt{constructor(t,e){super();let i=0;for(;i<e.notes.length;){const s=e.notes[i];if(s.start<t.selection.patternSelectionStart&&t.selection.patternSelectionStart<s.end){const n=s.clone();this.append(new li(t,s,s.start,t.selection.patternSelectionStart)),i++,this.append(new ai(t,e,n,i,!1)),this.append(new li(t,n,t.selection.patternSelectionStart,n.end))}else if(s.start<t.selection.patternSelectionEnd&&t.selection.patternSelectionEnd<s.end){const n=s.clone();this.append(new li(t,s,s.start,t.selection.patternSelectionEnd)),i++,this.append(new ai(t,e,n,i,!1)),this.append(new li(t,n,t.selection.patternSelectionEnd,n.end)),i++}else i++}}}class fi extends Lt{constructor(t,i,s,n,o=!1,r=!1){super(!1),this.j=t,this.nt=s,this.ct=s.pins,this.ut=[],this.ft=s.pitches,this.dt=[];const h=t.song.getChannelIsNoise(i);if(h!=t.song.getChannelIsNoise(t.channel))return;const a=h?e.drumCount-1:e.maxPitch;for(let i=0;i<this.ft.length;i++){let s=this.ft[i];if(r&&!h)s=n?Math.min(a,s+12):Math.max(0,s-12);else if(n){for(let i=s+1;i<=a;i++)if(h||o||e.scales[t.song.scale].flags[i%12]){s=i;break}}else for(let i=s-1;i>=0;i--)if(h||o||e.scales[t.song.scale].flags[i%12]){s=i;break}let l=!1;for(let t=0;t<this.dt.length;t++)if(this.dt[t]==s){l=!0;break}l||this.dt.push(s)}let l=0,c=a;for(let t=1;t<this.dt.length;t++){const e=this.dt[0]-this.dt[t];l<e&&(l=e),c>e+a&&(c=e+a)}for(const i of this.ct){let s=i.interval+this.ft[0];if(s<l&&(s=l),s>c&&(s=c),r&&!h)s=n?Math.min(c,s+12):Math.max(l,s-12);else if(n){for(let i=s+1;i<=c;i++)if(h||o||e.scales[t.song.scale].flags[i%12]){s=i;break}}else for(let i=s-1;i>=l;i--)if(h||o||e.scales[t.song.scale].flags[i%12]){s=i;break}s-=this.dt[0],this.ut.push(rt(s,i.time,i.size))}if(0!=this.ut[0].interval)throw new Error("wrong pin start interval");for(let t=1;t<this.ut.length-1;)this.ut[t-1].interval==this.ut[t].interval&&this.ut[t].interval==this.ut[t+1].interval&&this.ut[t-1].size==this.ut[t].size&&this.ut[t].size==this.ut[t+1].size?this.ut.splice(t,1):t++;this.tt(),this.J()}tt(){this.nt.pins=this.ut,this.nt.pitches=this.dt,this.j.notifier.changed()}et(){this.nt.pins=this.ct,this.nt.pitches=this.ft,this.j.notifier.changed()}}class pi extends Dt{constructor(t,e,i,s,n=!1,o=!1){super(),t.selection.patternSelectionActive&&this.append(new ui(t,i));for(const r of i.notes)t.selection.patternSelectionActive&&(r.end<=t.selection.patternSelectionStart||r.start>=t.selection.patternSelectionEnd)||this.append(new fi(t,e,r,s,n,o))}}class di extends Ct{constructor(t,e,i,s,n){super(),t.selection.boxSelectionX0=e,t.selection.boxSelectionX1=i,t.selection.boxSelectionY0=s,t.selection.boxSelectionY1=n,t.notifier.changed(),this.J()}}class mi extends Lt{constructor(t,e,i){super(!1),this.j=t,this.ot=t.selection.patternSelectionStart,this.rt=t.selection.patternSelectionEnd,this.jt=t.selection.patternSelectionActive,this.ht=e,this.lt=i,this.Wt=e<i,this.tt(),this.J()}tt(){this.j.selection.patternSelectionStart=this.ht,this.j.selection.patternSelectionEnd=this.lt,this.j.selection.patternSelectionActive=this.Wt,this.j.notifier.changed()}et(){this.j.selection.patternSelectionStart=this.ot,this.j.selection.patternSelectionEnd=this.rt,this.j.selection.patternSelectionActive=this.jt,this.j.notifier.changed()}}class yi extends Dt{constructor(t,i,s,n,o){if(super(),0==n&&0==o)return;t.selection.patternSelectionActive&&this.append(new ui(t,s));const r=t.selection.patternSelectionStart,h=t.selection.patternSelectionEnd,a=Math.max(0,Math.min(t.song.beatsPerBar*e.partsPerBeat,r+n)),l=Math.max(0,Math.min(t.song.beatsPerBar*e.partsPerBeat,h+n));a==l?this.append(new ci(t,s,r,h)):n<0?this.append(new ci(t,s,a,Math.min(r,l))):this.append(new ci(t,s,Math.max(h,a),l)),this.append(new mi(t,a,l));const c=[];let u=0,f=0;for(;f<s.notes.length;){const e=s.notes[f];e.end<=r||e.start>=h?(f++,e.end<=a&&(u=f)):(c.push(e.clone()),this.append(new ai(t,s,e,f,!0)))}for(const e of c)if(e.start+=n,e.end+=n,!(e.end<=a||e.start>=l)){this.append(new ai(t,s,e,u++,!1)),this.append(new li(t,e,Math.max(e.start,a),Math.min(l,e.end)));for(let s=0;s<Math.abs(o);s++)this.append(new fi(t,i,e,o>0,t.prefs.notesOutsideScale))}}}class gi extends zt{constructor(t,i,s,n,o){super();for(let r=n;r<n+o;r++){const n={};for(let o=i;o<i+s;o++){const h=t.song.channels[r].bars[o];if(0!=h){if(null==n[String(h)]){let a=!1;for(let e=0;e<t.song.barCount;e++)if((e<i||e>=i+s)&&t.song.channels[r].bars[e]==h){a=!0;break}if(a){const i=t.song.getPattern(r,o);this.append(new Wt(t,0,o,r,1,1)),this.append(new Ge(t,r,o));const s=t.song.getPattern(r,o);if(null==s)throw new Error;this.append(new Oe(t,s,i.notes,0,e.partsPerBeat*t.song.beatsPerBar,e.partsPerBeat*t.song.beatsPerBar)),s.instruments.length=0,s.instruments.push(...i.instruments),n[String(h)]=t.song.channels[r].bars[o]}else n[String(h)]=h}this.append(new Wt(t,n[String(h)],o,r,1,1))}}}}}class bi extends Ct{constructor(t,i,s){super(),t.selection.patternSelectionActive&&new ui(t,i);const n=e.maxPitch;for(const e of i.notes){if(t.selection.patternSelectionActive&&(e.end<=t.selection.patternSelectionStart||e.start>=t.selection.patternSelectionEnd))continue;const i=[],o=[];for(let t=0;t<e.pitches.length;t++){const n=e.pitches[t],o=s[n%12]+(n-n%12);-1==i.indexOf(o)&&i.push(o)}let r=0,h=n;for(let t=1;t<i.length;t++){const e=i[0]-i[t];r<e&&(r=e),h>e+n&&(h=e+n)}for(const t of e.pins){let n=t.interval+e.pitches[0];n<r&&(n=r),n>h&&(n=h);const a=s[n%12]+(n-n%12);o.push(rt(a-i[0],t.time,t.size))}if(0!=o[0].interval)throw new Error("wrong pin start interval");for(let t=1;t<o.length-1;)o[t-1].interval==o[t].interval&&o[t].interval==o[t+1].interval&&o[t-1].size==o[t].size&&o[t].size==o[t+1].size?o.splice(t,1):t++;e.pitches=i,e.pins=o}this.J(),t.notifier.changed()}}class wi extends Ct{constructor(t,e,i){super(),t.song.channels[t.channel].instruments[t.getCurrentInstrument()].volume=i,t.notifier.changed(),e!=i&&this.J()}}class vi extends Ct{constructor(t,e,i){super(),t.song.channels[t.channel].instruments[t.getCurrentInstrument()].pan=i,t.notifier.changed(),e!=i&&this.J()}}class ki extends Lt{constructor(t,e,i,s,n,o){super(!1),this.j=t,this.nt=e,this.ct=e.pins,this.ut=[];let r=!1;for(const t of e.pins)t.time<i?o?this.ut.push(rt(t.interval,t.time,s)):this.ut.push(t):t.time==i?(this.ut.push(rt(n,i,s)),r=!0):(o||r||(this.ut.push(rt(n,i,s)),r=!0),o?this.ut.push(rt(t.interval,t.time,s)):this.ut.push(t));Nt(this.ut),this.tt(),this.J()}tt(){this.nt.pins=this.ut,this.j.notifier.changed()}et(){this.nt.pins=this.ct,this.j.notifier.changed()}}class Mi extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.chipWave!=e&&(i.chipWave=e,i.preset=i.type,t.notifier.changed(),this.J())}}class xi extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.chipNoise!=e&&(i.chipNoise=e,i.preset=i.type,t.notifier.changed(),this.J())}}class Si extends Ct{constructor(t){super();const e=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];e.addEnvelope(0,0,0),e.preset=e.type,t.notifier.changed(),this.J()}}class Fi extends Ct{constructor(t,e){super();const i=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];i.envelopeCount--;for(let t=e;t<i.envelopeCount;t++)i.envelopes[t].target=i.envelopes[t+1].target,i.envelopes[t].index=i.envelopes[t+1].index,i.envelopes[t].envelope=i.envelopes[t+1].envelope;i.preset=i.type,t.notifier.changed(),this.J()}}class Pi extends Ct{constructor(t,e,i,s){super();const n=t.song.channels[t.channel].instruments[t.getCurrentInstrument()],o=n.envelopes[e].target,r=n.envelopes[e].index;o==i&&r==s||(n.envelopes[e].target=i,n.envelopes[e].index=s,n.preset=n.type,t.notifier.changed(),this.J())}}class Ii extends Ct{constructor(t,e,i){super();const s=t.song.channels[t.channel].instruments[t.getCurrentInstrument()];s.envelopes[e].envelope!=i&&(s.envelopes[e].envelope=i,s.preset=s.type,t.notifier.changed(),this.J())}}class Ti{constructor(){this.valid=!1,this.prevNote=null,this.curNote=null,this.nextNote=null,this.pitch=0,this.pitchIndex=-1,this.curIndex=0,this.start=0,this.end=0,this.part=0,this.exactPart=0,this.nearPinIndex=0,this.pins=[]}}class qi{constructor(t,i,s){this.j=t,this.Kt=i,this.Yt=s,this.Jt=A.pattern({id:"patternEditorNoteBackground"+this.Yt,x:"0",y:"0",patternUnits:"userSpaceOnUse"}),this.Qt=A.pattern({id:"patternEditorDrumBackground"+this.Yt,x:"0",y:"0",patternUnits:"userSpaceOnUse"}),this.Xt=A.rect({x:"0",y:"0","pointer-events":"none",fill:"url(#patternEditorNoteBackground"+this.Yt+")"}),this.Zt=A.svg(),this.te=A.rect({x:"0",y:"0",width:"4",fill:$.playhead,"pointer-events":"none"}),this.ee=A.rect({fill:$.boxSelectionFill,stroke:$.hoverPreview,"stroke-width":2,"stroke-dasharray":"5, 3","pointer-events":"none",visibility:"hidden"}),this.ie=A.path({fill:"none",stroke:$.hoverPreview,"stroke-width":"2","pointer-events":"none"}),this.se=A.svg({style:`background-color: ${$.editorBackground}; touch-action: none; position: absolute;`,width:"100%",height:"100%"},A.defs(this.Jt,this.Qt),this.Xt,this.ee,this.Zt,this.ie,this.te),this.container=D.div({style:"height: 100%; overflow:hidden; position: relative; flex-grow: 1;"},this.se),this.ne=[],this.oe=A.rect(),this.re=-1,this.he=0,this.ae=0,this.le=!1,this.ce=!1,this.ue=!1,this.fe=!1,this.pe=!1,this.de=[],this.me=0,this.ye=0,this.ge=!1,this.be=!1,this.we=0,this.ve=!1,this.ke=!1,this.Me=!1,this.xe=0,this.Se=0,this.Fe=0,this.Pe=!1,this.Ie=null,this.Te=null,this.qe=!1,this.Ee=new Ti,this.Vt=null,this.Ce=0,this.Le=0,this.ze=-1,this.De=-1,this.Ae=-1,this.Be=-1,this.Oe=!1,this.Ne=!1,this.Re=-1,this.He=-1,this.Ge=-1,this.$e=-1,this.resetCopiedPins=()=>{const t=this._e();this.de.length=this.j.song.getChannelCount();for(let i=0;i<this.j.song.pitchChannelCount;i++)this.de[i]=[rt(0,0,e.noteSizeMax),rt(0,t,e.noteSizeMax)];for(let i=this.j.song.pitchChannelCount;i<this.j.song.getChannelCount();i++)this.de[i]=[rt(0,0,e.noteSizeMax),rt(0,t,0)]},this.Ue=t=>{this.pe&&!this.be&&!this.ue&&this.le&&performance.now()>this.we+1e3&&this.Ee.valid&&this.j.lastChangeWas(this.Ie)&&(this.Ie.undo(),this.be=!0,this.Ve(),this.j.notifier.notifyWatchers());const e=Math.floor(this.j.synth.playhead);if(this.j.synth.playing&&(null!=this.Vt&&this.j.song.getPattern(this.j.channel,Math.floor(this.j.synth.playhead))==this.Vt||Math.floor(this.j.synth.playhead)==this.j.bar+this.Yt)){this.te.setAttribute("visibility","visible");const t=this.j.synth.playhead-e;Math.abs(t-this.Ce)>.1?this.Ce=t:this.Ce+=.2*(t-this.Ce),this.te.setAttribute("x",""+M(this.Ce*this.je-2))}else this.te.setAttribute("visibility","hidden");this.j.synth.playing&&(this.j.synth.recording||this.j.prefs.autoFollow)&&this.$e!=e&&(new ee(this.j,this.j.channel,e),this.j.notifier.notifyWatchers()),this.$e=e,this.j.currentPatternIsDirty&&this.We(),window.requestAnimationFrame(this.Ue)},this.Ke=t=>{this.ce||(this.ce=!0,this.pe=!1)},this.Ye=t=>{this.ce&&(this.ce=!1)},this.Je=t=>{t.preventDefault();const e=this.se.getBoundingClientRect();this.he=((t.clientX||t.pageX)-e.left)*this.je/(e.right-e.left),this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.pe=!1,this.ge=t.ctrlKey||t.metaKey,this.be=t.shiftKey,this.Ve()},this.Xe=t=>{t.preventDefault();const e=this.se.getBoundingClientRect();this.he=(t.touches[0].clientX-e.left)*this.je/(e.right-e.left),this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.pe=!0,this.ge=t.ctrlKey||t.metaKey,this.be=t.shiftKey,this.we=performance.now(),this.Ve()},this.Ze=t=>{const e=this.se.getBoundingClientRect();this.he=((t.clientX||t.pageX)-e.left)*this.je/(e.right-e.left),this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.pe=!1,this.ti()},this.ei=t=>{if(!this.le)return;t.preventDefault();const e=this.se.getBoundingClientRect();this.he=(t.touches[0].clientX-e.left)*this.je/(e.right-e.left),this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.ti()},this.ii=t=>{if(!this.Ee.valid)return;const i=this.j.lastChangeWas(this.Ie);if(this.le&&i&&null!=this.Ie)if(this.Me)this.j.record(this.Ie),this.Ie=null;else if(this.ve||this.ke||this.be)this.si(this.Ie),this.Ie=null;else if(this.ue||null==this.Ee.curNote||!this.Ie.isNoop()||this.ve||this.ke||this.Me||this.be)this.j.record(this.Ie),this.Ie=null;else{if(null==this.Vt)throw new Error;const t=new Dt;if(t.append(new mi(this.j,0,0)),-1==this.Ee.pitchIndex){if(this.Ee.curNote.pitches.length==e.maxChordSize&&t.append(new De(this.j,this.Ee.curNote,this.Ee.curNote.pitches[0],0,!0)),t.append(new De(this.j,this.Ee.curNote,this.Ee.pitch,this.Ee.curNote.pitches.length)),this.ni(this.Ee.curNote),this.j.prefs.enableNotePreview&&!this.j.synth.playing){const t=Math.min(e.partsPerBeat,this.Ee.end-this.Ee.start);this.j.performance.setTemporaryPitches(this.Ee.curNote.pitches,t)}}else 1==this.Ee.curNote.pitches.length?t.append(new ai(this.j,this.Vt,this.Ee.curNote,this.Ee.curIndex,!0)):t.append(new De(this.j,this.Ee.curNote,this.Ee.pitch,this.Ee.curNote.pitches.indexOf(this.Ee.pitch),!0));this.j.record(t)}this.le=!1,this.ue=!1,this.ve=!1,this.ke=!1,this.Me=!1,this.qe=!1,this.oi(),this.ri()};for(let t=0;t<e.pitchesPerOctave;t++){const e=A.rect();e.setAttribute("x","1"),e.setAttribute("fill",0==t?$.tonic:$.pitchBackground),this.Jt.appendChild(e),this.ne[t]=e}this.oe.setAttribute("x","1"),this.oe.setAttribute("y","1"),this.oe.setAttribute("fill",$.pitchBackground),this.Qt.appendChild(this.oe),this.Kt?(this.oi(),this.ri(),window.requestAnimationFrame(this.Ue),this.se.addEventListener("mousedown",this.Je),document.addEventListener("mousemove",this.Ze),document.addEventListener("mouseup",this.ii),this.se.addEventListener("mouseover",this.Ke),this.se.addEventListener("mouseout",this.Ye),this.se.addEventListener("touchstart",this.Xe),this.se.addEventListener("touchmove",this.ei),this.se.addEventListener("touchend",this.ii),this.se.addEventListener("touchcancel",this.ii)):(this.te.style.display="none",this.se.appendChild(A.rect({x:0,y:0,width:1e4,height:1e4,fill:$.editorBackground,style:"opacity: 0.5;"}))),this.resetCopiedPins()}hi(){return this.j.song.getChannelIsNoise(this.j.channel)?e.drumCount-1:e.maxPitch}_e(){const t=e.rhythms[this.j.song.rhythm].stepsPerBeat;return t%4==0?e.partsPerBeat/2:t%3==0?e.partsPerBeat/3:t%2==0?e.partsPerBeat/2:e.partsPerBeat}ai(){return e.partsPerBeat/e.rhythms[this.j.song.rhythm].stepsPerBeat}li(t){const e=this.ai();return Math.floor(t/e)*e}oi(){if(this.Ee=new Ti,this.he<0||this.he>this.je||this.ae<0||this.ae>this.Qe||this.re<=0)return;const t=this.ai();if(this.Ee.exactPart=this.he/this.ci,this.Ee.part=Math.floor(Math.max(0,Math.min(this.j.song.beatsPerBar*e.partsPerBeat-t,this.Ee.exactPart))/t)*t,null!=this.Vt)for(const t of this.Vt.notes)if(t.end<=this.Ee.exactPart)this.Ee.prevNote=t,this.Ee.curIndex++;else if(t.start<=this.Ee.exactPart&&t.end>this.Ee.exactPart)this.Ee.curNote=t;else if(t.start>this.Ee.exactPart){this.Ee.nextNote=t;break}let i=this.ui(this.ae);if(null!=this.Ee.curNote){this.Ee.start=this.Ee.curNote.start,this.Ee.end=this.Ee.curNote.end,this.Ee.pins=this.Ee.curNote.pins;let t,e=0,s=0,n=this.Ee.curNote.pins[0];for(let i=1;i<this.Ee.curNote.pins.length;i++){t=n,n=this.Ee.curNote.pins[i];const o=this.ci*(this.Ee.curNote.start+t.time),r=this.ci*(this.Ee.curNote.start+n.time);if(this.he>r)continue;if(this.he<o)throw new Error;const h=(this.he-o)/(r-o),a=Math.sqrt(1/Math.sqrt(4)-Math.pow(h-.5,2))-.5,l=Math.abs(n.interval-t.interval);e=t.interval*(1-h)+n.interval*h,s=a*l+.95;break}let o=Number.MAX_VALUE,r=-Number.MAX_VALUE,h=Number.MAX_VALUE;for(const t of this.Ee.curNote.pins){o>t.interval&&(o=t.interval),r<t.interval&&(r=t.interval);const e=Math.abs(this.Ee.curNote.start+t.time-this.he/this.ci);h>e&&(h=e,this.Ee.nearPinIndex=this.Ee.curNote.pins.indexOf(t))}if(i-=e,this.Ee.pitch=this.fi(i,-o,this.hi()-r),!this.j.song.getChannelIsNoise(this.j.channel)){let t=s;for(let e=0;e<this.Ee.curNote.pitches.length;e++){const s=Math.abs(this.Ee.curNote.pitches[e]-i+.5);s>t||(t=s,this.Ee.pitch=this.Ee.curNote.pitches[e])}}for(let t=0;t<this.Ee.curNote.pitches.length;t++)if(this.Ee.curNote.pitches[t]==this.Ee.pitch){this.Ee.pitchIndex=t;break}}else{this.Ee.pitch=this.fi(i,0,this.hi());const t=this.pi[this.pi.length-1].time,s=Math.floor(this.Ee.part/e.partsPerBeat),n=this._e(),o=this.Ee.part%e.partsPerBeat;if(1==t)this.Ee.start=this.Ee.part;else if(t>e.partsPerBeat)this.Ee.start=s*e.partsPerBeat;else if(t==e.partsPerBeat)this.Ee.start=s*e.partsPerBeat,n<e.partsPerBeat&&o>n&&(this.Ee.start+=Math.floor(o/n)*n);else{this.Ee.start=s*e.partsPerBeat;let i=e.partsPerBeat%t==0?t:Math.min(t,n);for(;i<n&&e.partsPerBeat%i!=0;)i++;this.Ee.start+=Math.floor(o/i)*i}this.Ee.end=this.Ee.start+t;let r=0,h=this.j.song.beatsPerBar*e.partsPerBeat;if(null!=this.Ee.prevNote&&(r=this.Ee.prevNote.end),null!=this.Ee.nextNote&&(h=this.Ee.nextNote.start),this.Ee.start<r?(this.Ee.start=r,this.Ee.end=this.Ee.start+t,this.Ee.end>h&&(this.Ee.end=h)):this.Ee.end>h&&(this.Ee.end=h,this.Ee.start=this.Ee.end-t,this.Ee.start<r&&(this.Ee.start=r)),this.Ee.end-this.Ee.start==t)this.Ee.pins=this.pi;else{this.Ee.pins=[];for(const t of this.pi){if(!(t.time<=this.Ee.end-this.Ee.start)){this.Ee.pins.push(rt(0,this.Ee.end-this.Ee.start,t.size));break}if(this.Ee.pins.push(rt(0,t.time,t.size)),t.time==this.Ee.end-this.Ee.start)break}}}this.Ee.valid=!0}di(){return this.Ee.valid&&this.j.selection.patternSelectionActive&&this.j.selection.patternSelectionStart<=this.Ee.exactPart&&this.Ee.exactPart<=this.j.selection.patternSelectionEnd}mi(){return this.Ee.valid&&this.j.selection.patternSelectionActive&&-1==this.Ee.pitchIndex&&this.j.selection.patternSelectionStart-3<=this.Ee.exactPart&&this.Ee.exactPart<=this.j.selection.patternSelectionStart+1.25}yi(){return this.Ee.valid&&this.j.selection.patternSelectionActive&&-1==this.Ee.pitchIndex&&this.j.selection.patternSelectionEnd-1.25<=this.Ee.exactPart&&this.Ee.exactPart<=this.j.selection.patternSelectionEnd+3}ui(t){return Math.max(0,Math.min(this.gi-1,this.gi-t/this.re))+this.Le}fi(t,i,s){t<i&&(t=i),t>s&&(t=s);const n=this.j.prefs.notesOutsideScale?e.scales.dictionary.expert.flags:e.scales[this.j.song.scale].flags;if(n[Math.floor(t)%e.pitchesPerOctave]||this.j.song.getChannelIsNoise(this.j.channel))return Math.floor(t);{let o=Math.floor(t)+1,r=Math.floor(t)-1;for(;!n[o%e.pitchesPerOctave];)o++;for(;!n[r%e.pitchesPerOctave];)r--;if(o>s)return r<i?i:r;if(r<i)return o;let h=o,a=r+1;return o%e.pitchesPerOctave!=0&&o%e.pitchesPerOctave!=7||(h-=.5),r%e.pitchesPerOctave!=0&&r%e.pitchesPerOctave!=7||(a+=.5),t-a>h-t?o:r}}ni(t){this.pi=[];for(const e of t.pins)this.pi.push(rt(0,e.time,e.size));for(let t=1;t<this.pi.length-1;)this.pi[t-1].size==this.pi[t].size&&this.pi[t].size==this.pi[t+1].size?this.pi.splice(t,1):t++;this.de[this.j.channel]=this.pi}movePlayheadToMouse(){return!!this.ce&&(this.j.synth.playhead=this.j.bar+this.Yt+this.he/this.je,!0)}Ve(){this.j.prefs.enableNotePreview&&this.j.synth.maintainLiveInput(),this.le=!0,this.me=this.he,this.ye=this.ae,this.oi(),this.ri();const t=new Dt;if(this.Ie=t,this.qe=this.j.lastChangeWas(this.Te),this.j.setProspectiveChange(this.Ie),this.mi())this.ve=!0;else if(this.yi())this.ke=!0;else if(this.be)if(this.j.selection.patternSelectionActive&&-1==this.Ee.pitchIndex||this.di())t.append(new mi(this.j,0,0));else if(null!=this.Ee.curNote)t.append(new mi(this.j,this.Ee.curNote.start,this.Ee.curNote.end));else{const i=Math.max(0,Math.min((this.j.song.beatsPerBar-1)*e.partsPerBeat,Math.floor(this.Ee.exactPart/e.partsPerBeat)*e.partsPerBeat)),s=i+e.partsPerBeat;t.append(new mi(this.j,i,s))}else if(this.di())this.Me=!0;else if(this.Ee.valid&&null==this.Ee.curNote){t.append(new mi(this.j,0,0));const i=new ht(this.Ee.pitch,this.Ee.start,this.Ee.end,e.noteSizeMax,this.j.song.getChannelIsNoise(this.j.channel));i.pins=[];for(const t of this.Ee.pins)i.pins.push(rt(0,t.time,t.size));t.append(new Ge(this.j,this.j.channel,this.j.bar));const s=this.j.getCurrentPattern(this.Yt);if(null==s)throw new Error;if(t.append(new ai(this.j,s,i,this.Ee.curIndex)),this.j.prefs.enableNotePreview&&!this.j.synth.playing){const t=Math.min(e.partsPerBeat,this.Ee.end-this.Ee.start);this.j.performance.setTemporaryPitches([this.Ee.pitch],t)}}this.bi()}ti(){this.j.prefs.enableNotePreview&&this.ce&&this.j.synth.maintainLiveInput();const t=this.j.lastChangeWas(this.Ie);if(!this.ue&&this.le&&this.Ee.valid&&t){const t=this.he-this.me,e=this.ae-this.ye;Math.sqrt(t*t+e*e)>5&&(this.ue=!0,this.fe=Math.abs(t)>=Math.abs(e))}if(this.ue&&this.le&&this.Ee.valid&&t){this.Ie.undo();const t=new Dt;this.Ie=t,this.j.setProspectiveChange(this.Ie);const i=this.ai(),s=this.li(this.he/this.ci);if(this.ve)t.append(new mi(this.j,Math.max(0,Math.min(this.j.song.beatsPerBar*e.partsPerBeat,s)),this.j.selection.patternSelectionEnd)),this.bi();else if(this.ke)t.append(new mi(this.j,this.j.selection.patternSelectionStart,Math.max(0,Math.min(this.j.song.beatsPerBar*e.partsPerBeat,s)))),this.bi();else if(this.Me){const t=this.j.getCurrentPattern(this.Yt);if(this.ue&&null!=t){this.Ie.undo();const s=new Dt;this.Ie=s,this.j.setProspectiveChange(this.Ie);const n=e.scales[this.j.song.scale].flags.filter((t=>t)).length,o=this.j.song.getChannelIsNoise(this.j.channel)?1:12/n,r=Math.round((this.he-this.me)/(this.ci*i))*i,h=Math.round((this.ye-this.ae)/(this.re*o));s.append(new yi(this.j,this.j.channel,t,r,h))}}else if(this.be){if(this.ue){let i=Math.max(0,Math.min((this.j.song.beatsPerBar-1)*e.partsPerBeat,Math.floor(this.Ee.exactPart/e.partsPerBeat)*e.partsPerBeat)),n=i+e.partsPerBeat;if(null!=this.Ee.curNote&&(i=Math.max(i,this.Ee.curNote.start),n=Math.min(n,this.Ee.curNote.end)),s<i){i=0;const t=this.j.getCurrentPattern(this.Yt);if(null!=t)for(let e=0;e<t.notes.length;e++)t.notes[e].start<=s&&(i=t.notes[e].start),t.notes[e].end<=s&&(i=t.notes[e].end);for(let t=0;t<=this.j.song.beatsPerBar;t++){const n=t*e.partsPerBeat;i<=n&&n<=s&&(i=n)}}if(s>n){n=e.partsPerBeat*this.j.song.beatsPerBar;const t=this.j.getCurrentPattern(this.Yt);if(null!=t)for(let e=0;e<t.notes.length;e++){if(t.notes[e].start>=s){n=t.notes[e].start;break}if(t.notes[e].end>=s){n=t.notes[e].end;break}}for(let t=0;t<=this.j.song.beatsPerBar;t++){const i=t*e.partsPerBeat;s<i&&i<n&&(n=i)}}t.append(new mi(this.j,i,n)),this.bi()}}else if(null==this.Ee.curNote){let n,o;t.append(new mi(this.j,0,0)),s<this.Ee.start?(n=!0,o=this.Ee.start-s):(n=!1,o=s-this.Ee.start+i);let r,h,a=i;for(let t=i;t<=this.j.song.beatsPerBar*e.partsPerBeat;t+=i){if(1==i){if(t<5);else if(t<=e.partsPerBeat/2){if(t%3!=0&&t%4!=0)continue}else if(t<=1.5*e.partsPerBeat){if(t%6!=0&&t%8!=0)continue}else if(t%e.partsPerBeat!=0)continue}else if(t>=5*i&&t%e.partsPerBeat!=0&&t!=3*e.partsPerBeat/4&&t!=3*e.partsPerBeat/2&&t!=4*e.partsPerBeat/3)continue;const s=t;if(s==o){a=s;break}if(s<o&&(a=s),s>o){a<o-i&&(a=s);break}}n?(h=this.Ee.start,r=h-a):(r=this.Ee.start,h=r+a);const l=r<0;if(r<0&&(r=0),h>this.j.song.beatsPerBar*e.partsPerBeat&&(h=this.j.song.beatsPerBar*e.partsPerBeat),r<h){t.append(new Ge(this.j,this.j.channel,this.j.bar));const i=this.j.getCurrentPattern(this.Yt);if(null==i)throw new Error;let s;for(t.append(new ci(this.j,i,r,h)),s=0;s<i.notes.length&&!(i.notes[s].start>=h);s++);const o=new ht(this.Ee.pitch,r,h,e.noteSizeMax,this.j.song.getChannelIsNoise(this.j.channel));o.continuesLastPattern=l,t.append(new ai(this.j,i,o,s)),this.ni(o),this.xe=n?r:h,this.Se=this.Ee.pitch,this.Fe=o.pins[n?0:1].size,this.Pe=!0}this.Vt=this.j.getCurrentPattern(this.Yt)}else if(this.fe){t.append(new mi(this.j,0,0));const s=(this.he-this.me)/this.ci,n=this.Ee.curNote.pins[this.Ee.nearPinIndex];let o=Math.round((this.Ee.curNote.start+n.time+s)/i)*i;const r=o<0;if(o<0&&(o=0),o>this.j.song.beatsPerBar*e.partsPerBeat&&(o=this.j.song.beatsPerBar*e.partsPerBeat),null==this.Vt)throw new Error;if(o<=this.Ee.curNote.start&&this.Ee.nearPinIndex==this.Ee.curNote.pins.length-1||o>=this.Ee.curNote.end&&0==this.Ee.nearPinIndex)t.append(new ai(this.j,this.Vt,this.Ee.curNote,this.Ee.curIndex,!0)),this.Pe=!1;else{const e=Math.min(this.Ee.curNote.start,o),i=Math.max(this.Ee.curNote.end,o);this.xe=o,this.Se=this.Ee.curNote.pitches[-1==this.Ee.pitchIndex?0:this.Ee.pitchIndex]+this.Ee.curNote.pins[this.Ee.nearPinIndex].interval,this.Fe=this.Ee.curNote.pins[this.Ee.nearPinIndex].size,this.Pe=!0,t.append(new ci(this.j,this.Vt,e,i,this.Ee.curNote)),t.append(new $e(this.j,this.Ee.curNote,this.Ee.nearPinIndex,o,r)),this.ni(this.Ee.curNote)}}else if(-1==this.Ee.pitchIndex){t.append(new mi(this.j,0,0));const s=Math.max(this.Ee.curNote.start,Math.min(this.Ee.curNote.end,Math.round(this.he/(this.ci*i))*i))-this.Ee.curNote.start;let n,o=this.Ee.curNote.pins[0],r=0,h=0;for(let t=1;t<this.Ee.curNote.pins.length;t++){if(n=o,o=this.Ee.curNote.pins[t],s>o.time)continue;if(s<n.time)throw new Error;const i=(s-n.time)/(o.time-n.time);r=Math.round(n.size*(1-i)+o.size*i+(this.ye-this.ae)/(75/e.noteSizeMax)),r<0&&(r=0),r>e.noteSizeMax&&(r=e.noteSizeMax),h=this.fi(Math.round(n.interval*(1-i)+o.interval*i+this.Ee.curNote.pitches[0]),0,this.hi())-this.Ee.curNote.pitches[0];break}this.xe=this.Ee.curNote.start+s,this.Se=this.Ee.curNote.pitches[-1==this.Ee.pitchIndex?0:this.Ee.pitchIndex]+h,this.Fe=r,this.Pe=!0,t.append(new ki(this.j,this.Ee.curNote,s,r,h,this.ge)),this.ni(this.Ee.curNote)}else{if(t.append(new mi(this.j,0,0)),this.Fe=this.Ee.curNote.pins[this.Ee.nearPinIndex].size,null==this.Vt)throw new Error;let n,o;this.he>=this.me?(n=Math.max(this.Ee.curNote.start,this.Ee.part),o=s+i):(n=Math.min(this.Ee.curNote.end,this.Ee.part+i),o=s),o<0&&(o=0),o>this.j.song.beatsPerBar*e.partsPerBeat&&(o=this.j.song.beatsPerBar*e.partsPerBeat),o>this.Ee.curNote.end&&t.append(new ci(this.j,this.Vt,this.Ee.curNote.start,o,this.Ee.curNote)),o<this.Ee.curNote.start&&t.append(new ci(this.j,this.Vt,o,this.Ee.curNote.end,this.Ee.curNote));let r=Number.MAX_VALUE,h=-Number.MAX_VALUE;for(const t of this.Ee.curNote.pitches)r>t&&(r=t),h<t&&(h=t);r-=this.Ee.curNote.pitches[this.Ee.pitchIndex],h-=this.Ee.curNote.pitches[this.Ee.pitchIndex];const a=this.fi(this.ui(this.ae),-r,this.hi()-h);t.append(new _e(this.j,this.Ee.curNote,n,o,a,this.Ee.pitchIndex)),this.ni(this.Ee.curNote),this.xe=o,this.Se=a,this.Pe=!0}}this.le&&this.Ee.valid&&t||(this.oi(),this.ri())}si(t){this.Te=t,this.j.hasRedoHistory()||this.j.record(this.Te,this.qe)}ri(){if(this.pe)if(!this.le||!this.Ee.valid||!this.ue||!this.Pe||this.be||this.ve||this.ke||this.Me)this.ie.setAttribute("visibility","hidden");else{this.ie.setAttribute("visibility","visible");const t=this.ci*this.xe,i=this.wi(this.Se-this.Le),s=this.re/2,n=80,o=60;let r="";const h=e.noteSizeMax;r+="M "+M(t)+" "+M(i-s*(this.Fe/h))+" ",r+="L "+M(t)+" "+M(i-s*(this.Fe/h)-o)+" ",r+="M "+M(t)+" "+M(i+s*(this.Fe/h))+" ",r+="L "+M(t)+" "+M(i+s*(this.Fe/h)+o)+" ",r+="M "+M(t)+" "+M(i-s*(this.Fe/h))+" ",r+="L "+M(t+n)+" "+M(i-s*(this.Fe/h))+" ",r+="M "+M(t)+" "+M(i+s*(this.Fe/h))+" ",r+="L "+M(t+n)+" "+M(i+s*(this.Fe/h))+" ",r+="M "+M(t)+" "+M(i-s*(this.Fe/h))+" ",r+="L "+M(t-n)+" "+M(i-s*(this.Fe/h))+" ",r+="M "+M(t)+" "+M(i+s*(this.Fe/h))+" ",r+="L "+M(t-n)+" "+M(i+s*(this.Fe/h))+" ",this.ie.setAttribute("d",r)}else if(this.ce&&!this.le&&this.Ee.valid)if(this.ie.setAttribute("visibility","visible"),this.mi()){const t=this.ci*this.j.selection.patternSelectionStart,e=M(t-4),i=M(t+4),s=this.wi(-.5);this.ie.setAttribute("d","M "+e+" 0 L "+e+" "+s+" L "+i+" "+s+" L "+i+" 0 z")}else if(this.yi()){const t=this.ci*this.j.selection.patternSelectionEnd,e=M(t-4),i=M(t+4),s=this.wi(-.5);this.ie.setAttribute("d","M "+e+" 0 L "+e+" "+s+" L "+i+" "+s+" L "+i+" 0 z")}else if(this.di()){const t=M(this.ci*this.j.selection.patternSelectionStart-2),e=M(this.ci*this.j.selection.patternSelectionEnd+2),i=this.wi(-.5);this.ie.setAttribute("d","M "+t+" 0 L "+t+" "+i+" L "+e+" "+i+" L "+e+" 0 z")}else this.vi(this.ie,this.Ee.pitch,this.Ee.start,this.Ee.pins,this.re/2+1,!0,this.Le);else this.ie.setAttribute("visibility","hidden")}bi(){this.j.selection.patternSelectionActive?(this.ee.setAttribute("visibility","visible"),this.ee.setAttribute("x",String(this.ci*this.j.selection.patternSelectionStart)),this.ee.setAttribute("width",String(this.ci*(this.j.selection.patternSelectionEnd-this.j.selection.patternSelectionStart)))):this.ee.setAttribute("visibility","hidden")}render(){const t=this.j.getCurrentPattern(this.Yt);this.Vt!=t&&null!=this.Vt&&(this.Ie=null,this.ii(null)),this.Vt=t,this.je=this.container.clientWidth,this.Qe=this.container.clientHeight,this.ci=this.je/(this.j.song.beatsPerBar*e.partsPerBeat),this.gi=this.j.song.getChannelIsNoise(this.j.channel)?e.drumCount:this.j.getVisiblePitchCount(),this.re=this.Qe/this.gi,this.Le=this.j.getBaseVisibleOctave(this.j.channel)*e.pitchesPerOctave,this.Re==this.j.song.rhythm&&this.He==this.j.song.pitchChannelCount&&this.Ge==this.j.song.noiseChannelCount||(this.Re=this.j.song.rhythm,this.He=this.j.song.pitchChannelCount,this.Ge=this.j.song.noiseChannelCount,this.resetCopiedPins()),this.pi=this.de[this.j.channel],this.ze==this.je&&this.De==this.Qe||(this.ze=this.je,this.De=this.Qe,this.Xt.setAttribute("width",""+this.je),this.Xt.setAttribute("height",""+this.Qe),this.te.setAttribute("height",""+this.Qe),this.ee.setAttribute("y","0"),this.ee.setAttribute("height",""+this.Qe));const i=this.je/this.j.song.beatsPerBar;if(this.Ae!=i||this.Be!=this.re){this.Ae=i,this.Be=this.re,this.Jt.setAttribute("width",""+i),this.Jt.setAttribute("height",""+this.re*e.pitchesPerOctave),this.Qt.setAttribute("width",""+i),this.Qt.setAttribute("height",""+this.re),this.oe.setAttribute("width",""+(i-2)),this.oe.setAttribute("height",""+(this.re-2));for(let t=0;t<e.pitchesPerOctave;t++){const s=this.ne[t],n=(e.pitchesPerOctave-t)%e.pitchesPerOctave;s.setAttribute("width",""+(i-2)),s.setAttribute("y",""+(n*this.re+1)),s.setAttribute("height",""+(this.re-2))}}this.Kt&&(this.le||this.oi(),this.ri(),this.bi()),this.Oe!=this.j.prefs.showFifth&&(this.Oe=this.j.prefs.showFifth,this.ne[7].setAttribute("fill",this.j.prefs.showFifth?$.fifthNote:$.pitchBackground));for(let t=0;t<e.pitchesPerOctave;t++)this.ne[t].style.visibility=e.scales[this.j.song.scale].flags[t]?"visible":"hidden";this.j.song.getChannelIsNoise(this.j.channel)?this.Ne||(this.Ne=!0,this.Xt.setAttribute("fill","url(#patternEditorDrumBackground"+this.Yt+")")):this.Ne&&(this.Ne=!1,this.Xt.setAttribute("fill","url(#patternEditorNoteBackground"+this.Yt+")")),this.We()}We(){if(this.Zt=function(t){const e=t.cloneNode(!1);return t.parentNode.replaceChild(e,t),e}(this.Zt),this.j.prefs.showChannels)for(let t=this.j.song.getChannelCount()-1;t>=0;t--){if(t==this.j.channel)continue;if(this.j.song.getChannelIsNoise(t)!=this.j.song.getChannelIsNoise(this.j.channel))continue;const i=this.j.song.getPattern(t,this.j.bar+this.Yt);if(null==i)continue;const s=this.j.getBaseVisibleOctave(t)*e.pitchesPerOctave;for(const e of i.notes)for(const i of e.pitches){const n=A.path();n.setAttribute("fill",$.getChannelColor(this.j.song,t).secondaryNote),n.setAttribute("pointer-events","none"),this.vi(n,i,e.start,e.pins,.19*this.re,!1,s),this.Zt.appendChild(n)}}if(null!=this.Vt){const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],e=t.getChord(),i=t.getTransition(),s=e.customInterval||e.arpeggiates||e.strumParts>0||i.slides;for(const t of this.Vt.notes)for(let e=0;e<t.pitches.length;e++){const i=t.pitches[e];let n=A.path();n.setAttribute("fill",$.getChannelColor(this.j.song,this.j.channel).secondaryNote),n.setAttribute("pointer-events","none"),this.vi(n,i,t.start,t.pins,this.re/2+1,!1,this.Le),this.Zt.appendChild(n),n=A.path(),n.setAttribute("fill",$.getChannelColor(this.j.song,this.j.channel).primaryNote),n.setAttribute("pointer-events","none"),this.vi(n,i,t.start,t.pins,this.re/2+1,!0,this.Le),this.Zt.appendChild(n);let o=2;if(t.continuesLastPattern){const e=Math.min(this.re,20);let s;s="M "+M(this.ci*t.start+o)+" "+M(this.wi(i-this.Le)-.1*e),s+="L "+M(this.ci*t.start+o)+" "+M(this.wi(i-this.Le)+.1*e),s+="L "+M(this.ci*t.start+o+4)+" "+M(this.wi(i-this.Le)+.1*e),s+="L "+M(this.ci*t.start+o+4)+" "+M(this.wi(i-this.Le)+.3*e),s+="L "+M(this.ci*t.start+o+12)+" "+M(this.wi(i-this.Le)),s+="L "+M(this.ci*t.start+o+4)+" "+M(this.wi(i-this.Le)-.3*e),s+="L "+M(this.ci*t.start+o+4)+" "+M(this.wi(i-this.Le)-.1*e);const n=A.path();n.setAttribute("d",s),n.setAttribute("fill",$.invertedText),this.Zt.appendChild(n),o+=12}if(t.pitches.length>1&&s){const s=A.text();s.setAttribute("x",""+M(this.ci*t.start+o)),s.setAttribute("y",""+M(this.wi(i-this.Le))),s.setAttribute("width","30"),s.setAttribute("fill",$.invertedText),s.setAttribute("text-anchor","start"),s.setAttribute("dominant-baseline","central"),s.setAttribute("pointer-events","none"),s.textContent=""+(e+1),this.Zt.appendChild(s)}}}this.j.currentPatternIsDirty=!1}vi(t,i,s,n,o,r,h){const a=this.ci*(n[n.length-1].time+n[0].time),l=.5*Math.min(2,a-1);let c=n[0],u="M "+M(this.ci*(s+c.time)+l)+" "+M(this.wi(i-h)+o*(r?c.size/e.noteSizeMax:1))+" ";for(let t=1;t<n.length;t++){let a=c;c=n[t];let f=this.ci*(s+a.time)+(1==t?l:0),p=this.ci*(s+c.time)-(t==n.length-1?l:0),d=this.wi(i+a.interval-h),m=this.wi(i+c.interval-h),y=r?a.size/e.noteSizeMax:1,g=r?c.size/e.noteSizeMax:1;u+="L "+M(f)+" "+M(d-o*y)+" ",a.interval>c.interval&&(u+="L "+M(f+1)+" "+M(d-o*y)+" "),a.interval<c.interval&&(u+="L "+M(p-1)+" "+M(m-o*g)+" "),u+="L "+M(p)+" "+M(m-o*g)+" "}for(let t=n.length-2;t>=0;t--){let a=c;c=n[t];let f=this.ci*(s+a.time)-(t==n.length-2?l:0),p=this.ci*(s+c.time)+(0==t?l:0),d=this.wi(i+a.interval-h),m=this.wi(i+c.interval-h),y=r?a.size/e.noteSizeMax:1,g=r?c.size/e.noteSizeMax:1;u+="L "+M(f)+" "+M(d+o*y)+" ",a.interval<c.interval&&(u+="L "+M(f-1)+" "+M(d+o*y)+" "),a.interval>c.interval&&(u+="L "+M(p+1)+" "+M(m+o*g)+" "),u+="L "+M(p)+" "+M(m+o*g)+" "}u+="z",t.setAttribute("d",u)}wi(t){return this.re*(this.gi-t-.5)}}class Ei{constructor(t){this.j=t,this.container=D.div({class:"envelopeEditor"}),this.ki=[],this.Mi=[],this.xi=[],this.Si=[],this.Fi=0,this.Pi=-1,this.Ii=-1,this.Ti=0,this.qi=t=>{const i=this.Mi.indexOf(t.target),s=this.xi.indexOf(t.target);if(-1!=i){const t=parseInt(this.Mi[i].value),s=t%e.instrumentAutomationTargets.length,n=t/e.instrumentAutomationTargets.length>>>0;this.j.record(new Pi(this.j,i,s,n))}else-1!=s&&this.j.record(new Ii(this.j,s,this.xi[s].selectedIndex))},this.Ei=t=>{const e=this.Si.indexOf(t.target);-1!=e&&this.j.record(new Fi(this.j,e))},this.container.addEventListener("change",this.qi),this.container.addEventListener("click",this.Ei)}Ci(t,i){let s=e.instrumentAutomationTargets[t].displayName;return e.instrumentAutomationTargets[t].maxCount>1&&(-1!=s.indexOf("#")?s=s.replace("#",String(i+1)):s+=" "+(i+1)),D.option({value:t+i*e.instrumentAutomationTargets.length},s)}Li(t,i){for(let s=0;s<t.childElementCount;s++){const n=t.children[s],o=parseInt(n.value),r=o%e.instrumentAutomationTargets.length,h=o/e.instrumentAutomationTargets.length>>>0;n.hidden=!i.supportsEnvelopeTarget(r,h)}}render(){const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()];if(this.j.prefs.alwaysShowSettings||t.preset==t.type){for(let i=this.ki.length;i<t.envelopeCount;i++){const t=D.select();for(let i=0;i<e.instrumentAutomationTargets.length;i++){const s=e.instrumentAutomationTargets[i].interleave;for(let n=0;n<e.instrumentAutomationTargets[i].maxCount;n++)t.appendChild(this.Ci(i,n)),s&&t.appendChild(this.Ci(i+1,n));s&&i++}const s=D.select();for(let t=0;t<e.envelopes.length;t++)s.appendChild(D.option({value:t},e.envelopes[t].name));const n=D.button({type:"button",class:"delete-envelope"}),o=D.div({class:"envelope-row"},D.div({class:"selectContainer",style:"width: 0; flex: 1;"},t),D.div({class:"selectContainer",style:"width: 0; flex: 0.7;"},s),n);this.container.appendChild(o),this.ki[i]=o,this.Mi[i]=t,this.xi[i]=s,this.Si[i]=n}for(let e=this.Fi;e<t.envelopeCount;e++)this.ki[e].style.display="",this.Li(this.Mi[e],t);for(let e=t.envelopeCount;e<this.Fi;e++)this.ki[e].style.display="none";if(this.Pi!=t.eqFilter.controlPointCount||this.Ii!=t.noteFilter.controlPointCount||this.zi!=t.type||this.Ti!=t.effects)for(let e=0;e<this.Fi;e++)this.Li(this.Mi[e],t);for(let i=0;i<t.envelopeCount;i++)this.Mi[i].value=String(t.envelopes[i].target+t.envelopes[i].index*e.instrumentAutomationTargets.length),this.xi[i].selectedIndex=t.envelopes[i].envelope;this.Fi=t.envelopeCount,this.Pi=t.eqFilter.controlPointCount,this.Ii=t.noteFilter.controlPointCount,this.zi=t.type,this.Ti=t.effects}}}class Ci{constructor(t){this.j=t,this.je=120,this.Qe=26,this.Di=A.path({fill:$.uiWidgetBackground,"pointer-events":"none"}),this.Ai=A.path({fill:"none",stroke:"currentColor","stroke-width":1,"stroke-dasharray":"3, 2","pointer-events":"none"}),this.Bi=A.path({fill:"none",stroke:"currentColor","stroke-width":2,"pointer-events":"none"}),this.se=A.svg({style:`background-color: ${$.editorBackground}; touch-action: none; cursor: crosshair;`,width:"100%",height:"100%",viewBox:"0 0 "+this.je+" "+this.Qe,preserveAspectRatio:"none"},this.Di,this.Ai,this.Bi),this.container=D.div({class:"fadeInOut",style:"height: 100%;"},this.se),this.he=0,this.me=0,this.le=!1,this.ue=!1,this.Oi=!1,this.Ie=null,this.Ni=-1,this.Ri=-1,this.Je=t=>{t.preventDefault();const e=this.se.getBoundingClientRect();this.he=(t.clientX||t.pageX)-e.left,this.Ve()},this.Xe=t=>{t.preventDefault();const e=this.se.getBoundingClientRect();this.he=t.touches[0].clientX-e.left,this.Ve()},this.Ze=t=>{if(null==this.container.offsetParent)return;const e=this.se.getBoundingClientRect();this.he=(t.clientX||t.pageX)-e.left,isNaN(this.he)&&(this.he=0),this.ti()},this.ei=t=>{if(null==this.container.offsetParent)return;if(!this.le)return;t.preventDefault();const e=this.se.getBoundingClientRect();this.he=t.touches[0].clientX-e.left,isNaN(this.he)&&(this.he=0),this.ti()},this.ii=t=>{if(null!=this.container.offsetParent){if(this.le&&this.j.lastChangeWas(this.Ie)&&null!=this.Ie)if(this.ue)this.j.record(this.Ie);else{const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()];this.Oi?this.j.record(new Me(this.j,this.Hi(this.he),t.fadeOut)):this.j.record(new Me(this.j,t.fadeIn,this.Gi(this.he)))}this.Ie=null,this.ue=!1,this.le=!1}};const i=this.$i(e.fadeOutNeutral);this.Ai.setAttribute("d",`M ${i} 0 L ${i} ${this.Qe}`),this.container.addEventListener("mousedown",this.Je),document.addEventListener("mousemove",this.Ze),document.addEventListener("mouseup",this.ii),this.container.addEventListener("touchstart",this.Xe),this.container.addEventListener("touchmove",this.ei),this.container.addEventListener("touchend",this.ii),this.container.addEventListener("touchcancel",this.ii)}_i(t){return 1+.4*(this.je-2)*t/(e.fadeInRange-1)}Hi(t){return tt(0,e.fadeInRange,Math.round((t-1)*(e.fadeInRange-1)/(.4*this.je-2)))}$i(t){return 1+(this.je-2)*(.5+.5*t/(e.fadeOutTicks.length-1))}Gi(t){return tt(0,e.fadeOutTicks.length,Math.round((e.fadeOutTicks.length-1)*((t-1)/(this.je-2)-.5)/.5))}Ve(){isNaN(this.he)&&(this.he=0),this.me=this.he,this.le=!0,this.ue=!1;const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],e=this._i(t.fadeIn),i=this.$i(t.fadeOut);this.Oi=this.me<(e+i)/2,this.Ie=new Dt,this.j.setProspectiveChange(this.Ie)}ti(){if(null!=this.Ie&&this.j.lastChangeWas(this.Ie)?this.Ie.undo():this.le=!1,this.Ie=null,this.le){const t=new Dt;if(this.Ie=t,this.j.setProspectiveChange(this.Ie),Math.abs(this.he-this.me)>4&&(this.ue=!0),this.ue){const e=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()];this.Oi?t.append(new Me(this.j,this.Hi(this._i(e.fadeIn)+this.he-this.me),e.fadeOut)):t.append(new Me(this.j,e.fadeIn,this.Gi(this.$i(e.fadeOut)+this.he-this.me)))}}}render(){const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()];if(this.Ni==t.fadeIn&&this.Ri==t.fadeOut)return;const i=this._i(t.fadeIn),s=this.$i(t.fadeOut);this.Bi.setAttribute("d",`M ${i} 0 L ${i} ${this.Qe} M ${s} 0 L ${s} ${this.Qe}`);const n=this.$i(e.fadeOutNeutral);let o="";o+=`M 0 ${this.Qe} `,o+=`L ${i} 0 `,Ft.fadeOutSettingToTicks(t.fadeOut)>0?(o+=`L ${n} 0 `,o+=`L ${s} ${this.Qe} `):(o+=`L ${s} 0 `,o+=`L ${n} ${this.Qe} `),o+="z",this.Di.setAttribute("d",o)}}class Li{constructor(t,e=!1){this.j=t,this.je=120,this.Qe=26,this.Ui=A.path({fill:$.uiWidgetBackground,"pointer-events":"none"}),this.Vi=A.path({fill:"currentColor","pointer-events":"none"}),this.Ai=A.path({fill:"none",stroke:"currentColor","stroke-width":1,"stroke-dasharray":"3, 2","pointer-events":"none"}),this.ji=A.circle({fill:"white",stroke:"none","pointer-events":"none",r:4}),this.se=A.svg({style:`background-color: ${$.editorBackground}; touch-action: none;`,width:"100%",height:"100%",viewBox:"0 0 "+this.je+" "+this.Qe,preserveAspectRatio:"none"},this.Ui,this.Ai,this.ji,this.Vi),this.Wi=D.div({style:"position: absolute; bottom: 0; left: 2px; font-size: 8px; line-height: 1; pointer-events: none;"}),this.container=D.div({class:"filterEditor",style:"height: 100%; position: relative;"},this.se,this.Wi),this.Ki=2,this.Yi=!1,this.Ji=!1,this.he=0,this.ae=0,this.ce=!1,this.le=!1,this.ue=!1,this.Qi=!1,this.Xi=!1,this.Zi=2,this.ts=0,this.es=0,this.ss=0,this.Ie=null,this.ns=-1,this.os=-1,this.rs=-1,this.hs=-1,this.ls=-1,this.Ke=t=>{this.ce=!0},this.Ye=t=>{this.ce=!1,this.cs()},this.Je=t=>{t.preventDefault(),this.Ji=!1;const e=this.se.getBoundingClientRect();this.he=((t.clientX||t.pageX)-e.left)*this.je/(e.right-e.left),this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.Ve()},this.Xe=t=>{t.preventDefault(),this.Ji=!0;const e=this.se.getBoundingClientRect();this.he=(t.touches[0].clientX-e.left)*this.je/(e.right-e.left),this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.Ve()},this.Ze=t=>{if(null==this.container.offsetParent)return;const e=this.se.getBoundingClientRect();this.he=((t.clientX||t.pageX)-e.left)*this.je/(e.right-e.left),this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.le||this.us(),this.ti()},this.ei=t=>{if(null==this.container.offsetParent)return;this.le&&t.preventDefault();const e=this.se.getBoundingClientRect();this.he=(t.touches[0].clientX-e.left)*this.je/(e.right-e.left),this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.le||this.us(),this.ti()},this.ii=t=>{if(null!=this.container.offsetParent){if(this.le&&this.j.lastChangeWas(this.Ie)&&null!=this.Ie){if(this.Qi||this.ue||this.Ji)this.j.record(this.Ie);else if(this.ts<this.Pt.controlPointCount&&-1!=this.ts){const t=this.Pt.controlPoints[this.ts];this.j.record(new ve(this.j,this.Pt,t,this.ts,this.Yi,!0))}this.cs()}this.Ie=null,this.ue=!1,this.Xi=!1,this.le=!1,this.us()}},this.Yi=e,this.container.addEventListener("mousedown",this.Je),this.container.addEventListener("mouseover",this.Ke),this.container.addEventListener("mouseout",this.Ye),document.addEventListener("mousemove",this.Ze),document.addEventListener("mouseup",this.ii),this.container.addEventListener("touchstart",this.Xe),this.container.addEventListener("touchmove",this.ei),this.container.addEventListener("touchend",this.ii),this.container.addEventListener("touchcancel",this.ii)}fs(t){return e.filterFreqRange*t/this.je-.5}ps(t){return this.je*(t+.5)/e.filterFreqRange}ds(t){return(e.filterGainRange-1)*(1-(t-.5)/(this.Qe-1))}ys(t){return(this.Qe-1)*(1-t/(e.filterGainRange-1))+.5}Ve(){this.le=!0;const t=new Dt;this.Ie=t,this.j.setProspectiveChange(this.Ie),this.us(),this.ti()}us(){this.es=this.fs(this.he),this.ss=this.ds(this.ae),this.Qi=!0,this.ts=-1;let t=Number.POSITIVE_INFINITY;for(let i=0;i<this.Pt.controlPointCount;i++){const s=this.Pt.controlPoints[i],n=Math.sqrt(Math.pow(this.ps(s.freq)-this.he,2)+Math.pow(this.ys(s.gain)-this.ae,2));(n<=13||this.Pt.controlPointCount>=e.filterMaxPoints)&&n<t&&(t=n,this.ts=i,this.Qi=!1)}if(this.Qi){const t=this.he/this.je;this.Zi=t<.2?1:t<.8?2:0}}ti(){if(null!=this.Ie&&this.j.lastChangeWas(this.Ie)?this.Ie.undo():this.le=!1,this.Ie=null,this.Xi=!1,this.le){const t=new Dt;if(this.Ie=t,this.j.setProspectiveChange(this.Ie),this.Qi){const i=Math.max(0,Math.min(e.filterGainRange-1,Math.round(this.ds(this.ae)))),s=this.gs(this.Pt,this.fs(this.he),-1);if(s>=0&&s<e.filterFreqRange){const e=new dt;e.type=this.Zi,e.freq=s,e.gain=i,t.append(new ve(this.j,this.Pt,e,this.Pt.controlPointCount,this.Yi))}else this.Xi=!0}else if(this.ts>=this.Pt.controlPointCount||-1==this.ts)this.Ie=null,this.le=!1;else{const i=this.fs(this.he)-this.es,s=this.ds(this.ae)-this.ss,n=this.Pt.controlPoints[this.ts],o=Math.max(0,Math.min(e.filterGainRange-1,Math.round(n.gain+s))),r=this.gs(this.Pt,n.freq+i,this.ts);0==Math.round(i)&&0==Math.round(s)&&r==n.freq&&o==n.gain||(this.ue=!0),r>=0&&r<e.filterFreqRange?t.append(new ke(this.j,n,n.freq,r,n.gain,o)):(t.append(new ve(this.j,this.Pt,n,this.ts,this.Yi,!0)),this.Xi=!0)}}(this.le||this.ce)&&this.cs()}gs(t,e,i){const s=Math.round(e);let n=s,o=s,r=s<=e;for(;;){let e=!1;const s=r?n:o;for(let n=0;n<t.controlPointCount;n++)if(n!=i&&t.controlPoints[n].freq==s){e=!0;break}if(!e)return s;r=!r,r&&n--,r||o++}}static bs(t,e,i,s=!1){return`M ${t-i} ${e} a ${i} ${i} 0 1 ${s?1:0} ${2*i} 0 a ${i} ${i} 0 1 ${s?1:0} ${2*-i} 0 `}cs(){this.ji.style.display="none",this.Wi.textContent="";let t="",i="";for(let s=0;s<this.Pt.controlPointCount;s++){const n=this.Pt.controlPoints[s],o=this.ps(n.freq),r=this.ys(n.gain);t+=Li.bs(o,r,this.Ki),1==n.type?i+="M 0 "+r+" L "+o+" "+r+" ":0==n.type&&(i+="M "+this.je+" "+r+" L "+o+" "+r+" "),this.ts==s&&this.ce&&!this.le&&(this.ji.setAttribute("cx",String(o)),this.ji.setAttribute("cy",String(r)),this.ji.style.display=""),(this.ts==s||this.Qi&&this.le&&s==this.Pt.controlPointCount-1)&&(this.ce||this.le)&&!this.Xi&&(this.Wi.textContent=s+1+": "+e.filterTypeNames[n.type])}this.Vi.setAttribute("d",t),this.Ai.setAttribute("d",i),this.Qi&&!this.le&&this.ce&&(this.Wi.textContent="+ "+e.filterTypeNames[this.Zi]);const s=[];for(let t=0;t<this.Pt.controlPointCount;t++){const e=this.Pt.controlPoints[t],i=new Y;e.toCoefficients(i,44800),s.push(i)}const n=new J;let o="M 0 "+this.Qe+" ";for(let t=-1;t<=e.filterFreqRange;t++){const i=dt.getHzFromSettingValue(t),r=2*Math.PI*i/44800,h=Math.cos(r),a=Math.sin(r);let l=1;for(const t of s)n.analyzeComplex(t,h,a),l*=n.magnitude();const c=Math.log2(l)/e.filterGainStep+e.filterGainCenter,u=this.ys(c);o+="L "+M(this.ps(t))+" "+M(u)+" "}o+="L "+this.je+" "+this.Qe+" L 0 "+this.Qe+" z ",this.Ui.setAttribute("d",o)}render(){const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],i=this.Yi?t.noteFilter:t.eqFilter;this.Pt!=i&&(this.Ie=null,this.le=!1),this.Pt=i,this.le||this.us();let s=0,n=0,o=0;for(let t=0;t<i.controlPointCount;t++){const r=i.controlPoints[t];s=3*s+r.type,n=n*e.filterFreqRange+r.freq,o=o*e.filterGainRange+r.gain}this.ns==this.ts&&this.os==i.controlPointCount&&this.rs==s&&this.hs==n&&this.ls==o||(this.ns=this.ts,this.os=i.controlPointCount,this.rs=s,this.hs=n,this.ls=o,this.cs())}}class zi{constructor(t,e){this.ws=document.createTextNode(""),this.Wi=D.div({class:"channelBoxLabel"},this.ws),this.container=D.div({class:"channelBox",style:`margin: 1px; height: ${Di.patternHeight-2}px;`},this.Wi),this.vs=-1,this.container.style.background=$.uiWidgetBackground,this.Wi.style.color=e}setWidth(t){this.container.style.width=t-2+"px"}setIndex(t,e,i){this.vs!=t&&(this.vs=t,this.ws.data=String(t)),this.Wi.style.color=e?$.invertedText:i,this.container.style.background=e?i:0==t?"none":$.uiWidgetBackground}}class Di{constructor(t,e){this.j=t,this.index=e,this.ks=-1,this.Ms=[],this.container=D.div({class:"channelRow"})}render(){const t=this.j.getBarWidth();if(this.Ms.length!=this.j.song.barCount){for(let e=this.Ms.length;e<this.j.song.barCount;e++){const i=new zi(this.index,$.getChannelColor(this.j.song,this.index).secondaryChannel);i.setWidth(t),this.container.appendChild(i.container),this.Ms[e]=i}for(let t=this.j.song.barCount;t<this.Ms.length;t++)this.container.removeChild(this.Ms[t].container);this.Ms.length=this.j.song.barCount}if(this.ks!=t){this.ks=t;for(let e=0;e<this.Ms.length;e++)this.Ms[e].setWidth(t)}for(let t=0;t<this.Ms.length;t++){const e=this.j.song.getPattern(this.index,t),i=t==this.j.bar&&this.index==this.j.channel,s=null==e||0==e.notes.length,n=this.Ms[t];if(t<this.j.song.barCount){const e=$.getChannelColor(this.j.song,this.index);n.setIndex(this.j.song.channels[this.index].bars[t],i,s&&!i?e.secondaryChannel:e.primaryChannel),n.container.style.visibility="visible"}else n.container.style.visibility="hidden"}}}Di.patternHeight=28;class Ai{constructor(t){this.j=t,this.xs=D.div({style:`background: ${$.editorBackground}; position: sticky; bottom: 0; left: 0; width: 32px; height: 30px;`}),this.container=D.div({class:"muteEditor"}),this.Ss=[],this.Ei=t=>{const e=this.Ss.indexOf(t.target);-1!=e&&(this.j.song.channels[e].muted=!this.j.song.channels[e].muted,this.j.notifier.changed())},this.container.addEventListener("click",this.Ei)}render(){if(this.j.prefs.enableChannelMuting){if(this.Ss.length!=this.j.song.getChannelCount()){for(let t=this.Ss.length;t<this.j.song.getChannelCount();t++){const e=D.button({class:"mute-button",title:"Mute (M), Mute All (⇧M), Solo (S), Exclude (⇧S)",style:`height: ${Di.patternHeight-4}px; margin: 2px;`});this.container.appendChild(e),this.Ss[t]=e}for(let t=this.j.song.getChannelCount();t<this.Ss.length;t++)this.container.removeChild(this.Ss[t]);this.Ss.length=this.j.song.getChannelCount(),this.container.appendChild(this.xs)}for(let t=0;t<this.j.song.getChannelCount();t++)this.j.song.channels[t].muted?this.Ss[t].classList.add("muted"):this.Ss[t].classList.remove("muted")}}}class Bi{constructor(t){this.j=t,this.Fs=D.div({style:"display: flex; flex-direction: column;"}),this.Ps=A.rect({fill:$.playhead,x:0,y:0,width:4,height:128}),this.Is=A.rect({fill:"none",stroke:$.hoverPreview,"stroke-width":2,"pointer-events":"none",x:1,y:1,width:30,height:30}),this.Ts=A.path({fill:$.invertedText,stroke:$.invertedText,"stroke-width":1,"pointer-events":"none"}),this.qs=A.path({fill:$.invertedText,stroke:$.invertedText,"stroke-width":1,"pointer-events":"none"}),this.ee=A.rect({fill:$.boxSelectionFill,stroke:$.hoverPreview,"stroke-width":2,"stroke-dasharray":"5, 3","pointer-events":"none",visibility:"hidden",x:1,y:1,width:62,height:62}),this.se=A.svg({style:"position: absolute; top: 0;"},this.ee,this.Is,this.Ts,this.qs,this.Ps),this.Es=D.select({class:"trackSelectBox",style:"background: none; border: none; appearance: none; border-radius: initial; box-shadow: none; color: transparent; position: absolute; touch-action: none;"}),this.container=D.div({class:"noSelection",style:"position: relative; overflow: hidden;"},this.Fs,this.se,this.Es),this.Cs=[],this.he=0,this.ae=0,this.Ls=0,this.zs=0,this.Ds=0,this.As=0,this.ce=!1,this.Bs=!1,this.ue=!1,this.Os=32,this.Ns=-1,this.Rs=-1,this.Hs=0,this.Gs=-1,this.Ji=k,this.$s=()=>{this.j.selection.setPattern(this.Es.selectedIndex)},this.Ue=t=>{const e=this.Os*this.j.synth.playhead-2;this.Gs!=e&&(this.Gs=e,this.Ps.setAttribute("x",""+e)),window.requestAnimationFrame(this.Ue)},this._s=t=>{this.Bs=!0,this.ue=!0,this.Us(t),this.Ls=this.Ds,this.zs=this.As},this.Vs=t=>{this.Us(t),this.Ls==this.Ds&&this.zs==this.As||t.preventDefault(),this.Bs&&this.js(),this.ri()},this.Ws=t=>{this.Bs=!1,this.ue=!1,this.ri()},this.Ke=t=>{this.ce||(this.ce=!0)},this.Ye=t=>{this.ce&&(this.ce=!1)},this.Je=t=>{t.preventDefault(),this.Bs=!0,this.Ks(t),this.Ls=this.Ds,this.zs=this.As,t.shiftKey?(this.ue=!0,this.j.selection.setTrackSelection(this.j.selection.boxSelectionX0,this.Ds,this.j.selection.boxSelectionY0,this.As),this.j.selection.selectionUpdated()):(this.ue=!1,this.j.channel==this.As&&this.j.bar==this.Ds||(this.j.selection.setChannelBar(this.As,this.Ds),this.ue=!0),this.j.selection.resetBoxSelection())},this.Ze=t=>{this.Ks(t),this.Bs&&(this.Ls==this.Ds&&this.zs==this.As||(this.ue=!0),this.js()),this.ri()},this.Ys=t=>{if(this.Bs&&!this.ue&&this.j.channel==this.As&&this.j.bar==this.Ds){const t=this.ae%Di.patternHeight<Di.patternHeight/2,e=this.j.song.patternsPerChannel;this.j.selection.setPattern((this.j.song.channels[this.As].bars[this.Ds]+(t?1:e))%(e+1))}this.Bs=!1,this.ue=!1,this.ri()},window.requestAnimationFrame(this.Ue),this.se.addEventListener("mousedown",this.Je),document.addEventListener("mousemove",this.Ze),document.addEventListener("mouseup",this.Ys),this.se.addEventListener("mouseover",this.Ke),this.se.addEventListener("mouseout",this.Ye),this.Es.addEventListener("change",this.$s),this.Es.addEventListener("touchstart",this._s),this.Es.addEventListener("touchmove",this.Vs),this.Es.addEventListener("touchend",this.Ws),this.Es.addEventListener("touchcancel",this.Ws);let e=!1;document.addEventListener("mousedown",(()=>{e||(this.Ji=!1,this.ri()),e=!0}),!0),document.addEventListener("touchstart",(()=>{e||(this.Ji=!0,this.ri()),e=!0}),!0)}movePlayheadToMouse(){return!!this.ce&&(this.j.synth.playhead=this.Ds+this.he%this.Os/this.Os,!0)}js(){this.j.selection.setTrackSelection(this.j.selection.boxSelectionX0,this.Ds,this.j.selection.boxSelectionY0,this.As),this.j.selection.selectionUpdated()}Us(t){const e=this.se.getBoundingClientRect();this.he=t.touches[0].clientX-e.left,this.ae=t.touches[0].clientY-e.top,isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.Ds=Math.floor(Math.min(this.j.song.barCount-1,Math.max(0,this.he/this.Os))),this.As=Math.floor(Math.min(this.j.song.getChannelCount()-1,Math.max(0,this.ae/Di.patternHeight)))}Ks(t){const e=this.se.getBoundingClientRect();this.he=(t.clientX||t.pageX)-e.left,this.ae=(t.clientY||t.pageY)-e.top,this.Ds=Math.floor(Math.min(this.j.song.barCount-1,Math.max(0,this.he/this.Os))),this.As=Math.floor(Math.min(this.j.song.getChannelCount()-1,Math.max(0,this.ae/Di.patternHeight)))}ri(){let t=this.As,e=this.Ds;this.Ji&&(e=this.j.bar,t=this.j.channel);const i=e==this.j.bar&&t==this.j.channel;if(!this.ce||this.Bs||i?this.Is.style.visibility="hidden":(this.Is.setAttribute("x",""+(1+this.Os*e)),this.Is.setAttribute("y",""+(1+Di.patternHeight*t)),this.Is.setAttribute("height",""+(Di.patternHeight-2)),this.Is.setAttribute("width",""+(this.Os-2)),this.Is.style.visibility="visible"),(this.ce||this.Ji)&&i){const i=this.ae%Di.patternHeight<Di.patternHeight/2,s=this.Os*(e+.8),n=Di.patternHeight*(t+.5),o=.1*Di.patternHeight,r=.4*Di.patternHeight,h=.175*Di.patternHeight;this.Ts.setAttribute("fill",i&&!this.Ji?$.hoverPreview:$.invertedText),this.qs.setAttribute("fill",i||this.Ji?$.invertedText:$.hoverPreview),this.Ts.setAttribute("d",`M ${s} ${n-r} L ${s+h} ${n-o} L ${s-h} ${n-o} z`),this.qs.setAttribute("d",`M ${s} ${n+r} L ${s+h} ${n+o} L ${s-h} ${n+o} z`),this.Ts.style.visibility="visible",this.qs.style.visibility="visible"}else this.Ts.style.visibility="hidden",this.qs.style.visibility="hidden";this.Es.style.left=this.Os*this.j.bar+"px",this.Es.style.width=this.Os+"px",this.Es.style.top=Di.patternHeight*this.j.channel+"px",this.Es.style.height=Di.patternHeight+"px";const s=this.j.song.patternsPerChannel+1;for(let t=this.Hs;t<s;t++)this.Es.appendChild(D.option({value:t},t));for(let t=s;t<this.Hs;t++)this.Es.removeChild(this.Es.lastChild);this.Hs=s;const n=this.j.song.channels[this.j.channel].bars[this.j.bar];this.Es.selectedIndex!=n&&(this.Es.selectedIndex=n)}render(){if(this.Os=this.j.getBarWidth(),this.Cs.length!=this.j.song.getChannelCount()){for(let t=this.Cs.length;t<this.j.song.getChannelCount();t++){const e=new Di(this.j,t);this.Cs[t]=e,this.Fs.appendChild(e.container)}for(let t=this.j.song.getChannelCount();t<this.Cs.length;t++)this.Fs.removeChild(this.Cs[t].container);this.Cs.length=this.j.song.getChannelCount(),this.Bs=!1}for(let t=0;t<this.j.song.getChannelCount();t++)this.Cs[t].render();const t=this.Os*this.j.song.barCount;this.Ns!=t&&(this.Ns=t,this.Fs.style.width=t+"px",this.container.style.width=t+"px",this.se.setAttribute("width",t+""),this.Bs=!1);const e=this.j.song.getChannelCount()*Di.patternHeight;this.Rs!=e&&(this.Rs=e,this.se.setAttribute("height",""+e),this.Ps.setAttribute("height",""+e),this.container.style.height=e+"px"),this.Es.style.display=this.Ji?"":"none",this.j.selection.boxSelectionActive?(this.ee.setAttribute("x",String(this.Os*this.j.selection.boxSelectionBar+1)),this.ee.setAttribute("y",String(Di.patternHeight*this.j.selection.boxSelectionChannel+1)),this.ee.setAttribute("width",String(this.Os*this.j.selection.boxSelectionWidth-2)),this.ee.setAttribute("height",String(Di.patternHeight*this.j.selection.boxSelectionHeight-2)),this.ee.setAttribute("visibility","visible")):this.ee.setAttribute("visibility","hidden"),this.ri()}}const{button:Oi,label:Ni,div:Ri,form:Hi,h2:Gi,input:$i}=D;class _i{constructor(t){this.j=t,this.Js=$i({type:"file",accept:".json,application/json,.mid,.midi,audio/midi,audio/x-midi"}),this.Qs=Oi({class:"okayButton",style:"width:45%;"},"Okay"),this.Xs=Oi({class:"cancelButton"}),this.Zs=Hi({style:"display: flex; gap: 10px;"},Ni({class:"layout-option"},$i({type:"radio",name:"layout",value:"small"}),A('\t\t\t\t\t<svg viewBox="-4 -1 28 22">\n\t\t\t\t\t\t<rect x="0" y="0" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1"/>\n\t\t\t\t\t\t<rect x="2" y="2" width="11" height="10" fill="currentColor"/>\n\t\t\t\t\t\t<rect x="14" y="2" width="4" height="16" fill="currentColor"/>\n\t\t\t\t\t\t<rect x="2" y="13" width="11" height="5" fill="currentColor"/>\n\t\t\t\t\t</svg>\n\t\t\t\t'),Ri("Small")),Ni({class:"layout-option"},$i({type:"radio",name:"layout",value:"long"}),A('\t\t\t\t\t<svg viewBox="-1 -1 28 22">\n\t\t\t\t\t\t<rect x="0" y="0" width="26" height="20" fill="none" stroke="currentColor" stroke-width="1"/>\n\t\t\t\t\t\t<rect x="2" y="2" width="12" height="10" fill="currentColor"/>\n\t\t\t\t\t\t<rect x="15" y="2" width="4" height="10" fill="currentColor"/>\n\t\t\t\t\t\t<rect x="20" y="2" width="4" height="10" fill="currentColor"/>\n\t\t\t\t\t\t<rect x="2" y="13" width="22" height="5" fill="currentColor"/>\n\t\t\t\t\t</svg>\n\t\t\t\t'),Ri("Long")),Ni({class:"layout-option"},$i({type:"radio",name:"layout",value:"tall"}),A('\t\t\t\t\t<svg viewBox="-1 -1 28 22">\n\t\t\t\t\t\t<rect x="0" y="0" width="26" height="20" fill="none" stroke="currentColor" stroke-width="1"/>\n\t\t\t\t\t\t<rect x="11" y="2" width="8" height="16" fill="currentColor"/>\n\t\t\t\t\t\t<rect x="20" y="2" width="4" height="16" fill="currentColor"/>\n\t\t\t\t\t\t<rect x="2" y="2" width="8" height="16" fill="currentColor"/>\n\t\t\t\t\t</svg>\n\t\t\t\t'),Ri("Tall"))),this.container=Ri({class:"prompt noSelection",style:"width: 300px;"},Gi("Layout"),this.Zs,Ri({style:"display: flex; flex-direction: row-reverse; justify-content: space-between;"},this.Qs),this.Xs),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.Qs.removeEventListener("click",this.tn),this.Xs.removeEventListener("click",this.K),this.container.removeEventListener("keydown",this.en)},this.en=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.tn()},this.tn=()=>{this.j.prefs.layout=this.Zs.elements.layout.value,this.j.prefs.save(),U.setLayout(this.j.prefs.layout),this.K()},this.Js.select(),setTimeout((()=>this.Js.focus())),this.Qs.addEventListener("click",this.tn),this.Xs.addEventListener("click",this.K),this.container.addEventListener("keydown",this.en),this.Zs.elements.layout.value=this.j.prefs.layout}}class Ui{constructor(t){this.j=t,this.Qe=20,this.sn=0,this.nn=1,this.rn=2,this.hn=A.path({fill:"none",stroke:$.loopAccent,"stroke-width":4}),this.ji=A.path({fill:$.hoverPreview,"pointer-events":"none"}),this.se=A.svg({style:"touch-action: pan-y; position: absolute;",height:this.Qe},this.hn,this.ji),this.container=D.div({class:"loopEditor"},this.se),this.Os=32,this.an=null,this.Ee={startBar:-1,mode:-1},this.he=0,this.ln=0,this.cn=0,this.un=!1,this.fn=!1,this.le=!1,this.ce=!1,this.pn=-1,this.dn=-1,this.mn=0,this.ks=-1,this.Ke=t=>{this.ce||(this.ce=!0,this.ri())},this.Ye=t=>{this.ce&&(this.ce=!1,this.ri())},this.Je=t=>{t.preventDefault(),this.le=!0;const e=this.se.getBoundingClientRect();this.he=(t.clientX||t.pageX)-e.left,this.oi(),this.ri(),this.Ze(t)},this.Xe=t=>{this.le=!0;const e=this.se.getBoundingClientRect();this.he=t.touches[0].clientX-e.left,this.oi(),this.ri(),this.ln=t.touches[0].clientX,this.cn=t.touches[0].clientY,this.fn=!1,this.un=!1},this.Ze=t=>{const e=this.se.getBoundingClientRect();this.he=(t.clientX||t.pageX)-e.left,this.ti()},this.ei=t=>{if(!this.le)return;const e=this.se.getBoundingClientRect();this.he=t.touches[0].clientX-e.left,this.fn||this.un||(Math.abs(t.touches[0].clientY-this.cn)>10?this.un=!0:Math.abs(t.touches[0].clientX-this.ln)>10&&(this.fn=!0)),this.fn&&(this.ti(),t.preventDefault())},this.yn=t=>{t.preventDefault(),this.un||(this.ti(),this.ce=!1,this.ii(t),this.ri()),this.le=!1},this.ii=t=>{null!=this.an&&this.j.record(this.an),this.an=null,this.le=!1,this.oi(),this.gn()},this.bn=()=>{this.gn()},this.oi(),this.gn(),this.j.notifier.watch(this.bn),this.container.addEventListener("mousedown",this.Je),document.addEventListener("mousemove",this.Ze),document.addEventListener("mouseup",this.ii),this.container.addEventListener("mouseover",this.Ke),this.container.addEventListener("mouseout",this.Ye),this.container.addEventListener("touchstart",this.Xe),this.container.addEventListener("touchmove",this.ei),this.container.addEventListener("touchend",this.yn),this.container.addEventListener("touchcancel",this.yn)}oi(){const t=this.he/this.Os;this.Ee.startBar=t,t>this.j.song.loopStart-.25&&t<this.j.song.loopStart+this.j.song.loopLength+.25?t-this.j.song.loopStart<.5*this.j.song.loopLength?this.Ee.mode=this.sn:this.Ee.mode=this.nn:this.Ee.mode=this.rn}wn(t){let e=Math.round(t-this.j.song.loopLength/2),i=e+this.j.song.loopLength;return e<0&&(i-=e,e=0),i>this.j.song.barCount&&(e-=i-this.j.song.barCount,i=this.j.song.barCount),{start:e,length:i-e}}ti(){if(this.le){let t=this.j.song.loopStart,e=this.j.song.loopStart+this.j.song.loopLength;null!=this.an&&this.j.lastChangeWas(this.an)&&(t=this.an.oldStart,e=t+this.an.oldLength);const i=this.he/this.Os;let s,n,o;if(this.Ee.mode==this.sn)s=t+Math.round(i-this.Ee.startBar),n=e,s<0&&(s=0),s>=this.j.song.barCount&&(s=this.j.song.barCount),s==n?s=n-1:s>n&&(o=s,s=n,n=o),this.an=new ze(this.j,t,e-t,s,n-s);else if(this.Ee.mode==this.nn)s=t,n=e+Math.round(i-this.Ee.startBar),n<0&&(n=0),n>=this.j.song.barCount&&(n=this.j.song.barCount),n==s?n=s+1:n<s&&(o=s,s=n,n=o),this.an=new ze(this.j,t,e-t,s,n-s);else if(this.Ee.mode==this.rn){const s=this.wn(i);this.an=new ze(this.j,t,e-t,s.start,s.length)}this.j.synth.jumpIntoLoop(),this.j.prefs.autoFollow&&new ee(this.j,this.j.channel,Math.floor(this.j.synth.playhead),!0),this.j.setProspectiveChange(this.an)}else this.oi(),this.ri()}ri(){const t=this.ce&&!this.le;if(this.ji.style.visibility=t?"visible":"hidden",t){const t=this.Qe/2;let e=this.j.song.loopStart*this.Os,i=(this.j.song.loopStart+this.j.song.loopLength)*this.Os;if(this.Ee.mode==this.sn)i=this.j.song.loopStart*this.Os+2*t;else if(this.Ee.mode==this.nn)e=(this.j.song.loopStart+this.j.song.loopLength)*this.Os-2*t;else{const t=this.wn(this.Ee.startBar);e=t.start*this.Os,i=(t.start+t.length)*this.Os}this.ji.setAttribute("d",`M ${e+t} 4 L ${i-t} 4 A ${t-4} ${t-4} 0 0 1 ${i-t} ${this.Qe-4} L ${e+t} ${this.Qe-4} A ${t-4} ${t-4} 0 0 1 ${e+t} 4 z`)}}gn(){this.Os=this.j.getBarWidth();const t=this.Qe/2,e=this.j.song.loopStart*this.Os,i=(this.j.song.loopStart+this.j.song.loopLength)*this.Os;if(this.mn!=this.j.song.barCount||this.ks!=this.Os){this.mn=this.j.song.barCount,this.ks=this.Os;const t=this.Os*this.j.song.barCount;this.container.style.width=t+"px",this.se.setAttribute("width",t+"")}this.pn==e&&this.dn==i||(this.pn=e,this.dn=i,this.hn.setAttribute("d",`M ${e+t} 2 L ${i-t} 2 A ${t-2} ${t-2} 0 0 1 ${i-t} ${this.Qe-2} L ${e+t} ${this.Qe-2} A ${t-2} ${t-2} 0 0 1 ${e+t} 2 z`)),this.ri()}}class Vi{constructor(t,i){this.j=t,this.vn=i,this.je=120,this.Qe=26,this.kn=A.path({fill:$.uiWidgetBackground,"pointer-events":"none"}),this.Mn=A.svg({"pointer-events":"none"}),this.xn=A.svg({"pointer-events":"none"}),this.Sn=A.path({fill:"none",stroke:"currentColor","stroke-width":2,"pointer-events":"none"}),this.Fn=A.path({fill:"currentColor","pointer-events":"none"}),this.se=A.svg({style:`background-color: ${$.editorBackground}; touch-action: none; cursor: crosshair;`,width:"100%",height:"100%",viewBox:"0 0 "+this.je+" "+this.Qe,preserveAspectRatio:"none"},this.kn,this.Mn,this.xn,this.Sn,this.Fn),this.container=D.div({class:"spectrum",style:"height: 100%;"},this.se),this.he=0,this.ae=0,this.Pn=0,this.In=0,this.le=!1,this.an=null,this.Tn="",this.Oe=!0,this.Je=t=>{t.preventDefault(),this.le=!0;const e=this.se.getBoundingClientRect();this.he=((t.clientX||t.pageX)-e.left)*this.je/(e.right-e.left),this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.Pn=this.fs(this.he),this.In=this.qn(this.ae),this.ti()},this.Xe=t=>{t.preventDefault(),this.le=!0;const e=this.se.getBoundingClientRect();this.he=(t.touches[0].clientX-e.left)*this.je/(e.right-e.left),this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.Pn=this.fs(this.he),this.In=this.qn(this.ae),this.ti()},this.Ze=t=>{if(null==this.container.offsetParent)return;const e=this.se.getBoundingClientRect();this.he=((t.clientX||t.pageX)-e.left)*this.je/(e.right-e.left),this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.ti()},this.ei=t=>{if(null==this.container.offsetParent)return;if(!this.le)return;t.preventDefault();const e=this.se.getBoundingClientRect();this.he=(t.touches[0].clientX-e.left)*this.je/(e.right-e.left),this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.ti()},this.ii=t=>{this.le&&(this.j.record(this.an),this.an=null),this.le=!1};for(let t=0;t<e.spectrumControlPoints;t+=e.spectrumControlPointsPerOctave)this.Mn.appendChild(A.rect({fill:$.tonic,x:(t+1)*this.je/(e.spectrumControlPoints+2)-1,y:0,width:2,height:this.Qe}));for(let t=4;t<=e.spectrumControlPoints;t+=e.spectrumControlPointsPerOctave)this.xn.appendChild(A.rect({fill:$.fifthNote,x:(t+1)*this.je/(e.spectrumControlPoints+2)-1,y:0,width:2,height:this.Qe}));this.container.addEventListener("mousedown",this.Je),document.addEventListener("mousemove",this.Ze),document.addEventListener("mouseup",this.ii),this.container.addEventListener("touchstart",this.Xe),this.container.addEventListener("touchmove",this.ei),this.container.addEventListener("touchend",this.ii),this.container.addEventListener("touchcancel",this.ii)}fs(t){return(e.spectrumControlPoints+2)*t/this.je-1}qn(t){return e.spectrumMax*(1-(t-1)/(this.Qe-2))}ti(){if(this.le){const t=this.fs(this.he),i=this.qn(this.ae),s=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],n=null==this.vn?s.spectrumWave:s.drumsetSpectrumWaves[this.vn];if(t!=this.Pn){const s=(i-this.In)/(t-this.Pn),o=this.In-this.Pn*s,r=Math.ceil(Math.min(this.Pn,t)),h=Math.floor(Math.max(this.Pn,t));for(let t=r;t<=h;t++)t<0||t>=e.spectrumControlPoints||(n.spectrum[t]=Math.max(0,Math.min(e.spectrumMax,Math.round(t*s+o))))}n.spectrum[Math.max(0,Math.min(e.spectrumControlPoints-1,Math.round(t)))]=Math.max(0,Math.min(e.spectrumMax,Math.round(i))),this.Pn=t,this.In=i,this.an=new oe(this.j,s,n),this.j.setProspectiveChange(this.an)}}render(){const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],i=null==this.vn?t.spectrumWave:t.drumsetSpectrumWaves[this.vn],s=t=>(1-t/e.spectrumMax)*(this.Qe-1)+1;let n=0,o="M 0 "+M(this.Qe)+" ";for(let t=0;t<e.spectrumControlPoints;t++){let r=i.spectrum[t];o+=0!=n||0!=r?"L ":"M ",o+=M((t+1)*this.je/(e.spectrumControlPoints+2))+" "+M(s(r))+" ",n=r}const r=s(n);n>0&&(o+="L "+(this.je-1)+" "+M(r)+" "),this.Tn!=o&&(this.Tn=o,this.Sn.setAttribute("d",o),this.kn.setAttribute("d",o+"L "+this.je+" "+M(r)+" L "+this.je+" "+M(this.Qe)+" L 0 "+M(this.Qe)+" z "),this.Fn.setAttribute("d","M "+this.je+" "+M(r)+" L "+(this.je-4)+" "+M(r-4)+" L "+(this.je-4)+" "+M(r+4)+" z"),this.Fn.style.display=n>0?"":"none"),this.Oe!=this.j.prefs.showFifth&&(this.Oe=this.j.prefs.showFifth,this.xn.style.display=this.j.prefs.showFifth?"":"none")}}class ji{constructor(t){this.j=t,this.je=120,this.Qe=26,this.Mn=A.svg({"pointer-events":"none"}),this.xn=A.svg({"pointer-events":"none"}),this.Sn=A.path({fill:"none",stroke:"currentColor","stroke-width":2,"pointer-events":"none"}),this.En=[],this.Cn=A.svg({"pointer-events":"none"}),this.se=A.svg({style:`background-color: ${$.editorBackground}; touch-action: none; cursor: crosshair;`,width:"100%",height:"100%",viewBox:"0 0 "+this.je+" "+this.Qe,preserveAspectRatio:"none"},this.Mn,this.xn,this.Sn,this.Cn),this.container=D.div({class:"harmonics",style:"height: 100%;"},this.se),this.he=0,this.ae=0,this.Pn=0,this.In=0,this.le=!1,this.an=null,this.Tn="",this.Oe=!0,this.Je=t=>{t.preventDefault(),this.le=!0;const e=this.se.getBoundingClientRect();this.he=((t.clientX||t.pageX)-e.left)*this.je/(e.right-e.left),this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.Pn=this.fs(this.he),this.In=this.qn(this.ae),this.ti()},this.Xe=t=>{t.preventDefault(),this.le=!0;const e=this.se.getBoundingClientRect();this.he=(t.touches[0].clientX-e.left)*this.je/(e.right-e.left),this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.Pn=this.fs(this.he),this.In=this.qn(this.ae),this.ti()},this.Ze=t=>{if(null==this.container.offsetParent)return;const e=this.se.getBoundingClientRect();this.he=((t.clientX||t.pageX)-e.left)*this.je/(e.right-e.left),this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.ti()},this.ei=t=>{if(null==this.container.offsetParent)return;if(!this.le)return;t.preventDefault();const e=this.se.getBoundingClientRect();this.he=(t.touches[0].clientX-e.left)*this.je/(e.right-e.left),this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.he)&&(this.he=0),isNaN(this.ae)&&(this.ae=0),this.ti()},this.ii=t=>{this.le&&(this.j.record(this.an),this.an=null),this.le=!1};for(let t=1;t<=e.harmonicsControlPoints;t*=2)this.Mn.appendChild(A.rect({fill:$.tonic,x:(t-.5)*(this.je-8)/(e.harmonicsControlPoints-1)-1,y:0,width:2,height:this.Qe}));for(let t=3;t<=e.harmonicsControlPoints;t*=2)this.xn.appendChild(A.rect({fill:$.fifthNote,x:(t-.5)*(this.je-8)/(e.harmonicsControlPoints-1)-1,y:0,width:2,height:this.Qe}));for(let t=0;t<4;t++){const e=A.rect({fill:"currentColor",x:this.je-2*t-1,y:0,width:1,height:this.Qe});this.En.push(e),this.Cn.appendChild(e)}this.container.addEventListener("mousedown",this.Je),document.addEventListener("mousemove",this.Ze),document.addEventListener("mouseup",this.ii),this.container.addEventListener("touchstart",this.Xe),this.container.addEventListener("touchmove",this.ei),this.container.addEventListener("touchend",this.ii),this.container.addEventListener("touchcancel",this.ii)}fs(t){return(e.harmonicsControlPoints-1)*t/(this.je-8)-.5}qn(t){return e.harmonicsMax*(1-t/this.Qe)}ti(){if(this.le){const t=this.fs(this.he),i=this.qn(this.ae),s=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],n=s.harmonicsWave;if(t!=this.Pn){const s=(i-this.In)/(t-this.Pn),o=this.In-this.Pn*s,r=Math.ceil(Math.min(this.Pn,t)),h=Math.floor(Math.max(this.Pn,t));for(let t=r;t<=h;t++)t<0||t>=e.harmonicsControlPoints||(n.harmonics[t]=Math.max(0,Math.min(e.harmonicsMax,Math.round(t*s+o))))}n.harmonics[Math.max(0,Math.min(e.harmonicsControlPoints-1,Math.round(t)))]=Math.max(0,Math.min(e.harmonicsMax,Math.round(i))),this.Pn=t,this.In=i,this.an=new re(this.j,s,n),this.j.setProspectiveChange(this.an)}}render(){const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()].harmonicsWave,i=t=>(1-t/e.harmonicsMax)*this.Qe;let s=M(this.Qe),n="";for(let o=0;o<e.harmonicsControlPoints-1;o++){if(0==t.harmonics[o])continue;let r=M((o+.5)*(this.je-8)/(e.harmonicsControlPoints-1));n+="M "+r+" "+s+" ",n+="L "+r+" "+M(i(t.harmonics[o]))+" "}const o=i(t.harmonics[e.harmonicsControlPoints-1]);for(let t=0;t<4;t++){const e=this.En[t];e.setAttribute("y",M(o)),e.setAttribute("height",M(this.Qe-o))}this.Tn!=n&&(this.Tn=n,this.Sn.setAttribute("d",n)),this.Oe!=this.j.prefs.showFifth&&(this.Oe=this.j.prefs.showFifth,this.xn.style.display=this.j.prefs.showFifth?"":"none")}}class Wi{constructor(t){this.j=t,this.je=512,this.Qe=20,this.Ln=A.svg({"pointer-events":"none"}),this.zn=A.rect({fill:$.uiWidgetBackground,x:0,y:2,width:10,height:this.Qe-4}),this.Dn=A.rect({fill:"none",stroke:$.hoverPreview,"stroke-width":2,"pointer-events":"none",x:0,y:1,width:10,height:this.Qe-2}),this.An=A.path({fill:$.hoverPreview,"pointer-events":"none"}),this.Bn=A.path({fill:$.hoverPreview,"pointer-events":"none"}),this.se=A.svg({style:`background-color: ${$.editorBackground}; touch-action: pan-y; position: absolute;`,width:this.je,height:this.Qe},this.Ln,this.zn,this.Dn,this.An,this.Bn),this.container=D.div({class:"barScrollBar",style:"width: 512px; height: 20px; overflow: hidden; position: relative;"},this.se),this.he=0,this.le=!1,this.ce=!1,this.On=!1,this.Nn=-1,this.Rn=-1,this.Ke=t=>{this.ce||(this.ce=!0,this.ri())},this.Ye=t=>{this.ce&&(this.ce=!1,this.ri())},this.Je=t=>{t.preventDefault(),this.le=!0;const e=this.se.getBoundingClientRect();this.he=(t.clientX||t.pageX)-e.left,this.ri(),this.he>=this.j.barScrollPos*this.Hn&&this.he<=(this.j.barScrollPos+this.j.trackVisibleBars)*this.Hn&&(this.On=!0,this.Gn=this.he)},this.Xe=t=>{t.preventDefault(),this.le=!0;const e=this.se.getBoundingClientRect();this.he=t.touches[0].clientX-e.left,this.ri(),this.he>=this.j.barScrollPos*this.Hn&&this.he<=(this.j.barScrollPos+this.j.trackVisibleBars)*this.Hn&&(this.On=!0,this.Gn=this.he)},this.Ze=t=>{const e=this.se.getBoundingClientRect();this.he=(t.clientX||t.pageX)-e.left,this.ti()},this.ei=t=>{if(!this.le)return;t.preventDefault();const e=this.se.getBoundingClientRect();this.he=t.touches[0].clientX-e.left,this.ti()},this.ii=t=>{!this.On&&this.le&&(this.he<(this.j.barScrollPos+8)*this.Hn?(this.j.barScrollPos>0&&this.j.barScrollPos--,this.j.notifier.changed()):(this.j.barScrollPos<this.j.song.barCount-this.j.trackVisibleBars&&this.j.barScrollPos++,this.j.notifier.changed())),this.le=!1,this.On=!1,this.ri()};const e=.5*this.Qe;this.An.setAttribute("d",`M 9 ${e} L 20 ${e+6} L 20 ${e-6} z`),this.Bn.setAttribute("d",`M ${this.je-9} ${e} L ${this.je-20} ${e+6} L ${this.je-20} ${e-6} z`),this.container.addEventListener("mousedown",this.Je),document.addEventListener("mousemove",this.Ze),document.addEventListener("mouseup",this.ii),this.container.addEventListener("mouseover",this.Ke),this.container.addEventListener("mouseout",this.Ye),this.container.addEventListener("touchstart",this.Xe),this.container.addEventListener("touchmove",this.ei),this.container.addEventListener("touchend",this.ii),this.container.addEventListener("touchcancel",this.ii)}ti(){if(this.On){for(;this.he-this.Gn<.5*-this.Hn&&this.j.barScrollPos>0;)this.j.barScrollPos--,this.Gn-=this.Hn,this.j.notifier.changed();for(;this.he-this.Gn>.5*this.Hn&&this.j.barScrollPos<this.j.song.barCount-this.j.trackVisibleBars;)this.j.barScrollPos++,this.Gn+=this.Hn,this.j.notifier.changed()}this.ce&&this.ri()}ri(){let t=!1,e=!1,i=!1;this.ce&&!this.le&&(this.he<this.j.barScrollPos*this.Hn?t=!0:this.he>(this.j.barScrollPos+this.j.trackVisibleBars)*this.Hn?e=!0:i=!0),this.An.style.visibility=t?"visible":"hidden",this.Bn.style.visibility=e?"visible":"hidden",this.Dn.style.visibility=i?"visible":"hidden"}render(){this.Hn=(this.je-1)/Math.max(this.j.trackVisibleBars,this.j.song.barCount);const t=this.Nn!=this.j.song.barCount;if(t){for(this.Nn=this.j.song.barCount;this.Ln.firstChild;)this.Ln.removeChild(this.Ln.firstChild);for(let t=0;t<=this.j.song.barCount;t++){const e=t%16==0?0:t%4==0?this.Qe/8:this.Qe/3;this.Ln.appendChild(A.rect({fill:$.uiWidgetBackground,x:t*this.Hn-1,y:e,width:2,height:this.Qe-2*e}))}}(t||this.Rn!=this.j.barScrollPos)&&(this.Rn=this.j.barScrollPos,this.zn.setAttribute("x",String(this.Hn*this.j.barScrollPos)),this.zn.setAttribute("width",String(this.Hn*this.j.trackVisibleBars)),this.Dn.setAttribute("x",String(this.Hn*this.j.barScrollPos)),this.Dn.setAttribute("width",String(this.Hn*this.j.trackVisibleBars))),this.ri()}}class Ki{constructor(t){this.j=t,this.je=20,this.Qe=481,this.$n=4,this._n=e.pitchOctaves,this.Un=(this.Qe-this.$n)/this._n,this.zn=A.rect({fill:$.uiWidgetBackground,x:2,y:0,width:this.je-4}),this.Dn=A.rect({fill:"none",stroke:$.hoverPreview,"stroke-width":2,"pointer-events":"none",x:1,y:0,width:this.je-2}),this.Ts=A.path({fill:$.hoverPreview,"pointer-events":"none"}),this.qs=A.path({fill:$.hoverPreview,"pointer-events":"none"}),this.se=A.svg({style:`background-color: ${$.editorBackground}; touch-action: pan-x; position: absolute;`,width:this.je,height:"100%",viewBox:"0 0 20 481",preserveAspectRatio:"none"}),this.container=D.div({id:"octaveScrollBarContainer",style:"width: 20px; height: 100%; overflow: hidden; position: relative; flex-shrink: 0;"},this.se),this.ae=0,this.le=!1,this.ce=!1,this.On=!1,this.Vn=-1,this.jn=-1,this.an=null,this.Ke=t=>{this.ce||(this.ce=!0,this.ri())},this.Ye=t=>{this.ce&&(this.ce=!1,this.ri())},this.Je=t=>{t.preventDefault(),this.le=!0;const e=this.se.getBoundingClientRect();this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.ae)&&(this.ae=0),this.j.song.getChannelIsNoise(this.j.channel)||(this.ri(),this.ae>=this.Wn-this.Kn&&this.ae<=this.Wn&&(this.On=!0,this.an=null,this.Gn=this.ae))},this.Xe=t=>{t.preventDefault(),this.le=!0;const e=this.se.getBoundingClientRect();this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.ae)&&(this.ae=0),this.j.song.getChannelIsNoise(this.j.channel)||(this.ri(),this.ae>=this.Wn-this.Kn&&this.ae<=this.Wn&&(this.On=!0,this.an=null,this.Gn=this.ae))},this.Ze=t=>{const e=this.se.getBoundingClientRect();this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.ae)&&(this.ae=0),this.ti()},this.ei=t=>{if(!this.le)return;t.preventDefault();const e=this.se.getBoundingClientRect();this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.ae)&&(this.ae=0),this.ti()},this.ii=t=>{if(!this.j.song.getChannelIsNoise(this.j.channel)&&this.le)if(this.On)null!=this.an&&this.j.record(this.an);else{const t=this.j.getVisibleOctaveCount(),i=e.pitchOctaves-t,s=this.j.lastChangeWas(this.an),n=s?this.an.oldValue:this.j.song.channels[this.j.channel].octave,o=this.j.getBaseVisibleOctave(this.j.channel);this.ae<this.Wn-.5*this.Kn?o<i&&(this.an=new Ae(this.j,n,Math.floor(o+1+.5*t)),this.j.record(this.an,s)):o>0&&(this.an=new Ae(this.j,n,Math.floor(o-1+.5*t)),this.j.record(this.an,s))}this.le=!1,this.On=!1,this.ri()},this.bn=()=>{this.Wn=this.Qe-this.Un*this.j.getBaseVisibleOctave(this.j.channel),this.se.style.visibility=this.j.song.getChannelIsNoise(this.j.channel)?"hidden":"visible";const t=this.j.getVisibleOctaveCount();this.Vn==this.Wn&&this.jn==t||(this.Vn=this.Wn,this.jn=t,this.Kn=this.Un*t+this.$n,this.zn.setAttribute("height",String(this.Kn)),this.Dn.setAttribute("height",String(this.Kn)),this.zn.setAttribute("y",String(this.Wn-this.Kn)),this.Dn.setAttribute("y",String(this.Wn-this.Kn))),this.ri()},this.j.notifier.watch(this.bn),this.bn(),this.se.appendChild(this.zn);for(let t=0;t<=this._n;t++)this.se.appendChild(A.rect({fill:$.tonic,x:0,y:t*this.Un,width:this.je,height:this.$n}));this.se.appendChild(this.Dn),this.se.appendChild(this.Ts),this.se.appendChild(this.qs);const i=.5*this.je;this.Ts.setAttribute("d",`M ${i} 9 L ${i+6} 20 L ${i-6} 20 z`),this.qs.setAttribute("d",`M ${i} ${this.Qe-9} L ${i+6} ${this.Qe-20} L ${i-6} ${this.Qe-20} z`),this.container.addEventListener("mousedown",this.Je),document.addEventListener("mousemove",this.Ze),document.addEventListener("mouseup",this.ii),this.container.addEventListener("mouseover",this.Ke),this.container.addEventListener("mouseout",this.Ye),this.container.addEventListener("touchstart",this.Xe),this.container.addEventListener("touchmove",this.ei),this.container.addEventListener("touchend",this.ii),this.container.addEventListener("touchcancel",this.ii)}ti(){if(!this.j.song.getChannelIsNoise(this.j.channel)){if(this.On){const t=this.j.getVisibleOctaveCount(),i=e.pitchOctaves-t,s=this.j.lastChangeWas(this.an)?this.an.oldValue:this.j.song.channels[this.j.channel].octave;let n=this.j.getBaseVisibleOctave(this.j.channel);for(;this.ae-this.Gn<.5*-this.Un&&n<i;)n++,this.Gn-=this.Un;for(;this.ae-this.Gn>.5*this.Un&&n>0;)n--,this.Gn+=this.Un;this.an=new Ae(this.j,s,Math.floor(n+.5*t)),this.j.setProspectiveChange(this.an)}this.ce&&this.ri()}}ri(){let t=!1,e=!1,i=!1;this.ce&&!this.le&&(this.ae<this.Wn-this.Kn?t=!0:this.ae>this.Wn?e=!0:i=!0),this.Ts.style.visibility=t?"inherit":"hidden",this.qs.style.visibility=e?"inherit":"hidden",this.Dn.style.visibility=i?"inherit":"hidden"}}const Yi=8192,Ji={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 Qi(t){return Math.pow(t/127,4)/.3844015376046128}var Xi=t&&t.Yn||function(t,e,i,s){return new(i||(i=Promise))((function(n,o){function r(t){try{a(s.next(t))}catch(t){o(t)}}function h(t){try{a(s.throw(t))}catch(t){o(t)}}function a(t){var e;t.done?n(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(r,h)}a((s=s.apply(t,e||[])).next())}))};const Zi=(4294967295*Math.random()>>>0).toString(16);class ts{constructor(t){this.j=t,this.Jn=t=>{localStorage.setItem("midiHandlerId",Zi)},this.Qn=t=>{if("input"===t.port.type)switch(t.port.state){case"connected":this.Xn(t.port);break;case"disconnected":this.Zn(t.port)}},this.Xn=t=>{t.addEventListener("midimessage",this.eo)},this.Zn=t=>{t.removeEventListener("midimessage",this.eo),this.j.performance.clearAllPitches()},this.eo=t=>{if(!this.j.prefs.enableMidi||localStorage.getItem("midiHandlerId")!=Zi)return;const i=this.j.song.getChannelIsNoise(this.j.channel);let[s,n,o]=t.data;if(s&=240,i){const t=Ji[n];if(null==t)return;n=t.frequency}else if(n-=e.keys[this.j.song.key].basePitch,n<0||n>e.maxPitch)return;switch(144==s&&0==o&&(s=128),s){case 144:this.j.synth.preferLowerLatency=!0,this.j.performance.addPerformedPitch(n);break;case 128:this.j.performance.removePerformedPitch(n)}},this.registerMidiAccessHandler()}registerMidiAccessHandler(){return Xi(this,void 0,void 0,(function*(){if(null!=navigator.requestMIDIAccess)try{const t=yield navigator.requestMIDIAccess();t.inputs.forEach(this.Xn),t.addEventListener("statechange",this.Qn),this.Jn(),window.addEventListener("focus",this.Jn)}catch(t){console.error("Failed to get MIDI access",t)}}))}}class es{constructor(t){this.j=t,this.io=!1,this.so=t=>{this.io&&(this.j.performance.clearAllPitches(),this.io=!1)},window.addEventListener("blur",this.so)}static keyPosToPitch(t,i,s,n){let o=null,r=null;switch(n){case"wickiHayden":o=5*s+2*i-2;break;case"songScale":const n=e.scales[t.song.scale].flags.map(((t,e)=>t?e:null)).filter((t=>null!=t));o=(s-1+Math.floor(i/n.length))*e.pitchesPerOctave+n[(i+n.length)%n.length];break;case"pianoAtC":o=es.no[s][i],r=e.keys.dictionary.C.basePitch;break;case"pianoAtA":o=es.oo[s][i],r=e.keys.dictionary.A.basePitch;break;case"pianoTransposingC":o=es.no[s][i];break;case"pianoTransposingA":o=es.oo[s][i]}if(null==o)return null;const h=Math.max(0,t.song.channels[t.channel].octave-1)*e.pitchesPerOctave;let a=0;if(null!=r){a=(r-e.keys[t.song.key].basePitch+144)%12}const l=h+a+o;return l<0||l>e.maxPitch?null:l}handleKeyEvent(t,e){switch(t.code){case"Backquote":this.handleKey(-1,3,e);break;case"Digit1":this.handleKey(0,3,e);break;case"Digit2":this.handleKey(1,3,e);break;case"Digit3":this.handleKey(2,3,e);break;case"Digit4":this.handleKey(3,3,e);break;case"Digit5":this.handleKey(4,3,e);break;case"Digit6":this.handleKey(5,3,e);break;case"Digit7":this.handleKey(6,3,e);break;case"Digit8":this.handleKey(7,3,e);break;case"Digit9":this.handleKey(8,3,e);break;case"Digit0":this.handleKey(9,3,e);break;case"Minus":this.handleKey(10,3,e);break;case"Equal":this.handleKey(11,3,e);break;case"IntlYen":this.handleKey(12,3,e);break;case"KeyQ":this.handleKey(0,2,e);break;case"KeyW":this.handleKey(1,2,e);break;case"KeyE":this.handleKey(2,2,e);break;case"KeyR":this.handleKey(3,2,e);break;case"KeyT":this.handleKey(4,2,e);break;case"KeyY":this.handleKey(5,2,e);break;case"KeyU":this.handleKey(6,2,e);break;case"KeyI":this.handleKey(7,2,e);break;case"KeyO":this.handleKey(8,2,e);break;case"KeyP":this.handleKey(9,2,e);break;case"BracketLeft":this.handleKey(10,2,e);break;case"BracketRight":this.handleKey(11,2,e);break;case"Backslash":"\\"==t.key||"|"==t.key?this.handleKey(12,2,e):this.handleKey(11,1,e);break;case"KeyA":this.handleKey(0,1,e);break;case"KeyS":this.handleKey(1,1,e);break;case"KeyD":this.handleKey(2,1,e);break;case"KeyF":this.handleKey(3,1,e);break;case"KeyG":this.handleKey(4,1,e);break;case"KeyH":this.handleKey(5,1,e);break;case"KeyJ":this.handleKey(6,1,e);break;case"KeyK":this.handleKey(7,1,e);break;case"KeyL":this.handleKey(8,1,e);break;case"Semicolon":this.handleKey(9,1,e);break;case"Quote":this.handleKey(10,1,e);break;case"IntlHash":this.handleKey(11,1,e);break;case"IntlBackslash":this.handleKey(-1,0,e);break;case"KeyZ":this.handleKey(0,0,e);break;case"KeyX":this.handleKey(1,0,e);break;case"KeyC":this.handleKey(2,0,e);break;case"KeyV":this.handleKey(3,0,e);break;case"KeyB":this.handleKey(4,0,e);break;case"KeyN":this.handleKey(5,0,e);break;case"KeyM":this.handleKey(6,0,e);break;case"Comma":this.handleKey(7,0,e);break;case"Period":this.handleKey(8,0,e);break;case"Slash":this.handleKey(9,0,e);break;case"IntlRo":this.handleKey(10,0,e);break;default:return}t.preventDefault()}handleKey(t,i,s){if(this.j.song.getChannelIsNoise(this.j.channel))return void(t>=0&&t<e.drumCount&&(s?(this.j.synth.preferLowerLatency=!0,this.j.performance.addPerformedPitch(t),this.io=!0):this.j.performance.removePerformedPitch(t)));const n=es.keyPosToPitch(this.j,t,i,this.j.prefs.keyboardLayout);null!=n&&(s?(this.j.synth.preferLowerLatency=!0,this.j.performance.addPerformedPitch(n),this.io=!0):this.j.performance.removePerformedPitch(n))}}es.no=[[0,2,4,5,7,9,11,12,14,16,17],[null,1,3,null,6,8,10,null,13,15,null,18],[12,14,16,17,19,21,23,24,26,28,29,31,33],[null,13,15,null,18,20,22,null,25,27,null,30,32]],es.oo=[[0,2,3,5,7,8,10,12,14,15,17],[-1,1,null,4,6,null,9,11,13,null,16,18],[12,14,15,17,19,20,22,24,26,27,29,31,32],[11,13,null,16,18,null,21,23,25,null,28,30,null]];class is{constructor(t){this.j=t,this.ro=D.div({style:"width: 100%; height: 100%; display: flex; flex-direction: column-reverse; align-items: stretch;"}),this.ho=D.div({style:"width: 100%; height: 100%; display: flex; flex-direction: column-reverse; align-items: stretch;"}),this.ao=D.div({style:`width: 100%; height: 40px; border: 2px solid ${$.primaryText}; position: absolute; box-sizing: border-box; pointer-events: none;`}),this.container=D.div({style:"width: 32px; height: 100%; overflow: hidden; position: relative; flex-shrink: 0; touch-action: none;"},this.ro,this.ho,this.ao),this.Qe=481,this.lo=[],this.co=[],this.ae=0,this.le=!1,this.ce=!1,this.uo=-1,this.fo=-1,this.Ne=!1,this.po=-1,this.do=-1,this.mo=[],this.Ke=t=>{this.ce||(this.ce=!0,this.ri())},this.Ye=t=>{this.ce&&(this.ce=!1,this.ri())},this.Je=t=>{t.preventDefault(),this.j.synth.maintainLiveInput(),this.le=!0;const e=this.container.getBoundingClientRect();this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.ae)&&(this.ae=0),this.yo(),this.bo(),this.ri()},this.Ze=t=>{(this.le||this.ce)&&this.j.synth.maintainLiveInput();const e=this.container.getBoundingClientRect();this.ae=((t.clientY||t.pageY)-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.ae)&&(this.ae=0),this.yo(),this.le&&this.bo(),this.ri()},this.Ys=t=>{this.le&&this.wo(),this.le=!1,this.ri()},this.Xe=t=>{t.preventDefault(),this.j.synth.maintainLiveInput(),this.le=!0;const e=this.container.getBoundingClientRect();this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.ae)&&(this.ae=0),this.yo(),this.bo()},this.ei=t=>{t.preventDefault(),this.j.synth.maintainLiveInput();const e=this.container.getBoundingClientRect();this.ae=(t.touches[0].clientY-e.top)*this.Qe/(e.bottom-e.top),isNaN(this.ae)&&(this.ae=0),this.yo(),this.le&&this.bo()},this.yn=t=>{t.preventDefault(),this.le=!1,this.wo()},this.vo=()=>{window.requestAnimationFrame(this.vo);let t=!1;const e=this.j.performance.pitchesAreTemporary()?0:this.j.synth.liveInputPitches.length;this.mo.length!=e&&(t=!0);for(let i=0;i<e;i++)this.mo[i]!=this.j.synth.liveInputPitches[i]&&(this.mo[i]=this.j.synth.liveInputPitches[i],t=!0);this.mo.length=e,t&&this.ri()},this.bn=()=>{const t=this.j.song.getChannelIsNoise(this.j.channel);if(this.gi=t?e.drumCount:this.j.getVisiblePitchCount(),this.re=this.Qe/this.gi,this.yo(),this.le&&this.bo(),this.j.prefs.showLetters&&(this.fo!=this.j.song.scale||this.po!=this.j.song.key||this.Ne!=t||this.do!=this.gi)){if(this.fo=this.j.song.scale,this.po=this.j.song.key,this.Ne=t,this.ro.style.display=t?"none":"flex",this.ho.style.display=t?"flex":"none",!t){if(this.do!=this.gi){this.ro.innerHTML="";for(let t=0;t<this.gi;t++){const e=D.div({class:"piano-label",style:"font-weight: bold; -webkit-text-stroke-width: 0; font-size: 11px; font-family: sans-serif; position: absolute; padding-left: 15px;"}),i=D.div({class:"piano-button",style:"background: gray;"},e);this.ro.appendChild(i),this.co[t]=e,this.lo[t]=i}this.co.length=this.gi,this.lo.length=this.gi,this.do=this.gi}for(let t=0;t<this.gi;t++){const i=(t+e.keys[this.j.song.key].basePitch)%e.pitchesPerOctave,s=e.keys[i].isWhiteKey;if(this.lo[t].style.background=s?$.whitePianoKey:$.blackPianoKey,e.scales[this.j.song.scale].flags[t%e.pitchesPerOctave]){this.lo[t].classList.remove("disabled"),this.co[t].style.display="";const s=this.co[t];s.style.color=e.keys[i].isWhiteKey?"black":"white",s.textContent=is.getPitchName(i,t)}else this.lo[t].classList.add("disabled"),this.co[t].style.display="none"}}this.ri()}};for(let t=0;t<e.drumCount;t++){const i=100*(1-t/e.drumCount*.35);this.ho.appendChild(D.div({class:"drum-button",style:`background-size: ${i}% ${i}%;`}))}this.container.addEventListener("mousedown",this.Je),document.addEventListener("mousemove",this.Ze),document.addEventListener("mouseup",this.Ys),this.container.addEventListener("mouseover",this.Ke),this.container.addEventListener("mouseout",this.Ye),this.container.addEventListener("touchstart",this.Xe),this.container.addEventListener("touchmove",this.ei),this.container.addEventListener("touchend",this.yn),this.container.addEventListener("touchcancel",this.yn),this.j.notifier.watch(this.bn),this.bn(),window.requestAnimationFrame(this.vo)}yo(){const t=e.scales[this.j.song.scale].flags,i=Math.max(0,Math.min(this.gi-1,this.gi-this.ae/this.re));if(t[Math.floor(i)%e.pitchesPerOctave]||this.j.song.getChannelIsNoise(this.j.channel))this.ko=Math.floor(i);else{let s=Math.floor(i)+1,n=Math.floor(i)-1;for(;!t[s%e.pitchesPerOctave];)s++;for(;!t[n%e.pitchesPerOctave];)n--;let o=s,r=n+1;s%e.pitchesPerOctave!=0&&s%e.pitchesPerOctave!=7||(o-=.5),n%e.pitchesPerOctave!=0&&n%e.pitchesPerOctave!=7||(r+=.5),this.ko=i-r>o-i?s:n}}bo(){const t=this.j.getBaseVisibleOctave(this.j.channel)*e.pitchesPerOctave,i=this.ko+t;this.uo!=i&&(this.j.performance.removePerformedPitch(this.uo),this.uo=i,this.j.performance.addPerformedPitch(i))}wo(){this.j.performance.removePerformedPitch(this.uo),this.uo=-1}ri(){if(this.ao.style.visibility=!this.ce||this.le?"hidden":"visible",this.ce&&!this.le){const t=this.container.getBoundingClientRect(),e=this.re/(this.Qe/(t.bottom-t.top));this.ao.style.left="0px",this.ao.style.top=e*(this.gi-this.ko-1)+"px",this.ao.style.height=e+"px"}const t=this.j.getBaseVisibleOctave(this.j.channel)*e.pitchesPerOctave,i=(this.j.song.getChannelIsNoise(this.j.channel)?this.ho:this.ro).children;for(let e=0;e<i.length;e++){const s=i[e];-1==this.mo.indexOf(e+t)?s.classList.remove("pressed"):s.classList.add("pressed")}}static getPitchName(t,i){let s;if(e.keys[t].isWhiteKey)s=e.keys[t].name;else{const n=e.blackKeyNameParents[i%e.pitchesPerOctave];s=e.keys[(t+e.pitchesPerOctave+n)%e.pitchesPerOctave].name,1==n?s+="♭":-1==n&&(s+="♯")}return s}}const{button:ss,div:ns,span:os,h2:rs,input:hs,br:as,select:ls,option:cs}=D;class us{constructor(t){this.j=t,this.Mo=hs({style:"width: 3em; margin-left: 1em;",type:"number",step:"1"}),this.xo=ls({style:"width: 100%;"},cs({value:"splice"},"Splice beats at end of bars."),cs({value:"stretch"},"Stretch notes to fit in bars."),cs({value:"overflow"},"Overflow notes across bars.")),this.Xs=ss({class:"cancelButton"}),this.Qs=ss({class:"okayButton",style:"width:45%;"},"Okay"),this.container=ns({class:"prompt noSelection",style:"width: 250px;"},rs("Beats Per Bar"),ns({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},ns({style:"text-align: right;"},"Beats per bar:",as(),os({style:`font-size: smaller; color: ${$.secondaryText};`},"(Multiples of 3 or 4 are recommended)")),this.Mo),ns({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},ns({class:"selectContainer",style:"width: 100%;"},this.xo)),ns({style:"display: flex; flex-direction: row-reverse; justify-content: space-between;"},this.Qs),this.Xs),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.Qs.removeEventListener("click",this.So),this.Xs.removeEventListener("click",this.K),this.Mo.removeEventListener("keypress",us.Fo),this.Mo.removeEventListener("blur",us.Po),this.container.removeEventListener("keydown",this.en)},this.en=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.So()},this.So=()=>{window.localStorage.setItem("beatCountStrategy",this.xo.value),this.j.prompt=null,this.j.record(new We(this.j,us.Io(this.Mo),this.xo.value),!0)},this.Mo.value=this.j.song.beatsPerBar+"",this.Mo.min=e.beatsPerBarMin+"",this.Mo.max=e.beatsPerBarMax+"";const i=window.localStorage.getItem("beatCountStrategy");null!=i&&(this.xo.value=i),this.Mo.select(),setTimeout((()=>this.Mo.focus())),this.Qs.addEventListener("click",this.So),this.Xs.addEventListener("click",this.K),this.Mo.addEventListener("keypress",us.Fo),this.Mo.addEventListener("blur",us.Po),this.container.addEventListener("keydown",this.en)}static Fo(t){const e=t.which?t.which:t.keyCode;return 46!=e&&e>31&&(e<48||e>57)&&(t.preventDefault(),!0)}static Po(t){const e=t.target;e.value=String(us.Io(e))}static Io(t){return Math.floor(Math.max(Number(t.min),Math.min(Number(t.max),Number(t.value))))}}const{button:fs,div:ps,span:ds,h2:ms,input:ys,br:gs,select:bs,option:ws}=D;class vs{constructor(t){this.j=t,this.Mo=ys({style:"width: 3em; margin-left: 1em;",type:"number",step:"0.01",value:"0"}),this.xo=bs({style:"width: 100%;"},ws({value:"overflow"},"Overflow notes across bars."),ws({value:"wrapAround"},"Wrap notes around within bars.")),this.Xs=fs({class:"cancelButton"}),this.Qs=fs({class:"okayButton",style:"width:45%;"},"Okay"),this.container=ps({class:"prompt noSelection",style:"width: 250px;"},ms("Move Notes Sideways"),ps({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},ps({style:"text-align: right;"},"Beats to move:",gs(),ds({style:`font-size: smaller; color: ${$.secondaryText};`},"(Negative is left, positive is right)")),this.Mo),ps({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},ps({class:"selectContainer",style:"width: 100%;"},this.xo)),ps({style:"display: flex; flex-direction: row-reverse; justify-content: space-between;"},this.Qs),this.Xs),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.Qs.removeEventListener("click",this.So),this.Xs.removeEventListener("click",this.K),this.Mo.removeEventListener("blur",vs.Po),this.container.removeEventListener("keydown",this.en)},this.en=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.So()},this.So=()=>{window.localStorage.setItem("moveNotesSidewaysStrategy",this.xo.value),this.j.prompt=null,this.j.record(new je(this.j,+this.Mo.value,this.xo.value),!0)},this.Mo.min=-this.j.song.beatsPerBar+"",this.Mo.max=this.j.song.beatsPerBar+"";const e=window.localStorage.getItem("moveNotesSidewaysStrategy");null!=e&&(this.xo.value=e),this.Mo.select(),setTimeout((()=>this.Mo.focus())),this.Qs.addEventListener("click",this.So),this.Xs.addEventListener("click",this.K),this.Mo.addEventListener("blur",vs.Po),this.container.addEventListener("keydown",this.en)}static Po(t){const i=t.target;let s=+i.value;s=Math.round(s*e.partsPerBeat)/e.partsPerBeat,s=Math.round(100*s)/100,i.value=Math.max(+i.min,Math.min(+i.max,s))+""}}const{button:ks,div:Ms,span:xs,h2:Ss,input:Fs,br:Ps,select:Is,option:Ts}=D;class qs{constructor(t){this.j=t,this.To=Fs({style:"width: 3em; margin-left: 1em;",type:"number",step:"1"}),this.qo=Is({style:"width: 100%;"},Ts({value:"end"},"Apply change at end of song."),Ts({value:"beginning"},"Apply change at beginning of song.")),this.Xs=ks({class:"cancelButton"}),this.Qs=ks({class:"okayButton",style:"width:45%;"},"Okay"),this.container=Ms({class:"prompt noSelection",style:"width: 250px;"},Ss("Song Length"),Ms({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},Ms({style:"display: inline-block; text-align: right;"},"Bars per song:",Ps(),xs({style:`font-size: smaller; color: ${$.secondaryText};`},"(Multiples of 4 are recommended)")),this.To),Ms({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},Ms({class:"selectContainer",style:"width: 100%;"},this.qo)),Ms({style:"display: flex; flex-direction: row-reverse; justify-content: space-between;"},this.Qs),this.Xs),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.Qs.removeEventListener("click",this.So),this.Xs.removeEventListener("click",this.K),this.To.removeEventListener("keypress",qs.Fo),this.To.removeEventListener("blur",qs.Po),this.container.removeEventListener("keydown",this.en)},this.en=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.So()},this.So=()=>{window.localStorage.setItem("barCountPosition",this.qo.value);const t=new zt;t.append(new Kt(this.j,qs.Io(this.To),"beginning"==this.qo.value)),this.j.prompt=null,this.j.record(t,!0)},this.To.value=this.j.song.barCount+"",this.To.min=e.barCountMin+"",this.To.max=e.barCountMax+"";const i=window.localStorage.getItem("barCountPosition");null!=i&&(this.qo.value=i),this.To.select(),setTimeout((()=>this.To.focus())),this.Qs.addEventListener("click",this.So),this.Xs.addEventListener("click",this.K),this.To.addEventListener("keypress",qs.Fo),this.To.addEventListener("blur",qs.Po),this.container.addEventListener("keydown",this.en)}static Fo(t){const e=t.which?t.which:t.keyCode;return 46!=e&&e>31&&(e<48||e>57)&&(t.preventDefault(),!0)}static Po(t){const e=t.target;e.value=String(qs.Io(e))}static Io(t){return Math.floor(Math.max(Number(t.min),Math.min(Number(t.max),Number(t.value))))}}const{button:Es,div:Cs,h2:Ls,p:zs,select:Ds,option:As}=D;class Bs{constructor(t){this.j=t,this.Eo=Ds({style:"width: 100%;"},As({value:"acoustic"},"(A) Acoustic"),As({value:"bright"},"(B) Bright")),this.Xs=Es({class:"cancelButton"}),this.Qs=Es({class:"okayButton",style:"width:45%;"},"Okay"),this.container=Cs({class:"prompt",style:"width: 300px;"},Cs(Ls("String Sustain"),zs("This setting controls how quickly the picked string vibration decays."),zs('Unlike most of BeepBox\'s instrument synthesizer features, a picked string cannot change frequency suddenly while maintaining its decay. If a tone\'s pitch changes suddenly (e.g. if the chord type is set to "arpeggio" or the transition type is set to "continues") then the string will be re-picked and start decaying from the beginning again, even if the envelopes don\'t otherwise restart.')),Cs({style:{display:e.enableAcousticSustain?void 0:"none"}},zs('BeepBox comes with two slightly different sustain designs. You can select one here and press "Okay" to confirm it.'),Cs({class:"selectContainer",style:"width: 100%;"},this.Eo)),Cs({style:{display:e.enableAcousticSustain?"flex":"none","flex-direction":"row-reverse","justify-content":"space-between"}},this.Qs),this.Xs),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.Qs.removeEventListener("click",this.So),this.Xs.removeEventListener("click",this.K),this.container.removeEventListener("keydown",this.en)},this.en=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.So()},this.So=()=>{if(e.enableAcousticSustain){const t=new zt;t.append(new we(this.j,e.sustainTypeNames.indexOf(this.Eo.value))),this.j.prompt=null,this.j.record(t,!0)}else this.K()};const i=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()];this.Eo.value=e.sustainTypeNames[i.stringSustainType],setTimeout((()=>this.Xs.focus())),this.Qs.addEventListener("click",this.So),this.Xs.addEventListener("click",this.K),this.container.addEventListener("keydown",this.en)}}const{button:Os,div:Ns,label:Rs,br:Hs,h2:Gs,input:$s}=D;class _s{constructor(t){this.j=t,this.Co=$s({style:"width: 3em; margin-left: 1em;",type:"number",step:"1"}),this.Lo=$s({style:"width: 3em; margin-left: 1em;",type:"number",step:"1"}),this.zo=$s({style:"width: 3em; margin-left: 1em;",type:"number",step:"1"}),this.Do=$s({style:"width: 3em; margin-left: 1em;",type:"checkbox"}),this.Ao=$s({style:"width: 3em; margin-left: 1em;",type:"checkbox"}),this.Xs=Os({class:"cancelButton"}),this.Qs=Os({class:"okayButton",style:"width:45%;"},"Okay"),this.container=Ns({class:"prompt noSelection",style:"width: 250px; text-align: right;"},Gs("Channel Settings"),Rs({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Pitch channels:",this.Lo),Rs({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Drum channels:",this.zo),Rs({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Available patterns per channel:",this.Co),Rs({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Simultaneous instruments",Hs(),"per channel:",this.Do),Rs({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Different instruments",Hs(),"per pattern:",this.Ao),Ns({style:"display: flex; flex-direction: row-reverse; justify-content: space-between;"},this.Qs),this.Xs),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.Qs.removeEventListener("click",this.So),this.Xs.removeEventListener("click",this.K),this.Co.removeEventListener("keypress",_s.Fo),this.Lo.removeEventListener("keypress",_s.Fo),this.zo.removeEventListener("keypress",_s.Fo),this.Co.removeEventListener("blur",this.Po),this.Lo.removeEventListener("blur",this.Po),this.zo.removeEventListener("blur",this.Po),this.container.removeEventListener("keydown",this.en)},this.en=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.So()},this.Po=t=>{const e=t.target;e.value=String(_s.Io(e))},this.So=()=>{const t=new zt;t.append(new Ce(this.j,this.Do.checked,this.Ao.checked)),t.append(new He(this.j,_s.Io(this.Co))),t.append(new Xt(this.j,_s.Io(this.Lo),_s.Io(this.zo))),this.j.prompt=null,this.j.record(t,!0)},this.Co.value=this.j.song.patternsPerChannel+"",this.Co.min="1",this.Co.max=e.barCountMax+"",this.Lo.value=this.j.song.pitchChannelCount+"",this.Lo.min=e.pitchChannelCountMin+"",this.Lo.max=e.pitchChannelCountMax+"",this.zo.value=this.j.song.noiseChannelCount+"",this.zo.min=e.noiseChannelCountMin+"",this.zo.max=e.noiseChannelCountMax+"",this.Do.checked=this.j.song.layeredInstruments,this.Ao.checked=this.j.song.patternInstruments,this.Lo.select(),setTimeout((()=>this.Lo.focus())),this.Qs.addEventListener("click",this.So),this.Xs.addEventListener("click",this.K),this.Co.addEventListener("keypress",_s.Fo),this.Lo.addEventListener("keypress",_s.Fo),this.zo.addEventListener("keypress",_s.Fo),this.Co.addEventListener("blur",this.Po),this.Lo.addEventListener("blur",this.Po),this.zo.addEventListener("blur",this.Po),this.container.addEventListener("keydown",this.en)}static Fo(t){const e=t.which?t.which:t.keyCode;return 46!=e&&e>31&&(e<48||e>57)&&(t.preventDefault(),!0)}static Io(t){return Math.floor(Math.max(Number(t.min),Math.min(Number(t.max),Number(t.value))))}}function Us(t,e){const i=new ArrayBuffer(e);let s=0,n=Math.min(t.byteLength,i.byteLength);const o=[8,4,2,1];for(const e of o)if(n>=e){const o=r(e,t,i,s,n);s=o.nextOffset,n=o.leftBytes}return i;function r(t,e,i,s,n){let o=Uint8Array;switch(t){case 8:o=Float64Array;break;case 4:o=Float32Array;break;case 2:o=Uint16Array;break;default:o=Uint8Array}const r=new o(e,s,n/t|0),h=new o(i,s,n/t|0);for(let t=0;t<h.length;t++)h[t]=r[t];return{nextOffset:r.byteOffset+r.byteLength,leftBytes:n-h.length*t}}}class Vs{constructor(t){this.Bo=0,this.Oo=0,this.No=new ArrayBuffer(t),this.Ro=new DataView(this.No)}Ho(t){this.Oo+=t,this.Oo>this.No.byteLength&&(this.No=Us(this.No,Math.max(2*this.No.byteLength,this.Oo)),this.Ro=new DataView(this.No))}getWriteIndex(){return this.Bo}rewriteUint32(t,e){this.Ro.setUint32(t,e>>>0,!1)}writeUint32(t){t>>>=0,this.Ho(4),this.Ro.setUint32(this.Bo,t,!1),this.Bo=this.Oo}writeUint24(t){t>>>=0,this.Ho(3),this.Ro.setUint8(this.Bo,t>>16&255),this.Ro.setUint8(this.Bo+1,t>>8&255),this.Ro.setUint8(this.Bo+2,255&t),this.Bo=this.Oo}writeUint16(t){t>>>=0,this.Ho(2),this.Ro.setUint16(this.Bo,t,!1),this.Bo=this.Oo}writeUint8(t){t>>>=0,this.Ho(1),this.Ro.setUint8(this.Bo,t),this.Bo=this.Oo}writeInt8(t){t|=0,this.Ho(1),this.Ro.setInt8(this.Bo,t),this.Bo=this.Oo}writeMidi7Bits(t){if((t>>>=0)>=128)throw new Error("7 bit value contained 8th bit!");this.Ho(1),this.Ro.setUint8(this.Bo,t),this.Bo=this.Oo}writeMidiVariableLength(t){if((t>>>=0)>268435455)throw new Error("writeVariableLength value too big.");let e=!1;for(let i=0;i<4;i++){const s=t>>>21-7*i&127;0==s&&3!=i||(e=!0),e&&this.writeUint8((3==i?0:128)|s)}}writeMidiAscii(t){this.writeMidiVariableLength(t.length);for(let e=0;e<t.length;e++){const i=t.charCodeAt(e);if(i>127)throw new Error("Trying to write unicode character as ascii.");this.writeUint8(i)}}toCompactArrayBuffer(){return Us(this.No,this.Oo)}}const{button:js,div:Ws,h2:Ks,input:Ys,select:Js,option:Qs}=D;function Xs(t,e,i){return t+i*(e-t)}function Zs(t,e){if(navigator.msSaveOrOpenBlob)return void navigator.msSaveOrOpenBlob(t,e);const i=document.createElement("a");if(null!=i.download){const s=URL.createObjectURL(t);setTimeout((function(){URL.revokeObjectURL(s)}),6e4),i.href=s,i.download=e,setTimeout((function(){i.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 tn{constructor(t){this.j=t,this.Go=Ys({type:"text",style:"width: 10em;",value:"BeepBox-Song",maxlength:250,autofocus:"autofocus"}),this.$o=Ys({type:"checkbox"}),this._o=Ys({style:"width: 2em;",type:"number",min:"1",max:"4",step:"1"}),this.Uo=Ys({type:"checkbox"}),this.Vo=Js({style:"width: 100%;"},Qs({value:"wav"},".wav"),Qs({value:"mp3"},".mp3"),Qs({value:"midi"},".mid"),Qs({value:"json"},".json (for any BeepBox version)"),Qs({value:"html"},".html (opens BeepBox)")),this.Xs=js({class:"cancelButton"}),this.jo=js({class:"exportButton",style:"width:45%;"},"Export"),this.container=Ws({class:"prompt noSelection",style:"width: 200px;"},Ks("Export Options"),Ws({style:"display: flex; flex-direction: row; align-items: center; justify-content: space-between;"},"File name:",this.Go),Ws({style:"display: table; width: 100%;"},Ws({style:"display: table-row;"},Ws({style:"display: table-cell;"},"Intro:"),Ws({style:"display: table-cell;"},"Loop Count:"),Ws({style:"display: table-cell;"},"Outro:")),Ws({style:"display: table-row;"},Ws({style:"display: table-cell; vertical-align: middle;"},this.$o),Ws({style:"display: table-cell; vertical-align: middle;"},this._o),Ws({style:"display: table-cell; vertical-align: middle;"},this.Uo))),Ws({style:"text-align: left;"},"File Type:"),Ws({class:"selectContainer",style:"width: 100%;"},this.Vo),Ws({style:"text-align: left;"},"(Be patient, exporting may take some time...)"),Ws({style:"display: flex; flex-direction: row-reverse; justify-content: space-between;"},this.jo),this.Xs),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.Go.removeEventListener("input",tn.Wo),this._o.removeEventListener("blur",tn.Po),this.jo.removeEventListener("click",this.Ko),this.Xs.removeEventListener("click",this.K),this.container.removeEventListener("keydown",this.en)},this.en=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.Ko()},this.Ko=()=>{switch(window.localStorage.setItem("exportFormat",this.Vo.value),this.Vo.value){case"wav":this.Yo();break;case"mp3":this.Jo();break;case"midi":this.Qo();break;case"json":this.Xo();break;case"html":this.Zo();break;default:throw new Error("Unhandled file export type.")}},this._o.value="1",0==this.j.song.loopStart?(this.$o.checked=!1,this.$o.disabled=!0):(this.$o.checked=!0,this.$o.disabled=!1),this.j.song.loopStart+this.j.song.loopLength==this.j.song.barCount?(this.Uo.checked=!1,this.Uo.disabled=!0):(this.Uo.checked=!0,this.Uo.disabled=!1);const e=window.localStorage.getItem("exportFormat");null!=e&&(this.Vo.value=e),this.Go.select(),setTimeout((()=>this.Go.focus())),this.Go.addEventListener("input",tn.Wo),this._o.addEventListener("blur",tn.Po),this.jo.addEventListener("click",this.Ko),this.Xs.addEventListener("click",this.K),this.container.addEventListener("keydown",this.en)}static Wo(t){const e=t.target,i=/[\+\*\$\?\|\{\}\\\/<>#%!`&'"=:@]/gi;if(i.test(e.value)){let t=e.selectionStart;e.value=e.value.replace(i,""),t--,e.setSelectionRange(t,t)}}static Po(t){const e=t.target;e.value=Math.floor(Math.max(Number(e.min),Math.min(Number(e.max),Number(e.value))))+""}tr(t){const e=new Ft(this.j.song);if(e.samplesPerSecond=t,e.loopRepeatCount=Number(this._o.value)-1,!this.$o.checked)for(let t=0;t<this.j.song.loopStart;t++)e.goToNextBar();const i=Math.ceil(e.getSamplesPerBar()*e.getTotalBars(this.$o.checked,this.Uo.checked)),s=new Float32Array(i),n=new Float32Array(i);return e.synthesize(s,n,i),{recordedSamplesL:s,recordedSamplesR:n}}Yo(){const t=48e3,{recordedSamplesL:e,recordedSamplesR:i}=this.tr(t),s=e.length,n=2*s;let o=0;const r=new ArrayBuffer(44+2*n),h=new DataView(r);h.setUint32(o,1380533830,!1),o+=4,h.setUint32(o,36+2*n,!0),o+=4,h.setUint32(o,1463899717,!1),o+=4,h.setUint32(o,1718449184,!1),o+=4,h.setUint32(o,16,!0),o+=4,h.setUint16(o,1,!0),o+=2,h.setUint16(o,2,!0),o+=2,h.setUint32(o,t,!0),o+=4,h.setUint32(o,192e3,!0),o+=4,h.setUint16(o,4,!0),o+=2,h.setUint16(o,16,!0),o+=2,h.setUint32(o,1684108385,!1),o+=4,h.setUint32(o,2*n,!0),o+=4;{const t=32767;for(let n=0;n<s;n++){let s=Math.floor(Math.max(-1,Math.min(1,e[n]))*t),r=Math.floor(Math.max(-1,Math.min(1,i[n]))*t);h.setInt16(o,s,!0),o+=2,h.setInt16(o,r,!0),o+=2}}Zs(new Blob([r],{type:"audio/wav"}),this.Go.value.trim()+".wav"),this.K()}Jo(){const t=()=>{const{recordedSamplesL:t,recordedSamplesR:e}=this.tr(44100),i=1152,s=new window.lamejs.Mp3Encoder(2,44100,192),n=[],o=new Int16Array(t.length),r=new Int16Array(e.length);for(let i=0;i<t.length;i++)o[i]=Math.floor(32767*Math.max(-1,Math.min(1,t[i]))),r[i]=Math.floor(32767*Math.max(-1,Math.min(1,e[i])));for(let t=0;t<o.length;t+=i){const e=o.subarray(t,t+i),h=r.subarray(t,t+i),a=s.encodeBuffer(e,h);a.length>0&&n.push(a)}const h=s.flush();h.length>0&&n.push(h);Zs(new Blob(n,{type:"audio/mp3"}),this.Go.value.trim()+".mp3"),this.K()};if("lamejs"in window)t();else{var e=document.createElement("script");e.src="https://cdn.jsdelivr.net/npm/[email protected]/lame.min.js",e.onload=t,document.head.appendChild(e)}}Qo(){const t=this.j.song,i=2*e.ticksPerPart*e.partsPerBeat,s=2*e.ticksPerPart,n=t.getBeatsPerMinute(),o=Math.round(6e7/n),r=i*t.beatsPerBar,a=24,l=[];if(this.$o.checked)for(let e=0;e<t.loopStart;e++)l.push(e);for(let e=0;e<Number(this._o.value);e++)for(let e=t.loopStart;e<t.loopStart+t.loopLength;e++)l.push(e);if(this.Uo.checked)for(let e=t.loopStart+t.loopLength;e<t.barCount;e++)l.push(e);const c=[{isMeta:!0,channel:-1,midiChannel:-1,isNoise:!1,isDrumset:!1}];let u=0,f=!1;for(let t=0;t<this.j.song.getChannelCount();t++)if(f||4!=this.j.song.channels[t].instruments[0].type){if(u>=16)continue;c.push({isMeta:!1,channel:t,midiChannel:u++,isNoise:this.j.song.getChannelIsNoise(t),isDrumset:!1}),9==u&&u++}else c.push({isMeta:!1,channel:t,midiChannel:9,isNoise:!0,isDrumset:!0}),f=!0;const p=new Vs(1024);p.writeUint32(1297377380),p.writeUint32(6),p.writeUint16(1),p.writeUint16(c.length),p.writeUint16(i);for(const n of c){p.writeUint32(1297379947);const{isMeta:c,channel:u,midiChannel:f,isNoise:m,isDrumset:y}=n,g=p.getWriteIndex();p.writeUint32(0);let b=0,w=0;const v=function(t){if(t<b)throw new Error("Midi event time cannot go backwards.");p.writeMidiVariableLength(t-b),b=t},k=function(t,e){if(!(e>=0&&e<=127))throw new Error("Midi control event value out of range: "+e);p.writeUint8(176|f),p.writeMidi7Bits(t),p.writeMidi7Bits(0|e)};if(c){v(0),p.writeUint8(255),p.writeMidi7Bits(1),p.writeMidiAscii("Composed with https://www.beepbox.co"),v(0),p.writeUint8(255),p.writeMidi7Bits(81),p.writeMidiVariableLength(3),p.writeUint24(o),v(0),p.writeUint8(255),p.writeMidi7Bits(88),p.writeMidiVariableLength(4),p.writeUint8(t.beatsPerBar),p.writeUint8(2),p.writeUint8(24),p.writeUint8(8);const i=e.scales[t.scale].flags[3]&&!e.scales[t.scale].flags[4],s=t.key;let n=s;for(1==(1&s)&&(n+=6),i&&(n+=9);n>6;)n-=12;v(0),p.writeUint8(255),p.writeMidi7Bits(89),p.writeMidiVariableLength(2),p.writeInt8(n),p.writeUint8(i?1:0),this.$o.checked&&(w+=r*t.loopStart),v(w),p.writeUint8(255),p.writeMidi7Bits(6),p.writeMidiAscii("Loop Start");for(let e=0;e<parseInt(this._o.value);e++)w+=r*t.loopLength,v(w),p.writeUint8(255),p.writeMidi7Bits(6),p.writeMidiAscii(e<Number(this._o.value)-1?"Loop Repeat":"Loop End");if(this.Uo.checked&&(w+=r*(t.barCount-t.loopStart-t.loopLength)),w!=r*l.length)throw new Error("Miscalculated number of bars.")}else{let n=$.getChannelColor(t,u).name+" channel";v(0),p.writeUint8(255),p.writeMidi7Bits(3),p.writeMidiAscii(n),v(0),k(101,0),v(0),k(100,0),v(0),k(6,a),v(0),k(38,0),v(0),k(101,127),v(0),k(100,127);let o=-1;function c(i){const s=t.channels[u].instruments[i],n=x.valueToPreset(s.preset);if(o!=i){if(o=i,v(w),p.writeUint8(255),p.writeMidi7Bits(4),p.writeMidiAscii("Instrument "+(i+1)),!y){let t=81;if(null!=n&&null!=n.midiProgram)t=n.midiProgram;else if(4==s.type)t=116;else if(2==s.type||3==s.type)t=m?116:75;else if(0==s.type)tn.midiChipInstruments.length>s.chipWave&&(t=tn.midiChipInstruments[s.chipWave]);else if(6==s.type||1==s.type||5==s.type||8==s.type)t=81;else{if(7!=s.type)throw new Error("Unrecognized instrument type.");t=25}v(w),p.writeUint8(192|f),p.writeMidi7Bits(t)}v(w);let t=(r=Ft.instrumentVolumeToVolumeMult(s.volume),127*Math.pow(.3844015376046128*r,.25));k(7,Math.min(127,Math.round(t))),v(w);let h=63*(s.pan/e.panCenter-1)+64;k(10,Math.min(127,Math.round(h)))}var r}null==t.getPattern(u,0)&&c(0);let g=Yi,b=127,M=!1;const S=m?e.spectrumBasePitch:e.keys[t.key].basePitch,F=m?e.noiseInterval:1;for(const n of l){const o=t.getPattern(u,n);if(null!=o){const n=o.instruments[0],r=t.channels[u].instruments[n],l=x.valueToPreset(r.preset);c(n);let P=r.getChord().arpeggiates,I=P?1:e.maxChordSize;r.getChord().customInterval&&(0==r.type||5==r.type?(I=2,P=!0):1==r.type?I=e.operatorCount:console.error("Unrecognized instrument type for harmonizing arpeggio: "+r.type));for(let n=0;n<o.notes.length;n++){const r=o.notes[n],c=w+r.start*s;let u=c,T=r.pins[0].size,q=r.pins[0].interval;const E=[-1,-1,-1,-1],C=[-1,-1,-1,-1],L=Math.min(I,r.pitches.length),z=y?Math.max(1,Math.round(90*r.pins[0].size/e.noteSizeMax)):90;let D=r.pickMainInterval(),A=D*F;if(!y){let t=a,e=-24;for(let i=1;i<r.pins.length;i++){const s=r.pins[i].interval*F;t=Math.min(t,s+a),e=Math.max(e,s-a)}A=Math.min(t,Math.max(e,A))}for(let n=1;n<r.pins.length;n++){const o=c+r.pins[n].time*s,M=r.pins[n].size,I=r.pins[n].interval,B=o-u;for(let n=0;n<B;n++){const o=u+n,O=Xs(T,M,n/B),N=Xs(q,I,n/B)*F-A,R=Math.max(0,Math.min(16383,Math.round(8192*(1+N/a)))),H=Math.min(127,Math.round((d=Ft.noteSizeToVolumeMult(O),127*Math.pow(d,.25))));R!=g&&(v(o),p.writeUint8(224|f),p.writeMidi7Bits(127&R),p.writeMidi7Bits(R>>7&127),g=R),H==b||y||(v(o),k(11,H),b=H);const G=o==c;for(let n=0;n<L;n++){let a=r.pitches[n];if(y){a+=D;const t=[36,41,45,48,40,39,59,49,46,55,69,54];if(a<0||a>=t.length)throw new Error("Could not find corresponding drumset pitch. "+a);a=t[a]}else{if(P&&r.pitches.length>n+1&&n==L-1){const l=(o-w)%i,c=e.rhythms[t.rhythm].ticksPerArpeggio*s/e.ticksPerPart,u=Math.floor(l/c);a=r.pitches[n+h(r.pitches.length-n,t.rhythm,u)]}a=S+a*F+A,null!=l&&null!=l.midiSubharmonicOctaves?a+=12*l.midiSubharmonicOctaves:m&&(a+=12*+x.presetCategories.dictionary["Drum Presets"].presets.dictionary["taiko drum"].midiSubharmonicOctaves),m&&(a*=2)}a=Math.max(0,Math.min(127,a)),C[n]=a,G||E[n]==C[n]||(v(o),p.writeUint8(128|f),p.writeMidi7Bits(E[n]),p.writeMidi7Bits(z))}for(let t=0;t<L;t++)(G||E[t]!=C[t])&&(v(o),p.writeUint8(144|f),p.writeMidi7Bits(C[t]),p.writeMidi7Bits(z),E[t]=C[t])}u=o,T=M,q=I}const B=w+r.end*s;for(let t=0;t<L;t++)v(B),p.writeUint8(128|f),p.writeMidi7Bits(E[t]),p.writeMidi7Bits(z);M=!0}}else M&&(M=!1,127!=b&&(b=127,v(w),k(11,b)),g!=Yi&&(g=Yi,v(w),p.writeUint8(224|f),p.writeMidi7Bits(127&g),p.writeMidi7Bits(g>>7&127)));w+=r}}v(w),p.writeUint8(255),p.writeMidi7Bits(47),p.writeMidiVariableLength(0),p.rewriteUint32(g,p.getWriteIndex()-g-4)}var d;Zs(new Blob([p.toCompactArrayBuffer()],{type:"audio/midi"}),this.Go.value.trim()+".mid"),this.K()}Xo(){const t=this.j.song.toJsonObject(this.$o.checked,Number(this._o.value),this.Uo.checked),e=JSON.stringify(t,null,"\t");Zs(new Blob([e],{type:"application/json"}),this.Go.value.trim()+".json"),this.K()}Zo(){const t=`<!DOCTYPE html><meta charset="utf-8">\n\nYou should be redirected to the song at:<br /><br />\n\n<a id="destination" href="${new URL("#"+this.j.song.toBase64String(),location.href).href}"></a>\n\n<style>\n\t:root {\n\t\tcolor: white;\n\t\tbackground: black;\n\t\tfont-family:\n\t\tsans-serif;\n\t}\n\ta {\n\t\tcolor: #98f;\n\t}\n\ta[href]::before {\n\t\tcontent: attr(href);\n\t}\n</style>\n\n<script>\n\tlocation.assign(document.querySelector("a#destination").href);\n<\/script>\n`;Zs(new Blob([t],{type:"text/html"}),this.Go.value.trim()+".html"),this.K()}}tn.midiChipInstruments=[74,71,80,70,68,81,81,81,81];class en{constructor(t){this.P=0,this.Ro=t}getReadIndex(){return this.P}readUint32(){if(this.P+4>this.Ro.byteLength)throw new Error("Reading past the end of the buffer.");const t=this.Ro.getUint32(this.P,!1);return this.P+=4,t}readUint24(){return this.readUint8()<<16|this.readUint8()<<8|this.readUint8()}readUint16(){if(this.P+2>this.Ro.byteLength)throw new Error("Reading past the end of the buffer.");const t=this.Ro.getUint16(this.P,!1);return this.P+=2,t}readUint8(){if(this.P+1>this.Ro.byteLength)throw new Error("Reading past the end of the buffer.");const t=this.Ro.getUint8(this.P);return this.P++,t}readInt8(){if(this.P+1>this.Ro.byteLength)throw new Error("Reading past the end of the buffer.");const t=this.Ro.getInt8(this.P);return this.P++,t}peakUint8(){if(this.P+1>this.Ro.byteLength)throw new Error("Reading past the end of the buffer.");return this.Ro.getUint8(this.P)}readMidi7Bits(){const t=this.readUint8();return t>=128&&console.log("7 bit value contained 8th bit! value "+t+", index "+this.P),127&t}readMidiVariableLength(){let t=0;for(let e=0;e<4;e++){const e=this.readUint8();if(t+=127&e,!(128&e))break;t<<=7}return t}skipBytes(t){this.P+=t}hasMore(){return this.Ro.byteLength>this.P}getReaderForNextBytes(t){if(this.P+t>this.Ro.byteLength)throw new Error("Reading past the end of the buffer.");const e=new en(new DataView(this.Ro.buffer,this.Ro.byteOffset+this.P,t));return this.skipBytes(t),e}}const{button:sn,p:nn,div:on,h2:rn,input:hn}=D;class an{constructor(t){this.j=t,this.Js=hn({type:"file",accept:".json,application/json,.mid,.midi,audio/midi,audio/x-midi"}),this.Xs=sn({class:"cancelButton"}),this.container=on({class:"prompt noSelection",style:"width: 300px;"},rn("Import"),nn({style:"text-align: left; margin: 0.5em 0;"},"BeepBox songs can be exported and re-imported as .json files. You could also use other means to make .json files for BeepBox as long as they follow the same structure."),nn({style:"text-align: left; margin: 0.5em 0;"},"BeepBox can also (crudely) import .mid files. There are many tools available for creating .mid files. Shorter and simpler songs are more likely to work well."),this.Js,this.Xs),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.Js.removeEventListener("change",this.er),this.Xs.removeEventListener("click",this.K)},this.er=()=>{const t=this.Js.files[0];if(!t)return;const e=t.name.slice(2+(t.name.lastIndexOf(".")-1>>>0)).toLowerCase();if("json"==e){const e=new FileReader;e.addEventListener("load",(t=>{this.j.prompt=null,this.j.goBackToStart(),this.j.record(new Xe(this.j,e.result),!0,!0)})),e.readAsText(t)}else if("midi"==e||"mid"==e){const e=new FileReader;e.addEventListener("load",(t=>{this.j.prompt=null,this.j.goBackToStart(),this.ir(e.result)})),e.readAsArrayBuffer(t)}else console.error("Unrecognized file extension."),this.K()},this.Js.select(),setTimeout((()=>this.Js.focus())),this.Js.addEventListener("change",this.er),this.Xs.addEventListener("click",this.K)}ir(t){const i=new en(new DataView(t));let s=null;const n=[];for(;i.hasMore();){const t=i.readUint32(),e=i.readUint32();if(1297377380==t)null==s?s=i.getReaderForNextBytes(e):console.error("This MIDI file has more than one header chunk.");else if(1297379947==t){const t=i.getReaderForNextBytes(e);t.hasMore()&&n.push({reader:t,nextEventMidiTick:t.readMidiVariableLength(),ended:!1,runningStatus:-1})}else i.skipBytes(e)}if(null==s)return console.error("No header chunk found in this MIDI file."),void this.K();const o=s.readUint16();s.readUint16();const r=s.readUint16();let h=0;const a=[],l=2==o;if(l)a.push(h);else for(let t=0;t<n.length;t++)a.push(t);const c=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255],u=[255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255],f=[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],d=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=[100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100],y=[64,64,64,64,64,64,64,64,64,64,64,64,64,64,64,64],g=[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]],b=[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]],w=[[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]];let v=5e5,k=8,M=0,S=!1,F=0;for(;;){let t=Number.MAX_VALUE,i=!1;for(const s of a){const o=n[s];for(;!o.ended&&o.nextEventMidiTick==F;){const s=128&o.reader.peakUint8()?o.reader.readUint8():o.runningStatus,r=240&s,x=15&s;240!=r&&(o.runningStatus=s);let I=!1;switch(r){case 128:{const t=o.reader.readMidi7Bits();o.reader.readMidi7Bits(),g[x].push({midiTick:F,pitch:t,velocity:0,program:-1,instrumentVolume:-1,instrumentPan:-1,on:!1})}break;case 144:{const t=o.reader.readMidi7Bits(),i=o.reader.readMidi7Bits();if(0==i)g[x].push({midiTick:F,pitch:t,velocity:0,program:-1,instrumentVolume:-1,instrumentPan:-1,on:!1});else{const s=Math.max(0,Math.min(e.volumeRange-1,Math.round(Ft.volumeMultToInstrumentVolume(Qi(m[x]))))),n=Math.max(0,Math.min(e.panMax,Math.round(((y[x]-64)/63+1)*e.panCenter)));g[x].push({midiTick:F,pitch:t,velocity:Math.max(0,Math.min(1,(i+14)/90)),program:d[x],instrumentVolume:s,instrumentPan:n,on:!0})}}break;case 160:o.reader.readMidi7Bits(),o.reader.readMidi7Bits();break;case 176:{const t=o.reader.readMidi7Bits(),e=o.reader.readMidi7Bits();switch(t){case 6:0==c[x]&&0==u[x]&&(f[x]=e);break;case 7:m[x]=e;break;case 10:y[x]=e;break;case 11:w[x].push({midiTick:F,size:Ft.volumeMultToNoteSize((P=e,Math.pow(P/127,4)))});break;case 38:0==c[x]&&0==u[x]&&(p[x]=e);break;case 100:u[x]=e;break;case 101:c[x]=e}}break;case 192:{const t=o.reader.readMidi7Bits();d[x]=t}break;case 208:o.reader.readMidi7Bits();break;case 224:{const t=o.reader.readMidi7Bits(),e=((o.reader.readMidi7Bits()<<7|t)/8192-1)*(f[x]+.01*p[x]);b[x].push({midiTick:F,interval:e})}break;case 240:if(255==s){const t=o.reader.readMidi7Bits(),i=o.reader.readMidiVariableLength();if(47==t)I=!0,o.reader.skipBytes(i);else if(81==t)v=o.reader.readUint24(),o.reader.skipBytes(i-3);else if(88==t){const t=o.reader.readUint8();let s=o.reader.readUint8();for(o.reader.readUint8(),o.reader.readUint8(),o.reader.skipBytes(i-4),k=4*t;0==(1&k)&&(s>0||k>e.beatsPerBarMax)&&k>=2*e.beatsPerBarMin;)k>>=1,s-=1;k=Math.max(e.beatsPerBarMin,Math.min(e.beatsPerBarMax,k))}else 89==t?(M=o.reader.readInt8(),S=1==o.reader.readUint8(),o.reader.skipBytes(i-2)):o.reader.skipBytes(i)}else{if(240!=s&&247!=s)return console.error("Unrecognized event status: "+s),void this.K();{const t=o.reader.readMidiVariableLength();o.reader.skipBytes(t)}}break;default:return console.error("Unrecognized event type: "+r),void this.K()}!I&&o.reader.hasMore()?o.nextEventMidiTick=F+o.reader.readMidiVariableLength():(o.ended=!0,l&&(h++,h<n.length&&(a[0]=h,n[h].nextEventMidiTick+=F,t=Math.min(t,n[h].nextEventMidiTick),i=!0)))}o.ended||(i=!0,t=Math.min(t,o.nextEventMidiTick))}if(!i)break;F=t}var P;const I=Math.max(e.tempoMin,Math.min(e.tempoMax,Math.round(6e7/v))),T=r/e.partsPerBeat,q=e.partsPerBeat*k,E=Math.ceil(F/T/q);function C(t){return Math.round(t/T)}let L=M;for(S&&(L+=3),1==(1&L)&&(L+=6);L<0;)L+=12;L%=12;const z=[],D=[];for(let t=0;t<16;t++){if(0==g[t].length)continue;const i=new bt,s=x.midiProgramToPresetValue(g[t][0].program),n=null==s?null:x.valueToPreset(s),o=9==t,h=o||null!=n&&1==n.isNoise,a=h?e.spectrumBasePitch:e.keys[L].basePitch,l=h?e.noiseInterval:1,c=h?.5:1,u=h?e.drumCount-1:e.maxPitch;h?o?D.unshift(i):D.push(i):z.push(i);let f=1,p=0,d=0,m=e.panCenter;if(o){const s=[];let n=-1,o=null,r=0,h=!1;const a=x.nameToPresetValue("standard drumset"),l=x.valueToPreset(a),c=new gt(!1);c.fromJsonObject(l.settings,!1,1),c.preset=a,i.instruments.push(c);for(let a=0;a<=g[t].length;a++){const l=a==g[t].length?null:g[t][a],p=null==l?Number.MAX_SAFE_INTEGER:C(l.midiTick);if(s.length>0&&p>r&&(null==l||l.on)){const t=Math.floor(r/q),a=t*q;if(n!=t||null==o){for(n++;n<t;)i.bars[n]=0,n++;o=new at,i.patterns.push(o),i.bars[n]=i.patterns.length,o.instruments[0]=0,o.instruments.length=1}(!h||c.volume>d)&&(c.volume=d,c.pan=m,h=!0);const l=[];let y=u,g=0,b=1;for(const t of s){const e=Ji[t];-1==l.indexOf(e.frequency)&&l.push(e.frequency),b=Math.max(b,Math.round(e.volume*f)),y=Math.min(y,e.duration),g=Math.max(g,e.duration)}const w=Math.min(g,Math.max(y,2)),v=r-a,k=Math.min(q,Math.min(p-a,v+6*w)),M=new ht(-1,v,k,b,!0);M.pitches.length=0;for(let t=0;t<Math.min(e.maxChordSize,l.length);t++){const i=l[t+Math.max(0,l.length-e.maxChordSize)];-1==M.pitches.indexOf(i)&&M.pitches.push(i)}o.notes.push(M),s.length=0}null!=l&&l.on&&null!=Ji[l.pitch]&&(s.push(l.pitch),r=p,f=l.velocity,d=l.instrumentVolume,m=l.instrumentPan)}}else{let s=0,n=e.noteSizeMax,o=0,y=0;function v(e){for(;o<b[t].length&&b[t][o].midiTick<=e;)s=b[t][o].interval,o++}function M(e){for(;y<w[t].length&&w[t][y].midiTick<=e;)n=w[t][y].size,y++}const S=[],F=[];let P=-1,I=null,E=0,L=0,z=0,D=0;for(let o of g[t]){const t=o.midiTick,y=C(t);if(F.length>0&&y>L){const o=Math.floor(L/q),g=Math.ceil(y/q);let b=!1;for(let w=o;w<g;w++){const o=w*q,g=w*k*r,C=(w+1)*k*r,A=Math.max(0,L-o),B=Math.min(q,y-o),O=Math.max(g,E),N=Math.min(C,t);if(A<B){const t=x.midiProgramToPresetValue(p),r=null==t?null:x.valueToPreset(t);if(P!=w||null==I){for(P++;P<w;)i.bars[P]=0,P++;if(I=new at,i.patterns.push(I),i.bars[P]=i.patterns.length,null==S[p]){const e=new gt(h);S[p]=e,null!=t&&null!=r&&1==r.isNoise==h?(e.fromJsonObject(r.settings,h,1),e.preset=t):(e.setTypeAndReset(h?2:0,h),e.chord=0),e.volume=d,e.pan=m,i.instruments.push(e)}I.instruments[0]=i.instruments.indexOf(S[p]),I.instruments.length=1}null!=S[p]&&(S[p].volume=Math.min(S[p].volume,d),S[p].pan=Math.min(S[p].pan,m));const y=new ht(-1,A,B,e.noteSizeMax,!1);y.pins.length=0,y.continuesLastPattern=b&&0==A,b=!0,v(O),M(O);const g=F[0]*c-a,k=Math.round((g+s)/l),q=Math.round(s-a);let E=rt(0,0,Math.round(f*n));y.pins.push(E);const C=[{part:0,pitch:k,size:E.size,keyPitch:!1,keySize:!1}];let L=0,R=(g+s)/l,H=f*n;for(let t=A+1;t<=B;t++){const e=Math.max(O,Math.min(N-1,Math.round(T*(t+o)))),i=t-A,r=t==B;v(e),M(e);const h=(s+g)/l,a=f*n,c=Math.round(h),u=Math.abs(h-c)<.01,p=Math.abs(R-Math.round(R))<.01?Math.abs(h-R)>=1:Math.floor(h)!=Math.floor(R),d=u||p,m=Math.round(a),b=Math.abs(a-m)<.01,w=Math.abs(H-Math.round(H))?Math.abs(a-H)>=1:Math.floor(a)!=Math.floor(H),x=b||w;if(R=h,H=a,d||x||r){const t={part:i,pitch:c,size:m,keyPitch:d||r,keySize:x||r},e=C[L];let s=!1,n=Number.MAX_VALUE;if(t.keyPitch){const i=(t.pitch-e.pitch)/(t.part-e.part);let o=Math.abs(i),r=!1,h=Number.MAX_VALUE;for(let t=L+1;t<C.length;t++){const s=C[t];if(s.keyPitch){const n=e.pitch+i*(s.part-e.part),a=Math.abs(n-s.pitch);o<a&&(o=a,r=!0,h=t)}}r&&(s=!0,n=Math.min(n,h))}if(t.keySize){const i=(t.size-e.size)/(t.part-e.part);let o=Math.abs(i),r=!1,h=Number.MAX_VALUE;for(let t=L+1;t<C.length;t++){const s=C[t];if(s.keySize){const n=e.size+i*(s.part-e.part),a=Math.abs(n-s.size);o<a&&(o=a,r=!0,h=t)}}r&&(s=!0,n=Math.min(n,h))}if(s){const t=C[n];y.pins.push(rt(t.pitch-k,t.part,t.size)),L=n}C.push(t)}}const G=C[C.length-1];y.pins.push(rt(G.pitch-k,G.part,G.size));let $=u,_=0;for(const t of y.pins)$=Math.min($,u-t.interval),_=Math.min(_,-t.interval);y.pitches.length=0;for(let t=0;t<Math.min(e.maxChordSize,F.length);t++){let i=F[t+Math.max(0,F.length-e.maxChordSize)]*c;null!=r&&null!=r.midiSubharmonicOctaves&&(i-=12*r.midiSubharmonicOctaves);const s=Math.max(_,Math.min($,Math.round((i+q)/l)));if(-1==y.pitches.indexOf(s)){y.pitches.push(s);const t=y.end-y.start;z+=s*t,D+=t}}I.notes.push(y)}}}-1!=F.indexOf(o.pitch)&&F.splice(F.indexOf(o.pitch),1),o.on&&(F.push(o.pitch),f=o.velocity,p=o.program,d=o.instrumentVolume,m=o.instrumentPan),E=t,L=y}const A=z/D;i.octave=h?0:Math.max(0,Math.min(e.pitchOctaves-1,Math.floor(A/12)))}for(;i.bars.length<E;)i.bars.push(0)}function A(t,e){for(;t.length>e;){let e=t.length-2,i=t.length-1,s=Number.MAX_VALUE,n=Number.MAX_VALUE;for(let o=0;o<t.length-1;o++)for(let r=o+1;r<t.length;r++){const h=t[o],a=t[r];let l=0,c=0;for(let t=0;t<h.bars.length&&t<a.bars.length;t++)0!=h.bars[t]&&0!=a.bars[t]&&l++,0==h.bars[t]&&0==a.bars[t]&&c++;l<=s&&(l<s||c<n)&&(e=o,i=r,s=l,n=c)}const o=t[e],r=t[i],h=o.instruments.length,a=o.patterns.length;for(const t of r.instruments)o.instruments.push(t);for(const t of r.patterns)t.instruments[0]+=h,o.patterns.push(t);for(let t=0;t<o.bars.length&&t<r.bars.length;t++)0==o.bars[t]&&0!=r.bars[t]&&(o.bars[t]=r.bars[t]+a);t.splice(i,1)}}A(z,e.pitchChannelCountMax),A(D,e.noiseChannelCountMax);this.j.goBackToStart();for(const t of this.j.song.channels)t.muted=!1;this.j.prompt=null,this.j.record(new class extends zt{constructor(t){super();const e=t.song;e.tempo=I,e.beatsPerBar=k,e.key=L,e.scale=11,e.rhythm=1,e.layeredInstruments=!1,e.patternInstruments=z.some((t=>t.instruments.length>1))||D.some((t=>t.instruments.length>1)),ii(z),ii(D),this.append(new ti(t,z,D)),e.loopStart=0,e.loopLength=e.barCount,this.J(),t.notifier.changed()}}(this.j),!0,!0)}}const ln="songVersion: ";function cn(t){return JSON.parse(t.substring(ln.length))}function un(t){return ln+JSON.stringify(t)}function fn(){return(Math.random()*(-1>>>0)>>>0).toString(32)}function pn(t){console.warn(t),window.alert('Whoops, the song data appears to have been corrupted! Please try to recover the last working version of the song from the "Recover Recent Song..." option in BeepBox\'s "File" menu.')}function dn(t,e){return e.versions[0].time-t.versions[0].time}function mn(t,e){return e.time-t.time}class yn{constructor(){this.sr=new wt}static getAllRecoveredSongs(){const t=[],e={};for(let i=0;i<localStorage.length;i++){const s=localStorage.key(i);if(0==s.indexOf(ln)){const i=cn(s);let n=e[i.uid];null==n&&(n={versions:[]},e[i.uid]=n,t.push(n)),n.versions.push(i)}}for(const e of t)e.versions.sort(mn);return t.sort(dn),t}saveVersion(t,e){const i=Math.round(Date.now());clearTimeout(this.nr),this.nr=setTimeout((()=>{try{this.sr.fromBase64String(e)}catch(t){return void pn(t)}const s=yn.getAllRecoveredSongs();let n=null;for(const e of s)e.versions[0].uid==t&&(n=e);null==n&&(n={versions:[]},s.unshift(n));let o=n.versions,r=1e3;if(o.length>0){const t=o[0].time;r=o[0].work+Math.min(18e4,i-t)}const h={uid:t,time:i,work:r},a=un(h);o.unshift(h),localStorage.setItem(a,e);let l=6e4;const c=Math.pow(2,.5);for(var u=1;u<o.length;u++){if(o[u].work-(u==o.length-1?0:o[u+1].work)<l){let t=u;if(u<o.length-1){const e=o[u].time,i=o[u-1].time;e-o[u+1].time<.5*(i-e)&&(t=u+1)}localStorage.removeItem(un(o[t]));break}l*=c}for(;s.length>8;){let t=null,e=Number.POSITIVE_INFINITY;for(let n=Math.round(4);n<s.length;n++){const o=s[n],r=1/((i-o.versions[0].time)/432e5+1),h=(o.versions[0].work+3e5)*r;e>h&&(e=h,t=o)}for(const e of t.versions)localStorage.removeItem(un(e));s.splice(s.indexOf(t),1)}}),750)}}const{button:gn,div:bn,h2:wn,p:vn,select:kn,option:Mn,iframe:xn}=D;class Sn{constructor(t){this.j=t,this.rr=bn(),this.Xs=gn({class:"cancelButton"}),this.container=bn({class:"prompt",style:"width: 300px;"},wn("Song Recovery"),bn({style:"max-height: 385px; overflow-y: auto;"},vn("This is a TEMPORARY list of songs you have recently modified. Please keep your own backups of songs you care about!"),this.rr,vn('(If "Display Song Data in URL" is enabled in your preferences, then you may also be able to find song versions in your browser history. However, song recovery won\'t work if you were browsing in private/incognito mode.)')),this.Xs),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.Xs.removeEventListener("click",this.K)},this.Xs.addEventListener("click",this.K);const e=yn.getAllRecoveredSongs();0==e.length&&this.rr.appendChild(vn("There are no recovered songs available yet. Try making a song!"));for(const t of e){const e=kn({style:"width: 100%;"});for(const i of t.versions)e.appendChild(Mn({value:i.time},new Date(i.time).toLocaleString()));const i=xn({style:"width: 100%; height: 60px; border: none; display: block;"});i.src="player/#song="+window.localStorage.getItem(un(t.versions[0]));const s=bn({style:"margin: 4px 0;"},bn({class:"selectContainer",style:"width: 100%; margin: 2px 0;"},e),i);this.rr.appendChild(s),e.addEventListener("change",(()=>{const s=t.versions[e.selectedIndex];i.contentWindow.location.replace("player/#song="+window.localStorage.getItem(un(s))),i.contentWindow.dispatchEvent(new Event("hashchange"))}))}}}const{button:Fn,label:Pn,div:In,p:Tn,a:qn,h2:En,input:Cn,select:Ln,option:zn}=D;class Dn{constructor(t){this.j=t,this.hr=Ln({style:"width: 100%;"},zn({value:"useCapsLockForNotes"},"simple shortcuts, use caps lock to play notes"),zn({value:"pressControlForShortcuts"},"simple notes, press "+x.ctrlName+" for shortcuts")),this.ar=Ln({style:"width: 100%;"},zn({value:"wickiHayden"},"Wicki-Hayden"),zn({value:"songScale"},"selected song scale"),zn({value:"pianoAtC"},"piano starting at C :)"),zn({value:"pianoAtA"},"piano starting at A :("),zn({value:"pianoTransposingC"},"piano transposing C :) to song key"),zn({value:"pianoTransposingA"},"piano transposing A :( to song key")),this.lr=In({style:"display: grid; row-gap: 4px; margin: 4px auto; font-size: 10px;"}),this.cr=Cn({style:"width: 2em; margin-left: 1em;",type:"checkbox"}),this.ur=Cn({style:"width: 2em; margin-left: 1em;",type:"checkbox"}),this.pr=Cn({style:"width: 2em; margin-left: 1em;",type:"checkbox"}),this.dr=Cn({style:"width: 2em; margin-left: 1em;",type:"checkbox"}),this.mr=Cn({style:"width: 2em; margin-left: 1em;",type:"checkbox"}),this.yr=Cn({style:"width: 2em; margin-left: 1em;",type:"checkbox"}),this.Qs=Fn({class:"okayButton",style:"width:45%;"},"Okay"),this.Xs=Fn({class:"cancelButton"}),this.container=In({class:"prompt noSelection recordingSetupPrompt",style:"width: 333px; text-align: right; max-height: 90%;"},En("Note Recording Setup"),In({style:"display: grid; overflow-y: auto; overflow-x: hidden; flex-shrink: 1;"},Tn("BeepBox can record notes as you perform them. You can start recording by pressing Ctrl+Space (or "+x.ctrlSymbol+"P)."),Pn({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Add ● record button next to ▶ play button:",this.ur),Pn({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Snap recorded notes to the song's rhythm:",this.pr),Pn({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Ignore notes not in the song's scale:",this.dr),Tn("While recording, you can perform notes on your keyboard!"),Pn({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Keyboard layout:",In({class:"selectContainer",style:"width: 65%; margin-left: 1em;"},this.ar)),this.lr,Tn("When not recording, you can use the computer keyboard either for shortcuts (like C and V for copy and paste) or for performing notes, depending on this mode:"),Pn({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},In({class:"selectContainer",style:"width: 100%;"},this.hr)),Tn("Performing music takes practice! Try slowing the tempo and using this metronome to help you keep a rhythm."),Pn({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Hear metronome while recording:",this.yr),Pn({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Count-in 1 bar of metronome before recording:",this.mr),Tn("If you have a ",qn({href:"https://caniuse.com/midi",target:"_blank"},"compatible browser")," on a device connected to a MIDI keyboard, you can use it to perform notes in BeepBox! (Or you could buy ",qn({href:"https://imitone.com/",target:"_blank"},"Imitone")," or ",qn({href:"https://vochlea.com/",target:"_blank"},"Dubler")," to hum notes into a microphone while wearing headphones!)"),Pn({style:"display: flex; flex-direction: row; align-items: center; height: 2em; justify-content: flex-end;"},"Enable MIDI performance:",this.cr),Tn("The range of pitches available to play via your computer keyboard is affected by the octave scrollbar of the currently selected channel."),Tn('Recorded notes often overlap such that one note ends after the next note already started. In BeepBox, these notes get split into multiple notes which may sound different when re-played than they did when you were recording. To fix the sound, you can either manually clean up the notes in the pattern editor, or you could try enabling the "transition type" effect on the instrument and setting it to "continue".'),In({style:`width: 100%; height: 80px; background: linear-gradient(rgba(0,0,0,0), ${$.editorBackground}); position: sticky; bottom: 0; pointer-events: none;`})),In({style:"display: flex; flex-direction: row-reverse; justify-content: space-between;"},this.Qs),this.Xs),this.K=()=>{this.j.undo()},this.cleanUp=()=>{this.Qs.removeEventListener("click",this.tn),this.Xs.removeEventListener("click",this.K),this.container.removeEventListener("keydown",this.en)},this.en=t=>{"BUTTON"!=t.target.tagName&&13==t.keyCode&&this.tn()},this.tn=()=>{this.j.prefs.pressControlForShortcuts="pressControlForShortcuts"==this.hr.value,this.j.prefs.keyboardLayout=this.ar.value,this.j.prefs.enableMidi=this.cr.checked,this.j.prefs.showRecordButton=this.ur.checked,this.j.prefs.snapRecordedNotesToRhythm=this.pr.checked,this.j.prefs.ignorePerformedNotesNotInScale=this.dr.checked,this.j.prefs.metronomeCountIn=this.mr.checked,this.j.prefs.metronomeWhileRecording=this.yr.checked,this.j.prefs.save(),this.K()},this.gr=()=>{for(;this.lr.firstChild;)this.lr.removeChild(this.lr.firstChild);const t=[12,12,11,10],i=e.scales[this.j.song.scale].flags;for(let s=0;s<4;s++){const n=In({style:"display: flex;"});this.lr.appendChild(n);const o=In({style:"width: "+12*s+"px; height: 20px; flex-shrink: 0;"});n.appendChild(o);for(let o=0;o<t[s];o++){const t=In({style:"width: 20px; height: 20px; margin: 0 2px; box-sizing: border-box; flex-shrink: 0; display: flex; justify-content: center; align-items: center;"});n.appendChild(t);const r=es.keyPosToPitch(this.j,o,3-s,this.ar.value);if(null!=r){const s=r%12;i[s]?0==s?t.style.background=$.tonic:7==s&&this.j.prefs.showFifth?t.style.background=$.fifthNote:t.style.background=$.pitchBackground:t.style.border="2px solid "+$.pitchBackground;const n=(s+e.keys[this.j.song.key].basePitch)%e.pitchesPerOctave;t.textContent=is.getPitchName(n,s)}}}},this.hr.value=this.j.prefs.pressControlForShortcuts?"pressControlForShortcuts":"useCapsLockForNotes",this.ar.value=this.j.prefs.keyboardLayout,this.cr.checked=this.j.prefs.enableMidi,this.ur.checked=this.j.prefs.showRecordButton,this.pr.checked=this.j.prefs.snapRecordedNotesToRhythm,this.dr.checked=this.j.prefs.ignorePerformedNotesNotInScale,this.mr.checked=this.j.prefs.metronomeCountIn,this.yr.checked=this.j.prefs.metronomeWhileRecording,setTimeout((()=>this.ur.focus())),this.Qs.addEventListener("click",this.tn),this.Xs.addEventListener("click",this.K),this.container.addEventListener("keydown",this.en),this.gr(),this.ar.addEventListener("change",this.gr)}}const{a:An,button:Bn,div:On,input:Nn,select:Rn,span:Hn,optgroup:Gn,option:$n}=D;function _n(t,e){for(let i=0;i<e.length;i++)t.appendChild($n({value:i},e[i]));return t}function Un(t){const e=Rn();e.appendChild(Gn({label:"Edit"},$n({value:"copyInstrument"},"Copy Instrument (⇧C)"),$n({value:"pasteInstrument"},"Paste Instrument (⇧V)"),$n({value:"randomPreset"},"Random Preset (R)"),$n({value:"randomGenerated"},"Random Generated (⇧R)")));const i=Gn({label:x.presetCategories[0].name});t?(i.appendChild($n({value:2},x.valueToPreset(2).name)),i.appendChild($n({value:3},x.valueToPreset(3).name)),i.appendChild($n({value:4},x.valueToPreset(4).name))):(i.appendChild($n({value:0},x.valueToPreset(0).name)),i.appendChild($n({value:6},x.valueToPreset(6).name)),i.appendChild($n({value:8},x.valueToPreset(8).name)),i.appendChild($n({value:5},x.valueToPreset(5).name)),i.appendChild($n({value:7},x.valueToPreset(7).name)),i.appendChild($n({value:3},x.valueToPreset(3).name)),i.appendChild($n({value:1},x.valueToPreset(1).name))),e.appendChild(i);for(let i=1;i<x.presetCategories.length;i++){const s=x.presetCategories[i],n=Gn({label:s.name});let o=!1;for(let e=0;e<s.presets.length;e++){const r=s.presets[e];1==r.isNoise==t&&(n.appendChild($n({value:(i<<6)+e},r.name)),o=!0)}o&&e.appendChild(n)}return e}function Vn(t,e){const i=e.toString();t.value!=i&&(t.value=i)}class jn{constructor(t,e,i){this.input=t,this.j=e,this.wr=i,this.an=null,this.vr=0,this.kr=0,this.Mr=()=>{this.j.lastChangeWas(this.an)||(this.kr=this.vr),this.an=this.wr(this.kr,parseInt(this.input.value)),this.j.setProspectiveChange(this.an)},this.Sr=()=>{this.j.record(this.an),this.an=null},t.addEventListener("input",this.Mr),t.addEventListener("change",this.Sr)}updateValue(t){this.vr=t,this.input.value=String(t)}}class Wn{constructor(t){this.j=t,this.prompt=null,this.ar=new es(this.j),this.Fr=new qi(this.j,!1,-1),this.Pr=new qi(this.j,!0,0),this.Ir=new qi(this.j,!1,1),this.Tr=new Ai(this.j),this.qr=new Bi(this.j),this.Er=new Ui(this.j),this.Cr=new Ki(this.j),this.Lr=new is(this.j),this.zr=Bn({class:"playButton",type:"button",title:"Play (Space)"},Hn("Play")),this.Dr=Bn({class:"pauseButton",style:"display: none;",type:"button",title:"Pause (Space)"},"Pause"),this.Ar=Bn({class:"recordButton",style:"display: none;",type:"button",title:"Record (Ctrl+Space)"},Hn("Record")),this.Br=Bn({class:"stopButton",style:"display: none;",type:"button",title:"Stop Recording (Space)"},"Stop Recording"),this.Or=Bn({class:"prevBarButton",type:"button",title:"Previous Bar (left bracket)"}),this.Nr=Bn({class:"nextBarButton",type:"button",title:"Next Bar (right bracket)"}),this.Rr=Nn({title:"main volume",style:"width: 5em; flex-grow: 1; margin: 0;",type:"range",min:"0",max:"75",value:"50",step:"1"}),this.Hr=Rn({style:"width: 100%;"},$n({selected:!0,disabled:!0,hidden:!1},"File"),$n({value:"new"},"+ New Blank Song"),$n({value:"import"},"↑ Import Song... ("+x.ctrlSymbol+"O)"),$n({value:"export"},"↓ Export Song... ("+x.ctrlSymbol+"S)"),$n({value:"copyUrl"},"⎘ Copy Song URL"),$n({value:"shareUrl"},"⤳ Share Song URL"),$n({value:"shortenUrl"},"… Shorten Song URL"),$n({value:"viewPlayer"},"▶ View in Song Player"),$n({value:"copyEmbed"},"⎘ Copy HTML Embed Code"),$n({value:"songRecovery"},"⚠ Recover Recent Song...")),this.Gr=Rn({style:"width: 100%;"},$n({selected:!0,disabled:!0,hidden:!1},"Edit"),$n({value:"undo"},"Undo (Z)"),$n({value:"redo"},"Redo (Y)"),$n({value:"copy"},"Copy Pattern (C)"),$n({value:"pasteNotes"},"Paste Pattern Notes (V)"),$n({value:"pasteNumbers"},"Paste Pattern Numbers ("+x.ctrlSymbol+"⇧V)"),$n({value:"insertBars"},"Insert Bar (⏎)"),$n({value:"deleteBars"},"Delete Selected Bars (⌫)"),$n({value:"insertChannel"},"Insert Channel ("+x.ctrlSymbol+"⏎)"),$n({value:"deleteChannel"},"Delete Selected Channels ("+x.ctrlSymbol+"⌫)"),$n({value:"selectAll"},"Select All (A)"),$n({value:"selectChannel"},"Select Channel (⇧A)"),$n({value:"duplicatePatterns"},"Duplicate Reused Patterns (D)"),$n({value:"transposeUp"},"Move Notes Up (+ or ⇧+)"),$n({value:"transposeDown"},"Move Notes Down (- or ⇧-)"),$n({value:"moveNotesSideways"},"Move All Notes Sideways..."),$n({value:"beatsPerBar"},"Change Beats Per Bar..."),$n({value:"barCount"},"Change Song Length..."),$n({value:"channelSettings"},"Channel Settings... (Q)")),this.$r=Rn({style:"width: 100%;"},$n({selected:!0,disabled:!0,hidden:!1},"Preferences"),$n({value:"autoPlay"},"Auto Play on Load"),$n({value:"autoFollow"},"Show And Play The Same Bar"),$n({value:"enableNotePreview"},"Hear Preview of Added Notes"),$n({value:"showLetters"},"Show Piano Keys"),$n({value:"showFifth"},'Highlight "Fifth" of Song Key'),$n({value:"notesOutsideScale"},"Allow Adding Notes Not in Scale"),$n({value:"setDefaultScale"},"Use Current Scale as Default"),$n({value:"showChannels"},"Show Notes From All Channels"),$n({value:"showScrollBar"},"Show Octave Scroll Bar"),$n({value:"alwaysShowSettings"},"Customize All Instruments"),$n({value:"instrumentCopyPaste"},"Instrument Copy/Paste Buttons"),$n({value:"enableChannelMuting"},"Enable Channel Muting"),$n({value:"displayBrowserUrl"},"Display Song Data in URL"),$n({value:"layout"},"Choose Layout..."),$n({value:"colorTheme"},"Light Theme"),$n({value:"recordingSetup"},"Set Up Note Recording...")),this._r=_n(Rn(),e.scales.map((t=>t.name))),this.Ur=_n(Rn(),e.keys.map((t=>t.name)).reverse()),this.Vr=new jn(Nn({style:"margin: 0; width: 4em; flex-grow: 1; vertical-align: middle;",type:"range",min:"0",max:"14",value:"7",step:"1"}),this.j,((t,e)=>new si(this.j,t,Math.round(120*Math.pow(2,(-4+e)/9))))),this.jr=Nn({style:"width: 3em; margin-left: 0.4em; vertical-align: middle;",type:"number",step:"1"}),this.Wr=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.chorusRange-1,value:"0",step:"1"}),this.j,((t,e)=>new ri(this.j,t,e))),this.Kr=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("chorus")},"Chorus:"),this.Wr.input),this.Jr=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.reverbRange-1,value:"0",step:"1"}),this.j,((t,e)=>new hi(this.j,t,e))),this.Qr=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("reverb")},"Reverb:"),this.Jr.input),this.Xr=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.echoSustainRange-1,value:"0",step:"1"}),this.j,((t,e)=>new oi(this.j,t,e))),this.Zr=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("echoSustain")},"Echo:"),this.Xr.input),this.th=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.echoDelayRange-1,value:"0",step:"1"}),this.j,((t,e)=>new ni(this.j,t,e))),this.eh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("echoDelay")},"Echo Delay:"),this.th.input),this.ih=_n(Rn(),e.rhythms.map((t=>t.name))),this.sh=Un(!1),this.nh=Un(!0),this.oh=_n(Rn(),e.algorithms.map((t=>t.name))),this.rh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("algorithm")},"Algorithm:"),On({class:"selectContainer"},this.oh)),this.hh=[],this.ah=Bn({type:"button",class:"add-instrument last-button"}),this.lh=Bn({type:"button",class:"remove-instrument"}),this.uh=On({class:"instrument-bar"},this.lh,this.ah),this.fh=On({class:"selectRow",style:"display: none;"},Hn({class:"tip",onclick:()=>this.Yr("instrumentIndex")},"Instrument:"),this.uh),this.ph=Bn({type:"button",class:"copy-instrument",title:"Copy Instrument (⇧C)"},"Copy"),this.dh=Bn({type:"button",class:"paste-instrument",title:"Paste Instrument (⇧V)"},"Paste"),this.mh=On({class:"instrumentCopyPasteRow",style:"display: none;"},this.ph,this.dh),this.yh=new jn(Nn({style:"margin: 0;",type:"range",min:-(e.volumeRange-1),max:"0",value:"0",step:"1"}),this.j,((t,e)=>new wi(this.j,t,-e))),this.gh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("instrumentVolume")},"Volume:"),this.yh.input),this.bh=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.panMax,value:e.panCenter,step:"1"}),this.j,((t,e)=>new vi(this.j,t,e))),this.wh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("pan")},"Panning:"),this.bh.input),this.kh=_n(Rn(),e.chipWaves.map((t=>t.name))),this.Mh=_n(Rn(),e.chipNoises.map((t=>t.name))),this.xh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("chipWave")},"Wave:"),On({class:"selectContainer"},this.kh)),this.Sh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("chipNoise")},"Noise:"),On({class:"selectContainer"},this.Mh)),this.Fh=new Ci(this.j),this.Ph=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("fadeInOut")},"Fade In/Out:"),this.Fh.container),this.Ih=_n(Rn(),e.transitions.map((t=>t.name))),this.Th=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("transition")},"Transition:"),On({class:"selectContainer"},this.Ih)),this.qh=Rn($n({selected:!0,disabled:!0,hidden:!1})),this.Eh=new Li(this.j),this.Ch=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("eqFilter")},"EQ Filter:"),this.Eh.container),this.Lh=new Li(this.j,!0),this.zh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("noteFilter")},"Note Filter:"),this.Lh.container),this.Dh=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.supersawDynamismMax,value:"0",step:"1"}),this.j,((t,e)=>new ce(this.j,t,e))),this.Ah=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("supersawDynamism")},"Dynamism:"),this.Dh.input),this.Bh=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.supersawSpreadMax,value:"0",step:"1"}),this.j,((t,e)=>new ue(this.j,t,e))),this.Oh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("supersawSpread")},"Spread:"),this.Bh.input),this.Nh=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.supersawShapeMax,value:"0",step:"1"}),this.j,((t,e)=>new fe(this.j,t,e))),this.Rh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("supersawShape")},"Saw↔Pulse:"),this.Nh.input),this.Hh=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.pulseWidthRange-1,value:"0",step:"1"}),this.j,((t,e)=>new le(this.j,t,e))),this.Gh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("pulseWidth")},"Pulse Width:"),this.Hh.input),this.$h=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.pitchShiftRange-1,value:"0",step:"1"}),this.j,((t,e)=>new pe(this.j,t,e))),this._h=[On({class:"pitchShiftMarker",style:{color:$.tonic}}),On({class:"pitchShiftMarker",style:{color:$.tonic,left:"50%"}}),On({class:"pitchShiftMarker",style:{color:$.tonic,left:"100%"}})],this.Uh=[On({class:"pitchShiftMarker",style:{color:$.fifthNote,left:700/24+"%"}}),On({class:"pitchShiftMarker",style:{color:$.fifthNote,left:1900/24+"%"}})],this.Vh=On({style:"display: flex; position: relative;"},this.$h.input,On({class:"pitchShiftMarkerContainer"},this._h,this.Uh)),this.jh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("pitchShift")},"Pitch Shift:"),this.Vh),this.Wh=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.detuneMax,value:"0",step:"1"}),this.j,((t,e)=>new de(this.j,t,e))),this.Kh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("detune")},"Detune:"),this.Wh.input),this.Yh=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.distortionRange-1,value:"0",step:"1"}),this.j,((t,e)=>new me(this.j,t,e))),this.Jh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("distortion")},"Distortion:"),this.Yh.input),this.Qh=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.bitcrusherQuantizationRange-1,value:"0",step:"1"}),this.j,((t,e)=>new ge(this.j,t,e))),this.Xh=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("bitcrusherQuantization")},"Bit Crush:"),this.Qh.input),this.Zh=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.bitcrusherFreqRange-1,value:"0",step:"1"}),this.j,((t,e)=>new ye(this.j,t,e))),this.ta=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("bitcrusherFreq")},"Freq Crush:"),this.Zh.input),this.ea=new jn(Nn({style:"margin: 0;",type:"range",min:"0",max:e.stringSustainRange-1,value:"0",step:"1"}),this.j,((t,e)=>new be(this.j,t,e))),this.ia=Hn({class:"tip",onclick:()=>this.Yr("stringSustain")},"Sustain:"),this.sa=On({class:"selectRow"},this.ia,this.ea.input),this.na=_n(Rn(),e.unisons.map((t=>t.name))),this.oa=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("unison")},"Unison:"),On({class:"selectContainer"},this.na)),this.ra=_n(Rn(),e.chords.map((t=>t.name))),this.ha=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("chords")},"Chords:"),On({class:"selectContainer"},this.ra)),this.aa=_n(Rn(),e.vibratos.map((t=>t.name))),this.la=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("vibrato")},"Vibrato:"),On({class:"selectContainer"},this.aa)),this.ca=On({class:"editor-controls"}),this.ua=_n(Rn(),e.feedbacks.map((t=>t.name))),this.fa=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("feedbackType")},"Feedback:"),On({class:"selectContainer"},this.ua)),this.pa=new Vi(this.j,null),this.da=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("spectrum")},"Spectrum:"),this.pa.container),this.ma=new ji(this.j),this.ya=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("harmonics")},"Harmonics:"),this.ma.container),this.ga=new Ei(this.j),this.ba=On({class:"editor-controls"}),this.wa=new jn(Nn({type:"range",min:"0",max:e.operatorAmplitudeMax,value:"0",step:"1",title:"Feedback Amplitude"}),this.j,((t,e)=>new Ie(this.j,t,e))),this.va=On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("feedbackVolume")},"Fdback Vol:"),this.wa.input),this.ka=Bn({type:"button",class:"customize-instrument"},"Customize Instrument"),this.Ma=Bn({type:"button",class:"add-envelope"}),this.xa=On({class:"editor-controls"},this.Ch,this.Ph,this.xh,this.Sh,this.rh,this.ca,this.fa,this.va,this.da,this.ya,this.ba,this.Ah,this.Oh,this.Rh,this.Gh,this.sa,this.oa,On({style:"margin: 2px 0; margin-left: 2em; display: flex; align-items: center;"},Hn({style:"flex-grow: 1; text-align: center;"},Hn({class:"tip",onclick:()=>this.Yr("effects")},"Effects")),On({class:"effects-menu"},this.qh)),this.Th,this.ha,this.jh,this.Kh,this.la,this.zh,this.Jh,this.Xh,this.ta,this.wh,this.Kr,this.Zr,this.eh,this.Qr,On({style:"margin: 2px 0; margin-left: 2em; display: flex; align-items: center;"},Hn({style:"flex-grow: 1; text-align: center;"},Hn({class:"tip",onclick:()=>this.Yr("envelopes")},"Envelopes")),this.Ma),this.ga.container),this.Sa=On({class:"editor-controls"},On({style:`margin: 3px 0; text-align: center; color: ${$.secondaryText};`},"Instrument Settings"),this.fh,this.mh,this.gh,On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("instrumentType")},"Type:"),On({class:"selectContainer"},this.sh,this.nh)),this.ka,this.xa),this.Fa=On({class:"promptContainer",style:"display: none;"}),this.Pa=Bn({class:"zoomInButton",type:"button",title:"Zoom In"}),this.Ia=Bn({class:"zoomOutButton",type:"button",title:"Zoom Out"}),this.Ta=On({style:"flex: 1; height: 100%; display: flex; overflow: hidden; justify-content: center;"},this.Fr.container,this.Pr.container,this.Ir.container),this.qa=On({class:"pattern-area"},this.Lr.container,this.Ta,this.Cr.container,this.Pa,this.Ia),this.Ea=On({class:"trackContainer"},this.qr.container,this.Er.container),this.Ca=On({style:"position: absolute; width: 100%; height: 100%; pointer-events: none;"}),this.La=On({class:"trackAndMuteContainer"},this.Tr.container,this.Ea,this.Ca),this.za=new Wi(this.j),this.Da=On({class:"track-area"},this.La,this.za.container),this.Aa=On({class:"menu-area"},On({class:"selectContainer menu file"},this.Hr),On({class:"selectContainer menu edit"},this.Gr),On({class:"selectContainer menu preferences"},this.$r)),this.Ba=On({class:"song-settings-area"},On({class:"editor-controls"},On({style:`margin: 3px 0; text-align: center; color: ${$.secondaryText};`},"Song Settings"),On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("scale")},"Scale:"),On({class:"selectContainer"},this._r)),On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("key")},"Key:"),On({class:"selectContainer"},this.Ur)),On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("tempo")},"Tempo:"),Hn({style:"display: flex;"},this.Vr.input,this.jr)),On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("rhythm")},"Rhythm:"),On({class:"selectContainer"},this.ih)))),this.Oa=On({class:"instrument-settings-area"},this.Sa),this.Na=On({class:"settings-area noSelection"},On({class:"version-area"},On({style:`text-align: center; margin: 3px 0; color: ${$.secondaryText};`},x.versionDisplayName," ",An({class:"tip",target:"_blank",href:x.releaseNotesURL},x.version))),On({class:"play-pause-area"},On({class:"playback-bar-controls"},this.zr,this.Dr,this.Ar,this.Br,this.Or,this.Nr),On({class:"playback-volume-controls"},Hn({class:"volume-speaker"}),this.Rr)),this.Aa,this.Ba,this.Oa),this.mainLayer=On({class:"beepboxEditor",tabIndex:"0"},this.qa,this.Da,this.Na,this.Fa),this.Ra=!1,this.Ha=null,this.Ga=-1,this.$a=0,this._a=!1,this.Ua=!1,this.Va=!1,this.ja=!1,this.ge=!1,this.Wa=!1,this.Ka=[],this.Ya=[],this.Ja=[],this.Qa=[],this.Xa=[],this.Za=()=>{this.mainLayer.focus({preventScroll:!0})},this.tl=t=>{this.j.synth.recording&&t.target!=this.mainLayer&&t.target!=this.Br&&t.target!=this.Rr&&this.Za()},this.whenUpdated=()=>{const t=this.j.prefs;this.Tr.container.style.display=t.enableChannelMuting?"":"none";const i=this.Ca.getBoundingClientRect();if(this.j.trackVisibleBars=Math.floor((i.right-i.left-(t.enableChannelMuting?32:0))/this.j.getBarWidth()),this.j.trackVisibleChannels=Math.floor((i.bottom-i.top-30)/Di.patternHeight),this.za.render(),this.Tr.render(),this.qr.render(),this.La.scrollLeft=this.j.barScrollPos*this.j.getBarWidth(),this.La.scrollTop=this.j.channelScrollPos*Di.patternHeight,this.Lr.container.style.display=t.showLetters?"":"none",this.Cr.container.style.display=t.showScrollBar?"":"none",this.za.container.style.display=this.j.song.barCount>this.j.trackVisibleBars?"":"none",this.j.getFullScreen()){const e=5*(this.Ta.clientHeight/this.j.getVisiblePitchCount()),i=this.Ta.clientWidth/(3*this.j.song.beatsPerBar),s=this.Ta.clientWidth/(this.j.song.beatsPerBar+2),n=Math.max(i,Math.min(s,e))*this.j.song.beatsPerBar;this.Fr.container.style.width=n+"px",this.Pr.container.style.width=n+"px",this.Ir.container.style.width=n+"px",this.Fr.container.style.flexShrink="0",this.Pr.container.style.flexShrink="0",this.Ir.container.style.flexShrink="0",this.Fr.container.style.display="",this.Ir.container.style.display="",this.Fr.render(),this.Ir.render(),this.Pa.style.display="",this.Ia.style.display="",this.Pa.style.right=t.showScrollBar?"24px":"4px",this.Ia.style.right=t.showScrollBar?"24px":"4px"}else this.Pr.container.style.width="",this.Pr.container.style.flexShrink="",this.Fr.container.style.display="none",this.Ir.container.style.display="none",this.Pa.style.display="none",this.Ia.style.display="none";this.Pr.render();const s=[(t.autoPlay?"✓ ":" ")+"Auto Play on Load",(t.autoFollow?"✓ ":" ")+"Show And Play The Same Bar",(t.enableNotePreview?"✓ ":" ")+"Hear Preview of Added Notes",(t.showLetters?"✓ ":" ")+"Show Piano Keys",(t.showFifth?"✓ ":" ")+'Highlight "Fifth" of Song Key',(t.notesOutsideScale?"✓ ":" ")+"Allow Adding Notes Not in Scale",(t.defaultScale==this.j.song.scale?"✓ ":" ")+"Use Current Scale as Default",(t.showChannels?"✓ ":" ")+"Show Notes From All Channels",(t.showScrollBar?"✓ ":" ")+"Show Octave Scroll Bar",(t.alwaysShowSettings?"✓ ":" ")+"Customize All Instruments",(t.instrumentCopyPaste?"✓ ":" ")+"Instrument Copy/Paste Buttons",(t.enableChannelMuting?"✓ ":" ")+"Enable Channel Muting",(t.displayBrowserUrl?"✓ ":" ")+"Display Song Data in URL"," Choose Layout...",("light classic"==t.colorTheme?"✓ ":" ")+"Light Theme"," Set Up Note Recording..."];for(let t=0;t<s.length;t++){const e=this.$r.children[t+1];e.textContent!=s[t]&&(e.textContent=s[t])}const o=this.j.song.channels[this.j.channel],r=this.j.getCurrentInstrument(),h=o.instruments[r],a=this.mainLayer.contains(document.activeElement),k=document.activeElement,x=$.getChannelColor(this.j.song,this.j.channel);for(let t=this.qh.childElementCount-1;t<e.effectOrder.length;t++)this.qh.appendChild($n({value:t}));this.qh.selectedIndex=0;for(let t=0;t<e.effectOrder.length;t++){let i=e.effectOrder[t];const s=(0!=(h.effects&1<<i)?"✓ ":" ")+e.effectNames[i],n=this.qh.children[t+1];n.textContent!=s&&(n.textContent=s)}if(Vn(this._r,this.j.song.scale),this._r.title=e.scales[this.j.song.scale].realName,Vn(this.Ur,e.keys.length-1-this.j.song.key),this.Vr.updateValue(Math.max(0,Math.min(28,Math.round(4+9*Math.log2(this.j.song.tempo/120))))),this.jr.value=this.j.song.tempo.toString(),Vn(this.ih,this.j.song.rhythm),this.j.song.getChannelIsNoise(this.j.channel)?(this.sh.style.display="none",this.nh.style.display="",Vn(this.nh,h.preset)):(this.sh.style.display="",this.nh.style.display="none",Vn(this.sh,h.preset)),t.instrumentCopyPaste?this.mh.style.display="":this.mh.style.display="none",t.alwaysShowSettings||h.preset==h.type){if(this.ka.style.display="none",this.xa.style.display="",2==h.type?(this.Sh.style.display="",Vn(this.Mh,h.chipNoise)):this.Sh.style.display="none",3==h.type?(this.da.style.display="",this.pa.render()):this.da.style.display="none",5==h.type||7==h.type?(this.ya.style.display="",this.ma.render()):this.ya.style.display="none",7==h.type?(this.sa.style.display="",this.ea.updateValue(h.stringSustain),this.ia.textContent=e.enableAcousticSustain?"Sustain ("+e.sustainTypeNames[h.stringSustainType].substring(0,1).toUpperCase()+"):":"Sustain:"):this.sa.style.display="none",4==h.type){this.ba.style.display="",this.Ph.style.display="none";for(let t=0;t<e.drumCount;t++)Vn(this.Xa[t],h.drumsetEnvelopes[t]),this.Qa[t].render()}else this.ba.style.display="none",this.Ph.style.display="",this.Fh.render();if(0==h.type?(this.xh.style.display="",Vn(this.kh,h.chipWave)):this.xh.style.display="none",1==h.type){this.rh.style.display="",this.ca.style.display="",this.fa.style.display="",this.va.style.display="",Vn(this.oh,h.algorithm),Vn(this.ua,h.feedbackType),this.wa.updateValue(h.feedbackAmplitude);for(let t=0;t<e.operatorCount;t++){const i=t<e.algorithms[h.algorithm].carrierCount;this.Ka[t].style.color=i?$.primaryText:"",Vn(this.Ja[t],h.operators[t].frequency),this.Ya[t].updateValue(h.operators[t].amplitude);const s=(i?"Voice ":"Modulator ")+(t+1);this.Ja[t].title=s+" Frequency",this.Ya[t].input.title=s+(i?" Volume":" Amplitude")}}else this.rh.style.display="none",this.ca.style.display="none",this.fa.style.display="none",this.va.style.display="none";if(8==h.type?(this.Ah.style.display="",this.Oh.style.display="",this.Rh.style.display="",this.Dh.updateValue(h.supersawDynamism),this.Bh.updateValue(h.supersawSpread),this.Nh.updateValue(h.supersawShape)):(this.Ah.style.display="none",this.Oh.style.display="none",this.Rh.style.display="none"),6==h.type||8==h.type?(this.Gh.style.display="",this.Hh.input.title=M(100*n(h.pulseWidth))+"%",this.Hh.updateValue(h.pulseWidth)):this.Gh.style.display="none",l(h.effects)?(this.Th.style.display="",Vn(this.Ih,h.transition)):this.Th.style.display="none",c(h.effects)?(this.ha.style.display="",Vn(this.ra,h.chord)):this.ha.style.display="none",u(h.effects)){this.jh.style.display="",this.$h.updateValue(h.pitchShift),this.$h.input.title=h.pitchShift-e.pitchShiftCenter+" semitone(s)";for(const e of this.Uh)e.style.display=t.showFifth?"":"none"}else this.jh.style.display="none";f(h.effects)?(this.Kh.style.display="",this.Wh.updateValue(h.detune),this.Wh.input.title=Ft.detuneToCents(h.detune-e.detuneCenter)+" cent(s)"):this.Kh.style.display="none",p(h.effects)?(this.la.style.display="",Vn(this.aa,h.vibrato)):this.la.style.display="none",d(h.effects)?(this.zh.style.display="",this.Lh.render()):this.zh.style.display="none",m(h.effects)?(this.Jh.style.display="",this.Yh.updateValue(h.distortion)):this.Jh.style.display="none",y(h.effects)?(this.Xh.style.display="",this.ta.style.display="",this.Qh.updateValue(h.bitcrusherQuantization),this.Zh.updateValue(h.bitcrusherFreq)):(this.Xh.style.display="none",this.ta.style.display="none"),g(h.effects)?(this.wh.style.display="",this.bh.updateValue(h.pan)):this.wh.style.display="none",b(h.effects)?(this.Kr.style.display="",this.Wr.updateValue(h.chorus)):this.Kr.style.display="none",w(h.effects)?(this.Zr.style.display="",this.Xr.updateValue(h.echoSustain),this.eh.style.display="",this.th.updateValue(h.echoDelay),this.th.input.title=Math.round((h.echoDelay+1)*e.echoDelayStepTicks/(e.ticksPerPart*e.partsPerBeat)*1e3)/1e3+" beat(s)"):(this.Zr.style.display="none",this.eh.style.display="none"),v(h.effects)?(this.Qr.style.display="",this.Jr.updateValue(h.reverb)):this.Qr.style.display="none",0==h.type||5==h.type||7==h.type?(this.oa.style.display="",Vn(this.na,h.unison)):this.oa.style.display="none",this.ga.render()}else this.ka.style.display="",this.xa.style.display="none";for(let t=0;t<e.chords.length;t++){let i=!e.instrumentTypeHasSpecialInterval[h.type]&&e.chords[t].customInterval;const s=this.ra.children[t];i?s.hasAttribute("hidden")||s.setAttribute("hidden",""):s.removeAttribute("hidden")}if(this.j.song.layeredInstruments||this.j.song.patternInstruments){this.fh.style.display="",this.uh.style.setProperty("--text-color-lit",x.primaryNote),this.uh.style.setProperty("--text-color-dim",x.secondaryNote),this.uh.style.setProperty("--background-color-lit",x.primaryChannel),this.uh.style.setProperty("--background-color-dim",x.secondaryChannel);const t=this.j.song.getMaxInstrumentsPerChannel();for(;this.hh.length<o.instruments.length;){const t=Bn(String(this.hh.length+1));this.hh.push(t),this.uh.insertBefore(t,this.lh)}for(let t=this.$a;t<o.instruments.length;t++)this.hh[t].style.display="";for(let t=o.instruments.length;t<this.$a;t++)this.hh[t].style.display="none";for(this.$a=o.instruments.length;this.hh.length>t;)this.uh.removeChild(this.hh.pop());if(this.lh.style.display=o.instruments.length>e.instrumentCountMin?"":"none",this.ah.style.display=o.instruments.length<t?"":"none",o.instruments.length<t?this.lh.classList.remove("last-button"):this.lh.classList.add("last-button"),o.instruments.length>1){if(this.Ga!=r){const t=this.hh[this.Ga];null!=t&&t.classList.remove("selected-instrument");this.hh[r].classList.add("selected-instrument"),this.Ga=r}}else{const t=this.hh[this.Ga];null!=t&&t.classList.remove("selected-instrument"),this.Ga=-1}if(this.j.song.layeredInstruments&&this.j.song.patternInstruments){for(let t=0;t<o.instruments.length;t++)-1!=this.j.recentPatternInstruments[this.j.channel].indexOf(t)?this.hh[t].classList.remove("deactivated"):this.hh[t].classList.add("deactivated");this.Wa=!0}else if(this.Wa){for(let t=0;t<o.instruments.length;t++)this.hh[t].classList.remove("deactivated");this.Wa=!1}}else this.fh.style.display="none";if(this.Sa.style.color=x.primaryNote,this.Eh.render(),this.yh.updateValue(-h.volume),this.Ma.disabled=h.envelopeCount>=e.maxEnvelopeCount,this.Rr.value=String(t.volume),a&&null!=k&&0==k.clientWidth&&this.Za(),this.el(this.j.prompt),t.autoFollow&&!this.j.synth.playing&&this.j.synth.goToBar(this.j.bar),this.j.addedEffect){const t=this.Ma.getBoundingClientRect(),e=this.Oa.getBoundingClientRect(),i=this.Na.getBoundingClientRect();this.Oa.scrollTop+=Math.max(0,t.top-(e.top+e.height)),this.Na.scrollTop+=Math.max(0,t.top-(i.top+i.height)),this.j.addedEffect=!1}this.j.addedEnvelope&&(this.Oa.scrollTop=this.Oa.scrollHeight,this.Na.scrollTop=this.Na.scrollHeight,this.j.addedEnvelope=!1)},this.updatePlayButton=()=>{this._a==this.j.synth.playing&&this.Ua==this.j.synth.recording&&this.Va==this.j.prefs.showRecordButton&&this.ja==this.ge||(this._a=this.j.synth.playing,this.Ua=this.j.synth.recording,this.Va=this.j.prefs.showRecordButton,this.ja=this.ge,document.activeElement!=this.zr&&document.activeElement!=this.Dr&&document.activeElement!=this.Ar&&document.activeElement!=this.Br||this.Za(),this.zr.style.display="none",this.Dr.style.display="none",this.Ar.style.display="none",this.Br.style.display="none",this.Or.style.display="",this.Nr.style.display="",this.zr.classList.remove("shrunk"),this.Ar.classList.remove("shrunk"),this.Ta.style.pointerEvents="",this.Cr.container.style.pointerEvents="",this.Cr.container.style.opacity="",this.Ea.style.pointerEvents="",this.Er.container.style.opacity="",this.Oa.style.pointerEvents="",this.Oa.style.opacity="",this.Aa.style.pointerEvents="",this.Aa.style.opacity="",this.Ba.style.pointerEvents="",this.Ba.style.opacity="",this.j.synth.recording?(this.Br.style.display="",this.Or.style.display="none",this.Nr.style.display="none",this.Ta.style.pointerEvents="none",this.Cr.container.style.pointerEvents="none",this.Cr.container.style.opacity="0.5",this.Ea.style.pointerEvents="none",this.Er.container.style.opacity="0.5",this.Oa.style.pointerEvents="none",this.Oa.style.opacity="0.5",this.Aa.style.pointerEvents="none",this.Aa.style.opacity="0.5",this.Ba.style.pointerEvents="none",this.Ba.style.opacity="0.5"):this.j.synth.playing?this.Dr.style.display="":this.j.prefs.showRecordButton?(this.zr.style.display="",this.Ar.style.display="",this.zr.classList.add("shrunk"),this.Ar.classList.add("shrunk")):this.ge?this.Ar.style.display="":this.zr.style.display=""),window.requestAnimationFrame(this.updatePlayButton)},this.il=t=>{this.j.barScrollPos=this.La.scrollLeft/this.j.getBarWidth()},this.sl=t=>!t.ctrlKey||(t.preventDefault(),!1),this.nl=t=>{switch(t.keyCode){case 8:case 13:case 38:case 40:case 37:case 39:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:t.stopPropagation()}},this.en=t=>{if(this.ge=t.ctrlKey,this.prompt)return void(27==t.keyCode&&this.j.undo());if(this.j.synth.recording)return t.ctrlKey||t.metaKey||this.ar.handleKeyEvent(t,!0),void((32==t.keyCode||80==t.keyCode&&(t.ctrlKey||t.metaKey))&&(this.ol(),t.preventDefault(),this.Za()));const i=this.j.prefs.pressControlForShortcuts!=t.getModifierState("CapsLock"),s=!t.ctrlKey&&!t.metaKey&&i;switch(s&&this.ar.handleKeyEvent(t,!0),t.keyCode){case 27:t.ctrlKey||t.metaKey||(new mi(this.j,0,0),this.j.selection.resetBoxSelection());break;case 32:t.ctrlKey?this.ol():t.shiftKey?(this.qr.movePlayheadToMouse()||this.Pr.movePlayheadToMouse())&&(this.j.synth.playing||this.j.performance.play()):this.rl(),t.preventDefault(),this.Za();break;case 80:if(s)break;(t.ctrlKey||t.metaKey)&&(this.ol(),t.preventDefault(),this.Za());break;case 90:if(s)break;t.shiftKey?this.j.redo():this.j.undo(),t.preventDefault();break;case 89:if(s)break;this.j.redo(),t.preventDefault();break;case 67:if(s)break;t.shiftKey?this.hl():this.j.selection.copy(),t.preventDefault();break;case 13:t.ctrlKey||t.metaKey?this.j.selection.insertChannel():this.j.selection.insertBars(),t.preventDefault();break;case 8:t.ctrlKey||t.metaKey?this.j.selection.deleteChannel():this.j.selection.deleteBars(),t.preventDefault();break;case 65:if(s)break;t.shiftKey?this.j.selection.selectChannel():this.j.selection.selectAll(),t.preventDefault();break;case 68:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.duplicatePatterns(),t.preventDefault());break;case 70:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.synth.snapToStart(),this.j.prefs.autoFollow&&this.j.selection.setChannelBar(this.j.channel,Math.floor(this.j.synth.playhead)),t.preventDefault());break;case 72:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.synth.goToBar(this.j.bar),this.j.synth.snapToBar(),this.j.prefs.autoFollow&&this.j.selection.setChannelBar(this.j.channel,Math.floor(this.j.synth.playhead)),t.preventDefault());break;case 77:if(s)break;i==(t.ctrlKey||t.metaKey)&&this.j.prefs.enableChannelMuting&&(this.j.selection.muteChannels(t.shiftKey),t.preventDefault());break;case 81:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.Yr("channelSettings"),t.preventDefault());break;case 83:if(s)break;t.ctrlKey||t.metaKey?(this.Yr("export"),t.preventDefault()):this.j.prefs.enableChannelMuting&&(this.j.selection.soloChannels(t.shiftKey),t.preventDefault());break;case 79:if(s)break;(t.ctrlKey||t.metaKey)&&(this.Yr("import"),t.preventDefault());break;case 86:if(s)break;(t.ctrlKey||t.metaKey)&&t.shiftKey&&!i?this.j.selection.pasteNumbers():t.shiftKey?this.al():this.j.selection.pasteNotes(),t.preventDefault();break;case 73:if(s)break;if(i==(t.ctrlKey||t.metaKey)&&t.shiftKey){const i=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()].toJsonObject();delete i.preset,delete i.volume,delete i.pan;const s=i.effects.indexOf(e.effectNames[2]);-1!=s&&i.effects.splice(s,1);for(let t=0;t<i.envelopes.length;t++){const e=i.envelopes[t];"panning"!=e.target&&"none"!=e.target&&"none"!=e.envelope||(i.envelopes.splice(t,1),t--)}this.ll(JSON.stringify(i)),t.preventDefault()}break;case 82:if(s)break;i==(t.ctrlKey||t.metaKey)&&(t.shiftKey?this.cl():this.ul(),t.preventDefault());break;case 219:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.synth.goToPrevBar(),this.j.prefs.autoFollow&&this.j.selection.setChannelBar(this.j.channel,Math.floor(this.j.synth.playhead)),t.preventDefault());break;case 221:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.synth.goToNextBar(),this.j.prefs.autoFollow&&this.j.selection.setChannelBar(this.j.channel,Math.floor(this.j.synth.playhead)),t.preventDefault());break;case 189:case 173:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.transpose(!1,t.shiftKey),t.preventDefault());break;case 187:case 61:case 171:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.transpose(!0,t.shiftKey),t.preventDefault());break;case 38:t.ctrlKey||t.metaKey?this.j.selection.swapChannels(-1):t.shiftKey?(this.j.selection.boxSelectionY1=Math.max(0,this.j.selection.boxSelectionY1-1),this.j.selection.scrollToEndOfSelection(),this.j.selection.selectionUpdated()):(this.j.selection.setChannelBar((this.j.channel-1+this.j.song.getChannelCount())%this.j.song.getChannelCount(),this.j.bar),this.j.selection.resetBoxSelection()),t.preventDefault();break;case 40:t.ctrlKey||t.metaKey?this.j.selection.swapChannels(1):t.shiftKey?(this.j.selection.boxSelectionY1=Math.min(this.j.song.getChannelCount()-1,this.j.selection.boxSelectionY1+1),this.j.selection.scrollToEndOfSelection(),this.j.selection.selectionUpdated()):(this.j.selection.setChannelBar((this.j.channel+1)%this.j.song.getChannelCount(),this.j.bar),this.j.selection.resetBoxSelection()),t.preventDefault();break;case 37:t.shiftKey?(this.j.selection.boxSelectionX1=Math.max(0,this.j.selection.boxSelectionX1-1),this.j.selection.scrollToEndOfSelection(),this.j.selection.selectionUpdated()):(this.j.selection.setChannelBar(this.j.channel,(this.j.bar+this.j.song.barCount-1)%this.j.song.barCount),this.j.selection.resetBoxSelection()),t.preventDefault();break;case 39:t.shiftKey?(this.j.selection.boxSelectionX1=Math.min(this.j.song.barCount-1,this.j.selection.boxSelectionX1+1),this.j.selection.scrollToEndOfSelection(),this.j.selection.selectionUpdated()):(this.j.selection.setChannelBar(this.j.channel,(this.j.bar+1)%this.j.song.barCount),this.j.selection.resetBoxSelection()),t.preventDefault();break;case 48:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.nextDigit("0",t.shiftKey),t.preventDefault());break;case 49:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.nextDigit("1",t.shiftKey),t.preventDefault());break;case 50:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.nextDigit("2",t.shiftKey),t.preventDefault());break;case 51:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.nextDigit("3",t.shiftKey),t.preventDefault());break;case 52:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.nextDigit("4",t.shiftKey),t.preventDefault());break;case 53:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.nextDigit("5",t.shiftKey),t.preventDefault());break;case 54:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.nextDigit("6",t.shiftKey),t.preventDefault());break;case 55:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.nextDigit("7",t.shiftKey),t.preventDefault());break;case 56:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.nextDigit("8",t.shiftKey),t.preventDefault());break;case 57:if(s)break;i==(t.ctrlKey||t.metaKey)&&(this.j.selection.nextDigit("9",t.shiftKey),t.preventDefault());break;default:this.j.selection.digits="",this.j.selection.instrumentDigits=""}s&&(this.j.selection.digits="",this.j.selection.instrumentDigits="")},this.fl=t=>{this.ge=t.ctrlKey,this.ar.handleKeyEvent(t,!1)},this.pl=()=>{this.j.synth.goToPrevBar()},this.dl=()=>{this.j.synth.goToNextBar()},this.rl=()=>{this.j.synth.playing?this.j.performance.pause():(this.j.synth.snapToBar(),this.j.performance.play())},this.ol=()=>{this.j.synth.playing?this.j.performance.pause():this.j.performance.record()},this.ml=()=>{this.j.setVolume(Number(this.Rr.value))},this.hl=()=>{const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()].toJsonObject();t.isDrum=this.j.song.getChannelIsNoise(this.j.channel),window.localStorage.setItem("instrumentCopy",JSON.stringify(t)),this.Za()},this.al=()=>{const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],e=JSON.parse(String(window.localStorage.getItem("instrumentCopy")));null!=e&&e.isDrum==this.j.song.getChannelIsNoise(this.j.channel)&&this.j.record(new Ne(this.j,t,e)),this.Za()},this.yl=()=>{this.j.record(new si(this.j,-1,0|parseInt(this.jr.value)))},this.gl=()=>{if(isNaN(this._r.value)){if("forceScale"===this._r.value)this.j.selection.forceScale();this.j.notifier.changed()}else this.j.record(new Ke(this.j,this._r.selectedIndex))},this.bl=()=>{if(isNaN(this.Ur.value)){if("detectKey"===this.Ur.value)this.j.record(new Ye(this.j));this.j.notifier.changed()}else this.j.record(new Le(this.j,e.keys.length-1-this.Ur.selectedIndex))},this.wl=()=>{if(isNaN(this.ih.value)){if("forceRhythm"===this.ih.value)this.j.selection.forceRhythm();this.j.notifier.changed()}else this.j.record(new Be(this.j,this.ih.selectedIndex))},this.vl=()=>{this.kl(this.sh.value)},this.Ml=()=>{this.kl(this.nh.value)},this.xl=()=>{this.j.record(new Se(this.j,this.ua.selectedIndex))},this.Sl=()=>{this.j.record(new xe(this.j,this.oh.selectedIndex))},this.Fl=t=>{if(t.target==this.ah)this.j.record(new Te(this.j));else if(t.target==this.lh)this.j.record(new qe(this.j));else{const e=this.hh.indexOf(t.target);-1!=e&&this.j.selection.selectInstrument(e)}this.Za()},this.Pl=()=>{this.j.record(new $t(this.j))},this.Il=()=>{this.j.record(new Mi(this.j,this.kh.selectedIndex))},this.Tl=()=>{this.j.record(new xi(this.j,this.Mh.selectedIndex))},this.ql=()=>{this.j.record(new Vt(this.j,this.Ih.selectedIndex))},this.El=()=>{const t=this.j.song.channels[this.j.channel].instruments[this.j.getCurrentInstrument()],i=t.effects,s=e.effectOrder[this.qh.selectedIndex-1];this.j.record(new jt(this.j,s)),this.qh.selectedIndex=0,t.effects>i&&(this.j.addedEffect=!0)},this.Cl=()=>{this.j.record(new ne(this.j,this.aa.selectedIndex))},this.Ll=()=>{this.j.record(new ie(this.j,this.na.selectedIndex))},this.zl=()=>{this.j.record(new se(this.j,this.ra.selectedIndex))},this.Dl=()=>{this.j.record(new Si(this.j)),this.Za(),this.j.addedEnvelope=!0},this.Al=()=>{this.j.prefs.visibleOctaves=Math.max(1,this.j.prefs.visibleOctaves-1),this.j.prefs.save(),this.j.notifier.changed(),this.Za()},this.Bl=()=>{this.j.prefs.visibleOctaves=Math.min(e.pitchOctaves,this.j.prefs.visibleOctaves+1),this.j.prefs.save(),this.j.notifier.changed(),this.Za()},this.Ol=t=>{switch(this.Hr.value){case"new":this.j.goBackToStart();for(const t of this.j.song.channels)t.muted=!1;this.j.record(new Xe(this.j,""),!1,!0);break;case"export":this.Yr("export");break;case"import":this.Yr("import");break;case"copyUrl":this.ll(new URL("#"+this.j.song.toBase64String(),location.href).href);break;case"shareUrl":navigator.share({url:new URL("#"+this.j.song.toBase64String(),location.href).href});break;case"shortenUrl":window.open("https://tinyurl.com/api-create.php?url="+encodeURIComponent(new URL("#"+this.j.song.toBase64String(),location.href).href));break;case"viewPlayer":location.href="player/#song="+this.j.song.toBase64String();break;case"copyEmbed":this.ll(`<iframe width="384" height="60" style="border: none;" src="${new URL("player/#song="+this.j.song.toBase64String(),location.href).href}"></iframe>`);break;case"songRecovery":this.Yr("songRecovery")}this.Hr.selectedIndex=0},this.Nl=t=>{switch(this.Gr.value){case"undo":this.j.undo();break;case"redo":this.j.redo();break;case"copy":this.j.selection.copy();break;case"insertBars":this.j.selection.insertBars();break;case"deleteBars":this.j.selection.deleteBars();break;case"insertChannel":this.j.selection.insertChannel();break;case"deleteChannel":this.j.selection.deleteChannel();break;case"pasteNotes":this.j.selection.pasteNotes();break;case"pasteNumbers":this.j.selection.pasteNumbers();break;case"transposeUp":this.j.selection.transpose(!0,!1);break;case"transposeDown":this.j.selection.transpose(!1,!1);break;case"selectAll":this.j.selection.selectAll();break;case"selectChannel":this.j.selection.selectChannel();break;case"duplicatePatterns":this.j.selection.duplicatePatterns();break;case"barCount":this.Yr("barCount");break;case"beatsPerBar":this.Yr("beatsPerBar");break;case"moveNotesSideways":this.Yr("moveNotesSideways");break;case"channelSettings":this.Yr("channelSettings")}this.Gr.selectedIndex=0},this.Rl=t=>{switch(this.$r.value){case"autoPlay":this.j.prefs.autoPlay=!this.j.prefs.autoPlay;break;case"autoFollow":this.j.prefs.autoFollow=!this.j.prefs.autoFollow;break;case"enableNotePreview":this.j.prefs.enableNotePreview=!this.j.prefs.enableNotePreview;break;case"showLetters":this.j.prefs.showLetters=!this.j.prefs.showLetters;break;case"showFifth":this.j.prefs.showFifth=!this.j.prefs.showFifth;break;case"notesOutsideScale":this.j.prefs.notesOutsideScale=!this.j.prefs.notesOutsideScale;break;case"setDefaultScale":this.j.prefs.defaultScale=this.j.song.scale;break;case"showChannels":this.j.prefs.showChannels=!this.j.prefs.showChannels;break;case"showScrollBar":this.j.prefs.showScrollBar=!this.j.prefs.showScrollBar;break;case"alwaysShowSettings":this.j.prefs.alwaysShowSettings=!this.j.prefs.alwaysShowSettings;break;case"instrumentCopyPaste":this.j.prefs.instrumentCopyPaste=!this.j.prefs.instrumentCopyPaste;break;case"enableChannelMuting":this.j.prefs.enableChannelMuting=!this.j.prefs.enableChannelMuting;for(const t of this.j.song.channels)t.muted=!1;break;case"displayBrowserUrl":this.j.toggleDisplayBrowserUrl();break;case"layout":this.Yr("layout");break;case"colorTheme":this.j.prefs.colorTheme="light classic"==this.j.prefs.colorTheme?"dark classic":"light classic",$.setTheme(this.j.prefs.colorTheme);break;case"recordingSetup":this.Yr("recordingSetup")}this.$r.selectedIndex=0,this.j.notifier.changed(),this.j.prefs.save()},this.j.notifier.watch(this.whenUpdated),new ts(this.j),window.addEventListener("resize",this.whenUpdated),window.requestAnimationFrame(this.updatePlayButton),"share"in navigator||this.Hr.removeChild(this.Hr.querySelector("[value='shareUrl']")),this._r.appendChild(Gn({label:"Edit"},$n({value:"forceScale"},"Snap Notes To Scale"))),this.Ur.appendChild(Gn({label:"Edit"},$n({value:"detectKey"},"Detect Key"))),this.ih.appendChild(Gn({label:"Edit"},$n({value:"forceRhythm"},"Snap Notes To Rhythm"))),this.ca.appendChild(On({class:"selectRow",style:`color: ${$.secondaryText}; height: 1em; margin-top: 0.5em;`},On({style:"margin-right: .1em; visibility: hidden;"},"1."),On({style:"width: 3em; margin-right: .3em;",class:"tip",onclick:()=>this.Yr("operatorFrequency")},"Freq:"),On({class:"tip",onclick:()=>this.Yr("operatorVolume")},"Volume:")));for(let t=0;t<e.operatorCount;t++){const i=t,s=On({style:`margin-right: .1em; color: ${$.secondaryText};`},t+1+"."),n=_n(Rn({style:"width: 100%;",title:"Frequency"}),e.operatorFrequencies.map((t=>t.name))),o=new jn(Nn({type:"range",min:"0",max:e.operatorAmplitudeMax,value:"0",step:"1",title:"Volume"}),this.j,((t,e)=>new Pe(this.j,i,t,e))),r=On({class:"selectRow"},s,On({class:"selectContainer",style:"width: 3em; margin-right: .3em;"},n),o.input);this.ca.appendChild(r),this.Ka[t]=r,this.Ya[t]=o,this.Ja[t]=n,n.addEventListener("change",(()=>{this.j.record(new Fe(this.j,i,n.selectedIndex))}))}this.ba.appendChild(On({class:"selectRow"},Hn({class:"tip",onclick:()=>this.Yr("drumsetEnvelope")},"Envelope:"),Hn({class:"tip",onclick:()=>this.Yr("drumsetSpectrum")},"Spectrum:")));for(let t=e.drumCount-1;t>=0;t--){const i=t,s=new Vi(this.j,i);s.container.addEventListener("mousedown",this.Za),this.Qa[t]=s;const n=_n(Rn({style:"width: 100%;",title:"Filter Envelope"}),e.envelopes.map((t=>t.name)));this.Xa[t]=n,n.addEventListener("change",(()=>{this.j.record(new he(this.j,i,n.selectedIndex))}));const o=On({class:"selectRow"},On({class:"selectContainer",style:"width: 5em; margin-right: .3em;"},n),this.Qa[t].container);this.ba.appendChild(o)}if(this.Hr.addEventListener("change",this.Ol),this.Gr.addEventListener("change",this.Nl),this.$r.addEventListener("change",this.Rl),this.jr.addEventListener("change",this.yl),this._r.addEventListener("change",this.gl),this.Ur.addEventListener("change",this.bl),this.ih.addEventListener("change",this.wl),this.sh.addEventListener("change",this.vl),this.nh.addEventListener("change",this.Ml),this.oh.addEventListener("change",this.Sl),this.uh.addEventListener("click",this.Fl),this.ph.addEventListener("click",this.hl),this.dh.addEventListener("click",this.al),this.ka.addEventListener("click",this.Pl),this.ua.addEventListener("change",this.xl),this.kh.addEventListener("change",this.Il),this.Mh.addEventListener("change",this.Tl),this.Ih.addEventListener("change",this.ql),this.qh.addEventListener("change",this.El),this.na.addEventListener("change",this.Ll),this.ra.addEventListener("change",this.zl),this.aa.addEventListener("change",this.Cl),this.zr.addEventListener("click",this.rl),this.Dr.addEventListener("click",this.rl),this.Ar.addEventListener("click",this.ol),this.Br.addEventListener("click",this.ol),this.Ar.addEventListener("contextmenu",(t=>{t.ctrlKey&&(t.preventDefault(),this.ol())})),this.Br.addEventListener("contextmenu",(t=>{t.ctrlKey&&(t.preventDefault(),this.ol())})),this.Or.addEventListener("click",this.pl),this.Nr.addEventListener("click",this.dl),this.Rr.addEventListener("input",this.ml),this.Pa.addEventListener("click",this.Al),this.Ia.addEventListener("click",this.Bl),this.qa.addEventListener("mousedown",this.Za),this.Da.addEventListener("mousedown",this.Za),this.Fh.container.addEventListener("mousedown",this.Za),this.pa.container.addEventListener("mousedown",this.Za),this.Eh.container.addEventListener("mousedown",this.Za),this.Lh.container.addEventListener("mousedown",this.Za),this.ma.container.addEventListener("mousedown",this.Za),this.jr.addEventListener("keydown",this.nl,!1),this.Ma.addEventListener("click",this.Dl),this.qa.addEventListener("contextmenu",this.sl),this.Da.addEventListener("contextmenu",this.sl),this.mainLayer.addEventListener("keydown",this.en),this.mainLayer.addEventListener("keyup",this.fl),this.mainLayer.addEventListener("focusin",this.tl),this.Fa.addEventListener("click",(t=>{t.target==this.Fa&&this.j.undo()})),this.La.addEventListener("scroll",this.il,{capture:!1,passive:!0}),k){const t=this.$r.querySelector("[value=autoPlay]");t.disabled=!0,t.setAttribute("hidden","")}if(window.screen.availWidth<710||window.screen.availHeight<710){const t=this.$r.querySelector("[value=layout]");t.disabled=!0,t.setAttribute("hidden","")}}Yr(t){this.j.openPrompt(t),this.el(t)}el(t){if(this.Ha!=t&&(this.Ha=t,this.prompt&&(this.Ra&&!(this.prompt instanceof Et||this.prompt instanceof Bs)&&this.j.performance.play(),this.Ra=!1,this.Fa.style.display="none",this.Fa.removeChild(this.prompt.container),this.prompt.cleanUp(),this.prompt=null,this.Za()),t)){switch(t){case"export":this.prompt=new tn(this.j);break;case"import":this.prompt=new an(this.j);break;case"songRecovery":this.prompt=new Sn(this.j);break;case"barCount":this.prompt=new qs(this.j);break;case"beatsPerBar":this.prompt=new us(this.j);break;case"moveNotesSideways":this.prompt=new vs(this.j);break;case"channelSettings":this.prompt=new _s(this.j);break;case"layout":this.prompt=new _i(this.j);break;case"recordingSetup":this.prompt=new Dn(this.j);break;case"stringSustain":this.prompt=new Bs(this.j);break;default:this.prompt=new Et(this.j,t)}this.prompt&&(this.prompt instanceof Et||this.prompt instanceof Bs||(this.Ra=this.j.synth.playing,this.j.performance.pause()),this.Fa.style.display="",this.Fa.appendChild(this.prompt.container))}}ll(t){if(navigator.clipboard&&navigator.clipboard.writeText)return void navigator.clipboard.writeText(t).catch((()=>{window.prompt("Copy to clipboard:",t)}));const e=document.createElement("textarea");e.textContent=t,document.body.appendChild(e),e.select();const i=document.execCommand("copy");e.remove(),this.Za(),i||window.prompt("Copy this:",t)}ul(){const t=this.j.song.getChannelIsNoise(this.j.channel);this.j.record(new _t(this.j,Je(t)))}cl(){this.j.record(new Ut(this.j))}kl(t){if(isNaN(t)){switch(t){case"copyInstrument":this.hl();break;case"pasteInstrument":this.al();break;case"randomPreset":this.ul();break;case"randomGenerated":this.cl()}this.j.notifier.changed()}else this.j.record(new _t(this.j,parseInt(t)))}}class Kn{constructor(t){this.j=t,this.Hl=!1,this.Gl=-1,this.$l=-1,this._l=!1,this.Ul=[],this.Vl=-1,this.jl=-1,this.Wl=null,this.Kl=!1,this.Yl=null,this.Jl=null,this.vo=()=>{if(window.requestAnimationFrame(this.vo),this.j.synth.recording){this.Ql()&&this.j.notifier.notifyWatchers()}},this.bn=()=>{const t=this.j.song.getChannelIsNoise(this.j.channel),e=this.j.song.channels[this.j.channel].octave;this.j.synth.liveInputChannel==this.j.channel&&this.Hl==t&&this.Gl==e&&this.$l==this.j.song.key||(this.j.synth.liveInputChannel=this.j.channel,this.Hl=t,this.Gl=e,this.$l=this.j.song.key,this.clearAllPitches()),this.j.synth.liveInputInstruments=this.j.recentPatternInstruments[this.j.channel]},this.j.notifier.watch(this.bn),this.bn(),window.requestAnimationFrame(this.vo)}play(){this.j.synth.play(),this.j.synth.enableMetronome=!1,this.j.synth.countInMetronome=!1,this.j.synth.maintainLiveInput()}pause(){this.clearAllPitches(),null!=this.Jl&&(this.j.song.barCount>this.Vl&&!this.Xl()&&(new Jt(this.j,this.j.song.barCount-1,1),new ee(this.j,this.j.channel,this.j.song.barCount-1)),this.Jl.isNoop()||(this.j.record(this.Jl),this.Jl=null),this.Yl=null),this.j.synth.pause(),this.j.synth.resetEffects(),this.j.synth.enableMetronome=!1,this.j.synth.countInMetronome=!1,this.j.prefs.autoFollow&&this.j.synth.goToBar(this.j.bar),this.j.synth.snapToBar()}record(){this.j.synth.snapToBar();const t=Math.floor(this.j.synth.playhead);t!=this.j.bar&&new ee(this.j,this.j.channel,t),this._l&&(this.clearAllPitches(),this._l=!1),this.j.synth.enableMetronome=this.j.prefs.metronomeWhileRecording,this.j.synth.countInMetronome=this.j.prefs.metronomeCountIn,this.j.synth.startRecording(),this.j.synth.maintainLiveInput(),this.Vl=this.j.song.barCount,this.jl=this.Zl(),this.Wl=null,this.Kl=!1,this.Yl=null,this.Ul.length=0,this.Jl=new zt,this.j.setProspectiveChange(this.Jl)}abortRecording(){this.Jl=null,this.pause()}pitchesAreTemporary(){return this._l}ai(){return this.j.prefs.snapRecordedNotesToRhythm?e.partsPerBeat/e.rhythms[this.j.song.rhythm].stepsPerBeat:1}Zl(){const t=this.j.synth.playhead*this.j.song.beatsPerBar*e.partsPerBeat;if(this.j.prefs.snapRecordedNotesToRhythm){const e=this.ai();return Math.round(t/e)*e}return Math.round(t)}Xl(){for(let t=0;t<this.j.song.getChannelCount();t++)if(0!=this.j.song.channels[t].bars[this.j.song.barCount-1])return!0;return!1}Ql(){if(null==this.Jl)return!1;if(!this.j.lastChangeWas(this.Jl))return this.abortRecording(),!1;if(this.j.synth.countInMetronome)return this.Ul.length=0,this.Kl=!1,!1;const t=this.j.song.beatsPerBar*e.partsPerBeat,i=this.jl%t,s=Math.floor(this.jl/t),n=this.jl;this.jl=this.Zl();const o=this.jl%t,r=Math.floor(this.jl/t);if(i==o&&s==r)return!1;if(this.jl<n)return this.Yl=null,this.Wl=null,!1;let h=!1;for(let n=s;n<=r;n++){n!=s&&(this.Wl=null);const a=n==s?i:0,l=n==r?o:t;if(a==l)break;if(null!=this.Yl&&!this.Kl&&a>0&&this.j.synth.liveInputPitches.length>0)this.Jl.append(new $e(this.j,this.Yl,1,l,this.Yl.continuesLastPattern)),this.j.currentPatternIsDirty=!0;else{null!=this.Yl&&(this.Yl=null);let t=a,i=l;for(;t<l;){let s=!1;if(this.Ul.length>0||this.j.synth.liveInputPitches.length>0){if(null==this.Wl&&(this.j.selection.erasePatternInBar(this.Jl,this.j.synth.liveInputChannel,n),this.Jl.append(new Ge(this.j,this.j.synth.liveInputChannel,n)),this.Wl=this.j.song.getPattern(this.j.synth.liveInputChannel,n)),null==this.Wl)throw new Error;for(this.Yl=new ht(-1,t,i,e.noteSizeMax,this.j.song.getChannelIsNoise(this.j.synth.liveInputChannel)),this.Yl.continuesLastPattern=0==t&&!this.Kl,this.Yl.pitches.length=0;this.Ul.length>0&&!(this.Yl.pitches.length>=e.maxChordSize);){const t=this.Ul.shift();-1==this.j.synth.liveInputPitches.indexOf(t)&&(this.Yl.pitches.push(t),s=!0)}for(let t=0;t<this.j.synth.liveInputPitches.length&&!(this.Yl.pitches.length>=e.maxChordSize);t++)this.Yl.pitches.push(this.j.synth.liveInputPitches[t]);this.Jl.append(new ai(this.j,this.Wl,this.Yl,this.Wl.notes.length)),s&&(i=t+this.ai(),new li(this.j,this.Yl,this.Yl.start,i),this.Yl=null),h=!0}this.Kl=s,t=i,i=l}}n==this.j.song.barCount-1&&this.Xl()&&(new Yt(this.j,this.j.song.barCount,1),this.j.bar--,h=!0)}return h}setTemporaryPitches(t,i){this.Ql();for(let e=0;e<t.length;e++)this.j.synth.liveInputPitches[e]=t[e];this.j.synth.liveInputPitches.length=Math.min(t.length,e.maxChordSize),this.j.synth.liveInputDuration=i,this.j.synth.liveInputStarted=!0,this._l=!0,this.Kl=!0}addPerformedPitch(t){if(this.j.synth.maintainLiveInput(),this.Ql(),this._l&&(this.clearAllPitches(),this._l=!1),(!this.j.prefs.ignorePerformedNotesNotInScale||e.scales[this.j.song.scale].flags[t%e.pitchesPerOctave])&&-1==this.j.synth.liveInputPitches.indexOf(t)){for(this.j.synth.liveInputPitches.push(t),this.Kl=!0;this.j.synth.liveInputPitches.length>e.maxChordSize;)this.j.synth.liveInputPitches.shift();if(this.j.synth.liveInputDuration=Number.MAX_SAFE_INTEGER,null!=this.Jl){const i=this.Ul.indexOf(t);for(-1!=i&&this.Ul.splice(i,1),this.Ul.push(t);this.Ul.length>4*e.maxChordSize;)this.Ul.shift()}}}removePerformedPitch(t){this.Ql();for(let e=0;e<this.j.synth.liveInputPitches.length;e++)this.j.synth.liveInputPitches[e]==t&&(this.j.synth.liveInputPitches.splice(e,1),this.Kl=!0,e--)}clearAllPitches(){this.Ql(),this.j.synth.liveInputPitches.length=0,this.Kl=!0}}class Yn{constructor(t){this.j=t,this.boxSelectionX0=0,this.boxSelectionY0=0,this.boxSelectionX1=0,this.boxSelectionY1=0,this.digits="",this.instrumentDigits="",this.patternSelectionStart=0,this.patternSelectionEnd=0,this.patternSelectionActive=!1,this.tc=null,this.ec=null,this.ic=null,this.sc=null}toJSON(){return{x0:this.boxSelectionX0,x1:this.boxSelectionX1,y0:this.boxSelectionY0,y1:this.boxSelectionY1,start:this.patternSelectionStart,end:this.patternSelectionEnd}}fromJSON(t){null!=t&&(this.boxSelectionX0=+t.x0,this.boxSelectionX1=+t.x1,this.boxSelectionY0=+t.y0,this.boxSelectionY1=+t.y1,this.patternSelectionStart=+t.start,this.patternSelectionEnd=+t.end,this.digits="",this.instrumentDigits="",this.patternSelectionActive=this.patternSelectionStart<this.patternSelectionEnd)}selectionUpdated(){this.j.notifier.changed(),this.digits="",this.instrumentDigits=""}get boxSelectionBar(){return Math.min(this.boxSelectionX0,this.boxSelectionX1)}get boxSelectionChannel(){return Math.min(this.boxSelectionY0,this.boxSelectionY1)}get boxSelectionWidth(){return Math.abs(this.boxSelectionX0-this.boxSelectionX1)+1}get boxSelectionHeight(){return Math.abs(this.boxSelectionY0-this.boxSelectionY1)+1}get boxSelectionActive(){return this.boxSelectionWidth>1||this.boxSelectionHeight>1}scrollToSelectedPattern(){this.j.barScrollPos=Math.min(this.j.bar,Math.max(this.j.bar-(this.j.trackVisibleBars-1),this.j.barScrollPos)),this.j.channelScrollPos=Math.min(this.j.channel,Math.max(this.j.channel-(this.j.trackVisibleChannels-1),this.j.channelScrollPos))}scrollToEndOfSelection(){this.j.barScrollPos=Math.min(this.boxSelectionX1,Math.max(this.boxSelectionX1-(this.j.trackVisibleBars-1),this.j.barScrollPos)),this.j.channelScrollPos=Math.min(this.boxSelectionY1,Math.max(this.boxSelectionY1-(this.j.trackVisibleChannels-1),this.j.channelScrollPos))}setChannelBar(t,e){if(t==this.j.channel&&e==this.j.bar)return;const i=this.j.lastChangeWas(this.ic);this.ic=new zt,this.ic.append(new ee(this.j,t,e));const s=this.j.getCurrentPattern(0);null!=s&&this.j.song.patternInstruments&&-1==s.instruments.indexOf(this.j.viewedInstrument[this.j.channel])&&(this.j.viewedInstrument[this.j.channel]=s.instruments[0]),this.j.hasRedoHistory()||this.j.record(this.ic,i),this.selectionUpdated()}setPattern(t){this.j.record(new Wt(this.j,t,this.boxSelectionBar,this.boxSelectionChannel,this.boxSelectionWidth,this.boxSelectionHeight))}nextDigit(t,e){const i=this.j.song.channels[this.j.channel];if(e){"0"==t&&(t="10"),this.instrumentDigits+=t;var s=parseInt(this.instrumentDigits);if(0!=s&&s<=i.instruments.length)return void this.selectInstrument(s-1);if(this.instrumentDigits=t,0!=(s=parseInt(this.instrumentDigits))&&s<=i.instruments.length)return void this.selectInstrument(s-1);this.instrumentDigits=""}else{this.digits.length>0&&this.digits!=String(i.bars[this.boxSelectionBar])&&(this.digits=""),this.digits+=t;let e=parseInt(this.digits);if(e<=this.j.song.patternsPerChannel)return void this.setPattern(e);if(this.digits=t,e=parseInt(this.digits),e<=this.j.song.patternsPerChannel)return void this.setPattern(e);this.digits=""}}insertBars(){this.j.record(new Yt(this.j,this.boxSelectionBar+this.boxSelectionWidth,this.boxSelectionWidth));const t=this.boxSelectionWidth;this.boxSelectionX0+=t,this.boxSelectionX1+=t}insertChannel(){const t=new zt,e=this.boxSelectionChannel+this.boxSelectionHeight,i=this.j.song.getChannelIsNoise(e-1);t.append(new Zt(this.j,e,i)),t.isNoop()||(this.boxSelectionY0=this.boxSelectionY1=e,t.append(new ee(this.j,e,this.j.bar)),this.j.record(t))}deleteBars(){const t=new zt;if(this.j.selection.patternSelectionActive){this.boxSelectionActive&&t.append(new gi(this.j,this.boxSelectionBar,this.boxSelectionWidth,this.boxSelectionChannel,this.boxSelectionHeight));for(const e of this.nc())for(const i of this.oc(e))t.append(new ci(this.j,i,this.j.selection.patternSelectionStart,this.j.selection.patternSelectionEnd));t.append(new mi(this.j,0,0))}else{t.append(new Jt(this.j,this.boxSelectionBar,this.boxSelectionWidth));const e=this.boxSelectionWidth;this.boxSelectionX0=Math.max(0,this.boxSelectionX0-e),this.boxSelectionX1=Math.max(0,this.boxSelectionX1-e)}this.j.record(t)}deleteChannel(){this.j.record(new te(this.j,this.boxSelectionChannel,this.boxSelectionChannel+this.boxSelectionHeight-1)),this.boxSelectionY0=this.boxSelectionY1=this.j.channel}*nc(){for(let t=this.boxSelectionChannel;t<this.boxSelectionChannel+this.boxSelectionHeight;t++)yield t}*rc(){for(let t=this.boxSelectionBar;t<this.boxSelectionBar+this.boxSelectionWidth;t++)yield t}*oc(t){const e={};for(const i of this.rc()){const s=this.j.song.channels[t].bars[i];if(0==s)continue;if(e[String(s)])continue;e[String(s)]=!0;const n=this.j.song.getPattern(t,i);if(null==n)throw new Error;yield n}}hc(t,e){const i=Array.from(t.instruments).map((t=>t>>>0));return Bt(i,this.j.song,e),i}ac(t,e){for(let i=0;i<this.j.song.barCount;i++)if(this.j.song.channels[t].bars[i]==e)return!1;return!0}copy(){const t=[];for(const e of this.nc()){const i={},s=[];for(const t of this.rc()){const n=this.j.song.channels[e].bars[t];if(s.push(n),null==i[String(n)]){const s=this.j.song.getPattern(e,t);let o=this.j.recentPatternInstruments[e],r=[];if(null!=s)if(o=s.instruments.concat(),this.patternSelectionActive)for(const t of s.cloneNotes())t.end<=this.patternSelectionStart||t.start>=this.patternSelectionEnd||(t.start-=this.patternSelectionStart,t.end-=this.patternSelectionStart,(t.start<0||t.end>this.patternSelectionEnd-this.patternSelectionStart)&&new li(null,t,Math.max(t.start,0),Math.min(this.patternSelectionEnd-this.patternSelectionStart,t.end)),r.push(t));else r=s.notes;i[String(n)]={instruments:o,notes:r}}}const n={isNoise:this.j.song.getChannelIsNoise(e),patterns:i,bars:s};t.push(n)}const i={partDuration:this.patternSelectionActive?this.patternSelectionEnd-this.patternSelectionStart:this.j.song.beatsPerBar*e.partsPerBeat,channels:t};window.localStorage.setItem("selectionCopy",JSON.stringify(i))}pasteNotes(){const t=JSON.parse(String(window.localStorage.getItem("selectionCopy")));if(null==t)return;const i=t.channels||[],s=t.partDuration>>>0,n=new zt,o=this.boxSelectionActive,r=o?this.boxSelectionHeight:Math.min(i.length,this.j.song.getChannelCount()-this.boxSelectionChannel);for(let t=0;t<r;t++){const h=i[t%i.length],a=this.boxSelectionChannel+t,l=!!h.isNoise,c=h.patterns||{},u=h.bars||[];if(0==u.length)continue;if(l!=this.j.song.getChannelIsNoise(a))continue;const f=o?this.boxSelectionWidth:Math.min(u.length,this.j.song.barCount-this.boxSelectionBar);if(o||1!=u.length||1!=i.length)if(this.patternSelectionActive){const t={},e={};n.append(new gi(this.j,this.boxSelectionBar,f,this.boxSelectionChannel,r));for(let i=0;i<f;i++){const o=this.boxSelectionBar+i,r=u[i%u.length]>>>0,h=this.j.song.channels[a].bars[o],l=[r,h].join(",");if(0==r&&0==h)continue;if(null!=t[l]){n.append(new Wt(this.j,t[l],o,a,1,1));continue}if(0==h){n.append(new Ge(this.j,a,o));const t=c[String(r)],e=this.hc(t,a),i=this.j.song.getPattern(a,o);n.append(new Re(this.j,a,e,i))}else{const t=this.j.song.getPattern(a,o);if(null==t)throw new Error;if(e[String(h)]){n.append(new Wt(this.j,0,o,a,1,1)),n.append(new Ge(this.j,a,o));const e=this.j.song.getPattern(a,o);if(null==e)throw new Error;for(const i of t.cloneNotes())n.append(new ai(this.j,e,i,e.notes.length,!1))}else e[String(h)]=!0}const f=this.j.song.getPattern(a,o);if(null==f)throw new Error;if(0==r)n.append(new ci(this.j,f,this.patternSelectionStart,this.patternSelectionEnd));else{const t=c[String(r)];n.append(new Oe(this.j,f,t.notes,this.patternSelectionStart,this.patternSelectionEnd,s))}t[l]=this.j.song.channels[a].bars[o]}}else{for(let t=0;t<f;t++)this.erasePatternInBar(n,a,this.boxSelectionBar+t);const t={};for(let i=0;i<f;i++){const o=this.boxSelectionBar+i,r=u[i%u.length]>>>0,h=String(r);if(0==r)continue;if(null!=t[h]){n.append(new Wt(this.j,t[h],o,a,1,1));continue}const l=c[String(r)],f=this.hc(l,a),p=this.j.song.channels[a].patterns[r-1];if(null!=p&&s==e.partsPerBeat*this.j.song.beatsPerBar&&ei(l.notes,p.notes)&&At(f,p.instruments))n.append(new Wt(this.j,r,o,a,1,1));else{null!=p&&this.ac(a,r)?n.append(new Wt(this.j,r,o,a,1,1)):n.append(new Ge(this.j,a,o));const t=this.j.song.getPattern(a,o);if(null==t)throw new Error;n.append(new Oe(this.j,t,l.notes,this.patternSelectionActive?this.patternSelectionStart:0,this.patternSelectionActive?this.patternSelectionEnd:e.partsPerBeat*this.j.song.beatsPerBar,s)),n.append(new Re(this.j,a,f,t))}t[h]=this.j.song.channels[a].bars[o]}}else{const t=u[0]>>>0,i=this.boxSelectionBar,o=this.j.song.channels[a].bars[i];if(0==t&&0==o)continue;const r=c[String(t)],h=this.hc(r,a);if(0==o){const e=this.j.song.channels[a].patterns[t-1];null!=e&&!this.patternSelectionActive&&(ei(r.notes,e.notes)&&At(h,e.instruments)||this.ac(a,t))?n.append(new Wt(this.j,t,i,a,1,1)):n.append(new Ge(this.j,a,i))}const l=this.j.song.getPattern(a,i);if(null==l)throw new Error;n.append(new Oe(this.j,l,r.notes,this.patternSelectionActive?this.patternSelectionStart:0,this.patternSelectionActive?this.patternSelectionEnd:e.partsPerBeat*this.j.song.beatsPerBar,s)),0==o&&n.append(new Re(this.j,a,h,l))}}this.j.record(n)}erasePatternInBar(t,e,i){const s=this.j.song.channels[e].bars[i];0!=s&&(t.append(new Wt(this.j,0,i,e,1,1)),this.ac(e,s)&&(this.j.song.channels[e].patterns[s-1].notes.length=0))}pasteNumbers(){const t=JSON.parse(String(window.localStorage.getItem("selectionCopy")));if(null==t)return;const e=t.channels||[],i=new zt,s=this.boxSelectionActive,n=s?this.boxSelectionHeight:Math.min(e.length,this.j.song.getChannelCount()-this.boxSelectionChannel);for(let t=0;t<n;t++){const n=e[t%e.length],o=this.boxSelectionChannel+t,r=n.bars||[];if(0==r.length)continue;const h=s?this.boxSelectionWidth:Math.min(r.length,this.j.song.barCount-this.boxSelectionBar);for(let t=0;t<h;t++){const e=r[t%r.length]>>>0,s=this.boxSelectionBar+t;e>this.j.song.patternsPerChannel&&i.append(new He(this.j,e)),i.append(new Wt(this.j,e,s,o,1,1))}}this.j.record(i)}selectAll(){new mi(this.j,0,0),0==this.boxSelectionBar&&0==this.boxSelectionChannel&&this.boxSelectionWidth==this.j.song.barCount&&this.boxSelectionHeight==this.j.song.getChannelCount()?this.setTrackSelection(this.j.bar,this.j.bar,this.j.channel,this.j.channel):this.setTrackSelection(0,this.j.song.barCount-1,0,this.j.song.getChannelCount()-1),this.selectionUpdated()}selectChannel(){new mi(this.j,0,0),0==this.boxSelectionBar&&this.boxSelectionWidth==this.j.song.barCount?this.setTrackSelection(this.j.bar,this.j.bar,this.boxSelectionY0,this.boxSelectionY1):this.setTrackSelection(0,this.j.song.barCount-1,this.boxSelectionY0,this.boxSelectionY1),this.selectionUpdated()}duplicatePatterns(){this.j.record(new gi(this.j,this.boxSelectionBar,this.boxSelectionWidth,this.boxSelectionChannel,this.boxSelectionHeight))}muteChannels(t){if(t){let t=!1;for(let e=0;e<this.j.song.channels.length;e++)if(this.j.song.channels[e].muted){t=!0;break}for(let e=0;e<this.j.song.channels.length;e++)this.j.song.channels[e].muted=!t}else{let t=!1;for(const e of this.nc())if(!this.j.song.channels[e].muted){t=!0;break}for(const e of this.nc())this.j.song.channels[e].muted=t}this.j.notifier.changed()}soloChannels(t){let e=!0;for(let i=0;i<this.j.song.channels.length;i++){const s=i<this.boxSelectionChannel||i>=this.boxSelectionChannel+this.boxSelectionHeight?!t:t;if(this.j.song.channels[i].muted!=s){e=!1;break}}if(e)for(let t=0;t<this.j.song.channels.length;t++)this.j.song.channels[t].muted=!1;else for(let e=0;e<this.j.song.channels.length;e++)this.j.song.channels[e].muted=e<this.boxSelectionChannel||e>=this.boxSelectionChannel+this.boxSelectionHeight?!t:t;this.j.notifier.changed()}forceRhythm(){const t=new zt;this.boxSelectionActive&&t.append(new gi(this.j,this.boxSelectionBar,this.boxSelectionWidth,this.boxSelectionChannel,this.boxSelectionHeight));for(const e of this.nc())for(const i of this.oc(e))t.append(new Ue(this.j,i));this.j.record(t)}forceScale(){const t=new zt;this.boxSelectionActive&&t.append(new gi(this.j,this.boxSelectionBar,this.boxSelectionWidth,this.boxSelectionChannel,this.boxSelectionHeight));const i=[!0,!1,!1,!1,!1,!1,!1,!1,!1,!1,!1,!1];for(const t of this.nc())if(!this.j.song.getChannelIsNoise(t))for(const e of this.oc(t))Ot(e,i);const s=function(t,i){const s=e.scales[i].flags,n=[],o=[];for(let e=0;e<12;e++)t[e]&&n.push(e),s[e]&&o.push(e);const r=n.length>o.length,h=r?o:n,a=r?n:o,l=["root","second","second","third","third","fourth","tritone","fifth","sixth","sixth","seventh","seventh","root"];let c=Number.MAX_SAFE_INTEGER,u=[];const f=[[0]];for(;f.length>0;){const t=f.pop();if(t.length==h.length){let e=0;for(let i=0;i<t.length;i++)e+=Math.abs(h[i]-a[t[i]]),l[h[i]]!=l[a[t[i]]]&&(e+=.75);c>e&&(c=e,u=t)}else{const e=t[t.length-1]+1,i=a.length-h.length+t.length;for(let s=e;s<=i;s++)f.push(t.concat(s))}}const p=[];for(let t=0;t<u.length;t++){const e=h[t],i=a[u[t]];p[t]=r?[i,e]:[e,i]}p.push([12,12]),o.push(12);let d=0;const m=[];for(let t=0;t<12;t++){const e=p[d][0],i=p[d][1],s=p[d+1][0],n=p[d+1][1];t==s-1&&d++;const r=(t-e)*(n-i)/(s-e)+i;let h=0,a=Number.MAX_SAFE_INTEGER;for(const e of o){let i=Math.abs(e-r);l[e]!=l[t]&&(i+=.1),a>i&&(a=i,h=e)}m[t]=h}return m}(i,this.j.song.scale);for(const e of this.nc())if(!this.j.song.getChannelIsNoise(e))for(const i of this.oc(e))t.append(new bi(this.j,i,s));this.j.record(t)}setTrackSelection(t,e,i,s){const n=this.j.lastChangeWas(this.ic);this.ic=new zt,this.ic.append(new di(this.j,t,e,i,s)),this.j.hasRedoHistory()||this.j.record(this.ic,n)}transpose(t,e){const i=this.j.lastChangeWas(this.tc);this.tc=new zt,this.boxSelectionActive&&this.tc.append(new gi(this.j,this.boxSelectionBar,this.boxSelectionWidth,this.boxSelectionChannel,this.boxSelectionHeight));for(const i of this.nc())for(const s of this.oc(i))this.tc.append(new pi(this.j,i,s,t,this.j.prefs.notesOutsideScale,e));this.j.record(this.tc,i)}swapChannels(t){const e=[this.j.song.pitchChannelCount,this.j.song.pitchChannelCount+this.j.song.noiseChannelCount,this.j.song.getChannelCount()];let i=0,s=0;for(const n of e){if(this.boxSelectionChannel<n&&t<0||this.boxSelectionChannel+this.boxSelectionHeight<=n){s=n-1;break}i=n}const n=Math.max(this.boxSelectionChannel,i),o=Math.min(this.boxSelectionChannel+this.boxSelectionHeight-1,s);if(t=Math.max(t,i-n),0!=(t=Math.min(t,s-o))){const e=this.j.lastChangeWas(this.ec);this.ec=new zt,this.boxSelectionY0=n+t,this.boxSelectionY1=o+t,this.ec.append(new Qt(this.j,n,o,t)),this.ec.append(new ee(this.j,Math.max(this.boxSelectionY0,Math.min(this.boxSelectionY1,this.j.channel+t)),this.j.bar)),this.selectionUpdated(),this.j.record(this.ec,e)}}selectInstrument(t){if(this.j.viewedInstrument[this.j.channel]==t){if(this.j.song.layeredInstruments&&this.j.song.patternInstruments){const e=this.j.lastChangeWas(this.sc);this.sc=new zt;const i=this.j.recentPatternInstruments[this.j.channel];if(this.j.notifier.changed(),-1==i.indexOf(t)){i.push(t);const e=this.j.song.getMaxInstrumentsPerPattern(this.j.channel);i.length>e&&i.splice(0,i.length-e)}else i.splice(i.indexOf(t),1),0==i.length&&(i[0]=0);this.boxSelectionActive&&this.sc.append(new gi(this.j,this.boxSelectionBar,this.boxSelectionWidth,this.boxSelectionChannel,this.boxSelectionHeight));for(const t of this.nc())for(const e of this.oc(t))this.sc.append(new Re(this.j,t,i,e));this.j.record(this.sc,e)}}else{const e=this.j.lastChangeWas(this.sc);if(this.sc=new zt,this.sc.append(new Ee(this.j,t)),!this.j.song.layeredInstruments&&this.j.song.patternInstruments){this.boxSelectionActive&&this.sc.append(new gi(this.j,this.boxSelectionBar,this.boxSelectionWidth,this.boxSelectionChannel,this.boxSelectionHeight));const i=[t];for(const t of this.nc())for(const e of this.oc(t))this.sc.append(new Re(this.j,t,i,e));this.j.record(this.sc,e)}else this.j.hasRedoHistory()||this.j.record(this.sc,e)}}resetBoxSelection(){this.boxSelectionX0=this.boxSelectionX1=this.j.bar,this.boxSelectionY0=this.boxSelectionY1=this.j.channel}}class Jn{constructor(){this.volume=75,this.visibleOctaves=Jn.defaultVisibleOctaves,this.reload()}reload(){this.autoPlay="true"==window.localStorage.getItem("autoPlay"),this.autoFollow="false"!=window.localStorage.getItem("autoFollow"),this.enableNotePreview="false"!=window.localStorage.getItem("enableNotePreview"),this.showFifth="true"==window.localStorage.getItem("showFifth"),this.notesOutsideScale="true"==window.localStorage.getItem("notesOutsideScale"),this.showLetters="true"==window.localStorage.getItem("showLetters"),this.showChannels="true"==window.localStorage.getItem("showChannels"),this.showScrollBar="true"==window.localStorage.getItem("showScrollBar"),this.alwaysShowSettings="true"==window.localStorage.getItem("alwaysShowSettings"),this.instrumentCopyPaste="true"==window.localStorage.getItem("instrumentCopyPaste"),this.enableChannelMuting="true"==window.localStorage.getItem("enableChannelMuting"),this.displayBrowserUrl="false"!=window.localStorage.getItem("displayBrowserUrl"),this.pressControlForShortcuts="true"==window.localStorage.getItem("pressControlForShortcuts"),this.enableMidi="false"!=window.localStorage.getItem("enableMidi"),this.showRecordButton="true"==window.localStorage.getItem("showRecordButton"),this.snapRecordedNotesToRhythm="true"==window.localStorage.getItem("snapRecordedNotesToRhythm"),this.ignorePerformedNotesNotInScale="true"==window.localStorage.getItem("ignorePerformedNotesNotInScale"),this.metronomeCountIn="false"!=window.localStorage.getItem("metronomeCountIn"),this.metronomeWhileRecording="false"!=window.localStorage.getItem("metronomeWhileRecording"),this.keyboardLayout=window.localStorage.getItem("keyboardLayout")||"wickiHayden",this.layout=window.localStorage.getItem("layout")||"small",this.colorTheme=window.localStorage.getItem("colorTheme")||"dark classic",this.visibleOctaves=window.localStorage.getItem("visibleOctaves")>>>0||Jn.defaultVisibleOctaves;const t=e.scales.dictionary[window.localStorage.getItem("defaultScale")];this.defaultScale=null!=t?t.index:0,null!=window.localStorage.getItem("volume")&&(this.volume=Math.min(window.localStorage.getItem("volume")>>>0,75)),null!=window.localStorage.getItem("fullScreen")&&("true"==window.localStorage.getItem("fullScreen")&&(this.layout="long"),window.localStorage.removeItem("fullScreen"))}save(){window.localStorage.setItem("autoPlay",this.autoPlay?"true":"false"),window.localStorage.setItem("autoFollow",this.autoFollow?"true":"false"),window.localStorage.setItem("enableNotePreview",this.enableNotePreview?"true":"false"),window.localStorage.setItem("showFifth",this.showFifth?"true":"false"),window.localStorage.setItem("notesOutsideScale",this.notesOutsideScale?"true":"false"),window.localStorage.setItem("defaultScale",e.scales[this.defaultScale].name),window.localStorage.setItem("showLetters",this.showLetters?"true":"false"),window.localStorage.setItem("showChannels",this.showChannels?"true":"false"),window.localStorage.setItem("showScrollBar",this.showScrollBar?"true":"false"),window.localStorage.setItem("alwaysShowSettings",this.alwaysShowSettings?"true":"false"),window.localStorage.setItem("enableChannelMuting",this.enableChannelMuting?"true":"false"),window.localStorage.setItem("instrumentCopyPaste",this.instrumentCopyPaste?"true":"false"),window.localStorage.setItem("displayBrowserUrl",this.displayBrowserUrl?"true":"false"),window.localStorage.setItem("pressControlForShortcuts",this.pressControlForShortcuts?"true":"false"),window.localStorage.setItem("enableMidi",this.enableMidi?"true":"false"),window.localStorage.setItem("showRecordButton",this.showRecordButton?"true":"false"),window.localStorage.setItem("snapRecordedNotesToRhythm",this.snapRecordedNotesToRhythm?"true":"false"),window.localStorage.setItem("ignorePerformedNotesNotInScale",this.ignorePerformedNotesNotInScale?"true":"false"),window.localStorage.setItem("metronomeCountIn",this.metronomeCountIn?"true":"false"),window.localStorage.setItem("metronomeWhileRecording",this.metronomeWhileRecording?"true":"false"),window.localStorage.setItem("keyboardLayout",this.keyboardLayout),window.localStorage.setItem("layout",this.layout),window.localStorage.setItem("colorTheme",this.colorTheme),window.localStorage.setItem("volume",String(this.volume)),window.localStorage.setItem("visibleOctaves",String(this.visibleOctaves))}}Jn.defaultVisibleOctaves=3;class Qn{constructor(){this.lc=[],this.cc=!1}watch(t){-1==this.lc.indexOf(t)&&this.lc.push(t)}unwatch(t){const e=this.lc.indexOf(t);-1!=e&&this.lc.splice(e,1)}changed(){this.cc=!0}notifyWatchers(){if(this.cc){this.cc=!1;for(const t of this.lc.concat())t()}}}class Xn{constructor(){this.notifier=new Qn,this.selection=new Yn(this),this.prefs=new Jn,this.channel=0,this.bar=0,this.recentPatternInstruments=[],this.viewedInstrument=[],this.trackVisibleBars=16,this.trackVisibleChannels=4,this.barScrollPos=0,this.channelScrollPos=0,this.prompt=null,this.addedEffect=!1,this.addedEnvelope=!1,this.currentPatternIsDirty=!1,this.uc=new yn,this.fc=null,this.dc=0,this.mc=0,this.yc=!1,this.gc=!1,this.bc=!1,this.wc=()=>{if(this.synth.recording&&this.performance.abortRecording(),null==window.history.state&&""!=window.location.hash){this.dc++,this.vc();const t={canUndo:!0,sequenceNumber:this.dc,bar:this.bar,channel:this.channel,instrument:this.viewedInstrument[this.channel],recoveryUid:this.kc,prompt:null,selection:this.selection.toJSON()};try{new Xe(this,window.location.hash)}catch(t){pn(t)}return this.prompt=t.prompt,this.prefs.displayBrowserUrl?this.Mc(t,this.song.toBase64String()):this.xc(t,this.song.toBase64String()),this.forgetLastChange(),void this.notifier.notifyWatchers()}const t=this.Sc();if(null==t)throw new Error("History state is null.");if(t.sequenceNumber!=this.dc){this.bar=t.bar,this.channel=t.channel,this.viewedInstrument[this.channel]=t.instrument,this.dc=t.sequenceNumber,this.prompt=t.prompt;try{new Xe(this,this.Fc())}catch(t){pn(t)}this.kc=t.recoveryUid,this.selection.fromJSON(t.selection),this.forgetLastChange(),this.notifier.notifyWatchers()}},this.Pc=()=>{this.notifier.notifyWatchers()},this.Ic=()=>{const t=this.song.getChannelCount();for(let e=this.recentPatternInstruments.length;e<t;e++)this.recentPatternInstruments[e]=[0];this.recentPatternInstruments.length=t;for(let e=0;e<t;e++){if(e==this.channel)if(this.song.patternInstruments){const t=this.song.getPattern(this.channel,this.bar);null!=t&&(this.recentPatternInstruments[e]=t.instruments.concat())}else{const t=this.song.channels[this.channel];for(let i=0;i<t.instruments.length;i++)this.recentPatternInstruments[e][i]=i;this.recentPatternInstruments[e].length=t.instruments.length}Bt(this.recentPatternInstruments[e],this.song,e)}for(let e=this.viewedInstrument.length;e<t;e++)this.viewedInstrument[e]=0;this.viewedInstrument.length=t;for(let e=0;e<t;e++){if(this.song.patternInstruments&&!this.song.layeredInstruments&&e==this.channel){const t=this.song.getPattern(this.channel,this.bar);null!=t&&(this.viewedInstrument[e]=t.instruments[0])}this.viewedInstrument[e]=Math.min(0|this.viewedInstrument[e],this.song.channels[e].instruments.length-1)}const e=this.getCurrentPattern();null!=e&&this.song.patternInstruments&&(this.recentPatternInstruments[this.channel]=e.instruments.concat()),(!this.synth.playing&&(this.bar<this.selection.boxSelectionBar||this.selection.boxSelectionBar+this.selection.boxSelectionWidth<=this.bar)||this.channel<this.selection.boxSelectionChannel||this.selection.boxSelectionChannel+this.selection.boxSelectionHeight<=this.channel||this.song.barCount<this.selection.boxSelectionBar+this.selection.boxSelectionWidth||t<this.selection.boxSelectionChannel+this.selection.boxSelectionHeight||1==this.selection.boxSelectionWidth&&1==this.selection.boxSelectionHeight)&&this.selection.resetBoxSelection(),this.barScrollPos=Math.max(0,Math.min(this.song.barCount-this.trackVisibleBars,this.barScrollPos)),this.channelScrollPos=Math.max(0,Math.min(this.song.getChannelCount()-this.trackVisibleChannels,this.channelScrollPos))},this.Tc=()=>{let t;this.bc=!1;try{t=this.song.toBase64String()}catch(t){return void pn(t)}this.yc&&this.dc++,this.gc?this.vc():this.uc.saveVersion(this.kc,t);let e={canUndo:!0,sequenceNumber:this.dc,bar:this.bar,channel:this.channel,instrument:this.viewedInstrument[this.channel],recoveryUid:this.kc,prompt:this.prompt,selection:this.selection.toJSON()};this.yc?this.xc(e,t):this.Mc(e,t),this.yc=!1,this.gc=!1},this.notifier.watch(this.Ic),$.setTheme(this.prefs.colorTheme),U.setLayout(this.prefs.layout),null==window.sessionStorage.getItem("currentUndoIndex")&&(window.sessionStorage.setItem("currentUndoIndex","0"),window.sessionStorage.setItem("oldestUndoIndex","0"),window.sessionStorage.setItem("newestUndoIndex","0"));let t=window.location.hash;""==t&&(t=this.Fc());try{this.song=new wt(t),""!=t&&null!=t||(Qe(this.song),this.song.scale=this.prefs.defaultScale)}catch(t){pn(t)}t=this.song.toBase64String(),this.synth=new Ft(this.song),this.synth.volume=this.qc(),this.synth.anticipatePoorPerformance=k;let e=this.Sc();null==e&&(e={canUndo:!1,sequenceNumber:0,bar:0,channel:0,instrument:0,recoveryUid:fn(),prompt:null,selection:this.selection.toJSON()}),null==e.recoveryUid&&(e.recoveryUid=fn()),this.Mc(e,t),window.addEventListener("hashchange",this.wc),window.addEventListener("popstate",this.wc),this.bar=0|e.bar,this.channel=0|e.channel;for(let t=0;t<=this.channel;t++)this.viewedInstrument[t]=0;this.viewedInstrument[this.channel]=0|e.instrument,this.kc=e.recoveryUid,this.prompt=e.prompt,this.selection.fromJSON(e.selection),this.selection.scrollToSelectedPattern();for(const t of["input","change","click","keyup","keydown","mousedown","mousemove","mouseup","touchstart","touchmove","touchend","touchcancel"])window.addEventListener(t,this.Pc);this.Ic(),this.performance=new Kn(this)}toggleDisplayBrowserUrl(){const t=this.Sc();if(null==t)throw new Error("History state is null.");this.prefs.displayBrowserUrl=!this.prefs.displayBrowserUrl,this.Mc(t,this.song.toBase64String())}Sc(){if(this.prefs.displayBrowserUrl)return window.history.state;{const t=JSON.parse(window.sessionStorage.getItem(window.sessionStorage.getItem("currentUndoIndex")));return null==t?null:t.state}}Fc(){if(this.prefs.displayBrowserUrl)return window.location.hash;{const t=JSON.parse(window.sessionStorage.getItem(window.sessionStorage.getItem("currentUndoIndex")));return null==t?"":t.hash}}Mc(t,e){this.prefs.displayBrowserUrl?window.history.replaceState(t,"","#"+e):(window.sessionStorage.setItem(window.sessionStorage.getItem("currentUndoIndex")||"0",JSON.stringify({state:t,hash:e})),window.history.replaceState(null,"",location.pathname))}xc(t,e){if(this.prefs.displayBrowserUrl)window.history.pushState(t,"","#"+e);else{let i=Number(window.sessionStorage.getItem("currentUndoIndex")),s=Number(window.sessionStorage.getItem("oldestUndoIndex"));i=(i+1)%Xn.Ec,window.sessionStorage.setItem("currentUndoIndex",String(i)),window.sessionStorage.setItem("newestUndoIndex",String(i)),i==s&&(s=(s+1)%Xn.Ec,window.sessionStorage.setItem("oldestUndoIndex",String(s))),window.sessionStorage.setItem(String(i),JSON.stringify({state:t,hash:e})),window.history.replaceState(null,"",location.pathname)}this.mc=t.sequenceNumber}hasRedoHistory(){return this.mc>this.dc}Cc(){if(this.prefs.displayBrowserUrl)window.history.forward();else{let t=Number(window.sessionStorage.getItem("currentUndoIndex"));t!=Number(window.sessionStorage.getItem("newestUndoIndex"))&&(t=(t+1)%Xn.Ec,window.sessionStorage.setItem("currentUndoIndex",String(t)),setTimeout(this.wc))}}Lc(){if(this.prefs.displayBrowserUrl)window.history.back();else{let t=Number(window.sessionStorage.getItem("currentUndoIndex"));t!=Number(window.sessionStorage.getItem("oldestUndoIndex"))&&(t=(t+Xn.Ec-1)%Xn.Ec,window.sessionStorage.setItem("currentUndoIndex",String(t)),setTimeout(this.wc))}}record(t,e=!1,i=!1){t.isNoop()?(this.fc=null,e&&this.Lc()):(t.commit(),this.fc=t,this.yc=this.yc||!e,this.gc=this.gc||i,this.bc||(window.requestAnimationFrame(this.Tc),this.bc=!0))}vc(){this.kc=fn()}openPrompt(t){this.prompt=t;const e=this.song.toBase64String();this.dc++;const i={canUndo:!0,sequenceNumber:this.dc,bar:this.bar,channel:this.channel,instrument:this.viewedInstrument[this.channel],recoveryUid:this.kc,prompt:this.prompt,selection:this.selection.toJSON()};this.xc(i,e)}undo(){const t=this.Sc();(null==t||t.canUndo)&&this.Lc()}redo(){this.Cc()}setProspectiveChange(t){this.fc=t}forgetLastChange(){this.fc=null}lastChangeWas(t){return null!=t&&t==this.fc}goBackToStart(){this.bar=0,this.channel=0,this.barScrollPos=0,this.channelScrollPos=0,this.synth.snapToStart(),this.notifier.changed()}setVolume(t){this.prefs.volume=t,this.prefs.save(),this.synth.volume=this.qc()}qc(){return Math.min(1,Math.pow(this.prefs.volume/50,.5))*Math.pow(2,(this.prefs.volume-75)/25)}getCurrentPattern(t=0){return this.song.getPattern(this.channel,this.bar+t)}getCurrentInstrument(t=0){return this.viewedInstrument[this.channel]}getMobileLayout(){return window.innerWidth<=710}getBarWidth(){return this.getMobileLayout()||!this.prefs.enableChannelMuting||this.getFullScreen()?32:30}getFullScreen(){return!this.getMobileLayout()&&"small"!=this.prefs.layout}getVisibleOctaveCount(){return this.getFullScreen()?this.prefs.visibleOctaves:Jn.defaultVisibleOctaves}getVisiblePitchCount(){return this.getVisibleOctaveCount()*e.pitchesPerOctave+1}getBaseVisibleOctave(t){const i=this.getVisibleOctaveCount();return Math.max(0,Math.min(e.pitchOctaves-i,Math.ceil(this.song.channels[t].octave-.5*i)))}}Xn.Ec=100;const Zn=new Xn,to=new Wn(Zn);if(document.getElementById("beepboxEditorContainer").appendChild(to.mainLayer),to.whenUpdated(),to.mainLayer.focus(),!k&&Zn.prefs.autoPlay){function t(){document.hidden||(Zn.synth.play(),to.updatePlayButton(),window.removeEventListener("visibilitychange",t))}document.hidden?window.addEventListener("visibilitychange",t):t()}return"scrollRestoration"in history&&(history.scrollRestoration="manual"),to.updatePlayButton(),"serviceWorker"in navigator&&navigator.serviceWorker.register("/service_worker.js",{updateViaCache:"all",scope:"/"}).catch((()=>{})),t.ChangePreset=_t,t.Channel=bt,t.ColorConfig=$,t.Config=e,t.EditorConfig=x,t.ExportPrompt=tn,t.Instrument=gt,t.Note=ht,t.Pattern=at,t.Song=wt,t.SongDocument=Xn,t.SongEditor=Wn,t.Synth=Ft,Object.defineProperty(t,"zc",{value:!0}),t}({});
//# sourceMappingURL=beepbox_editor.min.js.map
</script>
</body></html>