8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 1// How many orbits can this device play live?
2//
3// Almost all the cost is audio: the modal-synth instruments run on the single real-time audio
4// thread, and their load grows with the number of orbits (more notes → more ringing voices).
5// So, before the first play, we play the composition's actual instruments silently (into a muted
6// bus) for about a second at the note density the orbit count produces, and read the load the
7// synths report from the audio thread itself. That measures exactly what glitches, on this
8// device, and isn't affected by background-tab throttling. If the load is over BUDGET we try
9// fewer orbits. The answer is cached per device and settings.
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 11import { DEFAULTS } from "@modal-synth/engine/params.ts";
12import { PRESETS } from "@modal-synth/presets.ts";
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 13import type { Params } from "../../core/params.ts";
14import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 15import { parseModalPreset } from "../../instruments/modal.ts";
16import type { BenchNote, FromWorker, ToWorker } from "../../instruments/stream/protocol.ts";
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 17import { midiToFreq } from "../../music/scales.ts";
19// Synth load (share of real time) we accept on the audio thread. The synths' own measure excludes
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 20// the reverb, the hum, browser overhead, and what the page's own drawing and physics take from a
21// phone's CPU. A phone measured within 0.55 still glitched, so stay well below that.
22const BUDGET = 0.35;
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 23// With rendering ahead in workers (one per instrument, on other cores, buffered), each worker must
24// render comfortably faster than real time; the buffer absorbs momentary slowdowns.
25const BUDGET_STREAM = 0.6;
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 26const NOTES_PER_SIM_SECOND = 0.2; // crossings per orbit per simulated second (busy parts of the piece)
27const PLAY_S = 1.3; // how long the silent test plays
28const MEASURE_FROM = 0.5; // ignore the first part (voices filling up)
29const MAX_TRIES = 2;
31export interface CapacityResult {
32 cap: number; // orbits this device can play
33 tested: number; // the count asked for when this was measured
34 load: number; // measured synth load at the last count tried
35 at: number; // that count
36}
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 38function cacheKey(P: Params, sampleRate: number, slots: number, stream: boolean): string {
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 39 const sig = {
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 40 v: 5, // bump when the check itself (or the engine's speed) changes
41 stream,
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 42 sr: sampleRate,
43 speed: P.speed,
44 len: P.noteLength,
45 inst: Array.from({ length: slots }, (_, i) => P[`slot${i + 1}Instrument`]),
46 custom: P.modalCustom,
47 };
48 return `double-pendulum:capacity:02-orbits:${JSON.stringify(sig)}`;
49}
51function readCache(key: string): CapacityResult | null {
52 try {
53 const s = localStorage.getItem(key);
54 return s ? (JSON.parse(s) as CapacityResult) : null;
55 } catch {
56 return null;
57 }
58}
60function writeCache(key: string, r: CapacityResult) {
61 try {
62 localStorage.setItem(key, JSON.stringify(r));
63 } catch {
64 /* storage unavailable: we'll just measure again next time */
65 }
66}
68const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
70/** Play `n` orbits' worth of notes silently on the live context; returns the measured synth load. */
71async function measure(ctx: AudioContext, P: Params, n: number, slots: number): Promise<number> {
72 const mute = ctx.createGain();
73 mute.gain.value = 0;
74 mute.connect(ctx.destination); // connected so the audio thread renders it, but silent
75 const perSlot = new Array<number>(slots).fill(0);
76 for (let i = 0; i < n; i++) perSlot[i % slots]++;
77 const rate = (P.speed as number) * NOTES_PER_SIM_SECOND; // notes per second per orbit
78 const len = P.noteLength as number;
79 const insts = [];
80 for (let s = 0; s < slots; s++) {
81 if (!perSlot[s]) continue;
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 82 const inst = NOTE_INSTRUMENTS[P[`slot${s + 1}Instrument`] as string](ctx, mute, { custom: P.modalCustom as string, immediateRelease: true, effects: "none" });
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 83 insts.push({ inst, rate: rate * perSlot[s] });
84 }
85 try {
86 await Promise.all(insts.map((x) => x.inst.ready));
87 let seed = 12345;
88 const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
89 const t0 = ctx.currentTime + 0.05;
90 for (const { inst, rate: r } of insts) {
91 const note = (when: number) => inst.play({ when, freq: midiToFreq(50 + Math.floor(rnd() * 36)), velocity: 0.6, pan: 0, duration: len });
92 // start at the steady state: as many notes ringing as `rate × length` keeps going
93 const warm = Math.min(16, Math.round(r * len));
94 for (let k = 0; k < warm; k++) note(t0 + 0.002 * k);
95 for (let t = 0.05; t < PLAY_S; t += 1 / r) note(t0 + t);
96 }
97 // average the synths' reported load over the second part of the test
98 await sleep(MEASURE_FROM * 1000);
99 const samples: number[] = [];
100 const end = performance.now() + (PLAY_S - MEASURE_FROM) * 1000;
101 while (performance.now() < end) {
102 await sleep(100);
103 samples.push(insts.reduce((s, x) => s + (x.inst.load?.() ?? 0), 0));
104 }
105 return samples.length ? samples.reduce((a, b) => a + b, 0) / samples.length : 0;
106 } finally {
107 for (const x of insts) x.inst.dispose();
108 window.setTimeout(() => mute.disconnect(), 1200);
109 }
110}
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 112/** The modal-synth settings for an instrument slot (null: not a modal instrument). */
113function modalSound(P: Params, slot: number): Params | null {
114 const name = P[`slot${slot + 1}Instrument`] as string;
115 if (!name.startsWith("modal: ")) return null;
116 const p = name === "modal: custom" ? parseModalPreset(P.modalCustom as string) : PRESETS.find((x) => `modal: ${x.name}` === name)?.p;
117 return { ...DEFAULTS, ...(p ?? {}) };
118}
120/**
121 * Rendered-ahead check: every instrument's worker renders its share of `n` orbits' notes as fast
122 * as it can, all at once (as they would run). Returns the busiest worker's render time / audio time.
123 */
124async function measureWorkers(sampleRate: number, P: Params, n: number, slots: number): Promise<number> {
125 const perSlot = new Array<number>(slots).fill(0);
126 for (let i = 0; i < n; i++) perSlot[i % slots]++;
127 const rate = (P.speed as number) * NOTES_PER_SIM_SECOND;
128 const len = P.noteLength as number;
129 const SECONDS = 1.5, WARMUP = 0.5;
130 const jobs: Promise<number>[] = [];
131 for (let s = 0; s < slots; s++) {
132 const sound = perSlot[s] ? modalSound(P, s) : null;
133 if (!sound) continue;
134 const r = rate * perSlot[s];
135 let seed = 12345 + s;
136 const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
137 const notes: BenchNote[] = [];
138 const warm = Math.min(16, Math.round(r * len));
139 for (let k = 0; k < warm; k++) notes.push({ time: 0.002 * k, note: 50 + Math.floor(rnd() * 36), vel: 0.6, len });
140 for (let t = 0.05; t < SECONDS; t += 1 / r) notes.push({ time: t, note: 50 + Math.floor(rnd() * 36), vel: 0.6, len });
141 jobs.push(
142 new Promise<number>((resolve) => {
143 const w = new Worker(new URL("../../instruments/stream/renderWorker.ts", import.meta.url), { type: "module" });
144 w.onmessage = (e: MessageEvent<FromWorker>) => {
145 if (e.data.type === "bench") {
146 resolve(e.data.load);
147 w.terminate();
148 }
149 };
150 const m: ToWorker = { type: "bench", sampleRate, params: sound, notes, seconds: SECONDS, warmup: WARMUP };
151 w.postMessage(m);
152 }),
153 );
154 }
155 const loads = await Promise.all(jobs);
156 return loads.length ? Math.max(...loads) : 0;
157}
160 * Largest orbit count ≤ `wanted` this device can play live (cached when the cache covers `wanted`).
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 161 * `stream`: instruments render ahead in workers (measured that way, with its own budget).
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 163export async function orbitCapacity(ctx: AudioContext, P: Params, wanted: number, slots: number, stream = false): Promise<CapacityResult> {
164 const key = cacheKey(P, ctx.sampleRate, slots, stream);
165 const budget = stream ? BUDGET_STREAM : BUDGET;
166 const run = (n: number) => (stream ? measureWorkers(ctx.sampleRate, P, n, slots) : measure(ctx, P, n, slots));
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 167 const cached = readCache(key);
168 if (cached && (cached.cap < cached.tested || cached.tested >= wanted)) return { ...cached, cap: Math.min(cached.cap, wanted) };
170 let n = wanted;
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 173 for (let tries = 1; load > budget && n > 1 && tries < MAX_TRIES; tries++) {
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 174 // cost grows a little less than linearly with orbits (voices saturate), so step down generously
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 175 n = Math.max(1, Math.min(n - 1, Math.floor(n * Math.pow(budget / load, 1.3))));
176 load = await run(n);
178 }
216afddorbits: render instruments ahead in Web WorkersJeremy Magland 179 if (load > budget) n = Math.max(1, Math.min(n - 1, Math.floor(n * Math.pow(budget / load, 1.3)))); // estimate
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 180 const result: CapacityResult = { cap: n, tested: wanted, load, at };
181 writeCache(key, result);
182 return result;
183}