# Face tracking (sona_track)

A webcam, a phone's depth camera or any face tracker drives an avatar's face and head. The tracker gives the 52
ARKit-style blendshapes (MediaPipe's face landmarker, ARKit, Live Link Face and most others do) and a head
rotation; `sona_track` turns them into the avatar's face shapes and turns its head and neck, smoothed, against the
user's own neutral face.

It is an optional module, its own library beside the core: `include/sona_track.h`, `libsona_track.so`,
`sona_track.dll` (with `sona_track.lib`), `libsona_track.dylib`, and the static `libsona_track.a`
(`sona_track_static.lib` under MSVC). It links the core through `sona.h` like any app does, so the core library
does not grow for it. CMake builds it with the core (`-DSONA_BUILD_TRACK=OFF` leaves it out); `cmake/track.cmake`
has the targets. It is built and tested on Linux, Windows (MSVC) and Android; on the web the same tracker is
JavaScript (see "On the web" below), giving the same shapes frame for frame.

## Quick start

```c
#include "sona_track.h"

sona_track_options o;
sona_tracker *trk;
sona_track_defaults(&o);
o.flags = SONA_TRACK_MIRROR;                       /* a selfie view: the avatar mirrors the user */
sona_track_create(&o, &trk);

sona_track_calibrate_begin(trk);                   /* ask the user to look at the camera, relaxed */
/* ... feed about a second of frames ... */
sona_track_calibrate_end(trk, &saved);             /* keep `saved` for the next session: calibration_set */

/* each camera frame */
sona_track_face_input in;
sona_track_face_input_defaults(&in);
in.time = seconds;                                 /* the camera frame's time */
in.flags = face_found ? SONA_TRACK_FOUND | SONA_TRACK_HAS_HEAD : 0;
in.layout = SONA_TRACK_LAYOUT_MEDIAPIPE;           /* the scores exactly as the face landmarker returns them */
in.weights = scores;                               /* 52 floats */
sona_track_quat_from_matrix(transform, 4, 0, in.head_rotation);   /* MediaPipe's 4x4, row-major */
sona_track_face_feed(trk, &in);
sona_track_apply(trk, avatar);                     /* before sona_update */
sona_update(ctx, dt, &view, NULL);
```

```cpp
#include "sona_track.h"

sona_track_options o;
sona_tracker *trk = nullptr;
sona_track_defaults(&o);
o.flags = SONA_TRACK_MIRROR;                       // a selfie view: the avatar mirrors the user
sona_track_create(&o, &trk);

sona_track_calibrate_begin(trk);                   // ask the user to look at the camera, relaxed
// ... feed about a second of frames ...
sona_track_calibrate_end(trk, &saved);             // keep `saved` for the next session: calibration_set

// each camera frame
sona_track_face_input in;
sona_track_face_input_defaults(&in);
in.time = seconds;                                 // the camera frame's time
in.flags = face_found ? SONA_TRACK_FOUND | SONA_TRACK_HAS_HEAD : 0;
in.layout = SONA_TRACK_LAYOUT_MEDIAPIPE;           // the scores exactly as the face landmarker returns them
in.weights = scores;                               // 52 floats
sona_track_quat_from_matrix(transform, 4, 0, in.head_rotation);   // MediaPipe's 4x4, row-major
sona_track_face_feed(trk, &in);
sona_track_apply(trk, avatar.raw());               // before ctx.update
ctx.update(dt, &view);
```

```csharp
using var trk = new SonaTracker(SonaTrackFlags.Mirror);   // a selfie view: the avatar mirrors the user

trk.CalibrateBegin();                     // ask the user to look at the camera, relaxed
// ... feed about a second of frames ...
var saved = trk.CalibrateEnd();           // keep it for the next session

// each camera frame: the 52 scores exactly as the face landmarker returns them, and its head matrix
trk.Feed(seconds, scores, head);
trk.Apply(avatar);                        // before ctx.Update
ctx.Update(dt, view);
```

```rust
// The Rust crate does not wrap face tracking: the sona-track-sys crate declares sona_track.h's calls, made as in
// C (sona_track_create, sona_track_face_feed, sona_track_apply) with the avatar's handle, avatar.raw().
let handle = avatar.raw();
```

```python
from sona.track import Tracker, quat_from_matrix

trk = Tracker(mirror=True)                # a selfie view: the avatar mirrors the user

trk.calibrate_begin()                     # ask the user to look at the camera, relaxed
# ... feed about a second of frames ...
saved = trk.calibrate_end()               # keep it for the next session

# each camera frame: the 52 scores exactly as the face landmarker returns them, and its 4x4 head matrix
trk.feed(seconds, scores, head=quat_from_matrix(transform))
trk.apply(avatar)                         # before ctx.update
ctx.update(dt)
```

`sona_track_face_get` returns the state instead, for hosts that draw the avatar themselves through the data API: the
five face shape indices for `sona_avatar_expression`, the head rotation in the avatar's body space, the mood and the
filtered weights.

## What goes in

- **Weights**: 52 floats, 0 to 1. `SONA_TRACK_LAYOUT_ARKIT` is Apple's order (`sona_blendshape` in the header, the
  order Live Link Face streams). `SONA_TRACK_LAYOUT_MEDIAPIPE` is the face landmarker's own list, `_neutral` first
  and the rest sorted by name; it has no `tongueOut`. `sona_track_blendshape_find("jawOpen")` maps any other
  tracker's names.
- **Head rotation**: a unit quaternion (x, y, z, w) in the tracker's camera space: +X to the right of the image, +Y
  up, +Z out of the screen; identity is a face looking straight into the camera. `sona_track_quat_from_matrix` takes
  a 3x3 or the upper left of a 4x4, rows or columns (`stride` 4 and `transpose` 0 for MediaPipe's
  `facial_transformation_matrixes` as numpy holds them, `transpose` 1 for a column-major ARKit `simd_float4x4`), and
  takes the scale off. `sona_track_quat_from_euler(pitch, yaw, roll)` takes degrees from trackers that give angles.
- **Time**: seconds, rising. Filters and holds run on it, not on the number of calls, so cameras with a frame rate of 24, 30 or 60 fps
  behave the same. A gap of over a second, or a time that goes back, starts the filters again.
- **No face**: feed the frame without `SONA_TRACK_FOUND`. The last face holds for `lost_seconds` (0.5), then the
  head eases back to the clip over `return_seconds` (0.4) and the face is handed back to the clip half way.

## The avatar's face is drawn, not blended

The avatar's face is a set of drawn shapes, not a mesh with blendshapes: 14 mouths (seven moods and seven speech
shapes), 5 eyebrows a side (neutral, sad, angry, confused, raised) and 14 eyes a side (the seven moods, yawning,
sleeping, looking up, down, in and out, and the blink). The tracker picks one shape per part each frame, and the face
sheet is baked again only when a shape changes (each combination once; later ones come from the cache).

1. **A mood for the whole face**, from the weights together: happy (a smile), laughing (a smile with an open jaw),
   shocked (raised brows or wide eyes with an open jaw; raised brows alone stay a neutral face with raised brows),
   angry (lowered brows or a sneer, pressed lips), sad (a frown, or the inner brows up without the outer), confused
   (one brow up and the other not, or the mouth pulled to one side). Below 0.35 the face is neutral; a mood stays
   until it falls under 0.25 or another beats it by 0.1.
2. **Mouth**: a mood's mouth while the mouth is nearly closed (laughing and shocked always). Otherwise speech: W
   for a pucker, O for a funnel, DTH for the tongue, FV for the lower lip rolled in, then by how far the mouth is
   open (jaw open less lips closed, plus the lower lip pulled down): AI, EE (lips stretched or a slight smile), L,
   DTH, closed.
3. **Eyebrows**, per side: the mood's brows (raised for shocked and laughing, as the avatar clips themselves do), else
   lowered, raised or the sad inner lift from that side's weights.
4. **Eyes**, per side: shut is the blink at once (eyeBlink over 0.4, open again under 0.28), the sleeping eyes after
   `sleep_seconds` (1.5) shut, the laughing eyes while laughing. A wide-open jaw with half-shut eyes is a yawn. Then the
   mood's eyes, and in a neutral face the look up, down, in or out (over 0.45, held to 0.3). A wink is a wink: each eye
   is its own.
5. **Holds**: a new shape shows once it has been asked for over a threshold of 0.05, 0.08 or 0.1 s (the mouth; the brows and eyes;
   the mood); the blink shows at once. One stray frame never reaches the face.

`sensitivity` scales the weights before the choice (not the weights `face_get` returns). 0, the default, picks it by
layout: 1 for ARKit and 1.4 for MediaPipe, whose scores run lower.

## The head and neck

The head's rotation is limited (`head_limit_deg`: 40 pitch, 65 yaw, 35 roll, after `head_gain`) and split between
the Neck (`neck_share`, 0.35) and the Head joints, through `SONA_OVERRIDE_ADD` overrides. The rotation is aimed in
the avatar's body space, measured each frame from its posed joints (left from the shoulders, up from the hips to the
neck, forward from the feet), so it is right for a turned avatar, a leaning one and any clip: a subject turning to
their own left turns the avatar's head to the avatar's own left. Overrides need a clip playing (the default idle
does).

## Smoothing and calibration

Each weight and the head rotation go through a One Euro filter (Casiez, Roussel and Vogel, CHI 2012): smooth when still,
little lag when moving. Defaults: for the weights a cutoff set to 3 Hz at rest and a beta of 2; for the head a cutoff
set to 1.2 Hz and a beta set to 0.6 per radian a second.

`sona_track_calibrate_begin` and `_end` take the neutral face: each weight's 30th percentile over the frames between
(the first 300) and their mean head rotation. Blinks and words said during it do not move a low percentile. Each
weight then has its neutral taken off and the rest rescaled to 0..1, and the neutral head is identity, so a camera
off to one side is straight ahead. `sona_track_calibration_get` and `_set` save it for the next session.

## Mirroring

With `SONA_TRACK_MIRROR` the avatar is the user's reflection, as a selfie preview is: left and right weights swap and
the head turns the other way. Leave it off when the camera films someone else (the sample on a recorded clip does).

## Options

| Field | Default | Meaning |
|---|---|---|
| `flags` | 0 | `SONA_TRACK_MIRROR`, `_NO_HEAD`, `_NO_FACE`, `_NO_GAZE` |
| `face_min_cutoff`, `face_beta` | 3, 2 | the weights' filter |
| `head_min_cutoff`, `head_beta` | 1.2, 0.6 | the head's filter |
| `head_gain` | 1 | 0 to 4 |
| `head_limit_deg` | 40, 65, 35 | pitch, yaw, roll |
| `neck_share` | 0.35 | 0 to 1 |
| `sensitivity` | 0 (by layout) | up to 4 |
| `lost_seconds`, `return_seconds` | 0.5, 0.4 | seconds a lost face is held, then seconds to hand the face back to the clip |
| `sleep_seconds` | 1.5 | 0: never |

A tracker drives one avatar at a time. To drive several from one camera, feed the same frames to several trackers.

## The reference integration: MediaPipe and a sona-track stream

`mediapipe_track.py`, in the templates archive at `templates/vtuber/`
([getting it](../install.md#starters-and-templates)), runs MediaPipe's face landmarker (Apache-2.0,
`pip install mediapipe numpy`; the model is `face_landmarker.task`, [where it comes from](../install.md#third-party))
over a video file or a webcam, with ffmpeg decoding, and writes a sona-track stream. The
[VTuber kit](../tutorials/template-vtuber.md) reads the stream, drives one avatar and writes its frames:

```text
python3 sdk/templates/vtuber/mediapipe_track.py --video clip.webm --model face_landmarker.task --out clip.sonatrack
sona_vtuber --licence sona-licence.json --avatar me.b64 --face clip.sonatrack --headless --out out
```

Live, the tracker feeds the kit through a pipe: `mediapipe_track.py --webcam 0 ... --out - | sona_vtuber
--face - ...`. On a Linux desktop session MediaPipe can be killed at start (SIGKILL) when xdg-desktop-portal grants
its threads real-time priority; `DBUS_SESSION_BUS_ADDRESS=disabled:` in front of the tracker avoids it.

The stream is text: a header `sona-track 1 <arkit|mediapipe> 52`, `#` comments (`# frames W H` gives the frames
file's size), then one line a frame: `<seconds> <found 0|1> <qx> <qy> <qz> <qw> <52 weights>`.
`templates/vtuber/track_stream.h` reads it.

## On the web

`SonaTrack` in the web SDK is the same tracker in JavaScript. The page brings MediaPipe's face landmarker
(`@mediapipe/tasks-vision`, Apache-2.0) and a `<video>` showing the camera; nothing leaves the browser.

```js
import { FaceLandmarker, FilesetResolver } from '@mediapipe/tasks-vision';
import { SonaTrack } from '<the SDK bundle, sona-renderer.js>';
const { createFaceTracker, startFaceTracking } = SonaTrack;

const files = await FilesetResolver.forVisionTasks('<tasks-vision wasm>');
const landmarker = await FaceLandmarker.createFromOptions(files, {
  baseOptions: { modelAssetPath: 'face_landmarker.task' }, runningMode: 'VIDEO', numFaces: 1,
  outputFaceBlendshapes: true, outputFacialTransformationMatrixes: true,
});
video.srcObject = await navigator.mediaDevices.getUserMedia({ video: true });
await video.play();
const tracker = createFaceTracker({ mirror: true });          // a selfie view
const stop = startFaceTracking({ video, landmarker, tracker, avatar });
```

`startFaceTracking` calibrates on the first second with a face, feeds the tracker on each new video frame and puts
the face and head on the avatar: each pose the avatar takes shows the tracker's mouth, eyebrows and eyes over its
clip's, and its neck and head turned as the native module turns them (`driveAvatar` does only that part; while it
drives an avatar, that avatar poses every frame, and the function it returns puts the avatar back as it was).
`tracker.state()` has the rest: the mood, the head's turn in the avatar's body space and
the filtered weights. Hosts with their own camera code call `tracker.feed(frameFromLandmarker(result,
seconds))` themselves; `feed` also takes 52 numbers in ARKit or MediaPipe order, as the C struct does. The options
are the C options with camel-case names (`faceMinCutoff`, `headLimitDeg`, `lostSeconds`, ...).

## Body tracking

Body landmarks have their own module, `sona_body` ([body tracking](body-tracking.md)). It drives the body below the
neck; this one keeps the face, Neck and Head, and both run on one avatar.

## Bindings

- Python: `from sona import track`; `track.Tracker(mirror=True)`, `.feed(time, scores, head, layout="mediapipe")`,
  `.state()`, `.calibrate_begin()`, `.calibrate_end()` (bytes), `.calibration_set(bytes)`, `.apply(avatar)`,
  `.release(avatar)`.
- C#: `SonaTracker` in `Track.cs` (`Feed`, `State`, `CalibrateBegin`, `CalibrateEnd`, `CalibrationSet`, `Apply`,
  `Release`), over `TrackNative`.
- Rust: the `sona-track-sys` crate, raw declarations and `layout::check`, beside `sona360-sys`.

## Limits

- MediaPipe's "Left" scores are read as the subject's left, as ARKit's are. Should a MediaPipe build give the image's
  left, a wink shows on the other eye; the head is not affected (its rotation comes from the transformation matrix).
- The MediaPipe sensitivity and the speech thresholds are set for typical adult faces; `sensitivity` changes them.
