# Body tracking (sona_body)

A webcam drives an avatar's whole body, with no depth sensor. A pose tracker such as MediaPipe's pose landmarker gives a body's
33 landmarks every frame from one ordinary camera; `sona_body` turns them into the avatar's hips, spine,
chest, arms, hands, legs and feet, smoothed and kept inside a person's range. It drives the body below the neck;
`sona_track` ([face tracking](face-tracking.md)) drives the face, neck and head, and both run on one avatar.

It is an optional module, its own library beside the core: `include/sona_body.h`, `libsona_body.so`,
`sona_body.dll` (with `sona_body.lib`), `libsona_body.dylib` and the static `libsona_body.a` (`sona_body_static.lib`
under MSVC). It links the core through `sona.h` like any app does. CMake builds it with the core
(`-DSONA_BUILD_BODY=OFF` leaves it out); `cmake/body.cmake` has the target. Its calls are C, and C++ calls them as
they are; the C#, Rust and Python bindings do not wrap `sona_body`.

## Quick start

```c
#include "sona_body.h"

sona_body_tracker *body;
sona_body_options o;
sona_body_defaults(&o);
o.flags = SONA_BODY_MIRROR;                 /* a selfie view: the user's left hand moves the avatar's right */
sona_body_create(&o, &body);

/* each frame, with what the pose tracker saw */
sona_body_input in;
sona_body_input_defaults(&in);
in.flags = found ? SONA_BODY_FOUND : 0;
in.time = seconds;                          /* the camera frame's time, rising */
in.layout = SONA_BODY_LAYOUT_MEDIAPIPE;
in.points = landmarks;                      /* 33 x (x, y, z), metres, see below */
in.visibility = visibility;                 /* 33 values 0..1, or NULL */
in.image = image;                           /* 33 x (x, y) in the picture, 0..1; or NULL, see below */
sona_body_feed(body, &in);
sona_body_apply(body, avatar);
sona_update(ctx, dt, NULL, NULL);

/* later */
sona_body_release(body, avatar);            /* the clip has the body back */
sona_body_destroy(body);
```

```cpp
#include "sona_body.h"

sona_body_tracker *body = nullptr;
sona_body_options o;
sona_body_defaults(&o);
o.flags = SONA_BODY_MIRROR;                 // a selfie view: the user's left hand moves the avatar's right
sona_body_create(&o, &body);

// each frame, with what the pose tracker saw
sona_body_input in;
sona_body_input_defaults(&in);
in.flags = found ? SONA_BODY_FOUND : 0;
in.time = seconds;                          // the camera frame's time, rising
in.layout = SONA_BODY_LAYOUT_MEDIAPIPE;
in.points = landmarks;                      // 33 x (x, y, z), metres, see below
in.visibility = visibility;                 // 33 values 0..1, or nullptr
in.image = image;                           // 33 x (x, y) in the picture, 0..1; or nullptr, see below
sona_body_feed(body, &in);
sona_body_apply(body, avatar.raw());
ctx.update(dt);

// later
sona_body_release(body, avatar.raw());      // the clip has the body back
sona_body_destroy(body);
```

```csharp
// The body tracking module (sona_body) has no C# binding: its calls are C. Call them from C or C++, or
// declare the few you need with [DllImport("sona_body")] beside the SDK's own Native class.
```

```rust
// The body tracking module (sona_body) has no Rust crate: its calls are C. Declare the ones you need in an
// extern "C" block and link sona_body beside sona360-sys.
```

```python
# The body tracking module (sona_body) has no Python binding: its calls are C. Load libsona_body with
# ctypes and declare the calls you need, as the package's own _native module does for the core.
```

The avatar keeps playing its clip underneath (an idle is best): the body goes on as pose overrides after the clip and
before the IK, so foot planting and look-at still work on top.

## What goes in

`points` are MediaPipe's 33 pose world landmarks, nose first, in its order (`PoseLandmarker`'s
`pose_world_landmarks`): metres, the origin between the hips. Two of MediaPipe's axes are turned round: the SDK
takes +X to the right of the image, +Y up and +Z towards the camera, so pass `x, -y, -z` of what MediaPipe returns.
`visibility` is MediaPipe's per-landmark visibility. `image` is where each landmark is in the picture, 0..1 from its
top left: MediaPipe's normalized landmarks (`pose_landmarks`), x and y. Pass it whenever the tracker has it. A pose
tracker guesses the parts of the body the camera does not show, often at a high visibility (a desk camera that sees
the head and shoulders still gets a pair of standing legs); with `image`, a landmark outside the picture is not
seen, whatever its visibility.

`samples/body/mediapipe_body.py` runs the landmarker over a video file or a webcam and writes a `.sonabody` stream
(a header `sona-body 2 mediapipe 33`, `#` comments, then `<seconds> <found> <x y z visibility image_x image_y> * 33`
per frame; version 1 streams have no image coordinates); `samples/body/body_stream.h` reads both.

## What comes out

- **Hips**: the hip line turns and tilts the pelvis.
- **Spine and chest**: the shoulders' turn and lean over the hips, half each.
- **Arms and legs**: each bone is turned to point where its landmarks point. The upper arm and the thigh also roll
  so that the elbow or knee bends in the plane the landmarks bend in; a limb that is nearly straight keeps the clip's
  roll. Elbows bend up to 145 degrees and knees up to 150 (the IK's limits); a knee bent the wrong way, or a hip
  rolled past 70 degrees, keeps the leg straight.
- **Hands and feet**: the hand points between the index and little finger landmarks and turns with them, at most
  75 degrees from the forearm; the foot points along the heel-to-toe line, at most 45 degrees from the shin.

Everything is measured in the avatar's own body space, so it holds for any turn or placement of the avatar.

## Seen, lost and guessed

- A landmark seen less than `min_visibility` (0.5), or outside the picture, is left to the clip, and so is
  everything below it: a hidden elbow leaves the forearm and hand to the clip too. A landmark drives its joint once it
  has been seen for a threshold of 0.2 s in a row, so a guess that flickers above the visibility for a frame or two moves nothing. A
  joint eases in and out over a 0.2 s interval as its landmarks come and go; while it eases out it keeps the turn it last had,
  never the guess that replaced it. A landmark not seen keeps where it was last seen, so a joint still tracked above
  one that eases out (an upper arm over a forearm whose wrist left the picture) keeps its roll too.
- Without a body (`SONA_BODY_FOUND` unset) the last pose holds for `lost_seconds` (0.5), then the body eases back to
  the clip over `return_seconds` (0.4). A new body eases in over the same time.
- Frames that are a tracker's guess at a body half out of the picture count as no body: the shoulders not seen,
  the shoulders not above the hips, a seen knee above the shoulders, or both knees above the hips (which no standing
  or sitting body does). A jump no body makes in one frame (more than half a metre: a camera cut, someone else
  stepping in) restarts the filters instead of gliding between the two, and every landmark waits its 0.2 s threshold again.
  Lying down is not tracked.

## Flags

- `SONA_BODY_MIRROR`: left and right swap, as in a selfie view.
- `SONA_BODY_NO_LEGS`: hips and legs stay the clip's whatever the tracker sees. With `image` a desk camera's legs
  are left to the clip anyway; this is for hosts without picture coordinates, or a game that wants the legs its own.
- `SONA_BODY_NO_ROOT`: the user's turn about the vertical is dropped, so the avatar keeps facing where it was
  placed; leaning and tilting still show. World landmarks have no position in the room, so the avatar never walks
  with the user: move it with `sona_avatar_move` if the game wants that.

## Smoothing

Each landmark coordinate has a One Euro filter (Casiez, Roussel and Vogel 2012): `min_cutoff` (1.5 Hz) is how much a
still pose is smoothed, `beta` (0.8) how fast the smoothing gives way when the user moves. Lower `min_cutoff` for a
steadier but slower body; raise `beta` for quicker arms.

## The reference integration: a video to side-by-side PNGs

```sh
python3 samples/body/mediapipe_body.py --video clip.webm --model pose_landmarker_full.task \
        --out clip.sonabody --frames clip.rgba --frame-height 240
body_video_vk --cast devs-cast.json --stream clip.sonabody --frames clip.rgba \
              --out-dir body_video --every 24 --sheet sheet.png
```

`body_video_vk` drives one avatar with the stream, draws it headless with Vulkan beside the frame it came from, and
prints how far the arms and legs are from the landmarks. Live: `mediapipe_body.py --webcam 0 --out - | body_video_vk
--stream - ...`. MediaPipe's pose models (`pose_landmarker_lite`, `_full`, `_heavy`) are on its model page,
Apache-2.0.

## Limits

- `sona_body` is native only: the web SDK's avatar has no pose overrides to take it.
- The tolerances are set for one person in a plain room; a cluttered room or a loose costume is noisier.
