# Lip sync: a microphone or any audio drives the mouth

Three ways to move an avatar's mouth from sound, all in the core:

| You have | Call | What you get |
|---|---|---|
| PCM audio: a mic, a voice stream, a TTS clip | `sona_lipsync_feed`, `sona_lipsync_current` | a speech shape every 10 ms, after the delay set by the window (see below) |
| Only an audio level per remote player (voice chat) | `sona_avatar_voice` or `sona_voice_mouths` for a whole crowd | a talking mouth from a number, a few dozen flops a call |
| Text, with the audio or the phoneme timings a TTS reports | `sona_lipsync_text`, `sona_lipsync_phonemes`, `sona_lipsync_hint` | mouth keys that say the right shape, with lips that close on M, B and P |

![Four mouth shapes the analyser picked from a spoken line](../img/lipsync.webp)

The mouth is the face's own speech shapes: `SONA_MOUTH_O`, `_AI`, `_EE`, `_FV`, `_W`, `_L`, `_DTH` and the shut
`SONA_MOUTH_NEUTRAL`, set with `sona_avatar_mouth`, which changes only the mouth and leaves eyes and brows to the clip
or to `sona_avatar_expression`. Every frame also carries eight weights (neutral and the seven shapes, summing to 1) and
an openness, for engines that blend shapes on their own rig.

## Speaking a stream

```c
sona_lipsync_options o;
sona_lipsync *ls;
sona_lipsync_defaults(&o);
o.sample_rate = 48000;                 /* any rate from 8 to 192 kHz */
o.channels = 2;                        /* interleaved; averaged to mono */
o.format = SONA_PCM_S16;               /* or SONA_PCM_F32 */
sona_lipsync_create(&o, NULL, &ls);    /* NULL allocator: malloc */

/* each audio callback or game frame, whatever the chunk size: */
sona_lipsync_feed(ls, samples, frames);
sona_lipsync_frame f;
sona_lipsync_current(ls, &f);
sona_avatar_mouth(avatar, f.mouth);    /* the same shape again costs nothing */

sona_lipsync_destroy(ls);
```

```cpp
sona_lipsync_options o;
sona_lipsync *ls = nullptr;
sona_lipsync_defaults(&o);
o.sample_rate = 48000;                 // any rate from 8 to 192 kHz
o.channels = 2;                        // interleaved; averaged to mono
o.format = SONA_PCM_S16;               // or SONA_PCM_F32
sona_lipsync_create(&o, nullptr, &ls); // no allocator: malloc

// each audio callback or game frame, whatever the chunk size:
sona_lipsync_feed(ls, samples, frames);
sona_lipsync_frame f;
sona_lipsync_current(ls, &f);
sona_avatar_mouth(avatar.raw(), f.mouth);   // the same shape again costs nothing

sona_lipsync_destroy(ls);
```

```csharp
using var ls = new SonaLipSync(48000, 2);    // any rate from 8 to 192 kHz; interleaved, averaged to mono

// each audio callback or game frame, whatever the chunk size:
ls.Feed(pcm);                                // float samples
avatar.SetMouth(ls.Mouth(out float open));   // the same shape again costs nothing
```

```rust
let mut ls = LipSync::with_format(48000, 2, true)?;   // any rate from 8 to 192 kHz; 16-bit, interleaved, averaged to mono

// each audio callback or game frame, whatever the chunk size:
ls.feed_i16(samples)?;
avatar.set_mouth(ls.current().mouth as u8)?; // the same shape again costs nothing
```

```python
ls = sona.LipSync(48000, channels=2, s16=True)   # any rate from 8 to 192 kHz; interleaved, averaged to mono

# each audio callback or game frame, whatever the chunk size:
ls.feed(samples)
avatar.mouth(ls.current().mouth)             # the same shape again costs nothing

ls.close()
```

The analyser needs no ctx and no thread: one per speaker, on any thread (one thread at a time per analyser). It makes
a frame for every 10 ms of audio; `sona_lipsync_read` hands over every frame since the last read (the newest 256 are
kept), for an offline render at any frame rate, and `sona_lipsync_current` the newest. The frames are the same for the
same samples however they are chunked (one sample at a time, 480, or the whole clip), and the same bits on every
platform, little- or big-endian, 32- or 64-bit: only `+ - * /` and `sqrt` are used, with the core's own tables, exp
and log.

The analysis window is 30 ms long and each step 10 ms long, so `sona_lipsync_latency` is 25 ms: half the window
and one step, at the sample rates of 8, 16, 44.1 and 48 kHz.

The analysis runs on the thread that feeds it, a step at a time; the talking crowd below shows what the mouths cost.

## How it decides

It starts from the web SDK's microphone mode: loudness against a running noise floor and speech peak
opens the mouth, and the energy in three bands picks the shape. The default mode measures these its own way, on a
window set to 30 ms, every 10 ms, with a -55 dB gate and smoothing (below). `SONA_LIPSYNC_WEB_RULES` runs the demo itself
instead (next section). On top of the demo's idea, the default mode adds:

- **Vowels by formants.** An LPC envelope (order 10, from the power spectrum up to a cutoff of 5 kHz, so any sample rate gives the
  same model) finds F1 and F2, and the nearest vowel regions pick the shape: /a/ and /ae/ AI, /i/ and /e/ EE, /o/ O,
  /u/ (and the fronted /u/ of American English) W, the central vowels L. A higher F1 opens the jaw wider.
- **Higher voices.** The speaker's pitch (subharmonic summation, a running mean in octaves) scales the vowel regions:
  a high voice's formants sit higher than a low voice's for the same vowel.
- **Closed lips.** A nasal murmur (almost all its energy under a cutoff of 400 Hz) shuts the lips at once, so the M in "my"
  closes the mouth instead of flapping it open.
- **Fricatives.** Hiss above a cutoff of 3.5 kHz shows FV when it is quiet (f, v, th) and DTH when it is loud (s, sh, z), even
  when it is too quiet to open the mouth.
- **Smoothing.** Openness and weights rise in `attack_seconds` (20 ms) and fall in `release_seconds` (70 ms); a
  shape holds at least `hold_seconds` (70 ms), and the current shape keeps an edge (a threshold of 10%), so the face never flickers.

It works the same at sample rates of 8 to 192 kHz, on floats or 16-bit samples, and for low and high voices.

### The web demo's rules (`SONA_LIPSYNC_WEB_RULES`)

With this flag the analyser is the demo's `listen()` over a Web Audio `AnalyserNode` (fftSize 1024,
smoothingTimeConstant 0.4), so a game can show the same mouths as the page:

- Every 50 ms (five steps, each set to 10 ms, of `round(rate / 100)` samples), one tick over the last 1024 samples at any rate.
- Loudness: the time-domain rms times 1.6. The floor moves by a fixed 10% toward a quieter tick and a fixed 0.2% toward a louder one,
  from 0.01. The peak is the largest of the rms, the peak times 0.995 and four times the floor, from 0.05. Openness
  is `(rms - 1.6 floor) / (peak - 1.6 floor)`, clamped to 0..1. There is no gate and no smoothing.
- The spectrum is the analyser's own: a Blackman window, `|X| / 1024` smoothed over ticks (0.4 of the last and 0.6
  of the new), and power summed over bins `floor(lo / hz)` up to `ceil(hi / hz)` for 150-900, 900-2500 and
  3500-8000 Hz, where hz is rate / 1024.
- The table: shut under 0.12 open. If the high band holds over a threshold of 55% of the energy, FV (or DTH from 0.45 open). If mid
  is over 1.4 times low, EE (or L at 0.5 open or less). If mid is under 0.45 times low, O (or W at 0.55 open or
  less). Otherwise AI. The hold is 70 ms long: a new shape waits until more than that has passed since the last change.
- A frame every 10 ms of audio carries the last tick's result, timed at its end. `open` is the tick's openness and
  `VOICED` means the tick wanted a shape. `hold_seconds`, `attack_seconds`, `release_seconds`, `gate_db`,
  `lead_seconds` and hints do not apply. `sona_lipsync_latency` is (512 + 5 steps) / rate: set to 60.7 ms at a sample rate of 48 kHz.

Under these rules native and the page's own JavaScript agree tick for tick on the shape, on `VOICED` and on the
openness, when both are fed the same samples. A browser's analyser computes in float32 and advances in 128-sample
render quanta, so in a browser a tick can see audio up to 128 samples older, and a band ratio within float rounding
of a threshold can go the other way.

## Voice chat: a mouth from a level

When all a voice SDK gives you per remote player is a level (linear RMS; its scale does not matter, the state
learns it), keep one `sona_voice_mouth` per speaker:

```c
sona_voice_mouth v[64];
for (i = 0; i < n; i++) sona_voice_mouth_init(&v[i], sona_avatar_id(avatars[i]));
/* each frame: */
uint32_t changed = sona_voice_mouths(avatars, v, levels, n, dt);
```

```cpp
// sona.hpp has no wrapper for voice mouths: the C calls on the handles
std::vector<sona::Avatar *> talkers;    // the avatars in voice chat
float levels[64] = {};                  // each one's voice level this frame
sona_avatar *avatars[64];
sona_voice_mouth v[64];
uint32_t n = (uint32_t)talkers.size();
for (uint32_t k = 0; k < n; k++) { avatars[k] = talkers[k]->raw(); sona_voice_mouth_init(&v[k], sona_avatar_id(avatars[k])); }
// each frame:
uint32_t changed = sona_voice_mouths(avatars, v, levels, n, (float)dt);
```

```csharp
var talkers = new List<SonaAvatar> { avatar, other };   // the avatars in voice chat
var v = talkers.Select(t => SonaLipSync.VoiceState(t.Id)).ToArray();
var levels = new float[talkers.Count];                    // each one's voice level this frame
// each frame: the binding's raw call
var handles = talkers.Select(t => t.Handle).ToArray();
fixed (IntPtr* h = handles) fixed (Native.sona_voice_mouth* vp = v) fixed (float* lv = levels)
    Native.sona_voice_mouths(h, vp, lv, (uint)talkers.Count, (float)dt);
```

```rust
let mut talkers = [avatar, other];                        // the avatars in voice chat
let mut v: Vec<VoiceMouth> = talkers.iter().map(|t| VoiceMouth::new(t.id())).collect();
let levels = [0.0f32; 2];                                 // each one's voice level this frame
// each frame: each talker's mouth from its level
for (k, t) in talkers.iter_mut().enumerate() {
    t.voice(&mut v[k], levels[k], dt as f32)?;
}
```

```python
talkers = [avatar, other]                                 # the avatars in voice chat
v = [sona.VoiceMouth(t.id) for t in talkers]
levels = [0.0] * len(talkers)                             # each one's voice level this frame
# each frame: each talker's mouth from its level
for t, vm, level in zip(talkers, v, levels):
    t.voice(vm, level, dt)
```

Loudness opens the mouth; the level rising out of a dip starts a syllable, which picks a shape from a sequence seeded
by `seed` and weighted by how wide the mouth opens (AI and O wide, EE, W and L in between, DTH and FV small). Two
talkers with the same voice do not move in step. The mouth shuts in a pause between syllables, a shape holds at
least `hold_seconds`, and a long vowel picks a new shape after a set interval of 220 ms.

`sona_voice_mouth_step` alone gives the shape and openness without an avatar, for a host rig. A step costs little more than the call: in C it is a few dozen flops. What costs on the avatar is the face: see below.

## Text and TTS

- **Phonemes as they play** (`sona_lipsync_hint`): when the TTS reports phonemes with times on the audio's clock,
  give them to the stream's analyser. A hint wins while the audio is sounding (M, B, P shut the lips at once), shows
  `lead_seconds` (40 ms) before its sound, as lips move ahead of the voice, and the frame says `SONA_LIPSYNC_HINTED`.
- **Timed phonemes to keys** (`sona_lipsync_phonemes`): a whole utterance's phonemes to `sona_mouth_key`s (time,
  mouth, open), with the lead, closures kept, shapes shorter than the hold merged, and the mouth shut over gaps.
- **Text to keys** (`sona_lipsync_text`): English spelling rules make the shapes (th, sh, ph, ee, oo, magic e,
  silent e, double letters), punctuation makes pauses, accented Latin letters take their vowel and other scripts a
  syllable a letter. With the audio, a Viterbi pass aligns the letters to the analyser's frames (open vowels on loud
  voiced frames, closures and pauses on quiet ones, the vowel's own formants as a cost), so each shape lands where it
  is said. Without audio, an even pace. Up to 4096
  letters and the 10 minutes limit of audio; past 16 M frame-letter cells the text is paced over the sounding part instead.
- **Playing keys** (`sona_mouth_keys_sample`): the shape at time t, eased over a 50 ms interval, with weights.

Phoneme symbols (`sona_phoneme_mouth`): ARPAbet with or without stress digits (`AH0`), IPA in UTF-8 (`ʃ`, `aɪ`,
stress and length marks skipped), the 15 viseme names (`sil`, `PP`, `FF`, `TH`, `DD`, `kk`, `CH`, `SS`, `nn`, `RR`,
`aa`, `E`, `ih`, `oh`, `ou`), the 22 viseme ids as digits (`"0"` silence to `"21"` p b m), and the mouth names
themselves (`AI`, `DTH`, `MBP`, `etc`). Anything else is `SONA_MOUTH_UNKNOWN`.

## On the avatar

`sona_avatar_mouth(a, shape)` sets the mouth part of the expression alone: a speech shape, any other shape index of
the face, or 255 to hand the mouth back to the clip (when nothing else is set, the whole face goes back). The face
sheet is baked again only when the shape changes. Each combination is baked once and kept in the face cache, so a
talking avatar costs a sheet copy per shape change, plus an upload when no other avatar already
shows that face. Avatars drawn as crowd sprites show no expressions.

On the GPU a re-baked face is keyed by its content (the look and the shapes), as the built face is. Avatars that
show the same face share one texture, and one that changes its mouth moves to the texture of its new face. If no
avatar shows that face, the texture it held is refilled when nothing else uses it, or a new one is made. So two
players with the same look never show each other's mouths. A stock-look crowd needs one texture per face shown, not
one per talker. An expression set after an avatar's first draw shows on the next frame.

The cost of a talking crowd, from `lipsync_vk --crowd 100` on an RTX 4090 machine: 100 avatars of the cast, their
faces at the automatic size, 120 frames silent, then 120 with every avatar talking from a level and 120 silent again,
the frame updated, drawn and read back. The median of three runs:

| `lipsync_vk --crowd 100` | ms a frame | of it, `sona_update` (ms) |
|---|---|---|
| Silent | 0.92 | 0.13 |
| Talking | 4.4 | 3.55 |

The crowd changed mouths 1,858 times in the sample's set 2 s of talking. Almost all of what talking
adds is the update's face re-bakes on the CPU; the draw costs the same either way.

The renderers upload a face that was baked again after the avatar was first drawn. The sample checks this on the
GPU: held still, shut then O then shut again must draw A, B, A exactly.

## Bindings

- C#. Stream: `SonaLipSync` (`Feed`, `Read`, `Mouth`, `Hint`, `Latency`). Keys: `SonaLipSync.FromText`, `.Sample`, `.PhonemeMouth`. Voice chat: `SonaLipSync.VoiceState`, `Native.sona_voice_mouth_step`. Avatar: `SonaAvatar.SetMouth`, `.Voice`.
- Python. Stream: `sona.LipSync` (`feed`, `read`, `current`, `hint`, `latency`). Keys: `sona.lipsync_text`, `lipsync_phonemes`, `mouth_keys_sample`, `phoneme_mouth`. Voice chat: `sona.VoiceMouth.step`. Avatar: `Avatar.mouth`, `.voice`.
- Rust. Stream: `sona::LipSync` (`feed`, `feed_i16`, `read`, `current`, `hint`, `latency`). Keys: `sona::lipsync_text`, `lipsync_phonemes`, `mouth_keys_sample`, `phoneme_mouth`. Voice chat: `sona::VoiceMouth::step`. Avatar: `Avatar::set_mouth`, `::voice`.

## The sample

`samples/c/lipsync_vk.c`: an avatar speaking a WAV file (16-bit or float, any rate, 1 to 8 channels), drawn
headless with Vulkan at the face framing, every frame to PNG, plus a sheet with one cell per shape shown and
`mouths.csv`. The audio is fed in video-frame chunks, as a game would feed its voice stream; `--text` uses the
text aligned to the audio instead; `--synth` speaks a built-in synthesised line, so it runs without a file; `--mouth
N` holds one shape.

```text
lipsync_vk --wav speech.wav [--text "what is said"] [--index 2] [--fps 30] [--size 384x384]
           [--out lipsync] [--every 1]
lipsync_vk --crowd 100 [--same] [--size 1280x720]
```

A twin with the same look stands beside the speaker. At the end, both go through five mouth steps side by side
(`twins.png`). `--crowd N` times a talking crowd instead (see "On the avatar").

It fails when fewer than three shapes show, when the drawn mouth does not follow `sona_avatar_mouth`, or when the twin
shows a mouth that is not its own.

## Reference

| Function | Contract |
|---|---|
| `sona_lipsync_defaults(o)` | 48 kHz, 1 channel, float, hold 0.07, attack 0.02, release 0.07, gate -55 dB, lead 0.04; sets `size` |
| `sona_lipsync_create(o, al, out)` | NULL `o`: the defaults; NULL `al`: malloc. `SONA_E_ARGUMENT` for a short `size`, a rate outside 8000..192000, channels outside 1..8, another format, times out of range (hold 0..1, attack 0..1, release 0..2, lead 0..0.5 s, gate -120..0 dB), NaN, unknown flags or non-zero reserved words |
| `sona_lipsync_destroy(ls)`, `sona_lipsync_reset(ls)` | reset: time 0, frames and hints dropped, the floor and the speaker's pitch learnt again |
| `sona_lipsync_feed(ls, pcm, frames)` | frames are samples per channel; non-finite or out-of-range float samples count as 0. `SONA_E_ARGUMENT` for NULL `ls`, or NULL `pcm` with frames |
| `sona_lipsync_read(ls, out, max)` | moves up to `max` frames, oldest first; returns how many |
| `sona_lipsync_current(ls, out)` | the newest frame; a shut mouth at time 0 before the first |
| `sona_lipsync_latency(ls)` | (window / 2 + step) / rate, by default 25 ms; with `SONA_LIPSYNC_WEB_RULES` (512 + 5 steps) / rate |
| `sona_lipsync_hint(ls, ph, count)` | unknown symbols and empty spans are skipped; up to 256 held, the oldest go; hints that ended a second before the newest frame go |
| `sona_phoneme_mouth(symbol)` | `SONA_MOUTH_*`, or `SONA_MOUTH_UNKNOWN` (255) |
| `sona_lipsync_phonemes(ph, count, o, out, cap, total)` | phonemes in start order (`SONA_E_ARGUMENT` otherwise, or for an end before its start); `*total` keys, up to `cap` written; the same total for any `cap` |
| `sona_lipsync_text(text, pcm, frames, o, out, cap, total)` | `pcm` in `o`'s rate, channels and format; `SONA_E_LIMIT` past 4096 letters or the 10 minutes limit |
| `sona_mouth_keys_sample(keys, count, t, out)` | before the first key and with no keys: shut |
| `sona_avatar_mouth(a, shape)` | `SONA_E_ARGUMENT` for a shape past 13 that is not 255, `SONA_E_DESTROYED` for a removed avatar |
| `sona_voice_mouth_init(v, seed)`, `sona_voice_mouth_step(v, level, dt, open)` | dt clamped to 0..1 s, a NaN or negative level counts as 0; returns `SONA_MOUTH_NEUTRAL` for a state that was not initialised |
| `sona_avatar_voice(a, v, level, dt)`, `sona_voice_mouths(avatars, states, levels, count, dt)` | the step, then `sona_avatar_mouth`; the batch skips NULL avatars and returns how many mouths changed |

Structs: `sona_lipsync_options` (64 bytes, `size` first), `sona_lipsync_frame` (72), `sona_phoneme` (16, 12 on
32-bit), `sona_mouth_key` (16), `sona_voice_mouth` (56, `size` first), and the opaque `sona_lipsync`.
`sona_struct_size` and `sona_struct_offset` know them.

## Limits

- The WASM binding, the C++ header and the engine components (Unity, Unreal, Godot) do not wrap these calls; call
  the C functions.
- The web SDK's mouths are its own JavaScript. `SONA_LIPSYNC_WEB_RULES` makes the native analyser give the web's
  mouths tick for tick, so a native server and a web client agree.
- A talking crowd's cost is the CPU re-bake of each face that changes (above).
- The baked face has discrete shapes, so the mouth switches rather than blends; the weights are there for rigs that
  can blend.
- Speaker normalisation uses pitch alone; a child's or a very low voice is read with the nearest scale.
