Latency bug: Tracker._inference_worker read the camera and ran pose inference in the same synchronous loop, so a slow model frame backs up the camera driver queue and lag grows without bound - the same bug win_main.cpp fixed natively (dedicated capture thread, condition-variable wake, latest- frame-wins, no fixed poll). Added _capture_worker on its own thread, storing only the latest frame behind a lock+condvar; _inference_worker now waits for and consumes the newest capture, never a queued one. run()/stop() start and join both threads. Updated the regression test to drive capture then inference synchronously (both are plain methods, no real threading needed for a deterministic single-frame test). Full suite: 98/98 passing. Co-authored-by: sisyphus-dev-ai <sisyphus-dev-ai@users.noreply.github.com>
290 lines
11 KiB
Python
290 lines
11 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_and_publish():
|
|
"""tracker-native's win_main.cpp mirrors the capture pixel-for-pixel before
|
|
pose inference, matching the Windows reference's actual observed behavior
|
|
(a natural selfie-mirror video in-game); 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 (unmirrored) frame
|
|
instead leaves joint identity already correct on its own, so the shim's
|
|
swap then flips tracking backwards in-game. The published color frame is
|
|
this same mirrored copy (not the raw capture), independent of - and with
|
|
no effect on - skeleton/cursor correctness, which comes only from the
|
|
pose-inference path. 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._capture_worker()
|
|
tracker._inference_worker()
|
|
|
|
assert len(processed_frames) == 1
|
|
expected_mirrored = cv2.flip(frame, 1)
|
|
np.testing.assert_array_equal(processed_frames[0], expected_mirrored)
|
|
np.testing.assert_array_equal(tracker._latest_frame, expected_mirrored)
|
|
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()
|