Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions examples/egocap/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,15 @@ before any file is written. An existing derived episode is refused, never replac
rewriting `config.yaml`, and never record into a session that has none.
- Work that must survive a cancelled caller (notifying the aligner of a kept episode, for one) runs inside the
owned operation task, not after the awaited result.

## The wire tracking layout has hand-kept mirrors

- A change to `IC_TRACKING_V1_FIELDS` is also a change to the frontend's `KNOWN_TRACKING_FIELDS`, the
`realDescriptor.test.ts` fixture (regenerate it, then compare it with the server's own descriptor) and the
CaptureServer README's offset table and descriptor example. Check each against the code's output, not by eye.
- The acquisition adapter runs one code path for the real, mock and replay SDKs. Give a new SDK capability to
all three; never probe the SDK for it, which turns a missing export into silently absent data.
- New recorded data is opt-in on the request that enables its source, off by default: with it off, the
recorded layout and the plugin's arguments are what they were before. Absent data needs its own marker,
and a rule that never blends it with reported data when the episode is time aligned.
- A commit's README hunks describe only what that commit ships; check each against the branch, not a local tree.
10 changes: 7 additions & 3 deletions examples/egocap/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,13 @@ orientation for the head and both controllers, plus each controller's button and
sampled together so the three poses stay consistent with each other within one tick.

Hand tracking comes from the hand-tracking gloves, reported as a full per-joint hand skeleton for
each hand when it is being tracked. The recorded hand-tracking row for a tick is dropped entirely
each hand when it is being tracked, with the gloves' raw fingertip-sensor poses recorded on the
same row when the session requests them. The recorded hand-tracking row for a tick is dropped entirely
if either hand's wrist goes untracked — both hands together, not just the affected one — rather
than filled with a stale or fabricated pose; a live view can still show whichever hand remains
tracked, and the headset and controller rows for that tick are still recorded as usual.
tracked, and the headset and controller rows for that tick are still recorded as usual. With the
raw sensors requested, a tick where a glove reported them is kept, and an untracked hand is
all zero on that row.

A typical station uses one head camera and two wrist cameras. CaptureServer streams the supported
camera set requested by the client, so a station can be configured with a different camera set
Expand All @@ -118,7 +121,8 @@ values.
### Saved data

A kept episode is written to the station's local storage as one MP4 video file per recorded
camera, numeric tracking data — headset and controller pose, hand skeleton — stored in Zarr, and
camera, numeric tracking data — headset and controller pose, hand skeleton, raw glove fingertip
sensors — stored in Zarr, and
metadata: the task description and the operator who recorded it.

An automatic check runs once a take finishes recording and marks it kept, flagged, or rejected,
Expand Down
8 changes: 7 additions & 1 deletion examples/egocap/backend/egocap_web/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
from .preview_protocol import capture_session_facts
from .preview_routes import router as preview_router
from .recording_adapter import (
MANUS_GLOVE_SENSORS_SPEC,
MANUS_GLOVE_SPEC,
PICO_CONTROLLER_SPEC,
RecordingAdapterError,
Expand Down Expand Up @@ -196,6 +197,7 @@ def _recording_config_factory(
on_video_sources: Callable[[frozenset[str], frozenset[str]], None] | None = None,
video_encoder: str = DEFAULT_VIDEO_ENCODER,
video_encoder_options: dict[str, Any] | None = None,
manus_sensors: bool = False,
):
"""Builds the real ``ServiceConfig`` lazily, read fresh each time the
coordinator actually opens/reopens a session (not once at import time)
Expand Down Expand Up @@ -262,7 +264,10 @@ def factory() -> ServiceConfig:
)
config = ServiceConfig(
output_root=output_root,
numeric_sources=(PICO_CONTROLLER_SPEC, MANUS_GLOVE_SPEC),
numeric_sources=(
PICO_CONTROLLER_SPEC,
MANUS_GLOVE_SENSORS_SPEC if manus_sensors else MANUS_GLOVE_SPEC,
),
video_sources=video_sources,
qc=QcConfig(required_sources=required, capture=capture_qc),
calibration_assets=_station_calibration_assets(),
Expand Down Expand Up @@ -601,6 +606,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
initial_context=initial_context,
livekit_source=livekit_source,
tracking_latency=resolved_station.latency if resolved_station is not None else None,
manus_sensors=config.manus_sensors,
capture_facts=lambda: capture_session_facts(monitor.native),
)
monitor.set_recording(coordinator)
Expand Down
9 changes: 8 additions & 1 deletion examples/egocap/backend/egocap_web/capture_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
CaptureStatus,
CaptureStatusType,
CaptureStopped,
ManusPluginConfig,
RequestRejectedError,
StoppedBeforeAcceptedError,
)
Expand Down Expand Up @@ -383,7 +384,13 @@ async def _run_attempt(self) -> None:
await self._client.start(
sources=self._config.sources,
cameras=self._config.cameras,
plugins=self._config.plugins,
plugins=tuple(
# The Manus request carries the configured datasets; any other plugin keeps its defaults.
ManusPluginConfig(datasets=self._config.manus_datasets)
if plugin is p.PluginType.MANUS
else plugin
for plugin in self._config.plugins
),
on_started=self._on_started,
on_status=self._on_status,
on_capture_frame=self._on_capture_frame,
Expand Down
38 changes: 37 additions & 1 deletion examples/egocap/backend/egocap_web/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,17 @@ class CaptureStatusConfig:
)
cameras: tuple[p.CameraSelection, ...] = field(default_factory=tuple)
plugins: tuple[p.PluginType, ...] = field(default_factory=tuple)
#: The Manus plugin outputs to request. The raw fingertip sensors are sent and recorded only when asked for.
manus_datasets: tuple[p.ManusDataset, ...] = (p.ManusDataset.HUMAN,)

@property
def manus_sensors(self) -> bool:
"""Whether this session requests the gloves' raw fingertip sensors."""
return p.PluginType.MANUS in self.plugins and p.ManusDataset.SENSORS in self.manus_datasets


class PluginConfigError(ValueError):
"""Raised for a malformed EGOCAP_CAPTURE_PLUGINS value. Raised while the
"""Raised for a malformed EGOCAP_CAPTURE_PLUGINS or EGOCAP_MANUS_DATASETS value. Raised while the
backend is starting, so a typo in a deployment stops the process with a
message naming the bad value instead of silently running without the
plugin an operator asked for."""
Expand Down Expand Up @@ -83,6 +90,32 @@ def _parse_plugins(raw: str | None) -> tuple[p.PluginType, ...]:
return tuple(plugins)


#: Operator-facing Manus dataset names -> wire types, derived from the protocol enum like ``_PLUGIN_NAMES``.
_MANUS_DATASET_NAMES: dict[str, p.ManusDataset] = {member.name.lower(): member for member in p.ManusDataset}


def _parse_manus_datasets(raw: str | None) -> tuple[p.ManusDataset, ...] | None:
"""Parses EGOCAP_MANUS_DATASETS: a comma-separated list of Manus dataset names (``human``, ``sensors``;
case-insensitive), e.g. ``human,sensors`` to also record the gloves' raw fingertip sensors. Returns
``None`` when unset or blank, meaning "keep the default datasets"."""
if raw is None or raw.strip() == "":
return None
datasets: list[p.ManusDataset] = []
for item in raw.split(","):
name = item.strip().lower()
dataset = _MANUS_DATASET_NAMES.get(name)
# A blank or unknown entry fails fast with the accepted spellings rather than recording without it.
if dataset is None:
raise PluginConfigError(
f"EGOCAP_MANUS_DATASETS entry {item.strip()!r} is not a known dataset; "
f"valid names: {sorted(_MANUS_DATASET_NAMES)}"
)
if dataset in datasets:
raise PluginConfigError(f"EGOCAP_MANUS_DATASETS lists {name!r} more than once")
datasets.append(dataset)
return tuple(datasets)


class SourceConfigError(ValueError):
"""Raised for a malformed EGOCAP_CAPTURE_SOURCES value, at backend startup, so a typo stops the process
with a message naming the bad value instead of silently requesting different tracking than intended."""
Expand Down Expand Up @@ -125,6 +158,9 @@ def config_from_env() -> CaptureStatusConfig:
sources = _parse_sources(os.environ.get("EGOCAP_CAPTURE_SOURCES"))
if sources is not None:
overrides["sources"] = sources
manus_datasets = _parse_manus_datasets(os.environ.get("EGOCAP_MANUS_DATASETS"))
if manus_datasets is not None:
overrides["manus_datasets"] = manus_datasets
return CaptureStatusConfig(
capture_server_url=os.environ.get("EGOCAP_CAPTURE_SERVER_URL", "ws://127.0.0.1:8082"),
plugins=_parse_plugins(os.environ.get("EGOCAP_CAPTURE_PLUGINS")),
Expand Down
66 changes: 56 additions & 10 deletions examples/egocap/backend/egocap_web/recording_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@
),
"ManusFrame",
)
#: The glove source of a session that requested the raw fingertip sensors: per hand, the sensor transforms
#: and how many of them the glove reported.
MANUS_GLOVE_SENSORS_SPEC = NumericSourceSpec(
MANUS_GLOVE_SOURCE,
(
*MANUS_GLOVE_SPEC.fields,
FieldSpec("left_sensor_pose", "float64", (5, 4, 4)),
FieldSpec("right_sensor_pose", "float64", (5, 4, 4)),
FieldSpec("left_sensor_count", "int64"),
FieldSpec("right_sensor_count", "int64"),
),
"ManusFrame",
)


class RecordingAdapterError(ValueError):
Expand Down Expand Up @@ -294,19 +307,50 @@ def convert_hand_pose(tracking: dict[str, np.ndarray], side: Side) -> np.ndarray
return oxr_fingertips_to_manus_skeleton(matrices_26[1:], valid_26[1:], side)


def build_manus_glove_fields(tracking: dict[str, np.ndarray]) -> dict[str, np.ndarray] | None:
def convert_sensor_pose(tracking: dict[str, np.ndarray], side: Side) -> np.ndarray:
"""One hand's (5,4,4) raw fingertip-sensor transforms in the Manus SDK frame, thumb to little finger; all
zero, like an invalid hand joint, when the glove reported none this tick (``{side}_sensor_count`` is 0).

Recorded as transforms, not quaternions: the SDK flips a quaternion's sign between samples, which the
element-wise interpolation of time alignment cannot cross. A rotation matrix has no second form."""
prefix = f"manus_{side}"
pose = np.zeros((5, 4, 4), dtype=np.float64)
# Only a reported set is converted: placeholder quaternions are not data.
if bool(tracking[f"{prefix}.sensor_present"]):
quats = np.asarray(tracking[f"{prefix}.sensor_orientations"], dtype=np.float64)
pose[:, :3, :3] = Rotation.from_quat(quats).as_matrix()
pose[:, :3, 3] = tracking[f"{prefix}.sensor_positions"]
pose[:, 3, 3] = 1.0
return pose


def build_manus_glove_fields(
tracking: dict[str, np.ndarray], sensors: bool = False
) -> dict[str, np.ndarray] | None:
"""One ``manus_glove`` row, or ``None`` if either hand's wrist is
invalid this tick. Whole-row validity policy, matching
``pico_controller``'s combined gating above: a tick with one
untracked hand is omitted ENTIRELY for this source, counted as a real
gap, never backfilled with a stale or fabricated pose for the missing
hand (there is no per-hand stale-hold state anywhere in this
module)."""
left = convert_hand_pose(tracking, "left")
right = convert_hand_pose(tracking, "right")
if left is None or right is None:
module).

With *sensors*, the row also carries each glove's raw fingertip sensors, and a tick where a glove
reported them is kept even without both wrists: an untracked hand is then all zero, like an invalid joint."""
hands = {side: convert_hand_pose(tracking, side) for side in ("left", "right")}
complete = all(hand is not None for hand in hands.values())
if not sensors:
return {f"{side}_hand_pose": hand for side, hand in hands.items()} if complete else None
counts = {side: 5 * int(tracking[f"manus_{side}.sensor_present"]) for side in hands}
# The sensors are the glove's own data, so a missing skeleton does not drop them.
if not complete and not any(counts.values()):
return None
return {"left_hand_pose": left, "right_hand_pose": right}
fields: dict[str, np.ndarray] = {}
for side, hand in hands.items():
fields[f"{side}_hand_pose"] = hand if hand is not None else np.zeros((25, 4, 4), dtype=np.float64)
fields[f"{side}_sensor_pose"] = convert_sensor_pose(tracking, side)
fields[f"{side}_sensor_count"] = np.int64(counts[side])
return fields


# --- camera conversion --------------------------------------------------------
Expand All @@ -331,7 +375,9 @@ def convert_camera_image(
)


def convert_capture_frame(frame: CaptureFrame, latency: Mapping[str, float] | None = None) -> list[NumericSample]:
def convert_capture_frame(
frame: CaptureFrame, latency: Mapping[str, float] | None = None, manus_sensors: bool = False
) -> list[NumericSample]:
"""Decodes one raw tracking payload and converts it into zero, one or
two ``NumericSample``s (``pico_controller``/``manus_glove``), each
omitted entirely (not fabricated) when its own whole-row validity
Expand All @@ -354,7 +400,7 @@ def convert_capture_frame(frame: CaptureFrame, latency: Mapping[str, float] | No
PICO_CONTROLLER_SOURCE, capture_time, receive_time, pico_fields, continuity, frame.sequence
)
)
manus_fields = build_manus_glove_fields(tracking)
manus_fields = build_manus_glove_fields(tracking, manus_sensors)
if manus_fields is not None:
capture_time = poll_time - latency.get(MANUS_GLOVE_SOURCE, 0.0)
samples.append(
Expand All @@ -378,14 +424,14 @@ def _raw_item_bytes(raw_item: RawItem) -> int:


def convert_raw_item(
raw_item: RawItem, latency: Mapping[str, float] | None = None
raw_item: RawItem, latency: Mapping[str, float] | None = None, manus_sensors: bool = False
) -> list[NumericSample | VideoSample]:
"""The default, real conversion dispatch -- CPU-bound (JPEG decode,
pose math), so ``RecordingIngress`` always runs this inside its
bounded consumer (off the synchronous capture-callback path that
calls ``offer()``), via a worker executor, never before the queue."""
if isinstance(raw_item, CaptureFrame):
return list(convert_capture_frame(raw_item, latency))
return list(convert_capture_frame(raw_item, latency, manus_sensors))
if isinstance(raw_item, CameraImage):
return [convert_camera_image(raw_item, raw_item.name)]
if isinstance(raw_item, VideoSample):
Expand Down
5 changes: 4 additions & 1 deletion examples/egocap/backend/egocap_web/recording_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,11 @@ def __init__(
livekit_source: LiveKitRecordingSource | None = None,
tracking_latency: dict[str, float] | None = None,
capture_facts: Callable[[], dict[str, Any] | None] | None = None,
manus_sensors: bool = False,
) -> None:
self._config_factory = config_factory
# Whether the capture session requested the gloves' raw fingertip sensors, which its glove rows then carry.
self._manus_sensors = manus_sensors
# Reads the capture session's own facts when a take stops; injected because this coordinator must not
# import the capture client.
self._capture_facts = capture_facts
Expand Down Expand Up @@ -489,7 +492,7 @@ async def _start_episode_with_storage(self, frozen_context: TaskContext) -> Epis
queue_bytes=self._queue_bytes() if callable(self._queue_bytes) else self._queue_bytes,
submit=partial(service.submit_sample, episode_id),
on_failure=lambda message: self._schedule_failure_settlement(service, episode_id, message),
convert=partial(convert_raw_item, latency=self._tracking_latency),
convert=partial(convert_raw_item, latency=self._tracking_latency, manus_sensors=self._manus_sensors),
)
await ingress.start()
self._current_ingress = ingress
Expand Down
Loading
Loading