// How many orbits can this device play live? // // Almost all the cost is audio: the modal-synth instruments run on the single real-time audio // thread, and their load grows with the number of orbits (more notes → more ringing voices). // So, before the first play, we play the composition's actual instruments silently (into a muted // bus) for about a second at the note density the orbit count produces, and read the load the // synths report from the audio thread itself. That measures exactly what glitches, on this // device, and isn't affected by background-tab throttling. If the load is over BUDGET we try // fewer orbits. The answer is cached per device and settings. import type { Params } from "../../core/params.ts"; import { NOTE_INSTRUMENTS } from "../../instruments/index.ts"; import { midiToFreq } from "../../music/scales.ts"; // Synth load (share of real time) we accept on the audio thread. The synths' own measure excludes // the reverb, the hum, browser overhead, and what the page's own drawing and physics take from a // phone's CPU. A phone measured within 0.55 still glitched, so stay well below that. const BUDGET = 0.35; const NOTES_PER_SIM_SECOND = 0.2; // crossings per orbit per simulated second (busy parts of the piece) const PLAY_S = 1.3; // how long the silent test plays const MEASURE_FROM = 0.5; // ignore the first part (voices filling up) const MAX_TRIES = 2; export interface CapacityResult { cap: number; // orbits this device can play tested: number; // the count asked for when this was measured load: number; // measured synth load at the last count tried at: number; // that count } function cacheKey(P: Params, sampleRate: number, slots: number): string { const sig = { v: 4, // bump when the check itself (or the engine's speed) changes sr: sampleRate, speed: P.speed, len: P.noteLength, inst: Array.from({ length: slots }, (_, i) => P[`slot${i + 1}Instrument`]), custom: P.modalCustom, }; return `double-pendulum:capacity:02-orbits:${JSON.stringify(sig)}`; } function readCache(key: string): CapacityResult | null { try { const s = localStorage.getItem(key); return s ? (JSON.parse(s) as CapacityResult) : null; } catch { return null; } } function writeCache(key: string, r: CapacityResult) { try { localStorage.setItem(key, JSON.stringify(r)); } catch { /* storage unavailable: we'll just measure again next time */ } } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); /** Play `n` orbits' worth of notes silently on the live context; returns the measured synth load. */ async function measure(ctx: AudioContext, P: Params, n: number, slots: number): Promise { const mute = ctx.createGain(); mute.gain.value = 0; mute.connect(ctx.destination); // connected so the audio thread renders it, but silent const perSlot = new Array(slots).fill(0); for (let i = 0; i < n; i++) perSlot[i % slots]++; const rate = (P.speed as number) * NOTES_PER_SIM_SECOND; // notes per second per orbit const len = P.noteLength as number; const insts = []; for (let s = 0; s < slots; s++) { if (!perSlot[s]) continue; const inst = NOTE_INSTRUMENTS[P[`slot${s + 1}Instrument`] as string](ctx, mute, { custom: P.modalCustom as string, immediateRelease: true, effects: "none" }); insts.push({ inst, rate: rate * perSlot[s] }); } try { await Promise.all(insts.map((x) => x.inst.ready)); let seed = 12345; const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); const t0 = ctx.currentTime + 0.05; for (const { inst, rate: r } of insts) { const note = (when: number) => inst.play({ when, freq: midiToFreq(50 + Math.floor(rnd() * 36)), velocity: 0.6, pan: 0, duration: len }); // start at the steady state: as many notes ringing as `rate × length` keeps going const warm = Math.min(16, Math.round(r * len)); for (let k = 0; k < warm; k++) note(t0 + 0.002 * k); for (let t = 0.05; t < PLAY_S; t += 1 / r) note(t0 + t); } // average the synths' reported load over the second part of the test await sleep(MEASURE_FROM * 1000); const samples: number[] = []; const end = performance.now() + (PLAY_S - MEASURE_FROM) * 1000; while (performance.now() < end) { await sleep(100); samples.push(insts.reduce((s, x) => s + (x.inst.load?.() ?? 0), 0)); } return samples.length ? samples.reduce((a, b) => a + b, 0) / samples.length : 0; } finally { for (const x of insts) x.inst.dispose(); window.setTimeout(() => mute.disconnect(), 1200); } } /** * Largest orbit count ≤ `wanted` this device can play live (cached when the cache covers `wanted`). */ export async function orbitCapacity(ctx: AudioContext, P: Params, wanted: number, slots: number): Promise { const key = cacheKey(P, ctx.sampleRate, slots); const cached = readCache(key); if (cached && (cached.cap < cached.tested || cached.tested >= wanted)) return { ...cached, cap: Math.min(cached.cap, wanted) }; let n = wanted; let load = await measure(ctx, P, n, slots); let at = n; for (let tries = 1; load > BUDGET && n > 1 && tries < MAX_TRIES; tries++) { // cost grows a little less than linearly with orbits (voices saturate), so step down generously n = Math.max(1, Math.min(n - 1, Math.floor(n * Math.pow(BUDGET / load, 1.3)))); load = await measure(ctx, P, n, slots); at = n; } if (load > BUDGET) n = Math.max(1, Math.min(n - 1, Math.floor(n * Math.pow(BUDGET / load, 1.3)))); // estimate const result: CapacityResult = { cap: n, tested: wanted, load, at }; writeCache(key, result); return result; }