@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,394 @@
|
|
|
1
|
+
// Audio public API (plan 4.1, 4.5; spec/integration.md 1-5): one lazily made
|
|
2
|
+
// default AudioContext, scheduler and engine for the page-level functions;
|
|
3
|
+
// createAudio() makes further independent players (docs/improvements.md 29). `initStrudel` and
|
|
4
|
+
// `evaluate` follow SAAI's call shape; `play(pattern)` / `pattern.play()` and
|
|
5
|
+
// `hush()` / `stop()` are the plain-JS way in.
|
|
6
|
+
import { Pattern, silence } from '../pattern.js';
|
|
7
|
+
import { Scheduler, makeTicker, describeLayerError } from './clock.js';
|
|
8
|
+
import { AudioEngine } from './engine.js';
|
|
9
|
+
import { repl, hush, callMessage } from '../evaluate.js';
|
|
10
|
+
import { sampleSource as defaultSampleSource, getSampleBank, configureSamples } from './samples.js';
|
|
11
|
+
import { addScope, scopeEntries } from '../scope.js';
|
|
12
|
+
import { outline } from '../outline.js';
|
|
13
|
+
import { unlockContext } from './unlock.js';
|
|
14
|
+
import { setRandomMode, setSeed } from '../random.js';
|
|
15
|
+
import { setDrawEnvironment, commitPainters, resetPainters, cleanupDraw } from '../draw.js';
|
|
16
|
+
|
|
17
|
+
const IDENT = /^[A-Za-z_$][\w$]*$/;
|
|
18
|
+
|
|
19
|
+
let ctx = null;
|
|
20
|
+
let engine = null;
|
|
21
|
+
let scheduler = null;
|
|
22
|
+
let sampleSource = defaultSampleSource;
|
|
23
|
+
let hooked = false;
|
|
24
|
+
const settings = { latencyHint: null, sampleRate: undefined, maxVoices: null, sampleBudget: null, lateLimit: 0.1, lookahead: 0.2, interval: 0.05, ticker: null, log: console.warn, limiter: true, onError: null,
|
|
25
|
+
grace: 0.5, sampleDeadline: 0.5, patternCps: false, warnUnused: true, preload: 2 };
|
|
26
|
+
|
|
27
|
+
// Phones (UA-CH `mobile`, else a coarse pointer on a small screen) get a
|
|
28
|
+
// larger buffer, 48 voices and a 64 MB sample cache; desktop 'interactive',
|
|
29
|
+
// 128 and 192 MB. Explicit options win (operator decision 18 Nov 2026).
|
|
30
|
+
export function isMobile(nav = globalThis.navigator, win = globalThis) {
|
|
31
|
+
const m = nav?.userAgentData?.mobile;
|
|
32
|
+
if (typeof m === 'boolean') return m;
|
|
33
|
+
const sc = win?.screen;
|
|
34
|
+
return !!(win?.matchMedia?.('(pointer: coarse)')?.matches && sc && Math.min(sc.width, sc.height) < 600);
|
|
35
|
+
}
|
|
36
|
+
export const platformDefaults = (mobile = isMobile()) => (mobile
|
|
37
|
+
? { latencyHint: 'playback', maxVoices: 48, sampleBudget: 64 << 20 }
|
|
38
|
+
: { latencyHint: 'interactive', maxVoices: 128, sampleBudget: 192 << 20 });
|
|
39
|
+
const resolved = (o) => {
|
|
40
|
+
const d = platformDefaults();
|
|
41
|
+
return { ...o, latencyHint: o.latencyHint ?? d.latencyHint, maxVoices: o.maxVoices ?? d.maxVoices, sampleBudget: o.sampleBudget ?? d.sampleBudget };
|
|
42
|
+
};
|
|
43
|
+
// Seconds between the audio clock and the speaker (visual sync).
|
|
44
|
+
export const outputDelay = (c) => +(c?.outputLatency || c?.baseLatency || 0) || 0;
|
|
45
|
+
|
|
46
|
+
function defaultFactory({ latencyHint, sampleRate }) {
|
|
47
|
+
const C = globalThis.AudioContext ?? globalThis.webkitAudioContext;
|
|
48
|
+
if (typeof C !== 'function') throw new Error('Web Audio is not available here');
|
|
49
|
+
return new C(sampleRate ? { latencyHint, sampleRate } : { latencyHint });
|
|
50
|
+
}
|
|
51
|
+
let factory = defaultFactory;
|
|
52
|
+
|
|
53
|
+
// For tests and hosts that bring their own context (or an OfflineAudioContext).
|
|
54
|
+
export function setAudioContextFactory(fn) { factory = fn ?? defaultFactory; }
|
|
55
|
+
|
|
56
|
+
// initAudio(options): latencyHint, sampleRate, maxVoices (voice cap, 128;
|
|
57
|
+
// phones see platformDefaults), sampleBudget (bytes), lateLimit (s, 0.1),
|
|
58
|
+
// lookahead (s), interval (tick, s), ticker, log, grace (s a late tick still
|
|
59
|
+
// plays, 0.5), sampleDeadline (s a late-decoded sample still plays, 0.5),
|
|
60
|
+
// preload (cycles fetched ahead on play, 2; 0 = off), patternCps (opt-in:
|
|
61
|
+
// a `cps` control changes the tempo at its event), warnUnused (log controls
|
|
62
|
+
// without effect, true), limiter (master limiter,
|
|
63
|
+
// default true; plan 8.4), onError(err, info) (plan 8.3, see setErrorHandler);
|
|
64
|
+
// random ('default' | 'riff') and seed set the random mode and global seed (plan 8.9).
|
|
65
|
+
// Takes effect for parts not made yet (limiter and onError also at once);
|
|
66
|
+
// call before the first play to change the context options.
|
|
67
|
+
export function initAudio(options = {}) {
|
|
68
|
+
for (const k of Object.keys(settings)) if (options[k] !== undefined) settings[k] = options[k];
|
|
69
|
+
if (options.limiter !== undefined) engine?.setLimiter(options.limiter);
|
|
70
|
+
if (options.random !== undefined) setRandomMode(options.random); // plan 8.9
|
|
71
|
+
if (options.seed !== undefined) setSeed(options.seed);
|
|
72
|
+
return getAudioContext();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Resume a context the page suspended while hidden (visibilitychange, and
|
|
76
|
+
// pageshow after the back/forward cache); a context the host suspended itself
|
|
77
|
+
// (SAAI's pause) stays suspended. iOS reports 'interrupted' after a call or
|
|
78
|
+
// another app took the audio; that is resumed the same way.
|
|
79
|
+
function watchVisibility(c) {
|
|
80
|
+
const doc = globalThis.document;
|
|
81
|
+
const idle = () => c.state !== 'running' && c.state !== 'closed';
|
|
82
|
+
if (doc?.addEventListener) {
|
|
83
|
+
let wasRunning = false;
|
|
84
|
+
const back = () => { if (wasRunning && idle()) c.resume?.().catch?.(() => {}); };
|
|
85
|
+
doc.addEventListener('visibilitychange', () => {
|
|
86
|
+
if (doc.visibilityState === 'hidden') wasRunning = c.state === 'running' || wasRunning && c.state === 'interrupted';
|
|
87
|
+
else back();
|
|
88
|
+
});
|
|
89
|
+
globalThis.addEventListener?.('pageshow', back);
|
|
90
|
+
globalThis.addEventListener?.('pagehide', () => { wasRunning = c.state === 'running'; });
|
|
91
|
+
}
|
|
92
|
+
// A gesture while RIFF plays but the context is not running (made before
|
|
93
|
+
// any gesture, or interrupted on iOS) unlocks it. Stays installed: iOS can
|
|
94
|
+
// interrupt again later.
|
|
95
|
+
const onGesture = () => { if (idle() && scheduler?.started) unlockAudio(); };
|
|
96
|
+
for (const e of GESTURES) globalThis.addEventListener?.(e, onGesture, true);
|
|
97
|
+
}
|
|
98
|
+
const GESTURES = ['pointerdown', 'touchend', 'click', 'keydown'];
|
|
99
|
+
|
|
100
|
+
// unlockAudio(options) → Promise<state> (plan 8.10): makes the context if
|
|
101
|
+
// needed and starts it. Synchronous up to the promise, so hosts call it as
|
|
102
|
+
// the first statement of a tap/click handler, before any await (iOS and
|
|
103
|
+
// Android drop the gesture after an await). options.htmlAudio: 'auto' (iOS
|
|
104
|
+
// mute-switch workaround on iOS only), true, false.
|
|
105
|
+
export function unlockAudio(options = {}) {
|
|
106
|
+
return unlockContext(getAudioContext(), { log: settings.log, ...options });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// The one AudioContext RIFF plays through (same object every call).
|
|
110
|
+
export function getAudioContext() {
|
|
111
|
+
if (!ctx || ctx.state === 'closed') {
|
|
112
|
+
ctx = factory(resolved(settings));
|
|
113
|
+
engine = null;
|
|
114
|
+
watchVisibility(ctx);
|
|
115
|
+
}
|
|
116
|
+
return ctx;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function getEngine() {
|
|
120
|
+
const c = getAudioContext();
|
|
121
|
+
if (!engine || engine.ctx !== c) {
|
|
122
|
+
engine = new AudioEngine(c, { maxVoices: resolved(settings).maxVoices, log: settings.log, sampleSource, limiter: settings.limiter,
|
|
123
|
+
sampleDeadline: settings.sampleDeadline, warnUnused: settings.warnUnused });
|
|
124
|
+
connectSamples(c);
|
|
125
|
+
}
|
|
126
|
+
return engine;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// The default sample bank decodes with our context; made on first use.
|
|
130
|
+
let banking = null;
|
|
131
|
+
function connectSamples(c) {
|
|
132
|
+
const bank = getSampleBank();
|
|
133
|
+
if (bank) { bank.setAudioContext(c); return Promise.resolve(bank); }
|
|
134
|
+
banking ??= configureSamples({ audioContext: c, budgetBytes: resolved(settings).sampleBudget, warn: (m) => settings.log(`[riff] ${m}`) })
|
|
135
|
+
.catch((e) => settings.log(`[riff] sample loader: ${e?.message ?? e}`));
|
|
136
|
+
return banking;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// The sample loader (plan 4.2) installs { getBuffer(request) } here.
|
|
140
|
+
// Default: the sample bank of src/audio/samples.js.
|
|
141
|
+
export function setSampleSource(source) {
|
|
142
|
+
sampleSource = source ?? defaultSampleSource;
|
|
143
|
+
if (engine) engine.sampleSource = sampleSource;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function getScheduler() {
|
|
147
|
+
if (!scheduler) {
|
|
148
|
+
scheduler = new Scheduler({
|
|
149
|
+
now: () => getAudioContext().currentTime,
|
|
150
|
+
onTrigger: (tr) => getEngine().playTrigger(tr),
|
|
151
|
+
ticker: settings.ticker ?? makeTicker(settings.interval),
|
|
152
|
+
lookahead: settings.lookahead,
|
|
153
|
+
grace: settings.grace,
|
|
154
|
+
lateLimit: settings.lateLimit,
|
|
155
|
+
patternCps: settings.patternCps,
|
|
156
|
+
cps: repl.state.cps,
|
|
157
|
+
log: (m) => settings.log(m),
|
|
158
|
+
onError: reportPlayError,
|
|
159
|
+
onSwap: (time, fade) => { engine?.fadeOut(time, fade); },
|
|
160
|
+
onCycle: (c, p) => { if (settings.preload > 0) preloadAhead(sampleSource, p, 1, settings.log, c); },
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
return scheduler;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Plan 8.3: a layer that throws while playing is reported once through the
|
|
167
|
+
// handler (default: the log) and kept in repl.state.playError.
|
|
168
|
+
function reportPlayError(err, info) {
|
|
169
|
+
repl.state.playError = { ...info, error: err };
|
|
170
|
+
if (settings.onError) settings.onError(err, info);
|
|
171
|
+
else settings.log(describeLayerError(info));
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// setErrorHandler(fn(err, info)) for errors raised while playing; null
|
|
175
|
+
// restores logging. info: { layer, index, layers, message, cycle, line?,
|
|
176
|
+
// column?, endLine?, endColumn?, code, severity, hint, fallback, call? } (src/audio/clock.js).
|
|
177
|
+
export function setErrorHandler(fn) {
|
|
178
|
+
settings.onError = typeof fn === 'function' ? fn : null;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// setQuantize('cycle' | 'bar' | cycles | null, { crossfade }) for every later
|
|
182
|
+
// evaluate/play (plan 8.5); returns the step in cycles or null.
|
|
183
|
+
export function setQuantize(quantize, { crossfade } = {}) {
|
|
184
|
+
return getScheduler().setQuantize(quantize, crossfade);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Source location of layer \`index\` of the evaluated \`code\`, looked up only
|
|
188
|
+
// when an error is reported: \`$:\`/named labels by name and order, members
|
|
189
|
+
// of a final stack(...) by position.
|
|
190
|
+
function layerLocator(code, layers) {
|
|
191
|
+
let ol = null;
|
|
192
|
+
const pick = (o) => (o ? { name: o.name, line: o.line, column: o.column, endLine: o.endLine, endColumn: o.endColumn } : null);
|
|
193
|
+
return (index, count) => {
|
|
194
|
+
ol ??= outline(code);
|
|
195
|
+
if (layers) {
|
|
196
|
+
const L = layers[index];
|
|
197
|
+
if (!L) return null;
|
|
198
|
+
const labels = ol.filter((o) => o.kind === 'label');
|
|
199
|
+
const hit = L.key === null || L.key === undefined
|
|
200
|
+
? labels.filter((o) => o.name === '$' || o.name === '_$')[L.nth]
|
|
201
|
+
: labels.filter((o) => o.name === L.key).at(-1);
|
|
202
|
+
return hit ? { ...pick(hit), name: L.name } : null;
|
|
203
|
+
}
|
|
204
|
+
const played = ol.filter((o) => o.kind === 'expression' && o.played).at(-1);
|
|
205
|
+
if (count === 1) return played ? { ...pick(played), name: 'program' } : null;
|
|
206
|
+
return pick(played?.children?.[index]);
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// The analyser for `id` (spec/integration.md 5): a tap, never connected to
|
|
211
|
+
// the output; voices with `.analyze(id)` feed it.
|
|
212
|
+
export const getAnalyserById = (id) => getEngine().analyser(id);
|
|
213
|
+
|
|
214
|
+
function resume() {
|
|
215
|
+
const c = getAudioContext();
|
|
216
|
+
if (c.state === 'suspended' && typeof c.resume === 'function') {
|
|
217
|
+
return Promise.resolve(c.resume()).catch((e) => settings.log(`[riff] could not resume audio: ${e?.message ?? e}`));
|
|
218
|
+
}
|
|
219
|
+
return Promise.resolve();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Hook the default REPL: a successful evaluate plays, hush stops, setcps in
|
|
223
|
+
// user code reaches the scheduler.
|
|
224
|
+
function hookRepl() {
|
|
225
|
+
if (hooked) return;
|
|
226
|
+
hooked = true;
|
|
227
|
+
Object.assign(repl.options, {
|
|
228
|
+
onEvaluate: () => resetPainters(),
|
|
229
|
+
onPattern: (pattern, meta) => { play(pattern, meta); },
|
|
230
|
+
onHush: () => { stopAudio(); cleanupDraw(false); },
|
|
231
|
+
onCps: (cps) => { getScheduler().setCps(cps); },
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// play(pattern, options): make `pattern` the playing pattern and start (or
|
|
236
|
+
// hot-swap). options: quantize, crossfade (plan 8.5); code and layers (from
|
|
237
|
+
// evaluate) name the layers in error reports.
|
|
238
|
+
export function play(pattern, options = {}) {
|
|
239
|
+
hookRepl();
|
|
240
|
+
getEngine();
|
|
241
|
+
resume();
|
|
242
|
+
const s = getScheduler();
|
|
243
|
+
const { quantize, crossfade, layers, code, explain } = options;
|
|
244
|
+
s.setPattern(pattern, {
|
|
245
|
+
quantize, crossfade,
|
|
246
|
+
explain: code && explain ? (e, run) => { const c = explain(e, run); return c && { call: c.name, ...callMessage(code, c.from, c.to, String(e?.message ?? e)) }; } : null,
|
|
247
|
+
layers: layers?.map((L) => ({ name: L.name, pattern: L.pattern })),
|
|
248
|
+
locate: code ? layerLocator(code, layers) : null,
|
|
249
|
+
});
|
|
250
|
+
s.start();
|
|
251
|
+
preloadAhead(sampleSource, pattern, settings.preload, settings.log, Math.floor(s.now()));
|
|
252
|
+
commitPainters();
|
|
253
|
+
return pattern;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Fetch the sounds `pattern` plays in the next `cycles` cycles, so first hits
|
|
257
|
+
// are not lost to loading (docs/improvements.md 5). Never throws.
|
|
258
|
+
function preloadAhead(source, pattern, cycles, log, from) {
|
|
259
|
+
const n = Number(cycles);
|
|
260
|
+
if (!pattern || typeof source?.preload !== 'function' || !(n > 0)) return Promise.resolve(0);
|
|
261
|
+
try {
|
|
262
|
+
return Promise.resolve(source.preload(pattern, n, Math.max(0, from))).catch((e) => { log(`[riff] preload: ${e?.message ?? e}`); return 0; });
|
|
263
|
+
} catch (e) { log(`[riff] preload: ${e?.message ?? e}`); return Promise.resolve(0); }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// closeAudio() → Promise: stop, close the AudioContext and forget it; the
|
|
267
|
+
// next play or getAudioContext() makes a fresh one with the current
|
|
268
|
+
// initAudio options (docs/improvements.md 31).
|
|
269
|
+
export async function closeAudio() {
|
|
270
|
+
stopAudio();
|
|
271
|
+
const c = ctx;
|
|
272
|
+
ctx = null;
|
|
273
|
+
engine = null;
|
|
274
|
+
if (c && c.state !== 'closed' && typeof c.close === 'function') {
|
|
275
|
+
try { await c.close(); } catch (e) { settings.log(`[riff] could not close audio: ${e?.message ?? e}`); }
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// createAudio(options) → an independent player with its own AudioContext,
|
|
280
|
+
// engine, scheduler and voices (docs/improvements.md 29). Nothing is shared
|
|
281
|
+
// with the page-level play()/hush() or with other players.
|
|
282
|
+
// options: audioContext (else made from latencyHint/sampleRate), sampleSource
|
|
283
|
+
// (default: the default sample bank), cps (0.5), and the initAudio options
|
|
284
|
+
// maxVoices, limiter, lookahead, interval, ticker, grace, sampleDeadline,
|
|
285
|
+
// preload, patternCps, warnUnused, log, onError, quantize, crossfade.
|
|
286
|
+
// → { audioContext, engine, scheduler, play(pattern, opts), stop(),
|
|
287
|
+
// setcps(cps), close() }
|
|
288
|
+
export function createAudio(options = {}) {
|
|
289
|
+
const o = resolved({ ...settings, onError: null, ...options });
|
|
290
|
+
const c = options.audioContext ?? factory(o);
|
|
291
|
+
const engine = new AudioEngine(c, { maxVoices: o.maxVoices, log: o.log, sampleSource: o.sampleSource ?? sampleSource, limiter: o.limiter,
|
|
292
|
+
sampleDeadline: o.sampleDeadline, warnUnused: o.warnUnused });
|
|
293
|
+
const scheduler = new Scheduler({
|
|
294
|
+
now: () => c.currentTime,
|
|
295
|
+
onTrigger: (tr) => engine.playTrigger(tr),
|
|
296
|
+
ticker: o.ticker ?? makeTicker(o.interval),
|
|
297
|
+
lookahead: o.lookahead, grace: o.grace, lateLimit: o.lateLimit, patternCps: o.patternCps, cps: o.cps ?? 0.5,
|
|
298
|
+
log: (m) => o.log(m), onError: o.onError, quantize: o.quantize, crossfade: o.crossfade,
|
|
299
|
+
onSwap: (time, fade) => { engine.fadeOut(time, fade); },
|
|
300
|
+
onCycle: (c, p) => { if (o.preload > 0) preloadAhead(engine.sampleSource, p, 1, o.log, c); },
|
|
301
|
+
});
|
|
302
|
+
return {
|
|
303
|
+
audioContext: c, engine, scheduler,
|
|
304
|
+
play(pattern, opts = {}) {
|
|
305
|
+
if (c.state === 'suspended' && typeof c.resume === 'function') Promise.resolve(c.resume()).catch(() => {});
|
|
306
|
+
scheduler.setPattern(pattern, opts);
|
|
307
|
+
scheduler.start();
|
|
308
|
+
preloadAhead(engine.sampleSource, pattern, o.preload, o.log, Math.floor(scheduler.now()));
|
|
309
|
+
return pattern;
|
|
310
|
+
},
|
|
311
|
+
stop() { scheduler.stop(); engine.silence(); },
|
|
312
|
+
setcps: (cps) => scheduler.setCps(cps),
|
|
313
|
+
async close() {
|
|
314
|
+
scheduler.stop();
|
|
315
|
+
engine.silence();
|
|
316
|
+
if (c.state !== 'closed' && typeof c.close === 'function') await c.close();
|
|
317
|
+
},
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// The draw layer reads the scheduler's clock and pattern and our analysers
|
|
322
|
+
// (one source of truth for sound and visuals, docs/improvements.md 27).
|
|
323
|
+
setDrawEnvironment({
|
|
324
|
+
now: () => (scheduler ? scheduler.now(outputDelay(ctx)) : 0),
|
|
325
|
+
pattern: () => scheduler?.pattern ?? null,
|
|
326
|
+
analyser: (id) => (id === undefined ? mixAnalyser() : getAnalyserById(id)),
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
// The analyser behind a scope or spectrum whose pattern names none: a tap on
|
|
330
|
+
// the master bus (not on the destination path; the sound does not change).
|
|
331
|
+
const tapped = new WeakSet();
|
|
332
|
+
function mixAnalyser() {
|
|
333
|
+
const e = getEngine();
|
|
334
|
+
const a = e.analyser('__riff_mix');
|
|
335
|
+
if (!tapped.has(e.master)) { e.master.connect(a); tapped.add(e.master); }
|
|
336
|
+
return a;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function stopAudio() {
|
|
340
|
+
scheduler?.stop();
|
|
341
|
+
engine?.silence();
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// hush() through the REPL (state.playing = false) and the audio.
|
|
345
|
+
export function stop() {
|
|
346
|
+
hookRepl();
|
|
347
|
+
repl.hush();
|
|
348
|
+
return silence;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
export function setcps(cps) {
|
|
352
|
+
const n = getScheduler().setCps(cps);
|
|
353
|
+
repl.state.cps = n;
|
|
354
|
+
return silence;
|
|
355
|
+
}
|
|
356
|
+
export const setcpm = (cpm) => setcps(Number(cpm) / 60);
|
|
357
|
+
|
|
358
|
+
Object.defineProperty(Pattern.prototype, 'play', {
|
|
359
|
+
value: function playMethod() { return play(this); },
|
|
360
|
+
writable: true, configurable: true,
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
// initStrudel(options) → REPL object (spec/integration.md 1).
|
|
364
|
+
// options.prebake: async function run (and awaited) once; failures logged.
|
|
365
|
+
// Other options go to initAudio. Drawing needs no option: draw methods in
|
|
366
|
+
// evaluated code paint from the scheduler's clock (src/draw.js), and the
|
|
367
|
+
// draw API (Framer, cleanupDraw, getDrawContext) is on globalThis too.
|
|
368
|
+
export async function initStrudel(options = {}) {
|
|
369
|
+
initAudio(options);
|
|
370
|
+
hookRepl();
|
|
371
|
+
const scope = {};
|
|
372
|
+
Object.assign(scope, scopeEntries());
|
|
373
|
+
Object.assign(scope, { setcps, setcpm, hush, silence });
|
|
374
|
+
for (const [k, v] of Object.entries(scope)) {
|
|
375
|
+
if (!IDENT.test(k)) continue;
|
|
376
|
+
try { globalThis[k] = v; } catch { /* read-only global */ }
|
|
377
|
+
}
|
|
378
|
+
try { await connectSamples(getEngine().ctx); } catch (e) { settings.log(`[riff] audio unavailable: ${e?.message ?? e}`); }
|
|
379
|
+
if (typeof options.prebake === 'function') {
|
|
380
|
+
try { await options.prebake(); } catch (e) { settings.log(`[riff] prebake failed: ${e?.message ?? e}`); }
|
|
381
|
+
}
|
|
382
|
+
const s = getScheduler();
|
|
383
|
+
return {
|
|
384
|
+
scheduler: s,
|
|
385
|
+
state: repl.state,
|
|
386
|
+
evaluate: (code, o) => repl.evaluate(code, o),
|
|
387
|
+
hush: () => repl.hush(),
|
|
388
|
+
setcps,
|
|
389
|
+
setcpm,
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// Names for user code (src/scope.js).
|
|
394
|
+
addScope({ closeAudio, createAudio, getAnalyserById, getAudioContext, getEngine, getScheduler, initAudio, initStrudel, play, setAudioContextFactory, setErrorHandler, setQuantize, setSampleSource, setcpm, setcps, stop, unlockAudio });
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Offline rendering (plan 8.11, docs/improvements.md 37): a program or a
|
|
2
|
+
// pattern → its trigger list and, where an OfflineAudioContext exists, the
|
|
3
|
+
// rendered audio. Uses its own REPL, engine and clock, so it can run beside
|
|
4
|
+
// live playback and never touches the page-level player.
|
|
5
|
+
import { Pattern, isPattern } from '../pattern.js';
|
|
6
|
+
import { createRepl } from '../evaluate.js';
|
|
7
|
+
import { DRAW_METHODS } from '../draw.js';
|
|
8
|
+
import { renderTriggers } from './clock.js';
|
|
9
|
+
import { AudioEngine } from './engine.js';
|
|
10
|
+
import { sampleSource as defaultSampleSource, getSampleBank } from './samples.js';
|
|
11
|
+
import { addScope } from '../scope.js';
|
|
12
|
+
|
|
13
|
+
const offlineClass = () => globalThis.OfflineAudioContext ?? globalThis.webkitOfflineAudioContext;
|
|
14
|
+
|
|
15
|
+
// Evaluate `code` with play and draw methods turned into no-ops; → { pattern, cps }.
|
|
16
|
+
async function evaluateQuietly(code) {
|
|
17
|
+
let cps;
|
|
18
|
+
const swapped = ['play', ...DRAW_METHODS, ...DRAW_METHODS.map((n) => `_${n}`)]
|
|
19
|
+
.map((n) => [n, Object.getOwnPropertyDescriptor(Pattern.prototype, n)]);
|
|
20
|
+
for (const [n] of swapped) Object.defineProperty(Pattern.prototype, n, { value: function () { return this; }, writable: true, configurable: true });
|
|
21
|
+
const noop = () => undefined;
|
|
22
|
+
const r = createRepl({ onCps: (c) => { cps = c; }, onError: noop });
|
|
23
|
+
try {
|
|
24
|
+
const pattern = await r.evaluate(code, {
|
|
25
|
+
throwOnError: true,
|
|
26
|
+
scope: { play: (p) => p, stop: noop, hush: noop, initStrudel: async () => undefined, initAudio: noop, evaluate: async () => undefined },
|
|
27
|
+
});
|
|
28
|
+
return { pattern, cps };
|
|
29
|
+
} finally {
|
|
30
|
+
for (const [n, d] of swapped) { if (d) Object.defineProperty(Pattern.prototype, n, d); else delete Pattern.prototype[n]; }
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// renderOffline(codeOrPattern, options) → Promise<{ events, buffer, cps,
|
|
35
|
+
// seconds, sampleRate }>
|
|
36
|
+
// options: cycles (4), cps (else the program's setcps, else 0.5),
|
|
37
|
+
// sampleRate (44100), channels (2), tail (s of release/reverb after the
|
|
38
|
+
// last cycle, 1), OfflineAudioContext (class; default the global one),
|
|
39
|
+
// sampleSource (default: the default sample bank), maxVoices, limiter,
|
|
40
|
+
// patternCps, log.
|
|
41
|
+
// events: [{ time, duration, cycle, cps, value }] in time order (cycle 0 at
|
|
42
|
+
// time 0). buffer: the rendered AudioBuffer, or null where no
|
|
43
|
+
// OfflineAudioContext exists (node). Evaluation errors reject.
|
|
44
|
+
export async function renderOffline(code, options = {}) {
|
|
45
|
+
const { cycles = 4, sampleRate = 44100, channels = 2, tail = 1, maxVoices, limiter = true, patternCps = false, log = console.warn } = options;
|
|
46
|
+
let pattern = code;
|
|
47
|
+
let cps = options.cps;
|
|
48
|
+
if (!isPattern(code)) {
|
|
49
|
+
const r = await evaluateQuietly(String(code ?? ''));
|
|
50
|
+
pattern = r.pattern;
|
|
51
|
+
cps ??= r.cps;
|
|
52
|
+
}
|
|
53
|
+
cps = Number(cps ?? 0.5);
|
|
54
|
+
if (!Number.isFinite(cps) || cps <= 0) throw new RangeError(`cps must be a positive number, got ${cps}`);
|
|
55
|
+
const triggers = renderTriggers(pattern, { cps, cycles, patternCps });
|
|
56
|
+
const seconds = cycles / cps; // without patternCps; with it, the last trigger bounds the length
|
|
57
|
+
const end = triggers.reduce((m, t) => Math.max(m, t.time + t.duration), seconds);
|
|
58
|
+
const events = triggers.map((t) => ({ time: t.time, duration: t.duration, cycle: t.cycle, cps: t.cps, value: t.value }));
|
|
59
|
+
const C = options.OfflineAudioContext ?? offlineClass();
|
|
60
|
+
if (typeof C !== 'function') return { events, buffer: null, cps, seconds: end, sampleRate };
|
|
61
|
+
const length = Math.max(1, Math.ceil((end + Math.max(0, tail)) * sampleRate));
|
|
62
|
+
const ctx = new C(channels, length, sampleRate);
|
|
63
|
+
const source = options.sampleSource ?? defaultSampleSource;
|
|
64
|
+
const bank = getSampleBank();
|
|
65
|
+
if (source === defaultSampleSource && bank && !bank.hasAudioContext()) bank.setAudioContext(ctx); // decode only
|
|
66
|
+
const engine = new AudioEngine(ctx, { maxVoices, limiter, log, sampleSource: source, sampleDeadline: Infinity });
|
|
67
|
+
await Promise.all(triggers.map((t) => engine.playTrigger(t)));
|
|
68
|
+
const buffer = await ctx.startRendering();
|
|
69
|
+
return { events, buffer, cps, seconds: end, sampleRate };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Names for user code (src/scope.js).
|
|
73
|
+
addScope({ renderOffline });
|