the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Speech intelligibility: no nasal spread, Klatt durations, faster vowels, place cues
Jameson Hodge9a068dfe7f99
diff --git a/src/engine/anatomy/human.ts b/src/engine/anatomy/human.tsindex 9559a48..d511b70 100644--- a/src/engine/anatomy/human.ts+++ b/src/engine/anatomy/human.ts@@ -79,7 +79,7 @@ export const NEUTRAL: HumanArtic = {lipProt: 0.2,lipWidth: 0.5,labiodental: 0,- velum: 0,+ velum: -0.15,larynx: 0,epilarynx: 0,ventricular: 0,diff --git a/src/engine/control/articulators.ts b/src/engine/control/articulators.tsindex 2b1cc2e..7e80666 100644--- a/src/engine/control/articulators.ts+++ b/src/engine/control/articulators.ts@@ -18,20 +18,27 @@ export interface ArticSpec {hz: number;}+/** keys blended as base + min(1, w/2)·(value − base) instead of a weighted mean */+const BOUNDED = new Set<ArticKey>(["velum"]);+export const ARTIC_SPECS: Record<ArticKey, ArticSpec> = {- jaw: { min: -0.1, max: 2.6, hz: 5 },- tbX: { min: 1.0, max: 4.8, hz: 6.5 },- tbY: { min: 4.8, max: 9.2, hz: 6.5 },+ // vowel articulators fast enough to reach their targets in Klatt-length vowels (VocalTractLab's+ // fitted time constants are mostly 5–40 ms; second-order ω = 2π·hz here)+ jaw: { min: -0.1, max: 2.6, hz: 10 },+ tbX: { min: 1.0, max: 4.8, hz: 12 },+ tbY: { min: 4.8, max: 9.2, hz: 12 },ttX: { min: 3.5, max: 8.0, hz: 13 },ttY: { min: 5.0, max: 10.8, hz: 13 },ttCurl: { min: 0, max: 1, hz: 9 },- root: { min: -1, max: 1, hz: 5 },+ root: { min: -1, max: 1, hz: 9 },lipAp: { min: -0.4, max: 2.4, hz: 11 },- lipProt: { min: -0.2, max: 1.5, hz: 7 },- lipWidth: { min: 0, max: 1, hz: 7 },+ lipProt: { min: -0.2, max: 1.5, hz: 11 },+ lipWidth: { min: 0, max: 1, hz: 11 },labiodental: { min: 0, max: 1, hz: 10 },- velum: { min: 0, max: 1.4, hz: 5 },- larynx: { min: -1.6, max: 1.6, hz: 3.5 },+ // the velum moves fast (it must seal within a few tens of ms after a nasal) and rests a+ // little past closed, so a closure seals in finite time instead of creeping to zero+ velum: { min: -0.25, max: 1.4, hz: 12 },+ larynx: { min: -1.6, max: 1.6, hz: 8 },epilarynx: { min: 0, max: 1, hz: 6 },ventricular: { min: 0, max: 1, hz: 6 },lateral: { min: 0, max: 1, hz: 10 },@@ -98,8 +105,15 @@ export class ArticulatorBank {if (blend) {const b = blend(k);if (b && b.weight > 0) {- const bw = baseWeight;- tgt = (tgt * bw + b.value * b.weight) / (bw + b.weight);+ if (BOUNDED.has(k)) {+ // keys only consonant gestures touch (the velum): follow the gesture's own ramps+ // (with the weighted mean, a strength-4 gesture at 5 % activation already took 80 %+ // of the step, so nasality spread far into neighbouring vowels)+ tgt += Math.min(1, b.weight / 2) * (b.value - tgt);+ } else {+ const bw = baseWeight;+ tgt = (tgt * bw + b.value * b.weight) / (bw + b.weight);+ }sp *= b.speed;}}diff --git a/src/engine/phonetics/beatbox.ts b/src/engine/phonetics/beatbox.tsindex ff66d86..ffb53ff 100644--- a/src/engine/phonetics/beatbox.ts+++ b/src/engine/phonetics/beatbox.ts@@ -135,7 +135,7 @@ export const BEAT_SOUNDS: BeatSound[] = [role: "snare",airstream: "ejective",hint: "Back of the tongue bursts on larynx-compressed air",- latency: 0.009,+ latency: -0.0165,build: (body, o) => [...snap(oral(body, "k", -0.08, 0, 2, "K", { jaw: 0.35 }), 4, 0.008), ...ejective(-0.08, o.accent, "K")],},{@@ -144,7 +144,7 @@ export const BEAT_SOUNDS: BeatSound[] = [role: "snare",airstream: "ingressive",hint: "A sharp breath in past the back of the tongue",- latency: -0.002,+ latency: -0.014,build: (body, o) => [...snap(oral(body, "k", -0.06, 0, 2, "^K", { jaw: 0.35 }), 4, 0.008),...after(oral(body, "x", 0.012, 0.085, 1.4, "^K", { tbY: 7.35 })),@@ -161,8 +161,10 @@ export const BEAT_SOUNDS: BeatSound[] = [hint: "Tongue seals a pocket, hollows it and pops",latency: -0.007,build: (body) => [- ...snap(oral(body, "t", -0.12, 0, 2, "!")),- ...oral(body, "k", -0.12, 0.035, 2, "!"),+ // the tip seals without the alveolar's fronted tongue body (that would close the pocket)+ ...snap(oral(body, "t", -0.12, 0, 2, "!")).filter((x) => x.targets.tbX === undefined),+ // the back seal sits low, leaving a pocket for the dorsum to hollow+ ...oral(body, "k", -0.12, 0.035, 2, "!", { tbY: 7.85, jaw: 0.4 }),g(-0.03, 0.006, 0.04, 0.03, 40, { dorsum: 1 }, "!", 2),],},@@ -172,7 +174,7 @@ export const BEAT_SOUNDS: BeatSound[] = [role: "perc",airstream: "click",hint: "Sealed lips, the jaw drops, the lips pop open",- latency: 0.013,+ latency: -0.001,build: (body) => [// a light seal (pressing the lips squeezes the pocket before the suction starts)...snap(oral(body, "p", -0.12, 0, 2, "P!", { lipAp: -0.08 }), 5, 0.006),@@ -187,7 +189,7 @@ export const BEAT_SOUNDS: BeatSound[] = [role: "hat",airstream: "pulmonic",hint: "Back-of-tongue release into a long rounded hiss",- latency: -0.001,+ latency: -0.013,build: (body, o) => {const end = Math.max(0.14, Math.min(0.34, o.len * 2));return [...snap(oral(body, "k", -0.06, 0, 2, "kch"), 4, 0.008), ...after(oral(body, "ʃ", 0.014, end, 1.4, "kch")), ...blow(-0.035, end, 1.45 * o.accent, 0.45, "kch", 0.14)];@@ -199,7 +201,7 @@ export const BEAT_SOUNDS: BeatSound[] = [role: "bass",airstream: "voiced",hint: "Hummed bass note through the nose",- latency: 0.012,+ latency: 0.0056,build: (body, o) => {const end = Math.max(0.06, o.len * 0.92);return [diff --git a/src/engine/phonetics/durations.ts b/src/engine/phonetics/durations.tsnew file mode 100644index 0000000..2c6e309--- /dev/null+++ b/src/engine/phonetics/durations.ts@@ -0,0 +1,95 @@+/**+ * Segment durations by the Klatt (1979) / MITalk rules (Allen, Hunnicutt & Klatt 1987, ch. 9):+ * DUR = MIN + (INH − MIN) · PRCNT+ * with PRCNT the product of context factors: phrase-final lengthening, non-final shortening,+ * non-word-final and polysyllabic shortening, unstressed shortening (MIN halved), the vowel+ * length cue of the following consonant (bat/bad), cluster shortening, and aspiration.+ * Inherent / minimum durations (ms) per phoneme follow Klatt's table.+ */+import type { Segment } from "./planner.ts";++const T: Record<string, [number, number]> = {+ // vowels+ i: [155, 55], ɪ: [135, 40], e: [190, 70], eɪ: [190, 70], ɛ: [150, 70], æ: [230, 80], a: [230, 80], ɑ: [240, 100], ɒ: [240, 100],+ ɔ: [240, 100], o: [220, 80], oʊ: [220, 80], ʊ: [160, 60], u: [210, 70], ʌ: [140, 60], ə: [120, 60], ɚ: [180, 80], ɝ: [180, 80],+ aɪ: [250, 150], aʊ: [240, 100], ɔɪ: [280, 150], ɨ: [110, 40],+ // consonants+ p: [85, 50], t: [75, 50], k: [80, 60], b: [85, 60], d: [75, 50], g: [80, 60], ʔ: [40, 30],+ tʃ: [70, 50], dʒ: [50, 30],+ f: [100, 80], v: [60, 40], θ: [90, 60], ð: [50, 30], s: [105, 60], z: [75, 40], ʃ: [105, 80], ʒ: [70, 40], h: [80, 20],+ m: [70, 60], n: [60, 50], ŋ: [95, 45], l: [80, 40], ɫ: [80, 40], ɹ: [80, 30], w: [80, 60], j: [80, 40], ɾ: [20, 20],+};++export interface SegInfo {+ vowel: boolean;+ manner?: string;+ voiced?: boolean;+ /** fallback inherent duration (s) for phonemes outside the table */+ dur?: number;+}++/** Durations (s) for one phrase of segments (explicit `dur` values are kept). */+export function klattDurations(segs: Segment[], info: (s: Segment) => SegInfo): number[] {+ const n = segs.length;+ const inf = segs.map(info);+ // words: index ranges split after wordEnd+ const word = new Array<number>(n);+ const wordStart: number[] = [];+ let w = 0;+ for (let i = 0; i < n; i++) {+ if (i === 0 || segs[i - 1].wordEnd) wordStart.push(i);+ word[i] = wordStart.length - 1;+ if (segs[i].wordEnd) w++;+ }+ void w;+ const vowelsInWord = new Map<number, number>();+ for (let i = 0; i < n; i++) if (inf[i].vowel) vowelsInWord.set(word[i], (vowelsInWord.get(word[i]) ?? 0) + 1);+ let lastVowel = -1;+ for (let i = 0; i < n; i++) if (inf[i].vowel) lastVowel = i;++ return segs.map((s, i) => {+ if (s.dur !== undefined) return s.dur;+ const [inh0, min0] = T[s.ipa] ?? [1000 * (inf[i].dur ?? 0.08), 600 * (inf[i].dur ?? 0.08)];+ let inh = inh0, min = min0, p = 1;+ if (inf[i].vowel) {+ const stress = s.stress ?? 0;+ const finalSyl = i === lastVowel;+ let wordFinalSyl = true;+ for (let k = i + 1; k < n && word[k] === word[i]; k++) if (inf[k].vowel) wordFinalSyl = false;+ if (finalSyl) p *= 1.4; // clause-final lengthening+ else p *= 0.6; // non-phrase-final shortening+ if (!wordFinalSyl) p *= 0.85; // non-word-final shortening+ if ((vowelsInWord.get(word[i]) ?? 1) > 1) p *= 0.8; // polysyllabic shortening+ if (stress === 0) {+ min *= 0.5; // unstressed: minimum halved, shortened+ p *= 0.7;+ }+ // the following consonant (same word): voiced fricatives lengthen, voiceless stops shorten+ const nx = i + 1 < n && word[i + 1] === word[i] && !inf[i + 1].vowel ? inf[i + 1] : null;+ if (nx) {+ let f = 1;+ if (nx.manner === "fricative") f = nx.voiced ? 1.6 : 1;+ else if (nx.manner === "stop" || nx.manner === "affricate") f = nx.voiced ? 1.2 : 0.7;+ else if (nx.manner === "nasal") f = 0.85;+ p *= finalSyl ? f : 0.7 + 0.3 * f;+ }+ // vowel next to vowel+ if (i + 1 < n && inf[i + 1].vowel) p *= 1.2;+ if (i > 0 && inf[i - 1].vowel) p *= 0.7;+ let d = min + (inh - min) * p;+ // aspiration after a voiceless stop eats into a stressed vowel's onset: give it back+ const pv = i > 0 ? inf[i - 1] : null;+ if (stress > 0 && pv && pv.manner === "stop" && !pv.voiced) d += 20;+ return d / 1000;+ }+ // consonants+ const wordInitial = i === wordStart[word[i]];+ if (i > lastVowel && (inf[i].manner === "nasal" || inf[i].manner === "lateral" || inf[i].manner === "approximant")) p *= 1.4;+ if (!wordInitial) p *= 0.85;+ const prevC = i > 0 && !inf[i - 1].vowel;+ const nextC = i + 1 < n && !inf[i + 1].vowel;+ if (prevC && nextC) p *= 0.5;+ else if (prevC || nextC) p *= 0.7;+ return (min + (inh - min) * p) / 1000;+ });+}diff --git a/src/engine/phonetics/inventory.ts b/src/engine/phonetics/inventory.tsindex b7d028b..7f4bb29 100644--- a/src/engine/phonetics/inventory.ts+++ b/src/engine/phonetics/inventory.ts@@ -48,7 +48,9 @@ const DENT_STOP = { ttX: 6.85, ttY: 9.0 };const POSTALV_STOP = { ttX: 5.75, ttY: 10.0 };const RETRO_STOP = { ttX: 5.45, ttY: 10.05, ttCurl: 0.95 };const PAL_STOP = { tbX: 3.75, tbY: 8.45 };-const VEL_STOP = { tbX: 2.3, tbY: 7.85 };+// velar closure: aimed past contact (the contact model caps penetration) so it seals wherever the+// vowel puts the tongue body front–back, and the jaw rises part-way (open-vowel contexts leaked)+const VEL_STOP = { tbX: 2.3, tbY: 8.35, jaw: 0.7 };const UVU_STOP = { tbX: 1.55, tbY: 7.6 };const BASE: PhonemeDef[] = [diff --git a/src/engine/phonetics/planner.ts b/src/engine/phonetics/planner.tsindex 5081de2..d47867e 100644--- a/src/engine/phonetics/planner.ts+++ b/src/engine/phonetics/planner.ts@@ -6,6 +6,7 @@import type { Gesture } from "../control/score.ts";import type { HumanArtic } from "../anatomy/human.ts";import { phoneme, type PhonemeDef } from "./inventory.ts";+import { klattDurations } from "./durations.ts";import vowelTable from "./vowelTargets.generated.json";export interface Segment {@@ -38,6 +39,8 @@ export interface PlannedSegment {ipa: string;t0: number;t1: number;+ /** lexical stress of vowels (0 unstressed, 1 primary, 2 secondary) */+ stress?: number;kind: string;}@@ -82,15 +85,21 @@ export function vowelArtic(ipa: string, body: string): Partial<HumanArtic> | nulexport function planUtterance(input: Segment[], o: PlanOptions): Plan {const rate = o.rate ?? 1;const body = o.body;+ // durations by the Klatt rules, on whole segments (diphthongs before they are split)+ const durs = klattDurations(input, (s) => {+ if (isVowel(s.ipa, body)) return { vowel: true };+ const d = phoneme(s.ipa, body);+ return { vowel: false, manner: d?.manner, voiced: d?.voicing === "voiced", dur: d?.dur };+ });// expand diphthongs into two vowel targets sharing the durationconst segs: (Segment & { def?: PhonemeDef; vowel?: Partial<HumanArtic>; glideFrom?: boolean })[] = [];- for (const s of input) {+ input.forEach((s, si) => {if (EXPAND[s.ipa]) {const parts = EXPAND[s.ipa];- const base = s.dur ?? (s.stress ? 0.2 : 0.14);+ const base = durs[si];parts.forEach((p, i) => segs.push({ ...s, ipa: p, dur: parts.length > 1 ? base * (i === 0 ? 0.55 : 0.45) : base, glideFrom: i > 0, wordEnd: i === parts.length - 1 ? s.wordEnd : false }));- } else segs.push({ ...s });- }+ } else segs.push({ ...s, dur: durs[si] });+ });for (const s of segs) {const v = vowelArtic(s.ipa, body);if (v) s.vowel = v;@@ -116,8 +125,11 @@ export function planUtterance(input: Segment[], o: PlanOptions): Plan {vIdx.forEach((i, n) => {const prev = n > 0 ? times[vIdx[n - 1]].t1 : times[i].t0 - 0.08;const next = n < vIdx.length - 1 ? times[vIdx[n + 1]].t0 : times[i].t1 + 0.08;- const rIn = Math.max(0.04, 0.85 * (times[i].t0 - prev)) + 0.02;- const rOut = Math.max(0.04, 0.85 * (next - times[i].t1)) + 0.02;+ // vowel-to-vowel through the consonant (Öhman): the previous vowel lets go early in the gap+ // and the next one's target ramps in over most of it, so the tongue body is already near+ // the next vowel at the release and the transitions carry the consonant's place+ const rIn = Math.max(0.03, 0.75 * (times[i].t0 - prev)) + 0.01;+ const rOut = Math.max(0.03, 0.4 * (next - times[i].t1)) + 0.01;gestures.push({ t0: times[i].t0, t1: times[i].t1, rampIn: rIn, rampOut: rOut, strength: 1, targets: segs[i].vowel!, label: segs[i].ipa });});// utterance-initial/final consonants: lend them the nearest vowel's body posture@@ -125,7 +137,7 @@ export function planUtterance(input: Segment[], o: PlanOptions): Plan {segs.forEach((s, i) => {const { t0, t1 } = times[i];const dur = t1 - t0;- planned.push({ ipa: s.ipa, t0, t1, kind: s.vowel ? "vowel" : s.def?.manner ?? "?" });+ planned.push({ ipa: s.ipa, t0, t1, kind: s.vowel ? "vowel" : s.def?.manner ?? "?", ...(s.vowel ? { stress: s.stress ?? 0 } : {}) });const def = s.def;if (!def) return;const prevVowel = i > 0 && !!segs[i - 1].vowel;@@ -164,8 +176,9 @@ export function planUtterance(input: Segment[], o: PlanOptions): Plan {case "glottal":break;}- // nasality: velum lowering with anticipation into the preceding vowel- if (def.nasal) gestures.push({ t0: t0 - 0.03, t1: t1 + 0.01, rampIn: 0.06, rampOut: 0.05, strength: 4, targets: { velum: 0.85 }, label: "velum" });+ // nasality: the velum lowers in anticipation (into the preceding vowel, as in English) and+ // seals again by the end of the nasal; 0.45 cm² is ample for the murmur+ if (def.nasal) gestures.push({ t0: t0 - 0.02, t1: t1 - 0.02, rampIn: 0.05, rampOut: 0.03, strength: 4, targets: { velum: 0.45 }, label: "velum" });// phonationconst k2 = 1; // abduction is body-scaled in the voiceif (def.glottal === "open") gestures.push({ t0: t0 - 0.01, t1, rampIn: 0.03, rampOut: 0.035, strength: 5, targets: { abduction: 0.33 * k2 }, label: "h" });@@ -191,21 +204,35 @@ export function planUtterance(input: Segment[], o: PlanOptions): Plan {const f0 = o.f0 ?? 110;const accent = o.accent ?? 0.14;const total = Math.max(0.2, end - o.t0);+ // the nuclear accent: the phrase's last primary-stressed vowel, a bigger excursion that falls+ // (statements) into the final low; earlier accents are smaller (a "hat" pattern)+ let nuclear = -1;+ for (const i of vIdx) if (segs[i].stress === 1 && !segs[i].glideFrom) nuclear = i;vIdx.forEach((i, n) => {const s = segs[i];const { t0, t1 } = times[i];+ // pitch holds through the consonants up to the next vowel (instead of sagging to the base)+ const hold = n < vIdx.length - 1 ? Math.max(t1, times[vIdx[n + 1]].t0 - 0.03) : t1;let target: number;if (s.f0) target = s.f0;else {const prog = (t0 - o.t0) / total;const decl = 1 - 0.1 * prog;- const acc = s.stress === 1 ? 1 + accent : s.stress === 2 ? 1 + accent * 0.5 : 1;+ const acc = s.stress === 1 ? 1 + (i === nuclear ? accent * 1.8 : accent) : s.stress === 2 ? 1 + accent * 0.5 : 1;target = f0 * decl * acc;const last = n === vIdx.length - 1;if (last && o.intonation === "question") target = f0 * 1.35;- if (last && (o.intonation ?? "statement") === "statement") target = f0 * 0.82;+ if (last && (o.intonation ?? "statement") === "statement") {+ if (i === nuclear && t1 - t0 > 0.08) {+ // accent peak early in the vowel, then the fall within it+ gestures.push({ t0, t1: t0 + 0.35 * (t1 - t0), rampIn: 0.05, rampOut: 0.05, strength: 1, targets: { f0: target }, label: "pitch" });+ gestures.push({ t0: t0 + 0.55 * (t1 - t0), t1, rampIn: 0.06, rampOut: 0.06, strength: 1, targets: { f0: f0 * 0.82 }, label: "pitch" });+ return;+ }+ target = f0 * 0.82;+ }}- gestures.push({ t0, t1, rampIn: 0.06, rampOut: 0.06, strength: s.f0 ? 6 : 1, targets: { f0: target }, label: "pitch" });+ gestures.push({ t0, t1: s.f0 ? t1 : hold, rampIn: 0.06, rampOut: 0.06, strength: s.f0 ? 6 : 1, targets: { f0: target }, label: "pitch" });});return { gestures, segments: planned, end };}@@ -233,7 +260,17 @@ export function oralGestures(def: PhonemeDef, tg: Partial<HumanArtic>, a: number// the overlapping vowel contributes ~2 %, so closures seal instead of being dilutedconst early = closing ? (bodyOnly ? 0.024 : lipsOnly ? 0.022 : 0.031) : 0.008;if (Object.keys(dom).length) out.push({ t0: a - early, t1: Math.max(a + 0.01, b - lead), rampIn: 0.03, rampOut: bodyOnly ? 0.03 : 0.018, strength: 40, targets: dom, speed: sp, releaseHold: 0.045, label });- if (Object.keys(sec).length) out.push({ t0: a, t1: b, rampIn: 0.05, rampOut: 0.05, strength: 2.2, targets: sec, label });+ // alveolars front the tongue body during the closure (the alveolar F2 locus, ~1.8 kHz)+ const alveolar = def.place === "alveolar" && tg.tbX === undefined && ["stop", "nasal", "fricative", "affricate", "tap"].includes(def.manner);+ if (alveolar) out.push({ t0: a, t1: b, rampIn: 0.05, rampOut: 0.05, strength: 1.2, targets: { tbX: 3.2, tbY: 7.4 }, label });+ if (Object.keys(sec).length) {+ // a velar's front–back place follows the vowel (fronted /k/ in "key", backed in "caw"):+ // its own tbX only weakly, so the F2 locus moves with the vowel as in natural speech+ const place = bodyOnly && sec.tbX !== undefined ? { tbX: sec.tbX } : null;+ if (place) delete sec.tbX;+ if (Object.keys(sec).length) out.push({ t0: a, t1: b, rampIn: 0.05, rampOut: 0.05, strength: 2.2, targets: sec, label });+ if (place) out.push({ t0: a, t1: b, rampIn: 0.05, rampOut: 0.05, strength: 0.25, targets: place, label });+ }return out;}diff --git a/src/ui/components/ArticPanel.tsx b/src/ui/components/ArticPanel.tsxindex aeedb6b..0240aaa 100644--- a/src/ui/components/ArticPanel.tsx+++ b/src/ui/components/ArticPanel.tsx@@ -16,7 +16,7 @@ export function ArticPanel() {<Slider label="Jaw opening" value={a.jaw} min={0} max={2.4} onChange={(v) => set({ jaw: v })} format={cm} /><Slider label="Tongue root" value={a.root} min={-0.9} max={0.9} onChange={(v) => set({ root: v })} format={(v) => (v >= 0 ? `+${v.toFixed(2)} cm` : `${v.toFixed(2)} cm`)} /><Slider label="Tip curl" value={a.ttCurl} min={0} max={1} onChange={(v) => set({ ttCurl: v })} format={pct} />- <Slider label="Soft palate opening" value={a.velum} min={0} max={1.2} onChange={(v) => set({ velum: v })} format={(v) => `${v.toFixed(2)} cm²`} />+ <Slider label="Soft palate opening" value={a.velum} min={-0.25} max={1.2} onChange={(v) => set({ velum: v })} format={(v) => (v <= 0 ? "Closed" : `${v.toFixed(2)} cm²`)} /><Slider label="Larynx height" value={a.larynx} min={-1.5} max={1.5} onChange={(v) => set({ larynx: v })} format={(v) => (v >= 0 ? `+${v.toFixed(2)} cm` : `${v.toFixed(2)} cm`)} /><Slider label="Twang (epilarynx)" value={a.epilarynx} min={0} max={1} onChange={(v) => set({ epilarynx: v })} format={pct} /><Slider label="False folds" value={a.ventricular} min={0} max={1} onChange={(v) => set({ ventricular: v })} format={pct} />diff --git a/src/ui/store.ts b/src/ui/store.tsindex 208ffa3..ef19193 100644--- a/src/ui/store.ts+++ b/src/ui/store.ts@@ -282,7 +282,7 @@ export const useStore = create<State>((set, get) => ({const held = get().heldNotes.filter((n) => n !== midi);set({ heldNotes: held });const s = get();- if (s.mode === "beatbox" && !held.length) s.setArtic({ lipAp: beatReady(s.body).lipAp, velum: 0 });+ if (s.mode === "beatbox" && !held.length) s.setArtic({ lipAp: beatReady(s.body).lipAp, velum: NEUTRAL.velum });if (held.length) {// fall back to the most recent note still held (legato)const last = held[held.length - 1];diff --git a/tests/speech-quality.test.ts b/tests/speech-quality.test.tsnew file mode 100644index 0000000..4c1b274--- /dev/null+++ b/tests/speech-quality.test.ts@@ -0,0 +1,41 @@+import { describe, expect, test } from "bun:test";+import { HumanVoice } from "../src/engine/voice/humanVoice.ts";+import { planUtterance } from "../src/engine/phonetics/planner.ts";+import { tokenizeIpa } from "../src/engine/phonetics/ipa.ts";++const FS = 48000;++function render(ipa: string) {+ const v = new HumanVoice({ fsOut: FS });+ const plan = planUtterance(tokenizeIpa(ipa), { body: "male", t0: 0.05, f0: 110 });+ v.schedule(plan.gestures);+ const N = Math.round(FS * (plan.end + 0.15));+ const out = new Float32Array(N);+ const port: number[] = [];+ for (let i = 0; i < N; i += 128) {+ v.render(out, i, Math.min(128, N - i));+ port.push(v.airway.frame?.velumPort ?? 0);+ }+ return { plan, port, at: (t: number) => port[Math.min(port.length - 1, Math.round((t * FS) / 128))] };+}++describe("running-speech quality guards", () => {+ test("nasality does not spread into oral vowels (Bunton & Story: audible from ~0.01 cm²)", () => {+ // [ɑ n ə b ɑ b ɑ]: the last two vowels have no nasal neighbour+ const { plan, at } = render("ˈɑnəbɑbɑ");+ const vowels = plan.segments.filter((s) => s.kind === "vowel");+ expect(vowels.length).toBe(4);+ for (const v of vowels.slice(2)) for (let t = v.t0; t <= v.t1; t += 0.005) expect(at(t)).toBeLessThan(0.01);+ // and the nasal itself is nasal+ const n = plan.segments.find((s) => s.ipa === "n")!;+ expect(at((n.t0 + n.t1) / 2)).toBeGreaterThan(0.2);+ });+ test("phrase-final lengthening and stressed vs unstressed contrast (Klatt rules)", () => {+ const { plan } = render("ˈbɑbəˈbɑb");+ const v = plan.segments.filter((s) => s.kind === "vowel");+ const [first, mid, last] = [v[0], v[1], v[2]];+ const d = (s: { t0: number; t1: number }) => s.t1 - s.t0;+ expect(d(last) / d(first)).toBeGreaterThan(1.25);+ expect(d(first) / d(mid)).toBeGreaterThan(1.4);+ });+});diff --git a/tools/speech-diagnostics.ts b/tools/speech-diagnostics.tsnew file mode 100644index 0000000..442e94c--- /dev/null+++ b/tools/speech-diagnostics.ts@@ -0,0 +1,156 @@+/**+ * Running-speech diagnostics (the "marbles in the mouth" battery): renders sentences through the+ * full pipeline and measures, against published norms,+ * - nasal leakage: velopharyngeal port during vowels with no nasal neighbour+ * (heard as nasal from ~0.01 cm² for high vowels, ~0.15 cm² for low; Bunton & Story 2011)+ * - vowel undershoot: LPC F1/F2 at vowel midpoints vs the calibrated (Hillenbrand) targets+ * - formant bandwidths at vowel midpoints (Klatt defaults B1 60, B2 90, B3 150 Hz)+ * - spectral balance: octave-band long-term spectrum relative to 500 Hz+ * - duration contrasts: stressed vs unstressed, phrase-final vs not+ * - pitch: share of voiced time stuck at the baseline (snapping back between vowels)+ * Usage: bun tools/speech-diagnostics.ts [outdir]+ */+import { readFileSync, mkdirSync } from "node:fs";+import { gunzipSync } from "node:zlib";+import { HumanVoice } from "../src/engine/voice/humanVoice.ts";+import { EnglishG2P } from "../src/engine/phonetics/english.ts";+import { planPhrases, diphthongParts } from "../src/engine/phonetics/planner.ts";+import { VOWELS } from "../src/engine/phonetics/vowelData.ts";+import { estimateFormants } from "../src/engine/analysis/lpc.ts";+import { FFT, hann } from "../src/engine/analysis/fft.ts";+import { writeWav } from "./lib/wav.ts";+import { renderSpectrogram } from "./lib/spectrogram.ts";++const outDir = process.argv[2];+if (outDir) mkdirSync(outDir, { recursive: true });+const FS = 48000;+const SENTENCES = [+ "The north wind and the sun were disputing which was the stronger.",+ "We were away a year ago.",+ "Should we chase those cowboys?",+ "Can you hear me now?",+ "She sells sea shells by the sea shore.",+];+const NASALS = new Set(["m", "n", "ŋ"]);+const g2p = new EnglishG2P();+g2p.setDictionaryText(gunzipSync(readFileSync("public/data/cmudict.txt.gz")).toString("utf8"));+const REF = new Map(VOWELS.map((v) => [v.ipa, v.male]));++interface VowelStat { ipa: string; stressed: boolean; final: boolean; dur: number; f1: number; f2: number; t1: number; t2: number; bw: number[] }+const vowels: VowelStat[] = [];+let oralFrames = 0, leak1 = 0, leak5 = 0, leak15 = 0, maxOralPort = 0;+let voicedFrames = 0, atBase = 0;+const f0s: number[] = [];+const bands = [250, 500, 1000, 2000, 4000, 8000];+const bandE = new Float64Array(bands.length);+const fft = new FFT(2048), win = hann(2048);++for (const [si, text] of SENTENCES.entries()) {+ const v = new HumanVoice({ fsOut: FS });+ const phrases = g2p.toPhrases(text);+ const plan = planPhrases(phrases, { body: "male", t0: 0.1, f0: 110 });+ v.schedule(plan.gestures);+ const N = Math.round(FS * (plan.end + 0.3));+ const out = new Float32Array(N);+ const port: number[] = [], f0t: number[] = [], voic: number[] = [];+ for (let i = 0; i < N; i += 128) {+ v.render(out, i, Math.min(128, N - i));+ port.push(v.airway.frame?.velumPort ?? 0);+ f0t.push(v.glottis.f0Now);+ voic.push(v.glottis.voicing);+ }+ const frameAt = (t: number) => Math.min(port.length - 1, Math.max(0, Math.round((t * FS) / 128)));+ const segs = plan.segments;+ segs.forEach((s, k) => {+ if (s.kind !== "vowel") return;+ const nasalNb = (segs[k - 1] && NASALS.has(segs[k - 1].ipa)) || (segs[k + 1] && NASALS.has(segs[k + 1].ipa));+ if (!nasalNb)+ for (let f = frameAt(s.t0); f <= frameAt(s.t1); f++) {+ oralFrames++;+ if (port[f] > 0.01) leak1++;+ if (port[f] > 0.05) leak5++;+ if (port[f] > 0.15) leak15++;+ maxOralPort = Math.max(maxOralPort, port[f]);+ }+ // formants at the midpoint (first target of a diphthong at 30 %)+ const parts = diphthongParts(s.ipa);+ const tgt = parts ? parts[0] : s.ipa;+ const ref = REF.get(tgt);+ const tm = parts ? s.t0 + 0.3 * (s.t1 - s.t0) : (s.t0 + s.t1) / 2;+ const dec = 4, len = Math.round(0.025 * FS);+ const c = Math.round(tm * FS);+ const fr: number[] = [];+ for (let i = c - len / 2; i < c + len / 2; i += dec) {+ let acc = 0;+ for (let j = 0; j < dec; j++) acc += out[i + j] ?? 0;+ fr.push(acc / dec);+ }+ const fm = estimateFormants(fr, FS / dec, { order: 14, maxBw: 700 });+ if (ref && fm.length >= 2) {+ const next = segs.slice(k + 1).find((x) => x.kind === "vowel");+ vowels.push({ ipa: s.ipa, stressed: s.stress === 1, final: !next || next.t0 - s.t1 > 0.2, dur: s.t1 - s.t0, f1: fm[0].freq, f2: fm[1].freq, t1: ref[0], t2: ref[1], bw: fm.slice(0, 3).map((x) => x.bw) });+ }+ });+ // pitch: voiced frames within 3 % of the 110 Hz baseline+ for (let f = 0; f < f0t.length; f++)+ if (voic[f] > 0.5) {+ voicedFrames++;+ f0s.push(f0t[f]);+ if (Math.abs(f0t[f] / 110 - 1) < 0.03) atBase++;+ }+ // long-term spectrum over frames with signal+ let peak = 0;+ for (const x of out) peak = Math.max(peak, Math.abs(x));+ for (let i = 0; i + 2048 < N; i += 1024) {+ let e = 0;+ for (let j = 0; j < 2048; j++) e += out[i + j] * out[i + j];+ if (Math.sqrt(e / 2048) < peak * 0.01) continue;+ const re = new Float64Array(2048), im = new Float64Array(2048);+ for (let j = 0; j < 2048; j++) re[j] = out[i + j] * win[j];+ fft.transform(re, im);+ for (let k = 1; k < 1024; k++) {+ const f = (k * FS) / 2048;+ const p = re[k] * re[k] + im[k] * im[k];+ bands.forEach((b, bi) => {+ if (f >= b / Math.SQRT2 && f < b * Math.SQRT2) bandE[bi] += p;+ });+ }+ }+ if (outDir) {+ writeWav(`${outDir}/s${si + 1}.wav`, [out], FS);+ renderSpectrogram(`${outDir}/s${si + 1}.png`, out, FS, { title: text.replace(/[^\x20-\x7e]/g, "?"), maxFreq: 8000, windowMs: 5, marks: segs.map((s) => ({ t: s.t0, label: "" })) });+ }+}++const pct = (a: number, b: number) => `${((100 * a) / Math.max(1, b)).toFixed(1)} %`;+const mean = (xs: number[]) => xs.reduce((s, x) => s + x, 0) / Math.max(1, xs.length);+const median = (xs: number[]) => { const s = [...xs].sort((a, b) => a - b); return s[Math.floor(s.length / 2)] ?? NaN; };+console.log("== nasal leakage during vowels with no nasal neighbour");+console.log(` frames with port > 0.01 cm²: ${pct(leak1, oralFrames)} > 0.05: ${pct(leak5, oralFrames)} > 0.15: ${pct(leak15, oralFrames)} max ${maxOralPort.toFixed(3)} cm² (norm: ~0 %)`);+console.log("== vowel midpoints vs calibrated targets");+// LPC fails on short vowels that came out voiceless (aspiration): drop frames with no F1 below 1.2 kHz+const ok = (vs: VowelStat[]) => vs.filter((x) => x.f1 < 1200 && x.f2 < 3200);+const err = (vs0: VowelStat[]) => {+ const vs = ok(vs0);+ return `F1 ${(100 * median(vs.map((x) => Math.abs(x.f1 / x.t1 - 1)))).toFixed(0)} % F2 ${(100 * median(vs.map((x) => Math.abs(x.f2 / x.t2 - 1)))).toFixed(0)} % median error (n=${vs.length}/${vs0.length} measurable)`;+};+// distance from schwa in (F1, log F2) relative to the target's+const sch = [500, 1500];+const reach = (vs: VowelStat[]) => median(ok(vs).filter((x) => Math.hypot(x.t1 - sch[0], 1000 * Math.log(x.t2 / sch[1])) > 80).map((x) => Math.hypot(x.f1 - sch[0], 1000 * Math.log(x.f2 / sch[1])) / Math.hypot(x.t1 - sch[0], 1000 * Math.log(x.t2 / sch[1]))));+const S = vowels.filter((x) => x.stressed), U = vowels.filter((x) => !x.stressed);+console.log(` stressed: ${err(S)}; distance from schwa reached ${(100 * reach(S)).toFixed(0)} % (norm ≥ 90 %)`);+console.log(` unstressed: ${err(U)}; distance from schwa reached ${(100 * reach(U)).toFixed(0)} % (norm ≥ 75 %)`);+if (process.env.DIAG_VERBOSE) for (const x of vowels) console.log(` ${x.stressed ? "S" : "u"} ${x.ipa.padEnd(3)} ${(1000 * x.dur).toFixed(0).padStart(4)} ms F1 ${x.f1.toFixed(0).padStart(4)}/${x.t1} F2 ${x.f2.toFixed(0).padStart(5)}/${x.t2} B1 ${x.bw[0].toFixed(0)}`);+console.log("== formant bandwidths at vowel midpoints (median)");+console.log(` B1 ${median(vowels.map((x) => x.bw[0])).toFixed(0)} Hz B2 ${median(vowels.map((x) => x.bw[1])).toFixed(0)} Hz B3 ${median(vowels.map((x) => x.bw[2] ?? NaN).filter(Number.isFinite)).toFixed(0)} Hz (Klatt defaults 60 / 90 / 150)`);+console.log("== long-term spectrum, octave bands re 500 Hz");+const ref500 = bandE[1];+const ltass = [-2, 0, -6, -11, -16, -20]; // approximate natural male speech (Byrne et al. 1994 LTASS, octave-averaged)+console.log(" " + bands.map((b, i) => `${b >= 1000 ? b / 1000 + "k" : b}: ${(10 * Math.log10(bandE[i] / ref500)).toFixed(1)} (≈${ltass[i]})`).join(" "));+console.log("== durations");+const fin = vowels.filter((x) => x.final), non = vowels.filter((x) => !x.final);+console.log(` stressed ${(1000 * mean(S.map((x) => x.dur))).toFixed(0)} ms vs unstressed ${(1000 * mean(U.map((x) => x.dur))).toFixed(0)} ms (norm ≥ 2 ×); phrase-final ${(1000 * mean(fin.map((x) => x.dur))).toFixed(0)} ms vs non-final ${(1000 * mean(non.map((x) => x.dur))).toFixed(0)} ms (norm: final ≈ 1.3–1.4 ×)`);+console.log("== pitch");+const st = (a: number, b: number) => 12 * Math.log2(a / b);+const sorted = [...f0s].sort((a, b) => a - b);+console.log(` voiced time at the 110 Hz baseline (±3 %): ${pct(atBase, voicedFrames)} range (5–95 %) ${st(sorted[Math.floor(sorted.length * 0.95)], sorted[Math.floor(sorted.length * 0.05)]).toFixed(1)} semitones`);