"""Webcam -> MediaPipe pose -> IPC publish loop (plan todo 5). Architecture (satisfies the plan's MUST-NOTs): * Capture + inference run on a background thread and cache the latest `(frame, PoseResult)`. The publish loop NEVER blocks on inference - it publishes whatever pose is latest, re-publishing the previous one when inference has not produced a new result yet. * The publish loop paces to a monotonic frame clock (deadline = start + n*period). There are no fixed per-frame sleeps; it waits exactly until the next deadline, so cadence is held regardless of inference jitter. The real pipeline (`MediaPipePoseProvider` + `CvFrameSource`) and the test pipeline (`FakePoseProvider` + `FakeFrameSource`) share this loop through the `PoseProvider` seam and a duck-typed frame source (`read()` -> BGR frame | None). """ from __future__ import annotations import argparse import logging import threading import time from typing import Optional, Protocol from .control import ControlPlaneServer from .pose import PoseProvider, PoseResult from .publisher import FrameContractPublisher logger = logging.getLogger(__name__) class FrameSource(Protocol): def read(self): ... def release(self) -> None: ... class CvFrameSource: """OpenCV capture from a webcam index or a video file path.""" def __init__(self, source) -> None: import cv2 self._cap = cv2.VideoCapture(int(source) if str(source).isdigit() else source) if not self._cap.isOpened(): raise RuntimeError(f"could not open capture source: {source!r}") # V4L2 buffers several frames internally by default (commonly 4-5), so # even a tight read() loop can return a stale, already-buffered frame # rather than the newest one - a second, independent source of latency # beyond the capture/inference decoupling in Tracker._capture_worker. # Forcing a 1-frame buffer makes every read() return the camera's # actual latest frame. tracker-native has no equivalent knob (Media # Foundation's IMFSourceReader is pull-based, not a driver ring buffer), # so this is a genuine Linux/V4L2-specific fix, not a port. self._cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) def read(self): ok, frame = self._cap.read() return frame if ok else None def release(self) -> None: self._cap.release() class Tracker: def __init__( self, source: FrameSource, provider: PoseProvider, publisher: FrameContractPublisher, control: Optional[ControlPlaneServer] = None, target_fps: float = 30.0, player_lost_hold_frames: int = 15, ) -> None: self.source = source self.provider = provider self.publisher = publisher self.control = control self.target_fps = target_fps # IS-8: when the subject leaves frame (provider yields no pose), hold the # last tracked pose for a short number of publish ticks before falling # through to a no-body frame, so a brief occlusion/exit doesn't flap the # player-lost state. Recovery on return is immediate (first fresh pose # wins), never delayed. self.player_lost_hold_frames = player_lost_hold_frames # Liveness bound derived from the configured cadence (not a sleep/ # delay): if the worker's heartbeat (_update_count) hasn't moved for # this long, it is stalled, independent of whether it later recovers. self._stall_timeout = max(5.0 / target_fps, 0.25) self._lock = threading.Lock() self._latest_pose: Optional[PoseResult] = None self._latest_frame = None self._stop = threading.Event() self._source_done = threading.Event() self._worker: Optional[threading.Thread] = None # Heartbeat from the inference worker: bumped on every completed read+ # infer cycle (whether or not a pose was found), so the publish loop can # tell "no person in frame" (update_count keeps moving, pose is None) # apart from "the worker stalled/crashed" (update_count stops moving). self._update_count = 0 self._worker_crashed = threading.Event() self._hold_pose: Optional[PoseResult] = None self._hold_remaining = 0 self._last_update_count = -1 self._last_update_time = time.monotonic() # Dedicated capture thread (matching tracker-native's win_main.cpp): # decouples camera reads from inference so a slow model doesn't back up # the driver's frame queue and grow latency unboundedly. The inference # loop always consumes the newest captured frame, never a queued one. self._cap_lock = threading.Lock() self._cap_cv = threading.Condition(self._cap_lock) self._cap_frame = None self._cap_seq = 0 self._cap_thread: Optional[threading.Thread] = None def _capture_worker(self) -> None: while not self._stop.is_set(): try: frame = self.source.read() except Exception: logger.exception("capture read failed; marking worker crashed") self._worker_crashed.set() return if frame is None: self._source_done.set() with self._cap_cv: self._cap_cv.notify_all() return with self._cap_cv: self._cap_frame = frame self._cap_seq += 1 self._cap_cv.notify_all() def _inference_worker(self) -> None: t0 = time.monotonic() last_seq = 0 while not self._stop.is_set(): with self._cap_cv: got = self._cap_cv.wait_for( lambda: self._cap_seq != last_seq or self._stop.is_set() or self._source_done.is_set(), timeout=1.0, ) if self._stop.is_set(): return if not got: continue if self._cap_seq == last_seq: # Woken only by source_done with no new frame ever captured. return frame = self._cap_frame last_seq = self._cap_seq import cv2 # Mirror horizontally before pose inference, matching # tracker-native's win_main.cpp: the pose model sees a mirrored # frame, which flips which side MediaPipe calls "left"/"right" for # the subject; core/mapping's own coordinate mirror stays off # (FrameContractPublisher's mirror=False) since this physical flip # already does that job, and the shim's unconditional L/R swap # (fallback/windows-nui/src/sensor.cpp) corrects MediaPipe's # resulting mislabeling. Running pose on the raw (unmirrored) frame # instead - as this tracker used to - leaves joint identity already # correct on its own, so the shim's swap then flips it backwards: # left/right tracking reversed in-game. # # The published color frame is this SAME mirrored copy, not the raw # capture: the user's live Windows reference showed a natural # selfie-mirror video in-game, and the published color buffer is # fully independent of skeleton/cursor correctness (which comes # only from the pose-inference path above), so mirroring it here # carries no correctness risk. mirrored = cv2.flip(frame, 1) ts_ms = int((time.monotonic() - t0) * 1000) try: pose = self.provider.process(mirrored, timestamp_ms=ts_ms) except Exception: logger.exception("pose inference failed; marking worker crashed") self._worker_crashed.set() return with self._lock: self._latest_frame = mirrored self._latest_pose = pose self._update_count += 1 def _resolve_publish_frame(self): """One publish tick's fault-handling decision (IS-8): the fresh pose, a briefly held last-good pose across a player-exit, or a safe no-player state once the hold expires or the worker is stalled/ crashed. Pure state transition over `self`'s latched fields, so tests can drive it deterministically without racing the inference thread. """ with self._lock: pose = self._latest_pose frame = self._latest_frame update_count = self._update_count now = time.monotonic() if update_count != self._last_update_count: self._last_update_count = update_count self._last_update_time = now worker_stalled = ( self._worker_crashed.is_set() or (now - self._last_update_time) > self._stall_timeout ) if worker_stalled: # Crashed or stalled tracker: never keep serving a frozen stale # frame - the consumer must see a safe no-player state instead. pose = None self._hold_pose = None self._hold_remaining = 0 elif pose is not None: self._hold_pose = pose self._hold_remaining = self.player_lost_hold_frames elif self._hold_remaining > 0: pose = self._hold_pose self._hold_remaining -= 1 return pose, frame def run( self, max_frames: Optional[int] = None, max_seconds: Optional[float] = None, status_interval: Optional[float] = 2.0, ) -> int: # The tracker has no GUI (that only exists in the Windows-only # tracker-native/) and otherwise produces zero output, so a working run # looks identical to a silently stuck one. Print a status line every # status_interval seconds (None disables it, e.g. for tests) so a # terminal run shows live confirmation instead of nothing. self._cap_thread = threading.Thread(target=self._capture_worker, name="capture", daemon=True) self._cap_thread.start() self._worker = threading.Thread(target=self._inference_worker, name="inference", daemon=True) self._worker.start() period = 1.0 / self.target_fps start = time.monotonic() published = 0 last_status = start while not self._stop.is_set(): deadline = start + published * period now = time.monotonic() if now < deadline: self._stop.wait(deadline - now) if self._stop.is_set(): break pose, frame = self._resolve_publish_frame() seq = self.publisher.publish(pose, frame) if self.control is not None: self.control.send_heartbeat(seq) published += 1 now = time.monotonic() if status_interval is not None and now - last_status >= status_interval: elapsed = now - start fps = published / elapsed if elapsed > 0 else 0.0 print( f"[tracker] frame={published} fps={fps:.1f} " f"player={'tracked' if pose is not None else 'lost'} seq={seq}", flush=True, ) last_status = now if max_frames is not None and published >= max_frames: break if max_seconds is not None and (time.monotonic() - start) >= max_seconds: break if self._source_done.is_set(): break self.stop() return published def stop(self) -> None: self._stop.set() with self._cap_cv: self._cap_cv.notify_all() if self._worker is not None: self._worker.join(timeout=1.0) if self._cap_thread is not None: self._cap_thread.join(timeout=1.0) def measure_fps(provider: PoseProvider, frame, iterations: int = 60) -> float: """Time `iterations` inferences on one frame; returns achieved fps.""" for _ in range(3): provider.process(frame, timestamp_ms=None) start = time.monotonic() for _ in range(iterations): provider.process(frame, timestamp_ms=None) elapsed = time.monotonic() - start return iterations / elapsed if elapsed > 0 else float("inf") def _parse_size(text: str) -> tuple[int, int]: w, h = text.lower().split("x") return int(w), int(h) def calibrate_cursor( source: FrameSource, provider: PoseProvider, depth_size: tuple[int, int], hold_seconds: float = 1.8, ) -> int: """Port of tracker-native's win_main.cpp CalibrateCursor(): mirror each frame for pose inference (same as the main loop), compute Kinect joints with mirror=False (the physical flip already did that job), and read HAND_LEFT (index 7) minus SHOULDER_LEFT (index 4) - the slots the player's actual right arm lands in post-mirror, pre-shim-swap, exactly where win_main.cpp reads skeleton.joints[7]/[4]. Prints the same "Calibrated cursor gains X=... Y=... (saved)" / "Calibration failed: ..." status text the native tracker's status line shows.""" import cv2 from . import calibration as cal from .joint_mapping import map_pose_to_kinect_joints print( "Calibrating cursor: raise your right arm up and out toward the top " "corner of the screen - hand clearly above your shoulder and out to " "the side...", flush=True, ) samples: list[tuple[float, float]] = [] deadline = time.monotonic() + hold_seconds while time.monotonic() < deadline: frame = source.read() if frame is None: break mirrored = cv2.flip(frame, 1) pose = provider.process(mirrored, timestamp_ms=None) if pose is None: continue joints = map_pose_to_kinect_joints(pose, depth_size, mirror=False) hand = joints[7] shoulder = joints[4] samples.append((hand[0] - shoulder[0], hand[1] - shoulder[1])) gains, error = cal.derive_arm_gains(samples) if gains is None: print(f"Calibration failed: {error}", flush=True) return 1 path = cal.calibration_config_path() config = cal.load_config(path) or cal.CalibrationConfig() config.arm_gain_x = gains.x config.arm_gain_y = gains.y cal.save_config(config, path) print( f"Calibrated cursor gains X={gains.x:.6f} Y={gains.y:.6f} " f"(saved to {path})", flush=True, ) print( "Set KINECT_SHIM_CONFIG to this same path (reachable from Wine via its " "Z: drive) in the game's launch options so the shim reads it.", flush=True, ) return 0 def main(argv: Optional[list[str]] = None) -> int: parser = argparse.ArgumentParser(description="Webcam -> MediaPipe pose -> Kinect IPC contract publisher") parser.add_argument("--source", default="0", help="webcam index (e.g. 0) or video file path") parser.add_argument("--model", default="full", help="pose model tier (lite/full/heavy) or .task path") parser.add_argument("--models-dir", default=None, help="directory holding the .task model bundles") parser.add_argument("--target-fps", type=float, default=30.0) parser.add_argument("--depth-size", type=_parse_size, default=(640, 480)) parser.add_argument("--color-size", type=_parse_size, default=(640, 480)) parser.add_argument("--shm-name", default="virtual_kinect_frames") parser.add_argument("--control-socket", default=None, help="unix socket path for the control plane") parser.add_argument("--max-frames", type=int, default=None) parser.add_argument("--max-seconds", type=float, default=None) parser.add_argument("--measure-fps", action="store_true", help="benchmark lite/full/heavy and exit") parser.add_argument( "--calibrate", action="store_true", help="run the guided cursor arm-reach calibration and exit (writes the " "shim's shared calibration.cfg; stand at your playing distance and " "raise your right arm up and out when prompted)", ) args = parser.parse_args(argv) from .pose import MediaPipePoseProvider if args.calibrate: source = CvFrameSource(args.source) provider = MediaPipePoseProvider(model=args.model, models_dir=args.models_dir) try: return calibrate_cursor(source, provider, args.depth_size) finally: source.release() provider.close() if args.measure_fps: source = CvFrameSource(args.source) frame = source.read() source.release() if frame is None: print("measure-fps: could not read a frame from source") return 1 for tier in ("lite", "full", "heavy"): provider = MediaPipePoseProvider(model=tier, models_dir=args.models_dir) fps = measure_fps(provider, frame) provider.close() print(f"{tier}: {fps:.1f} fps") return 0 # No GUI on this path (camera picker / live preview only exist in the # Windows-only tracker-native/); print confirmation so a terminal run # shows the camera actually opened instead of silently doing nothing. print(f"[tracker] opening camera source={args.source!r} ...", flush=True) source = CvFrameSource(args.source) print(f"[tracker] camera opened; loading pose model (tier/path={args.model!r}) ...", flush=True) provider = MediaPipePoseProvider(model=args.model, models_dir=args.models_dir) publisher = FrameContractPublisher( depth_size=args.depth_size, color_size=args.color_size, name=args.shm_name ) print( f"[tracker] publishing to shared memory '{args.shm_name}' " f"({args.depth_size[0]}x{args.depth_size[1]} depth, " f"{args.color_size[0]}x{args.color_size[1]} color) at {args.target_fps} fps target", flush=True, ) control = None if args.control_socket: control = ControlPlaneServer(args.control_socket) control.start() tracker = Tracker(source, provider, publisher, control=control, target_fps=args.target_fps) try: published = tracker.run(max_frames=args.max_frames, max_seconds=args.max_seconds) print(f"published {published} frames to shm {publisher.name!r}") finally: tracker.stop() source.release() provider.close() publisher.close() if control is not None: control.close() return 0 if __name__ == "__main__": raise SystemExit(main())