git clone https://garage44.eu/jeroen/pinnacle.git.. /speech/src/synth.rs
//! The voice: sounds made into samples.
//!
//! This is a formant synthesizer in the manner of Klatt's of 1980. Two
//! sources make the sound: the voice, a train of pulses at the pitch of the
//! voice, each the shape of one opening and closing of the vocal folds,
//! and noise, from a small random-number generator. The voice and the
//! breath of an "h" pass through a chain of seven resonators, the formants
//! of the throat and mouth, of which the lowest three move from sound to
//! sound and the top four stand still; a pair of a resonance and an
//! anti-resonance in front of them gives the hum of the nose for `m n N`.
//! The noise of the fricatives and the bursts of the stops passes through
//! two resonators of its own, side by side, which put its energy where the
//! sound has it: high for "s", lower for "sh", spread flat for "f".
//!
//! Each resonator is the two-pole filter `y[n] = A·x[n] + B·y[n-1] +
//! C·y[n-2]`, with `C = -e^(-2π·BW/fs)`, `B = 2·e^(-π·BW/fs)·cos(2π·F/fs)`
//! and `A = 1 - B - C`, which rings at F Hz with a bandwidth of BW Hz.
//!
//! The settings are worked out every 5 ms (a frame) and held or slid
//! between frames. Between two sounds the formants move from one's values
//! to the other's over some tens of milliseconds; for a stop they start
//! from the point the stop's place of closure gives (its locus), partway
//! to the vowel, which is most of what tells "ba" from "da" from "ga". A
//! voiceless stop of English is followed by a breath before the voice
//! starts ("p" in "pin"); Dutch says them without one.
//!
//! The pitch starts near 124 Hz and drifts down through each phrase, rises
//! on each stressed word, and falls at the end of a sentence or climbs at
//! the end of a question. The samples are scaled to a peak at 70 % of the
//! largest value, so nothing ever clips.
use alloc::vec::Vec;
use core::f32::consts::PI;
use crate::math::{cos, exp, sqrt};
use crate::phonemes::{self, Class, Frication, Phoneme};
use crate::{Break, Language, SAMPLE_RATE, Unit};
const RATE: f32 = SAMPLE_RATE as f32;
const FRAME_MS: f32 = 5.0;
/// Samples in a frame.
const FRAME: usize = (SAMPLE_RATE / 200) as usize;
/// The speaking rate, as a factor on every length: above 1 is slower.
/// At 1 the voice says about 11 sounds a second, a little slower than
/// people talk: every sound is given its time, for being understood.
const PACE: f32 = 1.0;
/// Silence before and after the speech, in ms.
const EDGE_MS: f32 = 40.0;
/// The share of each pitch period the vocal folds are open.
const OPEN: f32 = 0.55;
/// The loudness of the breath of an "h" and of aspiration.
const BREATH: f32 = 0.15;
/// The loudness of the noise of fricatives and bursts.
const HISS: f32 = 1.2;
/// The length of a stop's burst, in ms.
const BURST_MS: f32 = 10.0;
/// The nose's resonance, which its anti-resonance cancels outside a nasal.
const NASAL_POLE: f32 = 270.0;
/// The anti-resonance of a nasal: the closed mouth, a side branch of the
/// nose's tube, swallowing the sound around it.
const NASAL_ZERO: f32 = 450.0;
/// The formants above F3, which hardly move: F4 and F5 as in Klatt's
/// synthesizer, and two more that the higher sample rate leaves room for,
/// without which the top of the voice is dull.
const FIXED_FORMANTS: [(f32, f32); 4] = [(3500.0, 250.0), (4500.0, 300.0), (5500.0, 500.0), (6500.0, 700.0)];
/// The highest sample, as a share of the largest an `i16` holds: -3 dB.
const PEAK: f32 = 0.7;
/// One sound placed in time.
#[derive(Clone, Copy)]
struct Segment {
phoneme: &'static Phoneme,
stressed: bool,
/// The stressed vowel of a word that is stressed at all: where the
/// pitch rises.
accent: bool,
/// Which word it is in; a pause is in none.
word: usize,
start: f32,
length: f32,
/// Its formants at its start and its end.
from: [f32; 3],
to: [f32; 3],
frication: Frication,
/// How long it starts with breath instead of voice: the aspiration of
/// the stop before it.
breath: f32,
/// Whether a stop opens with a burst at its end; not before another
/// closure, as in "doctor".
release: bool,
}
impl Segment {
fn of(phoneme: &'static Phoneme, stressed: bool, accent: bool, word: usize) -> Segment {
Segment {
phoneme,
stressed,
accent,
word,
start: 0.0,
length: 0.0,
from: phoneme.start,
to: phoneme.end,
frication: phoneme.frication,
breath: 0.0,
release: true,
}
}
fn class(&self) -> Class {
self.phoneme.class
}
fn end(&self) -> f32 {
self.start + self.length
}
}
/// A stretch of speech between pauses, said with one melody.
struct Phrase {
first: usize,
end: usize,
ending: Break,
}
/// The samples of `units` said in `language`.
pub fn render(units: &[Unit], language: Language) -> Vec<i16> {
let (mut segments, phrases) = segments(units);
if phrases.is_empty() {
return Vec::new();
}
lengths(&mut segments, &phrases, language);
shape_consonants(&mut segments, language);
let mut t = EDGE_MS;
for s in &mut segments {
s.start = t;
t += s.length;
}
let frames = track(&segments, &phrases);
finish(&play(&frames))
}
fn segments(units: &[Unit]) -> (Vec<Segment>, Vec<Phrase>) {
let pause = phonemes::get(phonemes::PAUSE);
let mut out: Vec<Segment> = Vec::new();
let mut phrases = Vec::new();
let mut first = 0;
let mut pending: Option<Break> = None;
for (word, unit) in units.iter().enumerate() {
match unit {
Unit::Word(sounds) => {
// The pause of a break is only made once speech follows
// it: the text's last full stop adds no silence.
if let Some(b) = pending.take() {
let mut p = Segment::of(pause, false, false, usize::MAX);
p.length = if b == Break::Comma { 220.0 } else { 450.0 };
out.push(p);
first = out.len();
}
let vowel = |s: &crate::Sound| phonemes::get(s.phoneme).class == Class::Vowel;
let accent = sounds.iter().position(|s| s.stressed && vowel(s));
for (k, s) in sounds.iter().enumerate() {
out.push(Segment::of(
phonemes::get(s.phoneme),
s.stressed,
accent == Some(k),
word,
));
}
}
Unit::Break(b) => {
if out.len() > first && pending.is_none() {
phrases.push(Phrase {
first,
end: out.len(),
ending: *b,
});
pending = Some(*b);
}
}
}
}
if pending.is_none() && out.len() > first {
phrases.push(Phrase {
first,
end: out.len(),
ending: Break::Stop,
});
}
(out, phrases)
}
/// How long each sound lasts, by the rules of Klatt's duration model in
/// short. A sound has a longest and a shortest length, and each rule that
/// applies takes a share of the way between them: a vowel is cut back
/// outside the last syllable of its phrase (which is drawn out, as speech
/// slows into a pause), outside the last syllable of its word, in a word
/// of more than one syllable, and most of all when it is unstressed; a
/// consonant is cut back next to another consonant, inside its word rather
/// than at its start, and in an unstressed syllable. A vowel before a
/// voiceless consonant is shorter, and in English one before a voiced
/// consonant ending the word longer, which is much of how "bet" and "bed"
/// are told apart.
fn lengths(segments: &mut [Segment], phrases: &[Phrase], language: Language) {
let n = segments.len();
let mut last_syllable = alloc::vec![false; n];
for p in phrases {
if let Some(v) = (p.first..p.end)
.rev()
.find(|&i| segments[i].class() == Class::Vowel)
{
last_syllable[v..p.end].fill(true);
}
}
// Where each sound's word starts and ends.
let mut words = alloc::vec![(0, 0); n];
let mut i = 0;
while i < n {
let word = segments[i].word;
let end = (i..n).find(|&j| segments[j].word != word).unwrap_or(n);
words[i..end].fill((i, end));
i = end;
}
let vowel = |t: &Segment| t.class() == Class::Vowel;
let mut out = Vec::with_capacity(n);
for (i, s) in segments.iter().enumerate() {
let ph = s.phoneme;
if ph.class == Class::Pause {
out.push(s.length);
continue;
}
let (first, end) = words[i];
let word = &segments[first..end];
let prev = if i > first { Some(&segments[i - 1]) } else { None };
let next = if i + 1 < end { Some(&segments[i + 1]) } else { None };
let mut share = 1.0f32;
if vowel(s) {
if !last_syllable[i] {
share *= 0.6;
}
if segments[i + 1..end].iter().any(vowel) {
share *= 0.85;
}
if word.iter().filter(|t| vowel(t)).count() > 1 {
share *= 0.8;
}
if !s.stressed {
// The little words, with no stress at all, are said shortest.
share *= if word.iter().any(|t| t.stressed) { 0.5 } else { 0.4 };
}
} else {
if prev.is_some_and(|t| !vowel(t)) || next.is_some_and(|t| !vowel(t)) {
share *= 0.7;
}
if i > first {
share *= 0.85;
}
// The syllable a consonant belongs to: the vowel after it in its
// word, or for one that ends a word, the vowel before.
let after = segments[i + 1..end].iter().find(|t| vowel(t));
let syllable = after.or_else(|| segments[first..i].iter().rev().find(|t| vowel(t)));
if syllable.is_some_and(|v| !v.stressed) {
share *= 0.7;
}
}
let mut d = ph.shortest + (ph.length - ph.shortest) * share;
if let Some(next) = next.filter(|_| vowel(s)) {
let obstruent = matches!(next.class(), Class::Stop | Class::Fricative | Class::Affricate);
if obstruent && !next.phoneme.voiced {
d *= 0.85;
} else if obstruent && language == Language::English && i + 2 == end {
d *= 1.2;
}
}
if last_syllable[i] && !vowel(s) {
d *= 1.2;
}
out.push(d * PACE);
}
for (s, d) in segments.iter_mut().zip(out) {
s.length = d;
}
}
/// What a consonant takes from its neighbours: an "h" the shape of its
/// vowel, a velar its place on the palate, a stop its burst and in English
/// the breath after it.
fn shape_consonants(segments: &mut [Segment], language: Language) {
let open = |t: Option<Segment>| t.filter(|t| matches!(t.class(), Class::Vowel | Class::Glide));
for i in 0..segments.len() {
let ph = segments[i].phoneme;
let prev = i.checked_sub(1).map(|k| segments[k]);
let next = segments.get(i + 1).copied();
if ph.class == Class::Aspirate {
let shape = open(next).map(|t| t.from).or_else(|| open(prev).map(|t| t.to));
if let Some(f) = shape {
segments[i].from = f;
segments[i].to = f;
}
}
if ph.velar {
let f2 = open(next)
.map(|t| t.from[1])
.or_else(|| open(prev).map(|t| t.to[1]));
if let Some(f2) = f2 {
let locus = (f2 + 200.0).clamp(1300.0, 2400.0);
let s = &mut segments[i];
s.from[1] = locus;
s.to[1] = locus;
s.from[2] = s.from[2].max(locus + 500.0);
s.to[2] = s.from[2];
s.frication.freq[0] = locus;
}
}
if ph.class == Class::Stop {
let into = next.map(|t| t.class());
segments[i].release = !matches!(into, Some(Class::Stop | Class::Affricate));
let after_s = prev.is_some_and(|p| p.word == segments[i].word && p.phoneme.symbol == "s");
if language == Language::English && !ph.voiced && !after_s && open(next).is_some() {
let vowel = segments[i + 1..]
.iter()
.take(3)
.find(|t| t.class() == Class::Vowel);
let breath = if vowel.is_some_and(|v| v.stressed) {
55.0
} else {
35.0
};
segments[i + 1].breath = breath;
segments[i + 1].length += 0.5 * breath;
}
}
}
}
/// The settings of one frame.
#[derive(Clone, Copy)]
struct Frame {
f0: f32,
voice: f32,
breath: f32,
hiss: f32,
formants: [f32; 3],
bandwidths: [f32; 3],
nasal_zero: f32,
frication: Frication,
}
/// How loud each source is.
#[derive(Clone, Copy)]
struct Source {
voice: f32,
breath: f32,
hiss: f32,
}
impl Source {
const QUIET: Source = Source {
voice: 0.0,
breath: 0.0,
hiss: 0.0,
};
}
fn track(segments: &[Segment], phrases: &[Phrase]) -> Vec<Frame> {
let end = segments.last().map_or(0.0, Segment::end) + EDGE_MS;
let count = (end / FRAME_MS) as usize + 1;
let mut frames = Vec::with_capacity(count);
let mut s = 0;
let mut p = 0;
let mut bandwidths = [80.0, 100.0, 140.0];
let mut nasal_zero = NASAL_POLE;
for k in 0..count {
let t = k as f32 * FRAME_MS;
while s + 1 < segments.len() && t >= segments[s].end() {
s += 1;
}
while p + 1 < phrases.len() && t >= segments[phrases[p + 1].first].start {
p += 1;
}
let seg = &segments[s];
let local = (t - seg.start).clamp(0.0, seg.length);
let inside = t >= seg.start && t < seg.end();
// Bandwidths and the nasal anti-resonance slide, not jump, so that
// a nasal fades in and out of its vowels.
let (want, zero) = damping(seg, local);
for (b, w) in bandwidths.iter_mut().zip(want) {
*b += 0.5 * (w - *b);
}
nasal_zero += 0.5 * (zero - nasal_zero);
let source = if inside {
source(segments, s, local)
} else {
Source::QUIET
};
frames.push(Frame {
f0: pitch(segments, &phrases[p], t),
voice: source.voice,
breath: source.breath,
hiss: source.hiss,
formants: formants(segments, s, local),
bandwidths,
nasal_zero,
frication: seg.frication,
});
}
frames
}
fn mix(a: [f32; 3], b: [f32; 3], w: f32) -> [f32; 3] {
core::array::from_fn(|i| a[i] + (b[i] - a[i]) * w)
}
fn smoothstep(x: f32) -> f32 {
let x = x.clamp(0.0, 1.0);
x * x * (3.0 - 2.0 * x)
}
/// The formants `local` ms into segment `s`: its own targets, bent at
/// either end towards where it meets its neighbour.
fn formants(segments: &[Segment], s: usize, local: f32) -> [f32; 3] {
let seg = &segments[s];
let x = if seg.length > 0.0 { local / seg.length } else { 0.0 };
let glide = if seg.phoneme.diphthong {
smoothstep((x - 0.15) / 0.7)
} else {
0.0
};
let mut f = mix(seg.from, seg.to, glide);
if let Some(prev) = s.checked_sub(1).map(|k| &segments[k]) {
let span = transition(seg, prev);
if local < span {
f = mix(meeting(prev, seg), f, local / span);
}
}
if let Some(next) = segments.get(s + 1) {
let span = transition(seg, next);
let left = seg.length - local;
if left < span {
f = mix(meeting(seg, next), f, left / span);
}
}
f
}
/// How long, in ms, `seg`'s formants take to reach their own values from
/// where it meets `other`. Vowels move slowly next to glides, quickly into
/// a stop; a consonant's own side of the meeting is short.
fn transition(seg: &Segment, other: &Segment) -> f32 {
use Class::*;
let ms: f32 = match (seg.class(), other.class()) {
(Pause, _) | (_, Pause) | (Aspirate, _) | (_, Aspirate) => 0.0,
(Vowel, Stop | Affricate) => 45.0,
(Vowel, Nasal) => 40.0,
(Vowel, Fricative) => 35.0,
(Vowel, Glide) => 60.0,
(Vowel, Vowel) => 40.0,
(Glide, _) => 50.0,
(Nasal | Fricative, _) => 20.0,
(Stop | Affricate, _) => 10.0,
};
ms.min(0.45 * seg.length)
}
/// The formants where `a` meets `b`. Where a consonant meets a vowel they
/// are its locus moved part of the way to the vowel: F1 hardly at all after
/// a stop, whose closure holds it low, F2 and F3 halfway. Elsewhere they
/// meet in the middle.
fn meeting(a: &Segment, b: &Segment) -> [f32; 3] {
let open = |c: Class| matches!(c, Class::Vowel | Class::Glide);
let pull = |c: Class| match c {
Class::Stop | Class::Affricate => Some([0.15, 0.5, 0.5]),
Class::Nasal => Some([0.3, 0.5, 0.5]),
Class::Fricative => Some([0.3, 0.6, 0.6]),
_ => None,
};
let toward = |locus: [f32; 3], vowel: [f32; 3], k: [f32; 3]| -> [f32; 3] {
core::array::from_fn(|i| locus[i] + k[i] * (vowel[i] - locus[i]))
};
let middle = mix(a.to, b.from, 0.5);
match (a.class(), b.class()) {
(Class::Pause, _) => b.from,
(_, Class::Pause) => a.to,
(ca, cb) if open(cb) => pull(ca).map_or(middle, |k| toward(a.to, b.from, k)),
(ca, cb) if open(ca) => pull(cb).map_or(middle, |k| toward(b.from, a.to, k)),
_ => middle,
}
}
/// The formants' bandwidths in a segment, and the frequency of the nasal
/// anti-resonance. The open glottis of breath and of the hissing sounds
/// damps F1; a voiced closure lets only a low hum through.
fn damping(seg: &Segment, local: f32) -> ([f32; 3], f32) {
let voiced = seg.phoneme.voiced;
let bandwidths = match seg.class() {
Class::Vowel | Class::Glide if local < seg.breath => [200.0, 110.0, 160.0],
Class::Vowel => [80.0, 100.0, 140.0],
Class::Glide => [80.0, 110.0, 170.0],
Class::Nasal => [90.0, 250.0, 300.0],
Class::Stop | Class::Affricate if voiced => [90.0, 400.0, 500.0],
Class::Stop | Class::Affricate | Class::Fricative => [200.0, 140.0, 220.0],
Class::Aspirate => [250.0, 140.0, 200.0],
Class::Pause => [100.0, 120.0, 200.0],
};
let zero = if seg.class() == Class::Nasal {
NASAL_ZERO
} else {
NASAL_POLE
};
(bandwidths, zero)
}
/// How loud the voice, the breath and the hiss are `local` ms into
/// segment `s`.
fn source(segments: &[Segment], s: usize, local: f32) -> Source {
let seg = &segments[s];
let ph = seg.phoneme;
let d = seg.length;
let left = d - local;
// At the edges of speech the voice starts and stops softly, not with a
// click.
let after_quiet = s == 0 || segments[s - 1].class() == Class::Pause;
let before_quiet = segments.get(s + 1).is_none_or(|t| t.class() == Class::Pause);
let mut edge = 1.0f32;
if after_quiet {
edge = edge.min(local / 15.0);
}
if before_quiet {
edge = edge.min(left / 30.0);
}
let edge = edge.clamp(0.0, 1.0);
let ramp = |ms: f32| ((local / ms).min(1.0) * (left / ms).min(1.0)).max(0.0);
let bar = if ph.voiced { 0.22 } else { 0.0 };
let voiced = |v: f32| if ph.voiced { v } else { 0.0 };
let only = |voice: f32, breath: f32, hiss: f32| Source { voice, breath, hiss };
let level = match ph.class {
Class::Vowel | Class::Glide | Class::Nasal if local < seg.breath => only(0.0, BREATH, 0.0),
Class::Vowel => only(if seg.stressed { 1.0 } else { 0.85 }, 0.0, 0.0),
Class::Glide => only(0.75, 0.0, 0.0),
Class::Nasal => only(0.6, 0.0, 0.0),
Class::Fricative => only(voiced(0.4), 0.0, HISS * ramp(15.0)),
Class::Stop if seg.release && left <= BURST_MS => {
let fade = if left > BURST_MS / 2.0 { 1.0 } else { 0.5 };
only(voiced(0.3), 0.0, HISS * fade)
}
Class::Stop => only(bar, 0.0, 0.0),
Class::Affricate if local < 0.45 * d => only(bar, 0.0, 0.0),
Class::Affricate => only(voiced(0.35), 0.0, HISS * (left / 20.0).min(1.0)),
Class::Aspirate => only(0.0, BREATH * ramp(10.0), 0.0),
Class::Pause => Source::QUIET,
};
Source {
voice: level.voice * edge,
breath: level.breath * edge,
hiss: level.hiss,
}
}
/// The raised-cosine bump of an accent, 1 at its peak, 0 from `u` = 1 on.
fn hat(u: f32) -> f32 {
if u >= 1.0 { 0.0 } else { 0.5 + 0.5 * cos(PI * u) }
}
/// The pitch at `t` ms, in Hz, within `phrase`.
fn pitch(segments: &[Segment], phrase: &Phrase, t: f32) -> f32 {
let body = &segments[phrase.first..phrase.end];
let t0 = body[0].start;
let t1 = body[body.len() - 1].end();
let span = (t1 - t0).max(1.0);
// The line the voice drifts down along, from 124 Hz to 102 Hz.
let mut f = 124.0 - 22.0 * ((t - t0) / span).clamp(0.0, 1.0);
let last = body.iter().rposition(|s| s.accent);
let peak_of = |s: &Segment| s.start + 0.45 * s.length;
// Each stressed word lifts the voice, the first the most; where two
// lifts overlap the higher holds. A question's last one is left out: it
// gets the question's rise instead.
let mut lift = 0.0f32;
let mut first = true;
for (k, s) in body.iter().enumerate() {
if !s.accent {
continue;
}
let height = if first { 26.0 } else { 16.0 };
first = false;
if phrase.ending == Break::Question && Some(k) == last {
continue;
}
let d = t - peak_of(s);
let u = if d < 0.0 { -d / 130.0 } else { d / 220.0 };
if u < 1.0 {
lift = lift.max(height * hat(u));
}
}
f += lift;
let progress = |from: f32| ((t - from) / (t1 - from).max(1.0)).clamp(0.0, 1.0);
match phrase.ending {
Break::Stop => {
let from = last.map_or(t1 - 250.0, |k| peak_of(&body[k]));
f -= 30.0 * progress(from);
}
Break::Question => {
let from = last.map_or(t1 - 300.0, |k| body[k].start);
let u = progress(from);
f += 60.0 * u * u;
}
Break::Comma => f += 14.0 * progress(t1 - 200.0),
}
f
}
/// A two-pole resonator, or with [`AntiResonator`] its inverse.
#[derive(Clone, Copy, Default)]
struct Resonator {
a: f32,
b: f32,
c: f32,
y1: f32,
y2: f32,
}
/// The coefficients B and C of a resonance at `freq` Hz, `bw` Hz wide,
/// with the pole radius and angle they come from.
fn poles(freq: f32, bw: f32) -> (f32, f32, f32, f32) {
let freq = freq.clamp(0.0, 0.45 * RATE);
let bw = bw.clamp(10.0, 4000.0);
let r = exp(-PI * bw / RATE);
let theta = 2.0 * PI * freq / RATE;
(2.0 * r * cos(theta), -r * r, r, theta)
}
impl Resonator {
/// Rings at `freq`, passing the lowest frequencies unchanged: the
/// formants in a chain, each lifting its own part of the spectrum.
fn tune(&mut self, freq: f32, bw: f32) {
let (b, c, _, _) = poles(freq, bw);
self.a = 1.0 - b - c;
self.b = b;
self.c = c;
}
/// Rings at `freq` with a gain of 1 there: the noise resonators side
/// by side, whose gains are then each one's own loudness.
fn tune_peak(&mut self, freq: f32, bw: f32) {
let (b, c, r, theta) = poles(freq, bw);
self.a = (1.0 - r) * sqrt(1.0 - 2.0 * r * cos(2.0 * theta) + r * r);
self.b = b;
self.c = c;
}
fn run(&mut self, x: f32) -> f32 {
let y = self.a * x + self.b * self.y1 + self.c * self.y2;
self.y2 = self.y1;
self.y1 = y;
y
}
}
/// The inverse of a resonator: a notch at its frequency. With a resonator
/// at the same frequency the two cancel; apart, they make a nasal's hum.
#[derive(Clone, Copy, Default)]
struct AntiResonator {
a: f32,
b: f32,
c: f32,
x1: f32,
x2: f32,
}
impl AntiResonator {
fn tune(&mut self, freq: f32, bw: f32) {
let (b, c, _, _) = poles(freq, bw);
let a = 1.0 - b - c;
self.a = 1.0 / a;
self.b = -b / a;
self.c = -c / a;
}
fn run(&mut self, x: f32) -> f32 {
let y = self.a * x + self.b * self.x1 + self.c * self.x2;
self.x2 = self.x1;
self.x1 = x;
y
}
}
/// The sources and filters, with their state from sample to sample.
#[derive(Default)]
struct Voice {
random: u32,
/// Where in its period the vocal folds are, 0 to 1.
phase: f32,
/// This period's small random stretch: a voice never keeps perfect
/// time, and one that does buzzes.
jitter: f32,
/// The pulse softened, the folds' closing never quite instant.
soft: f32,
nasal_pole: Resonator,
nasal_zero: AntiResonator,
formants: [Resonator; 7],
noise: [Resonator; 2],
gains: [f32; 2],
flat: f32,
dc_in: f32,
dc_out: f32,
smooth: f32,
}
impl Voice {
fn quiet() -> Voice {
let mut v = Voice {
random: 0x9e37_79b9,
jitter: 1.0,
..Voice::default()
};
v.nasal_pole.tune(NASAL_POLE, 100.0);
v.nasal_zero.tune(NASAL_POLE, 100.0);
for (r, (f, bw)) in v.formants[3..].iter_mut().zip(FIXED_FORMANTS) {
r.tune(f, bw);
}
v
}
fn tune(&mut self, frame: &Frame) {
self.nasal_zero.tune(frame.nasal_zero, 100.0);
for ((r, &f), &b) in self
.formants
.iter_mut()
.zip(&frame.formants)
.zip(&frame.bandwidths)
{
r.tune(f, b);
}
let fr = &frame.frication;
for ((r, &f), &b) in self.noise.iter_mut().zip(&fr.freq).zip(&fr.bw) {
r.tune_peak(f, b);
}
self.gains = fr.gain;
self.flat = fr.flat;
}
/// White noise, -1 to 1, from a xorshift generator.
fn noise(&mut self) -> f32 {
let mut x = self.random;
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
self.random = x;
(x >> 8) as f32 * (2.0 / 16_777_216.0) - 1.0
}
fn sample(&mut self, f0: f32, voice: f32, breath: f32, hiss: f32) -> f32 {
// The pulse is the rate of the air's flow through the folds: rising
// as they open, then the sharp fall of their closing, which is what
// excites the formants; flat while they are shut.
self.phase += f0 * self.jitter / RATE;
if self.phase >= 1.0 {
self.phase -= 1.0;
self.jitter = 1.0 + 0.01 * self.noise();
}
let x = self.phase / OPEN;
let pulse = if x < 1.0 { x * (2.0 - 3.0 * x) } else { 0.0 };
self.soft += 0.8 * (pulse - self.soft);
let source = self.soft * voice + self.noise() * breath;
let mut y = self.nasal_zero.run(self.nasal_pole.run(source));
for r in self.formants.iter_mut().rev() {
y = r.run(y);
}
let n = self.noise() * hiss;
let hissed =
self.noise[0].run(n) * self.gains[0] + self.noise[1].run(n) * self.gains[1] + n * self.flat;
let out = y + hissed;
// Take out any slow drift, then the harshest top.
let dc = out - self.dc_in + 0.995 * self.dc_out;
self.dc_in = out;
self.dc_out = dc;
self.smooth += 0.85 * (dc - self.smooth);
self.smooth
}
}
fn play(frames: &[Frame]) -> Vec<f32> {
let mut voice = Voice::quiet();
let mut out = Vec::with_capacity(frames.len() * FRAME);
for (k, now) in frames.iter().enumerate() {
let next = frames.get(k + 1).unwrap_or(now);
voice.tune(now);
for n in 0..FRAME {
// The pitch and the voice and breath slide across the frame;
// the hiss steps, its own ramps being in the frames.
let w = n as f32 / FRAME as f32;
let slide = |a: f32, b: f32| a + (b - a) * w;
let s = voice.sample(
slide(now.f0, next.f0),
slide(now.voice, next.voice),
slide(now.breath, next.breath),
now.hiss,
);
out.push(s);
}
}
out
}
/// The samples scaled to [`PEAK`] and made 16-bit.
fn finish(samples: &[f32]) -> Vec<i16> {
let peak = samples
.iter()
.filter(|x| x.is_finite())
.fold(0.0f32, |m, &x| m.max(x.max(-x)));
if peak <= 1e-9 {
return alloc::vec![0; samples.len()];
}
let scale = PEAK * f32::from(i16::MAX) / peak;
samples
.iter()
.map(|&x| if x.is_finite() { (x * scale) as i16 } else { 0 })
.collect()
}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
use crate::{Language, Sound, say};
use std::vec;
fn rms(samples: &[i16]) -> f64 {
let sum: f64 = samples.iter().map(|&x| f64::from(x) * f64::from(x)).sum();
(sum / samples.len().max(1) as f64).sqrt()
}
/// The power in `samples` at `freq` Hz (Goertzel's single-bin DFT).
fn power(samples: &[i16], freq: f64) -> f64 {
let w = 2.0 * core::f64::consts::PI * freq / f64::from(SAMPLE_RATE);
let coeff = 2.0 * w.cos();
let (mut s1, mut s2) = (0.0f64, 0.0f64);
for (i, &x) in samples.iter().enumerate() {
// A Hann window, so that one band's energy does not leak into
// the others.
let hann = 0.5 - 0.5 * (2.0 * core::f64::consts::PI * i as f64 / samples.len() as f64).cos();
let s = f64::from(x) * hann + coeff * s1 - s2;
s2 = s1;
s1 = s;
}
s1 * s1 + s2 * s2 - coeff * s1 * s2
}
fn band(samples: &[i16], from: u32, to: u32) -> f64 {
(from..=to)
.step_by(10)
.map(|f| power(samples, f64::from(f)))
.sum::<f64>()
/ f64::from((to - from) / 10 + 1)
}
/// The steady middle of one sound said alone.
fn alone(symbol: &str) -> std::vec::Vec<i16> {
let phoneme = phonemes::find(symbol).unwrap();
let samples = render(
&[Unit::Word(vec![Sound {
phoneme,
stressed: true,
}])],
Language::Dutch,
);
let third = samples.len() / 3;
samples[third..2 * third].to_vec()
}
#[test]
fn the_formants_are_where_they_should_be() {
// "aa": F1 near 780 Hz, F2 near 1300 Hz, nothing much at 2000.
let aa = alone("a:");
assert!(aa.len() > 1600, "{}", aa.len());
let f1 = band(&aa, 700, 860);
let valley = band(&aa, 1850, 2050);
assert!(f1 > 10.0 * valley, "aa: F1 band {f1:e}, valley {valley:e}");
let low = band(&aa, 150, 300);
assert!(f1 > low, "aa: F1 band {f1:e}, below it {low:e}");
// "ie": F1 low, F2 near 2250 Hz, and a valley between them, which
// the falling spectrum of the voice alone would not give.
let ie = alone("i");
let f2 = band(&ie, 2150, 2350);
let valley = band(&ie, 1000, 1200);
assert!(f2 > 3.0 * valley, "ie: F2 band {f2:e}, valley {valley:e}");
// "oe": both formants low, little above 1500 Hz.
let oe = alone("u");
let low = band(&oe, 250, 950);
let high = band(&oe, 1800, 2600);
assert!(low > 30.0 * high, "oe: low {low:e}, high {high:e}");
}
#[test]
fn the_hissing_sounds_hiss_where_they_should() {
// "s" is brightest at 5 to 6 kHz, "sh" at 2 to 3 kHz.
let s = alone("s");
assert!(band(&s, 5000, 6000) > 10.0 * band(&s, 2000, 3000), "s");
let sh = alone("S");
assert!(band(&sh, 2000, 3000) > 10.0 * band(&sh, 5000, 6000), "sh");
// The Dutch "ch" is low, below 2 kHz.
let ch = alone("x");
assert!(band(&ch, 1000, 2000) > 10.0 * band(&ch, 4000, 5000), "ch");
}
#[test]
fn hello_is_a_word_long() {
let samples = say("hello", Language::English);
let seconds = samples.len() as f64 / f64::from(SAMPLE_RATE);
assert!((0.2..=1.0).contains(&seconds), "{seconds} s");
assert!(rms(&samples) > 1000.0, "rms {}", rms(&samples));
let peak = samples.iter().map(|&x| i32::from(x).abs()).max().unwrap();
assert!(peak > 20_000 && peak < 32_767, "peak {peak}");
}
#[test]
fn every_sound_sounds() {
// Each sound between two vowels, so that the quiet ones are heard
// against something; none may come out as silence or as noise
// born of a filter gone unstable.
let a = phonemes::find("A").unwrap();
for i in 1..phonemes::count() as u8 {
let p = phonemes::get(i);
let units = [Unit::Word(vec![
Sound {
phoneme: a,
stressed: true,
},
Sound {
phoneme: i,
stressed: false,
},
Sound {
phoneme: a,
stressed: false,
},
])];
let samples = render(&units, Language::English);
assert!(rms(&samples) > 1000.0, "{}: rms {}", p.symbol, rms(&samples));
}
}
#[test]
fn silence_and_odd_text() {
assert!(say("", Language::English).is_empty());
assert!(say("!!! ...", Language::Dutch).is_empty());
assert!(say("🙂 日本語 مرحبا", Language::English).len() < 1600);
let long = say(&"Screen reader on. ".repeat(12), Language::English);
assert!(long.len() > 16_000 * 10, "{}", long.len());
assert!(rms(&long) > 1000.0);
let question = say("Is it on?", Language::English);
let statement = say("It is on.", Language::English);
assert!(!question.is_empty() && !statement.is_empty());
}
#[test]
fn a_question_rises_and_a_statement_falls() {
let units = |ending| {
let on = crate::read("it is on", Language::English);
let mut units = on;
units.push(Unit::Break(ending));
units
};
for (ending, rises) in [(Break::Question, true), (Break::Stop, false)] {
let (mut segments, phrases) = segments(&units(ending));
lengths(&mut segments, &phrases, Language::English);
let mut t = EDGE_MS;
for s in &mut segments {
s.start = t;
t += s.length;
}
let end = segments.last().unwrap().end();
let at_end = pitch(&segments, &phrases[0], end - 1.0);
let before = pitch(&segments, &phrases[0], end - 200.0);
assert_eq!(at_end > before, rises, "{ending:?}: {before} then {at_end}");
}
}
}