@escapeaihq/client-core 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -0
  3. package/dist/api.d.ts +836 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +781 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/audio.d.ts +278 -0
  8. package/dist/audio.d.ts.map +1 -0
  9. package/dist/audio.js +758 -0
  10. package/dist/audio.js.map +1 -0
  11. package/dist/audioProtocol.d.ts +101 -0
  12. package/dist/audioProtocol.d.ts.map +1 -0
  13. package/dist/audioProtocol.js +62 -0
  14. package/dist/audioProtocol.js.map +1 -0
  15. package/dist/index.d.ts +28 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +28 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/visemeGeometry.d.ts +198 -0
  20. package/dist/visemeGeometry.d.ts.map +1 -0
  21. package/dist/visemeGeometry.js +297 -0
  22. package/dist/visemeGeometry.js.map +1 -0
  23. package/dist/visemeScheduler.d.ts +28 -0
  24. package/dist/visemeScheduler.d.ts.map +1 -0
  25. package/dist/visemeScheduler.js +94 -0
  26. package/dist/visemeScheduler.js.map +1 -0
  27. package/dist/websocket.d.ts +196 -0
  28. package/dist/websocket.d.ts.map +1 -0
  29. package/dist/websocket.js +250 -0
  30. package/dist/websocket.js.map +1 -0
  31. package/package.json +40 -0
  32. package/src/__tests__/api-pollers.test.ts +524 -0
  33. package/src/__tests__/audio.test.ts +714 -0
  34. package/src/__tests__/visemeGeometry.test.ts +465 -0
  35. package/src/__tests__/visemeScheduler.test.ts +256 -0
  36. package/src/api.ts +1577 -0
  37. package/src/audio.ts +934 -0
  38. package/src/audioProtocol.ts +163 -0
  39. package/src/index.ts +28 -0
  40. package/src/visemeGeometry.ts +353 -0
  41. package/src/visemeScheduler.ts +133 -0
  42. package/src/websocket.ts +385 -0
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Audio WebSocket protocol helpers aligned with shared/audio_protocol.py
3
+ */
4
+
5
+ export const TAG_MIC = 0x01; // Client → Server (microphone input)
6
+ export const TAG_AI = 0x02; // Server → Client (AI speech output)
7
+
8
+ // PCM16 format constants (legacy)
9
+ export const SAMPLE_RATE = 16000;
10
+ export const BIT_DEPTH = 16;
11
+ export const CHANNELS = 1;
12
+ export const FRAME_DURATION_MS = 20;
13
+ export const SAMPLES_PER_FRAME = (SAMPLE_RATE * FRAME_DURATION_MS) / 1000; // 320 samples
14
+ export const BYTES_PER_SAMPLE = BIT_DEPTH / 8; // 2 bytes
15
+ export const FRAME_BYTES = SAMPLES_PER_FRAME * BYTES_PER_SAMPLE; // 640 bytes
16
+ export const WIRE_FRAME_BYTES = 1 + FRAME_BYTES; // tag + PCM payload
17
+
18
+ export const HELLO_VERSION = '1.0';
19
+
20
+ // Audio format type — PCM16 is the only supported format
21
+ export type AudioFormat = 'PCM16';
22
+
23
+ export type AudioFrame = {
24
+ tag: number;
25
+ audio: Int16Array;
26
+ };
27
+
28
+ export const encodeAudioFrame = (tag: number, audio: Uint8Array | Int16Array): Uint8Array => {
29
+ if (audio.byteLength !== FRAME_BYTES) {
30
+ throw new Error(`Invalid audio size: expected ${FRAME_BYTES} bytes, got ${audio.byteLength}`);
31
+ }
32
+ if (tag !== TAG_MIC && tag !== TAG_AI) {
33
+ throw new Error(`Invalid tag ${tag}`);
34
+ }
35
+
36
+ const tagged = new Uint8Array(WIRE_FRAME_BYTES);
37
+ tagged[0] = tag;
38
+ tagged.set(new Uint8Array(audio.buffer, audio.byteOffset, audio.byteLength), 1);
39
+ return tagged;
40
+ };
41
+
42
+ export const decodeAudioFrame = (data: ArrayBuffer): AudioFrame => {
43
+ if (data.byteLength !== WIRE_FRAME_BYTES) {
44
+ throw new Error(`Invalid frame length ${data.byteLength}, expected ${WIRE_FRAME_BYTES}`);
45
+ }
46
+
47
+ const view = new DataView(data);
48
+ const tag = view.getUint8(0);
49
+ if (tag !== TAG_MIC && tag !== TAG_AI) {
50
+ throw new Error(`Invalid frame tag ${tag}`);
51
+ }
52
+
53
+ const audio = new Int16Array(data.slice(1));
54
+ return { tag, audio };
55
+ };
56
+
57
+ export const isValidAudioFrameLength = (data: ArrayBuffer | Uint8Array): boolean =>
58
+ data.byteLength === WIRE_FRAME_BYTES;
59
+
60
+ // ─────────────────────────────────────────────────────────────
61
+ // Phoneme / Viseme Types (for lip-sync animation)
62
+ // ─────────────────────────────────────────────────────────────
63
+
64
+ /**
65
+ * Single phoneme timing info from Inworld TTS 1.5.
66
+ * Maps to backend shared/audio_protocol.py PhonemeInfo.
67
+ */
68
+ export interface PhonemeInfo {
69
+ phoneSymbol: string;
70
+ startTime: number;
71
+ duration: number;
72
+ visemeSymbol: string;
73
+ }
74
+
75
+ /**
76
+ * Per-word phoneme details from Inworld TTS 1.5.
77
+ * Maps to backend shared/audio_protocol.py WordPhonemeInfo.
78
+ */
79
+ export interface WordPhonemeInfo {
80
+ wordIndex: number;
81
+ phones: PhonemeInfo[];
82
+ }
83
+
84
+ // ─────────────────────────────────────────────────────────────
85
+ // Barge-In Protocol Types
86
+ // ─────────────────────────────────────────────────────────────
87
+
88
+ /**
89
+ * Word-level timing information for audio playback tracking.
90
+ */
91
+ export interface WordTimestampInfo {
92
+ word: string;
93
+ startTime: number;
94
+ endTime: number;
95
+ }
96
+
97
+ /**
98
+ * Client message to report current playback position.
99
+ * Sent periodically (e.g., every 100ms) during audio playback.
100
+ */
101
+ export interface PlaybackPositionMessage {
102
+ action: 'playback_position';
103
+ position: number;
104
+ }
105
+
106
+ /**
107
+ * Client message to trigger barge-in interruption.
108
+ */
109
+ export interface BargeInMessage {
110
+ action: 'barge_in';
111
+ }
112
+
113
+ /**
114
+ * Server acknowledgment of barge-in with spoken content details.
115
+ */
116
+ export interface BargeInAckMessage {
117
+ type: 'barge_in_ack';
118
+ spokenText: string;
119
+ cancelledText: string;
120
+ interruptionTime: number;
121
+ wordsSpoken: string[];
122
+ }
123
+
124
+ /**
125
+ * Server message with audio metadata including word timestamps.
126
+ */
127
+ export interface AudioMetadataMessage {
128
+ type: 'audio_metadata';
129
+ chunkId: string;
130
+ wordTimestamps: WordTimestampInfo[];
131
+ phonemes?: WordPhonemeInfo[];
132
+ processedChars: number;
133
+ isFinal: boolean;
134
+ cumulativeTime: number;
135
+ }
136
+
137
+ /**
138
+ * Helper to create a playback position message.
139
+ */
140
+ export const buildPlaybackPositionMessage = (position: number): PlaybackPositionMessage => ({
141
+ action: 'playback_position',
142
+ position,
143
+ });
144
+
145
+ /**
146
+ * Helper to create a barge-in message.
147
+ */
148
+ export const buildBargeInMessage = (): BargeInMessage => ({
149
+ action: 'barge_in',
150
+ });
151
+
152
+ /**
153
+ * Check if a message is a barge-in acknowledgment.
154
+ */
155
+ export const isBargeInAck = (msg: unknown): msg is BargeInAckMessage =>
156
+ typeof msg === 'object' && msg !== null && (msg as BargeInAckMessage).type === 'barge_in_ack';
157
+
158
+ /**
159
+ * Check if a message is audio metadata.
160
+ */
161
+ export const isAudioMetadata = (msg: unknown): msg is AudioMetadataMessage =>
162
+ typeof msg === 'object' && msg !== null && (msg as AudioMetadataMessage).type === 'audio_metadata';
163
+
package/src/index.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @escapeaihq/client-core
3
+ *
4
+ * Framework-agnostic Seer client building blocks. Imported by both the
5
+ * React web/ app in this repo and the Vue web-app sibling repo.
6
+ *
7
+ * - Audio I/O over WebSocket (mic capture, TTS playback, barge-in)
8
+ * - Viseme lip-sync timed against AudioContext.currentTime
9
+ * - Mouth-region geometry helpers (donut paths, clip ellipses)
10
+ * - Chat WebSocket multiplexer with auto-reconnect
11
+ *
12
+ * **Collision warning when adding exports.** Per ESM semantics, when two
13
+ * `export *` sources re-export the same name, the aggregated binding
14
+ * becomes an *ambiguous export* — at least Node and Vite report it as
15
+ * "module has no export named X" the first time a consumer touches the
16
+ * symbol, which can look like a missing export rather than a collision.
17
+ * One known case has already been resolved: `AudioFormat` is owned by
18
+ * `audioProtocol` and consumed in `api.ts` via `import type`. Before
19
+ * adding a new export, grep this src/ tree for the symbol name to avoid
20
+ * a fresh collision.
21
+ */
22
+
23
+ export * from './audioProtocol';
24
+ export * from './audio';
25
+ export * from './visemeScheduler';
26
+ export * from './visemeGeometry';
27
+ export * from './websocket';
28
+ export * from './api';
@@ -0,0 +1,353 @@
1
+ /**
2
+ * Geometry helpers for viseme bundle rendering.
3
+ *
4
+ * Pure functions that derive clip / mask / inner-lip geometry from the
5
+ * existing `mouth_paths` data so the chat-ws UI doesn't need any new
6
+ * server-side fields. Kept side-effect-free so they can be unit tested
7
+ * without rendering a React tree.
8
+ */
9
+
10
+ export interface Point {
11
+ x: number;
12
+ y: number;
13
+ }
14
+
15
+ /**
16
+ * Parse the (x, y) numeric pairs out of an SVG path `d` string.
17
+ *
18
+ * Our viseme paths are always M + 4×C with 13 explicit points (1 anchor +
19
+ * 4 segments × (2 controls + 1 endpoint)). Returning an array regardless
20
+ * of command structure keeps this useful for any of our paths — the bbox
21
+ * is conservative because it's the convex hull of *control points*, which
22
+ * always contains the rendered Bézier curve.
23
+ */
24
+ export function parsePathPoints(d: string): Point[] {
25
+ const numbers = d.match(/-?\d+(?:\.\d+)?/g) ?? [];
26
+ const points: Point[] = [];
27
+ for (let i = 0; i + 1 < numbers.length; i += 2) {
28
+ points.push({ x: parseFloat(numbers[i]), y: parseFloat(numbers[i + 1]) });
29
+ }
30
+ return points;
31
+ }
32
+
33
+ /** Axis-aligned bounding box of a list of points. */
34
+ export interface BBox {
35
+ minX: number;
36
+ maxX: number;
37
+ minY: number;
38
+ maxY: number;
39
+ }
40
+
41
+ export function pointsBBox(points: Point[]): BBox | null {
42
+ if (points.length === 0) return null;
43
+ let minX = Infinity;
44
+ let maxX = -Infinity;
45
+ let minY = Infinity;
46
+ let maxY = -Infinity;
47
+ for (const p of points) {
48
+ if (p.x < minX) minX = p.x;
49
+ if (p.x > maxX) maxX = p.x;
50
+ if (p.y < minY) minY = p.y;
51
+ if (p.y > maxY) maxY = p.y;
52
+ }
53
+ return { minX, maxX, minY, maxY };
54
+ }
55
+
56
+ /**
57
+ * Union of all viseme paths' control-point bboxes.
58
+ *
59
+ * Returns null if the input is empty or no path produces any points
60
+ * (defensive — callers should fall back to the hand-authored geometry).
61
+ */
62
+ export function unionMouthPathsBBox(
63
+ mouthPaths: Record<string, string>,
64
+ ): BBox | null {
65
+ let result: BBox | null = null;
66
+ for (const d of Object.values(mouthPaths)) {
67
+ const bb = pointsBBox(parsePathPoints(d));
68
+ if (!bb) continue;
69
+ if (!result) {
70
+ result = { ...bb };
71
+ } else {
72
+ result.minX = Math.min(result.minX, bb.minX);
73
+ result.maxX = Math.max(result.maxX, bb.maxX);
74
+ result.minY = Math.min(result.minY, bb.minY);
75
+ result.maxY = Math.max(result.maxY, bb.maxY);
76
+ }
77
+ }
78
+ return result;
79
+ }
80
+
81
+ export interface ClipEllipse {
82
+ cx: number;
83
+ cy: number;
84
+ rx: number;
85
+ ry: number;
86
+ /** Gaussian-blur stdDeviation for feathering the ellipse edge. */
87
+ featherStdDev: number;
88
+ }
89
+
90
+ /** Defaults for the mouth clip ellipse — exported so tuning UI sliders
91
+ * can label the slider middle and tests can verify edge cases without
92
+ * importing implementation magic numbers. */
93
+ export const DEFAULT_CLIP_MARGIN_X = 1.6;
94
+ export const DEFAULT_CLIP_MARGIN_Y = 1.8;
95
+ export const DEFAULT_FEATHER_FACTOR = 0.1;
96
+
97
+ export interface ClipEllipseOverrides {
98
+ marginX?: number;
99
+ marginY?: number;
100
+ featherFactor?: number;
101
+ }
102
+
103
+ /**
104
+ * Compute a feathered mouth-region clip ellipse from the union of all
105
+ * viseme outer-lip path bboxes.
106
+ *
107
+ * Default margin factors:
108
+ * - Horizontal: 1.6 (sqrt(2) ≈ 1.41 to inscribe corners + ~13% padding)
109
+ * - Vertical: 1.8 (more padding for `aei` / `o` which extend down)
110
+ *
111
+ * Feather: min(rx, ry) · 0.10 so the seam between body SVG and PNG is
112
+ * indiscernible. With normal alpha compositing the feather edge sums to
113
+ * 1.0 coverage at all points (PNG·α + body·(1-α) = 1).
114
+ *
115
+ * Optional overrides let the persona-tuner UI tweak these in real time.
116
+ */
117
+ export function computeMouthClipEllipse(
118
+ mouthPaths: Record<string, string>,
119
+ overrides?: ClipEllipseOverrides,
120
+ ): ClipEllipse | null {
121
+ const bbox = unionMouthPathsBBox(mouthPaths);
122
+ if (!bbox) return null;
123
+ const marginX = overrides?.marginX ?? DEFAULT_CLIP_MARGIN_X;
124
+ const marginY = overrides?.marginY ?? DEFAULT_CLIP_MARGIN_Y;
125
+ const featherFactor = overrides?.featherFactor ?? DEFAULT_FEATHER_FACTOR;
126
+ const cx = (bbox.minX + bbox.maxX) / 2;
127
+ const cy = (bbox.minY + bbox.maxY) / 2;
128
+ const halfWidth = (bbox.maxX - bbox.minX) / 2;
129
+ const halfHeight = (bbox.maxY - bbox.minY) / 2;
130
+ const rx = halfWidth * marginX;
131
+ const ry = halfHeight * marginY;
132
+ const featherStdDev = Math.max(1, Math.min(rx, ry) * featherFactor);
133
+ return { cx, cy, rx, ry, featherStdDev };
134
+ }
135
+
136
+ /**
137
+ * Lip thickness as a fraction of the outer mouth height. The inner lip
138
+ * ring is shrunk vertically by this much from each side, so the inner
139
+ * ring is `(1 - 2·LIP_THICKNESS_FRACTION)` of the outer height. With
140
+ * the current value (0.25) the inner ring is exactly half the outer
141
+ * ring's height.
142
+ */
143
+ export const LIP_THICKNESS_FRACTION = 0.25;
144
+
145
+ const TWO_DECIMALS = (n: number): string => n.toFixed(2);
146
+ const formatPoint = (p: Point): string =>
147
+ `${TWO_DECIMALS(p.x)},${TWO_DECIMALS(p.y)}`;
148
+
149
+ /**
150
+ * Derive an inner-lip path from the outer-lip path that morphs
151
+ * synchronously with it (same M+4C topology, 13 points).
152
+ *
153
+ * The outer path's anchors are: Left (M start), Up (end of C1), Right
154
+ * (end of C2), Lo (end of C3), back to Left (end of C4). Mouth corners
155
+ * (Left, Right) are physical pinch points and don't move when the lip
156
+ * thickens or thins. Up/Lo midpoints DO move — they shift toward the
157
+ * vertical centroid by `LIP_THICKNESS_FRACTION · h` each, so the inner
158
+ * ring height is `h · (1 - 2·LIP_THICKNESS_FRACTION)`.
159
+ *
160
+ * Bezier control points are shifted vertically by linear interp along
161
+ * each segment so the inner curve preserves the bulge shape of the
162
+ * outer curve (rather than collapsing to straight diamond edges).
163
+ *
164
+ * Properties:
165
+ * - Topology unchanged (M + 4C → 13 points → 26 numbers). Required for
166
+ * WAAPI d-string interpolation between visemes.
167
+ * - At rest (h ≈ 1-3 px), inner ring is a thin sliver — visually a
168
+ * hairline shadow between lips. Anatomically correct.
169
+ * - At fully open (h ≈ 100 px for `aei`), inner ring opens to expose
170
+ * the inner-mouth backdrop + teeth + tongue.
171
+ *
172
+ * Defensive falls back to returning the outer path unchanged if the
173
+ * input doesn't have the expected 13-point topology or the height is
174
+ * non-positive (degenerate path).
175
+ */
176
+ export function deriveInnerLipPath(
177
+ outerD: string,
178
+ overrides?: { lipThicknessFraction?: number },
179
+ ): string {
180
+ const points = parsePathPoints(outerD);
181
+ if (points.length !== 13) return outerD;
182
+
183
+ const Left = points[0];
184
+ const Up = points[3];
185
+ const Right = points[6];
186
+ const Lo = points[9];
187
+ const h = Lo.y - Up.y;
188
+ if (h <= 0) return outerD;
189
+
190
+ const fraction = overrides?.lipThicknessFraction ?? LIP_THICKNESS_FRACTION;
191
+ const shift = h * fraction;
192
+
193
+ // Inner anchors — corners stay, midpoints shift toward centroid.
194
+ const innerUp: Point = { x: Up.x, y: Up.y + shift };
195
+ const innerLo: Point = { x: Lo.x, y: Lo.y - shift };
196
+
197
+ // Bezier control shift: linear interp along each segment so the
198
+ // bulge shape is preserved relative to the (now-shorter) baseline.
199
+ // For a control at parametric position t along the segment, vertical
200
+ // shift = anchor_shift · (t at end-anchor side, 1-t at start side).
201
+ const c1_1: Point = { x: points[1].x, y: points[1].y + shift * (1 / 3) };
202
+ const c1_2: Point = { x: points[2].x, y: points[2].y + shift * (2 / 3) };
203
+ const c2_1: Point = { x: points[4].x, y: points[4].y + shift * (2 / 3) };
204
+ const c2_2: Point = { x: points[5].x, y: points[5].y + shift * (1 / 3) };
205
+ const c3_1: Point = { x: points[7].x, y: points[7].y - shift * (1 / 3) };
206
+ const c3_2: Point = { x: points[8].x, y: points[8].y - shift * (2 / 3) };
207
+ const c4_1: Point = { x: points[10].x, y: points[10].y - shift * (2 / 3) };
208
+ const c4_2: Point = { x: points[11].x, y: points[11].y - shift * (1 / 3) };
209
+
210
+ return (
211
+ `M ${formatPoint(Left)} ` +
212
+ `C ${formatPoint(c1_1)} ${formatPoint(c1_2)} ${formatPoint(innerUp)} ` +
213
+ `C ${formatPoint(c2_1)} ${formatPoint(c2_2)} ${formatPoint(Right)} ` +
214
+ `C ${formatPoint(c3_1)} ${formatPoint(c3_2)} ${formatPoint(innerLo)} ` +
215
+ `C ${formatPoint(c4_1)} ${formatPoint(c4_2)} ${formatPoint(Left)}`
216
+ );
217
+ }
218
+
219
+ /**
220
+ * Combine outer + inner lip paths into a donut path renderable with
221
+ * `fill-rule="evenodd"`. A point inside an odd number of subpaths is
222
+ * filled — so inside outer + outside inner = filled (lip flesh);
223
+ * inside both = unfilled (mouth opening).
224
+ *
225
+ * The combined string preserves both subpath topologies — for two
226
+ * M+4C paths that's 2M + 8C = 26 points = 52 numbers, identical
227
+ * across all visemes. WAAPI interpolates linearly.
228
+ */
229
+ export function combineDonutPath(outerD: string, innerD: string): string {
230
+ return `${outerD} ${innerD}`;
231
+ }
232
+
233
+ export interface TeethTongueGeom {
234
+ upperTeeth: { x: number; y: number; width: number; height: number };
235
+ lowerTeeth: { x: number; y: number; width: number; height: number };
236
+ tongue: { cx: number; cy: number; rx: number; ry: number };
237
+ }
238
+
239
+ /**
240
+ * Compute static teeth + tongue positions sized to fit inside the
241
+ * largest mouth opening across all visemes (the union bbox).
242
+ *
243
+ * These shapes are clipped at render time to the morphing inner lip
244
+ * ring. When the mouth is closed (inner ring degenerate), the clip
245
+ * reveals nothing. When open (`aei`/`o`), the clip exposes upper
246
+ * teeth → tongue → lower teeth from top to bottom.
247
+ *
248
+ * Layout proportions of the union bbox half-extents (hw, hh):
249
+ * - upper teeth: rectangle covering top 30% of the inner area
250
+ * (y range [cy-0.5hh, cy-0.2hh]), 70% of the width on each side
251
+ * - lower teeth: same width, bottom 30% (y [cy+0.2hh, cy+0.5hh])
252
+ * - tongue: ellipse centered slightly below center, 60% horizontal
253
+ * radius, 20% vertical radius
254
+ */
255
+ export function computeTeethTongueGeom(
256
+ mouthPaths: Record<string, string>,
257
+ ): TeethTongueGeom | null {
258
+ const bbox = unionMouthPathsBBox(mouthPaths);
259
+ if (!bbox) return null;
260
+ const cx = (bbox.minX + bbox.maxX) / 2;
261
+ const cy = (bbox.minY + bbox.maxY) / 2;
262
+ const hw = (bbox.maxX - bbox.minX) / 2;
263
+ const hh = (bbox.maxY - bbox.minY) / 2;
264
+ const teethWidth = hw * 1.4;
265
+ return {
266
+ upperTeeth: {
267
+ x: cx - hw * 0.7,
268
+ y: cy - hh * 0.5,
269
+ width: teethWidth,
270
+ height: hh * 0.3,
271
+ },
272
+ lowerTeeth: {
273
+ x: cx - hw * 0.7,
274
+ y: cy + hh * 0.2,
275
+ width: teethWidth,
276
+ height: hh * 0.3,
277
+ },
278
+ tongue: {
279
+ cx,
280
+ cy: cy + hh * 0.1,
281
+ rx: hw * 0.6,
282
+ ry: hh * 0.2,
283
+ },
284
+ };
285
+ }
286
+
287
+ /**
288
+ * Default inner-mouth color palette. Hardcoded for now to avoid a
289
+ * round-trip through bundle regeneration; can be replaced with sampled
290
+ * colors once we add a backend extraction step.
291
+ */
292
+ export const INNER_MOUTH_COLORS = {
293
+ interior: '#3d1a14', // dark reddish brown
294
+ teeth: '#f4ecd6', // off-white, slightly yellow
295
+ tongue: '#a44d52', // muted pink
296
+ };
297
+
298
+ /**
299
+ * Per-viseme "openness" — outer mouth height (Lo.y - Up.y) min/max
300
+ * normalized across all visemes in this bundle.
301
+ *
302
+ * The result is in [0, 1] where 0 means the most closed-mouth viseme
303
+ * (typically `bmp` or `rest`) and 1 means the most open (typically
304
+ * `aei`). Returns null for malformed inputs.
305
+ *
306
+ * Used to drive teeth/tongue visibility: closed visemes show no teeth
307
+ * even though the inner-lip-ring clip would technically reveal a thin
308
+ * sliver of them.
309
+ */
310
+ export function computeVisemeOpenness(
311
+ mouthPaths: Record<string, string>,
312
+ ): Record<string, number> | null {
313
+ const heights: Record<string, number> = {};
314
+ for (const [v, d] of Object.entries(mouthPaths)) {
315
+ const points = parsePathPoints(d);
316
+ if (points.length !== 13) continue;
317
+ const h = points[9].y - points[3].y;
318
+ if (h > 0) heights[v] = h;
319
+ }
320
+ const values = Object.values(heights);
321
+ if (values.length === 0) return null;
322
+ const minH = Math.min(...values);
323
+ const maxH = Math.max(...values);
324
+ const range = maxH - minH;
325
+ const result: Record<string, number> = {};
326
+ for (const [v, h] of Object.entries(heights)) {
327
+ result[v] = range > 0 ? (h - minH) / range : 0;
328
+ }
329
+ return result;
330
+ }
331
+
332
+ /**
333
+ * Map a per-viseme openness in [0, 1] to a teeth/tongue opacity in
334
+ * [0, 1] via a soft floor.
335
+ *
336
+ * Below `OPENNESS_FLOOR` (15% of the range), opacity is 0 — the closed
337
+ * visemes (`bmp`, `rest`, often `cdgknstxyz`) cleanly hide the teeth
338
+ * even though the morphing inner-lip clip alone would let a sliver
339
+ * through. Above the floor, opacity ramps linearly to 1 at full
340
+ * openness, with a steeper-than-linear slope so wide-open visemes
341
+ * (`aei`, `th`, `qw`) saturate visibly.
342
+ */
343
+ export const OPENNESS_FLOOR = 0.15;
344
+ export const OPENNESS_SLOPE = 1.5;
345
+
346
+ export function teethOpacityFromOpenness(
347
+ openness: number,
348
+ overrides?: { floor?: number; slope?: number },
349
+ ): number {
350
+ const floor = overrides?.floor ?? OPENNESS_FLOOR;
351
+ const slope = overrides?.slope ?? OPENNESS_SLOPE;
352
+ return Math.max(0, Math.min(1, (openness - floor) * slope));
353
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * VisemeScheduler — drives lip-sync animation from Inworld TTS 1.5 phoneme data.
3
+ *
4
+ * Receives phoneme timing from audio_metadata WebSocket messages and maps them
5
+ * to AudioContext.currentTime so mouth shapes stay in lockstep with audio output.
6
+ */
7
+
8
+ import type { WordPhonemeInfo } from './audioProtocol';
9
+
10
+ export type VisemeSymbol =
11
+ | 'rest'
12
+ | 'aei'
13
+ | 'o'
14
+ | 'ee'
15
+ | 'bmp'
16
+ | 'fv'
17
+ | 'l'
18
+ | 'r'
19
+ | 'th'
20
+ | 'qw'
21
+ | 'cdgknstxyz';
22
+
23
+ const VALID_VISEMES: ReadonlySet<string> = new Set<string>([
24
+ 'rest',
25
+ 'aei',
26
+ 'o',
27
+ 'ee',
28
+ 'bmp',
29
+ 'fv',
30
+ 'l',
31
+ 'r',
32
+ 'th',
33
+ 'qw',
34
+ 'cdgknstxyz',
35
+ ]);
36
+
37
+ interface ScheduledViseme {
38
+ startTime: number; // Absolute AudioContext.currentTime
39
+ endTime: number;
40
+ visemeSymbol: string;
41
+ }
42
+
43
+ export class VisemeScheduler {
44
+ private queue: ScheduledViseme[] = [];
45
+
46
+ private currentViseme = 'rest';
47
+
48
+ private animationFrameId: number | null = null;
49
+
50
+ private onVisemeChange: (viseme: string) => void;
51
+
52
+ private audioContext: AudioContext;
53
+
54
+ constructor(audioContext: AudioContext, onVisemeChange: (viseme: string) => void) {
55
+ this.audioContext = audioContext;
56
+ this.onVisemeChange = onVisemeChange;
57
+ }
58
+
59
+ /**
60
+ * Schedule visemes from an audio_metadata message.
61
+ * @param phonemes - WordPhonemeInfo[] from the audio_metadata message
62
+ * @param chunkAudioStartTime - AudioContext.currentTime when this chunk starts playing
63
+ */
64
+ scheduleChunk(phonemes: WordPhonemeInfo[], chunkAudioStartTime: number): void {
65
+ for (const word of phonemes) {
66
+ for (const phone of word.phones) {
67
+ const symbol = VALID_VISEMES.has(phone.visemeSymbol) ? phone.visemeSymbol : 'rest';
68
+ this.queue.push({
69
+ startTime: chunkAudioStartTime + phone.startTime,
70
+ endTime: chunkAudioStartTime + phone.startTime + phone.duration,
71
+ visemeSymbol: symbol,
72
+ });
73
+ }
74
+ }
75
+ this.queue.sort((a, b) => a.startTime - b.startTime);
76
+
77
+ if (this.animationFrameId === null) {
78
+ this.tick();
79
+ }
80
+ }
81
+
82
+ private tick = (): void => {
83
+ const now = this.audioContext.currentTime;
84
+
85
+ // Discard expired visemes from the front of the sorted queue
86
+ while (this.queue.length > 0 && this.queue[0].endTime <= now) {
87
+ this.queue.shift();
88
+ }
89
+
90
+ // The first remaining item whose startTime <= now is the active viseme
91
+ const active =
92
+ this.queue.length > 0 && this.queue[0].startTime <= now ? this.queue[0] : undefined;
93
+ const newViseme = active?.visemeSymbol ?? 'rest';
94
+
95
+ if (newViseme !== this.currentViseme) {
96
+ this.currentViseme = newViseme;
97
+ this.onVisemeChange(newViseme);
98
+ }
99
+
100
+ // Stop the loop when idle to avoid CPU/battery leak. Safe to bail
101
+ // here because `scheduleChunk` re-arms requestAnimationFrame whenever
102
+ // `animationFrameId === null`. Removing that null-guard in
103
+ // `scheduleChunk` would make this idle-stop silently strand any
104
+ // newly-enqueued phonemes.
105
+ if (this.queue.length === 0 && this.currentViseme === 'rest') {
106
+ this.animationFrameId = null;
107
+ return;
108
+ }
109
+
110
+ this.animationFrameId = requestAnimationFrame(this.tick);
111
+ };
112
+
113
+ /** Call on barge-in or when audio stops. */
114
+ clear(): void {
115
+ this.queue = [];
116
+ if (this.currentViseme !== 'rest') {
117
+ this.currentViseme = 'rest';
118
+ this.onVisemeChange('rest');
119
+ }
120
+ if (this.animationFrameId !== null) {
121
+ cancelAnimationFrame(this.animationFrameId);
122
+ this.animationFrameId = null;
123
+ }
124
+ }
125
+
126
+ getCurrentViseme(): string {
127
+ return this.currentViseme;
128
+ }
129
+
130
+ destroy(): void {
131
+ this.clear();
132
+ }
133
+ }