The in-game skeleton/cursor tracking was left/right reversed. Root cause: tracker-native's win_main.cpp physically mirrors the captured frame (pixel-level horizontal flip) before pose inference, but publishes the raw unmirrored frame as the color stream, and runs its mapper with cal_mapping_cfg.mirror=false (verified by reading win_main.cpp and core/mapping.cpp directly). The shim's unconditional L/R joint swap (fallback/windows-nui/src/sensor.cpp) then corrects MediaPipe's resulting left/right mislabeling. The Python tracker never physically mirrored the capture - it only applied a coordinate-level flip (1-u) in joint_mapping.py, with FrameContractPublisher defaulting mirror=True. That left joint identity already correct on its own (no image mirror -> no MediaPipe mislabeling -> no swap needed), so the shim's unconditional swap then flipped it backwards: the exact "tracking is backwards" symptom. Fix: Tracker._inference_worker now mirrors the frame (cv2.flip) before handing it to the pose provider, exactly like win_main.cpp, while keeping the raw frame for self._latest_frame (the published color stream). FrameContractPublisher's mirror default changes to False to match cal_mapping_cfg.mirror=false, so the physical flip isn't double-applied. New regression test calls the real Tracker._inference_worker directly (not a reimplementation) with an asymmetric synthetic frame and asserts the pose provider receives the mirrored version while the stored/published frame stays unmirrored. Updated test_publish_and_read_back_fake_pose to compute its independent expectation with the publisher's actual mirror setting instead of assuming it matches joint_mapping's own default. Full suite: 11/11 passing. Co-authored-by: sisyphus-dev-ai <sisyphus-dev-ai@users.noreply.github.com>
284 lines
10 KiB
Python
284 lines
10 KiB
Python
"""Data-path tests for the webcam tracker (plan todo 5).
|
|
|
|
These exercise landmarks -> contract packing -> shared-memory publish -> read
|
|
back entirely with the fake pose provider, so the IPC path is verified without
|
|
MediaPipe. A live MediaPipe run is a separate smoke script, not a unit test.
|
|
"""
|
|
|
|
import ctypes
|
|
import os
|
|
import socket
|
|
import sys
|
|
import time
|
|
|
|
import numpy as np
|
|
import pytest
|
|
|
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
sys.path.insert(0, ROOT)
|
|
|
|
from tracker import contract as c # noqa: E402
|
|
from tracker import control # noqa: E402
|
|
from tracker.fake_pose import FakeFrameSource, FakePoseProvider, make_fake_pose # noqa: E402
|
|
from tracker.joint_mapping import map_pose_to_kinect_joints # noqa: E402
|
|
from tracker.publisher import ( # noqa: E402
|
|
PROVISIONAL_BODY_DEPTH_MM,
|
|
FrameContractPublisher,
|
|
pack_depth_word,
|
|
)
|
|
from tracker.tracker import Tracker # noqa: E402
|
|
|
|
|
|
@pytest.fixture
|
|
def publisher():
|
|
pub = FrameContractPublisher(depth_size=(160, 120), color_size=(160, 120))
|
|
try:
|
|
yield pub
|
|
finally:
|
|
pub.close()
|
|
|
|
|
|
def test_region_layout_and_version(publisher):
|
|
expected = ctypes.sizeof(c.FrameContract) + c.FRAME_SLOT_COUNT * (
|
|
publisher.depth_bytes + publisher.color_bytes
|
|
)
|
|
assert publisher.region_size == expected
|
|
assert publisher.contract.contract_version == c.CONTRACT_VERSION
|
|
assert publisher.contract.published_sequence == 0
|
|
assert publisher.read_latest_frame() is None
|
|
|
|
|
|
def test_publish_and_read_back_fake_pose(publisher):
|
|
pose = make_fake_pose(frame_index=0, image_width=160, image_height=120)
|
|
color = np.full((120, 160, 3), 200, dtype=np.uint8)
|
|
|
|
seq = publisher.publish(pose, color)
|
|
assert seq == 1
|
|
assert publisher.contract.published_sequence == 1
|
|
|
|
frame = publisher.read_latest_frame()
|
|
assert frame is not None
|
|
assert frame.frame_number == 1
|
|
assert frame.skeleton.skeleton_tracking_id == 1
|
|
|
|
mapped = map_pose_to_kinect_joints(pose, (160, 120), mirror=publisher.mirror)
|
|
for j in range(c.JOINT_COUNT):
|
|
joint = frame.skeleton.joints[j]
|
|
assert joint.position.x == pytest.approx(mapped[j][0], abs=1e-5)
|
|
assert joint.position.y == pytest.approx(mapped[j][1], abs=1e-5)
|
|
assert joint.position.z == pytest.approx(mapped[j][2], abs=1e-5)
|
|
assert joint.position.w == pytest.approx(1.0)
|
|
assert joint.tracking_state == c.JointTrackingState.TRACKED
|
|
|
|
assert frame.depth.width == 160 and frame.depth.height == 120
|
|
assert frame.color.width == 160 and frame.color.height == 120
|
|
assert frame.depth.pitch == 160 * 2
|
|
assert frame.color.pitch == 160 * 4
|
|
|
|
slot = publisher.latest_slot_index()
|
|
depth = publisher.read_depth(slot)
|
|
body_word = pack_depth_word(PROVISIONAL_BODY_DEPTH_MM, 1)
|
|
assert int(depth.max()) == body_word
|
|
assert np.count_nonzero(depth) > 0
|
|
assert np.count_nonzero(depth == 0) > 0
|
|
|
|
color_out = publisher.read_color(slot)
|
|
assert color_out.shape == (120, 160, 4)
|
|
assert np.all(color_out[:, :, 3] == 255)
|
|
assert int(color_out[:, :, 0].max()) == 200
|
|
|
|
|
|
def test_inference_worker_mirrors_frame_for_pose_but_not_for_publish():
|
|
"""tracker-native's win_main.cpp mirrors the capture pixel-for-pixel before
|
|
pose inference, but publishes the raw (unmirrored) frame as the color
|
|
stream; the shim's L/R joint swap then corrects MediaPipe's resulting
|
|
left/right mislabeling. The Python tracker must match that exactly - running
|
|
pose on the raw frame instead leaves joint identity already correct on its
|
|
own, so the shim's swap then flips tracking backwards in-game. Calls the
|
|
real Tracker._inference_worker (not a reimplementation) directly, bypassing
|
|
run()'s threaded pacing so the assertion is deterministic."""
|
|
import cv2
|
|
|
|
width, height = 10, 4
|
|
frame = np.zeros((height, width, 3), dtype=np.uint8)
|
|
frame[:, : width // 2] = 10
|
|
frame[:, width // 2 :] = 200
|
|
|
|
class OneFrameSource:
|
|
def __init__(self):
|
|
self._served = False
|
|
|
|
def read(self):
|
|
if self._served:
|
|
return None
|
|
self._served = True
|
|
return frame
|
|
|
|
def release(self):
|
|
pass
|
|
|
|
processed_frames = []
|
|
|
|
class SpyProvider:
|
|
def process(self, frame_bgr, timestamp_ms=None):
|
|
processed_frames.append(frame_bgr.copy())
|
|
return None
|
|
|
|
def close(self):
|
|
pass
|
|
|
|
publisher = FrameContractPublisher(depth_size=(160, 120), color_size=(160, 120))
|
|
try:
|
|
tracker = Tracker(OneFrameSource(), SpyProvider(), publisher)
|
|
tracker._inference_worker()
|
|
|
|
assert len(processed_frames) == 1
|
|
np.testing.assert_array_equal(processed_frames[0], cv2.flip(frame, 1))
|
|
np.testing.assert_array_equal(tracker._latest_frame, frame)
|
|
finally:
|
|
publisher.close()
|
|
|
|
|
|
def test_joint_depth_uses_z0_placement_and_has_body_relief(publisher):
|
|
pose = make_fake_pose(frame_index=0, image_width=160, image_height=120)
|
|
publisher.publish(pose, None)
|
|
|
|
frame = publisher.read_latest_frame()
|
|
depths_mm = [
|
|
round(frame.skeleton.joints[index].position.z * 1000)
|
|
for index in range(c.JOINT_COUNT)
|
|
]
|
|
assert min(depths_mm) >= 800
|
|
assert max(depths_mm) <= 4000
|
|
assert max(depths_mm) - min(depths_mm) >= 100
|
|
|
|
|
|
def test_no_person_publishes_no_body_frame(publisher):
|
|
seq = publisher.publish(None, None)
|
|
assert seq == 1
|
|
|
|
frame = publisher.read_latest_frame()
|
|
assert frame is not None
|
|
assert frame.skeleton.skeleton_tracking_id == 0
|
|
for j in range(c.JOINT_COUNT):
|
|
joint = frame.skeleton.joints[j]
|
|
assert joint.tracking_state == c.JointTrackingState.NOT_TRACKED
|
|
assert joint.position.x == 0.0 and joint.position.y == 0.0 and joint.position.z == 0.0
|
|
|
|
depth = publisher.read_depth(publisher.latest_slot_index())
|
|
assert int(depth.max()) == 0
|
|
|
|
|
|
def test_low_visibility_marks_inferred_and_not_tracked(publisher):
|
|
# Joints 4/5/6 (SHOULDER_LEFT/ELBOW_LEFT/WRIST_LEFT) map directly from a
|
|
# single MediaPipe landmark each (11/13/15, nui-contracts.md section 1.2),
|
|
# so their tracking state follows that one landmark's visibility exactly.
|
|
pose = make_fake_pose(image_width=160, image_height=120)
|
|
pose.visibility[11] = 0.0
|
|
pose.visibility[13] = 0.2
|
|
pose.visibility[15] = 0.9
|
|
|
|
publisher.publish(pose, None)
|
|
frame = publisher.read_latest_frame()
|
|
assert frame.skeleton.joints[4].tracking_state == c.JointTrackingState.NOT_TRACKED
|
|
assert frame.skeleton.joints[5].tracking_state == c.JointTrackingState.INFERRED
|
|
assert frame.skeleton.joints[6].tracking_state == c.JointTrackingState.TRACKED
|
|
|
|
|
|
def test_sequence_increments_newest_wins(publisher):
|
|
for i in range(7):
|
|
publisher.publish(make_fake_pose(frame_index=i, image_width=160, image_height=120), None)
|
|
assert publisher.contract.published_sequence == 7
|
|
frame = publisher.read_latest_frame()
|
|
assert frame.frame_number == 7
|
|
|
|
|
|
def test_tracker_loop_paces_to_monotonic_clock():
|
|
publisher = FrameContractPublisher(depth_size=(80, 60), color_size=(80, 60))
|
|
source = FakeFrameSource(n_frames=None, width=80, height=60)
|
|
provider = FakePoseProvider(image_width=80, image_height=60)
|
|
tracker = Tracker(source, provider, publisher, target_fps=50.0)
|
|
|
|
period = 1.0 / 50.0
|
|
start = time.monotonic()
|
|
published = tracker.run(max_frames=5)
|
|
elapsed = time.monotonic() - start
|
|
try:
|
|
assert published == 5
|
|
assert publisher.contract.published_sequence == 5
|
|
assert elapsed >= 4 * period * 0.7
|
|
frame = publisher.read_latest_frame()
|
|
assert frame.skeleton.skeleton_tracking_id == 1
|
|
finally:
|
|
source.release()
|
|
publisher.close()
|
|
|
|
|
|
def test_tracker_loop_stops_at_source_end_without_crash():
|
|
publisher = FrameContractPublisher(depth_size=(80, 60), color_size=(80, 60))
|
|
source = FakeFrameSource(n_frames=4, width=80, height=60)
|
|
provider = FakePoseProvider(image_width=80, image_height=60, no_person=True)
|
|
tracker = Tracker(source, provider, publisher, target_fps=200.0)
|
|
try:
|
|
published = tracker.run(max_frames=1000)
|
|
assert published >= 1
|
|
frame = publisher.read_latest_frame()
|
|
assert frame.skeleton.skeleton_tracking_id == 0
|
|
finally:
|
|
source.release()
|
|
publisher.close()
|
|
|
|
|
|
def test_control_messages_roundtrip():
|
|
a, b = socket.socketpair()
|
|
try:
|
|
a.sendall(control.build_handshake(client_version=c.CONTRACT_VERSION, capabilities=7))
|
|
raw = b.recv(ctypes.sizeof(c.HandshakeMessage))
|
|
msg = control.parse_message(raw)
|
|
assert isinstance(msg, c.HandshakeMessage)
|
|
assert msg.header.message_type == c.ControlMessageType.HANDSHAKE_VERSION
|
|
assert msg.header.contract_version == c.CONTRACT_VERSION
|
|
assert msg.capabilities == 7
|
|
|
|
a.sendall(control.build_heartbeat(sequence=42, timestamp_micros=123456))
|
|
raw = b.recv(ctypes.sizeof(c.HeartbeatMessage))
|
|
hb = control.parse_message(raw)
|
|
assert isinstance(hb, c.HeartbeatMessage)
|
|
assert hb.header.message_type == c.ControlMessageType.HEARTBEAT
|
|
assert hb.sequence == 42
|
|
assert hb.timestamp_micros == 123456
|
|
finally:
|
|
a.close()
|
|
b.close()
|
|
|
|
|
|
def test_control_server_handshake_then_heartbeat(tmp_path):
|
|
sock_path = str(tmp_path / "control.sock")
|
|
server = control.ControlPlaneServer(sock_path)
|
|
server.start()
|
|
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
client.settimeout(2.0)
|
|
try:
|
|
deadline = time.monotonic() + 2.0
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
client.connect(sock_path)
|
|
break
|
|
except (FileNotFoundError, ConnectionRefusedError):
|
|
continue
|
|
else:
|
|
pytest.fail("could not connect to control server")
|
|
|
|
raw = client.recv(ctypes.sizeof(c.HandshakeMessage))
|
|
msg = control.parse_message(raw)
|
|
assert isinstance(msg, c.HandshakeMessage)
|
|
|
|
assert server.send_heartbeat(99) is True
|
|
raw = client.recv(ctypes.sizeof(c.HeartbeatMessage))
|
|
hb = control.parse_message(raw)
|
|
assert isinstance(hb, c.HeartbeatMessage)
|
|
assert hb.sequence == 99
|
|
finally:
|
|
client.close()
|
|
server.close()
|