@kairotic/app 0.0.0-stage → 0.2.1

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,270 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ // Kairotic · ring~: the core of the box (Study 48's heads, in the app). One AudioWorklet node holds the span —
3
+ // a buffer of the last `len` seconds of sound — and every head on it: the ring's own write head and the
4
+ // writer~ and reader~ boxes connected to its right outlet, each in a slot of the node. So they share the
5
+ // buffer, and what one writes another reads in the same sample.
6
+ //
7
+ // input 0 the ring's own input: written where its time is (its write head, a tape head)
8
+ // input 1 + s (2 ch) slot s: channel 0 what a writer~ writes, channel 1 a position (seconds, or 0…1 × len
9
+ // with norm), when its position comes from a signal
10
+ // output s (mono) slot s: what a reader~ reads
11
+ //
12
+ // A writer writes what it gets on every sample it passes, as a tape head: ovr replaces, mix keeps what was
13
+ // there times keep. Its position: the ring's head (by default), a signal, or a clock from t at speed 1 (:rec t
14
+ // / :ovr t; rec also erases the ring first). A reader reads (cubic): following the ring's head d behind and then
15
+ // drifting by its speed (a new d glides at a second per second, or seeks with a crossfade when it is larger than
16
+ // jump), or at a position signal (a jump is a seek, crossfaded). Readers read before writers write, so a reader
17
+ // d behind meets the sound exactly d later.
18
+ //
19
+ // A faust~ in a loop of the ring (reader~ → faust~ → writer~, all on this ring~) runs here, in the writer's slot
20
+ // (Study 49): what the readers it hears send goes through it one sample at a time and is written with what reaches
21
+ // the writer~'s left. So the loop is exact at any d; through other boxes it would cost a block. The page sends
22
+ // the faust~'s compiled bytes and JSON; they are instantiated here as faustwasm does (synchronously).
23
+ //
24
+ // Messages on the port: {attach: {slot, role, ...opts}} · {detach: slot} · {set: {slot, ...}} ·
25
+ // {fold: {slot, readers: [slots], code, json}} · {unfold: slot} · {param: {slot, address, value}} ·
26
+ // {cue: {slot, kind, t}} · {clear: true} · {own: false} (its own head stops writing: nothing on its left). In a worklet it registers "kairotic-ring"; in Node it is a module.
27
+
28
+ const READER = { role: "read", mode: "follow", d: 1, speed: 1, jump: 0.25, xfade: 0.03, gain: 1, norm: false };
29
+ const WRITER = { role: "write", mode: "head", write: "ovr", keep: 1, jump: 0.25, norm: false };
30
+
31
+ export class RingCore {
32
+ constructor(sr, len = 8, maxSeconds = 60, slots = 8) {
33
+ this.sr = sr;
34
+ this.max = Math.max(8, Math.ceil(maxSeconds * sr));
35
+ this.buf = new Float32Array(this.max);
36
+ this.N = Math.min(this.max, Math.max(8, Math.round(len * sr)));
37
+ this.len = this.N / sr;
38
+ this.n = 0;
39
+ this.own = true; // its own write head writes its input (with nothing on its left, the page turns it off)
40
+ this.slots = new Array(slots).fill(null);
41
+ }
42
+
43
+ // ── heads ──
44
+ attach(slot, o) {
45
+ if (slot < 0 || slot >= this.slots.length) return;
46
+ const h = Object.assign({}, o.role === "write" ? WRITER : READER, o,
47
+ { p: null, last: null, dc: null, drift: 0, old: null, xf: 0, xfLen: 1, y: 0, clock: null });
48
+ h.dc = h.d;
49
+ this.slots[slot] = h;
50
+ }
51
+ detach(slot) { if (slot >= 0 && slot < this.slots.length) this.slots[slot] = null; }
52
+ set(slot, o) {
53
+ const h = this.slots[slot]; if (!h) return;
54
+ const was = h.mode;
55
+ Object.assign(h, o);
56
+ // a new d is a distance from now: the drift starts again (first the distance, then the speed)
57
+ if (h.role === "read" && (o.d != null || (o.mode === "follow" && was !== "follow"))) h.drift = 0;
58
+ }
59
+ cue(slot, kind, t) {
60
+ const h = this.slots[slot]; if (!h || h.role !== "write") return;
61
+ if (kind === "stop") { h.clock = null; if (h.mode === "clock") h.mode = "held"; return; }
62
+ h.mode = "clock"; h.write = "ovr"; h.clock = { n: this.n, p: t || 0 }; h.p = null; // a seek: nothing between
63
+ if (kind === "rec") this.buf.fill(0, 0, this.N);
64
+ }
65
+ clear() { this.buf.fill(0, 0, this.N); }
66
+ message(m) {
67
+ if (!m) return;
68
+ if (m.attach) { const { slot, ...o } = m.attach; this.attach(slot, o); }
69
+ if (m.detach != null) this.detach(m.detach);
70
+ if (m.set) { const { slot, ...o } = m.set; this.set(slot, o); }
71
+ if (m.cue) this.cue(m.cue.slot, m.cue.kind, m.cue.t);
72
+ if (m.clear) this.clear();
73
+ if (m.own != null) this.own = !!m.own;
74
+ if (m.fold) this.fold(m.fold.slot, m.fold.readers, makeInsert(m.fold.code, m.fold.json, this.sr));
75
+ if (m.unfold != null) { const h = this.slots[m.unfold]; if (h) h.fold = null; }
76
+ if (m.param) { const h = this.slots[m.param.slot]; if (h && h.fold && h.fold.insert) h.fold.insert.set(m.param.address, m.param.value); }
77
+ }
78
+ // a writer hears these readers through an insert ({step(x) → y, set(address, value)}; null: straight)
79
+ fold(slot, readers, insert) {
80
+ const h = this.slots[slot]; if (!h || h.role !== "write") return;
81
+ h.fold = { readers: readers || [], insert };
82
+ }
83
+
84
+ // ── the buffer ──
85
+ idx(i) { const N = this.N; i %= N; return i < 0 ? i + N : i; }
86
+ cell(p) { return Math.floor(p * this.sr + 1e-6); }
87
+ read(p) {
88
+ const b = this.buf, s = p * this.sr, i = Math.floor(s + 1e-6), f = Math.max(0, s - i);
89
+ const y1 = b[this.idx(i)];
90
+ if (f === 0) return y1;
91
+ const y0 = b[this.idx(i - 1)], y2 = b[this.idx(i + 1)], y3 = b[this.idx(i + 2)];
92
+ const c1 = 0.5 * (y2 - y0), c2 = y0 - 2.5 * y1 + 2 * y2 - 0.5 * y3, c3 = 0.5 * (y3 - y0) + 1.5 * (y1 - y2);
93
+ return ((c3 * f + c2) * f + c1) * f + y1;
94
+ }
95
+ put(i, v, h) { const j = this.idx(i); this.buf[j] = h.write === "mix" ? h.keep * this.buf[j] + v : v; }
96
+ // a writer from a to b writes v on every sample it passes (forwards (a, b], backwards [b, a)); still, it writes
97
+ // the sample it is on once, and again only with ovr
98
+ write(h, a, b, v) {
99
+ const sa = this.cell(a), sb = this.cell(b);
100
+ if (sb > sa) for (let i = sa + 1; i <= sb; i++) this.put(i, v, h);
101
+ else if (sb < sa) for (let i = sa - 1; i >= sb; i--) this.put(i, v, h);
102
+ else if (h.write === "ovr" || h.last !== sb) this.put(sb, v, h);
103
+ h.last = sb;
104
+ }
105
+ // a position from a signal: seconds (or 0…1 × len with norm), unwrapped so that a phasor~ going back to 0 has
106
+ // gone on, not back
107
+ fromSignal(h, q) {
108
+ const l = this.len, x = h.norm ? q * l : q;
109
+ if (h.p == null) return x;
110
+ const w = ((h.p % l) + l) % l;
111
+ let d = ((x - w) % l + l) % l; if (d > l / 2) d -= l;
112
+ return h.p + d;
113
+ }
114
+
115
+ // ── a block: inputs and outputs as an AudioWorkletProcessor gets them ──
116
+ process(inputs, outputs) {
117
+ const L = outputs.length && outputs[0][0] ? outputs[0][0].length : 128, sr = this.sr, S = this.slots;
118
+ const in0 = inputs[0] && inputs[0][0];
119
+ for (let k = 0; k < L; k++) {
120
+ const t = this.n / sr, head = t;
121
+ // where the writers are now (they write after the readers have read)
122
+ for (let s = 0; s < S.length; s++) {
123
+ const h = S[s]; if (!h || h.role !== "write") continue;
124
+ const ch = inputs[s + 1];
125
+ if (h.mode === "pos") h.np = ch && ch[1] ? this.fromSignal(h, ch[1][k]) : (h.p != null ? h.p : head);
126
+ else if (h.mode === "clock" && h.clock) h.np = h.clock.p + (this.n - h.clock.n) / sr;
127
+ else if (h.mode === "held") h.np = h.p != null ? h.p : head;
128
+ else h.np = head;
129
+ }
130
+ // the readers move and read
131
+ for (let s = 0; s < S.length; s++) {
132
+ const h = S[s]; if (!h || h.role !== "read") continue;
133
+ let p;
134
+ if (h.mode === "pos") {
135
+ const ch = inputs[s + 1];
136
+ p = this.fromSignal(h, ch && ch[1] ? ch[1][k] : 0);
137
+ } else {
138
+ const diff = h.d - h.dc;
139
+ if (diff !== 0) h.dc = Math.abs(diff) > h.jump ? h.d : h.dc + Math.max(-1 / sr, Math.min(1 / sr, diff));
140
+ h.drift += (1 - h.speed) / sr;
141
+ p = head - h.dc - h.drift;
142
+ }
143
+ if (h.p != null && Math.abs(p - h.p) > h.jump && h.xf === 0) {
144
+ h.old = h.p; h.xfLen = Math.max(1, Math.round(h.xfade * sr)); h.xf = h.xfLen;
145
+ } else if (h.old != null && h.p != null) h.old += p - h.p; // the head it leaves keeps moving as it did
146
+ let y = this.read(p);
147
+ if (h.xf > 0) {
148
+ const g = h.xf / h.xfLen;
149
+ y = g * this.read(h.old) + (1 - g) * y;
150
+ if (--h.xf === 0) h.old = null;
151
+ }
152
+ h.p = p; h.y = y;
153
+ const o = outputs[s] && outputs[s][0];
154
+ if (o) o[k] = h.gain * y;
155
+ }
156
+ // the ring's own write head: its input, where its time is
157
+ if (this.own) this.buf[this.idx(this.n)] = in0 ? in0[k] : 0;
158
+ // then the writers, in the order of their slots
159
+ for (let s = 0; s < S.length; s++) {
160
+ const h = S[s]; if (!h || h.role !== "write") continue;
161
+ const ch = inputs[s + 1], p = h.np;
162
+ let v = ch && ch[0] ? ch[0][k] : 0;
163
+ // a loop folded here: what its readers read this sample, through the insert (which runs on every sample)
164
+ if (h.fold) {
165
+ let fb = 0;
166
+ for (const r of h.fold.readers) { const q = S[r]; if (q && q.role === "read") fb += q.y; }
167
+ v += h.fold.insert ? h.fold.insert.step(fb) : fb;
168
+ }
169
+ if (h.p == null || Math.abs(p - h.p) > h.jump) { const c = this.cell(p); this.put(c, v, h); h.last = c; } // a seek
170
+ else this.write(h, h.p, p, v);
171
+ h.p = p;
172
+ }
173
+ this.n++;
174
+ }
175
+ // outputs of empty slots (or of writers) are silent
176
+ for (let s = 0; s < outputs.length; s++) {
177
+ const h = S[s], o = outputs[s] && outputs[s][0];
178
+ if (o && (!h || h.role !== "read")) o.fill(0);
179
+ }
180
+ }
181
+
182
+ // where the heads are (wrapped, in seconds), for a drawing
183
+ state() {
184
+ const l = this.len, w = (p) => (p == null ? null : ((p % l) + l) % l);
185
+ return { len: l, t: this.n / this.sr, head: w(this.n / this.sr),
186
+ slots: this.slots.map((h) => (h ? { role: h.role, mode: h.mode, p: w(h.p) } : null)) };
187
+ }
188
+ }
189
+
190
+ // ── a Faust DSP as an insert (Study 49): compiled bytes and their JSON → {step(x) → y, set(address, value)} ──
191
+ // Its math imports by the names the Faust backend gives them; its memory as faustwasm lays it out (the DSP at 0,
192
+ // the pointers to its buffers after it, then the buffers); every input gets x, output 0 is the result.
193
+ const SPECIAL = {
194
+ max_f: Math.max, max_i: Math.max, max: Math.max, min_f: Math.min, min_i: Math.min, min: Math.min,
195
+ abs: Math.abs, fabsf: Math.abs, fabs: Math.abs,
196
+ isnanf: (x) => +Number.isNaN(x), isnan: (x) => +Number.isNaN(x),
197
+ isinff: (x) => +(x === Infinity || x === -Infinity), isinf: (x) => +(x === Infinity || x === -Infinity),
198
+ copysignf: (x, y) => (y < 0 || Object.is(y, -0) ? -Math.abs(x) : Math.abs(x)),
199
+ copysign: (x, y) => (y < 0 || Object.is(y, -0) ? -Math.abs(x) : Math.abs(x)),
200
+ fmodf: (x, y) => x % y, fmod: (x, y) => x % y,
201
+ remainderf: (x, y) => x - y * Math.round(x / y), remainder: (x, y) => x - y * Math.round(x / y),
202
+ rintf: Math.round, rint: Math.round, nearbyintf: Math.round, nearbyint: Math.round, roundf: Math.round, round: Math.round,
203
+ exp10f: (x) => Math.pow(10, x), exp10: (x) => Math.pow(10, x)
204
+ };
205
+ function mathFn(name) {
206
+ const n = name.replace(/^_+/, "");
207
+ if (SPECIAL[n]) return SPECIAL[n];
208
+ if (typeof Math[n] === "function") return Math[n];
209
+ if (n.endsWith("f") && typeof Math[n.slice(0, -1)] === "function") return Math[n.slice(0, -1)];
210
+ return () => 0;
211
+ }
212
+ export function faustInsert(module, json, sr) {
213
+ const meta = typeof json === "string" ? JSON.parse(json) : json;
214
+ const imports = {};
215
+ let imported = null;
216
+ for (const imp of WebAssembly.Module.imports(module)) {
217
+ const m = (imports[imp.module] = imports[imp.module] || {});
218
+ if (imp.kind === "function") m[imp.name] = mathFn(imp.name);
219
+ else if (imp.kind === "memory") m[imp.name] = imported = new WebAssembly.Memory({ initial: 100 });
220
+ else if (imp.kind === "table") m[imp.name] = new WebAssembly.Table({ initial: 0, element: "anyfunc" });
221
+ else if (imp.kind === "global") m[imp.name] = 0;
222
+ }
223
+ const e = new WebAssembly.Instance(module, imports).exports;
224
+ const memory = e.memory || imported;
225
+ const nin = meta.inputs, nout = meta.outputs;
226
+ if (nout < 1) throw new Error("the faust~ in the loop has no output");
227
+ const inPtrs = meta.size, outPtrs = inPtrs + nin * 4, bufs = outPtrs + nout * 4;
228
+ const need = bufs + (nin + nout) * 4 + 64;
229
+ if (memory.buffer.byteLength < need) memory.grow(Math.ceil((need - memory.buffer.byteLength) / 65536));
230
+ const H32 = new Int32Array(memory.buffer), F32 = new Float32Array(memory.buffer);
231
+ const inBuf = [];
232
+ for (let i = 0; i < nin; i++) { const q = bufs + i * 4; H32[(inPtrs >> 2) + i] = q; inBuf.push(q >> 2); }
233
+ for (let o = 0; o < nout; o++) H32[(outPtrs >> 2) + o] = bufs + (nin + o) * 4;
234
+ const out0 = (bufs + nin * 4) >> 2;
235
+ e.init(0, sr);
236
+ const params = [];
237
+ const walk = (it) => { if (it.items) it.items.forEach(walk); else if (it.address != null && it.index != null) params.push(it); };
238
+ (meta.ui || []).forEach(walk);
239
+ return {
240
+ step(x) {
241
+ for (let i = 0; i < inBuf.length; i++) F32[inBuf[i]] = x;
242
+ e.compute(0, 1, inPtrs, outPtrs);
243
+ const y = F32[out0];
244
+ return Number.isFinite(y) ? y : 0;
245
+ },
246
+ set(address, value) {
247
+ const p = params.find((q) => q.address === address || q.label === address);
248
+ if (p) e.setParamValue(0, p.index, value);
249
+ }
250
+ };
251
+ }
252
+ function makeInsert(code, json, sr) {
253
+ if (!code) return null;
254
+ try { return faustInsert(code instanceof WebAssembly.Module ? code : new WebAssembly.Module(code), json, sr); }
255
+ catch (err) { if (typeof console !== "undefined") console.error("ring~: the faust~ in the loop", err); return null; }
256
+ }
257
+
258
+ // in an AudioWorklet: the processor
259
+ if (typeof registerProcessor === "function") {
260
+ class KairoticRing extends AudioWorkletProcessor {
261
+ constructor(o) {
262
+ super();
263
+ const p = (o && o.processorOptions) || {};
264
+ this.core = new RingCore(sampleRate, p.len || 8, p.max || 60, p.slots || 8);
265
+ this.port.onmessage = (e) => this.core.message(e.data);
266
+ }
267
+ process(inputs, outputs) { this.core.process(inputs, outputs); return true; }
268
+ }
269
+ registerProcessor("kairotic-ring", KairoticRing);
270
+ }
@@ -0,0 +1,176 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · score
3
+ ;; A musical voice in time as EDN data, projected to notation (MEI, drawn with Verovio), with a
4
+ ;; time ⇄ space relation built from the drawn notation, in the style of INScore.
5
+ ;; Voice data: {:tempo beats-per-minute :meter [4 4] :events {:e1 {:t beat :pitch midi :dur beats :txt "…"}}}
6
+ ;; (a canvas gives one with kairotic.canvas/->voice). Also: pitch names and a melody parser for the REPL.
7
+
8
+ (ns kairotic.score
9
+ (:require [clojure.string :as str]))
10
+
11
+ (defn num? [x] (and (number? x) (not (js/isNaN x))))
12
+
13
+ (defn sorted-events [s] (sort-by (fn [[_ e]] [(:t e) (- (:pitch e))]) (:events s)))
14
+
15
+ ;; ───────── pitches ─────────
16
+
17
+ (def pcs {"c" 0 "d" 2 "e" 4 "f" 5 "g" 7 "a" 9 "b" 11})
18
+ (def sharp-names ["c" "c" "d" "d" "e" "f" "f" "g" "g" "a" "a" "b"])
19
+ (def sharp-acc [nil "s" nil "s" nil nil "s" nil "s" nil "s" nil])
20
+
21
+ (defn pitch
22
+ "60, \"c4\", \"f#3\", \"bb2\", \"f##3\", \"fx3\", \"ebb2\", \"cn4\" → MIDI number (c4 = 60)."
23
+ [x]
24
+ (cond (num? x) x
25
+ (keyword? x) (pitch (name x))
26
+ (symbol? x) (pitch (str x))
27
+ (string? x) (let [m (re-matches #"(?i)([a-g])(##|#|x|s|bb|b|n)?(-?\d)" (str/trim x))]
28
+ (when m
29
+ (+ (* 12 (inc (js/parseInt (nth m 3) 10)))
30
+ (get pcs (str/lower-case (nth m 1)))
31
+ (case (some-> (nth m 2) str/lower-case) ("##" "x") 2 ("#" "s") 1 "bb" -2 "b" -1 0))))
32
+ :else nil))
33
+
34
+ (defn parse-melody
35
+ "\"c4/1 d4/.5 r/1 c4+e4+g4/2\" → [[t pitch dur] ...] starting at beat t0."
36
+ [txt t0]
37
+ (loop [toks (remove str/blank? (str/split (str/trim (str txt)) #"\s+")) t t0 out []]
38
+ (if (empty? toks)
39
+ out
40
+ (let [[p d] (str/split (first toks) #"/")
41
+ dur (if d (js/parseFloat d) 1)
42
+ dur (if (js/isNaN dur) 1 dur)]
43
+ (if (= (str/lower-case p) "r")
44
+ (recur (rest toks) (+ t dur) out)
45
+ (let [ps (map pitch (str/split p #"\+"))]
46
+ (when (some nil? ps) (throw (js/Error. (str "I don't understand the note «" p "». Use for example c4, f#3 or bb2."))))
47
+ (recur (rest toks) (+ t dur) (into out (map (fn [a] [t a dur]) ps)))))))))
48
+
49
+ ;; ───────── projection to MEI (notation) ─────────
50
+ ;; A sixteenth-note grid; one voice per staff: notes that start together form a chord,
51
+ ;; a note is cut when the next one starts.
52
+ ;; Every element has its own id (n-<event>-<piece>) so that the notation can be related to the model.
53
+
54
+ (def unit 0.25)
55
+ (defn slots [x] (js/Math.round (/ x unit)))
56
+ (def lens [[16 "1" 0] [12 "2" 1] [8 "2" 0] [6 "4" 1] [4 "4" 0] [3 "8" 1] [2 "8" 0] [1 "16" 0]])
57
+ (defn bar-slots [s] (let [[n d] (:meter s)] (* n (/ 4 d) 4)))
58
+
59
+ (defn segments [notes total]
60
+ (let [groups (vec (sort-by key (group-by :s notes)))
61
+ starts (mapv key groups)]
62
+ (loop [i 0 cur 0 out []]
63
+ (if (>= i (count groups))
64
+ (if (< cur total) (conj out {:s cur :e total :notes nil}) out)
65
+ (let [[s g] (nth groups i)
66
+ nxt (get starts (inc i))
67
+ e (min (apply min (map :e g)) (or nxt js/Infinity))
68
+ e (max e (inc s))
69
+ out (if (> s cur) (conj out {:s cur :e s :notes nil}) out)]
70
+ (recur (inc i) (max cur e) (conj out {:s s :e e :notes (sort-by :pitch g)})))))))
71
+
72
+ (defn pieces [s e bar]
73
+ (loop [p s out []]
74
+ (if (>= p e)
75
+ out
76
+ (let [room (- bar (mod p bar))
77
+ remaining (- e p)
78
+ [len du dots] (first (filter (fn [[l]] (<= l (min room remaining))) lens))]
79
+ (recur (+ p len) (conj out {:p p :len len :dur du :dots dots}))))))
80
+
81
+ (defn nid [pre id k] (str "n-" pre (name id) "-" k))
82
+
83
+ (defn note-xml [pre n k durattr]
84
+ (let [a (:pitch n) pc (mod a 12)]
85
+ (str "<note xml:id=\"" (nid pre (:id n) k) "\" pname=\"" (nth sharp-names pc) "\" oct=\"" (dec (js/Math.floor (/ a 12))) "\""
86
+ (when-let [ac (nth sharp-acc pc)] (str " accid=\"" ac "\""))
87
+ durattr
88
+ ;; a text under the note (e.g. the deviation in cents of an untempered pitch)
89
+ (if (and (:txt n) (zero? k))
90
+ (str "><verse n=\"1\"><syl>" (-> (str (:txt n)) (str/replace "&" "&amp;") (str/replace "<" "&lt;")) "</syl></verse></note>")
91
+ "/>"))))
92
+
93
+ (defn ->mei*
94
+ "MEI of the voice. `staves` = [[n filter clef-shape clef-line] ...]; `pre` prefixes the ids
95
+ (so that several scores can live on one page). Returns {:mei text :pieces [{:id :t :ev :staff}]}."
96
+ [s staves pre]
97
+ (let [bar (bar-slots s)
98
+ notes (for [[id e] (sorted-events s)]
99
+ (let [a (slots (:t e))]
100
+ {:id id :s a :e (max (inc a) (slots (+ (:t e) (:dur e)))) :pitch (:pitch e) :txt (:txt e)}))
101
+ nbars (max 2 (js/Math.ceil (/ (reduce max 0 (map :e notes)) bar)))
102
+ total (* nbars bar)
103
+ measures (atom (vec (repeat nbars {:ties []})))
104
+ placed (atom [])]
105
+ (doseq [[st keep? _ _] staves]
106
+ (doseq [[si seg] (map-indexed vector (segments (filter keep? notes) total))]
107
+ (let [pz (pieces (:s seg) (:e seg) bar)]
108
+ (doseq [[k pc] (map-indexed vector pz)]
109
+ (let [m (quot (:p pc) bar)
110
+ durattr (str " dur=\"" (:dur pc) "\"" (when (pos? (:dots pc)) " dots=\"1\""))
111
+ t (* (:p pc) unit)
112
+ ns-seg (:notes seg)
113
+ xml (if (seq ns-seg)
114
+ (do
115
+ (doseq [n ns-seg]
116
+ (swap! placed conj {:id (nid pre (:id n) k) :t t :ev (:id n) :staff st}))
117
+ (when (< (inc k) (count pz))
118
+ (swap! measures update-in [m :ties] into
119
+ (for [n ns-seg]
120
+ (str "<tie startid=\"#" (nid pre (:id n) k) "\" endid=\"#" (nid pre (:id n) (inc k)) "\"/>"))))
121
+ (if (= 1 (count ns-seg))
122
+ (note-xml pre (first ns-seg) k durattr)
123
+ (str "<chord xml:id=\"c-" pre st "-" si "-" k "\"" durattr ">"
124
+ (apply str (map (fn [n] (note-xml pre n k "")) ns-seg))
125
+ "</chord>")))
126
+ (let [rid (str "r-" pre st "-" si "-" k)]
127
+ (swap! placed conj {:id rid :t t :ev nil :staff st})
128
+ (str "<rest xml:id=\"" rid "\"" durattr "/>")))]
129
+ (swap! measures update-in [m st] (fnil conj []) xml))))))
130
+ {:mei (str "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
131
+ "<mei xmlns=\"http://www.music-encoding.org/ns/mei\" meiversion=\"5.0\">"
132
+ "<meiHead><fileDesc><titleStmt><title>Kairotic</title></titleStmt><pubStmt/></fileDesc></meiHead>"
133
+ "<music><body><mdiv><score>"
134
+ "<scoreDef meter.count=\"" (first (:meter s)) "\" meter.unit=\"" (second (:meter s)) "\" key.sig=\"0\">"
135
+ "<staffGrp" (when (> (count staves) 1) " symbol=\"brace\" bar.thru=\"true\"") ">"
136
+ (apply str (for [[st _ shape line] staves]
137
+ (str "<staffDef n=\"" st "\" lines=\"5\" clef.shape=\"" shape "\" clef.line=\"" line "\"/>")))
138
+ "</staffGrp></scoreDef><section>"
139
+ (apply str (map-indexed (fn [i m]
140
+ (str "<measure n=\"" (inc i) "\">"
141
+ (apply str (for [[st] staves]
142
+ (str "<staff n=\"" st "\"><layer n=\"1\">" (apply str (get m st)) "</layer></staff>")))
143
+ (apply str (:ties m))
144
+ "</measure>"))
145
+ @measures))
146
+ "</section></score></mdiv></body></music></mei>")
147
+ :pieces (vec (sort-by :t @placed))}))
148
+
149
+ (defn ->mei
150
+ "Grand staff (treble and bass, split at middle C)."
151
+ [s]
152
+ (->mei* s [[1 (fn [n] (>= (:pitch n) 60)) "G" 2] [2 (fn [n] (< (:pitch n) 60)) "F" 4]] ""))
153
+
154
+ (defn ->mei-voice
155
+ "A single voice on one staff, with treble or bass clef according to its mean register."
156
+ [s pre]
157
+ (let [as (map :pitch (vals (:events s)))
158
+ low? (and (seq as) (< (/ (reduce + as) (count as)) 57))]
159
+ (->mei* s [[1 (constantly true) (if low? "F" "G") (if low? 4 2)]] pre)))
160
+
161
+ ;; ───────── notation: time ⇄ space relation from the drawn notation ─────────
162
+ ;; After drawing, each piece (note or rest) with its beat is located on the page: those
163
+ ;; anchors {:t :x :y0 :y1 :right} (built by the page) map time to position (cursor).
164
+
165
+ (defn t->pos [as t]
166
+ (when (seq as)
167
+ (let [a (last (filter (fn [x] (<= (:t x) t)) as))
168
+ b (first (filter (fn [x] (> (:t x) t)) as))]
169
+ (cond
170
+ (nil? a) (first as)
171
+ (nil? b) a
172
+ :else
173
+ (let [f (/ (- t (:t a)) (- (:t b) (:t a)))]
174
+ (if (< (js/Math.abs (- (:y0 a) (:y0 b))) 2)
175
+ (assoc a :x (+ (:x a) (* f (- (:x b) (:x a)))))
176
+ (assoc a :x (+ (:x a) (* f (- (- (:right a) 8) (:x a)))))))))))