@kairotic/app 0.0.0-stage → 0.2.2

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.
Files changed (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,439 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ // @kairotic/faust-units · Faust code → a subpatch of unit boxes.
3
+ //
4
+ // Not a compiler: a small evaluator of Faust's block-diagram algebra over the vocabulary of units.mjs.
5
+ // Every expression is a block {nin, nout, build(inputs) → outputs}; building a block makes the boxes
6
+ // and wires it stands for. The operators mean what they mean in Faust:
7
+ // A : B sequence A , B parallel A <: B split A :> B merge (a sum)
8
+ // A ~ B recursion, through one-sample delay boxes (')
9
+ // a + b is a, b : + and +(b) is _, b : + (partial application, from the right)
10
+ // x' one-sample delay a @ n delay by n
11
+ // f(a, b) a unit or a definition of the program called with arguments
12
+ // … with { definitions } … letrec { 'y = …; }
13
+ // What is not in the vocabulary (a library function the boxes do not know) becomes a box of Faust code
14
+ // kept as written, once the compiler has said how many inputs and outputs it has (`arity`).
15
+
16
+ import { UNITS, CODE } from "./units.mjs";
17
+ import { newBox, layout, name } from "./graph.mjs";
18
+
19
+ // ── tokens ──
20
+ const OPS = ["<:", ":>", "<=", ">=", "==", "!=", ":", ",", "~", "+", "-", "*", "/", "%", "^", "@", "'", "<", ">", "=", ";", "(", ")", "{", "}", "!"];
21
+ export function lex(src) {
22
+ const out = [], layoutLines = [];
23
+ let i = 0;
24
+ while (i < src.length) {
25
+ const c = src[i];
26
+ if (/\s/.test(c)) { i++; continue; }
27
+ if (src.startsWith("//", i)) {
28
+ const e = src.indexOf("\n", i), line = src.slice(i, e < 0 ? src.length : e);
29
+ if (line.startsWith("//@ layout")) layoutLines.push(line.slice(10));
30
+ i = e < 0 ? src.length : e; continue;
31
+ }
32
+ if (src.startsWith("/*", i)) { const e = src.indexOf("*/", i + 2); i = e < 0 ? src.length : e + 2; continue; }
33
+ if (c === '"') {
34
+ let j = i + 1, s = "";
35
+ while (j < src.length && src[j] !== '"') { if (src[j] === "\\") j++; s += src[j++]; }
36
+ out.push({ t: "str", v: s, at: i, end: j + 1 }); i = j + 1; continue;
37
+ }
38
+ const num = /^(\d+\.?\d*|\.\d+)(e-?\d+)?f?/i.exec(src.slice(i, i + 40));
39
+ if (num) { out.push({ t: "num", v: parseFloat(num[0]), at: i, end: i + num[0].length }); i += num[0].length; continue; }
40
+ const id = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*/.exec(src.slice(i, i + 200));
41
+ if (id) { out.push({ t: "id", v: id[0], at: i, end: i + id[0].length }); i += id[0].length; continue; }
42
+ const op = OPS.find((o) => src.startsWith(o, i));
43
+ if (op) { out.push({ t: "op", v: op, at: i, end: i + op.length }); i += op.length; continue; }
44
+ throw new Error(`a character Faust does not use here: ${c}`);
45
+ }
46
+ out.push({ t: "eof", at: src.length, end: src.length });
47
+ const lay = new Map();
48
+ for (const l of layoutLines) for (const part of l.split(",")) {
49
+ const m = /^\s*(\S+)\s+(-?\d+)\s+(-?\d+)\s*$/.exec(part);
50
+ if (m) lay.set(m[1], { x: +m[2], y: +m[3] });
51
+ }
52
+ return { toks: out, layout: lay };
53
+ }
54
+
55
+ // ── syntax ──
56
+ const INFIX = { "<:": 1, ":>": 1, ":": 2, ",": 3, "~": 4, "<": 5, ">": 5, "<=": 5, ">=": 5, "==": 5, "!=": 5,
57
+ "+": 6, "-": 6, "*": 7, "/": 7, "%": 7, "^": 8, "@": 9 };
58
+ const COMPOSE = new Set(["<:", ":>", ":", ",", "~"]);
59
+
60
+ export function parseProgram(src) {
61
+ const { toks, layout: lay } = lex(src);
62
+ let p = 0;
63
+ const peek = (k = 0) => toks[p + k], next = () => toks[p++];
64
+ const is = (v, k = 0) => toks[p + k].t === "op" && toks[p + k].v === v;
65
+ const expect = (v) => { const t = next(); if (!(t.t === "op" && t.v === v)) throw new Error(`expected ${v} at ${t.at}`); return t; };
66
+
67
+ function expr(minBp = 0, noComma = false) {
68
+ let left = nud(noComma);
69
+ for (;;) {
70
+ const t = peek();
71
+ if (t.t === "op" && t.v === "'") { next(); left = { k: "mem", x: left, at: left.at, end: t.end }; continue; }
72
+ if (t.t !== "op" || !(t.v in INFIX)) break;
73
+ if (noComma && t.v === ",") break;
74
+ const bp = INFIX[t.v];
75
+ if (bp <= minBp) break;
76
+ next();
77
+ const right = expr(bp, noComma);
78
+ left = { k: COMPOSE.has(t.v) ? "comp" : "bin", op: t.v, l: left, r: right, at: left.at, end: right.end };
79
+ }
80
+ return left;
81
+ }
82
+ function full(noComma = false) {
83
+ let e = expr(0, noComma);
84
+ for (;;) {
85
+ const t = peek();
86
+ if (t.t === "id" && t.v === "with") { next(); expect("{"); const defs = definitions(); expect("}"); e = { k: "with", x: e, defs, at: e.at, end: t.end }; continue; }
87
+ if (t.t === "id" && t.v === "letrec") { next(); expect("{"); const defs = recdefs(); expect("}"); e = { k: "letrec", x: e, defs, at: e.at, end: t.end }; continue; }
88
+ return e;
89
+ }
90
+ }
91
+ function args() {
92
+ expect("(");
93
+ const a = [];
94
+ if (!is(")")) { a.push(full(true)); while (is(",")) { next(); a.push(full(true)); } }
95
+ expect(")");
96
+ return a;
97
+ }
98
+ function nud() {
99
+ const t = next();
100
+ if (t.t === "num") return { k: "num", v: t.v, at: t.at, end: t.end };
101
+ if (t.t === "str") return { k: "str", v: t.v, at: t.at, end: t.end };
102
+ if (t.t === "op" && t.v === "(") { const e = full(false); const c = expect(")"); return { ...e, at: t.at, end: c.end, paren: true }; }
103
+ if (t.t === "op" && t.v === "-" && peek().t === "num") { const n = next(); return { k: "num", v: -n.v, at: t.at, end: n.end }; }
104
+ if (t.t === "op" && t.v === "!") return { k: "id", v: "!", at: t.at, end: t.end };
105
+ if ((t.t === "op" && t.v in INFIX && !COMPOSE.has(t.v)) || t.t === "id") {
106
+ const node = { k: "id", v: t.v, at: t.at, end: t.end };
107
+ if (is("(")) { const a = args(); return { k: "call", f: node, args: a, at: t.at, end: toks[p - 1].end }; }
108
+ return node;
109
+ }
110
+ throw new Error(`unexpected ${t.v === undefined ? "end" : t.v} at ${t.at}`);
111
+ }
112
+ function definitions() {
113
+ const defs = [];
114
+ while (peek().t === "id" && (is("=", 1) || is("(", 1))) defs.push(definition());
115
+ return defs;
116
+ }
117
+ function definition() {
118
+ const n = next().v, params = [];
119
+ if (is("(")) { next(); for (;;) { params.push(next().v); if (is(",")) { next(); continue; } expect(")"); break; } }
120
+ expect("=");
121
+ const body = full(false);
122
+ expect(";");
123
+ return { name: n, params, body };
124
+ }
125
+ function recdefs() {
126
+ const defs = [];
127
+ while (is("'")) { next(); const n = next().v; expect("="); const body = full(false); expect(";"); defs.push({ name: n, body }); }
128
+ return defs;
129
+ }
130
+ const top = [];
131
+ while (peek().t !== "eof") {
132
+ const t = peek();
133
+ if (t.t === "id" && (t.v === "import" || t.v === "declare")) { while (!is(";")) next(); next(); continue; }
134
+ top.push(definition());
135
+ }
136
+ return { defs: top, layout: lay, src };
137
+ }
138
+
139
+ // ── evaluation ──
140
+ export class NeedArity extends Error { constructor(texts) { super("needs the compiler"); this.texts = texts; } }
141
+
142
+ const P = (box, k = 0) => ({ box, k });
143
+ const N = (v) => ({ num: v });
144
+ const portsBlock = (ports) => ({ nin: 0, nout: ports.length, build: () => ports });
145
+
146
+ export function toGraph(src, arity = () => undefined) {
147
+ const prog = parseProgram(src);
148
+ const graph = { boxes: [], wires: [] };
149
+ const need = new Set();
150
+ const lay = prog.layout;
151
+
152
+ // boxes are named after parsing: a definition's name wins over an automatic one
153
+ const box = (type, args, extra) => { const b = newBox(graph, type, args, undefined, undefined, extra); delete b.name; b.autoName = true; return b; };
154
+ const named = (b, n) => { b.name = n; delete b.autoName; return b; };
155
+ const nameBox = (b, n) => { if (b.autoName) named(b, n); };
156
+ const fresh = (b) => b;
157
+ function asPort(port) {
158
+ if (port.num !== undefined) return P(fresh(box("num", [port.num])).id);
159
+ return port;
160
+ }
161
+ function wire(port, to, inlet) {
162
+ if (port.sum) { port.sum.forEach((q) => wire(q, to, inlet)); return; }
163
+ const q = asPort(port);
164
+ graph.wires.push({ from: [q.box, q.k], to: [to, inlet] });
165
+ }
166
+
167
+ // a unit applied to its slot ports (or numbers)
168
+ function unitBox(u, ports, extraArgs) {
169
+ const slots = u.slots;
170
+ let args = [];
171
+ if (u.kind === "prim") {
172
+ let j = slots.length;
173
+ while (j > 0 && ports[j - 1] && ports[j - 1].num !== undefined) j--;
174
+ if (u.mem) j = slots.length; // x' keeps x as a wire, even a number
175
+ args = ports.slice(j).map((q) => q.num);
176
+ const b = fresh(box(u.name, args));
177
+ ports.slice(0, j).forEach((q, i) => wire(q, b.id, i));
178
+ return b;
179
+ }
180
+ if (u.kind === "lib") {
181
+ let last = -1;
182
+ slots.forEach((s, i) => { if (s.kind !== "in" && ports[i] && ports[i].num !== undefined) last = i; });
183
+ slots.forEach((s, i) => { if (s.kind !== "in" && i <= last) args.push(ports[i] && ports[i].num !== undefined ? ports[i].num : s.def); });
184
+ const b = fresh(box(u.name, args));
185
+ let inlet = 0;
186
+ slots.forEach((s, i) => {
187
+ if (s.kind === "const") { if (!ports[i] || ports[i].num === undefined) throw new Error(`${u.name}: ${s.name} must be a number`); return; }
188
+ if (ports[i] && !(s.kind !== "in" && ports[i].num !== undefined)) wire(ports[i], b.id, inlet);
189
+ inlet++;
190
+ });
191
+ return b;
192
+ }
193
+ return fresh(box(u.name, extraArgs || []));
194
+ }
195
+
196
+ const constNum = (blk) => {
197
+ if (blk.nin !== 0 || blk.nout !== 1) return undefined;
198
+ const q = blk.build([])[0];
199
+ return q.num;
200
+ };
201
+
202
+ // blocks for the vocabulary
203
+ const uiMemo = new Map();
204
+ function unitBlock(u, callArgs, env, node) {
205
+ if (u.kind === "ui") {
206
+ const vals = callArgs.map((a) => (a.k === "str" ? a.v : constNum(evaluate(a, env))));
207
+ const args = u.defs.map((d, i) => (vals[i] !== undefined ? vals[i] : d));
208
+ const key = u.name + JSON.stringify(args);
209
+ return { nin: 0, nout: 1, build: () => {
210
+ if (!uiMemo.has(key)) uiMemo.set(key, P(unitBox(u, [], args).id));
211
+ return [uiMemo.get(key)];
212
+ } };
213
+ }
214
+ const argBlocks = (callArgs || []).map((a) => evaluate(a, env));
215
+ argBlocks.forEach((b) => { if (b.nin !== 0 || b.nout !== 1) throw new Error(`${u.name}: an argument must be one signal`); });
216
+ const n = u.slots.length;
217
+ let filled; // slot index → block
218
+ if (u.kind === "prim") {
219
+ filled = new Map(argBlocks.map((b, j) => [n - argBlocks.length + j, b]));
220
+ } else {
221
+ const params = u.slots.map((s, i) => [s, i]).filter(([s]) => s.kind !== "in").map(([, i]) => i);
222
+ if (argBlocks.length && argBlocks.length !== params.length) throw new Error(`${u.name} takes ${params.length} arguments`);
223
+ filled = new Map(argBlocks.map((b, j) => [params[j], b]));
224
+ if (!argBlocks.length && u.slots.some((s) => s.kind === "const")) throw new Error(`${u.name} needs its arguments`);
225
+ }
226
+ const open = u.slots.map((_, i) => i).filter((i) => !filled.has(i));
227
+ return { nin: open.length, nout: u.outs, build: (inputs) => {
228
+ const ports = u.slots.map((_, i) => (filled.has(i) ? filled.get(i).build([])[0] : inputs[open.indexOf(i)]));
229
+ return [P(unitBox(u, ports).id)];
230
+ } };
231
+ }
232
+
233
+ function codeBlock(node) {
234
+ const text = prog.src.slice(node.at, node.end).trim().replace(/^\((.*)\)$/s, "$1");
235
+ const a = arity(text);
236
+ if (!a) throw new NeedArity([text]);
237
+ return { nin: a.ins, nout: a.outs, build: (inputs) => {
238
+ const b = fresh(box("faust", [text], { io: { ins: a.ins, outs: a.outs } }));
239
+ inputs.forEach((q, i) => wire(q, b.id, i));
240
+ return Array.from({ length: a.outs }, (_, k) => P(b.id, k));
241
+ } };
242
+ }
243
+
244
+ function lookup(env, n) { for (let e = env; e; e = e.up) if (e.vars.has(n)) return e.vars.get(n); return undefined; }
245
+
246
+ // a definition of the program, used by name: a block (or a function when it has parameters)
247
+ function defBlock(d, env, callArgs, callEnv) {
248
+ if (!d.params.length) {
249
+ if (callArgs) throw new Error(`${d.name} takes no arguments`);
250
+ if (!d.memo) {
251
+ const blk = evaluate(d.body, d.env);
252
+ if (blk.nin === 0) {
253
+ let ports = blk.build([]);
254
+ ports = ports.map((q) => {
255
+ if (q.num !== undefined && lay.has(d.name)) return P(named(box("num", [q.num]), d.name).id);
256
+ return q;
257
+ });
258
+ const ids = new Set(ports.map((q) => q.box));
259
+ if (ports.length && ids.size === 1 && ports[0].box !== undefined) {
260
+ const b = graph.boxes.find((x) => x.id === ports[0].box);
261
+ if (b.autoName && b.type !== "in") nameBox(b, d.name);
262
+ }
263
+ d.memo = portsBlock(ports);
264
+ } else d.memo = blk;
265
+ }
266
+ return d.memo;
267
+ }
268
+ // a function: bound to blocks (its arguments), or used bare, its parameters taken as inputs
269
+ if (callArgs) {
270
+ const blocks = callArgs.map((a) => evaluate(a, callEnv));
271
+ if (blocks.length !== d.params.length) throw new Error(`${d.name} takes ${d.params.length} arguments`);
272
+ const key = blocks.every((b) => b.nin === 0) ? JSON.stringify(blocks.map((b) => b.build([]))) : null;
273
+ d.calls = d.calls || new Map();
274
+ if (key && d.calls.has(key)) return d.calls.get(key);
275
+ const inner = { vars: new Map(d.params.map((p, i) => [p, { block: blocks[i] }])), up: d.env };
276
+ let blk = evaluate(d.body, inner);
277
+ if (key && blk.nin === 0) {
278
+ const ports = blk.build([]);
279
+ if (ports.length === 1 && ports[0].box !== undefined) {
280
+ const b = graph.boxes.find((x) => x.id === ports[0].box);
281
+ if (b.autoName) nameBox(b, d.name);
282
+ }
283
+ blk = portsBlock(ports);
284
+ d.calls.set(key, blk);
285
+ }
286
+ return blk;
287
+ }
288
+ return { nin: d.params.length, nout: undefined, params: d.params, build: (inputs) => {
289
+ const inner = { vars: new Map(d.params.map((p, i) => [p, { block: portsBlock([inputs[i]]) }])), up: d.env };
290
+ const blk = evaluate(d.body, inner);
291
+ if (blk.nin !== 0) throw new Error(`${d.name}: too many inputs`);
292
+ return blk.build([]);
293
+ } };
294
+ }
295
+
296
+ function evaluate(node, env) {
297
+ switch (node.k) {
298
+ case "num": return portsBlock([N(node.v)]);
299
+ case "str": throw new Error("a text is only a label of a control");
300
+ case "id": case "call": {
301
+ const fnode = node.k === "id" ? node : node.f;
302
+ const n = fnode.v, callArgs = node.k === "call" ? node.args : null;
303
+ if (n === "_" && !callArgs) return { nin: 1, nout: 1, build: (i) => [i[0]] };
304
+ if (n === "!" && !callArgs) return { nin: 1, nout: 0, build: () => [] };
305
+ if (n === "ba.selector" && callArgs) {
306
+ const [k, m] = callArgs.map((a) => constNum(evaluate(a, env)));
307
+ return { nin: m, nout: 1, build: (i) => [i[k]] };
308
+ }
309
+ const v = lookup(env, n);
310
+ if (v) {
311
+ if (v.block) { if (callArgs) throw new Error(`${n} is a signal, not a function`); return v.block; }
312
+ return defBlock(v.def, env, callArgs, env);
313
+ }
314
+ if (UNITS[n] && UNITS[n].kind !== "num" && UNITS[n].kind !== "io") return unitBlock(UNITS[n], callArgs, env, node);
315
+ if (/^[A-Za-z_]/.test(n)) return codeBlock(node);
316
+ throw new Error(`${n} is not something the boxes know`);
317
+ }
318
+ case "mem": return evaluate({ k: "comp", op: ":", l: node.x, r: { k: "id", v: "'" } }, env);
319
+ case "bin": return evaluate({ k: "comp", op: ":", l: { k: "comp", op: ",", l: node.l, r: node.r }, r: { k: "id", v: node.op } }, env);
320
+ case "comp": {
321
+ const A = evaluate(node.l, env), B = evaluate(node.r, env);
322
+ if (node.op === ",") return { nin: A.nin + B.nin, nout: A.nout !== undefined && B.nout !== undefined ? A.nout + B.nout : undefined, build: (i) => A.build(i.slice(0, A.nin)).concat(B.build(i.slice(A.nin))) };
323
+ if (node.op === ":") return { nin: A.nin, nout: B.nout, build: (i) => {
324
+ const o = A.build(i);
325
+ if (o.length !== B.nin) throw new Error(`${o.length} outputs into ${B.nin} inputs (:)`);
326
+ return B.build(o);
327
+ } };
328
+ if (node.op === "<:") return { nin: A.nin, nout: B.nout, build: (i) => {
329
+ const o = A.build(i);
330
+ if (!o.length || B.nin % o.length) throw new Error(`${o.length} outputs cannot split into ${B.nin} inputs (<:)`);
331
+ return B.build(Array.from({ length: B.nin }, (_, j) => o[j % o.length]));
332
+ } };
333
+ if (node.op === ":>") return { nin: A.nin, nout: B.nout, build: (i) => {
334
+ const o = A.build(i);
335
+ if (!B.nin || o.length % B.nin) throw new Error(`${o.length} outputs cannot merge into ${B.nin} inputs (:>)`);
336
+ const sums = Array.from({ length: B.nin }, () => []);
337
+ o.forEach((q, j) => sums[j % B.nin].push(q));
338
+ // a merge is a sum: explicit + boxes
339
+ return B.build(sums.map((s) => s.reduce((a, q) => P(unitBox(UNITS["+"], [a, q]).id))));
340
+ } };
341
+ if (node.op === "~") {
342
+ if (B.nout === undefined) throw new Error("~: cannot tell how many signals come back");
343
+ const k = B.nout;
344
+ return { nin: A.nin - k, nout: A.nout, build: (i) => {
345
+ // B's outputs come back into A's first inputs through one-sample delays
346
+ // named after the loop function's parameters when there is one (the form the code of a patch takes)
347
+ const mems = Array.from({ length: k }, (_, j) => (A.params && A.params[j] ? named(box("'", []), A.params[j]) : box("'", [])));
348
+ const o = A.build(mems.map((m) => P(m.id)).concat(i));
349
+ const fb = B.build(o.slice(0, B.nin));
350
+ fb.forEach((q, j) => wire(q, mems[j].id, 0));
351
+ return o;
352
+ } };
353
+ }
354
+ break;
355
+ }
356
+ case "with": {
357
+ const inner = { vars: new Map(), up: env };
358
+ for (const d of node.defs) inner.vars.set(d.name, { def: { ...d, env: inner } });
359
+ return evaluate(node.x, inner);
360
+ }
361
+ case "letrec": {
362
+ // 'v = e: inside the definitions of a letrec, v is its own value one sample before (a delay's
363
+ // output); in the expression the letrec belongs to, v is the value itself (that delay's input)
364
+ // both appear only when used: an unused variable leaves no box behind
365
+ const inside = { vars: new Map(), up: env }, outside = { vars: new Map(), up: env };
366
+ const PENDING = {}, mem = new Map(), val = new Map(), defs = new Map(node.defs.map((d) => [d.name, d]));
367
+ const memOf = (n) => {
368
+ if (!mem.has(n)) { const m = box("'", []); mem.set(n, m); if (val.get(n) && val.get(n) !== PENDING) wire(val.get(n), m.id, 0); }
369
+ return mem.get(n);
370
+ };
371
+ const valOf = (n) => {
372
+ if (!val.has(n)) {
373
+ val.set(n, PENDING); // while its own definition is being read
374
+ const b = evaluate(defs.get(n).body, inside);
375
+ const o = b.nin === 0 ? b.build([]) : [];
376
+ if (o.length !== 1) throw new Error(`'${n} must be one signal`);
377
+ val.set(n, o[0]);
378
+ if (mem.has(n)) wire(o[0], mem.get(n).id, 0);
379
+ }
380
+ return val.get(n);
381
+ };
382
+ for (const d of node.defs) {
383
+ inside.vars.set(d.name, { block: { nin: 0, nout: 1, build: () => { const m = memOf(d.name); valOf(d.name); return [P(m.id)]; } } });
384
+ outside.vars.set(d.name, { block: { nin: 0, nout: 1, build: () => [valOf(d.name)] } });
385
+ }
386
+ return evaluate(node.x, outside);
387
+ }
388
+ }
389
+ throw new Error("cannot read this part");
390
+ }
391
+
392
+ // the program
393
+ const env = { vars: new Map(), up: null };
394
+ for (const d of prog.defs) env.vars.set(d.name, { def: { ...d, env } });
395
+ const pd = env.vars.get("process");
396
+ if (!pd) throw new Error("no process");
397
+ const d = pd.def;
398
+ let ins = [], blk;
399
+ if (d.params.length) {
400
+ ins = d.params.map((pn, j) => P(named(box("in", [j + 1]), pn).id));
401
+ const inner = { vars: new Map(d.params.map((pn, j) => [pn, { block: portsBlock([ins[j]]) }])), up: env };
402
+ blk = evaluate(d.body, inner);
403
+ } else blk = evaluate(d.body, env);
404
+ for (let j = 0; j < (blk.nin || 0); j++) { const b = box("in", [ins.length + 1]); ins.push(P(b.id)); }
405
+ const extra = ins.slice(d.params.length);
406
+ const outs = blk.build(d.params.length ? extra : ins);
407
+ if (need.size) throw new NeedArity([...need]);
408
+ outs.forEach((q, j) => { const b = box("out", [j + 1]); wire(q, b.id, 0); });
409
+
410
+ // names: what the code called them (unique), then automatic ones; positions: from the layout comment
411
+ const taken = new Set();
412
+ for (const b of graph.boxes) {
413
+ if (b.autoName) continue;
414
+ if (taken.has(b.name)) { b.autoName = true; continue; }
415
+ taken.add(b.name);
416
+ }
417
+ for (const b of graph.boxes) if (b.autoName) { delete b.autoName; delete b.name; name(graph, b); }
418
+ graph.boxes.forEach((b) => { if (lay.has(b.name)) Object.assign(b, lay.get(b.name)); });
419
+ return layout(graph);
420
+ }
421
+
422
+ // parse, asking the compiler (async) for the inputs and outputs of the Faust code the boxes do not know
423
+ export async function toGraphAsync(src, arityOf, cache = new Map()) {
424
+ for (let round = 0; round < 8; round++) {
425
+ try {
426
+ return toGraph(src, (t) => cache.get(t));
427
+ } catch (e) {
428
+ if (!(e instanceof NeedArity)) throw e;
429
+ for (const t of e.texts) if (!cache.has(t)) {
430
+ const a = await arityOf(t);
431
+ if (!a) throw new Error(`the compiler does not understand: ${t}`);
432
+ cache.set(t, a);
433
+ }
434
+ }
435
+ }
436
+ throw new Error("could not read the code");
437
+ }
438
+
439
+ export { CODE };
@@ -0,0 +1,195 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ // @kairotic/faust-units · a sound → the values of a faust~'s sliders that sound closest to it → its code
3
+ // with the sliders starting there: a recipe (discussion #114, Study 35).
4
+ //
5
+ // Nothing in it is about one synth: the code's own sliders are the parameters (their range, and a log
6
+ // scale when the code says [scale:log]); a small bank of random settings, rendered, standardises the
7
+ // distance and gives the first guess (the nearest one); the pitch, when a slider is called pitch, key,
8
+ // note or midi (MIDI) or freq, frequency, f0 or hz (Hz), is heard by YIN and held, at the octave that
9
+ // sounds closest; and CMA-ES looks for the rest by rendering the real code and listening (Meyda, as
10
+ // features~). Every render is brought to the target's loudest frame first, so a recording at any level
11
+ // can be matched. It runs in the page, a moment at a time (the browser keeps drawing and playing), and
12
+ // stops when its signal is aborted.
13
+ //
14
+ // const r = await find({ faust, code, Meyda, sound: { sr, chans }, budget, signal, onProgress });
15
+ // r.code // the code, its sliders starting at the values found; r.values, r.fx, r.nearestFx, r.pitch
16
+
17
+ import { renderer, controls } from "./render.mjs";
18
+ import { analyse, matcher, peakRms, pitchOf, octaveOf, SR } from "./listen.mjs";
19
+ import { cmaes } from "./cmaes.mjs";
20
+
21
+ export { renderer, controls };
22
+
23
+ export function sliders(json) {
24
+ return controls(json).filter((c) => c.type === "hslider" || c.type === "vslider" || c.type === "nentry");
25
+ }
26
+ const logOk = (c) => c.scale === "log" && c.min > 0 && c.max > c.min;
27
+ export function toValue(c, u) {
28
+ u = Math.min(1, Math.max(0, u));
29
+ return logOk(c) ? c.min * Math.pow(c.max / c.min, u) : c.min + (c.max - c.min) * u;
30
+ }
31
+ export function fromValue(c, v) {
32
+ if (c.max === c.min) return 0;
33
+ const u = logOk(c) ? Math.log(v / c.min) / Math.log(c.max / c.min) : (v - c.min) / (c.max - c.min);
34
+ return Math.min(1, Math.max(0, u));
35
+ }
36
+ export const valuesOf = (cs, u) => Object.fromEntries(cs.map((c, i) => [c.label, toValue(c, u[i])]));
37
+
38
+ function rng(seed) {
39
+ let a = seed >>> 0;
40
+ return () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
41
+ }
42
+
43
+ // a render brought to a loudness (its loudest frame at `ref`), then analysed as features~ does
44
+ function heard(Meyda, y, ref) {
45
+ const p = peakRms(y);
46
+ if (p > 1e-6 && ref > 0) { const g = ref / p, z = new Float32Array(y.length); for (let i = 0; i < y.length; i++) z[i] = y[i] * g; y = z; }
47
+ return analyse(Meyda, y);
48
+ }
49
+
50
+ // the slider a pitch is held on: {index, kind: "midi"|"hz"} or null
51
+ export function pitchSlider(cs) {
52
+ const i = cs.findIndex((c) => /^(pitch|key|note|midi)$/i.test(c.label));
53
+ if (i >= 0) return { index: i, kind: "midi" };
54
+ const j = cs.findIndex((c) => /^(freq|frequency|f0|hz)$/i.test(c.label));
55
+ return j >= 0 ? { index: j, kind: "hz" } : null;
56
+ }
57
+
58
+ const stopped = () => Object.assign(new Error("stopped"), { name: "AbortError" });
59
+ const now = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
60
+ // a moment given back to the page: a message to itself (a timer in a page that is not in front waits a second
61
+ // or more; a message does not)
62
+ const breath = () => new Promise((ok) => {
63
+ if (typeof MessageChannel === "undefined") return setTimeout(ok, 0);
64
+ const c = new MessageChannel();
65
+ c.port1.onmessage = () => { c.port1.close(); ok(); };
66
+ c.port2.postMessage(0);
67
+ });
68
+
69
+ // fit(Meyda, render, json, target, opts) → Promise of { values, u, fx, f0, start, pitch, history, bank, sliders, nearestFx }
70
+ // render(values, {dur, gate}) → samples; target: samples (at 44.1 kHz, dur seconds)
71
+ // opts: bank (random settings rendered first), budget (renders for the search), seed, dur, gate,
72
+ // start (a guess in [0, 1] to begin from instead of the nearest), signal (an AbortSignal),
73
+ // slice (ms of work between two moments given back to the browser), onProgress(phase, done, total, best)
74
+ export async function fit(Meyda, render, json, target, { bank = 64, budget = 300, seed = 1, dur = 1.0, gate = 0.65, start = null,
75
+ holdPitch = true, signal = null, slice = 30, onProgress = () => {} } = {}) {
76
+ const cs = sliders(json);
77
+ if (!cs.length) throw new Error("this code has no sliders to look for");
78
+ const ref = peakRms(target);
79
+ if (!(ref > 1e-4)) throw new Error("the sound is silent");
80
+ const ft = analyse(Meyda, target);
81
+ let t0 = now();
82
+ const breathe = async () => {
83
+ if (signal && signal.aborted) throw stopped();
84
+ if (now() - t0 > slice) { await breath(); t0 = now(); if (signal && signal.aborted) throw stopped(); }
85
+ };
86
+ const play = async (u) => { const f = heard(Meyda, render(valuesOf(cs, u), { dur, gate }), ref); await breathe(); return f; };
87
+ // 1. a bank of random settings: the distance's statistics, and the nearest as a first guess
88
+ const r = rng(seed), B = [];
89
+ for (let k = 0; k < bank; k++) {
90
+ const u = cs.map(() => r());
91
+ B.push({ u, f: await play(u) });
92
+ onProgress("bank", k + 1, bank);
93
+ }
94
+ const m = matcher(B);
95
+ const tq = m.vec(ft), dist = async (u) => m.dist(m.vec(await play(u)), tq);
96
+ const nearest = m.nearest(ft).example.u;
97
+ const s0 = start ? start.slice() : nearest.slice();
98
+ // 2. the pitch, heard apart and held
99
+ const ps = holdPitch ? pitchSlider(cs) : null;
100
+ let pitch = null, fixed = null;
101
+ const midiRange = (c, kind) => kind === "midi" ? [c.min, c.max]
102
+ : [69 + 12 * Math.log2(Math.max(1, c.min) / 440), 69 + 12 * Math.log2(Math.max(1, c.max) / 440)];
103
+ const atMidi = (c, kind, mid) => fromValue(c, kind === "midi" ? mid : 440 * Math.pow(2, (mid - 69) / 12));
104
+ if (ps) {
105
+ const yp = pitchOf(target);
106
+ if (yp.midi !== null) {
107
+ const c = cs[ps.index], guess = toValue(c, s0[ps.index]);
108
+ const guessMidi = ps.kind === "midi" ? guess : 69 + 12 * Math.log2(Math.max(1, guess) / 440);
109
+ const [lo, hi] = midiRange(c, ps.kind);
110
+ // YIN's note, at the octave that sounds closest (the guess's, and one below and above: three renders)
111
+ const base = octaveOf(yp.midi, guessMidi, lo, hi);
112
+ let best = null;
113
+ for (const mid of [base - 12, base, base + 12]) {
114
+ if (mid < lo - 0.5 || mid > hi + 0.5) continue;
115
+ const u = s0.slice(); u[ps.index] = atMidi(c, ps.kind, mid);
116
+ const d = await dist(u);
117
+ if (!best || d < best.d) best = { mid, d };
118
+ }
119
+ if (best) { pitch = best.mid; fixed = atMidi(c, ps.kind, pitch); s0[ps.index] = fixed; }
120
+ }
121
+ }
122
+ // 3. the search that listens, over every slider but the one holding the pitch
123
+ const free = cs.map((_, i) => i).filter((i) => !(fixed !== null && i === ps.index));
124
+ const full = (v) => { const u = s0.slice(); free.forEach((i, k) => { u[i] = v[k]; }); return u; };
125
+ let u = s0.slice(), fx, history = [], f0;
126
+ if (free.length) {
127
+ const res = await cmaes((v) => dist(full(v)), free.map((i) => s0[i]), { budget, seed: seed + 2,
128
+ onStep: (best, n) => onProgress("search", n, budget, best.fx) });
129
+ u = full(res.x); fx = res.fx; history = res.history; f0 = res.history[0][1];
130
+ } else { fx = f0 = await dist(u); }
131
+ // the octave again, now that the rest is found (two renders): a filtered note can sound closest an
132
+ // octave away with the first guess's timbre, not with its own
133
+ if (fixed !== null) {
134
+ const c = cs[ps.index], [lo, hi] = midiRange(c, ps.kind);
135
+ for (const mid of [pitch - 12, pitch + 12]) {
136
+ if (mid < lo - 0.5 || mid > hi + 0.5) continue;
137
+ const v = u.slice(); v[ps.index] = atMidi(c, ps.kind, mid);
138
+ const d = await dist(v);
139
+ if (d < fx) { u = v; fx = d; pitch = mid; }
140
+ }
141
+ }
142
+ return { values: valuesOf(cs, u), u, fx, f0, start: s0, pitch, history, bank: B.length, sliders: cs, nearestFx: await dist(nearest) };
143
+ }
144
+
145
+ // the recipe: the same code with each slider starting at the value found
146
+ export function recipe(code, values, cs) {
147
+ const byLabel = new Map(cs.map((c) => [c.label, c]));
148
+ return code.replace(/\b(hslider|vslider|nentry)\s*\(\s*"([^"]*)"\s*,\s*([^,()]+?)\s*,/g, (all, kind, label, init) => {
149
+ const name = label.replace(/\[[^\]]*\]/g, "").trim(), c = byLabel.get(name);
150
+ if (!c || !(name in values)) return all;
151
+ const digits = c.step > 0 ? Math.max(0, Math.min(6, Math.ceil(-Math.log10(c.step)))) : 4;
152
+ return `${kind}("${label}", ${(+values[name].toFixed(digits)).toString()},`;
153
+ });
154
+ }
155
+
156
+ // a sound as the search hears it: its channels mixed, at 44.1 kHz, from where it starts (its silence
157
+ // before left out), `dur` seconds long (silence after, if it is shorter)
158
+ export function targetOf({ sr, chans }, { dur = 1.0 } = {}) {
159
+ const n0 = chans[0].length, mono = new Float32Array(n0);
160
+ for (const ch of chans) for (let i = 0; i < n0; i++) mono[i] += ch[i] / chans.length;
161
+ let peak = 0;
162
+ for (const v of mono) peak = Math.max(peak, Math.abs(v));
163
+ let at = 0;
164
+ while (at < n0 && Math.abs(mono[at]) < 0.05 * peak) at++;
165
+ at = Math.max(0, at - Math.round(0.005 * sr));
166
+ const n = Math.round(dur * SR), y = new Float32Array(n), k = sr / SR;
167
+ for (let i = 0; i < n; i++) {
168
+ const p = at + i * k, j = Math.floor(p), f = p - j;
169
+ if (j + 1 >= n0) break;
170
+ y[i] = mono[j] * (1 - f) + mono[j + 1] * f;
171
+ }
172
+ return y;
173
+ }
174
+
175
+ // compiles code with faustwasm ({F, compiler}, as the page loads it) and plays it offline
176
+ export async function compileOffline(faust, code) {
177
+ const gen = new faust.F.FaustMonoDspGenerator();
178
+ const ok = await gen.compile(faust.compiler, "recipe" + Math.random().toString(36).slice(2, 7), code, "-ftz 2");
179
+ if (!ok) throw new Error("Faust could not compile this code");
180
+ const json = JSON.parse(gen.factory.json);
181
+ return { json, render: renderer(gen.factory.module || gen.factory.code, json) };
182
+ }
183
+
184
+ // the whole of it: the code of a faust~ and a sound → its recipe
185
+ export async function find({ faust, code, Meyda, sound, bank = 48, budget = 240, seed = 1, dur = 1.0, gate = 0.65, signal = null,
186
+ onProgress = () => {} }) {
187
+ const { json, render } = await compileOffline(faust, code);
188
+ if (!sliders(json).length) throw new Error("this code has no sliders to look for (hslider, vslider or nentry)");
189
+ const target = targetOf(sound, { dur });
190
+ const r = await fit(Meyda, render, json, target, { bank, budget, seed, dur, gate, signal, onProgress });
191
+ return Object.assign(r, { code: recipe(code, r.values, r.sliders), target, y: render(r.values, { dur, gate }) });
192
+ }
193
+
194
+ // what api/import-module gives the page (it takes a module's default export)
195
+ export default { find, fit, recipe, targetOf, compileOffline, sliders, valuesOf, toValue, fromValue, pitchSlider, renderer, controls };