the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Review fixes: one cancellation path for singing; ordered body switch; MIDI ownership
Jameson Hodge2f34d2949c06
diff --git a/src/engine/control/score.ts b/src/engine/control/score.tsindex 72d7ca6..5b23fe7 100644--- a/src/engine/control/score.ts+++ b/src/engine/control/score.ts@@ -79,12 +79,23 @@ export class GestureScore {this.end = 0;}- /** End every gesture with this tag at time t (those already ended are left alone). */+ /**+ * End every gesture with this tag at time t. One not yet begun is dropped; one still ramping+ * in turns round and ramps out from its present activation (no later rise); one at full+ * strength starts its ramp-out now. Those already ending are left alone.+ */release(tag: number, t: number): void {- for (const g of this.gestures)- if (g.tag === tag && g.t1 > t) {- g.t1 = Math.max(g.t0, t);- }+ this.gestures = this.gestures.filter((g) => g.tag !== tag || t > g.t0 - g.rampIn);+ for (const g of this.gestures) {+ if (g.tag !== tag || g.t1 <= t) continue;+ if (t < g.t0) {+ // the point on the ramp-out curve whose value is the present activation+ const a = activation(g, t);+ const u = Math.acos(Math.min(1, Math.max(-1, 2 * a - 1))) / Math.PI;+ g.t1 = t - u * Math.max(1e-6, g.rampOut);+ g.t0 = g.t1;+ } else g.t1 = t;+ }let end = 0;for (const g of this.gestures) end = Math.max(end, g.t1 + g.rampOut + (g.releaseHold ?? 0));this.end = end;diff --git a/src/engine/phonetics/planner.ts b/src/engine/phonetics/planner.tsindex 1b47fe2..e484f86 100644--- a/src/engine/phonetics/planner.ts+++ b/src/engine/phonetics/planner.ts@@ -52,6 +52,9 @@ export interface Plan {end: number;}+/** label of the end-of-breath-group abduction (a live note can drop it when the next one starts) */+export const EXHALE_LABEL = "exhale";+const VOWEL_KEYS = ["tbX", "tbY", "jaw", "lipAp", "lipProt", "lipWidth", "root", "larynx", "ttCurl"] as const;type VTable = Record<string, Record<string, { artic: Partial<HumanArtic> }>>;const VT = vowelTable as unknown as VTable;@@ -209,7 +212,7 @@ export function planUtterance(input: Segment[], o: PlanOptions): Plan {const last = segs[segs.length - 1];const sonorant = !!last?.vowel || ["nasal", "approximant", "lateral", "tap", "trill"].includes(last?.def?.manner ?? "");const at = end + (sonorant ? 0.045 : 0.015);- gestures.push({ t0: at, t1: end + 0.1, rampIn: 0.03, rampOut: 0.06, strength: 6, targets: { abduction: 0.22 }, label: "exhale" });+ gestures.push({ t0: at, t1: end + 0.1, rampIn: 0.03, rampOut: 0.06, strength: 6, targets: { abduction: 0.22 }, label: EXHALE_LABEL });}// ---- intonation: pitch targets on vowelsconst f0 = o.f0 ?? 110;diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex b3224a2..70f126e 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -129,7 +129,7 @@ function StartPrompt() {const first = creatureById(creature)?.calls[0];if (mode === "bestiary" && first) playCall(first.id);else if (mode === "beatbox") setBeatPlaying(true);- else if (mode === "sing") void playDemo(DEMO_SONGS[0].name, useStore.getState().body);+ 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/components/SingPanel.tsx b/src/ui/components/SingPanel.tsxindex f01bc4b..c1a0235 100644--- a/src/ui/components/SingPanel.tsx+++ b/src/ui/components/SingPanel.tsx@@ -83,8 +83,7 @@ function SongAndVoice() {stopSinging();return;}- await start();- await playDemo(s.name, body);+ await playDemo(s.name, body, start);}}>{demo === s.name ? `Stop “${s.name}”` : s.name}diff --git a/src/ui/midi.ts b/src/ui/midi.tsindex 2294c6e..9cc8ae8 100644--- a/src/ui/midi.ts+++ b/src/ui/midi.ts@@ -1,6 +1,8 @@/*** Web MIDI keyboards: note on/off (with velocity) from every connected input, including ones- * plugged in later. All-notes-off and unplugging release whatever that input was holding.+ * plugged in later. The voice hears one note per pitch: a pitch held on several keyboards or+ * channels sounds until the last of them lets go. All-notes-off and unplugging release what+ * that input (channel) was holding.*/export type MidiStatus = "off" | "connecting" | "on" | "unsupported" | "denied";@@ -13,51 +15,87 @@ export interface MidiHandlers {export const midiSupported = (): boolean => typeof navigator !== "undefined" && typeof navigator.requestMIDIAccess === "function";+let handlers: MidiHandlers | null = null;let access: MIDIAccess | null = null;-/** notes held per input id */-const held = new Map<string, Set<number>>();--export async function connectMidi(h: MidiHandlers): Promise<void> {- if (access) return;- const a = await navigator.requestMIDIAccess({ sysex: false });- access = a;- const releaseInput = (id: string) => {- const notes = held.get(id);- if (notes) for (const n of notes) h.noteOff(n);- held.delete(id);- };- const attach = () => {- const names: string[] = [];- const live = new Set<string>();- a.inputs.forEach((input) => {- live.add(input.id);- names.push(input.name || "MIDI keyboard");- input.onmidimessage = (e: MIDIMessageEvent) => {- const d = e.data;- if (!d || d.length < 2) return;- const kind = d[0] & 0xf0;- const notes = held.get(input.id) ?? new Set<number>();- held.set(input.id, notes);- if (kind === 0x90 && d[2] > 0) {- notes.add(d[1]);- h.noteOn(d[1], d[2]);- } else if (kind === 0x80 || (kind === 0x90 && d[2] === 0)) {- if (notes.delete(d[1])) h.noteOff(d[1]);- } else if (kind === 0xb0 && (d[1] === 123 || d[1] === 120)) releaseInput(input.id); // all notes / sound off- };- });- for (const id of [...held.keys()]) if (!live.has(id)) releaseInput(id);- h.inputs(names);+let pending: Promise<void> | null = null;+/** bumped by disconnect: a connection still waiting for permission then gives up */+let generation = 0;+/** who holds each pitch, as "input id \0 channel" */+const owners = new Map<number, Set<string>>();+const SEP = "\u0000";++function press(owner: string, note: number, velocity: number): void {+ let set = owners.get(note);+ if (!set) owners.set(note, (set = new Set()));+ const first = set.size === 0;+ set.add(owner);+ if (first) handlers?.noteOn(note, velocity);+}++function lift(owner: string, note: number): void {+ const set = owners.get(note);+ if (!set || !set.delete(owner)) return;+ if (set.size > 0) return;+ owners.delete(note);+ handlers?.noteOff(note);+}++/** Release every note whose owner matches. */+function liftWhere(match: (owner: string) => boolean): void {+ for (const [note, set] of [...owners]) for (const o of [...set]) if (match(o)) lift(o, note);+}++function attach(a: MIDIAccess): void {+ const names: string[] = [];+ const live = new Set<string>();+ a.inputs.forEach((input) => {+ if (input.state === "disconnected") return;+ live.add(input.id);+ names.push(input.name || "MIDI keyboard");+ input.onmidimessage = (e: MIDIMessageEvent) => {+ const d = e.data;+ if (!d || d.length < 2) return;+ const kind = d[0] & 0xf0;+ const owner = input.id + SEP + (d[0] & 0x0f);+ if (kind === 0x90 && d.length > 2 && d[2] > 0) press(owner, d[1], d[2]);+ else if (kind === 0x80 || kind === 0x90) lift(owner, d[1]);+ else if (kind === 0xb0 && (d[1] === 123 || d[1] === 120)) liftWhere((o) => o === owner); // all notes / sound off+ };+ });+ // unplugged inputs release what they held+ liftWhere((o) => !live.has(o.slice(0, o.indexOf(SEP))));+ handlers?.inputs(names);+}++/** Ask for MIDI access and listen (one request at a time; resolves when connected). */+export function connectMidi(h: MidiHandlers): Promise<void> {+ handlers = h;+ if (access) return Promise.resolve();+ if (pending) return pending;+ const gen = generation;+ const p = navigator.requestMIDIAccess({ sysex: false }).then(+ (a) => {+ if (gen !== generation) return; // disconnected while the browser was asking+ access = a;+ a.onstatechange = () => attach(a);+ attach(a);+ },+ );+ pending = p;+ const clear = () => {+ if (pending === p) pending = null;};- a.onstatechange = attach;- attach();+ p.then(clear, clear);+ return p;}-export function disconnectMidi(h: Pick<MidiHandlers, "noteOff">): void {- if (!access) return;- access.inputs.forEach((input) => (input.onmidimessage = null));- access.onstatechange = null;- access = null;- for (const notes of held.values()) for (const n of notes) h.noteOff(n);- held.clear();+export function disconnectMidi(): void {+ generation++;+ pending = null;+ if (access) {+ access.inputs.forEach((input) => (input.onmidimessage = null));+ access.onstatechange = null;+ access = null;+ }+ liftWhere(() => true);}diff --git a/src/ui/singing.ts b/src/ui/singing.tsindex 92bce1a..db6aa6c 100644--- a/src/ui/singing.ts+++ b/src/ui/singing.ts@@ -11,6 +11,7 @@ import { engine } from "../audio/AudioEngine.ts";import { g2p } from "./speech.ts";import { lyricsToSyllables, type Syllable } from "../engine/phonetics/syllables.ts";import { planSong, planNoteOn, planNoteOff, planMelisma } from "../engine/phonetics/sing.ts";+import { EXHALE_LABEL } from "../engine/phonetics/planner.ts";import { DEMO_SONGS } from "../engine/phonetics/songs.ts";import type { Gesture } from "../engine/control/score.ts";import type { BodyName } from "../worklet/protocol.ts";@@ -93,6 +94,8 @@ 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;/** 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);@@ -118,6 +121,8 @@ 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);const from = sounding;if (from) {engine.release(from.tag);@@ -170,8 +175,12 @@ export function singNoteOff(midi: number, body: BodyName): void {// a melisma comes next: this vowel carries on there, and the coda waits for the chain's endconst st = useSing.getState();if (st.syllables[st.cursor]?.melisma) return;- const tail = planNoteOff(s.syl, midi, body);- if (tail.length) engine.scheduleGestures(tail);+ const gs = planNoteOff(s.syl, midi, body);+ if (!gs.length) return;+ const tag = nextTag;+ nextTag += 2;+ engine.scheduleGestures(gs.map((g) => ({ ...g, tag: g.label === EXHALE_LABEL ? tag + 1 : tag })));+ tail = tag;}// ---- demo songs@@ -188,6 +197,8 @@ interface DemoRun {}let demoRun: DemoRun | null = null;+/** bumped by every stop: a demo still waiting for audio or the dictionary then gives up */+let demoToken = 0;engine.onPlanned((m) => {const d = demoRun;@@ -196,15 +207,19 @@ engine.onPlanned((m) => {d.times.forEach(([a, b], k) => addNote(d.midi[k], m.t0 + a, d.text[k], true, m.t0 + b - 0.02));});-export async function playDemo(name: string, body: BodyName): Promise<void> {+/** Sing a demo song (after `ready`, e.g. audio startup, resolves; unless stopped meanwhile). */+export async function playDemo(name: string, body: BodyName, ready?: () => Promise<void>): Promise<void> {const song = DEMO_SONGS.find((s) => s.name === name);if (!song) return;stopSinging();+ const token = demoToken;+ await ready?.();try {await g2p.load();} catch {// letter-to-sound rules}+ if (token !== demoToken) return;const syl = lyricsToSyllables(song.lyrics, g2p);if (!syl.length) return;const shift = song.octave[body] * 12;@@ -224,6 +239,7 @@ export async function playDemo(name: string, body: BodyName): Promise<void> {}function stopDemo(): void {+ demoToken++;const d = demoRun;if (!d) return;demoRun = null;@@ -250,7 +266,7 @@ export function tickSinging(): void {if (k !== useSing.getState().demoAt) useSing.setState({ demoAt: k });}-/** Stop everything sung (leaving Sing mode, changing body). */+/** Stop everything sung (leaving Sing mode, changing body): demo, notes and endings. */export function stopSinging(): void {stopDemo();if (sounding) {@@ -259,6 +275,11 @@ export function stopSinging(): void {sounding.note.t1 = now();sounding = null;}+ if (tail !== null) {+ engine.release(tail);+ engine.release(tail + 1);+ tail = null;+ }keys = [];}diff --git a/src/ui/store.ts b/src/ui/store.tsindex 7a8681c..4d01c16 100644--- a/src/ui/store.ts+++ b/src/ui/store.ts@@ -276,6 +276,16 @@ export const useStore = create<State>((set, get) => ({const held = get().heldNotes.filter((n) => n !== midi).concat(midi);set({ heldNotes: held });const s = get();+ // 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+ if (!s.started && (s.mode === "sing" || (s.mode === "bestiary" && s.keyCall))) {+ const mode = s.mode;+ void s.start().then(() => {+ const t = get();+ if (t.started && t.mode === mode && t.heldNotes.includes(midi)) t.noteOn(midi, velocity);+ });+ return;+ }if (s.mode === "sing") singNoteOn(midi, velocity, s.body);else if (s.mode === "bestiary") {const pp = creatureById(s.creature)?.params.find((p) => p.role === "pitch");@@ -315,7 +325,7 @@ export const useStore = create<State>((set, get) => ({setMidi: (on) => {const noteOff = (n: number) => get().noteOff(n);if (!on) {- disconnectMidi({ noteOff });+ disconnectMidi();set({ midi: { status: "off", inputs: [] } });return;}@@ -329,6 +339,8 @@ export const useStore = create<State>((set, get) => ({},noteOff,inputs: (names) => set({ midi: { status: "on", inputs: names } }),- }).catch(() => set({ midi: { status: "denied", inputs: [] } }));+ }).catch(() => {+ if (get().midi.status === "connecting") set({ midi: { status: "denied", inputs: [] } });+ });},}));diff --git a/src/worklet/processor.ts b/src/worklet/processor.tsindex 0b15b2f..084a5c6 100644--- a/src/worklet/processor.ts+++ b/src/worklet/processor.ts@@ -34,6 +34,8 @@ 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 */+ private afterBody: ToWorklet[] = [];constructor() {super();@@ -53,6 +55,10 @@ class ChimeraProcessor extends AudioWorkletProcessor {}private onMessage(m: ToWorklet): void {+ if (this.pendingBody && (m.type === "schedule" || m.type === "release" || m.type === "stopSpeech" || m.type === "beatHit")) {+ this.afterBody.push(m);+ return;+ }switch (m.type) {case "body":this.pendingBody = m.body;@@ -146,6 +152,9 @@ 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.pendingCreature !== null) {const id = this.pendingCreature;diff --git a/tests/live-control.test.ts b/tests/live-control.test.tsnew file mode 100644index 0000000..01d8231--- /dev/null+++ b/tests/live-control.test.ts@@ -0,0 +1,110 @@+/**+ * Ownership and ordering of live control: tagged releases never let a gesture rise again, the+ * worklet applies score messages sent during a body change to the new voice, and MIDI notes+ * held on several keyboards/channels end only when the last one lets go.+ */+import { describe, expect, test } from "bun:test";+import { GestureScore, activation } from "../src/engine/control/score.ts";+import { planNoteOn } from "../src/engine/phonetics/sing.ts";+import type { Syllable } from "../src/engine/phonetics/syllables.ts";+import type { HumanVoice } from "../src/engine/voice/humanVoice.ts";++describe("tagged release", () => {+ test("a note released early drops what has not begun and fades what has, never rising again", () => {+ // /strɑ/ held, released 30 ms in: the vowel and its pitch have not begun yet+ const syl: Syllable = { text: "stra", onset: [{ ipa: "s" }, { ipa: "t" }, { ipa: "ɹ" }], nucleus: { ipa: "ɑ", stress: 1 }, coda: [], wordEnd: true, phraseEnd: false };+ const gs = planNoteOn(syl, 57, { body: "male", vibrato: 30, tag: 4 });+ const score = new GestureScore();+ score.addAll(gs.map((g) => ({ ...g, t0: g.t0 + 0.05, t1: g.t1 + 0.05 })));+ const t = 0.08;+ const before = new Map(score.activeAt(t).map((g) => [g, activation(g, t)]));+ score.release(4, t);+ score.release(5, t);+ for (const g of score.activeAt(t)) expect(activation(g, t)).toBeCloseTo(before.get(g) ?? 0, 6); // continuous+ // after the release, no released gesture's activation exceeds what it had at the release+ for (let tt = t; tt < t + 0.5; tt += 0.002)+ for (const g of score.activeAt(tt)) if (g.tag === 4 || g.tag === 5) expect(activation(g, tt)).toBeLessThanOrEqual((before.get(g) ?? 0) + 1e-9);+ // the vowel (not begun at 80 ms) is gone, and everything is over soon after+ expect(score.activeAt(0.3).length).toBe(0);+ });+});++describe("worklet ordering", () => {+ test("a note scheduled right after a body change plays on the new voice", async () => {+ let Proc: (new () => { port: { onmessage: ((e: { data: unknown }) => void) | null }; process: (i: unknown, o: Float32Array[][]) => boolean }) | null = null;+ const g = globalThis as Record<string, unknown>;+ g.sampleRate = 48000;+ g.AudioWorkletProcessor = class {+ port = { onmessage: null as unknown, postMessage: () => {} };+ };+ g.registerProcessor = (_name: string, ctor: typeof Proc) => (Proc = ctor);+ await import("../src/worklet/processor.ts");+ const p = new Proc!();+ const send = (data: unknown) => p.port.onmessage!({ data });+ const breath = { t0: 0, t1: 1, rampIn: 0.04, rampOut: 0.05, strength: 1, targets: { breath: 1 }, label: "breath" };+ send({ type: "body", body: "female" });+ send({ type: "schedule", gestures: [breath], segments: [], end: 1, id: 1, replace: false, lead: 0.006 });+ p.process([], [[new Float32Array(128)]]);+ const voice = (p as unknown as { voice: HumanVoice }).voice;+ expect(voice.airway.body.scale).toBeLessThan(1); // the new (female) voice+ expect(voice.score.size).toBe(1); // holding the note+ });+});++describe("MIDI ownership", () => {+ type Listener = ((e: { data: Uint8Array }) => void) | null;+ function fakeMidi() {+ const inputs = new Map<string, { id: string; name: string; state: string; onmidimessage: Listener }>();+ const access = { inputs, onstatechange: null as null | (() => void) };+ let resolve!: (a: typeof access) => void;+ let requests = 0;+ Object.defineProperty(globalThis.navigator, "requestMIDIAccess", {+ configurable: true,+ value: () => {+ requests++;+ return new Promise((r) => (resolve = r));+ },+ });+ const plug = (id: string) => inputs.set(id, { id, name: id, state: "connected", onmidimessage: null });+ const msg = (id: string, ...bytes: number[]) => inputs.get(id)!.onmidimessage?.({ data: Uint8Array.from(bytes) });+ return { access, plug, msg, grant: () => resolve(access), requests: () => requests };+ }++ test("one note per pitch across keyboards and channels; unplugging releases; disconnect cancels a pending request", async () => {+ const midi = await import("../src/ui/midi.ts");+ const f = fakeMidi();+ f.plug("A");+ f.plug("B");+ const log: string[] = [];+ let names: string[] = [];+ const h = { noteOn: (n: number) => log.push(`on ${n}`), noteOff: (n: number) => log.push(`off ${n}`), inputs: (x: string[]) => (names = x) };+ const c = midi.connectMidi(h);+ void midi.connectMidi(h); // a second click while the browser is asking+ expect(f.requests()).toBe(1);+ f.grant();+ await c;+ expect(names).toEqual(["A", "B"]);+ f.msg("A", 0x90, 60, 100); // A holds C4+ f.msg("B", 0x90, 60, 90); // B holds C4 too+ f.msg("A", 0x91, 60, 80); // and A again, on channel 2+ f.msg("A", 0x80, 60, 0);+ f.msg("A", 0x91, 60, 0); // note-on with velocity 0 = note-off+ expect(log).toEqual(["on 60"]); // B still holds it+ f.msg("B", 0x90, 64, 70);+ f.access.inputs.delete("B"); // B unplugged+ f.access.onstatechange!();+ expect(log).toEqual(["on 60", "on 64", "off 60", "off 64"]);+ midi.disconnectMidi();++ // disconnect while the browser is still asking: the late grant must not connect+ const g2 = fakeMidi();+ g2.plug("C");+ let late: string[] | null = null;+ const pending = midi.connectMidi({ ...h, inputs: (x) => (late = x) });+ midi.disconnectMidi();+ g2.grant();+ await pending;+ expect(late).toBeNull();+ expect(g2.access.inputs.get("C")!.onmidimessage).toBeNull();+ });+});diff --git a/tests/singing-live.test.ts b/tests/singing-live.test.tsindex 2240f34..c051365 100644--- a/tests/singing-live.test.ts+++ b/tests/singing-live.test.ts@@ -6,7 +6,7 @@import { describe, expect, mock, test } from "bun:test";import { HumanVoice } from "../src/engine/voice/humanVoice.ts";import { midiToHz } from "../src/engine/phonetics/sing.ts";-import type { Gesture } from "../src/engine/control/score.ts";+import { activation, type Gesture } from "../src/engine/control/score.ts";const FS = 48000;let voice = new HumanVoice({ fsOut: FS });@@ -28,7 +28,8 @@ const fakeEngine = {stopSpeech: () => voice.cancelScore(),};mock.module("../src/audio/AudioEngine.ts", () => ({ engine: fakeEngine }));-const { useSing, singNoteOn, singNoteOff } = await import("../src/ui/singing.ts");+const { useSing, singNoteOn, singNoteOff, playDemo, stopSinging } = await import("../src/ui/singing.ts");+const gesturesOf = () => (voice.score as unknown as { gestures: Gesture[] }).gestures;/** Render `sec` seconds; per 2.7 ms block: f0, voicing, output RMS, narrowest oral area. */function run(sec: number) {@@ -118,4 +119,47 @@ describe("Sing mode, live keys", () => {if (process.env.SING_VERBOSE) console.log(`hard vs soft key: ${(20 * Math.log10(hard.rms / soft.rms)).toFixed(1)} dB`);expect(hard.rms / soft.rms).toBeGreaterThan(1.6); // > 4 dB});++ 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));+ 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+ go();+ await waiting;+ expect(scheduled).toBe(0);+ expect(useSing.getState().demo).toBeNull();+ await playDemo("Made of air", "male", () => Promise.resolve());+ expect(scheduled).toBe(1);+ expect(useSing.getState().demo).toBe("Made of air");+ stopSinging();+ fakeEngine.schedule = schedule;+ });++ test("a quick next note drops the last one's breath-out; leaving Sing cancels a pending ending", () => {+ voice = new HumanVoice({ fsOut: FS });+ useSing.getState().setVibrato(0);+ useSing.getState().setLyrics("cat dog");+ run(0.05);+ singNoteOn(50, 96, "male");+ run(0.4);+ singNoteOff(50, "male"); // "cat": its /t/ and the breath-out are scheduled+ expect(gesturesOf().some((g) => g.label === "exhale")).toBe(true);+ run(0.02);+ singNoteOn(52, 96, "male"); // "dog" straight after+ expect(gesturesOf().some((g) => g.label === "exhale")).toBe(false);+ const d = run(0.4);+ expect(Math.min(...d.late(d.voicing))).toBeGreaterThan(0.5);+ singNoteOff(52, "male"); // "dog": its /g/ ending is scheduled...+ run(0.01);+ stopSinging(); // ...and the mode changes at once+ run(0.06);+ // the cancelled ending's breath is gone (the note's own breath is at the end of its 70 ms fade)+ 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);+ });});diff --git a/tools/e2e.ts b/tools/e2e.tsindex e81adf1..a780910 100644--- a/tools/e2e.ts+++ b/tools/e2e.ts@@ -177,6 +177,24 @@ async function run(viewport: { width: number; height: number }, tag: string) {await page.close();}+// the very first key in Sing mode, before audio has started, still sings once audio is up+{+ const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });+ page.on("pageerror", (e) => errors.push(`[first-key] pageerror: ${e.message}`));+ await page.goto(url, { waitUntil: "networkidle" });+ await page.getByRole("radio", { name: "Sing" }).click();+ await page.keyboard.down("d");+ await page.waitForTimeout(1200);+ const level = await page.evaluate(() => {+ // @ts-expect-error debug handle+ return window.__chimeraEngine?.latest?.t?.outRms ?? -1;+ });+ await page.keyboard.up("d");+ logs.push(`[first-key] sing before start: rms ${level.toFixed(4)}`);+ if (!(level > 0.01)) errors.push(`[first-key] the first sung key, pressed before audio started, made no sound (${level})`);+ await page.close();+}+await run({ width: 1440, height: 980 }, "desktop");await run({ width: 390, height: 844 }, "mobile");await browser.close();