the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Worklet on the wasm engine (human + beat paths), TS engine facade and types (WIP)
Jameson Hodgee56b575d73a9
diff --git a/crates/chimera-wasm/src/api.rs b/crates/chimera-wasm/src/api.rsindex 0c86659..a2706c3 100644--- a/crates/chimera-wasm/src/api.rs+++ b/crates/chimera-wasm/src/api.rs@@ -75,6 +75,7 @@ fn dispatch(st: &mut State, req: &Value) -> Res {"glottisPort": a.glottis_port,}))}+ "restTip" => to_json(&chimera::anatomy::human::rest_tip(arg(req, "jaw")?, arg(req, "tbX")?, arg(req, "tbY")?)),"frame" => {let a: HumanArtic = arg(req, "artic")?;let m = model(st, req)?;diff --git a/src/wasm/engine.ts b/src/wasm/engine.tsnew file mode 100644index 0000000..9b80257--- /dev/null+++ b/src/wasm/engine.ts@@ -0,0 +1,248 @@+/**+ * The engine as the UI uses it: constants, planners, G2P, the anatomy model and the creature+ * catalogue, all from the Rust engine (crates/chimera) through its JSON interface. Import only+ * after `initChimera()` has resolved (main.tsx does this before loading any UI module): the+ * constants below are read from the engine when this module loads.+ */+import { call } from "./chimera.ts";+import { CREATURE_VISUALS } from "../ui/creatureVisuals.ts";+import type {+ ArticKey, ArticSpec, BeatPreset, BeatSound, BeatStep, CreatureDef, CreatureTelemetry, DemoSong, Gesture, HumanArtic, HumanBody,+ HumanFrame, Phrase, Plan, Segment, SungNote, Syllable, VoiceSource, VowelRef,+} from "./types.ts";++export type * from "./types.ts";++interface Catalog {+ neutral: HumanArtic;+ bodies: { male: HumanBody; female: HumanBody; child: HumanBody };+ articKeys: ArticKey[];+ articSpecs: Record<ArticKey, ArticSpec>;+ defaultSource: VoiceSource;+ exhaleLabel: string;+ bassNote: number;+ beatSounds: BeatSound[];+ beatPresets: BeatPreset[];+ vowelTargets: Record<string, Record<string, { artic: Partial<HumanArtic>; formants: number[] }>>;+ demoSongs: DemoSong[];+ vowels: VowelRef[];+ creatures: Omit<CreatureDef, "visual">[];+}++const CATALOG = call<Catalog>("catalog");++export const NEUTRAL: Readonly<HumanArtic> = CATALOG.neutral;+export const BODY_MALE: HumanBody = CATALOG.bodies.male;+export const BODY_FEMALE: HumanBody = CATALOG.bodies.female;+export const BODY_CHILD: HumanBody = CATALOG.bodies.child;+export const ARTIC_KEYS: readonly ArticKey[] = CATALOG.articKeys;+export const ARTIC_SPECS: Readonly<Record<ArticKey, ArticSpec>> = CATALOG.articSpecs;+export const DEFAULT_SOURCE: Readonly<VoiceSource> = CATALOG.defaultSource;+/** label of the end-of-breath-group abduction (a live note can drop it when the next one starts) */+export const EXHALE_LABEL: string = CATALOG.exhaleLabel;+/** default hum note of the beatbox bass (MIDI) */+export const BASS_NOTE: number = CATALOG.bassNote;+export const BEAT_SOUNDS: readonly BeatSound[] = CATALOG.beatSounds;+export const BEAT_PRESETS: readonly BeatPreset[] = CATALOG.beatPresets;+/** calibrated vowels per body: articulation and the formants it gives */+export const VOWEL_TARGETS = CATALOG.vowelTargets;+export const DEMO_SONGS: readonly DemoSong[] = CATALOG.demoSongs;+/** reference vowels (IPA chart, vowel map) */+export const VOWELS: readonly VowelRef[] = CATALOG.vowels;+/** the creatures, with how each is drawn */+export const CREATURES: readonly CreatureDef[] = CATALOG.creatures.map((c) => ({ ...c, visual: CREATURE_VISUALS[c.id] }));+export const creatureById = (id: string): CreatureDef | undefined => CREATURES.find((c) => c.id === id);++// ------------------------------------------------------------------ text → phonemes++/** IPA text → segments (stress marks, word breaks, multi-character symbols). */+export function tokenizeIpa(text: string): Segment[] {+ return call("tokenizeIpa", { text });+}++/**+ * English text → phonemes: CMUdict once loaded (fetched and gunzipped here, parsed by the+ * engine), letter-to-sound rules until then. One dictionary per page (the engine keeps it).+ */+export class EnglishG2P {+ private loading: Promise<void> | null = null;+ private isLoaded = false;++ get loaded(): boolean {+ return this.isLoaded;+ }++ /** Load the gzipped dictionary ("word\tPHONES" lines). */+ load(url = "/data/cmudict.txt.gz"): Promise<void> {+ if (this.isLoaded) return Promise.resolve();+ if (this.loading) return this.loading;+ this.loading = (async () => {+ try {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`dictionary ${res.status}`);+ const bytes = new Uint8Array(await res.arrayBuffer());+ // servers differ: some send Content-Encoding: gzip (already inflated by the browser)+ let text: string;+ if (bytes[0] === 0x1f && bytes[1] === 0x8b) {+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));+ text = await new Response(stream).text();+ } else text = new TextDecoder().decode(bytes);+ this.setDictionaryText(text);+ } catch (e) {+ this.loading = null; // allow a retry+ throw e;+ }+ })();+ return this.loading;+ }++ setDictionaryText(text: string): void {+ call("g2pLoad", { text });+ this.isLoaded = true;+ }++ /** Text → phrases of segments. */+ toPhrases(text: string): Phrase[] {+ return call("g2pPhrases", { text });+ }++ /** One word → segments with lexical stress. `reduce`: weak forms of function words (speech). */+ word(w: string, reduce = true): Segment[] {+ return call("g2pWord", { word: w, reduce });+ }+}++/** Lyrics → sung syllables, through the page's dictionary (see EnglishG2P). */+export function lyricsToSyllables(text: string): Syllable[] {+ return call("lyricsToSyllables", { text });+}++// ------------------------------------------------------------------ planning++export interface PlanOptions {+ body: string;+ /** voice-clock start time (s) */+ t0: number;+ /** speaking-rate multiplier (>1 = faster) */+ rate?: number;+ /** baseline pitch (Hz) */+ f0?: number;+ intonation?: "statement" | "question" | "flat";+ /** pitch excursion for stressed syllables (fraction) */+ accent?: number;+ /** the last segment is held open-ended (a sung note): no end-of-breath release */+ openEnd?: boolean;+}++export function planUtterance(segments: Segment[], options: PlanOptions): Plan {+ return call("planUtterance", { segments, options });+}++export function planPhrases(phrases: { segments: Segment[]; intonation?: "statement" | "question" | "flat"; pause?: number }[], options: PlanOptions): Plan {+ return call("planPhrases", { phrases: phrases.map((p) => ({ segments: p.segments, intonation: p.intonation, pause: p.pause })), options });+}++export function planSong(notes: SungNote[], options: { body: string; bpm: number; t0: number; vibrato: number }): Plan {+ return call("planSong", { notes, options });+}++export function planNoteOn(syl: Syllable, midi: number, options: { body: string; vibrato: number; tag: number; legatoFrom?: { syl: Syllable; midi: number } }): Gesture[] {+ return call("planNoteOn", { syl, midi, options });+}++export function planMelisma(midi: number, options: { vibrato: number; tag: number }): Gesture[] {+ return call("planMelisma", { midi, options });+}++export function planNoteOff(syl: Syllable, midi: number, body: string): Gesture[] {+ return call("planNoteOff", { syl, midi, body });+}++/** Smooth activation 0..1..0 with cosine ramps (for drawing the score; the engine's own blend uses its Rust twin). */+export function activation(g: Gesture, t: number): number {+ if (t <= g.t0 - g.rampIn || t >= g.t1 + g.rampOut) return 0;+ if (t < g.t0) return 0.5 - 0.5 * Math.cos((Math.PI * (t - (g.t0 - g.rampIn))) / Math.max(1e-6, g.rampIn));+ if (t > g.t1) return 0.5 + 0.5 * Math.cos((Math.PI * (t - g.t1)) / Math.max(1e-6, g.rampOut));+ return 1;+}++// ------------------------------------------------------------------ beatbox++export function parseBeat(text: string): (BeatStep | null)[] {+ return call("parseBeat", { text });+}++export function formatBeat(steps: readonly (BeatStep | null)[]): string {+ return call("formatBeat", { steps });+}++/** A beatboxer's ready posture for this body. */+export function beatReady(body: string): Partial<HumanArtic> {+ return call("beatReady", { body });+}++// ------------------------------------------------------------------ anatomy++/** Resting tongue-tip position (template coordinates) for a jaw and tongue body. */+export function restTip(jaw: number, tbX: number, tbY: number): { x: number; y: number } {+ return call("restTip", { jaw, tbX, tbY });+}++/** Template ↔ body coordinates of one body (mirrors HumanVocalTract::p / un_p, for drawing and dragging). */+export class TractMap {+ readonly scale: number;+ private readonly ph: number;+ constructor(body: HumanBody) {+ this.scale = body.scale;+ this.ph = body.pharynx;+ }+ P(x: number, y: number): { x: number; y: number } {+ const k = this.scale;+ const xx = x > 0.5 ? 0.5 + (x - 0.5) * 0.86 : x;+ const yy = y < 7 ? 7 - (7 - y) * this.ph : y;+ return { x: xx * k, y: yy * k };+ }+ unP(x: number, y: number): { x: number; y: number } {+ const k = this.scale;+ let xx = x / k, yy = y / k;+ if (xx > 0.5) xx = 0.5 + (xx - 0.5) / 0.86;+ if (yy < 7) yy = 7 - (7 - yy) / this.ph;+ return { x: xx, y: yy };+ }+}++/** The main thread's mirror of the worklet's airway for one body and sample rate. */+export interface AirwayModel {+ model: number;+ body: HumanBody;+ nPh: number;+ nOr: number;+ pharynxBranches: { base: number; n: number };+ oralBranches: { base: number; n: number };+ glottisPort: number;+}++export function airwayModel(body: string, sampleRate: number): AirwayModel {+ return call("model", { body, sampleRate });+}++export function airwayFrame(m: AirwayModel, artic: HumanArtic): HumanFrame {+ return call("frame", { model: m.model, artic });+}++/** The tract's area function (what the worklet's airway would be given) for an articulation. */+export function airwayAreas(m: AirwayModel, artic: HumanArtic): { phAreas: number[]; orAreas: number[]; phLen: number; orLen: number } {+ return call("apply", { model: m.model, artic });+}++/** Transfer function (dB at 360 log-spaced frequencies 60 Hz–8 kHz) and formants. */+export function airwayTransfer(m: AirwayModel, artic: HumanArtic): { freqs: number[]; db: number[]; formants: number[] } {+ return call("transfer", { model: m.model, artic });+}++// ------------------------------------------------------------------ creatures++/** A creature's telemetry right after construction at these settings (drawn before audio starts). */+export function creaturePreview(id: string, params?: Record<string, number>): CreatureTelemetry {+ return call("creaturePreview", { id, params: params ?? {} });+}diff --git a/src/wasm/types.ts b/src/wasm/types.tsindex 6d2f1e6..728ce6e 100644--- a/src/wasm/types.ts+++ b/src/wasm/types.ts@@ -18,3 +18,277 @@ export interface Gesture {/** open-ended gestures (a sung note held until its key is released) end via release(tag) */tag?: number;}++export interface Vec {+ x: number;+ y: number;+}++export interface HumanArtic {+ jaw: number;+ tbX: number;+ tbY: number;+ ttX: number;+ ttY: number;+ ttCurl: number;+ root: number;+ lipAp: number;+ lipProt: number;+ lipWidth: number;+ labiodental: number;+ velum: number;+ larynx: number;+ epilarynx: number;+ ventricular: number;+ lateral: number;+ dorsum: number;+}++export interface HumanBody {+ name: string;+ /** overall size scale (1 = adult male) */+ scale: number;+ /** extra pharynx length scale (female/child have proportionally shorter pharynx) */+ pharynx: number;+ /** tongue body radius (cm, before scale) */+ tongueRadius: number;+ /** max lip width (cm, before scale) */+ lipWidth: number;+}++export interface ArticSpec {+ min: number;+ max: number;+ /** natural frequency (Hz) of the critically damped tracking dynamics */+ hz: number;+}++export interface GridSample {+ inner: Vec;+ outer: Vec;+ mid: Vec;+ d: number;+ area: number;+ s: number;+ region: 0 | 1 | 2 | 3;+ ray: number;+}++export interface HumanFrame {+ outer: Vec[];+ inner: Vec[];+ tongue: Vec[];+ velum: Vec[];+ upperLip: Vec[];+ lowerLip: Vec[];+ upperTeeth: Vec[];+ lowerTeeth: Vec[];+ jawBone: Vec[];+ epiglottis: Vec[];+ nasalCavity: Vec[];+ glottis: Vec;+ grid: GridSample[];+ length: number;+ pharynxLength: number;+ teethS: number;+ lipS: number;+ velumPort: number;+ lipArea: number;+ tongueCenter: Vec;+ tongueRadius: number;+ tip: Vec;+ splitIndex: number;+}++export interface VoiceSource {+ f0: number;+ glide: number;+ pressure: number;+ breathiness: number;+ tension: number;+ fry: number;+ roughness: number;+ vibratoDepth: number;+ vibratoRate: number;+ drift: number;+ voiced: boolean;+}++export interface VoiceTelemetry {+ artic: Float32Array;+ phAreas: Float32Array;+ orAreas: Float32Array;+ phLen: number;+ orLen: number;+ pressureRms: Float32Array;+ flow: Float32Array;+ velumPort: number;+ glottalArea: Float32Array;+ glottalFlow: Float32Array;+ f0: number;+ voicing: number;+ pLung: number;+ outRms: number;+ noiseLevel: number;+ noiseNode: number;+ gate: number;+ /** voice clock (s) for score playheads */+ clock: number;+ /** labels of gestures active now (most recent first) */+ active: string[];+}++export interface Segment {+ ipa: string;+ dur?: number;+ stress?: number;+ f0?: number;+ wordEnd?: boolean;+}++export interface PlannedSegment {+ ipa: string;+ t0: number;+ t1: number;+ stress?: number;+ kind: string;+}++export interface Plan {+ gestures: Gesture[];+ segments: PlannedSegment[];+ end: number;+}++export interface Phrase {+ segments: Segment[];+ intonation: "statement" | "question";+ /** pause after the phrase (s) */+ pause: number;+ words: string[];+}++export interface Syllable {+ text: string;+ onset: Segment[];+ nucleus: Segment;+ coda: Segment[];+ melisma?: boolean;+ wordEnd: boolean;+ phraseEnd: boolean;+}++export interface SungNote {+ midi: number;+ /** length in beats */+ beats: number;+ syl: Syllable;+}++export type BeatRole = "kick" | "snare" | "hat" | "perc" | "bass";+export type Airstream = "pulmonic" | "ejective" | "click" | "ingressive" | "voiced";++export interface BeatStep {+ id: string;+ note?: number;+ accent?: number;+}++/** A beatbox sound as the UI lists it (its gestures are built in the engine). */+export interface BeatSound {+ id: string;+ name: string;+ role: BeatRole;+ airstream: Airstream;+ hint: string;+ latency: number;+}++export interface BeatPreset {+ name: string;+ bpm: number;+ swing: number;+ text: string;+}++export interface DemoSong {+ name: string;+ bpm: number;+ lyrics: string;+ notes: [number, number][];+ octave: { male: number; female: number; child: number };+}++export interface VowelRef {+ ipa: string;+ /** example word / description */+ example: string;+ male: [number, number, number];+ female: [number, number, number];+ child: [number, number, number];+ round: boolean;+ /** 0 close … 1 open */+ height: number;+ /** 0 front … 1 back */+ back: number;+}++export type CreatureGroup = "human" | "bird" | "mammal" | "marine" | "reptile" | "amphibian" | "insect" | "crustacean" | "fantasy";++export interface ParamDef {+ key: string;+ label: string;+ min: number;+ max: number;+ default: number;+ unit?: string;+ log?: boolean;+ /** smoothing time constant (s) */+ smooth?: number;+ /** "pitch" params follow the keyboard */+ role?: "pitch";+ /** decimals for display */+ digits?: number;+}++export interface CallKey {+ t: number;+ v: Record<string, number>;+ curve?: "lin" | "exp" | "step";+}++export interface CallDef {+ id: string;+ name: string;+ hint: string;+ keys: CallKey[];+ pitchRef?: number;+}++/** A creature: the engine's definition joined with its drawing data (src/ui/creatureVisuals.ts). */+export interface CreatureDef {+ id: string;+ name: string;+ latin: string;+ group: CreatureGroup;+ blurb: string;+ role: string;+ oversample: number;+ gateTimes?: { attack: number; release: number };+ params: ParamDef[];+ calls: CallDef[];+ visual: import("../ui/creatureVisuals.ts").CreatureVisual;+}++export interface CreatureTelemetry {+ kind: "creature";+ id: string;+ params: Record<string, number>;+ gate: number;+ outRms: number;+ clock: number;+ /** per tube: areas (cm²) and acoustic pressure RMS (dyn/cm², static pressure removed) per node */+ tubes: Record<string, { areas: Float32Array | number[]; rms: Float32Array | number[] }>;+ source: Record<string, number>;+ call: string | null;+}diff --git a/src/worklet/processor.ts b/src/worklet/processor.tsindex 5d15e2d..40be255 100644--- a/src/worklet/processor.ts+++ b/src/worklet/processor.ts@@ -1,13 +1,14 @@/**- * CHIMERA AudioWorklet processor. Execution contract: message handlers only record state;- * all DSP happens in process(); telemetry is fixed-size and rate-limited (~60 Hz).+ * CHIMERA AudioWorklet processor: the Rust engine (wasm) on the audio thread.+ *+ * Messages map to engine calls as they arrive (between render quanta, on this thread), so their+ * order is the order they take effect. process() renders, measures load and posts fixed-size+ * telemetry (~60 Hz). If the engine traps (a bug), the processor outputs silence from then on and+ * reports once; the main thread may build a new node, which restarts playback state.*/-import { HumanVoice } from "../engine/voice/humanVoice.ts";-import { BODY_MALE, BODY_FEMALE, BODY_CHILD, type HumanBody } from "../engine/anatomy/human.ts";-import type { ToWorklet, FromWorklet, BodyName } from "./protocol.ts";-import { CreatureVoice } from "../engine/creatures/voice.ts";-import { creatureById } from "../engine/creatures/index.ts";-import { BeatPlayer } from "../engine/control/beatPlayer.ts";+import { writeGestures, writeSteps, fromUtf8, utf8, CONTROL_KEYS } from "../wasm/wire.ts";+import type { ToWorklet, FromWorklet, BodyName, TelemetryMessage } from "./protocol.ts";+import type { CreatureTelemetry } from "../wasm/types.ts";// Minimal AudioWorkletGlobalScope typingsdeclare const sampleRate: number;@@ -17,202 +18,237 @@ declare class AudioWorkletProcessor {constructor(options?: unknown);}-const BODIES: Record<BodyName, HumanBody> = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD };-const DEFAULT_F0: Record<BodyName, number> = { male: 110, female: 205, child: 260 };-/** gestures taken from one schedule message (and replayed per block) */+type Fn = (...a: number[]) => number;+type Exports = { memory: WebAssembly.Memory } & Record<string, Fn>;++const BODIES: BodyName[] = ["male", "female", "child"];+const ARTIC_KEYS = CONTROL_KEYS.slice(0, 17);+const SOURCE_KEYS = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced"];+/** scalars at the head of the human telemetry block (crates/chimera-wasm/src/lib.rs) */+const TELE_HEADER = 16;+/** gestures taken from one schedule message */const MAX_GESTURES = 4000;+/** What the engine says about the creature it switched to (crates/chimera-wasm/src/lib.rs). */+interface CreatureInfo {+ id: string;+ params: string[];+ calls: string[];+ tubes: { name: string; n: number }[];+ sources: string[];+}+class ChimeraProcessor extends AudioWorkletProcessor {- private voice: HumanVoice;- private body: BodyName = "male";+ private readonly x: Exports;+ private readonly h: number;+ private failed = false;private telemetryOn = true;private blocks = 0;private load = 0;- private pendingBody: BodyName | null = null;- private creature: CreatureVoice | null = null;- private pendingCreature: string | null = null;- /** params and a call that arrived while a creature switch was pending */- private pendingCreatureParams: Record<string, number> = {};- private pendingCall: { id: string; pitch?: number; amp?: number } | null = null;- private gateLevel = 0;- private beat = new BeatPlayer();- /**- * Score messages that arrived while a body change was pending (they belong to the new voice),- * replayed in order within a per-block budget; later ones wait behind them.- */- private afterBody: ToWorklet[] = [];-- constructor() {- super();- this.voice = this.makeVoice("male");- this.port.onmessage = (e: MessageEvent<ToWorklet>) => this.onMessage(e.data);- this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr, creature: "human" });- }+ private creature: CreatureInfo | null = null;- private makeVoice(body: BodyName): HumanVoice {- const v = new HumanVoice({ fsOut: sampleRate, body: BODIES[body], oversample: sampleRate > 60000 ? 1 : 2 });- v.setSource({ f0: DEFAULT_F0[body] });- return v;+ constructor(options: { processorOptions: { module: WebAssembly.Module } }) {+ super();+ this.x = new WebAssembly.Instance(options.processorOptions.module, {}).exports as unknown as Exports;+ this.h = this.x.engine_new(sampleRate);+ this.port.onmessage = (e: MessageEvent<ToWorklet>) => {+ if (this.failed) return;+ try {+ this.handle(e.data);+ } catch (err) {+ this.fail(err);+ }+ };+ this.postReady();}private post(msg: FromWorklet): void {this.port.postMessage(msg);}- private onMessage(m: ToWorklet): void {- const ordered = m.type === "schedule" || m.type === "release" || m.type === "stopSpeech" || m.type === "beatHit" || m.type === "beat";- if (ordered && (this.pendingBody || this.afterBody.length)) {- this.afterBody.push(m);- return;- }- this.handle(m);+ private fail(err: unknown): void {+ if (this.failed) return;+ this.failed = true;+ this.post({ type: "error", message: `engine stopped: ${String(err)}` });}- /** Replay held-back score messages: at most one full-size schedule's worth per block. */- private replay(): void {- let spent = 0;- while (this.afterBody.length) {- const m = this.afterBody[0];- const cost = m.type === "schedule" ? Math.min(MAX_GESTURES, m.gestures.length) : 1;- if (spent > 0 && spent + cost > MAX_GESTURES) break;- this.afterBody.shift();- this.handle(m);- spent += cost;- }+ private get mem(): ArrayBuffer {+ return this.x.memory.buffer;+ }++ private postReady(): void {+ const x = this.x, h = this.h;+ this.post({ type: "ready", sampleRate, body: BODIES[x.engine_body(h)], nPh: x.engine_n_ph(h), nOr: x.engine_n_or(h), creature: this.creature?.id ?? "human" });+ }++ /** A JSON call on this instance's engine (non-real-time: creature switches). */+ private engineJson<T>(fn: string, args: Record<string, unknown>): T {+ const x = this.x;+ const bytes = utf8(JSON.stringify(args));+ const p = x.chimera_alloc(bytes.length);+ new Uint8Array(this.mem, p, bytes.length).set(bytes);+ const status = x[fn](this.h, p, bytes.length);+ x.chimera_free(p, bytes.length);+ const v = JSON.parse(fromUtf8(new Uint8Array(this.mem, x.chimera_result_ptr(), x.chimera_result_len())));+ if (status !== 0) throw new Error(v.error);+ return v as T;+ }++ /** The engine's value area, cleared to NaN ("unchanged"). */+ private values(): Float64Array {+ return new Float64Array(this.mem, this.x.engine_values(this.h), 32).fill(NaN);}private handle(m: ToWorklet): void {+ const x = this.x, h = this.h;switch (m.type) {case "body":- this.pendingBody = m.body;+ x.engine_set_body(h, Math.max(0, BODIES.indexOf(m.body)));+ this.postReady();break;- case "artic":- this.voice.setArticulation(m.values, m.tipFree);+ case "artic": {+ const v = this.values();+ for (const [k, val] of Object.entries(m.values)) {+ const i = ARTIC_KEYS.indexOf(k as never);+ if (i >= 0 && typeof val === "number") v[i] = val;+ }+ x.engine_set_artic(h, m.tipFree === undefined ? 2 : m.tipFree ? 1 : 0);break;- case "source":- this.voice.setSource(m.values);+ }+ case "source": {+ const v = this.values();+ for (const [k, val] of Object.entries(m.values)) {+ const i = SOURCE_KEYS.indexOf(k);+ if (i >= 0) v[i] = typeof val === "boolean" ? (val ? 1 : 0) : (val as number);+ }+ x.engine_set_source(h);break;+ }case "gate":- this.gateLevel = m.level;- this.voice.setGate(m.level);- this.creature?.setGate(m.level);- break;- case "creature":- this.pendingCreature = m.id;- this.pendingCreatureParams = { ...(m.params ?? {}) };- this.pendingCall = null;- break;- case "cparams":- if (this.pendingCreature !== null) Object.assign(this.pendingCreatureParams, m.values);- else this.creature?.setParams(m.values);- break;- case "call":- if (this.pendingCreature !== null) this.pendingCall = { id: m.id, pitch: m.pitch, amp: m.amp };- else this.creature?.playCall(m.id, m.pitch, m.amp);- break;- case "stopCall":- if (this.pendingCreature !== null) this.pendingCall = null;- else this.creature?.stopCall();+ x.engine_set_gate(h, m.level);break;case "telemetry":this.telemetryOn = m.enabled;break;case "schedule": {- // O(n) time shift onto the voice clock; planning happened on the main thread- const off = this.voice.clock + (m.lead ?? 0.03);- const gs = m.gestures.slice(0, MAX_GESTURES);- for (const g of gs) {- g.t0 += off;- g.t1 += off;- }- if (m.replace) this.voice.cancelScore();- this.voice.schedule(gs);+ // planning happened on the main thread; the engine shifts the gestures onto its clock+ const n = writeGestures(this.mem, x.engine_records(h), m.gestures, MAX_GESTURES);+ const off = x.engine_schedule(h, n, m.lead ?? 0.03, m.replace ? 1 : 0);if (m.segments.length) this.post({ type: "planned", id: m.id, t0: off, end: m.end + off, segments: m.segments.map((s) => ({ ...s, t0: s.t0 + off, t1: s.t1 + off })) });break;}case "stopSpeech":- this.voice.cancelScore();+ x.engine_stop_speech(h);+ break;+ case "release":+ x.engine_release(h, m.tag);break;case "beat": {- const b = this.beat;- if (m.steps) b.steps = m.steps.slice(0, 128);- if (m.bpm !== undefined || m.swing !== undefined) b.setTempo(m.bpm ?? b.bpm, m.swing ?? b.swing);- if (m.playing === true && !b.playing) b.start(this.voice.clock);- if (m.playing === false && b.playing) {- b.stop();- // hits already scheduled within the horizon would still sound- this.voice.cancelScore();- }+ const n = m.steps ? writeSteps(this.mem, x.engine_records(h), m.steps) : 0;+ x.engine_set_beat(h, m.steps ? 1 : 0, n, m.bpm ?? NaN, m.swing ?? NaN, m.playing === undefined ? 2 : m.playing ? 1 : 0);break;}- case "release":- this.voice.release(m.tag);+ case "beatHit":+ writeSteps(this.mem, x.engine_records(h), [{ id: m.id, note: m.note, accent: m.accent }]);+ x.engine_beat_hit(h);break;- case "beatHit": {- const hit = this.voice.clock + BeatPlayer.leadIn(m.id, this.body);- this.voice.schedule(this.beat.gestures({ id: m.id, note: m.note, accent: m.accent }, hit, 0.18));+ case "creature":+ this.creature = m.id === "human" ? (x.engine_set_human(h), null) : this.engineJson<CreatureInfo>("engine_set_creature", { id: m.id, params: m.params ?? {} });+ this.postReady();+ break;+ case "cparams": {+ const c = this.creature;+ if (!c) break;+ for (const [k, val] of Object.entries(m.values)) {+ const i = c.params.indexOf(k);+ if (i >= 0) x.engine_creature_param(h, i, val);+ }break;}+ case "call": {+ const i = this.creature ? this.creature.calls.indexOf(m.id) : -1;+ if (i >= 0) x.engine_play_call(h, i, m.pitch ?? NaN, m.amp ?? NaN);+ break;+ }+ case "stopCall":+ x.engine_stop_call(h);+ break;}}process(_inputs: Float32Array[][], outputs: Float32Array[][]): boolean {const out = outputs[0];if (!out || out.length === 0) return true;- if (this.pendingBody) {- // carry the performer's settings across the body change- const prev = this.voice;- this.body = this.pendingBody;- this.pendingBody = null;- this.voice = this.makeVoice(this.body);- // the new voice's clock starts at zero: keep the beat's phase across the switch, and- // queue again the hits the old voice's score was holding (built for the new body)- this.beat.body = this.body;- this.beat.rebase(this.voice.clock - prev.clock);- this.beat.rewind(this.voice.clock);- this.voice.setSource({ ...prev.source, f0: DEFAULT_F0[this.body] });- this.voice.setArticulation({ ...prev.artic.target }, prev.artic.tipFree);- // the performer's breath, not the voice's (which includes breath from the score)- this.voice.setGate(this.gateLevel);- this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr, creature: this.creature ? this.creature.def.id : "human" });- }- if (this.afterBody.length && !this.pendingBody) this.replay();- if (this.pendingCreature !== null) {- const id = this.pendingCreature;- this.pendingCreature = null;- if (id === "human") this.creature = null;- else {- const def = creatureById(id);- if (def) {- this.creature = new CreatureVoice(def, sampleRate, this.pendingCreatureParams);- this.creature.setGate(this.gateLevel);- if (this.pendingCall) this.creature.playCall(this.pendingCall.id, this.pendingCall.pitch, this.pendingCall.amp);- }- }- this.pendingCreatureParams = {};- this.pendingCall = null;- this.post({ type: "ready", sampleRate, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr, creature: this.creature ? this.creature.def.id : "human" });- }const ch0 = out[0];- if (!this.creature) this.beat.tick(this.voice.clock, (gs) => this.voice.schedule(gs));+ if (this.failed) {+ for (const ch of out) ch.fill(0);+ return true;+ }const t0 = Date.now();try {- if (this.creature) this.creature.render(ch0, 0, ch0.length);- else this.voice.render(ch0, 0, ch0.length);+ const p = this.x.engine_render(this.h, ch0.length);+ ch0.set(new Float32Array(this.mem, p, ch0.length));} catch (err) {ch0.fill(0);- this.post({ type: "error", message: String(err) });+ this.fail(err);}for (let c = 1; c < out.length; c++) out[c].set(ch0);const dt = Date.now() - t0;const budget = (ch0.length / sampleRate) * 1000;this.load += 0.05 * (dt / budget - this.load);- if (this.telemetryOn && ++this.blocks % 6 === 0) {- if (this.creature) this.post({ type: "ctelemetry", t: this.creature.telemetry(), load: this.load });- else this.post({ type: "telemetry", t: this.voice.telemetry(), load: this.load, body: this.body, nPh: this.voice.airway.nPh, nOr: this.voice.airway.nOr, beatStep: this.beat.stepAt(this.voice.clock) });+ if (this.telemetryOn && !this.failed && ++this.blocks % 6 === 0) {+ try {+ if (this.creature) this.post({ type: "ctelemetry", t: this.creatureTelemetry(this.creature), load: this.load });+ else this.post(this.humanTelemetry());+ } catch (err) {+ this.fail(err);+ }}return true;}++ /** The human voice's telemetry block → the message the UI reads. */+ private humanTelemetry(): TelemetryMessage {+ const x = this.x, h = this.h;+ const p = x.engine_telemetry(h);+ const [phLen, orLen, velumPort, f0, voicing, pLung, outRms, noiseLevel, noiseNode, gate, clock, nArtic, nPh, nOr, nScope, nActive] = new Float64Array(this.mem, p, TELE_HEADER);+ const all = new Float64Array(this.mem, p, TELE_HEADER + nArtic + 3 * (nPh + nOr) + 2 * nScope);+ let o = TELE_HEADER;+ const take = (n: number) => Float32Array.from(all.subarray(o, (o += n)));+ const artic = take(nArtic), phAreas = take(nPh), orAreas = take(nOr), pressureRms = take(nPh + nOr), flow = take(nPh + nOr), glottalArea = take(nScope), glottalFlow = take(nScope);+ const labels = new Uint8Array(this.mem, x.engine_tele_labels(h), 4 * 25);+ const active: string[] = [];+ for (let i = 0; i < nActive; i++) active.push(fromUtf8(labels.subarray(i * 25 + 1, i * 25 + 1 + labels[i * 25])));+ return {+ type: "telemetry",+ t: { artic, phAreas, orAreas, phLen, orLen, pressureRms, flow, velumPort, glottalArea, glottalFlow, f0, voicing, pLung, outRms, noiseLevel, noiseNode, gate, clock, active },+ load: this.load,+ body: BODIES[x.engine_body(h)],+ nPh,+ nOr,+ beatStep: x.engine_beat_step(h),+ };+ }++ /** A creature's telemetry block → the message the UI reads (names from the switch's info). */+ private creatureTelemetry(c: CreatureInfo): CreatureTelemetry {+ const x = this.x, h = this.h;+ const len = 4 + c.params.length + c.tubes.reduce((s, t) => s + 2 * t.n, 0) + c.sources.length;+ const b = new Float64Array(this.mem, x.engine_creature_telemetry(h), len);+ const [gate, outRms, clock, call] = b;+ let o = 4;+ const params: Record<string, number> = {};+ for (const k of c.params) params[k] = b[o++];+ const tubes: CreatureTelemetry["tubes"] = {};+ for (const t of c.tubes) {+ const areas = Float32Array.from(b.subarray(o, (o += t.n)));+ const rms = Float32Array.from(b.subarray(o, (o += t.n)));+ tubes[t.name] = { areas, rms };+ }+ const source: Record<string, number> = {};+ for (const k of c.sources) source[k] = b[o++];+ return { kind: "creature", id: c.id, params, gate, outRms, clock, tubes, source, call: call >= 0 ? c.calls[call] : null };+ }}registerProcessor("chimera", ChimeraProcessor);