the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Pitch bends (#32 step 4): a syllable can shape the pitch at its note's start or end; the planner draws them and knows no language's tones
Joshua Phame09ba69d2c03
diff --git a/crates/chimera/src/phonetics/mod.rs b/crates/chimera/src/phonetics/mod.rsindex 715994d..bf1ab37 100644--- a/crates/chimera/src/phonetics/mod.rs+++ b/crates/chimera/src/phonetics/mod.rs@@ -116,4 +116,28 @@ pub struct Syllable {/// a breath follows (comma, full stop, line break); may be left out (false)#[serde(default)]pub phrase_end: bool,+ /// pitch bends inside the sung note, as the syllable's front end writes them (a tone, a pitch+ /// accent, a scoop); none: the note's pitch as written+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub pitch: Vec<Bend>,+}++/// Which end of its sung vowel a pitch bend sits at.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Edge {+ Start,+ End,+}++/// 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).+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Bend {+ pub at: Edge,+ pub len: f64,+ pub max: f64,+ pub st: f64,}diff --git a/crates/chimera/src/phonetics/sing.rs b/crates/chimera/src/phonetics/sing.rsindex efbd96b..c4bb353 100644--- a/crates/chimera/src/phonetics/sing.rs+++ b/crates/chimera/src/phonetics/sing.rs@@ -14,7 +14,7 @@use super::inventory::phoneme;use crate::anatomy::human::BodyMix;use super::planner::{PlanOptions, diphthong_parts, plan_utterance};-use super::{Intonation, Plan, PlannedSegment, Segment, Syllable};+use super::{Bend, Edge, Intonation, Plan, PlannedSegment, Segment, Syllable};use crate::control::score::{ControlKey, Gesture, Targets};use crate::math::{js_max, js_min};use serde::{Deserialize, Serialize};@@ -102,6 +102,26 @@ pub struct SongOptions {pub vibrato: f64,}+/// A bend's blending strength against the note's own pitch (6): it wins while it lasts.+const BEND_STRENGTH: f64 = 30.0;++/// Pitch gestures for a syllable's bends on a vowel sung at `hz` from a to b.+fn bend_gestures(bends: &[Bend], hz: f64, a: f64, b: f64, out: &mut Vec<Gesture>) {+ let d = b - a;+ if d <= 0.02 {+ return;+ }+ for bend in bends {+ let len = js_min(bend.len * d, bend.max);+ let (t0, t1) = match bend.at {+ Edge::Start => (a - 0.03, a + len),+ Edge::End => (b - len, b + 0.02),+ };+ let f = hz * crate::math::pow(2.0, bend.st / 12.0);+ out.push(Gesture::new(t0, t1, 0.015, 0.04, BEND_STRENGTH, Targets::default().with(ControlKey::F0, f)).label("bend"));+ }+}+fn melisma(s: &Syllable) -> bool {s.melisma == Some(true)}@@ -126,10 +146,19 @@ 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 the syllables with bends+ let mut bend_spans: Vec<(usize, f64, f64)> = Vec::new();// 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);- 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, hz_of(k)) }).collect();+ // a bend at the vowel's start begins in the onset: the consonants already sing its pitch, so+ // a rising tone starts low instead of starting at the note and dipping. Without a start+ // bend this is the note's pitch, exactly as before.+ let onset_hz = |k: usize| match notes[k].syl.pitch.iter().find(|b| b.at == Edge::Start) {+ Some(b) => hz_of(k) * crate::math::pow(2.0, b.st / 12.0),+ None => hz_of(k),+ };+ 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 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();@@ -167,12 +196,19 @@ pub fn plan_song(notes: &[SungNote], o: &SongOptions) -> Plan {}segs.extend(coda);vowel_spans.push((times[k], times[k] + vdur));+ // bends shape their syllable's first note (a melisma continues at the written pitches)+ if !n.syl.pitch.is_empty() && !melisma(&n.syl) {+ bend_spans.push((k, times[k], times[k] + vdur));+ }}if !segs.is_empty() {// the planner lays segments out from t0 + 0.06: start so the first vowel lands on its beatlet plan = plan_utterance(&segs, &PlanOptions { body: o.body, t0: times[i] - first_onset - 0.06, f0: Some(hz_of(i)), intonation: Some(Intonation::Flat), sung: Some(true), ..Default::default() });gestures.extend_from_slice(&plan.gestures);segments.extend(plan.segments);+ for &(k, a, b) in &bend_spans {+ bend_gestures(¬es[k].syl.pitch, hz_of(k), a, b, &mut gestures);+ }for (a, b) in vowel_spans {if b - a > 0.3 {gestures.push(vibrato_gesture(a, b, o.vibrato, None));diff --git a/crates/chimera/tests/bends.rs b/crates/chimera/tests/bends.rsnew file mode 100644index 0000000..fbc350d--- /dev/null+++ b/crates/chimera/tests/bends.rs@@ -0,0 +1,69 @@+//! Pitch bends: a syllable's front end shapes the pitch inside its note (start or end, capped in+//! length); none leaves the note as written.+use chimera::control::score::{ControlKey, Gesture};+use chimera::phonetics::sing::{SongOptions, SungNote, midi_to_hz, plan_song};+use chimera::phonetics::{Bend, Edge, Segment, Syllable};++fn syl(onset: &str, v: &str, pitch: Vec<Bend>) -> Syllable {+ Syllable { text: v.into(), onset: vec![Segment::new(onset)], nucleus: Segment::new(v), word_end: true, pitch, ..Default::default() }+}+fn opts() -> SongOptions {+ SongOptions { body: "male".into(), bpm: 60.0, t0: 0.5, ..Default::default() }+}+fn labelled<'a>(gs: &'a [Gesture], l: &str) -> Vec<&'a Gesture> {+ gs.iter().filter(|g| g.label.as_ref().is_some_and(|x| x.as_str() == l)).collect()+}+/// the pitch targets of the gestures that end by the beat (the onset's)+fn onset_f0(gs: &[Gesture]) -> Vec<f64> {+ labelled(gs, "pitch").into_iter().filter(|g| g.t1 <= 0.5 + 1e-9).filter_map(|g| g.targets.get(ControlKey::F0)).collect()+}++#[test]+fn bends_colour_the_start_or_end_of_the_note_and_none_leave_it() {+ let hz = midi_to_hz(57.0);+ let one = |pitch| plan_song(&[SungNote { midi: 57.0, beats: 2.0, syl: syl("l", "a", pitch) }], &opts());+ assert!(labelled(&one(vec![]).gestures, "bend").is_empty());+ let up = Bend { at: Edge::Start, len: 0.35, max: 0.15, st: -2.0 };+ let down = Bend { at: Edge::End, len: 0.35, max: 0.15, st: -3.0 };+ let p = one(vec![up, down]);+ let b = labelled(&p.gestures, "bend");+ assert_eq!(b.len(), 2);+ // the start bend: from just before the beat, at most 0.15 s into a 2 s note, 2 semitones down+ assert!((b[0].targets.get(ControlKey::F0).unwrap() / hz - 2f64.powf(-2.0 / 12.0)).abs() < 1e-9);+ assert!(b[0].t0 < 0.5 && (b[0].t1 - 0.65).abs() < 1e-9);+ // the end bend: the last 0.15 s of the vowel+ assert!(b[1].targets.get(ControlKey::F0).unwrap() < hz && (b[1].t1 - b[1].t0 - 0.17).abs() < 1e-9);+}++#[test]+fn no_bends_plan_exactly_as_before() {+ let notes = [SungNote { midi: 57.0, beats: 1.0, syl: syl("m", "a", vec![]) }, SungNote { midi: 60.0, beats: 1.0, syl: syl("t", "i", vec![]) }];+ let p = plan_song(¬es, &opts());+ assert!(labelled(&p.gestures, "bend").is_empty());+ // with an empty bend list serialised away, the syllables round-trip unchanged+ let j = serde_json::to_value(¬es[0].syl).unwrap();+ assert!(j.get("pitch").is_none());+}++#[test]+fn a_melisma_keeps_its_written_pitches() {+ let bend = vec![Bend { at: Edge::Start, len: 0.35, max: 0.15, st: -2.0 }];+ let first = syl("l", "a", bend.clone());+ let cont = Syllable { text: "~".into(), nucleus: Segment::new("a"), melisma: Some(true), pitch: bend, ..Default::default() };+ let p = plan_song(&[SungNote { midi: 57.0, beats: 1.0, syl: first }, SungNote { midi: 59.0, beats: 1.0, syl: cont }], &opts());+ assert_eq!(labelled(&p.gestures, "bend").len(), 1, "only the syllable's first note bends");+}++#[test]+fn a_start_bend_begins_in_the_onset() {+ // a rising tone starts low: the onset consonant already sings the bend's pitch, not the note's+ let hz = midi_to_hz(57.0);+ let up = Bend { at: Edge::Start, len: 0.35, max: 0.15, st: -3.0 };+ let p = plan_song(&[SungNote { midi: 57.0, beats: 2.0, syl: syl("m", "a", vec![up]) }], &opts());+ let f = onset_f0(&p.gestures);+ assert!(!f.is_empty());+ assert!(f.iter().all(|f| (f / hz - 2f64.powf(-3.0 / 12.0)).abs() < 1e-9), "{f:?}");+ // without a start bend the onset sings the note+ let plain = plan_song(&[SungNote { midi: 57.0, beats: 2.0, syl: syl("m", "a", vec![]) }], &opts());+ assert!(onset_f0(&plain.gestures).iter().all(|f| (f - hz).abs() < 1e-9));+}diff --git a/docs/language-front-ends.md b/docs/language-front-ends.mdindex 513ce6c..f3f5db2 100644--- a/docs/language-front-ends.md+++ b/docs/language-front-ends.md@@ -53,8 +53,8 @@ how long they aspirate (`vot`, voice onset time):| measured in the render (male; female within 3 ms) | 53 ms | 96 ms | 22 ms |Between voiced sounds a lax stop is voiced (아기 [agi]). Not modelled yet: the lower pitch that-follows a lax stop (Seoul speakers rely on it as much as on aspiration; it needs pitch contours,-#32 step 4) and the stiff voice of tense stops. A Korean speaker's ear is still wanted.+follows a lax stop (Seoul speakers rely on it as much as on aspiration; a start bend could carry+it, untried) and the stiff voice of tense stops. A Korean speaker's ear is still wanted.## The one format@@ -72,10 +72,30 @@ 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.+- `pitch`: bends that colour the note's start or end (below).- 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).+## Pitch bends++A syllable can carry pitch bends: what tones, pitch accent or a scoop need (#32 step 4). Each is+`st` semitones from the note at the vowel's `start` or `end`, over `len` of the vowel but at most+`max` seconds:++```json+"pitch": [{"at": "start", "len": 0.3, "max": 0.2, "st": -3}, {"at": "end", "len": 0.3, "max": 0.2, "st": -4}]+```++The melody stays as written; a bend only colours the note's edges. A start bend begins in the+onset, so the consonants already sing its pitch and a rise starts low rather than at the note. 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.++A front end that writes no bends sings exactly as before. Bends are drawn by `plan_song` (Sing's+playback, `chimera render notes`, duets), **not yet on live notes**: a key pressed in Sing or a+note from the plugin (`plan_note_on`) sings the note's pitch.+Any front end's output can be frozen to JSON, edited and sung with `"syllables"` instead of`"lyrics"`, in `render notes` and duet melody files. Use it to fix a readingby hand, or to sing a language that has no front end yet.@@ -138,4 +158,5 @@ in for a native listener; the test says where to look and whether a change moved- **Latin-script languages.** Routing by script can't tell Turkish or German from English, soLatin text is English. The second Latin-script front end brings an explicit language choice,with English the default (#40).-- **Tone and pitch accent** need pitch contours (#32 step 4).+- **Bends on live notes** (above), and **IPA tone letters** (`˥˩`, #52): IPA text doesn't write+ bends yet.diff --git a/src/wasm/types.ts b/src/wasm/types.tsindex c7e767c..7983f4f 100644--- a/src/wasm/types.ts+++ b/src/wasm/types.ts@@ -207,6 +207,16 @@ export interface Syllable {melisma?: boolean;wordEnd: boolean;phraseEnd: boolean;+ /** pitch bends inside the sung note, written by the syllable's front end (a tone, an accent) */+ pitch?: Bend[];+}++/** 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). */+export interface Bend {+ at: "start" | "end";+ len: number;+ max: number;+ st: number;}export interface SungNote {