"""Shared-memory frame publisher for the frozen IPC contract (plan todo 5). `FrameContractPublisher` owns one shared-memory region laid out as: [ FrameContract header + 3 FrameSlots ][ slot0 depth ][ slot0 color ] [ slot1 depth ][ slot1 color ] [ slot2 depth ][ slot2 color ] and publishes one `PoseResult` per call into the triple buffer using the seqlock protocol documented in `core/contract/contract.h`: * write the slot *one ahead* of `published_sequence`, * bump that slot's `sequence` to odd before writing `data`, back to even after (so a reader that sees an odd or changed sequence retries), * then publish by bumping `FrameContract.published_sequence`. This is the *producer* side the C++ core reads with `read_latest_frame`. A matching in-process `read_latest_frame` lives here too so the data path can be round-tripped in a pytest without the C++ build. The skeleton path mirrors core/mapping exactly: MediaPipe 33 landmarks are reduced to Kinect 20 joints, each joint is placed at clamp(Z0 + depthGain * worldZ, 0.8, 4.0), then back-projected through Kinect's depth-camera transform. The C++ synth consumes these placed joint depths to produce an articulated depth surface. """ from __future__ import annotations import ctypes import gc import time from multiprocessing import shared_memory from typing import Optional import numpy as np from .contract import ( CONTRACT_VERSION, FRAME_SLOT_COUNT, JOINT_COUNT, FrameContract, FrameData, JointTrackingState, ) from .joint_mapping import DEFAULT_DEPTH_GAIN, DEFAULT_Z0_METERS, map_pose_to_kinect_joints from .pose import PoseResult # Provisional constant body depth for the silhouette placeholder (millimetres), # inside the Kinect ~[800,4000]mm valid range. Replaced by articulated metric # depth in todo 7. PROVISIONAL_BODY_DEPTH_MM = 2000 MASK_BODY_THRESHOLD = 0.5 PLAYER_INDEX = 1 def pack_depth_word(depth_mm: int, player: int) -> int: """Kinect v1 packed depth word: (mm & 0x1FFF) << 3 | (player & 0x7).""" return ((depth_mm & 0x1FFF) << 3) | (player & 0x7) def _resize_nearest(arr: np.ndarray, out_h: int, out_w: int) -> np.ndarray: """Nearest-neighbour resize (numpy-only, no OpenCV dependency on this path).""" ih, iw = arr.shape[:2] if ih == out_h and iw == out_w: return arr ys = (np.arange(out_h) * ih // out_h).clip(0, ih - 1) xs = (np.arange(out_w) * iw // out_w).clip(0, iw - 1) return arr[ys][:, xs] class FrameContractPublisher: def __init__( self, depth_size: tuple[int, int] = (640, 480), color_size: tuple[int, int] = (640, 480), name: Optional[str] = None, create: bool = True, z0_meters: float = DEFAULT_Z0_METERS, depth_gain: float = DEFAULT_DEPTH_GAIN, mirror: bool = True, ) -> None: self.depth_w, self.depth_h = depth_size self.color_w, self.color_h = color_size self.depth_bytes = self.depth_w * self.depth_h * 2 # 16-bit packed depth word self.color_bytes = self.color_w * self.color_h * 4 # BGRA self._contract_size = ctypes.sizeof(FrameContract) self._slot_pixel_bytes = self.depth_bytes + self.color_bytes self.region_size = self._contract_size + FRAME_SLOT_COUNT * self._slot_pixel_bytes self.shm = shared_memory.SharedMemory(create=create, size=self.region_size, name=name) self.name = self.shm.name self._buf = self.shm.buf self._create = create self.z0_meters = z0_meters self.depth_gain = depth_gain self.mirror = mirror self.contract = FrameContract.from_buffer(self._buf) if create: self.contract.contract_version = CONTRACT_VERSION self.contract.reserved = 0 self.contract.published_sequence = 0 for i in range(FRAME_SLOT_COUNT): self.contract.slots[i].sequence = 0 self._frame_number = 0 self._t0_ns = time.monotonic_ns() def _depth_offset(self, slot_idx: int) -> int: return self._contract_size + slot_idx * self._slot_pixel_bytes def _color_offset(self, slot_idx: int) -> int: return self._depth_offset(slot_idx) + self.depth_bytes def publish(self, pose: Optional[PoseResult], color_bgr: Optional[np.ndarray] = None) -> int: """Publish one frame; returns the new published_sequence. Never blocks.""" next_seq = self.contract.published_sequence + 1 slot_idx = next_seq % FRAME_SLOT_COUNT slot = self.contract.slots[slot_idx] slot.sequence += 1 # odd => writing in progress data = slot.data self._frame_number += 1 data.frame_number = self._frame_number data.timestamp_micros = (time.monotonic_ns() - self._t0_ns) // 1000 self._write_skeleton(data, pose) self._write_descriptors(data, slot_idx) self._write_depth(slot_idx, pose) self._write_color(slot_idx, color_bgr) slot.sequence += 1 # even => write complete self.contract.published_sequence = next_seq return next_seq def _write_skeleton(self, data: FrameData, pose: Optional[PoseResult]) -> None: skel = data.skeleton skel.quality_flags = 0 if pose is None: skel.skeleton_tracking_id = 0 for j in range(JOINT_COUNT): joint = skel.joints[j] joint.position.x = joint.position.y = joint.position.z = 0.0 joint.position.w = 1.0 joint.tracking_state = JointTrackingState.NOT_TRACKED return joints = map_pose_to_kinect_joints( pose, (self.depth_w, self.depth_h), self.z0_meters, self.depth_gain, self.mirror, ) any_tracked = any(joint[4] != JointTrackingState.NOT_TRACKED for joint in joints) skel.skeleton_tracking_id = PLAYER_INDEX if any_tracked else 0 for j, mapped in enumerate(joints): joint = skel.joints[j] joint.position.x = mapped[0] joint.position.y = mapped[1] joint.position.z = mapped[2] joint.position.w = mapped[3] joint.tracking_state = mapped[4] def _write_descriptors(self, data: FrameData, slot_idx: int) -> None: data.depth.width = self.depth_w data.depth.height = self.depth_h data.depth.pitch = self.depth_w * 2 data.depth.byte_offset = self._depth_offset(slot_idx) data.color.width = self.color_w data.color.height = self.color_h data.color.pitch = self.color_w * 4 data.color.byte_offset = self._color_offset(slot_idx) def _write_depth(self, slot_idx: int, pose: Optional[PoseResult]) -> None: off = self._depth_offset(slot_idx) depth = np.zeros((self.depth_h, self.depth_w), dtype=np.uint16) if pose is not None and pose.mask is not None: mask = _resize_nearest(pose.mask, self.depth_h, self.depth_w) body = mask >= MASK_BODY_THRESHOLD depth[body] = pack_depth_word(PROVISIONAL_BODY_DEPTH_MM, PLAYER_INDEX) self._buf[off:off + self.depth_bytes] = np.ascontiguousarray(depth).tobytes() def _write_color(self, slot_idx: int, color_bgr: Optional[np.ndarray]) -> None: off = self._color_offset(slot_idx) if color_bgr is None: self._buf[off:off + self.color_bytes] = bytes(self.color_bytes) return resized = _resize_nearest(color_bgr, self.color_h, self.color_w) alpha = np.full((self.color_h, self.color_w, 1), 255, dtype=np.uint8) bgra = np.concatenate([resized.astype(np.uint8), alpha], axis=2) self._buf[off:off + self.color_bytes] = np.ascontiguousarray(bgra).tobytes() def read_latest_frame(self) -> Optional[FrameData]: """Seqlock snapshot of the newest published frame; None if nothing published.""" for _ in range(16): pub = self.contract.published_sequence if pub == 0: return None slot = self.contract.slots[pub % FRAME_SLOT_COUNT] s1 = slot.sequence if s1 & 1: continue snapshot = FrameData.from_buffer_copy(slot.data) if slot.sequence == s1 and self.contract.published_sequence == pub: return snapshot raise RuntimeError("read_latest_frame could not get a stable snapshot") def read_depth(self, slot_idx: int) -> np.ndarray: off = self._depth_offset(slot_idx) raw = bytes(self._buf[off:off + self.depth_bytes]) return np.frombuffer(raw, dtype=np.uint16).reshape(self.depth_h, self.depth_w).copy() def read_color(self, slot_idx: int) -> np.ndarray: off = self._color_offset(slot_idx) raw = bytes(self._buf[off:off + self.color_bytes]) return np.frombuffer(raw, dtype=np.uint8).reshape(self.color_h, self.color_w, 4).copy() def latest_slot_index(self) -> int: return self.contract.published_sequence % FRAME_SLOT_COUNT def close(self, unlink: Optional[bool] = None) -> None: if self.contract is not None: self.contract = None self._buf = None gc.collect() self.shm.close() if unlink if unlink is not None else self._create: try: self.shm.unlink() except FileNotFoundError: pass def __enter__(self) -> "FrameContractPublisher": return self def __exit__(self, *exc: object) -> None: self.close()