the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Language front ends: a router sends each lyric word to the front end whose script it is in (English, Korean); explicit IPA syllables pass through
Joshua Pham1aa2d47577df
diff --git a/crates/chimera-cli/src/render.rs b/crates/chimera-cli/src/render.rsindex 9e105a2..5e8a7d3 100644--- a/crates/chimera-cli/src/render.rs+++ b/crates/chimera-cli/src/render.rs@@ -484,7 +484,9 @@ fn render_tracked(v: &mut HumanVoice, out: &mut [f32], artic: bool, tele: bool)/// `render notes <in.json> <out> [body] [--artic tracks.json] [--tele voice.tele]`: `--artic` also/// writes the articulators over time (`{"rate", "body", "keys", "frames"}`), to animate a face in/// sync; `--tele` writes the voice's whole telemetry over time (see `TeleRecorder`), which the-/// app's duet page replays on a 3D head.+/// app's duet page replays on a 3D head. The melody file may give `"syllables"` (IPA+/// onset/nucleus/coda per sounding note) instead of English `"lyrics"`: a language front end's+/// output (docs/language-front-ends.md).pub fn notes(ctx: &Ctx, a: &[String]) -> Result<(), String> {let mut artic_out: Option<String> = None;let mut tele_out: Option<String> = None;@@ -509,8 +511,14 @@ pub fn notes(ctx: &Ctx, a: &[String]) -> Result<(), String> {let bpm = j["bpm"].as_f64().ok_or("bpm missing")?;let vibrato = j["vibrato"].as_f64().unwrap_or(35.0);let raw: Vec<[f64; 2]> = serde_json::from_value(j["notes"].clone()).map_err(|e| format!("notes: {e}"))?;- let g = g2p()?;- let syl = lyrics_to_syllables(j["lyrics"].as_str().ok_or("lyrics missing")?, &g);+ // "syllables" sing what a language front end wrote; otherwise the lyrics go through the+ // English front end (the pronouncing dictionary)+ let syl: Vec<Syllable> = if j.get("syllables").is_some() {+ serde_json::from_value(j["syllables"].clone()).map_err(|e| format!("syllables: {e}"))?+ } else {+ let g = g2p()?;+ lyrics_to_syllables(j["lyrics"].as_str().ok_or("lyrics missing")?, &g)+ };let sounding = raw.iter().filter(|n| n[0] > 0.0).count();if syl.len() != sounding {return Err(format!("{} syllables for {sounding} notes: {}", syl.len(),diff --git a/crates/chimera-cli/tests/cli.rs b/crates/chimera-cli/tests/cli.rsindex 1264486..27e9871 100644--- a/crates/chimera-cli/tests/cli.rs+++ b/crates/chimera-cli/tests/cli.rs@@ -377,6 +377,32 @@ fn render_notes_artic_tracks_follow_the_sound_without_changing_it() {assert!(closed < 0.1 && open > 0.5, "lipAp closed {closed}, open {open}");}+#[test]+fn render_notes_sings_a_front_ends_syllables_without_lyrics() {+ // a language front end writes IPA syllables; no lyrics, no pronouncing dictionary+ let melody = tmp("melody-syllables.json");+ let syl = |onset: &[&str], v: &str, coda: &[&str]| {+ let segs = |xs: &[&str]| xs.iter().map(|x| serde_json::json!({ "ipa": x })).collect::<Vec<_>>();+ serde_json::json!({ "text": v, "onset": segs(onset), "nucleus": { "ipa": v }, "coda": segs(coda), "wordEnd": true, "phraseEnd": false })+ };+ let j = serde_json::json!({+ "bpm": 120, "t0": 0, "notes": [[0, 1], [67, 1], [63, 0.5], [60, 1.5]],+ "syllables": [syl(&["t"], "eɪ", &["k"]), syl(&["m"], "aɪ", &[]), syl(&["h"], "æ", &["n", "d"])],+ });+ std::fs::write(&melody, j.to_string()).unwrap();+ let (stem, tracks) = (tmp("notes-syllables"), tmp("notes-syllables-artic.json"));+ let stdout = chimera(&["render", "notes", &melody, &stem, "female", "--artic", &tracks]);+ assert!(stdout.contains("3 notes"), "{stdout}");+ let t: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&tracks).unwrap()).unwrap();+ let keys: Vec<&str> = t["keys"].as_array().unwrap().iter().map(|k| k.as_str().unwrap()).collect();+ let lip = keys.iter().position(|k| *k == "lipAp").unwrap();+ let ap = |i: usize| t["frames"][i][lip].as_f64().unwrap();+ // the /m/ of the second syllable (its note starts at 1 s) closes the lips, its vowel opens them+ let closed = (85..105).map(ap).fold(f64::MAX, f64::min);+ let open = (105..125).map(ap).fold(f64::MIN, f64::max);+ assert!(closed < 0.1 && open > 0.5, "lipAp closed {closed}, open {open}");+}+#[test]fn render_notes_tele_records_the_live_telemetry_without_changing_the_sound() {let melody = tmp("tele-melody.json");diff --git a/crates/chimera/src/phonetics/korean.rs b/crates/chimera/src/phonetics/korean.rsindex c3a92c4..0ea9f4e 100644--- a/crates/chimera/src/phonetics/korean.rs+++ b/crates/chimera/src/phonetics/korean.rs@@ -7,6 +7,7 @@//! The engine has no tense (fortis) stops, so tense ㄲ ㄸ ㅃ ㅉ sing as unaspirated (voiced) stops,//! and lax and aspirated stops both take the planner's aspiration. ㅅ before [i] or [j] is [ʃ].+use super::syllables::FrontEnd;use super::{Segment, Syllable};const BASE: u32 = 0xAC00;@@ -224,3 +225,15 @@ pub fn word_syllables(word: &str) -> Vec<Syllable> {}out}++/// The Korean front end: Hangul blocks, by the rules above (no data needed).+pub struct Korean;++impl FrontEnd for Korean {+ fn starts(&self, c: char) -> bool {+ is_hangul(c)+ }+ fn word(&self, word: &str) -> Vec<Syllable> {+ word_syllables(word)+ }+}diff --git a/crates/chimera/src/phonetics/syllables.rs b/crates/chimera/src/phonetics/syllables.rsindex f186110..22d6352 100644--- a/crates/chimera/src/phonetics/syllables.rs+++ b/crates/chimera/src/phonetics/syllables.rs@@ -1,13 +1,17 @@-//! Lyrics → sung syllables. Hangul words go to [`super::korean`], one syllable per block. Other-//! words come from the pronouncing dictionary (unreduced: sung function words keep full vowels),-//! are split into syllables by the maximal-onset principle with English onset clusters, and the-//! spelling is split to match for display ("twin-kle").-//! Typed hyphens force syllable breaks; a lone "-" (or "~") holds the previous vowel onto the-//! next note (melisma), as in vocaloid editors.+//! Lyrics → sung syllables, through language front ends (docs/language-front-ends.md). A front+//! end claims the words written in its script and turns each into syllables in IPA; the router+//! here walks the lyrics, sends each word to the front end that claims it, and handles what every+//! language shares: melisma marks, phrase punctuation and word ends.+//!+//! English words come from the pronouncing dictionary (unreduced: sung function words keep full+//! vowels), are split into syllables by the maximal-onset principle with English onset clusters,+//! and the spelling is split to match for display ("twin-kle"). Hangul words go to+//! [`super::korean`], one syllable per block. Typed hyphens force syllable breaks; a lone "-" (or+//! "~") holds the previous vowel onto the next note (melisma), as in vocaloid editors.use crate::anatomy::human::BodyMix;use super::english::js_is_space;-use super::korean::{is_hangul, word_syllables};+use super::korean::Korean;use super::planner::is_vowel;use super::{Segment, Syllable};use serde::{Deserialize, Serialize};@@ -149,86 +153,114 @@ impl<F: Fn(&str, bool) -> Vec<Segment>> WordSource for F {fn is_lyric_punct(c: char) -> bool {matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | '\n')}-fn is_word_start(c: char) -> bool {- c.is_ascii_alphabetic() || c == '\''++/// A language front end: claims the words written in its script and turns each into sung syllables+/// (IPA onset, nucleus and coda; each syllable's text is its part of the word's spelling).+pub trait FrontEnd {+ /// A word this front end reads starts with `c`.+ fn starts(&self, c: char) -> bool;+ /// `c` continues a word this front end started.+ fn continues(&self, c: char) -> bool {+ self.starts(c)+ }+ /// One word → its syllables (the router marks the last as the word's end).+ fn word(&self, word: &str) -> Vec<Syllable>;}-/// `text.match(/[A-Za-z'][A-Za-z'\-]*|[가-힣]+|(?<=\s|^)[~-](?=\s|$)|[.,;:!?\n]/g)`-fn lyric_tokens(text: &str) -> Vec<String> {+/// English, through a [`WordSource`] (the pronouncing dictionary, or letter-to-sound rules).+pub struct English<'a, W: WordSource>(pub &'a W);++impl<W: WordSource> FrontEnd for English<'_, W> {+ fn starts(&self, c: char) -> bool {+ c.is_ascii_alphabetic() || c == '\''+ }+ fn continues(&self, c: char) -> bool {+ self.starts(c) || c == '-'+ }+ fn word(&self, tok: &str) -> Vec<Syllable> {+ // typed hyphens split syllables explicitly ("ti-ger"); otherwise the dictionary decides+ let parts: Vec<&str> = tok.split('-').filter(|p| !p.is_empty()).collect();+ let mut syls: Vec<Syllable> = Vec::new();+ for part in &parts {+ let sy = syllabify_segments(&self.0.word(&part.to_lowercase(), false));+ let spell: Vec<String> = if parts.len() > 1 {+ let mut v = vec![part.to_string()];+ v.extend(std::iter::repeat_n("~".to_string(), sy.len().saturating_sub(1)));+ v+ } else {+ split_spelling(part, sy.len())+ };+ for (i, s) in sy.into_iter().enumerate() {+ syls.push(Syllable { text: spell.get(i).cloned().unwrap_or_else(|| "~".into()), onset: s.onset, nucleus: s.nucleus, coda: s.coda, melisma: None, word_end: false, phrase_end: false });+ }+ }+ syls+ }+}++enum Token {+ Word(usize, String),+ Mark(char),+}++/// Words (with the index of the front end that claims them), melisma marks and phrase punctuation,+/// in order. For English and Hangul this is+/// `text.match(/[A-Za-z'][A-Za-z'\-]*|[가-힣]+|(?<=\s|^)[~-](?=\s|$)|[.,;:!?\n]/g)`.+fn lyric_tokens(text: &str, front_ends: &[&dyn FrontEnd]) -> Vec<Token> {let s: Vec<char> = text.chars().collect();let mut out = Vec::new();let mut i = 0;while i < s.len() {let c = s[i];- if is_hangul(c) {- let start = i;- while i < s.len() && is_hangul(s[i]) {- i += 1;- }- out.push(s[start..i].iter().collect());- continue;- }- if is_word_start(c) {+ if let Some(k) = front_ends.iter().position(|f| f.starts(c)) {let start = i;i += 1;- while i < s.len() && (is_word_start(s[i]) || s[i] == '-') {+ while i < s.len() && front_ends[k].continues(s[i]) {i += 1;}- out.push(s[start..i].iter().collect());+ out.push(Token::Word(k, s[start..i].iter().collect()));continue;}let melisma = (c == '~' || c == '-') && (i == 0 || js_is_space(s[i - 1])) && (i + 1 == s.len() || js_is_space(s[i + 1]));if melisma || is_lyric_punct(c) {- out.push(c.to_string());+ out.push(Token::Mark(c));}i += 1;}out}-/// Lyrics text → syllables (needs the pronouncing dictionary for real words).-pub fn lyrics_to_syllables(text: &str, g2p: &impl WordSource) -> Vec<Syllable> {+/// Lyrics text → syllables, each word read by the first front end that claims it. Characters no+/// front end claims (other scripts, symbols) are skipped.+pub fn read_lyrics(text: &str, front_ends: &[&dyn FrontEnd]) -> Vec<Syllable> {let mut out: Vec<Syllable> = Vec::new();- // words, melisma marks and phrase punctuation, in order- let tokens = lyric_tokens(&text.replace('’', "'"));- for tok in &tokens {- if tok.chars().count() == 1 && tok.chars().all(is_lyric_punct) {- if let Some(last) = out.last_mut() {- last.phrase_end = true;+ for tok in lyric_tokens(&text.replace('’', "'"), front_ends) {+ match tok {+ Token::Mark(c) if is_lyric_punct(c) => {+ if let Some(last) = out.last_mut() {+ last.phrase_end = true;+ }}- continue;- }- if tok == "-" || tok == "~" {- if let Some(prev) = out.last() {- let s = Syllable { text: "~".into(), onset: vec![], nucleus: prev.nucleus.clone(), coda: vec![], melisma: Some(true), word_end: prev.word_end, phrase_end: false };- out.push(s);+ Token::Mark(_) => {+ if let Some(prev) = out.last() {+ let s = Syllable { text: "~".into(), onset: vec![], nucleus: prev.nucleus.clone(), coda: vec![], melisma: Some(true), word_end: prev.word_end, phrase_end: false };+ out.push(s);+ }}- continue;- }- if tok.starts_with(is_hangul) {- out.extend(word_syllables(tok));- continue;- }- // typed hyphens split syllables explicitly ("ti-ger"); otherwise the dictionary decides- let parts: Vec<&str> = tok.split('-').filter(|p| !p.is_empty()).collect();- let mut syls: Vec<Syllable> = Vec::new();- for part in &parts {- let sy = syllabify_segments(&g2p.word(&part.to_lowercase(), false));- let spell: Vec<String> = if parts.len() > 1 {- let mut v = vec![part.to_string()];- v.extend(std::iter::repeat_n("~".to_string(), sy.len().saturating_sub(1)));- v- } else {- split_spelling(part, sy.len())- };- for (i, s) in sy.into_iter().enumerate() {- syls.push(Syllable { text: spell.get(i).cloned().unwrap_or_else(|| "~".into()), onset: s.onset, nucleus: s.nucleus, coda: s.coda, melisma: None, word_end: false, phrase_end: false });+ Token::Word(k, w) => {+ let mut syls = front_ends[k].word(&w);+ if let Some(last) = syls.last_mut() {+ last.word_end = true;+ }+ out.append(&mut syls);}}- if let Some(last) = syls.last_mut() {- last.word_end = true;- }- out.append(&mut syls);}out}++/// Lyrics text → syllables through the built-in front ends that need no data beyond the English+/// dictionary: English (`g2p`) and Korean.+pub fn lyrics_to_syllables(text: &str, g2p: &impl WordSource) -> Vec<Syllable> {+ read_lyrics(text, &[&English(g2p), &Korean])+}diff --git a/src/show/words.ts b/src/show/words.tsindex d4cded6..83b551d 100644--- a/src/show/words.ts+++ b/src/show/words.ts@@ -11,6 +11,8 @@ export interface Melody {t0?: number;lyrics: string;notes: [number, number][];+ /** sung syllables from a language front end: used instead of reading the lyrics as English */+ syllables?: Syllable[];}export interface SungWords {diff --git a/src/ui/components/DuetPage.tsx b/src/ui/components/DuetPage.tsxindex 38dced7..9f9e4a3 100644--- a/src/ui/components/DuetPage.tsx+++ b/src/ui/components/DuetPage.tsx@@ -83,7 +83,7 @@ export function DuetPage(props: { id: string }) {const words = melodies.map((m) => {if (!m) return null;try {- return sungWords(m, lyricsToSyllables(m.lyrics), show.spell);+ return sungWords(m, m.syllables ?? lyricsToSyllables(m.lyrics), show.spell);} catch (e) {console.warn("duet: no words for a voice:", e);return null;diff --git a/src/ui/singing.ts b/src/ui/singing.tsindex 77e2c1b..a40ceee 100644--- a/src/ui/singing.ts+++ b/src/ui/singing.ts@@ -71,6 +71,8 @@ export function ensureDictionary(): void {.load().then(() => {const s = useSing.getState();+ // a song that brings its own syllables (another language's front end) is not re-read as English+ if (DEMO_SONGS.some((d) => d.syllables && d.lyrics === s.lyrics)) return;const syllables = lyricsToSyllables(s.lyrics);useSing.setState({ syllables, cursor: Math.min(s.cursor, Math.max(0, syllables.length - 1)) });})@@ -269,7 +271,7 @@ export async function playDemo(name: string, body: BodyMix, ready?: () => Promis// letter-to-sound rules}if (token !== demoToken) return;- const syl = lyricsToSyllables(song.lyrics);+ const syl = song.syllables ?? lyricsToSyllables(song.lyrics);if (!syl.length) return;const shift = song.octave[nearestBody(body)] * 12;const notes = song.notes.map((n, i) => ({ midi: n[0] + shift, beats: n[1], syl: syl[i % syl.length] }));diff --git a/src/wasm/types.ts b/src/wasm/types.tsindex b120cbe..f2ead13 100644--- a/src/wasm/types.ts+++ b/src/wasm/types.ts@@ -236,6 +236,8 @@ export interface DemoSong {lyrics: string;notes: [number, number][];octave: { male: number; female: number; child: number };+ /** sung syllables from a language front end (IPA), used instead of reading the lyrics as English */+ syllables?: Syllable[];}export interface VowelRef {