// 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 { DEFAULTS } from "@modal-synth/engine/params.ts"; import { PRESETS } from "@modal-synth/presets.ts"; import type { Params } from "../../core/params.ts"; import { NOTE_INSTRUMENTS } from "../../instruments/index.ts"; import { parseModalPreset } from "../../instruments/modal.ts"; import type { BenchNote, FromWorker, ToWorker } from "../../instruments/stream/protocol.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; // With rendering ahead in workers (one per instrument, on other cores, buffered), each worker must // render comfortably faster than real time; the buffer absorbs momentary slowdowns. const BUDGET_STREAM = 0.6; 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, stream: boolean): string { const sig = { v: 5, // bump when the check itself (or the engine's speed) changes stream, 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); } } /** The modal-synth settings for an instrument slot (null: not a modal instrument). */ function modalSound(P: Params, slot: number): Params | null { const name = P[`slot${slot + 1}Instrument`] as string; if (!name.startsWith("modal: ")) return null; const p = name === "modal: custom" ? parseModalPreset(P.modalCustom as string) : PRESETS.find((x) => `modal: ${x.name}` === name)?.p; return { ...DEFAULTS, ...(p ?? {}) }; } /** * Rendered-ahead check: every instrument's worker renders its share of `n` orbits' notes as fast * as it can, all at once (as they would run). Returns the busiest worker's render time / audio time. */ async function measureWorkers(sampleRate: number, P: Params, n: number, slots: number): Promise { 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; const len = P.noteLength as number; const SECONDS = 1.5, WARMUP = 0.5; const jobs: Promise[] = []; for (let s = 0; s < slots; s++) { const sound = perSlot[s] ? modalSound(P, s) : null; if (!sound) continue; const r = rate * perSlot[s]; let seed = 12345 + s; const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); const notes: BenchNote[] = []; const warm = Math.min(16, Math.round(r * len)); for (let k = 0; k < warm; k++) notes.push({ time: 0.002 * k, note: 50 + Math.floor(rnd() * 36), vel: 0.6, len }); for (let t = 0.05; t < SECONDS; t += 1 / r) notes.push({ time: t, note: 50 + Math.floor(rnd() * 36), vel: 0.6, len }); jobs.push( new Promise((resolve) => { const w = new Worker(new URL("../../instruments/stream/renderWorker.ts", import.meta.url), { type: "module" }); w.onmessage = (e: MessageEvent) => { if (e.data.type === "bench") { resolve(e.data.load); w.terminate(); } }; const m: ToWorker = { type: "bench", sampleRate, params: sound, notes, seconds: SECONDS, warmup: WARMUP }; w.postMessage(m); }), ); } const loads = await Promise.all(jobs); return loads.length ? Math.max(...loads) : 0; } /** * Largest orbit count ≤ `wanted` this device can play live (cached when the cache covers `wanted`). * `stream`: instruments render ahead in workers (measured that way, with its own budget). */ export async function orbitCapacity(ctx: AudioContext, P: Params, wanted: number, slots: number, stream = false): Promise { const key = cacheKey(P, ctx.sampleRate, slots, stream); const budget = stream ? BUDGET_STREAM : BUDGET; const run = (n: number) => (stream ? measureWorkers(ctx.sampleRate, P, n, slots) : measure(ctx, P, n, 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 run(n); 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 run(n); 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; }