the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Duet: the words at each mouth, on the side the head faces
Jameson Hodgece3c615f312e
diff --git a/src/show/words.ts b/src/show/words.tsnew file mode 100644index 0000000..d4cded6--- /dev/null+++ b/src/show/words.ts@@ -0,0 +1,62 @@+/**+ * The words at a duet head's mouth: each sung note's syllable over the note's time, from the voice's+ * melody file (the one `chimera render notes` sang), as Sing mode's demo shows them.+ */+import type { Syllable } from "../wasm/types.ts";+import type { MouthWord } from "../ui/mouthWords.ts";++/** a melody file: `{"bpm", "t0"?, "lyrics", "notes": [[midi, beats], ...]}` (midi <= 0 is a rest) */+export interface Melody {+ bpm: number;+ t0?: number;+ lyrics: string;+ notes: [number, number][];+}++export interface SungWords {+ /** sounding notes' start and end (s, on the render's clock) */+ times: [number, number][];+ /** what the mouth shows per note: its syllable, or a melisma's parent's */+ shown: string[];+ /** the note whose syllable each note sings (a melisma's parent) */+ parent: number[];+}++/**+ * Note times and syllables for a melody. `syls` is lyricsToSyllables(melody.lyrics); `spell` writes+ * a syllable another way at the mouth (lyrics spelled for the dictionary: "owr" → "our").+ * Throws when the syllables don't match the sounding notes, as the CLI does.+ */+export function sungWords(m: Melody, syls: Syllable[], spell: Record<string, string> = {}): SungWords {+ const beat = 60 / m.bpm;+ const times: [number, number][] = [];+ let t = m.t0 ?? 0.3; // the CLI's default+ for (const [midi, beats] of m.notes) {+ if (midi > 0) times.push([t, t + beats * beat]);+ t += beats * beat;+ }+ if (syls.length !== times.length) throw new Error(`${syls.length} syllables for ${times.length} notes`);+ const respell = new Map(Object.entries(spell).map(([k, v]) => [k.toLowerCase(), v]));+ const parent: number[] = [];+ syls.forEach((s, i) => parent.push(s.melisma && i > 0 ? parent[i - 1] : i));+ const shown = parent.map((p) => {+ const s = syls[p];+ return (respell.get(s.text.toLowerCase()) ?? s.text) + (s.wordEnd ? "" : "-");+ });+ return { times, shown, parent };+}++/** the word sounding at time t (s), keyed by its note so a repeated word is still a new one */+export function wordAt(w: SungWords, t: number): MouthWord | null {+ // binary search: the last note starting at or before t+ let lo = 0, hi = w.times.length - 1, k = -1;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ if (w.times[mid][0] <= t) {+ k = mid;+ lo = mid + 1;+ } else hi = mid - 1;+ }+ if (k < 0 || t >= w.times[k][1]) return null;+ return { key: w.parent[k], text: w.shown[k] };+}diff --git a/src/ui/components/DuetPage.tsx b/src/ui/components/DuetPage.tsxindex 289f303..38dced7 100644--- a/src/ui/components/DuetPage.tsx+++ b/src/ui/components/DuetPage.tsx@@ -10,7 +10,9 @@* { "title": "…", "audio": "mix.mp3", "bpm": 103, "downbeat": 0,* "voices": [{ "name": "Lower", "tele": "male.tele" }, { "name": "Upper", "tele": "female.tele" }] }*- * `bpm` and `downbeat` (s, a bar's first beat) are optional: with them the heads nod on the beat.+ * Optional: `bpm` and `downbeat` (s, a bar's first beat) nod the heads on the beat; a voice's+ * `melody` (the melody file it was rendered from) writes its words at its mouth, and the show's+ * `spell` ({"owr": "our"}) writes a syllable spelled for the dictionary as it should read.*/import { useEffect, useRef, useState } from "react";import { AnatomyView3D, type HeadFeed } from "./AnatomyView3D.tsx";@@ -21,18 +23,25 @@ import { getModel } from "../useModel.ts";import { VoiceModel } from "../analysis.ts";import { bodyLabel } from "../body.ts";import type { ViewFlags } from "../render/anatomy.ts";+import { mouthWords } from "../mouthWords.ts";+import { V } from "../colors.ts";+import { g2p } from "../speech.ts";+import { lyricsToSyllables } from "../../wasm/engine.ts";+import { sungWords, wordAt, type Melody, type SungWords } from "../../show/words.ts";+import type { OverlayFn } from "./AnatomyView.tsx";interface ShowFile {title: string;audio: string;bpm?: number;downbeat?: number;- voices: { name: string; tele: string }[];+ spell?: Record<string, string>;+ voices: { name: string; tele: string; melody?: string }[];}interface Loaded {show: ShowFile;- voices: { name: string; track: TeleTrack }[];+ voices: { name: string; track: TeleTrack; words: SungWords | null }[];}/** the heads as the face screen shows them by default, less the measurement labels */@@ -68,7 +77,19 @@ export function DuetPage(props: { id: string }) {const show = (await (await fetchOk(base + "show.json")).json()) as ShowFile;if (!show.voices?.length || !show.audio) throw new Error("show.json needs audio and voices");const [audio, ...teles] = await Promise.all([fetchOk(base + show.audio).then((r) => r.arrayBuffer()), ...show.voices.map((v) => fetchOk(base + v.tele).then((r) => r.arrayBuffer()))]);- const voices = show.voices.map((v, i) => ({ name: v.name, track: new TeleTrack(teles[i]) }));+ // the words: syllables as the CLI splits them (the pronouncing dictionary first, as it does)+ const melodies = await Promise.all(show.voices.map((v) => (v.melody ? fetchOk(base + v.melody).then((r) => r.json() as Promise<Melody>) : null)));+ if (melodies.some(Boolean)) await g2p.load().catch(() => {});+ const words = melodies.map((m) => {+ if (!m) return null;+ try {+ return sungWords(m, lyricsToSyllables(m.lyrics), show.spell);+ } catch (e) {+ console.warn("duet: no words for a voice:", e);+ return null;+ }+ });+ const voices = show.voices.map((v, i) => ({ name: v.name, track: new TeleTrack(teles[i]), words: words[i] }));await transport.load(audio);if (live) setLoaded({ show, voices });})().catch((e: unknown) => live && setError(e instanceof Error ? e.message : String(e)));@@ -103,7 +124,7 @@ export function DuetPage(props: { id: string }) {<span className="duet-title">{title}</span></header><main className="duet-heads" style={{ "--voices": loaded?.voices.length ?? 2 } as React.CSSProperties}>- {loaded && transport ? loaded.voices.map((v, i) => <Head key={i} name={v.name} track={v.track} show={loaded.show} transport={transport} facing={i > 0 && i === loaded.voices.length - 1 ? -1 : 1} />) : <p className="duet-msg">Loading the song…</p>}+ {loaded && transport ? loaded.voices.map((v, i) => <Head key={i} name={v.name} track={v.track} words={v.words} show={loaded.show} transport={transport} facing={i > 0 && i === loaded.voices.length - 1 ? -1 : 1} />) : <p className="duet-msg">Loading the song…</p>}</main><footer className="duet-bar"><button className="primary large" disabled={!loaded} onClick={() => (st.playing ? transport?.pause() : transport?.play())}>@@ -129,9 +150,12 @@ export function DuetPage(props: { id: string }) {}/** one voice's head; the last of several turns to face the others */-function Head(props: { name: string; track: TeleTrack; show: ShowFile; transport: Transport; facing: 1 | -1 }) {- const { track, show, transport } = props;+function Head(props: { name: string; track: TeleTrack; words: SungWords | null; show: ShowFile; transport: Transport; facing: 1 | -1 }) {+ const { track, show, transport, words } = props;const feedRef = useRef<HeadFeed | null>(null);+ // the syllable at the mouth, written on the side the face looks to+ const overlayRef = useRef<OverlayFn | undefined>(undefined);+ if (words && !overlayRef.current) overlayRef.current = mouthWords(() => wordAt(words, transport.time()), V.green, props.facing);if (!feedRef.current) {const model = getModel(track.body, track.sampleRate);const beatStep = (t: number) => {@@ -156,7 +180,7 @@ function Head(props: { name: string; track: TeleTrack; show: ShowFile; transport}return (<Screen className="duet-head" focus title={props.name} sub={bodyLabel(track.body)} label={`${props.name} voice, ${bodyLabel(track.body)}, in 3D`}>- <AnatomyView3D feed={feedRef.current} readouts={false} />+ <AnatomyView3D feed={feedRef.current} readouts={false} overlay={overlayRef.current} /></Screen>);}diff --git a/src/ui/mouthWords.ts b/src/ui/mouthWords.tsindex 0bf86d6..1cad2f0 100644--- a/src/ui/mouthWords.ts+++ b/src/ui/mouthWords.ts@@ -35,21 +35,30 @@ export function advanceTrail(t: Trail, word: MouthWord | null, clock: number): vwhile (e.length && (e.length > 8 || (e[0].left !== null && clock - e[0].left > FADE))) e.shift();}-/** 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 {+/**+ * An overlay writing `now()`'s word at the mouth in `color`; each call keeps its own trail.+ * `side` is where the face looks on screen: 1 writes to the right of the lips, −1 to the left (a+ * head turned to face left), so the word is always in the open space in front of the mouth.+ */+export function mouthWords(now: () => MouthWord | null, color: string, side: 1 | -1 = 1): OverlayFn {const t: Trail = { entries: [] };const trail = t.entries;let clock = 0;- return (ctx, r, m, f, a, { w, dt }) => {+ return (ctx, r, m, f, a, { w, h, dt }) => {clock += dt;advanceTrail(t, now(), clock);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 x0 = lx + side * r.pxPerCm * 1.2;+ const ahead = side > 0 ? w - x0 - 14 : x0 - 14;+ // no room in front of the mouth (a narrow screen the head fills): the words go under the chin,+ // below the neck, and fall away downwards+ const below = ahead < 60;+ const room = below ? w - 16 : ahead;const base = Math.max(26, Math.min(64, r.pxPerCm * 1.7));+ const by = Math.min(h - 14, ly + r.pxPerCm * 18);for (const { word: wd, left } of trail) {const age = left === null ? 0 : clock - left;const u = Math.min(1, age / FADE);@@ -58,8 +67,12 @@ export function mouthWords(now: () => MouthWord | null, color: string): OverlayFconst 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, moving: left !== null });+ const o = { size, color, weight: "m" as const, ls: 0.05, alpha, moving: left !== null };+ if (below) {+ const half = (Math.min(wide, room) * (1 - 0.55 * u)) / 2;+ label(ctx, text, Math.min(w - 8 - half, Math.max(8 + half, lx)), by + age * 120, { ...o, align: "center" });+ } else label(ctx, text, x0 + side * age * 240, ly + size * 0.36 - age * 200, { ...o, align: side > 0 ? "left" : "right" });}- if (trail[trail.length - 1].left === null) seg(ctx, lx + 10, ly, x0 - 10, ly, color, 1, { dash: [2, 5], alpha: 0.7 });+ if (!below && trail[trail.length - 1].left === null) seg(ctx, lx + side * 10, ly, x0 - side * 10, ly, color, 1, { dash: [2, 5], alpha: 0.7 });};}diff --git a/tools/layout-lint.ts b/tools/layout-lint.tsindex 0982f21..5a21c9a 100644--- a/tools/layout-lint.ts+++ b/tools/layout-lint.ts@@ -251,7 +251,7 @@ function makeDuet(dir: string): void {if (r.exitCode) throw new Error(`rendering the lint duet: ${r.stderr.toString()}`);}// a long title, to see it trimmed on a phone- const voices = [{ name: "Lower", tele: "low.tele" }, { name: "Upper", tele: "high.tele" }];+ const voices = [{ name: "Lower", tele: "low.tele", melody: "low.json" }, { name: "Upper", tele: "high.tele", melody: "high.json" }];writeFileSync(`${dir}/show.json`, JSON.stringify({ title: "A duet with a title long enough to need trimming", audio: "low.wav", bpm: 120, voices }));}@@ -316,6 +316,7 @@ async function main() {await page.waitForSelector(".duet-head canvas", { timeout: 15000 });await check("duet", 2000);await page.locator(".duet-bar button.primary").click();+ // 1.2 s in: both heads singing, a word at each mouthawait check("duet, playing", 1200);}if (!modes.length) {