Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

Slow devices: the audio falls back to 32 kHz when the worklet can't keep up at 48, and says so if it still can't (silence on #86, #113)

Jameson Hodge3a54af3285ca
diff --git a/crates/chimera/tests/engine.rs b/crates/chimera/tests/engine.rs
index 782e6d7..826983c 100644
--- a/crates/chimera/tests/engine.rs
+++ b/crates/chimera/tests/engine.rs
@@ -115,6 +115,30 @@ fn the_voice_holds_at_a_bluetooth_headsets_sample_rate() {
assert_eq!([44100.0, 48000.0, 60000.0, 88200.0, 96000.0].map(oversample_for), [2, 2, 2, 1, 1]);
}
+fn creature_call_rms(fs: f64, id: &str) -> f64 {
+ let def = chimera::creatures::creature_by_id(id).expect("a creature");
+ let mut e = Engine::new(fs);
+ e.set_creature(Some(def), &[]);
+ e.set_gate(1.0);
+ e.play_call(0, None, None);
+ let mut out = vec![0.0f32; fs as usize];
+ for chunk in out.chunks_mut(128) {
+ e.render(chunk);
+ }
+ assert!(out.iter().all(|x| x.is_finite()), "{id} at {fs} Hz went NaN");
+ (out.iter().map(|&x| (x as f64) * (x as f64)).sum::<f64>() / out.len() as f64).sqrt()
+}
+
+#[test]
+fn the_creatures_hold_at_the_lighter_rate() {
+ // A device that can't keep up at 48 kHz falls back to a 32 kHz context (src/audio): each
+ // creature's first call must still sound there, about as loud.
+ for id in ["songbird", "seal", "alligator", "elephant"] {
+ let (reference, light) = (creature_call_rms(48000.0, id), creature_call_rms(32000.0, id));
+ assert!(light > 0.5 * reference && light < 2.0 * reference, "{id}: RMS {light:.4} at 32 kHz, {reference:.4} at 48 kHz");
+ }
+}
+
#[test]
fn the_voice_holds_for_a_child_at_low_device_rates() {
// A 16 or 32 kHz device runs the airway at 64 kHz, where the child's 1.5 cm piriform fossa,
diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.ts
index eaa3239..89388d8 100644
--- a/src/audio/AudioEngine.ts
+++ b/src/audio/AudioEngine.ts
@@ -12,6 +12,22 @@ import type { VoiceSource } from "../wasm/types.ts";
type Listener = (t: TelemetryMessage) => void;
+// 48 kHz whatever the device runs at (the browser resamples): the airway's cost grows with the
+// square of its rate, and a 192 kHz device took ~3x the CPU of 48 kHz and starved the worklet
+// (load 120-150%, no sound; issue #33). 32 kHz is the fallback for a device too slow for 48: its
+// airway runs at 64 kHz instead of 96 (about 40 % less CPU), a little duller (output up to 16 kHz).
+const FULL_RATE = 48000;
+const LIGHT_RATE = 32000;
+/** the averaged load (see watchLoad) past which the device can't keep up, and back under which it can */
+const OVERLOADED = 0.9;
+const KEEPING_UP = 0.6;
+const AVERAGE_S = 2;
+/** a reading counts as no more than this: a stall (a hidden tab, a laptop asleep, a busy moment)
+ * mustn't alone make a fast device look slow, so it takes ~1 s of overload at least to fall back */
+const MOST = 1.5;
+/** the first moments' load is the wasm compiling, not the device's speed */
+const WARM_UP_MS = 2000;
+
export class AudioEngine {
ctx: AudioContext | null = null;
private node: AudioWorkletNode | null = null;
@@ -30,7 +46,18 @@ export class AudioEngine {
latestCreature: CreatureTelemetryMessage | null = null;
/** load of the most recent telemetry of either kind */
load = 0;
- sampleRate = 48000;
+ sampleRate = FULL_RATE;
+ /** the device couldn't keep up at the full rate: the voice runs at the lighter one */
+ light = false;
+ /** the device can't keep up even so: the voice breaks up or goes silent */
+ overloaded = false;
+ private slowLoad = 0;
+ private loadAt = 0;
+ private builtAt = 0;
+ private rebuilding = false;
+ private triedLighter = false;
+ private statusListeners = new Set<() => void>();
+ private rebuiltListeners = new Set<() => void>();
private listeners = new Set<Listener>();
private pendingArtic: Partial<HumanArtic> | null = null;
private pendingTipFree: boolean | undefined;
@@ -71,16 +98,19 @@ export class AudioEngine {
await this.ctx.resume();
return;
}
- // 48 kHz whatever the device runs at (the browser resamples): the airway's cost grows with
- // the square of its rate, and a 192 kHz device took ~3x the CPU of 48 kHz and starved the
- // worklet (load 120-150%, no sound; issue #33)
+ await this.build(FULL_RATE);
+ }
+
+ /**
+ * The context, the worklet and the graph, at this rate; they replace the current ones only once
+ * built (a failure leaves things as they were).
+ */
+ private async build(rate: number): Promise<void> {
preferPlaybackSession();
- const ctx = new AudioContext({ latencyHint: "interactive", sampleRate: 48000 });
+ const ctx = new AudioContext({ latencyHint: "interactive", sampleRate: rate });
// resume now, while the tap that called start() is still the current gesture: iOS Safari
// refuses a resume() that comes after the awaits below (the context stays suspended, silent)
const resumed = ctx.resume().catch(() => {});
- this.ctx = ctx;
- this.sampleRate = ctx.sampleRate;
let node: AudioWorkletNode;
try {
await ctx.audioWorklet.addModule(workletUrl);
@@ -89,11 +119,22 @@ export class AudioEngine {
} catch (e) {
// without its worklet the context is empty: forget it, so a retry builds the graph again
// instead of resuming a context with nothing in it (and reporting that the audio started)
- this.ctx = null;
void ctx.close().catch(() => {});
throw e;
}
+ const old = this.ctx;
+ // the old engine's last telemetry mustn't read as the new one's
+ if (this.node) this.node.port.onmessage = null;
+ this.ctx = ctx;
+ this.sampleRate = ctx.sampleRate;
this.node = node;
+ this.tap = null;
+ this.latest = null;
+ this.latestCreature = null;
+ this.lastPlan = null;
+ this.builtAt = this.loadAt = performance.now();
+ this.slowLoad = 0;
+ if (old) void old.close().catch(() => {});
const master = ctx.createGain();
master.gain.value = 0.8;
this.master = master;
@@ -139,12 +180,12 @@ export class AudioEngine {
this.latest = m;
this.latestAt = performance.now();
this.latestCreature = null;
- this.load = m.load;
+ this.watchLoad(m.load);
for (const l of this.listeners) l(m);
} else if (m.type === "ctelemetry") {
this.latestCreature = m;
this.latest = null;
- this.load = m.load;
+ this.watchLoad(m.load);
} else if (m.type === "planned") {
this.lastPlan = m;
for (const l of this.plannedListeners) l(m);
@@ -158,6 +199,68 @@ export class AudioEngine {
await resumed;
// a second chance where the first resume was refused (the result is what callers see)
await ctx.resume();
+ if (ctx.state !== "running") {
+ // a rebuild comes from no gesture, and some browsers wait for one: the next tap or key
+ const resume = () => void ctx.resume().catch(() => {});
+ for (const ev of ["pointerdown", "keydown"]) window.addEventListener(ev, resume, { once: true, capture: true });
+ }
+ }
+
+ /**
+ * Whether the audio thread keeps up, from the worklet's load (render time over the block's
+ * time). Averaged over ~2 s, past the start's warm-up: over 90 %, the device can't keep up,
+ * and the voice breaks up or goes silent. At 48 kHz it then rebuilds at 32 kHz, once; at 32 kHz
+ * it says so. A fast device never comes near (about 30-40 %), so its sound doesn't change.
+ */
+ private watchLoad(load: number): void {
+ this.load = load;
+ const t = performance.now();
+ // a gap between readings counts as no more than a moment
+ const dt = Math.min(0.1, (t - this.loadAt) / 1000);
+ this.loadAt = t;
+ if (t - this.builtAt < WARM_UP_MS || this.rebuilding) return;
+ this.slowLoad += ((Math.min(MOST, load) - this.slowLoad) * dt) / AVERAGE_S;
+ if (this.slowLoad > OVERLOADED && this.sampleRate > LIGHT_RATE && !this.triedLighter) void this.rebuildLighter();
+ else if (this.slowLoad > OVERLOADED) this.setOverloaded(true);
+ else if (this.slowLoad < KEEPING_UP) this.setOverloaded(false);
+ }
+
+ private setOverloaded(on: boolean): void {
+ if (on === this.overloaded) return;
+ this.overloaded = on;
+ for (const l of this.statusListeners) l();
+ }
+
+ /** The lighter rate for a device that can't keep up: ~40 % less work, output up to 16 kHz. */
+ private async rebuildLighter(): Promise<void> {
+ this.rebuilding = this.triedLighter = true;
+ const load = this.load;
+ try {
+ await this.build(LIGHT_RATE);
+ } catch (e) {
+ // the full-rate voice goes on (and says it can't keep up)
+ console.error("audio: couldn't rebuild at the lighter rate:", e);
+ return;
+ } finally {
+ this.rebuilding = false;
+ }
+ console.warn(`audio: this device can't keep up at ${FULL_RATE} Hz (engine load ${Math.round(load * 100)} %): running at ${this.sampleRate} Hz`);
+ this.light = true;
+ for (const l of this.statusListeners) l();
+ // the new engine starts from scratch: what it plays is sent again
+ for (const l of this.rebuiltListeners) l();
+ }
+
+ /** Called when `light` or `overloaded` changes. */
+ onStatus(l: () => void): () => void {
+ this.statusListeners.add(l);
+ return () => this.statusListeners.delete(l);
+ }
+
+ /** Called after the audio was rebuilt lighter, with a fresh engine that knows nothing yet. */
+ onRebuilt(l: () => void): () => void {
+ this.rebuiltListeners.add(l);
+ return () => this.rebuiltListeners.delete(l);
}
onTelemetry(l: Listener): () => void {
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index c7a86bd..8abdd20 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -38,6 +38,7 @@ function TopBar() {
const setVolume = useStore((s) => s.setVolume);
const mode = useStore((s) => s.mode);
const setMode = useStore((s) => s.setMode);
+ const light = useStore((s) => s.lightAudio);
const [load, setLoad] = useState(0);
useEffect(() => {
const id = setInterval(() => setLoad(engine.load), 500);
@@ -67,8 +68,8 @@ function TopBar() {
<input type="range" min={0} max={1} step={0.01} value={volume} onChange={(e) => setVolume(Number(e.target.value))} style={{ "--pos": `${volume * 100}%` } as React.CSSProperties} />
</label>
{started && (
- <span className="load" title="Share of the audio thread's time budget used by the simulation">
- Engine load {Math.round(load * 100)} %
+ <span className="load" title={"Share of the audio thread's time budget used by the simulation" + (light ? ". This device couldn't keep up at 48 kHz, so the voice runs at 32 kHz: lighter, a little duller. Reload to try 48 kHz again." : "")}>
+ Engine load {Math.round(load * 100)} %{light && " · 32 kHz"}
</span>
)}
<a className="repo-link" href="https://github.com/jamesondh/chimera-vocal-synth" target="_blank" rel="noreferrer" aria-label="Source code on GitHub" title="Source code on GitHub">
diff --git a/src/ui/components/ActionBar.tsx b/src/ui/components/ActionBar.tsx
index ce15011..c7e8d87 100644
--- a/src/ui/components/ActionBar.tsx
+++ b/src/ui/components/ActionBar.tsx
@@ -4,11 +4,13 @@ import { useStore } from "../store.ts";
/**
* The top of each tab's right column: the one bright button for what the tab is for, in the same
* place on every tab, and the few settings that belong beside it. Its button starts the audio too
- * (there's no separate start step), and failing to start shows here. Space presses it, unless the
- * focus is in a field or on another control.
+ * (there's no separate start step), and failing to start shows here, as does a device too slow
+ * to run the voice in real time. Space presses it, unless the focus is in a field or on another
+ * control.
*/
export function ActionBar(props: { label: string; onSpace: () => void; children: ReactNode }) {
const err = useStore((s) => s.startError);
+ const overloaded = useStore((s) => s.overloaded);
const onSpace = useRef(props.onSpace);
onSpace.current = props.onSpace;
useEffect(() => {
@@ -32,6 +34,11 @@ export function ActionBar(props: { label: string; onSpace: () => void; children:
Audio could not start: {err}. Press again to retry.
</p>
)}
+ {overloaded && (
+ <p className="act-error" role="status">
+ This device can't keep up, so the voice breaks up or goes silent. Plugging in, or closing other tabs, may help.
+ </p>
+ )}
</div>
</section>
);
diff --git a/src/ui/store.ts b/src/ui/store.ts
index e45bbef..2bc4272 100644
--- a/src/ui/store.ts
+++ b/src/ui/store.ts
@@ -34,6 +34,10 @@ interface State {
started: boolean;
starting: boolean;
startError: string | null;
+ /** the device couldn't keep up at 48 kHz: the voice runs at 32 kHz (see AudioEngine) */
+ lightAudio: boolean;
+ /** the device can't keep up even so: the voice breaks up or goes silent */
+ overloaded: boolean;
/** the body shown; while the body pad is dragged it runs ahead of the voice (see previewBody) */
body: BodyMix;
source: VoiceSource;
@@ -107,6 +111,20 @@ function updateGate(s: { hold: boolean; heldNotes: number[]; mode: Mode; keyCall
engine.gate(s.hold || (keysBreathe && s.heldNotes.length > 0) ? 1 : 0);
}
+/** Everything the voice plays from, sent to an engine that knows none of it (a new one). */
+function sendState(s: State) {
+ engine.setVolume(s.volume);
+ if (!sameBody(s.body, PRESETS.male)) engine.setBody(s.body);
+ engine.setSource(s.source);
+ engine.setArtic(s.artic, s.tipFree);
+ if (s.mode === "bestiary") engine.setCreature(s.creature, s.cparams[s.creature]);
+ if (s.mode === "beatbox") {
+ engine.setMic(s.mic);
+ engine.setBeat({ steps: s.beat.steps, bpm: s.beat.bpm, swing: s.beat.swing, playing: s.beat.playing });
+ }
+ updateGate(s);
+}
+
let startPromise: Promise<void> | null = null;
/**
@@ -131,6 +149,8 @@ export const useStore = create<State>((set, get) => ({
started: false,
starting: false,
startError: null,
+ lightAudio: false,
+ overloaded: false,
body: PRESETS.male,
source: { ...DEFAULT_SOURCE },
artic: (() => {
@@ -266,17 +286,7 @@ export const useStore = create<State>((set, get) => ({
try {
await engine.start();
// anything set before audio existed was not delivered: send the whole state now
- const s = get();
- engine.setVolume(s.volume);
- if (!sameBody(s.body, PRESETS.male)) engine.setBody(s.body);
- engine.setSource(s.source);
- engine.setArtic(s.artic, s.tipFree);
- if (s.mode === "bestiary") engine.setCreature(s.creature, s.cparams[s.creature]);
- if (s.mode === "beatbox") {
- engine.setMic(s.mic);
- engine.setBeat({ steps: s.beat.steps, bpm: s.beat.bpm, swing: s.beat.swing, playing: s.beat.playing });
- }
- updateGate(s);
+ sendState(get());
set({ started: true, starting: false });
} catch (e) {
set({ starting: false, startError: e instanceof Error ? e.message : String(e) });
@@ -397,3 +407,14 @@ export const useStore = create<State>((set, get) => ({
});
},
}));
+
+engine.onStatus(() => useStore.setState({ lightAudio: engine.light, overloaded: engine.overloaded }));
+// the lighter audio is a new engine: the phrase being sung or spoken is gone (the score was the
+// old engine's), and the rest is sent again
+engine.onRebuilt(() => {
+ session++;
+ stopSinging();
+ stopSpeaking();
+ useStore.setState({ heldNotes: [] });
+ sendState(useStore.getState());
+});
diff --git a/src/ui/useModel.ts b/src/ui/useModel.ts
index b3bbacf..2bd3e1a 100644
--- a/src/ui/useModel.ts
+++ b/src/ui/useModel.ts
@@ -29,10 +29,12 @@ export function getModel(body: BodyMix, sampleRate: number): VoiceModel {
export function useModel(): React.MutableRefObject<VoiceModel | null> {
const body = useStore((s) => s.body);
const started = useStore((s) => s.started);
+ // the audio's rate drops to 32 kHz on a device that can't keep up at 48
+ const light = useStore((s) => s.lightAudio);
const ref = useRef<VoiceModel | null>(null);
ref.current = getModel(body, started ? engine.sampleRate : 48000);
useEffect(() => {
ref.current = getModel(body, started ? engine.sampleRate : 48000);
- }, [body, started]);
+ }, [body, started, light]);
return ref;
}
diff --git a/tools/e2e.ts b/tools/e2e.ts
index 5ea2616..7cc4a9b 100644
--- a/tools/e2e.ts
+++ b/tools/e2e.ts
@@ -269,6 +269,13 @@ async function run(viewport: { width: number; height: number }, tag: string) {
return { human: !!e?.latest, creature: !!e?.latestCreature };
});
logs.push(`[${tag}] back to play: ${JSON.stringify(human)}`);
+ // a device that keeps up keeps the full rate through the whole run (the fallback is for slow ones)
+ const rate = await page.evaluate(() => {
+ // @ts-expect-error debug handle
+ return window.__chimeraEngine?.ctx?.sampleRate ?? -1;
+ });
+ logs.push(`[${tag}] rate after the run: ${rate} Hz`);
+ if (rate !== 48000) errors.push(`[${tag}] this machine fell back to ${rate} Hz (it keeps up at 48 kHz)`);
await page.close();
}
@@ -347,6 +354,51 @@ async function run(viewport: { width: number; height: number }, tag: string) {
await page.close();
}
+// a device too slow for 48 kHz falls back to 32 kHz and keeps sounding; one too slow for that says
+// so (issues #86, #113). The patched node adds to the load the worklet reports: at 48 kHz only
+// (it keeps up at 32), or at every rate.
+for (const slowAt of ["48000", "any"]) {
+ const tag = `slow-${slowAt}`;
+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
+ page.on("pageerror", (e) => errors.push(`[${tag}] pageerror: ${e.message}`));
+ await page.addInitScript((slowAt) => {
+ const Node = window.AudioWorkletNode;
+ const onmessage = Object.getOwnPropertyDescriptor(MessagePort.prototype, "onmessage")!;
+ window.AudioWorkletNode = class extends Node {
+ constructor(ctx: BaseAudioContext, name: string, o?: AudioWorkletNodeOptions) {
+ super(ctx, name, o);
+ const port = this.port, slow = slowAt === "any" || String(ctx.sampleRate) === slowAt;
+ let h: ((e: MessageEvent) => void) | null = null;
+ Object.defineProperty(port, "onmessage", {
+ get: () => h,
+ set(f: ((e: MessageEvent) => void) | null) {
+ h = f;
+ onmessage.set!.call(port, f && ((e: MessageEvent) => f(slow && "load" in e.data ? ({ data: { ...e.data, load: e.data.load + 1.5 } } as MessageEvent) : e)));
+ },
+ });
+ }
+ };
+ }, slowAt);
+ await page.goto(url, { waitUntil: "networkidle" });
+ await page.getByRole("radio", { name: "Play" }).click();
+ await page.getByRole("button", { name: /^Breathe$/ }).click();
+ // the start's warm-up and the averaging, at each rate
+ await page.waitForTimeout(10000);
+ const state = await page.evaluate(() => {
+ // @ts-expect-error debug handle
+ const e = window.__chimeraEngine;
+ return { rate: e?.ctx?.sampleRate ?? -1, rms: e?.latest?.t?.outRms ?? -1 };
+ });
+ const warned = await page.getByText(/This device can't keep up/).isVisible();
+ const badge = await page.getByText(/· 32 kHz/).isVisible();
+ logs.push(`[${tag}] slow device: runs at ${state.rate} Hz, rms ${state.rms.toFixed(4)}, 32 kHz shown ${badge}, warning ${warned}`);
+ if (state.rate !== 32000) errors.push(`[${tag}] a device too slow for 48 kHz ran at ${state.rate} Hz (want 32000)`);
+ if (!badge) errors.push(`[${tag}] the top bar doesn't say the voice runs at 32 kHz`);
+ if (!(state.rms > 0.01)) errors.push(`[${tag}] the breath stopped sounding across the fallback (rms ${state.rms})`);
+ if (warned !== (slowAt === "any")) errors.push(`[${tag}] the can't-keep-up warning ${warned ? "showed" : "didn't show"}`);
+ await page.close();
+}
+
// Sing's Record video: sings the lyrics to the tune again into a clip to save; the face screen leaves out
// its readouts while it records
{
@@ -599,6 +651,6 @@ await run({ width: 1440, height: 980 }, "desktop");
await run({ width: 390, height: 844 }, "mobile");
await browser.close();
console.log("console errors:", errors.length ? "\n" + errors.join("\n") : "none");
-console.log(logs.filter((l) => /load|rate|warn|transcription|example|creature|held|back to|beatbox|silence|sing|octave|retry|tongue|song|video/i.test(l)).slice(0, 52).join("\n"));
+console.log(logs.filter((l) => /load|rate|slow|warn|transcription|example|creature|held|back to|beatbox|silence|sing|octave|retry|tongue|song|video/i.test(l)).slice(0, 52).join("\n"));
// a run that collected errors fails, so CI and agents can't read it as a pass
if (errors.length) process.exit(1);