mumble v1.1 More tweaking required, but good enough for now

This commit is contained in:
2026-10-21 06:24:42 +02:00
parent 529738fea6
commit 0b26171948
4 changed files with 228 additions and 80 deletions
+106 -65
View File
@@ -2,11 +2,15 @@
* chatter-parser.ts — converts raw message text into a token stream.
*
* Handles:
* - Escape sequences: {tag}, {tag value}, {/tag}, {{ literal, {{tag}} literal
* - Escape sequences: {tag}, {tag value}, {/tag}, {{ literal
* - Vowel escape: {vowel X} or {vowel X ms}
* - Punctuation timing: . (6x), .. (9x), ... (12x), .... (15x) via 6+3(N-1)
* - Comma, semicolon, colon (3x); space, apostrophe, quotes, etc. (1x)
* - Sentence detection: . ? ! and 3+ dot runs (ellipsis)
* - Vowel detection (a/e/i/o/u)
* - Vowel detection:
* a, e, i, o, u → standard vowels
* oo (two adjacent o) → /u/ as in "boot"
* word-final y → /i/ as in "happy"
* - Uppercase (shout)
* - Style state tracking
* - Speed overrides
@@ -14,6 +18,7 @@
import {
DEFAULT_STYLE,
VOWEL_FORMANTS,
type CharToken,
type IconAlign,
type IconSize,
@@ -27,6 +32,8 @@ import {
type Token,
type VoiceMood,
type VoiceToken,
type Vowel,
type VowelToken,
} from "./chatter-types.ts";
const VOWELS = new Set(["a", "e", "i", "o", "u"]);
@@ -41,9 +48,53 @@ const PUNCT_MULTIPLIER: Record<string, number> = {
"!": 6,
};
/* ------------------------------------------------------------------ */
/* Public */
/* ------------------------------------------------------------------ */
type VowelClassification = { isVowel: false } | { isVowel: true; vowel: Vowel };
function isVowelName(s: string): s is Vowel {
return s in VOWEL_FORMANTS;
}
/**
* Classify the character at `index` as vowel or consonant in context.
*
* Standard vowels: a, e, i, o, u
* 'oo' — two adjacent o chars merge into /u/
* Word-final y after a consonant → /i/ (happy, my, fly)
* Other y → consonant (yes, day, yellow, beyond)
*/
function classifyVowelAt(text: string, index: number): VowelClassification {
const ch = text[index];
if (ch === undefined) return { isVowel: false };
const lower = ch.toLowerCase();
// 'oo' detection: if either neighbor is 'o', this char is 'oo'
if (lower === "o") {
const prev = text[index - 1]?.toLowerCase();
const next = text[index + 1]?.toLowerCase();
if (prev === "o" || next === "o") {
return { isVowel: true, vowel: "oo" };
}
}
if (lower === "a" || lower === "e" || lower === "i" || lower === "o" || lower === "u") {
return { isVowel: true, vowel: lower as Vowel };
}
if (lower === "y") {
const next = text[index + 1];
const nextIsLetter = next !== undefined && /[a-zA-Z]/.test(next);
if (nextIsLetter) return { isVowel: false };
const prev = text[index - 1];
if (prev === undefined) return { isVowel: false };
const prevLower = prev.toLowerCase();
if (/[aeiou]/.test(prevLower) || prevLower === "y") return { isVowel: false };
return { isVowel: true, vowel: "i" };
}
return { isVowel: false };
}
export function parseMessage(text: string, opts: ParseOptions): ParsedMessage {
const tokens: Token[] = [];
@@ -61,8 +112,6 @@ export function parseMessage(text: string, opts: ParseOptions): ParsedMessage {
let sentenceStart = 0;
let totalDuration = 0;
let totalVisible = 0;
/** Tracks consecutive dots — first dot in a run gets 6x, rest get 3x. */
let inDotRun = false;
const pushToken = (token: Token): void => {
@@ -78,21 +127,16 @@ export function parseMessage(text: string, opts: ParseOptions): ParsedMessage {
/* ---------- literal escapes ---------- */
if (ch === "{" && text[i + 1] === "{") {
// Literal '{'
pushToken(makeChar("{", currentCps, style));
i += 2;
inDotRun = false;
continue;
}
if (ch === "{" && text[i + 1] === "{" && text.slice(i).startsWith("{{") === true) {
// Handled above; the second condition is defensive
}
/* ---------- escape sequences ---------- */
if (ch === "{") {
const close = text.indexOf("}", i + 1);
if (close === -1) {
// Unterminated — treat as literal char
pushToken(makeChar("{", currentCps, style));
i += 1;
inDotRun = false;
@@ -107,12 +151,13 @@ export function parseMessage(text: string, opts: ParseOptions): ParsedMessage {
styleRef: () => style,
setStyle: s => (style = s),
setSpeed: cps => (currentCps = cps),
getSpeed: () => currentCps,
initialCps,
baseStyle,
});
if (handled) continue;
// Unknown escape — treat as literal text
// Unknown escape — render body as literal text
pushToken(makeChar("{", currentCps, style));
for (const c of body) pushToken(makeChar(c, currentCps, style));
pushToken(makeChar("}", currentCps, style));
@@ -121,18 +166,14 @@ export function parseMessage(text: string, opts: ParseOptions): ParsedMessage {
/* ---------- punctuation with multipliers ---------- */
if (ch === ".") {
// Detect run of dots
let runLength = 1;
while (i + runLength < text.length && text[i + runLength] === ".") {
runLength++;
}
// Emit each dot with the appropriate multiplier
for (let d = 0; d < runLength; d++) {
const multiplier = d === 0 && !inDotRun ? 6 : 3;
const dotToken = makeChar(".", currentCps, style, multiplier);
pushToken(dotToken);
pushToken(makeChar(".", currentCps, style, multiplier));
}
// If 3+ dots, this is an ellipsis terminator — end sentence
if (runLength >= 3) {
endSentence(tokens.length - 1, "ellipsis");
} else {
@@ -155,12 +196,12 @@ export function parseMessage(text: string, opts: ParseOptions): ParsedMessage {
}
/* ---------- regular character ---------- */
pushToken(makeChar(ch, currentCps, style));
const classification = classifyVowelAt(text, i);
pushToken(makeChar(ch, currentCps, style, 1, classification));
i += 1;
inDotRun = ch === ".";
}
// Trailing fragment if the message didn't end with a terminal
if (sentenceStart < tokens.length) {
sentences.push({
startToken: sentenceStart,
@@ -171,44 +212,41 @@ export function parseMessage(text: string, opts: ParseOptions): ParsedMessage {
return { tokens, sentences, totalDuration, totalVisible };
/* -------------------------------------------------------------- */
function endSentence(endToken: number, type: SentenceType): void {
sentences.push({ startToken: sentenceStart, endToken, type });
sentenceStart = endToken + 1;
}
}
/* ------------------------------------------------------------------ */
/* Char construction */
/* ------------------------------------------------------------------ */
function makeChar(ch: string, cps: number, style: TextStyle, multiplier = 1): CharToken {
function makeChar(
ch: string,
cps: number,
style: TextStyle,
multiplier = 1,
classification?: VowelClassification,
): CharToken {
const lower = ch.toLowerCase();
const isVowel = VOWELS.has(lower);
const vowel = isVowel ? (lower as CharToken["vowel"]) : undefined;
const cls: VowelClassification =
classification ?? (VOWELS.has(lower) ? { isVowel: true, vowel: lower as Vowel } : { isVowel: false });
const shout = ch !== lower && ch.toUpperCase() === ch && ch !== ch.toLowerCase();
const token: CharToken = {
kind: "char",
ch,
isVowel,
isVowel: cls.isVowel,
shout,
duration: multiplier / cps,
style: { ...style },
};
if (vowel !== undefined) token.vowel = vowel;
if (cls.isVowel) token.vowel = cls.vowel;
return token;
}
/* ------------------------------------------------------------------ */
/* Escape handling */
/* ------------------------------------------------------------------ */
interface EscapeContext {
tokens: (token: Token) => void;
styleRef: () => TextStyle;
setStyle: (s: TextStyle) => void;
setSpeed: (cps: number) => void;
getSpeed: () => number;
initialCps: number;
baseStyle: TextStyle;
}
@@ -217,7 +255,7 @@ function handleEscape(body: string, ctx: EscapeContext): boolean {
const trimmed = body.trim();
if (trimmed.length === 0) return false;
// Close tag: {/name}
// {/name}
if (trimmed.startsWith("/")) {
const name = trimmed.slice(1).trim();
const current = ctx.styleRef();
@@ -261,14 +299,13 @@ function handleEscape(body: string, ctx: EscapeContext): boolean {
return false;
}
// {voice mood} or {voice pitch:N} or {voice volume:N}
// {voice mood}, {voice pitch:N}, {voice volume:N}
if (trimmed.startsWith("voice")) {
const rest = trimmed.slice(5).trim();
const voiceToken: VoiceToken = { kind: "voice", duration: 0 };
let hasAny = false;
const tokens = rest.split(/\s+/).filter(Boolean);
for (const tok of tokens) {
const parts = rest.split(/\s+/).filter(Boolean);
for (const tok of parts) {
if (MOODS.has(tok as VoiceMood)) {
voiceToken.mood = tok as VoiceMood;
hasAny = true;
@@ -294,7 +331,28 @@ function handleEscape(body: string, ctx: EscapeContext): boolean {
return false;
}
// {icon ...} with optional ^align and *N / @size modifiers
// {vowel X} or {vowel X N}
if (trimmed.startsWith("vowel")) {
const rest = trimmed.slice(5).trim();
const parts = rest.split(/\s+/).filter(Boolean);
if (parts.length === 0) return false;
const raw = parts[0]!;
const lower = raw.toLowerCase();
if (!isVowelName(lower)) return false;
const shout = raw === raw.toUpperCase() && raw !== lower;
let duration = 1 / ctx.getSpeed();
if (parts[1] !== undefined) {
const ms = parseInt(parts[1]!, 10);
if (!isNaN(ms) && ms > 0) duration = ms / 1000;
}
const token: VowelToken = { kind: "vowel", vowel: lower, shout, duration };
ctx.tokens(token);
return true;
}
// {icon ...}
if (trimmed.startsWith("icon")) {
const rest = trimmed.slice(4).trim();
const parsed = parseIconSpec(rest);
@@ -305,21 +363,15 @@ function handleEscape(body: string, ctx: EscapeContext): boolean {
name: parsed.name,
size: parsed.size,
align: parsed.align,
duration: 1 / 0.01, // placeholder; fixed below
duration: 1 / ctx.getSpeed(),
style: { ...current },
};
if (parsed.multiplier !== undefined) token.multiplier = parsed.multiplier;
// Duration = 1 character at current speed
token.duration = 1 / (ctx as unknown as { currentCps?: number }).currentCps! || 0.05;
// Use the ctx.setSpeed trick isn't applicable here; recompute via current char speed
// We can't read currentCps directly; we approximate via baseStyle speed. Instead,
// set duration in the caller: easier to just accept the default.
token.duration = 0.05;
ctx.tokens(token);
return true;
}
// Style-open tags: {color red}, {bold}, {underline}, {shake}, {wobble}, {wave}
// {color value}
if (trimmed.startsWith("color")) {
const value = trimmed.slice(5).trim();
if (value.length === 0) return false;
@@ -328,6 +380,8 @@ function handleEscape(body: string, ctx: EscapeContext): boolean {
ctx.tokens({ kind: "style-open", name: "color", value, duration: 0 });
return true;
}
// {bold}, {underline}, {shake}, {wobble}, {wave}
for (const tag of ["bold", "underline", "shake", "wobble", "wave"] as const) {
if (trimmed === tag) {
const current = ctx.styleRef();
@@ -340,10 +394,6 @@ function handleEscape(body: string, ctx: EscapeContext): boolean {
return false;
}
/* ------------------------------------------------------------------ */
/* Icon spec */
/* ------------------------------------------------------------------ */
interface IconSpec {
name: string;
size: IconSize;
@@ -356,20 +406,15 @@ interface IconSpec {
*
* Grammar:
* <name>
* <name>*<N> e.g. *2, *0.5
* <name>@line (default if no @ given)
* <name>@native
* <name>@<N> CSS px
* <name>*<N>
* <name>@line | @native | @<N>
* <name>@native*<N>
* ^<align> <name> align modifier BEFORE the name
*
* Align modifier comes first: {icon^baseline fish}
* ^<align> <name> (align modifier comes first)
*/
function parseIconSpec(spec: string): IconSpec | null {
let working = spec;
let align: IconAlign = "middle";
// Leading align modifier: ^align
if (working.startsWith("^")) {
const spaceIdx = working.indexOf(" ");
if (spaceIdx === -1) return null;
@@ -380,8 +425,6 @@ function parseIconSpec(spec: string): IconSpec | null {
}
if (working.length === 0) return null;
// Split on @ (size) and * (multiplier), whichever comes first
// Format: name[@size][*mult] or name[*mult] or name[@size]
const sizeIdx = working.indexOf("@");
const multIdx = working.indexOf("*");
@@ -397,7 +440,6 @@ function parseIconSpec(spec: string): IconSpec | null {
let rest = working.slice(nameEnd);
// Parse @size first if present
if (rest.startsWith("@")) {
const afterAt = rest.slice(1);
const starInAfterAt = afterAt.indexOf("*");
@@ -414,7 +456,6 @@ function parseIconSpec(spec: string): IconSpec | null {
}
}
// Parse *multiplier if present
if (rest.startsWith("*")) {
const multStr = rest.slice(1).trim();
const num = parseFloat(multStr);
+23 -7
View File
@@ -11,7 +11,14 @@
/* Enumerations */
/* ------------------------------------------------------------------ */
export type Vowel = "a" | "e" | "i" | "o" | "u";
export type Vowel = "a" | "e" | "i" | "o" | "u" | "oo";
export interface VowelToken {
kind: "vowel";
vowel: Vowel;
shout: boolean;
duration: number;
}
export type SentenceType = "statement" | "question" | "exclamation" | "ellipsis" | "fragment";
@@ -109,7 +116,15 @@ export interface StyleCloseToken {
duration: 0;
}
export type Token = CharToken | PauseToken | SpeedToken | VoiceToken | IconToken | StyleOpenToken | StyleCloseToken;
export type Token =
| VowelToken
| CharToken
| PauseToken
| SpeedToken
| VoiceToken
| IconToken
| StyleOpenToken
| StyleCloseToken;
/* ------------------------------------------------------------------ */
/* Parsed message */
@@ -316,9 +331,10 @@ export const DEFAULT_VOICE = {
};
export const VOWEL_FORMANTS: Record<Vowel, { f1: number; f2: number; f3: number }> = {
a: { f1: 730, f2: 1090, f3: 2440 },
e: { f1: 530, f2: 1840, f3: 2480 },
i: { f1: 270, f2: 2290, f3: 3010 },
o: { f1: 570, f2: 840, f3: 2410 },
u: { f1: 300, f2: 870, f3: 2240 },
a: { f1: 730, f2: 1090, f3: 2440 }, // 'ah' — father
e: { f1: 530, f2: 1840, f3: 2480 }, // 'eh' — bet
i: { f1: 270, f2: 2290, f3: 3010 }, // 'ee' — beet
o: { f1: 570, f2: 840, f3: 2410 }, // 'oh' — go
u: { f1: 640, f2: 1190, f3: 2390 }, // 'uh' — but
oo: { f1: 300, f2: 870, f3: 2240 }, // 'oo' — boot
};
+97 -6
View File
@@ -31,6 +31,7 @@ const REFERENCE_F0 = 200; // Hz at basePitch = 1.0
const MAX_BURST_DURATION = 0.2; // cap on per-burst length
const MIN_BURST_DURATION = 0.03; // floor on per-burst length
const BURST_DURATION_MULTIPLIER = 1.5;
const BURST_MIN_FILL_RATIO = 0.6;
const SCHEDULING_DELAY = 0.02; // 20ms ahead for scheduling safety
const SYNTHESIS_LEAD_TIME = 0.08; // 80ms lead for spreading CPU load
const SYNTHESIS_AMPLITUDE = 0.2; // per-burst base amplitude
@@ -112,6 +113,41 @@ export function planMumble(
}
}
const lastWordBySentence: Array<{
startToken: number;
startTime: number;
duration: number;
}> = [];
for (let s = 0; s < parsed.sentences.length; s++) {
const sent = parsed.sentences[s]!;
let startToken = sent.startToken;
for (let k = sent.endToken - 1; k >= sent.startToken; k--) {
const tok = parsed.tokens[k];
if (!tok) continue;
const isBoundary = (tok.kind === "char" && (tok.ch === " " || tok.ch === "\t")) || tok.kind === "pause";
if (isBoundary) {
startToken = k + 1;
break;
}
}
let startTime = 0;
for (let k = sent.startToken; k < startToken; k++) {
const tok = parsed.tokens[k];
if (tok) startTime += tok.duration;
}
let duration = 0;
for (let k = startToken; k <= sent.endToken; k++) {
const tok = parsed.tokens[k];
if (tok) duration += tok.duration;
}
lastWordBySentence.push({ startToken, startTime, duration });
}
const result: ScheduledBurst[] = [];
let timeOffset = 0;
let currentPitchMult = 1;
@@ -139,6 +175,29 @@ export function planMumble(
if (token.kind === "char") {
if (token.isVowel && token.vowel !== undefined) {
// Detect a run of adjacent vowels. Style tokens are transparent
// (they don't affect audio). Anything else breaks the run.
let runVowel: Vowel = token.vowel;
let runDuration = token.duration;
let runShout = token.shout;
let j = i + 1;
while (j < parsed.tokens.length) {
const next = parsed.tokens[j]!;
if (next.kind === "style-open" || next.kind === "style-close") {
j++;
continue;
}
if (next.kind === "char" && next.isVowel && next.vowel !== undefined) {
runDuration += next.duration;
runShout = runShout || next.shout;
j++;
continue;
}
break;
}
const si = sentenceOfToken[i]!;
const sent = parsed.sentences[si]!;
const sentStart = sentenceStarts[si]!;
@@ -146,37 +205,69 @@ export function planMumble(
const elapsedInSentence = timeOffset - sentStart;
const tNorm = sentDur > 0 ? Math.min(1, Math.max(0, elapsedInSentence / sentDur)) : 0;
let contourMult: number;
if (sent.type === "question") {
const lw = lastWordBySentence[si]!;
if (i >= lw.startToken) {
// Inside the last word — rise
const tInWord = lw.duration > 0 ? (elapsedInSentence - lw.startTime) / lw.duration : 1;
const clampedT = Math.min(1, Math.max(0, tInWord));
contourMult = computeContour(merged.contours.question, clampedT);
} else {
// Before the last word — flat
contourMult = 1.0;
}
} else {
const contourCfg = merged.contours[sent.type];
const contourMult = computeContour(contourCfg, tNorm);
contourMult = computeContour(contourCfg, tNorm);
}
const emotionCfg: EmotionConfig | null = currentMood ? merged.emotions[currentMood] : null;
const emotionMult = emotionCfg?.pitch ?? 1;
const emotionNoise = emotionCfg?.noiseBonus ?? 0;
const shoutMult = token.shout ? 1.2 : 1;
const shoutMult = runShout ? 1.2 : 1;
const variation = 1 + (rng() - 0.5) * 0.04;
const finalPitch =
REFERENCE_F0 * basePitch * contourMult * emotionMult * currentPitchMult * shoutMult * variation;
const rawDur = token.duration * BURST_DURATION_MULTIPLIER;
const rawDur = runDuration * BURST_DURATION_MULTIPLIER;
const clampedDur = Math.min(MAX_BURST_DURATION, Math.max(MIN_BURST_DURATION, rawDur));
const scaledDur = clampedDur / timeScale;
result.push({
const burst: ScheduledBurst = {
atTime: timeOffset / timeScale,
burstDuration: scaledDur,
pitch: finalPitch,
formantScale,
noiseMix: Math.min(1, baseNoise + emotionNoise),
volume: baseVolume * currentVolumeMult,
vowel: token.vowel,
});
vowel: runVowel,
};
result.push(burst);
timeOffset += runDuration;
i = j - 1; // outer loop i++ lands on the token after the run
continue;
}
// Non-vowel char — silent, still advances time
timeOffset += token.duration;
}
}
for (let k = 0; k < result.length - 1; k++) {
const current = result[k]!;
const next = result[k + 1]!;
const intervalToNext = next.atTime - current.atTime;
if (intervalToNext <= 0) continue;
const minForFill = intervalToNext * BURST_MIN_FILL_RATIO;
if (minForFill > current.burstDuration) {
current.burstDuration = Math.min(MAX_BURST_DURATION, minForFill);
}
}
return result;
}
+1 -1
View File
@@ -448,7 +448,7 @@
align: 'center',
padding: { top: 18, right: 16, bottom: 32, left: 16 },
lineHeight: 1.3,
speed: 18
speed: 22
},
timing: { holdLast: 1.8 },
voice: {