the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Review round 2: demo start, press identity, owned endings, ordered and budgeted replay
Jameson Hodge3a31e029588e
diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 70f126e..11fb869 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -125,11 +125,12 @@ function StartPrompt() {className="primary large"disabled={starting}onClick={async () => {+ // the demo waits for audio itself, so a stop meanwhile (body, mode) cancels it+ if (mode === "sing") return void playDemo(DEMO_SONGS[0].name, useStore.getState().body, start);await start();const first = creatureById(creature)?.calls[0];if (mode === "bestiary" && first) playCall(first.id);else if (mode === "beatbox") setBeatPlaying(true);- else if (mode === "sing" && useStore.getState().mode === "sing") void playDemo(DEMO_SONGS[0].name, useStore.getState().body);else if (mode === "play") setHold(true);}}>diff --git a/src/ui/singing.ts b/src/ui/singing.tsindex db6aa6c..e82b311 100644--- a/src/ui/singing.ts+++ b/src/ui/singing.ts@@ -94,8 +94,10 @@ let sounding: Sounding | null = null;let keys: number[] = [];/** gesture tags: a note uses tag (articulation, breath) and tag + 1 (pitch, vibrato) */let nextTag = 2;-/** the last note's ending (glide, coda) still playing: tag, and tag + 1 for its exhale */-let tail: number | null = null;+/** endings (glide, coda) that may still be playing: tag, and tag + 1 for the breath-out */+const tails: number[] = [];+/** endings whose breath-out has not been dropped by a following note */+let exhalesLive = false;/** breath level for a key velocity (1 at the on-screen keys' default of 96) */const breathFor = (velocity: number) => 0.62 + 0.4 * Math.min(1, Math.max(0, velocity / 96)) + 0.12 * Math.max(0, (velocity - 96) / 31);@@ -121,8 +123,9 @@ function startNote(syl: Syllable, midi: number, velocity: number, body: BodyNameconst t = now();const tag = nextTag;nextTag += 2;- // the previous note's coda may finish, but its breath-out must not open the folds on this onset- if (tail !== null) engine.release(tail + 1);+ // earlier codas may finish, but their breath-out must not open the folds on this onset+ if (exhalesLive) for (const t of tails) engine.release(t + 1);+ exhalesLive = false;const from = sounding;if (from) {engine.release(from.tag);@@ -180,7 +183,9 @@ export function singNoteOff(midi: number, body: BodyName): void {const tag = nextTag;nextTag += 2;engine.scheduleGestures(gs.map((g) => ({ ...g, tag: g.label === EXHALE_LABEL ? tag + 1 : tag })));- tail = tag;+ tails.push(tag);+ if (tails.length > 8) tails.shift(); // long finished by now+ exhalesLive = true;}// ---- demo songs@@ -275,11 +280,12 @@ export function stopSinging(): void {sounding.note.t1 = now();sounding = null;}- if (tail !== null) {- engine.release(tail);- engine.release(tail + 1);- tail = null;+ for (const t of tails) {+ engine.release(t);+ engine.release(t + 1);}+ tails.length = 0;+ exhalesLive = false;keys = [];}diff --git a/src/ui/store.ts b/src/ui/store.tsindex 4d01c16..4e82d3f 100644--- a/src/ui/store.ts+++ b/src/ui/store.ts@@ -102,6 +102,14 @@ function updateGate(s: { hold: boolean; heldNotes: number[]; mode: Mode; keyCalllet startPromise: Promise<void> | null = null;+/**+ * A key pressed before the audio exists is sent once it does: only if that same press is still+ * down (not a later press of the same key) and the mode and body have not changed since.+ */+let pressSerial = 0;+const pressOf = new Map<number, number>();+let session = 0;+const FIRST_BEAT = BEAT_PRESETS[0];export const useStore = create<State>((set, get) => ({@@ -123,6 +131,7 @@ export const useStore = create<State>((set, get) => ({setMode: (m) => {const prev = get().mode;if (prev === m) return;+ session++;// notes held across the switch would keep breathing into the other voiceset({ mode: m, heldNotes: [] });// speech belongs to Speak: under a creature the human clock stops and it would resume later@@ -250,6 +259,7 @@ export const useStore = create<State>((set, get) => ({return startPromise;},setBody: (b) => {+ session++;// the new voice starts without the old one's score: a sung note would hangif (get().mode === "sing") stopSinging();const f0 = DEFAULT_F0[b];@@ -276,13 +286,15 @@ export const useStore = create<State>((set, get) => ({const held = get().heldNotes.filter((n) => n !== midi).concat(midi);set({ heldNotes: held });const s = get();+ const press = ++pressSerial;+ pressOf.set(midi, press);// a sung note or a call is a one-off message, lost if sent before the audio exists (held- // pitches and breath are resent at startup): send it once audio is up, if the key is still down+ // pitches and breath are resent at startup): send it once audio is up, if still pressedif (!s.started && (s.mode === "sing" || (s.mode === "bestiary" && s.keyCall))) {- const mode = s.mode;+ const sess = session;void s.start().then(() => {const t = get();- if (t.started && t.mode === mode && t.heldNotes.includes(midi)) t.noteOn(midi, velocity);+ if (t.started && session === sess && pressOf.get(midi) === press) t.noteOn(midi, velocity);});return;}@@ -301,6 +313,7 @@ export const useStore = create<State>((set, get) => ({updateGate(get());},noteOff: (midi) => {+ pressOf.delete(midi);const held = get().heldNotes.filter((n) => n !== midi);set({ heldNotes: held });const s = get();diff --git a/src/worklet/processor.ts b/src/worklet/processor.tsindex 084a5c6..5d15e2d 100644--- a/src/worklet/processor.ts+++ b/src/worklet/processor.ts@@ -19,6 +19,8 @@ declare class AudioWorkletProcessor {const BODIES: Record<BodyName, HumanBody> = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD };const DEFAULT_F0: Record<BodyName, number> = { male: 110, female: 205, child: 260 };+/** gestures taken from one schedule message (and replayed per block) */+const MAX_GESTURES = 4000;class ChimeraProcessor extends AudioWorkletProcessor {private voice: HumanVoice;@@ -34,7 +36,10 @@ class ChimeraProcessor extends AudioWorkletProcessor {private pendingCall: { id: string; pitch?: number; amp?: number } | null = null;private gateLevel = 0;private beat = new BeatPlayer();- /** score messages that arrived while a body change was pending: they belong to the new voice */+ /**+ * Score messages that arrived while a body change was pending (they belong to the new voice),+ * replayed in order within a per-block budget; later ones wait behind them.+ */private afterBody: ToWorklet[] = [];constructor() {@@ -55,10 +60,28 @@ class ChimeraProcessor extends AudioWorkletProcessor {}private onMessage(m: ToWorklet): void {- if (this.pendingBody && (m.type === "schedule" || m.type === "release" || m.type === "stopSpeech" || m.type === "beatHit")) {+ const ordered = m.type === "schedule" || m.type === "release" || m.type === "stopSpeech" || m.type === "beatHit" || m.type === "beat";+ if (ordered && (this.pendingBody || this.afterBody.length)) {this.afterBody.push(m);return;}+ this.handle(m);+ }++ /** Replay held-back score messages: at most one full-size schedule's worth per block. */+ private replay(): void {+ let spent = 0;+ while (this.afterBody.length) {+ const m = this.afterBody[0];+ const cost = m.type === "schedule" ? Math.min(MAX_GESTURES, m.gestures.length) : 1;+ if (spent > 0 && spent + cost > MAX_GESTURES) break;+ this.afterBody.shift();+ this.handle(m);+ spent += cost;+ }+ }++ private handle(m: ToWorklet): void {switch (m.type) {case "body":this.pendingBody = m.body;@@ -97,7 +120,7 @@ class ChimeraProcessor extends AudioWorkletProcessor {case "schedule": {// O(n) time shift onto the voice clock; planning happened on the main threadconst off = this.voice.clock + (m.lead ?? 0.03);- const gs = m.gestures.slice(0, 4000);+ const gs = m.gestures.slice(0, MAX_GESTURES);for (const g of gs) {g.t0 += off;g.t1 += off;@@ -152,10 +175,8 @@ class ChimeraProcessor extends AudioWorkletProcessor {// the performer's breath, not the voice's (which includes breath from the score)this.voice.setGate(this.gateLevel);this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr, creature: this.creature ? this.creature.def.id : "human" });- const queued = this.afterBody;- this.afterBody = [];- for (const q of queued) this.onMessage(q);}+ if (this.afterBody.length && !this.pendingBody) this.replay();if (this.pendingCreature !== null) {const id = this.pendingCreature;this.pendingCreature = null;diff --git a/tests/live-control.test.ts b/tests/live-control.test.tsindex 01d8231..b97029e 100644--- a/tests/live-control.test.ts+++ b/tests/live-control.test.ts@@ -48,6 +48,29 @@ describe("worklet ordering", () => {const voice = (p as unknown as { voice: HumanVoice }).voice;expect(voice.airway.body.scale).toBeLessThan(1); // the new (female) voiceexpect(voice.score.size).toBe(1); // holding the note++ // a beat stop sent after a hit, during a body change, still cancels that hit+ send({ type: "beat", steps: [{ id: "B" }, null, null, null], bpm: 96, playing: true });+ for (let i = 0; i < 20; i++) p.process([], [[new Float32Array(128)]]);+ send({ type: "body", body: "male" });+ send({ type: "beatHit", id: "B" });+ send({ type: "beat", playing: false });+ p.process([], [[new Float32Array(128)]]);+ const v2 = (p as unknown as { voice: HumanVoice }).voice;+ expect(v2.airway.body.scale).toBe(1);+ expect(v2.score.size).toBe(0);++ // a backlog replays in order, one full-size schedule per block+ const big = Array.from({ length: 4000 }, (_, i) => ({ ...breath, t0: 1 + i * 1e-3, t1: 1.5 + i * 1e-3, label: `g${i}` }));+ send({ type: "body", body: "child" });+ for (let k = 0; k < 3; k++) send({ type: "schedule", gestures: big, segments: [], end: 1, id: 10 + k, replace: false });+ send({ type: "stopSpeech" }); // must come after all three+ const sizes: number[] = [];+ for (let i = 0; i < 4; i++) {+ p.process([], [[new Float32Array(128)]]);+ sizes.push((p as unknown as { voice: HumanVoice }).voice.score.size);+ }+ expect(sizes).toEqual([4000, 8000, 12000, 0]);});});diff --git a/tests/singing-live.test.ts b/tests/singing-live.test.tsindex c051365..1625f91 100644--- a/tests/singing-live.test.ts+++ b/tests/singing-live.test.ts@@ -27,7 +27,16 @@ const fakeEngine = {release: (tag: number) => voice.release(tag),stopSpeech: () => voice.cancelScore(),};-mock.module("../src/audio/AudioEngine.ts", () => ({ engine: fakeEngine }));+let startAudio: () => void = () => {};+const engineStub = new Proxy(+ {+ ...fakeEngine,+ start: () => new Promise<void>((r) => (startAudio = r)),+ } as Record<string, unknown>,+ // every other engine call the store makes (volume, body, gate…) does nothing here+ { get: (t, k) => (k in t ? t[k as string] : () => {}), set: (t, k, v) => ((t[k as string] = v), true) },+);+mock.module("../src/audio/AudioEngine.ts", () => ({ engine: engineStub }));const { useSing, singNoteOn, singNoteOff, playDemo, stopSinging } = await import("../src/ui/singing.ts");const gesturesOf = () => (voice.score as unknown as { gestures: Gesture[] }).gestures;@@ -123,8 +132,8 @@ describe("Sing mode, live keys", () => {test("a demo still waiting for audio or the dictionary is cancelled by a stop", async () => {voice = new HumanVoice({ fsOut: FS });let scheduled = 0;- const schedule = fakeEngine.schedule;- fakeEngine.schedule = (plan) => (scheduled++, schedule(plan));+ const schedule = engineStub.schedule as typeof fakeEngine.schedule;+ engineStub.schedule = (plan: { gestures: Gesture[] }) => (scheduled++, schedule(plan));let go!: () => void;const waiting = playDemo("Made of air", "male", () => new Promise<void>((r) => (go = r)));stopSinging(); // e.g. the mode changed while audio was starting@@ -136,7 +145,7 @@ describe("Sing mode, live keys", () => {expect(scheduled).toBe(1);expect(useSing.getState().demo).toBe("Made of air");stopSinging();- fakeEngine.schedule = schedule;+ engineStub.schedule = schedule;});test("a quick next note drops the last one's breath-out; leaving Sing cancels a pending ending", () => {@@ -162,4 +171,61 @@ describe("Sing mode, live keys", () => {for (const g of voice.score.activeAt(voice.clock)) if (g.targets.breath !== undefined) breath += activation(g, voice.clock) * g.strength;expect(breath).toBeLessThan(0.01);});++ test("overlapping endings all stay owned: a stop cancels every one", () => {+ voice = new HumanVoice({ fsOut: FS });+ useSing.getState().setLyrics("cats dogs");+ run(0.05);+ singNoteOn(50, 96, "male");+ run(0.3);+ singNoteOff(50, "male"); // "cats": /ts/ and breath-out+ run(0.01);+ singNoteOn(52, 96, "male");+ run(0.03);+ singNoteOff(52, "male"); // "dogs" released quickly, while the /ts/ is still going+ run(0.01);+ stopSinging();+ run(0.08);+ let breath = 0;+ for (const g of voice.score.activeAt(voice.clock)) if (g.targets.breath !== undefined) breath += activation(g, voice.clock) * g.strength;+ expect(breath).toBeLessThan(0.01);+ });+});++describe("keys pressed before the audio has started", () => {+ test("only the press still down sings, once, and not after the body changed", async () => {+ const { useStore } = await import("../src/ui/store.ts");+ voice = new HumanVoice({ fsOut: FS });+ useStore.setState({ started: false, mode: "play" });+ useStore.getState().setMode("sing");+ useSing.getState().setLyrics("one two three");+ let scheduled = 0;+ const sg = engineStub.scheduleGestures as typeof fakeEngine.scheduleGestures;+ engineStub.scheduleGestures = (gs: Gesture[], lead?: number) => (scheduled++, sg(gs, lead));+ const st = useStore.getState();+ // press, release and press again while audio starts: one note, one syllable+ st.noteOn(50);+ st.noteOff(50);+ st.noteOn(50);+ startAudio();+ await new Promise((r) => setTimeout(r, 0));+ await new Promise((r) => setTimeout(r, 0));+ expect(useStore.getState().started).toBe(true);+ expect(scheduled).toBe(1);+ expect(useSing.getState().cursor).toBe(1);+ useStore.getState().noteOff(50);++ // a press waiting for audio is dropped by a body change+ useStore.setState({ started: false });+ scheduled = 0;+ const before = useSing.getState().cursor;+ useStore.getState().noteOn(52);+ useStore.getState().setBody("female");+ startAudio();+ await new Promise((r) => setTimeout(r, 0));+ await new Promise((r) => setTimeout(r, 0));+ expect(scheduled).toBe(0);+ expect(useSing.getState().cursor).toBe(before);+ engineStub.scheduleGestures = sg;+ });});