Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

Russian text in Sing: a Cyrillic front end on the lyrics router, open sung syllables, and a demo song (#59)

Anton Leneve1e489b26d45
diff --git a/README.md b/README.md
index 8a67154..fcfe2c4 100644
--- a/README.md
+++ b/README.md
@@ -29,8 +29,8 @@ for tests and the `chimera` CLI.
notice under the box lists the symbols and marks the voice doesn't say (`chimera render speech`
prints the same as warnings).
- **Sing**: a pitch roll with lyrics per note; consonants land before the beat. Lyrics can be
- English or Korean (Hangul: one block per note, with Korean sound rules); each language is a
- front end ([docs/language-front-ends.md](docs/language-front-ends.md)).
+ English, Korean (Hangul: one block per note, with Korean sound rules) or Russian; each language
+ is a front end ([docs/language-front-ends.md](docs/language-front-ends.md)).
- **Beatbox**: pads and a step sequencer, every drum an articulatory gesture.
- **Bestiary**: songbird (two-voice syrinx), seal, alligator and elephant.
- **Duet** (`?show=<id>`): two 3D heads replay a pre-rendered song.
@@ -74,6 +74,7 @@ bun tools/musicxml-to-notes.ts score.mxl P1 --out p1.json # a score's part →
Song Dataset.
- [docs/speech-comparison.md](docs/speech-comparison.md): scoring the speech against real
speakers, phone by phone (the TSP speech database).
+- [docs/russian.md](docs/russian.md): how Russian text is read, and what is approximate.
- [docs/hill-climb/](docs/hill-climb/): the rules and log for tuning the voice one measured
step at a time.
diff --git a/crates/chimera-cli/src/render.rs b/crates/chimera-cli/src/render.rs
index 6555893..73740f3 100644
--- a/crates/chimera-cli/src/render.rs
+++ b/crates/chimera-cli/src/render.rs
@@ -48,12 +48,13 @@ pub fn g2p() -> Result<EnglishG2P, String> {
Ok(g)
}
-/// `name.toLowerCase().replace(/[^a-z]+/g, "-")`
+/// A file name from a song's name: letters of any script, everything else as one "-".
+/// (Only a-z counted, so "Ночной ветер" was written to "--male.wav".)
fn slug(name: &str) -> String {
let mut out = String::new();
let mut run = false;
for c in name.to_lowercase().chars() {
- if c.is_ascii_lowercase() {
+ if c.is_alphabetic() {
out.push(c);
run = false;
} else if !run {
@@ -64,6 +65,15 @@ fn slug(name: &str) -> String {
out
}
+#[cfg(test)]
+mod slug_tests {
+ #[test]
+ fn a_song_named_in_another_script_keeps_its_name() {
+ assert_eq!(super::slug("Twinkle, twinkle"), "twinkle-twinkle");
+ assert_eq!(super::slug("Ночной ветер"), "ночной-ветер");
+ }
+}
+
fn ms_since(t: Instant) -> f64 {
t.elapsed().as_secs_f64() * 1000.0
}
diff --git a/crates/chimera-cli/tests/cli.rs b/crates/chimera-cli/tests/cli.rs
index 27e9871..141732a 100644
--- a/crates/chimera-cli/tests/cli.rs
+++ b/crates/chimera-cli/tests/cli.rs
@@ -403,6 +403,21 @@ fn render_notes_sings_a_front_ends_syllables_without_lyrics() {
assert!(closed < 0.1 && open > 0.5, "lipAp closed {closed}, open {open}");
}
+#[test]
+fn the_cli_reads_russian_lyrics() {
+ // The CLI reads lyrics through its own call into the router (on #85, a list of its own): a
+ // language missing there is skipped, and the cargo tests on lyrics_to_syllables still pass
+ let syl: serde_json::Value = serde_json::from_str(&chimera(&["syllables", "в лесу́ молоко́"])).unwrap();
+ let texts: Vec<&str> = syl.as_array().unwrap().iter().map(|s| s["text"].as_str().unwrap()).collect();
+ assert_eq!(texts, ["в ле", "су\u{301}", "мо", "ло", "ко\u{301}"]);
+ // and a melody with Russian lyrics renders one syllable per note
+ let melody = tmp("melody-russian.json");
+ let j = serde_json::json!({ "bpm": 120, "lyrics": "молоко́", "notes": [[60, 1], [62, 1], [64, 2]] });
+ std::fs::write(&melody, j.to_string()).unwrap();
+ let stdout = chimera(&["render", "notes", &melody, &tmp("notes-russian"), "male"]);
+ assert!(stdout.contains("3 notes"), "{stdout}");
+}
+
#[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/mod.rs b/crates/chimera/src/phonetics/mod.rs
index 47411db..715994d 100644
--- a/crates/chimera/src/phonetics/mod.rs
+++ b/crates/chimera/src/phonetics/mod.rs
@@ -12,6 +12,7 @@ pub mod inventory;
pub mod ipa;
pub mod korean;
pub mod planner;
+pub mod russian;
pub mod sing;
pub mod songs;
pub mod syllables;
diff --git a/crates/chimera/src/phonetics/russian.rs b/crates/chimera/src/phonetics/russian.rs
new file mode 100644
index 0000000..078a8cd
--- /dev/null
+++ b/crates/chimera/src/phonetics/russian.rs
@@ -0,0 +1,339 @@
+//! Russian spelling → the existing inventory (no new sounds).
+//!
+//! Stress: a combining acute (молоко́) wins, then ё, then a short table of frequent words, then
+//! the first vowel (a guess: mark the stress for anything else). Vowels reduce in speech
+//! (`reduce`), not in singing.
+//!
+//! Approximations: a soft consonant is the plain one plus a 25 ms /j/ glide, not a palatalised
+//! articulation; щ is a long /ʃ/ with that glide; р is one tap. Stress and voicing do not cross
+//! word boundaries, except that a preposition takes its voicing from the word after it
+//! (`word_before`).
+use super::inventory::phoneme;
+use super::syllables::{is_english_onset, syllabify_with, FrontEnd};
+use super::{Segment, Syllable};
+use crate::anatomy::human::BodyMix;
+
+pub fn is_letter(c: char) -> bool {
+ matches!(c, 'а'..='я' | 'А'..='Я' | 'ё' | 'Ё')
+}
+pub fn contains_russian(s: &str) -> bool {
+ s.chars().any(is_letter)
+}
+/// false for в, с, к: a word that cannot carry a note
+pub fn has_vowel(s: &str) -> bool {
+ s.chars().any(|c| c.to_lowercase().any(vowel))
+}
+fn vowel(c: char) -> bool {
+ "аэыоуяеёию".contains(c)
+}
+fn devoiced(s: &str) -> Option<&'static str> {
+ Some(match s { "b" => "p", "d" => "t", "g" => "k", "v" => "f", "z" => "s", "ʐ" => "ʂ", _ => return None })
+}
+fn voiced(s: &str) -> Option<&'static str> {
+ Some(match s { "p" => "b", "t" => "d", "k" => "g", "f" => "v", "s" => "z", "ʂ" => "ʐ", _ => return None })
+}
+
+/// Prepositions and the particles не, ни: said as part of the next word, so unstressed, and
+/// their last consonant is not word-final.
+#[rustfmt::skip]
+const PROCLITICS: &[&str] = &[
+ "в", "во", "к", "ко", "с", "со", "из", "от", "до", "по", "за", "на", "над", "под", "об", "о", "у",
+ "при", "про", "для", "без", "через", "перед", "не", "ни",
+];
+
+/// Frequent words whose stress is not on the first vowel: (word, index of the stressed vowel).
+#[rustfmt::skip]
+const STRESS: &[(&str, usize)] = &[
+ ("меня", 1), ("тебя", 1), ("себя", 1), ("тебе", 1), ("себе", 1), ("его", 1), ("ему", 1), ("она", 1), ("оно", 1), ("они", 1),
+ ("моя", 1), ("твоя", 1), ("своя", 1), ("мои", 1), ("твои", 1), ("свои", 1), ("один", 1), ("одна", 1), ("одни", 1),
+ ("когда", 1), ("тогда", 1), ("всегда", 1), ("куда", 1), ("туда", 1), ("сюда", 1), ("сейчас", 1), ("теперь", 1),
+ ("зачем", 1), ("потом", 1), ("опять", 1), ("уже", 1), ("пока", 1), ("привет", 1), ("давай", 1), ("прости", 1),
+ ("большой", 1), ("какой", 1), ("такой", 1), ("другой", 1), ("домой", 1), ("назад", 1), ("вокруг", 1),
+ ("вода", 1), ("зима", 1), ("весна", 1), ("луна", 1), ("рука", 1), ("нога", 1), ("земля", 1), ("любовь", 1),
+ ("хочу", 1), ("могу", 1), ("люблю", 1), ("пою", 1), ("иду", 1), ("сегодня", 1), ("спасибо", 1), ("пожалуйста", 1),
+ ("хорошо", 2), ("почему", 2), ("потому", 2), ("никогда", 2), ("человек", 2), ("говорит", 2), ("говорю", 2),
+ ("молоко", 2), ("голова", 2), ("далеко", 2), ("высоко", 2),
+];
+
+/// Words ending in -ого / -его where г is /g/, not the /v/ of the genitive ending.
+const G_STAYS: &[&str] = &["много", "немного", "намного", "строго", "дорого", "недорого", "убого", "ого"];
+
+/// г said /v/: его, сегодня, and the genitive endings -ого / -его (кра́сного, ничего́).
+fn g_as_v(clean: &str, i: usize, n: usize) -> bool {
+ if clean == "сегодня" || clean.starts_with("сегодняшн") {
+ return i == 2;
+ }
+ i + 2 == n && (clean.ends_with("ого") || clean.ends_with("его")) && !G_STAYS.contains(&clean)
+}
+
+/// What follows the word's last sound.
+#[derive(Clone, Copy, PartialEq)]
+enum After {
+ /// a pause or another word: a final obstruent devoices
+ Devoice,
+ /// a preposition before a voiced obstruent (с горы́ → z)
+ Voice,
+ /// a preposition before a vowel or sonorant (над ле́сом keeps its d)
+ Keep,
+}
+
+pub fn word(input: &str, reduce: bool) -> Vec<Segment> {
+ word_before(input, None, reduce)
+}
+
+/// One word → segments. `next` is the word said after it (speech): a preposition's last
+/// consonant assimilates to it. Without it a preposition keeps its spelling's voicing.
+pub fn word_before(input: &str, next: Option<&str>, reduce: bool) -> Vec<Segment> {
+ if input.contains('-') {
+ let parts: Vec<&str> = input.split('-').filter(|p| !p.is_empty()).collect();
+ return parts.iter().enumerate().flat_map(|(i, p)| word_before(p, parts.get(i + 1).copied().or(next), reduce)).collect();
+ }
+ let lower = input.to_lowercase().replace("е\u{308}", "ё").replace("и\u{306}", "й");
+ let mut letters = Vec::new();
+ let mut explicit = None;
+ for c in lower.chars() {
+ if c == '\u{301}' {
+ if letters.last().copied().is_some_and(vowel) {
+ explicit = Some(letters.len() - 1);
+ }
+ } else if is_letter(c) {
+ letters.push(c);
+ }
+ }
+ let n = letters.len();
+ let clean: String = letters.iter().collect();
+ let clean = clean.as_str();
+ let proclitic = PROCLITICS.contains(&clean);
+ let positions: Vec<usize> = (0..n).filter(|&i| vowel(letters[i])).collect();
+ let listed = || STRESS.iter().find(|(w, _)| *w == clean).and_then(|(_, k)| positions.get(*k).copied());
+ let stress = explicit
+ .or_else(|| letters.iter().position(|c| *c == 'ё'))
+ .or_else(|| if proclitic { None } else { listed().or_else(|| positions.first().copied()) });
+
+ let mut out: Vec<Segment> = Vec::new();
+ let mut long = false;
+ let mut i = 0;
+ while i < n {
+ let at = i;
+ let mut c = letters[i];
+ let prev = i.checked_sub(1).map(|p| letters[p]);
+ let rest = &letters[i..];
+ i += 1;
+ if vowel(c) {
+ let iotated = ("яеёю".contains(c) && prev.is_none_or(|p| vowel(p) || "ьъ".contains(p))) || ("ио".contains(c) && prev == Some('ь'));
+ if iotated {
+ out.push(Segment::new("j"));
+ }
+ let stressed = stress == Some(at);
+ let weak = reduce && !stressed;
+ let last = at + 1 == n;
+ let hard_hiss = prev.is_some_and(|p| "жшц".contains(p));
+ let ipa = match c {
+ 'а' if weak && !last && prev.is_some_and(|p| "чщ".contains(p)) => "ɪ",
+ 'а' | 'о' if weak => "ɐ",
+ 'я' if weak => if last { "ɐ" } else { "ɪ" },
+ 'е' if weak => if hard_hiss { "ɨ" } else { "ɪ" },
+ 'э' if weak => "ɪ",
+ 'а' | 'я' => "a", 'о' | 'ё' => "o", 'у' | 'ю' => "u",
+ 'и' if hard_hiss => "ɨ", 'и' => "i", 'ы' => "ɨ", 'э' | 'е' => "e", _ => unreachable!(),
+ };
+ let mut seg = Segment { stress: Some(u8::from(stressed)), ..Segment::new(ipa) };
+ if weak {
+ // The duration rules are English's (Klatt), and have no /ɐ/: an unstressed
+ // vowel came out at 40–50 ms and the syllable was swallowed. Most Russian
+ // syllables are unstressed, so they get Russian lengths: the one before the
+ // stress is the longest, an open final one is longer again at a phrase's end.
+ let k = positions.iter().position(|&p| p == at).unwrap_or(0);
+ let pretonic = stress.is_some() && positions.get(k + 1).copied() == stress;
+ seg.dur = Some(if last && next.is_none() {
+ 0.12
+ } else if last || pretonic {
+ 0.09
+ } else {
+ 0.07
+ });
+ } else if reduce && ipa == "ɨ" {
+ // The table's /ɨ/ is English's reduced vowel (roses), 110 ms: a stressed ы came
+ // out half as long as у, and "дым" was heard as "дум"
+ seg.dur = Some(if next.is_none() && positions.last() == Some(&at) { 0.19 } else { 0.12 });
+ }
+ out.push(seg);
+ continue;
+ }
+ // -тся, -ться: a long /ts/ and an unstressed vowel
+ if rest == ['т', 'с', 'я'] || rest == ['т', 'ь', 'с', 'я'] {
+ out.push(lengthened("ts"));
+ let dur = reduce.then_some(if next.is_none() { 0.12 } else { 0.09 });
+ out.push(Segment { stress: Some(0), dur, ..Segment::new(if reduce { "ɐ" } else { "a" }) });
+ break;
+ }
+ // a doubled letter is one consonant, long between vowels (ва́нна), plain otherwise (ру́сский)
+ if rest.get(1) == Some(&c) && "ьъй".find(c).is_none() {
+ long = true;
+ continue;
+ }
+ // silent letters: стн (гру́стный), стл (счастли́вый), здн (по́здно), рдц (се́рдце),
+ // лнц (со́лнце), вств (чу́вство)
+ let silent = match c {
+ 'т' => prev == Some('с') && matches!(rest.get(1), Some('н' | 'л')),
+ 'д' => matches!((prev, rest.get(1)), (Some('з'), Some('н')) | (Some('р'), Some('ц'))),
+ 'л' => rest.starts_with(&['л', 'н', 'ц']),
+ 'в' => rest.starts_with(&['в', 'с', 'т', 'в']),
+ _ => false,
+ };
+ if silent {
+ continue;
+ }
+ // сч, зч, жч are щ (сча́стье, мужчи́на)
+ if "сзж".contains(c) && rest.get(1) == Some(&'ч') {
+ c = 'щ';
+ i += 1;
+ }
+ let next_c = letters.get(i).copied();
+ // ч is /ʂ/ in что and a few -чн- words
+ let ch_as_sh = c == 'ч'
+ && ((next_c == Some('т') && matches!(clean, "что" | "чтобы" | "чтоб" | "ничто"))
+ || (next_c == Some('н') && matches!(clean, "конечно" | "скучно" | "нарочно")));
+ let ipa = match c {
+ 'г' if g_as_v(clean, at, n) => "v",
+ 'ч' if ch_as_sh => "ʂ",
+ 'б' => "b", 'п' => "p", 'в' => "v", 'ф' => "f", 'г' => "g", 'к' => "k",
+ 'д' => "d", 'т' => "t", 'з' => "z", 'с' => "s", 'ж' => "ʐ", 'ш' => "ʂ",
+ 'х' => "x", 'ц' => "ts", 'ч' => "tʃ", 'щ' => "ʃ", 'м' => "m", 'н' => "n",
+ // р is one tap. The trill held the tip near the ridge for ~100 ms and the voicing
+ // all but stopped, so "рыба" was heard as "дыба".
+ 'л' => "ɫ", 'р' => "ɾ", 'й' => "j", _ => continue, // ь, ъ
+ };
+ let soft = !ch_as_sh && ("чщ".contains(c) || (!"жшцй".contains(c) && next_c.is_some_and(|x| "яеёиюь".contains(x))));
+ let ipa = if c == 'л' && soft { "l" } else { ipa };
+ let mut seg = if long && next_c.is_some_and(vowel) { lengthened(ipa) } else { Segment::new(ipa) };
+ long = false;
+ if c == 'щ' {
+ seg.dur = Some(0.18);
+ }
+ out.push(seg);
+ // a timed glide keeps softness audible without adding a vowel (a sung syllable)
+ if soft {
+ out.push(Segment { dur: Some(0.025), ..Segment::new("j") });
+ }
+ }
+
+ // Voicing spreads backwards from an obstruent through the cluster before it (в does not
+ // start it: твой keeps its t). The end of the word devoices, unless it's a preposition.
+ let after = if !proclitic {
+ After::Devoice
+ } else {
+ match next.and_then(|w| w.chars().find(|c| is_letter(*c))).and_then(|c| c.to_lowercase().next()) {
+ Some(c) if "пткфсшхцчщ".contains(c) => After::Devoice,
+ Some(c) if "бдгзж".contains(c) => After::Voice,
+ _ => After::Keep,
+ }
+ };
+ for i in (0..out.len()).rev() {
+ // the softness glide between two consonants doesn't block assimilation
+ let next = out[i + 1..].iter().find(|s| s.ipa != "j").map(|s| s.ipa.as_str());
+ let replacement = match next {
+ None if after == After::Keep => None,
+ None if after == After::Voice => voiced(&out[i].ipa),
+ None | Some("p" | "t" | "k" | "f" | "s" | "ʂ" | "ʃ" | "x" | "ts" | "tʃ") => devoiced(&out[i].ipa),
+ Some("b" | "d" | "g" | "z" | "ʐ") => voiced(&out[i].ipa),
+ _ => None,
+ };
+ if let Some(s) = replacement {
+ out[i].ipa = s.to_owned();
+ }
+ }
+ out
+}
+
+/// A consonant held half again as long as usual.
+fn lengthened(ipa: &str) -> Segment {
+ Segment { dur: phoneme(ipa, BodyMix::MALE).map(|p| p.dur * 1.5), ..Segment::new(ipa) }
+}
+
+/// Onsets for the lyric syllabifier. Russian singing keeps syllables open, so the next syllable
+/// takes the whole cluster (я-бло-ко, мо-сква́), except that a leading sonorant stays with the
+/// vowel before it (се́р-дце, вой-ска́). A /j/ after a consonant (its softness glide, or the /j/
+/// after ь in се-мья́) goes with that consonant.
+pub fn is_onset(cluster: &[Segment]) -> bool {
+ let first = cluster.first().map(|s| s.ipa.as_str());
+ let consonants = cluster.iter().enumerate().filter(|(i, s)| *i == 0 || s.ipa != "j").count();
+ consonants == 1 || first.is_some_and(|c| !["ɾ", "ɫ", "l", "n", "m", "j"].contains(&c))
+}
+
+/// Split a written word into n chunks, each ending after a vowel (and its stress mark).
+pub fn split_spelling(word: &str, n: usize) -> Vec<String> {
+ if n <= 1 {
+ return vec![word.to_owned()];
+ }
+ let chars: Vec<char> = word.chars().collect();
+ let vowels: Vec<usize> = chars.iter().enumerate().filter(|(_, c)| c.to_lowercase().any(vowel)).map(|(i, _)| i).collect();
+ if vowels.len() != n {
+ let mut out = vec![word.to_owned()];
+ out.extend(std::iter::repeat_n("~".to_owned(), n - 1));
+ return out;
+ }
+ let mut cuts = vec![0];
+ for &i in vowels.iter().take(n - 1) {
+ let mut cut = i + 1;
+ while chars.get(cut).is_some_and(|c| *c == '\u{301}') {
+ cut += 1;
+ }
+ // a sonorant before another consonant stays on this note, as is_onset leaves it (се́р-дце,
+ // вой-ска́, бо́ль-но)
+ let lower = |k: usize| chars.get(k).and_then(|c| c.to_lowercase().next());
+ if lower(cut).is_some_and(|c| "рлнмй".contains(c)) {
+ let soft = usize::from(lower(cut + 1) == Some('ь'));
+ if lower(cut + 1 + soft).is_some_and(|c| is_letter(c) && !vowel(c) && !"ьъ".contains(c)) {
+ cut += 1 + soft;
+ }
+ }
+ cuts.push(cut);
+ }
+ cuts.push(chars.len());
+ cuts.windows(2).map(|w| chars[w[0]..w[1]].iter().collect()).collect()
+}
+
+/// The Russian front end for sung lyrics: Cyrillic words, unreduced (no data needed).
+pub struct Russian;
+
+impl FrontEnd for Russian {
+ // a stress mark continues a word but never starts one: a lone U+0301 after a Latin word is
+ // another front end's (pinyin typed with a separate tone mark, ni + U+0301)
+ fn starts(&self, c: char) -> bool {
+ is_letter(c)
+ }
+ fn continues(&self, c: char) -> bool {
+ is_letter(c) || c == '\u{301}' || c == '-'
+ }
+ fn word(&self, word: &str) -> Vec<Syllable> {
+ self.word_after(word, None)
+ }
+ fn word_after(&self, tok: &str, prev: Option<&str>) -> Vec<Syllable> {
+ // typed hyphens split syllables explicitly, as in English
+ 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_with(&word(&part.to_lowercase(), false), |c| is_english_onset(c) || is_onset(c));
+ 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, ..Default::default() });
+ }
+ }
+ // a word with no vowel before this one (в, с, к) has no note of its own (it returned no
+ // syllables): it starts this word's first syllable, voiced by this word
+ if let (Some(c), Some(first)) = (prev.filter(|p| !has_vowel(p)), syls.first_mut()) {
+ let mut onset = word_before(c, parts.first().copied(), false);
+ onset.append(&mut first.onset);
+ first.onset = onset;
+ first.text = format!("{c} {}", first.text);
+ }
+ syls
+ }
+}
diff --git a/crates/chimera/src/phonetics/sing.rs b/crates/chimera/src/phonetics/sing.rs
index 37151db..efbd96b 100644
--- a/crates/chimera/src/phonetics/sing.rs
+++ b/crates/chimera/src/phonetics/sing.rs
@@ -27,8 +27,11 @@ fn cdur(ipa: &str, body: BodyMix, k: f64) -> f64 {
phoneme(ipa, body).map_or(0.07, |d| d.dur) * k
}
+/// Sung consonants: a duration the front end gives is its own (a language's timing: Mandarin's long
+/// nasal codas); otherwise the phoneme's spoken length times `k`. Either is squeezed when a note is
+/// too short for it.
fn consonants(segs: &[Segment], body: BodyMix, k: f64) -> Vec<Segment> {
- segs.iter().map(|c| Segment { ipa: c.ipa.clone(), dur: Some(cdur(&c.ipa, body, k)), aspirated: c.aspirated, vot: c.vot, palatalized: c.palatalized, breathy: c.breathy, ..Default::default() }).collect()
+ segs.iter().map(|c| Segment { ipa: c.ipa.clone(), dur: Some(c.dur.unwrap_or_else(|| cdur(&c.ipa, body, k))), aspirated: c.aspirated, vot: c.vot, palatalized: c.palatalized, breathy: c.breathy, ..Default::default() }).collect()
}
/// A sung vowel (or one half of a diphthong) at the note's pitch, with the sound marks of the
diff --git a/crates/chimera/src/phonetics/songs.rs b/crates/chimera/src/phonetics/songs.rs
index 7455826..1899451 100644
--- a/crates/chimera/src/phonetics/songs.rs
+++ b/crates/chimera/src/phonetics/songs.rs
@@ -48,4 +48,16 @@ pub static DEMO_SONGS: &[DemoSong] = &[
],
octave: SongOctave { male: -1.0, female: 0.0, child: 0.0 },
},
+ DemoSong {
+ // an original tune and words ("The night wind sings softly. Moonlight drifts over the
+ // forest."); the stress marks are part of the lyrics
+ name: "Ночной ветер",
+ bpm: 112.0,
+ lyrics: "Но́чью ве́тер ти́хо поёт. Лу́нный све́т над ле́сом плывёт.",
+ notes: &[
+ [64.0, 1.0], [62.0, 0.5], [60.0, 0.5], [59.0, 1.0], [60.0, 1.0], [62.0, 1.0], [59.0, 1.0], [57.0, 2.0],
+ [60.0, 1.0], [62.0, 0.5], [64.0, 1.5], [65.0, 1.0], [64.0, 0.5], [62.0, 0.5], [59.0, 1.0], [57.0, 2.0],
+ ],
+ octave: SongOctave { male: -1.0, female: 0.0, child: 0.0 },
+ },
];
diff --git a/crates/chimera/src/phonetics/syllables.rs b/crates/chimera/src/phonetics/syllables.rs
index 02b487e..cc160bc 100644
--- a/crates/chimera/src/phonetics/syllables.rs
+++ b/crates/chimera/src/phonetics/syllables.rs
@@ -6,12 +6,13 @@
//! 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
+//! [`super::korean`], one syllable per block, Cyrillic words to [`super::russian`]. 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::Korean;
+use super::russian::Russian;
use super::planner::is_vowel;
use super::{Segment, Syllable};
use serde::{Deserialize, Serialize};
@@ -35,8 +36,20 @@ pub struct SyllableParts {
pub coda: Vec<Segment>,
}
-/// Split one word's segments into onset / nucleus / coda syllables.
+/// Split one word's segments into onset / nucleus / coda syllables, with English's onsets.
pub fn syllabify_segments(segs: &[Segment]) -> Vec<SyllableParts> {
+ syllabify_with(segs, is_english_onset)
+}
+
+/// A consonant cluster that can start an English syllable.
+pub fn is_english_onset(cluster: &[Segment]) -> bool {
+ let cluster: String = cluster.iter().map(|s| s.ipa.as_str()).collect();
+ ONSETS.contains(&cluster.as_str())
+}
+
+/// Split one word's segments into syllables: of the consonants between two vowels, the longest
+/// run that `is_onset` accepts starts the second syllable.
+pub fn syllabify_with(segs: &[Segment], is_onset: impl Fn(&[Segment]) -> bool) -> Vec<SyllableParts> {
let vi: Vec<usize> = segs.iter().enumerate().filter(|(_, s)| is_vowel(&s.ipa, BodyMix::MALE)).map(|(i, _)| i).collect();
if vi.is_empty() {
return Vec::new();
@@ -49,9 +62,8 @@ pub fn syllabify_segments(segs: &[Segment]) -> Vec<SyllableParts> {
// consonants between this vowel and the next: the longest legal onset goes right
let between = &segs[v + 1..next];
let mut k = 0;
- for len in (1..=3.min(between.len())).rev() {
- let cluster: String = between[between.len() - len..].iter().map(|s| s.ipa.as_str()).collect();
- if ONSETS.contains(&cluster.as_str()) {
+ for len in (1..=between.len()).rev() {
+ if is_onset(&between[between.len() - len..]) {
k = len;
break;
}
@@ -165,6 +177,12 @@ pub trait FrontEnd {
}
/// One word → its syllables (the router marks the last as the word's end).
fn word(&self, word: &str) -> Vec<Syllable>;
+ /// The same, knowing the word of this front end just before it in the phrase, for a language
+ /// whose words lean on each other (a Russian preposition with no vowel has no note of its
+ /// own: it returns no syllables and starts the next word's first one).
+ fn word_after(&self, word: &str, _prev: Option<&str>) -> Vec<Syllable> {
+ self.word(word)
+ }
}
/// English, through a [`WordSource`] (the pronouncing dictionary, or letter-to-sound rules).
@@ -234,9 +252,12 @@ fn lyric_tokens(text: &str, front_ends: &[&dyn FrontEnd]) -> Vec<Token> {
/// 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();
+ // the word before this one and its front end, within a phrase
+ let mut prev: Option<(usize, String)> = None;
for tok in lyric_tokens(&text.replace('’', "'"), front_ends) {
match tok {
Token::Mark(c) if is_lyric_punct(c) => {
+ prev = None;
if let Some(last) = out.last_mut() {
last.phrase_end = true;
}
@@ -248,11 +269,13 @@ pub fn read_lyrics(text: &str, front_ends: &[&dyn FrontEnd]) -> Vec<Syllable> {
}
}
Token::Word(k, w) => {
- let mut syls = front_ends[k].word(&w);
+ let before = prev.as_ref().filter(|(pk, _)| *pk == k).map(|(_, p)| p.as_str());
+ let mut syls = front_ends[k].word_after(&w, before);
if let Some(last) = syls.last_mut() {
last.word_end = true;
}
out.append(&mut syls);
+ prev = Some((k, w));
}
}
}
@@ -260,7 +283,7 @@ pub fn read_lyrics(text: &str, front_ends: &[&dyn FrontEnd]) -> Vec<Syllable> {
}
/// Lyrics text → syllables through the built-in front ends that need no data beyond the English
-/// dictionary: English (`g2p`) and Korean.
+/// dictionary: English (`g2p`), Korean and Russian.
pub fn lyrics_to_syllables(text: &str, g2p: &impl WordSource) -> Vec<Syllable> {
- read_lyrics(text, &[&English(g2p), &Korean])
+ read_lyrics(text, &[&English(g2p), &Korean, &Russian])
}
diff --git a/crates/chimera/tests/golden_phonetics_text.rs b/crates/chimera/tests/golden_phonetics_text.rs
index aa9dd7b..de44cc7 100644
--- a/crates/chimera/tests/golden_phonetics_text.rs
+++ b/crates/chimera/tests/golden_phonetics_text.rs
@@ -121,7 +121,9 @@ fn syllables_match_typescript() {
fn songs_and_vowel_data_match_typescript() {
let fx = load("phonetics-data");
let mut f = Vec::new();
- check("demo songs", &fx["songs"], songs::DEMO_SONGS, &mut f);
+ // the fixture has the TypeScript engine's songs; later ones are checked in their own tests
+ let ts = fx["songs"].as_array().unwrap().len();
+ check("demo songs", &fx["songs"], &songs::DEMO_SONGS[..ts], &mut f);
check("vowel refs", &fx["vowels"], vowel_data::VOWELS, &mut f);
report("data", 2, f);
}
diff --git a/crates/chimera/tests/russian.rs b/crates/chimera/tests/russian.rs
new file mode 100644
index 0000000..c40747d
--- /dev/null
+++ b/crates/chimera/tests/russian.rs
@@ -0,0 +1,280 @@
+//! Russian spelling → segments (`phonetics::russian`), through speech and through sung lyrics.
+use chimera::anatomy::human::BodyMix;
+use chimera::phonetics::english::EnglishG2P;
+use chimera::phonetics::planner::{PlanOptions, plan_utterance};
+use chimera::phonetics::russian;
+use chimera::phonetics::songs::DEMO_SONGS;
+use chimera::phonetics::syllables::lyrics_to_syllables;
+
+fn ipa(segs: &[chimera::phonetics::Segment]) -> String {
+ segs.iter().map(|s| s.ipa.as_str()).collect::<Vec<_>>().join(" ")
+}
+/// as sung: no vowel reduction
+fn sung(w: &str) -> String {
+ ipa(&russian::word(w, false))
+}
+/// as spoken: unstressed vowels reduce
+fn said(w: &str) -> String {
+ ipa(&russian::word(w, true))
+}
+/// a spoken phrase of Russian words, each read with the word after it (Speak has no Russian yet:
+/// it comes back through the shared speech path, so the speech rules are tested on the reader)
+fn spoken(text: &str) -> Vec<chimera::phonetics::Segment> {
+ let words: Vec<&str> = text.split_whitespace().collect();
+ words.iter().enumerate().flat_map(|(i, w)| russian::word_before(w, words.get(i + 1).copied(), true)).collect()
+}
+fn phrase(text: &str) -> String {
+ ipa(&spoken(text))
+}
+
+#[test]
+fn vowels_and_consonants() {
+ assert_eq!(sung("аоуыэи"), "a o u ɨ e i");
+ assert_eq!(sung("шар"), "ʂ a ɾ");
+ assert_eq!(sung("хор"), "x o ɾ");
+ assert_eq!(sung("цирк"), "ts ɨ ɾ k");
+ assert_eq!(sung("жир"), "ʐ ɨ ɾ");
+ // р is a tap: the trill closed the voice off for ~100 ms and "рыба" was heard as "дыба"
+ assert_eq!(sung("рыба"), "ɾ ɨ b a");
+}
+
+#[test]
+fn iotation_and_softness() {
+ assert_eq!(sung("ёж"), "j o ʂ");
+ assert_eq!(sung("маяк"), "m a j a k");
+ assert_eq!(sung("съезд"), "s j e s t");
+ // a soft consonant is the plain one and a short glide; л also changes from dark to clear
+ assert_eq!(sung("лук"), "ɫ u k");
+ assert_eq!(sung("люк"), "l j u k");
+ let soft = russian::word("люк", false);
+ assert_eq!(soft[1].dur, Some(0.025));
+ // ь before и and о: the vowel gets its own /j/ (it was dropped)
+ assert_eq!(sung("чьи"), "tʃ j j i");
+ assert_eq!(sung("бульо́н"), "b u l j j o n");
+}
+
+#[test]
+fn stress_marks_and_the_fallbacks() {
+ let s = russian::word("молоко́", true);
+ assert_eq!(ipa(&s), "m ɐ ɫ ɐ k o");
+ assert_eq!(s.iter().filter_map(|s| s.stress).collect::<Vec<_>>(), [0, 0, 1]);
+ // ё is stressed
+ assert_eq!(said("поёт"), "p ɐ j o t");
+ // a frequent word from the table, then the first vowel
+ assert_eq!(said("тебя"), "t j ɪ b j a");
+ assert_eq!(said("мама"), "m a m ɐ");
+ // singing keeps full vowels
+ assert_eq!(sung("молоко́"), "m o ɫ o k o");
+}
+
+#[test]
+fn unstressed_ya_and_a_after_ch() {
+ // я was /ɐ/ everywhere; before the stress it is /ɪ/
+ assert_eq!(said("язы́к"), "j ɪ z ɨ k");
+ assert_eq!(said("пяти́"), "p j ɪ t j i");
+ assert_eq!(said("часы́"), "tʃ j ɪ s ɨ");
+ // but word-final я and а stay open
+ assert_eq!(said("неде́ля"), "n j ɪ d j e l j ɐ");
+ assert_eq!(said("ту́ча"), "t u tʃ j ɐ");
+}
+
+#[test]
+fn devoicing_and_assimilation_inside_a_word() {
+ assert_eq!(sung("дуб"), "d u p");
+ assert_eq!(sung("лодка"), "ɫ o t k a");
+ assert_eq!(sung("сдать"), "z d a t j");
+ assert_eq!(sung("вторник"), "f t o ɾ n j i k");
+ // в doesn't voice what's before it
+ assert_eq!(sung("твой"), "t v o j");
+ // through the softness glide
+ assert_eq!(sung("ло́шадь"), "ɫ o ʂ a t j");
+}
+
+#[test]
+fn a_preposition_is_part_of_the_next_word() {
+ // each was devoiced as if it ended a phrase: "нат лесом", "ф лесу", "ис дома"
+ assert_eq!(phrase("над ле́сом"), "n ɐ d l j e s ɐ m");
+ assert_eq!(phrase("в лесу́"), "v l j ɪ s u");
+ assert_eq!(phrase("из до́ма"), "i z d o m ɐ");
+ // and it assimilates to an obstruent
+ assert_eq!(phrase("в ти́хом"), "f t j i x ɐ m");
+ assert_eq!(phrase("с горы́"), "z g ɐ ɾ ɨ");
+ assert_eq!(phrase("из-под стола́"), "i s p ɐ t s t ɐ ɫ a");
+ // sung words come one at a time: the preposition keeps its spelling's voicing
+ assert_eq!(sung("над"), "n a d");
+ // a word that isn't a preposition still devoices
+ assert_eq!(phrase("са́д мо́й"), "s a t m o j");
+}
+
+#[test]
+fn g_in_the_genitive_ending_is_v() {
+ assert_eq!(said("его́"), "j ɪ v o");
+ assert_eq!(said("сего́дня"), "s j ɪ v o d n j ɐ");
+ assert_eq!(said("кра́сного"), "k ɾ a s n ɐ v ɐ");
+ assert_eq!(said("ничего́"), "n j i tʃ j ɪ v o");
+ assert_eq!(said("мно́го"), "m n o g ɐ");
+}
+
+#[test]
+fn spelling_conventions() {
+ assert_eq!(sung("что"), "ʂ t o");
+ assert_eq!(sung("коне́чно"), "k o n j e ʂ n o");
+ assert_eq!(sung("сча́стье"), "ʃ j a s t j j e");
+ assert_eq!(sung("мужчи́на"), "m u ʃ j i n a");
+ assert_eq!(sung("по́здно"), "p o z n o");
+ assert_eq!(sung("со́лнце"), "s o n ts e");
+ assert_eq!(sung("чу́вство"), "tʃ j u s t v o");
+ assert_eq!(said("смеётся"), "s m j ɪ j o ts ɐ");
+ assert_eq!(sung("купа́ться"), "k u p a ts a");
+}
+
+#[test]
+fn the_review_s_small_gaps() {
+ // silent д in рдц, т in стл (they were said)
+ assert_eq!(sung("се́рдце"), "s j e ɾ ts e");
+ assert_eq!(sung("счастли́вый"), "ʃ j a s l j i v ɨ j");
+ // unstressed э reduces like е (it stayed /e/)
+ assert_eq!(said("этажа́"), "ɪ t ɐ ʐ a");
+ assert_eq!(said("э́то"), "e t ɐ");
+ // the vowel of -тся, -ться gets a Russian length, not English's 40-50 ms
+ let s = spoken("смеётся");
+ assert_eq!(s.last().unwrap().dur, Some(0.12));
+ let s = spoken("смеётся он");
+ assert_eq!((s[7].ipa.as_str(), s[7].dur), ("ɐ", Some(0.09)));
+}
+
+#[test]
+fn a_doubled_letter_is_one_consonant() {
+ // long between vowels, plain before a consonant (it was two separate closures)
+ let vanna = russian::word("ва́нна", false);
+ assert_eq!(ipa(&vanna), "v a n a");
+ assert!(vanna[2].dur.is_some_and(|d| d > 0.1), "{:?}", vanna[2].dur);
+ let russkiy = russian::word("ру́сский", false);
+ assert_eq!(ipa(&russkiy), "ɾ u s k j i j");
+ assert_eq!(russkiy[2].dur, None);
+}
+
+#[test]
+fn the_reader_s_speech_plans() {
+ for text in ["Приве́т", "Ты меня́ слы́шишь"] {
+ let plan = plan_utterance(&spoken(text), &PlanOptions { body: BodyMix::MALE, ..Default::default() });
+ assert!(plan.end.is_finite() && plan.end > 0.0);
+ assert!(!plan.gestures.is_empty());
+ }
+}
+
+#[test]
+fn english_speech_is_untouched() {
+ // Speak's tokenizer kept U+0301 in every word for Russian, so "cafe" + U+0301 (as pasted
+ // text sometimes arrives) read as one word, "k eɪ f ɛ", where main read "cafe"
+ let g = EnglishG2P::new();
+ assert_eq!(g.to_phrases("cafe\u{301}")[0].segments, g.to_phrases("cafe")[0].segments);
+}
+
+#[test]
+fn lyrics_split_into_syllables() {
+ let g = EnglishG2P::new();
+ let s = lyrics_to_syllables("мо-ло-ко́ ~", &g);
+ assert_eq!(s.len(), 4);
+ assert_eq!(s[3].melisma, Some(true));
+ let texts = |t: &str| lyrics_to_syllables(t, &g).iter().map(|s| s.text.clone()).collect::<Vec<_>>();
+ assert_eq!(texts("мая́к"), ["ма", "я\u{301}к"]);
+ assert_eq!(russian::split_spelling("поёт", 2), ["по", "ёт"]);
+}
+
+#[test]
+fn sung_syllables_are_open() {
+ // Russian singing gives the next syllable the whole cluster, so the vowel holds the note: only
+ // the onsets пр, стр were allowed, and я́блоко sang as я́б-ло-ко, Москва́ put /sk/ on the first
+ // note, ло́дка sang as ло́д-ка
+ let g = EnglishG2P::new();
+ let onsets = |t: &str| lyrics_to_syllables(t, &g).iter().map(|s| ipa(&s.onset)).collect::<Vec<_>>();
+ assert_eq!(onsets("ло́дка"), ["ɫ", "t k"]);
+ assert_eq!(onsets("я́блоко"), ["j", "b ɫ", "k"]);
+ assert_eq!(onsets("Москва́"), ["m", "s k v"]);
+ assert_eq!(onsets("сестра́"), ["s j", "s t ɾ"]);
+ // a leading sonorant (р л н м й) stays with the vowel before it
+ assert_eq!(onsets("се́рдце"), ["s j", "ts"]);
+ assert_eq!(onsets("войска́"), ["v", "s k"]);
+ assert_eq!(onsets("темно́"), ["t j", "n"]);
+ // a soft consonant's glide, and the /j/ after ь, go with it
+ assert_eq!(onsets("семья́"), ["s j", "m j j"]);
+ // the spelling on the notes splits the same way
+ let texts = lyrics_to_syllables("я́блоко", &g).iter().map(|s| s.text.clone()).collect::<Vec<_>>();
+ assert_eq!(texts, ["я\u{301}", "бло", "ко"]);
+ // a sonorant left on the note before is written there too
+ let texts = |t: &str| lyrics_to_syllables(t, &g).iter().map(|s| s.text.clone()).collect::<Vec<_>>();
+ assert_eq!(texts("войска́"), ["вой", "ска\u{301}"]);
+ assert_eq!(texts("се́рдце"), ["се\u{301}р", "дце"]);
+ assert_eq!(texts("бо́льно"), ["бо\u{301}ль", "но"]);
+ assert_eq!(texts("Москва́"), ["Мо", "сква\u{301}"]);
+}
+
+#[test]
+fn the_demo_song_has_a_note_per_syllable() {
+ let g = EnglishG2P::new();
+ let song = DEMO_SONGS.iter().find(|s| russian::contains_russian(s.lyrics)).expect("a Russian demo song");
+ assert_eq!(lyrics_to_syllables(song.lyrics, &g).len(), song.notes.len());
+}
+
+#[test]
+fn a_sung_preposition_without_a_vowel_joins_the_next_word() {
+ // в, с, к have no vowel, so no note: they were silently dropped from the song
+ let g = EnglishG2P::new();
+ let s = lyrics_to_syllables("в лесу́", &g);
+ assert_eq!(s.len(), 2);
+ assert_eq!(s[0].text, "в ле");
+ assert_eq!(ipa(&s[0].onset), "v l j");
+ // and it takes the next word's voicing
+ assert_eq!(ipa(&lyrics_to_syllables("к тебе́", &g)[0].onset), "k t j");
+ assert_eq!(ipa(&lyrics_to_syllables("с горы́", &g)[0].onset), "z g");
+ assert_eq!(ipa(&lyrics_to_syllables("в ти́хом", &g)[0].onset), "f t j");
+}
+
+#[test]
+fn unstressed_vowels_keep_a_syllable_s_length() {
+ // the duration rules are English's and have no /ɐ/: unstressed vowels came out 40-50 ms,
+ // "Доброе утро" took 0.75 s for five syllables, and Whisper lost whole words
+ let p = spoken("До́брое у́тро");
+ let weak: Vec<f64> = p.iter().filter(|s| s.stress == Some(0)).filter_map(|s| s.dur).collect();
+ assert_eq!(weak.len(), 3);
+ assert!(weak.iter().all(|d| *d >= 0.07), "{weak:?}");
+ // the last one, before a pause, is the longest
+ assert!(weak[2] > weak[0]);
+}
+
+#[test]
+fn a_stressed_y_is_as_long_as_the_other_stressed_vowels() {
+ // the duration table's /ɨ/ is English's reduced vowel (110 ms inherent): "дым" came out with
+ // half the vowel of "дум" and Whisper wrote "дум" for it
+ let y = |text: &str| spoken(text).iter().find(|s| s.ipa == "ɨ").unwrap().dur;
+ assert_eq!(y("ды́м"), Some(0.19));
+ assert_eq!(y("ды́м и до́м"), Some(0.12));
+ // sung, the note sets the length
+ assert!(russian::word("дым", false).iter().all(|s| s.ipa != "ɨ" || s.dur.is_none()));
+}
+
+#[test]
+fn russian_is_a_front_end_on_the_lyrics_router() {
+ let g = EnglishG2P::new();
+ // one line, three front ends: each word goes to its own
+ let s = lyrics_to_syllables("twinkle ми́р 별", &g);
+ assert_eq!(s.iter().map(|s| s.text.as_str()).collect::<Vec<_>>(), ["twin", "kle", "ми́р", "별"]);
+ assert!(s.iter().filter(|s| s.word_end).count() == 3);
+ // a preposition with no vowel leans only on a Russian word right after it in the phrase
+ assert_eq!(lyrics_to_syllables("в лесу́", &g)[0].text, "в ле");
+ assert_eq!(lyrics_to_syllables("в, лесу́", &g)[0].text, "ле");
+ let s = lyrics_to_syllables("в star ми́р", &g);
+ assert_eq!(s.iter().map(|s| s.text.as_str()).collect::<Vec<_>>(), ["star", "ми́р"]);
+}
+
+#[test]
+fn a_lone_stress_mark_is_not_a_russian_word() {
+ // Russian claimed a word that starts with U+0301, so ni + U+0301 (pinyin with a separate
+ // tone mark) would lose its tone to Russian once Mandarin is on the router
+ use chimera::phonetics::syllables::FrontEnd;
+ assert!(!russian::Russian.starts('\u{301}'));
+ assert!(russian::Russian.continues('\u{301}'));
+ let g = EnglishG2P::new();
+ assert_eq!(lyrics_to_syllables("молоко́", &g).len(), 3);
+}
diff --git a/docs/language-front-ends.md b/docs/language-front-ends.md
index f8bd7be..513ce6c 100644
--- a/docs/language-front-ends.md
+++ b/docs/language-front-ends.md
@@ -24,6 +24,7 @@ Korean and Mandarin need (`ɕ ʑ tɕ dʑ tʂ dʐ ɥ`, step 3) and aspiration as
|---|---|---|---|
| Latin | English | CMUdict (letter-to-sound until it loads) | `phonetics/english.rs`, `syllables.rs` |
| Hangul | Korean | nothing: a block's letters are its sounds | `phonetics/korean.rs` |
+| Cyrillic | Russian | nothing: spelling rules, stress marked with an acute ([russian.md](russian.md)) | `phonetics/russian.rs` |
The router (`read_lyrics` in `syllables.rs`) sends each word to the front end whose script it is
in, so a line can mix them (`twinkle 빵야 star`). It also handles what every language shares:
@@ -85,7 +86,8 @@ by hand, or to sing a language that has no front end yet.
`ɕ ʑ tɕ dʑ tʂ dʐ ɥ` were, and let `chimera calibrate consonants` set a fricative's constriction:
it appends new entries and leaves existing ones alone.
2. **Write the front end**: implement `FrontEnd` (which characters start and continue its words,
- and word → syllables), then add it to the router's list in `lyrics_to_syllables`. A front end
+ and word → syllables; `word_after` also gets the word before, for words that lean on each
+ other, as a Russian preposition with no vowel does), then add it to the router's list in `lyrics_to_syllables`. A front end
that needs data should load it like CMUdict: a gzipped file in `public/data/`, fetched only when
the lyrics need it.
3. **Say the phonology** in the syllables (aspiration and its length). Build `Syllable` and
diff --git a/docs/russian.md b/docs/russian.md
new file mode 100644
index 0000000..064f8df
--- /dev/null
+++ b/docs/russian.md
@@ -0,0 +1,52 @@
+# Russian
+
+Sing accepts Cyrillic lyrics. A word with a Cyrillic letter is read by
+`crates/chimera/src/phonetics/russian.rs`, a front end on the lyrics router
+([language-front-ends.md](language-front-ends.md)), so a line can mix it with English and Korean.
+There are no new sounds: Russian is mapped onto the existing inventory.
+
+Speak doesn't read Russian yet. The reader already has the speech rules (`word_before` with
+`reduce`: vowel reduction, Russian vowel lengths, prepositions voiced by the next word), and they
+are tested on it directly; Russian Speak comes back through the shared speech path, with the same
+front-end list as Sing.
+
+## Writing it
+
+- **Mark the stress** with a combining acute after the vowel: `молоко́`. ё is always stressed.
+ An unmarked word is looked up in a short table of frequent words (`STRESS`); failing that, its
+ **first vowel** is stressed. That guess is wrong for most longer words, so mark them.
+- In Sing, one vowel is one note. `мо-ло-ко́` forces the breaks, `~` holds the previous vowel.
+- Sung syllables are open: the next note takes the whole consonant cluster (я-бло-ко, мо-сква́),
+ except a leading sonorant р л н м й, which stays on the note before (се́р-дце, вой-ска́).
+- Write numbers as words: digits still go through the English number expander.
+
+## What it does
+
+| | |
+|---|---|
+| Vowels | а о у э ы и; я е ё ю add /j/ at the start of a word, after a vowel and after ь ъ |
+| Reduction (speech only) | unstressed о а → /ɐ/; е, э, and я before the end of the word → /ɪ/; а after ч щ → /ɪ/ |
+| Hard-only consonants | ж ш ц: и and unstressed е after them are /ɨ/ |
+| Voicing | a final obstruent devoices (дуб → /p/); voicing spreads backwards through a cluster (ло́дка → /tk/, сдать → /zd/); в doesn't start it (твой) |
+| Prepositions | в, с, к, из, над, под… are unstressed and take their voicing from the next word (в лесу́ /v/, в ти́хом /f/, с горы́ /z/) |
+| Spelling conventions | -ого, -его and его, сего́дня → /v/; что, коне́чно → /ʂ/; сч, зч, жч → щ; silent т д л в in стн, стл, здн, рдц, лнц, вств; -тся, -ться → /tsa/ |
+| Doubled letters | one consonant, half again as long between vowels (ва́нна), plain before a consonant (ру́сский) |
+
+## What is approximate
+
+- **Soft consonants** are the plain consonant and a 25 ms /j/ glide, not a palatalised
+ articulation. л is the exception: dark /ɫ/ when hard, clear /l/ when soft.
+- **щ** is a long /ʃ/ with that glide, and **ч** is /tʃ/ with it; the inventory has no
+ alveolo-palatals.
+- **р** is one tap /ɾ/. The trill /r/ held the tongue tip near the ridge for about 100 ms and the
+ voicing nearly stopped, so рыба was heard as дыба.
+- **Sung prepositions**: в, с, к have no vowel and so no note; they start the next word's first
+ syllable (and take its voicing). A preposition with a vowel is sung as its own word and keeps
+ its spelling's voicing (над ти́хим keeps /d/).
+- Not done: stress for arbitrary unmarked words, voicing across other word boundaries, loanwords
+ with hard consonants before е (те́ннис), numbers.
+- Ukrainian і ї є ґ are not Russian letters, so they split a word (привіт sings as прив and т).
+
+## Tests
+
+`crates/chimera/tests/russian.rs` has one case per rule above.
diff --git a/tests/russian-lyrics.test.ts b/tests/russian-lyrics.test.ts
new file mode 100644
index 0000000..4fb932d
--- /dev/null
+++ b/tests/russian-lyrics.test.ts
@@ -0,0 +1,15 @@
+// The web app's Sing reads lyrics through the wasm engine's own front-end list, not the Rust
+// `lyrics_to_syllables`: a language missing from that list is silently skipped in the browser
+// while the cargo tests still pass.
+import { describe, expect, test } from "bun:test";
+import { initEngine } from "./harness.ts";
+
+await initEngine();
+const { lyricsToSyllables } = await import("../src/wasm/engine.ts");
+
+describe("Russian lyrics in the web app", () => {
+ test("a Cyrillic word reaches the Russian front end", () => {
+ const s = lyricsToSyllables("молоко́ star");
+ expect(s.map((x) => x.text)).toEqual(["мо", "ло", "ко́", "star"]);
+ });
+});