-
Notifications
You must be signed in to change notification settings - Fork 3.6k
feat(voice): animate the mascot's mouth during realtime voice calls #5546
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
YellowSnnowmann
merged 6 commits into
tinyhumansai:main
from
YellowSnnowmann:feat/5545-realtime-voice-lipsync
Aug 14, 2026
Merged
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
49984c9
feat(voice): animate the mascot's mouth during realtime voice calls
YellowSnnowmann 02b4d67
fix(voice): reset the lip-sync level on an invalid analyser reading
YellowSnnowmann eb0496e
fix(voice): gate the lip-sync frame loop on the agent's speaking edge
YellowSnnowmann 6974b9f
fix(voice): guard audioRef.current and cover the publication path
YellowSnnowmann ca25bca
test(voice): cover the active→idle audioRef cleanup while mounted
YellowSnnowmann a970d51
test(voice): cover the isSpeaking edge while the session stays active
YellowSnnowmann File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| import { describe, expect, it } from 'vitest'; | ||
|
|
||
| import { amplitudeToVisemeCode, smoothAmplitude } from './amplitudeLipsync'; | ||
|
|
||
| describe('amplitudeToVisemeCode', () => { | ||
| it('rests the mouth on silence and room tone', () => { | ||
| expect(amplitudeToVisemeCode(0)).toBe('sil'); | ||
| // Below the floor: the tail of a word, not speech. Holding the mouth open | ||
| // through these gaps is what makes naive amplitude lip-sync look slack. | ||
| expect(amplitudeToVisemeCode(0.03)).toBe('sil'); | ||
| }); | ||
|
|
||
| it('opens the mouth further as the signal gets louder', () => { | ||
| const codes = [0.08, 0.2, 0.6].map(amplitudeToVisemeCode); | ||
| expect(codes).toEqual(['I', 'E', 'aa']); | ||
| }); | ||
|
|
||
| // A garbage reading (analyser torn down mid-frame) must not map to a wide-open | ||
| // mouth that then sticks for the rest of the call. Infinity rests for the same | ||
| // reason NaN does: it is a broken sample, not a loud one. | ||
| it('rests on a non-finite reading', () => { | ||
| expect(amplitudeToVisemeCode(Number.NaN)).toBe('sil'); | ||
| expect(amplitudeToVisemeCode(Number.POSITIVE_INFINITY)).toBe('sil'); | ||
| }); | ||
| }); | ||
|
|
||
| describe('smoothAmplitude', () => { | ||
| it('moves toward the new sample', () => { | ||
| expect(smoothAmplitude(0, 1)).toBeGreaterThan(0); | ||
| expect(smoothAmplitude(1, 0)).toBeLessThan(1); | ||
| }); | ||
|
|
||
| // Asymmetric on purpose: consonant onsets must land on time, but the mouth | ||
| // must not snap shut inside a word. | ||
| it('opens faster than it closes', () => { | ||
| const opening = smoothAmplitude(0, 1) - 0; | ||
| const closing = 1 - smoothAmplitude(1, 0); | ||
| expect(opening).toBeGreaterThan(closing); | ||
| }); | ||
|
|
||
| it('converges on a held level rather than oscillating', () => { | ||
| let level = 0; | ||
| for (let i = 0; i < 40; i += 1) level = smoothAmplitude(level, 0.5); | ||
| expect(level).toBeCloseTo(0.5, 2); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| /** | ||
| * Amplitude-driven lip-sync for the realtime voice session (#5399). | ||
| * | ||
| * The classic tap-and-speak path animates the mouth from a viseme *timeline*: | ||
| * frames of `{viseme, ms}` sampled against our own audio element's clock. That | ||
| * is not available here — the realtime SDK owns playback, so there is no | ||
| * `currentMs()` to sample and no per-character timing unless we subscribe to | ||
| * alignment events and reconstruct one. | ||
| * | ||
| * What the SDK does expose is the output signal itself (`getOutputVolume()`), | ||
| * so the mouth is driven from loudness instead. That is genuinely less accurate | ||
| * — it opens and closes with the envelope rather than forming phonemes, so no | ||
| * `M`/`F` closures — but it is in sync *by construction*, because it is the | ||
| * audio being played rather than a prediction of it. A frozen mouth while the | ||
| * agent talks reads as broken; an approximate one reads as alive. | ||
| * | ||
| * The viseme-timeline version is the follow-up, and this is the fallback it | ||
| * would keep for the case where alignment is absent or has run dry. | ||
| */ | ||
|
|
||
| /** Viseme codes, ordered by how open the mouth is. */ | ||
| const REST = 'sil'; | ||
| const NARROW = 'I'; // openness 0.30 | ||
| const MID = 'E'; // openness 0.45 | ||
| const OPEN = 'aa'; // openness ~0.95 | ||
|
|
||
| /** | ||
| * Below this the signal is room tone or the tail of a word, not speech. Holding | ||
| * the mouth open through those gaps is what makes naive amplitude lip-sync look | ||
| * slack-jawed, so anything under it rests. | ||
| */ | ||
| const SILENCE_FLOOR = 0.04; | ||
|
|
||
| /** Where the mouth steps from narrow to mid, and from mid to wide open. */ | ||
| const MID_THRESHOLD = 0.12; | ||
| const OPEN_THRESHOLD = 0.28; | ||
|
|
||
| /** | ||
| * Smoothing applied to the raw reading, as the weight given to the new sample. | ||
| * | ||
| * `getOutputVolume()` is sampled per animation frame and is noisy at that rate: | ||
| * fed straight through it produces a chattering mouth that reads as a glitch | ||
| * rather than as speech. Asymmetric on purpose — opening tracks the signal | ||
| * quickly so consonant onsets land on time, closing lags so the mouth does not | ||
| * snap shut inside a word. | ||
| */ | ||
| const ATTACK = 0.55; | ||
| const RELEASE = 0.18; | ||
|
|
||
| /** Smooth one amplitude sample toward the previous level. Pure + unit-tested. */ | ||
| export function smoothAmplitude(previous: number, sample: number): number { | ||
| const weight = sample > previous ? ATTACK : RELEASE; | ||
| return previous + (sample - previous) * weight; | ||
| } | ||
|
|
||
| /** | ||
| * Map a smoothed amplitude (0..1) onto a viseme code. Steps rather than | ||
| * interpolates because the Rive mouth is driven by a code, not a scalar. | ||
| * Pure + unit-tested. | ||
| */ | ||
| export function amplitudeToVisemeCode(level: number): string { | ||
| if (!Number.isFinite(level) || level < SILENCE_FLOOR) return REST; | ||
| if (level < MID_THRESHOLD) return NARROW; | ||
| if (level < OPEN_THRESHOLD) return MID; | ||
| return OPEN; | ||
| } | ||
|
|
||
| /** | ||
| * What the realtime controls publish for the mascot to read. Held in a ref and | ||
| * mutated in place: the mascot samples it once per animation frame, and routing | ||
| * a 60fps signal through React state would re-render the page on every frame. | ||
| */ | ||
| export interface RealtimeVoiceAudio { | ||
| /** SDK accessor for output loudness, or null when no session is live. */ | ||
| getOutputVolume: (() => number) | null; | ||
| /** Whether the agent is currently speaking (SDK `isSpeaking`). */ | ||
| speaking: boolean; | ||
| } | ||
|
|
||
| export const IDLE_REALTIME_VOICE_AUDIO: RealtimeVoiceAudio = { | ||
| getOutputVolume: null, | ||
| speaking: false, | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| import { act, renderHook } from '@testing-library/react'; | ||
| import { createRef } from 'react'; | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; | ||
|
|
||
| import { type RealtimeVoiceAudio } from './amplitudeLipsync'; | ||
| import { useAmplitudeLipsync } from './useAmplitudeLipsync'; | ||
|
|
||
| /** Drive the rAF loop by hand so frames are deterministic. */ | ||
| let frames: FrameRequestCallback[] = []; | ||
|
|
||
| function flushFrames(count: number): void { | ||
| for (let i = 0; i < count; i += 1) { | ||
| const pending = frames; | ||
| frames = []; | ||
| act(() => pending.forEach(cb => cb(performance.now()))); | ||
| } | ||
| } | ||
|
|
||
| function audioRef(overrides: Partial<RealtimeVoiceAudio> = {}) { | ||
| const ref = createRef<RealtimeVoiceAudio>() as { current: RealtimeVoiceAudio }; | ||
| ref.current = { getOutputVolume: null, speaking: false, ...overrides }; | ||
| return ref; | ||
| } | ||
|
|
||
| describe('useAmplitudeLipsync', () => { | ||
| beforeEach(() => { | ||
| frames = []; | ||
| vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { | ||
| frames.push(cb); | ||
| return frames.length; | ||
| }); | ||
| vi.stubGlobal('cancelAnimationFrame', () => {}); | ||
| }); | ||
| afterEach(() => vi.unstubAllGlobals()); | ||
|
|
||
| it('stays inactive and rested while nothing is speaking', () => { | ||
| const { result } = renderHook(() => useAmplitudeLipsync(audioRef())); | ||
| flushFrames(3); | ||
| expect(result.current).toEqual({ active: false, visemeCode: 'sil' }); | ||
| }); | ||
|
|
||
| it('drives the mouth from output loudness while the agent speaks', () => { | ||
| const ref = audioRef({ speaking: true, getOutputVolume: () => 0.9 }); | ||
| const { result } = renderHook(() => useAmplitudeLipsync(ref)); | ||
| flushFrames(10); | ||
| expect(result.current.active).toBe(true); | ||
| expect(result.current.visemeCode).toBe('aa'); | ||
| }); | ||
|
|
||
| // The mouth must return to rest when the turn ends, not freeze on its last | ||
| // shape — a stuck-open mascot is worse than one that never moved. | ||
| it('rests the mouth when speaking stops', () => { | ||
| const ref = audioRef({ speaking: true, getOutputVolume: () => 0.9 }); | ||
| const { result } = renderHook(() => useAmplitudeLipsync(ref)); | ||
| flushFrames(10); | ||
| expect(result.current.visemeCode).toBe('aa'); | ||
|
|
||
| ref.current.speaking = false; | ||
| flushFrames(2); | ||
| expect(result.current).toEqual({ active: false, visemeCode: 'sil' }); | ||
| }); | ||
|
|
||
| // The SDK reads a live analyser; a session torn down mid-frame throws rather | ||
| // than returning 0. An uncaught throw would kill the loop and freeze the mouth. | ||
| it('survives an accessor that throws mid-session', () => { | ||
| const ref = audioRef({ | ||
| speaking: true, | ||
| getOutputVolume: () => { | ||
| throw new Error('analyser closed'); | ||
| }, | ||
| }); | ||
| const { result } = renderHook(() => useAmplitudeLipsync(ref)); | ||
| expect(() => flushFrames(5)).not.toThrow(); | ||
| expect(result.current.visemeCode).toBe('sil'); | ||
| }); | ||
|
|
||
| it('cancels its frame loop on unmount', () => { | ||
| const cancel = vi.fn(); | ||
| vi.stubGlobal('cancelAnimationFrame', cancel); | ||
| const { unmount } = renderHook(() => useAmplitudeLipsync(audioRef())); | ||
| unmount(); | ||
| expect(cancel).toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.