garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /speech/src/phonemes.rs

raw

//! The sounds both languages are spoken with, and what makes each one.
//!
//! The symbols are SAMPA's, the way phoneticians write sounds in plain
//! ASCII: `i` as in "see" (Dutch "ie"), `I` as in "sit", `{` as in "cat",
//! `V` as in "cup", `3` as in "bird", `@` the weak vowel of "about" and of
//! Dutch "de"; `2:` is Dutch "eu", `9y` Dutch "ui", `y` Dutch "uu", `x` and
//! `G` the Dutch "ch" and "g"; `T` and `D` are the two English "th", `S`
//! "sh", `N` "ng"; `P` is a pause. A word is written as its symbols with
//! spaces between, and a `'` before the vowel that carries the stress.
//!
//! What a sound is to the synthesizer is a handful of numbers: how long it
//! lasts at most and at least, the three lowest resonances of the mouth
//! (the formants F1, F2 and F3, which are what make one vowel differ from
//! another), whether the voice sounds in it, and for the hissing sounds
//! the shape of their noise. The vowel formants are the classic measured
//! averages of men's voices: Peterson and Barney's for the English vowels,
//! Pols, Tromp and Plomp's for the Dutch; the consonants' are the points
//! the formants of a neighbouring vowel bend towards (their "loci"), as in
//! Klatt's synthesizer. One inventory serves both languages, so a sound
//! the two share, such as `E` in "bed" and Dutch "bed", is one sound.

use alloc::vec::Vec;

use crate::Sound;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Class {
    /// A vowel or a diphthong: the voice through an open mouth.
    Vowel,
    /// `l r w j`: voiced, the mouth narrowed but open, and gliding.
    Glide,
    /// `m n N`: the voice through the nose, the mouth closed.
    Nasal,
    /// Noise from air forced through a narrow place, voiced or not.
    Fricative,
    /// A closure, then a burst when it opens: `p t k b d g`.
    Stop,
    /// A closure that opens into a fricative: `tS dZ`.
    Affricate,
    /// `h`: breath through the shape of the vowel that follows.
    Aspirate,
    /// Silence.
    Pause,
}

/// The noise of a fricative or a burst: two resonances, each with its
/// loudness, and a share of plain unfiltered noise.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Frication {
    pub freq: [f32; 2],
    pub bw: [f32; 2],
    pub gain: [f32; 2],
    pub flat: f32,
}

impl Frication {
    pub const NONE: Frication = Frication {
        freq: [1500.0, 3000.0],
        bw: [500.0, 500.0],
        gain: [0.0, 0.0],
        flat: 0.0,
    };

    /// The same noise, quieter: the voiced twin of a voiceless sound.
    const fn times(self, k: f32) -> Frication {
        Frication {
            gain: [self.gain[0] * k, self.gain[1] * k],
            flat: self.flat * k,
            ..self
        }
    }
}

#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Phoneme {
    pub symbol: &'static str,
    pub class: Class,
    pub voiced: bool,
    /// Its formants glide from `start` to `end` (a diphthong).
    pub diphthong: bool,
    /// Its velar sounds (`k g N`) take their formants from the vowel beside
    /// them: the tongue meets the palate wherever that vowel has it.
    pub velar: bool,
    /// Its length in milliseconds when stressed, and the shortest it gets.
    pub length: f32,
    pub shortest: f32,
    /// F1, F2, F3 in Hz at its start and its end.
    pub start: [f32; 3],
    pub end: [f32; 3],
    pub frication: Frication,
}

const fn sound(symbol: &'static str, class: Class, length: f32, shortest: f32, f: [f32; 3]) -> Phoneme {
    Phoneme {
        symbol,
        class,
        voiced: true,
        diphthong: false,
        velar: false,
        length,
        shortest,
        start: f,
        end: f,
        frication: Frication::NONE,
    }
}

const fn vowel(symbol: &'static str, length: f32, shortest: f32, f: [f32; 3]) -> Phoneme {
    sound(symbol, Class::Vowel, length, shortest, f)
}

const fn diphthong(
    symbol: &'static str,
    length: f32,
    shortest: f32,
    from: [f32; 3],
    to: [f32; 3],
) -> Phoneme {
    Phoneme {
        diphthong: true,
        end: to,
        ..sound(symbol, Class::Vowel, length, shortest, from)
    }
}

/// A vowel that moves a little towards a closer one, as Dutch "ee", "oo"
/// and "eu" do: written as a diphthong, but not one to the ear.
const fn closing(symbol: &'static str, length: f32, shortest: f32, from: [f32; 3], to: [f32; 3]) -> Phoneme {
    diphthong(symbol, length, shortest, from, to)
}

const fn noisy(
    symbol: &'static str,
    class: Class,
    voiced: bool,
    timing: [f32; 2],
    f: [f32; 3],
    frication: Frication,
) -> Phoneme {
    Phoneme {
        voiced,
        frication,
        ..sound(symbol, class, timing[0], timing[1], f)
    }
}

const fn hiss(freq: [f32; 2], bw: [f32; 2], gain: [f32; 2], flat: f32) -> Frication {
    Frication { freq, bw, gain, flat }
}

const fn velar(p: Phoneme) -> Phoneme {
    Phoneme { velar: true, ..p }
}

// The noise of each place in the mouth. "s" is the brightest and loudest,
// a narrow peak high up; "sh" lower and broader; "f" and "th" weak and
// flat; the Dutch "ch" a rough noise low down, near the back of the mouth.
const S: Frication = hiss([5300.0, 7000.0], [800.0, 1200.0], [0.9, 0.35], 0.02);
const SH: Frication = hiss([2700.0, 4200.0], [450.0, 900.0], [0.85, 0.45], 0.02);
const F: Frication = hiss([6500.0, 3000.0], [2000.0, 2000.0], [0.15, 0.04], 0.12);
const TH: Frication = hiss([5500.0, 2600.0], [2000.0, 1000.0], [0.15, 0.05], 0.1);
const CH: Frication = hiss([1500.0, 3000.0], [600.0, 1500.0], [0.55, 0.25], 0.05);
// The bursts of the stops: the lips' low and soft, the tongue tip's high,
// the back of the tongue's at the neighbouring vowel's F2 (set per word).
const P_BURST: Frication = hiss([1100.0, 2500.0], [900.0, 1500.0], [0.35, 0.1], 0.15);
const T_BURST: Frication = hiss([4200.0, 6000.0], [1200.0, 1500.0], [0.85, 0.35], 0.05);
const K_BURST: Frication = hiss([2000.0, 3300.0], [600.0, 1000.0], [0.8, 0.25], 0.05);

const LIPS: [f32; 3] = [250.0, 1000.0, 2100.0];
const TIP: [f32; 3] = [250.0, 1700.0, 2650.0];
const BACK: [f32; 3] = [280.0, 1900.0, 2500.0];

use Class::{Affricate, Aspirate, Fricative, Glide, Nasal, Pause, Stop};

/// Every sound, the pause first.
static PHONEMES: &[Phoneme] = &[
    sound("P", Pause, 0.0, 0.0, [500.0, 1500.0, 2500.0]),
    // The vowels.
    vowel("i", 160.0, 60.0, [280.0, 2250.0, 2900.0]),
    vowel("I", 135.0, 45.0, [400.0, 1950.0, 2550.0]),
    closing(
        "e:",
        200.0,
        100.0,
        [400.0, 2050.0, 2600.0],
        [340.0, 2200.0, 2650.0],
    ),
    vowel("E", 150.0, 70.0, [550.0, 1770.0, 2490.0]),
    vowel("{", 230.0, 80.0, [680.0, 1720.0, 2410.0]),
    vowel("a:", 220.0, 100.0, [780.0, 1300.0, 2500.0]),
    vowel("A", 170.0, 75.0, [720.0, 1100.0, 2450.0]),
    vowel("O", 190.0, 80.0, [560.0, 870.0, 2550.0]),
    closing("o:", 210.0, 90.0, [470.0, 920.0, 2450.0], [400.0, 820.0, 2400.0]),
    vowel("u", 180.0, 70.0, [320.0, 870.0, 2250.0]),
    vowel("U", 160.0, 60.0, [450.0, 1050.0, 2250.0]),
    vowel("@", 110.0, 50.0, [500.0, 1450.0, 2450.0]),
    vowel("y", 170.0, 70.0, [300.0, 1750.0, 2200.0]),
    vowel("Y", 140.0, 60.0, [440.0, 1500.0, 2350.0]),
    closing(
        "2:",
        210.0,
        90.0,
        [440.0, 1500.0, 2250.0],
        [390.0, 1550.0, 2250.0],
    ),
    vowel("V", 140.0, 60.0, [640.0, 1200.0, 2400.0]),
    vowel("3", 180.0, 80.0, [480.0, 1350.0, 1700.0]),
    // The diphthongs: from the first vowel to the second.
    diphthong(
        "aI",
        250.0,
        150.0,
        [720.0, 1250.0, 2500.0],
        [380.0, 2000.0, 2600.0],
    ),
    diphthong(
        "aU",
        260.0,
        100.0,
        [720.0, 1250.0, 2500.0],
        [430.0, 900.0, 2350.0],
    ),
    diphthong(
        "OI",
        280.0,
        150.0,
        [540.0, 850.0, 2450.0],
        [390.0, 1950.0, 2550.0],
    ),
    diphthong(
        "eI",
        200.0,
        100.0,
        [500.0, 1900.0, 2550.0],
        [330.0, 2200.0, 2700.0],
    ),
    diphthong("oU", 220.0, 80.0, [530.0, 1050.0, 2400.0], [400.0, 850.0, 2350.0]),
    diphthong(
        "Ei",
        220.0,
        110.0,
        [560.0, 1750.0, 2500.0],
        [380.0, 2050.0, 2600.0],
    ),
    diphthong(
        "9y",
        220.0,
        110.0,
        [560.0, 1400.0, 2350.0],
        [380.0, 1700.0, 2250.0],
    ),
    diphthong(
        "Au",
        230.0,
        110.0,
        [700.0, 1150.0, 2450.0],
        [430.0, 850.0, 2300.0],
    ),
    // The stops: their formants are the loci the vowels bend towards.
    noisy("p", Stop, false, [90.0, 50.0], LIPS, P_BURST),
    noisy("b", Stop, true, [85.0, 60.0], LIPS, P_BURST.times(0.5)),
    noisy("t", Stop, false, [80.0, 50.0], TIP, T_BURST),
    noisy("d", Stop, true, [75.0, 50.0], TIP, T_BURST.times(0.5)),
    velar(noisy("k", Stop, false, [85.0, 60.0], BACK, K_BURST)),
    velar(noisy("g", Stop, true, [80.0, 60.0], BACK, K_BURST.times(0.5))),
    // The fricatives.
    noisy("f", Fricative, false, [100.0, 80.0], [340.0, 1100.0, 2100.0], F),
    noisy(
        "v",
        Fricative,
        true,
        [65.0, 40.0],
        [340.0, 1100.0, 2100.0],
        F.times(0.6),
    ),
    noisy("T", Fricative, false, [95.0, 60.0], [320.0, 1400.0, 2600.0], TH),
    noisy(
        "D",
        Fricative,
        true,
        [55.0, 30.0],
        [320.0, 1400.0, 2600.0],
        TH.times(0.5),
    ),
    noisy("s", Fricative, false, [110.0, 60.0], [320.0, 1550.0, 2600.0], S),
    noisy(
        "z",
        Fricative,
        true,
        [80.0, 40.0],
        [320.0, 1550.0, 2600.0],
        S.times(0.6),
    ),
    noisy("S", Fricative, false, [110.0, 80.0], [300.0, 1850.0, 2650.0], SH),
    noisy(
        "Z",
        Fricative,
        true,
        [75.0, 40.0],
        [300.0, 1850.0, 2650.0],
        SH.times(0.6),
    ),
    noisy("x", Fricative, false, [100.0, 70.0], [400.0, 1300.0, 2400.0], CH),
    noisy(
        "G",
        Fricative,
        true,
        [80.0, 50.0],
        [400.0, 1300.0, 2400.0],
        CH.times(0.7),
    ),
    noisy(
        "h",
        Aspirate,
        false,
        [80.0, 30.0],
        [500.0, 1500.0, 2500.0],
        Frication::NONE,
    ),
    // The affricates: a stop's closure opening into a fricative's noise.
    noisy("tS", Affricate, false, [120.0, 80.0], [300.0, 1850.0, 2650.0], SH),
    noisy(
        "dZ",
        Affricate,
        true,
        [100.0, 70.0],
        [300.0, 1850.0, 2650.0],
        SH.times(0.6),
    ),
    // The nasals.
    sound("m", Nasal, 75.0, 60.0, [280.0, 1100.0, 2150.0]),
    sound("n", Nasal, 65.0, 50.0, [280.0, 1600.0, 2600.0]),
    velar(sound("N", Nasal, 95.0, 60.0, [280.0, 1900.0, 2500.0])),
    // The glides: "l" fairly dark, "r" the English one, its F3 low.
    sound("l", Glide, 80.0, 40.0, [330.0, 1050.0, 2800.0]),
    sound("r", Glide, 80.0, 30.0, [330.0, 1100.0, 1450.0]),
    sound("w", Glide, 80.0, 60.0, [300.0, 650.0, 2200.0]),
    sound("j", Glide, 80.0, 40.0, [270.0, 2100.0, 2950.0]),
];

/// The index of the pause in the inventory.
pub const PAUSE: u8 = 0;

/// The sound written `symbol`.
pub fn find(symbol: &str) -> Option<u8> {
    PHONEMES
        .iter()
        .position(|p| p.symbol == symbol)
        .and_then(|i| u8::try_from(i).ok())
}

/// The sound at `index`, as [`find`] gives it.
pub fn get(index: u8) -> &'static Phoneme {
    &PHONEMES[usize::from(index)]
}

/// Whether a sound is a vowel other than the weak `@`: one that can take
/// the stress of a word when nothing says which does.
fn full_vowel(index: u8) -> bool {
    let p = get(index);
    p.class == Class::Vowel && p.symbol != "@"
}

/// The sounds of a word written in the crate's symbols.
///
/// Besides the symbols and the `'` of stress, two marks are understood,
/// which the spelling rules write: `~` stresses the vowel before it (for
/// endings such as "-tion" that put the stress on the syllable before
/// them), and `_` ends an unstressed prefix (Dutch "be-", "ver-"), so that
/// the stress, if nothing else places it, falls after it. With `guess`, a
/// word with no stress marked is stressed on its first full vowel after
/// any such prefix; without it, it stays unstressed, as the little words
/// ("the", "of", "de") of the dictionaries are written to.
pub fn sounds(written: &str, guess: bool) -> Vec<Sound> {
    let mut out: Vec<Sound> = Vec::new();
    let mut marked = false;
    let mut after_prefix = 0;
    for token in written.split_ascii_whitespace() {
        match token {
            "~" => {
                let vowel = out
                    .iter_mut()
                    .rev()
                    .find(|s| get(s.phoneme).class == Class::Vowel);
                if let Some(v) = vowel {
                    v.stressed = true;
                    marked = true;
                }
            }
            "_" => after_prefix = out.len(),
            _ => {
                let (stressed, symbol) = match token.strip_prefix('\'') {
                    Some(rest) => (true, rest),
                    None => (false, token),
                };
                if let Some(phoneme) = find(symbol) {
                    marked |= stressed;
                    out.push(Sound { phoneme, stressed });
                }
            }
        }
    }
    if guess && !marked {
        let first_full = |from: usize| {
            out[from..]
                .iter()
                .position(|s| full_vowel(s.phoneme))
                .map(|k| k + from)
        };
        let pick = first_full(after_prefix)
            .or_else(|| first_full(0))
            .or_else(|| out.iter().position(|s| get(s.phoneme).class == Class::Vowel));
        if let Some(k) = pick {
            out[k].stressed = true;
        }
    }
    out
}

/// A word's sounds written back in symbols, the stressed vowel with its `'`.
pub fn write(sounds: &[Sound], out: &mut alloc::string::String) {
    for (i, s) in sounds.iter().enumerate() {
        if i > 0 {
            out.push(' ');
        }
        if s.stressed {
            out.push('\'');
        }
        out.push_str(get(s.phoneme).symbol);
    }
}

/// How many sounds there are, the pause included.
#[cfg(test)]
pub fn count() -> usize {
    PHONEMES.len()
}

/// Whether every token of `written` is a symbol or a mark the crate knows:
/// for the tests of the dictionaries and the rules.
#[cfg(test)]
pub fn all_known(written: &str) -> bool {
    written
        .split_ascii_whitespace()
        .all(|t| t == "~" || t == "_" || find(t.strip_prefix('\'').unwrap_or(t)).is_some())
}

#[cfg(test)]
mod tests {
    extern crate std;
    use super::*;
    use alloc::string::String;

    fn round_trip(written: &str, guess: bool) -> String {
        let mut out = String::new();
        write(&sounds(written, guess), &mut out);
        out
    }

    #[test]
    fn the_pause_comes_first_and_symbols_are_unique() {
        assert_eq!(get(PAUSE).symbol, "P");
        for (i, p) in PHONEMES.iter().enumerate() {
            assert_eq!(find(p.symbol), Some(i as u8), "{} twice", p.symbol);
            assert!(p.shortest <= p.length, "{}", p.symbol);
        }
    }

    #[test]
    fn stress_marks() {
        assert_eq!(round_trip("s 'E t I N z", false), "s 'E t I N z");
        assert_eq!(round_trip("D @", false), "D @");
        assert_eq!(round_trip("D @", true), "D '@");
        assert_eq!(round_trip("s t eI ~ S @ n", true), "s t 'eI S @ n");
        assert_eq!(round_trip("b @ _ G I n", true), "b @ G 'I n");
        assert_eq!(round_trip("@ b aU t", true), "@ b 'aU t");
        assert_eq!(round_trip("k 'A n q x", false), "k 'A n x");
    }
}