moontide-mcp 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +372 -2
- package/dist/ask.js +634 -0
- package/dist/build-id.js +85 -0
- package/dist/catalog.js +454 -0
- package/dist/drum-maps.js +119 -0
- package/dist/edit-code.js +237 -0
- package/dist/history.js +692 -0
- package/dist/import-midnam.js +185 -0
- package/dist/index.js +93 -0
- package/dist/instruments.js +1316 -0
- package/dist/listen.js +88 -0
- package/dist/mcp.js +787 -0
- package/dist/midi-state.js +270 -0
- package/dist/midnam.js +571 -0
- package/dist/open-browser.js +54 -0
- package/dist/protocol.js +341 -0
- package/dist/reference.js +102 -0
- package/dist/rig-util.js +79 -0
- package/dist/session-label.js +35 -0
- package/dist/session.js +2039 -0
- package/dist/start.js +192 -0
- package/dist/version.js +32 -0
- package/dist/web-server.js +353 -0
- package/instruments/mt32.json +208 -0
- package/instruments/sc55.json +441 -0
- package/package.json +64 -4
- package/page/ask-view.js +533 -0
- package/page/ask.js +697 -0
- package/page/bar-model.js +296 -0
- package/page/change-timing.js +204 -0
- package/page/drum-lane.js +61 -0
- package/page/evaluate-tag.js +38 -0
- package/page/harmony.js +191 -0
- package/page/history-view.js +849 -0
- package/page/history.js +543 -0
- package/page/index.html +121 -0
- package/page/instruments-model.js +793 -0
- package/page/instruments-view.js +894 -0
- package/page/jam-analysis.js +662 -0
- package/page/jam-model.js +585 -0
- package/page/jam-view.js +518 -0
- package/page/load-failure-view.js +142 -0
- package/page/load-failure.js +96 -0
- package/page/main.js +4402 -0
- package/page/midi-clock.js +621 -0
- package/page/midi-controls.js +678 -0
- package/page/midi-out.js +2612 -0
- package/page/midi-plan.js +1098 -0
- package/page/midi-rig.js +655 -0
- package/page/midi-view.js +298 -0
- package/page/mixer-gesture.js +208 -0
- package/page/mixer-model.js +1206 -0
- package/page/mixer-registry.js +493 -0
- package/page/mixer-rewrite.js +1563 -0
- package/page/mixer-view.js +2003 -0
- package/page/parts.js +652 -0
- package/page/problem-view.js +269 -0
- package/page/query-check.js +182 -0
- package/page/session-identity.js +58 -0
- package/page/session-view.js +208 -0
- package/page/split-model.js +97 -0
- package/page/split-view.js +157 -0
- package/page/style.css +5355 -0
- package/page/takeover.js +253 -0
- package/page/tempo-guard.js +87 -0
- package/page/timeline.js +561 -0
- package/page/top-bar-view.js +138 -0
- package/page/tracks.js +710 -0
- package/page/ui-state.js +273 -0
- package/page/views.js +265 -0
- package/reference/effects.md +119 -0
- package/reference/functions.md +167 -0
- package/reference/midi.md +111 -0
- package/reference/mini-notation.md +118 -0
- package/reference/sounds.md +202 -0
- package/reference/theory.md +407 -0
- package/reference/tidal-differences.md +106 -0
- package/reference/transitions.md +140 -0
|
@@ -0,0 +1,1563 @@
|
|
|
1
|
+
// Pure module for the Mixer view: reads a track's chain out of the playing code and writes a
|
|
2
|
+
// control change back as a list of `{ from, to, insert }` edits. Only the track's "spine" is
|
|
3
|
+
// ever read or written: the outer `.method(args)` calls of the track expression, down to its
|
|
4
|
+
// root call. Calls inside function arguments (`.every(2, x => x.gain(0.5))`) are never touched,
|
|
5
|
+
// and every byte of the program outside the edits is preserved.
|
|
6
|
+
// `parse` (acorn) is injected — Node resolves the `acorn` package directly, the browser reads
|
|
7
|
+
// the pinned `window.acorn` global — so this module has no DOM access at import time and can be
|
|
8
|
+
// imported directly by node:test and by page/main.js without a build step.
|
|
9
|
+
//
|
|
10
|
+
// The mixer never guesses where to write: a track that depends on a runtime
|
|
11
|
+
// condition or is written in a shape this module does not understand is refused with a reason
|
|
12
|
+
// code, and the caller disables that track's controls. A track built from a declared constant or
|
|
13
|
+
// function is written at the end of its own chain, so the declaration and the other tracks that
|
|
14
|
+
// read it are never touched.
|
|
15
|
+
|
|
16
|
+
import { PARSE_OPTIONS, SOLO_MARKER, extractTracks, trackNodes, isRuntimeConditional, parseLabel } from './tracks.js';
|
|
17
|
+
import { BUSES, BUS_IDS, COMPRESSOR_FIELDS, CHAIN_ORDER, DEFAULT_POSTGAIN, EFFECTS, EFFECT_IDS, MOVE_OVER_MAX, MOVE_OVER_MIN, MOVE_SHAPES, SENDS, busParamById, clampToParam, effectById, effectOfMethod, fixedValueOf, formatNumber, methodOf, moveText, normalizeStoredCall, roundTo, roundToParam, storedCallText } from './mixer-registry.js';
|
|
18
|
+
|
|
19
|
+
/** Why a track is refused; the view maps each to one short line. */
|
|
20
|
+
export const REFUSAL_REASONS = ['condition', 'unsupported-shape'];
|
|
21
|
+
|
|
22
|
+
const REASON_MESSAGES = {
|
|
23
|
+
condition: 'this track depends on a condition, so the mixer cannot edit it.',
|
|
24
|
+
'unsupported-shape': 'this track is written in a shape the mixer does not understand.',
|
|
25
|
+
'track-gone': 'this track is not in the code any more.',
|
|
26
|
+
'unsupported-change': 'the mixer cannot make this change to this track.',
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* A rewrite the mixer refuses. `reason` is one of REFUSAL_REASONS, or 'track-gone' (the identity
|
|
31
|
+
* is not in the code any more) or 'unsupported-change' (a change this track's code cannot take,
|
|
32
|
+
* such as gain and post-gain both moving). The message always starts with 'Moontide: '.
|
|
33
|
+
*/
|
|
34
|
+
export class MixerRewriteError extends Error {
|
|
35
|
+
constructor(reason, detail) {
|
|
36
|
+
super(`Moontide: ${detail ?? REASON_MESSAGES[reason] ?? reason}`);
|
|
37
|
+
this.name = 'MixerRewriteError';
|
|
38
|
+
this.reason = reason;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Applies `edits` — `{ from, to, insert }` in ORIGINAL coordinates — and returns the rebuilt
|
|
44
|
+
* text. Edits are sorted by `from`; two edits that overlap throw. Every other byte is kept.
|
|
45
|
+
*/
|
|
46
|
+
export function applyEdits(code, edits) {
|
|
47
|
+
const sorted = [...edits].sort((a, b) => a.from - b.from || a.to - b.to);
|
|
48
|
+
let out = '';
|
|
49
|
+
let pos = 0;
|
|
50
|
+
for (const edit of sorted) {
|
|
51
|
+
if (edit.from < pos) {
|
|
52
|
+
throw new Error(`Moontide: two mixer edits overlap at offset ${edit.from}.`);
|
|
53
|
+
}
|
|
54
|
+
out += code.slice(pos, edit.from) + edit.insert;
|
|
55
|
+
pos = edit.to;
|
|
56
|
+
}
|
|
57
|
+
return out + code.slice(pos);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The same edits mapped to NEW coordinates, `[{ from, to }]` ascending: the ranges of the
|
|
62
|
+
* rebuilt text that the edits wrote, for the touched-line highlight. Sorted like applyEdits.
|
|
63
|
+
*/
|
|
64
|
+
export function touchedRanges(edits) {
|
|
65
|
+
const sorted = [...edits].sort((a, b) => a.from - b.from || a.to - b.to);
|
|
66
|
+
let delta = 0;
|
|
67
|
+
const ranges = [];
|
|
68
|
+
for (const edit of sorted) {
|
|
69
|
+
const from = edit.from + delta;
|
|
70
|
+
ranges.push({ from, to: from + edit.insert.length });
|
|
71
|
+
delta += edit.insert.length - (edit.to - edit.from);
|
|
72
|
+
}
|
|
73
|
+
return ranges;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// --- Reading the spine ---
|
|
77
|
+
|
|
78
|
+
/** The names of the calls this module reads and writes (the volume). */
|
|
79
|
+
const MIXER_CALLS = new Set(['gain', 'postgain']);
|
|
80
|
+
|
|
81
|
+
/** The numeric value of a number Literal, or of a negated one (`-N`); null for anything else.
|
|
82
|
+
* Same rule as page/parts.js numericLiteralValue, with one more limit: a value the mixer can
|
|
83
|
+
* neither show nor write back (Infinity from `1e400`, or 1e21 and above, which formatNumber
|
|
84
|
+
* refuses) is not read as a number, so the track reads as moving instead of crashing the mixer. */
|
|
85
|
+
function numericLiteralValue(node) {
|
|
86
|
+
if (!node) return null;
|
|
87
|
+
let value = null;
|
|
88
|
+
if (node.type === 'Literal' && typeof node.value === 'number') value = node.value;
|
|
89
|
+
else if (node.type === 'UnaryExpression' && node.operator === '-' && node.argument.type === 'Literal' && typeof node.argument.value === 'number') {
|
|
90
|
+
value = -node.argument.value;
|
|
91
|
+
}
|
|
92
|
+
return value !== null && Number.isFinite(value) && Math.abs(value) < 1e21 ? value : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Adds every identifier a binding pattern declares (destructuring included) to `names`. */
|
|
96
|
+
function collectPatternNames(pattern, names) {
|
|
97
|
+
if (!pattern) return;
|
|
98
|
+
if (pattern.type === 'Identifier') {
|
|
99
|
+
names.add(pattern.name);
|
|
100
|
+
} else if (pattern.type === 'ObjectPattern') {
|
|
101
|
+
for (const property of pattern.properties) {
|
|
102
|
+
collectPatternNames(property.type === 'RestElement' ? property.argument : property.value, names);
|
|
103
|
+
}
|
|
104
|
+
} else if (pattern.type === 'ArrayPattern') {
|
|
105
|
+
for (const element of pattern.elements) collectPatternNames(element, names);
|
|
106
|
+
} else if (pattern.type === 'AssignmentPattern') {
|
|
107
|
+
collectPatternNames(pattern.left, names);
|
|
108
|
+
} else if (pattern.type === 'RestElement') {
|
|
109
|
+
collectPatternNames(pattern.argument, names);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Every name declared at the top level of the program: variables (destructured names too),
|
|
114
|
+
* functions and classes. A track rooted in one of them is built by shared code the mixer cannot
|
|
115
|
+
* see into; it still writes at the end of the track's own chain (see `sharedRoot`). Exported because
|
|
116
|
+
* page/midi-controls.js reads it too: a declared name keeps a MIDI track's strip. */
|
|
117
|
+
export function topLevelDeclaredNames(ast) {
|
|
118
|
+
const names = new Set();
|
|
119
|
+
for (const statement of ast.body) {
|
|
120
|
+
if (statement.type === 'VariableDeclaration') {
|
|
121
|
+
for (const declarator of statement.declarations) collectPatternNames(declarator.id, names);
|
|
122
|
+
} else if ((statement.type === 'FunctionDeclaration' || statement.type === 'ClassDeclaration') && statement.id) {
|
|
123
|
+
names.add(statement.id.name);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return names;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Calls `visit` for every AST node under (and including) `node`. Exported because page/midi-controls.js walks trees too. */
|
|
130
|
+
export function walkNodes(node, visit) {
|
|
131
|
+
if (node === null || typeof node !== 'object') return;
|
|
132
|
+
if (Array.isArray(node)) {
|
|
133
|
+
for (const child of node) walkNodes(child, visit);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (typeof node.type !== 'string') return;
|
|
137
|
+
visit(node);
|
|
138
|
+
for (const key of Object.keys(node)) {
|
|
139
|
+
if (key !== 'type') walkNodes(node[key], visit);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The child nodes of `node`, in source order of their keys. */
|
|
144
|
+
function childNodes(node) {
|
|
145
|
+
const children = [];
|
|
146
|
+
for (const key of Object.keys(node)) {
|
|
147
|
+
const value = node[key];
|
|
148
|
+
if (Array.isArray(value)) {
|
|
149
|
+
for (const item of value) if (item !== null && typeof item === 'object' && typeof item.type === 'string') children.push(item);
|
|
150
|
+
} else if (value !== null && typeof value === 'object' && typeof value.type === 'string') {
|
|
151
|
+
children.push(value);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return children;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const FUNCTION_TYPES = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
|
|
158
|
+
|
|
159
|
+
/** The names a list of statements declares in its own block: let, const, class and function declarations. */
|
|
160
|
+
function lexicalNames(statements) {
|
|
161
|
+
const names = new Set();
|
|
162
|
+
for (const statement of statements) {
|
|
163
|
+
if (statement.type === 'VariableDeclaration' && statement.kind !== 'var') {
|
|
164
|
+
for (const declarator of statement.declarations) collectPatternNames(declarator.id, names);
|
|
165
|
+
} else if ((statement.type === 'FunctionDeclaration' || statement.type === 'ClassDeclaration') && statement.id) {
|
|
166
|
+
names.add(statement.id.name);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return names;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Adds the `var` names and the function declarations under `node` that hoist to its function, without entering nested functions. */
|
|
173
|
+
function hoistedNames(node, names) {
|
|
174
|
+
if (node.type === 'VariableDeclaration' && node.kind === 'var') {
|
|
175
|
+
for (const declarator of node.declarations) collectPatternNames(declarator.id, names);
|
|
176
|
+
}
|
|
177
|
+
for (const child of childNodes(node)) {
|
|
178
|
+
if (child.type === 'FunctionDeclaration' && child.id) names.add(child.id.name);
|
|
179
|
+
if (!FUNCTION_TYPES.has(child.type)) hoistedNames(child, names);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Calls `visit(name)` for every identifier under `root` that reads a binding from outside `root`: not the
|
|
185
|
+
* property of a plain member access (`.scale`), not an object key (`{ lead: 1 }`), not a label, not the target of a plain
|
|
186
|
+
* assignment, not a name a declaration inside `root` introduces, and not a name a parameter, a local
|
|
187
|
+
* binding, a catch clause or a loop shadows at that point. What it reports is a reference to a name declared outside `root`.
|
|
188
|
+
*/
|
|
189
|
+
function walkReferences(root, visit) {
|
|
190
|
+
const isBound = (scope, name) => {
|
|
191
|
+
for (let at = scope; at !== null; at = at.parent) if (at.names.has(name)) return true;
|
|
192
|
+
return false;
|
|
193
|
+
};
|
|
194
|
+
const inner = (scope, names) => ({ names, parent: scope });
|
|
195
|
+
const each = (node, scope) => {
|
|
196
|
+
for (const child of childNodes(node)) go(child, scope);
|
|
197
|
+
};
|
|
198
|
+
const pattern = (node, scope) => {
|
|
199
|
+
if (node === null || node === undefined) return;
|
|
200
|
+
if (node.type === 'Identifier') return;
|
|
201
|
+
if (node.type === 'ObjectPattern') {
|
|
202
|
+
for (const property of node.properties) {
|
|
203
|
+
if (property.type === 'RestElement') {
|
|
204
|
+
pattern(property.argument, scope);
|
|
205
|
+
} else {
|
|
206
|
+
if (property.computed) go(property.key, scope);
|
|
207
|
+
pattern(property.value, scope);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
} else if (node.type === 'ArrayPattern') {
|
|
211
|
+
for (const element of node.elements) pattern(element, scope);
|
|
212
|
+
} else if (node.type === 'AssignmentPattern') {
|
|
213
|
+
pattern(node.left, scope);
|
|
214
|
+
go(node.right, scope);
|
|
215
|
+
} else if (node.type === 'RestElement') {
|
|
216
|
+
pattern(node.argument, scope);
|
|
217
|
+
} else {
|
|
218
|
+
go(node, scope);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
const go = (node, scope) => {
|
|
222
|
+
switch (node.type) {
|
|
223
|
+
case 'Identifier':
|
|
224
|
+
if (!isBound(scope, node.name)) visit(node.name);
|
|
225
|
+
return;
|
|
226
|
+
case 'MemberExpression':
|
|
227
|
+
go(node.object, scope);
|
|
228
|
+
if (node.computed) go(node.property, scope);
|
|
229
|
+
return;
|
|
230
|
+
case 'Property':
|
|
231
|
+
if (node.computed) go(node.key, scope);
|
|
232
|
+
go(node.value, scope);
|
|
233
|
+
return;
|
|
234
|
+
case 'MethodDefinition':
|
|
235
|
+
case 'PropertyDefinition':
|
|
236
|
+
if (node.computed) go(node.key, scope);
|
|
237
|
+
if (node.value) go(node.value, scope);
|
|
238
|
+
return;
|
|
239
|
+
case 'LabeledStatement':
|
|
240
|
+
go(node.body, scope);
|
|
241
|
+
return;
|
|
242
|
+
case 'BreakStatement':
|
|
243
|
+
case 'ContinueStatement':
|
|
244
|
+
case 'MetaProperty':
|
|
245
|
+
return;
|
|
246
|
+
case 'VariableDeclaration':
|
|
247
|
+
for (const declarator of node.declarations) {
|
|
248
|
+
pattern(declarator.id, scope);
|
|
249
|
+
if (declarator.init) go(declarator.init, scope);
|
|
250
|
+
}
|
|
251
|
+
return;
|
|
252
|
+
case 'AssignmentExpression':
|
|
253
|
+
if (node.left.type === 'ObjectPattern' || node.left.type === 'ArrayPattern') pattern(node.left, scope);
|
|
254
|
+
else if (!(node.left.type === 'Identifier' && node.operator === '=')) go(node.left, scope);
|
|
255
|
+
go(node.right, scope);
|
|
256
|
+
return;
|
|
257
|
+
case 'FunctionDeclaration':
|
|
258
|
+
case 'FunctionExpression':
|
|
259
|
+
case 'ArrowFunctionExpression': {
|
|
260
|
+
const names = new Set();
|
|
261
|
+
for (const param of node.params) collectPatternNames(param, names);
|
|
262
|
+
if (node.type === 'FunctionExpression' && node.id) names.add(node.id.name);
|
|
263
|
+
if (node.body.type === 'BlockStatement') hoistedNames(node.body, names);
|
|
264
|
+
const local = inner(scope, names);
|
|
265
|
+
for (const param of node.params) pattern(param, local);
|
|
266
|
+
go(node.body, local);
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
case 'ClassDeclaration':
|
|
270
|
+
case 'ClassExpression': {
|
|
271
|
+
const local = node.type === 'ClassExpression' && node.id ? inner(scope, new Set([node.id.name])) : scope;
|
|
272
|
+
if (node.superClass) go(node.superClass, local);
|
|
273
|
+
go(node.body, local);
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
case 'Program':
|
|
277
|
+
case 'BlockStatement':
|
|
278
|
+
case 'StaticBlock': {
|
|
279
|
+
const local = inner(scope, lexicalNames(node.body));
|
|
280
|
+
for (const statement of node.body) go(statement, local);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
case 'SwitchStatement': {
|
|
284
|
+
go(node.discriminant, scope);
|
|
285
|
+
const local = inner(scope, lexicalNames(node.cases.flatMap((entry) => entry.consequent)));
|
|
286
|
+
for (const entry of node.cases) {
|
|
287
|
+
if (entry.test) go(entry.test, local);
|
|
288
|
+
for (const statement of entry.consequent) go(statement, local);
|
|
289
|
+
}
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
case 'ForStatement':
|
|
293
|
+
case 'ForInStatement':
|
|
294
|
+
case 'ForOfStatement': {
|
|
295
|
+
const head = node.type === 'ForStatement' ? node.init : node.left;
|
|
296
|
+
const names = head && head.type === 'VariableDeclaration' && head.kind !== 'var' ? lexicalNames([head]) : new Set();
|
|
297
|
+
each(node, inner(scope, names));
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
case 'CatchClause': {
|
|
301
|
+
const names = new Set();
|
|
302
|
+
collectPatternNames(node.param, names);
|
|
303
|
+
const local = inner(scope, names);
|
|
304
|
+
pattern(node.param, local);
|
|
305
|
+
go(node.body, local);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
default:
|
|
309
|
+
each(node, scope);
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
go(root, null);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* What the program declares at its top level: `{ declared, bodies }`. `declared` is the Set of
|
|
317
|
+
* topLevelDeclaredNames; `bodies` maps each declared name to the code that defines it (the initializer of its
|
|
318
|
+
* variable or an assignment to it, or its function or class), so a track's reach into shared code can be read (see reachableCode).
|
|
319
|
+
*/
|
|
320
|
+
function readScope(ast) {
|
|
321
|
+
const bodies = new Map();
|
|
322
|
+
const add = (names, body) => {
|
|
323
|
+
for (const name of names) {
|
|
324
|
+
if (!bodies.has(name)) bodies.set(name, []);
|
|
325
|
+
bodies.get(name).push(body);
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
for (const statement of ast.body) {
|
|
329
|
+
if (statement.type === 'VariableDeclaration') {
|
|
330
|
+
for (const declarator of statement.declarations) {
|
|
331
|
+
const names = new Set();
|
|
332
|
+
collectPatternNames(declarator.id, names);
|
|
333
|
+
if (declarator.init) add(names, declarator.init);
|
|
334
|
+
}
|
|
335
|
+
} else if ((statement.type === 'FunctionDeclaration' || statement.type === 'ClassDeclaration') && statement.id) {
|
|
336
|
+
add([statement.id.name], statement);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
// A name assigned later (`let synth; synth = note("c").midi('JX')`, anywhere in the program) is defined by that code too.
|
|
340
|
+
walkNodes(ast, (node) => {
|
|
341
|
+
if (node.type !== 'AssignmentExpression') return;
|
|
342
|
+
const names = new Set();
|
|
343
|
+
collectPatternNames(node.left, names);
|
|
344
|
+
add(names, node.right);
|
|
345
|
+
});
|
|
346
|
+
return { declared: topLevelDeclaredNames(ast), bodies };
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* The code a track's sound can come from, beyond its own chain: `{ expression, declarations }`, the track's
|
|
351
|
+
* `expression` (the arguments of its calls included) and the bodies of the shared code it reaches, that is
|
|
352
|
+
* every declared name that code refers to, transitively. Only a real reference counts (see walkReferences): a method
|
|
353
|
+
* name (`.scale(`), an object key (`{ lead: 1 }`) or a name a parameter or a local binding shadows is not one. `declarations` is empty for a track that names none.
|
|
354
|
+
*/
|
|
355
|
+
function reachableCode(expression, scope) {
|
|
356
|
+
const declarations = [];
|
|
357
|
+
const seen = new Set();
|
|
358
|
+
const queue = [expression];
|
|
359
|
+
while (queue.length > 0) {
|
|
360
|
+
walkReferences(queue.pop(), (name) => {
|
|
361
|
+
if (seen.has(name) || !scope.bodies.has(name)) return;
|
|
362
|
+
seen.add(name);
|
|
363
|
+
for (const body of scope.bodies.get(name)) {
|
|
364
|
+
declarations.push(body);
|
|
365
|
+
queue.push(body);
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
return { expression, declarations };
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** The text of a property key or computed member that is a plain string (or a template without a placeholder), else null. */
|
|
373
|
+
function plainKeyText(node) {
|
|
374
|
+
if (node.type === 'Literal' && typeof node.value === 'string') return node.value;
|
|
375
|
+
if (node.type === 'TemplateLiteral' && node.expressions.length === 0) return node.quasis[0].value.cooked ?? null;
|
|
376
|
+
return null;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** The name a call writes: `.name(`, `['name'](` or a bare `name(`; null for any other callee. */
|
|
380
|
+
function calledName(call) {
|
|
381
|
+
const { callee } = call;
|
|
382
|
+
if (callee.type === 'Identifier') return callee.name;
|
|
383
|
+
if (callee.type !== 'MemberExpression') return null;
|
|
384
|
+
if (!callee.computed) return callee.property.type === 'Identifier' ? callee.property.name : null;
|
|
385
|
+
return plainKeyText(callee.property);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** The names an object literal holds as keys (`{ orbit: 2 }`, `{ 'orbit': 2 }`, `{ orbit }`, `{ ['orbit']: 2 }`). */
|
|
389
|
+
function objectKeyNames(node) {
|
|
390
|
+
const names = [];
|
|
391
|
+
for (const property of node.properties) {
|
|
392
|
+
if (property.type !== 'Property') continue;
|
|
393
|
+
if (!property.computed && property.key.type === 'Identifier') names.push(property.key.name);
|
|
394
|
+
else {
|
|
395
|
+
const text = plainKeyText(property.key);
|
|
396
|
+
if (text !== null) names.push(text);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
return names;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* True when some node under `roots` writes a name that satisfies `test`: a call (`.name(`, `['name'](` or a bare
|
|
404
|
+
* `name(`) that is not one of the `skip` calls, or, unless `keys` is false, an object literal with such a key
|
|
405
|
+
* (`.set({ name: ... })`).
|
|
406
|
+
*/
|
|
407
|
+
function writesName(roots, test, { skip = new Set(), keys = true } = {}) {
|
|
408
|
+
let found = false;
|
|
409
|
+
for (const root of roots) {
|
|
410
|
+
walkNodes(root, (node) => {
|
|
411
|
+
if (found) return;
|
|
412
|
+
if (node.type === 'CallExpression' && !skip.has(node)) {
|
|
413
|
+
const name = calledName(node);
|
|
414
|
+
if (name !== null && test(name)) found = true;
|
|
415
|
+
} else if (keys && node.type === 'ObjectExpression' && objectKeyNames(node).some(test)) {
|
|
416
|
+
found = true;
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
return found;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** The registry keys that decide which bus a sound goes to or is shaped by: the orbit, the two sends and the bus values. */
|
|
424
|
+
const BUS_KEYS = new Set(['orbit', ...Object.values(SENDS).map((send) => send.key), ...BUS_IDS.flatMap((bus) => BUSES[bus].params.map((param) => param.key))]);
|
|
425
|
+
|
|
426
|
+
/** True for a method name (or alias) that writes one of the BUS_KEYS. */
|
|
427
|
+
function writesBusKey(name) {
|
|
428
|
+
const meta = methodOf(name);
|
|
429
|
+
return meta !== null && meta.keys.some((key) => BUS_KEYS.has(key));
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* What a track reaches beyond its own chain: `{ playsMidi, innerPostgain, busHidden }`. `playsMidi` is true when a `.midi(`
|
|
434
|
+
* call (or `['midi'](`, or a bare `midi(`) sits anywhere the track's code reaches (its own chain, the arguments of its calls or shared code it
|
|
435
|
+
* names): MIDI output ignores `postgain`, so a post-gain fader would do nothing on such a track.
|
|
436
|
+
* `innerPostgain` is true when a `.postgain(` call (or a bare `postgain(`, or a `{ postgain }` key as in `.set({ postgain: .5 })`) sits anywhere that code reaches other than on the spine:
|
|
437
|
+
* `postgain` is replaced by a later write like `gain` is, so a fader's `.postgain(n)` at the end of the chain
|
|
438
|
+
* would flatten it. `busHidden` is true when anything the track reaches, other than the calls of its own chain,
|
|
439
|
+
* writes an orbit, a send or a bus value (a call inside another call, a bare call, `.set({ orbit })`, a constant
|
|
440
|
+
* or a function it names): the spine read cannot see which bus the track is really on, so it must not edit one. The
|
|
441
|
+
* mixer prefers refusing to guessing: any such write, even one it could read, turns the sends off.
|
|
442
|
+
*/
|
|
443
|
+
function readReach(spine, expression, scope) {
|
|
444
|
+
const { declarations } = reachableCode(expression, scope);
|
|
445
|
+
const all = [expression, ...declarations];
|
|
446
|
+
const spineNodes = new Set(spine.calls.map((call) => call.node));
|
|
447
|
+
return {
|
|
448
|
+
playsMidi: writesName(all, (name) => name === 'midi', { keys: false }),
|
|
449
|
+
innerPostgain: writesName(all, (name) => name === 'postgain', { skip: spineNodes }),
|
|
450
|
+
busHidden: writesName(all, writesBusKey, { skip: spineNodes }),
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* The spine of `expression`: `{ calls, root }`, `calls` in source order, each `{ node, name,
|
|
456
|
+
* dotStart }` (`dotStart` the offset of its `.` token), `root` the first node that is not such a
|
|
457
|
+
* call. Throws 'unsupported-shape' when a call's `.` is not a plain dot directly before the
|
|
458
|
+
* method name (a comment between them, or `?.`). Exported because page/midi-controls.js reads the
|
|
459
|
+
* spine of a MIDI track too (it imports this module, never the reverse).
|
|
460
|
+
*/
|
|
461
|
+
export function readSpine(code, expression) {
|
|
462
|
+
const calls = [];
|
|
463
|
+
let cur = expression;
|
|
464
|
+
while (
|
|
465
|
+
cur.type === 'CallExpression' &&
|
|
466
|
+
!cur.optional &&
|
|
467
|
+
cur.callee.type === 'MemberExpression' &&
|
|
468
|
+
!cur.callee.computed &&
|
|
469
|
+
!cur.callee.optional &&
|
|
470
|
+
cur.callee.property.type === 'Identifier'
|
|
471
|
+
) {
|
|
472
|
+
let dot = cur.callee.property.start - 1;
|
|
473
|
+
while (dot > cur.callee.object.end && /\s/.test(code[dot])) dot -= 1;
|
|
474
|
+
if (code[dot] !== '.' || code[dot - 1] === '?') {
|
|
475
|
+
throw new MixerRewriteError('unsupported-shape');
|
|
476
|
+
}
|
|
477
|
+
calls.push({ node: cur, name: cur.callee.property.name, dotStart: dot });
|
|
478
|
+
cur = cur.callee.object;
|
|
479
|
+
}
|
|
480
|
+
calls.reverse();
|
|
481
|
+
return { calls, root: cur };
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** Throws the refusal for a root the mixer does not understand. */
|
|
485
|
+
function checkRoot(root) {
|
|
486
|
+
if (isRuntimeConditional(root)) throw new MixerRewriteError('condition');
|
|
487
|
+
if (root.type === 'CallExpression' && root.callee.type === 'Identifier') return;
|
|
488
|
+
if (root.type === 'Identifier') return;
|
|
489
|
+
if (root.type === 'Literal' && typeof root.value === 'string') return;
|
|
490
|
+
if (root.type === 'TemplateLiteral' || root.type === 'TaggedTemplateExpression') return;
|
|
491
|
+
throw new MixerRewriteError('unsupported-shape');
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** What the LAST spine call named `name` says: `{ kind: 'none'|'fixed'|'pattern', value, call }`.
|
|
495
|
+
* The last writer wins (verified live). */
|
|
496
|
+
function readControl(calls, name) {
|
|
497
|
+
let last = null;
|
|
498
|
+
for (const call of calls) if (call.name === name) last = call;
|
|
499
|
+
if (!last) return { kind: 'none', value: null, call: null };
|
|
500
|
+
const value = numericLiteralValue(last.node.arguments[0]);
|
|
501
|
+
return value === null ? { kind: 'pattern', value: null, call: last } : { kind: 'fixed', value, call: last };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** The text of a string Literal, or null for anything else. */
|
|
505
|
+
function stringLiteralValue(node) {
|
|
506
|
+
return node && node.type === 'Literal' && typeof node.value === 'string' ? node.value : null;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const PLAIN_NUMBER = /^-?(?:\d+\.?\d*|\.\d+)$/;
|
|
510
|
+
|
|
511
|
+
/** The numbers of a compressor string `"t:r:k:a:l"` (one to five plain numbers), or null. */
|
|
512
|
+
function compressorStringFields(text) {
|
|
513
|
+
const parts = text.split(':');
|
|
514
|
+
if (parts.length > COMPRESSOR_FIELDS.length || !parts.every((part) => PLAIN_NUMBER.test(part))) return null;
|
|
515
|
+
return parts.map(Number);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** True for an argument that can write every key of a method's pack: a string with a `:` in it
|
|
519
|
+
* (`"300:4"`). A number, a signal or any other pattern of plain values writes only the first key. */
|
|
520
|
+
function packedArgument(node) {
|
|
521
|
+
const text = stringLiteralValue(node);
|
|
522
|
+
if (text !== null) return text.includes(':');
|
|
523
|
+
return node.type === 'TemplateLiteral' && node.quasis.some((quasi) => quasi.value.raw.includes(':'));
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** True for a call `.name(...)` written with a plain dot on an expression: not `?.`, not `obj[name]`. */
|
|
527
|
+
function plainMethodCall(node, name) {
|
|
528
|
+
return (
|
|
529
|
+
node.type === 'CallExpression' &&
|
|
530
|
+
!node.optional &&
|
|
531
|
+
node.callee.type === 'MemberExpression' &&
|
|
532
|
+
!node.callee.computed &&
|
|
533
|
+
!node.callee.optional &&
|
|
534
|
+
node.callee.property.type === 'Identifier' &&
|
|
535
|
+
node.callee.property.name === name
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* The filter move `arg` writes, `{ shape, from, to, over }`, or null. Exactly `X.range(a, b).slow(N)`
|
|
541
|
+
* is read: `X` a bare sine, tri or saw that the program does not declare itself, `a` and `b` number
|
|
542
|
+
* literals inside the parameter's range, `N` a whole number literal from MOVE_OVER_MIN to
|
|
543
|
+
* MOVE_OVER_MAX. Every other pattern is null and stays "Moving (from code)": the mixer never guesses.
|
|
544
|
+
*/
|
|
545
|
+
function readMove(arg, param, declared) {
|
|
546
|
+
if (!param.movable || !plainMethodCall(arg, 'slow') || arg.arguments.length !== 1) return null;
|
|
547
|
+
const over = numericLiteralValue(arg.arguments[0]);
|
|
548
|
+
if (over === null || !Number.isInteger(over) || over < MOVE_OVER_MIN || over > MOVE_OVER_MAX) return null;
|
|
549
|
+
const range = arg.callee.object;
|
|
550
|
+
if (!plainMethodCall(range, 'range') || range.arguments.length !== 2) return null;
|
|
551
|
+
const [from, to] = range.arguments.map(numericLiteralValue);
|
|
552
|
+
if (from === null || to === null) return null;
|
|
553
|
+
if (from < param.min || from > param.max || to < param.min || to > param.max) return null;
|
|
554
|
+
const shape = range.callee.object;
|
|
555
|
+
if (shape.type !== 'Identifier' || !MOVE_SHAPES.includes(shape.name) || declared.has(shape.name)) return null;
|
|
556
|
+
return { shape: shape.name, from, to, over };
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* What the calls of the track say about one parameter: `{ kind: 'unwritten'|'fixed'|'move'|'pattern',
|
|
561
|
+
* value, method }` (`move` only for the cutoff of a filter, with `move: { shape, from, to, over }`, see readMove). The last call that writes the parameter's control key wins (verified live):
|
|
562
|
+
* a plain value (a number, a signal, a pattern of numbers) writes only its method's first key, a
|
|
563
|
+
* string with a `:` in it may write every key of the pack. A parameter is 'fixed' only for a
|
|
564
|
+
* numeric literal (for a select, a string literal from its own list written by its own method).
|
|
565
|
+
*/
|
|
566
|
+
function readParam(calls, param, declared) {
|
|
567
|
+
const keys = param.alt ? [param.key, param.alt.key] : [param.key];
|
|
568
|
+
let last = null;
|
|
569
|
+
let lastIsPrimary = false;
|
|
570
|
+
for (const call of calls) {
|
|
571
|
+
const meta = methodOf(call.name);
|
|
572
|
+
const arg = call.node.arguments[0];
|
|
573
|
+
if (!meta || !arg) continue;
|
|
574
|
+
const writes = packedArgument(arg) ? meta.keys.some((key) => keys.includes(key)) : keys.includes(meta.keys[0]);
|
|
575
|
+
if (!writes) continue;
|
|
576
|
+
// The per-cycle form wins over the Hz form of a parameter with `alt` (`tremolosync` over
|
|
577
|
+
// `tremolo`, whatever the order): the Hz call is read only while no per-cycle call writes it.
|
|
578
|
+
if (param.alt && lastIsPrimary && meta.canonical !== param.method) continue;
|
|
579
|
+
if (param.alt && meta.canonical === param.method) lastIsPrimary = true;
|
|
580
|
+
last = call;
|
|
581
|
+
}
|
|
582
|
+
if (!last) return { kind: 'unwritten', value: null, method: null, call: null };
|
|
583
|
+
const meta = methodOf(last.name);
|
|
584
|
+
const arg = last.node.arguments[0];
|
|
585
|
+
if (param.kind === 'number') {
|
|
586
|
+
const value = numericLiteralValue(arg);
|
|
587
|
+
if (value !== null) return { kind: 'fixed', value, method: meta.canonical, call: last };
|
|
588
|
+
const move = readMove(arg, param, declared);
|
|
589
|
+
return move === null ? { kind: 'pattern', value: null, method: meta.canonical, call: last } : { kind: 'move', value: null, method: meta.canonical, move, call: last };
|
|
590
|
+
}
|
|
591
|
+
const text = stringLiteralValue(arg);
|
|
592
|
+
if (text !== null && param.options.includes(text) && meta.canonical === param.method) {
|
|
593
|
+
return { kind: 'fixed', value: text, method: meta.canonical, call: last };
|
|
594
|
+
}
|
|
595
|
+
return { kind: 'pattern', value: null, method: meta.canonical, call: last };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** The five compressor fields, folded over every `.compressor(...)` call in source order: a number
|
|
599
|
+
* sets the threshold, a string of plain numbers sets its fields, anything else is a pattern. */
|
|
600
|
+
function readCompressorFields(calls) {
|
|
601
|
+
let fields = COMPRESSOR_FIELDS.map(() => ({ kind: 'unwritten', value: null, method: null }));
|
|
602
|
+
for (const call of calls) {
|
|
603
|
+
const arg = call.node.arguments[0];
|
|
604
|
+
const number = numericLiteralValue(arg);
|
|
605
|
+
if (number !== null) {
|
|
606
|
+
fields[0] = { kind: 'fixed', value: number, method: 'compressor' };
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
const text = stringLiteralValue(arg);
|
|
610
|
+
const parts = text === null ? null : compressorStringFields(text);
|
|
611
|
+
if (parts === null) {
|
|
612
|
+
fields = COMPRESSOR_FIELDS.map(() => ({ kind: 'pattern', value: null, method: 'compressor' }));
|
|
613
|
+
} else {
|
|
614
|
+
parts.forEach((value, i) => {
|
|
615
|
+
fields[i] = { kind: 'fixed', value, method: 'compressor' };
|
|
616
|
+
});
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
return fields;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** Why a bypass is refused: the sentence page/mixer-model.js shows (MIXER_COPY.bypassNeedsFixed). */
|
|
623
|
+
const BYPASS_NEEDS_FIXED = 'Bypass needs fixed values; use a fixed value first, or Remove.';
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* The calls of an effect as a bypass record stores them, or why they cannot be stored: `{ calls,
|
|
627
|
+
* why: null }` (canonical calls in source order: `{ method, value }`, or one `{ method:
|
|
628
|
+
* 'compressor', fields }`), `{ calls: null, why: 'moving' }` for a value that is not fixed in the
|
|
629
|
+
* code, or `{ calls: null, why: 'range' }` for a value outside the registry range.
|
|
630
|
+
*/
|
|
631
|
+
function storableCalls(effect, calls, declared) {
|
|
632
|
+
if (effect.id === 'compressor') {
|
|
633
|
+
const fields = readCompressorFields(calls);
|
|
634
|
+
if (fields.some((field) => field.kind === 'pattern')) return { calls: null, why: 'moving' };
|
|
635
|
+
const values = [];
|
|
636
|
+
for (const field of fields) {
|
|
637
|
+
if (field.kind !== 'fixed') break;
|
|
638
|
+
values.push(field.value);
|
|
639
|
+
}
|
|
640
|
+
const stored = normalizeStoredCall('compressor', { method: 'compressor', fields: values });
|
|
641
|
+
return stored ? { calls: [stored], why: null } : { calls: null, why: 'range' };
|
|
642
|
+
}
|
|
643
|
+
const stored = [];
|
|
644
|
+
for (const call of calls) {
|
|
645
|
+
const method = methodOf(call.name).canonical;
|
|
646
|
+
const param = effect.params.find((candidate) => candidate.method === method || (candidate.alt && candidate.alt.method === method));
|
|
647
|
+
const arg = call.node.arguments[0];
|
|
648
|
+
const value = param.kind === 'select' ? stringLiteralValue(arg) : numericLiteralValue(arg);
|
|
649
|
+
// A filter move the mixer understands is stored as its shape and three numbers.
|
|
650
|
+
const move = value === null && param.kind === 'number' ? readMove(arg, param, declared) : null;
|
|
651
|
+
if (value === null && move === null) return { calls: null, why: 'moving' };
|
|
652
|
+
const normalized = normalizeStoredCall(effect.id, move === null ? { method, value } : { method, move });
|
|
653
|
+
if (normalized === null) return { calls: null, why: 'range' };
|
|
654
|
+
stored.push(normalized);
|
|
655
|
+
}
|
|
656
|
+
return { calls: stored, why: null };
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* The chain effects of a spine: a Map from effect id to `{ calls, params, written, stored, bypassWhy }` for every
|
|
661
|
+
* effect with at least one spine call. `calls` are the spine calls (source order, aliases and
|
|
662
|
+
* duplicates included), `params` one read per parameter id, `written` the source text of the
|
|
663
|
+
* calls from their dots, joined in source order, `stored` the calls a bypass would store (null
|
|
664
|
+
* when it cannot) and `bypassWhy` null, 'moving' or 'range' (see storableCalls).
|
|
665
|
+
*/
|
|
666
|
+
function readEffects(code, spineCalls, declared) {
|
|
667
|
+
const effects = new Map();
|
|
668
|
+
for (const effect of EFFECTS) {
|
|
669
|
+
const calls = spineCalls.filter((call) => effectOfMethod(call.name) === effect.id);
|
|
670
|
+
if (calls.length === 0) continue;
|
|
671
|
+
const params = {};
|
|
672
|
+
if (effect.id === 'compressor') {
|
|
673
|
+
const fields = readCompressorFields(calls);
|
|
674
|
+
for (const param of effect.params) params[param.id] = fields[param.field];
|
|
675
|
+
} else {
|
|
676
|
+
for (const param of effect.params) params[param.id] = readParam(spineCalls, param, declared);
|
|
677
|
+
}
|
|
678
|
+
const { calls: stored, why } = storableCalls(effect, calls, declared);
|
|
679
|
+
effects.set(effect.id, { calls, params, written: calls.map((call) => code.slice(call.dotStart, call.node.end)).join(''), stored, bypassWhy: why });
|
|
680
|
+
}
|
|
681
|
+
return effects;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// --- Sends, buses and orbits ---
|
|
685
|
+
|
|
686
|
+
/** The orbit is read like a number parameter: the last writer wins, a plain number is fixed. */
|
|
687
|
+
const ORBIT_PARAM = Object.freeze({ key: 'orbit', kind: 'number' });
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* What a track's spine says about the shared buses: `{ orbit, sends, busParams }`, each read carrying
|
|
691
|
+
* its last call. `orbit` is `{ kind: 'unwritten' | 'fixed' | 'pattern', value }` (1 when unwritten,
|
|
692
|
+
* Strudel's default); `sends.reverb` and `sends.delay` are parameter reads of the `.room` and `.delay`
|
|
693
|
+
* calls (an unwritten send is not sent); `busParams.reverb.size` and the rest are parameter reads of
|
|
694
|
+
* the bus values written on this track. The mixer never writes an orbit.
|
|
695
|
+
*/
|
|
696
|
+
function readBusFacts(calls, declared) {
|
|
697
|
+
const orbit = readParam(calls, ORBIT_PARAM, declared);
|
|
698
|
+
const sends = {};
|
|
699
|
+
const busParams = {};
|
|
700
|
+
for (const bus of BUS_IDS) {
|
|
701
|
+
sends[bus] = readParam(calls, SENDS[BUSES[bus].send], declared);
|
|
702
|
+
busParams[bus] = Object.fromEntries(BUSES[bus].params.map((param) => [param.id, readParam(calls, param, declared)]));
|
|
703
|
+
}
|
|
704
|
+
return { orbit: { ...orbit, value: orbit.kind === 'unwritten' ? 1 : orbit.value }, sends, busParams };
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/** True when a track with these facts feeds `bus` on `orbit`: a send above 0 (or one that moves in the code). */
|
|
708
|
+
function feedsBus(facts, bus, orbit) {
|
|
709
|
+
const send = facts.sends[bus];
|
|
710
|
+
const sending = send.kind === 'pattern' || (send.kind === 'fixed' && send.value > 0);
|
|
711
|
+
return sending && facts.orbit.kind !== 'pattern' && facts.orbit.value === orbit;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/** Reads one track: its spine and its volume controls. Throws the refusal (MixerRewriteError). */
|
|
715
|
+
function inspectTrack(code, entry, scope) {
|
|
716
|
+
const { declared } = scope;
|
|
717
|
+
if (entry.unnamed) throw new MixerRewriteError('condition');
|
|
718
|
+
const spine = readSpine(code, entry.expression);
|
|
719
|
+
checkRoot(spine.root);
|
|
720
|
+
const root = spine.root;
|
|
721
|
+
const sharedRoot =
|
|
722
|
+
(root.type === 'Identifier' && declared.has(root.name)) ||
|
|
723
|
+
(root.type === 'CallExpression' && root.callee.type === 'Identifier' && declared.has(root.callee.name));
|
|
724
|
+
for (const call of spine.calls) {
|
|
725
|
+
if (!MIXER_CALLS.has(call.name) && effectOfMethod(call.name) === null) continue;
|
|
726
|
+
const args = call.node.arguments;
|
|
727
|
+
if (args.length !== 1 || args[0].type === 'SpreadElement') {
|
|
728
|
+
throw new MixerRewriteError('unsupported-shape');
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
return {
|
|
732
|
+
spine,
|
|
733
|
+
sharedRoot,
|
|
734
|
+
...readReach(spine, entry.expression, scope),
|
|
735
|
+
gain: readControl(spine.calls, 'gain'),
|
|
736
|
+
postgain: readControl(spine.calls, 'postgain'),
|
|
737
|
+
effects: readEffects(code, spine.calls, declared),
|
|
738
|
+
bus: readBusFacts(spine.calls, declared),
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** The read of the effects without source positions, for the model: the call names, the parameter
|
|
743
|
+
* reads and the written text. */
|
|
744
|
+
function publicEffects(effects) {
|
|
745
|
+
return new Map(
|
|
746
|
+
[...effects].map(([id, effect]) => [
|
|
747
|
+
id,
|
|
748
|
+
{
|
|
749
|
+
calls: effect.calls.map((call) => ({ method: call.name, canonical: methodOf(call.name).canonical })),
|
|
750
|
+
params: Object.fromEntries(Object.entries(effect.params).map(([id, { kind, value, method, move }]) => [id, move === undefined ? { kind, value, method } : { kind, value, method, move }])),
|
|
751
|
+
written: effect.written,
|
|
752
|
+
bypassable: effect.stored !== null,
|
|
753
|
+
bypassWhy: effect.bypassWhy,
|
|
754
|
+
},
|
|
755
|
+
]),
|
|
756
|
+
);
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
function publicControl({ kind, value }) {
|
|
760
|
+
return { kind, value };
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/** The bus facts of a track without source positions, for the model. */
|
|
764
|
+
function publicBus({ orbit, sends, busParams }) {
|
|
765
|
+
return {
|
|
766
|
+
orbit: publicControl(orbit),
|
|
767
|
+
sends: Object.fromEntries(Object.entries(sends).map(([bus, read]) => [bus, publicControl(read)])),
|
|
768
|
+
busParams: Object.fromEntries(
|
|
769
|
+
Object.entries(busParams).map(([bus, reads]) => [bus, Object.fromEntries(Object.entries(reads).map(([id, read]) => [id, publicControl(read)]))]),
|
|
770
|
+
),
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Parses `code` once and reads every track: `{ tracks, reads }`, `tracks` from extractTracks and
|
|
776
|
+
* `reads` a Map from track identity to `{ ok: true, gain: { kind, value }, postgain: { kind,
|
|
777
|
+
* value }, effects, bus, label, sharedRoot, playsMidi, innerPostgain }` (`sharedRoot` is true when the track's root is a declared name or a call of one; `playsMidi` is true when a `.midi(` call sits anywhere the track's code reaches, `innerPostgain` is true when a `.postgain(` call sits in that code off the spine; `busHidden` is true when the track writes an orbit, a send or a bus value anywhere but on its own chain (inside another call, in shared code it names, through `.set({ ... })` or a bare call), so its bus facts are not trusted; see readReach; kind 'none', 'fixed' or 'pattern'; `bus` is `{ orbit, sends, busParams }`
|
|
778
|
+
* of readBusFacts without call positions (kind 'unwritten', 'fixed' or 'pattern'); `effects` is a Map from effect id
|
|
779
|
+
* to `{ calls, params, written, bypassable, bypassWhy }`, see readEffects; `label` is null for a track without one,
|
|
780
|
+
* else `{ raw, ...parseLabel(raw) }`) or `{ ok: false, reason }`. One bad track never throws; an
|
|
781
|
+
* unparsable program throws the parser's own error.
|
|
782
|
+
*/
|
|
783
|
+
export function readProgram(code, { parse }) {
|
|
784
|
+
const ast = parse(code, PARSE_OPTIONS);
|
|
785
|
+
const tracks = extractTracks(code, { parse });
|
|
786
|
+
const nodes = trackNodes(ast);
|
|
787
|
+
const scope = readScope(ast);
|
|
788
|
+
const reads = new Map();
|
|
789
|
+
tracks.forEach((track, i) => {
|
|
790
|
+
try {
|
|
791
|
+
const read = inspectTrack(code, nodes[i], scope);
|
|
792
|
+
const raw = nodes[i].labelNode ? nodes[i].labelNode.name : null;
|
|
793
|
+
reads.set(track.identity, {
|
|
794
|
+
ok: true,
|
|
795
|
+
gain: publicControl(read.gain),
|
|
796
|
+
postgain: publicControl(read.postgain),
|
|
797
|
+
effects: publicEffects(read.effects),
|
|
798
|
+
bus: publicBus(read.bus),
|
|
799
|
+
label: raw === null ? null : { raw, ...parseLabel(raw) },
|
|
800
|
+
sharedRoot: read.sharedRoot,
|
|
801
|
+
playsMidi: read.playsMidi,
|
|
802
|
+
innerPostgain: read.innerPostgain,
|
|
803
|
+
busHidden: read.busHidden,
|
|
804
|
+
});
|
|
805
|
+
} catch (err) {
|
|
806
|
+
if (!(err instanceof MixerRewriteError)) throw err;
|
|
807
|
+
reads.set(track.identity, { ok: false, reason: err.reason });
|
|
808
|
+
}
|
|
809
|
+
});
|
|
810
|
+
return { tracks, reads };
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// --- Writing ---
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* The edit that adds `text` (a `.name(args)` call) at the end of the spine. The insertion point is the expression's end: before a trailing `;` and before
|
|
817
|
+
* the comma of a stack() branch. A chain on one line gets the call inline. A chain written over
|
|
818
|
+
* several lines gets a newline, the indentation of its last continuation line and the call; when
|
|
819
|
+
* a `//` comment follows the last call on its line (and no `;` does), the call goes at the end
|
|
820
|
+
* of that line so the comment stays attached to its own call.
|
|
821
|
+
*/
|
|
822
|
+
function insertCallEdit(code, expression, spine, text) {
|
|
823
|
+
const texts = Array.isArray(text) ? text : [text];
|
|
824
|
+
const indentation = chainIndentation(code, spine);
|
|
825
|
+
if (indentation === null) {
|
|
826
|
+
return { from: expression.end, to: expression.end, insert: texts.join('') };
|
|
827
|
+
}
|
|
828
|
+
const comment = /^[ \t]*\/\/[^\r\n]*/.exec(code.slice(expression.end));
|
|
829
|
+
const at = comment ? expression.end + comment[0].length : expression.end;
|
|
830
|
+
return { from: at, to: at, insert: `\n${indentation}${texts.join(`\n${indentation}`)}` };
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/** The indentation of the last continuation line of a chain written over several lines, or null
|
|
834
|
+
* for a chain on one line. */
|
|
835
|
+
function chainIndentation(code, spine) {
|
|
836
|
+
let indentation = null;
|
|
837
|
+
let previousEnd = spine.root.end;
|
|
838
|
+
for (const call of spine.calls) {
|
|
839
|
+
if (code.slice(previousEnd, call.dotStart).includes('\n')) {
|
|
840
|
+
const lineStart = code.lastIndexOf('\n', call.dotStart) + 1;
|
|
841
|
+
indentation = /^[ \t]*/.exec(code.slice(lineStart, call.dotStart))[0];
|
|
842
|
+
}
|
|
843
|
+
previousEnd = call.node.end;
|
|
844
|
+
}
|
|
845
|
+
return indentation;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* The edit that adds calls right after `call`, a call in the middle of the chain. Inline on a chain
|
|
850
|
+
* written on one line, and when another call follows on the same line. On a chain written over
|
|
851
|
+
* several lines, when `call` ends its line, the new calls get their own lines (after a trailing
|
|
852
|
+
* `//` comment, so the comment stays with its own call), indented like the other calls.
|
|
853
|
+
*/
|
|
854
|
+
function insertAfterCallEdit(code, spine, call, texts) {
|
|
855
|
+
const indentation = chainIndentation(code, spine);
|
|
856
|
+
const newline = code.indexOf('\n', call.node.end);
|
|
857
|
+
const lineEnd = newline === -1 ? code.length : newline;
|
|
858
|
+
const rest = code.slice(call.node.end, lineEnd).replace(/\r$/, '');
|
|
859
|
+
if (indentation !== null && /^[ \t]*(?:\/\/.*)?$/.test(rest)) {
|
|
860
|
+
const at = call.node.end + rest.length;
|
|
861
|
+
return { from: at, to: at, insert: `\n${indentation}${texts.join(`\n${indentation}`)}` };
|
|
862
|
+
}
|
|
863
|
+
return { from: call.node.end, to: call.node.end, insert: texts.join('') };
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
/** The edit that adds calls right before `call`: on its own lines when `call` starts its line
|
|
867
|
+
* (so a neighbour's trailing comment stays with its call), else inline. */
|
|
868
|
+
function insertBeforeCallEdit(code, call, texts) {
|
|
869
|
+
const lineStart = code.lastIndexOf('\n', call.dotStart - 1) + 1;
|
|
870
|
+
const before = code.slice(lineStart, call.dotStart);
|
|
871
|
+
if (/^[ \t]*$/.test(before)) {
|
|
872
|
+
return { from: lineStart, to: lineStart, insert: texts.map((text) => `${before}${text}\n`).join('') };
|
|
873
|
+
}
|
|
874
|
+
return { from: call.dotStart, to: call.dotStart, insert: texts.join('') };
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/**
|
|
878
|
+
* The edit that adds the calls `texts` of effect `effectId` in Strudel's chain order: after the source-last call of a present effect that comes earlier in the
|
|
879
|
+
* chain, else before the source-first call of a present effect that comes later, else at the end
|
|
880
|
+
* of the spine. Later edits find the calls again by method name, never by position.
|
|
881
|
+
*/
|
|
882
|
+
function insertEffectEdit(code, entry, read, effectId, texts) {
|
|
883
|
+
const order = CHAIN_ORDER.indexOf(effectId);
|
|
884
|
+
let after = null;
|
|
885
|
+
let before = null;
|
|
886
|
+
for (const call of read.spine.calls) {
|
|
887
|
+
const id = effectOfMethod(call.name);
|
|
888
|
+
if (id === null) continue;
|
|
889
|
+
const index = CHAIN_ORDER.indexOf(id);
|
|
890
|
+
if (index < order && (after === null || call.node.end > after.node.end)) after = call;
|
|
891
|
+
if (index > order && (before === null || call.dotStart < before.dotStart)) before = call;
|
|
892
|
+
}
|
|
893
|
+
const last = read.spine.calls[read.spine.calls.length - 1];
|
|
894
|
+
if (after !== null && after !== last) return insertAfterCallEdit(code, read.spine, after, texts);
|
|
895
|
+
if (after === null && before !== null) return insertBeforeCallEdit(code, before, texts);
|
|
896
|
+
return insertCallEdit(code, entry.expression, read.spine, texts);
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/** The call text an added effect writes: its primary call with its starting value (the compressor
|
|
900
|
+
* writes its first two fields). Numbers go through formatNumber, strings through JSON.stringify of
|
|
901
|
+
* a registry value, so nothing else is ever written. */
|
|
902
|
+
function startCallText(effect) {
|
|
903
|
+
if (effect.id === 'compressor') {
|
|
904
|
+
const [threshold, ratio] = effect.params;
|
|
905
|
+
return `.compressor(${JSON.stringify(`${formatNumber(threshold.start)}:${formatNumber(ratio.start)}`)})`;
|
|
906
|
+
}
|
|
907
|
+
const first = effect.params[0];
|
|
908
|
+
return first.kind === 'select' ? `.${first.method}(${JSON.stringify(first.start)})` : `.${first.method}(${formatNumber(first.start)})`;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/** The edits of taking an effect out of the code: every spine call of it, aliases and duplicates included. */
|
|
912
|
+
function removeEffectEdits(code, read, effectId) {
|
|
913
|
+
const effect = read.effects.get(effectId);
|
|
914
|
+
if (!effect) {
|
|
915
|
+
throw new MixerRewriteError('unsupported-change', `the track does not have ${effectById(effectId).name.toLowerCase()}.`);
|
|
916
|
+
}
|
|
917
|
+
return effect.calls.map((call) => removeCallEdit(code, call));
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
/** The edits of a bypass: the calls go and the caller gets them back, canonical, to store. */
|
|
921
|
+
function bypassEffectEdits(code, read, effectId) {
|
|
922
|
+
const edits = removeEffectEdits(code, read, effectId);
|
|
923
|
+
const { stored } = read.effects.get(effectId);
|
|
924
|
+
if (stored === null) throw new MixerRewriteError('unsupported-change', BYPASS_NEEDS_FIXED);
|
|
925
|
+
return { edits, removed: stored };
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
/** The edits of turning a bypassed effect back on: the stored calls, each checked against the
|
|
929
|
+
* registry again, written in canonical form in chain order. */
|
|
930
|
+
function restoreEffectEdits(code, entry, read, effectId, calls) {
|
|
931
|
+
if (read.effects.has(effectId)) {
|
|
932
|
+
throw new MixerRewriteError('unsupported-change', `the track already has ${effectById(effectId).name.toLowerCase()}.`);
|
|
933
|
+
}
|
|
934
|
+
if (!Array.isArray(calls) || calls.length === 0 || calls.length > 16) {
|
|
935
|
+
throw new MixerRewriteError('unsupported-change', 'a restore needs the stored calls of the effect.');
|
|
936
|
+
}
|
|
937
|
+
const texts = calls.map((call) => {
|
|
938
|
+
const normalized = normalizeStoredCall(effectId, call);
|
|
939
|
+
if (normalized === null) throw new MixerRewriteError('unsupported-change', 'a stored call is not one the mixer can write.');
|
|
940
|
+
return storedCallText(normalized);
|
|
941
|
+
});
|
|
942
|
+
return [insertEffectEdit(code, entry, read, effectId, texts)];
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/** The edits of adding an effect: its primary call with its starting value, in chain order. */
|
|
946
|
+
function addEffectEdits(code, entry, read, effectId) {
|
|
947
|
+
if (read.effects.has(effectId)) {
|
|
948
|
+
throw new MixerRewriteError('unsupported-change', `the track already has ${effectById(effectId).name.toLowerCase()}.`);
|
|
949
|
+
}
|
|
950
|
+
return [insertEffectEdit(code, entry, read, effectId, [startCallText(effectById(effectId))])];
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// --- Parameters ---
|
|
954
|
+
|
|
955
|
+
/** The parameter `id` of `effect`, or a refusal. */
|
|
956
|
+
function paramOf(effect, id) {
|
|
957
|
+
const param = effect.params.find((candidate) => candidate.id === id);
|
|
958
|
+
if (!param) throw new MixerRewriteError('unsupported-change', `${effect.name.toLowerCase()} has no parameter '${String(id)}'.`);
|
|
959
|
+
return param;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/** The read of `effect` on this track, or a refusal when the track does not have it. */
|
|
963
|
+
function presentEffect(read, effect) {
|
|
964
|
+
const found = read.effects.get(effect.id);
|
|
965
|
+
if (!found) throw new MixerRewriteError('unsupported-change', `the track does not have ${effect.name.toLowerCase()}.`);
|
|
966
|
+
return found;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
/** The refusal for a parameter whose value the code moves (a pattern or a signal). */
|
|
970
|
+
function movingRefusal(param) {
|
|
971
|
+
return new MixerRewriteError('unsupported-change', `the ${param.name.toLowerCase()} moves in the code; use a fixed value first.`);
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/** The range a read is edited in: the Hz range for a `.tremolo()` speed, else the parameter's own. */
|
|
975
|
+
function rangeOf(param, paramRead) {
|
|
976
|
+
return param.alt && paramRead.method === param.alt.method ? param.alt : param;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
/**
|
|
980
|
+
* The code text of a value written into `param`: a number is clamped and rounded by the registry and
|
|
981
|
+
* written by formatNumber; a select value must be one of the parameter's own options and is written
|
|
982
|
+
* by JSON.stringify. Nothing else is ever put into code.
|
|
983
|
+
*/
|
|
984
|
+
function valueText(param, range, value) {
|
|
985
|
+
if (param.kind === 'select') {
|
|
986
|
+
if (typeof value !== 'string' || !param.options.includes(value)) {
|
|
987
|
+
throw new MixerRewriteError('unsupported-change', `'${String(value)}' is not one of the ${param.name.toLowerCase()} values.`);
|
|
988
|
+
}
|
|
989
|
+
return JSON.stringify(value);
|
|
990
|
+
}
|
|
991
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
992
|
+
throw new MixerRewriteError('unsupported-change', `a ${param.name.toLowerCase()} must be a finite number.`);
|
|
993
|
+
}
|
|
994
|
+
return formatNumber(roundToParam(range, value));
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
/** The call of `calls` that ends last in the source. */
|
|
998
|
+
function lastCallOf(calls) {
|
|
999
|
+
return calls.reduce((last, call) => (call.node.end > last.node.end ? call : last));
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/** The edit that replaces the argument of `call`. */
|
|
1003
|
+
function replaceArgEdit(call, text) {
|
|
1004
|
+
const arg = call.node.arguments[0];
|
|
1005
|
+
return { from: arg.start, to: arg.end, insert: text };
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
/** The text a compressor call holds for `values` (numbers): a plain number when it is one field and
|
|
1009
|
+
* the call was a plain number, else one string `"t:r:k:a:l"` cut after the last field. */
|
|
1010
|
+
function compressorArgText(call, values) {
|
|
1011
|
+
const joined = values.map((value) => formatNumber(value)).join(':');
|
|
1012
|
+
const plain = values.length === 1 && numericLiteralValue(call.node.arguments[0]) !== null;
|
|
1013
|
+
return plain ? joined : JSON.stringify(joined);
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/** The reads of the five compressor fields, or a refusal when any of them moves in the code. */
|
|
1017
|
+
function compressorFieldReads(effect, eff) {
|
|
1018
|
+
const reads = effect.params.map((param) => eff.params[param.id]);
|
|
1019
|
+
if (reads.some((field) => field.kind === 'pattern')) throw movingRefusal(effect.params[0]);
|
|
1020
|
+
return reads;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/** The index of the last written compressor field, or -1. */
|
|
1024
|
+
function lastWrittenField(reads) {
|
|
1025
|
+
let last = -1;
|
|
1026
|
+
reads.forEach((field, i) => {
|
|
1027
|
+
if (field.kind === 'fixed') last = i;
|
|
1028
|
+
});
|
|
1029
|
+
return last;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
/** The edits that set compressor field `index` to `value`: the last compressor call is rewritten to
|
|
1033
|
+
* hold every field up to the last written or touched one, earlier unwritten fields filled with
|
|
1034
|
+
* Strudel's defaults. */
|
|
1035
|
+
function compressorSetEdits(effect, eff, index, value) {
|
|
1036
|
+
const reads = compressorFieldReads(effect, eff);
|
|
1037
|
+
const param = effect.params[index];
|
|
1038
|
+
const next = roundToParam(param, value);
|
|
1039
|
+
if (reads[index].kind === 'fixed' && reads[index].value === next) return [];
|
|
1040
|
+
const end = Math.max(lastWrittenField(reads), index);
|
|
1041
|
+
const values = [];
|
|
1042
|
+
for (let j = 0; j <= end; j += 1) {
|
|
1043
|
+
if (j === index) values.push(next);
|
|
1044
|
+
else values.push(reads[j].kind === 'fixed' ? reads[j].value : effect.params[j].strudelDefault);
|
|
1045
|
+
}
|
|
1046
|
+
const call = eff.calls[eff.calls.length - 1];
|
|
1047
|
+
return [replaceArgEdit(call, compressorArgText(call, values))];
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/** The edits that give compressor field `index` back its Strudel default: the string is cut after the
|
|
1051
|
+
* last field still written, or holds the default in that field when a later one is written. Several
|
|
1052
|
+
* compressor calls become one. */
|
|
1053
|
+
function compressorDefaultEdits(code, effect, eff, index) {
|
|
1054
|
+
const reads = compressorFieldReads(effect, eff);
|
|
1055
|
+
if (reads[index].kind !== 'fixed') return [];
|
|
1056
|
+
const last = lastWrittenField(reads);
|
|
1057
|
+
const values = [];
|
|
1058
|
+
if (index === last) {
|
|
1059
|
+
for (let j = 0; j < index; j += 1) values.push(reads[j].value);
|
|
1060
|
+
} else {
|
|
1061
|
+
for (let j = 0; j <= last; j += 1) values.push(j === index ? effect.params[j].strudelDefault : reads[j].value);
|
|
1062
|
+
}
|
|
1063
|
+
// The fields fold over every compressor call, so a value an earlier call wrote would survive a
|
|
1064
|
+
// reset of the last call alone: the last call takes the whole result and the earlier ones go.
|
|
1065
|
+
const call = eff.calls[eff.calls.length - 1];
|
|
1066
|
+
return [...eff.calls.slice(0, -1).map((earlier) => removeCallEdit(code, earlier)), replaceArgEdit(call, compressorArgText(call, values))];
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
/** The edits that replace a moving compressor with `"-20:4"`: the last call takes the starting value
|
|
1070
|
+
* of its first two fields and every earlier compressor call goes. A compressor that is only partly
|
|
1071
|
+
* moving is refused rather than guessed at. */
|
|
1072
|
+
function compressorFixedEdits(code, effect, eff) {
|
|
1073
|
+
const reads = effect.params.map((param) => eff.params[param.id]);
|
|
1074
|
+
if (!reads.every((field) => field.kind === 'pattern')) {
|
|
1075
|
+
throw new MixerRewriteError('unsupported-change', 'the compressor is not moving as a whole, so it cannot be replaced by one fixed value.');
|
|
1076
|
+
}
|
|
1077
|
+
const [threshold, ratio] = effect.params;
|
|
1078
|
+
const text = JSON.stringify(`${formatNumber(fixedValueOf(threshold))}:${formatNumber(fixedValueOf(ratio))}`);
|
|
1079
|
+
const call = eff.calls[eff.calls.length - 1];
|
|
1080
|
+
return [...eff.calls.slice(0, -1).map((earlier) => removeCallEdit(code, earlier)), replaceArgEdit(call, text)];
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
/**
|
|
1084
|
+
* `move` as the mixer writes it: a shape from MOVE_SHAPES, From and To finite numbers clamped to the
|
|
1085
|
+
* parameter's range, Over a whole number of cycles from MOVE_OVER_MIN to MOVE_OVER_MAX. Anything
|
|
1086
|
+
* else throws, so nothing but these ever reaches the code.
|
|
1087
|
+
*/
|
|
1088
|
+
function checkedMove(param, move) {
|
|
1089
|
+
const bad = (what) => new MixerRewriteError('unsupported-change', what);
|
|
1090
|
+
if (move === null || typeof move !== 'object') throw bad('a filter move needs a shape, From, To and Over.');
|
|
1091
|
+
if (typeof move.shape !== 'string' || !MOVE_SHAPES.includes(move.shape)) throw bad(`'${String(move.shape)}' is not a filter-move shape.`);
|
|
1092
|
+
for (const field of ['from', 'to']) {
|
|
1093
|
+
if (typeof move[field] !== 'number' || !Number.isFinite(move[field])) throw bad(`a filter move needs a finite number for ${field}.`);
|
|
1094
|
+
}
|
|
1095
|
+
if (!Number.isInteger(move.over) || move.over < MOVE_OVER_MIN || move.over > MOVE_OVER_MAX) {
|
|
1096
|
+
throw bad(`a filter move lasts a whole number of cycles from ${MOVE_OVER_MIN} to ${MOVE_OVER_MAX}.`);
|
|
1097
|
+
}
|
|
1098
|
+
return { shape: move.shape, from: clampToParam(param, move.from), to: clampToParam(param, move.to), over: move.over };
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
/** The edits of one 'filter-move' change: the cutoff's last writer takes the move in its argument
|
|
1102
|
+
* (a fixed value or an earlier move is replaced); an unwritten cutoff gets a call after the effect's
|
|
1103
|
+
* last call. A pattern the mixer does not understand is refused, never overwritten by a guess. */
|
|
1104
|
+
function moveEdits(code, read, change) {
|
|
1105
|
+
const effect = effectById(change.effect);
|
|
1106
|
+
const param = paramOf(effect, change.param);
|
|
1107
|
+
const eff = presentEffect(read, effect);
|
|
1108
|
+
const paramRead = eff.params[param.id];
|
|
1109
|
+
const text = moveText(checkedMove(param, change.move));
|
|
1110
|
+
if (paramRead.kind === 'pattern') throw movingRefusal(param);
|
|
1111
|
+
if (paramRead.kind === 'unwritten') return [insertAfterCallEdit(code, read.spine, lastCallOf(eff.calls), [`.${param.method}(${text})`])];
|
|
1112
|
+
if (paramRead.kind === 'move' && text === code.slice(paramRead.call.node.arguments[0].start, paramRead.call.node.arguments[0].end)) return [];
|
|
1113
|
+
return [replaceArgEdit(paramRead.call, text)];
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
/** The edits of one 'param', 'param-default' or 'param-fixed' change on an effect the track has. Only
|
|
1117
|
+
* the parameter's own call is added, edited or removed; every other call stays byte for byte. */
|
|
1118
|
+
function paramEdits(code, read, change) {
|
|
1119
|
+
const effect = effectById(change.effect);
|
|
1120
|
+
const param = paramOf(effect, change.param);
|
|
1121
|
+
const eff = presentEffect(read, effect);
|
|
1122
|
+
const index = effect.params.indexOf(param);
|
|
1123
|
+
const paramRead = eff.params[param.id];
|
|
1124
|
+
|
|
1125
|
+
if (change.type === 'param-default') {
|
|
1126
|
+
if (index === 0) throw new MixerRewriteError('unsupported-change', `the ${param.name.toLowerCase()} is the ${effect.name.toLowerCase()}'s own value and has no Default.`);
|
|
1127
|
+
if (effect.id === 'compressor') return compressorDefaultEdits(code, effect, eff, index);
|
|
1128
|
+
if (paramRead.kind === 'unwritten') return [];
|
|
1129
|
+
if (paramRead.kind === 'pattern') throw movingRefusal(param);
|
|
1130
|
+
const own = eff.calls.filter((call) => {
|
|
1131
|
+
const { canonical } = methodOf(call.name);
|
|
1132
|
+
return canonical === param.method || (param.alt && canonical === param.alt.method);
|
|
1133
|
+
});
|
|
1134
|
+
return own.map((call) => removeCallEdit(code, call));
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
if (change.type === 'param-fixed') {
|
|
1138
|
+
if (effect.id === 'compressor') return compressorFixedEdits(code, effect, eff);
|
|
1139
|
+
if (paramRead.kind !== 'pattern' && paramRead.kind !== 'move') throw new MixerRewriteError('unsupported-change', `the ${param.name.toLowerCase()} does not move in the code.`);
|
|
1140
|
+
const canonical = methodOf(paramRead.call.name).canonical;
|
|
1141
|
+
const hz = param.alt !== undefined && canonical === param.alt.method;
|
|
1142
|
+
const text = valueText(param, hz ? param.alt : param, fixedValueOf(param, hz));
|
|
1143
|
+
// A packed string such as .lpf("1000:10") also writes the other keys of its pack, and a call
|
|
1144
|
+
// of another method writes this parameter through its own pack: replacing that argument would
|
|
1145
|
+
// drop values without saying so. The parameter's own call goes after the effect's last call
|
|
1146
|
+
// and overrides only this key.
|
|
1147
|
+
if ((canonical === param.method || hz) && !packedArgument(paramRead.call.node.arguments[0])) return [replaceArgEdit(paramRead.call, text)];
|
|
1148
|
+
return [insertAfterCallEdit(code, read.spine, lastCallOf(eff.calls), [`.${hz ? param.alt.method : param.method}(${text})`])];
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
// 'param'
|
|
1152
|
+
if (effect.id === 'compressor') {
|
|
1153
|
+
if (typeof change.value !== 'number' || !Number.isFinite(change.value)) throw new MixerRewriteError('unsupported-change', `a ${param.name.toLowerCase()} must be a finite number.`);
|
|
1154
|
+
return compressorSetEdits(effect, eff, index, change.value);
|
|
1155
|
+
}
|
|
1156
|
+
if (paramRead.kind === 'pattern') throw movingRefusal(param);
|
|
1157
|
+
const range = paramRead.kind === 'fixed' ? rangeOf(param, paramRead) : param;
|
|
1158
|
+
const text = valueText(param, range, change.value);
|
|
1159
|
+
// A filter move turns back into a fixed value: its whole expression is replaced.
|
|
1160
|
+
if (paramRead.kind === 'move') return [replaceArgEdit(paramRead.call, text)];
|
|
1161
|
+
if (paramRead.kind === 'fixed') {
|
|
1162
|
+
if (param.kind === 'number' ? roundToParam(range, change.value) === paramRead.value : change.value === paramRead.value) return [];
|
|
1163
|
+
return [replaceArgEdit(paramRead.call, text)];
|
|
1164
|
+
}
|
|
1165
|
+
return [insertAfterCallEdit(code, read.spine, lastCallOf(eff.calls), [`.${param.method}(${text})`])];
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
// --- Sends and bus parameters ---
|
|
1169
|
+
|
|
1170
|
+
/** The spine calls whose canonical method is one of `methods`. */
|
|
1171
|
+
function callsOfMethods(spine, methods) {
|
|
1172
|
+
return spine.calls.filter((call) => {
|
|
1173
|
+
const meta = methodOf(call.name);
|
|
1174
|
+
return meta !== null && methods.includes(meta.canonical);
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
/** The bus values a joining track is given: `busParams` is `{ paramId: number }`, checked by the caller. */
|
|
1179
|
+
function busParamsObject(value, bus) {
|
|
1180
|
+
const bad = (what) => new MixerRewriteError('unsupported-change', what);
|
|
1181
|
+
if (value === undefined) return {};
|
|
1182
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) throw bad('the bus values of a send must be an object.');
|
|
1183
|
+
for (const [id, number] of Object.entries(value)) {
|
|
1184
|
+
if (busParamById(bus, id) === null) throw bad(`the ${BUSES[bus].name.toLowerCase()} has no parameter '${id}'.`);
|
|
1185
|
+
if (typeof number !== 'number' || !Number.isFinite(number)) throw bad(`the ${id} of the ${BUSES[bus].name.toLowerCase()} must be a finite number.`);
|
|
1186
|
+
}
|
|
1187
|
+
return value;
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
/** The call texts a track that starts sending takes from the bus: every value the bus holds that the
|
|
1191
|
+
* track does not write itself, in registry order, each rounded and written by the registry. */
|
|
1192
|
+
function joinTexts(bus, facts, values) {
|
|
1193
|
+
const texts = [];
|
|
1194
|
+
for (const param of BUSES[bus].params) {
|
|
1195
|
+
if (!Object.hasOwn(values, param.id) || facts.busParams[bus][param.id].kind !== 'unwritten') continue;
|
|
1196
|
+
texts.push(`.${param.method}(${formatNumber(roundToParam(param, values[param.id]))})`);
|
|
1197
|
+
}
|
|
1198
|
+
return texts;
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
/**
|
|
1202
|
+
* The edits of one 'send' change. Above 0 the send is written (its argument replaced, or `.room(v)` /
|
|
1203
|
+
* `.delay(v)` added at the end of the spine) and a track that starts sending takes the bus's current
|
|
1204
|
+
* values right after it. Exactly 0 removes the send and that bus's parameter calls from this track.
|
|
1205
|
+
* A send that moves in the code is refused, never overwritten.
|
|
1206
|
+
*/
|
|
1207
|
+
function sendEdits(code, entry, read, change) {
|
|
1208
|
+
const send = SENDS[change.bus];
|
|
1209
|
+
const bus = BUSES[change.bus];
|
|
1210
|
+
const sendRead = read.bus.sends[change.bus];
|
|
1211
|
+
if (sendRead.kind === 'pattern') {
|
|
1212
|
+
throw new MixerRewriteError('unsupported-change', `the ${send.name.toLowerCase()} send moves in the code; ask Claude to change it.`);
|
|
1213
|
+
}
|
|
1214
|
+
const value = roundToParam(send, change.value);
|
|
1215
|
+
const values = busParamsObject(change.busParams, change.bus);
|
|
1216
|
+
const sendCalls = callsOfMethods(read.spine, [send.method]);
|
|
1217
|
+
if (value === 0) {
|
|
1218
|
+
if (sendCalls.length === 0) return [];
|
|
1219
|
+
const paramCalls = callsOfMethods(read.spine, bus.params.map((param) => param.method));
|
|
1220
|
+
return [...sendCalls, ...paramCalls].map((call) => removeCallEdit(code, call));
|
|
1221
|
+
}
|
|
1222
|
+
const text = formatNumber(value);
|
|
1223
|
+
const joining = joinTexts(change.bus, read.bus, values);
|
|
1224
|
+
if (sendRead.kind === 'fixed') {
|
|
1225
|
+
const edits = [];
|
|
1226
|
+
if (sendRead.value !== value) edits.push(replaceArgEdit(sendRead.call, text));
|
|
1227
|
+
// A send written as 0 that starts sending takes the bus values like a new sender.
|
|
1228
|
+
if (sendRead.value <= 0 && joining.length > 0) edits.push(insertAfterCallEdit(code, read.spine, sendRead.call, joining));
|
|
1229
|
+
return edits;
|
|
1230
|
+
}
|
|
1231
|
+
return [insertCallEdit(code, entry.expression, read.spine, [`.${send.method}(${text})`, ...joining])];
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
/** The edits that give one sending track `sets` (`[[param, number | null]]`, null removes the parameter):
|
|
1235
|
+
* a written value is replaced in place, an unwritten one is added directly after the send or after the
|
|
1236
|
+
* last bus parameter the track keeps. A parameter this track writes as a pattern is refused. */
|
|
1237
|
+
function busTrackEdits(code, sender, bus, sets) {
|
|
1238
|
+
const { read } = sender;
|
|
1239
|
+
const paramReads = read.bus.busParams[bus.id];
|
|
1240
|
+
const edits = [];
|
|
1241
|
+
const inserts = [];
|
|
1242
|
+
const removed = new Set();
|
|
1243
|
+
for (const [param, value] of sets) {
|
|
1244
|
+
const paramRead = paramReads[param.id];
|
|
1245
|
+
if (paramRead.kind === 'pattern') {
|
|
1246
|
+
throw new MixerRewriteError('unsupported-change', `a track writes the ${param.name.toLowerCase()} of the ${bus.name.toLowerCase()} as a pattern; the mixer cannot set it on every track.`);
|
|
1247
|
+
}
|
|
1248
|
+
if (value === null) {
|
|
1249
|
+
for (const call of callsOfMethods(read.spine, [param.method])) {
|
|
1250
|
+
edits.push(removeCallEdit(code, call));
|
|
1251
|
+
removed.add(call);
|
|
1252
|
+
}
|
|
1253
|
+
continue;
|
|
1254
|
+
}
|
|
1255
|
+
const next = roundToParam(param, value);
|
|
1256
|
+
if (paramRead.kind === 'fixed') {
|
|
1257
|
+
if (paramRead.value !== next) edits.push(replaceArgEdit(paramRead.call, formatNumber(next)));
|
|
1258
|
+
} else {
|
|
1259
|
+
inserts.push(`.${param.method}(${formatNumber(next)})`);
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
if (inserts.length > 0) {
|
|
1263
|
+
const keep = [read.bus.sends[bus.id].call, ...callsOfMethods(read.spine, bus.params.map((param) => param.method)).filter((call) => !removed.has(call))];
|
|
1264
|
+
edits.push(insertAfterCallEdit(code, read.spine, lastCallOf(keep), inserts));
|
|
1265
|
+
}
|
|
1266
|
+
return edits;
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
/**
|
|
1270
|
+
* Writes one bus parameter on EVERY track that sends to the bus, in one edit list (Strudel gives
|
|
1271
|
+
* unpredictable results when two tracks on one orbit set different values). `change` is `{ type:
|
|
1272
|
+
* 'bus-param', orbit, bus, param, value, align }`: `orbit` the number the bus is on (read from the
|
|
1273
|
+
* code, never written), `align` an optional `{ paramId: number | null }` that sets other parameters
|
|
1274
|
+
* of the bus on every sender in the same change (null removes them). A track the mixer cannot read
|
|
1275
|
+
* never counts as a sender, nor does one that sets its own orbit or bus values off its own chain (its bus is not
|
|
1276
|
+
* visible from its chain). Asking for what the code already holds returns the identical code and no
|
|
1277
|
+
* edits. Throws MixerRewriteError.
|
|
1278
|
+
*/
|
|
1279
|
+
export function writeBus(code, change, { parse }) {
|
|
1280
|
+
const bad = (what) => new MixerRewriteError('unsupported-change', what);
|
|
1281
|
+
if (change === null || typeof change !== 'object' || change.type !== 'bus-param') throw bad('a bus change needs type: bus-param.');
|
|
1282
|
+
if (!Object.hasOwn(BUSES, change.bus)) throw bad(`unknown bus '${String(change.bus)}'.`);
|
|
1283
|
+
const bus = BUSES[change.bus];
|
|
1284
|
+
const param = busParamById(change.bus, change.param);
|
|
1285
|
+
if (param === null) throw bad(`the ${bus.name.toLowerCase()} has no parameter '${String(change.param)}'.`);
|
|
1286
|
+
if (typeof change.value !== 'number' || !Number.isFinite(change.value)) throw bad(`a ${param.name.toLowerCase()} must be a finite number.`);
|
|
1287
|
+
if (typeof change.orbit !== 'number' || !Number.isFinite(change.orbit)) throw bad('a bus change needs the orbit it is on.');
|
|
1288
|
+
const sets = [[param, change.value]];
|
|
1289
|
+
if (change.align !== undefined) {
|
|
1290
|
+
if (change.align === null || typeof change.align !== 'object' || Array.isArray(change.align)) throw bad('align must be an object.');
|
|
1291
|
+
for (const [id, value] of Object.entries(change.align)) {
|
|
1292
|
+
const other = busParamById(change.bus, id);
|
|
1293
|
+
if (other === null) throw bad(`the ${bus.name.toLowerCase()} has no parameter '${id}'.`);
|
|
1294
|
+
if (id === param.id) continue;
|
|
1295
|
+
if (value !== null && (typeof value !== 'number' || !Number.isFinite(value))) throw bad(`the ${id} of the ${bus.name.toLowerCase()} must be a finite number or null.`);
|
|
1296
|
+
sets.push([other, value]);
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
const ast = parse(code, PARSE_OPTIONS);
|
|
1300
|
+
const tracks = extractTracks(code, { parse });
|
|
1301
|
+
const nodes = trackNodes(ast);
|
|
1302
|
+
const scope = readScope(ast);
|
|
1303
|
+
const senders = [];
|
|
1304
|
+
tracks.forEach((track, i) => {
|
|
1305
|
+
let read;
|
|
1306
|
+
try {
|
|
1307
|
+
read = inspectTrack(code, nodes[i], scope);
|
|
1308
|
+
} catch (err) {
|
|
1309
|
+
if (err instanceof MixerRewriteError) return;
|
|
1310
|
+
throw err;
|
|
1311
|
+
}
|
|
1312
|
+
// A track that sets its own orbit or bus values off its own chain is not read as a sender: its bus is not the one its chain shows. A track that plays MIDI is no sender either: its sound never goes through a bus.
|
|
1313
|
+
if (!read.busHidden && !read.playsMidi && feedsBus(read.bus, bus.id, change.orbit)) senders.push({ entry: nodes[i], read });
|
|
1314
|
+
});
|
|
1315
|
+
if (senders.length === 0) throw bad(`no track sends to the ${bus.name.toLowerCase()} on orbit ${formatNumber(change.orbit)}.`);
|
|
1316
|
+
const edits = senders.flatMap((sender) => busTrackEdits(code, sender, bus, sets));
|
|
1317
|
+
return { code: applyEdits(code, edits), edits };
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
/** Writes a fixed volume on `name` ('gain' or 'postgain'): edits the last fixed writer in place,
|
|
1321
|
+
* or adds a call at the end of the spine. An unchanged value yields no edit at all: that includes the neutral
|
|
1322
|
+
* post-gain on a track that writes none (1 plays the code as written, so a `.postgain(1)` would change nothing). */
|
|
1323
|
+
function writeVolume(code, entry, read, name, control, text, value) {
|
|
1324
|
+
if (control.kind === 'fixed') {
|
|
1325
|
+
if (control.value === value) return [];
|
|
1326
|
+
const arg = control.call.node.arguments[0];
|
|
1327
|
+
return [{ from: arg.start, to: arg.end, insert: text }];
|
|
1328
|
+
}
|
|
1329
|
+
if (name === 'postgain' && value === DEFAULT_POSTGAIN) return [];
|
|
1330
|
+
return [insertCallEdit(code, entry.expression, read.spine, `.${name}(${text})`)];
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
/**
|
|
1334
|
+
* The edit that removes one spine call (`.hush()`). A call alone on its line (only whitespace before
|
|
1335
|
+
* its dot, and only whitespace or a `//` comment after it) goes with its whole line, its trailing
|
|
1336
|
+
* comment and its newline; any other call goes from its dot to its end, so a neighbour's trailing
|
|
1337
|
+
* comment stays.
|
|
1338
|
+
*/
|
|
1339
|
+
function removeCallEdit(code, call) {
|
|
1340
|
+
const lineStart = code.lastIndexOf('\n', call.dotStart - 1) + 1;
|
|
1341
|
+
const alone = /^[ \t]*$/.test(code.slice(lineStart, call.dotStart));
|
|
1342
|
+
const rest = /^[ \t]*(?:\/\/[^\r\n]*)?(\r?\n|$)/.exec(code.slice(call.node.end));
|
|
1343
|
+
if (!alone || !rest) return { from: call.dotStart, to: call.node.end, insert: '' };
|
|
1344
|
+
if (rest[1] === '' && lineStart > 0) {
|
|
1345
|
+
// The last line of the program: take the line break before it instead of leaving a blank line.
|
|
1346
|
+
const from = code[lineStart - 2] === '\r' ? lineStart - 2 : lineStart - 1;
|
|
1347
|
+
return { from, to: call.node.end + rest[0].length, insert: '' };
|
|
1348
|
+
}
|
|
1349
|
+
return { from: lineStart, to: call.node.end + rest[0].length, insert: '' };
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
/**
|
|
1353
|
+
* The edits of one mute or solo press on a track. A labeled
|
|
1354
|
+
* track changes its label (labelEdit); a `.hush()` on its spine is one more way to be muted, so
|
|
1355
|
+
* unmuting and soloing remove every one and muting a hushed track changes nothing. A track without
|
|
1356
|
+
* a label mutes by adding `.hush()` at the end of its chain and unmutes by removing every one; it
|
|
1357
|
+
* cannot be soloed (unsupported-change).
|
|
1358
|
+
*/
|
|
1359
|
+
function muteSoloEdits(code, entry, read, change, ast) {
|
|
1360
|
+
const hushes = read.spine.calls.filter((call) => call.name === 'hush');
|
|
1361
|
+
const removeHushes = () => hushes.map((call) => removeCallEdit(code, call));
|
|
1362
|
+
if (!entry.labelNode) {
|
|
1363
|
+
if (change.type === 'solo') {
|
|
1364
|
+
throw new MixerRewriteError('unsupported-change', 'a track without a label cannot be soloed.');
|
|
1365
|
+
}
|
|
1366
|
+
if (change.on) return hushes.length > 0 ? [] : [insertCallEdit(code, entry.expression, read.spine, '.hush()')];
|
|
1367
|
+
return removeHushes();
|
|
1368
|
+
}
|
|
1369
|
+
if (change.type === 'mute' && change.on && hushes.length > 0) return [];
|
|
1370
|
+
const edits = [];
|
|
1371
|
+
const label = labelEdit(entry, change, ast);
|
|
1372
|
+
if (label) edits.push(label);
|
|
1373
|
+
// Unmuting and soloing drop the hush; muting and un-soloing leave it alone.
|
|
1374
|
+
if (change.on !== (change.type === 'solo')) return edits;
|
|
1375
|
+
return [...edits, ...removeHushes()];
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
/**
|
|
1379
|
+
* The edit that rewrites a labeled track's label for a mute or solo press, or null when the label already has the asked state. One edit replaces the
|
|
1380
|
+
* label identifier and nothing else. Mute and solo exclude each other on one label, so Strudel is
|
|
1381
|
+
* never given `_S_name`. Throws 'unsupported-shape' for a label the mixer cannot read and
|
|
1382
|
+
* 'unsupported-change' for a change the label cannot take (a name that starts with S plays alone
|
|
1383
|
+
* by itself; the mixer never renames it).
|
|
1384
|
+
*/
|
|
1385
|
+
function labelEdit(entry, change, ast) {
|
|
1386
|
+
const raw = entry.labelNode.name;
|
|
1387
|
+
const label = parseLabel(raw);
|
|
1388
|
+
if (!label.safe) throw new MixerRewriteError('unsupported-shape');
|
|
1389
|
+
let next;
|
|
1390
|
+
if (change.type === 'mute') {
|
|
1391
|
+
if (change.on) {
|
|
1392
|
+
next = label.mutedByLabel ? raw : `_${label.solo === 'marker' ? label.base : label.core}`;
|
|
1393
|
+
} else {
|
|
1394
|
+
next = label.core;
|
|
1395
|
+
}
|
|
1396
|
+
} else if (label.solo === 'name') {
|
|
1397
|
+
throw new MixerRewriteError('unsupported-change', 'a name that starts with a capital S plays alone by itself; the mixer does not rename it.');
|
|
1398
|
+
} else if (change.on) {
|
|
1399
|
+
next = label.solo === 'marker' && !label.soloInert ? raw : `${SOLO_MARKER}${label.base}`;
|
|
1400
|
+
} else if (label.solo === 'marker' && !label.soloInert) {
|
|
1401
|
+
if (label.base.length > 1 && label.base.startsWith('S')) {
|
|
1402
|
+
throw new MixerRewriteError('unsupported-change', 'the name under the solo marker starts with a capital S, so it would still play alone.');
|
|
1403
|
+
}
|
|
1404
|
+
next = label.base;
|
|
1405
|
+
} else {
|
|
1406
|
+
next = raw;
|
|
1407
|
+
}
|
|
1408
|
+
if (next === raw) return null;
|
|
1409
|
+
refuseSharedLabel(entry, raw, next, ast);
|
|
1410
|
+
return { from: entry.labelNode.start, to: entry.labelNode.end, insert: next };
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
/** The change types a track that plays MIDI refuses: each writes a browser effect, a send or a bus value. */
|
|
1414
|
+
const PLAYS_MIDI_REFUSED = new Set(['add-effect', 'bypass-effect', 'restore-effect', 'remove-effect', 'param', 'param-default', 'param-fixed', 'filter-move', 'send']);
|
|
1415
|
+
|
|
1416
|
+
/**
|
|
1417
|
+
* Strudel keeps only the last statement of a repeated plain label (a label with `$` never repeats).
|
|
1418
|
+
* A label edit on a track that shares its label with a shadowed statement would bring that
|
|
1419
|
+
* statement back to life or make it the survivor, and a label edit that lands on a label another
|
|
1420
|
+
* statement already holds would merge two tracks. Both are refused, so a press never changes
|
|
1421
|
+
* which statements play.
|
|
1422
|
+
*/
|
|
1423
|
+
function refuseSharedLabel(entry, raw, next, ast) {
|
|
1424
|
+
const others = ast.body.filter((node) => node.type === 'LabeledStatement' && node.body && node.body.type === 'ExpressionStatement' && node !== entry.statement);
|
|
1425
|
+
if (!raw.includes('$') && others.some((node) => node.label.name === raw)) {
|
|
1426
|
+
throw new MixerRewriteError('unsupported-change', 'another statement in the code uses the same label, so a mute or solo would change which one plays.');
|
|
1427
|
+
}
|
|
1428
|
+
if (!next.includes('$') && others.some((node) => node.label.name === next)) {
|
|
1429
|
+
throw new MixerRewriteError('unsupported-change', 'another track already uses the label this change would write.');
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
/**
|
|
1434
|
+
* Writes one control change on the track `identity` of `code` and returns `{ code, edits }`,
|
|
1435
|
+
* `edits` in the original coordinates (the same list drives the editor change and the highlight).
|
|
1436
|
+
* `change` is `{ identity, type: 'gain', value }`, `{ identity, type: 'mute', on }`,
|
|
1437
|
+
* `{ identity, type: 'solo', on }`, `{ identity, type: 'add-effect', effect }`, `{ identity, type:
|
|
1438
|
+
* 'bypass-effect', effect }` (the result also carries `removed`, the calls to store), `{ identity,
|
|
1439
|
+
* type: 'restore-effect', effect, calls }` (the stored calls, checked again) or `{ identity, type:
|
|
1440
|
+
* 'remove-effect', effect }`, `{ identity, type: 'param', effect, param, value }` (one parameter, the
|
|
1441
|
+
* value clamped and rounded by the registry; a select takes a listed string), `{ identity, type:
|
|
1442
|
+
* 'param-default', effect, param }` (removes a written extra parameter again) or `{ identity, type:
|
|
1443
|
+
* 'param-fixed', effect, param }` (replaces a moving parameter by its starting value) or `{ identity,
|
|
1444
|
+
* type: 'filter-move', effect, param, move: { shape, from, to, over } }` (the cutoff of a filter becomes
|
|
1445
|
+
* `<shape>.range(from, to).slow(over)`; shape from MOVE_SHAPES, Over a whole number of cycles) or `{ identity,
|
|
1446
|
+
* type: 'send', bus: 'reverb' | 'delay', value, busParams }` (the track's send, 0 to 1: above 0 writes `.room(v)` /
|
|
1447
|
+
* `.delay(v)` and, for a track that starts sending, the bus values in `busParams` directly after it; exactly
|
|
1448
|
+
* 0 removes the send and that bus's parameter calls; see sendEdits). A volume is written to two decimals into the last `.gain(n)`
|
|
1449
|
+
* when that is a plain number; otherwise into `.postgain(n)` (edited in place when a plain one is
|
|
1450
|
+
* there, added at the end of the chain when there is none), so the gains inside the track keep their
|
|
1451
|
+
* differences; it is refused when the post-gain moves, or when the track plays MIDI (which ignores a post-gain; such a track also refuses every effect, send and bus change), or when a post-gain is set inside the track or its shared code (a fader's would replace it). A mute or solo rewrites the track's label (see labelEdit). Adding an effect writes only
|
|
1452
|
+
* its primary call with its starting value, in Strudel's chain order (see insertEffectEdit). Asking for the state the code
|
|
1453
|
+
* already holds returns the identical code and no edits. Throws MixerRewriteError.
|
|
1454
|
+
*/
|
|
1455
|
+
export function writeTrack(code, identity, change, { parse }) {
|
|
1456
|
+
const type = change ? change.type : undefined;
|
|
1457
|
+
if (type === 'gain') {
|
|
1458
|
+
if (typeof change.value !== 'number' || !Number.isFinite(change.value) || change.value < 0) {
|
|
1459
|
+
throw new MixerRewriteError('unsupported-change', 'a volume must be a finite number of at least 0.');
|
|
1460
|
+
}
|
|
1461
|
+
} else if (type === 'mute' || type === 'solo') {
|
|
1462
|
+
if (typeof change.on !== 'boolean') {
|
|
1463
|
+
throw new MixerRewriteError('unsupported-change', `a ${type} change needs on: true or false.`);
|
|
1464
|
+
}
|
|
1465
|
+
} else if (type === 'add-effect' || type === 'bypass-effect' || type === 'restore-effect' || type === 'remove-effect') {
|
|
1466
|
+
if (!EFFECT_IDS.has(change.effect)) {
|
|
1467
|
+
throw new MixerRewriteError('unsupported-change', `unknown effect '${String(change.effect)}'.`);
|
|
1468
|
+
}
|
|
1469
|
+
} else if (type === 'param' || type === 'param-default' || type === 'param-fixed') {
|
|
1470
|
+
if (!EFFECT_IDS.has(change.effect)) {
|
|
1471
|
+
throw new MixerRewriteError('unsupported-change', `unknown effect '${String(change.effect)}'.`);
|
|
1472
|
+
}
|
|
1473
|
+
paramOf(effectById(change.effect), change.param);
|
|
1474
|
+
} else if (type === 'send') {
|
|
1475
|
+
if (!Object.hasOwn(SENDS, change.bus)) throw new MixerRewriteError('unsupported-change', `unknown send '${String(change.bus)}'.`);
|
|
1476
|
+
if (typeof change.value !== 'number' || !Number.isFinite(change.value) || change.value < 0 || change.value > 1) {
|
|
1477
|
+
throw new MixerRewriteError('unsupported-change', 'a send must be a finite number from 0 to 1.');
|
|
1478
|
+
}
|
|
1479
|
+
busParamsObject(change.busParams, change.bus);
|
|
1480
|
+
} else if (type === 'filter-move') {
|
|
1481
|
+
if (!EFFECT_IDS.has(change.effect)) {
|
|
1482
|
+
throw new MixerRewriteError('unsupported-change', `unknown effect '${String(change.effect)}'.`);
|
|
1483
|
+
}
|
|
1484
|
+
const param = paramOf(effectById(change.effect), change.param);
|
|
1485
|
+
if (!param.movable) throw new MixerRewriteError('unsupported-change', `the ${param.name.toLowerCase()} cannot move.`);
|
|
1486
|
+
checkedMove(param, change.move);
|
|
1487
|
+
} else {
|
|
1488
|
+
throw new MixerRewriteError('unsupported-change', `unknown mixer change '${String(type)}'.`);
|
|
1489
|
+
}
|
|
1490
|
+
const ast = parse(code, PARSE_OPTIONS);
|
|
1491
|
+
const tracks = extractTracks(code, { parse });
|
|
1492
|
+
const index = tracks.findIndex((track) => track.identity === identity);
|
|
1493
|
+
if (index === -1) throw new MixerRewriteError('track-gone');
|
|
1494
|
+
const entry = trackNodes(ast)[index];
|
|
1495
|
+
const read = inspectTrack(code, entry, readScope(ast));
|
|
1496
|
+
|
|
1497
|
+
if (read.playsMidi && PLAYS_MIDI_REFUSED.has(type)) {
|
|
1498
|
+
// MIDI output never plays the browser's effects, reverb or delay, so the write would move a control while the sound cannot change.
|
|
1499
|
+
throw new MixerRewriteError('unsupported-change', 'This track plays MIDI, which has no effects, reverb or delay here; the mixer has nothing to write for it.');
|
|
1500
|
+
}
|
|
1501
|
+
if (type === 'add-effect') {
|
|
1502
|
+
const edits = addEffectEdits(code, entry, read, change.effect);
|
|
1503
|
+
return { code: applyEdits(code, edits), edits };
|
|
1504
|
+
}
|
|
1505
|
+
if (type === 'bypass-effect') {
|
|
1506
|
+
const { edits, removed } = bypassEffectEdits(code, read, change.effect);
|
|
1507
|
+
return { code: applyEdits(code, edits), edits, removed };
|
|
1508
|
+
}
|
|
1509
|
+
if (type === 'restore-effect') {
|
|
1510
|
+
const edits = restoreEffectEdits(code, entry, read, change.effect, change.calls);
|
|
1511
|
+
return { code: applyEdits(code, edits), edits };
|
|
1512
|
+
}
|
|
1513
|
+
if (type === 'remove-effect') {
|
|
1514
|
+
const edits = removeEffectEdits(code, read, change.effect);
|
|
1515
|
+
return { code: applyEdits(code, edits), edits };
|
|
1516
|
+
}
|
|
1517
|
+
if (type === 'param' || type === 'param-default' || type === 'param-fixed') {
|
|
1518
|
+
const edits = paramEdits(code, read, change);
|
|
1519
|
+
return { code: applyEdits(code, edits), edits };
|
|
1520
|
+
}
|
|
1521
|
+
if (type === 'filter-move') {
|
|
1522
|
+
const edits = moveEdits(code, read, change);
|
|
1523
|
+
return { code: applyEdits(code, edits), edits };
|
|
1524
|
+
}
|
|
1525
|
+
if (type === 'send') {
|
|
1526
|
+
if (read.busHidden) {
|
|
1527
|
+
throw new MixerRewriteError('unsupported-change', 'This track sets its own orbit or bus values somewhere the mixer does not read (inside another call or in shared code), so it cannot tell which bus a send would feed.');
|
|
1528
|
+
}
|
|
1529
|
+
const edits = sendEdits(code, entry, read, change);
|
|
1530
|
+
return { code: applyEdits(code, edits), edits };
|
|
1531
|
+
}
|
|
1532
|
+
if (type !== 'gain') {
|
|
1533
|
+
const edits = muteSoloEdits(code, entry, read, change, ast);
|
|
1534
|
+
return { code: applyEdits(code, edits), edits };
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
const value = roundTo(change.value, 2);
|
|
1538
|
+
const text = formatNumber(value);
|
|
1539
|
+
let edits;
|
|
1540
|
+
if (read.gain.kind === 'fixed') {
|
|
1541
|
+
// One plain gain already covers every event, so editing it loses nothing and converts nothing.
|
|
1542
|
+
edits = writeVolume(code, entry, read, 'gain', read.gain, text, value);
|
|
1543
|
+
} else {
|
|
1544
|
+
// A later .gain(n) would replace every gain set inside the track, so the fader
|
|
1545
|
+
// multiplies with .postgain(n) instead and the loud-to-quiet ratio of the notes stays.
|
|
1546
|
+
if (read.playsMidi) {
|
|
1547
|
+
// MIDI output reads gain and velocity but never the post-gain, so the write would change nothing audible.
|
|
1548
|
+
throw new MixerRewriteError('unsupported-change', 'This track plays MIDI, which ignores a post-gain; the mixer has no level to write for it.');
|
|
1549
|
+
}
|
|
1550
|
+
if (read.innerPostgain) {
|
|
1551
|
+
// A later .postgain(n) replaces every post-gain set inside the track or its shared code, as a later .gain(n) replaces gains.
|
|
1552
|
+
throw new MixerRewriteError('unsupported-change', 'The post-gain is set inside the track, so a fader would flatten it.');
|
|
1553
|
+
}
|
|
1554
|
+
if (read.postgain.kind === 'pattern') {
|
|
1555
|
+
throw new MixerRewriteError(
|
|
1556
|
+
'unsupported-change',
|
|
1557
|
+
read.gain.kind === 'pattern' ? 'Gain and post-gain both move in the code.' : 'The post-gain moves in the code.',
|
|
1558
|
+
);
|
|
1559
|
+
}
|
|
1560
|
+
edits = writeVolume(code, entry, read, 'postgain', read.postgain, text, value);
|
|
1561
|
+
}
|
|
1562
|
+
return { code: applyEdits(code, edits), edits };
|
|
1563
|
+
}
|