From 888929c778d27bee64ee424d8249081c9f54086c Mon Sep 17 00:00:00 2001 From: yunjul Date: Thu, 26 Nov 2026 19:29:00 +0800 Subject: [PATCH 1/2] egocap: record the Manus raw fingertip sensors The Manus plugin pushes each glove's five raw fingertip-sensor poses. CaptureServer now reads them whenever the plugin is enabled and sends them in the tracking payload as manus_left/manus_right fields, appended after the existing fields so every earlier offset is unchanged; the payload grows from 1995 to 2277 bytes. The backend records them in the manus_glove source as {left,right}_sensor_pose, a (5, 4, 4) transform stack on the same row and capture time as the hand skeleton. A hand whose sensors were not reported is written as all-zero transforms, like an invalid hand joint. Transforms rather than quaternions, so that time alignment can interpolate them element-wise. The mock and replay SDKs mirror the new tracker, and the frontend field table, its descriptor fixture and the READMEs follow the new layout. Signed-off-by: yunjul Co-Authored-By: Claude Fable 5.2 --- examples/egocap/AGENTS.md | 8 +++ examples/egocap/DESIGN.md | 6 +- examples/egocap/README.md | 2 +- .../backend/egocap_web/recording_adapter.py | 26 +++++++- examples/egocap/capture_server/README.md | 44 +++++++++----- .../acquisition/isaac_capture.py | 55 ++++++++++++++++- .../capture_server/acquisition/isaac_sdk.py | 7 ++- .../capture_server/mock/mock_isaac_capture.py | 18 +++++- .../capture_server/capture_server/protocol.py | 23 +++++++- .../replay/replay_isaac_capture.py | 4 ++ examples/egocap/frontend/src/App.test.tsx | 2 +- .../egocap/frontend/src/captureProtocol.ts | 5 ++ .../frontend/src/realDescriptor.test.ts | 17 ++++-- examples/egocap/recording/README.md | 1 + .../recording/egocap/recording/alignment.py | 4 +- .../tests/backend/test_recording_adapter.py | 4 ++ .../tests/backend/test_recording_session.py | 4 ++ .../test_acquisition_adapters.py | 59 +++++++++++++++++++ .../tests/capture_server/test_protocol.py | 12 ++-- .../tests/capture_server/test_server.py | 2 +- 20 files changed, 265 insertions(+), 38 deletions(-) diff --git a/examples/egocap/AGENTS.md b/examples/egocap/AGENTS.md index 59cae280d2..252ccdeeae 100644 --- a/examples/egocap/AGENTS.md +++ b/examples/egocap/AGENTS.md @@ -86,3 +86,11 @@ 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. diff --git a/examples/egocap/DESIGN.md b/examples/egocap/DESIGN.md index 26f7baac26..109ed8ddd7 100644 --- a/examples/egocap/DESIGN.md +++ b/examples/egocap/DESIGN.md @@ -103,7 +103,8 @@ 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. 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. @@ -118,7 +119,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, diff --git a/examples/egocap/README.md b/examples/egocap/README.md index afb0b76017..bfa05fac20 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -102,7 +102,7 @@ It is not in this tree (it is added by the camera_streamer mock-sender change, P mock sender the mock video goes through the same receiver, bridge and page, with the frame-ready time as its timestamp because the mock sender has no clock to measure. A recording made in this mode is synthetic data. -Without `--orin` or `--mock` only the PC side starts. `--skip-deploy` reuses the previous release. The sender runs +CaptureServer listens on loopback port 8082 by default; `--capture-server-port N` moves it, and the backend is pointed at the new port, when something else on the PC already holds 8082. Without `--orin` or `--mock` only the PC side starts. `--skip-deploy` reuses the previous release. The sender runs for `--seconds` (default one hour) and the launcher stops the whole stack when it ends, so a take in progress is cut off; the launcher prints the stop time at startup. The sender release the profile describes, its deploy tool, the timesync tool, the LiveKit server and the bridge are not in this tree's base, so pass their paths (or set diff --git a/examples/egocap/backend/egocap_web/recording_adapter.py b/examples/egocap/backend/egocap_web/recording_adapter.py index f06e20dca4..03fcdc3585 100644 --- a/examples/egocap/backend/egocap_web/recording_adapter.py +++ b/examples/egocap/backend/egocap_web/recording_adapter.py @@ -78,6 +78,8 @@ ( FieldSpec("left_hand_pose", "float64", (25, 4, 4)), FieldSpec("right_hand_pose", "float64", (25, 4, 4)), + FieldSpec("left_sensor_pose", "float64", (5, 4, 4)), + FieldSpec("right_sensor_pose", "float64", (5, 4, 4)), ), "ManusFrame", ) @@ -294,6 +296,23 @@ 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 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. + + 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]) -> 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 @@ -306,7 +325,12 @@ def build_manus_glove_fields(tracking: dict[str, np.ndarray]) -> dict[str, np.nd right = convert_hand_pose(tracking, "right") if left is None or right is None: return None - return {"left_hand_pose": left, "right_hand_pose": right} + return { + "left_hand_pose": left, + "right_hand_pose": right, + "left_sensor_pose": convert_sensor_pose(tracking, "left"), + "right_sensor_pose": convert_sensor_pose(tracking, "right"), + } # --- camera conversion -------------------------------------------------------- diff --git a/examples/egocap/capture_server/README.md b/examples/egocap/capture_server/README.md index 803a564639..163463ab2c 100644 --- a/examples/egocap/capture_server/README.md +++ b/examples/egocap/capture_server/README.md @@ -383,7 +383,7 @@ An immutable description of the tracking frame format. CaptureStarted.streams su | `stream_id` | `int`, 0. | Associates tracking frames with this descriptor. | | `kind` | `StreamKind`: `TRACKING=1`. | Descriptor kind. | | `name` | `str`, tracking. | Logical stream name. | -| `schema` | `TrackingSchema`: `IC_TRACKING_V1=1`. | Fixed head/controller/hand schema. | +| `schema` | `TrackingSchema`: `IC_TRACKING_V1=1`. | Fixed head/controller/hand/Manus raw-sensor schema. | | `sources` | `tuple[SourceType, ...]`: `HEAD=1`, `CONTROLLERS=2`, `HANDS=3`. | Outputs selected for this stream. | | `rate_hz` | Positive finite `float`, at most 120. | Requested polling cadence. | | `pose_representation` | `PoseRepresentation`: `POSITION_QUATERNION=1`. | Poses contain a translation vector and rotation quaternion. | @@ -392,7 +392,7 @@ An immutable description of the tracking frame format. CaptureStarted.streams su | `axes` | `Axes`: `RIGHT_HANDED_Y_UP_MINUS_Z_FORWARD=1`. | Right-handed coordinates, +Y up and −Z forward. | | `reference_space` | Nonempty `str`, such as session\_floor. | Identifies the shared session coordinate space for these poses. | | `hand_joint_order` | `HandJointOrder`: `OPENXR_26=1`. | Joint indexing of the hand arrays in the binary payload. | -| `payload_size` | `int`, 1995. | Exact tracking payload size, excluding the transport header. | +| `payload_size` | `int`, 2277. | Exact tracking payload size, excluding the transport header. | | `fields` | `tuple[FieldDescriptor, ...]` | Complete binary field descriptions, including presence and validity flags, with offsets measured within CaptureFrame.payload. | #### FieldDescriptor @@ -527,7 +527,7 @@ An immutable Python dataclass containing ordinary metadata fields and a binary p | `sequence` | Nonnegative `int`. | Per-stream sample counter starting at zero. Gaps identify samples not delivered to the application. | | `capture_time_ns` | Nonnegative `int`. | Station monotonic host sampling time, interpreted using CaptureClock. | | `receive_time_ns` | Nonnegative `int`. | Station-side time the server assembled this sample for transport, not the adapter's own sampling time (that is `capture_time_ns`) and not the time the remote client received the frame. | -| `payload` | Immutable `bytes`, exactly 1995 bytes for IC_TRACKING_V1. | Original packed tracking payload, without the 32-byte transport header. Retaining the frame after callback return is safe. | +| `payload` | Immutable `bytes`, exactly 2277 bytes for IC_TRACKING_V1. | Original packed tracking payload, without the 32-byte transport header. Retaining the frame after callback return is safe. | CaptureFrame.description is a shared reference, not a per-frame copy or another wire message. Access changing metadata directly, such as frame.sequence; there is no nested metadata/header object or separate FrameMetadata type. The callback identifies tracking versus image data, so no redundant kind field is needed in Python. The transport kind is still validated internally. @@ -655,7 +655,7 @@ JSON object keys, session IDs, provider/device IDs, device paths, stream names, The [Python enum reference](#python-enums) lists every enum member and numeric wire value. Each message-field table also names its enum and accepted values. -BinaryKind is the compact binary-header discriminator; MessageType discriminates JSON messages. They are separate enum types. Version remains integer 1. The 32-byte framing and 1995-byte tracking payload below remain fixed; controller scalars remain float64. +BinaryKind is the compact binary-header discriminator; MessageType discriminates JSON messages. They are separate enum types. Version remains integer 1. The 32-byte framing and 2277-byte tracking payload below remain fixed; controller scalars remain float64. #### How IC selects and observes devices @@ -766,7 +766,7 @@ later session's first device can be different. `plugins` defaults to an empty array. Each entry selects a defined PluginType and supported output settings. A plugin kind occurs at most once. The server assigns IC's internal instance namespace and returns observed provider IDs as opaque identifiers; clients do not choose or construct those IDs. `enabled` and `required` retain the native PluginConfig semantics. The station owns plugin installation, execution and calibration defaults. The plugin list is independent of the tracking source list: enabling an injector does not subscribe its data automatically. -A plugin is a supporting program started by IC, rather than a physical device. Manus's plugin receives glove data and injects hand skeletons into OpenXR, where HandsSource can read them. An instance is one configured launch of that program; its ID gives its status records a namespace so records from different providers do not collide. +A plugin is a supporting program started by IC, rather than a physical device. Manus's plugin receives glove data and injects hand skeletons into OpenXR, where HandsSource can read them. It also pushes each glove's raw fingertip-sensor poses, which the server reads whenever the plugin is enabled and sends in the `manus_left`/`manus_right` tracking fields. An instance is one configured launch of that program; its ID gives its status records a namespace so records from different providers do not collide. | Plugin request field | Allowed contents/default | Meaning and effect | |---|---|---| @@ -867,7 +867,7 @@ This is a complete SessionInit for head, controllers and hands: "reference_space": "session_floor", "hand_joint_order": 1, "layout": { - "payload_size": 1995, + "payload_size": 2277, "fields": [ {"name":"head.present","dtype":1,"shape":[],"offset":0}, {"name":"head.position","dtype":2,"shape":[3],"offset":1}, @@ -913,7 +913,13 @@ This is a complete SessionInit for head, controllers and hands: {"name":"hand_right.joint_positions","dtype":2,"shape":[26,3],"offset":1137}, {"name":"hand_right.joint_orientations","dtype":2,"shape":[26,4],"offset":1449}, {"name":"hand_right.joint_radii","dtype":2,"shape":[26],"offset":1865}, - {"name":"hand_right.joint_valid","dtype":1,"shape":[26],"offset":1969} + {"name":"hand_right.joint_valid","dtype":1,"shape":[26],"offset":1969}, + {"name":"manus_left.sensor_present","dtype":1,"shape":[],"offset":1995}, + {"name":"manus_left.sensor_positions","dtype":2,"shape":[5,3],"offset":1996}, + {"name":"manus_left.sensor_orientations","dtype":2,"shape":[5,4],"offset":2056}, + {"name":"manus_right.sensor_present","dtype":1,"shape":[],"offset":2136}, + {"name":"manus_right.sensor_positions","dtype":2,"shape":[5,3],"offset":2137}, + {"name":"manus_right.sensor_orientations","dtype":2,"shape":[5,4],"offset":2197} ] } } @@ -1084,7 +1090,7 @@ Dotted field names preserve the public IC group/field identity. Dtype codes are | `stream_id` | Not an enum: integer 0 for tracking. | Associates a binary message's header with this descriptor. | | `kind` | `StreamKind`: `TRACKING=1` for this descriptor; `IMAGE=2` for camera descriptors; `LIVEKIT_IMAGE=3` for LiveKit camera descriptors. | Selects the kind of decoder to use for the stream. | | `name` | String, `tracking` for this stream; no enum. | Provides a readable stream label. Routing uses stream\_id, not this label. | -| `schema` | `TrackingSchema`: `IC_TRACKING_V1=1`. | Identifies the complete field contract, including presence/validity meanings and the 1995-byte layout. A client rejects an unsupported schema rather than interpreting a similar-looking blob. | +| `schema` | `TrackingSchema`: `IC_TRACKING_V1=1`. | Identifies the complete field contract, including presence/validity meanings and the 2277-byte layout. A client rejects an unsupported schema rather than interpreting a similar-looking blob. | | `sources` | `SourceType`: unique array drawn from `HEAD=1`, `CONTROLLERS=2`, `HANDS=3`. | Records the source channels selected for this tracking stream. Unselected channels retain inert slots in the fixed binary layout. | | `rate_hz` | Not an enum: finite number greater than 0 and at most 120. | Advertises the accepted polling rate. It does not certify that every device generated a new sample at that rate. | | `pose_representation` | `PoseRepresentation`: `POSITION_QUATERNION=1`. | Each pose uses a 3-number position and a 4-number orientation, rather than a 4×4 matrix or three rotation angles. | @@ -1093,14 +1099,14 @@ Dotted field names preserve the public IC group/field identity. Dtype codes are | `axes` | `Axes`: `RIGHT_HANDED_Y_UP_MINUS_Z_FORWARD=1`. | Defines coordinate directions: positive Y is up and negative Z is forward, using a right-handed coordinate system. This tells the client how to interpret motion and avoid swapping or reflecting axes accidentally. | | `reference_space` | Nonempty string identifying the session coordinate frame; no enum. | Identifies the common origin/frame in which the positions and orientations are expressed. For example, session\_floor denotes a floor-based session space. It does not locate the origin in a surveyed building coordinate system or guarantee the same origin after reconnect. | | `hand_joint_order` | `HandJointOrder`: `OPENXR_26=1`. | Defines which anatomical joint each array index means. Both hands use the same 26-index order described below. | -| `layout.payload_size` | Not an enum: integer 1995 for this schema. | Gives the exact binary sample size excluding the 32-byte header. The decoder rejects a different size. | +| `layout.payload_size` | Not an enum: integer 2277 for this schema. | Gives the exact binary sample size excluding the 32-byte header. The decoder rejects a different size. | | `layout.fields` | Array of field records. | Gives the byte-level recipe for extracting every named value from the blob. Field records contain the next four fields. | | Field `name` | String identifying a declared schema field, such as head.position; no enum. | Names the extracted value using IC's output group and field identity. This is not an extra string stored inside each binary sample. | | Field `dtype` | `WireDType`: `UINT8=1`, `FLOAT32_LE=2`, `FLOAT64_LE=3`. | Selects an unsigned 1-byte integer, a 4-byte floating-point value, or an 8-byte floating-point value. LE means least-significant byte first. Presence/validity use UINT8; positions/quaternions/radii use FLOAT32\_LE; controller input scalars use FLOAT64\_LE. | | Field `shape` | Not an enum: array of positive integer dimensions, or `[]` for one scalar. | `[]` means one value, `[3]` means three values, and `[26,3]` means 26 rows of 3 values. C order means each row's values are adjacent before the next row begins. | -| Field `offset` | Not an enum: nonnegative integer byte offset within the 1995-byte payload. | Gives where the field starts, counted from the first sample byte after the header. It is not counted from the start of the whole WebSocket message. | +| Field `offset` | Not an enum: nonnegative integer byte offset within the 2277-byte payload. | Gives where the field starts, counted from the first sample byte after the header. It is not counted from the start of the whole WebSocket message. | -For example, head.position has dtype FLOAT32\_LE=2, shape \[3\] and offset 1. The client skips the 32-byte header, skips one payload byte, then reads three little-endian float32 values from payload bytes 1–12. The next field, head.orientation, starts at payload offset 13. In general, a field occupies the product of its dimensions times its dtype size; a scalar occupies one dtype-sized value. The descriptor must have no overlaps, out-of-bounds fields or missing required schema fields. Clients validate it once before accepting frames; they do not infer correctness merely because its declared total size is 1995. +For example, head.position has dtype FLOAT32\_LE=2, shape \[3\] and offset 1. The client skips the 32-byte header, skips one payload byte, then reads three little-endian float32 values from payload bytes 1–12. The next field, head.orientation, starts at payload offset 13. In general, a field occupies the product of its dimensions times its dtype size; a scalar occupies one dtype-sized value. The descriptor must have no overlaps, out-of-bounds fields or missing required schema fields. Clients validate it once before accepting frames; they do not infer correctness merely because its declared total size is 2277. Head, each controller and each hand has independent presence. For a selected source, absent OptionalTensorGroup maps to present=0; an existing group maps to present=1 and retains its native flags. For absent/unselected groups, zero numeric values and validity flags and use identity xyzw quaternions as inert placeholders. Presence, not placeholder content, determines absence. @@ -1129,12 +1135,16 @@ The following table explains the values packed into the binary fields. These are | Hand `joint_orientations` | Float32 array \[26,4\], xyzw quaternions. | Session-space orientation of each joint, in the same index order as positions. | | Hand `joint_radii` | Float32 array \[26\], meters. | Runtime-estimated radius associated with each joint, useful for visualizing or modeling its spatial extent. It is not a confidence score. | | Hand `joint_valid` | UINT8 array \[26\], each value 0 or 1. | Whether each joint has a valid position and orientation according to IC. Some joints can be invalid while the hand group remains present. This is not a separate per-joint actively-tracked flag. | +| `manus_left.sensor_present`, `manus_right.sensor_present` | Independent scalar 0 or 1 per side. | Whether the Manus plugin has pushed a complete five-fingertip raw-sensor set for that glove. It stays 1, on the last set, after a glove stops reporting while the plugin keeps running. | +| Manus `sensor_positions` | Float32 array \[5,3\], meters. | Raw fingertip-sensor positions, thumb to little finger, in the Manus SDK frame the plugin configures. These are not session-space positions. | +| Manus `sensor_orientations` | Float32 array \[5,4\], xyzw quaternions. | Raw fingertip-sensor orientations, in the same order and frame as the positions. | + Preserve session-space positions/quaternions. Do not select grip over aim, rename buttons, remove the palm, make hands wrist-relative, generate recorder matrices, or apply an application-specific alignment. The client performs any desired downstream conversion. Hand presence/validity does not provide provider identity, and joint validity is not a separate active-tracking flag. ##### Tracking field offsets -Each row is one field inside the 1995-byte tracking payload. Offset 0 starts immediately after the 32-byte binary header. Dtype is Python `WireDType`: `UINT8=1` (1 byte), `FLOAT32_LE=2` (4 bytes), or `FLOAT64_LE=3` (8 bytes). Empty shape `[]` means one scalar; all arrays use C order. +Each row is one field inside the 2277-byte tracking payload. Offset 0 starts immediately after the 32-byte binary header. Dtype is Python `WireDType`: `UINT8=1` (1 byte), `FLOAT32_LE=2` (4 bytes), or `FLOAT64_LE=3` (8 bytes). Empty shape `[]` means one scalar; all arrays use C order. | Field name | Python enum member / wire dtype | Shape | Byte offset | Bytes | |---|---|---|---|---| @@ -1183,6 +1193,12 @@ Each row is one field inside the 1995-byte tracking payload. Offset 0 starts imm | `hand_right.joint_orientations` | `WireDType.FLOAT32_LE=2` | `[26,4]` | 1449 | 416 | | `hand_right.joint_radii` | `WireDType.FLOAT32_LE=2` | `[26]` | 1865 | 104 | | `hand_right.joint_valid` | `WireDType.UINT8=1` | `[26]` | 1969 | 26 | +| `manus_left.sensor_present` | `WireDType.UINT8=1` | `[]` | 1995 | 1 | +| `manus_left.sensor_positions` | `WireDType.FLOAT32_LE=2` | `[5,3]` | 1996 | 60 | +| `manus_left.sensor_orientations` | `WireDType.FLOAT32_LE=2` | `[5,4]` | 2056 | 80 | +| `manus_right.sensor_present` | `WireDType.UINT8=1` | `[]` | 2136 | 1 | +| `manus_right.sensor_positions` | `WireDType.FLOAT32_LE=2` | `[5,3]` | 2137 | 60 | +| `manus_right.sensor_orientations` | `WireDType.FLOAT32_LE=2` | `[5,4]` | 2197 | 80 | #### Camera descriptor and binary transport @@ -1265,13 +1281,13 @@ Both binary families use `struct.Struct("<4sBBHQQQ")`: | 8 | uint64 LE | Per-stream generated sequence, starting at 0. | | 16 | uint64 LE | Sample/capture-host monotonic timestamp, ns. | | 24 | uint64 LE | Capture-host receive/assembly timestamp, ns. | -| 32 | bytes | Exactly 1995 tracking bytes or one complete JPEG. | +| 32 | bytes | Exactly 2277 tracking bytes or one complete JPEG. | Tracking messages are 2027 bytes. The session ID is supplied by the active SessionBegun association; do not repeat it per sample. No binary data precedes SessionBegun or follows its matching SessionStopped. A rejection for another ID does not disturb the active stream. ##### CaptureFrame -CaptureFrame uses BinaryKind.CAPTURE\_FRAME=1, stream\_id=0, and exactly 1995 payload bytes after the 32-byte header. The payload contains all fields in the tracking-offset table. Source presence and validity determine which values are usable; absent groups do not shorten the message. Every frame is a complete snapshot rather than a delta against a previous frame. +CaptureFrame uses BinaryKind.CAPTURE\_FRAME=1, stream\_id=0, and exactly 2277 payload bytes after the 32-byte header. The payload contains all fields in the tracking-offset table. Source presence and validity determine which values are usable; absent groups do not shorten the message. Every frame is a complete snapshot rather than a delta against a previous frame. ##### CaptureImage diff --git a/examples/egocap/capture_server/capture_server/acquisition/isaac_capture.py b/examples/egocap/capture_server/capture_server/acquisition/isaac_capture.py index bbc379528e..6630a3d8d3 100644 --- a/examples/egocap/capture_server/capture_server/acquisition/isaac_capture.py +++ b/examples/egocap/capture_server/capture_server/acquisition/isaac_capture.py @@ -47,6 +47,12 @@ #: silently, when the plugin is optional. The mock mirrors this constant and a test keeps the two equal. MANUS_PLUGIN_NAME = "manus_hand_plugin" +#: The tensor collection the Manus plugin pushes each glove's raw fingertip sensors on, by the prefix of the +#: wire fields it fills (src/plugins/manus/core/inc/manus/manus_glove_collection.hpp). +_MANUS_SENSOR_COLLECTIONS = {"manus_left": "manus_sensors_left", "manus_right": "manus_sensors_right"} +#: The plugin's raw-sensor order, thumb to little finger, as the ``JointName.HAND_RAW_*_TIP`` suffixes. +_SENSOR_TIPS = ("THUMB", "INDEX", "MIDDLE", "RING", "LITTLE") + def _zero_controller_fields(prefix: str) -> dict[str, Any]: import numpy as np @@ -132,6 +138,32 @@ def _hand_fields(prefix: str, group: Any, index: type) -> dict[str, Any]: } +def _zero_sensor_fields(prefix: str) -> dict[str, Any]: + """The placeholder values for a glove whose raw sensors are not reported.""" + import numpy as np + + return { + f"{prefix}.sensor_present": np.uint8(0), + f"{prefix}.sensor_positions": np.zeros((5, 3), dtype=np.float32), + f"{prefix}.sensor_orientations": np.tile(np.array([0, 0, 0, 1], dtype=np.float32), (5, 1)), + } + + +def _sensor_fields(prefix: str, data: Any, joint_name: type) -> dict[str, Any]: + """*data* is the Manus plugin's ``JointSe3PoseOutput``, which always carries all five + fingertip sensors, keyed by the SDK's ``JointName``.""" + import numpy as np + + poses = [data.lookup(getattr(joint_name, f"HAND_RAW_{tip}_TIP")).pose for tip in _SENSOR_TIPS] + return { + f"{prefix}.sensor_present": np.uint8(1), + f"{prefix}.sensor_positions": [(pose.position.x, pose.position.y, pose.position.z) for pose in poses], + f"{prefix}.sensor_orientations": [ + (pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w) for pose in poses + ], + } + + @dataclass(frozen=True) class TrackingSelection: """Which ic_tracking_v1 groups this session requested -- independent @@ -192,6 +224,8 @@ def __init__( self._clock = clock or MonotonicClock() self._runner = ThreadRunner() self._session: Any = None + # One tracker per Manus raw-sensor collection, by wire prefix; empty unless the plugin is requested. + self._sensor_trackers: dict[str, Any] = {} self._launcher: Any = None # Tracks whether each object's own __enter__() actually returned, # separately from whether the field itself is set -- close() must @@ -241,7 +275,18 @@ def _build_config(self) -> Any: if self._selection.manus_enabled else [] ) - return self._sdk.TeleopSessionConfig(app_name="capture_server", pipeline=pipeline, plugins=plugins) + if self._selection.manus_enabled: + # Registered with the session like any tracker, so step() refreshes them with the sources. + self._sensor_trackers = { + prefix: self._sdk.JointSe3PoseTracker(collection) + for prefix, collection in _MANUS_SENSOR_COLLECTIONS.items() + } + return self._sdk.TeleopSessionConfig( + app_name="capture_server", + pipeline=pipeline, + plugins=plugins, + trackers=list(self._sensor_trackers.values()), + ) def _manus_args(self) -> list[str]: """The Manus plugin's calibration arguments for the files this session selected.""" @@ -394,6 +439,14 @@ def _map_tracking(self, native: dict[str, Any]) -> dict[str, Any]: fields.update(_hand_fields(prefix, group, HandInputIndex)) else: fields.update(_zero_hand_fields(prefix)) + for prefix in _MANUS_SENSOR_COLLECTIONS: + tracker = self._sensor_trackers.get(prefix) + # No tracker without the plugin, and no data until the plugin pushes its first frame. + data = tracker.get_data(self._session.deviceio_session) if tracker is not None else None + if data is not None: + fields.update(_sensor_fields(prefix, data, self._sdk.JointName)) + else: + fields.update(_zero_sensor_fields(prefix)) return fields async def status(self, updated_at_ns: int) -> p.StatusSnapshot: diff --git a/examples/egocap/capture_server/capture_server/acquisition/isaac_sdk.py b/examples/egocap/capture_server/capture_server/acquisition/isaac_sdk.py index 82c8d1cdea..6401040e6f 100644 --- a/examples/egocap/capture_server/capture_server/acquisition/isaac_sdk.py +++ b/examples/egocap/capture_server/capture_server/acquisition/isaac_sdk.py @@ -40,7 +40,8 @@ def load_isaac_capture() -> SimpleNamespace: Cached after the first success. The returned namespace has the adapter's ``sdk`` surface (``HeadSource``, ``ControllersSource``, ``HandsSource``, ``OutputCombiner``, ``PluginConfig``, - ``TeleopSessionConfig``, ``CloudXRLauncher``) plus ``TeleopSession``, ``version`` and ``package_dir``. + ``TeleopSessionConfig``, ``CloudXRLauncher``) plus ``TeleopSession``, ``JointSe3PoseTracker``, ``JointName``, + ``version`` and ``package_dir``. """ global _loaded if _loaded is not None: @@ -78,6 +79,8 @@ def load_isaac_capture() -> SimpleNamespace: indices = importlib.import_module("isaaccapture.retargeting_engine.tensor_types.indices") launcher = importlib.import_module("isaaccapture.cloudxr.launcher") runtime = importlib.import_module("isaaccapture.cloudxr.runtime") + trackers = importlib.import_module("isaaccapture.deviceio_trackers") + schema = importlib.import_module("isaaccapture.schema") except ImportError as exc: # missing/unloadable native library or module raise IsaacCaptureUnavailable(f"cannot import isaaccapture from {package_dir}: {exc}") from exc @@ -139,6 +142,8 @@ def launch_context(args): TeleopSessionConfig=session_config, CloudXRLauncher=AttachOnlyCloudXR, TeleopSession=teleop.TeleopSession, + JointSe3PoseTracker=trackers.JointSe3PoseTracker, + JointName=schema.JointName, version=package.__version__, package_dir=package_dir, ) diff --git a/examples/egocap/capture_server/capture_server/mock/mock_isaac_capture.py b/examples/egocap/capture_server/capture_server/mock/mock_isaac_capture.py index 8029b29dd4..d30f820d33 100644 --- a/examples/egocap/capture_server/capture_server/mock/mock_isaac_capture.py +++ b/examples/egocap/capture_server/capture_server/mock/mock_isaac_capture.py @@ -88,6 +88,7 @@ "HandsSource", "HeadInputIndex", "HeadSource", + "JointSe3PoseTracker", "KNOWN_FAULTS", "NoopContext", "OptionalTensorGroup", @@ -366,13 +367,26 @@ class PluginConfig: @dataclass(frozen=True) class TeleopSessionConfig: """Reproduces the real ``TeleopSessionConfig``'s public construction - shape (``app_name``/``pipeline``/``plugins``) -- not a graph engine: + shape (``app_name``/``pipeline``/``plugins``/``trackers``) -- not a graph engine: this mock only inspects ``pipeline.outputs`` to know which leaf keys and source-node types to synthesize samples for.""" app_name: str pipeline: OutputCombiner plugins: list[PluginConfig] = field(default_factory=list) + trackers: list[Any] = field(default_factory=list) + + +class JointSe3PoseTracker: + """Reproduces the real tracker's construction and read shape for a tensor collection this mock never + fills: ``get_data`` is always None, as the real one is until a plugin pushes a frame.""" + + def __init__(self, collection_id: str) -> None: + self.collection_id = collection_id + + def get_data(self, session: Any) -> None: + """No sample: nothing pushes to this collection.""" + return None # --------------------------------------------------------------------------- CloudXRLauncher @@ -689,6 +703,8 @@ def __init__( ) -> None: self.config = config self.frame_count = 0 + # The real session's DeviceIO handle, which trackers are read against; there is none to open here. + self.deviceio_session = None # Synthetic device-to-host delay: a source's content is what the operator was doing this long before the # poll, plus seeded bounded jitter, so a configured latency can be checked against a known truth. self._delays = {"controller": controller_delay_s, "glove": glove_delay_s} diff --git a/examples/egocap/capture_server/capture_server/protocol.py b/examples/egocap/capture_server/capture_server/protocol.py index 9f48c6d2ab..88e1010229 100644 --- a/examples/egocap/capture_server/capture_server/protocol.py +++ b/examples/egocap/capture_server/capture_server/protocol.py @@ -408,6 +408,17 @@ def _hand_fields(prefix: str, start_offset: int) -> list[Field]: return fields +def _sensor_fields(prefix: str, start_offset: int) -> list[Field]: + """One glove's raw fingertip sensors, thumb to little finger.""" + offset = start_offset + fields = [Field(f"{prefix}.sensor_present", "u1", (), offset)] + offset += fields[-1].nbytes + fields.append(Field(f"{prefix}.sensor_positions", "f4", (5, 3), offset)) + offset += fields[-1].nbytes + fields.append(Field(f"{prefix}.sensor_orientations", "f4", (5, 4), offset)) + return fields + + def _controller_fields(prefix: str, start_offset: int) -> list[Field]: offset = start_offset names_dtypes_shapes = [ @@ -465,15 +476,23 @@ def _build_ic_tracking_v1_fields() -> tuple[Field, ...]: right_hand = _hand_fields("hand_right", offset) fields.extend(right_hand) + offset = right_hand[-1].offset + right_hand[-1].nbytes + + left_sensors = _sensor_fields("manus_left", offset) + fields.extend(left_sensors) + offset = left_sensors[-1].offset + left_sensors[-1].nbytes + + right_sensors = _sensor_fields("manus_right", offset) + fields.extend(right_sensors) return tuple(fields) IC_TRACKING_V1_FIELDS: tuple[Field, ...] = _build_ic_tracking_v1_fields() IC_TRACKING_V1_PAYLOAD_SIZE = IC_TRACKING_V1_FIELDS[-1].offset + IC_TRACKING_V1_FIELDS[-1].nbytes -assert IC_TRACKING_V1_PAYLOAD_SIZE == 1995, ( +assert IC_TRACKING_V1_PAYLOAD_SIZE == 2277, ( f"ic_tracking_v1 payload size drifted: {IC_TRACKING_V1_PAYLOAD_SIZE}, " - "expected the fixed 1995-byte tracking payload" + "expected the fixed 2277-byte tracking payload" ) # 26-joint OpenXR hand order: palm, wrist, four thumb joints, then five each diff --git a/examples/egocap/capture_server/capture_server/replay/replay_isaac_capture.py b/examples/egocap/capture_server/capture_server/replay/replay_isaac_capture.py index 9b67e8e2ff..82be19fcf8 100644 --- a/examples/egocap/capture_server/capture_server/replay/replay_isaac_capture.py +++ b/examples/egocap/capture_server/capture_server/replay/replay_isaac_capture.py @@ -35,6 +35,7 @@ DeviceStatus, HandsSource, HeadSource, + JointSe3PoseTracker, NoopContext, OptionalTensorGroup, OutputCombiner, @@ -56,6 +57,7 @@ "ControllersSource", "HandsSource", "HeadSource", + "JointSe3PoseTracker", "NoopContext", "OutputCombiner", "PluginConfig", @@ -88,6 +90,8 @@ def __init__( ) -> None: self.config = config self.frame_count = 0 + # The real session's DeviceIO handle, which trackers are read against; a recording has none. + self.deviceio_session = None self._episode = episode self._playback = playback self._clock = clock or MonotonicClock() diff --git a/examples/egocap/frontend/src/App.test.tsx b/examples/egocap/frontend/src/App.test.tsx index 56fe1e87e1..fb83021a23 100644 --- a/examples/egocap/frontend/src/App.test.tsx +++ b/examples/egocap/frontend/src/App.test.tsx @@ -89,7 +89,7 @@ function makeTrackingSample(decoded: DecodedTracking, overrides: Partial { } describe("the real, complete ic_tracking_v1 descriptor CaptureServer publishes", () => { - it("parses successfully -- 45 fields, 1995-byte payload, all head/controller/hand fields present", () => { + it("parses successfully -- 51 fields, 2277-byte payload, all head/controller/hand/sensor fields present", () => { const parsed = parseSnapshot(snapshotBodyWithRealDescriptor()); const stream = parsed.started?.streams[0]; expect(stream?.kind).toBe("tracking"); const tracking = stream as TrackingStreamDescriptor; - expect(tracking.payload_size).toBe(1995); - expect(tracking.fields).toHaveLength(45); + expect(tracking.payload_size).toBe(2277); + expect(tracking.fields).toHaveLength(51); expect(tracking.fields.map((f) => f.name)).toContain("hand_left.joint_valid"); expect(tracking.fields.map((f) => f.name)).toContain("hand_right.joint_valid"); + expect(tracking.fields.map((f) => f.name)).toContain("manus_right.sensor_orientations"); // parseSnapshot succeeding above already proves the real layout passes // the one authoritative extent/overlap boundary check. }); - it("decodes a real 1995-byte frame built against the actual complete layout", () => { + it("decodes a real 2277-byte frame built against the actual complete layout", () => { const parsed = parseSnapshot(snapshotBodyWithRealDescriptor()); const tracking = parsed.started?.streams[0] as TrackingStreamDescriptor; diff --git a/examples/egocap/recording/README.md b/examples/egocap/recording/README.md index 59a9f1c677..01b62cf623 100644 --- a/examples/egocap/recording/README.md +++ b/examples/egocap/recording/README.md @@ -169,6 +169,7 @@ Recorded numeric sources, exactly as written by `backend/egocap_web/recording_ad | `pico_controller` | `left_trigger`, `right_trigger` | scalar | `float64` | Analog trigger values. | | `pico_controller` | `a_button`, `b_button`, `x_button`, `y_button` | scalar | `bool` | Controller buttons. | | `manus_glove` | `left_hand_pose`, `right_hand_pose` | `(25, 4, 4)` | `float64` | Root-relative transform stacks, one per hand joint. | +| `manus_glove` | `left_sensor_pose`, `right_sensor_pose` | `(5, 4, 4)` | `float64` | Raw fingertip-sensor transforms in the Manus SDK frame, thumb to little finger; all zero when none were reported. | Both groups carry `capture_time`/`receive_time` as seconds (converted from CaptureServer's nanosecond timestamps). Camera groups each have a matching `.mp4`, plus capture time, receive diff --git a/examples/egocap/recording/egocap/recording/alignment.py b/examples/egocap/recording/egocap/recording/alignment.py index 0c8569ece2..34d725f3b4 100644 --- a/examples/egocap/recording/egocap/recording/alignment.py +++ b/examples/egocap/recording/egocap/recording/alignment.py @@ -219,7 +219,7 @@ class AlignedEpisode: #: How each field of a frame type is resampled when an episode is time aligned. A session's config.yaml names the -#: frame type of each source. Head and controller poses are rigid transforms (slerp); the glove's joint transforms +#: frame type of each source. Head and controller poses are rigid transforms (slerp); the glove's transform stacks #: are interpolated element-wise, so their shape never selects slerp; triggers and sensor values are continuous; #: a count is the nearest sample's; buttons and flags are not resampled, so they are absent here (raw). FRAME_FIELD_RULES: dict[str, dict[str, FieldRule]] = { @@ -233,7 +233,7 @@ class AlignedEpisode: "right_trigger": "linear", }, "ManusFrame": { - **{f"{side}_hand_pose": "linear" for side in ("left", "right")}, + **{f"{side}_{part}_pose": "linear" for side in ("left", "right") for part in ("hand", "sensor")}, **{ f"{side}_sensor_{kind}": "linear" for side in ("left", "right") diff --git a/examples/egocap/tests/backend/test_recording_adapter.py b/examples/egocap/tests/backend/test_recording_adapter.py index 9d5c385fea..a57e7a5db1 100644 --- a/examples/egocap/tests/backend/test_recording_adapter.py +++ b/examples/egocap/tests/backend/test_recording_adapter.py @@ -99,6 +99,10 @@ def default_tracking_values() -> dict[str, object]: values.update(_controller_defaults("controller_right")) values.update(_hand_defaults("hand_left")) values.update(_hand_defaults("hand_right")) + for prefix in ("manus_left", "manus_right"): + values[f"{prefix}.sensor_present"] = 1 + values[f"{prefix}.sensor_positions"] = (np.arange(15, dtype=np.float32).reshape(5, 3) + 1.0) * 0.01 + values[f"{prefix}.sensor_orientations"] = np.tile(np.array(IDENTITY_QUAT, dtype=np.float32), (5, 1)) return values diff --git a/examples/egocap/tests/backend/test_recording_session.py b/examples/egocap/tests/backend/test_recording_session.py index 57a9adbeb1..a8a44a7af0 100644 --- a/examples/egocap/tests/backend/test_recording_session.py +++ b/examples/egocap/tests/backend/test_recording_session.py @@ -141,6 +141,10 @@ def _fake_tracking_frame(*, head_x: float = 0.0, capture_time_ns: int = 1_000_00 values.update(_controller_values("controller_right")) values.update(_hand_values("hand_left")) values.update(_hand_values("hand_right")) + for prefix in ("manus_left", "manus_right"): + values[f"{prefix}.sensor_present"] = 1 + values[f"{prefix}.sensor_positions"] = np.zeros((5, 3), dtype=np.float32) + values[f"{prefix}.sensor_orientations"] = np.tile(np.array(IDENTITY_QUAT, dtype=np.float32), (5, 1)) payload = capture_protocol.encode_tracking_frame(values) return CaptureFrame( session_id="s1", diff --git a/examples/egocap/tests/capture_server/test_acquisition_adapters.py b/examples/egocap/tests/capture_server/test_acquisition_adapters.py index aaad25f998..e12cd26e6e 100644 --- a/examples/egocap/tests/capture_server/test_acquisition_adapters.py +++ b/examples/egocap/tests/capture_server/test_acquisition_adapters.py @@ -11,8 +11,10 @@ from __future__ import annotations from functools import partial +from types import SimpleNamespace from unittest.mock import patch +import numpy as np import pytest from capture_server import protocol as p @@ -80,3 +82,60 @@ async def test_depthai_skips_pipeline_exit_when_pipeline_enter_raised(): await adapter.close() pipeline_exit.assert_not_called() + + +def _raw_tip(index: int) -> SimpleNamespace: + return SimpleNamespace( + pose=SimpleNamespace( + position=SimpleNamespace(x=index, y=index + 0.25, z=index + 0.5), + orientation=SimpleNamespace(x=0.0, y=0.5, z=0.0, w=1.0), + ) + ) + + +async def test_isaac_capture_reads_the_manus_raw_sensors_of_each_glove(): + frames = { + "manus_sensors_left": SimpleNamespace(lookup={i: _raw_tip(i) for i in range(5)}.get), + "manus_sensors_right": None, + } + + class FakeTracker: + def __init__(self, collection_id: str) -> None: + self.collection_id = collection_id + + def get_data(self, _session: object) -> SimpleNamespace | None: + return frames[self.collection_id] + + sdk = SimpleNamespace(**{name: getattr(mock_isaac_capture, name) for name in mock_isaac_capture.__all__}) + sdk.JointSe3PoseTracker = FakeTracker + sdk.JointName = SimpleNamespace( + HAND_RAW_THUMB_TIP=0, + HAND_RAW_INDEX_TIP=1, + HAND_RAW_MIDDLE_TIP=2, + HAND_RAW_RING_TIP=3, + HAND_RAW_LITTLE_TIP=4, + ) + selection = TrackingSelection( + head=True, + controller_left=False, + controller_right=False, + hand_left=False, + hand_right=False, + manus_enabled=True, + ) + adapter = IsaacCaptureAdapter( + sdk=sdk, + session_factory=partial(mock_isaac_capture.TeleopSession, scenario="demo", seed=1), + selection=selection, + rate_hz=120, + ) + await adapter.enter() + try: + _, fields = await adapter.next_tracking_sample() + finally: + await adapter.close() + + assert fields["manus_left.sensor_present"] == 1 + np.testing.assert_allclose(fields["manus_left.sensor_positions"][4], [4.0, 4.25, 4.5]) + np.testing.assert_allclose(fields["manus_left.sensor_orientations"][4], [0.0, 0.5, 0.0, 1.0]) + assert fields["manus_right.sensor_present"] == 0 diff --git a/examples/egocap/tests/capture_server/test_protocol.py b/examples/egocap/tests/capture_server/test_protocol.py index 135e06c60b..95b9f164dd 100644 --- a/examples/egocap/tests/capture_server/test_protocol.py +++ b/examples/egocap/tests/capture_server/test_protocol.py @@ -87,8 +87,8 @@ def _zero_tracking_values() -> dict: return values -def test_ic_tracking_v1_payload_size_is_1995(): - assert p.IC_TRACKING_V1_PAYLOAD_SIZE == 1995 +def test_ic_tracking_v1_payload_size_is_2277(): + assert p.IC_TRACKING_V1_PAYLOAD_SIZE == 2277 def test_ic_tracking_v1_fields_have_no_gaps_or_overlaps(): @@ -108,7 +108,7 @@ def test_encode_tracking_frame_round_trips_exact_bytes(): values["controller_left.trigger_value"] = np.float64(0.75) payload = p.encode_tracking_frame(values) - assert len(payload) == 1995 + assert len(payload) == 2277 decoded = p.decode_tracking_frame(payload) np.testing.assert_array_equal(decoded["head.position"], values["head.position"]) @@ -129,7 +129,7 @@ def test_encode_tracking_frame_rejects_missing_field(): def test_decode_tracking_frame_rejects_wrong_size(): - with pytest.raises(p.TrackingPayloadError, match="expected 1995"): + with pytest.raises(p.TrackingPayloadError, match="expected 2277"): p.decode_tracking_frame(b"\x00" * 10) @@ -137,7 +137,7 @@ def test_tracking_payload_error_is_a_protocol_error(): """Same rationale as HeaderError -- a malformed tracking payload IS a protocol violation, not just a bare ValueError.""" assert issubclass(p.TrackingPayloadError, p.ProtocolError) - with pytest.raises(p.ProtocolError, match="expected 1995"): + with pytest.raises(p.ProtocolError, match="expected 2277"): p.decode_tracking_frame(b"\x00" * 10) @@ -170,7 +170,7 @@ def test_tracking_stream_descriptor_matches_sessioninit_example(): assert descriptor["quaternion_order"] == int(p.QuaternionOrder.XYZW) assert descriptor["hand_joint_order"] == int(p.HandJointOrder.OPENXR_26) assert descriptor["reference_space"] == "session_floor" - assert descriptor["layout"]["payload_size"] == 1995 + assert descriptor["layout"]["payload_size"] == 2277 assert len(descriptor["layout"]["fields"]) == len(p.IC_TRACKING_V1_FIELDS) first_field = descriptor["layout"]["fields"][0] diff --git a/examples/egocap/tests/capture_server/test_server.py b/examples/egocap/tests/capture_server/test_server.py index 579b84597d..5e9e20ed52 100644 --- a/examples/egocap/tests/capture_server/test_server.py +++ b/examples/egocap/tests/capture_server/test_server.py @@ -57,7 +57,7 @@ async def test_full_lifecycle_real_client_against_real_server(unused_tcp_port): assert events[0] == ("started", False, 2) assert ("status", "BEGUN", True) in events assert len(frames) > 0 - assert all(len(f.payload) == 1995 for f in frames) + assert all(len(f.payload) == 2277 for f in frames) # The actual object-identity check: every frame's description is # the SAME object CaptureStarted.streams carried for stream_id 0, # not a rebuilt copy per frame. From 75cf8eadaf5ed5d652c1aa18284650095dde3512 Mon Sep 17 00:00:00 2001 From: yunjul Date: Wed, 2 Dec 2026 11:40:48 +0800 Subject: [PATCH 2/2] egocap: make the Manus raw sensors opt-in and address review The raw fingertip sensors are now requested by name: ManusDataset gains SENSORS, off by default. Without it the plugin runs with its default datasets, no tracker is registered, the wire fields report absent and the manus_glove layout is unchanged. With it the plugin is launched with --datasets=human,sensors. The backend asks for it through EGOCAP_MANUS_DATASETS. - A sensor frame that has not changed for 0.5 s is reported absent: the tracker keeps returning its last frame once the plugin stops pushing. - {side}_sensor_count records how many sensors a glove reported, and a row is kept for reported sensors when a hand skeleton is untracked. - Time alignment takes the nearer sample instead of blending a reported sensor stack with an unreported one. - The mock produces sensor frames and replay serves recorded ones. - The trackers are created with the session, not while building its config; the sensor constants are tested against the plugin header and the schema. - README: the tracking message is 2309 bytes; drop a launcher option that is not in this tree. Co-Authored-By: Claude Fable 5.2 Signed-off-by: yunjul --- examples/egocap/AGENTS.md | 4 + examples/egocap/DESIGN.md | 6 +- examples/egocap/README.md | 2 +- examples/egocap/backend/egocap_web/app.py | 8 +- .../backend/egocap_web/capture_status.py | 9 +- examples/egocap/backend/egocap_web/config.py | 38 +++++++- .../backend/egocap_web/recording_adapter.py | 54 +++++++---- .../backend/egocap_web/recording_session.py | 5 +- examples/egocap/capture_server/README.md | 18 ++-- .../acquisition/isaac_capture.py | 51 +++++++--- .../capture_server/capture_server/client.py | 3 + .../capture_server/capture_server/launch.py | 1 + .../capture_server/mock/mock_isaac_capture.py | 50 ++++++++-- .../capture_server/capture_server/protocol.py | 2 + .../capture_server/replay/episode.py | 13 ++- .../replay/replay_isaac_capture.py | 17 ++++ examples/egocap/frontend/README.md | 1 + examples/egocap/recording/README.md | 6 +- .../recording/egocap/recording/alignment.py | 26 ++++- .../tests/backend/test_capture_status.py | 20 ++++ examples/egocap/tests/backend/test_config.py | 29 +++++- .../tests/backend/test_recording_adapter.py | 47 +++++++++ .../test_acquisition_adapters.py | 95 +++++++++++++++++++ .../tests/capture_server/test_device_query.py | 20 ++++ .../tests/capture_server/test_replay.py | 45 +++++++++ .../tests/recording/unit/test_alignment.py | 18 ++++ 26 files changed, 526 insertions(+), 62 deletions(-) diff --git a/examples/egocap/AGENTS.md b/examples/egocap/AGENTS.md index 252ccdeeae..0a45826d4b 100644 --- a/examples/egocap/AGENTS.md +++ b/examples/egocap/AGENTS.md @@ -94,3 +94,7 @@ before any file is written. An existing derived episode is refused, never replac 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. diff --git a/examples/egocap/DESIGN.md b/examples/egocap/DESIGN.md index 109ed8ddd7..e6d83517e6 100644 --- a/examples/egocap/DESIGN.md +++ b/examples/egocap/DESIGN.md @@ -104,10 +104,12 @@ sampled together so the three poses stay consistent with each other within one t Hand tracking comes from the hand-tracking gloves, reported as a full per-joint hand skeleton for each hand when it is being tracked, with the gloves' raw fingertip-sensor poses recorded on the -same row. The recorded hand-tracking row for a tick is dropped entirely +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 diff --git a/examples/egocap/README.md b/examples/egocap/README.md index bfa05fac20..afb0b76017 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -102,7 +102,7 @@ It is not in this tree (it is added by the camera_streamer mock-sender change, P mock sender the mock video goes through the same receiver, bridge and page, with the frame-ready time as its timestamp because the mock sender has no clock to measure. A recording made in this mode is synthetic data. -CaptureServer listens on loopback port 8082 by default; `--capture-server-port N` moves it, and the backend is pointed at the new port, when something else on the PC already holds 8082. Without `--orin` or `--mock` only the PC side starts. `--skip-deploy` reuses the previous release. The sender runs +Without `--orin` or `--mock` only the PC side starts. `--skip-deploy` reuses the previous release. The sender runs for `--seconds` (default one hour) and the launcher stops the whole stack when it ends, so a take in progress is cut off; the launcher prints the stop time at startup. The sender release the profile describes, its deploy tool, the timesync tool, the LiveKit server and the bridge are not in this tree's base, so pass their paths (or set diff --git a/examples/egocap/backend/egocap_web/app.py b/examples/egocap/backend/egocap_web/app.py index 30ebe748e0..7b555655f7 100644 --- a/examples/egocap/backend/egocap_web/app.py +++ b/examples/egocap/backend/egocap_web/app.py @@ -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, @@ -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) @@ -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(), @@ -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) diff --git a/examples/egocap/backend/egocap_web/capture_status.py b/examples/egocap/backend/egocap_web/capture_status.py index 692ff998c8..c6e4c40b5f 100644 --- a/examples/egocap/backend/egocap_web/capture_status.py +++ b/examples/egocap/backend/egocap_web/capture_status.py @@ -32,6 +32,7 @@ CaptureStatus, CaptureStatusType, CaptureStopped, + ManusPluginConfig, RequestRejectedError, StoppedBeforeAcceptedError, ) @@ -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, diff --git a/examples/egocap/backend/egocap_web/config.py b/examples/egocap/backend/egocap_web/config.py index 25ba319572..0e262130af 100644 --- a/examples/egocap/backend/egocap_web/config.py +++ b/examples/egocap/backend/egocap_web/config.py @@ -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.""" @@ -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.""" @@ -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")), diff --git a/examples/egocap/backend/egocap_web/recording_adapter.py b/examples/egocap/backend/egocap_web/recording_adapter.py index 0409609dd0..6ef522d0c3 100644 --- a/examples/egocap/backend/egocap_web/recording_adapter.py +++ b/examples/egocap/backend/egocap_web/recording_adapter.py @@ -78,8 +78,19 @@ ( FieldSpec("left_hand_pose", "float64", (25, 4, 4)), FieldSpec("right_hand_pose", "float64", (25, 4, 4)), + ), + "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", ) @@ -298,7 +309,7 @@ def convert_hand_pose(tracking: dict[str, np.ndarray], side: Side) -> np.ndarray 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. + 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.""" @@ -313,24 +324,33 @@ def convert_sensor_pose(tracking: dict[str, np.ndarray], side: Side) -> np.ndarr return pose -def build_manus_glove_fields(tracking: dict[str, np.ndarray]) -> dict[str, np.ndarray] | None: +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, - "left_sensor_pose": convert_sensor_pose(tracking, "left"), - "right_sensor_pose": convert_sensor_pose(tracking, "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 -------------------------------------------------------- @@ -355,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 @@ -378,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( @@ -402,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): diff --git a/examples/egocap/backend/egocap_web/recording_session.py b/examples/egocap/backend/egocap_web/recording_session.py index e0d79e381d..db28b4891c 100644 --- a/examples/egocap/backend/egocap_web/recording_session.py +++ b/examples/egocap/backend/egocap_web/recording_session.py @@ -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 @@ -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 diff --git a/examples/egocap/capture_server/README.md b/examples/egocap/capture_server/README.md index 163463ab2c..34e49bc5ef 100644 --- a/examples/egocap/capture_server/README.md +++ b/examples/egocap/capture_server/README.md @@ -153,7 +153,7 @@ async def query_devices(self) -> tuple[protocol.DeviceEntry, ...]: ... | Constructor `url` | Nonempty `str`, a `ws://` or `wss://` station URL. | Identifies the remote capture server. Construction creates an idle client without connecting. | | `sources` | Sequence of unique `SourceType`: `HEAD=1`, `CONTROLLERS=2`, `HANDS=3`. Required; an empty sequence is allowed. | Chooses tracking outputs. CONTROLLERS selects both controller sides; HANDS selects both hand sides. An empty sequence supports camera-only capture. | | `cameras` | Sequence of `CameraSelection`, default empty; at most three, with unique names. | Selects station-configured cameras by logical name and type. | -| `plugins` | Sequence of unique plugins: a `PluginType` (`MANUS=1`) or a `ManusPluginConfig` that also names MCAL files; default empty. | Enables these tracking plugins. Manus uses its HUMAN dataset and is optional: missing plugin discovery does not itself require session failure. This selection does not require connected gloves or filter hands by vendor. | +| `plugins` | Sequence of unique plugins: a `PluginType` (`MANUS=1`) or a `ManusPluginConfig` that also names MCAL files; default empty. | Enables these tracking plugins. Manus uses its HUMAN dataset unless a `ManusPluginConfig` names others in `datasets`, and is optional: missing plugin discovery does not itself require session failure. This selection does not require connected gloves or filter hands by vendor. | | Five `on_...` arguments | `Callback[T] \| None`, default None; argument types appear below. | Registers notifications. None discards that notification; it does not disable acquisition. | An empty `sources` sequence together with any enabled plugin is rejected as `INVALID_CONFIG`: an enabled plugin needs IC actually entered for discovery to run, but the real IC graph-construction API rejects an empty output mapping outright, so that combination has no valid native graph to build. Plugin requests are otherwise independent of output subscriptions — a session can enable Manus without selecting `HANDS`, and vice versa; only the specific zero-sources-with-an-enabled-plugin combination is rejected, not any particular source choice. Camera-only capture (empty `sources`, no enabled plugin) remains supported and never enters IC. @@ -361,7 +361,7 @@ The client validates the wire SessionInit notification and converts it to Captur | `plugin` | `PluginType`: `MANUS=1`. | Plugin kind. | | `enabled` | `bool` | Whether the station launches it; true for a plugin selected through start. | | `required` | `bool` | Whether failure to discover the plugin fails startup; false for start selections. It does not require connected gloves. | -| `datasets` | `tuple[ManusDataset, ...]`: `HUMAN=1`. | Requested live human-skeleton dataset. start selects HUMAN. | +| `datasets` | `tuple[ManusDataset, ...]`: `HUMAN=1`, `SENSORS=2`. | Requested plugin outputs. start selects HUMAN unless a `ManusPluginConfig` names others. | | `left_calibration`, `right_calibration` | `str` or omitted: an `.mcal` basename. | MCAL file for that glove, chosen from the server's MCAL folder (see Device query). Omitted when none was selected. | #### CaptureClock @@ -581,7 +581,7 @@ All enums are IntEnum classes. Supply enum members to the Python API; incoming n | `CaptureStatusType` | `STARTING=1`, `BEGUN=2`, `STATUS_CHANGE=3` | | `SourceType` | `HEAD=1`, `CONTROLLERS=2`, `HANDS=3` | | `PluginType` | `MANUS=1` | -| `ManusDataset` | `HUMAN=1` | +| `ManusDataset` | `HUMAN=1`, `SENSORS=2` | | `CaptureMode` | `MOCK=0`, `LIVE=1` | | `StartupStage` | `INITIALIZING=1`, `WAITING_FOR_HEADSET=2`, `CONNECTING=3`, `STARTING_SOURCES=4` | | `StopReason` | `REQUESTED=1`, `OWNER_DISCONNECTED=4`, `SERVER_SHUTDOWN=6`, `IC_ERROR=7`, `IC_EXITED=8`, `CAMERA_ERROR=9` | @@ -665,7 +665,7 @@ The application chooses source nodes and connects their outputs into an OutputCo Choosing HandsSource does not select Manus. The native hand implementation enumerates XDev candidates, tries non-display devices before display-device candidates, and retains default session hand trackers as a final fallback. At each update it selects the first active successful candidate independently per hand. Neither HandsSource's HandInput nor the current tracking payload contains a device/provider identity. A valid hand can therefore be an OpenXR headset hand when no Manus hand is active. -Manus is configured separately as a plugin. The server maps a Manus plugin request to IC PluginConfig (`plugin_name` is the manifest name `manus_hand_plugin`, matched exactly by the IC plugin manager; the search path is the package's bundled plugins plus `$ISAAC_ROOT/install/plugins`, where IC's `cmake --install --component manus` places the plugin) and launches its human dataset. The plugin injects 26-joint hands into OpenXR. Its manifest declares left/right hand devices; its status publisher reports their actual hardware/data state. This protocol supports the human dataset only; it does not expose raw flex sensors, haptics or calibration commands. +Manus is configured separately as a plugin. The server maps a Manus plugin request to IC PluginConfig (`plugin_name` is the manifest name `manus_hand_plugin`, matched exactly by the IC plugin manager; the search path is the package's bundled plugins plus `$ISAAC_ROOT/install/plugins`, where IC's `cmake --install --component manus` places the plugin) and launches its human dataset. The plugin injects 26-joint hands into OpenXR. Its manifest declares left/right hand devices; its status publisher reports their actual hardware/data state. This protocol supports the human dataset and, on request, the raw fingertip sensors; it does not expose haptics or calibration commands. IC PluginConfig.required means discovery of the plugin is required. It does not mean both physical gloves must be connected before session entry returns. A missing required plugin or source initialization error can raise during startup. A running plugin with missing gloves can coexist with a successfully entered session. No automatic switch from a requested plugin to another plugin is promised. @@ -766,14 +766,14 @@ later session's first device can be different. `plugins` defaults to an empty array. Each entry selects a defined PluginType and supported output settings. A plugin kind occurs at most once. The server assigns IC's internal instance namespace and returns observed provider IDs as opaque identifiers; clients do not choose or construct those IDs. `enabled` and `required` retain the native PluginConfig semantics. The station owns plugin installation, execution and calibration defaults. The plugin list is independent of the tracking source list: enabling an injector does not subscribe its data automatically. -A plugin is a supporting program started by IC, rather than a physical device. Manus's plugin receives glove data and injects hand skeletons into OpenXR, where HandsSource can read them. It also pushes each glove's raw fingertip-sensor poses, which the server reads whenever the plugin is enabled and sends in the `manus_left`/`manus_right` tracking fields. An instance is one configured launch of that program; its ID gives its status records a namespace so records from different providers do not collide. +A plugin is a supporting program started by IC, rather than a physical device. Manus's plugin receives glove data and injects hand skeletons into OpenXR, where HandsSource can read them. It also pushes each glove's raw fingertip-sensor poses, which the server reads and sends in the `manus_left`/`manus_right` tracking fields only when the request's `datasets` include SENSORS; the plugin is then launched with `--datasets=human,sensors`, and otherwise with its own default datasets. An instance is one configured launch of that program; its ID gives its status records a namespace so records from different providers do not collide. | Plugin request field | Allowed contents/default | Meaning and effect | |---|---|---| | `plugin` | `PluginType`: required, currently only `MANUS=1`. | Selects the server's installed Manus adapter. It is not an executable name or path supplied by the client. | | `enabled` | Boolean; default true. | True permits launching the requested plugin; false skips it. A disabled entry does not imply its hardware is absent. | | `required` | Boolean; default false, matching native PluginConfig. | True makes missing plugin discovery a startup error. False permits IC to skip a plugin it cannot find. Neither value makes physical glove connection a prerequisite for SessionBegun. | -| `datasets` | `ManusDataset`: unique nonempty array, currently `HUMAN=1` only, so `[1]`; default `[1]`. | HUMAN enables the 26-joint hand-skeleton injection path. A dataset here is a category of live plugin output, not a recorded training dataset or filesystem directory. | +| `datasets` | `ManusDataset`: unique nonempty array of `HUMAN=1`, `SENSORS=2`; default `[1]`. | HUMAN enables the 26-joint hand-skeleton injection path. SENSORS adds each glove's raw fingertip sensors to the tracking fields; without it they are reported absent. A dataset here is a category of live plugin output, not a recorded training dataset or filesystem directory. | HANDS selects generic OpenXR hand outputs. A client requiring Manus hardware checks Manus device status. HandsSource does not provide per-sample provider identity or an exclusive Manus filter, so a valid generic hand sample does not certify Manus origin. Recording requirements remain client policy. @@ -1135,7 +1135,7 @@ The following table explains the values packed into the binary fields. These are | Hand `joint_orientations` | Float32 array \[26,4\], xyzw quaternions. | Session-space orientation of each joint, in the same index order as positions. | | Hand `joint_radii` | Float32 array \[26\], meters. | Runtime-estimated radius associated with each joint, useful for visualizing or modeling its spatial extent. It is not a confidence score. | | Hand `joint_valid` | UINT8 array \[26\], each value 0 or 1. | Whether each joint has a valid position and orientation according to IC. Some joints can be invalid while the hand group remains present. This is not a separate per-joint actively-tracked flag. | -| `manus_left.sensor_present`, `manus_right.sensor_present` | Independent scalar 0 or 1 per side. | Whether the Manus plugin has pushed a complete five-fingertip raw-sensor set for that glove. It stays 1, on the last set, after a glove stops reporting while the plugin keeps running. | +| `manus_left.sensor_present`, `manus_right.sensor_present` | Independent scalar 0 or 1 per side. | Whether the Manus plugin is pushing a complete five-fingertip raw-sensor set for that glove. Always 0 unless the request's datasets include SENSORS, and 0 again once the set has not changed for 0.5 s: a glove that stops reporting leaves its last set behind, which is not sent as current. | | Manus `sensor_positions` | Float32 array \[5,3\], meters. | Raw fingertip-sensor positions, thumb to little finger, in the Manus SDK frame the plugin configures. These are not session-space positions. | | Manus `sensor_orientations` | Float32 array \[5,4\], xyzw quaternions. | Raw fingertip-sensor orientations, in the same order and frame as the positions. | @@ -1283,7 +1283,7 @@ Both binary families use `struct.Struct("<4sBBHQQQ")`: | 24 | uint64 LE | Capture-host receive/assembly timestamp, ns. | | 32 | bytes | Exactly 2277 tracking bytes or one complete JPEG. | -Tracking messages are 2027 bytes. The session ID is supplied by the active SessionBegun association; do not repeat it per sample. No binary data precedes SessionBegun or follows its matching SessionStopped. A rejection for another ID does not disturb the active stream. +Tracking messages are 2309 bytes. The session ID is supplied by the active SessionBegun association; do not repeat it per sample. No binary data precedes SessionBegun or follows its matching SessionStopped. A rejection for another ID does not disturb the active stream. ##### CaptureFrame @@ -1298,7 +1298,7 @@ CaptureImage uses BinaryKind.CAPTURE\_IMAGE=2 and the corresponding camera strea | Transport setting | Value and interpretation | |---|---| | Inbound control-message limit | 64 KiB per complete JSON message. An oversized message closes with WebSocket code 1009. | -| Tracking message size | Exactly 2027 bytes, including its header. | +| Tracking message size | Exactly 2309 bytes, including its header. | | JPEG payload ceiling | 2 MiB; the complete binary image message is at most 2 MiB plus 32 bytes. The client configures its receive limit for the complete message. | | Compression | WebSocket per-message compression is disabled; JPEG is already encoded image data. | | Ping interval / timeout | 20 seconds / 20 seconds. Ping/Pong tests transport liveness, not device availability or sample age. | diff --git a/examples/egocap/capture_server/capture_server/acquisition/isaac_capture.py b/examples/egocap/capture_server/capture_server/acquisition/isaac_capture.py index 6630a3d8d3..8b03fa6e7e 100644 --- a/examples/egocap/capture_server/capture_server/acquisition/isaac_capture.py +++ b/examples/egocap/capture_server/capture_server/acquisition/isaac_capture.py @@ -52,6 +52,9 @@ _MANUS_SENSOR_COLLECTIONS = {"manus_left": "manus_sensors_left", "manus_right": "manus_sensors_right"} #: The plugin's raw-sensor order, thumb to little finger, as the ``JointName.HAND_RAW_*_TIP`` suffixes. _SENSOR_TIPS = ("THUMB", "INDEX", "MIDDLE", "RING", "LITTLE") +#: A sensor frame unchanged for this long is no longer reported. The tracker keeps returning its last frame +#: once the plugin stops pushing (schema_tracker.hpp), and the frame carries no time of its own. +_SENSOR_STALE_AFTER_S = 0.5 def _zero_controller_fields(prefix: str) -> dict[str, Any]: @@ -185,6 +188,9 @@ class TrackingSelection: # silently. Meaningless when manus_enabled is False (no plugin is # constructed at all in that case). manus_required: bool = False + # Whether the request's datasets include the gloves' raw fingertip sensors. Off, the plugin runs with its + # default datasets and no sensor is read, sent or recorded. + manus_sensors: bool = False # Resolved host paths of MCAL files for the Manus plugin (the server turns the client's basenames into these # before any hardware starts). Passed to the plugin as its own calibration arguments, so whether the glove # accepted a file is still reported by the plugin's per-hand status, not assumed here. @@ -224,8 +230,10 @@ def __init__( self._clock = clock or MonotonicClock() self._runner = ThreadRunner() self._session: Any = None - # One tracker per Manus raw-sensor collection, by wire prefix; empty unless the plugin is requested. + # One tracker per Manus raw-sensor collection, by wire prefix; empty unless the sensors are requested. self._sensor_trackers: dict[str, Any] = {} + # Each glove's last sensor frame and when it last changed, to stop reporting a frame that went stale. + self._sensor_changed: dict[str, tuple[Any, float]] = {} self._launcher: Any = None # Tracks whether each object's own __enter__() actually returned, # separately from whether the field itself is set -- close() must @@ -275,22 +283,20 @@ def _build_config(self) -> Any: if self._selection.manus_enabled else [] ) - if self._selection.manus_enabled: - # Registered with the session like any tracker, so step() refreshes them with the sources. - self._sensor_trackers = { - prefix: self._sdk.JointSe3PoseTracker(collection) - for prefix, collection in _MANUS_SENSOR_COLLECTIONS.items() - } return self._sdk.TeleopSessionConfig( app_name="capture_server", pipeline=pipeline, plugins=plugins, + # Registered with the session like any tracker, so step() refreshes them with the sources. trackers=list(self._sensor_trackers.values()), ) def _manus_args(self) -> list[str]: - """The Manus plugin's calibration arguments for the files this session selected.""" + """The Manus plugin's arguments: the calibration files this session selected and, when the raw + sensors are requested, the datasets to run. Without that request the plugin keeps its own default.""" args = [] + if self._selection.manus_sensors: + args.append("--datasets=human,sensors") if self._selection.manus_left_calibration is not None: args.append(f"--left-calibration={self._selection.manus_left_calibration}") if self._selection.manus_right_calibration is not None: @@ -316,6 +322,11 @@ def _enter_sync(self) -> Any: try: launcher.__enter__() self._launcher_entered = True + if self._selection.manus_sensors: + self._sensor_trackers = { + prefix: self._sdk.JointSe3PoseTracker(collection) + for prefix, collection in _MANUS_SENSOR_COLLECTIONS.items() + } session = self._session_factory(self._build_config()) self._session = session session.__enter__() @@ -441,12 +452,26 @@ def _map_tracking(self, native: dict[str, Any]) -> dict[str, Any]: fields.update(_zero_hand_fields(prefix)) for prefix in _MANUS_SENSOR_COLLECTIONS: tracker = self._sensor_trackers.get(prefix) - # No tracker without the plugin, and no data until the plugin pushes its first frame. + # No tracker unless the sensors are requested, and no data until the plugin pushes its first frame. data = tracker.get_data(self._session.deviceio_session) if tracker is not None else None - if data is not None: - fields.update(_sensor_fields(prefix, data, self._sdk.JointName)) - else: - fields.update(_zero_sensor_fields(prefix)) + fields.update(self._live_sensor_fields(prefix, data)) + return fields + + def _live_sensor_fields(self, prefix: str, data: Any) -> dict[str, Any]: + """One glove's sensor fields for *data*, reported as absent when there is no frame or the frame has + not changed for ``_SENSOR_STALE_AFTER_S``: a glove that stopped reporting must not record its last + pose as live.""" + if data is None: + return _zero_sensor_fields(prefix) + fields = _sensor_fields(prefix, data, self._sdk.JointName) + frame = (fields[f"{prefix}.sensor_positions"], fields[f"{prefix}.sensor_orientations"]) + now = self._clock.monotonic() + last = self._sensor_changed.get(prefix) + # A new frame restarts the age; a polled tick between two pushes legitimately repeats one. + if last is None or last[0] != frame: + self._sensor_changed[prefix] = (frame, now) + elif now - last[1] >= _SENSOR_STALE_AFTER_S: + return _zero_sensor_fields(prefix) return fields async def status(self, updated_at_ns: int) -> p.StatusSnapshot: diff --git a/examples/egocap/capture_server/capture_server/client.py b/examples/egocap/capture_server/capture_server/client.py index 237de9589c..a6524658f3 100644 --- a/examples/egocap/capture_server/capture_server/client.py +++ b/examples/egocap/capture_server/capture_server/client.py @@ -308,6 +308,8 @@ class ManusPluginConfig: left_calibration: str | None = None right_calibration: str | None = None + #: The plugin outputs to request; add ``ManusDataset.SENSORS`` for the raw fingertip sensors. + datasets: tuple[p.ManusDataset, ...] = (p.ManusDataset.HUMAN,) plugin: ClassVar[p.PluginType] = p.PluginType.MANUS def __post_init__(self) -> None: @@ -1110,6 +1112,7 @@ def _build_begin_request( plugin=plugin.plugin, left_calibration=plugin.left_calibration, right_calibration=plugin.right_calibration, + datasets=plugin.datasets, ) if isinstance(plugin, ManusPluginConfig) else p.PluginRequest(plugin=plugin) diff --git a/examples/egocap/capture_server/capture_server/launch.py b/examples/egocap/capture_server/capture_server/launch.py index deed30e984..1e4728af53 100644 --- a/examples/egocap/capture_server/capture_server/launch.py +++ b/examples/egocap/capture_server/capture_server/launch.py @@ -99,6 +99,7 @@ def _tracking_adapter( hand_right=_group_selected(begin, p.SourceType.HANDS), manus_enabled=manus_plugin_request is not None, manus_required=manus_plugin_request.required if manus_plugin_request is not None else False, + manus_sensors=manus_plugin_request is not None and p.ManusDataset.SENSORS in manus_plugin_request.datasets, manus_left_calibration=_calibration_path( manus_plugin_request.left_calibration if manus_plugin_request is not None else None, calibration_dir, diff --git a/examples/egocap/capture_server/capture_server/mock/mock_isaac_capture.py b/examples/egocap/capture_server/capture_server/mock/mock_isaac_capture.py index d30f820d33..3bc65df528 100644 --- a/examples/egocap/capture_server/capture_server/mock/mock_isaac_capture.py +++ b/examples/egocap/capture_server/capture_server/mock/mock_isaac_capture.py @@ -64,6 +64,7 @@ from dataclasses import dataclass, field from enum import Enum, IntEnum from functools import lru_cache +from types import SimpleNamespace from typing import Any import numpy as np @@ -88,6 +89,7 @@ "HandsSource", "HeadInputIndex", "HeadSource", + "JointName", "JointSe3PoseTracker", "KNOWN_FAULTS", "NoopContext", @@ -377,16 +379,44 @@ class TeleopSessionConfig: trackers: list[Any] = field(default_factory=list) +class JointName(IntEnum): + """The real schema's raw fingertip-sensor joints (src/core/schema/fbs/joint_se3_pose.fbs).""" + + HAND_RAW_THUMB_TIP = 1100 + HAND_RAW_INDEX_TIP = 1101 + HAND_RAW_MIDDLE_TIP = 1102 + HAND_RAW_RING_TIP = 1103 + HAND_RAW_LITTLE_TIP = 1104 + + class JointSe3PoseTracker: - """Reproduces the real tracker's construction and read shape for a tensor collection this mock never - fills: ``get_data`` is always None, as the real one is until a plugin pushes a frame.""" + """Reproduces the real tracker's construction and read shape. The session a tracker is registered with + sets ``frame`` on each step; ``get_data`` is None until then, as the real one is until a plugin pushes.""" def __init__(self, collection_id: str) -> None: self.collection_id = collection_id - - def get_data(self, session: Any) -> None: - """No sample: nothing pushes to this collection.""" - return None + self.frame: Any = None + + def get_data(self, session: Any) -> Any: + """The frame of the last step, or None.""" + return self.frame + + +def sensor_frame(poses: np.ndarray) -> Any: + """A ``JointSe3PoseOutput``-shaped frame from five ``[x, y, z, qx, qy, qz, qw]`` rows, thumb to little + finger.""" + joints = { + joint: SimpleNamespace( + pose=SimpleNamespace( + position=SimpleNamespace(x=float(pose[0]), y=float(pose[1]), z=float(pose[2])), + orientation=SimpleNamespace( + x=float(pose[3]), y=float(pose[4]), z=float(pose[5]), w=float(pose[6]) + ), + ) + ) + for joint, pose in zip(JointName, poses) + } + return SimpleNamespace(lookup=joints.__getitem__) # --------------------------------------------------------------------------- CloudXRLauncher @@ -535,6 +565,10 @@ def _blend(a, b, u): _FINGER_MAX = (math.radians(85), math.radians(100), math.radians(70)) +#: The fingertip rows of a 26-joint hand, thumb to little finger. +_TIP_JOINTS = [joint for joint in HandJointIndex if joint.name.endswith("_TIP")] + + @dataclass(frozen=True) class _HandPose: wrist: np.ndarray # (7,) @@ -809,6 +843,10 @@ def step( _, left_ctrl, right_ctrl = self._operator.core(t_controller) _, left_hand, right_hand = self._operator.core(t_glove) inputs = self._operator.inputs(t_controller) + # A registered sensor tracker reads the fingertips of the same delayed hand the skeleton comes from. + for tracker in self.config.trackers: + hand = left_hand if tracker.collection_id.endswith("left") else right_hand + tracker.frame = sensor_frame(hand.joints[_TIP_JOINTS]) result: dict[str, OptionalTensorGroup] = {} for leaf_key, (source_node, selector) in self.config.pipeline.outputs.items(): diff --git a/examples/egocap/capture_server/capture_server/protocol.py b/examples/egocap/capture_server/capture_server/protocol.py index 88e1010229..cf370adf6f 100644 --- a/examples/egocap/capture_server/capture_server/protocol.py +++ b/examples/egocap/capture_server/capture_server/protocol.py @@ -99,6 +99,8 @@ class PluginType(IntEnum): class ManusDataset(IntEnum): HUMAN = 1 + #: The gloves' raw fingertip sensors. Off unless requested. + SENSORS = 2 class ManusCalibrationCatalogStatus(IntEnum): diff --git a/examples/egocap/capture_server/capture_server/replay/episode.py b/examples/egocap/capture_server/capture_server/replay/episode.py index fe2751019c..07b7bb08e5 100644 --- a/examples/egocap/capture_server/capture_server/replay/episode.py +++ b/examples/egocap/capture_server/capture_server/replay/episode.py @@ -57,6 +57,8 @@ ) #: Per-row arrays a hand table must provide (besides ``capture_time``). HAND_ARRAYS: tuple[str, ...] = ("left_hand_pose", "right_hand_pose") +#: Per-row arrays a hand table has only when the raw fingertip sensors were recorded. +SENSOR_ARRAYS: tuple[str, ...] = ("left_sensor_pose", "right_sensor_pose") _TIME_ARRAY = "capture_time" _INTRINSICS_ARRAY = "intrinsics" @@ -129,9 +131,10 @@ def _read_times(group: Any, name: str) -> np.ndarray: def _read_table( - group: Any | None, name: str, required: tuple[str, ...] + group: Any | None, name: str, required: tuple[str, ...], optional: tuple[str, ...] = () ) -> tuple[np.ndarray, dict[str, np.ndarray]] | None: - """A tracking group's absolute times and its required arrays, fully loaded; None when the group is absent. + """A tracking group's absolute times, its required arrays and the optional ones it has, fully loaded; None + when the group is absent. Every array must have one row per timestamp -- a row-count mismatch would silently pair samples with the wrong time, so it is a format error, not something to truncate past. @@ -140,8 +143,10 @@ def _read_table( return None times = _read_times(group, name) arrays: dict[str, np.ndarray] = {} - for array_name in required: + for array_name in (*required, *optional): if array_name not in group: + if array_name in optional: + continue raise EpisodeFormatError(f"{name}: no '{array_name}' array") values = np.asarray(group[array_name][:]) if values.shape[:1] != times.shape: @@ -207,7 +212,7 @@ def group(name: str) -> Any | None: return root[name] if name in root else None controllers_raw = _read_table(group(CONTROLLER_GROUP), CONTROLLER_GROUP, CONTROLLER_ARRAYS) - hands_raw = _read_table(group(HAND_GROUP), HAND_GROUP, HAND_ARRAYS) + hands_raw = _read_table(group(HAND_GROUP), HAND_GROUP, HAND_ARRAYS, SENSOR_ARRAYS) # Cameras are discovered from the MP4 files; each needs its Zarr group for frame times, since the # container's own timestamps are relative to the file, not to the other streams. diff --git a/examples/egocap/capture_server/capture_server/replay/replay_isaac_capture.py b/examples/egocap/capture_server/capture_server/replay/replay_isaac_capture.py index 82be19fcf8..dc83de46c5 100644 --- a/examples/egocap/capture_server/capture_server/replay/replay_isaac_capture.py +++ b/examples/egocap/capture_server/capture_server/replay/replay_isaac_capture.py @@ -25,6 +25,8 @@ from typing import Any +import numpy as np + from capture_server.acquisition.clock import Clock, MonotonicClock from capture_server.acquisition.tensor_indices import ControllerInputIndex, HandInputIndex, HeadInputIndex from capture_server.mock.mock_isaac_capture import ( @@ -35,6 +37,7 @@ DeviceStatus, HandsSource, HeadSource, + JointName, JointSe3PoseTracker, NoopContext, OptionalTensorGroup, @@ -46,6 +49,7 @@ StatusReason, StatusSnapshot, TeleopSessionConfig, + sensor_frame, ) from . import tracking_map @@ -57,6 +61,7 @@ "ControllersSource", "HandsSource", "HeadSource", + "JointName", "JointSe3PoseTracker", "NoopContext", "OutputCombiner", @@ -125,6 +130,8 @@ def step( # start offsets, so "the current row" is per table, never a common index. controller_row = controllers.latest_row(position) if controllers is not None else -1 hand_row = hands.latest_row(position) if hands is not None else -1 + for tracker in self.config.trackers: + tracker.frame = self._sensors("left" if tracker.collection_id.endswith("left") else "right", hand_row) result: dict[str, OptionalTensorGroup] = {} for leaf_key, (source_node, selector) in self.config.pipeline.outputs.items(): @@ -177,6 +184,16 @@ def _hand(self, side: str, controller_row: int, hand_row: int) -> OptionalTensor group = tracking_map.hand_group(table.arrays[f"{side}_hand_pose"][hand_row], anchor, side) return group if group is not None else OptionalTensorGroup(len(HandInputIndex)) + def _sensors(self, side: str, row: int) -> Any: + """One glove's recorded sensor frame for hand-table *row*, or None where the episode has none.""" + table = self._episode.hands + poses = table.arrays.get(f"{side}_sensor_pose") if table is not None and row >= 0 else None + # An all-zero stack is how a recording marks a glove that reported no sensors. + if poses is None or not poses[row].any(): + return None + quaternions = [tracking_map.quaternion_xyzw(pose[:3, :3]) for pose in poses[row]] + return sensor_frame(np.hstack([poses[row][:, :3, 3], quaternions])) + def get_status(self) -> StatusSnapshot: """Native-shaped inventory describing the recording: one replay provider standing in for the OpenXR runtime, with a device per recorded stream the graph selected. A selected stream the episode lacks is diff --git a/examples/egocap/frontend/README.md b/examples/egocap/frontend/README.md index 2836b60525..d1f4d9963d 100644 --- a/examples/egocap/frontend/README.md +++ b/examples/egocap/frontend/README.md @@ -189,6 +189,7 @@ Fixed defaults the backend starts with, set in `backend/egocap_web/config.py`'s | Sources | head, controllers, hands | fixed | | Cameras | none requested | the station YAML's `video_sources`, see below | | Plugins | none | `EGOCAP_CAPTURE_PLUGINS`, a comma-separated list of plugin names (case-insensitive); only `manus` exists today, so `manus` requests glove hand tracking. An unknown name stops the backend at startup. | +| Manus datasets | human | `EGOCAP_MANUS_DATASETS`, a comma-separated list of `human`, `sensors`; `human,sensors` also sends and records each glove's raw fingertip sensors. Used only with the `manus` plugin. | | Tracking sources | head, controllers, hands | `EGOCAP_CAPTURE_SOURCES`, a comma-separated list of `head`, `controllers`, `hands`, or `none` for a cameras-only session that needs no headset and no IsaacCapture (it cannot be combined with `EGOCAP_CAPTURE_PLUGINS`). | | Preview sample rates | 10 Hz cameras, 10 Hz tracking | `EGOCAP_CAMERA_SAMPLE_HZ`, `EGOCAP_TRACKING_SAMPLE_HZ`: how often the page is sent camera frames / tracking samples (positive Hz). Raise to the capture rate (e.g. `60`) to see the native feed; every viewer pays for each sample. | diff --git a/examples/egocap/recording/README.md b/examples/egocap/recording/README.md index e8100a239a..b42870e7a5 100644 --- a/examples/egocap/recording/README.md +++ b/examples/egocap/recording/README.md @@ -169,7 +169,8 @@ Recorded numeric sources, exactly as written by `backend/egocap_web/recording_ad | `pico_controller` | `left_trigger`, `right_trigger` | scalar | `float64` | Analog trigger values. | | `pico_controller` | `a_button`, `b_button`, `x_button`, `y_button` | scalar | `bool` | Controller buttons. | | `manus_glove` | `left_hand_pose`, `right_hand_pose` | `(25, 4, 4)` | `float64` | Root-relative transform stacks, one per hand joint. | -| `manus_glove` | `left_sensor_pose`, `right_sensor_pose` | `(5, 4, 4)` | `float64` | Raw fingertip-sensor transforms in the Manus SDK frame, thumb to little finger; all zero when none were reported. | +| `manus_glove` | `left_sensor_pose`, `right_sensor_pose` | `(5, 4, 4)` | `float64` | Only when the session requested the raw sensors (`EGOCAP_MANUS_DATASETS=human,sensors`). Raw fingertip-sensor transforms in the Manus SDK frame, thumb to little finger; all zero when none were reported. Time alignment never blends a reported stack with an unreported one: it takes the nearer sample. | +| `manus_glove` | `left_sensor_count`, `right_sensor_count` | scalar | `int64` | With the sensor transforms: how many sensors that glove reported on the row, 5 or 0. | Both groups carry `capture_time`/`receive_time` as seconds (converted from CaptureServer's nanosecond timestamps) and `source_sequence` (int64), the producer's own count for that row, or @@ -181,7 +182,8 @@ streams and device status, listing what the protocol does not report) and its `p the LiveKit receiver's loss counters since the take began and the ingress queue's offered count (raw items, so it does not reconcile one-to-one with rows). Episodes recorded before these fields existed have no `source_sequence` array and are still accepted by the integrity check. A `manus_glove` row is omitted entirely for a tick where -either hand's wrist is untracked — never backfilled with a stale or fabricated zero pose. The +either hand's wrist is untracked — never backfilled with a stale or fabricated zero pose. With the raw +sensors requested, a tick where a glove reported them is kept and an untracked hand is all zero. The OpenXR-to-this-skeleton hand-joint mapping is implemented but not yet validated against real hardware (see `capture_server/README.md`'s "implemented but not exercised on hardware" note). diff --git a/examples/egocap/recording/egocap/recording/alignment.py b/examples/egocap/recording/egocap/recording/alignment.py index 34d725f3b4..cafea530a6 100644 --- a/examples/egocap/recording/egocap/recording/alignment.py +++ b/examples/egocap/recording/egocap/recording/alignment.py @@ -16,7 +16,9 @@ * the index source's own fields are only filtered by ``valid_indices``; every other source's fields are interpolated at the kept times by their declared rule, written as ``_interp``: ``pose`` (4x4 transforms: linear position, slerp rotation), ``linear`` (element-wise, also used for a 4x4 field with extra - leading dimensions) or ``nearest`` (the value at the nearest sample); ``raw`` fields are not resampled. + leading dimensions), ``present`` (``linear``, but the nearest sample where one neighbour is all zero, the + mark of a sample that was not reported) or ``nearest`` (the value at the nearest sample); ``raw`` fields are + not resampled. There is no file access here. The times passed in are the ones to align on: each source's recorded capture time, used exactly as given and never adjusted here. @@ -48,7 +50,7 @@ ] #: How one field is resampled onto the kept times. -FieldRule = Literal["pose", "linear", "nearest", "raw"] +FieldRule = Literal["pose", "linear", "present", "nearest", "raw"] class AlignmentError(ValueError): @@ -163,6 +165,18 @@ def _linear(times: np.ndarray, values: np.ndarray, targets: np.ndarray) -> np.nd return interpolate.interp1d(times, values, kind="linear", axis=0)(targets) +def _present(times: np.ndarray, values: np.ndarray, targets: np.ndarray) -> np.ndarray: + """Element-wise linear between two samples that are both reported or both all zero (absent); where only + one is reported, the nearest sample, since a blend of an absent sample and a reported one is neither.""" + times, values = _clean(times, values) + out = interpolate.interp1d(times, values, kind="linear", axis=0)(targets) + reported = values.reshape(len(values), -1).any(axis=1) + after = np.clip(np.searchsorted(times, targets), 1, len(times) - 1) + mixed = reported[after - 1] != reported[after] + out[mixed] = values[find_nearest_timestamp_indices(times, targets)][mixed] + return out + + def _pose(times: np.ndarray, values: np.ndarray, targets: np.ndarray) -> np.ndarray: """Rigid transforms ``(N, 4, 4)``: linear position and slerp rotation, with a bottom row of [0, 0, 0, 1].""" times, values = _clean(times, values) @@ -191,6 +205,8 @@ def interpolate_field( return _pose(times, values, targets) if rule in ("pose", "linear"): return _linear(times, values, targets) + if rule == "present": + return _present(times, values, targets) raise AlignmentError(f"unknown field rule {rule!r}") @@ -220,7 +236,8 @@ class AlignedEpisode: #: How each field of a frame type is resampled when an episode is time aligned. A session's config.yaml names the #: frame type of each source. Head and controller poses are rigid transforms (slerp); the glove's transform stacks -#: are interpolated element-wise, so their shape never selects slerp; triggers and sensor values are continuous; +#: are interpolated element-wise, so their shape never selects slerp, and a sensor stack is never blended with +#: an unreported (all-zero) one; triggers and sensor values are continuous; #: a count is the nearest sample's; buttons and flags are not resampled, so they are absent here (raw). FRAME_FIELD_RULES: dict[str, dict[str, FieldRule]] = { "RGBCameraFrame": {"pose": "pose"}, @@ -233,7 +250,8 @@ class AlignedEpisode: "right_trigger": "linear", }, "ManusFrame": { - **{f"{side}_{part}_pose": "linear" for side in ("left", "right") for part in ("hand", "sensor")}, + **{f"{side}_hand_pose": "linear" for side in ("left", "right")}, + **{f"{side}_sensor_pose": "present" for side in ("left", "right")}, **{ f"{side}_sensor_{kind}": "linear" for side in ("left", "right") diff --git a/examples/egocap/tests/backend/test_capture_status.py b/examples/egocap/tests/backend/test_capture_status.py index 206e53c636..27ee78c6f5 100644 --- a/examples/egocap/tests/backend/test_capture_status.py +++ b/examples/egocap/tests/backend/test_capture_status.py @@ -49,6 +49,26 @@ async def test_monitor_reaches_begun_against_real_mock_server(unused_tcp_port): await _stop_server(server) +@pytest.mark.parametrize( + "datasets", + [(p.ManusDataset.HUMAN,), (p.ManusDataset.HUMAN, p.ManusDataset.SENSORS)], + ids=["default", "sensors"], +) +async def test_monitor_requests_the_configured_manus_datasets(unused_tcp_port, datasets): + server = await _start_server(unused_tcp_port) + try: + config = _config(unused_tcp_port, plugins=(p.PluginType.MANUS,), manus_datasets=datasets) + monitor = CaptureStatusMonitor(config, backend_instance_id="b1") + await monitor.start() + await _poll_until(lambda: monitor.snapshot().running) + + assert monitor.native.started.effective_config.plugins[0].datasets == datasets + + await monitor.stop() + finally: + await _stop_server(server) + + async def test_monitor_reports_terminal_on_explicit_stop(unused_tcp_port): server = await _start_server(unused_tcp_port) try: diff --git a/examples/egocap/tests/backend/test_config.py b/examples/egocap/tests/backend/test_config.py index 36c6827527..49e1336c6b 100644 --- a/examples/egocap/tests/backend/test_config.py +++ b/examples/egocap/tests/backend/test_config.py @@ -5,7 +5,14 @@ import pytest from capture_server import protocol as p -from egocap_web.config import PluginConfigError, SourceConfigError, _parse_plugins, _parse_sources, config_from_env +from egocap_web.config import ( + PluginConfigError, + SourceConfigError, + _parse_manus_datasets, + _parse_plugins, + _parse_sources, + config_from_env, +) @pytest.mark.parametrize("raw", [None, "", " "]) @@ -52,6 +59,26 @@ def test_config_from_env_fails_at_startup_on_a_bad_plugin_name(monkeypatch): config_from_env() +def test_manus_raw_sensors_are_requested_only_by_name(monkeypatch): + monkeypatch.setenv("EGOCAP_CAPTURE_PLUGINS", "manus") + monkeypatch.delenv("EGOCAP_MANUS_DATASETS", raising=False) + assert config_from_env().manus_datasets == (p.ManusDataset.HUMAN,) + assert not config_from_env().manus_sensors + + monkeypatch.setenv("EGOCAP_MANUS_DATASETS", " Human, sensors ") + assert config_from_env().manus_datasets == (p.ManusDataset.HUMAN, p.ManusDataset.SENSORS) + assert config_from_env().manus_sensors + + monkeypatch.delenv("EGOCAP_CAPTURE_PLUGINS") + assert not config_from_env().manus_sensors, "no Manus plugin, no sensors" + + +@pytest.mark.parametrize("raw", ["human,", "tips", "sensors,sensors"]) +def test_a_malformed_manus_dataset_list_fails_at_startup(raw): + with pytest.raises(PluginConfigError): + _parse_manus_datasets(raw) + + @pytest.mark.parametrize("raw", [None, "", " "]) def test_unset_or_blank_sources_keeps_the_default(raw): assert _parse_sources(raw) is None diff --git a/examples/egocap/tests/backend/test_recording_adapter.py b/examples/egocap/tests/backend/test_recording_adapter.py index 451874def2..bd721841b2 100644 --- a/examples/egocap/tests/backend/test_recording_adapter.py +++ b/examples/egocap/tests/backend/test_recording_adapter.py @@ -26,6 +26,7 @@ from capture_server import protocol as capture_protocol from capture_server.client import CameraImage, CaptureFrame from egocap_web.recording_adapter import ( + MANUS_GLOVE_SENSORS_SPEC, MANUS_GLOVE_SPEC, PICO_CONTROLLER_SPEC, RecordingAdapterError, @@ -40,6 +41,7 @@ convert_hand_pose, convert_head_pose, convert_raw_item, + convert_sensor_pose, oxr_fingertips_to_manus_skeleton, pose7d_to_matrix, validate_tracking_descriptor, @@ -277,6 +279,51 @@ def test_build_manus_glove_fields_present_when_both_hands_valid(): assert fields is not None assert fields["left_hand_pose"].shape == (25, 4, 4) assert fields["right_hand_pose"].shape == (25, 4, 4) + assert set(fields) == {spec.name for spec in MANUS_GLOVE_SPEC.fields}, "no sensors unless requested" + + +def test_convert_sensor_pose_is_all_zero_when_the_glove_reported_none(): + t = tracking_dict(**{"manus_left.sensor_present": 0}) + assert not convert_sensor_pose(t, "left").any() + assert convert_sensor_pose(t, "right")[:, 3, 3].tolist() == [1.0] * 5 + + +def test_convert_sensor_pose_is_the_same_for_either_sign_of_a_quaternion(): + quats = np.tile(np.array([0.0, 0.6, 0.0, 0.8], dtype=np.float32), (5, 1)) + pose = convert_sensor_pose(tracking_dict(**{"manus_left.sensor_orientations": quats}), "left") + flipped = convert_sensor_pose(tracking_dict(**{"manus_left.sensor_orientations": -quats}), "left") + + np.testing.assert_allclose(flipped, pose, atol=1e-7) + np.testing.assert_allclose( + pose[0, :3, :3], [[0.28, 0.0, 0.96], [0.0, 1.0, 0.0], [-0.96, 0.0, 0.28]], atol=1e-6 + ) + np.testing.assert_allclose(pose[2, :3, 3], [0.07, 0.08, 0.09], atol=1e-7) + + +def test_requested_sensors_are_recorded_with_how_many_each_glove_reported(): + fields = build_manus_glove_fields(tracking_dict(**{"manus_right.sensor_present": 0}), sensors=True) + + assert set(fields) == {spec.name for spec in MANUS_GLOVE_SENSORS_SPEC.fields} + assert (fields["left_sensor_count"], fields["right_sensor_count"]) == (5, 0) + assert fields["left_sensor_pose"].shape == (5, 4, 4) + assert not fields["right_sensor_pose"].any() + + +def test_requested_sensors_are_kept_when_a_hand_skeleton_is_untracked(): + valid = np.ones(26, dtype=np.uint8) + valid[1] = 0 # right wrist untracked + fields = build_manus_glove_fields(tracking_dict(**{"hand_right.joint_valid": valid}), sensors=True) + + assert fields["right_sensor_count"] == 5 + assert not fields["right_hand_pose"].any(), "an untracked hand is all zero, never fabricated" + assert fields["left_hand_pose"].any() + + +def test_requested_sensors_row_is_omitted_when_neither_skeleton_nor_sensors_are_there(): + valid = np.ones(26, dtype=np.uint8) + valid[1] = 0 + absent = {"hand_right.joint_valid": valid, "manus_left.sensor_present": 0, "manus_right.sensor_present": 0} + assert build_manus_glove_fields(tracking_dict(**absent), sensors=True) is None # --- descriptor validation ---------------------------------------------------- diff --git a/examples/egocap/tests/capture_server/test_acquisition_adapters.py b/examples/egocap/tests/capture_server/test_acquisition_adapters.py index e12cd26e6e..63b810fffb 100644 --- a/examples/egocap/tests/capture_server/test_acquisition_adapters.py +++ b/examples/egocap/tests/capture_server/test_acquisition_adapters.py @@ -10,7 +10,9 @@ from __future__ import annotations +import re from functools import partial +from pathlib import Path from types import SimpleNamespace from unittest.mock import patch @@ -122,6 +124,7 @@ def get_data(self, _session: object) -> SimpleNamespace | None: hand_left=False, hand_right=False, manus_enabled=True, + manus_sensors=True, ) adapter = IsaacCaptureAdapter( sdk=sdk, @@ -139,3 +142,95 @@ def get_data(self, _session: object) -> SimpleNamespace | None: np.testing.assert_allclose(fields["manus_left.sensor_positions"][4], [4.0, 4.25, 4.5]) np.testing.assert_allclose(fields["manus_left.sensor_orientations"][4], [0.0, 0.5, 0.0, 1.0]) assert fields["manus_right.sensor_present"] == 0 + + +async def _mock_manus_fields(**selection: bool) -> tuple[list, dict]: + configs = [] + + def session_factory(config): + configs.append(config) + return mock_isaac_capture.TeleopSession(config, scenario="demo", seed=1) + + adapter = IsaacCaptureAdapter( + sdk=mock_isaac_capture, + session_factory=session_factory, + selection=TrackingSelection( + head=True, controller_left=False, controller_right=False, hand_left=True, hand_right=True, **selection + ), + rate_hz=120, + ) + await adapter.enter() + try: + _, fields = await adapter.next_tracking_sample() + finally: + await adapter.close() + return configs, fields + + +async def test_manus_raw_sensors_are_off_unless_requested(): + configs, fields = await _mock_manus_fields(manus_enabled=True) + + assert configs[0].trackers == [] + assert configs[0].plugins[0].plugin_args == [] + assert fields["manus_left.sensor_present"] == 0 + assert fields["manus_right.sensor_present"] == 0 + + +async def test_requested_manus_raw_sensors_select_the_plugin_datasets_and_are_mocked(): + configs, fields = await _mock_manus_fields(manus_enabled=True, manus_sensors=True) + + assert [tracker.collection_id for tracker in configs[0].trackers] == [ + "manus_sensors_left", + "manus_sensors_right", + ] + assert configs[0].plugins[0].plugin_args == ["--datasets=human,sensors"] + for prefix, hand in (("manus_left", "hand_left"), ("manus_right", "hand_right")): + assert fields[f"{prefix}.sensor_present"] == 1 + tips = [joint for joint in mock_isaac_capture.HandJointIndex if joint.name.endswith("_TIP")] + np.testing.assert_allclose(fields[f"{prefix}.sensor_positions"], fields[f"{hand}.joint_positions"][tips]) + + +def test_a_sensor_frame_that_stops_changing_is_no_longer_reported(): + clock = SimpleNamespace(now=10.0) + clock.monotonic = lambda: clock.now + adapter = IsaacCaptureAdapter( + sdk=mock_isaac_capture, + session_factory=mock_isaac_capture.TeleopSession, + selection=TrackingSelection( + head=False, controller_left=False, controller_right=False, hand_left=False, hand_right=False + ), + rate_hz=120, + clock=clock, + ) + frame = mock_isaac_capture.sensor_frame(np.tile([0.1, 0.2, 0.3, 0.0, 0.0, 0.0, 1.0], (5, 1))) + + def present(data) -> int: + return int(adapter._live_sensor_fields("manus_left", data)["manus_left.sensor_present"]) + + assert present(None) == 0 + assert present(frame) == 1 + clock.now += 0.4 + assert present(frame) == 1, "a tick between two pushes repeats the frame" + clock.now += 0.2 + assert present(frame) == 0, "the plugin stopped pushing: the retained frame is not live" + moved = mock_isaac_capture.sensor_frame(np.tile([0.1, 0.2, 0.4, 0.0, 0.0, 0.0, 1.0], (5, 1))) + assert present(moved) == 1 + + +def test_sensor_constants_match_the_plugin_and_the_schema(): + from capture_server.acquisition import isaac_capture + + repo = Path(__file__).resolve().parents[4] + header = (repo / "src/plugins/manus/core/inc/manus/manus_glove_collection.hpp").read_text() + schema = (repo / "src/core/schema/fbs/joint_se3_pose.fbs").read_text() + + collections = dict(re.findall(r'MANUS_SENSORS_(LEFT|RIGHT)_COLLECTION_ID\s*=\s*"([^"]+)"', header)) + assert isaac_capture._MANUS_SENSOR_COLLECTIONS == { + "manus_left": collections["LEFT"], + "manus_right": collections["RIGHT"], + } + joints = re.findall(r"(HAND_RAW_(\w+)_TIP)\s*=\s*(\d+)", schema) + assert tuple(tip for _, tip, _ in joints) == isaac_capture._SENSOR_TIPS + assert {name: int(value) for name, _, value in joints} == { + joint.name: joint.value for joint in mock_isaac_capture.JointName + } diff --git a/examples/egocap/tests/capture_server/test_device_query.py b/examples/egocap/tests/capture_server/test_device_query.py index 077564fece..f011e64b0c 100644 --- a/examples/egocap/tests/capture_server/test_device_query.py +++ b/examples/egocap/tests/capture_server/test_device_query.py @@ -324,6 +324,7 @@ def args(**kwargs): return adapter._manus_args() assert args(manus_enabled=True) == [] + assert args(manus_enabled=True, manus_sensors=True) == ["--datasets=human,sensors"] assert args(manus_enabled=True, manus_left_calibration="/d/l.mcal", manus_right_calibration="/d/r.mcal") == [ "--left-calibration=/d/l.mcal", "--right-calibration=/d/r.mcal", @@ -606,6 +607,25 @@ def test_manus_plugin_config_validates_names(): with pytest.raises(ValueError, match="different files"): ManusPluginConfig(left_calibration="x.mcal", right_calibration="x.mcal") assert ManusPluginConfig().plugin is p.PluginType.MANUS + assert ManusPluginConfig().datasets == (p.ManusDataset.HUMAN,) + + +async def test_begin_carries_the_requested_manus_datasets(station): + url, _, _ = station + client = CaptureClient(url) + started = asyncio.Event() + seen = [] + datasets = (p.ManusDataset.HUMAN, p.ManusDataset.SENSORS) + await client.start( + sources=(p.SourceType.HEAD,), + plugins=(ManusPluginConfig(datasets=datasets),), + on_started=lambda s: (seen.append(s), started.set()), + ) + try: + await asyncio.wait_for(started.wait(), 5) + assert seen[0].effective_config.plugins[0].datasets == datasets + finally: + await client.stop() async def _fake_server(handler, port): diff --git a/examples/egocap/tests/capture_server/test_replay.py b/examples/egocap/tests/capture_server/test_replay.py index 66e7b13ce1..169eadcdc5 100644 --- a/examples/egocap/tests/capture_server/test_replay.py +++ b/examples/egocap/tests/capture_server/test_replay.py @@ -13,6 +13,7 @@ import asyncio import math import shutil +from dataclasses import replace from pathlib import Path import cv2 @@ -327,6 +328,50 @@ def _mean_bgr(frame) -> np.ndarray: return image.reshape(-1, 3).mean(axis=0) +def test_session_serves_the_recorded_raw_sensors_through_the_trackers(episode_dir): + reported = np.tile(np.eye(4), (5, 1, 1)) + reported[:, :3, 3] = [[0.01 * tip, 0.02, 0.03] for tip in range(5)] + reported[:, :3, :3] = tracking_map._rot_z(math.pi / 2) + # The first row reports no sensors; the right glove never does. + left = np.stack([np.zeros((5, 4, 4)), *[reported] * (HAND_ROWS - 1)]) + hands = zarr.open_group(str(episode_dir), mode="r+")["manus_glove"] + _write(hands, "left_sensor_pose", left) + _write(hands, "right_sensor_pose", np.zeros((HAND_ROWS, 5, 4, 4))) + + episode = load_episode(episode_dir) + clock = FakeClock(100.0) + sdk = replay_isaac_capture + trackers = [sdk.JointSe3PoseTracker("manus_sensors_left"), sdk.JointSe3PoseTracker("manus_sensors_right")] + config = replace(_graph(sdk), trackers=trackers) + playback = PlaybackClock(episode.period, clock=clock) + with sdk.TeleopSession(config, episode=episode, playback=playback, clock=clock) as session: + clock.t += 0.02 + session.step() + assert trackers[0].get_data(session.deviceio_session) is None, "an all-zero row is an unreported set" + + clock.t += 0.05 + session.step() + tip = trackers[0].get_data(session.deviceio_session).lookup(sdk.JointName.HAND_RAW_LITTLE_TIP).pose + assert (tip.position.x, tip.position.y, tip.position.z) == pytest.approx((0.04, 0.02, 0.03)) + orientation = (tip.orientation.x, tip.orientation.y, tip.orientation.z, tip.orientation.w) + assert orientation == pytest.approx((0.0, 0.0, math.sqrt(0.5), math.sqrt(0.5))) + assert trackers[1].get_data(session.deviceio_session) is None + + +def test_session_without_recorded_sensors_reports_none(episode_dir): + episode = load_episode(episode_dir) + clock = FakeClock(100.0) + sdk = replay_isaac_capture + tracker = sdk.JointSe3PoseTracker("manus_sensors_left") + config = replace(_graph(sdk), trackers=[tracker]) + with sdk.TeleopSession( + config, episode=episode, playback=PlaybackClock(episode.period, clock=clock), clock=clock + ) as session: + clock.t += 0.07 + session.step() + assert tracker.get_data(session.deviceio_session) is None + + def test_pipeline_serves_due_frames_in_order_skips_overdue_ones_and_loops(episode_dir): episode = load_episode(episode_dir) clock = FakeClock(5.0) diff --git a/examples/egocap/tests/recording/unit/test_alignment.py b/examples/egocap/tests/recording/unit/test_alignment.py index 8cffbd8589..c08d18d30d 100644 --- a/examples/egocap/tests/recording/unit/test_alignment.py +++ b/examples/egocap/tests/recording/unit/test_alignment.py @@ -344,6 +344,24 @@ def test_glove_poses_are_elementwise_linear_never_slerped(): assert "pose" not in rules.values() +@pytest.mark.parametrize("side", ["left", "right"]) +def test_a_sensor_stack_is_never_blended_with_an_unreported_one(side): + assert FRAME_FIELD_RULES["ManusFrame"][f"{side}_sensor_pose"] == "present" + + reported = np.tile(np.eye(4), (5, 1, 1)) + later = reported.copy() + later[:, 0, 3] = 2.0 + times = np.array([0.0, 1.0, 2.0, 3.0]) + values = np.stack([np.zeros((5, 4, 4)), reported, later, np.zeros((5, 4, 4))]) + out = interpolate_field("present", times, values, np.array([0.4, 0.6, 1.5, 2.4, 2.6])) + + assert not out[0].any() and not out[4].any(), "nearer the unreported sample" + np.testing.assert_array_equal(out[1], reported) + np.testing.assert_array_equal(out[3], later) + np.testing.assert_allclose(out[2][:, 0, 3], 1.0) + np.testing.assert_allclose(out[2][:, 3, 3], 1.0) + + @pytest.mark.parametrize("side", ["left", "right"]) def test_glove_sensors_are_linear_and_their_counts_nearest(side): rules = FRAME_FIELD_RULES["ManusFrame"]