"""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}") 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() def _inference_worker(self) -> None: t0 = time.monotonic() while not self._stop.is_set(): try: frame = self.source.read() except Exception: logger.exception("frame source read failed; marking worker crashed") self._worker_crashed.set() return if frame is None: self._source_done.set() return ts_ms = int((time.monotonic() - t0) * 1000) try: pose = self.provider.process(frame, 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 = frame 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._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() if self._worker is not None: self._worker.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 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") args = parser.parse_args(argv) from .pose import MediaPipePoseProvider 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())