the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Mandarin, by a native speaker's ear: medials, er, u and ong, rhymes that close in one movement, songs that sing their melody (#115)
Sayo2adb3c7e4343
diff --git a/crates/chimera-cli/src/calibrate.rs b/crates/chimera-cli/src/calibrate.rsindex 24ef897..d93ee5e 100644--- a/crates/chimera-cli/src/calibrate.rs+++ b/crates/chimera-cli/src/calibrate.rs@@ -46,13 +46,78 @@ fn round3(x: f64) -> f64 {const LO: [f64; 9] = [1.2, 5.0, 0.05, 0.12, 0.0, 0.0, -0.9, -1.3, 0.0];const HI: [f64; 9] = [4.6, 8.8, 2.3, 2.0, 1.4, 1.0, 0.9, 1.3, 1.0];-fn to_artic(p: &[f64]) -> HumanArtic {- let (tb_x, tb_y, jaw, lip_ap, lip_prot, lip_width, root, larynx, curl) =+/// What an apical vowel (ɿ after z c s, ʅ after zh ch sh r) fixes by construction instead of+/// leaving to the formant fit: the lips (spread and open as for [i], never narrowed or protruded, which+/// is how the fit once hit the formants without the tongue tip) and the tongue tip, held at the+/// place of the consonant before it, opened just enough to be a vowel's constriction. The tongue+/// body, jaw, root and larynx are fitted around that.+struct Apical {+ lip_ap: f64,+ lip_prot: f64,+ lip_width: f64,+ tt_x: f64,+ tt_y: f64,+ curl: f64,+}++/// How far below its sibilant's calibrated constriction an apical vowel's tongue tip sits (the same+/// coordinate as `calibrate consonants` sets, TtY). That constriction is ~0.15 cm² (the fricative's+/// hiss); 0.11 lower it is ~0.3 cm², a vowel's (the fit's own floor is 0.22).+const APICAL_OPENING: f64 = 0.11;++/// The apical vowel `ipa`'s tip, curl and lips for a body: the tip is the place of the sibilant+/// before it (s for ɿ, ʂ for ʅ), from the inventory with its calibrated TtY, and the lips are+/// those of the body's [i] (its already-calibrated entry).+fn apical(ipa: &str, bname: &str, i_lips: Option<[f64; 3]>) -> Option<Apical> {+ let consonant = match ipa {+ "ɿ" => "s",+ "ʅ" => "ʂ",+ _ => return None,+ };+ let c = chimera::phonetics::inventory::phoneme(consonant, bname.into())?.targets;+ let [lip_ap, lip_prot, lip_width] = i_lips?;+ Some(Apical { lip_ap, lip_prot, lip_width, tt_x: c.get(ArticKey::TtX)?, tt_y: c.get(ArticKey::TtY)? - APICAL_OPENING, curl: c.get(ArticKey::TtCurl).unwrap_or(0.0) })+}++/// Where a vowel's Nelder-Mead search starts, when the generic height/back guess is not enough:+/// the (body, vowel) entry whose solved posture is the start. Only the female [u̠] has one, the+/// male's. [u̠] is a corner of the tube (tbX, jaw, lip width at their lower bounds, protrusion at+/// its upper), and from the generic guess the female fit settled in another basin (jaw 1.8,+/// F2 +11 %), as did every start from the English [u] (jaw 1.6, F2 +10 % for male and female).+/// Deterministic: the male body is fitted before the female one, in a full run and, with+/// `--missing`, from the file. The start also centres the cost's priors, as the generic guess does.+fn start_from(ipa: &str, body: &str) -> Option<(&'static str, &'static str)> {+ match (ipa, body) {+ ("u̠", "female") => Some(("male", "u̠")),+ _ => None,+ }+}++/// The 9 fitted coordinates (`VOWEL_KEYS` order) of the entry `ipa` in a body's table.+fn solved_posture(table: &[(String, Json)], ipa: &str) -> Option<Vec<f64>> {+ let Json::Obj(entry) = &table.iter().find(|(k, _)| k == ipa)?.1 else { return None };+ let Json::Obj(artic) = &entry.iter().find(|(k, _)| k == "artic")?.1 else { return None };+ ["tbX", "tbY", "jaw", "lipAp", "lipProt", "lipWidth", "root", "larynx", "ttCurl"]+ .iter()+ .map(|key| match artic.iter().find(|(k, _)| k == key)?.1 {+ Json::Num(x) => Some(x),+ _ => None,+ })+ .collect()+}++fn to_artic(p: &[f64], fixed: Option<&Apical>) -> HumanArtic {+ let (tb_x, tb_y, jaw, mut lip_ap, mut lip_prot, mut lip_width, root, larynx, mut curl) =(p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]);+ if let Some(f) = fixed {+ (lip_ap, lip_prot, lip_width, curl) = (f.lip_ap, f.lip_prot, f.lip_width, f.curl);+ }let tip = rest_tip(jaw, tb_x, tb_y);// rhotic curl raises the tip toward the post-alveolar region- let tt_x = tip.x - 0.4 * curl;- let tt_y = tip.y + 2.0 * curl;+ let (mut tt_x, mut tt_y) = (tip.x - 0.4 * curl, tip.y + 2.0 * curl);+ if let Some(f) = fixed {+ (tt_x, tt_y) = (f.tt_x, f.tt_y);+ }HumanArtic {tb_x,tb_y,@@ -86,9 +151,20 @@ fn formants(air: &mut HumanAirway, freqs: &[f64], a: &HumanArtic) -> (Vec<f64>,}/// Articulatory vowel targets fitted to reference formants with the frequency-domain airway-/// model. `calibrate vowels [male|female|child|all] [--out file]`+/// model. `calibrate vowels [male|female|child|all] [--missing] [--out file]`+///+/// `--missing` fits only the vowels of `VOWELS` that the table lacks, and keeps every entry it+/// already has byte for byte (the fit isn't bit-reproducible, so a full rerun moves old entries+/// by ±0.001–0.002). New entries are appended after the old ones.pub fn vowels(a: &[String]) -> Result<(), String> {- let (rest, out) = out_option(a, VOWEL_TABLE)?;+ let (mut rest, out) = out_option(a, VOWEL_TABLE)?;+ let missing_only = match rest.iter().position(|x| x == "--missing") {+ Some(i) => {+ rest.remove(i);+ true+ }+ None => false,+ };let which = rest.first().map(String::as_str).unwrap_or("all");let n = 700;let freqs: Vec<f64> = (0..n)@@ -105,8 +181,25 @@ pub fn vowels(a: &[String]) -> Result<(), String> {}let mut air = HumanAirway::new(96000.0, body);let k = body.scale;- let mut table: Vec<(String, Json)> = Vec::new();+ // `--missing`: start from the entries already in the file and skip those vowels+ let mut table: Vec<(String, Json)> = match (&results, missing_only) {+ (Json::Obj(m), true) => match m.iter().find(|(k, _)| k == bname) {+ Some((_, Json::Obj(old))) => old.clone(),+ _ => Vec::new(),+ },+ _ => Vec::new(),+ };+ // [i]'s lips (aperture, protrusion, width) once calibrated, for the apical vowels+ let mut i_lips: Option<[f64; 3]> = None;for vw in VOWELS {+ if missing_only && table.iter().any(|(k, _)| k == vw.ipa) {+ // an [i] kept from the file still gives the apical vowels its lips: without them+ // a missing ɿ or ʅ was fitted unpinned, with no word of it+ if vw.ipa == "i" {+ i_lips = solved_posture(&table, "i").map(|p| [p[3], p[4], p[5]]);+ }+ continue;+ }let t = match bname {"male" => vw.male,"female" => vw.female,@@ -131,9 +224,33 @@ pub fn vowels(a: &[String]) -> Result<(), String> {if vw.ipa == "ɯ" {x0 = vec![2.6, 7.35, 0.25, 0.5, 0.1, 0.65, 0.4, 0.2, 0.0];}+ // a declared start replaces the generic guess, and the priors below centre on it too+ if let Some(start) = start_from(vw.ipa, bname)+ .and_then(|(b, e)| match &results {+ Json::Obj(m) => match &m.iter().find(|(k, _)| k == b)?.1 {+ Json::Obj(t) => solved_posture(t, e),+ _ => None,+ },+ _ => None,+ })+ {+ x0 = start;+ }let jaw_prior = 0.2 + 1.5 * vw.height;+ let pinned = apical(vw.ipa, bname, i_lips);+ // the apical vowels' tongue body and jaw are held a little nearer the vowel-space guess+ // (a close vowel, the tongue hardly leaving the consonant): with the tip and lips+ // pinned the fit otherwise spent the jaw (1.4) and the body on the formants. 0.05 held+ // them best but cost F2 +10% and F3 -10%; 0.01 keeps the formants within 11%.+ let (w_body, w_jaw) = if pinned.is_some() { (0.01, 0.01) } else { (0.006, 0.004) };let mut cost = |p: &[f64]| -> f64 {- let a = to_artic(p);+ let a = to_artic(p, pinned.as_ref());+ // the apical vowels' fixed lips and curl, in the priors below too+ let mut q = p.to_vec();+ if let Some(f) = &pinned {+ (q[3], q[4], q[5], q[8]) = (f.lip_ap, f.lip_prot, f.lip_width, f.curl);+ }+ let p = &q[..];let (f, min_area) = formants(&mut air, &freqs, &a);if f.len() < 3 {return 50.0;@@ -148,7 +265,7 @@ pub fn vowels(a: &[String]) -> Result<(), String> {if min_area < min_ok {c += 0.4 * pow((min_ok - min_area) / min_ok, 2.0);}- c += 0.004 * pow(p[2] - jaw_prior, 2.0);+ c += w_jaw * pow(p[2] - jaw_prior, 2.0);let open = vw.height > 0.6;if vw.round {let (w_max, p_min, ap_max) = (@@ -169,7 +286,7 @@ pub fn vowels(a: &[String]) -> Result<(), String> {// the tongue body near where the vowel's height and backness put it: many postures// give the same formants, and without this the fit wandered (a schwa with the// tongue as low as /ɑ/), making every transition through it needlessly long- c += 0.006 * (pow(p[0] - x0[0], 2.0) + pow(p[1] - x0[1], 2.0));+ c += w_body * (pow(p[0] - x0[0], 2.0) + pow(p[1] - x0[1], 2.0));if !matches!(vw.ipa, "ɝ" | "ʅ") {c += 0.5 * p[8] * p[8];}@@ -198,7 +315,10 @@ pub fn vowels(a: &[String]) -> Result<(), String> {best = nb;}}- let a = to_artic(&best.x);+ let a = to_artic(&best.x, pinned.as_ref());+ if vw.ipa == "i" {+ i_lips = Some([a.lip_ap, a.lip_prot, a.lip_width]);+ }let (f, _) = formants(&mut air, &freqs, &a);let err: Vec<f64> = (0..3).map(|i| match f.get(i) {diff --git a/crates/chimera-cli/src/main.rs b/crates/chimera-cli/src/main.rsindex 9f7b958..18f8035 100644--- a/crates/chimera-cli/src/main.rs+++ b/crates/chimera-cli/src/main.rs@@ -30,7 +30,8 @@ usage: chimera <command> [args] [--float][--against earlier/score.json] (score.json: distance to the singer, and the verdict)compare tsp [tsp-dir] [outdir] [--speakers FA,MA,…] [--jobs n] [--dump][--against earlier/score.json] (distance to 23 real speakers, phone by phone)- calibrate vowels [male|female|child|all] [--out file]+ calibrate vowels [male|female|child|all] [--missing] [--out file]+ (--missing: fit only vowels the table lacks; existing entries stay untouched)calibrate consonants [--out file]Output names are stems (<out>.wav). --float writes 32-bit float WAVs instead of 16-bit PCM.diff --git a/crates/chimera-cli/tests/cli.rs b/crates/chimera-cli/tests/cli.rsindex 77a1157..5340ef0 100644--- a/crates/chimera-cli/tests/cli.rs+++ b/crates/chimera-cli/tests/cli.rs@@ -87,6 +87,50 @@ fn calibrate_consonants_reproduces_the_committed_table() {);}+/// `--missing` fits only the vowels the table lacks and leaves every other entry as it was, byte+/// for byte: with nothing missing it rewrites the file unchanged.+#[test]+fn calibrate_vowels_missing_changes_nothing_when_nothing_is_missing() {+ let committed = std::fs::read_to_string(format!("{PHONETICS}/vowelTargets.generated.json")).unwrap();+ let out = tmp("vowelTargets-missing.json");+ std::fs::write(&out, &committed).unwrap();+ chimera(&["calibrate", "vowels", "all", "--missing", "--out", &out]);+ assert!(std::fs::read_to_string(&out).unwrap() == committed, "nothing missing: the file must not change");+}++/// `--missing` fits a vowel the file lacks and leaves every other entry as it was. An apical vowel+/// is fitted with its tip and lips pinned even though [i], whose lips it takes, is not refitted+/// (it came out unpinned, lips narrowed, with no word of it).+#[test]+fn calibrate_vowels_missing_fits_only_the_missing_vowel_and_pins_an_apical_one() {+ let committed = std::fs::read_to_string(format!("{PHONETICS}/vowelTargets.generated.json")).unwrap();+ // the first ɿ entry is the male body's: cut it out of the text+ let key = "\"ɿ\": {";+ let a = committed[..committed.find(key).unwrap()].rfind('\n').unwrap();+ let b = a + 1 + committed[a + 1..].find("\n },\n").unwrap() + "\n },".len();+ let without = format!("{}{}", &committed[..a], &committed[b..]);+ let json = |s: &str| serde_json::from_str::<serde_json::Value>(s).unwrap();+ assert!(json(&without)["male"].get("ɿ").is_none() && json(&without)["female"].get("ɿ").is_some());+ let out = tmp("vowelTargets-missing-apical.json");+ std::fs::write(&out, &without).unwrap();+ chimera(&["calibrate", "vowels", "male", "--missing", "--out", &out]);+ let (was, now) = (json(&committed), json(&std::fs::read_to_string(&out).unwrap()));+ for body in ["male", "female", "child"] {+ for (ipa, entry) in was[body].as_object().unwrap() {+ if (body, ipa.as_str()) != ("male", "ɿ") {+ assert_eq!(&now[body][ipa], entry, "{body} {ipa} changed");+ }+ }+ }+ let (fit, i, old) = (&now["male"]["ɿ"]["artic"], &now["male"]["i"]["artic"], &was["male"]["ɿ"]["artic"]);+ for k in ["lipAp", "lipProt", "lipWidth"] {+ assert_eq!(fit[k], i[k], "ɿ's {k} is [i]'s");+ }+ for k in ["ttX", "ttY", "ttCurl"] {+ assert_eq!(fit[k], old[k], "ɿ's {k} is pinned");+ }+}+/// About 100 s in release. Not byte-identical: the Nelder–Mead fit runs 1 800 + 2 × 1 000/// iterations on a flat minimum, which amplifies last-ulp differences between V8's libm and Rust's/// (in the airway geometry and the transfer function) into ~1e-4 changes of the fitted posture.diff --git a/crates/chimera/src/phonetics/durations.rs b/crates/chimera/src/phonetics/durations.rsindex df993b8..1545b4d 100644--- a/crates/chimera/src/phonetics/durations.rs+++ b/crates/chimera/src/phonetics/durations.rs@@ -27,7 +27,12 @@ fn table(ipa: &str) -> Option<(f64, f64)> {"o" => (220.0, 80.0),"oʊ" => (220.0, 80.0),"ʊ" => (160.0, 60.0),+ // Mandarin's ʊ and ao (vowel_data.rs): as long as ʊ and aʊ+ "ʊ̠" => (160.0, 60.0),+ "aʊ̠" => (240.0, 100.0),"u" => (210.0, 70.0),+ // Mandarin's back u (vowel_data.rs): as long as u+ "u̠" => (210.0, 70.0),"ʌ" => (140.0, 60.0),"ə" => (120.0, 60.0),"ɚ" => (180.0, 80.0),diff --git a/crates/chimera/src/phonetics/mandarin.rs b/crates/chimera/src/phonetics/mandarin.rsindex e6ecf49..960f67b 100644--- a/crates/chimera/src/phonetics/mandarin.rs+++ b/crates/chimera/src/phonetics/mandarin.rs@@ -10,15 +10,15 @@//! turns the others second (你好 ni2 hao3).//! - Pinyin → IPA on the inventory. Stops and affricates say their aspiration, which is what//! Mandarin contrasts: b d g z zh j are unaspirated (p˭ t˭ k˭ ts˭ tʂ˭ tɕ˭), p t k c ch q aspirated.-//! - Tones → pitch bends ([`tone_bends`]): the melody stays as written, the tone colours the-//! note's start or end.+//! - Tones are read, not sung: a song follows its melody. They decide the sandhi above and the+//! neutral tone's reduced vowel, and wait for speech to be drawn as pitch.//!//! [`Pinyin`] reads Mandarin typed as pinyin instead, with no lexicon: a Latin word that carries//! tones (marks, "nǐhǎo", or numbers, "ni3 hao3") and parses as pinyin. Toneless words stay//! English.use super::syllables::FrontEnd;-use super::{Bend, Edge, Segment, Syllable};+use super::{Segment, Syllable};use std::collections::HashMap;pub fn is_han(c: char) -> bool {@@ -134,30 +134,22 @@ fn third_tones(py: &mut [String]) {}}-/// How a Mandarin tone bends its sung note (semitones from the note; see [`Bend`]): 2 scoops up-/// from below, 3 dips, 4 starts a little high and falls off the end, 1 and 5 stay on the note.-pub fn tone_bends(tone: u8) -> Vec<Bend> {- let b = |at, len, max, st| Bend { at, len, max, st };- match tone {- 2 => vec![b(Edge::Start, 0.45, 0.25, -3.5)],- // sung low from the start: a dip in the middle (Edge::Middle), or a dip then a rise (214),- // measured no better on the poems (tone 3 ~50% wrong either way, mostly heard as 4)- 3 => vec![b(Edge::Start, 0.55, 0.3, -4.0)],- 4 => vec![b(Edge::Start, 0.25, 0.12, 1.5), b(Edge::End, 0.4, 0.2, -4.0)],- _ => vec![],- }-}--/// Fraction of a vowel nasalised before -n/-ng.-const NASAL_LEAD: f64 = 0.4;+const NASAL_LEAD: f64 = 0.6;++/// A rhyme's ending (the off-glide of ai ei ao ou, a nasal coda) is one closing movement at the end+/// of the syllable, this long at most (s): Mandarin's 韵尾 is where the vowel ends up, not a second+/// sound (`Syllable::closing`).+const CLOSING: f64 = 0.2;-/// Mandarin's sung timing: nasal codas held long enough to tell -n from -ng (the place cue is in-/// the vowel's last formant movement and the murmur; at the default ~60 ms they read as one).+/// Mandarin's sung timing: a nasal coda is a short murmur at the end of a closing rhyme. The place+/// cue is in the vowel's last formant movement (the song planner moves the tongue body toward the+/// coda over the vowel's last 150 ms). Held 130 and 100 ms after a vowel that didn't move, as they+/// were, a native listener heard a second sound: 昂 as an + ng.fn coda_dur(ipa: &str) -> Option<f64> {match ipa {- "ŋ" => Some(0.13),- "n" => Some(0.10),+ "ŋ" => Some(0.08),+ "n" => Some(0.07),_ => None,}}@@ -176,8 +168,6 @@ fn onset_dur(ipa: &str, aspirated: Option<bool>) -> Option<f64> {/// Aspiration length of Mandarin's aspirated stops and affricates (s).const MANDARIN_VOT: f64 = 0.09;-/// The share of a falling diphthong's note its off-glide takes.-const OFFGLIDE: f64 = 0.35;/// An initial → its sound and, for stops and affricates, its aspiration.fn initial(i: &str) -> Option<(&'static str, Option<bool>)> {@@ -215,29 +205,29 @@ fn final_parts(f: &str) -> Option<(&'static [&'static str], &'static str, &'stat"o" => (&["w"], "ɔ", N),"e" => (N, "ɤ", N),"i" => (N, "i", N),- "u" => (N, "u", N),+ "u" => (N, "u̠", N),"v" => (N, "y", N),"er" => (N, "ɝ", N),"ai" => (N, "aɪ", N),"ei" => (N, "eɪ", N),- "ao" => (N, "aʊ", N),- "ou" => (N, "əʊ", N),+ "ao" => (N, "aʊ̠", N),+ "ou" => (N, "əʊ̠", N),"an" => (N, "a", &["n"]),"en" => (N, "ə", &["n"]),"ang" => (N, "ɑ", &["ŋ"]),"eng" => (N, "ɤ", &["ŋ"]),- "ong" => (N, "ʊ", &["ŋ"]),+ "ong" => (N, "ʊ̠", &["ŋ"]),"ia" => (&["j"], "a", N),// yo (哟 唷): an interjection's [jɔ]"io" => (&["j"], "ɔ", N),"ie" => (&["j"], "ɛ", N),- "iao" => (&["j"], "aʊ", N),- "iu" | "iou" => (&["j"], "əʊ", N),+ "iao" => (&["j"], "aʊ̠", N),+ "iu" | "iou" => (&["j"], "əʊ̠", N),"ian" => (&["j"], "ɛ", &["n"]),"in" => (N, "i", &["n"]),"iang" => (&["j"], "ɑ", &["ŋ"]),"ing" => (N, "i", &["ŋ"]),- "iong" => (&["j"], "ʊ", &["ŋ"]),+ "iong" => (&["j"], "ʊ̠", &["ŋ"]),"ua" => (&["w"], "a", N),"uo" => (&["w"], "ɔ", N),"uai" => (&["w"], "aɪ", N),@@ -298,6 +288,11 @@ pub fn pinyin_syllable(py: &str, text: &str) -> Option<Syllable> {// the apical vowels: the consonant's tongue held open (ɿ after z c s, ʅ after zh ch sh r)let apical_vowel = if matches!(ini, "z" | "c" | "s") { "ɿ" } else { "ʅ" };let (glide, mut nucleus, coda) = if apical { (&[][..], apical_vowel, &[][..]) } else { final_parts(&fin)? };+ // er is a central vowel (a, for the fourth tone: 二 is more open) moving into the r-colouring, not+ // English's /ɝ/ held still: the start is the quick on-glide, the r-coloured vowel holds the note+ if fin == "er" {+ nucleus = if t == 4 { "aɝ" } else { "əɝ" };+ }// a neutral-tone syllable's e reduces (的 de, 了 le)if t == 5 && nucleus == "ɤ" {nucleus = "ə";@@ -308,17 +303,17 @@ pub fn pinyin_syllable(py: &str, text: &str) -> Option<Syllable> {(["j"], "a") => Some("ia"),(["j"], "ɛ") => Some("iɛ"),(["j"], "ɑ") => Some("iɑ"),- (["j"], "ʊ") => Some("iʊ"),- (["w"], "a") => Some("ua"),- (["w"], "ɔ") => Some("uɔ"),- (["w"], "ɑ") => Some("uɑ"),- (["w"], "ə") => Some("uə"),+ (["j"], "ʊ̠") => Some("iʊ̠"),+ (["w"], "a") => Some("u̠a"),+ (["w"], "ɔ") => Some("u̠ɔ"),+ (["w"], "ɑ") => Some("u̠ɑ"),+ (["w"], "ə") => Some("u̠ə"),(["ɥ"], "ɛ") => Some("yɛ"),// the three-vowel finals: the glide into a falling diphthong (iao, iou, uai, uei)- (["j"], "aʊ") => Some("iaʊ"),- (["j"], "əʊ") => Some("iəʊ"),- (["w"], "aɪ") => Some("uaɪ"),- (["w"], "eɪ") => Some("ueɪ"),+ (["j"], "aʊ̠") => Some("iaʊ̠"),+ (["j"], "əʊ̠") => Some("iəʊ̠"),+ (["w"], "aɪ") => Some("u̠aɪ"),+ (["w"], "eɪ") => Some("u̠eɪ"),_ => None,};if let Some(r) = rising {@@ -342,13 +337,10 @@ pub fn pinyin_syllable(py: &str, text: &str) -> Option<Syllable> {onset,nucleus: Segment::new(nucleus),coda: coda.iter().map(|c| Segment { dur: coda_dur(c), ..Segment::new(c) }).collect(),- pitch: tone_bends(t),// vowels before -n/-ng are nasalised. (Lighter neutral tones, breath 0.7 on 的 了, sounded// more natural but made them harder to recognise in the scramble test, so they stay full.)nasal_lead: (!coda.is_empty()).then_some(NASAL_LEAD),- // ai ao ei ou (and iao iou uai uei) glide off over the note's last 35%: at the planner's- // 20% the glide was too short to hear on a long note- offglide: super::planner::offglide(nucleus).is_some().then_some(OFFGLIDE),+ closing: Some(CLOSING),..Default::default()})}@@ -380,7 +372,6 @@ fn rhotacize(s: &mut Syllable) {}s.coda = vec![Segment::new("ɻ")];s.nasal_lead = None;- s.offglide = None;}/// The Mandarin front end, over a loaded lexicon (without one it reads nothing).diff --git a/crates/chimera/src/phonetics/mod.rs b/crates/chimera/src/phonetics/mod.rsindex a4989d5..bac49df 100644--- a/crates/chimera/src/phonetics/mod.rs+++ b/crates/chimera/src/phonetics/mod.rs@@ -56,6 +56,11 @@ pub struct Segment {/// vowel said with them part-open (IPA combining diaeresis below); None or false: modal#[serde(default, skip_serializing_if = "Option::is_none")]pub breathy: Option<bool>,+ /// a vowel that is a glide off the vowel before it: reached over this long (s) while that vowel+ /// lets go over the glide's own length, so the two are one movement, not two held targets;+ /// None: a vowel of its own+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub glide: Option<f64>,}impl Segment {@@ -121,14 +126,16 @@ pub struct Syllable {/// accent, a scoop); none: the note's pitch as written#[serde(default, skip_serializing_if = "Vec::is_empty")]pub pitch: Vec<Bend>,- /// nasalise this fraction of the vowel before a nasal coda (at most 0.25 s), as Mandarin does;- /// None: the song's SongOptions::nasal_lead+ /// nasalise this fraction of the vowel before a closing rhyme's nasal coda (`closing`; at most+ /// 0.25 s), as Mandarin does; None: the velum lowers only for the nasal itself#[serde(default, skip_serializing_if = "Option::is_none")]pub nasal_lead: Option<f64>,- /// the share of a falling diphthong's held note its off-glide takes (Mandarin's ai ao ei ou glide- /// over the last 35%); None: the planner's 20%+ /// the rhyme's ending (a falling diphthong's off-glide, a nasal coda) is one closing movement at+ /// the end of the note, this long at most (s), as Mandarin's 韵尾 is: the main vowel moves into+ /// it and it is not held. None: the off-glide holds a share of the note and the coda is a+ /// consonant of its own#[serde(default, skip_serializing_if = "Option::is_none")]- pub offglide: Option<f64>,+ pub closing: Option<f64>,}/// Which end of its sung vowel a pitch bend sits at.@@ -143,7 +150,7 @@ pub enum Edge {/// A bend of the pitch inside a sung note: `st` semitones from the note, at the vowel's start or/// end, over `len` of the vowel but at most `max` seconds. The melody stays as written; a bend only-/// colours the note's start or end (Mandarin's tones, Japanese pitch accent, an English scoop).+/// colours part of the note (a scoop, a pitch accent).#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Bend {diff --git a/crates/chimera/src/phonetics/planner.rs b/crates/chimera/src/phonetics/planner.rsindex dcf4f33..4d0009f 100644--- a/crates/chimera/src/phonetics/planner.rs+++ b/crates/chimera/src/phonetics/planner.rs@@ -63,7 +63,24 @@ pub fn expand(ipa: &str) -> Option<&'static [&'static str]> {"uɑ" => &["u", "ɑ"],"uə" => &["u", "ə"],"yɛ" => &["y", "ɛ"],+ // Mandarin's er: a central (er4: open) start, the r-colouring arriving in the held vowel+ "əɝ" => &["ə", "ɝ"],+ "aɝ" => &["a", "ɝ"],"uɔ" => &["u", "ɔ"],+ // Mandarin's own back u (Zee & Lee 2001: F2 ~660, English /u/'s is ~1000) as the medial glide:+ // the same compounds with `u̠` (vowel_data.rs), beside the ones above, which stay as they were+ "u̠a" => &["u̠", "a"],+ "u̠ɔ" => &["u̠", "ɔ"],+ "u̠ɑ" => &["u̠", "ɑ"],+ "u̠ə" => &["u̠", "ə"],+ "u̠aɪ" => &["u̠", "a", "ɪ"],+ "u̠eɪ" => &["u̠", "e", "i"],+ // and Mandarin's ʊ (ong, and the off-glide of ao ou iao iou, Zee & Lee: F2 ~730 where English /ʊ/ has ~1120)+ "iʊ̠" => &["i", "ʊ̠"],+ "aʊ̠" => &["a", "ʊ̠"],+ "əʊ̠" => &["ə", "ʊ̠"],+ "iaʊ̠" => &["i", "a", "ʊ̠"],+ "iəʊ̠" => &["i", "ə", "ʊ̠"],// a central start, Mandarin's ou ([əʊ], where English [oʊ] starts nearly at [u])"əʊ" => &["ə", "ʊ"],// triphthongs: a glide into a falling diphthong (Mandarin iao, iou, uai, uei)@@ -77,7 +94,7 @@ pub fn expand(ipa: &str) -> Option<&'static [&'static str]> {/// A rising nucleus (a rising diphthong or a triphthong): its first part is a short glide.pub fn is_rising(ipa: &str) -> bool {- matches!(ipa, "ia" | "iɛ" | "iɑ" | "iʊ" | "ua" | "uo" | "uɑ" | "uə" | "yɛ" | "uɔ" | "iaʊ" | "iəʊ" | "uaɪ" | "ueɪ")+ matches!(ipa, "ia" | "iɛ" | "iɑ" | "iʊ" | "ua" | "uo" | "uɑ" | "uə" | "yɛ" | "uɔ" | "əɝ" | "aɝ" | "iaʊ" | "iəʊ" | "uaɪ" | "ueɪ" | "u̠a" | "u̠ɔ" | "u̠ɑ" | "u̠ə" | "u̠aɪ" | "u̠eɪ" | "iʊ̠" | "iaʊ̠" | "iəʊ̠")}/// A rising nucleus's on-glide (its first part), sung short at the note's start.@@ -143,8 +160,10 @@ fn preset_vowel_artic(ipa: &str, body: BodyName) -> Option<ArticPatch> {}}// a rhotic's tip is raised and curled back, not resting behind the teeth: without its- // calibrated position the tip stayed down and /ɝ/'s F3 sat ~15–20 % high (weakly rhotic)- if v.artic.get(ArticKey::TtCurl).unwrap_or(0.0) > 0.05 {+ // calibrated position the tip stayed down and /ɝ/'s F3 sat ~15–20 % high (weakly rhotic). The+ // apical vowels are made with the tongue tip, at the place of the sibilant before them (ʅ+ // curled, ɿ not): their tip is part of the vowel too+ if v.artic.get(ArticKey::TtCurl).unwrap_or(0.0) > 0.05 || ipa == "ɿ" {if let Some(x) = v.artic.get(ArticKey::TtX) {out.set(ArticKey::TtX, x);}@@ -223,6 +242,8 @@ struct Seg<'a> {nasalized: Option<bool>,palatalized: Option<bool>,breathy: Option<bool>,+ /// a glide off the vowel before it, reached over this long (s): see `Segment::glide`+ glide: Option<f64>,}/// glottal abduction of breathy voice: /ɦ/'s, a gap the folds still vibrate across@@ -294,10 +315,10 @@ pub fn plan_utterance(input: &[Segment], o: &PlanOptions) -> Plan {};for (i, p) in parts.iter().enumerate() {let dur = base * shares.get(i).copied().unwrap_or(1.0);- segs.push(Seg { ipa: p, dur: Some(dur), stress: s.stress, f0: s.f0, def: None, vowel: None, glide_from: i > 0, aspirated: None, vot: None, nasalized: s.nasalized, palatalized: None, breathy: s.breathy });+ segs.push(Seg { ipa: p, dur: Some(dur), stress: s.stress, f0: s.f0, def: None, vowel: None, glide_from: i > 0, aspirated: None, vot: None, nasalized: s.nasalized, palatalized: None, breathy: s.breathy, glide: None });}} else {- segs.push(Seg { ipa: &s.ipa, dur: Some(durs[si]), stress: s.stress, f0: s.f0, def: None, vowel: None, glide_from: false, aspirated: s.aspirated, vot: s.vot, nasalized: s.nasalized, palatalized: s.palatalized, breathy: s.breathy });+ segs.push(Seg { ipa: &s.ipa, dur: Some(durs[si]), stress: s.stress, f0: s.f0, def: None, vowel: None, glide_from: false, aspirated: s.aspirated, vot: s.vot, nasalized: s.nasalized, palatalized: s.palatalized, breathy: s.breathy, glide: s.glide });}}for s in segs.iter_mut() {@@ -340,8 +361,17 @@ pub fn plan_utterance(input: &[Segment], o: &PlanOptions) -> Plan {// 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- let r_in = js_max(0.03, 0.75 * (times[i].t0 - prev)) + 0.01;- let r_out = js_max(0.03, 0.4 * (next - times[i].t1)) + 0.01;+ let mut r_in = js_max(0.03, 0.75 * (times[i].t0 - prev)) + 0.01;+ let mut r_out = js_max(0.03, 0.4 * (next - times[i].t1)) + 0.01;+ // a glide off the vowel right before it (`Segment::glide`): it comes in over its given time+ // and that vowel lets go over the glide's own length, so the tongue is on its way from the+ // start of the one ramp to the end of the other and holds neither target in between+ if let Some(g) = segs[i].glide.filter(|_| i > 0 && segs[i - 1].vowel.is_some()) {+ r_in = js_max(0.01, g);+ }+ if i + 1 < segs.len() && segs[i + 1].vowel.is_some() && segs[i + 1].glide.is_some() {+ r_out = js_max(0.01, times[i + 1].t1 - times[i + 1].t0);+ }gestures.push(Gesture::new(times[i].t0, times[i].t1, r_in, r_out, 1.0, artic_targets(segs[i].vowel.as_ref().unwrap())).label(segs[i].ipa));}// utterance-initial/final consonants: lend them the nearest vowel's body posturediff --git a/crates/chimera/src/phonetics/sing.rs b/crates/chimera/src/phonetics/sing.rsindex ff6a3db..8ff54f7 100644--- a/crates/chimera/src/phonetics/sing.rs+++ b/crates/chimera/src/phonetics/sing.rs@@ -1,7 +1,10 @@//! Singing: syllables on notes, through the same gestural planner as speech.//! - A note's vowel lands on the beat. Its onset consonants are sung just before it (they take//! their time from the previous note, as singers do), its coda just before the next onset.-//! - Diphthongs sustain their first vowel and glide to the second at the end of the note.+//! - Diphthongs sustain their first vowel and glide to the second at the end of the note. A rising+//! one's medial glide is sung with the onset, so the main vowel holds from the beat.+//! - A closing rhyme (`Syllable::closing`, Mandarin's) ends in one movement: its off-glide or its+//! nasal coda is where the vowel ends up at the end of the note, not a part held after it.//! - A melisma ("-") carries the vowel onto further notes; the coda waits for the last of them.//! - Vibrato blooms a quarter of a second into a held vowel.//!@@ -13,7 +16,7 @@use super::inventory::phoneme;use crate::anatomy::human::{ArticKey, BodyMix};-use super::planner::{PlanOptions, held_vowel, offglide, onglide, plan_utterance};+use super::planner::{PlanOptions, held_vowel, offglide, onglide, plan_utterance, vowel_artic};use super::{Bend, Edge, Intonation, Plan, PlannedSegment, Segment, Syllable};use crate::control::score::{ControlKey, Gesture, Targets};use crate::math::{js_max, js_min};@@ -50,12 +53,39 @@ fn consonants_at(segs: &[Segment], body: BodyMix, k: f64, hz: f64) -> Vec<Segmenout}-/// a rising diphthong's glide lasts a quarter of its vowel, at most this long (s)-const RISING_GLIDE: f64 = 0.12;/// A falling diphthong (or a triphthong) glides off over this share of its held part, unless its-/// syllable says (Syllable::offglide).+/// syllable's rhyme is closing (Syllable::closing).const OFFGLIDE: f64 = 0.2;+/// A rising nucleus's medial glide is sung as the last part of the note's onset, this long (s): a+/// quick transition that ends on the beat, co-produced with the initial consonant (the lips round+/// or the tongue fronts while the consonant is made), and the main vowel carries the beat. Sung on+/// the beat as a vowel of its own (up to 120 ms, a quarter of the vowel) it was a plateau: the jaw+/// and tongue sat at the glide's posture for 80-100 ms and the main vowel was 90% reached 200 ms+/// after the beat, and listening diagnoses of the renders heard 两 as li-ang, 快 as ku-ai (language+/// models, asked after a native speaker called the singing a foreigner's). As an onset consonant+/// before the consonants (the design before that) the glide was lost to the recogniser (话 hua+/// toward 哈 ha); it follows the initial, so it keeps its own time, and is a vowel segment, so it+/// takes the Öhman coarticulation of a vowel rather than a consonant's constriction.+const MEDIAL_GLIDE: f64 = 0.05;++/// A closing rhyme (`Syllable::closing`, Mandarin's) ends in one movement, over at most this share+/// of the vowel: on a short note the main vowel keeps the rest, on a long one the movement is as+/// long as the front end says and the vowel holds until then. Before, the ending was a part of its+/// own: 奥 ao sung for 1.3 s was [a] still for 0.76 s, a jump in 80 ms, then [ʊ] still for 0.35 s,+/// and 昂 ang was an oral [ɑ], a 40 ms jump of the tongue body, then 0.4 s of murmur: a native+/// listener heard two sounds (a-u, an-ng) where Mandarin has one.+const CLOSING_SHARE: f64 = 0.6;+/// In a closing rhyme the tongue body is this far on its way to a velar coda when the coda closes+/// (its strength against the vowel's 1.0: 1.2 is 55 % of the way), over this long at most (s). The+/// dorsum is slow, so -ng is heard in the vowel's last 150 ms before the closure.+const CLOSING_VELAR: f64 = 1.2;+const CLOSING_APPROACH_MAX: f64 = 0.15;+/// And toward an alveolar coda the tongue body fronts and rises (the body posture of an alveolar+/// closure, as `oral_gestures` holds it during one), 0.6: 37 % of the way. This is what tells -n+/// from -ng before the closure: 安 an's vowel ends fronted ([aɛ̃n], F2 rising), 昂 ang's backed.+const CLOSING_ALVEOLAR: f64 = 0.6;+/// a sung vowel keeps at least this long when a short note squeezes its consonants (s)const MIN_VOWEL: f64 = 0.05;/// a squeezed consonant keeps at least this long (s); a flap is 16 ms@@ -153,9 +183,13 @@ pub fn plan_song(notes: &[SungNote], o: &SongOptions) -> Plan {}let mut segs: Vec<Segment> = Vec::new();let mut vowel_spans: Vec<(f64, f64)> = Vec::new();- // (note, vowel start, vowel end) of syllables with bends, and of vowels before a nasal coda+ // (note, vowel start, vowel end) of syllables with bendslet mut bend_spans: Vec<(usize, f64, f64)> = Vec::new();- let mut nasal_spans: Vec<(f64, f64, f64, &str)> = Vec::new();+ // (vowel start, vowel end, fraction nasalised, the tongue body's approach to the coda) of+ // closing rhymes+ let mut closing_spans: Vec<(f64, f64, f64, Option<(f64, Targets)>)> = Vec::new();+ // a closing rhyme's nasal coda that ends the phrase: (its end, the closure it holds)+ let mut final_coda: Option<(f64, Targets)> = None;// each note's onset and coda consonants, at the note's pitch (a coda at the pitch of the// note whose syllable it ends; a melisma has neither)let hz_of = |k: usize| midi_to_hz(notes[k].midi);@@ -165,7 +199,19 @@ pub fn plan_song(notes: &[SungNote], o: &SongOptions) -> Plan {let start = notes[k].syl.pitch.iter().find(|b| b.at == Edge::Start).map_or(0.0, |b| b.st);hz_of(k) * crate::math::pow(2.0, start / 12.0)};- let mut onsets: Vec<Vec<Segment>> = (i..=j).map(|k| if melisma(¬es[k].syl) { Vec::new() } else { consonants_at(¬es[k].syl.onset, o.body, 0.8, onset_hz(k)) }).collect();+ let mut onsets: Vec<Vec<Segment>> = (i..=j)+ .map(|k| {+ if melisma(¬es[k].syl) {+ return Vec::new();+ }+ let mut on = consonants_at(¬es[k].syl.onset, o.body, 0.8, onset_hz(k));+ // a rising nucleus's medial glide ends the onset, so it is done by the beat+ if let Some(a) = onglide(¬es[k].syl.nucleus.ipa) {+ on.push(nucleus_part(a, MEDIAL_GLIDE, onset_hz(k), ¬es[k].syl.nucleus));+ }+ on+ })+ .collect();let mut codas: Vec<Vec<Segment>> = (i..=j).map(|k| if k < j && melisma(¬es[k + 1].syl) { Vec::new() } else { consonants_at(&last_of_chain(notes, k).coda, o.body, 0.8, hz_of(k)) }).collect();@@ -174,6 +220,17 @@ pub fn plan_song(notes: &[SungNote], o: &SongOptions) -> Plan {// the rest: hold that note to its end, less the breath's release.let reserve = if j == notes.len() - 1 { 0.05 } else { 0.12 };let last_end = times[j] + notes[j].beats * beat - js_min(reserve, 0.3 * notes[j].beats * beat);+ // how long past the phrase's end its last sound may be held while the voice fades (a nasal+ // coda's closure): until the voice is gone, but when another phrase+ // follows in this call, only until 50 ms (the hold's release) before that phrase's first+ // consonant, so the hold is out of its way+ let fade = if j + 1 < notes.len() {+ let next = ¬es[j + 1].syl;+ let onset = total(&consonants(&next.onset, o.body, 0.8)) + if onglide(&next.nucleus.ipa).is_some() { MEDIAL_GLIDE } else { 0.0 };+ js_min(0.15, js_max(0.0, times[j + 1] - onset - 0.05 - last_end))+ } else {+ 0.15+ };for k in i..=j {let (span, next) = if k < j { (times[k + 1] - times[k], &mut onsets[k + 1 - i][..]) } else { (last_end - times[k], &mut [][..]) };fit([&mut codas[k - i][..], next], span);@@ -190,33 +247,35 @@ pub fn plan_song(notes: &[SungNote], o: &SongOptions) -> Plan {// only consonants squeezed to their floor can leave less than MIN_VOWELlet vdur = js_max(0.02, note_end - times[k] - total(&coda));segs.extend(onset);- // the nucleus in time: a rising on-glide short on the beat (not on a melisma's later- // notes), the vowel that holds, and a falling off-glide in the note's last fifth (not+ // the nucleus in time: the vowel that holds from the beat (a rising nucleus's glide+ // came with the onset), and a falling off-glide over the held part's last share (not// when a melisma continues the vowel)let nuc = n.syl.nucleus.ipa.as_str();- let on = onglide(nuc).filter(|_| !melisma(&n.syl));- let g = if on.is_some() { js_min(0.25 * vdur, RISING_GLIDE) } else { 0.0 };- if let Some(a) = on {- segs.push(nucleus_part(a, g, hz, &n.syl.nucleus));- }- let rest = vdur - g;- // a falling diphthong glides off over this share of its held part (the front end may say)- let glide_off = n.syl.offglide.unwrap_or(OFFGLIDE);- match offglide(nuc).filter(|_| !next_melisma) {- Some(b) => {- segs.push(nucleus_part(held_vowel(nuc), rest * (1.0 - glide_off), hz, &n.syl.nucleus));- segs.push(nucleus_part(b, rest * glide_off, hz, &n.syl.nucleus));+ let rest = vdur;+ // the syllable whose rhyme this is decides (a melisma's ending is its parent's)+ let closing = last_of_chain(notes, k).closing.filter(|c| *c > 0.0);+ match (offglide(nuc).filter(|_| !next_melisma), closing) {+ // a closing rhyme: the vowel moves into the off-glide over the note's end and the+ // glide is not held (half the movement is the glide coming in, half the vowel letting go)+ (Some(b), Some(c)) => {+ let half = 0.5 * js_min(c, CLOSING_SHARE * rest);+ segs.push(nucleus_part(held_vowel(nuc), rest - half, hz, &n.syl.nucleus));+ segs.push(Segment { glide: Some(half), ..nucleus_part(b, half, hz, &n.syl.nucleus) });+ }+ (Some(b), None) => {+ segs.push(nucleus_part(held_vowel(nuc), rest * (1.0 - OFFGLIDE), hz, &n.syl.nucleus));+ segs.push(nucleus_part(b, rest * OFFGLIDE, hz, &n.syl.nucleus));}- None => segs.push(nucleus_part(held_vowel(nuc), rest, hz, &n.syl.nucleus)),+ (None, _) => segs.push(nucleus_part(held_vowel(nuc), rest, hz, &n.syl.nucleus)),}if coda.first().is_some_and(|c| matches!(c.ipa.as_str(), "m" | "n" | "ŋ")) {// the syllable whose coda this is decides (a melisma's coda is its parent's)let lead = last_of_chain(notes, k).nasal_lead.unwrap_or(0.0);- if lead > 0.0 {- // the tongue body's rise toward -ng after the back vowel ɑ (ang, iang, uang); after- // other vowels, and toward -n, it measured no better or worse- let place = if coda[0].ipa == "ŋ" && held_vowel(nuc) == "ɑ" { "velar" } else { "" };- nasal_spans.push((times[k], times[k] + vdur, lead, place));+ if closing.is_some() {+ closing_spans.push((times[k], times[k] + vdur, lead, coda_approach(&coda[0].ipa, held_vowel(nuc), o.body)));+ if k == j && coda.len() == 1 {+ final_coda = closure(&coda[0].ipa, o.body).map(|t| (times[k] + vdur + total(&coda), t));+ }}}segs.extend(coda);@@ -234,20 +293,32 @@ pub fn plan_song(notes: &[SungNote], o: &SongOptions) -> Plan {for &(k, a, b) in &bend_spans {bend_gestures(¬es[k].syl.pitch, hz_of(k), a, b, &mut gestures);}- for &(a, b, lead, place) in &nasal_spans {- let t0 = b - js_min(lead * (b - a), 0.25);- gestures.push(Gesture::new(t0, b + 0.02, 0.06, 0.03, 4.0, Targets::default().with(ArticKey::Velum, 0.3)).label("nasal vowel"));- // and the tongue on its way to the coda's place, which is where -n and -ng differ- // in the vowel: the body rising toward the velum for -ng, the tip toward the ridge- // for -n (short of closure; the coda closes)- let approach = match place {- "velar" => Some(Targets::default().with(ArticKey::TbY, 7.95)),- "alveolar" => Some(Targets::default().with(ArticKey::TtX, 6.2).with(ArticKey::TtY, 9.3)),- _ => None,- };- if let Some(t) = approach {- gestures.push(Gesture::new(t0, b + 0.02, 0.06, 0.03, 2.5, t).label("coda approach"));+ // a closing rhyme's nasal coda: the velum comes down gradually over the nasalised part of+ // the vowel (strength 2 follows the ramp itself, see Articulators) instead of dropping+ // at its start, and the tongue body is on its way to a velar coda before it closes+ for (a, b, lead, approach) in closing_spans {+ let len = js_min(lead * (b - a), 0.25);+ if len > 0.0 {+ // open before the coda's closure starts (~55 ms ahead of b): a close vowel that+ // closed first was a stop for a moment (东 dong dipped 9 dB before its -ng)+ gestures.push(Gesture::new(b - 0.06, b + 0.02, len, 0.03, 2.0, Targets::default().with(ArticKey::Velum, 0.3)).label("nasal vowel"));}+ if let Some((pull, t)) = approach {+ let len = js_min(CLOSING_APPROACH_MAX, 0.5 * (b - a));+ gestures.push(Gesture::new(b - 0.01, b + 0.02, len, 0.03, pull, t).label("coda approach"));+ }+ }+ // and at the end of a phrase it stays closed, the velum open, until the voice has faded:+ // the closure used to let go as the breath stopped, a short vowel after the nasal+ // (安 an ended [an-ə], a 3.5 dB bump)+ if let Some((t, hold)) = final_coda {+ // (the velum stays down past the tongue's release, so no pressure is left to pop. The+ // release itself still measures -29 dB re the vowel, 0.2 s after the voice ends.)+ // Before another phrase the hold is only as long as `fade` and lets go quickly.+ let alone = j + 1 >= notes.len();+ let (held, release, velum) = if alone { (0.1, 0.12, 0.25) } else { (js_min(0.1, fade), 0.05, js_min(0.1, fade)) };+ gestures.push(Gesture::new(t - 0.03, t + held, 0.02, release, 40.0, hold).label("coda held"));+ gestures.push(Gesture::new(t - 0.03, t + velum, 0.02, 0.05, 4.0, Targets::default().with(ArticKey::Velum, 0.45)).label("velum"));}for (a, b) in vowel_spans {if b - a > 0.3 {@@ -261,6 +332,43 @@ pub fn plan_song(notes: &[SungNote], o: &SongOptions) -> Plan {Plan { gestures, segments, end }}+/// Where the tongue body heads in a closing rhyme's vowel before its nasal coda closes, and how+/// strongly against the vowel (see [`CLOSING_VELAR`], [`CLOSING_ALVEOLAR`]).+fn coda_approach(coda: &str, vowel: &str, body: BodyMix) -> Option<(f64, Targets)> {+ let v = vowel_artic(vowel, body);+ let at = |k: ArticKey| v.as_ref().and_then(|v| v.get(k));+ match coda {+ "ŋ" => {+ let mut t = Targets::default();+ // up toward the velum, unless the vowel's body is already close under it (ong, ing:+ // any higher and the vowel itself is choked off before the coda)+ let rise = at(ArticKey::TbY).is_none_or(|y| y < 6.95);+ if rise {+ t = t.with(ArticKey::TbY, 7.95);+ }+ // and back to the velar closure's place from a front vowel (英 ying [iə̃ŋ]: before, the+ // tongue closed where [i] was and slid back inside the murmur)+ let back = at(ArticKey::TbX).is_some_and(|x| x > 3.0);+ if back {+ t = t.with(ArticKey::TbX, 2.83);+ }+ (rise || back).then_some((CLOSING_VELAR, t))+ }+ "n" => Some((CLOSING_ALVEOLAR, Targets::default().with(ArticKey::TbX, 3.2).with(ArticKey::TbY, 7.4))),+ _ => None,+ }+}++/// A consonant's own closure: the targets of the articulators that make it.+fn closure(ipa: &str, body: BodyMix) -> Option<Targets> {+ let def = phoneme(ipa, body)?;+ let mut t = Targets::default();+ for (k, v) in def.targets.iter().filter(|(k, _)| def.dominant.contains(k)) {+ t = t.with(k, v);+ }+ Some(t)+}+/// The syllable whose coda ends a melisma chain starting at note k.fn last_of_chain(notes: &[SungNote], k: usize) -> &Syllable {let mut b = k;@@ -304,7 +412,7 @@ pub fn plan_note_on(syl: &Syllable, midi: f64, o: &NoteOnOptions) -> Vec<Gesture}segs.extend(consonants(&syl.onset, o.body, 0.7));if let Some(a) = onglide(&syl.nucleus.ipa) {- segs.push(nucleus_part(a, RISING_GLIDE * 0.6, hz, &syl.nucleus));+ segs.push(nucleus_part(a, MEDIAL_GLIDE, hz, &syl.nucleus));}segs.push(nucleus_part(held_vowel(&syl.nucleus.ipa), HOLD, hz, &syl.nucleus));let plan = plan_utterance(&segs, &PlanOptions { body: o.body, t0: LIVE_T0, f0: Some(hz), intonation: Some(Intonation::Flat), open_end: Some(true), ..Default::default() });diff --git a/crates/chimera/src/phonetics/vowelTargets.generated.json b/crates/chimera/src/phonetics/vowelTargets.generated.jsonindex 3e0c0a4..a3b2eba 100644--- a/crates/chimera/src/phonetics/vowelTargets.generated.json+++ b/crates/chimera/src/phonetics/vowelTargets.generated.json@@ -684,23 +684,23 @@},"ɿ": {"artic": {- "tbX": 2.851,- "tbY": 7.604,- "jaw": 0.191,- "lipAp": 0.151,- "lipProt": 0.327,- "lipWidth": 0.55,- "root": 0.871,- "larynx": 0.313,- "ttX": 6.373,- "ttY": 7.441,+ "tbX": 2.348,+ "tbY": 7.392,+ "jaw": 0.365,+ "lipAp": 1.046,+ "lipProt": 0,+ "lipWidth": 1,+ "root": 0.9,+ "larynx": 0.32,+ "ttX": 6.3,+ "ttY": 9.001,"ttCurl": 0},"formants": [- 360,- 1401,- 2309,- 3762+ 363,+ 1447,+ 2321,+ 3679],"target": [360,@@ -708,30 +708,30 @@2600],"err": [- -0.1,- 0.1,- -11.2+ 1,+ 3.4,+ -10.7]},"ʅ": {"artic": {- "tbX": 2.778,- "tbY": 7.554,- "jaw": 0.302,- "lipAp": 0.23,- "lipProt": 0.35,+ "tbX": 2.047,+ "tbY": 7.244,+ "jaw": 0.545,+ "lipAp": 1.046,+ "lipProt": 0,"lipWidth": 1,- "root": -0.531,- "larynx": -0.177,- "ttX": 6.313,- "ttY": 7.323,- "ttCurl": 0+ "root": -0.9,+ "larynx": -0.916,+ "ttX": 5.45,+ "ttY": 9.62,+ "ttCurl": 0.9},"formants": [- 399,- 1500,- 2019,- 3767+ 406,+ 1599,+ 2085,+ 2717],"target": [400,@@ -739,9 +739,71 @@2000],"err": [- -0.2,- 0,- 1+ 1.4,+ 6.6,+ 4.2+ ]+ },+ "u̠": {+ "artic": {+ "tbX": 1.2,+ "tbY": 6.091,+ "jaw": 0.05,+ "lipAp": 0.151,+ "lipProt": 1.4,+ "lipWidth": 0,+ "root": 0.674,+ "larynx": -0.183,+ "ttX": 5.924,+ "ttY": 7.039,+ "ttCurl": 0+ },+ "formants": [+ 383,+ 649,+ 2482,+ 3854+ ],+ "target": [+ 345,+ 661,+ 2783+ ],+ "err": [+ 11.1,+ -1.9,+ -10.8+ ]+ },+ "ʊ̠": {+ "artic": {+ "tbX": 1.877,+ "tbY": 7.18,+ "jaw": 1.175,+ "lipAp": 0.12,+ "lipProt": 1.4,+ "lipWidth": 0.055,+ "root": 0.654,+ "larynx": 1.151,+ "ttX": 5.704,+ "ttY": 6.422,+ "ttCurl": 0+ },+ "formants": [+ 422,+ 765,+ 2345,+ 3826+ ],+ "target": [+ 441,+ 730,+ 2881+ ],+ "err": [+ -4.4,+ 4.8,+ -18.6]}},@@ -1428,22 +1490,22 @@},"ɿ": {"artic": {- "tbX": 2.843,- "tbY": 7.651,- "jaw": 0.194,- "lipAp": 0.301,- "lipProt": 0.35,- "lipWidth": 0.628,- "root": 0.62,- "larynx": 0.561,- "ttX": 6.369,- "ttY": 7.454,+ "tbX": 2.46,+ "tbY": 7.472,+ "jaw": 0.405,+ "lipAp": 1.092,+ "lipProt": 0,+ "lipWidth": 1,+ "root": 0.413,+ "larynx": 0.319,+ "ttX": 6.3,+ "ttY": 9.007,"ttCurl": 0},"formants": [- 421,- 1681,- 2785+ 418,+ 1708,+ 2757],"target": [421,@@ -1451,30 +1513,30 @@2990],"err": [- -0.2,- 0.1,- -6.9+ -0.7,+ 1.7,+ -7.8]},"ʅ": {"artic": {- "tbX": 2.681,- "tbY": 7.528,- "jaw": 0.557,- "lipAp": 0.419,- "lipProt": 0.351,- "lipWidth": 0.939,- "root": -0.891,- "larynx": -0.291,- "ttX": 5.835,- "ttY": 8.866,- "ttCurl": 0.89+ "tbX": 1.874,+ "tbY": 7.25,+ "jaw": 0.469,+ "lipAp": 1.092,+ "lipProt": 0,+ "lipWidth": 1,+ "root": -0.9,+ "larynx": -0.624,+ "ttX": 5.45,+ "ttY": 9.628,+ "ttCurl": 0.9},"formants": [- 466,- 1799,- 2326,- 3644+ 461,+ 1868,+ 2360,+ 3008],"target": [468,@@ -1482,9 +1544,71 @@2300],"err": [- -0.3,- -0.1,- 1.1+ -1.4,+ 3.8,+ 2.6+ ]+ },+ "u̠": {+ "artic": {+ "tbX": 1.2,+ "tbY": 5.149,+ "jaw": 0.05,+ "lipAp": 0.144,+ "lipProt": 1.4,+ "lipWidth": 0,+ "root": 0.692,+ "larynx": -0.437,+ "ttX": 5.924,+ "ttY": 6.709,+ "ttCurl": 0+ },+ "formants": [+ 366,+ 776,+ 2841,+ 4570+ ],+ "target": [+ 345,+ 759,+ 3309+ ],+ "err": [+ 6,+ 2.3,+ -14.1+ ]+ },+ "ʊ̠": {+ "artic": {+ "tbX": 1.947,+ "tbY": 7.25,+ "jaw": 1.002,+ "lipAp": 0.139,+ "lipProt": 1.4,+ "lipWidth": 0.311,+ "root": 0.42,+ "larynx": 1.259,+ "ttX": 5.798,+ "ttY": 6.597,+ "ttCurl": 0+ },+ "formants": [+ 513,+ 972,+ 2859,+ 4210+ ],+ "target": [+ 533,+ 945,+ 3314+ ],+ "err": [+ -3.8,+ 2.9,+ -13.7]}},@@ -2152,22 +2276,22 @@},"ɿ": {"artic": {- "tbX": 2.909,- "tbY": 7.768,- "jaw": 0.194,- "lipAp": 0.141,- "lipProt": 0.35,- "lipWidth": 0.549,- "root": -0.314,- "larynx": -0.165,- "ttX": 6.389,- "ttY": 7.496,+ "tbX": 2.38,+ "tbY": 7.589,+ "jaw": 0.205,+ "lipAp": 0.386,+ "lipProt": 0.004,+ "lipWidth": 0.655,+ "root": -0.452,+ "larynx": -0.078,+ "ttX": 6.3,+ "ttY": 9.016,"ttCurl": 0},"formants": [- 468,- 1862,- 3280+ 464,+ 1886,+ 3263],"target": [468,@@ -2175,29 +2299,30 @@3224],"err": [- -0.1,- 0,- 1.8+ -0.8,+ 1.3,+ 1.2]},"ʅ": {"artic": {- "tbX": 2.243,- "tbY": 7.515,- "jaw": 0.411,- "lipAp": 0.591,- "lipProt": 0,- "lipWidth": 0.549,- "root": -0.9,- "larynx": -1.27,- "ttX": 5.785,- "ttY": 8.853,- "ttCurl": 0.821+ "tbX": 1.97,+ "tbY": 6.918,+ "jaw": 0.889,+ "lipAp": 0.386,+ "lipProt": 0.004,+ "lipWidth": 0.655,+ "root": 0.9,+ "larynx": -0.718,+ "ttX": 5.45,+ "ttY": 9.64,+ "ttCurl": 0.9},"formants": [- 518,- 1992,- 2648+ 528,+ 2084,+ 2649,+ 4023],"target": [520,@@ -2205,10 +2330,70 @@2480],"err": [- -0.3,- -0.1,+ 1.5,+ 4.5,6.8]+ },+ "u̠": {+ "artic": {+ "tbX": 2.04,+ "tbY": 7.402,+ "jaw": 1.395,+ "lipAp": 0.12,+ "lipProt": 1.4,+ "lipWidth": 0,+ "root": 0.9,+ "larynx": -0.306,+ "ttX": 5.657,+ "ttY": 6.311,+ "ttCurl": 0+ },+ "formants": [+ 465,+ 942,+ 3344+ ],+ "target": [+ 449,+ 879,+ 3451+ ],+ "err": [+ 3.7,+ 7.2,+ -3.1+ ]+ },+ "ʊ̠": {+ "artic": {+ "tbX": 1.716,+ "tbY": 7.262,+ "jaw": 1.055,+ "lipAp": 0.12,+ "lipProt": 1.4,+ "lipWidth": 0.134,+ "root": 0.203,+ "larynx": 0.416,+ "ttX": 5.706,+ "ttY": 6.554,+ "ttCurl": 0+ },+ "formants": [+ 555,+ 1004,+ 3360+ ],+ "target": [+ 573,+ 971,+ 3572+ ],+ "err": [+ -3.1,+ 3.4,+ -5.9+ ]}}}\ No newline at end of filediff --git a/crates/chimera/src/phonetics/vowel_data.rs b/crates/chimera/src/phonetics/vowel_data.rsindex b94e734..ada3454 100644--- a/crates/chimera/src/phonetics/vowel_data.rs+++ b/crates/chimera/src/phonetics/vowel_data.rs@@ -67,4 +67,21 @@ pub static VOWELS: &[VowelRef] = &[// consonant's tongue held open; the retroflex one has a low F3 (approximate male means)vref("ɿ", "Mandarin si (apical)", [360.0, 1400.0, 2600.0], None, None, false, 0.0, 0.45),vref("ʅ", "Mandarin shi (apical, retroflex)", [400.0, 1500.0, 2000.0], None, None, false, 0.05, 0.55),+ // Mandarin's own vowels, measured on Beijing speakers (Zee & Lee 2001, doi 10.21437/Eurospeech.2001-169:+ // 10 men and 10 women, 5 repetitions, LPC at the vowel's midpoint; female values are theirs, the child's+ // are the male's scaled by the file's factor). The English vowels of the same name are not Mandarin's:+ // American /u/ "who'd" has F2 ~1000 Hz, Mandarin's 661. The key is the English symbol plus U+0320+ // (retracted), so these entries cannot collide with, or be reached by typing, the English ones.+ // u̠ achieves (F1 / F2 / F3 Hz, target in brackets): male 383 / 649 / 2482 (345 / 661 / 2783), female 366 / 776 / 2841+ // (345 / 759 / 3309), child 465 / 942 / 3344 (449 / 879 / 3451). F2, what makes it not English /u/, is within+ // 2-3 % for the adults; F1 is +11 % male and +6 % female because the tube cannot go lower: male tbX, jaw and+ // lip width are at their lower bounds (1.2, 0.05, 0) and lip protrusion at its upper (1.4). The female+ // fit starts from the male solution (calibrate.rs `start_from`; from the generic guess it settled at+ // jaw 1.8, F2 +11 %). The child's F2 is +7 %.+ vref("u̠", "Mandarin wu, hu (back u)", [345.0, 661.0, 2783.0], Some([345.0, 759.0, 3309.0]), None, true, 0.0, 1.0),+ // ʊ̠ is the vowel of ong / iong and the off-glide of ao ou iao iou (the table's "u before ŋ": Zee & Lee's+ // men 441 / 730 / 2881, women 533 / 945 / 3314; English /ʊ/ "hood" has F2 1122 / 1225). It achieves+ // (F1 / F2 / F3 Hz): male 422 / 765 / 2345, female 513 / 972 / 2859, child 555 / 1004 / 3360: F1 and F2 within+ // 5 % on every body (F3, weighted least in the fit, -14 to -19 % for the adults).+ vref("ʊ̠", "Mandarin ong (back ʊ)", [441.0, 730.0, 2881.0], Some([533.0, 945.0, 3314.0]), None, true, 0.2, 1.0),];diff --git a/crates/chimera/tests/apical.rs b/crates/chimera/tests/apical.rsnew file mode 100644index 0000000..ed34c65--- /dev/null+++ b/crates/chimera/tests/apical.rs@@ -0,0 +1,107 @@+//! The apical vowels (ɿ in 资 词 思, ʅ in 只 吃 师 日) are the consonant's own tongue-tip+//! constriction, held open and voiced, with the lips spread: the tongue tip hardly moves from the+//! consonant into the vowel. They were once fitted to their formants alone, which the calibration+//! did with narrowed lips and a backed tongue body and no tip at all (ʅ: lipAp 0.23, tip at rest),+//! and listening diagnoses of the renders (language models) heard 只 as zhu, zhe or zhi.+use chimera::anatomy::human::{ArticKey, BODY_CHILD, BODY_FEMALE, BODY_MALE, HumanBody};+use chimera::phonetics::inventory::phoneme;+use chimera::phonetics::mandarin::pinyin_syllable;+use chimera::phonetics::planner::vowel_table;+use chimera::phonetics::sing::{SongOptions, SungNote, plan_song};+use chimera::voice::human_voice::{HumanVoice, SourcePatch, oversample_for};++const BODIES: [(&str, HumanBody); 3] = [("male", BODY_MALE), ("female", BODY_FEMALE), ("child", BODY_CHILD)];++#[test]+fn the_table_has_spread_lips_and_the_tip_of_the_consonant() {+ let t = vowel_table();+ for (name, _) in BODIES {+ let i = &t[name]["i"].artic;+ for (v, cons, curled) in [("ɿ", "s", false), ("ʅ", "ʂ", true)] {+ let a = &t[name][v].artic;+ let c = phoneme(cons, name.into()).unwrap().targets;+ let g = |p: &chimera::anatomy::human::ArticPatch, k| p.get(k).unwrap();+ // lips as for [i]: spread, not protruded, not narrowed (they were 0.23 aperture, 0.35 protrusion)+ assert!(g(a, ArticKey::LipProt) <= 0.01, "{name} {v}: lips protruded");+ assert!(g(a, ArticKey::LipWidth) >= g(i, ArticKey::LipWidth) - 1e-9, "{name} {v}: lips not spread");+ assert!(g(a, ArticKey::LipAp) >= g(i, ArticKey::LipAp) - 1e-9, "{name} {v}: lips narrowed");+ // the tip where the sibilant before it puts it, the constriction opened by 0.11+ assert!((g(a, ArticKey::TtX) - g(&c, ArticKey::TtX)).abs() < 0.01, "{name} {v}: tip x");+ assert!((g(&c, ArticKey::TtY) - g(a, ArticKey::TtY) - 0.11).abs() < 0.01, "{name} {v}: tip y");+ assert_eq!(g(a, ArticKey::TtCurl) > 0.8, curled, "{name} {v}: curl");+ }+ }+}++const FS: f64 = 48000.0;+const BEAT_AT: f64 = 0.5;++/// the articulators at `ms` after the beat, a one-beat note at 90 bpm, and the voice's samples+fn sing(py: &str, name: &str, body: HumanBody, fs: f64) -> (impl Fn(ArticKey, f64) -> f64, Vec<f32>) {+ let syl = pinyin_syllable(py, py).unwrap();+ let plan = plan_song(&[SungNote { midi: if name == "male" { 50.0 } else { 62.0 }, beats: 1.0, syl }], &SongOptions { body: name.into(), bpm: 90.0, t0: BEAT_AT, vibrato: 0.0, ..Default::default() });+ let mut v = HumanVoice::new(fs, body, oversample_for(fs));+ v.set_source(&SourcePatch::f0(if name == "male" { 110.0 } else { 220.0 }));+ v.schedule(&plan.gestures);+ let step = (fs / 200.0) as usize; // 5 ms+ let mut out = vec![0f32; (fs * (BEAT_AT + 0.7)) as usize / step * step];+ let mut frames = vec![ArticKey::ALL.iter().map(|k| v.artic.x.get(*k)).collect::<Vec<f64>>()];+ for block in out.chunks_mut(step) {+ v.render(block);+ frames.push(ArticKey::ALL.iter().map(|k| v.artic.x.get(*k)).collect());+ }+ (move |k: ArticKey, ms: f64| frames[(((BEAT_AT + ms / 1000.0) * 200.0).round() as usize).min(frames.len() - 1)][k.index()], out)+}++#[test]+fn the_tip_barely_moves_from_the_consonant_into_the_vowel() {+ // 只 吃 师 日 (ʅ) and 资 词 思 (ɿ): the consonant's release (just before the beat) against the+ // vowel's middle. Measured: the tip 0.07 or less in x, 0.05-0.28 in y, curl 0.13 at most (before:+ // y -1.7 to -2.5, curl -0.9 for ʅ), the lips open and spread (aperture 1.0, was 0.2)+ for py in ["zhi1", "chi1", "shi1", "ri4", "zi1", "ci1", "si1"] {+ let (a, _) = sing(py, "male", BODY_MALE, FS);+ let d = |k| (a(k, 250.0) - a(k, -25.0)).abs();+ assert!(d(ArticKey::TtX) <= 0.15, "{py}: tip x moves {:.2}", d(ArticKey::TtX));+ assert!(d(ArticKey::TtY) <= 0.4, "{py}: tip y moves {:.2}", d(ArticKey::TtY));+ assert!(d(ArticKey::TtCurl) <= 0.2, "{py}: curl moves {:.2}", d(ArticKey::TtCurl));+ assert!(a(ArticKey::LipAp, 250.0) >= 0.9 && a(ArticKey::LipProt, 250.0) <= 0.05, "{py}: lips");+ // and the lips are not rounded while the consonant is made either+ assert!(a(ArticKey::LipProt, -25.0) <= 0.15, "{py}: lips rounded at the release");+ }+}++/// normalised autocorrelation peak (3-20 ms lag) over 60 ms frames: 1 is a clean periodic voice,+/// turbulent noise in the vowel pulls it down+fn periodicity(x: &[f32], fs: f64, a: f64, b: f64) -> f64 {+ let (len, hop) = ((0.06 * fs) as usize, (0.02 * fs) as usize);+ let s = &x[(a * fs) as usize..(b * fs) as usize];+ let mut peaks = Vec::new();+ let mut k = 0;+ while k + len <= s.len() {+ let m = s[k..k + len].iter().map(|v| *v as f64).sum::<f64>() / len as f64;+ let fr: Vec<f64> = s[k..k + len].iter().map(|v| *v as f64 - m).collect();+ let ac = |lag: usize| fr.iter().zip(&fr[lag..]).map(|(p, q)| p * q).sum::<f64>();+ let r0 = ac(0) + 1e-12;+ peaks.push(((0.003 * fs) as usize..(0.02 * fs) as usize).map(|l| ac(l) / r0).fold(0.0, f64::max));+ k += hop;+ }+ peaks.iter().sum::<f64>() / peaks.len() as f64+}++#[test]+fn they_sing_steady_and_periodic_on_every_body_and_at_a_low_sample_rate() {+ // the tip's constriction (0.3 cm2) must not hiss or go unstable: no NaN, a clear voice, as periodic as before (0.83-0.89)+ for (name, body) in BODIES {+ for fs in [48000.0, 16000.0] {+ for py in ["zhi1", "si1"] {+ let (_, out) = sing(py, name, body, fs);+ assert!(out.iter().all(|x| x.is_finite()), "{name} {py} at {fs}: NaN");+ let (a, b) = (BEAT_AT + 0.15, BEAT_AT + 0.5);+ let rms = (out[(a * fs) as usize..(b * fs) as usize].iter().map(|v| (*v as f64).powi(2)).sum::<f64>() / ((b - a) * fs)).sqrt();+ assert!(rms > 0.02, "{name} {py} at {fs}: silent vowel (RMS {rms:.4})");+ let p = periodicity(&out, fs, a, b);+ assert!(p > 0.8, "{name} {py} at {fs}: periodicity {p:.2}");+ }+ }+ }+}diff --git a/crates/chimera/tests/bends.rs b/crates/chimera/tests/bends.rsindex 12496a4..3697dea 100644--- a/crates/chimera/tests/bends.rs+++ b/crates/chimera/tests/bends.rs@@ -55,10 +55,12 @@ fn a_melisma_keeps_its_written_pitches() {#[test]fn nasal_lead_nasalises_only_before_a_nasal_coda() {- // the syllable says its nasal lead (a front end: Mandarin's 0.4); unsaid, none- let notes = |lead| vec![SungNote { midi: 57.0, beats: 2.0, syl: Syllable { nasal_lead: lead, ..syl("ɕ", "i", &["ŋ"], vec![]) } }, SungNote { midi: 59.0, beats: 2.0, syl: Syllable { nasal_lead: lead, ..syl("t", "a", &[], vec![]) } }];- assert!(labelled(&plan_song(¬es(None), &opts()).gestures, "nasal vowel").is_empty());- let p = plan_song(¬es(Some(0.4)), &opts());+ // a closing rhyme says its nasal lead (a front end: Mandarin's 0.6); unsaid, none; and a rhyme+ // that isn't a closing one has its coda as a part of its own, with nothing leading it+ let notes = |lead, closing| vec![SungNote { midi: 57.0, beats: 2.0, syl: Syllable { nasal_lead: lead, closing, ..syl("ɕ", "i", &["ŋ"], vec![]) } }, SungNote { midi: 59.0, beats: 2.0, syl: Syllable { nasal_lead: lead, closing, ..syl("t", "a", &[], vec![]) } }];+ assert!(labelled(&plan_song(¬es(None, Some(0.2)), &opts()).gestures, "nasal vowel").is_empty());+ assert!(labelled(&plan_song(¬es(Some(0.4), None), &opts()).gestures, "nasal vowel").is_empty());+ let p = plan_song(¬es(Some(0.4), Some(0.2)), &opts());let nv = labelled(&p.gestures, "nasal vowel");assert_eq!(nv.len(), 1, "only the syllable with a nasal coda");assert!(nv[0].targets.get(ArticKey::Velum).unwrap() > 0.0);@@ -78,18 +80,3 @@ fn a_start_bend_begins_in_the_onset() {let plain = plan_song(&[SungNote { midi: 57.0, beats: 2.0, syl: syl("m", "a", &[], vec![]) }], &opts());assert!(plain.gestures.iter().filter(|g| g.label.as_ref().is_some_and(|l| l.as_str() == "pitch") && g.t1 <= 0.5 + 1e-9).filter_map(|g| g.targets.get(ControlKey::F0)).all(|f| (f - hz).abs() < 1e-9));}--#[test]-fn before_ng_after_a_back_vowel_the_tongue_rises_toward_the_velum() {- // in the nasal-lead window, -ng after ɑ gets the tongue body's approach; -n and other vowels don't- let approach = |v: &str, coda: &str| {- let p = plan_song(&[SungNote { midi: 57.0, beats: 2.0, syl: Syllable { nasal_lead: Some(0.4), ..syl("t", v, &[coda], vec![]) } }], &opts());- labelled(&p.gestures, "coda approach").len()- };- assert_eq!(approach("ɑ", "ŋ"), 1);- assert_eq!(approach("ɑ", "n"), 0);- assert_eq!(approach("ə", "ŋ"), 0);- // no nasal lead, no approach- let p = plan_song(&[SungNote { midi: 57.0, beats: 2.0, syl: syl("t", "ɑ", &["ŋ"], vec![]) }], &opts());- assert!(labelled(&p.gestures, "coda approach").is_empty());-}diff --git a/crates/chimera/tests/er.rs b/crates/chimera/tests/er.rsnew file mode 100644index 0000000..ce896c0--- /dev/null+++ b/crates/chimera/tests/er.rs@@ -0,0 +1,103 @@+//! Mandarin er (耳 ěr, 二 èr, 儿 ér) is a central vowel moving into the r-colouring ([əɚ]; 二 more+//! open, [aɚ]), not English's /ɝ/ held still: F3, the formant of the r-colour, falls over the+//! syllable instead of sitting low from the first frame. Formants are the airway's resonances in+//! the posture the sung voice has at each moment (as `chimera calibrate` measures them).+use chimera::airway::frequency::{find_peaks, transfer_function};+use chimera::anatomy::human::{BODY_MALE, HumanArtic};+use chimera::phonetics::mandarin::pinyin_syllable;+use chimera::phonetics::sing::{SongOptions, SungNote, plan_song};+use chimera::phonetics::{Segment, Syllable};+use chimera::voice::human_airway::HumanAirway;+use chimera::voice::human_voice::{HumanVoice, SourcePatch};++const FS: f64 = 48000.0;+const BEAT_AT: f64 = 0.5;+const STEP: usize = 240; // 5 ms++/// the posture of the male voice every 5 ms singing one one-beat note at 90 bpm+fn postures(syl: &Syllable) -> Vec<HumanArtic> {+ let plan = plan_song(&[SungNote { midi: 50.0, beats: 1.0, syl: syl.clone() }], &SongOptions { body: "male".into(), bpm: 90.0, t0: BEAT_AT, vibrato: 0.0, ..Default::default() });+ let mut v = HumanVoice::new(FS, BODY_MALE, 2);+ v.set_source(&SourcePatch::f0(110.0));+ v.schedule(&plan.gestures);+ let mut out = vec![0f32; STEP];+ let mut frames = vec![v.artic.x];+ for _ in 0..(FS * (BEAT_AT + 0.7)) as usize / STEP {+ v.render(&mut out);+ frames.push(v.artic.x);+ }+ frames+}++/// F1 F2 F3 (Hz) at `ms` after the beat+struct Formants(Vec<[f64; 3]>);++impl Formants {+ fn of(frames: &[HumanArtic]) -> Self {+ let mut air = HumanAirway::new(96000.0, BODY_MALE);+ let freqs: Vec<f64> = (0..700).map(|i| 120.0 * (4600.0f64 / 120.0).powf(i as f64 / 699.0)).collect();+ Formants(+ frames+ .iter()+ .map(|a| {+ air.apply(a, 0.0);+ let el = air.net.linear_elements();+ let h = transfer_function(&el, air.pharynx.first_node(), &freqs, &[air.glottis_port]);+ let pk = find_peaks(&freqs, &h.mag, 150.0);+ let f = |i: usize| pk.get(i).map_or(f64::NAN, |p| p.freq);+ [f(0), f(1), f(2)]+ })+ .collect(),+ )+ }+ fn at(&self, ms: f64) -> [f64; 3] {+ let i = ((BEAT_AT + ms / 1000.0) * FS / STEP as f64).round() as usize;+ self.0[i.min(self.0.len() - 1)]+ }+}++fn held(ipa: &str) -> Syllable {+ Syllable { text: "x".into(), onset: vec![Segment::new("ʔ")], nucleus: Segment::new(ipa), word_end: true, ..Default::default() }+}++/// 耳 and 儿 (any tone but the fourth) and 二+fn er(tone: u8) -> Formants {+ Formants::of(&postures(&pinyin_syllable(&format!("er{tone}"), "耳").unwrap()))+}++#[test]+fn the_r_colouring_arrives_late_not_from_the_first_frame() {+ // English's /ɝ/ held: F3 is already low at the beat (measured 1940 Hz there, 2280 at -80 ms)+ let old = Formants::of(&postures(&held("ɝ")));+ assert!(old.at(0.0)[2] < 2000.0);+ for tone in [2, 3, 4] {+ let f = er(tone);+ // still central (F3 ~2300-2550: ə, a) at the beat and just before it, then falling...+ assert!(f.at(-20.0)[2] > 2250.0 && f.at(0.0)[2] > 2250.0, "er{tone}: F3 {:.0} / {:.0} at -20 / 0 ms", f.at(-20.0)[2], f.at(0.0)[2]);+ let fall: Vec<f64> = [0.0, 40.0, 80.0].iter().map(|m| f.at(*m)[2]).collect();+ assert!(fall.windows(2).all(|w| w[1] < w[0] - 50.0), "er{tone}: F3 does not fall steadily {fall:?}");+ // ...into the r-colour, where it settles near ɝ's (1850 Hz), 450-650 Hz below its start+ assert!(f.at(150.0)[2] < 1900.0 && f.at(300.0)[2] < 1900.0, "er{tone}: F3 {:.0} / {:.0} at 150 / 300 ms", f.at(150.0)[2], f.at(300.0)[2]);+ assert!(f.at(0.0)[2] - f.at(300.0)[2] > 350.0);+ }+}++#[test]+fn er4_starts_more_open_than_the_other_tones() {+ // 二 [aɚ] against 耳 [əɚ]: F1 higher at the start (measured ~700 against ~495 Hz at -20 ms)+ let (a, e) = (er(4), er(3));+ assert!(a.at(-20.0)[0] > e.at(-20.0)[0] + 120.0, "F1 {:.0} against {:.0}", a.at(-20.0)[0], e.at(-20.0)[0]);+ // ...and the same r-coloured vowel once it has arrived+ assert!((a.at(300.0)[2] - e.at(300.0)[2]).abs() < 30.0);+}++#[test]+fn er_is_one_rising_nucleus_and_erhua_keeps_its_coda() {+ let s = |p: &str| pinyin_syllable(p, p).unwrap();+ assert_eq!(s("er3").nucleus.ipa, "əɝ");+ assert_eq!(s("er2").nucleus.ipa, "əɝ");+ assert_eq!(s("er4").nucleus.ipa, "aɝ");+ // 点儿: the vowel before the r is unchanged, and the r is its coda, not another nucleus+ let d = s("dianr3");+ assert_eq!((d.nucleus.ipa.as_str(), d.coda[0].ipa.as_str()), ("iɛ", "ɻ"));+}diff --git a/crates/chimera/tests/golden/phonetics-data.json b/crates/chimera/tests/golden/phonetics-data.jsonindex 9620fae..5fe164e 100644--- a/crates/chimera/tests/golden/phonetics-data.json+++ b/crates/chimera/tests/golden/phonetics-data.json@@ -1 +1 @@-{"songs":[{"name":"Made of air","bpm":84,"lyrics":"Breathe in, breathe out, I am made of air. Tongue and lips and throat, singing anywhere.","notes":[[64,1],[60,1],[62,1],[57,1],[57,0.5],[60,0.5],[64,1],[62,0.5],[60,1.5],[65,1],[64,0.5],[62,0.5],[60,0.5],[62,1.5],[64,0.5],[62,0.5],[60,0.5],[59,0.5],[57,2]],"octave":{"male":-1,"female":0,"child":0}},{"name":"Twinkle, twinkle","bpm":100,"lyrics":"Twinkle twinkle little star, how I wonder what you are.","notes":[[60,1],[60,1],[67,1],[67,1],[69,1],[69,1],[67,2],[65,1],[65,1],[64,1],[64,1],[62,1],[62,1],[60,2]],"octave":{"male":-1,"female":0,"child":0}}],"vowels":[{"ipa":"i","example":"heed","male":[342,2322,3000],"female":[437,2761,3372],"child":[452,3081,3702],"round":false,"height":0,"back":0},{"ipa":"ɪ","example":"hid","male":[427,2034,2684],"female":[483,2365,3053],"child":[511,2552,3403],"round":false,"height":0.2,"back":0.15},{"ipa":"e","example":"hayed","male":[476,2089,2691],"female":[536,2530,3047],"child":[564,2656,3323],"round":false,"height":0.3,"back":0.05},{"ipa":"ɛ","example":"head","male":[580,1799,2605],"female":[731,2058,2979],"child":[749,2267,3310],"round":false,"height":0.55,"back":0.1},{"ipa":"æ","example":"had","male":[640,1760,2500],"female":[669,2349,2972],"child":[717,2501,3289],"round":false,"height":0.8,"back":0.15},{"ipa":"a","example":"front open (Fr. patte)","male":[780,1450,2550],"female":[912.5999999999999,1740,2932.5],"child":[1014,1928.5,3162],"round":false,"height":1,"back":0.35},{"ipa":"ɑ","example":"hod","male":[768,1333,2522],"female":[936,1551,2815],"child":[1002,1688,2950],"round":false,"height":1,"back":0.85},{"ipa":"ɒ","example":"Br. lot","male":[620,880,2500],"female":[725.4,1056,2875],"child":[806,1170.4,3100],"round":true,"height":0.9,"back":1},{"ipa":"ɔ","example":"hawed","male":[652,997,2538],"female":[781,1136,2824],"child":[803,1210,2982],"round":true,"height":0.65,"back":1},{"ipa":"o","example":"hoed","male":[497,910,2459],"female":[555,1035,2828],"child":[597,1137,2987],"round":true,"height":0.35,"back":1},{"ipa":"ʊ","example":"hood","male":[469,1122,2434],"female":[519,1225,2827],"child":[568,1490,3072],"round":true,"height":0.2,"back":0.85},{"ipa":"u","example":"who'd","male":[378,997,2343],"female":[459,1105,2735],"child":[494,1345,2988],"round":true,"height":0,"back":1},{"ipa":"ʌ","example":"hud","male":[623,1200,2550],"female":[753,1426,2933],"child":[749,1546,3145],"round":false,"height":0.6,"back":0.7},{"ipa":"ə","example":"sofa","male":[500,1450,2450],"female":[585,1740,2817.5],"child":[650,1928.5,3038],"round":false,"height":0.5,"back":0.5},{"ipa":"ɐ","example":"near-open central","male":[640,1350,2500],"female":[748.8,1620,2875],"child":[832,1795.5,3100],"round":false,"height":0.8,"back":0.5},{"ipa":"ɝ","example":"heard","male":[474,1379,1710],"female":[523,1588,1929],"child":[586,1719,2143],"round":true,"height":0.45,"back":0.5},{"ipa":"y","example":"Fr. tu","male":[300,1800,2150],"female":[351,2160,2472.5],"child":[390,2394,2666],"round":true,"height":0,"back":0},{"ipa":"ø","example":"Fr. peu","male":[390,1550,2250],"female":[456.29999999999995,1860,2587.5],"child":[507,2061.5,2790],"round":true,"height":0.3,"back":0.1},{"ipa":"œ","example":"Fr. peur","male":[520,1450,2350],"female":[608.4,1740,2702.5],"child":[676,1928.5,2914],"round":true,"height":0.55,"back":0.15},{"ipa":"ɨ","example":"close central","male":[330,1600,2400],"female":[386.09999999999997,1920,2760],"child":[429,2128,2976],"round":false,"height":0,"back":0.5},{"ipa":"ɯ","example":"close back unrounded","male":[340,1350,2400],"female":[397.79999999999995,1620,2760],"child":[442,1795.5,2976],"round":false,"height":0,"back":1},{"ipa":"ɤ","example":"close-mid back unrounded","male":[460,1250,2450],"female":[538.1999999999999,1500,2817.5],"child":[598,1662.5,3038],"round":false,"height":0.35,"back":1},{"ipa":"ɿ","example":"Mandarin si (apical)","male":[360.0,1400.0,2600.0],"female":[421.2,1680.0,2989.9999999999995],"child":[468.0,1862.0,3224.0],"round":false,"height":0.0,"back":0.45},{"ipa":"ʅ","example":"Mandarin shi (apical, retroflex)","male":[400.0,1500.0,2000.0],"female":[468.0,1800.0,2300.0],"child":[520.0,1995.0,2480.0],"round":false,"height":0.05,"back":0.55}]}\ No newline at end of file+{"songs":[{"name":"Made of air","bpm":84,"lyrics":"Breathe in, breathe out, I am made of air. Tongue and lips and throat, singing anywhere.","notes":[[64,1],[60,1],[62,1],[57,1],[57,0.5],[60,0.5],[64,1],[62,0.5],[60,1.5],[65,1],[64,0.5],[62,0.5],[60,0.5],[62,1.5],[64,0.5],[62,0.5],[60,0.5],[59,0.5],[57,2]],"octave":{"male":-1,"female":0,"child":0}},{"name":"Twinkle, twinkle","bpm":100,"lyrics":"Twinkle twinkle little star, how I wonder what you are.","notes":[[60,1],[60,1],[67,1],[67,1],[69,1],[69,1],[67,2],[65,1],[65,1],[64,1],[64,1],[62,1],[62,1],[60,2]],"octave":{"male":-1,"female":0,"child":0}}],"vowels":[{"ipa":"i","example":"heed","male":[342,2322,3000],"female":[437,2761,3372],"child":[452,3081,3702],"round":false,"height":0,"back":0},{"ipa":"ɪ","example":"hid","male":[427,2034,2684],"female":[483,2365,3053],"child":[511,2552,3403],"round":false,"height":0.2,"back":0.15},{"ipa":"e","example":"hayed","male":[476,2089,2691],"female":[536,2530,3047],"child":[564,2656,3323],"round":false,"height":0.3,"back":0.05},{"ipa":"ɛ","example":"head","male":[580,1799,2605],"female":[731,2058,2979],"child":[749,2267,3310],"round":false,"height":0.55,"back":0.1},{"ipa":"æ","example":"had","male":[640,1760,2500],"female":[669,2349,2972],"child":[717,2501,3289],"round":false,"height":0.8,"back":0.15},{"ipa":"a","example":"front open (Fr. patte)","male":[780,1450,2550],"female":[912.5999999999999,1740,2932.5],"child":[1014,1928.5,3162],"round":false,"height":1,"back":0.35},{"ipa":"ɑ","example":"hod","male":[768,1333,2522],"female":[936,1551,2815],"child":[1002,1688,2950],"round":false,"height":1,"back":0.85},{"ipa":"ɒ","example":"Br. lot","male":[620,880,2500],"female":[725.4,1056,2875],"child":[806,1170.4,3100],"round":true,"height":0.9,"back":1},{"ipa":"ɔ","example":"hawed","male":[652,997,2538],"female":[781,1136,2824],"child":[803,1210,2982],"round":true,"height":0.65,"back":1},{"ipa":"o","example":"hoed","male":[497,910,2459],"female":[555,1035,2828],"child":[597,1137,2987],"round":true,"height":0.35,"back":1},{"ipa":"ʊ","example":"hood","male":[469,1122,2434],"female":[519,1225,2827],"child":[568,1490,3072],"round":true,"height":0.2,"back":0.85},{"ipa":"u","example":"who'd","male":[378,997,2343],"female":[459,1105,2735],"child":[494,1345,2988],"round":true,"height":0,"back":1},{"ipa":"ʌ","example":"hud","male":[623,1200,2550],"female":[753,1426,2933],"child":[749,1546,3145],"round":false,"height":0.6,"back":0.7},{"ipa":"ə","example":"sofa","male":[500,1450,2450],"female":[585,1740,2817.5],"child":[650,1928.5,3038],"round":false,"height":0.5,"back":0.5},{"ipa":"ɐ","example":"near-open central","male":[640,1350,2500],"female":[748.8,1620,2875],"child":[832,1795.5,3100],"round":false,"height":0.8,"back":0.5},{"ipa":"ɝ","example":"heard","male":[474,1379,1710],"female":[523,1588,1929],"child":[586,1719,2143],"round":true,"height":0.45,"back":0.5},{"ipa":"y","example":"Fr. tu","male":[300,1800,2150],"female":[351,2160,2472.5],"child":[390,2394,2666],"round":true,"height":0,"back":0},{"ipa":"ø","example":"Fr. peu","male":[390,1550,2250],"female":[456.29999999999995,1860,2587.5],"child":[507,2061.5,2790],"round":true,"height":0.3,"back":0.1},{"ipa":"œ","example":"Fr. peur","male":[520,1450,2350],"female":[608.4,1740,2702.5],"child":[676,1928.5,2914],"round":true,"height":0.55,"back":0.15},{"ipa":"ɨ","example":"close central","male":[330,1600,2400],"female":[386.09999999999997,1920,2760],"child":[429,2128,2976],"round":false,"height":0,"back":0.5},{"ipa":"ɯ","example":"close back unrounded","male":[340,1350,2400],"female":[397.79999999999995,1620,2760],"child":[442,1795.5,2976],"round":false,"height":0,"back":1},{"ipa":"ɤ","example":"close-mid back unrounded","male":[460,1250,2450],"female":[538.1999999999999,1500,2817.5],"child":[598,1662.5,3038],"round":false,"height":0.35,"back":1},{"ipa":"ɿ","example":"Mandarin si (apical)","male":[360.0,1400.0,2600.0],"female":[421.2,1680.0,2989.9999999999995],"child":[468.0,1862.0,3224.0],"round":false,"height":0.0,"back":0.45},{"ipa":"ʅ","example":"Mandarin shi (apical, retroflex)","male":[400.0,1500.0,2000.0],"female":[468.0,1800.0,2300.0],"child":[520.0,1995.0,2480.0],"round":false,"height":0.05,"back":0.55},{"ipa":"u̠","example":"Mandarin wu, hu (back u)","male":[345.0,661.0,2783.0],"female":[345.0,759.0,3309.0],"child":[448.5,879.13,3450.92],"round":true,"height":0.0,"back":1.0},{"ipa":"ʊ̠","example":"Mandarin ong (back ʊ)","male":[441.0,730.0,2881.0],"female":[533.0,945.0,3314.0],"child":[573.3000000000001,970.9000000000001,3572.44],"round":true,"height":0.2,"back":1.0}]}\ No newline at end of filediff --git a/crates/chimera/tests/mandarin.rs b/crates/chimera/tests/mandarin.rsindex f29002a..a84919b 100644--- a/crates/chimera/tests/mandarin.rs+++ b/crates/chimera/tests/mandarin.rs@@ -1,10 +1,10 @@//! Mandarin: the front end reads Han characters: longest phrase match, tone sandhi, pinyin → IPA-//! with aspiration said, tones → pitch bends; and pinyin typed with tones.+//! with aspiration said, tones read and not sung; and pinyin typed with tones.use chimera::phonetics::english::EnglishG2P;use chimera::phonetics::korean::Korean;-use chimera::phonetics::mandarin::{Mandarin, MandarinLexicon, Pinyin, tone_bends};+use chimera::phonetics::mandarin::{Mandarin, MandarinLexicon, Pinyin};use chimera::phonetics::syllables::{English, FrontEnd, read_lyrics};-use chimera::phonetics::{Edge, Syllable};+use chimera::phonetics::Syllable;const LEX: &str = "举\tju3\n风\tfeng1\n多\tduo1\n头\ttou2\n鸟\tniao3\n光\tguang1\n四\tsi4\n是\tshi4\n点\tdian3\n哪\tna3\n儿\ter2\n女\tnv3\n子\tzi5\n块\tkuai4\n一会儿\tyi1 hui4 er5\n天\ttian1\n你\tni3\n好\thao3\n我\two3\n不\tbu4\n会\thui4\n银\tyin2\n行\txing2\n银行\tyin2 hang2\n走\tzou3\n的\tde5\n跑\tpao3\n一\tyi1\n个\tge4\n绿\tlv4\n学\txue2\n吃\tchi1\n爱\tai4\n去\tqu4\n";@@ -42,18 +42,20 @@ fn pinyin_becomes_ipa_with_aspiration_said() {let all: Vec<String> = syls("跑不吃学绿的爱").iter().map(ipa).collect();// p aspirated, b unaspirated; ch aspirated before an apical vowel; xue = ɕ ɥ ɛ; lü; neutral de; ai// apical ʅ after ch; xue's glide sings inside the vowel (yɛ); 爱 starts with a glottal catch- assert_eq!(all, ["pʰaʊ", "p˭u", "tʂʰʅ", "ɕyɛ", "ly", "t˭ə", "ʔaɪ"]);+ assert_eq!(all, ["pʰaʊ̠", "p˭u̠", "tʂʰʅ", "ɕyɛ", "ly", "t˭ə", "ʔaɪ"]);}#[test]-fn tones_become_bends_and_text_keeps_the_character() {+fn tones_are_read_and_not_sung_and_text_keeps_the_character() {let s = syls("你好");assert_eq!((s[0].text.as_str(), s[1].text.as_str()), ("你", "好"));- assert_eq!(s[0].pitch, tone_bends(2)); // sandhi: sung as a rising tone- assert_eq!(s[1].pitch, tone_bends(3));assert!(s[1].word_end && !s[0].word_end);- assert!(tone_bends(1).is_empty() && tone_bends(5).is_empty());- assert_eq!(tone_bends(4).iter().map(|b| b.at).collect::<Vec<_>>(), [Edge::Start, Edge::End]);+ // the reading has its tones, sandhi applied (你 before a third tone is second)+ assert_eq!(lex().read("你好"), ["ni2", "hao3"]);+ // and no syllable bends the pitch for them: a song sings its melody. A native listener chose+ // this over the tones drawn on the melody at half and at full depth ("flat sounds sung, the+ // full tones sound spoken, half sounds odd")+ assert!(syls("你好,我是中国人,谢谢").iter().all(|s| s.pitch.is_empty()));}#[test]@@ -81,12 +83,9 @@ fn pinyin_with_tones_is_mandarin_and_without_is_english() {let text: Vec<&str> = t.iter().map(|x| x.0.as_str()).collect();assert_eq!(text, ["nǐ", "hǎo", "xiè", "xie", "ni3", "hao3", "de5", "Xī", "ān", "nǚ"]); // capitals keptlet ipa: Vec<&str> = t.iter().map(|x| x.1.as_str()).collect();- assert_eq!(ipa, ["ni", "xaʊ", "ɕiɛ", "ɕiɛ", "ni", "xaʊ", "t˭ə", "ɕi", "ʔan", "ny"]);- // nǐhǎo is one word: third-tone sandhi sings nǐ rising (one bend); "ni3 hao3" are two words- assert_eq!(t[0].2, tone_bends(2).len());- assert_eq!(t[4].2, tone_bends(3).len());- // the unmarked syllable of a marked word is neutral: no bend- assert_eq!(t[3].2, 0);+ assert_eq!(ipa, ["ni", "xaʊ̠", "ɕiɛ", "ɕiɛ", "ni", "xaʊ̠", "t˭ə", "ɕi", "ʔan", "ny"]);+ // the tones make it pinyin; none of them bends the pitch (a song sings its melody)+ assert!(t.iter().all(|x| x.2 == 0));// English: no tones, not pinyin. A word pinyin declines reads as it would without pinyin// ("café" English's "caf", not "caf" and a pinyin "é"), and nothing in it is lost: "Zürich über"// sings "Z rich ber" as on main (review of #78: it sang "Z ber")@@ -135,12 +134,12 @@ fn erhua_merges_into_the_syllable_before() {let shown = |t: &str| syls(t).iter().map(|s| format!("{}={}", s.text, ipa(s))).collect::<Vec<_>>().join(" ");// erhua: the syllable ends in ɻ, its -n gives way, a falling diphthong keeps its first vowelassert_eq!(shown("一点儿"), "一=i 点儿=t˭iɛɻ");- assert_eq!(shown("块儿"), "块儿=kʰuaɻ"); // uai → ua + ɻ (the off-glide gives way, the on-glide stays)+ assert_eq!(shown("块儿"), "块儿=kʰu̠aɻ"); // uai → ua + ɻ (the off-glide gives way, the on-glide stays)assert_eq!(shown("哪儿"), "哪儿=naɻ");assert_eq!(shown("一会儿"), "一=i 会儿=xweɻ");// 儿 as a word's own syllable- assert_eq!(shown("女儿"), "女=ny 儿=ʔɝ");- assert_eq!(shown("儿子"), "儿=ʔɝ 子=ts˭ɿ");+ assert_eq!(shown("女儿"), "女=ny 儿=ʔəɝ");+ assert_eq!(shown("儿子"), "儿=ʔəɝ 子=ts˭ɿ");// pinyin's rlet p: Vec<String> = typed("nǎr yìdiǎnr").into_iter().map(|x| x.1).collect();assert_eq!(p, ["naɻ", "i", "t˭iɛɻ"]);@@ -150,16 +149,16 @@ fn erhua_merges_into_the_syllable_before() {fn mandarin_timing_and_vowels() {let s = syls("光天你风举");let dur = |segs: &[chimera::phonetics::Segment]| segs.iter().map(|x| x.dur).collect::<Vec<_>>();- // nasal codas held long enough to tell -n from -ng- assert_eq!(dur(&s[0].coda), [Some(0.13)]);- assert_eq!(dur(&s[1].coda), [Some(0.10)]);+ // nasal codas a short murmur at the end of the rhyme (tests/mandarin_rhymes.rs)+ assert_eq!(dur(&s[0].coda), [Some(0.08)]);+ assert_eq!(dur(&s[1].coda), [Some(0.07)]);// nasal onsets and f longer; an unaspirated affricate's frication shorterassert_eq!(s[2].onset[0].dur, Some(0.09));assert_eq!(s[3].onset[0].dur, Some(0.13));assert_eq!(s[4].onset[0].dur, Some(0.08));- // Mandarin's own vowels: eng back [ɤŋ], uo open [uɔ], ou central [əʊ], iao one three-part nucleus+ // Mandarin's own vowels: eng back [ɤŋ], uo open [u̠ɔ], ou central [əʊ̠], iao one three-part nucleuslet n: Vec<String> = syls("风多头鸟").iter().map(|s| s.nucleus.ipa.clone()).collect();- assert_eq!(n, ["ɤ", "uɔ", "əʊ", "iaʊ"]);+ assert_eq!(n, ["ɤ", "u̠ɔ", "əʊ̠", "iaʊ̠"]);}#[test]diff --git a/crates/chimera/tests/mandarin_ong.rs b/crates/chimera/tests/mandarin_ong.rsnew file mode 100644index 0000000..a515e58--- /dev/null+++ b/crates/chimera/tests/mandarin_ong.rs@@ -0,0 +1,101 @@+//! Mandarin's ong (东 dong, 中 zhong, 兄 xiong) is [ʊŋ] with F2 ~730 Hz (Zee & Lee 2001,+//! doi 10.21437/Eurospeech.2001-169, "u before ŋ": men 441 / 730 Hz F1 / F2), where English /ʊ/+//! "hood" has ~1120. The front end sang the English vowel. Mandarin gets `ʊ̠` (ʊ + U+0320), also the+//! off-glide of ao ou iao iou. The back u (乌 wu) has its own tests in `mandarin_u.rs`.+use chimera::analysis::lpc::{FormantOpts, estimate_formants};+use chimera::anatomy::human::{BODY_FEMALE, BODY_MALE, HumanBody};+use chimera::phonetics::ipa::tokenize_ipa;+use chimera::phonetics::mandarin::pinyin_syllable;+use chimera::phonetics::planner::{expand, vowel_table};+use chimera::phonetics::sing::{SongOptions, SungNote, plan_song};+use chimera::phonetics::{Segment, Syllable};+use chimera::voice::human_voice::{HumanVoice, SourcePatch, oversample_for};++const ONG: &str = "ʊ\u{320}";++fn nucleus(py: &str) -> String {+ pinyin_syllable(py, py).unwrap().nucleus.ipa+}++#[test]+fn the_front_end_sings_ong_and_the_off_glides_with_the_back_ʊ() {+ for py in ["dong1", "zhong1", "gong1"] {+ assert_eq!(nucleus(py), ONG, "{py}");+ }+ assert_eq!(nucleus("xiong2"), format!("i{ONG}"));+ assert_eq!(nucleus("hao3"), format!("aʊ\u{320}"));+ assert_eq!(nucleus("dou1"), format!("əʊ\u{320}"));+ assert_eq!(nucleus("liao3"), format!("iaʊ\u{320}"));+ assert_eq!(nucleus("you3"), format!("iəʊ\u{320}"));+ // the compounds expand to the new vowel as their last part+ for k in ["iʊ\u{320}", "aʊ\u{320}", "əʊ\u{320}", "iaʊ\u{320}", "iəʊ\u{320}"] {+ assert_eq!(expand(k).unwrap().last().copied(), Some(ONG), "{k}");+ }+ // English's falling diphthongs, and the coda of 东, are as they were+ assert_eq!(expand("aʊ").unwrap(), ["a", "ʊ"]);+ assert_eq!(pinyin_syllable("dong1", "dong1").unwrap().coda[0].ipa, "ŋ");+}++#[test]+fn english_hood_is_still_the_english_vowel() {+ let ipas = |s: &str| tokenize_ipa(s).into_iter().map(|x| x.ipa).collect::<Vec<_>>();+ assert_eq!(ipas("hʊd"), ["h", "ʊ", "d"]);+ assert_eq!(ipas("haʊs"), ["h", "aʊ", "s"]);+ let t = vowel_table();+ for body in ["male", "female", "child"] {+ let (eng, man) = (t[body]["ʊ"].formants[1], t[body][ONG].formants[1]);+ assert!(eng > 1100.0, "{body}: English ʊ F2 {eng} moved");+ assert!(man < 0.9 * eng, "{body}: ʊ̠ F2 {man} vs ʊ {eng}");+ }+}++const FS: f64 = 48000.0;+const BEAT_AT: f64 = 0.5;++/// median F2 (Hz) of the voice's LPC frames of 40 ms, from 0.1 s to 0.2 s after the beat of a one-beat note+fn sung_f2(syl: Syllable, body: HumanBody, name: &str, fs: f64) -> f64 {+ // 110 Hz on every body: at a woman's 220 Hz the harmonics are too sparse for LPC to place F1 and F2 well+ let (midi, f0) = (50.0, 110.0);+ let plan = plan_song(&[SungNote { midi, beats: 1.0, syl }], &SongOptions { body: name.into(), bpm: 90.0, t0: BEAT_AT, vibrato: 0.0, ..Default::default() });+ let mut v = HumanVoice::new(fs, body, oversample_for(fs));+ v.set_source(&SourcePatch::f0(f0));+ v.schedule(&plan.gestures);+ let mut out = vec![0f32; (fs * (BEAT_AT + 0.7)) as usize];+ for block in out.chunks_mut(512) {+ v.render(block);+ }+ assert!(out.iter().all(|x| x.is_finite()), "{name} at {fs}: NaN");+ let len = (0.04 * fs) as usize;+ let mut f2: Vec<f64> = (0..5)+ .map(|k| {+ let a = ((BEAT_AT + 0.1 + 0.025 * k as f64) * fs) as usize;+ let frame: Vec<f64> = out[a..a + len].iter().map(|x| *x as f64).collect();+ estimate_formants(&frame, fs, FormantOpts::default())[1].freq+ })+ .collect();+ f2.sort_by(f64::total_cmp);+ f2[2]+}++fn english_ong() -> Syllable {+ let mut s = pinyin_syllable("dong1", "dong1").unwrap();+ s.nucleus = Segment::new("ʊ");+ s+}++#[test]+fn sung_dong_has_an_f2_below_the_english_ʊ() {+ for (name, body) in [("male", BODY_MALE), ("female", BODY_FEMALE)] {+ let mandarin = sung_f2(pinyin_syllable("dong1", "dong1").unwrap(), body, name, FS);+ let english = sung_f2(english_ong(), body, name, FS);+ assert!(mandarin + 150.0 < english, "{name}: Mandarin dong F2 {mandarin:.0} Hz vs English ʊŋ {english:.0} Hz");+ }+}++#[test]+fn ong_holds_at_a_low_sample_rate() {+ for (name, body) in [("male", BODY_MALE), ("female", BODY_FEMALE)] {+ let f2 = sung_f2(pinyin_syllable("dong1", "dong1").unwrap(), body, name, 16000.0);+ assert!(f2 > 300.0 && f2 < 1400.0, "{name}: F2 {f2:.0}");+ }+}diff --git a/crates/chimera/tests/mandarin_rhymes.rs b/crates/chimera/tests/mandarin_rhymes.rsnew file mode 100644index 0000000..4041f18--- /dev/null+++ b/crates/chimera/tests/mandarin_rhymes.rs@@ -0,0 +1,164 @@+//! A Mandarin rhyme is one sound: its ending (the off-glide of ai ei ao ou, a nasal coda) is where+//! the vowel ends up, not a second sound after it. A native listener heard every compound and nasal+//! rhyme as two: 奥 ao sung for 1.33 s was [a] still for 0.76 s, a jump, then [ʊ] still for 0.35 s;+//! 昂 ang was an oral [ɑ], the tongue body jumping in 40 ms, then 0.4 s of murmur ("an + ng"); and a+//! phrase's last -n let go while the breath was still on ([an-ə]). The front end now marks its+//! rhymes closing (`Syllable::closing`), and the song planner sings the ending as one movement over+//! the end of the note.+use chimera::analysis::lpc::{FormantOpts, estimate_formants};+use chimera::anatomy::human::BODY_MALE;+use chimera::phonetics::mandarin::pinyin_syllable;+use chimera::phonetics::sing::{SongOptions, SungNote, plan_song};+use chimera::phonetics::{Plan, Segment, Syllable};+use chimera::voice::human_voice::{HumanVoice, SourcePatch, oversample_for};++const FS: f64 = 48000.0;+const BEAT_AT: f64 = 0.5;++/// one note of `secs` seconds, its beat at [`BEAT_AT`]; it ends (the breath's reserve) 50 ms early+fn plan(syl: Syllable, secs: f64) -> Plan {+ plan_song(&[SungNote { midi: 45.0, beats: secs, syl }], &SongOptions { body: "male".into(), bpm: 60.0, t0: BEAT_AT, vibrato: 0.0, ..Default::default() })+}++fn mandarin(py: &str) -> Syllable {+ pinyin_syllable(py, py).unwrap()+}++fn render(p: &Plan, secs: f64, fs: f64) -> Vec<f32> {+ let mut v = HumanVoice::new(fs, BODY_MALE, oversample_for(fs));+ v.set_source(&SourcePatch::f0(110.0));+ v.schedule(&p.gestures);+ let mut out = vec![0f32; (fs * (BEAT_AT + secs + 0.4)) as usize];+ for block in out.chunks_mut(512) {+ v.render(block);+ }+ assert!(out.iter().all(|x| x.is_finite()), "NaN at {fs}");+ out+}++/// level (dB) of the 40 ms centred on t+fn level(out: &[f32], t: f64) -> f64 {+ let a = ((t - 0.02) * FS) as usize;+ let n = (0.04 * FS) as usize;+ let ms = out[a..a + n].iter().map(|x| (*x as f64) * (*x as f64)).sum::<f64>() / n as f64;+ 10.0 * ms.max(1e-12).log10()+}++/// F1 and F2 (Hz) of the 40 ms centred on t+fn formants(out: &[f32], t: f64) -> (f64, f64) {+ let a = ((t - 0.02) * FS) as usize;+ let frame: Vec<f64> = out[a..a + (0.04 * FS) as usize].iter().map(|x| *x as f64).collect();+ let f = estimate_formants(&frame, FS, FormantOpts::default());+ (f[0].freq, f[1].freq)+}++#[test]+fn the_front_end_marks_its_rhymes_closing_and_its_codas_short() {+ for py in ["ao1", "ang1", "an1", "ma1"] {+ assert_eq!(mandarin(py).closing, Some(0.2), "{py}");+ }+ assert_eq!(mandarin("ang1").coda[0].dur, Some(0.08));+ assert_eq!(mandarin("an1").coda[0].dur, Some(0.07));+}++#[test]+fn a_long_ao_holds_its_a_and_glides_only_at_the_end() {+ let secs = 1.33;+ let p = plan(mandarin("ao1"), secs);+ // the off-glide is a short last part, coming in over its own length: no second held vowel+ let glide = p.segments.iter().find(|s| s.ipa == "ʊ\u{320}").expect("the off-glide");+ assert!(glide.t1 - glide.t0 <= 0.101, "the off-glide is held {:.3} s", glide.t1 - glide.t0);+ let g = p.gestures.iter().find(|g| g.label_str() == "ʊ\u{320}").unwrap();+ assert!(g.ramp_in >= 0.099, "the off-glide comes in over {:.3} s", g.ramp_in);+ // heard: 0.3 s before the note ends it is still [a] (it was [ʊ], F2 ~780), and it has moved by the end+ let out = render(&p, secs, FS);+ let end = BEAT_AT + secs - 0.05;+ let (_, still_a) = formants(&out, end - 0.3);+ let (_, closed) = formants(&out, end - 0.03);+ assert!(still_a > 1250.0, "0.3 s before the end F2 is {still_a:.0}");+ assert!(closed < 1150.0, "at the end F2 is {closed:.0}");+}++#[test]+fn a_short_note_keeps_some_of_its_main_vowel() {+ // 0.3 s: the movement takes at most 60 % of the vowel+ let p = plan(mandarin("ai1"), 0.3);+ let v: Vec<_> = p.segments.iter().filter(|s| s.kind == "vowel").collect();+ assert_eq!(v.len(), 2);+ let (held, glide) = (v[0].t1 - v[0].t0, v[1].t1 - v[1].t0);+ assert!((glide - 0.3 * (held + glide)).abs() < 1e-9, "held {held:.3}, glide {glide:.3}");+}++#[test]+fn a_long_ang_is_a_vowel_until_its_last_fifth_of_a_second() {+ let secs = 1.33;+ let p = plan(mandarin("ang1"), secs);+ let out = render(&p, secs, FS);+ let end = BEAT_AT + secs - 0.05;+ let vowel = level(&out, BEAT_AT + 0.4);+ // 0.3 s before the end it was already the murmur (10 dB down, F1 ~440)+ let late = level(&out, end - 0.3);+ let (f1, _) = formants(&out, end - 0.3);+ assert!(late > vowel - 3.0, "0.3 s before the end the level is {:.1} dB under the vowel's", vowel - late);+ assert!(f1 > 600.0, "0.3 s before the end F1 is {f1:.0}");+ // and it still closes into the -ng+ let murmur = level(&out, end - 0.04);+ let (f1, _) = formants(&out, end - 0.04);+ assert!(murmur < vowel - 4.0, "the murmur is {:.1} dB under the vowel", vowel - murmur);+ assert!(f1 < 560.0, "the murmur's F1 is {f1:.0}");+ // the velum comes down over the nasalised part instead of dropping at its start, and the+ // tongue body is on its way before the coda closes+ let velum = p.gestures.iter().find(|g| g.label_str() == "nasal vowel").unwrap();+ assert!(velum.ramp_in >= 0.2, "the velum lowers over {:.3} s", velum.ramp_in);+ assert!(p.gestures.iter().any(|g| g.label_str() == "coda approach" && g.ramp_in >= 0.1));+}++/// the deepest fall-and-recover (dB) of the level between a and b, in 20 ms steps+fn dip(out: &[f32], a: f64, b: f64) -> f64 {+ let n = ((b - a) / 0.02) as usize;+ let l: Vec<f64> = (0..n).map(|i| level(out, a + 0.02 * i as f64)).collect();+ (1..n - 1).map(|i| l[..i].iter().cloned().fold(f64::MIN, f64::max).min(l[i + 1..].iter().cloned().fold(f64::MIN, f64::max)) - l[i]).fold(0.0, f64::max)+}++#[test]+fn a_close_vowel_does_not_stop_before_its_ng() {+ // 东 dong: [ʊ] is close under the velum already. With the velum still up as the coda closed, the+ // voice dipped 9 dB for a moment, a stop between the vowel and the murmur+ let secs = 0.4;+ let out = render(&plan(mandarin("dong1"), secs), secs, FS);+ let d = dip(&out, BEAT_AT + 0.1, BEAT_AT + secs - 0.06);+ assert!(d < 3.0, "the level falls and recovers by {d:.1} dB inside the rhyme");+}++#[test]+fn a_phrase_final_n_is_not_released_into_a_vowel() {+ // 安 an: the murmur fades; it used to rise 2.7 dB again as the tongue let go ([an-ə])+ let secs = 0.4;+ let p = plan(mandarin("an1"), secs);+ let out = render(&p, secs, FS);+ let end = p.segments.last().unwrap().t1;+ let murmur = level(&out, end - 0.05);+ for k in 0..6 {+ let t = end - 0.02 + 0.02 * k as f64;+ assert!(level(&out, t) < murmur + 1.0, "{:.0} ms after the coda's end the level is {:.1} dB over the murmur", (t - end) * 1000.0, level(&out, t) - murmur);+ }+}++#[test]+fn a_syllable_that_is_not_closing_sings_as_before() {+ // English "my": the off-glide holds 20 % of the vowel+ let syl = Syllable { text: "my".into(), onset: vec![Segment::new("m")], nucleus: Segment::new("aɪ"), ..Default::default() };+ let p = plan(syl, 1.0);+ let v: Vec<_> = p.segments.iter().filter(|s| s.kind == "vowel").collect();+ let (held, glide) = (v[0].t1 - v[0].t0, v[1].t1 - v[1].t0);+ assert!((glide - 0.2 * (held + glide)).abs() < 1e-9, "held {held:.3}, glide {glide:.3}");+ let g = p.gestures.iter().find(|g| g.label_str() == "ɪ").unwrap();+ assert!((g.ramp_in - 0.04).abs() < 1e-9, "ramp {}", g.ramp_in);+}++#[test]+fn closing_rhymes_hold_at_a_low_sample_rate() {+ for py in ["ao1", "ang1", "an1", "ying1"] {+ render(&plan(mandarin(py), 0.4), 0.4, 16000.0);+ }+}diff --git a/crates/chimera/tests/mandarin_u.rs b/crates/chimera/tests/mandarin_u.rsnew file mode 100644index 0000000..e74fbd3--- /dev/null+++ b/crates/chimera/tests/mandarin_u.rs@@ -0,0 +1,98 @@+//! Mandarin's u (乌 wu, 虎 hu, the medial of 话 hua and 朵 duo) is not English's /u/. Beijing+//! speakers' u has F2 ~660 Hz (Zee & Lee 2001, doi 10.21437/Eurospeech.2001-169: 345 / 661 Hz+//! F1 / F2, men), English "who'd" ~1000 Hz (Hillenbrand et al. 1995). The front end used to+//! sing the English vowel (a native speaker still heard a foreigner in the singing, and this was+//! its largest measured distance from Beijing speakers' vowels). Mandarin gets its+//! own table entry, `u̠` (u + U+0320), that no English, Korean, Japanese or IPA-lyrics text reaches.+use chimera::analysis::lpc::{FormantOpts, estimate_formants};+use chimera::anatomy::human::{BODY_FEMALE, BODY_MALE, HumanBody};+use chimera::phonetics::ipa::tokenize_ipa;+use chimera::phonetics::mandarin::pinyin_syllable;+use chimera::phonetics::planner::vowel_table;+use chimera::phonetics::sing::{SongOptions, SungNote, plan_song};+use chimera::phonetics::{Segment, Syllable};+use chimera::voice::human_voice::{HumanVoice, SourcePatch, oversample_for};++const BACK_U: &str = "u\u{320}";++fn nucleus(py: &str) -> String {+ pinyin_syllable(py, py).unwrap().nucleus.ipa+}++#[test]+fn the_front_end_sings_the_back_u_in_wu_hu_and_every_u_medial() {+ for py in ["wu1", "hu3", "bu4", "gu1", "ku4", "fu2", "lu2"] {+ assert_eq!(nucleus(py), BACK_U, "{py}");+ }+ // the u medial of a rising nucleus (and of the triphthongs), also u̠+ for (py, want) in [("gua1", "a"), ("duo1", "ɔ"), ("guan1", "a"), ("dun1", "ə"), ("guang1", "ɑ"), ("weng1", "ə"), ("guai4", "aɪ"), ("gui1", "eɪ"), ("bo1", "ɔ")] {+ assert_eq!(nucleus(py), format!("{BACK_U}{want}"), "{py}");+ }+ // 块儿: the off-glide gives way to the r and the back-u on-glide stays+ assert_eq!(nucleus("kuair4"), format!("{BACK_U}a"));+}++#[test]+fn english_and_ipa_text_still_sing_the_english_vowels() {+ let ipas = |s: &str| tokenize_ipa(s).into_iter().map(|x| x.ipa).collect::<Vec<_>>();+ assert_eq!(ipas("hud"), ["h", "u", "d"]); // who'd+ assert_eq!(ipas("hʊd"), ["h", "ʊ", "d"]); // hood+ // the mark can't be typed into the entry: the tokenizer drops it and sings the English u+ assert_eq!(ipas("hu\u{320}d"), ["h", "u", "d"]);+ let t = vowel_table();+ for body in ["male", "female", "child"] {+ assert!(t[body]["u"].formants[1] > 990.0 * if body == "male" { 1.0 } else { 1.1 }, "{body} English u moved");+ assert!(t[body][BACK_U].formants[1] < 0.8 * t[body]["u"].formants[1], "{body}: u̠ F2 {} vs u {}", t[body][BACK_U].formants[1], t[body]["u"].formants[1]);+ }+}++const FS: f64 = 48000.0;+const BEAT_AT: f64 = 0.5;++/// F2 (Hz) of a sung one-beat note at 90 bpm, a median over LPC frames of 40 ms in the held vowel+fn sung_f2(syl: Syllable, body: HumanBody, name: &str, fs: f64) -> f64 {+ // 110 Hz on every body: at a woman's 220 Hz the harmonics are too sparse for LPC to place F1 and F2 well+ let (midi, f0) = (50.0, 110.0);+ let plan = plan_song(&[SungNote { midi, beats: 1.0, syl }], &SongOptions { body: name.into(), bpm: 90.0, t0: BEAT_AT, vibrato: 0.0, ..Default::default() });+ let mut v = HumanVoice::new(fs, body, oversample_for(fs));+ v.set_source(&SourcePatch::f0(f0));+ v.schedule(&plan.gestures);+ let mut out = vec![0f32; (fs * (BEAT_AT + 0.7)) as usize];+ for block in out.chunks_mut(512) {+ v.render(block);+ }+ assert!(out.iter().all(|x| x.is_finite()), "{name} at {fs}: NaN");+ let len = (0.04 * fs) as usize;+ let mut f2: Vec<f64> = (0..5)+ .map(|k| {+ let a = ((BEAT_AT + 0.2 + 0.03 * k as f64) * fs) as usize;+ let frame: Vec<f64> = out[a..a + len].iter().map(|x| *x as f64).collect();+ estimate_formants(&frame, fs, FormantOpts::default())[1].freq+ })+ .collect();+ f2.sort_by(f64::total_cmp);+ f2[2]+}++fn english_u() -> Syllable {+ Syllable { text: "who'd".into(), onset: vec![Segment::new("x")], nucleus: Segment::new("u"), ..Default::default() }+}++#[test]+fn sung_wu_has_an_f2_far_below_the_english_u() {+ // measured from the rendered voice (LPC): the Mandarin u's F2 was the English one's ~1000 Hz+ for (name, body) in [("male", BODY_MALE), ("female", BODY_FEMALE)] {+ let mandarin = sung_f2(pinyin_syllable("hu3", "hu3").unwrap(), body, name, FS);+ let english = sung_f2(english_u(), body, name, FS);+ assert!(mandarin + 200.0 < english, "{name}: Mandarin hu F2 {mandarin:.0} Hz vs English u {english:.0} Hz");+ }+}++#[test]+fn the_back_u_holds_at_a_low_sample_rate() {+ // a tight back constriction must not go unstable at a Bluetooth headset's 16 kHz (sung_f2 asserts finite)+ for (name, body) in [("male", BODY_MALE), ("female", BODY_FEMALE)] {+ let f2 = sung_f2(pinyin_syllable("wu1", "wu1").unwrap(), body, name, 16000.0);+ assert!(f2 > 300.0 && f2 < 1200.0, "{name}: F2 {f2:.0}");+ }+}diff --git a/crates/chimera/tests/medials.rs b/crates/chimera/tests/medials.rsnew file mode 100644index 0000000..0b69de2--- /dev/null+++ b/crates/chimera/tests/medials.rs@@ -0,0 +1,142 @@+//! A Mandarin medial glide (两 liang, 快 kuai, 话 hua) is a quick transition into the main vowel,+//! not a held vowel of its own: it is made with the initial consonant and is leaving by the beat, so+//! the main vowel's posture arrives within ~110 ms of the beat (it took ~200 ms when the glide sat+//! on the beat as a 120 ms plateau, and listening diagnoses of the renders, by language models,+//! heard 两 as li-ang). Measured on the voice's+//! articulators, as `chimera render notes --artic` records them.+use chimera::anatomy::human::{ArticKey, BODY_MALE};+use chimera::phonetics::mandarin::pinyin_syllable;+use chimera::phonetics::sing::{SongOptions, SungNote, plan_song};+use chimera::phonetics::Syllable;+use chimera::voice::human_voice::{HumanVoice, SourcePatch};++const FS: f64 = 48000.0;+const BPM: f64 = 90.0;+const BEAT_AT: f64 = 0.5;+const STEP: usize = 240; // 5 ms++/// The articulators of one sung one-beat syllable on the male body at 90 bpm, every 5 ms from the+/// start; `at(key, ms after the beat)`.+struct Track {+ frames: Vec<Vec<f64>>,+ vowels: Vec<(String, f64, f64)>,+}++impl Track {+ fn at(&self, k: ArticKey, ms: f64) -> f64 {+ let i = ((BEAT_AT + ms / 1000.0) * FS / STEP as f64).round() as usize;+ self.frames[i.min(self.frames.len() - 1)][k.index()]+ }+ /// first time (ms after the beat) the key is within 10% of its travel to its value at `hold` ms+ fn reaches_90(&self, k: ArticKey, hold: f64) -> f64 {+ let (s, h) = (self.at(k, 0.0), self.at(k, hold));+ (0..400).step_by(5).map(f64::from).find(|ms| (self.at(k, *ms) - h).abs() <= 0.1 * (s - h).abs()).unwrap_or(999.0)+ }+}++fn sing(syl: &Syllable) -> Track {+ let plan = plan_song(&[SungNote { midi: 50.0, beats: 1.0, syl: syl.clone() }], &SongOptions { body: "male".into(), bpm: BPM, t0: BEAT_AT, vibrato: 0.0, ..Default::default() });+ let mut v = HumanVoice::new(FS, BODY_MALE, 2);+ v.set_source(&SourcePatch::f0(110.0));+ v.schedule(&plan.gestures);+ let n = (FS * (BEAT_AT + 0.7)) as usize;+ let mut out = vec![0f32; STEP];+ let mut frames = vec![ArticKey::ALL.iter().map(|k| v.artic.x.get(*k)).collect()];+ for _ in 0..n / STEP {+ v.render(&mut out);+ frames.push(ArticKey::ALL.iter().map(|k| v.artic.x.get(*k)).collect());+ }+ Track { frames, vowels: plan.segments.iter().filter(|s| s.kind == "vowel").map(|s| (s.ipa.clone(), s.t0, s.t1)).collect() }+}++fn py(p: &str) -> Syllable {+ pinyin_syllable(p, p).unwrap_or_else(|| panic!("{p}"))+}++/// 两 快 朵 怪 有 话 家 月: a medial, a triphthong, a medial with no initial, ü+const MEDIALS: [&str; 8] = ["liang3", "kuai4", "duo3", "guai4", "you3", "hua4", "jia1", "yue4"];++#[test]+fn the_main_vowel_arrives_soon_after_the_beat() {+ // measured 75-90 ms (a syllable with no medial: 50 ms); with the glide as a 120 ms plateau on+ // the beat it was ~200 ms+ for p in MEDIALS {+ let t = sing(&py(p));+ let mut checked = 0;+ for k in [ArticKey::Jaw, ArticKey::TbY] {+ if (t.at(k, 0.0) - t.at(k, 200.0)).abs() < 0.3 {+ continue; // this articulator hardly moves into this vowel+ }+ checked += 1;+ let ms = t.reaches_90(k, 200.0);+ assert!(ms <= 110.0, "{p}: {k:?} reaches its vowel {ms} ms after the beat");+ }+ assert!(checked >= 1, "{p}: nothing moved");+ }+}++#[test]+fn nothing_waits_on_the_beat() {+ // no plateau: a quarter of the way to the vowel within 40 ms (measured 40-80%; the plateau gave ~0)+ for p in MEDIALS {+ let t = sing(&py(p));+ let k = if (t.at(ArticKey::Jaw, 0.0) - t.at(ArticKey::Jaw, 200.0)).abs() > 0.3 { ArticKey::Jaw } else { ArticKey::TbY };+ let (s, h) = (t.at(k, 0.0), t.at(k, 200.0));+ let done = (t.at(k, 40.0) - s) / (h - s);+ assert!(done >= 0.25, "{p}: {k:?} has done {:.0}% of its travel 40 ms after the beat", done * 100.0);+ }+}++#[test]+fn the_glide_is_reached_before_the_beat() {+ // the medial is made with the consonant: at its release (just before the beat) the lips are+ // rounded for u and ü, the tongue body fronted for i+ for p in ["kuai4", "duo3", "guai4", "hua4", "yue4"] {+ let t = sing(&py(p));+ assert!(t.at(ArticKey::LipProt, -20.0) >= 1.0, "{p}: lips not rounded before the beat ({})", t.at(ArticKey::LipProt, -20.0));+ }+ for p in ["liang3", "you3", "jia1"] {+ let t = sing(&py(p));+ // i's tongue body is high (TbY 7.5-7.7), the main vowels' lower (5.7-6.7)+ assert!(t.at(ArticKey::TbY, -20.0) >= 7.4, "{p}: tongue body not at i before the beat ({})", t.at(ArticKey::TbY, -20.0));+ assert!(t.at(ArticKey::TbY, -20.0) - t.at(ArticKey::TbY, 200.0) >= 0.7, "{p}: the vowel does not lower from i");+ }+}++#[test]+fn the_medial_is_still_there_against_the_same_syllable_without_it() {+ // the old failure: the medial lost (话 hua heard as 哈 ha). Each pair has the same initial and+ // main vowel; the medial's lip rounding or tongue fronting must show in the first 60 ms of the vowel+ // (measured: lip protrusion differs by 0.8 at +20 ms, tongue body by 0.5-1.1)+ for (with, without) in [("hua4", "ha4"), ("kuai4", "kai4"), ("guang1", "gang1"), ("zhuang1", "zhang1")] {+ let (x, y) = (sing(&py(with)), sing(&py(without)));+ let d = (x.at(ArticKey::LipProt, 20.0) - y.at(ArticKey::LipProt, 20.0)).abs();+ assert!(d >= 0.5, "{with} vs {without}: lips differ by {d:.2} at +20 ms");+ }+ for (with, without) in [("jia1", "ja1"), ("xia1", "xa1"), ("liang3", "lang3")] {+ let (x, y) = (sing(&py(with)), sing(&py(without)));+ let d = [0.0, 20.0, 40.0].iter().flat_map(|ms| [ArticKey::TbX, ArticKey::TbY].map(|k| (x.at(k, *ms) - y.at(k, *ms)).abs())).fold(0.0, f64::max);+ assert!(d >= 0.4, "{with} vs {without}: the tongue body differs by {d:.2} in the first 40 ms");+ }+}++#[test]+fn triphthongs_keep_their_off_glide() {+ for (p, off) in [("guai4", "ɪ"), ("kuai4", "ɪ"), ("you3", "ʊ̠")] {+ let t = sing(&py(p));+ let v: Vec<&str> = t.vowels.iter().map(|x| x.0.as_str()).collect();+ assert_eq!(v.len(), 3, "{p}: glide, held vowel, off-glide: {v:?}");+ assert_eq!(v[2], off);+ // the off-glide is sung: the tongue and jaw leave the held vowel in the note's last part+ let moved = [ArticKey::Jaw, ArticKey::TbY, ArticKey::TbX, ArticKey::LipProt].iter().map(|k| (t.at(*k, 560.0) - t.at(*k, 300.0)).abs()).fold(0.0, f64::max);+ assert!(moved >= 0.15, "{p}: moved {moved:.2} over the off-glide");+ }+}++#[test]+fn a_live_note_sings_the_glide_short_too() {+ use chimera::phonetics::sing::{NoteOnOptions, plan_note_on};+ let g = plan_note_on(&py("hua4"), 50.0, &NoteOnOptions { body: "male".into(), vibrato: 0.0, tag: 10.0, legato_from: None });+ let u = g.iter().find(|g| g.label.as_ref().is_some_and(|l| l.as_str() == "u̠")).expect("the glide u");+ assert!(u.t1 - u.t0 <= 0.06, "the live glide is {} s", u.t1 - u.t0);+}diff --git a/crates/chimera/tests/rising.rs b/crates/chimera/tests/rising.rsindex a7b378e..e1ed7c1 100644--- a/crates/chimera/tests/rising.rs+++ b/crates/chimera/tests/rising.rs@@ -1,34 +1,30 @@-//! Rising diphthongs (Mandarin's medials as one nucleus): sung, the glide comes on the beat and is-//! short, and the second vowel holds; a held melisma continues the vowel, not the glide.+//! Rising diphthongs (Mandarin's medials as one nucleus): sung, the glide is the last of the onset+//! (done by the beat, short) and the second vowel holds from the beat; a held melisma continues the vowel, not the glide.use chimera::phonetics::sing::{SongOptions, SungNote, plan_song};use chimera::phonetics::{Segment, Syllable};fn vowels(nucleus: &str, beats: f64) -> Vec<(String, f64)> {+ vowel_spans(nucleus, beats).into_iter().map(|(i, a, b)| (i, b - a)).collect()+}++/// the vowel parts' (ipa, start, end); the note's beat is at 0.5 s+fn vowel_spans(nucleus: &str, beats: f64) -> Vec<(String, f64, f64)> {let syl = Syllable { text: "x".into(), onset: vec![Segment::new("x")], nucleus: Segment::new(nucleus), word_end: true, ..Default::default() };let p = plan_song(&[SungNote { midi: 57.0, beats, syl }], &SongOptions { body: "male".into(), bpm: 60.0, t0: 0.5, ..Default::default() });- p.segments.iter().filter(|s| s.kind == "vowel").map(|s| (s.ipa.clone(), s.t1 - s.t0)).collect()+ p.segments.iter().filter(|s| s.kind == "vowel").map(|s| (s.ipa.clone(), s.t0, s.t1)).collect()}#[test]fn a_rising_diphthong_sings_a_short_glide_then_holds_its_vowel() {let v = vowels("ua", 2.0);assert_eq!(v.iter().map(|x| x.0.as_str()).collect::<Vec<_>>(), ["u", "a"]);- assert!(v[0].1 <= 0.12 + 1e-9, "the glide is at most 120 ms, got {}", v[0].1);+ // a quick transition (50 ms), not a held vowel of its own (it was up to 120 ms, on the beat)+ assert!(v[0].1 <= 0.06, "the glide is at most 60 ms, got {}", v[0].1);+ // and it ends on the beat (0.5 s): the main vowel is what the beat lands on+ let s = vowel_spans("ua", 2.0);+ assert!((s[0].2 - 0.5).abs() < 1e-9 && (s[1].1 - 0.5).abs() < 1e-9, "{s:?}");assert!(v[1].1 > 1.5, "the vowel holds the note");// a falling diphthong is the other way round: the first vowel holdslet f = vowels("aɪ", 2.0);assert!(f[0].1 > f[1].1);}--#[test]-fn a_syllable_can_say_how_long_its_off_glide_is() {- let glide = |offglide: Option<f64>| {- let syl = Syllable { text: "x".into(), onset: vec![Segment::new("x")], nucleus: Segment::new("aɪ"), word_end: true, offglide, ..Default::default() };- let p = plan_song(&[SungNote { midi: 57.0, beats: 2.0, syl }], &SongOptions { body: "male".into(), bpm: 60.0, t0: 0.5, ..Default::default() });- let v: Vec<f64> = p.segments.iter().filter(|s| s.kind == "vowel").map(|s| s.t1 - s.t0).collect();- v[1] / (v[0] + v[1])- };- // the planner's 20% when unsaid (as before), the syllable's share when said- assert!((glide(None) - 0.2).abs() < 1e-9);- assert!((glide(Some(0.35)) - 0.35).abs() < 1e-9);-}diff --git a/docs/architecture.md b/docs/architecture.mdindex d96486f..430b1bd 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -175,7 +175,10 @@ and the commit history actually cite, and says where they cite nothing.load. The code names Flanagan but no publication.- **Vowel targets** (`phonetics/vowel_data.rs`, `chimera calibrate`): the English vowels arecalibrated to the men's, women's and children's means of Hillenbrand, Getty, Clark & Wheeler- (1995). The other vowels use "typical literature values" whose source isn't recorded.+ (1995). Mandarin's back u `u̠` and ong `ʊ̠` are calibrated to the means of Zee & Lee (2001), "An acoustical+ analysis of the vowels in Beijing Mandarin", Eurospeech 2001, doi 10.21437/Eurospeech.2001-169+ (10 men and 10 women, 5 repetitions each, LPC at the vowel's midpoint). The other vowels use+ "typical literature values" whose source isn't recorded.- **Segment durations** (`phonetics/durations.rs`): Klatt's (1979) duration rules as given forMITalk in Allen, Hunnicutt & Klatt (1987), ch. 9.- **Gestures** (`control/score.rs`, `control/articulators.rs`, `phonetics/planner.rs`): the codediff --git a/docs/language-front-ends.md b/docs/language-front-ends.mdindex 9f9f19b..ca1843a 100644--- a/docs/language-front-ends.md+++ b/docs/language-front-ends.md@@ -7,7 +7,7 @@ lyrics ──► router ──► FRONT END ──► syllables ──► BACK E(by script) English: CMUdict (IPA, with what the planner, the airway,Korean: Hangul rules the language the voice: the same forMandarin: pinyin lexicon decides: aspiration, every language- Pinyin: typed with tones tones as pitch bends)+ Pinyin: typed with tones consonant lengths)Russian: spelling rulesexplicit syllables```@@ -69,19 +69,24 @@ it, untried) and the stiff voice of tense stops. A Korean speaker's ear is stillHan characters are read through a lexicon of character and phrase readings (MIT-licensed pinyindata, `tools/build-mandarin.ts`), longest phrase first: 银行 is yín háng, 行走 xíng zǒu. Then:-- **Tone changes:** third-tone sandhi inside a phrase (你好 sings ní hǎo), and 不 and 一 before a+- **Tone changes:** third-tone sandhi inside a phrase (你好 reads ní hǎo), and 不 and 一 before afourth tone (不会 bú huì, 一个 yí gè).- **Aspiration said:** p t k q ch c are aspirated with Mandarin's longer aspiration (`vot` 90 ms),b d g j zh z voiceless and unaspirated, not voiced stand-ins.-- **Tones as pitch bends** (below): 2 scoops up from below, 3 starts low, 4 starts a little high and- falls off the end, 1 and the neutral tone stay on the note. The melody stays as written.-- **Medials inside the vowel:** 话 is the rising diphthong `ua` and 鸟 the three-part `iaʊ`, sung as a- short glide on the beat, rather than a glide squeezed before the beat with the consonants.-- **Mandarin's own vowels:** the apical vowels ɿ (四) and ʅ (是), eng [ɤŋ], uo [uɔ], ou [əʊ].-- **Timing:** nasal codas held long enough to tell -n from -ng, j zh z with short frication, n m f- long enough to hear; the off-glide of ai ao ei ou over the note's last 35%.-- **Before a nasal coda** the vowel nasalises over its last 40% (at most 0.25 s), and before -ng- after ɑ the tongue body rises toward the velum.+- **Tones are read and not sung:** a song follows its melody. The reading keeps its tones (they+ decide the sandhi above and the neutral tone's reduced vowel), and no syllable bends the pitch+ for them. A native listener compared a nursery song and a greeting sung as written and with+ each tone drawn on the note as a contour, at half and at full depth, and chose the melody as+ written wherever there was one: "flat sounds sung, the full tones sound spoken, half sounds+ odd". Drawing them is for speech (#48).+- **Medials inside the vowel:** 话 is the rising diphthong `u̠a` and 鸟 the three-part `iaʊ̠`: the+ medial is a 50 ms glide that ends on the beat, after the initial consonant.+- **Mandarin's own vowels:** the apical vowels ɿ (四) and ʅ (是), the back u `u̠` (乌, and the medial+ of 话 朵 光) and ong's `ʊ̠` (东, and the off-glide of ao ou), er [əɚ] (二 [aɚ]), eng [ɤŋ], uo [u̠ɔ],+ ou [əʊ̠].+- **Rhymes close in one movement:** the off-glide of ai ei ao ou, and -n / -ng, are where the vowel+ ends up at the end of the note, not a part held after it (`closing`, below).+- **Timing:** j zh z with short frication, n m f long enough to hear, -n 70 ms and -ng 80 ms.- **Erhua:** 一点儿 sings 一 + 点儿, one syllable ending in ɻ; a 儿 that is a word's own syllable(女儿, 儿子) stays one.- **A vowel-initial syllable** (爱, 安) starts with a soft glottal catch, so it doesn't run into the@@ -115,8 +120,65 @@ What each choice measured, on the scramble test (#80) where it was tuned:The last row is measured with #80's corrected judge (this branch, 8 scrambles × 2 voices); theothers on #34 before that fix, so compare within a row. Now: **25.9% / 27.2%** scrambled (male /female) and 10% / 15% on the real poems. What's left: tone 3 (about half wrong, mostly heard as 4;-a dip in the middle or a 214 measured no better), the sibilants (c heard as ch) and in/ing. A-Mandarin speaker's ear is still wanted.+a dip in the middle or a 214 measured no better), the sibilants (c heard as ch) and in/ing.++These numbers were measured before the changes in "By a native speaker's ear" below, with the+tones drawn as held bends and the endings held. As it ships, with no tones drawn and the rhymes+closing in one movement: **37.8% / 39.7%** scrambled (male / female) and 12.5% / 15.0% on the+real poems (8 scrambles × 2 voices, on Windows). On the same machine #85's head reads 25.0% /+27.8% and 7.5% / 15.0%, and Korean and English read the same on both builds to the digit+(52.8 / 53.4% and 68.0 / 73.5% scrambled; their 36 renders are byte-identical), within 2.2+points of the table below. So the recogniser scores this 12 points worse than the version the+native listener called "a foreigner speaking Chinese"; the listener chose this one. Of the+scrambled syllables it heard, the wrong initials went from 19% to 29% (s as sh 13 of 15 times,+as before; sh as f, ch as h), the wrong finals from 15% to 23% (uang as ang or uan, i as e, eng+as ong), the wrong tones from 34% to 48%. Which of the changes cost the initials is not known.+It listens at 16 kHz, so it hears nothing of a sibilant above 8 kHz.++### By a native speaker's ear++A native Mandarin speaker listened to the front end above, and again after each round of changes.+Their reports, in order:++1. The singing sounds like a foreigner speaking Chinese.+2. After the first four rows below: a little better, still a foreigner, heard at once.+3. Every compound and nasal rhyme is two sounds where Mandarin has one, "ang comes out as an ++ ng", and they are all drawn out.+4. After that row: much better, it is one sound now; but single syllables all sound like a second+ tone.++The first report named no sound, so the renders were given to language models to say what they+heard ("model" below), and what they named was measured. Everything was measured in+the render (level, LPC formants, the articulator tracks, the pitch) and fixed in the front end or+in what a front end can ask of the singer. English, Korean and Russian plan exactly as before (the+goldens are untouched). One thing is not opt-in: any rising nucleus sings its glide before the+beat; only the Mandarin front end writes one.++| Reported | By | Measured | Now | Test |+|---|---|---|---|---|+| 两 as *li-ang*, 快 as *ku-ai* | model | the medial sat on the beat for 80-100 ms; the main vowel 90% reached 200 ms after it | a 50 ms glide ending on the beat; 80-90 ms | `medials.rs` |+| the tones laid over the tune | model, then the native speaker's choice | every 2nd and 3rd tone scooped up from 3.5-4 semitones below, every 4th dropped 4 at its end | no tone is drawn: a song follows its melody | `mandarin.rs` |+| 二, 耳 as an American "er" | model | /ɝ/ held still | a central vowel moving into the r-colouring, 二 more open | `er.rs` |+| 只 as zhu, zhe or zhi | model | ɿ ʅ fitted to formants alone: lips narrowed to 0.2, no tongue tip | the sibilant's tip held open, lips spread, by the calibrator | `apical.rs` |+| still a foreigner (report 2) | native speaker | the largest distance from Beijing speakers' vowels: u and ong's F2 997 and 1126 Hz (men) against 661 and 730 (Zee & Lee 2001) | `u̠` 649 Hz, `ʊ̠` 765 Hz | `mandarin_u.rs`, `mandarin_ong.rs` |+| every compound and nasal rhyme two sounds: "ang is an + ng" (report 3) | native speaker | 奥 for 1.33 s: [a] still 0.76 s, a jump, [ʊ] still 0.35 s. 昂: an oral [ɑ], a 40 ms jump of the tongue body, 0.4 s of murmur. A phrase's last -n let go into a vowel | one movement into the ending over the note's last 0.2 s at most; the velum lowers gradually; the tongue body approaches the coda's place; a final coda stays closed | `mandarin_rhymes.rs` |+| every single syllable "a second tone" (report 4) | native speaker | each was one flat note; drawn as #85's held bends, 2 and 3 were one shape (low, then a jump to the note) | nothing in a song (the row above). Each tone as its own contour through the syllable was what the listener then heard as "like normal speech" on one pitch; it waits for speech (#48) | |++The same listener's verdict on the result: much improved, and still not a native speaker. What is+known to be wrong, with where it was measured:++- **Vowel qualities still lean English.** Against Zee & Lee's means for Beijing speakers: a's F1+ is 20-25% low (the model's jaw and lip range ends before it), o's F2 23% high, e [ɤ]'s F2 14-18%+ high, en and eng's F1 16-34% low, i and y's F2 7-12% low.+- **No tones.** On a melody that is the listener's choice. On one pitch, with no melody, the+ same listener heard the flat version as "speech with something wrong" and the tones drawn in+ full as "like normal speech": that is Speak's to do (#48), with declination, the neutral tone+ following the tone before it, and neighbouring tones leaning on each other, none of which a+ table of citation shapes has.+- **Aspirated affricates** (q ch c) have a silent gap between the frication and the vowel.+- **Rhythm is the notes'.** Nothing speaks Mandarin: Speak doesn't read it, and its timing and+ intonation come with #48.+- **Live notes** (a key pressed, the plugin) don't sing the closing rhyme.## The one format@@ -134,13 +196,28 @@ Every front end writes the same thing, one sung syllable per sounding note:millisecond; the measured voice onset also depends on the place and the voice (the Korean tableabove: 45 asked gives 53–69 ms, 90 gives 96–110).- `nucleus`: one vowel, or a diphthong the planner knows. Falling ones (aɪ eɪ aʊ oʊ ɔɪ əʊ) hold- their first vowel and glide off at the note's end; rising ones (ia iɛ iɑ iʊ ua uo uɔ uɑ uə yɛ) sing- a short glide on the beat (a quarter of the vowel, at most 120 ms) and hold the second;- triphthongs (iaʊ iəʊ uaɪ ueɪ) do both. The apical vowels ɿ ʅ are calibrated vowels too.+ their first vowel and glide off at the note's end; rising ones (ia iɛ iɑ iʊ ua uo uɔ uɑ uə yɛ, with+ Mandarin's back u and ʊ: u̠a u̠ɔ u̠ɑ u̠ə iʊ̠, and er's əɝ aɝ) sing+ the first vowel as a quick glide of 50 ms that ends on the beat, after the initial consonant, so+ the second vowel holds from the beat; triphthongs (iaʊ iəʊ uaɪ ueɪ, and iaʊ̠ iəʊ̠ u̠aɪ u̠eɪ) do both. The glide is not held+ on the beat: sung there as a vowel of its own (it was a quarter of the vowel, at most 120 ms) the+ jaw and tongue sat at its posture for 80-100 ms and the main vowel was 90% reached 200 ms after+ the beat, and listening diagnoses of the renders heard 两 as *li-ang* and 快 as *ku-ai*. Now it is 90% reached+ 80-90 ms after the beat (50 ms without a medial), `tests/medials.rs`. The apical vowels ɿ ʅ are+ calibrated vowels too.- A consonant may say its sung `"dur"` (s); unsaid, its spoken length × 0.8.- `pitch`: bends at the note's start, middle or end (below).-- `nasalLead`: nasalise this fraction of the vowel before a nasal coda (unsaid: none).-- `offglide`: the share of a falling diphthong's note its off-glide takes (unsaid: 20%).+- `nasalLead`: on a closing rhyme (`closing`), nasalise this fraction of the vowel before its+ nasal coda (unsaid: none).+- `closing`: the rhyme's ending is one closing movement at the end of the note, this long at most+ (seconds; Mandarin says 0.2), instead of a part of its own. A falling off-glide then takes at+ most that long and at most 60% of the vowel, half of it the glide coming in and half the vowel+ letting go, so neither is held. Before a nasal coda the velum lowers gradually over the+ nasalised part and is open 60 ms before the closure (later, 东's close vowel was a stop for a+ moment), the tongue body moves toward the coda over the vowel's last 150 ms (up for -ng, back+ from a front vowel, forward and up for -n: what tells 安 from 昂 before the closure), and a+ phrase's last coda stays closed until the voice has faded. Unsaid: the off-glide holds the last+ 20% of the note and the coda is a consonant after the vowel.- A melisma note is `"melisma": true` with the same nucleus; its coda moves to the run's last note.- `text` is what the lyrics panel and the piano roll show.- `wordEnd` and `phraseEnd` may be left out (false).@@ -162,8 +239,9 @@ Tones, pitch accent or a scoop need the pitch to move inside a note (#32 step 4)The melody stays as written; a bend only colours part of the note. A start bend begins in theonset, so the consonants already sing its pitch and a rise starts low rather than at the note. Amiddle bend is centred on the vowel (a dip or a peak inside it). A melisma continues at its written-pitches. The planner draws bends without knowing what they mean: a language's tones are a table in-its front end (Mandarin's is `tone_bends`). A syllable without bends sings exactly as before.+pitches. The planner draws bends without knowing what they mean. A syllable without bends sings+exactly as before, and no built-in front end writes one now: Mandarin's tones were bends, and+its listener chose the melody as written (above).## Adding a language@@ -228,6 +306,6 @@ in for a native listener; the test says where to look and whether a change movedbuilt on the one front-end list (#40).- **Bends on live notes:** a key pressed in Sing or a note from the plugin (`plan_note_on`) singsthe note's pitch.-- **Tones in speech:** Speak doesn't read Mandarin yet; its tone contours and speech tuning come+- **Tones in speech:** Speak doesn't read Mandarin yet; the tones' contours and speech tuning comenext, from #48, onto this front end.- **IPA tone letters** (`˥˩`, #52) don't write bends yet.diff --git a/src/ui/analysis.ts b/src/ui/analysis.tsindex 4606638..17e0854 100644--- a/src/ui/analysis.ts+++ b/src/ui/analysis.ts@@ -7,8 +7,10 @@ import { airwayModel, dropAirwayModel, airwayFrame, airwayAreas, airwayTransfer,import { bodyWeights, type BodyMix } from "./body.ts";-/** apical vowels: sung, but not points in the vowel space */-const APICAL = new Set(["ɿ", "ʅ"]);+/** Mandarin-only vowels, which the planner sings but the vowel space leaves out: the apical vowels ɿ ʅ+ * (a consonant's tongue held open, not a point among the vowels) and the retracted u̠ ʊ̠ (Beijing back u and ong, F2 ~660 and+ * ~730 Hz), which would sit on top of the English u ʊ the map is drawn for. */+const NOT_ON_THE_MAP = new Set(["ɿ", "ʅ", "u̠", "ʊ̠"]);export interface VowelPoint {ipa: string;@@ -45,9 +47,9 @@ export class VoiceModel {const parts = bodyWeights(body).filter(([, w]) => w > 0).map(([n, w]) => ({ w, table: VOWEL_TARGETS[n] ?? {} }));- // the vowel space (chart, pad, readouts) leaves out the apical vowels ɿ ʅ (Mandarin 四 si, 是 shi):- // a consonant's tongue held open, not a point among the vowels; the planner still sings them- this.vowels = VOWELS.filter((v) => !APICAL.has(v.ipa) && parts.every((p) => p.table[v.ipa])).map((v) => {+ // the vowel space (chart, pad, readouts) leaves out the Mandarin-only vowels (NOT_ON_THE_MAP);+ // the planner still sings them+ this.vowels = VOWELS.filter((v) => !NOT_ON_THE_MAP.has(v.ipa) && parts.every((p) => p.table[v.ipa])).map((v) => {const at = (f: (t: (typeof parts)[number]["table"][string]) => number | undefined) => {let acc = 0, ws = 0;for (const p of parts) {diff --git a/src/wasm/types.ts b/src/wasm/types.tsindex a9441f8..9f1f9c8 100644--- a/src/wasm/types.ts+++ b/src/wasm/types.ts@@ -165,6 +165,8 @@ export interface Segment {palatalized?: boolean;/** breathy voice: a voiced stop or affricate's release (IPA ʱ), or a vowel (combining diaeresis below) */breathy?: boolean;+ /** a vowel that is a glide off the vowel before it, reached over this long (s): one movement, not a second held vowel */+ glide?: number;}/** What the engine will not say as written in a piece of IPA text (see `skippedIpa`). */@@ -209,10 +211,10 @@ export interface Syllable {phraseEnd: boolean;/** pitch bends inside the sung note, written by the syllable's front end (a tone, an accent) */pitch?: Bend[];- /** nasalise this fraction of the vowel before a nasal coda (unset: none) */+ /** nasalise this fraction of the vowel before a closing rhyme's nasal coda (see `closing`; unset: none) */nasalLead?: number;- /** the share of a falling diphthong's note its off-glide takes (unset: 20%) */- offglide?: number;+ /** the rhyme's ending (an off-glide, a nasal coda) is one closing movement at the note's end, this long at most (s); unset: a held part */+ closing?: number;}/** A bend of the pitch inside a sung note: `st` semitones, at its vowel's start or end, over `len` of the vowel (at most `max` s). */