@zeeuw/riff 0.0.0-stage → 0.1.0-beta.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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +195 -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/random.js ADDED
@@ -0,0 +1,344 @@
1
+ // The random family (plan 2.3, spec/random.md): one pure random source r(t)
2
+ // plus rand, irand, perlin, choose, the degrade / sometimes / someCycles
3
+ // families, chooseCycles, shuffle and scramble. RIFF's own generator: same
4
+ // distributions and sharing rules as the spec, different sequences.
5
+ import { Fraction, fraction } from './fraction.js';
6
+ import { TimeSpan } from './time.js';
7
+ import { Hap } from './hap.js';
8
+ import { Pattern, reify, silence } from './pattern.js';
9
+ import { register, registerFree } from './register.js';
10
+ import { stack } from './constructors.js';
11
+ import { continuous } from './signals.js';
12
+ import { frac, wholeCount as count } from './util.js';
13
+
14
+ // --- the source -----------------------------------------------------------
15
+ // r(t, seed): a 32-bit hash (multiply-rotate rounds over both words of t as a
16
+ // double, then a final avalanche) of the time and the seed. No period, no
17
+ // fixed value at t = 0 (docs/decisions.md, "Random source").
18
+ const view = new DataView(new ArrayBuffer(8));
19
+ const rotl = (x, r) => (x << r) | (x >>> (32 - r));
20
+ const round = (h, w) => {
21
+ let k = Math.imul(w, 0xcc9e2d51);
22
+ k = Math.imul(rotl(k, 15), 0x1b873593);
23
+ h = rotl(h ^ k, 13);
24
+ return (Math.imul(h, 5) + 0xe6546b64) | 0;
25
+ };
26
+ const avalanche = (h) => {
27
+ h = Math.imul(h ^ (h >>> 16), 0x85ebca6b);
28
+ h = Math.imul(h ^ (h >>> 13), 0xc2b2ae35);
29
+ return (h ^ (h >>> 16)) >>> 0;
30
+ };
31
+
32
+ export function randAt(t, seed = 0) {
33
+ const x = typeof t === 'number' ? t : t.toNumber();
34
+ view.setFloat64(0, x === 0 ? 0 : x); // -0 and 0 are the same time
35
+ let h = round(round(seed ^ 0x2545f491, view.getUint32(4)), view.getUint32(0));
36
+ if (salt !== 0) h = round(h, salt); // plan 8.9: only when a seed is set
37
+ return avalanche(h ^ 8) / 4294967296;
38
+ }
39
+
40
+ // --- seeds and random mode (plan 8.9, RIFF extension) ----------------------
41
+ // The draw is shifted by a salt derived from the global seed (setSeed) and
42
+ // the seed scope in force while a pattern is queried (.seed(n), or the layer
43
+ // id in 'riff' mode). Salt 0 = no shift, so the default stream is unchanged.
44
+ // Queries are synchronous, so the scope is a dynamic variable set around the
45
+ // inner query and restored after it (docs/decisions.md, "Seeds").
46
+ let salt = 0;
47
+ let globalSeed = 0;
48
+ let scopeSeed = 0;
49
+ let mode = 'default';
50
+
51
+ // A seed is an int32: integers as they are, anything else (fractions,
52
+ // strings, layer labels) through FNV-1a over its string form.
53
+ export function toSeed(n) {
54
+ if (typeof n === 'number' && Number.isInteger(n) && Math.abs(n) <= 0x7fffffff) return n | 0;
55
+ const str = String(n);
56
+ let h = 0x811c9dc5;
57
+ for (let i = 0; i < str.length; i++) h = Math.imul(h ^ str.charCodeAt(i), 0x01000193);
58
+ return h | 0;
59
+ }
60
+
61
+ const resalt = () => {
62
+ salt = globalSeed === 0 && scopeSeed === 0 ? 0 : (avalanche(round(round(0x3c6ef372, globalSeed), scopeSeed)) | 0) || 1;
63
+ };
64
+
65
+ export function setSeed(n = 0) { globalSeed = toSeed(n); resalt(); return globalSeed; }
66
+ export const getSeed = () => globalSeed;
67
+
68
+ const MODES = { default: 'default', strudel: 'default', riff: 'riff' };
69
+ export function setRandomMode(m = 'default') {
70
+ const next = MODES[m];
71
+ if (!next) throw new TypeError(`setRandomMode: unknown mode ${JSON.stringify(m)} (use 'default' or 'riff')`);
72
+ mode = next;
73
+ return mode;
74
+ }
75
+ export const getRandomMode = () => mode;
76
+
77
+ // Query pat with seed scope s (replaces an outer scope) while active().
78
+ function scoped(pat, s, active = () => true) {
79
+ return new Pattern((state) => {
80
+ if (!active()) return pat.query(state);
81
+ const prev = scopeSeed;
82
+ scopeSeed = s;
83
+ resalt();
84
+ try { return pat.query(state); } finally { scopeSeed = prev; resalt(); }
85
+ }, pat._steps);
86
+ }
87
+
88
+ // pat.seed(n): its own reproducible random stream; seed(0) = the default one.
89
+ export const seed = register('seed', (pat, n) => scoped(pat, toSeed(n)), { patternArgs: 0 });
90
+ // A `$:` / named layer: in 'riff' mode its stream is hashed from the layer id,
91
+ // so layers no longer drop or choose on the same steps. Default mode: as is.
92
+ export const seedLayer = (pat, id) => scoped(pat, toSeed(`layer:${id}`), () => mode === 'riff');
93
+
94
+ // The draw for a hap: at its whole begin (part begin when analog), rule 5.
95
+ const hapDraw = (h, seed) => randAt(h.wholeOrPart().begin, seed);
96
+
97
+ // --- continuous random signals ------------------------------------------
98
+ export const randWith = (seed) => continuous((t) => randAt(t, seed));
99
+ export const rand = randWith(0);
100
+ export const rand2 = continuous((t) => randAt(t) * 2 - 1);
101
+ export const brand = continuous((t) => randAt(t) < 0.5);
102
+
103
+ const perlinAt = (t) => {
104
+ const i = t.floor();
105
+ const x = t.sub(i).toNumber();
106
+ const a = randAt(i);
107
+ const b = randAt(i.add(1));
108
+ return a + (b - a) * x * x * x * (x * (x * 6 - 15) + 10);
109
+ };
110
+ export const perlin = continuous(perlinAt);
111
+ // perlinWith(pat): perlin noise read at the pattern's values instead of time.
112
+ export const perlinWith = (pat) => reify(pat).fmap((v) => perlinAt(fraction(Number(v))));
113
+
114
+ // Constant-argument path when possible, else inner join over the argument.
115
+ const patternable = (arg, make) => (typeof arg === 'number' ? make(arg) : reify(arg).fmap(make).innerJoin());
116
+
117
+ export const irand = (n) => patternable(n, (k) => continuous((t) => Math.floor(randAt(t) * k)));
118
+ export const brandBy = (p) => patternable(p, (q) => continuous((t) => randAt(t) < q));
119
+
120
+ // --- choices --------------------------------------------------------------
121
+ const pick = (items, r) => items[Math.min(items.length - 1, Math.floor(r * items.length))];
122
+
123
+ // Index of the first cumulative weight above r * W (spec/random.md 2.2).
124
+ function weightedIndex(weights, r) {
125
+ const total = weights.reduce((s, w) => s + w, 0);
126
+ const target = r * total;
127
+ let acc = 0;
128
+ for (let i = 0; i < weights.length; i++) {
129
+ acc += weights[i];
130
+ if (target < acc) return i;
131
+ }
132
+ return weights.length - 1;
133
+ }
134
+
135
+ // In a program, "bd" arrives as a mini pattern: a picked pattern gives the
136
+ // value of its hap at the sample point (saai/jazz-template-01, functions/choose).
137
+ function sampleChosen(pat) {
138
+ return new Pattern((state) => {
139
+ const out = [];
140
+ for (const h of pat.query(state)) {
141
+ if (!(h.value instanceof Pattern)) { out.push(h); continue; }
142
+ const inner = h.value.query(state.setSpan(h.part));
143
+ if (inner.length) out.push(h.withValue(() => inner[0].value));
144
+ }
145
+ return out;
146
+ });
147
+ }
148
+
149
+ export function choose(...items) {
150
+ if (items.length === 0) return silence;
151
+ const pat = continuous((t) => pick(items, randAt(t)));
152
+ return items.some((x) => x instanceof Pattern) ? sampleChosen(pat) : pat;
153
+ }
154
+ export const chooseOut = choose;
155
+
156
+ export function wchoose(...pairs) {
157
+ if (pairs.length === 0) return silence;
158
+ const weights = pairs.map((p) => Number(p[1]));
159
+ const pat = continuous((t) => pairs[weightedIndex(weights, randAt(t))][0]);
160
+ return pairs.some((p) => p[0] instanceof Pattern) ? sampleChosen(pat) : pat;
161
+ }
162
+
163
+ // chooseWith(pat, items): items picked by the pattern's values in [0, 1).
164
+ export const chooseWith = (pat, items) => reify(pat).fmap((v) => pick(items, Math.max(0, Number(v))));
165
+
166
+ // One pattern per cycle, chosen from r(c, seed), queried at the global time.
167
+ function perCycle(pats, chooseIndex) {
168
+ return new Pattern((state) => {
169
+ const out = [];
170
+ for (const span of state.span.spanCycles()) {
171
+ const p = pats[chooseIndex(span.begin.sam())];
172
+ for (const h of p.query(state.setSpan(span))) out.push(h);
173
+ }
174
+ return out;
175
+ });
176
+ }
177
+
178
+ export function chooseCyclesWith(seed, ...items) {
179
+ const pats = items.map(reify);
180
+ if (pats.length === 0) return silence;
181
+ if (pats.length === 1) return pats[0];
182
+ return perCycle(pats, (c) => Math.min(pats.length - 1, Math.floor(randAt(c, seed) * pats.length)));
183
+ }
184
+ export const chooseCycles = (...items) => chooseCyclesWith(0, ...items);
185
+ export const randcat = chooseCycles;
186
+
187
+ export function wchooseCycles(...pairs) {
188
+ if (pairs.length === 0) return silence;
189
+ const pats = pairs.map((p) => reify(p[0]));
190
+ const weights = pairs.map((p) => Number(p[1]));
191
+ return perCycle(pats, (c) => weightedIndex(weights, randAt(c)));
192
+ }
193
+ export const wrandcat = wchooseCycles;
194
+
195
+ // --- degrade --------------------------------------------------------------
196
+ // Seeded forms are for the mini-notation `?` (spec/random.md 3).
197
+ export const degradeBySeed = (pat, p, seed = 0) => pat.filterHaps((h) => hapDraw(h, seed) > p);
198
+ export const undegradeBySeed = (pat, p, seed = 0) => pat.filterHaps((h) => hapDraw(h, seed) < 1 - p);
199
+
200
+ export const degradeBy = register('degradeBy', (pat, p) => degradeBySeed(pat, Number(p)));
201
+ export const undegradeBy = register('undegradeBy', (pat, p) => undegradeBySeed(pat, Number(p)));
202
+ export const degrade = register('degrade', (pat) => degradeBySeed(pat, 0.5));
203
+ export const undegrade = register('undegrade', (pat) => undegradeBySeed(pat, 0.5));
204
+
205
+ // degradeByWith(withPat, p): like degradeBy, drawing from withPat sampled
206
+ // over each hap (a continuous withPat gives its value at the whole begin).
207
+ export const degradeByWith = register('degradeByWith', (pat, withPat, p) =>
208
+ pat.fmap((v) => (x) => ({ v, x })).appLeft(reify(withPat)).filterValues((o) => o.x > p).fmap((o) => o.v),
209
+ { patternArgs: 0 });
210
+
211
+ // --- sometimes ------------------------------------------------------------
212
+ // stack(untouched where r > p, f(haps where r < p)); r == p drops from both.
213
+ export const sometimesBy = register('sometimesBy', (pat, p, f) => {
214
+ p = Number(p);
215
+ const untouched = pat.filterHaps((h) => hapDraw(h, 0) > p);
216
+ const chosen = pat.filterHaps((h) => hapDraw(h, 0) < p);
217
+ return stack(untouched, f(chosen));
218
+ }, { patternArgs: 1 });
219
+
220
+ const fixedBy = { sometimes: 0.5, often: 0.75, rarely: 0.25, almostNever: 0.1, almostAlways: 0.9 };
221
+ export const sometimes = register('sometimes', (pat, f) => sometimesBy(0.5, f, pat), { patternArgs: 0 });
222
+ export const often = register('often', (pat, f) => sometimesBy(fixedBy.often, f, pat), { patternArgs: 0 });
223
+ export const rarely = register('rarely', (pat, f) => sometimesBy(fixedBy.rarely, f, pat), { patternArgs: 0 });
224
+ export const almostNever = register('almostNever', (pat, f) => sometimesBy(fixedBy.almostNever, f, pat), { patternArgs: 0 });
225
+ export const almostAlways = register('almostAlways', (pat, f) => sometimesBy(fixedBy.almostAlways, f, pat), { patternArgs: 0 });
226
+ export const always = register('always', (pat, f) => f(pat), { patternArgs: 0 });
227
+ export const never = register('never', (pat) => pat, { patternArgs: 0 });
228
+
229
+ // Per cycle c: the whole cycle is f(pat) iff r(c) < p.
230
+ export const someCyclesBy = register('someCyclesBy', (pat, p, f) => {
231
+ p = Number(p);
232
+ const changed = f(pat);
233
+ return new Pattern((state) => {
234
+ const out = [];
235
+ for (const span of state.span.spanCycles()) {
236
+ const src = randAt(span.begin.sam()) < p ? changed : pat;
237
+ for (const h of src.query(state.setSpan(span))) out.push(h);
238
+ }
239
+ return out;
240
+ }, pat._steps);
241
+ }, { patternArgs: 1 });
242
+ export const someCycles = register('someCycles', (pat, f) => someCyclesBy(0.5, f, pat), { patternArgs: 0 });
243
+
244
+ // --- shuffle / scramble -----------------------------------------------------
245
+ // Slot k of cycle c plays slice choice(c, k) of the same cycle; haps are cut
246
+ // to their slot (whole and part).
247
+ function slices(pat, n, choice) {
248
+ n = Math.floor(Number(n));
249
+ if (!(n >= 1)) return silence;
250
+ const N = BigInt(n);
251
+ return new Pattern((state) => {
252
+ const out = [];
253
+ for (const span of state.span.spanCycles()) {
254
+ const c = span.begin.sam();
255
+ const picks = choice(c, n);
256
+ for (let k = 0; k < n; k++) {
257
+ const slot = new TimeSpan(c.add(new Fraction(BigInt(k), N)), c.add(new Fraction(BigInt(k + 1), N)));
258
+ const q = span.intersect(slot);
259
+ if (!q) continue;
260
+ const shift = new Fraction(BigInt(k - picks[k]), N);
261
+ const back = (t) => t.sub(shift);
262
+ for (const h of pat.query(state.setSpan(q.withTime(back)))) {
263
+ const moved = h.withTime((t) => t.add(shift));
264
+ const part = moved.part.intersect(slot);
265
+ const whole = moved.whole && moved.whole.intersect(slot);
266
+ if (part && (whole || !moved.whole)) out.push(new Hap(whole, part, h.value, h.context));
267
+ }
268
+ }
269
+ }
270
+ return out;
271
+ }, n);
272
+ }
273
+
274
+ // Fisher-Yates with one draw per slot, taken at the slot begins.
275
+ const permutation = (c, n) => {
276
+ const idx = Array.from({ length: n }, (_, i) => i);
277
+ for (let k = 0; k < n - 1; k++) {
278
+ const j = k + Math.floor(randAt(c.add(new Fraction(BigInt(k), BigInt(n)))) * (n - k));
279
+ [idx[k], idx[j]] = [idx[j], idx[k]];
280
+ }
281
+ return idx;
282
+ };
283
+ const withReplacement = (c, n) => Array.from({ length: n }, (_, k) =>
284
+ Math.min(n - 1, Math.floor(randAt(c.add(new Fraction(BigInt(k), BigInt(n)))) * n)));
285
+
286
+ export const shuffle = register('shuffle', (pat, n) => slices(pat, n, permutation));
287
+ export const scramble = register('scramble', (pat, n) => slices(pat, n, withReplacement));
288
+
289
+ const free = { rand, rand2, brand, perlin, perlinWith, irand, brandBy, choose, chooseOut, wchoose, chooseWith, chooseCycles, randcat, wchooseCycles, wrandcat };
290
+ for (const [name, f] of Object.entries(free)) registerFree(name, f);
291
+
292
+ // --- moved here from the Tier 2/3 batch modules (audit 6) ---------------------
293
+
294
+ // --- randrun (spec/functions/randrun.md) ------------------------------------------
295
+ // Each cycle a Fisher-Yates permutation of 0 … n-1, one draw per slot begin.
296
+ export function randrun(n) {
297
+ if (n instanceof Pattern || typeof n === 'string' || !Number.isFinite(Number(n))) throw new Error('randrun: Invalid argument');
298
+ const k = count(n);
299
+ if (k === 0) return silence;
300
+ return new Pattern((state) => {
301
+ const out = [];
302
+ for (const span of state.span.spanCycles()) {
303
+ const c = span.begin.sam();
304
+ const idx = Array.from({ length: k }, (_, i) => i);
305
+ for (let i = 0; i < k - 1; i++) {
306
+ const j = i + Math.floor(randAt(c.add(frac(i, k))) * (k - i));
307
+ [idx[i], idx[j]] = [idx[j], idx[i]];
308
+ }
309
+ for (let i = 0; i < k; i++) {
310
+ const whole = new TimeSpan(c.add(frac(i, k)), c.add(frac(i + 1, k)));
311
+ const part = span.clip(whole);
312
+ if (part) out.push(new Hap(whole, part, idx[i]));
313
+ }
314
+ }
315
+ return out;
316
+ }, k);
317
+ }
318
+ registerFree('randrun', randrun);
319
+
320
+ // --- berlin, berlinWith (spec/functions/berlin.md) ---------------------------------
321
+ // A ramp per cycle: r(n) + frac(t) · r(n + 1), r(0) = 0, r(n) in [0, 0.5).
322
+ const berlinR = (n) => (n === 0 ? 0 : randAt(fraction(n)) / 2);
323
+ const berlinAt = (t) => {
324
+ const n = Math.floor(t);
325
+ return berlinR(n) + (t - n) * berlinR(n + 1);
326
+ };
327
+ export const berlin = continuous((t) => berlinAt(t.toNumber()));
328
+ export const berlinWith = (pat) => reify(pat).fmap((v) => berlinAt(Number(v)));
329
+ registerFree('berlin', berlin);
330
+ registerFree('berlinWith', berlinWith);
331
+
332
+ // --- chooseIn, chooseInWith (spec/functions/chooseIn.md) ---------------------------
333
+ // The chosen element is inner-joined: its own structure, not the selector's.
334
+ export function chooseInWith(sel, xs) {
335
+ const items = (Array.isArray(xs) ? xs : [xs]).map(reify);
336
+ if (items.length === 0) return silence;
337
+ return reify(sel).fmap((v) => {
338
+ const i = Math.min(items.length - 1, Math.max(0, Math.floor(Number(v) * items.length)));
339
+ return Number.isNaN(i) ? silence : items[i];
340
+ }).innerJoin();
341
+ }
342
+ export const chooseIn = (...xs) => chooseInWith(rand, xs);
343
+ registerFree('chooseInWith', chooseInWith);
344
+ registerFree('chooseIn', chooseIn);
@@ -0,0 +1,83 @@
1
+ // Registration helper: one call adds a Pattern method and a matching free
2
+ // function (pattern last), with patterned arguments handled by inner join
3
+ // (spec/functions/README.md). Later modules (signals, operators, controls,
4
+ // Tier 1 functions) add names here without touching the core.
5
+ import { Pattern, reify } from './pattern.js';
6
+
7
+ // name -> free function, the scope the evaluator exposes (Epic 3).
8
+ export const registry = new Map();
9
+
10
+ const isPatternArg = (a) => a instanceof Pattern || typeof a === 'string';
11
+
12
+ // Apply impl(pat, ...args) with the first `patternArgs` args patternable.
13
+ export function applyPatterned(impl, pat, args, patternArgs = args.length, memo = false) {
14
+ const n = Math.min(patternArgs, args.length);
15
+ let patterned = false;
16
+ for (let i = 0; i < n; i++) if (isPatternArg(args[i])) { patterned = true; break; }
17
+ if (!patterned) return impl(pat, ...args);
18
+ const rest = args.slice(n);
19
+ if (memo && n === 1) {
20
+ // One patterned argument and a pure impl: the inner pattern for a given
21
+ // number or string is built once, not on every query (plan 8.7).
22
+ const built = new Map();
23
+ return reify(args[0]).fmap((v) => {
24
+ if (typeof v !== 'number' && typeof v !== 'string') return impl(pat, v, ...rest);
25
+ let p = built.get(v);
26
+ if (p === undefined) {
27
+ if (built.size >= 64) built.clear();
28
+ p = impl(pat, v, ...rest);
29
+ built.set(v, p);
30
+ }
31
+ return p;
32
+ }).innerJoin();
33
+ }
34
+ let argPat = reify(args[0]).fmap((v) => [v]);
35
+ for (let i = 1; i < n; i++) argPat = argPat.fmap((vs) => (v) => [...vs, v]).appLeft(reify(args[i]));
36
+ return argPat.fmap((vs) => impl(pat, ...vs, ...rest)).innerJoin();
37
+ }
38
+
39
+ // register(name, impl, options) -> the free function.
40
+ // impl(pat, ...args): the constant-argument implementation.
41
+ // patternArgs: how many leading args are patternable (default: all; 0 = none).
42
+ // method / free: install a Pattern method / record a free function.
43
+ // aliases: extra names for both.
44
+ // memo: impl is pure (same arguments, same pattern), so with one patterned
45
+ // argument its result is cached per plain value.
46
+ // curry: the number of arguments before the pattern; a free call with
47
+ // exactly that many returns a pattern -> pattern function, so
48
+ // `chunk(4, hurry(2))` works (Tier 2; opt-in per name).
49
+ export function register(name, impl, { patternArgs = Infinity, method = true, free = true, aliases = [], memo = false, curry } = {}) {
50
+ const run = (pat, args) => applyPatterned(impl, pat, args, patternArgs, memo);
51
+ const fn = (...args) => (args.length === curry
52
+ ? (pat) => run(reify(pat), args)
53
+ : run(reify(args[args.length - 1]), args.slice(0, -1)));
54
+ for (const n of [name, ...aliases]) {
55
+ if (method) {
56
+ Object.defineProperty(Pattern.prototype, n, {
57
+ value: function (...args) { return run(this, args); },
58
+ writable: true, configurable: true,
59
+ });
60
+ }
61
+ if (free) registry.set(n, fn);
62
+ }
63
+ return fn;
64
+ }
65
+
66
+ // Record a free function that is not pattern-last (stack, cat, pure ...).
67
+ export function registerFree(name, fn, aliases = []) {
68
+ for (const n of [name, ...aliases]) registry.set(n, fn);
69
+ return fn;
70
+ }
71
+
72
+ // alias(name, target): `name` is the target's own function, as a method and
73
+ // in the registry (spec/functions/tier3-aliases.md): same signature, same
74
+ // errors. Returns the registry function (undefined when there is none).
75
+ export function alias(name, target) {
76
+ const method = Pattern.prototype[target];
77
+ if (typeof method === 'function') {
78
+ Object.defineProperty(Pattern.prototype, name, { value: method, writable: true, configurable: true });
79
+ }
80
+ const fn = registry.get(target);
81
+ if (fn) registry.set(name, fn);
82
+ return fn;
83
+ }
@@ -0,0 +1,52 @@
1
+ // Plan 8.6 (RIFF extension): the function registry at runtime. The data is
2
+ // data/registry-data.js (about 300 KB, outside src/: generated data, not
3
+ // engine code), generated with registry.json by tools/registry/build.mjs.
4
+ // Plan 8.12: it is loaded lazily with a dynamic import on the first call, so
5
+ // hosts that never ask for it never download it. It is optional: a copy of
6
+ // src/ without data/ (SAAI's vendored copy) works, and only these two
7
+ // functions reject. Both functions are therefore async.
8
+ let dataP = null;
9
+ let index = null;
10
+ const DATA_URL = new URL('../data/registry-data.js', import.meta.url).href;
11
+ const load = () => (dataP ??= import(DATA_URL).then((m) => m.default, (e) => {
12
+ dataP = null;
13
+ throw new Error(`RIFF registry data is not available (data/registry-data.js, optional): ${e?.message ?? e}`);
14
+ }));
15
+
16
+ async function byName() {
17
+ if (index) return index;
18
+ const data = await load();
19
+ const map = new Map();
20
+ for (const e of data.functions) map.set(e.name, e);
21
+ // Aliases resolve to their entry unless they have one of their own.
22
+ for (const e of data.functions) for (const a of e.aliases) if (!map.has(a)) map.set(a, e);
23
+ index = map;
24
+ return index;
25
+ }
26
+
27
+ const copy = (e) => JSON.parse(JSON.stringify(e));
28
+
29
+ // describeFunction(name) → Promise<registry entry (a copy) | null> for a name or alias.
30
+ export async function describeFunction(name) {
31
+ const e = (await byName()).get(String(name));
32
+ return e ? copy(e) : null;
33
+ }
34
+
35
+ // listFunctions(filter) → Promise<entries (copies)>. filter: a predicate, or
36
+ // an object whose keys are matched: kind (also matches any of `kinds`), area,
37
+ // tier, extension, implemented, search (substring of name, alias or description).
38
+ export async function listFunctions(filter = {}) {
39
+ const data = await load();
40
+ let test = filter;
41
+ if (typeof filter !== 'function') {
42
+ const f = filter ?? {};
43
+ const q = f.search != null ? String(f.search).toLowerCase() : null;
44
+ test = (e) => (f.kind == null || e.kind === f.kind || (e.kinds ?? []).includes(f.kind)) &&
45
+ (f.area == null || e.area === f.area) &&
46
+ (f.tier == null || e.tier === f.tier) &&
47
+ (f.extension == null || e.extension === f.extension) &&
48
+ (f.implemented == null || e.status.implemented === f.implemented) &&
49
+ (q == null || [e.name, ...e.aliases, e.description ?? ''].some((s) => s.toLowerCase().includes(q)));
50
+ }
51
+ return data.functions.filter((e) => test(e)).map(copy);
52
+ }
package/src/samples.js ADDED
@@ -0,0 +1,14 @@
1
+ // samples(source, baseUrl?) (spec/samples.md 2). The pattern engine only
2
+ // records the sources; fetching and playing belong to the sound layer (Epic 4),
3
+ // which reads them through getSampleSources() / setSamplesLoader().
4
+ const sources = [];
5
+ let loader = null;
6
+
7
+ // loader(source, baseUrl) -> Promise; set by the sound layer.
8
+ export function setSamplesLoader(fn) { loader = fn ?? null; }
9
+ export const getSampleSources = () => sources.slice();
10
+
11
+ export function samples(source, baseUrl) {
12
+ sources.push({ source, baseUrl });
13
+ return Promise.resolve(loader ? loader(source, baseUrl) : undefined);
14
+ }
@@ -0,0 +1,123 @@
1
+ // Sample manipulation: chop, striate, slice, splice, loopAt, fit, scrub and
2
+ // loopAtCps (spec/functions/chop.md, slice.md, loopAt.md, scrub.md,
3
+ // loopAtCps.md). Regrouped from the Tier 2/3 batch modules (audit 6).
4
+ import { fastBy, fastcat } from './constructors.js';
5
+ import { ONE, fraction } from './fraction.js';
6
+ import { Hap, combineContext } from './hap.js';
7
+ import { Pattern, assignMap, pure, reify, silence } from './pattern.js';
8
+ import { register } from './register.js';
9
+ import { asMap, floorMod, wholeCount, wholeCount as count } from './util.js';
10
+
11
+ // --- sample manipulation (spec/functions/chop.md, slice.md, loopAt.md, scrub.md)
12
+
13
+ // Each hap cut into floor(n) parts in time; part i gets the i-th n-th of the
14
+ // hap's begin..end sample range.
15
+ export const chop = register('chop', (pat, n) => {
16
+ const nn = Number(n);
17
+ const count = wholeCount(n);
18
+ if (count < 1) return silence;
19
+ return pat.fmap((v) => {
20
+ const o = asMap(v);
21
+ const b = o.begin ?? 0;
22
+ const d = (o.end ?? 1) - b;
23
+ const parts = [];
24
+ for (let i = 0; i < count; i++) parts.push(pure({ ...o, begin: b + (d * i) / nn, end: b + (d * (i + 1)) / nn }));
25
+ return fastcat(...parts);
26
+ }).squeezeJoin();
27
+ }, { curry: 1 });
28
+
29
+ // The cycle played floor(n) times at n x speed; pass i plays the i-th share of
30
+ // the sample (begin i/n, end (i+1)/n), overwriting begin/end. Pass i of result
31
+ // cycle C is source cycle C n + i, so haps come grouped by source hap.
32
+ export const striate = register('striate', (pat, n) => {
33
+ const nn = Number(n);
34
+ const count = wholeCount(n);
35
+ if (count < 1) return silence;
36
+ const passes = new Pattern((state) => pat.query(state).map((h) => {
37
+ const i = floorMod(h.wholeOrPart().begin.sam().toNumber(), count);
38
+ return h.withValue((v) => ({ ...asMap(v), begin: i / nn, end: (i + 1) / nn }));
39
+ }), pat._steps);
40
+ return fastBy(passes, count);
41
+ }, { curry: 1 });
42
+
43
+ // Structure from `index` (outer join): each index hap takes the source value
44
+ // at its onset plus begin/end of slice i of n. splice adds unit "c" and a speed
45
+ // that fits the slice into the hap, unless the value has a speed already.
46
+ const slicer = (splice) => (pat, n, index) => {
47
+ const nn = Number(n);
48
+ const idx = reify(index);
49
+ return new Pattern((state) => {
50
+ const out = [];
51
+ for (const oh of idx.query(state)) {
52
+ const span = oh.wholeOrPart();
53
+ const i = Number(oh.value);
54
+ for (const ih of pat.query(state.setSpan(span))) {
55
+ if (!ih.part.begin.eq(span.begin)) continue;
56
+ const o = { ...asMap(ih.value), begin: i / nn, end: (i + 1) / nn, _slices: nn };
57
+ if (splice) {
58
+ o.unit = 'c';
59
+ if (o.speed === undefined) o.speed = (1 / nn) / span.end.sub(span.begin).toNumber();
60
+ }
61
+ out.push(new Hap(oh.whole, oh.part, o, combineContext(oh.context, ih.context)));
62
+ }
63
+ }
64
+ return out;
65
+ }, idx._steps);
66
+ };
67
+ export const slice = register('slice', slicer(false), { patternArgs: 1 });
68
+ export const splice = register('splice', slicer(true), { patternArgs: 1 });
69
+
70
+ // Query-time tempo: the scheduler passes { cps } in the query controls.
71
+ // Without it (plain queries, the oracle fixtures) loopAt counts with 0.5 and
72
+ // fit with 1, the values the oracle shows (spec/sound.md 10.1).
73
+ const queryCps = (state, dflt) => {
74
+ const c = Number(state.controls?.cps);
75
+ return Number.isFinite(c) && c > 0 ? c : dflt;
76
+ };
77
+
78
+ // slow(n), unit "c" and speed cps / n (spec/functions/loopAt.md, spec/sound.md 10.1).
79
+ export const loopAt = register('loopAt', (pat, n) => {
80
+ const f = fraction(n);
81
+ if (f.sign() <= 0) return silence;
82
+ const slow = fastBy(pat, ONE.div(f));
83
+ return new Pattern((state) => {
84
+ const speed = queryCps(state, 0.5) / Number(n);
85
+ return slow.query(state).map((h) => h.withValue((v) => ({ ...asMap(v), speed, unit: 'c' })));
86
+ }, slow._steps);
87
+ }, { aliases: ['loopat'], memo: true, curry: 1 });
88
+ export const loopat = loopAt;
89
+
90
+ // unit "c" and speed cps / (whole duration); an earlier speed is replaced.
91
+ export const fit = register('fit', (pat) => new Pattern((state) => {
92
+ const cps = queryCps(state, 1);
93
+ return pat.query(state).map((h) => {
94
+ if (!h.whole) return h;
95
+ const speed = cps / h.whole.end.sub(h.whole.begin).toNumber();
96
+ return h.withValue((v) => ({ ...asMap(v), speed, unit: 'c' }));
97
+ });
98
+ }, pat._steps), { patternArgs: 0 });
99
+
100
+ // Structure from `pos` (outer join); `position` or `position:speed`.
101
+ export const scrub = register('scrub', (pat, pos) => {
102
+ const ps = reify(pos);
103
+ return new Pattern((state) => {
104
+ const out = [];
105
+ for (const oh of ps.query(state)) {
106
+ const span = oh.wholeOrPart();
107
+ const [begin, speed] = Array.isArray(oh.value) ? [oh.value[0], oh.value[1] ?? 1] : [oh.value, 1];
108
+ for (const ih of pat.query(state.setSpan(span))) {
109
+ if (!ih.part.begin.eq(span.begin)) continue;
110
+ out.push(new Hap(oh.whole, oh.part, { ...asMap(ih.value), begin, clip: 1, speed }, combineContext(oh.context, ih.context)));
111
+ }
112
+ }
113
+ return out;
114
+ }, ps._steps);
115
+ }, { patternArgs: 0 });
116
+
117
+ // --- loopAtCps, loopatcps (spec/functions/loopAtCps.md) ----------------------------
118
+ export const loopAtCps = register('loopAtCps', (pat, n, cps) => {
119
+ const f = fraction(n);
120
+ if (f.sign() <= 0) return silence;
121
+ return fastBy(pat, ONE.div(f)).fmap(assignMap([['speed', Number(cps) / Number(n)], ['unit', 'c']]));
122
+ }, { aliases: ['loopatcps'], curry: 2 });
123
+ export const loopatcps = loopAtCps;