@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
package/src/visuals.js ADDED
@@ -0,0 +1,216 @@
1
+ // Canvas 2D renderers for the draw methods (plan 5.2; spec/integration.md 11).
2
+ // Each renderer is render(ctx, { pattern, now, options, env, query }):
3
+ // ctx is a 2D context whose canvas is sized in device pixels, now the cycle
4
+ // position, env the audio layer's { pattern(), analyser(id) }, query the
5
+ // draw-time hap query of src/draw.js. Unknown options are ignored. The canvas
6
+ // was already cleared for this frame unless the painter keeps a trail.
7
+ import { noteToMidi } from './ops.js';
8
+
9
+ const dpr = () => globalThis.devicePixelRatio || 1;
10
+ const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
11
+ const finite = (x) => typeof x === 'number' && Number.isFinite(x);
12
+
13
+ // --- pianoroll / punchcard ---------------------------------------------------
14
+
15
+ const ROLL_DEFAULTS = {
16
+ cycles: 4, playhead: 0.5, vertical: false, labels: false, flipTime: false, flipValues: false,
17
+ overscan: 1, hideNegative: false, smear: false, fold: false, autorange: false,
18
+ active: '#FFCA28', inactive: '#7491D2', background: 'transparent', playheadColor: '#FFFFFF',
19
+ fill: true, fillActive: true, stroke: false, strokeActive: true,
20
+ hideInactive: false, colorizeInactive: true, fontFamily: 'monospace', minMidi: 10, maxMidi: 90,
21
+ };
22
+
23
+ // The row key of a value: a MIDI number for pitched values (note, freq, n
24
+ // without a sound), otherwise a name (s, s:n, or the plain string).
25
+ export function rollKey(v) {
26
+ if (finite(v)) return { key: v, label: String(v) };
27
+ if (typeof v === 'string') {
28
+ const m = noteToMidi(v);
29
+ return m === undefined ? { key: v, label: v } : { key: m, label: v };
30
+ }
31
+ if (!isObj(v)) return null;
32
+ if (v.note !== undefined) {
33
+ const m = finite(Number(v.note)) ? Number(v.note) : noteToMidi(String(v.note));
34
+ if (m !== undefined) return { key: m, label: String(v.note) };
35
+ }
36
+ if (finite(Number(v.freq)) && v.freq > 0) {
37
+ const m = 69 + 12 * Math.log2(Number(v.freq) / 440);
38
+ return { key: m, label: `${Math.round(v.freq)}Hz` };
39
+ }
40
+ if (v.s !== undefined) {
41
+ const name = v.n !== undefined ? `${v.s}:${v.n}` : String(v.s);
42
+ return { key: name, label: name };
43
+ }
44
+ if (finite(Number(v.n))) return { key: Number(v.n), label: String(v.n) };
45
+ return null;
46
+ }
47
+
48
+ const compareKeys = (a, b) => (typeof a === typeof b
49
+ ? (typeof a === 'number' ? a - b : String(a).localeCompare(String(b)))
50
+ : (typeof a === 'number' ? -1 : 1));
51
+
52
+ // Row layout: folded (one row per distinct key, also whenever a name occurs)
53
+ // or a MIDI range (minMidi..maxMidi widened to the keys; autorange: the keys).
54
+ export function rollRows(keys, o) {
55
+ const folded = o.fold || keys.some((k) => typeof k !== 'number');
56
+ if (folded) {
57
+ const distinct = [...new Set(keys)].sort(compareKeys);
58
+ const index = new Map(distinct.map((k, i) => [k, i]));
59
+ return { count: Math.max(1, distinct.length), row: (k) => index.get(k) };
60
+ }
61
+ let lo = o.autorange && keys.length ? Infinity : Number(o.minMidi);
62
+ let hi = o.autorange && keys.length ? -Infinity : Number(o.maxMidi);
63
+ for (const k of keys) { lo = Math.min(lo, Math.floor(k)); hi = Math.max(hi, Math.ceil(k)); }
64
+ return { count: Math.max(1, hi - lo + 1), row: (k) => k - lo };
65
+ }
66
+
67
+ function pianoroll(ctx, { pattern, now, options, query }, defaults = ROLL_DEFAULTS) {
68
+ const o = { ...defaults, ...options };
69
+ const cycles = Math.max(1e-6, Number(o.cycles) || 4);
70
+ const playhead = Math.min(1, Math.max(0, Number(o.playhead)));
71
+ const W = ctx.canvas.width;
72
+ const H = ctx.canvas.height;
73
+ const r = dpr();
74
+ const lookbehind = cycles * playhead;
75
+ const from = now - lookbehind;
76
+ let events = query(pattern, now, { lookbehind, lookahead: cycles - lookbehind, overscan: Number(o.overscan) || 1 });
77
+ if (o.hideNegative) events = events.filter((e) => e.end > now);
78
+ if (o.hideInactive) events = events.filter((e) => e.active);
79
+ const keyed = [];
80
+ for (const e of events) {
81
+ const k = rollKey(e.value);
82
+ if (k) keyed.push({ ...e, ...k });
83
+ }
84
+ const rows = rollRows(keyed.map((e) => e.key), o);
85
+ const timeLen = o.vertical ? H : W;
86
+ const valueLen = o.vertical ? W : H;
87
+ const rowSize = valueLen / rows.count;
88
+ const timePos = (t) => {
89
+ const p = (t - from) / cycles;
90
+ return (o.flipTime ? 1 - p : p) * timeLen;
91
+ };
92
+
93
+ if (o.background && o.background !== 'transparent') {
94
+ ctx.fillStyle = o.background;
95
+ ctx.fillRect(0, 0, W, H);
96
+ }
97
+ ctx.lineWidth = r;
98
+ for (const e of keyed) {
99
+ const row = rows.row(e.key);
100
+ // Higher values sit at the top (horizontal) or right (vertical) unless flipValues.
101
+ const up = o.vertical ? !o.flipValues : o.flipValues;
102
+ const v0 = up ? row * rowSize : valueLen - (row + 1) * rowSize;
103
+ const a = timePos(e.begin);
104
+ const b = timePos(e.end);
105
+ const t0 = Math.min(a, b);
106
+ const len = Math.max(r, Math.abs(b - a) - r);
107
+ const [x, y, w, h] = o.vertical ? [v0, t0, rowSize - r, len] : [t0, v0, len, rowSize - r];
108
+ const own = isObj(e.value) && typeof e.value.color === 'string' ? e.value.color : null;
109
+ const color = e.active ? (own ?? o.active) : (o.colorizeInactive && own ? own : o.inactive);
110
+ if (e.active ? o.fillActive : o.fill) { ctx.fillStyle = color; ctx.fillRect(x, y, w, h); }
111
+ if (e.active ? o.strokeActive : o.stroke) { ctx.strokeStyle = color; ctx.strokeRect(x, y, w, h); }
112
+ if (o.labels && rowSize >= 6 * r) {
113
+ ctx.fillStyle = e.active && o.fillActive ? (o.background !== 'transparent' ? o.background : '#000000') : color;
114
+ ctx.font = `${Math.round(Math.min(rowSize, 24 * r) * 0.75)}px ${o.fontFamily}`;
115
+ ctx.fillText(e.label, x + 2 * r, y + Math.min(h, rowSize) * 0.8);
116
+ }
117
+ }
118
+ if (o.playheadColor) {
119
+ const p = timePos(now);
120
+ ctx.strokeStyle = o.playheadColor;
121
+ ctx.beginPath();
122
+ if (o.vertical) { ctx.moveTo(0, p); ctx.lineTo(W, p); } else { ctx.moveTo(p, 0); ctx.lineTo(p, H); }
123
+ ctx.stroke();
124
+ }
125
+ }
126
+
127
+ // punchcard: a pianoroll with one row per distinct value.
128
+ const punchcard = (ctx, args) => pianoroll(ctx, args, { ...ROLL_DEFAULTS, fold: true });
129
+
130
+ // --- analyser views -------------------------------------------------------------
131
+
132
+ // The analyser a scope or spectrum reads: options.analyser, else the
133
+ // `analyze` id on the playing pattern's current haps (SAAI's 'viz'), else the
134
+ // one on the painted pattern, else env.analyser(undefined): the audio layer's
135
+ // tap on the whole mix.
136
+ const analyserIds = new WeakMap();
137
+ function analyzeIdOf(pattern, now) {
138
+ if (!pattern?.queryArc) return undefined;
139
+ if (analyserIds.has(pattern)) return analyserIds.get(pattern);
140
+ const c = Math.floor(now);
141
+ for (const h of pattern.queryArc(c, c + 1)) {
142
+ if (isObj(h.value) && h.value.analyze !== undefined) {
143
+ analyserIds.set(pattern, h.value.analyze);
144
+ return h.value.analyze;
145
+ }
146
+ }
147
+ return undefined;
148
+ }
149
+ export function pickAnalyser({ pattern, now, options, env }) {
150
+ const id = options.analyser ?? analyzeIdOf(env.pattern?.(), now) ?? analyzeIdOf(pattern, now);
151
+ return env.analyser?.(id) ?? null;
152
+ }
153
+
154
+ const SCOPE_DEFAULTS = { align: true, color: '#FFFFFF', thickness: 3, scale: 0.25, pos: 0.75, trigger: 0 };
155
+
156
+ function scope(ctx, args) {
157
+ const o = { ...SCOPE_DEFAULTS, ...args.options };
158
+ const analyser = pickAnalyser(args);
159
+ if (!analyser?.getFloatTimeDomainData) return;
160
+ const n = analyser.fftSize || (analyser.frequencyBinCount || 1024) * 2;
161
+ const data = new Float32Array(n);
162
+ analyser.getFloatTimeDomainData(data);
163
+ const W = ctx.canvas.width;
164
+ const H = ctx.canvas.height;
165
+ // align: start at the first upward crossing of `trigger` in the first half,
166
+ // so a steady tone stands still.
167
+ let start = 0;
168
+ if (o.align) {
169
+ for (let i = 1; i < n / 2; i++) if (data[i - 1] < o.trigger && data[i] >= o.trigger) { start = i; break; }
170
+ }
171
+ const count = Math.max(2, Math.floor(n / 2));
172
+ ctx.strokeStyle = o.color;
173
+ ctx.lineWidth = Number(o.thickness) * dpr();
174
+ ctx.beginPath();
175
+ for (let i = 0; i < count; i++) {
176
+ const x = (i / (count - 1)) * W;
177
+ const y = (o.pos - (data[start + i] ?? 0) * o.scale) * H;
178
+ if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
179
+ }
180
+ ctx.stroke();
181
+ }
182
+
183
+ const SPECTRUM_DEFAULTS = { thickness: 3, speed: 1, min: -80, max: 0, color: '#FFFFFF' };
184
+
185
+ // A scrolling waterfall: the picture moves `speed` px left per frame and the
186
+ // newest column is drawn on the right, one line per bin on a log frequency
187
+ // axis, its opacity the level between min and max dB.
188
+ function spectrum(ctx, args) {
189
+ const o = { ...SPECTRUM_DEFAULTS, ...args.options };
190
+ const analyser = pickAnalyser(args);
191
+ if (!analyser?.getFloatFrequencyData) return;
192
+ const n = analyser.frequencyBinCount || 1024;
193
+ const data = new Float32Array(n);
194
+ analyser.getFloatFrequencyData(data);
195
+ const W = ctx.canvas.width;
196
+ const H = ctx.canvas.height;
197
+ const r = dpr();
198
+ const speed = Math.max(1, Math.round(Number(o.speed) * r));
199
+ const thick = Math.max(1, Number(o.thickness) * r);
200
+ ctx.drawImage(ctx.canvas, -speed, 0);
201
+ ctx.clearRect(W - speed, 0, speed, H);
202
+ ctx.fillStyle = o.color;
203
+ const span = o.max - o.min || 1;
204
+ const logN = Math.log(n);
205
+ for (let i = 0; i < n; i++) {
206
+ const level = Math.min(1, Math.max(0, (data[i] - o.min) / span));
207
+ if (!(level > 0)) continue;
208
+ ctx.globalAlpha = level;
209
+ const y = H - (Math.log(i + 1) / logN) * H;
210
+ ctx.fillRect(W - speed, y - thick / 2, speed, thick);
211
+ }
212
+ ctx.globalAlpha = 1;
213
+ }
214
+
215
+ // Draw methods with a renderer. `spiral` has none yet: it stays a pass-through.
216
+ export const RENDERERS = { pianoroll, punchcard, scope, tscope: scope, spectrum };