the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Words at the mouth: the syllable sung or word spoken, in front of the lips
Jameson Hodgee1d0a5fc3cbd
diff --git a/crates/chimera-wasm/src/api.rs b/crates/chimera-wasm/src/api.rsindex 3b46e72..6174d63 100644--- a/crates/chimera-wasm/src/api.rs+++ b/crates/chimera-wasm/src/api.rs@@ -138,6 +138,9 @@ fn dispatch(st: &mut State, req: &Value) -> Res {}// ---------------------------------------------------------------- planning (speech, song)"planUtterance" => to_json(&planner::plan_utterance(&arg::<Vec<Segment>>(req, "segments")?, &arg::<PlanOptions>(req, "options")?)),+ // how many planned segments each segment becomes (a diphthong plans as its two vowels),+ // so the UI can find a word's span in a plan's timeline+ "plannedCounts" => to_json(&arg::<Vec<String>>(req, "ipa")?.iter().map(|s| planner::expand(s).map_or(1, |p| p.len())).collect::<Vec<_>>()),"planPhrases" => to_json(&planner::plan_phrases(&arg::<Vec<PhraseInput>>(req, "phrases")?, &arg::<PlanOptions>(req, "options")?)),"planSong" => to_json(&sing::plan_song(&arg::<Vec<SungNote>>(req, "notes")?, &arg::<SongOptions>(req, "options")?)),"planNoteOn" => to_json(&sing::plan_note_on(&arg::<Syllable>(req, "syl")?, arg(req, "midi")?, &arg::<NoteOnOptions>(req, "options")?)),diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 3669bf0..42549da 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -10,12 +10,12 @@ import { VoiceControls, VoiceToggles } from "./components/VoiceControls.tsx";import { Keys } from "./components/Keys.tsx";import { Segmented, Toggle } from "./components/Controls.tsx";import { Screen } from "./components/Screen.tsx";-import { SpeakRight, speechInfo, speechSlots } from "./components/SpeakPanel.tsx";+import { SpeakRight, speechInfo, speechSlots, speechWords } from "./components/SpeakPanel.tsx";import { BestiaryRight } from "./components/BestiaryPanel.tsx";import { CreatureView } from "./components/CreatureView.tsx";import { creatureById } from "../wasm/engine.ts";import { BeatboxRight, BeatOverlay, beatInfo, beatSlots } from "./components/BeatboxPanel.tsx";-import { SingRight, singInfo } from "./components/SingPanel.tsx";+import { SingRight, singInfo, singWords } from "./components/SingPanel.tsx";import { playDemo, DEMO_SONGS } from "./singing.ts";import type { Mode } from "./store.ts";import type { BodyName } from "../worklet/protocol.ts";@@ -157,7 +157,7 @@ function LeftScreen() {label={bestiary ? "Live creature airway" : "Live vocal tract"}tools={<ViewToggles />}>- {bestiary ? <CreatureView /> : mode === "speak" ? <AnatomyView slots={speechSlots} info={speechInfo} /> : mode === "sing" ? <AnatomyView info={singInfo} /> : mode === "beatbox" ? <AnatomyView slots={beatSlots} info={beatInfo} showFormants={false} /> : <AnatomyView />}+ {bestiary ? <CreatureView /> : mode === "speak" ? <AnatomyView slots={speechSlots} info={speechInfo} overlay={speechWords} /> : mode === "sing" ? <AnatomyView info={singInfo} overlay={singWords} /> : mode === "beatbox" ? <AnatomyView slots={beatSlots} info={beatInfo} showFormants={false} /> : <AnatomyView />}{mode === "beatbox" && <BeatOverlay />}<StartPrompt /></Screen>diff --git a/src/ui/components/AnatomyView.tsx b/src/ui/components/AnatomyView.tsxindex b214384..aee4307 100644--- a/src/ui/components/AnatomyView.tsx+++ b/src/ui/components/AnatomyView.tsx@@ -15,6 +15,9 @@ export type SlotsFn = (m: VoiceModel, a: HumanArtic, f: HumanFrame, formants: nu/** The small lines under the formants; a mode can pass its own. */export type InfoFn = (m: VoiceModel, f: HumanFrame, tele: TelemetryMessage | null) => string[];+/** drawn over the face each frame, before the glow (Sing and Speak write the words at the mouth) */+export type OverlayFn = (ctx: CanvasRenderingContext2D, r: AnatomyRenderer, m: VoiceModel, f: HumanFrame, a: HumanArtic, size: { w: number; h: number; dt: number }) => void;+/** the tract's length and mouth opening, then the live pitch and lungs */export const tractInfo: InfoFn = (_m, f, tele) => {const info = [`Tract ${f.length.toFixed(1)} cm`, `Mouth ${f.lipArea.toFixed(1)} cm²`];@@ -43,7 +46,9 @@ export const articulatorSlots: SlotsFn = (m, a, f, formants) => [f.velumPort > 0.02 ? { label: "Soft palate", value: f.velumPort.toFixed(2), unit: "cm²", color: V.white } : { label: "Soft palate", value: "Shut", color: V.white },];-export function AnatomyView(props: { slots?: SlotsFn; info?: InfoFn; showFormants?: boolean }) {+export function AnatomyView(props: { slots?: SlotsFn; info?: InfoFn; showFormants?: boolean; overlay?: OverlayFn }) {+ const overlayRef = useRef<OverlayFn | undefined>(props.overlay);+ overlayRef.current = props.overlay;const formantsRef = useRef(props.showFormants ?? true);formantsRef.current = props.showFormants ?? true;const slotsRef = useRef<SlotsFn>(props.slots ?? articulatorSlots);@@ -100,6 +105,7 @@ export function AnatomyView(props: { slots?: SlotsFn; info?: InfoFn; showFormantctx.fillRect(0, 0, canvas.width, canvas.height);ctx.setTransform(dpr, 0, 0, dpr, 0, 0);r.draw(ctx, m, f, a, tele, st.view, { hover: hoverRef.current, drag: dragRef.current?.id ?? null, dt, formants: formantsRef.current ? formants : [], slots: slotsRef.current(m, a, f, formants, tele), info: info.map((s) => s.toUpperCase()) });+ overlayRef.current?.(ctx, r, m, f, a, { w, h, dt });glow.apply(canvas, ctx, dpr);}raf = requestAnimationFrame(loop);diff --git a/src/ui/components/SingPanel.tsx b/src/ui/components/SingPanel.tsxindex 5dc01e2..6783b68 100644--- a/src/ui/components/SingPanel.tsx+++ b/src/ui/components/SingPanel.tsx@@ -1,5 +1,7 @@import { useStore } from "../store.ts";-import { useSing, playDemo, stopSinging, soundingSyllable, DEMO_SONGS } from "../singing.ts";+import { useSing, playDemo, stopSinging, soundingSyllable, sungNow, DEMO_SONGS } from "../singing.ts";+import { mouthWords } from "../mouthWords.ts";+import { V } from "../colors.ts";import { Keys } from "./Keys.tsx";import { PianoRoll } from "./PianoRoll.tsx";import { SpectrumView } from "./SpectrumView.tsx";@@ -18,6 +20,9 @@ function syllableNow(): string | null {return soundingSyllable();}+/** the syllable being sung, at the mouth */+export const singWords = mouthWords(sungNow, V.green);+/** Sing mode's lines over the face: the note, the syllable, the ring */export const singInfo: InfoFn = (_m, _f, tele) => {const out: string[] = [];diff --git a/src/ui/components/SpeakPanel.tsx b/src/ui/components/SpeakPanel.tsxindex 9b929de..5bb8ee5 100644--- a/src/ui/components/SpeakPanel.tsx+++ b/src/ui/components/SpeakPanel.tsx@@ -1,6 +1,7 @@import { useEffect, useState } from "react";import { useStore } from "../store.ts";-import { speakText, speakPhrases, stopSpeaking, onPlan, currentPlan } from "../speech.ts";+import { speakText, speakPhrases, stopSpeaking, onPlan, currentPlan, spokenWordNow } from "../speech.ts";+import { mouthWords } from "../mouthWords.ts";import { tokenizeIpa } from "../../wasm/engine.ts";import { Slider, Toggle } from "./Controls.tsx";import { Chip, Screen } from "./Screen.tsx";@@ -38,6 +39,9 @@ function soundingSegment(): string | null {}/** Speak mode's readouts under the chin: the sound being made, jaw, lip shape, soft palate */+/** the word being spoken, at the mouth */+export const speechWords = mouthWords(spokenWordNow, V.white);+export const speechSlots: SlotsFn = (_m, a, f) => {const sound = soundingSegment();const lips = a.lipAp < 0.05 ? "Closed" : a.lipWidth < 0.55 ? "Round" : a.lipAp > 1.3 ? "Open" : "Spread";diff --git a/src/ui/mouthWords.ts b/src/ui/mouthWords.tsnew file mode 100644index 0000000..4c03b6b--- /dev/null+++ b/src/ui/mouthWords.ts@@ -0,0 +1,48 @@+/**+ * Words at the mouth: the syllable being sung or the word being spoken, written just in front of+ * the lips as it sounds. When the next one starts, it shrinks, dims and flies up and away, so a+ * fast scat run leaves a short trail instead of a pile-up.+ */+import { hfont, label, seg } from "./render/vector.ts";+import type { OverlayFn } from "./components/AnatomyView.tsx";++/** What is being said now. `key` changes with each new syllable or word (equal text may repeat). */+export interface MouthWord {+ key: unknown;+ text: string;+}++/** how long a word takes to fly off (s) */+const FADE = 0.45;++/** An overlay writing `now()`'s word at the mouth in `color`; each call keeps its own trail. */+export function mouthWords(now: () => MouthWord | null, color: string): OverlayFn {+ const trail: { word: MouthWord; left: number | null }[] = [];+ let clock = 0;+ return (ctx, r, m, f, a, { w, dt }) => {+ clock += dt;+ const word = now();+ const top = trail[trail.length - 1];+ if (top && top.left === null && top.word.key !== word?.key) top.left = clock;+ if (word && top?.word.key !== word.key) trail.push({ word, left: null });+ while (trail.length && (trail.length > 8 || (trail[0].left !== null && clock - trail[0].left > FADE))) trail.shift();+ if (!trail.length) return;+ const lips = r.handles(m, f, a).find((h) => h.id === "lips");+ if (!lips) return;+ const lx = r.X(lips.pos), ly = r.Y(lips.pos);+ const x0 = lx + r.pxPerCm * 1.2;+ const room = Math.max(60, w - x0 - 14);+ const base = Math.max(26, Math.min(64, r.pxPerCm * 1.7));+ for (const { word: wd, left } of trail) {+ const age = left === null ? 0 : clock - left;+ const u = Math.min(1, age / FADE);+ const text = wd.text.toUpperCase();+ ctx.font = hfont(base, "m");+ const wide = ctx.measureText(text).width * 1.08;+ const size = (wide > room ? (base * room) / wide : base) * (1 - 0.55 * u);+ const alpha = left === null ? 1 : 0.75 * (1 - u) ** 1.5;+ label(ctx, text, x0 + age * 240, ly + size * 0.36 - age * 200, { size, color, weight: "m", ls: 0.05, alpha });+ }+ if (trail[trail.length - 1].left === null) seg(ctx, lx + 10, ly, x0 - 10, ly, color, 1, { dash: [2, 5], alpha: 0.7 });+ };+}diff --git a/src/ui/singing.ts b/src/ui/singing.tsindex e1d8ff3..7032e4e 100644--- a/src/ui/singing.ts+++ b/src/ui/singing.ts@@ -91,6 +91,24 @@ interface Sounding {let sounding: Sounding | null = null;+/** How a syllable is written at the mouth: a hyphen when its word goes on. */+const written = (s: Syllable) => s.text + (s.wordEnd ? "" : "-");++/**+ * The syllable being sung now, for the words at the mouth: the demo's note under the clock, or+ * the held key's. A melisma keeps its syllable's key, so the word stays while the pitch moves.+ */+export function sungNow(): { key: unknown; text: string } | null {+ const d = demoRun;+ if (d) {+ if (d.offset === null) return null;+ const t = now() - d.offset;+ const k = d.times.findIndex(([a, b]) => t >= a && t < b - 0.02);+ return k < 0 ? null : { key: `${d.id}:${d.parent[k]}`, text: d.shown[k] };+ }+ return sounding ? { key: sounding, text: written(sounding.syl) } : null;+}+/** The syllable whose vowel is sounding from the keys now (null when no key sings). */export function soundingSyllable(): string | null {return sounding?.syl.text ?? null;@@ -201,6 +219,9 @@ interface DemoRun {times: [number, number][];midi: number[];text: string[];+ /** what the mouth shows per note, and the note whose syllable it is (a melisma's parent) */+ shown: string[];+ parent: number[];end: number;/** voice clock of plan time 0, once the worklet has it */offset: number | null;@@ -244,7 +265,10 @@ export async function playDemo(name: string, body: BodyMix, ready?: () => Promisreturn [a, t];});const id = engine.schedule({ gestures: plan.gestures, segments: plan.segments, end: plan.end });- demoRun = { id, times, midi: notes.map((n) => n.midi), text: notes.map((n) => n.syl.text), end: plan.end, offset: null };+ const parent: number[] = [];+ notes.forEach((n, i) => parent.push(n.syl.melisma && i > 0 ? parent[i - 1] : i));+ const shown = parent.map((p) => written(notes[p].syl));+ demoRun = { id, times, midi: notes.map((n) => n.midi), text: notes.map((n) => n.syl.text), shown, parent, end: plan.end, offset: null };useSing.setState({ lyrics: song.lyrics, syllables: syl, cursor: 0, demo: song.name, demoAt: -1 });}diff --git a/src/ui/speech.ts b/src/ui/speech.tsindex 87d78bb..16630c2 100644--- a/src/ui/speech.ts+++ b/src/ui/speech.ts@@ -5,6 +5,7 @@ import { tokenizeIpa } from "../wasm/engine.ts";import { planPhrases, type Plan, type Segment } from "../wasm/engine.ts";import { engine } from "../audio/AudioEngine.ts";import type { Gesture } from "../wasm/types.ts";+import { wordSpans, type WordSpan } from "./words.ts";export const g2p = new EnglishG2P();@@ -14,9 +15,13 @@ export interface SpokenPlan {offset: number | null;id: number;transcription: string;+ /** each word's span in the plan */+ words: WordSpan[];}let current: SpokenPlan | null = null;+/** the plan a stop cut short: its words are no longer being said */+let cutId = -1;const listeners = new Set<(p: SpokenPlan | null) => void>();engine.onPlanned((m) => {if (current && m.id === current.id) {@@ -46,10 +51,10 @@ export function transcribe(phrases: { segments: Segment[]; intonation?: string }return phrases.map((p) => p.segments.map((s) => (s.stress === 1 ? "ˈ" : s.stress === 2 ? "ˌ" : "") + s.ipa + (s.wordEnd ? " " : "")).join("").trim() + (p.intonation === "question" ? "?" : "")).join(" | ");}-export function speakPhrases(phrases: { segments: Segment[]; intonation?: "statement" | "question" | "flat"; pause?: number }[], o: { body: BodyMix; rate: number; f0: number }): SpokenPlan {+export function speakPhrases(phrases: { segments: Segment[]; intonation?: "statement" | "question" | "flat"; pause?: number; words?: string[] }[], o: { body: BodyMix; rate: number; f0: number }): SpokenPlan {const plan = planPhrases(phrases, { body: o.body, t0: 0, rate: o.rate, f0: o.f0 });const id = engine.schedule({ gestures: plan.gestures.map((g: Gesture) => ({ ...g, targets: { ...g.targets } })), segments: plan.segments, end: plan.end });- current = { plan, offset: null, id, transcription: transcribe(phrases) };+ current = { plan, offset: null, id, transcription: transcribe(phrases), words: wordSpans(phrases, plan) };for (const l of listeners) l(current);return current;}@@ -72,4 +77,15 @@ export async function speakText(text: string, o: { ipa: boolean; body: BodyMix;export function stopSpeaking(): void {engine.stopSpeech();+ if (current) cutId = current.id;+}++/** The word being spoken now (null between words and once the speech is over or stopped). */+export function spokenWordNow(): { key: string; text: string } | null {+ const p = current;+ const t = engine.voiceClock();+ if (!p || p.offset === null || t === null || p.id === cutId) return null;+ const pt = t - p.offset;+ const i = p.words.findIndex((w) => pt >= w.t0 && pt < w.t1 + 0.05);+ return i < 0 ? null : { key: `${p.id}:${i}`, text: p.words[i].text };}diff --git a/src/ui/store.ts b/src/ui/store.tsindex ebe79d6..6e14cfe 100644--- a/src/ui/store.ts+++ b/src/ui/store.ts@@ -7,6 +7,7 @@ import { creatureById } from "../wasm/engine.ts";import type { ParamDef } from "../wasm/types.ts";import { BEAT_PRESETS, BASS_NOTE, beatReady, parseBeat, type BeatStep } from "../wasm/engine.ts";import { singNoteOn, singNoteOff, stopSinging, ensureDictionary } from "./singing.ts";+import { stopSpeaking } from "./speech.ts";import { connectMidi, disconnectMidi, type MidiStatus } from "./midi.ts";export type Mode = "play" | "speak" | "sing" | "bestiary" | "beatbox";@@ -137,7 +138,7 @@ export const useStore = create<State>((set, get) => ({// 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- if (prev === "speak" || m === "bestiary") engine.stopSpeech();+ if (prev === "speak" || m === "bestiary") stopSpeaking();if ((prev === "bestiary") !== (m === "bestiary")) {// a sustain belongs to the voice it was started onset({ hold: false });@@ -265,6 +266,8 @@ export const useStore = create<State>((set, get) => ({// the new voice starts without the old one's score: a sung note would hangif (get().mode === "sing") stopSinging();const f0 = defaultF0(b);+ // nor does speech carry over (and the new voice's clock starts again from zero)+ if (get().mode === "speak") stopSpeaking();set((s) => ({ body: b, source: { ...s.source, f0 } }));engine.setBody(b);},diff --git a/src/ui/words.ts b/src/ui/words.tsnew file mode 100644index 0000000..1d22743--- /dev/null+++ b/src/ui/words.ts@@ -0,0 +1,38 @@+/** Where each spoken word falls in a speech plan's timeline (for the words drawn at the mouth). */+import { plannedCounts, type Plan, type Segment } from "../wasm/engine.ts";++export interface WordSpan {+ text: string;+ /** plan time (s) */+ t0: number;+ t1: number;+}++/**+ * Each word's span in the plan of these phrases: from its first segment's start to its last's end.+ * A word ends at a segment marked `wordEnd` or at the end of its phrase. Without written words+ * (IPA input), a word is shown as its IPA.+ */+export function wordSpans(phrases: { segments: Segment[]; words?: string[] }[], plan: Plan): WordSpan[] {+ const out: WordSpan[] = [];+ const counts = plannedCounts(phrases.flatMap((p) => p.segments.map((s) => s.ipa)));+ let k = 0, j = 0;+ for (const p of phrases) {+ let wi = 0, t0: number | null = null, ipa = "";+ p.segments.forEach((s, i) => {+ const n = counts[k++];+ const first = plan.segments[j], last = plan.segments[j + n - 1];+ j += n;+ if (!first || !last) return;+ t0 ??= first.t0;+ ipa += s.ipa;+ if (s.wordEnd || i === p.segments.length - 1) {+ out.push({ text: p.words?.[wi] ?? ipa, t0, t1: last.t1 });+ wi++;+ t0 = null;+ ipa = "";+ }+ });+ }+ return out;+}diff --git a/src/wasm/engine.ts b/src/wasm/engine.tsindex 3bf5cd8..e18c180 100644--- a/src/wasm/engine.ts+++ b/src/wasm/engine.ts@@ -141,6 +141,11 @@ export function planUtterance(segments: Segment[], options: PlanOptions): Plan {return call("planUtterance", { segments, options });}+/** How many planned segments each segment becomes (a diphthong is planned as its two vowels). */+export function plannedCounts(ipa: string[]): number[] {+ return call("plannedCounts", { ipa });+}+export function planPhrases(phrases: { segments: Segment[]; intonation?: "statement" | "question" | "flat"; pause?: number }[], options: PlanOptions): Plan {return call("planPhrases", { phrases: phrases.map((p) => ({ segments: p.segments, intonation: p.intonation, pause: p.pause })), options });}diff --git a/tests/words.test.ts b/tests/words.test.tsnew file mode 100644index 0000000..4850acd--- /dev/null+++ b/tests/words.test.ts@@ -0,0 +1,43 @@+/**+ * Words at the mouth: each spoken word's span in a speech plan, across diphthongs (planned as two+ * vowels) and phrase breaks.+ */+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { gunzipSync } from "node:zlib";+import { initEngine } from "./harness.ts";++await initEngine();+const { EnglishG2P, planPhrases, tokenizeIpa } = await import("../src/wasm/engine.ts");+const { wordSpans } = await import("../src/ui/words.ts");+const g2p = new EnglishG2P();+g2p.setDictionaryText(gunzipSync(readFileSync(new URL("../public/data/cmudict.txt.gz", import.meta.url))).toString());+const male = { female: 0, child: 0 };++describe("word spans", () => {+ test("a diphthong doesn't shift the words after it", () => {+ const phrases = g2p.toPhrases("I'll be here all week.");+ const plan = planPhrases(phrases, { body: male, t0: 0 });+ const words = wordSpans(phrases, plan);+ expect(words.map((w) => w.text)).toEqual(["i'll", "be", "here", "all", "week"]);+ // "I'll" is a, ɪ, ɫ in the plan: it ends where the ɫ ends, and "be" starts on the b+ const l = plan.segments.findIndex((s) => s.ipa === "ɫ");+ expect(words[0].t1).toBe(plan.segments[l].t1);+ expect(words[1].t0).toBe(plan.segments.find((s) => s.ipa === "b")!.t0);+ expect(words[4].t1).toBe(plan.segments[plan.segments.length - 1].t1);+ for (let i = 1; i < words.length; i++) expect(words[i].t0).toBeGreaterThanOrEqual(words[i - 1].t1 - 1e-9);+ });++ test("phrases follow one another, and IPA input is shown as IPA", () => {+ const phrases = [+ { segments: tokenizeIpa("haɪ ðɛə"), intonation: "statement" as const, pause: 0.3 },+ { segments: tokenizeIpa("goʊ"), intonation: "statement" as const, pause: 0.3 },+ ];+ const plan = planPhrases(phrases, { body: male, t0: 0 });+ const words = wordSpans(phrases, plan);+ expect(words.map((w) => w.text)).toEqual(["haɪ", "ðɛə", "goʊ"]);+ // the second phrase's word starts after the pause, on its own g+ expect(words[2].t0).toBe(plan.segments.find((s) => s.ipa === "g")!.t0);+ expect(words[2].t0).toBeGreaterThan(words[1].t1 + 0.2);+ });+});