@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/scope.js ADDED
@@ -0,0 +1,77 @@
1
+ // The names user code sees (audit 7): every registered function (register.js
2
+ // `registry`) plus the explicit list below of public names that are not
3
+ // registered (classes, constants, host helpers). Modules that sit above the
4
+ // evaluator (evaluate, outline, audio/index, offline, index, and the optional
5
+ // extras/: check, describe, editor)
6
+ // add their own names with addScope() when they load, so nothing here imports
7
+ // them and the import graph stays acyclic (test/unit/imports.test.js).
8
+ import { registry } from './register.js';
9
+ // Every module that registers functions, so a host that imports only
10
+ // evaluate.js (the editor, describe, offline) sees the whole registry.
11
+ import './constructors.js';
12
+ import './transforms.js';
13
+ import './euclid.js';
14
+ import './combinators.js';
15
+ import './sampling.js';
16
+ import './stepwise.js';
17
+ import './helpers.js';
18
+ import { Fraction, fraction } from './fraction.js';
19
+ import { TimeSpan } from './time.js';
20
+ import { Hap } from './hap.js';
21
+ import { NeedsMiniNotation, Pattern, State, getStringParser, isPattern, pure, reify, setStringParser, signal, silence } from './pattern.js';
22
+ import { register, registerFree } from './register.js';
23
+ import { MiniParseError, mini, miniAt, parseMini } from './mini/index.js';
24
+ import { NoteConversionError, OPERATORS, applyOp, isControlMap, noteToMidi } from './ops.js';
25
+ import { VOICING_DICTIONARIES, midiToNoteName, parseChord, parseScale, scaleDegree, scaleNames, voiceChord } from './tonal.js';
26
+ import { chooseCyclesWith, degradeBySeed, getRandomMode, getSeed, randAt, randWith, seedLayer, setRandomMode, setSeed, undegradeBySeed } from './random.js';
27
+ import { continuous } from './signals.js';
28
+ import { controlFunctions, controlKeys, controlValue } from './controls.js';
29
+ import { fastGapBy, zoomSpan } from './structure.js';
30
+ import { DRAW_METHODS, Framer, cleanupDraw, commitPainters, fitCanvas, getDrawContext, getPainters, getWidgetContext, paintFrame, queryDrawHaps, setDrawEnvironment, setDrawHandler } from './draw.js';
31
+ import { RENDERERS, rollKey, rollRows } from './visuals.js';
32
+ import { getSampleSources, samples, setSamplesLoader } from './samples.js';
33
+ import { describeFunction, listFunctions } from './registry.js';
34
+ import { getCompat, setCompat } from './compat.js';
35
+ import { registerWidgetType, transpile } from './transpile.js';
36
+ import { AUDIO_CONTROLS, SYNTHS, envelopePoints, unusedControls, voiceParams } from './audio/params.js';
37
+ import { AudioEngine, LIMITER } from './audio/engine.js';
38
+ import { Scheduler, describeLayerError, makeTicker, quantizeCycles, queryTriggers, renderTriggers, splitLayers } from './audio/clock.js';
39
+ import { VoicePool } from './audio/voices.js';
40
+ import { configureSamples, createSampleBank, getSampleBank, parseSampleMap, preload, resolveBase, resolveMapUrl, sampleSource, soundName, wrapIndex } from './audio/samples.js';
41
+
42
+ const extra = Object.create(null);
43
+ let added = 0;
44
+
45
+ // A key that changes whenever the scope grows (check.js caches on it).
46
+ export const scopeKey = () => `${registry.size}:${added}`;
47
+
48
+ // addScope({name: value, ...}): names for user code (undefined values skipped).
49
+ export function addScope(names) {
50
+ for (const [k, v] of Object.entries(names)) if (v !== undefined) { extra[k] = v; added++; }
51
+ }
52
+
53
+ addScope({
54
+ Fraction, fraction, TimeSpan, Hap,
55
+ NeedsMiniNotation, Pattern, State, getStringParser, isPattern, pure, reify, setStringParser, signal, silence,
56
+ register, registerFree, registry,
57
+ MiniParseError, mini, miniAt, parseMini,
58
+ NoteConversionError, OPERATORS, applyOp, isControlMap, noteToMidi,
59
+ VOICING_DICTIONARIES, midiToNoteName, parseChord, parseScale, scaleDegree, scaleNames, voiceChord,
60
+ chooseCyclesWith, degradeBySeed, getRandomMode, getSeed, randAt, randWith, seedLayer, setRandomMode, setSeed, undegradeBySeed,
61
+ continuous, controlFunctions, controlKeys, controlValue, fastGapBy, zoomSpan,
62
+ DRAW_METHODS, Framer, cleanupDraw, commitPainters, fitCanvas, getDrawContext, getPainters, getWidgetContext, paintFrame, queryDrawHaps, setDrawEnvironment, setDrawHandler,
63
+ RENDERERS, rollKey, rollRows, getSampleSources, samples, setSamplesLoader,
64
+ describeFunction, listFunctions, getCompat, setCompat, registerWidgetType, transpile,
65
+ AUDIO_CONTROLS, SYNTHS, envelopePoints, unusedControls, voiceParams, AudioEngine, LIMITER,
66
+ Scheduler, describeLayerError, makeTicker, quantizeCycles, queryTriggers, renderTriggers, splitLayers, VoicePool,
67
+ configureSamples, createSampleBank, getSampleBank, parseSampleMap, preload, resolveBase, resolveMapUrl, sampleSource, soundName, wrapIndex,
68
+ });
69
+
70
+ // scopeEntries() -> {name: value}: the registry, then the explicit names
71
+ // (which win on a clash, as the package exports did before).
72
+ export function scopeEntries() {
73
+ const scope = Object.create(null);
74
+ for (const [k, v] of registry) scope[k] = v;
75
+ Object.assign(scope, extra);
76
+ return scope;
77
+ }
package/src/signals.js ADDED
@@ -0,0 +1,76 @@
1
+ // Deterministic signals and numeric scaling (plan 2.3): sine, cosine, saw,
2
+ // isaw, tri, itri, square, time, their bipolar *2 forms, run, range, rangex,
3
+ // range2, toBipolar, fromBipolar (spec/functions/signals.md, range.md).
4
+ import { fraction } from './fraction.js';
5
+ import { signal, reify, silence } from './pattern.js';
6
+ import { register, registerFree } from './register.js';
7
+ import { fastcat } from './constructors.js';
8
+ import { isControlMap } from './util.js';
9
+
10
+ // A continuous pattern: one analog hap per cycle piece of the query, valued
11
+ // at the piece's begin (signals.md "Shared behaviour"). f gets a Fraction.
12
+ export const continuous = (f) => signal(f).splitQueries();
13
+
14
+ // Position inside the cycle. JS remainder semantics, so negative time gives a
15
+ // negative position (spec/time.md 6.2, fixture analog-segment-late).
16
+ const pos = (t) => t.toNumber() % 1;
17
+ const TAU = Math.PI * 2;
18
+ const sineAt = (t) => (Math.sin(TAU * t.toNumber()) + 1) / 2;
19
+ const QUARTER = fraction(1).div(4);
20
+
21
+ export const sine = continuous(sineAt);
22
+ export const cosine = continuous((t) => sineAt(t.add(QUARTER)));
23
+ export const saw = continuous(pos);
24
+ export const isaw = continuous((t) => 1 - pos(t));
25
+ export const tri = continuous((t) => 1 - Math.abs(2 * pos(t) - 1));
26
+ export const itri = continuous((t) => Math.abs(2 * pos(t) - 1));
27
+ export const square = continuous((t) => (pos(t) < 0.5 ? 0 : 1));
28
+ // time: the exact query begin as a Fraction (signals.md table).
29
+ export const time = continuous((t) => t);
30
+
31
+
32
+ // Numeric value map; control maps pass through unchanged (range.md edge).
33
+ export const numeric = (pat, f) => pat.fmap((v) => (isControlMap(v) ? v : f(Number(v))));
34
+
35
+ const toBi = (v) => v * 2 - 1;
36
+ const fromBi = (v) => (v + 1) / 2;
37
+ export const toBipolar = register('toBipolar', (pat) => numeric(pat, toBi));
38
+ export const fromBipolar = register('fromBipolar', (pat) => numeric(pat, fromBi));
39
+
40
+ export const sine2 = toBipolar(sine);
41
+ export const cosine2 = toBipolar(cosine);
42
+ export const saw2 = toBipolar(saw);
43
+ export const isaw2 = toBipolar(isaw);
44
+ export const tri2 = toBipolar(tri);
45
+ export const itri2 = toBipolar(itri);
46
+ export const square2 = toBipolar(square);
47
+
48
+ // v in [0,1] -> [lo, hi]; lo > hi inverts. Patterned bounds use inner join.
49
+ export const range = register('range', (pat, lo, hi) => numeric(pat, (v) => v * (hi - lo) + lo));
50
+ // Exponential: equal ratios for equal steps (lo, hi > 0).
51
+ export const rangex = register('rangex', (pat, lo, hi) => {
52
+ const a = Math.log(lo);
53
+ const b = Math.log(hi);
54
+ return numeric(pat, (v) => Math.exp(v * (b - a) + a));
55
+ });
56
+ // Bipolar input in [-1, 1] -> [lo, hi].
57
+ export const range2 = register('range2', (pat, lo, hi) => numeric(pat, (v) => fromBi(v) * (hi - lo) + lo));
58
+
59
+ // run(n): the sequence 0 .. n-1 in one cycle; n patternable (inner join).
60
+ const runConst = (n) => {
61
+ const k = Math.floor(Number(n));
62
+ return k <= 0 ? silence : fastcat(...Array.from({ length: k }, (_, i) => i));
63
+ };
64
+ export function run(n) {
65
+ if (typeof n === 'number') return runConst(n);
66
+ return reify(n).fmap(runConst).innerJoin();
67
+ }
68
+ registerFree('run', run);
69
+ for (const [name, p] of Object.entries({ sine, cosine, saw, isaw, tri, itri, square, time, sine2, cosine2, saw2, isaw2, tri2, itri2, square2 })) {
70
+ registerFree(name, p);
71
+ }
72
+
73
+ // --- moved here from the Tier 2/3 batch modules (audit 6) ---------------------
74
+
75
+ // --- steady (spec/functions/steady.md) --------------------------------------------
76
+ export const steady = registerFree('steady', (x) => signal(() => x));
@@ -0,0 +1,150 @@
1
+ // Step-wise functions (spec/functions/stepwise.md, shrinklist.md): pace,
2
+ // expand, contract, extend, take, drop, shrink, grow, tour, zip, stepalt and
3
+ // the s_* names. Regrouped from the Tier 2/3 batch modules (audit 6).
4
+ import { fastBy, fastcat, polymeter, timecat } from './constructors.js';
5
+ import { ONE, ZERO, fraction } from './fraction.js';
6
+ import { Hap, combineContext } from './hap.js';
7
+ import { Pattern, reify, silence } from './pattern.js';
8
+ import { register, registerFree } from './register.js';
9
+ import { zoomSpan } from './structure.js';
10
+ import { isPatLike as isPat, lcm } from './util.js';
11
+
12
+ // --- step-wise functions (spec/functions/stepwise.md) ---------------------------
13
+
14
+ // A patterned step argument: inner join with the source's locations first.
15
+ const srcFirst = (impl) => (pat, n) => {
16
+ if (!isPat(n)) return impl(pat, n);
17
+ const outer = reify(n).fmap((v) => impl(pat, v));
18
+ return new Pattern((state) => {
19
+ const out = [];
20
+ for (const oh of outer.query(state)) {
21
+ for (const ih of oh.value.query(state.setSpan(oh.part))) out.push(new Hap(ih.whole, ih.part, ih.value, combineContext(ih.context, oh.context)));
22
+ }
23
+ return out;
24
+ });
25
+ };
26
+ const stepsOf = (pat) => (pat._steps === undefined ? undefined : fraction(pat._steps));
27
+
28
+ // Play at n steps per cycle.
29
+ export const pace = register('pace', (pat, n) => {
30
+ const S = stepsOf(pat);
31
+ const t = fraction(n);
32
+ if (S === undefined || S.sign() <= 0) return pat;
33
+ if (t.sign() <= 0) return silence;
34
+ return fastBy(pat, t.div(S)).withSteps(t);
35
+ }, { aliases: ['steps'], curry: 1 });
36
+
37
+ export const expand = register('expand', srcFirst((pat, f) => {
38
+ const S = stepsOf(pat);
39
+ return S === undefined ? pat : pat.withSteps(S.mul(fraction(f)));
40
+ }), { patternArgs: 0, aliases: ['s_expand'], curry: 1 });
41
+ export const contract = register('contract', srcFirst((pat, f) => {
42
+ const S = stepsOf(pat);
43
+ return S === undefined ? pat : pat.withSteps(S.div(fraction(f)));
44
+ }), { patternArgs: 0, aliases: ['s_contract'], curry: 1 });
45
+ export const extend = register('extend', srcFirst((pat, n) => {
46
+ const S = stepsOf(pat);
47
+ const out = fastBy(pat, n);
48
+ return S === undefined ? out : out.withSteps(S.mul(fraction(n)));
49
+ }), { patternArgs: 0, aliases: ['s_extend'], curry: 1 });
50
+
51
+ // First n steps (last |n| for n < 0) stretched over the cycle.
52
+ function takeSteps(pat, n) {
53
+ const S = stepsOf(pat);
54
+ if (S === undefined) return pat;
55
+ const k = fraction(n);
56
+ if (k.n === 0n || S.sign() <= 0) return silence;
57
+ const a = k.abs().min(S);
58
+ const r = a.div(S);
59
+ return (k.sign() < 0 ? zoomSpan(pat, ONE.sub(r), ONE) : zoomSpan(pat, ZERO, r)).withSteps(a);
60
+ }
61
+ // Without the first n steps (the last |n| for n < 0).
62
+ function dropSteps(pat, n) {
63
+ const S = stepsOf(pat);
64
+ if (S === undefined) return pat;
65
+ const k = fraction(n);
66
+ const rest = S.sub(k.abs());
67
+ if (rest.sign() <= 0) return silence;
68
+ return takeSteps(pat, k.sign() < 0 ? rest : rest.neg());
69
+ }
70
+ export const take = register('take', srcFirst(takeSteps), { patternArgs: 0, aliases: ['s_add'], curry: 1 });
71
+ export const drop = register('drop', srcFirst(dropSteps), { patternArgs: 0, aliases: ['s_sub'], curry: 1 });
72
+
73
+ // shrink(n): the pattern with 0, n, 2n, ... steps dropped (one per step of the
74
+ // source), stepcat'd; grow(n): take(S - i|n|) for the same i, shortest first.
75
+ // Negative n works from the back. Fractional n follows the same rule (fixtures
76
+ // grow, grow-neg, shrink-frac).
77
+ const taper = (grow) => (pat, n) => {
78
+ const S = stepsOf(pat);
79
+ if (S === undefined) return pat;
80
+ const k = fraction(n);
81
+ const a = k.abs();
82
+ const neg = k.sign() < 0;
83
+ const parts = [];
84
+ for (let i = 0; fraction(i).lt(S); i++) {
85
+ const amount = S.sub(a.mul(i));
86
+ if (amount.sign() <= 0) break;
87
+ if (grow) parts.unshift(takeSteps(pat, neg ? amount.neg() : amount));
88
+ else parts.push(dropSteps(pat, neg ? a.mul(i).neg() : a.mul(i)));
89
+ }
90
+ return timecat(...parts);
91
+ };
92
+ export const shrink = register('shrink', srcFirst(taper(false)), { patternArgs: 0, aliases: ['s_taper'], curry: 1 });
93
+ export const grow = register('grow', srcFirst(taper(true)), { patternArgs: 0, curry: 1 });
94
+
95
+ // Stepcats of pats with pat inserted from the end to the front.
96
+ export const tour = register('tour', (pat, ...pats) => {
97
+ const ps = pats.map(reify);
98
+ const items = [];
99
+ for (let k = ps.length; k >= 0; k--) items.push(...ps.slice(0, k), pat, ...ps.slice(k));
100
+ return timecat(...items);
101
+ }, { patternArgs: 0, aliases: ['s_tour'] });
102
+
103
+ // Step i of each pattern in turn, for the lcm of the step counts; lcm steps
104
+ // per cycle.
105
+ export function zip(...args) {
106
+ const pats = args.map(reify).filter((p) => stepsOf(p) !== undefined && stepsOf(p).sign() > 0);
107
+ if (pats.length === 0) return silence;
108
+ const counts = pats.map((p) => Math.max(1, Math.round(stepsOf(p).toNumber())));
109
+ const L = lcm(counts);
110
+ const items = [];
111
+ for (let i = 0; i < L; i++) {
112
+ pats.forEach((p, j) => {
113
+ const s = i % counts[j];
114
+ items.push(zoomSpan(p, fraction(s).div(counts[j]), fraction(s + 1).div(counts[j])));
115
+ });
116
+ }
117
+ return fastBy(fastcat(...items), fraction(1).div(pats.length)).withSteps(L);
118
+ }
119
+ registerFree('zip', zip, ['s_zip']);
120
+
121
+ // A stepcat in which a list argument gives its next element each round.
122
+ export function stepalt(...args) {
123
+ const lists = args.map((a) => (Array.isArray(a) ? a.map(reify) : [reify(a)]));
124
+ const R = lcm(lists.map((l) => Math.max(1, l.length)));
125
+ const items = [];
126
+ for (let r = 0; r < R; r++) for (const l of lists) if (l.length) items.push(l[r % l.length]);
127
+ return timecat(...items);
128
+ }
129
+ registerFree('stepalt', stepalt, ['s_alt']);
130
+
131
+ // s_polymeter: the same function as polymeter() (LCM alignment since plan 7.5).
132
+ export const s_polymeter = registerFree('s_polymeter', polymeter);
133
+
134
+ // --- shrinklist, s_taperlist (spec/functions/shrinklist.md) -----------------------
135
+ // The stages shrink() stepcats, as a plain array of patterns.
136
+ export const shrinklist = register('shrinklist', (pat, amount) => {
137
+ if (pat._steps === undefined) return [pat];
138
+ const S = fraction(pat._steps);
139
+ const a = fraction(amount).abs();
140
+ const neg = fraction(amount).sign() < 0;
141
+ const out = [];
142
+ for (let i = 0; fraction(i).lt(S); i++) {
143
+ const k = a.mul(i);
144
+ if (S.sub(k).sign() <= 0) break;
145
+ out.push(pat.drop(neg ? k.neg() : k));
146
+ if (a.sign() === 0) break;
147
+ }
148
+ return out;
149
+ }, { patternArgs: 0, aliases: ['s_taperlist'] });
150
+ export const s_taperlist = shrinklist;