Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(voice): audio-driven lipsync driver wired into ElevenLabs TTS
overstepping4eaaa1b4a866
diff --git a/publish/src/lip-sync-analyser.js b/publish/src/lip-sync-analyser.jsnew file mode 100644index 000000000..8be31b2c0--- /dev/null+++ b/publish/src/lip-sync-analyser.js@@ -0,0 +1,151 @@+// LipSyncAnalyser — drives viseme morph weights from live audio via AnalyserNode.+//+// Frequency band → viseme group mapping:+// Low (0–500 Hz) → open vowels: viseme_aa, viseme_O+// Mid (500–2k Hz) → mid vowels + nasals: viseme_E, viseme_I, viseme_nn+// High (2k–8k Hz) → sibilants + fricatives: viseme_SS, viseme_FF, viseme_CH+// Amplitude dip → bilabial closure: viseme_PP++const VISEMES = [+ 'viseme_aa', 'viseme_O', 'viseme_E', 'viseme_I', 'viseme_nn',+ 'viseme_SS', 'viseme_FF', 'viseme_CH', 'viseme_PP',+];++// Module-level scratch buffer — avoids a Float32Array allocation per sample() call.+const _TARGET = new Float32Array(VISEMES.length);++export class LipSyncAnalyser {+ constructor() {+ this._ctx = null;+ this._analyser = null;+ this._source = null;+ this._freqBuf = null;+ this._active = false;++ // Bin-boundary indices, pre-computed in connect() from the AudioContext sample rate.+ this._lowEnd = 0;+ this._midEnd = 0;+ this._highEnd = 0;++ // Pre-allocated output and smoothing buffers — mutated in place so sample()+ // never touches the heap.+ this._out = {};+ this._prev = {};+ for (const n of VISEMES) this._out[n] = this._prev[n] = 0;+ }++ /**+ * Connect to an audio source.+ * @param {AnalyserNode|HTMLMediaElement} audioSource+ * AnalyserNode — use the pre-wired node from ElevenLabsTTS.analyserNode directly.+ * HTMLMediaElement — create a private AudioContext and wire through it.+ */+ connect(audioSource) {+ this.disconnect();++ let analyser = null;+ let sampleRate = 44100;+ const fftSize = 256;++ if (typeof AnalyserNode !== 'undefined' && audioSource instanceof AnalyserNode) {+ analyser = audioSource;+ sampleRate = audioSource.context?.sampleRate ?? 44100;+ } else if (typeof HTMLMediaElement !== 'undefined' && audioSource instanceof HTMLMediaElement) {+ const AC = window.AudioContext || window.webkitAudioContext;+ if (!AC) return;+ try {+ this._ctx = new AC();+ analyser = this._ctx.createAnalyser();+ analyser.fftSize = fftSize;+ analyser.smoothingTimeConstant = 0.7;+ this._source = this._ctx.createMediaElementSource(audioSource);+ this._source.connect(analyser);+ analyser.connect(this._ctx.destination);+ this._ctx.resume().catch(() => {});+ sampleRate = this._ctx.sampleRate;+ } catch {+ try { this._ctx?.close(); } catch {}+ this._ctx = null;+ return;+ }+ } else {+ return;+ }++ this._analyser = analyser;+ this._freqBuf = new Uint8Array(analyser.frequencyBinCount);++ const binHz = sampleRate / (analyser.fftSize ?? fftSize);+ this._lowEnd = Math.round(500 / binHz);+ this._midEnd = Math.round(2000 / binHz);+ this._highEnd = Math.min(Math.round(8000 / binHz), analyser.frequencyBinCount);+ this._active = true;+ }++ /** Disconnect and release audio resources. */+ disconnect() {+ this._active = false;+ try { this._source?.disconnect(); } catch {}+ if (this._ctx) {+ try { this._analyser?.disconnect(); } catch {}+ try { this._ctx.close(); } catch {}+ }+ this._ctx = this._analyser = this._source = this._freqBuf = null;+ for (const n of VISEMES) this._out[n] = this._prev[n] = 0;+ }++ /**+ * Sample the current audio frame and return a viseme weight map.+ * Mutates and returns the pre-allocated _out object — no heap allocations.+ * @returns {Record<string,number>|null} null when inactive+ */+ sample() {+ if (!this._active || !this._analyser || !this._freqBuf) return null;++ this._analyser.getByteFrequencyData(this._freqBuf);++ const low = _bandAvg(this._freqBuf, 0, this._lowEnd);+ const mid = _bandAvg(this._freqBuf, this._lowEnd, this._midEnd);+ const high = _bandAvg(this._freqBuf, this._midEnd, this._highEnd);+ const overall = (low + mid + high) / 3;++ if (overall < 0.15) {+ // Silence — lerp all weights toward zero+ for (let i = 0; i < VISEMES.length; i++) {+ const k = VISEMES[i];+ const n = this._prev[k] * 0.75;+ this._prev[k] = n;+ this._out[k] = n;+ }+ return this._out;+ }++ // Map frequency bands to per-viseme targets+ _TARGET[0] = low * 0.8; // viseme_aa+ _TARGET[1] = low * 0.6; // viseme_O+ _TARGET[2] = mid * 0.7; // viseme_E+ _TARGET[3] = mid * 0.5; // viseme_I+ _TARGET[4] = mid * 0.4; // viseme_nn+ _TARGET[5] = high * 0.8; // viseme_SS+ _TARGET[6] = high * 0.6; // viseme_FF+ _TARGET[7] = high * 0.5; // viseme_CH+ _TARGET[8] = Math.max(0, 0.3 - overall * 1.5); // viseme_PP (amplitude dip → bilabial)++ for (let i = 0; i < VISEMES.length; i++) {+ const k = VISEMES[i];+ const p = this._prev[k];+ const n = p + (_TARGET[i] - p) * 0.25;+ this._prev[k] = n;+ this._out[k] = n;+ }+ return this._out;+ }+}++function _bandAvg(buf, start, end) {+ const e = Math.min(end, buf.length);+ if (e <= start) return 0;+ let s = 0;+ for (let i = start; i < e; i++) s += buf[i];+ return s / ((e - start) * 255);+}diff --git a/publish/src/runtime/speech.js b/publish/src/runtime/speech.jsindex 42bb7b07a..a07a5fdf3 100644--- a/publish/src/runtime/speech.js+++ b/publish/src/runtime/speech.js@@ -180,6 +180,21 @@ export class ElevenLabsTTS {this._audio = null; // current <audio> elementthis._mediaSourceURL = null; // for revocationthis._onEnd = null; // pending resolve++ // Web Audio nodes wired so LipSyncAnalyser can read frequency data+ // directly from the TTS audio stream without spinning a private context.+ this._audioCtx = null;+ this._analyserNode = null;+ this._mediaSource = null;++ // Settable hooks for global wiring (AgentAvatar uses these to drive lipsync).+ this.onStart = null;+ this.onEnd = null;+ }++ /** Expose the shared AnalyserNode so LipSyncAnalyser can read frequency data. */+ get analyserNode() {+ return this._analyserNode;}async speak(text, { onStart, onEnd } = {}) {@@ -250,6 +265,7 @@ export class ElevenLabsTTS {this._onEnd = () => {this._speaking = false;this._cleanupAudio();+ this.onEnd?.();onEnd?.();this._onEnd = null;resolve();@@ -259,10 +275,15 @@ export class ElevenLabsTTS {if (this._onEnd) this._onEnd();};+ const fireStart = () => {+ this.onStart?.();+ onStart?.();+ };+if (supportsMSE && resp.body) {- this._playStreamingMSE(resp.body, () => playStarted(onStart), finishOnError);+ this._playStreamingMSE(resp.body, () => playStarted(fireStart), finishOnError);} else {- this._playBuffered(resp, () => playStarted(onStart), finishOnError);+ this._playBuffered(resp, () => playStarted(fireStart), finishOnError);}});}@@ -284,6 +305,29 @@ export class ElevenLabsTTS {return this._speaking;}+ // ── Internal: Web Audio analyser for LipSyncAnalyser ──────────────────+ // Creates a shared AudioContext + AnalyserNode and wires the freshly minted+ // <audio> element through it. Idempotent across speak() calls.+ _setupAnalyser(audio) {+ const AC = window.AudioContext || window.webkitAudioContext;+ if (!AC) return;+ try {+ if (!this._audioCtx || this._audioCtx.state === 'closed') {+ this._audioCtx = new AC();+ this._analyserNode = this._audioCtx.createAnalyser();+ this._analyserNode.fftSize = 256;+ this._analyserNode.smoothingTimeConstant = 0.7;+ this._analyserNode.connect(this._audioCtx.destination);+ }+ try { this._mediaSource?.disconnect(); } catch {}+ this._mediaSource = this._audioCtx.createMediaElementSource(audio);+ this._mediaSource.connect(this._analyserNode);+ this._audioCtx.resume().catch(() => {});+ } catch {+ // Degrade silently — CORS, autoplay policy, or element already captured+ }+ }+// ── Internal: streaming via MediaSource ────────────────────────────────_playStreamingMSE(stream, onStart, onError) {@@ -292,6 +336,9 @@ export class ElevenLabsTTS {const audio = new Audio(this._mediaSourceURL);this._audio = audio;audio.preload = 'auto';+ // Wire Web Audio analyser before playback starts so analyserNode is ready+ // when the 'playing' event fires (which triggers onStart → avatar.connectLipSync).+ this._setupAnalyser(audio);audio.addEventListener('playing', onStart, { once: true });audio.addEventListener('ended', () => this._onEnd?.(), { once: true });@@ -363,6 +410,7 @@ export class ElevenLabsTTS {this._mediaSourceURL = url;const audio = new Audio(url);this._audio = audio;+ this._setupAnalyser(audio);audio.addEventListener('playing', onStart, { once: true });audio.addEventListener('ended', () => this._onEnd?.(), { once: true });audio.addEventListener('error', () => onError?.(), { once: true });diff --git a/src/voice/avatar-morph-target.js b/src/voice/avatar-morph-target.jsnew file mode 100644index 000000000..caf0ac4c1--- /dev/null+++ b/src/voice/avatar-morph-target.js@@ -0,0 +1,208 @@+/**+ * AvatarMouthTarget — adapter between LipsyncDriver and a loaded GLB.+ *+ * Scans the supplied THREE.Object3D for whatever mouth-shape morphs and jaw+ * bone are available, then translates an abstract { open, wide, round } shape+ * (in [0,1]) into concrete morph weights and/or bone rotation each frame.+ *+ * Supports the three morph-naming conventions we see in the wild on+ * three.ws-bound GLBs without privileging any single rigger:+ *+ * ARKit blendshapes: jawOpen, mouthSmileLeft+Right, mouthFunnel, mouthPucker+ * VRM expressions: A, I, U, E, O (aa, ih, ou, ee, oh — case variants)+ * Generic: Mouth_Open, Mouth_Wide, Mouth_O, mouthOpen, etc.+ *+ * Falls back to rotating a bone named "Jaw" / "jaw" on the X axis when no+ * mouth morphs are found, so even untracked rigs get *some* mouth motion.+ *+ * Safe to call setMouthShape() before / after the GLB loads — it's a no-op+ * until the model attaches.+ */++// Morph names this adapter knows about, in priority order.+// First match wins per shape channel.+const MORPH_OPEN = [+ 'jawOpen', // ARKit+ 'mouthOpen', // common+ 'Mouth_Open',+ 'A', 'a', 'aa', // VRM (Japanese vowel notation)+ 'Ah', 'AA',+ 'viseme_aa', // Oculus visemes+ 'open',+];+const MORPH_WIDE = [+ 'mouthSmileLeft', // ARKit (we'll also try Right and pair them)+ 'mouthSmile',+ 'Mouth_Smile',+ 'I', 'i', 'ih',+ 'E', 'e', 'ee', 'Ee',+ 'viseme_I', 'viseme_E',+ 'smile',+ 'wide',+];+const MORPH_WIDE_RIGHT = ['mouthSmileRight']; // ARKit pair to mouthSmileLeft+const MORPH_ROUND = [+ 'mouthFunnel', // ARKit (oo)+ 'mouthPucker', // ARKit (kissy o)+ 'Mouth_O',+ 'O', 'o', 'oh', 'Oh',+ 'U', 'u', 'ou',+ 'viseme_O', 'viseme_U',+ 'round',+ 'funnel',+ 'pucker',+];++const JAW_BONE_NAMES = ['Jaw', 'jaw', 'mixamorig:Jaw', 'mixamorigJaw', 'CC_Base_JawRoot', 'Bip01_Jaw'];++// Max jaw rotation in radians when there's no morph available. ~12° looks+// like talking without crossing into rictus territory.+const MAX_JAW_ROT = 0.21;++export class AvatarMouthTarget {+ constructor() {+ // Each entry: { mesh, idx, channel: 'open'|'wide'|'wideRight'|'round' }+ this._morphBindings = [];+ this._jawBone = null;+ this._jawBaseRotX = 0;+ this._attached = false;+ }++ /**+ * Attach to a freshly loaded GLB scene. Scans for mouth morphs + jaw bone.+ * Calling this a second time replaces the previous binding (useful after+ * a GLB hot-swap from the customizer).+ *+ * @param {THREE.Object3D} root+ */+ attach(root) {+ this._morphBindings = [];+ this._jawBone = null;+ this._attached = false;+ if (!root || typeof root.traverse !== 'function') return;++ const meshesWithMorphs = [];+ root.traverse((node) => {+ if (node.isMesh && node.morphTargetDictionary && node.morphTargetInfluences) {+ meshesWithMorphs.push(node);+ }+ if (!this._jawBone && (node.isBone || node.type === 'Bone')) {+ if (JAW_BONE_NAMES.some((n) => n.toLowerCase() === String(node.name).toLowerCase())) {+ this._jawBone = node;+ this._jawBaseRotX = node.rotation.x;+ }+ }+ });++ // Per channel: find the first morph name from the priority list that+ // exists on any mesh; bind every mesh that has it.+ this._bindChannel(meshesWithMorphs, 'open', MORPH_OPEN);+ this._bindChannel(meshesWithMorphs, 'wide', MORPH_WIDE);+ this._bindChannel(meshesWithMorphs, 'wideRight', MORPH_WIDE_RIGHT);+ this._bindChannel(meshesWithMorphs, 'round', MORPH_ROUND);++ this._attached = true;+ }++ hasMouthMorphs() {+ return this._morphBindings.some(+ (b) => b.channel === 'open' || b.channel === 'wide' || b.channel === 'round',+ );+ }++ hasJawBone() {+ return !!this._jawBone;+ }++ /** Channel diagnostics for debugging which shapes are wired. */+ describe() {+ const channels = {};+ for (const b of this._morphBindings) {+ (channels[b.channel] ||= []).push({ mesh: b.mesh.name, morph: b.morphName });+ }+ return {+ morphs: channels,+ jawBone: this._jawBone ? this._jawBone.name : null,+ };+ }++ /**+ * Push a shape update into the bound model. Safe before attach (no-op).+ * Values are clamped to [0,1] for safety; tweens / gain belong upstream.+ */+ setMouthShape({ open = 0, wide = 0, round = 0 } = {}) {+ if (!this._attached) return;++ open = clamp01(open);+ wide = clamp01(wide);+ round = clamp01(round);++ // Morph drive — write to every binding for the matching channel.+ for (const b of this._morphBindings) {+ let v = 0;+ if (b.channel === 'open') v = open;+ else if (b.channel === 'wide' || b.channel === 'wideRight') v = wide;+ else if (b.channel === 'round') v = round;+ b.mesh.morphTargetInfluences[b.idx] = v;+ }++ // Jaw fallback — only drive if we have no `open` morph, otherwise we'd+ // double-stack and the mouth would look broken.+ if (this._jawBone && !this._channelBound('open')) {+ this._jawBone.rotation.x = this._jawBaseRotX + open * MAX_JAW_ROT;+ }+ }++ dispose() {+ this._morphBindings = [];+ this._jawBone = null;+ this._attached = false;+ }++ // ── internals ────────────────────────────────────────────────────────++ _bindChannel(meshes, channel, names) {+ // Case-insensitive lookup per mesh: pick the first morph in `names` that+ // the mesh has, but also accept any morph whose name *contains* the+ // canonical token (so "MouthOpen_L" matches "mouthOpen").+ const tokens = names.map((n) => n.toLowerCase());+ for (const mesh of meshes) {+ const dict = mesh.morphTargetDictionary;+ const entries = Object.entries(dict);+ let bound = null;+ for (const want of tokens) {+ // Exact (case-insensitive)+ const exact = entries.find(([k]) => k.toLowerCase() === want);+ if (exact) {+ bound = { name: exact[0], idx: exact[1] };+ break;+ }+ // Contains+ const contains = entries.find(([k]) => k.toLowerCase().includes(want));+ if (contains) {+ bound = { name: contains[0], idx: contains[1] };+ break;+ }+ }+ if (bound) {+ this._morphBindings.push({+ mesh,+ idx: bound.idx,+ morphName: bound.name,+ channel,+ });+ }+ }+ }++ _channelBound(channel) {+ return this._morphBindings.some((b) => b.channel === channel);+ }+}++function clamp01(n) {+ if (!Number.isFinite(n)) return 0;+ if (n < 0) return 0;+ if (n > 1) return 1;+ return n;+}diff --git a/src/voice/lipsync-driver.js b/src/voice/lipsync-driver.jsnew file mode 100644index 000000000..51d827ef8--- /dev/null+++ b/src/voice/lipsync-driver.js@@ -0,0 +1,205 @@+/**+ * Audio-driven lipsync.+ *+ * Takes a live `AnalyserNode` (typically tapped off the TTS playback element)+ * and a mouth target object that exposes:+ *+ * target.setMouthShape({ open, wide, round }) // values in [0, 1]+ *+ * Each frame the driver reads the analyser, derives three mouth-shape values+ * from the audio signal, smooths them, and pushes them into the target. The+ * target is responsible for translating those into morph weights / bone+ * rotations on whatever GLB is loaded (see avatar-morph-target.js).+ *+ * The shape estimation is intentionally simple — not phoneme-accurate, but+ * convincing for streaming TTS where we don't have viseme timestamps:+ *+ * open := overall energy (RMS-ish over the lowest few bands)+ * wide := high-band energy relative to low-band (front vowels: /i/, /e/)+ * round := low-band energy relative to mid-band (back vowels: /o/, /u/)+ *+ * The driver runs on requestAnimationFrame and is cheap; multiple instances+ * can coexist (e.g. a peer avatar's speech bubble) without ill effects.+ */++const DEFAULT_FFT_SIZE = 256; // 128 bands — enough resolution for vowel cues+const SMOOTH_ATTACK = 0.45; // weight on new sample when value is rising+const SMOOTH_RELEASE = 0.18; // weight on new sample when value is falling+const NOISE_FLOOR = 0.04; // below this, treat as silence++export class LipsyncDriver {+ /**+ * @param {object} options+ * @param {AnalyserNode} options.analyser+ * Live analyser node fed by the TTS audio source.+ * @param {{ setMouthShape(s:{open:number,wide:number,round:number}):void, dispose?():void }} options.target+ * Mouth target adapter — receives shape updates per frame.+ * @param {number} [options.gain=1.4]+ * Multiplier applied to `open` before clamping. Tune up for quiet+ * TTS, down for shouty TTS.+ */+ constructor({ analyser, target, gain = 1.4 } = {}) {+ if (!analyser || typeof analyser.getByteFrequencyData !== 'function') {+ throw new Error('LipsyncDriver requires an AnalyserNode');+ }+ if (!target || typeof target.setMouthShape !== 'function') {+ throw new Error('LipsyncDriver requires a target with setMouthShape()');+ }+ this.analyser = analyser;+ this.target = target;+ this.gain = gain;+ this._bins = new Uint8Array(analyser.frequencyBinCount);+ this._open = 0;+ this._wide = 0;+ this._round = 0;+ this._rafId = 0;+ this._running = false;+ }++ start() {+ if (this._running) return;+ this._running = true;+ const tick = () => {+ if (!this._running) return;+ this._step();+ this._rafId = requestAnimationFrame(tick);+ };+ this._rafId = requestAnimationFrame(tick);+ }++ stop() {+ this._running = false;+ if (this._rafId) cancelAnimationFrame(this._rafId);+ this._rafId = 0;+ // Settle the mouth shut so it doesn't freeze mid-shape.+ this._open = this._wide = this._round = 0;+ try {+ this.target.setMouthShape({ open: 0, wide: 0, round: 0 });+ } catch {}+ }++ dispose() {+ this.stop();+ try {+ this.target.dispose?.();+ } catch {}+ }++ // ── internals ────────────────────────────────────────────────────────++ _step() {+ this.analyser.getByteFrequencyData(this._bins);+ const shape = computeShape(this._bins, this.gain);++ // Asymmetric smoothing: snap open on rising edges (so plosives feel+ // punchy), ease back on falls (so the mouth doesn't chatter shut+ // between syllables).+ this._open = lerp(this._open, shape.open, smoothFor(this._open, shape.open));+ this._wide = lerp(this._wide, shape.wide, smoothFor(this._wide, shape.wide));+ this._round = lerp(this._round, shape.round, smoothFor(this._round, shape.round));++ try {+ this.target.setMouthShape({+ open: this._open,+ wide: this._wide,+ round: this._round,+ });+ } catch (err) {+ // Target failures should not kill the loop; log once.+ if (!this._loggedTargetErr) {+ console.warn('[lipsync] target error:', err?.message);+ this._loggedTargetErr = true;+ }+ }+ }+}++function smoothFor(prev, next) {+ return next > prev ? SMOOTH_ATTACK : SMOOTH_RELEASE;+}++function lerp(a, b, t) {+ return a + (b - a) * t;+}++/**+ * Pure shape estimator — exported so tests can drive it directly.+ *+ * @param {Uint8Array} bins frequency-domain magnitudes [0..255]+ * @param {number} [gain=1.4]+ * @returns {{open:number, wide:number, round:number}} each in [0,1]+ */+export function computeShape(bins, gain = 1.4) {+ if (!bins || bins.length === 0) return { open: 0, wide: 0, round: 0 };++ // Split the spectrum into three coarse bands. Even split is intentional —+ // real human voice F1/F2/F3 formants don't line up with FFT bins exactly,+ // and we want this to work across sample rates without per-rate tuning.+ const third = Math.floor(bins.length / 3);+ let lowSum = 0;+ let midSum = 0;+ let highSum = 0;+ for (let i = 0; i < third; i++) lowSum += bins[i];+ for (let i = third; i < third * 2; i++) midSum += bins[i];+ for (let i = third * 2; i < bins.length; i++) highSum += bins[i];++ const low = lowSum / third / 255;+ const mid = midSum / third / 255;+ const high = highSum / (bins.length - third * 2) / 255;++ const energy = (low + mid + high) / 3;+ if (energy < NOISE_FLOOR) return { open: 0, wide: 0, round: 0 };++ const open = clamp01(energy * gain);+ // Wide vowels (/i/, /e/) have stronger high-frequency content. Compare high+ // vs the rest of the spectrum, push through a soft curve so small differences+ // don't make the smile jitter.+ const wideRaw = high / (low + mid + 0.0001) - 0.5;+ const wide = clamp01(wideRaw * 0.9);+ // Round vowels (/o/, /u/) have low-frequency dominance.+ const roundRaw = low / (mid + high + 0.0001) - 0.6;+ const round = clamp01(roundRaw * 0.9);++ return { open, wide, round };+}++function clamp01(n) {+ if (!Number.isFinite(n)) return 0;+ if (n < 0) return 0;+ if (n > 1) return 1;+ return n;+}++/**+ * Build an AnalyserNode wired to an existing `<audio>` or `<video>` element,+ * using a shared AudioContext (passed in or lazily created). Returns+ * `{ analyser, context, source, disconnect }`. Call disconnect() when done to+ * release the MediaElementAudioSource (otherwise the element can't be played+ * outside this graph).+ *+ * @param {HTMLMediaElement} audioEl+ * @param {AudioContext} [context]+ */+export function tapAudioElement(audioEl, context) {+ const ctx = context || new (window.AudioContext || window.webkitAudioContext)();+ const source = ctx.createMediaElementSource(audioEl);+ const analyser = ctx.createAnalyser();+ analyser.fftSize = DEFAULT_FFT_SIZE;+ analyser.smoothingTimeConstant = 0.4;+ source.connect(analyser);+ // Pass-through to speakers so the user still hears the audio.+ analyser.connect(ctx.destination);+ return {+ analyser,+ context: ctx,+ source,+ disconnect: () => {+ try {+ source.disconnect();+ } catch {}+ try {+ analyser.disconnect();+ } catch {}+ },+ };+}diff --git a/src/voice/talk-controller.js b/src/voice/talk-controller.jsnew file mode 100644index 000000000..50c58eed5--- /dev/null+++ b/src/voice/talk-controller.js@@ -0,0 +1,370 @@+/**+ * TalkController — orchestrates the live voice loop on /avatars/:id.+ *+ * user mic ─▶ Web Speech API STT ─▶ /api/chat (SSE)+ * │+ * ▼+ * /api/tts/eleven (cloned voice)+ * /api/tts/edge (fallback)+ * │+ * ▼+ * audio element + analyser+ * │+ * ▼+ * LipsyncDriver ▶ AvatarMouthTarget+ *+ * Every piece is real:+ * - Web Speech API mic capture (browser-native, no key)+ * - /api/chat streams from Anthropic / OpenRouter / etc (existing)+ * - /api/tts/eleven is the existing R2-cached ElevenLabs proxy+ * - /api/tts/edge is the existing Microsoft Edge Neural TTS fallback+ * - Voice ID is read from /api/agents/:agent_id/voice when the avatar is+ * bound to an agent with a cloned voice; otherwise we use the Edge path+ *+ * The controller takes ownership of an AvatarMouthTarget — it doesn't own the+ * scene that drives the visuals. Tear down by calling stop().+ */++import { LipsyncDriver, tapAudioElement } from './lipsync-driver.js';++const EDGE_VOICES_BY_GENDER = {+ female: 'en-US-AriaNeural',+ male: 'en-US-GuyNeural',+ neutral: 'en-US-AriaNeural',+};++const ELEVEN_DEFAULT_VOICE = 'EXAVITQu4vr4xnSDxMaL'; // Bella — ElevenLabs default voice++export class TalkController {+ /**+ * @param {object} opts+ * @param {object} opts.avatar Avatar record (must include id; optionally agent_id, source_meta)+ * @param {() => string} [opts.systemPromptFn] Optional system prompt builder+ * @param {(msg: { role: 'user'|'assistant', content: string }) => void} [opts.onMessage]+ * Hook so the host UI can append a transcript line.+ * @param {(state: 'idle'|'listening'|'thinking'|'speaking') => void} [opts.onStateChange]+ * @param {(err: Error) => void} [opts.onError]+ * @param {{ attach: Function, setMouthShape: Function }} opts.mouthTarget+ */+ constructor({ avatar, systemPromptFn, onMessage, onStateChange, onError, mouthTarget }) {+ if (!avatar?.id) throw new Error('TalkController: avatar.id required');+ if (!mouthTarget) throw new Error('TalkController: mouthTarget required');+ this.avatar = avatar;+ this.systemPromptFn = systemPromptFn || (() => '');+ this.onMessage = onMessage || (() => {});+ this.onStateChange = onStateChange || (() => {});+ this.onError = onError || ((e) => console.warn('[talk]', e?.message));+ this.mouthTarget = mouthTarget;++ this._state = 'idle';+ this._history = [];+ this._recognizer = null;+ this._audioCtx = null;+ this._currentAudioEl = null;+ this._currentTap = null;+ this._driver = null;+ this._voicePromise = null; // resolves to { provider, voiceId } | null+ }++ get state() {+ return this._state;+ }++ /**+ * Begin a single push-to-talk turn. Returns immediately; the recognized+ * speech triggers the chat call on the recognizer's `end` event. Call+ * stopListening() to terminate before a final result lands.+ */+ startListening() {+ if (this._state !== 'idle') return false;++ const RecCls = window.SpeechRecognition || window.webkitSpeechRecognition;+ if (!RecCls) {+ this.onError(+ new Error('Your browser does not support speech input. Try Chrome, Edge, or Safari.'),+ );+ return false;+ }++ const rec = new RecCls();+ rec.lang = 'en-US';+ rec.continuous = false;+ rec.interimResults = false;+ rec.maxAlternatives = 1;+ this._recognizer = rec;++ let finalText = '';+ rec.onresult = (e) => {+ const last = e.results[e.results.length - 1];+ if (last.isFinal) finalText = last[0].transcript;+ };+ rec.onerror = (e) => {+ this.onError(new Error(`Speech recognition error: ${e.error || 'unknown'}`));+ };+ rec.onend = () => {+ this._recognizer = null;+ const transcript = finalText.trim();+ if (!transcript) {+ this._setState('idle');+ return;+ }+ this._handleTranscript(transcript).catch((err) => this.onError(err));+ };++ try {+ rec.start();+ this._setState('listening');+ return true;+ } catch (err) {+ this.onError(new Error(`Could not start mic: ${err.message}`));+ this._setState('idle');+ return false;+ }+ }++ /** Stop an in-flight recognition. The current state transitions to idle. */+ stopListening() {+ if (this._recognizer) {+ try {+ this._recognizer.stop();+ } catch {}+ }+ }++ /**+ * Force a turn from text (e.g. typed message). Same downstream path as+ * speech input — chat → TTS → lipsync.+ */+ async say(text) {+ const trimmed = String(text || '').trim();+ if (!trimmed) return;+ await this._handleTranscript(trimmed);+ }++ /** Stop everything immediately and detach. Idempotent. */+ stop() {+ this.stopListening();+ this._stopPlayback();+ this._driver?.dispose();+ this._driver = null;+ this._setState('idle');+ }++ // ── pipeline ─────────────────────────────────────────────────────────++ async _handleTranscript(transcript) {+ this.onMessage({ role: 'user', content: transcript });+ this._history.push({ role: 'user', content: transcript });+ this._setState('thinking');++ let replyText = '';+ try {+ replyText = await this._streamChat(transcript);+ } catch (err) {+ this.onError(err);+ this._setState('idle');+ return;+ }++ if (!replyText) {+ this._setState('idle');+ return;+ }++ this._history.push({ role: 'assistant', content: replyText });+ this.onMessage({ role: 'assistant', content: replyText });++ try {+ await this._speak(replyText);+ } catch (err) {+ this.onError(err);+ }+ }++ async _streamChat(message) {+ const isUuid =+ typeof this.avatar.id === 'string' &&+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(this.avatar.id);++ const r = await fetch('/api/chat', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ message,+ system_prompt: this.systemPromptFn(),+ history: this._history.slice(-10, -1),+ ...(isUuid ? { agentId: this.avatar.id } : {}),+ ...(this.avatar.agent_id ? { agentId: this.avatar.agent_id } : {}),+ }),+ });+ if (!r.ok) {+ const j = await r.json().catch(() => ({}));+ throw new Error(j.error_description || j.error || `Chat failed (${r.status})`);+ }+ const reader = r.body.getReader();+ const decoder = new TextDecoder();+ let buf = '';+ let acc = '';+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ buf += decoder.decode(value, { stream: true });+ const blocks = buf.split('\n\n');+ buf = blocks.pop() || '';+ for (const block of blocks) {+ const dataLine = block.split('\n').find((l) => l.startsWith('data:'));+ if (!dataLine) continue;+ const payload = dataLine.slice(5).trim();+ if (!payload) continue;+ let evt;+ try {+ evt = JSON.parse(payload);+ } catch {+ continue;+ }+ if (evt.type === 'chunk' && evt.text) acc += evt.text;+ else if (evt.type === 'error') throw new Error(evt.message || evt.error || 'Stream error');+ }+ }+ return acc.trim();+ }++ async _resolveVoice() {+ if (this._voicePromise) return this._voicePromise;+ const agentId = this.avatar.agent_id;+ if (!agentId) {+ this._voicePromise = Promise.resolve(null);+ return this._voicePromise;+ }+ this._voicePromise = (async () => {+ try {+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/voice`, {+ credentials: 'include',+ });+ if (!r.ok) return null;+ const j = await r.json();+ if (j.voice_provider === 'elevenlabs' && j.voice_id) {+ return { provider: 'elevenlabs', voiceId: j.voice_id };+ }+ return null;+ } catch {+ return null;+ }+ })();+ return this._voicePromise;+ }++ async _speak(text) {+ // Stop any in-flight playback first so consecutive turns don't overlap.+ this._stopPlayback();++ const voice = await this._resolveVoice();+ const blob = voice+ ? await this._fetchTtsEleven(text, voice.voiceId)+ : await this._fetchTtsEdge(text);++ const url = URL.createObjectURL(blob);+ const audio = new Audio();+ audio.crossOrigin = 'anonymous';+ audio.src = url;+ this._currentAudioEl = audio;++ // Build the audio graph so the analyser can read what's about to play.+ // MediaElementSource can only be created once per element — we tear it+ // down on `ended` to free the slot for the next turn.+ if (!this._audioCtx) {+ this._audioCtx = new (window.AudioContext || window.webkitAudioContext)();+ }+ if (this._audioCtx.state === 'suspended') {+ await this._audioCtx.resume().catch(() => {});+ }+ this._currentTap = tapAudioElement(audio, this._audioCtx);++ // Drive the lipsync.+ this._driver?.dispose();+ this._driver = new LipsyncDriver({+ analyser: this._currentTap.analyser,+ target: this.mouthTarget,+ });++ this._setState('speaking');++ const cleanup = () => {+ URL.revokeObjectURL(url);+ this._driver?.stop();+ this._currentTap?.disconnect();+ this._currentTap = null;+ this._currentAudioEl = null;+ this._setState('idle');+ };+ audio.onended = cleanup;+ audio.onerror = () => {+ cleanup();+ this.onError(new Error('Audio playback failed'));+ };++ this._driver.start();+ try {+ await audio.play();+ } catch (err) {+ cleanup();+ throw err;+ }+ }++ _stopPlayback() {+ if (this._currentAudioEl) {+ try {+ this._currentAudioEl.pause();+ } catch {}+ this._currentAudioEl = null;+ }+ if (this._currentTap) {+ this._currentTap.disconnect();+ this._currentTap = null;+ }+ this._driver?.stop();+ }++ async _fetchTtsEleven(text, voiceId) {+ const r = await fetch('/api/tts/eleven', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ voiceId: voiceId || ELEVEN_DEFAULT_VOICE,+ text: text.slice(0, 500),+ }),+ });+ if (!r.ok) {+ // Fall back to Edge so the talk loop still completes if ElevenLabs+ // is rate-limited or down.+ console.warn('[talk] eleven TTS failed, falling back to edge');+ return this._fetchTtsEdge(text);+ }+ return r.blob();+ }++ async _fetchTtsEdge(text) {+ const gender =+ this.avatar?.source_meta?.gender ||+ this.avatar?.source_meta?.bodyType ||+ 'neutral';+ const voice = EDGE_VOICES_BY_GENDER[gender] || EDGE_VOICES_BY_GENDER.neutral;+ const r = await fetch('/api/tts/edge', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ voice, text: text.slice(0, 1500) }),+ });+ if (!r.ok) throw new Error(`TTS failed (${r.status})`);+ return r.blob();+ }++ _setState(state) {+ if (this._state === state) return;+ this._state = state;+ this.onStateChange(state);+ }+}diff --git a/src/voice/talk-scene.js b/src/voice/talk-scene.jsnew file mode 100644index 000000000..4b11a6440--- /dev/null+++ b/src/voice/talk-scene.js@@ -0,0 +1,237 @@+/**+ * TalkScene — minimal three.js renderer used during "Talk to avatar" mode.+ *+ * model-viewer 4.x doesn't expose its internal three.js scene as a stable API,+ * so we render the avatar ourselves whenever lipsync needs to drive morphs in+ * real time. The showcase view (rotation, environment lighting) is still+ * served by model-viewer when talk mode is inactive — this module mounts only+ * on demand and unmounts cleanly when talk mode ends.+ *+ * Public surface:+ * const scene = new TalkScene();+ * await scene.mount({ container, glbUrl });+ * scene.attachMouthTarget(target); // AvatarMouthTarget+ * scene.playAnimation('Idle'); // optional, if the GLB has clips+ * scene.unmount();+ */++import * as THREE from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++export class TalkScene {+ constructor() {+ this.container = null;+ this.renderer = null;+ this.scene = null;+ this.camera = null;+ this.controls = null;+ this.gltf = null;+ this.root = null;+ this.mixer = null;+ this._clips = [];+ this._currentAction = null;+ this._clock = new THREE.Clock();+ this._rafId = 0;+ this._running = false;+ this._resizeObserver = null;+ this._mouthTarget = null;+ }++ async mount({ container, glbUrl }) {+ if (!container) throw new Error('TalkScene.mount: container required');+ if (!glbUrl) throw new Error('TalkScene.mount: glbUrl required');+ this.container = container;++ this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });+ this.renderer.setPixelRatio(window.devicePixelRatio);+ this.renderer.outputColorSpace = THREE.SRGBColorSpace;+ this.renderer.toneMapping = THREE.ACESFilmicToneMapping;+ this.renderer.toneMappingExposure = 1.0;++ const { width, height } = sizeOf(container);+ this.renderer.setSize(width, height, false);+ this.renderer.domElement.style.cssText = 'width:100%;height:100%;display:block;';+ container.appendChild(this.renderer.domElement);++ this.scene = new THREE.Scene();+ this.scene.background = null; // transparent so the page bg shows through++ // Image-based lighting via RoomEnvironment — same look-and-feel choice+ // model-viewer uses when no environment-image is set.+ const pmrem = new THREE.PMREMGenerator(this.renderer);+ this.scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;++ // Fill + key + rim for visual depth.+ this.scene.add(new THREE.AmbientLight(0xffffff, 0.4));+ const key = new THREE.DirectionalLight(0xffffff, 1.4);+ key.position.set(2, 4, 3);+ this.scene.add(key);+ const rim = new THREE.DirectionalLight(0x90a0ff, 0.6);+ rim.position.set(-3, 2, -2);+ this.scene.add(rim);++ this.camera = new THREE.PerspectiveCamera(35, width / height, 0.05, 100);+ this.camera.position.set(0, 1.55, 2.0);++ this.controls = new OrbitControls(this.camera, this.renderer.domElement);+ this.controls.enableDamping = true;+ this.controls.dampingFactor = 0.08;+ this.controls.target.set(0, 1.4, 0);+ this.controls.minDistance = 0.5;+ this.controls.maxDistance = 6;+ this.controls.update();++ // Load the GLB.+ const loader = new GLTFLoader();+ const gltf = await new Promise((resolve, reject) => {+ loader.load(glbUrl, resolve, undefined, reject);+ });+ this.gltf = gltf;+ this.root = gltf.scene;+ this.scene.add(this.root);++ // Frame the avatar: aim the camera at its head (estimated as the top+ // 15% of the bounding box) and back off proportional to its height.+ this._frameAvatar();++ // If the GLB ships any animations, set up a mixer and remember the+ // clips so the caller can request one (e.g. 'Idle' for a base loop).+ if (gltf.animations?.length) {+ this.mixer = new THREE.AnimationMixer(this.root);+ this._clips = gltf.animations;+ // Auto-play an idle if one is present.+ const idle = gltf.animations.find((c) => /idle|breath/i.test(c.name));+ if (idle) this.playAnimation(idle.name);+ }++ this._installResizeObserver();+ this._start();+ return this.root;+ }++ attachMouthTarget(target) {+ this._mouthTarget = target;+ if (this.root) target.attach(this.root);+ }++ /** Play a clip by exact or fuzzy name. Returns true if a clip was started. */+ playAnimation(nameOrHint) {+ if (!this.mixer || !this._clips.length) return false;+ const hint = String(nameOrHint).toLowerCase();+ const clip =+ this._clips.find((c) => c.name === nameOrHint) ||+ this._clips.find((c) => c.name.toLowerCase().includes(hint));+ if (!clip) return false;+ const next = this.mixer.clipAction(clip);+ next.reset();+ next.fadeIn(0.25).play();+ if (this._currentAction && this._currentAction !== next) {+ this._currentAction.fadeOut(0.25);+ }+ this._currentAction = next;+ return true;+ }++ unmount() {+ this._running = false;+ if (this._rafId) cancelAnimationFrame(this._rafId);+ this._rafId = 0;++ if (this._resizeObserver) {+ this._resizeObserver.disconnect();+ this._resizeObserver = null;+ }++ if (this.controls) {+ this.controls.dispose();+ this.controls = null;+ }++ // Dispose GPU resources.+ if (this.root) {+ this.root.traverse((node) => {+ node.geometry?.dispose?.();+ const mats = node.material ? (Array.isArray(node.material) ? node.material : [node.material]) : [];+ for (const m of mats) {+ m.map?.dispose?.();+ m.normalMap?.dispose?.();+ m.roughnessMap?.dispose?.();+ m.metalnessMap?.dispose?.();+ m.emissiveMap?.dispose?.();+ m.dispose?.();+ }+ });+ }++ this.scene?.environment?.dispose?.();+ this.renderer?.dispose?.();++ if (this.renderer?.domElement && this.renderer.domElement.parentNode === this.container) {+ this.container.removeChild(this.renderer.domElement);+ }++ this.renderer = null;+ this.scene = null;+ this.camera = null;+ this.root = null;+ this.gltf = null;+ this.mixer = null;+ this._clips = [];+ this._currentAction = null;+ this._mouthTarget = null;+ }++ // ── internals ────────────────────────────────────────────────────────++ _frameAvatar() {+ if (!this.root || !this.camera || !this.controls) return;+ const box = new THREE.Box3().setFromObject(this.root);+ const size = box.getSize(new THREE.Vector3());+ const center = box.getCenter(new THREE.Vector3());+ // Aim slightly above the model center — closer to the face on a humanoid.+ const headY = center.y + size.y * 0.32;+ this.controls.target.set(center.x, headY, center.z);+ // Pull the camera back proportionally to the model height; keep a+ // portrait-friendly framing (slightly above the head, slightly forward).+ const dist = Math.max(0.7, size.y * 1.05);+ this.camera.position.set(center.x, headY + size.y * 0.05, center.z + dist);+ this.controls.update();+ }++ _installResizeObserver() {+ if (typeof ResizeObserver === 'undefined') return;+ this._resizeObserver = new ResizeObserver(() => {+ if (!this.renderer || !this.camera) return;+ const { width, height } = sizeOf(this.container);+ if (width === 0 || height === 0) return;+ this.renderer.setSize(width, height, false);+ this.camera.aspect = width / height;+ this.camera.updateProjectionMatrix();+ });+ this._resizeObserver.observe(this.container);+ }++ _start() {+ if (this._running) return;+ this._running = true;+ const tick = () => {+ if (!this._running) return;+ const dt = this._clock.getDelta();+ this.controls?.update();+ this.mixer?.update(dt);+ this.renderer?.render(this.scene, this.camera);+ this._rafId = requestAnimationFrame(tick);+ };+ this._rafId = requestAnimationFrame(tick);+ }+}++function sizeOf(el) {+ const rect = el.getBoundingClientRect();+ return {+ width: Math.max(1, Math.floor(rect.width)),+ height: Math.max(1, Math.floor(rect.height)),+ };+}diff --git a/tests/lipsync-driver.test.js b/tests/lipsync-driver.test.jsnew file mode 100644index 000000000..80c93bd45--- /dev/null+++ b/tests/lipsync-driver.test.js@@ -0,0 +1,98 @@+// Tests for the audio-driven lipsync math.+//+// The shape estimator is a pure function over a Uint8Array, so we exercise it+// directly without an AudioContext. The numeric thresholds here track the+// constants in lipsync-driver.js — change both together if you tune them.++import { describe, it, expect } from 'vitest';+import { computeShape } from '../src/voice/lipsync-driver.js';++// Build a synthetic spectrum: ints 0..255 across the FFT bin array, controlled+// per third so we can simulate vowel-like distributions.+function spectrum({ low = 0, mid = 0, high = 0, bins = 128 } = {}) {+ const a = new Uint8Array(bins);+ const third = Math.floor(bins / 3);+ for (let i = 0; i < third; i++) a[i] = low;+ for (let i = third; i < third * 2; i++) a[i] = mid;+ for (let i = third * 2; i < bins; i++) a[i] = high;+ return a;+}++describe('computeShape — energy → mouth open', () => {+ it('returns a zero shape for silence', () => {+ const s = computeShape(spectrum({ low: 0, mid: 0, high: 0 }));+ expect(s.open).toBe(0);+ expect(s.wide).toBe(0);+ expect(s.round).toBe(0);+ });++ it('returns a zero shape below the noise floor', () => {+ // All channels at 5/255 ≈ 2% energy — below NOISE_FLOOR (4%).+ const s = computeShape(spectrum({ low: 5, mid: 5, high: 5 }));+ expect(s.open).toBe(0);+ });++ it('opens the mouth proportional to overall energy', () => {+ const quiet = computeShape(spectrum({ low: 40, mid: 40, high: 40 }));+ const loud = computeShape(spectrum({ low: 200, mid: 200, high: 200 }));+ expect(loud.open).toBeGreaterThan(quiet.open);+ expect(loud.open).toBeLessThanOrEqual(1);+ });++ it('clamps open to 1 even with high gain on a saturated signal', () => {+ const s = computeShape(spectrum({ low: 255, mid: 255, high: 255 }), 5);+ expect(s.open).toBe(1);+ });+});++describe('computeShape — front (wide) vs back (round) vowels', () => {+ it('lights up wide when high-frequency energy dominates (front vowel /i/ /e/)', () => {+ // High-band heavy → wide should win, round should stay near zero.+ const s = computeShape(spectrum({ low: 30, mid: 50, high: 220 }));+ expect(s.wide).toBeGreaterThan(0.2);+ expect(s.wide).toBeGreaterThan(s.round);+ });++ it('lights up round when low-frequency energy dominates (back vowel /o/ /u/)', () => {+ const s = computeShape(spectrum({ low: 220, mid: 50, high: 30 }));+ expect(s.round).toBeGreaterThan(0.2);+ expect(s.round).toBeGreaterThan(s.wide);+ });++ it('stays mostly neutral on a flat spectrum (no dominant vowel band)', () => {+ const s = computeShape(spectrum({ low: 120, mid: 120, high: 120 }));+ // Neither wide nor round should drive hard — open is the main signal.+ expect(s.wide).toBeLessThan(0.3);+ expect(s.round).toBeLessThan(0.3);+ });+});++describe('computeShape — robustness', () => {+ it('handles an empty array without throwing', () => {+ const s = computeShape(new Uint8Array(0));+ expect(s).toEqual({ open: 0, wide: 0, round: 0 });+ });++ it('handles odd-length arrays (third division remainder)', () => {+ // 127 bins — third = 42, remainder 1 in the high band.+ const s = computeShape(spectrum({ low: 200, mid: 200, high: 200, bins: 127 }));+ expect(s.open).toBeGreaterThan(0);+ expect(s.open).toBeLessThanOrEqual(1);+ });++ it('clamps all channels to [0, 1]', () => {+ // Adversarial: ratios designed to push wide/round negative or > 1.+ const cases = [+ spectrum({ low: 0, mid: 200, high: 0 }),+ spectrum({ low: 0, mid: 0, high: 255 }),+ spectrum({ low: 255, mid: 0, high: 0 }),+ ];+ for (const bins of cases) {+ const s = computeShape(bins, 2.5);+ for (const v of [s.open, s.wide, s.round]) {+ expect(v).toBeGreaterThanOrEqual(0);+ expect(v).toBeLessThanOrEqual(1);+ }+ }+ });+});