the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Breathy voice: IPA ʱ on a voiced stop and a diaeresis below on a vowel part the folds (#32 step 1)
Sayoaa6c49d10108
diff --git a/crates/chimera/src/phonetics/ipa.rs b/crates/chimera/src/phonetics/ipa.rsindex 1d6809f..8036083 100644--- a/crates/chimera/src/phonetics/ipa.rs+++ b/crates/chimera/src/phonetics/ipa.rs@@ -1,7 +1,7 @@//! IPA string → segments (stress ˈ ˌ, length ː, tie bars, affricates, diphthongs, word gaps).use super::Segment;-use super::inventory::Manner;+use super::inventory::{Manner, PhonemeDef, Voicing};use serde::Deserialize;use std::collections::{HashMap, HashSet};use std::sync::OnceLock;@@ -10,11 +10,12 @@ const VOWEL_CHARS: &str = "iyɨʉɯuɪʏʊeøɘɵɤoəɛœɜɞʌɔæɐaɶɑɒɝconst MULTI: [&str; 10] = ["tʃ", "dʒ", "ts", "dz", "pf", "aɪ", "aʊ", "ɔɪ", "eɪ", "oʊ"];const ALIASES: [(&str, &str); 9] = [("t͡ʃ", "tʃ"), ("d͡ʒ", "dʒ"), ("t͡s", "ts"), ("d͡z", "dz"), ("ɡ", "g"), ("ʧ", "tʃ"), ("ʤ", "dʒ"), ("r̥", "r"), ("ɐ̯", "ɐ")];-/// combining tilde: the vowel before it is nasalized+/// combining tilde and combining diaeresis below: the vowel before them is nasalized, breathyconst NASALIZED: char = '\u{303}';-/// NFC composes these vowels with their tilde into one code point; the tokenizer reads them as the+const BREATHY: char = '\u{324}';+/// NFC composes these vowels with their mark into one code point; the tokenizer reads them as the/// vowel and the mark (those that don't compose, like ɛ̃, arrive as two)-const PRECOMPOSED: [(&str, &str); 6] = [("ã", "a\u{303}"), ("õ", "o\u{303}"), ("ẽ", "e\u{303}"), ("ĩ", "i\u{303}"), ("ũ", "u\u{303}"), ("ỹ", "y\u{303}")];+const PRECOMPOSED: [(&str, &str); 7] = [("ã", "a\u{303}"), ("õ", "o\u{303}"), ("ẽ", "e\u{303}"), ("ĩ", "i\u{303}"), ("ũ", "u\u{303}"), ("ỹ", "y\u{303}"), ("ṳ", "u\u{324}")];fn known() -> &'static HashSet<&'static str> {static K: OnceLock<HashSet<&'static str>> = OnceLock::new();@@ -80,16 +81,28 @@ pub fn tokenize_ipa(input: &str) -> Vec<Segment> {}// palatalization, on a consonant made with a mouth gesture (not a glottal one)if ch == 'ʲ' {- if let Some(last) = out.last_mut().filter(|l| super::inventory::consonants().iter().any(|c| c.ipa == l.ipa && c.manner != Manner::Glottal)) {+ if let Some(last) = out.last_mut().filter(|l| consonant(&l.ipa).is_some_and(|c| c.manner != Manner::Glottal)) {last.palatalized = Some(true);}i += 1;continue;}- // a tilde after the length mark instead of the vowel (ɛː̃)- if ch == NASALIZED && i > 0 && (s[i - 1] == 'ː' || s[i - 1] == ':') {+ // a breathy-voiced release, on a voiced stop or affricate (Hindi bʱ dʱ gʱ)+ if ch == 'ʱ' {+ if let Some(last) = out.last_mut().filter(|l| consonant(&l.ipa).is_some_and(|c| c.voicing == Voicing::Voiced && matches!(c.manner, Manner::Stop | Manner::Affricate))) {+ last.breathy = Some(true);+ }+ i += 1;+ continue;+ }+ // a vowel mark after the length mark instead of the vowel (ɛː̃)+ if (ch == NASALIZED || ch == BREATHY) && i > 0 && (s[i - 1] == 'ː' || s[i - 1] == ':') {if let Some(last) = out.last_mut().filter(|l| is_vowel_token(&l.ipa)) {- last.nasalized = Some(true);+ if ch == NASALIZED {+ last.nasalized = Some(true);+ } else {+ last.breathy = Some(true);+ }}i += 1;continue;@@ -112,17 +125,18 @@ pub fn tokenize_ipa(input: &str) -> Vec<Segment> {tok = ch.to_string();}i += tok.chars().count();- // combining diacritics: the tilde is read, the rest we do not model- let mut nasalized = false;+ // combining diacritics: the tilde and the diaeresis below are read, the rest we do not model+ let (mut nasalized, mut breathy) = (false, false);while i < s.len() && ('\u{300}'..='\u{36F}').contains(&s[i]) {nasalized |= s[i] == NASALIZED;+ breathy |= s[i] == BREATHY;i += 1;}if !known.contains(tok.as_str()) {continue;}let is_v = is_vowel_token(&tok);- out.push(Segment { ipa: tok, stress: Some(if is_v { stress } else { 0 }), nasalized: (is_v && nasalized).then_some(true), ..Default::default() });+ out.push(Segment { ipa: tok, stress: Some(if is_v { stress } else { 0 }), nasalized: (is_v && nasalized).then_some(true), breathy: (is_v && breathy).then_some(true), ..Default::default() });if is_v {stress = 0;}@@ -130,6 +144,10 @@ pub fn tokenize_ipa(input: &str) -> Vec<Segment> {out}+fn consonant(ipa: &str) -> Option<&'static PhonemeDef> {+ super::inventory::consonants().iter().find(|c| c.ipa == ipa)+}+fn is_vowel_token(tok: &str) -> bool {tok.chars().next().is_some_and(|c| VOWEL_CHARS.contains(c)) && !super::inventory::consonant_symbols().contains(&tok)}diff --git a/crates/chimera/src/phonetics/mod.rs b/crates/chimera/src/phonetics/mod.rsindex 105531e..ad77d86 100644--- a/crates/chimera/src/phonetics/mod.rs+++ b/crates/chimera/src/phonetics/mod.rs@@ -45,6 +45,10 @@ pub struct Segment {/// the palate (IPA ʲ); None or false: plain#[serde(default, skip_serializing_if = "Option::is_none")]pub palatalized: Option<bool>,+ /// breathy voice: a voiced stop or affricate released with the folds apart (IPA ʱ), or a+ /// 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>,}impl Segment {diff --git a/crates/chimera/src/phonetics/planner.rs b/crates/chimera/src/phonetics/planner.rsindex ca79954..64810e7 100644--- a/crates/chimera/src/phonetics/planner.rs+++ b/crates/chimera/src/phonetics/planner.rs@@ -173,8 +173,15 @@ struct Seg<'a> {aspirated: Option<bool>,nasalized: Option<bool>,palatalized: Option<bool>,+ breathy: Option<bool>,}+/// glottal abduction of breathy voice: /ɦ/'s, a gap the folds still vibrate across+const BREATHY_ABDUCTION: f64 = 0.1;+/// how long past its release a breathy-voiced stop's folds stay apart (s), at most to the end of+/// the next segment+const BREATHY_RELEASE: f64 = 0.08;+/// velum port area (cm²) of a nasalized vowel, and the ramps of its lowering and raising (s)const NASAL_VOWEL_PORT: f64 = 0.3;const NASAL_VOWEL_RAMP: f64 = 0.04;@@ -203,10 +210,10 @@ pub fn plan_utterance(input: &[Segment], o: &PlanOptions) -> Plan {let base = durs[si];for (i, p) in parts.iter().enumerate() {let dur = if parts.len() > 1 { base * (if i == 0 { 0.55 } else { 0.45 }) } else { base };- segs.push(Seg { ipa: p, dur: Some(dur), stress: s.stress, f0: s.f0, def: None, vowel: None, glide_from: i > 0, aspirated: None, nasalized: s.nasalized, palatalized: None });+ segs.push(Seg { ipa: p, dur: Some(dur), stress: s.stress, f0: s.f0, def: None, vowel: None, glide_from: i > 0, aspirated: None, nasalized: s.nasalized, palatalized: None, breathy: s.breathy });}} 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, nasalized: s.nasalized, palatalized: s.palatalized });+ 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, nasalized: s.nasalized, palatalized: s.palatalized, breathy: s.breathy });}}for s in segs.iter_mut() {@@ -265,10 +272,17 @@ pub fn plan_utterance(input: &[Segment], o: &PlanOptions) -> Plan {stress: if s.vowel.is_some() { Some(s.stress.unwrap_or(0)) } else { None },kind: if s.vowel.is_some() { "vowel".to_string() } else { s.def.map_or("?", |d| d.manner.as_str()).to_string() },});- if s.vowel.is_some() && s.nasalized == Some(true) && !s.glide_from {- // a nasalized vowel: the velum is down for the whole vowel, through a diphthong's glide- let last = (i + 1..segs.len()).take_while(|&j| segs[j].glide_from).last().unwrap_or(i);- gestures.push(Gesture::new(t0, times[last].t1, NASAL_VOWEL_RAMP, NASAL_VOWEL_RAMP, 4.0, one(ArticKey::Velum, NASAL_VOWEL_PORT)).label("velum"));+ if s.vowel.is_some() && !s.glide_from {+ // what a vowel's marks hold for the whole vowel, through a diphthong's glide+ let end = times[(i + 1..segs.len()).take_while(|&j| segs[j].glide_from).last().unwrap_or(i)].t1;+ if s.nasalized == Some(true) {+ // nasalized: the velum is down+ gestures.push(Gesture::new(t0, end, NASAL_VOWEL_RAMP, NASAL_VOWEL_RAMP, 4.0, one(ArticKey::Velum, NASAL_VOWEL_PORT)).label("velum"));+ }+ if s.breathy == Some(true) {+ // breathy: the folds part-open, as for /ɦ/+ gestures.push(Gesture::new(t0, end, 0.03, 0.03, 5.0, one(ControlKey::ABDUCTION, BREATHY_ABDUCTION)).label("breathy"));+ }}let Some(def) = s.def.as_ref() else { continue };let next_vowel = i < segs.len() - 1 && segs[i + 1].vowel.is_some();@@ -334,6 +348,12 @@ pub fn plan_utterance(input: &[Segment], o: &PlanOptions) -> Plan {} else if def.manner == Manner::Fricative {gestures.push(Gesture::new(t0, t1, 0.03, 0.03, 3.0, one(ControlKey::ABDUCTION, 0.035)).label("voiced frication"));}+ // a breathy-voiced release (Hindi bʱ): the folds part as the closure lets go and stay+ // apart into the start of the vowel+ if s.breathy == Some(true) && def.voicing == Voicing::Voiced && matches!(def.manner, Manner::Stop | Manner::Affricate) {+ let until = js_min(t1 + BREATHY_RELEASE, times.get(i + 1).map_or(f64::MAX, |n| n.t1));+ gestures.push(Gesture::new(t1 - 0.02, until, 0.03, 0.03, 5.0, one(ControlKey::ABDUCTION, BREATHY_ABDUCTION)).label("breathy"));+ }// palatalization: the tongue body goes toward /j/ under the consonant, stays there until the// voice returns, and lets go into the vowel, so the release carries the [j]-like transitionif s.palatalized == Some(true) {diff --git a/crates/chimera/src/phonetics/sing.rs b/crates/chimera/src/phonetics/sing.rsindex 56ee989..7124d16 100644--- a/crates/chimera/src/phonetics/sing.rs+++ b/crates/chimera/src/phonetics/sing.rs@@ -28,13 +28,13 @@ fn cdur(ipa: &str, body: BodyMix, k: f64) -> f64 {}fn consonants(segs: &[Segment], body: BodyMix, k: f64) -> Vec<Segment> {- segs.iter().map(|c| Segment { ipa: c.ipa.clone(), dur: Some(cdur(&c.ipa, body, k)), aspirated: c.aspirated, palatalized: c.palatalized, ..Default::default() }).collect()+ segs.iter().map(|c| Segment { ipa: c.ipa.clone(), dur: Some(cdur(&c.ipa, body, k)), aspirated: c.aspirated, palatalized: c.palatalized, breathy: c.breathy, ..Default::default() }).collect()}/// A sung vowel (or one half of a diphthong) at the note's pitch, with the sound marks of the/// syllable's nucleus.fn nucleus_part(ipa: &str, dur: f64, hz: f64, nucleus: &Segment) -> Segment {- Segment { ipa: ipa.to_string(), dur: Some(dur), f0: Some(hz), stress: Some(1), nasalized: nucleus.nasalized, ..Default::default() }+ Segment { ipa: ipa.to_string(), dur: Some(dur), f0: Some(hz), stress: Some(1), nasalized: nucleus.nasalized, breathy: nucleus.breathy, ..Default::default() }}/// Sung consonants at their note's pitch: an onset consonant moves the pitch to the new notediff --git a/crates/chimera/tests/sound_marks.rs b/crates/chimera/tests/sound_marks.rsindex 08b9abb..191530e 100644--- a/crates/chimera/tests/sound_marks.rs+++ b/crates/chimera/tests/sound_marks.rs@@ -3,7 +3,7 @@//! keeps them. Unflagged segments plan exactly as before (the planning goldens). Rendered tests//! are in `sound_marks_acoustic.rs`.use chimera::anatomy::human::{ArticKey, BodyMix};-use chimera::control::score::Gesture;+use chimera::control::score::{ControlKey, Gesture};use chimera::phonetics::ipa::tokenize_ipa;use chimera::phonetics::planner::{PlanOptions, plan_utterance};use chimera::phonetics::sing::{NoteOnOptions, SongOptions, SungNote, plan_note_on, plan_song};@@ -181,6 +181,106 @@ fn the_palatal_posture_holds_until_the_voice_returns() {assert!(end(Some(false)) < t1 + 0.03, "unaspirated: {}", end(Some(false)) - t1);}+fn breathy(s: &Segment) -> Option<bool> {+ s.breathy+}++#[test]+fn a_breathy_release_mark_sets_voiced_stops_and_affricates() {+ assert_eq!(flags("bʱa", breathy), pairs(&[("b", true), ("a", false)]));+ assert_eq!(flags("bʱ dʱ ɡʱ ɖʱ dʒʱ dzʱ", breathy), pairs(&[("b", true), ("d", true), ("g", true), ("ɖ", true), ("dʒ", true), ("dz", true)]));+}++#[test]+fn the_combining_diaeresis_below_makes_a_vowel_breathy() {+ assert_eq!(flags("a\u{324}", breathy), pairs(&[("a", true)]));+ assert_eq!(flags("\u{25B}\u{324}", breathy), pairs(&[("ɛ", true)]));+ // ṳ is one code point after NFC; the length mark may come first (aː̤)+ assert_eq!(tokenize_ipa("\u{1E73}"), tokenize_ipa("u\u{324}"));+ assert_eq!(flags("\u{1E73}", breathy), pairs(&[("u", true)]));+ let long = tokenize_ipa("a\u{2D0}\u{324}");+ assert_eq!((long.len(), long[0].breathy, long[0].dur), (1, Some(true), Some(0.15 * 1.7)));+ // with a nasal mark too, in either order+ for ipa in ["a\u{324}\u{303}", "a\u{303}\u{324}"] {+ let s = tokenize_ipa(ipa);+ assert_eq!((s.len(), s[0].breathy, s[0].nasalized), (1, Some(true), Some(true)), "{ipa:?}");+ }+}++#[test]+fn a_breathy_mark_on_the_wrong_sound_is_ignored() {+ // ʱ: not after a voiceless stop, a fricative, a nasal, a glottal, a vowel, a pause, or alone+ for ipa in ["pʱ", "sʱ", "zʱ", "mʱ", "hʱ", "ɦʱ", "aʱ", "|ʱ", "ʱ", "ʱb"] {+ assert!(tokenize_ipa(ipa).iter().all(|s| s.breathy.is_none()), "{ipa}");+ }+ // the diaeresis below: not on a consonant+ for ipa in ["b\u{324}a", "m\u{324}a", "s\u{324}a", "\u{324}a"] {+ assert!(tokenize_ipa(ipa).iter().all(|s| s.breathy.is_none()), "{ipa:?}");+ }+ assert_eq!(tokenize_ipa("m\u{324}a"), tokenize_ipa("ma"));+}++#[test]+fn the_owners_hindi_pair_now_differs() {+ // पल / फल were both "p ʌ l"; and बल / भल differ by the breathy release+ assert_ne!(tokenize_ipa("pʌl"), tokenize_ipa("pʰʌl"));+ assert_ne!(tokenize_ipa("bʌl"), tokenize_ipa("bʱʌl"));+ assert_ne!(tokenize_ipa("bʌl"), tokenize_ipa("pʰʌl"));+}++#[test]+fn a_breathy_release_parts_the_folds_across_the_release_and_into_the_vowel() {+ let seg = |b| vec![Segment { breathy: b, ..Segment::new("b") }, Segment { stress: Some(1), ..Segment::new("a") }];+ let (modal, soft) = (plan(&seg(None)), plan(&seg(Some(true))));+ assert!(labelled(&modal.gestures, "breathy").is_empty());+ let g = labelled(&soft.gestures, "breathy");+ assert_eq!(g.len(), 1);+ let (stop, vowel) = (&soft.segments[0], &soft.segments[1]);+ // ɦ's abduction, from just before the release to 80 ms after it (the vowel here lasts longer)+ assert_eq!(g[0].targets.get(ControlKey::ABDUCTION), Some(0.1));+ assert!((g[0].t0 - (stop.t1 - 0.02)).abs() < 1e-9 && (g[0].t1 - (stop.t1 + 0.08)).abs() < 1e-9 && vowel.t1 > g[0].t1);+ // a short vowel ends it+ let short = plan(&[Segment { breathy: Some(true), ..Segment::new("b") }, Segment { dur: Some(0.04), ..Segment::new("a") }]);+ assert_eq!(labelled(&short.gestures, "breathy")[0].t1, short.segments[1].t1);+ // nothing else about the plan changes+ let rest = |p: &Plan| serde_json::to_string(&p.gestures.iter().filter(|g| g.label.as_ref().is_none_or(|l| l.as_str() != "breathy")).collect::<Vec<_>>()).unwrap();+ assert_eq!(rest(&modal), rest(&soft));+ // a flag on a sound the mark does not apply to does nothing+ for c in ["p", "s", "m", "ɦ", "l"] {+ let p = plan(&[Segment { breathy: Some(true), ..Segment::new(c) }, Segment::new("a")]);+ assert!(labelled(&p.gestures, "breathy").is_empty(), "{c}");+ }+}++#[test]+fn a_breathy_vowel_parts_the_folds_for_the_whole_vowel() {+ let modal = plan(&tokenize_ipa("pa"));+ let soft = plan(&tokenize_ipa("pa\u{324}"));+ assert!(labelled(&modal.gestures, "breathy").is_empty());+ let g = labelled(&soft.gestures, "breathy");+ assert_eq!(g.len(), 1);+ assert_eq!((g[0].t0, g[0].t1), (soft.segments[1].t0, soft.segments[1].t1));+ assert_eq!(g[0].targets.get(ControlKey::ABDUCTION), Some(0.1));+ // through a diphthong's glide+ let d = plan(&tokenize_ipa("a\u{26A}\u{324}"));+ let g = labelled(&d.gestures, "breathy");+ assert_eq!((g.len(), g[0].t0, g[0].t1), (1, d.segments[0].t0, d.segments[1].t1));+}++#[test]+fn sung_syllables_keep_their_breathiness() {+ let song = |onset: Vec<Segment>, nucleus: Segment| plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: syl(onset, nucleus) }], &SongOptions { body: "male".into(), bpm: 90.0, t0: 0.5, vibrato: 0.0 });+ let live = |onset: Vec<Segment>, nucleus: Segment| plan_note_on(&syl(onset, nucleus), 57.0, &NoteOnOptions { body: "male".into(), vibrato: 0.0, tag: 1.0, legato_from: None });+ let (b, b_soft) = (Segment::new("b"), Segment { breathy: Some(true), ..Segment::new("b") });+ let (a, a_soft) = (Segment::new("a"), Segment { breathy: Some(true), ..Segment::new("a") });+ assert_eq!(labelled(&song(vec![b_soft.clone()], a.clone()).gestures, "breathy").len(), 1);+ assert_eq!(labelled(&song(vec![b.clone()], a_soft.clone()).gestures, "breathy").len(), 1);+ assert!(labelled(&song(vec![b.clone()], a.clone()).gestures, "breathy").is_empty());+ assert_eq!(labelled(&live(vec![b_soft], a.clone()), "breathy").len(), 1);+ assert_eq!(labelled(&live(vec![b.clone()], a_soft), "breathy").len(), 1);+ assert!(labelled(&live(vec![b], a), "breathy").is_empty());+}+#[test]fn a_sung_consonant_keeps_its_palatalization() {let onset = |soft| vec![Segment { palatalized: soft, ..Segment::new("t") }];diff --git a/crates/chimera/tests/sound_marks_acoustic.rs b/crates/chimera/tests/sound_marks_acoustic.rsindex dde0d48..4d06dd0 100644--- a/crates/chimera/tests/sound_marks_acoustic.rs+++ b/crates/chimera/tests/sound_marks_acoustic.rs@@ -4,7 +4,7 @@ use chimera::analysis::fft::{Fft, hann, power_spectrum_db};use chimera::analysis::lpc::{FormantOpts, estimate_formants};use chimera::anatomy::human::{BODY_FEMALE, BODY_MALE, HumanBody};use chimera::phonetics::planner::{PlanOptions, plan_utterance};-use chimera::phonetics::{Plan, Segment};+use chimera::phonetics::{Intonation, Plan, Segment};use chimera::voice::human_voice::{HumanVoice, SourcePatch};const FS: f64 = 48000.0;@@ -24,9 +24,18 @@ struct Rendered {}fn render(segs: &[Segment], body: HumanBody, name: &str, f0: f64) -> Rendered {+ render_with(segs, body, name, f0, Intonation::Statement)+}++/// [`render`] with the pitch held level, so a window of harmonics is not smeared by a fall.+fn render_flat(segs: &[Segment], body: HumanBody, name: &str, f0: f64) -> Rendered {+ render_with(segs, body, name, f0, Intonation::Flat)+}++fn render_with(segs: &[Segment], body: HumanBody, name: &str, f0: f64, intonation: Intonation) -> Rendered {let mut v = HumanVoice::new(FS, body, 2);v.set_source(&SourcePatch::f0(f0));- let plan = plan_utterance(segs, &PlanOptions { body: name.into(), t0: 0.05, f0: Some(f0), ..Default::default() });+ let plan = plan_utterance(segs, &PlanOptions { body: name.into(), t0: 0.05, f0: Some(f0), intonation: Some(intonation), ..Default::default() });v.schedule(&plan.gestures);let mut out = vec![0.0f32; (FS * (plan.end + 0.3)).round() as usize];let (mut port, mut voicing, mut narrowest) = (vec![], vec![], vec![]);@@ -153,6 +162,7 @@ fn a_palatalized_consonant_starts_its_vowel_with_a_high_f2() {println!("{name} /{c}a/ F2 {a:.0} Hz, /{c}ʲa/ F2 {b:.0} Hz at the voice onset");assert!(b > a + rise, "{name} /{c}ʲa/: F2 {b:.0} Hz against {a:.0} Hz plain");let (a, b) = (plain.f2(on_plain + 0.2), pal.f2(on_pal + 0.2));+ println!(" settled: {a:.0} Hz plain, {b:.0} Hz palatalized");assert!((a - b).abs() < 50.0, "{name} /{c}ʲa/: F2 {b:.0} Hz against {a:.0} Hz plain, 200 ms after the voice sets in");}}@@ -180,3 +190,73 @@ fn a_palatalized_stop_still_closes() {}}}++impl Rendered {+ /// How much louder (dB) the harmonics are than the spectrum halfway between them, 2-5 kHz, in+ /// the `LEN` samples centred on t: a harmonics-to-noise measure that falls as breath noise rises.+ /// `f0` is where to look for the pitch; the harmonics are taken from the pitch found there.+ fn harmonic_contrast<const LEN: usize>(&self, t: f64, f0: f64) -> f64 {+ let mid = (t * FS) as usize;+ let x: Vec<f64> = self.out[mid - LEN / 2..mid + LEN / 2].iter().map(|v| *v as f64).collect();+ // the pitch: the lag of the best autocorrelation within 30 % of the planned one+ let (lo, hi) = ((FS / (f0 * 1.3)) as usize, (FS / (f0 * 0.7)) as usize);+ let r = |l: usize| x[..LEN - l].iter().zip(&x[l..]).map(|(a, b)| a * b).sum::<f64>() / x.iter().map(|a| a * a).sum::<f64>();+ let lag = (lo..=hi).max_by(|a, b| r(*a).total_cmp(&r(*b))).unwrap();+ let f0 = FS / lag as f64;+ let db = power_spectrum_db(&x, &Fft::new(LEN), &hann(LEN));+ let df = FS / LEN as f64;+ let peak = |f: f64| ((f - 12.0) / df) as usize..=((f + 12.0) / df) as usize;+ let (mut sum, mut n) = (0.0, 0);+ let mut k = (2000.0 / f0).ceil();+ while (k + 0.5) * f0 < 5000.0 {+ sum += peak(k * f0).map(|b| db[b]).fold(f64::MIN, f64::max) - db[((k + 0.5) * f0 / df) as usize];+ n += 1;+ k += 1.0;+ }+ sum / n as f64+ }+}++#[test]+fn a_breathy_vowel_is_noisier_than_a_modal_one() {+ // Harmonic contrast (dB, 2-5 kHz) in the middle of a held vowel, modal -> breathy:+ // (4096-sample window, level pitch)+ // male /a/ 12.9 -> 7.6, /i/ 18.4 -> 8.8, /ɛ/ 13.4 -> 7.9 (a drop of 5.3 to 9.6)+ // female /a/ 26.4 -> 16.9, /i/ 28.5 -> 17.7, /ɛ/ 28.0 -> 17.0 (a drop of 9.5 to 11.0)+ // (H1-H2 moves by only 0 to 1.7 dB: abduction 0.1 adds breath noise, not much of a tilt.)+ for (body, name, f0) in VOICES {+ for vowel in ["a", "i", "ɛ"] {+ let held = |breathy: bool| {+ let r = render_flat(&[Segment { dur: Some(0.5), breathy: breathy.then_some(true), ..Segment::new(vowel) }], body, name, f0);+ let s = &r.plan.segments[0];+ r.harmonic_contrast::<4096>((s.t0 + s.t1) / 2.0, f0)+ };+ let (modal, soft) = (held(false), held(true));+ println!("{vowel} ({name}): harmonic contrast {modal:.1} dB modal, {soft:.1} dB breathy");+ assert!(modal - soft > 3.0, "{vowel} ({name}): {modal:.1} dB modal, {soft:.1} dB breathy");+ }+ }+}++#[test]+fn a_breathy_release_is_noisy_into_the_vowel_and_then_modal() {+ // /bʱa/ against /ba/: the harmonic contrast after the release (mean of the windows centred+ // 50, 60 and 70 ms after it), and 250 ms after, where the vowel is the same sound again:+ // male 15.0 -> 9.8 dB (a drop of 5.2); female 28.8 -> 22.0 dB (a drop of 6.8)+ for (body, name, f0) in VOICES {+ let say = |breathy: bool| {+ let segs = [Segment { breathy: breathy.then_some(true), ..Segment::new("b") }, Segment { dur: Some(0.4), stress: Some(1), ..Segment::new("a") }];+ render_flat(&segs, body, name, f0)+ };+ let (modal, soft) = (say(false), say(true));+ let release = modal.plan.segments[0].t1;+ let mean = |r: &Rendered| [0.05, 0.06, 0.07].iter().map(|k| r.harmonic_contrast::<4096>(release + k, f0)).sum::<f64>() / 3.0;+ let (a, b) = (mean(&modal), mean(&soft));+ println!("/bʱa/ ({name}): harmonic contrast {a:.1} dB modal, {b:.1} dB breathy, mean of the windows centred 50, 60 and 70 ms after the release");+ assert!(a - b > 3.5, "{name}: {a:.1} dB modal, {b:.1} dB breathy");+ let (a, b) = (modal.harmonic_contrast::<4096>(release + 0.25, f0), soft.harmonic_contrast::<4096>(release + 0.25, f0));+ println!(" 250 ms after: {a:.1} dB modal, {b:.1} dB breathy");+ assert!((a - b).abs() < 0.5, "{name} +250 ms: {a:.1} dB modal, {b:.1} dB breathy");+ assert!(soft.out.iter().all(|x| x.is_finite()) && soft.out.iter().any(|x| x.abs() > 0.01));+ }+}diff --git a/src/wasm/types.ts b/src/wasm/types.tsindex 8619905..b120cbe 100644--- a/src/wasm/types.ts+++ b/src/wasm/types.ts@@ -161,6 +161,8 @@ export interface Segment {nasalized?: boolean;/** a consonant with a secondary palatal gesture, the tongue body raised and fronted (IPA ʲ) */palatalized?: boolean;+ /** breathy voice: a voiced stop or affricate's release (IPA ʱ), or a vowel (combining diaeresis below) */+ breathy?: boolean;}export interface PlannedSegment {