@zeeuw/riff 0.0.0-stage → 0.1.0-beta.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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/data/registry-data.js +3 -0
  4. package/data/signatures.js +3 -0
  5. package/docs/clean-room.md +450 -0
  6. package/package.json +69 -4
  7. package/src/audio/clock.js +383 -0
  8. package/src/audio/engine.js +678 -0
  9. package/src/audio/index.js +394 -0
  10. package/src/audio/offline.js +73 -0
  11. package/src/audio/params.js +397 -0
  12. package/src/audio/samples.js +274 -0
  13. package/src/audio/unlock.js +70 -0
  14. package/src/audio/voices.js +44 -0
  15. package/src/combinators.js +150 -0
  16. package/src/compat.js +16 -0
  17. package/src/constructors.js +236 -0
  18. package/src/controls.js +199 -0
  19. package/src/draw.js +252 -0
  20. package/src/euclid.js +57 -0
  21. package/src/evaluate.js +251 -0
  22. package/src/extras/check.js +678 -0
  23. package/src/extras/describe.js +433 -0
  24. package/src/extras/editor.js +369 -0
  25. package/src/extras/index.js +10 -0
  26. package/src/fraction.js +300 -0
  27. package/src/hap.js +64 -0
  28. package/src/helpers.js +68 -0
  29. package/src/index.js +74 -0
  30. package/src/mini/index.js +36 -0
  31. package/src/mini/parser.js +400 -0
  32. package/src/ops.js +293 -0
  33. package/src/outline.js +175 -0
  34. package/src/pattern.js +365 -0
  35. package/src/random.js +344 -0
  36. package/src/register.js +83 -0
  37. package/src/registry.js +52 -0
  38. package/src/samples.js +14 -0
  39. package/src/sampling.js +123 -0
  40. package/src/scope.js +77 -0
  41. package/src/signals.js +76 -0
  42. package/src/stepwise.js +150 -0
  43. package/src/structure.js +636 -0
  44. package/src/time.js +70 -0
  45. package/src/tonal.js +583 -0
  46. package/src/transforms.js +125 -0
  47. package/src/transpile.js +394 -0
  48. package/src/util.js +80 -0
  49. package/src/visuals.js +216 -0
@@ -0,0 +1,433 @@
1
+ // Musical analysis (plan 8.8). A RIFF extension with no Strudel counterpart:
2
+ // it changes no event output.
3
+ //
4
+ // describe(codeOrPattern, opts) -> Promise<Description> evaluates a program
5
+ // with audio swapped out (as check() does), queries every played layer for a
6
+ // number of cycles and returns plain JSON about the music: tempo, period,
7
+ // per-layer statistics, a key estimate, chords, an energy curve, sections,
8
+ // rhythm figures and a one-line human summary. It never throws, never starts
9
+ // audio and never fetches anything. Thresholds: docs/decisions.md (plan 8.8).
10
+ import { outline } from '../outline.js';
11
+ import { createRepl } from '../evaluate.js';
12
+ import { Pattern, isPattern, silence, reify } from '../pattern.js';
13
+ import { DRAW_METHODS } from '../draw.js';
14
+ import { toMidi, midiToNoteName } from '../tonal.js';
15
+ import { isSynth } from '../audio/params.js';
16
+ import { lineStarts } from '../util.js';
17
+ import { addScope } from '../scope.js';
18
+
19
+ const DEFAULT_CYCLES = 16;
20
+ const MAX_PERIOD = 64;
21
+ const DEFAULT_BUDGET_MS = 10;
22
+ const NOOP = () => undefined;
23
+ const NOOP_ASYNC = async () => undefined;
24
+
25
+ // Key profiles (Krumhansl & Kessler 1982, probe-tone ratings), index 0 = tonic.
26
+ const MAJOR_PROFILE = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88];
27
+ const MINOR_PROFILE = [6.33, 2.68, 3.52, 5.38, 2.6, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17];
28
+ const PC_NAMES = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B'];
29
+ // Chord templates, larger first; on equal size the earlier one wins.
30
+ const CHORDS = [
31
+ ['maj7', [0, 4, 7, 11]], ['m7', [0, 3, 7, 10]], ['7', [0, 4, 7, 10]], ['m7b5', [0, 3, 6, 10]],
32
+ ['dim7', [0, 3, 6, 9]], ['mMaj7', [0, 3, 7, 11]], ['6', [0, 4, 7, 9]], ['m6', [0, 3, 7, 9]],
33
+ ['', [0, 4, 7]], ['m', [0, 3, 7]], ['dim', [0, 3, 6]], ['aug', [0, 4, 8]], ['sus4', [0, 5, 7]], ['sus2', [0, 2, 7]],
34
+ ];
35
+ const DRUM_SOUND = /^(bd|sd|hh|oh|ch|cp|rim|rs|lt|mt|ht|cr|rd|cb|sh|perc|tom|kick|snare|hat|clap|crash|ride|cowbell|tabla|breaks?|amen|drum)/i;
36
+
37
+ const round = (x, d = 3) => (Number.isFinite(x) ? Number(x.toFixed(d)) : null);
38
+ const mod12 = (x) => ((Math.round(x) % 12) + 12) % 12;
39
+ const num = (x, dflt) => { const n = typeof x === 'number' ? x : Number(x); return Number.isFinite(n) ? n : dflt; };
40
+ const densityLabel = (perCycle, sparse, dense) => (perCycle < sparse ? 'sparse' : perCycle < dense ? 'moderate' : 'dense');
41
+
42
+ function pitchOf(v) {
43
+ if (v === null || v === undefined) return undefined;
44
+ if (typeof v !== 'object') return typeof v === 'string' ? toMidi(v) : undefined;
45
+ if (v.note !== undefined) { const m = toMidi(v.note); if (m !== undefined) return m; }
46
+ if (typeof v.freq === 'number' && v.freq > 0) return 69 + 12 * Math.log2(v.freq / 440);
47
+ return undefined;
48
+ }
49
+
50
+ // --- evaluation: one pattern per played layer ---
51
+
52
+
53
+ async function layersFromCode(code) {
54
+ const starts = lineStarts(code);
55
+ const off = (line, col) => starts[line - 1] + col - 1;
56
+ const trimEnd = (a, b) => { while (b > a && /[\s;]/.test(code[b - 1])) b--; return b; };
57
+ const played = outline(code).filter((L) => L.played && (L.kind === 'label' || L.kind === 'expression'));
58
+ const targets = [];
59
+ for (const L of played) {
60
+ let a = off(L.line, L.column);
61
+ const b = trimEnd(a, off(L.endLine, L.endColumn));
62
+ if (L.kind === 'label') { a = code.indexOf(':', a) + 1; targets.push({ name: L.name, a, b }); continue; }
63
+ const kids = L.children.filter((k) => k.group === 'stack');
64
+ const lastEnd = kids.length ? off(kids.at(-1).endLine, kids.at(-1).endColumn) : 0;
65
+ const chained = code.slice(lastEnd, b).replace(/\/\/.*$/gm, '').replace(/[\s,]/g, '') !== ')';
66
+ if (played.length === 1 && kids.length > 1 && kids.length === L.children.length && !chained) {
67
+ for (const k of kids) targets.push({ name: k.name, a: off(k.line, k.column), b: trimEnd(0, off(k.endLine, k.endColumn)) });
68
+ } else targets.push({ name: played.length === 1 ? 'program' : L.name, a, b });
69
+ }
70
+ let rewritten = code;
71
+ const order = targets.map((t, i) => [t, i]).sort((x, y) => y[0].a - x[0].a);
72
+ for (const [t, i] of order) {
73
+ rewritten = `${rewritten.slice(0, t.a)} await __riff_describe(${i}, async () => (${rewritten.slice(t.a, t.b)}))${rewritten.slice(t.b)}`;
74
+ }
75
+ const errors = [];
76
+ let cps = null;
77
+ const scope = {
78
+ __riff_describe: async (i, fn) => {
79
+ try {
80
+ const v = await fn();
81
+ targets[i].pattern = isPattern(v) ? v : reify(v);
82
+ return v;
83
+ } catch (e) { errors.push(`${targets[i].name}: ${e?.message ?? e}`); return silence; }
84
+ },
85
+ samples: NOOP_ASYNC, initStrudel: NOOP_ASYNC, initAudio: NOOP, evaluate: NOOP_ASYNC, stop: NOOP, play: (p) => p,
86
+ configureSamples: NOOP_ASYNC, preload: NOOP_ASYNC, setSampleSource: NOOP, getAudioContext: NOOP,
87
+ };
88
+ const swapped = ['play', ...DRAW_METHODS, ...DRAW_METHODS.map((n) => `_${n}`)]
89
+ .map((n) => [n, Object.getOwnPropertyDescriptor(Pattern.prototype, n)]);
90
+ for (const [n] of swapped) Object.defineProperty(Pattern.prototype, n, { value: function () { return this; }, writable: true, configurable: true });
91
+ let program;
92
+ try {
93
+ const repl = createRepl({ onError: NOOP, onCps: (c) => { cps = c; } });
94
+ program = await repl.evaluate(rewritten, { throwOnError: true, scope });
95
+ } catch (e) {
96
+ errors.push(String(e?.message ?? e));
97
+ } finally {
98
+ for (const [n, d] of swapped) { if (d) Object.defineProperty(Pattern.prototype, n, d); else delete Pattern.prototype[n]; }
99
+ }
100
+ // Several anonymous `$:` layers get numbered names ($1, $2, ...).
101
+ const anon = targets.filter((t) => t.name === '$').length > 1;
102
+ let layers = targets.map((t, i) => ({ name: anon && t.name === '$' ? '$' + (i + 1) : t.name, pattern: t.pattern }))
103
+ .filter((L) => L.pattern);
104
+ if (layers.length === 0 && isPattern(program)) layers = [{ name: 'program', pattern: program }];
105
+ return { layers, cps, errors };
106
+ }
107
+
108
+ // --- querying ---
109
+
110
+ function sigValue(v) {
111
+ return JSON.stringify(v, (k, x) => (typeof x === 'number' ? Number(x.toPrecision(6)) : x));
112
+ }
113
+
114
+ // events[layer][cycle] = [{b, e, value, pitch, gain}] for onsets in [c, c+1).
115
+ function queryLayers(layers, cycles, budgetMs, errors) {
116
+ const t0 = performance.now();
117
+ const events = layers.map(() => []);
118
+ const sigs = [];
119
+ const maxCycles = Math.max(cycles, 2 * MAX_PERIOD);
120
+ let c = 0;
121
+ for (; c < maxCycles; c++) {
122
+ if (c >= cycles && performance.now() - t0 > budgetMs) break;
123
+ const parts = [];
124
+ layers.forEach((L, i) => {
125
+ let haps = [];
126
+ if (!L.queryError) {
127
+ try { haps = L.pattern.queryArc(c, c + 1); } catch (e) { L.queryError = e; errors.push(`${L.name}: ${e?.message ?? e}`); }
128
+ }
129
+ const list = [];
130
+ for (const h of haps) {
131
+ if (!h.hasOnset()) continue;
132
+ const b = h.whole.begin.valueOf();
133
+ const e = h.whole.end.valueOf();
134
+ const v = h.value;
135
+ const isObj = v !== null && typeof v === 'object';
136
+ const gain = isObj ? num(v.gain, 1) * num(v.velocity, 1) : 1;
137
+ list.push({ b, e, value: v, pitch: pitchOf(v), gain, s: isObj && typeof v.s === 'string' ? v.s : (typeof v === 'string' && toMidi(v) === undefined ? v : undefined), bank: isObj && typeof v.bank === 'string' ? v.bank : undefined });
138
+ }
139
+ list.sort((x, y) => x.b - y.b);
140
+ if (c < cycles) events[i].push(list);
141
+ parts.push(list.map((x) => `${round(x.b - c, 6)},${round(x.e - x.b, 6)},${sigValue(x.value)}`).join(';'));
142
+ });
143
+ sigs.push(parts.join('#'));
144
+ }
145
+ return { events, sigs, queried: c };
146
+ }
147
+
148
+ function findPeriod(sigs) {
149
+ for (let n = 1; n <= MAX_PERIOD && 2 * n <= sigs.length; n++) {
150
+ let ok = true;
151
+ for (let c = 0; c + n < sigs.length && ok; c++) ok = sigs[c] === sigs[c + n];
152
+ if (ok) return n;
153
+ }
154
+ return null;
155
+ }
156
+
157
+ // --- harmony ---
158
+
159
+ function pearson(x, y) {
160
+ const n = x.length;
161
+ const mx = x.reduce((a, b) => a + b, 0) / n;
162
+ const my = y.reduce((a, b) => a + b, 0) / n;
163
+ let sxy = 0, sxx = 0, syy = 0;
164
+ for (let i = 0; i < n; i++) { sxy += (x[i] - mx) * (y[i] - my); sxx += (x[i] - mx) ** 2; syy += (y[i] - my) ** 2; }
165
+ return sxx === 0 || syy === 0 ? 0 : sxy / Math.sqrt(sxx * syy);
166
+ }
167
+
168
+ // Pitch-class histogram weighted by note duration, correlated with the 24
169
+ // rotated profiles. confidence = best correlation scaled down when the
170
+ // runner-up is within 0.1 of it.
171
+ export function estimateKey(hist) {
172
+ if (hist.every((w) => w === 0)) return null;
173
+ const scores = [];
174
+ for (let t = 0; t < 12; t++) {
175
+ for (const [mode, prof] of [['major', MAJOR_PROFILE], ['minor', MINOR_PROFILE]]) {
176
+ const rot = prof.map((_, i) => prof[(i - t + 12) % 12]);
177
+ scores.push({ tonic: PC_NAMES[t], mode, r: pearson(hist, rot) });
178
+ }
179
+ }
180
+ scores.sort((a, b) => b.r - a.r);
181
+ const [best, second] = scores;
182
+ const margin = best.r - second.r;
183
+ const confidence = best.r <= 0 ? 0 : best.r * Math.min(1, margin / 0.1);
184
+ return {
185
+ tonic: best.tonic, mode: best.mode, name: `${best.tonic} ${best.mode}`,
186
+ correlation: round(best.r), confidence: round(confidence),
187
+ runnerUp: `${second.tonic} ${second.mode}`,
188
+ };
189
+ }
190
+
191
+ // Name the chord of a set of MIDI pitches (>= 3 distinct pitch classes).
192
+ export function nameChord(pitches) {
193
+ const pcs = [...new Set(pitches.map(mod12))];
194
+ if (pcs.length < 3) return null;
195
+ const bass = mod12(Math.min(...pitches));
196
+ let best = null;
197
+ for (const r of pcs) {
198
+ const rel = new Set(pcs.map((p) => (p - r + 12) % 12));
199
+ CHORDS.forEach(([suffix, tpl], order) => {
200
+ if (!tpl.every((x) => rel.has(x))) return;
201
+ const cand = { name: `${PC_NAMES[r]}${suffix}`, size: tpl.length, bassRoot: r === bass ? 1 : 0, order };
202
+ if (!best || cand.size > best.size || (cand.size === best.size && (cand.bassRoot > best.bassRoot || (cand.bassRoot === best.bassRoot && cand.order < best.order)))) best = cand;
203
+ });
204
+ }
205
+ return best ? best.name : '?';
206
+ }
207
+
208
+ // The chord held longest in one cycle's pitched events, or null.
209
+ function chordOfCycle(list) {
210
+ if (list.length < 3) return null;
211
+ const points = [...new Set(list.map((x) => x.b))].sort((a, b) => a - b);
212
+ const ends = Math.max(...list.map((x) => x.e));
213
+ const weight = new Map();
214
+ points.forEach((t, i) => {
215
+ const active = list.filter((x) => x.b <= t && x.e > t);
216
+ if (new Set(active.map((x) => mod12(x.pitch))).size < 3) return;
217
+ const pitches = active.map((x) => x.pitch);
218
+ const name = nameChord(pitches);
219
+ const w = (points[i + 1] ?? ends) - t;
220
+ const cur = weight.get(name) ?? { w: 0, pitches };
221
+ cur.w += w;
222
+ weight.set(name, cur);
223
+ });
224
+ let best = null;
225
+ for (const [name, v] of weight) if (!best || v.w > best.w) best = { name, w: v.w, pitches: v.pitches };
226
+ if (!best) return null;
227
+ return { name: best.name, notes: [...new Set(best.pitches.map((p) => Math.round(p)))].sort((a, b) => a - b).map(midiToNoteName) };
228
+ }
229
+
230
+ // --- rhythm ---
231
+
232
+ const level = (k) => (k % 16 === 0 ? 0 : k % 8 === 0 ? 1 : k % 4 === 0 ? 2 : k % 2 === 0 ? 3 : 4);
233
+
234
+ // Share of onsets on weak 16th positions whose next stronger position is empty.
235
+ function syncopation(onsetSets) {
236
+ let total = 0, sync = 0;
237
+ onsetSets.forEach((set, c) => {
238
+ for (const k of set) {
239
+ total++;
240
+ const lv = level(k);
241
+ if (lv < 3) continue;
242
+ const j = lv === 4 ? k + 1 : k + 2;
243
+ const has = j >= 16 ? (onsetSets[c + 1] ?? onsetSets[0]).has(j - 16) : set.has(j);
244
+ if (!has) sync++;
245
+ }
246
+ });
247
+ return total ? round(sync / total) : null;
248
+ }
249
+
250
+ // Swing: mean in-beat position (4 beats a cycle) of onsets between the
251
+ // straight off-beat (0.5) and just past the triplet one (0.72); needs at
252
+ // least two such onsets per cycle, else a lone triplet would read as swing.
253
+ function swing(positions, cycles) {
254
+ const off = positions.map((p) => (p * 4) % 1).filter((p) => p >= 0.45 && p <= 0.72);
255
+ if (off.length < 4 || off.length < 2 * cycles) return null;
256
+ const ratio = off.reduce((a, b) => a + b, 0) / off.length;
257
+ return { ratio: round(ratio), amount: round(Math.max(0, Math.min(1, (ratio - 0.5) / (1 / 6)))) };
258
+ }
259
+
260
+ // --- per layer ---
261
+
262
+ function layerStats(L, cyc, cycles) {
263
+ const all = cyc.flat();
264
+ const pitched = all.filter((x) => x.pitch !== undefined);
265
+ const sounds = [...new Set(all.map((x) => x.s).filter(Boolean))].sort();
266
+ const banks = [...new Set(all.map((x) => x.bank).filter(Boolean))].sort();
267
+ const eventsPerCycle = all.length / cycles;
268
+ let pitch = null;
269
+ if (pitched.length) {
270
+ const lo = Math.round(Math.min(...pitched.map((x) => x.pitch)));
271
+ const hi = Math.round(Math.max(...pitched.map((x) => x.pitch)));
272
+ pitch = { low: lo, high: hi, lowNote: midiToNoteName(lo), highNote: midiToNoteName(hi) };
273
+ }
274
+ let polyphony = 0;
275
+ for (const list of cyc) for (const x of list) polyphony = Math.max(polyphony, list.filter((y) => y.b <= x.b && y.e > x.b).length);
276
+ let role;
277
+ if (all.length === 0) role = 'silent';
278
+ else if (pitched.length >= all.length / 2) {
279
+ const pcs = new Set(pitched.map((x) => mod12(x.pitch))).size;
280
+ role = polyphony >= 3 && pcs >= 3 ? 'chords' : pitch.high <= 52 ? 'bass' : 'lead';
281
+ } else if (banks.length || sounds.some((s) => DRUM_SOUND.test(s))) role = 'drums';
282
+ else if (sounds.length && sounds.every((s) => isSynth(s))) role = 'synth';
283
+ else role = 'samples';
284
+ const out = {
285
+ name: L.name, role,
286
+ eventsPerCycle: round(eventsPerCycle, 2), density: densityLabel(eventsPerCycle, 3, 8),
287
+ sounds, pitch,
288
+ activeCycles: cyc.map((list, c) => (list.length ? c : -1)).filter((c) => c >= 0),
289
+ avgGain: all.length ? round(all.reduce((a, x) => a + x.gain, 0) / all.length) : null,
290
+ polyphony,
291
+ };
292
+ if (banks.length) out.banks = banks;
293
+ return out;
294
+ }
295
+
296
+ // --- sections ---
297
+
298
+ function sectionsOf(energy, activeSets, soundSets) {
299
+ const out = [];
300
+ const peak = Math.max(...energy, 1e-9);
301
+ let start = 0;
302
+ const changed = (c) => {
303
+ if (Math.abs(energy[c] - energy[c - 1]) / peak > 0.3) return true;
304
+ if (activeSets[c] !== activeSets[c - 1]) return true;
305
+ const a = soundSets[c], b = soundSets[c - 1];
306
+ const union = new Set([...a, ...b]).size;
307
+ const inter = [...a].filter((x) => b.has(x)).length;
308
+ return union > 0 && inter / union < 0.5;
309
+ };
310
+ for (let c = 1; c <= energy.length; c++) {
311
+ if (c < energy.length && !changed(c)) continue;
312
+ const slice = energy.slice(start, c);
313
+ out.push({ from: start, to: c, energy: round(slice.reduce((a, b) => a + b, 0) / slice.length), sounds: [...soundSets[start]].sort() });
314
+ start = c;
315
+ }
316
+ return out;
317
+ }
318
+
319
+ // --- summary ---
320
+
321
+ function summarise(d) {
322
+ const parts = [];
323
+ if (d.key) parts.push(d.key.confidence >= 0.3 ? d.key.name : `maybe ${d.key.name}`);
324
+ else parts.push('no pitched notes');
325
+ parts.push(`~${Math.round(d.tempo.bpm)} bpm${d.tempo.set ? '' : ' (default tempo)'}`);
326
+ const n = d.layers.length;
327
+ parts.push(`${n} layer${n === 1 ? '' : 's'}`);
328
+ if (n) parts.push(d.layers.map((L) => `${L.role} ${L.density}`).join(', '));
329
+ if (d.chords.length) {
330
+ const seq = [];
331
+ for (const ch of d.chords) if (seq.at(-1) !== ch.name) seq.push(ch.name);
332
+ parts.push(`chords ${seq.slice(0, 4).join(' ')}${seq.length > 4 ? ' …' : ''}`);
333
+ }
334
+ parts.push(d.period.cycles ? `repeats every ${d.period.cycles} cycle${d.period.cycles === 1 ? '' : 's'}` : `no repeat within ${d.period.searched} cycles`);
335
+ if (d.rhythm.swing && d.rhythm.swing.amount >= 0.3) parts.push('swung');
336
+ if (d.rhythm.syncopation !== null && d.rhythm.syncopation >= 0.3) parts.push('syncopated');
337
+ if (d.sections.length > 1) parts.push(`${d.sections.length} sections`);
338
+ return parts.join(', ');
339
+ }
340
+
341
+ // --- entry point ---
342
+
343
+ // describe(codeOrPattern, {cycles = 16, budgetMs = 15}) -> Promise<Description>.
344
+ // `budgetMs` bounds only the extra cycles queried for period detection.
345
+ export async function describe(codeOrPattern, opts = {}) {
346
+ const t0 = performance.now();
347
+ const cycles = Math.max(1, Math.min(256, Math.floor(opts.cycles ?? DEFAULT_CYCLES)));
348
+ const errors = [];
349
+ let layers = [];
350
+ let cps = null;
351
+ try {
352
+ if (isPattern(codeOrPattern)) layers = [{ name: 'pattern', pattern: codeOrPattern }];
353
+ else {
354
+ const r = await layersFromCode(String(codeOrPattern ?? ''));
355
+ layers = r.layers;
356
+ cps = r.cps;
357
+ errors.push(...r.errors);
358
+ }
359
+ } catch (e) { errors.push(String(e?.message ?? e)); }
360
+ if (opts.cps !== undefined) cps = num(opts.cps, cps);
361
+
362
+ const { events, sigs, queried } = queryLayers(layers, cycles, opts.budgetMs ?? DEFAULT_BUDGET_MS, errors);
363
+ const period = { cycles: layers.length ? findPeriod(sigs) : null, searched: queried };
364
+
365
+ const stats = layers.map((L, i) => layerStats(L, events[i], cycles));
366
+ const tonalLayers = events.filter((_, i) => stats[i].role !== 'drums');
367
+
368
+ const hist = new Array(12).fill(0);
369
+ for (const cyc of tonalLayers) for (const list of cyc) for (const x of list) if (x.pitch !== undefined) hist[mod12(x.pitch)] += x.e - x.b;
370
+ const key = estimateKey(hist);
371
+
372
+ const chords = [];
373
+ const energy = [];
374
+ const activeSets = [];
375
+ const soundSets = [];
376
+ const positions = [];
377
+ const onsetSets = [];
378
+ for (let c = 0; c < cycles; c++) {
379
+ const pitchedNow = tonalLayers.flatMap((cyc) => cyc[c] ?? []).filter((x) => x.pitch !== undefined);
380
+ const ch = chordOfCycle(pitchedNow);
381
+ if (ch) chords.push({ cycle: c, ...ch });
382
+ let e = 0;
383
+ const sounds = new Set();
384
+ const active = [];
385
+ const grid = new Set();
386
+ events.forEach((cyc, i) => {
387
+ const list = cyc[c] ?? [];
388
+ if (list.length) active.push(i);
389
+ for (const x of list) {
390
+ e += x.gain;
391
+ sounds.add(x.s ?? (x.pitch !== undefined ? 'note' : 'event'));
392
+ const p = x.b - c;
393
+ positions.push(p);
394
+ const k = Math.round(p * 16);
395
+ if (Math.abs(p * 16 - k) < 0.1 && k < 16) grid.add(k);
396
+ }
397
+ });
398
+ energy.push(round(e));
399
+ activeSets.push(active.join(','));
400
+ soundSets.push(sounds);
401
+ onsetSets.push(grid);
402
+ }
403
+ const totalEvents = events.reduce((a, cyc) => a + cyc.reduce((b, l) => b + l.length, 0), 0);
404
+ const onsetsPerCycle = events.length
405
+ ? Array.from({ length: cycles }, (_, c) => new Set(events.flatMap((cyc) => (cyc[c] ?? []).map((x) => round(x.b, 6)))).size).reduce((a, b) => a + b, 0) / cycles
406
+ : 0;
407
+
408
+ const tempoCps = cps ?? 0.5;
409
+ const d = {
410
+ tempo: { cps: round(tempoCps, 4), cpm: round(tempoCps * 60, 2), bpm: round(tempoCps * 240, 1), set: cps !== null, beatsPerCycle: 4 },
411
+ cycles,
412
+ period,
413
+ layers: stats,
414
+ key,
415
+ chords,
416
+ energy,
417
+ sections: sectionsOf(energy, activeSets, soundSets),
418
+ rhythm: {
419
+ eventsPerCycle: round(totalEvents / cycles, 2),
420
+ onsetsPerCycle: round(onsetsPerCycle, 2),
421
+ density: densityLabel(onsetsPerCycle, 4, 12),
422
+ syncopation: syncopation(onsetSets),
423
+ swing: swing(positions, cycles),
424
+ },
425
+ };
426
+ d.summary = summarise(d);
427
+ if (errors.length) d.errors = errors;
428
+ d.ms = round(performance.now() - t0, 1);
429
+ return d;
430
+ }
431
+
432
+ // Names for user code (src/scope.js).
433
+ addScope({ describe });