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.
11import type { Params } from "../../core/params.ts";
12import { NOTE_INSTRUMENTS } from "../../instruments/index.ts";
13import { midiToFreq } from "../../music/scales.ts";
15// 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 16// the reverb, the hum, browser overhead, and what the page's own drawing and physics take from a
17// phone's CPU. A phone measured within 0.55 still glitched, so stay well below that.
18const BUDGET = 0.35;
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 19const NOTES_PER_SIM_SECOND = 0.2; // crossings per orbit per simulated second (busy parts of the piece)
20const PLAY_S = 1.3; // how long the silent test plays
21const MEASURE_FROM = 0.5; // ignore the first part (voices filling up)
22const MAX_TRIES = 2;
24export interface CapacityResult {
25 cap: number; // orbits this device can play
26 tested: number; // the count asked for when this was measured
27 load: number; // measured synth load at the last count tried
28 at: number; // that count
29}
31function cacheKey(P: Params, sampleRate: number, slots: number): string {
32 const sig = {
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 33 v: 4, // bump when the check itself (or the engine's speed) changes
8a22646orbits: limit the orbit count to what the device can play liveJeremy Magland 34 sr: sampleRate,
35 speed: P.speed,
36 len: P.noteLength,
37 inst: Array.from({ length: slots }, (_, i) => P[`slot${i + 1}Instrument`]),
38 custom: P.modalCustom,
39 };
40 return `double-pendulum:capacity:02-orbits:${JSON.stringify(sig)}`;
41}
43function readCache(key: string): CapacityResult | null {
44 try {
45 const s = localStorage.getItem(key);
46 return s ? (JSON.parse(s) as CapacityResult) : null;
47 } catch {
48 return null;
49 }
50}
52function writeCache(key: string, r: CapacityResult) {
53 try {
54 localStorage.setItem(key, JSON.stringify(r));
55 } catch {
56 /* storage unavailable: we'll just measure again next time */
57 }
58}
60const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
62/** Play `n` orbits' worth of notes silently on the live context; returns the measured synth load. */
63async function measure(ctx: AudioContext, P: Params, n: number, slots: number): Promise<number> {
64 const mute = ctx.createGain();
65 mute.gain.value = 0;
66 mute.connect(ctx.destination); // connected so the audio thread renders it, but silent
67 const perSlot = new Array<number>(slots).fill(0);
68 for (let i = 0; i < n; i++) perSlot[i % slots]++;
69 const rate = (P.speed as number) * NOTES_PER_SIM_SECOND; // notes per second per orbit
70 const len = P.noteLength as number;
71 const insts = [];
72 for (let s = 0; s < slots; s++) {
73 if (!perSlot[s]) continue;
79e1f25orbits: lighter on phones (faster engine, shared reverb, cached drawing)Jeremy Magland 74 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 75 insts.push({ inst, rate: rate * perSlot[s] });
76 }
77 try {
78 await Promise.all(insts.map((x) => x.inst.ready));
79 let seed = 12345;
80 const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
81 const t0 = ctx.currentTime + 0.05;
82 for (const { inst, rate: r } of insts) {
83 const note = (when: number) => inst.play({ when, freq: midiToFreq(50 + Math.floor(rnd() * 36)), velocity: 0.6, pan: 0, duration: len });
84 // start at the steady state: as many notes ringing as `rate × length` keeps going
85 const warm = Math.min(16, Math.round(r * len));
86 for (let k = 0; k < warm; k++) note(t0 + 0.002 * k);
87 for (let t = 0.05; t < PLAY_S; t += 1 / r) note(t0 + t);
88 }
89 // average the synths' reported load over the second part of the test
90 await sleep(MEASURE_FROM * 1000);
91 const samples: number[] = [];
92 const end = performance.now() + (PLAY_S - MEASURE_FROM) * 1000;
93 while (performance.now() < end) {
94 await sleep(100);
95 samples.push(insts.reduce((s, x) => s + (x.inst.load?.() ?? 0), 0));
96 }
97 return samples.length ? samples.reduce((a, b) => a + b, 0) / samples.length : 0;
98 } finally {
99 for (const x of insts) x.inst.dispose();
100 window.setTimeout(() => mute.disconnect(), 1200);
101 }
102}
104/**
105 * Largest orbit count ≤ `wanted` this device can play live (cached when the cache covers `wanted`).
106 */
107export async function orbitCapacity(ctx: AudioContext, P: Params, wanted: number, slots: number): Promise<CapacityResult> {
108 const key = cacheKey(P, ctx.sampleRate, slots);
109 const cached = readCache(key);
110 if (cached && (cached.cap < cached.tested || cached.tested >= wanted)) return { ...cached, cap: Math.min(cached.cap, wanted) };
112 let n = wanted;
113 let load = await measure(ctx, P, n, slots);
114 let at = n;
115 for (let tries = 1; load > BUDGET && n > 1 && tries < MAX_TRIES; tries++) {
116 // cost grows a little less than linearly with orbits (voices saturate), so step down generously
117 n = Math.max(1, Math.min(n - 1, Math.floor(n * Math.pow(BUDGET / load, 1.3))));
118 load = await measure(ctx, P, n, slots);
119 at = n;
120 }
121 if (load > BUDGET) n = Math.max(1, Math.min(n - 1, Math.floor(n * Math.pow(BUDGET / load, 1.3)))); // estimate
122 const result: CapacityResult = { cap: n, tested: wanted, load, at };
123 writeCache(key, result);
124 return result;
125}