68 lines
2.3 KiB
Python
68 lines
2.3 KiB
Python
"""Python mirror of the C triple-buffer publish/read protocol (plan todo 16).
|
|
|
|
Mirrors ``nui::contract::publish_frame`` / ``read_latest_frame`` from
|
|
core/contract/contract.h against the ctypes ``FrameContract`` in
|
|
tracker/contract.py, so the harness can record frames out of (and replay them
|
|
back into) the real shared-memory frame contract, not a parallel copy of it.
|
|
|
|
Semantics match the header: a single writer publishes by writing the slot one
|
|
ahead of the last published slot and then bumping ``published_sequence``; a
|
|
reader takes ``slots[published_sequence % FRAME_SLOT_COUNT]`` as newest. Only
|
|
one writer may call ``publish``.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ctypes
|
|
import os
|
|
import sys
|
|
|
|
_REPO_ROOT = os.path.dirname(
|
|
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
)
|
|
if _REPO_ROOT not in sys.path:
|
|
sys.path.insert(0, _REPO_ROOT)
|
|
|
|
from tracker.contract import ( # noqa: E402
|
|
CONTRACT_VERSION,
|
|
FRAME_SLOT_COUNT,
|
|
FrameContract,
|
|
FrameData,
|
|
)
|
|
|
|
|
|
def copy_frame(frame: FrameData) -> FrameData:
|
|
"""Return an independent byte-for-byte copy of ``frame``."""
|
|
return FrameData.from_buffer_copy(bytes(frame))
|
|
|
|
|
|
class ContractFrameBuffer:
|
|
"""Single-writer / multi-reader triple buffer over a ctypes ``FrameContract``."""
|
|
|
|
__slots__ = ("_contract",)
|
|
|
|
def __init__(self) -> None:
|
|
self._contract = FrameContract()
|
|
self._contract.contract_version = CONTRACT_VERSION
|
|
|
|
@property
|
|
def published_sequence(self) -> int:
|
|
return self._contract.published_sequence
|
|
|
|
def publish(self, frame: FrameData) -> int:
|
|
"""Publish ``frame`` as the newest slot; returns its sequence number."""
|
|
contract = self._contract
|
|
next_sequence = contract.published_sequence + 1
|
|
slot = contract.slots[next_sequence % FRAME_SLOT_COUNT]
|
|
slot.sequence = next_sequence
|
|
ctypes.memmove(ctypes.byref(slot.data), ctypes.byref(frame), ctypes.sizeof(FrameData))
|
|
contract.published_sequence = next_sequence
|
|
return next_sequence
|
|
|
|
def read_latest(self) -> tuple[int, FrameData]:
|
|
"""Snapshot the newest published frame as ``(sequence, FrameData copy)``."""
|
|
contract = self._contract
|
|
sequence = contract.published_sequence
|
|
slot = contract.slots[sequence % FRAME_SLOT_COUNT]
|
|
return int(slot.sequence), copy_frame(slot.data)
|