@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.
- package/LICENSE +21 -0
- package/README.md +46 -2
- package/data/registry-data.js +3 -0
- package/data/signatures.js +3 -0
- package/docs/clean-room.md +450 -0
- package/package.json +69 -4
- package/src/audio/clock.js +383 -0
- package/src/audio/engine.js +678 -0
- package/src/audio/index.js +394 -0
- package/src/audio/offline.js +73 -0
- package/src/audio/params.js +397 -0
- package/src/audio/samples.js +274 -0
- package/src/audio/unlock.js +70 -0
- package/src/audio/voices.js +44 -0
- package/src/combinators.js +150 -0
- package/src/compat.js +16 -0
- package/src/constructors.js +236 -0
- package/src/controls.js +199 -0
- package/src/draw.js +252 -0
- package/src/euclid.js +57 -0
- package/src/evaluate.js +251 -0
- package/src/extras/check.js +678 -0
- package/src/extras/describe.js +433 -0
- package/src/extras/editor.js +369 -0
- package/src/extras/index.js +10 -0
- package/src/fraction.js +300 -0
- package/src/hap.js +64 -0
- package/src/helpers.js +68 -0
- package/src/index.js +74 -0
- package/src/mini/index.js +36 -0
- package/src/mini/parser.js +400 -0
- package/src/ops.js +293 -0
- package/src/outline.js +175 -0
- package/src/pattern.js +365 -0
- package/src/random.js +344 -0
- package/src/register.js +83 -0
- package/src/registry.js +52 -0
- package/src/samples.js +14 -0
- package/src/sampling.js +123 -0
- package/src/scope.js +77 -0
- package/src/signals.js +76 -0
- package/src/stepwise.js +150 -0
- package/src/structure.js +636 -0
- package/src/time.js +70 -0
- package/src/tonal.js +583 -0
- package/src/transforms.js +125 -0
- package/src/transpile.js +394 -0
- package/src/util.js +80 -0
- package/src/visuals.js +216 -0
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
// Clock and scheduler (plan 4.1, docs/improvements.md 3-4). No Web Audio in
|
|
2
|
+
// here: the scheduler reads a clock function (seconds) and hands triggers to
|
|
3
|
+
// a callback, so the same code runs offline in node (renderTriggers) and in
|
|
4
|
+
// the browser (clock = audioContext.currentTime).
|
|
5
|
+
//
|
|
6
|
+
// The cycle position is exact: each query window is [lastEnd, end) with both
|
|
7
|
+
// ends Fractions; `end` is the audio-clock position plus the lookahead,
|
|
8
|
+
// rounded down to a 1/GRID cycle grid, so consecutive windows meet exactly
|
|
9
|
+
// and no hap is played twice or skipped. Cycles map to seconds through an
|
|
10
|
+
// anchor { cycle (Fraction), time (s), cps }; a tempo change re-anchors at the
|
|
11
|
+
// next window boundary, so the cycle→time map stays exact on both sides.
|
|
12
|
+
import { Fraction, ZERO, fraction } from '../fraction.js';
|
|
13
|
+
import { stackMembers } from '../constructors.js';
|
|
14
|
+
|
|
15
|
+
const GRID = 1024n;
|
|
16
|
+
|
|
17
|
+
const quantise = (cycle) => new Fraction(BigInt(Math.floor(cycle * Number(GRID))), 1n).div(new Fraction(GRID, 1n));
|
|
18
|
+
|
|
19
|
+
// Seconds at which `cycle` (Fraction) sounds under `anchor`.
|
|
20
|
+
export const timeAt = (cycle, anchor) => anchor.time + cycle.sub(anchor.cycle).toNumber() / anchor.cps;
|
|
21
|
+
|
|
22
|
+
// Every onset hap of `pattern` with whole.begin in [begin, end) (Fractions or
|
|
23
|
+
// numbers) as a trigger { time, duration, cycle, value, hap }, sorted by time.
|
|
24
|
+
export function queryTriggers(pattern, begin, end, anchor, out = []) {
|
|
25
|
+
const n = out.length;
|
|
26
|
+
for (const hap of pattern.queryArc(begin, end, { cps: anchor.cps })) {
|
|
27
|
+
if (!hap.hasOnset()) continue;
|
|
28
|
+
const time = timeAt(hap.whole.begin, anchor);
|
|
29
|
+
out.push({
|
|
30
|
+
time,
|
|
31
|
+
duration: hap.whole.end.sub(hap.whole.begin).toNumber() / anchor.cps,
|
|
32
|
+
cycle: hap.whole.begin.toNumber(),
|
|
33
|
+
cps: anchor.cps,
|
|
34
|
+
value: hap.value,
|
|
35
|
+
hap,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return n === 0 ? out.sort((a, b) => a.time - b.time) : out;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Quantise setting → cycles (Fraction) or null (swap at once). 'cycle' and
|
|
42
|
+
// 'bar' are one cycle (RIFF follows the convention one cycle = one bar,
|
|
43
|
+
// setcpm(bpm / 4)); a positive number is that many cycles.
|
|
44
|
+
export function quantizeCycles(q) {
|
|
45
|
+
if (q === undefined || q === null || q === false || q === 0 || q === 'off' || q === 'none') return null;
|
|
46
|
+
if (q === 'cycle' || q === 'bar' || q === true) return fraction(1);
|
|
47
|
+
const n = Number(q);
|
|
48
|
+
if (!Number.isFinite(n) || n <= 0) throw new RangeError(`quantize must be 'cycle', 'bar' or a positive number of cycles, got ${q}`);
|
|
49
|
+
return fraction(n);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const validFade = (x) => { const n = Number(x ?? 0); return Number.isFinite(n) && n > 0 ? Math.min(n, 10) : 0; };
|
|
53
|
+
|
|
54
|
+
// The top-level layers of a pattern (plan 8.3): a stack's members, else the
|
|
55
|
+
// pattern itself. Querying them one by one gives the same haps in the same
|
|
56
|
+
// order as querying the stack, so isolation changes no output.
|
|
57
|
+
export function splitLayers(pattern) {
|
|
58
|
+
const members = stackMembers.get(pattern);
|
|
59
|
+
if (members) return members.map((p, index) => ({ name: `layer ${index + 1}`, pattern: p, index }));
|
|
60
|
+
return [{ name: 'program', pattern, index: 0 }];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// "[riff] error in layer "bd" (line 2:1): message" for a log line.
|
|
64
|
+
export function describeLayerError(info) {
|
|
65
|
+
const where = info.line !== undefined && !info.call ? ` (line ${info.line}:${info.column})` : '';
|
|
66
|
+
const which = info.layers > 1 ? ` in layer "${info.layer}"` : '';
|
|
67
|
+
return `[riff] error while playing${which}${where}: ${info.message}${info.fallback ? ' (playing its last good version)' : ''}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const validCps = (cps) => {
|
|
71
|
+
const n = Number(cps);
|
|
72
|
+
if (!Number.isFinite(n) || n <= 0) throw new RangeError(`cps must be a positive number, got ${cps}`);
|
|
73
|
+
return n;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// Scheduler(options)
|
|
77
|
+
// now(): clock in seconds (audioContext.currentTime in the browser);
|
|
78
|
+
// onTrigger(trigger): called once per onset hap, in time order;
|
|
79
|
+
// ticker: { start(fn), stop() } (makeTicker in the browser, manual in tests);
|
|
80
|
+
// lookahead (s, 0.2), latency (start delay, s, 0.05), grace (s, 0.5): a tick
|
|
81
|
+
// that finds events at most `grace` late handles them by `lateLimit`;
|
|
82
|
+
// further behind, the scheduler skips to the present and logs how much.
|
|
83
|
+
// lateLimit (s, 0.1): a late event at most this late plays at now + 10 ms
|
|
84
|
+
// with its full attack (trigger.late holds how late); a later one is
|
|
85
|
+
// dropped (dropCount). One log line per late tick. Infinity: the old way,
|
|
86
|
+
// every late event at now (operator decision 18 Nov 2026).
|
|
87
|
+
// onCycle(cycle, pattern): the window reached cycle boundary `cycle - 1`
|
|
88
|
+
// (rolling sample preload).
|
|
89
|
+
// onError(err, info): a layer threw while queried (plan 8.3); info is
|
|
90
|
+
// { layer, index, layers, message, cycle, count, line?, column?, endLine?,
|
|
91
|
+
// endColumn?, code, severity, hint, fallback, call? }. Called once per
|
|
92
|
+
// layer and message until the next setPattern; repeats only raise
|
|
93
|
+
// errorCount. Without it the error is logged. A failing layer plays its
|
|
94
|
+
// last good pattern (same name and order), else is silent.
|
|
95
|
+
// onSwap(time, fade): the pattern changed at `time` (s) with a crossfade of
|
|
96
|
+
// `fade` s (plan 8.5); the engine fades the voices still sounding.
|
|
97
|
+
// quantize ('cycle' | 'bar' | cycles, default none), crossfade (s, 0).
|
|
98
|
+
// patternCps (false, opt-in; docs/improvements.md 4): a hap whose value
|
|
99
|
+
// carries `cps` changes the tempo exactly at its onset; later events of the
|
|
100
|
+
// same window are re-timed from that new anchor.
|
|
101
|
+
export class Scheduler {
|
|
102
|
+
constructor({ now, onTrigger, ticker = null, lookahead = 0.2, latency = 0.05, grace = 0.5, cps = 0.5, log = console.warn,
|
|
103
|
+
onError = null, onSwap = null, quantize = null, crossfade = 0, patternCps = false, lateLimit = 0.1, onCycle = null } = {}) {
|
|
104
|
+
this.clock = now;
|
|
105
|
+
this.onTrigger = onTrigger ?? (() => {});
|
|
106
|
+
this.ticker = ticker;
|
|
107
|
+
this.lookahead = lookahead;
|
|
108
|
+
this.latency = latency;
|
|
109
|
+
this.grace = grace;
|
|
110
|
+
this.log = log;
|
|
111
|
+
this.cps = validCps(cps);
|
|
112
|
+
this.pattern = null;
|
|
113
|
+
this.started = false;
|
|
114
|
+
this.anchor = null;
|
|
115
|
+
this.lastEnd = ZERO;
|
|
116
|
+
this.pendingCps = null;
|
|
117
|
+
this.lateCount = 0;
|
|
118
|
+
this.dropCount = 0;
|
|
119
|
+
const l = Number(lateLimit);
|
|
120
|
+
this.lateLimit = l >= 0 ? l : 0.1;
|
|
121
|
+
this.onCycle = onCycle;
|
|
122
|
+
this.skipped = 0;
|
|
123
|
+
this.errors = new Set();
|
|
124
|
+
this.onError = onError;
|
|
125
|
+
this.onSwap = onSwap;
|
|
126
|
+
this.quantize = quantizeCycles(quantize);
|
|
127
|
+
this.crossfade = validFade(crossfade);
|
|
128
|
+
this.layers = [];
|
|
129
|
+
this.locate = null;
|
|
130
|
+
this.pending = null;
|
|
131
|
+
this.layerErrors = new Map();
|
|
132
|
+
this.errorCount = 0;
|
|
133
|
+
this.patternCps = patternCps === true;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// patternCps: walk the window's triggers in onset order and re-anchor at
|
|
137
|
+
// each one whose value sets a different cps (exact Fraction cycle).
|
|
138
|
+
applyPatternCps(triggers) {
|
|
139
|
+
let a = this.anchor;
|
|
140
|
+
for (const tr of triggers) {
|
|
141
|
+
const w = tr.hap.whole;
|
|
142
|
+
if (a !== this.anchor) {
|
|
143
|
+
tr.time = timeAt(w.begin, a);
|
|
144
|
+
tr.duration = w.end.sub(w.begin).toNumber() / a.cps;
|
|
145
|
+
tr.cps = a.cps;
|
|
146
|
+
}
|
|
147
|
+
let c = tr.value?.cps;
|
|
148
|
+
if (Array.isArray(c)) c = c[0];
|
|
149
|
+
c = Number(c);
|
|
150
|
+
if (tr.value?.cps === undefined || !Number.isFinite(c) || c <= 0 || c === a.cps) continue;
|
|
151
|
+
a = { cycle: w.begin, time: timeAt(w.begin, a), cps: c };
|
|
152
|
+
tr.duration = w.end.sub(w.begin).toNumber() / c;
|
|
153
|
+
tr.cps = c;
|
|
154
|
+
}
|
|
155
|
+
if (a !== this.anchor) { this.anchor = a; this.cps = a.cps; }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// setPattern(pattern, options): options.layers [{ name, pattern }] (default:
|
|
159
|
+
// the stack members), options.locate(index) → { name?, line, column, ... }
|
|
160
|
+
// for error reports, options.quantize / options.crossfade override the
|
|
161
|
+
// scheduler's own. With a quantize step and a running clock the swap waits
|
|
162
|
+
// for the next boundary at or after the scheduled position (swapAt).
|
|
163
|
+
setPattern(pattern, options = {}) {
|
|
164
|
+
const q = options.quantize !== undefined ? quantizeCycles(options.quantize) : this.quantize;
|
|
165
|
+
const fade = options.crossfade !== undefined ? validFade(options.crossfade) : this.crossfade;
|
|
166
|
+
const next = { pattern: pattern ?? null, layers: options.layers, locate: options.locate ?? null, explain: options.explain, fade };
|
|
167
|
+
if (!this.started || !q || !this.pattern || !next.pattern) {
|
|
168
|
+
this.pending = null;
|
|
169
|
+
if (this.started && fade > 0 && this.pattern) this.onSwap?.(timeAt(this.lastEnd, this.anchor), fade);
|
|
170
|
+
this.install(next);
|
|
171
|
+
return pattern;
|
|
172
|
+
}
|
|
173
|
+
const k = this.lastEnd.div(q).ceil();
|
|
174
|
+
next.at = k.mul(q);
|
|
175
|
+
this.pending = next;
|
|
176
|
+
return pattern;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Cycle at which a waiting pattern takes over (null when none waits).
|
|
180
|
+
get swapAt() { return this.pending ? this.pending.at.toNumber() : null; }
|
|
181
|
+
|
|
182
|
+
setQuantize(quantize, crossfade) {
|
|
183
|
+
this.quantize = quantizeCycles(quantize);
|
|
184
|
+
if (crossfade !== undefined) this.crossfade = validFade(crossfade);
|
|
185
|
+
return this.quantize ? this.quantize.toNumber() : null;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
install({ pattern, layers, locate, explain }) {
|
|
189
|
+
// last good pattern per layer key (name#nth)
|
|
190
|
+
const good = new Map(this.layers.map((L) => [L.key, L.ok ? L.pattern : L.fallback]));
|
|
191
|
+
const nth = new Map();
|
|
192
|
+
this.pattern = pattern;
|
|
193
|
+
this.layers = !pattern ? [] : (layers ?? splitLayers(pattern)).map((L, index) => {
|
|
194
|
+
const name = L.name ?? `layer ${index + 1}`;
|
|
195
|
+
const key = `${name}#${nth.set(name, (nth.get(name) ?? 0) + 1).get(name)}`;
|
|
196
|
+
return { name, pattern: L.pattern, index, key, fallback: good.get(key) };
|
|
197
|
+
});
|
|
198
|
+
this.locate = locate;
|
|
199
|
+
this.explain = explain;
|
|
200
|
+
this.layerErrors.clear();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Queries every layer over [begin, end) into `out`; a layer that throws
|
|
204
|
+
// is reported (once per message) and the others keep playing.
|
|
205
|
+
queryLayers(layers, begin, end, a, out) {
|
|
206
|
+
for (const L of layers) {
|
|
207
|
+
const mark = out.length;
|
|
208
|
+
try {
|
|
209
|
+
queryTriggers(L.pattern, begin, end, a, out);
|
|
210
|
+
L.ok = true;
|
|
211
|
+
} catch (err) {
|
|
212
|
+
out.length = mark;
|
|
213
|
+
this.reportError(err, L, begin, layers.length, end);
|
|
214
|
+
try { if (L.fallback) queryTriggers(L.fallback, begin, end, a, out); } catch { out.length = mark; L.fallback = null; }
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return out;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
reportError(err, L, begin, count, end) {
|
|
221
|
+
this.errorCount++;
|
|
222
|
+
const message = String(err?.message ?? err);
|
|
223
|
+
const key = `${L.index}\u0000${message}`;
|
|
224
|
+
const seen = this.layerErrors.get(key);
|
|
225
|
+
if (seen) { seen.count++; return; }
|
|
226
|
+
let loc = null;
|
|
227
|
+
try { loc = this.locate?.(L.index, count) ?? null; } catch { loc = null; }
|
|
228
|
+
const info = {
|
|
229
|
+
layer: loc?.name ?? L.name, index: L.index, layers: count, message, cycle: begin.toNumber(), count: 1, code: 'layer-runtime', severity: 'error',
|
|
230
|
+
fallback: !!L.fallback, hint: `the layer ${L.fallback ? 'plays its last good version' : 'is silent'} until it is fixed`,
|
|
231
|
+
};
|
|
232
|
+
if (loc && loc.line !== undefined) Object.assign(info, { line: loc.line, column: loc.column, endLine: loc.endLine, endColumn: loc.endColumn });
|
|
233
|
+
try { const c = this.explain?.(err, () => L.pattern.queryArc(begin, end)); if (c) Object.assign(info, c); } catch { /* best effort */ }
|
|
234
|
+
this.layerErrors.set(key, info);
|
|
235
|
+
this.errors.add(message);
|
|
236
|
+
if (this.onError) {
|
|
237
|
+
try { this.onError(err, info); } catch (e) { this.log(`[riff] error handler failed: ${e?.message ?? e}`); }
|
|
238
|
+
} else this.log(describeLayerError(info));
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
setCps(cps) {
|
|
242
|
+
const n = validCps(cps);
|
|
243
|
+
if (this.started) this.pendingCps = n;
|
|
244
|
+
else this.cps = n;
|
|
245
|
+
return n;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Current cycle position as a number (0 when stopped); `delay` s earlier
|
|
249
|
+
// (the draw layer passes the output latency).
|
|
250
|
+
now(delay = 0) {
|
|
251
|
+
if (!this.started) return 0;
|
|
252
|
+
const a = this.anchor;
|
|
253
|
+
return a.cycle.toNumber() + (this.clock() - delay - a.time) * a.cps;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
start() {
|
|
257
|
+
if (this.started) return;
|
|
258
|
+
this.started = true;
|
|
259
|
+
this.anchor = { cycle: ZERO, time: this.clock() + this.latency, cps: this.cps };
|
|
260
|
+
this.lastEnd = ZERO;
|
|
261
|
+
this.ticker?.start(() => this.tick());
|
|
262
|
+
this.tick();
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
stop() {
|
|
266
|
+
if (!this.started) return;
|
|
267
|
+
this.started = false;
|
|
268
|
+
this.ticker?.stop();
|
|
269
|
+
if (this.pendingCps !== null) { this.cps = this.pendingCps; this.pendingCps = null; }
|
|
270
|
+
this.anchor = null;
|
|
271
|
+
this.lastEnd = ZERO;
|
|
272
|
+
if (this.pending) { this.install(this.pending); this.pending = null; }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
tick() {
|
|
276
|
+
if (!this.started) return;
|
|
277
|
+
if (this.pendingCps !== null) {
|
|
278
|
+
const at = this.lastEnd;
|
|
279
|
+
this.anchor = { cycle: at, time: timeAt(at, this.anchor), cps: this.pendingCps };
|
|
280
|
+
this.cps = this.pendingCps;
|
|
281
|
+
this.pendingCps = null;
|
|
282
|
+
}
|
|
283
|
+
const t = this.clock();
|
|
284
|
+
const a = this.anchor;
|
|
285
|
+
// Far behind (stalled thread, sleeping tab): skip to the present, say so.
|
|
286
|
+
if (timeAt(this.lastEnd, a) < t - this.grace) {
|
|
287
|
+
const resume = quantise(a.cycle.toNumber() + (t - a.time) * a.cps);
|
|
288
|
+
if (resume.compare(this.lastEnd) > 0) {
|
|
289
|
+
const lost = resume.sub(this.lastEnd).toNumber();
|
|
290
|
+
this.skipped += lost;
|
|
291
|
+
this.log(`[riff] scheduler fell ${(t - timeAt(this.lastEnd, a)).toFixed(2)} s behind; skipped ${lost.toFixed(3)} cycles`);
|
|
292
|
+
this.lastEnd = resume;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const end = quantise(a.cycle.toNumber() + (t + this.lookahead - a.time) * a.cps);
|
|
296
|
+
if (end.compare(this.lastEnd) <= 0) return;
|
|
297
|
+
const begin = this.lastEnd;
|
|
298
|
+
this.lastEnd = end;
|
|
299
|
+
if (!this.pattern) return;
|
|
300
|
+
const triggers = [];
|
|
301
|
+
const p = this.pending;
|
|
302
|
+
if (p && p.at.compare(end) < 0) {
|
|
303
|
+
// Quantised swap inside this window: old pattern up to the boundary,
|
|
304
|
+
// the new one from it.
|
|
305
|
+
if (p.at.compare(begin) > 0) this.queryLayers(this.layers, begin, p.at, a, triggers);
|
|
306
|
+
this.pending = null;
|
|
307
|
+
this.install(p);
|
|
308
|
+
if (p.fade > 0) this.onSwap?.(timeAt(p.at, a), p.fade);
|
|
309
|
+
if (this.pattern) this.queryLayers(this.layers, p.at.compare(begin) > 0 ? p.at : begin, end, a, triggers);
|
|
310
|
+
} else this.queryLayers(this.layers, begin, end, a, triggers);
|
|
311
|
+
triggers.sort((x, y) => x.time - y.time);
|
|
312
|
+
if (this.patternCps && triggers.length) this.applyPatternCps(triggers);
|
|
313
|
+
let late = 0, drop = 0;
|
|
314
|
+
const lim = this.lateLimit, pad = lim < Infinity ? 0.01 : 0;
|
|
315
|
+
for (const tr of triggers) {
|
|
316
|
+
if (tr.time < t) {
|
|
317
|
+
if (t - tr.time > lim) { drop++; continue; }
|
|
318
|
+
tr.late = t - tr.time; tr.time = t + pad; late++;
|
|
319
|
+
}
|
|
320
|
+
this.onTrigger(tr);
|
|
321
|
+
}
|
|
322
|
+
if (late || drop) {
|
|
323
|
+
this.lateCount += late;
|
|
324
|
+
this.dropCount += drop;
|
|
325
|
+
this.log(`[riff] ${late} event(s) played late, ${drop} dropped (tick was behind by up to ${(t - timeAt(begin, a)).toFixed(3)} s)`);
|
|
326
|
+
}
|
|
327
|
+
const c = Math.floor(end.toNumber());
|
|
328
|
+
if (this.onCycle && c > Math.floor(begin.toNumber())) this.onCycle(c + 1, this.pattern);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Ticker: calls fn every `interval` seconds. A Worker-driven timer is not
|
|
333
|
+
// throttled in background tabs; where a Worker cannot be made (node, CSP),
|
|
334
|
+
// a plain timer is used.
|
|
335
|
+
export function makeTicker(interval = 0.05) {
|
|
336
|
+
let worker = null;
|
|
337
|
+
let timer = null;
|
|
338
|
+
const ms = Math.max(1, Math.round(interval * 1000));
|
|
339
|
+
const plain = (fn) => { timer = setInterval(fn, ms); timer?.unref?.(); };
|
|
340
|
+
return {
|
|
341
|
+
start(fn) {
|
|
342
|
+
this.stop();
|
|
343
|
+
if (typeof Worker === 'function' && typeof Blob === 'function' && typeof URL?.createObjectURL === 'function') {
|
|
344
|
+
try {
|
|
345
|
+
const src = `let t=null;onmessage=(e)=>{clearInterval(t);if(e.data>0)t=setInterval(()=>postMessage(0),e.data)}`;
|
|
346
|
+
const url = URL.createObjectURL(new Blob([src], { type: 'text/javascript' }));
|
|
347
|
+
worker = new Worker(url);
|
|
348
|
+
URL.revokeObjectURL(url);
|
|
349
|
+
worker.onmessage = () => fn();
|
|
350
|
+
worker.onerror = () => { worker?.terminate(); worker = null; if (timer === null) plain(fn); };
|
|
351
|
+
worker.postMessage(ms);
|
|
352
|
+
return;
|
|
353
|
+
} catch { worker = null; }
|
|
354
|
+
}
|
|
355
|
+
plain(fn);
|
|
356
|
+
},
|
|
357
|
+
stop() {
|
|
358
|
+
if (worker) { worker.postMessage(0); worker.terminate(); worker = null; }
|
|
359
|
+
if (timer !== null) { clearInterval(timer); timer = null; }
|
|
360
|
+
},
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Offline trigger list: runs a Scheduler on a simulated clock that advances
|
|
365
|
+
// `interval` seconds per tick (the browser path, minus Web Audio).
|
|
366
|
+
// options: cps (0.5), cycles (4) or seconds, interval (0.05), lookahead,
|
|
367
|
+
// latency (0: cycle 0 at time 0), onTick(scheduler, time) for tempo changes,
|
|
368
|
+
// patternCps (see Scheduler).
|
|
369
|
+
export function renderTriggers(pattern, options = {}) {
|
|
370
|
+
const { cps = 0.5, interval = 0.05, lookahead = 0.2, latency = 0, onTick, patternCps = false } = options;
|
|
371
|
+
let clock = 0;
|
|
372
|
+
const out = [];
|
|
373
|
+
const s = new Scheduler({ now: () => clock, onTrigger: (tr) => out.push(tr), lookahead, latency, cps, log: () => {}, patternCps });
|
|
374
|
+
s.setPattern(pattern);
|
|
375
|
+
const seconds = options.seconds ?? (options.cycles ?? 4) / cps;
|
|
376
|
+
s.start();
|
|
377
|
+
while (clock + lookahead < seconds + latency) {
|
|
378
|
+
clock += interval;
|
|
379
|
+
onTick?.(s, clock);
|
|
380
|
+
s.tick();
|
|
381
|
+
}
|
|
382
|
+
return out.filter((tr) => tr.time < seconds + latency - 1e-9);
|
|
383
|
+
}
|