Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

Sing Hangul lyrics: one block per note, with Korean sound rules

Daniel Lee84ded38ee9b2
diff --git a/README.md b/README.md
index f66f419..81ed9a6 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,8 @@ for tests and the `chimera` CLI.
computer keyboard and Web MIDI.
- **Speak**: English text (CMUdict with a letter-to-sound fallback) or IPA, turned into
gestures and prosody, with the gestural score and a consonant chart on screen.
-- **Sing**: piano roll with lyrics per note; consonants land before the beat.
+- **Sing**: piano roll with lyrics per note; consonants land before the beat. Lyrics can be
+ English or Korean (Hangul: one block per note, with Korean sound rules).
- **Beatbox**: pads and a step sequencer, every drum an articulatory gesture.
- **Bestiary**: songbird (two-voice syrinx), seal, alligator and elephant.
- **Duet** (`?show=<id>`): two 3D heads replay a pre-rendered song.
diff --git a/crates/chimera/src/phonetics/korean.rs b/crates/chimera/src/phonetics/korean.rs
new file mode 100644
index 0000000..c3a92c4
--- /dev/null
+++ b/crates/chimera/src/phonetics/korean.rs
@@ -0,0 +1,226 @@
+//! Hangul lyrics → sung syllables. Each Hangul block is one sung syllable, so a block maps to one
+//! note. The block keeps its spelling as the note's text; its sounds follow standard Seoul
+//! pronunciation inside a word: a coda moves onto a following silent ㅇ (먹어 → 머거), codas
+//! neutralise to seven sounds, obstruents nasalise before nasals (국물 → 궁물), ㄴ/ㄹ meet as [ll],
+//! ㅎ aspirates its neighbour (좋다 → 조타), and obstruents tense after an obstruent coda.
+//!
+//! The engine has no tense (fortis) stops, so tense ㄲ ㄸ ㅃ ㅉ sing as unaspirated (voiced) stops,
+//! and lax and aspirated stops both take the planner's aspiration. ㅅ before [i] or [j] is [ʃ].
+
+use super::{Segment, Syllable};
+
+const BASE: u32 = 0xAC00;
+
+pub fn is_hangul(c: char) -> bool {
+ ('\u{AC00}'..='\u{D7A3}').contains(&c)
+}
+
+/// Initial consonants in Unicode order. 'ㅇ' as an initial is silent.
+const INITIALS: [char; 19] = ['ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'];
+
+/// Medial vowels in Unicode order as (glide, vowel).
+const MEDIALS: [(&str, &str); 21] = [
+ ("", "a"), ("", "ɛ"), ("j", "a"), ("j", "ɛ"), ("", "ʌ"), ("", "e"), ("j", "ʌ"), ("j", "e"), // ㅏㅐㅑㅒㅓㅔㅕㅖ
+ ("", "o"), ("w", "a"), ("w", "ɛ"), ("w", "e"), ("j", "o"), // ㅗㅘㅙㅚㅛ
+ ("", "u"), ("w", "ʌ"), ("w", "e"), ("w", "i"), ("j", "u"), // ㅜㅝㅞㅟㅠ
+ ("", "ɯ"), ("ɰ", "i"), ("", "i"), // ㅡㅢㅣ
+];
+
+/// Final consonants in Unicode order, as one or two letters ("" is no coda).
+const FINALS: [&str; 28] = [
+ "", "ㄱ", "ㄲ", "ㄱㅅ", "ㄴ", "ㄴㅈ", "ㄴㅎ", "ㄷ", "ㄹ", "ㄹㄱ", "ㄹㅁ", "ㄹㅂ", "ㄹㅅ", "ㄹㅌ", "ㄹㅍ", "ㄹㅎ",
+ "ㅁ", "ㅂ", "ㅂㅅ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ",
+];
+
+/// One block with its letters, rewritten in place by the sound rules.
+struct Block {
+ text: char,
+ /// None: silent ㅇ
+ onset: Option<char>,
+ glide: &'static str,
+ vowel: &'static str,
+ coda: Vec<char>,
+}
+
+fn decompose(c: char) -> Block {
+ let i = c as u32 - BASE;
+ let (cho, jung, jong) = ((i / 588) as usize, ((i % 588) / 28) as usize, (i % 28) as usize);
+ let onset = Some(INITIALS[cho]).filter(|&o| o != 'ㅇ');
+ let (glide, vowel) = MEDIALS[jung];
+ Block { text: c, onset, glide, vowel, coda: FINALS[jong].chars().collect() }
+}
+
+/// A coda's sound once it can't move on: one of ㄱ ㄴ ㄷ ㄹ ㅁ ㅂ ㅇ.
+fn neutral(c: char) -> char {
+ match c {
+ 'ㄱ' | 'ㄲ' | 'ㅋ' => 'ㄱ',
+ 'ㄷ' | 'ㅅ' | 'ㅆ' | 'ㅈ' | 'ㅊ' | 'ㅌ' | 'ㅎ' => 'ㄷ',
+ 'ㅂ' | 'ㅍ' => 'ㅂ',
+ other => other,
+ }
+}
+
+/// Which letter of a two-letter coda sounds when nothing follows to take the other.
+fn simplify(coda: &[char]) -> Option<char> {
+ match coda {
+ [] => None,
+ [c] => Some(*c),
+ ['ㄹ', b @ ('ㄱ' | 'ㅁ' | 'ㅍ')] => Some(*b),
+ [a, _] => Some(*a),
+ _ => unreachable!("codas have at most two letters"),
+ }
+}
+
+fn aspirated(c: char) -> Option<char> {
+ Some(match c {
+ 'ㄱ' => 'ㅋ',
+ 'ㄷ' => 'ㅌ',
+ 'ㅂ' => 'ㅍ',
+ 'ㅈ' => 'ㅊ',
+ _ => return None,
+ })
+}
+
+fn tense(c: char) -> char {
+ match c {
+ 'ㄱ' => 'ㄲ',
+ 'ㄷ' => 'ㄸ',
+ 'ㅂ' => 'ㅃ',
+ 'ㅅ' => 'ㅆ',
+ 'ㅈ' => 'ㅉ',
+ other => other,
+ }
+}
+
+/// Apply the sound rules at the boundary between block `a` and the next block `b`.
+fn join(a: &mut Block, b: &mut Block) {
+ // a coda before a silent ㅇ moves over (ㅎ drops, ㅇ stays: 좋아 → 조아, 빵야 → 빵야)
+ if b.onset.is_none() {
+ match a.coda.last() {
+ Some('ㅎ') => {
+ a.coda.pop();
+ }
+ Some('ㅇ') | None => {}
+ Some(_) => b.onset = a.coda.pop(),
+ }
+ return;
+ }
+ // ㅎ meets a stop or affricate: one aspirated consonant (좋다 → 조타, 축하 → 추카)
+ if a.coda.last() == Some(&'ㅎ') {
+ a.coda.pop();
+ let o = b.onset.unwrap();
+ b.onset = Some(match o {
+ 'ㅅ' => 'ㅆ',
+ 'ㄴ' => {
+ a.coda = vec!['ㄴ'];
+ 'ㄴ'
+ }
+ _ => aspirated(o).unwrap_or(o),
+ });
+ if a.coda.is_empty() {
+ return;
+ }
+ }
+ let Some(c) = simplify(&a.coda).map(neutral) else { return };
+ a.coda = vec![c];
+ let o = b.onset.unwrap();
+ if o == 'ㅎ' && matches!(c, 'ㄱ' | 'ㄷ' | 'ㅂ') {
+ a.coda.clear();
+ b.onset = aspirated(c);
+ return;
+ }
+ // ㄹ after any coda but ㄴ/ㄹ reads ㄴ (국립 → 궁닙); ㄴ and ㄹ together read [ll] (신라 → 실라)
+ let o = match (c, o) {
+ ('ㄹ', 'ㄴ') | ('ㄴ', 'ㄹ') => {
+ a.coda = vec!['ㄹ'];
+ 'ㄹ'
+ }
+ (_, 'ㄹ') if c != 'ㄹ' => 'ㄴ',
+ _ => o,
+ };
+ b.onset = Some(o);
+ // obstruent codas nasalise before nasals, and tense the obstruent after them
+ if matches!(c, 'ㄱ' | 'ㄷ' | 'ㅂ') {
+ if matches!(o, 'ㄴ' | 'ㅁ') {
+ a.coda = vec![match c {
+ 'ㄱ' => 'ㅇ',
+ 'ㄷ' => 'ㄴ',
+ _ => 'ㅁ',
+ }];
+ } else {
+ b.onset = Some(tense(o));
+ }
+ }
+}
+
+fn onset_ipa(o: char, voiced_before: bool, front: bool, after_l: bool) -> &'static str {
+ match o {
+ 'ㄱ' if voiced_before => "g",
+ 'ㄱ' | 'ㅋ' => "k",
+ 'ㄲ' => "g",
+ 'ㄷ' if voiced_before => "d",
+ 'ㄷ' | 'ㅌ' => "t",
+ 'ㄸ' => "d",
+ 'ㅂ' if voiced_before => "b",
+ 'ㅂ' | 'ㅍ' => "p",
+ 'ㅃ' => "b",
+ 'ㅈ' if voiced_before => "dʒ",
+ 'ㅈ' | 'ㅊ' => "tʃ",
+ 'ㅉ' => "dʒ",
+ 'ㅅ' | 'ㅆ' if front => "ʃ",
+ 'ㅅ' | 'ㅆ' => "s",
+ 'ㅎ' if voiced_before => "ɦ",
+ 'ㅎ' => "h",
+ 'ㄴ' => "n",
+ 'ㅁ' => "m",
+ 'ㄹ' if after_l => "l",
+ 'ㄹ' => "ɾ",
+ _ => unreachable!("not an initial: {o}"),
+ }
+}
+
+fn coda_ipa(c: char) -> &'static str {
+ match c {
+ 'ㄱ' => "k",
+ 'ㄴ' => "n",
+ 'ㄷ' => "t",
+ 'ㄹ' => "l",
+ 'ㅁ' => "m",
+ 'ㅂ' => "p",
+ 'ㅇ' => "ŋ",
+ _ => unreachable!("not a neutral coda: {c}"),
+ }
+}
+
+/// One word of Hangul (a run of blocks) → its sung syllables, the last marked as the word's end.
+pub fn word_syllables(word: &str) -> Vec<Syllable> {
+ let mut blocks: Vec<Block> = word.chars().filter(|&c| is_hangul(c)).map(decompose).collect();
+ for i in 1..blocks.len() {
+ let (l, r) = blocks.split_at_mut(i);
+ join(l.last_mut().unwrap(), &mut r[0]);
+ }
+ if let Some(last) = blocks.last_mut() {
+ last.coda = simplify(&last.coda).map(neutral).into_iter().collect();
+ }
+ let mut out = Vec::with_capacity(blocks.len());
+ for (i, b) in blocks.iter().enumerate() {
+ let prev_coda = if i > 0 { blocks[i - 1].coda.last().copied() } else { None };
+ let voiced_before = i > 0 && prev_coda.is_none_or(|c| matches!(c, 'ㄴ' | 'ㄹ' | 'ㅁ' | 'ㅇ'));
+ let front = b.vowel == "i" && b.glide != "w" || b.glide == "j";
+ let mut onset: Vec<Segment> = b.onset.map(|o| Segment::new(onset_ipa(o, voiced_before, front, prev_coda == Some('ㄹ')))).into_iter().collect();
+ // ㅢ after a consonant is plain [i] (희 → 히)
+ if !b.glide.is_empty() && !(b.glide == "ɰ" && b.onset.is_some()) {
+ onset.push(Segment::new(b.glide));
+ }
+ out.push(Syllable {
+ text: b.text.to_string(),
+ onset,
+ nucleus: Segment::new(b.vowel),
+ coda: b.coda.iter().map(|&c| Segment::new(coda_ipa(c))).collect(),
+ melisma: None,
+ word_end: i + 1 == blocks.len(),
+ phrase_end: false,
+ });
+ }
+ out
+}
diff --git a/crates/chimera/src/phonetics/mod.rs b/crates/chimera/src/phonetics/mod.rs
index ad77d86..6d2d01e 100644
--- a/crates/chimera/src/phonetics/mod.rs
+++ b/crates/chimera/src/phonetics/mod.rs
@@ -10,6 +10,7 @@ pub mod durations;
pub mod english;
pub mod inventory;
pub mod ipa;
+pub mod korean;
pub mod planner;
pub mod sing;
pub mod songs;
diff --git a/crates/chimera/src/phonetics/syllables.rs b/crates/chimera/src/phonetics/syllables.rs
index 40fc7ed..f186110 100644
--- a/crates/chimera/src/phonetics/syllables.rs
+++ b/crates/chimera/src/phonetics/syllables.rs
@@ -1,11 +1,13 @@
-//! Lyrics → sung syllables. Words come from the pronouncing dictionary (unreduced: sung function
-//! words keep full vowels), are split into syllables by the maximal-onset principle with English
-//! onset clusters, and the spelling is split to match for display ("twin-kle").
+//! Lyrics → sung syllables. Hangul words go to [`super::korean`], one syllable per block. Other
+//! words come from the pronouncing dictionary (unreduced: sung function words keep full vowels),
+//! are split into syllables by the maximal-onset principle with English onset clusters, and the
+//! spelling is split to match for display ("twin-kle").
//! Typed hyphens force syllable breaks; a lone "-" (or "~") holds the previous vowel onto the
//! next note (melisma), as in vocaloid editors.
use crate::anatomy::human::BodyMix;
use super::english::js_is_space;
+use super::korean::{is_hangul, word_syllables};
use super::planner::is_vowel;
use super::{Segment, Syllable};
use serde::{Deserialize, Serialize};
@@ -151,13 +153,21 @@ fn is_word_start(c: char) -> bool {
c.is_ascii_alphabetic() || c == '\''
}
-/// `text.match(/[A-Za-z'][A-Za-z'\-]*|(?<=\s|^)[~-](?=\s|$)|[.,;:!?\n]/g)`
+/// `text.match(/[A-Za-z'][A-Za-z'\-]*|[가-힣]+|(?<=\s|^)[~-](?=\s|$)|[.,;:!?\n]/g)`
fn lyric_tokens(text: &str) -> Vec<String> {
let s: Vec<char> = text.chars().collect();
let mut out = Vec::new();
let mut i = 0;
while i < s.len() {
let c = s[i];
+ if is_hangul(c) {
+ let start = i;
+ while i < s.len() && is_hangul(s[i]) {
+ i += 1;
+ }
+ out.push(s[start..i].iter().collect());
+ continue;
+ }
if is_word_start(c) {
let start = i;
i += 1;
@@ -195,6 +205,10 @@ pub fn lyrics_to_syllables(text: &str, g2p: &impl WordSource) -> Vec<Syllable> {
}
continue;
}
+ if tok.starts_with(is_hangul) {
+ out.extend(word_syllables(tok));
+ continue;
+ }
// typed hyphens split syllables explicitly ("ti-ger"); otherwise the dictionary decides
let parts: Vec<&str> = tok.split('-').filter(|p| !p.is_empty()).collect();
let mut syls: Vec<Syllable> = Vec::new();
diff --git a/crates/chimera/tests/syllables.rs b/crates/chimera/tests/syllables.rs
index 8fd9571..b6b253a 100644
--- a/crates/chimera/tests/syllables.rs
+++ b/crates/chimera/tests/syllables.rs
@@ -55,3 +55,33 @@ fn lyrics_words_melisma_phrase_ends_unreduced_function_words() {
assert_eq!(syl[7].nucleus.ipa, "aɪ");
assert!(syl[1].word_end && !syl[0].word_end);
}
+
+/// Each syllable as onset+nucleus+coda IPA, joined with "."
+fn sung(text: &str) -> String {
+ lyrics_to_syllables(text, &word).iter().map(|s| format!("{}{}{}", ipa(&s.onset), s.nucleus.ipa, ipa(&s.coda))).collect::<Vec<_>>().join(".")
+}
+
+#[test]
+fn hangul_sings_one_syllable_per_block_with_korean_sound_rules() {
+ assert_eq!(sung("빵야"), "baŋ.ja"); // ㅇ coda stays; tense ㅃ sings unaspirated
+ assert_eq!(sung("먹어"), "mʌ.gʌ"); // a coda moves onto a silent ㅇ, voiced between vowels
+ assert_eq!(sung("좋아"), "tʃo.a"); // ㅎ drops before a vowel
+ assert_eq!(sung("좋다"), "tʃo.ta"); // ㅎ + ㄷ aspirates
+ assert_eq!(sung("국물"), "kuŋ.mul"); // nasalisation
+ assert_eq!(sung("신라"), "ʃil.la"); // ㄴ + ㄹ is [ll]; ㅅ before i is [ʃ]
+ assert_eq!(sung("없는"), "ʌm.nɯn"); // a two-letter coda simplifies, then nasalises
+ assert_eq!(sung("학교"), "hak.gjo"); // tensing after an obstruent coda
+ assert_eq!(sung("사랑해"), "sa.ɾaŋ.ɦɛ");
+ assert_eq!(sung("닭"), "tak");
+ assert_eq!(sung("의사"), "ɰi.sa");
+}
+
+#[test]
+fn hangul_keeps_its_spelling_and_mixes_with_english() {
+ let syls = lyrics_to_syllables("twinkle 빵야 빵야, star", &word);
+ let shown: Vec<(&str, bool, bool)> = syls.iter().map(|s| (s.text.as_str(), s.word_end, s.phrase_end)).collect();
+ assert_eq!(
+ shown,
+ [("twin", false, false), ("kle", true, false), ("빵", false, false), ("야", true, false), ("빵", false, false), ("야", true, true), ("star", true, false)]
+ );
+}