From e6d4e510d3ed3105cf856d5b0dbc4ad5e586e638 Mon Sep 17 00:00:00 2001 From: kinect-bot Date: Wed, 25 Nov 2026 03:54:41 -0500 Subject: [PATCH] feat(contract,spikes): frozen IPC data contract + Linux/Windows spikes (wave 2) --- CMakeLists.txt | 12 +- core/contract/README.md | 22 +- core/contract/contract.cpp | 30 +- core/contract/contract.h | 264 ++++++++++++++++- core/contract/contract_layout_dump.cpp | 100 +++++++ docs/spike-linux.md | 380 +++++++++++++++++++++++++ docs/spike-windows.md | 349 +++++++++++++++++++++++ tests/test_contract.cpp | 88 ++++++ tests/test_contract_py.py | 123 ++++++++ tests/test_core.cpp | 2 +- tracker/contract.py | 167 +++++++++++ 11 files changed, 1523 insertions(+), 14 deletions(-) create mode 100644 core/contract/contract_layout_dump.cpp create mode 100644 docs/spike-linux.md create mode 100644 docs/spike-windows.md create mode 100644 tests/test_contract.cpp create mode 100644 tests/test_contract_py.py create mode 100644 tracker/contract.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 6554b31..2b07069 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -20,7 +20,15 @@ set_target_properties(libnui_core PROPERTIES PREFIX "" OUTPUT_NAME "libnui_core" target_include_directories(libnui_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/core) # --------------------------------------------------------------------------- -# Tests: GoogleTest via FetchContent + CTest. One trivial passing test today. +# contract_layout_dump: prints the frozen contract's sizeof/offsetof golden +# table so tests/test_contract_py.py can check the Python ctypes mirror +# against the CURRENT C layout instead of a hardcoded, driftable copy. +# --------------------------------------------------------------------------- +add_executable(contract_layout_dump core/contract/contract_layout_dump.cpp) +target_link_libraries(contract_layout_dump PRIVATE libnui_core) + +# --------------------------------------------------------------------------- +# Tests: GoogleTest via FetchContent + CTest. # --------------------------------------------------------------------------- option(NUI_CORE_BUILD_TESTS "Build libnui_core unit tests" ON) if(NUI_CORE_BUILD_TESTS) @@ -36,7 +44,7 @@ if(NUI_CORE_BUILD_TESTS) FetchContent_MakeAvailable(googletest) enable_testing() - add_executable(libnui_core_tests tests/test_core.cpp) + add_executable(libnui_core_tests tests/test_core.cpp tests/test_contract.cpp) target_link_libraries(libnui_core_tests PRIVATE libnui_core GTest::gtest_main) include(GoogleTest) diff --git a/core/contract/README.md b/core/contract/README.md index 7d4c75d..333bb22 100644 --- a/core/contract/README.md +++ b/core/contract/README.md @@ -1,8 +1,20 @@ # core/contract/ — frozen, versioned IPC data contract (todo 2) -Shared-memory frame contract (C header + generated Python mirror): triple-buffered -newest-wins slot with a monotonic sequence counter, skeleton + depth/player-index + -color buffer descriptors, frame number, QPC timestamp, and a named-pipe/socket control -schema. `static_assert` on every struct size/offset; embedded contract-version constant. +Shared-memory frame contract (`contract.h`/`contract.cpp` + the ctypes mirror in +`tracker/contract.py`): a triple-buffered, newest-wins `FrameContract` with a +monotonic (seqlock-style) sequence counter guarding each slot, a 20-joint +`SkeletonFrame` (position + per-joint tracking state + tracking id + quality +flags), depth/player-index and color buffer descriptors, a frame number, a +QPC-style monotonic `timestamp_micros`, and a named-pipe/socket control-plane +message schema (`HANDSHAKE_VERSION`/`CONFIG`/`CALIBRATION`/`HEARTBEAT`, each +behind a versioned `ControlMessageHeader`). -Placeholder only until todo 2. +Every struct is `#pragma pack(push, 1)`-packed with no implicit padding, and +`static_assert`s in `contract.h` pin each struct's `sizeof`/`offsetof` to a +golden table; `contract_layout_dump` (built alongside the library) prints that +same table so `tests/test_contract_py.py` can check the Python mirror against +the CURRENT compiled C layout rather than a hardcoded, driftable copy. +`CONTRACT_VERSION` bumps only via an explicit contract-version commit. + +Frame data never travels on the control channel - only handshake/config/ +calibration/heartbeat messages do. diff --git a/core/contract/contract.cpp b/core/contract/contract.cpp index 6c02ad7..10cd583 100644 --- a/core/contract/contract.cpp +++ b/core/contract/contract.cpp @@ -2,9 +2,33 @@ namespace nui::contract { -int contract_version() { - // v0: scaffold placeholder; frozen layout defined in todo 2. - return 0; +int contract_version() { return static_cast(kContractVersion); } + +void publish_frame(FrameContract& contract, const FrameData& data) { + const uint64_t next_sequence = contract.published_sequence + 1; + FrameSlot& slot = contract.slots[next_sequence % kFrameSlotCount]; + // Seqlock parity: odd while writing, even once `data` is fully written. + slot.sequence = next_sequence * 2 - 1; + slot.data = data; + slot.sequence = next_sequence * 2; + contract.published_sequence = next_sequence; +} + +void read_latest_frame(const FrameContract& contract, FrameData& out) { + for (;;) { + const uint64_t published = contract.published_sequence; + const FrameSlot& slot = contract.slots[published % kFrameSlotCount]; + const uint64_t seq_before = slot.sequence; + if (seq_before != published * 2) { + continue; // mid-write (odd) or stale slot; retry against the current publish + } + FrameData snapshot = slot.data; + const uint64_t seq_after = slot.sequence; + if (seq_after == seq_before) { + out = snapshot; + return; + } + } } } // namespace nui::contract diff --git a/core/contract/contract.h b/core/contract/contract.h index 467bb12..4b8e4b1 100644 --- a/core/contract/contract.h +++ b/core/contract/contract.h @@ -1,14 +1,272 @@ #ifndef NUI_CORE_CONTRACT_H #define NUI_CORE_CONTRACT_H -// Placeholder for the frozen, versioned IPC data contract (plan todo 2). -// The real triple-buffered frame structs + static_asserts arrive there. +// Frozen, versioned IPC data contract (plan todo 2). +// +// This header is the single source of truth for the shared-memory frame layout +// and the control-plane message schema shared between the tracker (producer), +// the synth/protocol emitter (consumer), and the Python mirror in +// tracker/contract.py. It is frozen from this commit: any field-shape change is +// an explicit CONTRACT_VERSION bump, never a silent edit, because the Python +// mirror does not re-derive this layout - it hardcodes the same golden values +// and a test cross-checks them. +// +// Packing: every struct in this header is declared under +// `#pragma pack(push, 1)` so there is no compiler- or platform-dependent +// implicit padding; every field is placed at a fixed, documented byte offset. +// This trades natural alignment for cross-language, cross-compiler layout +// determinism, which this IPC boundary needs more than it needs aligned +// access (frames are copied, not hot-looped over field-by-field). +// +// Transport model (see .omo/design/architecture.md "Transport"): the frame +// side is a lock-free, single-writer / multi-reader triple buffer with a +// monotonic sequence counter (seqlock-style: writer always writes one slot +// ahead of the last published slot, then bumps `sequence`; a reader snapshots +// `sequence`, reads the indicated slot, and retries if `sequence` moved +// during the read). The control side is a named-pipe/socket message schema +// carrying ONLY handshake/config/calibration/heartbeat traffic - never +// per-frame data. + +#include +#include namespace nui::contract { -// Contract schema version. Bumped only via an explicit contract-version commit (todo 2). +// Contract schema version. Bump only via an explicit contract-version commit; +// every golden size/offset constant below is pinned to this version's layout. +constexpr uint32_t kContractVersion = 1; + int contract_version(); +// Number of Kinect v1 skeleton joints (NUI_SKELETON_POSITION_COUNT). +constexpr std::size_t kJointCount = 20; + +// Number of frame slots in the triple buffer. +constexpr std::size_t kFrameSlotCount = 3; + +#pragma pack(push, 1) + +// --- Skeleton ------------------------------------------------------------- + +// A homogeneous 3D point, matching Kinect's NUI Vector4 (x, y, z, w=1.0). +struct Vector4 { + float x; + float y; + float z; + float w; +}; +static_assert(sizeof(Vector4) == 16, "Vector4 golden size"); +static_assert(offsetof(Vector4, x) == 0, "Vector4.x golden offset"); +static_assert(offsetof(Vector4, y) == 4, "Vector4.y golden offset"); +static_assert(offsetof(Vector4, z) == 8, "Vector4.z golden offset"); +static_assert(offsetof(Vector4, w) == 12, "Vector4.w golden offset"); + +// Per-joint tracking state (NUI_SKELETON_POSITION_TRACKING_STATE), stored as a +// fixed-width uint32 field so the layout is identical in the C struct and the +// ctypes mirror. +enum class JointTrackingState : uint32_t { + NOT_TRACKED = 0, + INFERRED = 1, + TRACKED = 2, +}; + +// One joint's position + per-joint tracking state (nui-contracts.md §1.7). +struct JointData { + Vector4 position; + JointTrackingState tracking_state; +}; +static_assert(sizeof(JointData) == 20, "JointData golden size"); +static_assert(offsetof(JointData, position) == 0, "JointData.position golden offset"); +static_assert(offsetof(JointData, tracking_state) == 16, "JointData.tracking_state golden offset"); + +// A full skeleton frame: 20 joints, an overall tracking id, and quality flags +// (NUI_SKELETON_DATA, minus bone orientations which the app derives itself - +// see nui-contracts.md §1.7). +struct SkeletonFrame { + JointData joints[kJointCount]; + uint32_t skeleton_tracking_id; // dwTrackingID: stable nonzero id per player + uint32_t quality_flags; // dwQualityFlags: e.g. CLIPPED_* bits +}; +static_assert(sizeof(SkeletonFrame) == 408, "SkeletonFrame golden size"); +static_assert(offsetof(SkeletonFrame, joints) == 0, "SkeletonFrame.joints golden offset"); +static_assert(offsetof(SkeletonFrame, skeleton_tracking_id) == 400, + "SkeletonFrame.skeleton_tracking_id golden offset"); +static_assert(offsetof(SkeletonFrame, quality_flags) == 404, + "SkeletonFrame.quality_flags golden offset"); + +// --- Image buffer descriptors ---------------------------------------------- + +// Describes a depth+player-index buffer living in the shared-memory region: +// its geometry and a byte offset to its pixel data (nui-contracts.md §2.2). +// Pixel format is the packed 16-bit Kinect word: (mm & 0x1FFF) << 3 | (player & 0x7). +struct DepthBufferDescriptor { + uint32_t width; + uint32_t height; + uint32_t pitch; // bytes per row, as reported to the host (NUI_SURFACE_DESC) + uint64_t byte_offset; // offset of pixel data within the shared-memory region +}; +static_assert(sizeof(DepthBufferDescriptor) == 20, "DepthBufferDescriptor golden size"); +static_assert(offsetof(DepthBufferDescriptor, width) == 0, "DepthBufferDescriptor.width golden offset"); +static_assert(offsetof(DepthBufferDescriptor, height) == 4, "DepthBufferDescriptor.height golden offset"); +static_assert(offsetof(DepthBufferDescriptor, pitch) == 8, "DepthBufferDescriptor.pitch golden offset"); +static_assert(offsetof(DepthBufferDescriptor, byte_offset) == 12, + "DepthBufferDescriptor.byte_offset golden offset"); + +// Describes a color (BGRA) buffer living in the shared-memory region. +struct ColorBufferDescriptor { + uint32_t width; + uint32_t height; + uint32_t pitch; + uint64_t byte_offset; +}; +static_assert(sizeof(ColorBufferDescriptor) == 20, "ColorBufferDescriptor golden size"); +static_assert(offsetof(ColorBufferDescriptor, width) == 0, "ColorBufferDescriptor.width golden offset"); +static_assert(offsetof(ColorBufferDescriptor, height) == 4, "ColorBufferDescriptor.height golden offset"); +static_assert(offsetof(ColorBufferDescriptor, pitch) == 8, "ColorBufferDescriptor.pitch golden offset"); +static_assert(offsetof(ColorBufferDescriptor, byte_offset) == 12, + "ColorBufferDescriptor.byte_offset golden offset"); + +// --- Frame ------------------------------------------------------------------ + +// One published frame: frame number + QPC-style monotonic timestamp (micros +// since init, nui-contracts.md §3.6), the skeleton, and the two image buffer +// descriptors. Depth, color, and skeleton all carry the SAME frame_number and +// timestamp_micros - the most recent depth tick's stamp - matching the real +// NUI contract where skeleton timestamp = the depth frame it derived from. +struct FrameData { + uint32_t frame_number; + int64_t timestamp_micros; // monotonic, QPC-style, microseconds since init + SkeletonFrame skeleton; + DepthBufferDescriptor depth; + ColorBufferDescriptor color; +}; +static_assert(sizeof(FrameData) == 460, "FrameData golden size"); +static_assert(offsetof(FrameData, frame_number) == 0, "FrameData.frame_number golden offset"); +static_assert(offsetof(FrameData, timestamp_micros) == 4, "FrameData.timestamp_micros golden offset"); +static_assert(offsetof(FrameData, skeleton) == 12, "FrameData.skeleton golden offset"); +static_assert(offsetof(FrameData, depth) == 420, "FrameData.depth golden offset"); +static_assert(offsetof(FrameData, color) == 440, "FrameData.color golden offset"); + +// One triple-buffer slot: a sequence counter guarding `data` (seqlock-style - +// a reader must observe the same even sequence before and after copying +// `data`, else the slot was mid-write and the read must retry). +struct FrameSlot { + uint64_t sequence; + FrameData data; +}; +static_assert(sizeof(FrameSlot) == 468, "FrameSlot golden size"); +static_assert(offsetof(FrameSlot, sequence) == 0, "FrameSlot.sequence golden offset"); +static_assert(offsetof(FrameSlot, data) == 8, "FrameSlot.data golden offset"); + +// The full frame contract: a triple-buffered, newest-wins frame region plus +// its version stamp. A single producer publishes by writing the slot ahead +// of the currently-published one and then bumping `published_sequence`; +// readers derive the current slot index as `published_sequence % kFrameSlotCount`. +struct FrameContract { + uint32_t contract_version; + uint32_t reserved; // explicit padding to keep 8-byte fields aligned-by-convention + uint64_t published_sequence; // monotonic; slots[published_sequence % kFrameSlotCount] is newest + FrameSlot slots[kFrameSlotCount]; +}; +static_assert(sizeof(FrameContract) == 1420, "FrameContract golden size"); +static_assert(offsetof(FrameContract, contract_version) == 0, "FrameContract.contract_version golden offset"); +static_assert(offsetof(FrameContract, reserved) == 4, "FrameContract.reserved golden offset"); +static_assert(offsetof(FrameContract, published_sequence) == 8, "FrameContract.published_sequence golden offset"); +static_assert(offsetof(FrameContract, slots) == 16, "FrameContract.slots golden offset"); + +// --- Control plane ---------------------------------------------------------- +// +// Carried over a named pipe / unix socket, NEVER shared memory and NEVER +// per-frame data (frames only ever travel through FrameContract above). + +enum class ControlMessageType : uint32_t { + HANDSHAKE_VERSION = 0, + CONFIG = 1, + CALIBRATION = 2, + HEARTBEAT = 3, +}; + +// Versioned header prefixing every control-plane message. +struct ControlMessageHeader { + ControlMessageType message_type; + uint32_t contract_version; + uint32_t payload_size; // size of the full message (header + payload), bytes + uint32_t reserved; +}; +static_assert(sizeof(ControlMessageHeader) == 16, "ControlMessageHeader golden size"); +static_assert(offsetof(ControlMessageHeader, message_type) == 0, "ControlMessageHeader.message_type golden offset"); +static_assert(offsetof(ControlMessageHeader, contract_version) == 4, + "ControlMessageHeader.contract_version golden offset"); +static_assert(offsetof(ControlMessageHeader, payload_size) == 8, + "ControlMessageHeader.payload_size golden offset"); +static_assert(offsetof(ControlMessageHeader, reserved) == 12, "ControlMessageHeader.reserved golden offset"); + +// Sent once by the producer on connect; the consumer rejects a mismatched +// contract_version in the header rather than guessing at compatibility. +struct HandshakeMessage { + ControlMessageHeader header; + uint32_t client_version; + uint32_t capabilities; +}; +static_assert(sizeof(HandshakeMessage) == 24, "HandshakeMessage golden size"); +static_assert(offsetof(HandshakeMessage, header) == 0, "HandshakeMessage.header golden offset"); +static_assert(offsetof(HandshakeMessage, client_version) == 16, "HandshakeMessage.client_version golden offset"); +static_assert(offsetof(HandshakeMessage, capabilities) == 20, "HandshakeMessage.capabilities golden offset"); + +// Stream geometry the consumer has requested (nui-contracts.md §2.1: read the +// host's requested eResolution, never hardcode it). +struct ConfigMessage { + ControlMessageHeader header; + uint32_t depth_width; + uint32_t depth_height; + uint32_t color_width; + uint32_t color_height; +}; +static_assert(sizeof(ConfigMessage) == 32, "ConfigMessage golden size"); +static_assert(offsetof(ConfigMessage, header) == 0, "ConfigMessage.header golden offset"); +static_assert(offsetof(ConfigMessage, depth_width) == 16, "ConfigMessage.depth_width golden offset"); +static_assert(offsetof(ConfigMessage, depth_height) == 20, "ConfigMessage.depth_height golden offset"); +static_assert(offsetof(ConfigMessage, color_width) == 24, "ConfigMessage.color_width golden offset"); +static_assert(offsetof(ConfigMessage, color_height) == 28, "ConfigMessage.color_height golden offset"); + +// Calibration result (Z0/scale, mirror bit, floor plane); the full +// calibration flow is todo 11 - this pins only the wire shape. +struct CalibrationMessage { + ControlMessageHeader header; + float z0_meters; + uint32_t mirror; // 0 or 1; see nui-contracts.md §1.4 + float floor_plane[4]; +}; +static_assert(sizeof(CalibrationMessage) == 40, "CalibrationMessage golden size"); +static_assert(offsetof(CalibrationMessage, header) == 0, "CalibrationMessage.header golden offset"); +static_assert(offsetof(CalibrationMessage, z0_meters) == 16, "CalibrationMessage.z0_meters golden offset"); +static_assert(offsetof(CalibrationMessage, mirror) == 20, "CalibrationMessage.mirror golden offset"); +static_assert(offsetof(CalibrationMessage, floor_plane) == 24, "CalibrationMessage.floor_plane golden offset"); + +// Liveness ping both directions can use to detect a stalled peer (drives +// IS-8's graceful-degradation recovery, not a fixed-delay reconnect). +struct HeartbeatMessage { + ControlMessageHeader header; + int64_t timestamp_micros; + uint64_t sequence; // last FrameContract.published_sequence the sender observed +}; +static_assert(sizeof(HeartbeatMessage) == 32, "HeartbeatMessage golden size"); +static_assert(offsetof(HeartbeatMessage, header) == 0, "HeartbeatMessage.header golden offset"); +static_assert(offsetof(HeartbeatMessage, timestamp_micros) == 16, "HeartbeatMessage.timestamp_micros golden offset"); +static_assert(offsetof(HeartbeatMessage, sequence) == 24, "HeartbeatMessage.sequence golden offset"); + +#pragma pack(pop) + +// --- Triple-buffer publish/read protocol ------------------------------------ + +// Writes `data` into the next slot and publishes it as newest, overwriting the +// oldest-but-one slot (single-writer only; never call concurrently). +void publish_frame(FrameContract& contract, const FrameData& data); + +// Snapshots the newest published frame into `out`. Retries internally against +// a concurrent publish (seqlock-style) and always returns a consistent frame. +void read_latest_frame(const FrameContract& contract, FrameData& out); + } // namespace nui::contract #endif // NUI_CORE_CONTRACT_H diff --git a/core/contract/contract_layout_dump.cpp b/core/contract/contract_layout_dump.cpp new file mode 100644 index 0000000..63aff57 --- /dev/null +++ b/core/contract/contract_layout_dump.cpp @@ -0,0 +1,100 @@ +#include + +#include "contract/contract.h" + +// Prints every golden sizeof/offsetof pair from contract.h as KEY=VALUE lines. +// tests/test_contract_py.py runs this binary and diffs its output against the +// ctypes mirror in tracker/contract.py, so the Python side is checked against +// whatever the C header ACTUALLY compiles to today, never a hardcoded copy +// that could silently drift from the real layout. + +using namespace nui::contract; + +int main() { + std::printf("CONTRACT_VERSION=%u\n", kContractVersion); + std::printf("JOINT_COUNT=%zu\n", kJointCount); + std::printf("FRAME_SLOT_COUNT=%zu\n", kFrameSlotCount); + + std::printf("sizeof(Vector4)=%zu\n", sizeof(Vector4)); + std::printf("offsetof(Vector4,x)=%zu\n", offsetof(Vector4, x)); + std::printf("offsetof(Vector4,y)=%zu\n", offsetof(Vector4, y)); + std::printf("offsetof(Vector4,z)=%zu\n", offsetof(Vector4, z)); + std::printf("offsetof(Vector4,w)=%zu\n", offsetof(Vector4, w)); + + std::printf("sizeof(JointData)=%zu\n", sizeof(JointData)); + std::printf("offsetof(JointData,position)=%zu\n", offsetof(JointData, position)); + std::printf("offsetof(JointData,tracking_state)=%zu\n", offsetof(JointData, tracking_state)); + + std::printf("sizeof(SkeletonFrame)=%zu\n", sizeof(SkeletonFrame)); + std::printf("offsetof(SkeletonFrame,joints)=%zu\n", offsetof(SkeletonFrame, joints)); + std::printf("offsetof(SkeletonFrame,skeleton_tracking_id)=%zu\n", + offsetof(SkeletonFrame, skeleton_tracking_id)); + std::printf("offsetof(SkeletonFrame,quality_flags)=%zu\n", offsetof(SkeletonFrame, quality_flags)); + + std::printf("sizeof(DepthBufferDescriptor)=%zu\n", sizeof(DepthBufferDescriptor)); + std::printf("offsetof(DepthBufferDescriptor,width)=%zu\n", offsetof(DepthBufferDescriptor, width)); + std::printf("offsetof(DepthBufferDescriptor,height)=%zu\n", offsetof(DepthBufferDescriptor, height)); + std::printf("offsetof(DepthBufferDescriptor,pitch)=%zu\n", offsetof(DepthBufferDescriptor, pitch)); + std::printf("offsetof(DepthBufferDescriptor,byte_offset)=%zu\n", + offsetof(DepthBufferDescriptor, byte_offset)); + + std::printf("sizeof(ColorBufferDescriptor)=%zu\n", sizeof(ColorBufferDescriptor)); + std::printf("offsetof(ColorBufferDescriptor,width)=%zu\n", offsetof(ColorBufferDescriptor, width)); + std::printf("offsetof(ColorBufferDescriptor,height)=%zu\n", offsetof(ColorBufferDescriptor, height)); + std::printf("offsetof(ColorBufferDescriptor,pitch)=%zu\n", offsetof(ColorBufferDescriptor, pitch)); + std::printf("offsetof(ColorBufferDescriptor,byte_offset)=%zu\n", + offsetof(ColorBufferDescriptor, byte_offset)); + + std::printf("sizeof(FrameData)=%zu\n", sizeof(FrameData)); + std::printf("offsetof(FrameData,frame_number)=%zu\n", offsetof(FrameData, frame_number)); + std::printf("offsetof(FrameData,timestamp_micros)=%zu\n", offsetof(FrameData, timestamp_micros)); + std::printf("offsetof(FrameData,skeleton)=%zu\n", offsetof(FrameData, skeleton)); + std::printf("offsetof(FrameData,depth)=%zu\n", offsetof(FrameData, depth)); + std::printf("offsetof(FrameData,color)=%zu\n", offsetof(FrameData, color)); + + std::printf("sizeof(FrameSlot)=%zu\n", sizeof(FrameSlot)); + std::printf("offsetof(FrameSlot,sequence)=%zu\n", offsetof(FrameSlot, sequence)); + std::printf("offsetof(FrameSlot,data)=%zu\n", offsetof(FrameSlot, data)); + + std::printf("sizeof(FrameContract)=%zu\n", sizeof(FrameContract)); + std::printf("offsetof(FrameContract,contract_version)=%zu\n", offsetof(FrameContract, contract_version)); + std::printf("offsetof(FrameContract,reserved)=%zu\n", offsetof(FrameContract, reserved)); + std::printf("offsetof(FrameContract,published_sequence)=%zu\n", + offsetof(FrameContract, published_sequence)); + std::printf("offsetof(FrameContract,slots)=%zu\n", offsetof(FrameContract, slots)); + + std::printf("sizeof(ControlMessageHeader)=%zu\n", sizeof(ControlMessageHeader)); + std::printf("offsetof(ControlMessageHeader,message_type)=%zu\n", + offsetof(ControlMessageHeader, message_type)); + std::printf("offsetof(ControlMessageHeader,contract_version)=%zu\n", + offsetof(ControlMessageHeader, contract_version)); + std::printf("offsetof(ControlMessageHeader,payload_size)=%zu\n", + offsetof(ControlMessageHeader, payload_size)); + std::printf("offsetof(ControlMessageHeader,reserved)=%zu\n", offsetof(ControlMessageHeader, reserved)); + + std::printf("sizeof(HandshakeMessage)=%zu\n", sizeof(HandshakeMessage)); + std::printf("offsetof(HandshakeMessage,header)=%zu\n", offsetof(HandshakeMessage, header)); + std::printf("offsetof(HandshakeMessage,client_version)=%zu\n", + offsetof(HandshakeMessage, client_version)); + std::printf("offsetof(HandshakeMessage,capabilities)=%zu\n", offsetof(HandshakeMessage, capabilities)); + + std::printf("sizeof(ConfigMessage)=%zu\n", sizeof(ConfigMessage)); + std::printf("offsetof(ConfigMessage,header)=%zu\n", offsetof(ConfigMessage, header)); + std::printf("offsetof(ConfigMessage,depth_width)=%zu\n", offsetof(ConfigMessage, depth_width)); + std::printf("offsetof(ConfigMessage,depth_height)=%zu\n", offsetof(ConfigMessage, depth_height)); + std::printf("offsetof(ConfigMessage,color_width)=%zu\n", offsetof(ConfigMessage, color_width)); + std::printf("offsetof(ConfigMessage,color_height)=%zu\n", offsetof(ConfigMessage, color_height)); + + std::printf("sizeof(CalibrationMessage)=%zu\n", sizeof(CalibrationMessage)); + std::printf("offsetof(CalibrationMessage,header)=%zu\n", offsetof(CalibrationMessage, header)); + std::printf("offsetof(CalibrationMessage,z0_meters)=%zu\n", offsetof(CalibrationMessage, z0_meters)); + std::printf("offsetof(CalibrationMessage,mirror)=%zu\n", offsetof(CalibrationMessage, mirror)); + std::printf("offsetof(CalibrationMessage,floor_plane)=%zu\n", offsetof(CalibrationMessage, floor_plane)); + + std::printf("sizeof(HeartbeatMessage)=%zu\n", sizeof(HeartbeatMessage)); + std::printf("offsetof(HeartbeatMessage,header)=%zu\n", offsetof(HeartbeatMessage, header)); + std::printf("offsetof(HeartbeatMessage,timestamp_micros)=%zu\n", + offsetof(HeartbeatMessage, timestamp_micros)); + std::printf("offsetof(HeartbeatMessage,sequence)=%zu\n", offsetof(HeartbeatMessage, sequence)); + return 0; +} diff --git a/docs/spike-linux.md b/docs/spike-linux.md new file mode 100644 index 0000000..1942323 --- /dev/null +++ b/docs/spike-linux.md @@ -0,0 +1,380 @@ +# Spike - Linux USB protocol + "does a real tracker skeletonize synthetic depth" (todo 3) + +> **STATUS: Enumeration/attach path BLOCKED in this environment; skeletonization crux UNPROVEN here.** +> This spike was executed on a Linux/WSL2 host (kernel `6.6.87.2-microsoft-standard-WSL2`) with +> **no `usbip` userspace**, **no OpenNI2**, **no NiTE2**, and **no Kinect viewer tools**. The USB +> probes below are real, verbatim, observed command output. The Kinect v1 USB protocol section is +> drawn from the real **libfreenect** source (master @ commit `09a1f098`, retrieved 2026-11-25) with +> per-fact file/line citations. The skeletonization crux **was NOT executed** (no host tracker is +> installed); it is documented as UNPROVEN with an exact runbook to prove it if the user supplies +> OpenNI2 + NiTE2. No skeleton result is claimed. + +Closes plan **GAP-4 (Linux half)**. Plan todo 3; blocks todo 8 (exact protocol) and todo 15 +(fallback decision). References: libfreenect USB protocol (`github.com/OpenKinect/libfreenect` +`src/`), OpenNI2-FreenectDriver, usbip/vhci-hcd, NiTE2 skeleton sample. + +Evidence: `.omo/evidence/task-3-webcam-kinect-emulator.probe.log` (verbatim probe transcript). + +--- + +## 0. Go/no-go summary (read this first) + +| Question | Verdict in THIS environment | Consequence | +| --- | --- | --- | +| Can this box run the usbip/vhci **device-attach** path (plan todos 9/10)? | **NO - BLOCKED.** The `vhci-hcd` *module* exists and `modprobe -n` resolves it, but the `usbip` userspace binary is absent and no vhci controller is present/loaded. | The Linux device-attach proof (todos 9/10) cannot run here. It needs `usbip`/`linux-tools` installed **and** the module loaded, or a native-Linux host. The WSL2 kernel ships the module, so a custom-kernel rebuild is **not** strictly required - see §2. | +| Is the Kinect v1 (1414) USB protocol understood well enough to spec the todo-8 emitter? | **YES.** Device topology, identity, init/control sequence, firmware handshake, and depth/video iso framing are extracted from libfreenect with citations (§3). One gap is flagged: the exact camera *command-header* byte layout (§3.4). | Todo 8 has a concrete minimal descriptor/control set (§4). | +| Does a real host tracker skeletonize **synthetic** depth (the kill-gate crux)? | **UNPROVEN here.** No OpenNI2/NiTE2 installed; cannot execute. | Per the plan, the crux kill-gate is satisfied by **whichever of spike 3 or spike 4 can first test it**. This box cannot; **spike 4 (Windows MS NUI)** must carry it, OR the user installs OpenNI2+NiTE2 and runs §5 here. **If NEITHER spike 3 nor spike 4 can test it before build waves 4-11, that is a HALT-and-re-plan condition** (plan Execution strategy / todo 4). | + +--- + +## 1. Environment probe (verbatim) + +Host: `/home/athapa/kinect-wt/wave2`. Commands run 2026-11-25; `[exit=N]` is the shell exit code. + +``` +$ pwd +/home/athapa/kinect-wt/wave2 +$ uname -r +6.6.87.2-microsoft-standard-WSL2 +[exit=0] +$ modprobe -n vhci-hcd 2>&1 +[exit=0] +$ ls /sys/devices/platform/vhci_hcd* 2>&1 +ls: cannot access '/sys/devices/platform/vhci_hcd*': No such file or directory +[exit=2] +$ which usbip +[exit=1] +$ lsmod | grep -i vhci +[exit=1] +``` + +Supplementary probes (module resolution + tracker/tooling inventory): + +``` +$ modprobe -n -v vhci-hcd 2>&1 +insmod /lib/modules/6.6.87.2-microsoft-standard-WSL2/kernel/drivers/usb/common/usb-common.ko +insmod /lib/modules/6.6.87.2-microsoft-standard-WSL2/kernel/drivers/usb/core/usbcore.ko +insmod /lib/modules/6.6.87.2-microsoft-standard-WSL2/kernel/drivers/usb/usbip/usbip-core.ko +insmod /lib/modules/6.6.87.2-microsoft-standard-WSL2/kernel/drivers/usb/usbip/vhci-hcd.ko +[exit=0] +$ modinfo -F filename vhci-hcd 2>&1 +/lib/modules/6.6.87.2-microsoft-standard-WSL2/kernel/drivers/usb/usbip/vhci-hcd.ko +[exit=0] + +$ pkg-config --modversion libopenni2 +/bin/bash: line 1: pkg-config: command not found +[exit=127] +$ dpkg-query -W libopenni2-0 libopenni2-dev +dpkg-query: no packages found matching libopenni2-0 +dpkg-query: no packages found matching libopenni2-dev +[exit=1] +$ printenv OPENNI2_INCLUDE OPENNI2_REDIST NITE2_INCLUDE NITE2_REDIST +[exit=1] + +$ for b in freenect-glview NiViewer SimpleViewer usbip python3 cmake gcc; do ...; done +freenect-glview -> MISSING +NiViewer -> MISSING +SimpleViewer -> MISSING +usbip -> MISSING +python3 -> /usr/bin/python3 +cmake -> /home/athapa/.local/bin/cmake +gcc -> /usr/bin/gcc +$ ls /usr/lib/OpenNI2 ... +ls: cannot access '/usr/lib/OpenNI2': No such file or directory +``` + +## 2. vhci/usbip finding and its consequence + +**Finding (correction to the prior recon's expectation).** The prior recon assumed the `vhci-hcd` +kernel module is *absent* on this WSL2 kernel. That is **not** what this box shows. The module file +is present and `modprobe -n -v vhci-hcd` resolves the full dependency chain +(`usb-common` -> `usbcore` -> `usbip-core` -> `vhci-hcd`), and `modinfo -F filename vhci-hcd` +returns the `.ko` path. So this stock WSL2 kernel (`6.6.87.2-microsoft-standard-WSL2`) **does ship +the usbip/vhci modules**. + +What is actually missing here is twofold, and it is still **blocking**: + +1. **No `usbip` userspace** (`which usbip` -> exit 1; `linux-tools`/`usbip` package not installed). + The device-attach path needs the `usbip` tool (or a raw-gadget userspace server) to speak the + USB/IP protocol to `vhci-hcd`. +2. **No vhci controller active** (`ls /sys/devices/platform/vhci_hcd*` -> not found; `lsmod | grep + vhci` -> exit 1, module not loaded). `modprobe -n` is a dry run; the module was never actually + loaded, and nothing has created the `vhci_hcd` platform device / sysfs attach points. + +**Consequence for the plan.** The Linux device-attach path (plan todos 9 and 10) is **BLOCKED as the +box stands**, but the blocker is lighter than "needs a custom kernel": + +- The likely-sufficient fix on this WSL2 kernel: `sudo modprobe vhci-hcd` to load the module (which + should create `/sys/devices/platform/vhci_hcd.0` and `/sys/.../vhci_hcd/`), then install the + `usbip` userspace (Debian/Ubuntu: `apt install linux-tools-generic` / `usbip`, or build + `tools/usb/usbip` from the kernel tree). This must be **verified**, not assumed - the module file + existing does not guarantee it loads cleanly under the MS WSL2 kernel, and WSL2's init may lack + the udev/sysfs plumbing usbip expects. +- The fallback if `modprobe vhci-hcd` fails to load or the sysfs attach points do not appear: a + **custom WSL2 kernel** built with `CONFIG_USBIP_VHCI_HCD=m`/`=y` (`.wslconfig` -> `kernel=`), or a + **native-Linux host**. Either way the attach path cannot be exercised in the current state. +- Todo 9/10 acceptance (`lsusb` shows the Kinect VID/PID; `freenect-glview`/OpenNI enumerates it) + **cannot be met here today**: `usbip`, `freenect-glview`, `NiViewer`/`SimpleViewer`, and the + OpenNI2 runtime are all absent. These todos must be marked blocked on (a) usbip userspace + a + loaded vhci controller and (b) an installed OpenNI2 (+FreenectDriver) viewer, or run on a + native-Linux box. + +`cmake`, `gcc`, and `python3` are present, so the pure build/compile portions of later todos can run +here; the device-attach and host-tracker portions cannot. + +## 3. Kinect v1 (model 1414) USB protocol - what a virtual device must emit + +All citations are to libfreenect master @ `09a1f098` (`src/`), retrieved 2026-11-25. Line numbers +are from those retrieved files. + +### 3.1 Composite topology and USB identity + +The Kinect v1 is **not** a single composite USB device with multiple interfaces - it presents as +**three independent USB devices behind an internal hub**, all with vendor `0x045e` (Microsoft): + +| Sub-device | idVendor | idProduct | Role | +| --- | --- | --- | --- | +| Camera | `0x045e` | `0x02ae` (`PID_NUI_CAMERA`) | Depth + color/IR iso streams (the stream the tracker needs) | +| Audio | `0x045e` | `0x02ad` (`PID_NUI_AUDIO`) | 4-mic array; also the firmware-upload target (§3.5) | +| Motor | `0x045e` | `0x02b0` (`PID_NUI_MOTOR`) | Tilt + accelerometer + LED (control transfers only) | + +- Constants: `freenect_internal.h:137-140` (`VID_MICROSOFT 0x45e`, `PID_NUI_AUDIO 0x02ad`, + `PID_NUI_CAMERA 0x02ae`, `PID_NUI_MOTOR 0x02b0`). +- Enumeration counts only the camera PID (`fnusb_is_camera`, `usb_libusb10.c:75-79`); the audio and + motor siblings are then found by **shared parent hub / same bus** (`fnusb_find_sibling_device`, + `usb_libusb10.c:94-152`, called from `fnusb_open_subdevices`, `usb_libusb10.c:381-546`). A virtual + Kinect must therefore expose the three functions as **sibling devices on a common (virtual) hub**, + not as one multi-interface device, so the host's sibling-matching succeeds. +- **Model discriminator:** the original "1414" Kinect is identified by `bcdDevice == 267` (0x010B) + on the camera descriptor (`usb_libusb10.c:431`); any other `bcdDevice` (or `PID_K4W_CAMERA`) is + treated as a newer model that drops the standalone motor and does motor control via the audio + device (`usb_libusb10.c:431-456`, `device_does_motor_control_with_audio`). The emitter should + report `bcdDevice = 267` to be handled on the simple 1414 path, which also sets + `zero_plane_res = 322` (`usb_libusb10.c:455`; non-1414 uses 334 at `usb_libusb10.c:438`). +- **Camera interface:** the host claims **interface 0** of the camera device + (`libusb_claim_interface(dev->usb_cam.dev, 0)`, `usb_libusb10.c:318`, in `fnusb_claim_camera` at + `usb_libusb10.c:296`). For the 1414 it does **not** change alt setting; the alt-setting-1 switch at + `usb_libusb10.c:329` is K4W-only. The camera + device's interface 0 must carry the two iso IN endpoints (§3.3) with a non-zero alt setting whose + iso endpoints have the right `wMaxPacketSize`. + +### 3.2 Init / control-transfer sequence + +Camera bring-up runs in `freenect_camera_init` (`cameras.c:1251-1273`), which performs a sequence of +command reads before streaming: + +| Order | Call | Opcode | Reply size | Citation | +| --- | --- | --- | --- | --- | +| 1 | `freenect_fetch_reg_info` | `0x16` (ALGORITHM_PARAMS); cmd[5] = {ParamID `0x40`, format 0, resolution, fps, offset} | 118 bytes | `cameras.c:664-680` | +| 2 | `freenect_fetch_reg_pad_info` | `0x16` | 8 bytes | `cameras.c:742-756` | +| 3 | `freenect_fetch_zero_plane_info` | `0x04` (GET_FIXED_PARAMS) | `zero_plane_res` = **322** for 1414 | `cameras.c:794-804` | +| 4 | set video mode (RGB 640x480) + depth mode (11-bit 640x480) | register writes (§3.3) | - | `cameras.c:1265-1266` | +| 5 | `freenect_fetch_reg_const_shift` | `0x16` | 4 bytes | `cameras.c:769-783` | + +These replies feed the registration/depth-to-mm math; a virtual device must return +**correctly-sized, self-consistent payloads** (the host checks the exact byte counts and errors out +otherwise, e.g. `cameras.c:678-680`). Each command carries an incrementing tag (`cam_tag`, +`freenect_internal.h:240`) that the reply must echo. + +**Stream start is a sequence of register writes** (`write_register(dev, reg, value)`), not special +opcodes: + +Depth start (`freenect_start_depth`, `cameras.c:880-899`): +``` +write_register(0x105, 0x00) // disable projector auto-cycle +write_register(0x06, 0x00) // reset depth stream +write_register(0x12, 0x03) // depth format: 0x03 = 11-bit (0x02 = 10-bit) +write_register(0x13, 0x01) // depth resolution 640x480 +write_register(0x14, 0x1e) // depth FPS = 30 +write_register(0x06, 0x02) // START depth stream +write_register(0x17, 0x00) // disable depth horizontal flip +``` +Video start (`freenect_start_video`, `cameras.c:1030-1050`): writes mode/res/fps registers then +`write_register(0x05, 0x01)` (or `0x03` with projector cycling) to start, and `0x47 = 0x00` to +disable video hflip. Stop = `0x06=0x00` (depth) / `0x05=0x00` (video) (`cameras.c:1065,1087`). +Mirror toggles live at register `0x17` (depth) and `0x47` (video) (`flags.c:37-43`). + +The virtual device must **accept and ACK** all of these register writes (and the §3.2 reads) and +only begin pushing iso frames after the `0x06=0x02` / `0x05=0x01` start writes. + +### 3.3 Depth / video stream framing (iso) + +- **Endpoints:** depth = iso IN **`0x82`**, video = iso IN **`0x81`** (`cameras.c:871`, `:1021`). +- **Per-packet size:** `DEPTH_PKTSIZE 1760`, `VIDEO_PKTSIZE 1920`, each with a **12-byte header**; + so payload per packet is `DEPTH_PKTDSIZE 1748`, `VIDEO_PKTDSIZE 1908` + (`freenect_internal.h:131-135`). Iso transfer geometry on Linux: `PKTS_PER_XFER 16`, + `NUM_XFERS 16`, buffer `DEPTH_PKTBUF/VIDEO_PKTBUF = 1920` (`usb_libusb10.h`). +- **Packet header** (`struct pkt_hdr`, `cameras.c:76-85`), 12 bytes, little-endian timestamp: + ``` + uint8 magic[2] = {0x52, 0x42} // 'R','B' (checked at cameras.c:102) + uint8 pad + uint8 flag // start/mid/end-of-frame marker (below) + uint8 unk1 + uint8 seq // per-packet sequence, increments; wraps at 256 + uint8 unk2 + uint8 unk3 + uint32 timestamp // little-endian (fn_le32), cameras.c:214 + ``` +- **Frame markers (`flag`):** base flag per stream - depth base `0x70`, video base `0x80` + (`cameras.c:849`, `:913`). Within a frame: Start-Of-Frame = `base|1`, Middle = `base|2`, + End-Of-Frame = `base|5` (`cameras.c:110-112`). So depth packets carry `0x71`/`0x72`/`0x75`, video + `0x81`/`0x82`/`0x85`. The host re-syncs on these; the emitter must set them correctly or the host + drops the frame (`cameras.c:159-200`). +- **Depth bit format (default):** `FREENECT_DEPTH_11BIT`, 640x480 @ 30 fps. On the wire it is + **11-bit packed** (8 pixels per 11 bytes, MSB-first), unpacked by `convert_packed11_to_16bit` + (`cameras.c:345-374`; depth-mode table `cameras.c:65-73`). A virtual device replaying depth must + **pack to this exact 11-bit layout** for the default mode (register `0x12=0x03`). The host can + also request 10-bit (`0x12=0x02`), packed variants, registered, and MM modes (same table), but + 11-bit is the libfreenect default and the simplest target. +- Color default is Bayer/RGB 640x480 @ 30 (`cameras.c:42-62`); IR modes also exist. For the DEA / + NUI depth+skeleton goal, **depth is the load-bearing stream**; color can start as a static/valid + Bayer frame. + +### 3.4 Gap: exact camera command-header byte layout (flagged for todo 8) + +The register reads/writes in §3.2 go through libfreenect helpers `send_cmd(...)` / +`write_register(...)` / `read_register(...)`. In the retrieved **master** `src/cameras.c` +(45,395 bytes, 1,296 lines) these helpers are **used but their definitions are not present in that +file or in any sibling `src/*.c`/`*.h` fetched** (verified: the strings `send_cmd` / `write_register` +first appear only at their call sites, lines 677 and 880, with no definition or forward declaration +in `cameras.c`, `usb_libusb10.c/.h`, `core.c`, `audio.c`, `registration.c/.h`, `loader.c/.h`, +`flags.c/.h`, `cameras.h`, or `freenect_internal.h`). The OpenKinect wiki protocol page +(`openkinect.org/wiki/Protocol_Documentation` and `/USB_Devices`) returned **HTTP 403** to automated +fetch, so the camera command-header magic/length/opcode/tag byte order could **not** be captured +from an authoritative source in this spike. **Do not treat any specific camera command-header magic +bytes as established by this spike.** + +What *is* established: the command envelope carries an **incrementing `cam_tag`** +(`freenect_internal.h:240`) that the reply echoes, and uses the opcodes in §3.2's table +(`0x16` ALGORITHM_PARAMS, `0x04` GET_FIXED_PARAMS, plus the register read/write ops). The analogous +**audio bootloader** envelope *is* fully visible (§3.5) and is a good structural model +(`magic | tag | len | cmd | addr`). + +**Action for todo 8:** extract the exact `send_cmd`/`write_register` byte layout by (a) reading the +libfreenect `send_cmd` definition directly from a working local checkout/build of libfreenect (it is +in the compiled library; the master tree webfetch elided it), and/or (b) a `usbmon`/Wireshark +capture of a real or reference Kinect init. Treat §3.2/§3.3 as the behavioral contract and §3.4 as +the one byte-level detail to pin before freezing the emitter's control parser. + +### 3.5 Firmware-upload handshake + +Firmware upload is **audio-sub-device-only**; the **camera and motor need no firmware upload** +(`loader.c`; `usb_libusb10.c:548-592`). Flow: + +- A fresh audio device enumerates **in bootloader mode with 1 interface**. The host detects "already + loaded" by `fnusb_num_interfaces(&dev->usb_audio) >= 2` (`usb_libusb10.c:554-555`); if fewer, it + uploads `audios.bin` (`upload_firmware`, `loader.c:125`) and waits for the device to re-enumerate + with the same serial and 2 interfaces (`usb_libusb10.c:620-660`). +- Bootloader command envelope (`loader.c:84-90`, `check_version_string`), 24-byte struct, all LE: + ``` + uint32 magic = 0x06022009 + uint32 tag // = audio_tag, increments per command (loader.c:120) + uint32 bytes + uint32 cmd + uint32 addr + ... // bootloader_command, dumped as 24 bytes (loader.c:38) + ``` + Commands go **out on bulk endpoint 1**; replies come **in on bulk endpoint `0x81`** + (`loader.c:56,99,106`). The status reply has `magic == 0x0a6fe000` and must echo the `tag` + (`loader.c:62-68`). + +**Implication for the virtual Kinect (minimal path):** because only the audio device requires +firmware, a first-cut emitter can present the **audio device already in "loaded" state (>= 2 +interfaces)** so the host skips the firmware dance entirely, OR omit the audio device if the host +stack tolerates a camera-only Kinect. The depth/color/skeleton path depends on the **camera** device +(§3.1-3.3), which never needs a firmware upload. Audio firmware emulation is therefore **deferrable** +and is not on the critical path to the depth-fidelity crux. + +## 4. Minimal descriptor / control set for the todo-8 emitter + +Concrete contract the emitter (todo 8) must satisfy to make a host stack enumerate and stream: + +1. **Three sibling USB devices on one virtual hub**, all `idVendor=0x045e`: + - Camera `idProduct=0x02ae`, `bcdDevice=267` (0x010B); one configuration; **interface 0** with + an alt setting exposing two **iso IN** endpoints: `0x82` (depth) and `0x81` (video), each with + `wMaxPacketSize` sufficient for 1760/1920-byte packets (negotiated via + `fnusb_get_max_iso_packet_size`). + - Audio `idProduct=0x02ad` - present with **>= 2 interfaces** so the host treats firmware as + already loaded (§3.5), or omitted if the target stack allows camera-only. + - Motor `idProduct=0x02b0` - control-transfer-only; needed for the 1414 path if the host enables + the motor subdevice (`FREENECT_DEVICE_MOTOR`). +2. **Control endpoint 0** must answer: + - Standard descriptor requests for the three devices above. + - The command reads of §3.2 with correctly-sized replies: `0x16`/ParamID `0x40` -> 118 bytes; + `0x16` pad-info -> 8 bytes; `0x04` -> 322 bytes (zero-plane, 1414); `0x16` const-shift -> 4 + bytes - each echoing the incrementing `cam_tag`. (Exact command-header byte layout: §3.4, + pin before freeze.) + - The register writes of §3.2 (`0x105,0x06,0x12,0x13,0x14,0x17` for depth; `0x05,0x47` + mode + regs for video), ACKed; only start iso frames after `0x06=0x02` / `0x05=0x01`. +3. **Iso IN data** on `0x82`/`0x81`: 12-byte `pkt_hdr` (magic `'RB'`, correct `flag` + SOF/MOF/EOF per §3.3, incrementing `seq`, LE `timestamp`) + payload, depth packed **11-bit** + (register `0x12=0x03`) at 640x480, color as a valid Bayer/RGB 640x480 frame. +4. **No skeleton is ever emitted** (the device never computes it; the host stack does) - consistent + with plan todo 8's "Must NOT emit a skeleton." + +This is the "minimal descriptor/control set" that unblocks todo 8. The only item not fully +byte-specified by this spike is §3.4 (camera command-header framing). + +## 5. Skeletonization crux - UNPROVEN here, with the exact runbook to prove it + +**Status: UNPROVEN in this environment.** The crux question - *does a real host tracker produce a +stable, moving skeleton from synthetic (webcam-derived) articulated depth?* - **cannot be executed +on this box**: there is no OpenNI2 runtime and no NiTE2 tracker installed (§1: `dpkg` finds neither +`libopenni2-0` nor `-dev`; `pkg-config` absent; `/usr/lib/OpenNI2` absent; `OPENNI2_*`/`NITE2_*` env +unset; `NiViewer`/`SimpleViewer` MISSING). **No skeleton result is claimed by this spike.** + +**HALT condition (from the plan).** The depth-fidelity crux is a **kill-gate**. Per the plan's +Execution strategy and todo 4: the crux is satisfied by **whichever of spike 3 (Linux, if NiTE2 +supplied) or spike 4 (Windows MS NUI runtime) can first test it**; **if neither can confirm that a +real host tracker skeletonizes synthetic depth before build waves 4-11, HALT and re-plan the depth +model** (e.g. a monocular-depth network producing a denser, more Kinect-like depth map) before +committing to waves 4-11. Since this box cannot test it, the Linux half is UNPROVEN and the +responsibility falls to **spike 4 on the real Windows MS NUI runtime** unless the user installs the +Linux tracker and runs the procedure below. + +**Runbook to prove/disprove the crux on Linux (run only if the user supplies OpenNI2 + NiTE2).** +NiTE2 is EOL and non-redistributable: it is used only if the user already has it; it is never +bundled. + +1. **Install the attach + stream stack on a capable host** (native Linux, or WSL2 after + `sudo modprobe vhci-hcd` succeeds and creates `/sys/devices/platform/vhci_hcd.0`): + ``` + sudo modprobe vhci-hcd && ls -d /sys/devices/platform/vhci_hcd* # must now exist + sudo apt-get install -y usbip linux-tools-generic # or build kernel tools/usb/usbip + # OpenNI2 2.2.0.33+ (user-supplied or distro), e.g. unpack to ~/OpenNI2 + # Build libfreenect with the OpenNI2 driver: + git clone https://github.com/OpenKinect/libfreenect && cd libfreenect + mkdir build && cd build && cmake .. -DBUILD_OPENNI2_DRIVER=ON && make + # copy lib/OpenNI2-FreenectDriver/libFreenectDriver.so into OpenNI2 Drivers/ repo + ``` +2. **Install NiTE2 (user-supplied)** and set `NITE2_REDIST`/`NITE2_INCLUDE`; the NiTE2 package ships + the `UserViewer` sample (skeleton tracker over OpenNI2). +3. **Bring up the virtual Kinect** (todos 8+9): start the emitter, `usbip attach` it through + `vhci-hcd`; confirm `lsusb` shows `045e:02ae` and `NiViewer` (OpenNI SimpleViewer) renders the + virtual device's depth. This proves enumeration + stream correctness. +4. **Feed two depth sequences** via the emitter (pre-recorded, deterministic - never a live human): + - A **recorded real-person** Kinect depth sequence (ground-truth control). + - A **synthetic articulated-depth** sequence generated from webcam + pose (the thing under test). +5. **Run NiTE2 `UserViewer`** against the virtual device for each sequence and record the observable: + - **PASS:** `UserViewer` reports a tracked user and renders a **stable skeleton whose joints + move with the recorded subject** on the **synthetic** sequence (not only the real one), held + across several seconds without constant loss. Capture a screen recording + the NiTE user/skeleton + state log to `.omo/evidence/task-3-webcam-kinect-emulator.*`. + - **FAIL:** NiTE never acquires a user, or the skeleton is unstable/absent on synthetic depth + while fine on real depth. Record the failure mode (no-user, flickering joints, wrong scale). + **A FAIL here (with spike 4 also unable to pass) is the HALT-and-re-plan trigger** for the depth + model. + +Until step 5 passes on *synthetic* depth (here or in spike 4), the depth-fidelity crux stays +UNPROVEN and waves 4-11 are gated. + +## 6. What this spike did and did not do + +- **Did (observed):** environment/vhci/usbip capability probe (§1-2, verbatim); extracted the Kinect + v1 1414 USB protocol from libfreenect master with citations (§3-4); confirmed the host tracker + stack is absent (§1, §5). +- **Did NOT (honest gaps):** did not stand up a usbip virtual device (no `usbip` userspace, no loaded + vhci controller); did not render depth in a viewer (no `freenect-glview`/`NiViewer`); did not run + any skeleton tracker (no OpenNI2/NiTE2); did not capture the camera command-header byte layout + (§3.4; wiki returned HTTP 403, and master `cameras.c` elides the `send_cmd`/`write_register` + bodies). No test was run that is reported as passing. diff --git a/docs/spike-windows.md b/docs/spike-windows.md new file mode 100644 index 0000000..ad83792 --- /dev/null +++ b/docs/spike-windows.md @@ -0,0 +1,349 @@ +# Spike - Windows/DEA behavior, bitness, and synthetic-depth skeletonization crux (todo 4) + +> **STATUS: BLOCKED in the build environment (no Windows).** This is the runbook to execute on +> the user's Windows box; the depth-fidelity crux remains **UNPROVEN** until **Step 5** passes +> there. +> +> This document was authored on a Linux/WSL2 host with **no Windows**, **no DanceEvolution +> Arcade (DEA)**, and **no Kinect for Windows SDK**. Every active probe below (loading a +> pass-through logging `Kinect10.dll` into `gamekdm.dll`, running `dumpbin` on `gamekdm.dll`, +> binding a `usbip-win` virtual device against `kinectsensor.inf`, and feeding synthetic depth to +> the real MS NUI runtime to capture skeleton output) **requires the user's Windows box and was +> NOT executed here.** No results in this file are observed; every result cell is a placeholder to +> be filled in on Windows. Do not treat any value below as captured. + +Closes plan **GAP-4** (Windows half + the Windows synthetic-depth skeletonization crux). Plan +todo 4; references `.omo/design/architecture.md` (Top risks A/B, Sequencing) and +`.omo/design/nui-contracts.md` §3.2 (init sequence), §5 (open questions this spike resolves). + +## Kill-gate summary (read this first) + +Two things in this spike can HALT the whole project: + +- **Bitness (Step 2, risk B):** if DEA / `gamekdm.dll` is x86, the shipping Windows shim/driver + must be x86. A 64-bit DLL will not load into a 32-bit game. This is project-ending if mismatched; + it is cheap to settle and gates todo 1's arch selection and todos 12/14. +- **Synthetic-depth skeletonization (Step 5, risk D - the CRUX):** if the real MS NUI runtime + cannot produce a *moving* skeleton from our *synthetic* (no physical Kinect) articulated-depth + replay, the whole device-level approach for Windows (and the Linux path when NiTE2 is absent) + is invalid. **If Step 5 fails: HALT and re-plan the depth model** (e.g. a monocular-depth net + feeding a denser, more Kinect-like depth map) before building waves 4-11. + +Fill the **Results ledger** at the bottom as each step runs; the plan's acceptance criteria require +each claim to be backed by a captured log line / archived output. + +--- + +## 1. Prerequisites (install on the Windows box) + +Target: a Windows 10/11 x64 machine (it can host both x86 and x64 game/driver code). + +1. **Kinect for Windows Runtime + SDK v1.8** - both the Runtime and the Developer Toolkit/SDK: + - Kinect for Windows SDK v1.8 (`KinectSDK-v1.8-Setup.exe`) - installs `Kinect10.dll` (the real + NUI runtime), `kinectsensor.inf` and the WDF USB driver, and the headers (`NuiApi.h`, + `NuiImageCamera.h`, `NuiSkeleton.h`) under `%KINECTSDK10_DIR%\inc`. + - Kinect for Windows Developer Toolkit v1.8 (`KinectDeveloperToolkit-v1.8-Setup.exe`) - ships the + **SkeletonBasics-D2D** and **KinectExplorer-D2D** C++ samples used in Step 5. + - Record the real `Kinect10.dll` path (typically + `C:\Windows\System32\Kinect10.dll` for x64 and `C:\Windows\SysWOW64\Kinect10.dll` for x86; + both are installed by the 1.8 setup). You will forward to this in Step 3. +2. **spice2x** - with the **Kinect bypass** option available (it defeats DEA's boot-time Kinect + presence check; it does NOT provide gameplay data). Needed so DEA boots far enough to exercise + the NUI gameplay path in Step 3. +3. **DanceEvolution Arcade (DEA)** - the `gamekdm.dll` game module and its data (P3dro200 / spice2x + install layout). Note the directory that contains `gamekdm.dll`; the logging shim is placed + beside it in Step 3. +4. **Build tools:** + - **Visual Studio 2022** (or 2019) with the **Desktop development with C++** workload, including + the **x86 and x64 MSVC toolsets** and the Windows SDK (gives you `dumpbin.exe`, `cl.exe`, + `link.exe`, the Developer Command Prompt). MSVC is the authoritative toolchain for shim ABI. + - Confirm `dumpbin` is on PATH from a *Developer Command Prompt for VS* (x86 or x64 - `dumpbin` + reads either arch regardless of the prompt). +5. **usbip-win** (Steps 4-5) - the signed/test-signed `usbip-win` (or `usbip-win2`) package with its + virtual host-controller (VHCI) bus driver. Requires **test-signing ON** and/or **Secure Boot + OFF** (see Step 4). A second machine or a Linux VM runs the `usbipd` server that exports the + synthetic device; or use the Windows-local stub server if the chosen `usbip-win` build ships one. + +**Pass/fail for this section:** all five installed; `dumpbin /?` runs; the SkeletonBasics and +KinectExplorer samples build and launch (they will show "no Kinect" until Steps 4-5 attach a +virtual device); the real `Kinect10.dll` path(s) recorded for forwarding. + +--- + +## 2. Bitness capture (risk B - settle first, it is cheap and project-defining) + +From a **Developer Command Prompt for VS** in the DEA directory: + +``` +dumpbin /headers gamekdm.dll > %TEMP%\gamekdm_headers.txt +dumpbin /imports gamekdm.dll > %TEMP%\gamekdm_imports.txt +dumpbin /exports gamekdm.dll > %TEMP%\gamekdm_exports.txt +``` + +**What to read and record:** + +- **Architecture** - in `gamekdm_headers.txt`, the `FILE HEADER VALUES` line `machine`: + - `14C machine (x86)` -> **DEA is 32-bit** (the expected case - record "x86"). + - `8664 machine (x64)` -> **DEA is 64-bit** (record "x64"). + - Also note the `magic` in `OPTIONAL HEADER VALUES` (`10B` = PE32/x86, `20B` = PE32+/x64) as a + cross-check. +- **Kinect import surface** - in `gamekdm_imports.txt`, find the `Kinect10.dll` import block and + record **every** imported symbol verbatim (e.g. `NuiInitialize`, `NuiShutdown`, + `NuiGetSensorCount`, `NuiCreateSensorByIndex`/`NuiCreateSensorById`, `NuiSkeletonTrackingEnable`, + `NuiSkeletonGetNextFrame`, `NuiImageStreamOpen`, `NuiImageStreamGetNextFrame`, + `NuiImageStreamReleaseFrame`, `NuiTransformSmooth`, the `NuiTransform*` coordinate mappers, etc.). + This exact list is the ABI surface the Step 3 forwarding shim must re-export **and** the surface + the todo-14 clean-room fallback `Kinect10.dll` must implement (no fewer exports than DEA imports, + `__stdcall`/`WINAPI` decoration matched bit-for-bit). + - Note whether `Kinect10.dll` is imported **statically** (named in the import table) or resolved + dynamically via `LoadLibrary`/`GetProcAddress`, or via **COM `CoCreateInstance`** (a CLSID, not a + named import). If it is not in the static import table, Step 3's search-order shadowing may not + fire - see the Step 3 failure branch. + +**Decision this step gates:** the SHIPPING Windows architecture for todos 1, 12, 14. Per the plan, +scaffold both x86 and x64 but build the real driver/shim for whatever `machine` says here. DEA is +**likely x86**; if so, the entire Windows shim/driver chain is x86, and any x64 artifact is a smoke +build only. + +**Pass/fail:** `machine` recorded (x86 vs x64) with the `magic` cross-check; the complete +`Kinect10.dll` import list archived; linkage style (static import vs dynamic vs COM) noted. All three +`dumpbin` output files saved under `.omo/evidence/task-4-webcam-kinect-emulator.*`. + +--- + +## 3. Pass-through logging `Kinect10.dll` (risk A - learn DEA's exact NUI call pattern) + +Goal: a drop-in `Kinect10.dll` placed beside `gamekdm.dll` that **forwards every export to the real +`Kinect10.dll`** and **logs** each call's name, arguments, flags, requested resolution, return code, +and which event handles DEA waits on - WITHOUT modifying the game binary. Reference +`.omo/design/nui-contracts.md` §3.2 for the init sequence you are trying to observe and §5 for the +open questions this log resolves. + +### 3a. Build the forwarding shim (choose ONE technique) + +Build it for the **same arch as Step 2** (x86 if DEA is x86). MSVC authoritative. + +- **Technique A - linker export forwarding (simplest, no code for pure forwarding, but to log you + need stubs).** For a *logging* shim, write a thin stub per imported export that logs then tail-calls + the real function. Load the real DLL by its full System32/SysWOW64 path at `DllMain` + `DLL_PROCESS_ATTACH`: + ```cpp + // sketch - real project lives in tools/logging-shim/ + static HMODULE g_real; // real Kinect10.dll + BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) { + if (reason == DLL_PROCESS_ATTACH) { + OpenLog("kinect10_shim.log"); + g_real = LoadLibraryW(L"C:\\Windows\\SysWOW64\\Kinect10.dll"); // real one, full path + Log("DllMain ATTACH, real=%p", g_real); + } + return TRUE; + } + // one stub per export from Step 2's import list, exact __stdcall decoration: + extern "C" HRESULT __stdcall NuiInitialize(DWORD dwFlags) { + Log("NuiInitialize flags=0x%08X", dwFlags); + auto fn = (HRESULT(__stdcall*)(DWORD))GetProcAddress(g_real, "NuiInitialize"); + HRESULT hr = fn(dwFlags); + Log("NuiInitialize -> 0x%08X", hr); + return hr; + } + ``` + Provide a `.def` file listing **exactly** the exports DEA imports (from Step 2), each with the + correct ordinal/decoration, so `gamekdm.dll` binds to your stubs. For functions you do not need to + inspect, you may still forward via the `.def` `EXPORTS Name=RealModule.Name` syntax (pure + forwarder, no log line). +- **Technique B - Microsoft Detours / MinHook** inline-hooking the real `Kinect10.dll` after it + loads. Heavier; use only if export-shadowing (Technique A) does not fire (see failure branch). + +### 3b. Install and capture + +1. Copy the built `Kinect10.dll` (logging shim) into the DEA directory **beside `gamekdm.dll`**. + Back up / do not overwrite the system `Kinect10.dll`. +2. Boot DEA through spice2x **with the Kinect bypass** so it passes the boot presence check and + reaches gameplay. +3. Play/observe enough to enter a dance so DEA opens its streams and consumes skeleton frames. +4. Capture `kinect10_shim.log`. + +### 3c. What to extract from the log (fills nui-contracts §3.2 / §5 open items) + +Record, each backed by a log line: + +- **`DllMain` attach** fired (confirms the shim is the loaded module - risk C). +- **`NuiInitialize` flags** - exact `dwFlags` (e.g. `USES_DEPTH_AND_PLAYER_INDEX | USES_COLOR | + USES_SKELETON`, or a subset). Settles which streams DEA actually gates on. +- **`NuiImageStreamOpen` calls** - for each: `eImageType` (depth / depth+player-index / color), + `eResolution` (the exact enum - settles nui-contracts §5 open item 1: 640x480 vs 320x240 vs 80x60), + `dwImageFrameFlags`, `dwFrameLimit`, and whether an event handle is passed. +- **Skeleton model** - `NuiSkeletonTrackingEnable` flags; and whether DEA uses the **event** model + (waits on the skeleton event via `WaitForSingleObject`/`WaitForMultipleObjects` then + `NuiSkeletonGetNextFrame`) or **polls** (`NuiSkeletonGetNextFrame(0)` in a loop). Log the + `dwMillisecondsToWait` values. +- **Bone orientations** - whether DEA calls `NuiSkeletonCalculateBoneOrientations` (settles + nui-contracts §5 open item 4). +- **Coordinate mappers** - which `NuiTransform*` / `INuiCoordinateMapper` calls DEA makes. +- **Return-code expectations** - which HRESULTs DEA tolerates (e.g. `E_NUI_FRAME_NO_DATA`, + `S_FALSE`) vs. which make it drop the player. + +**Pass/fail:** `kinect10_shim.log` shows the `DllMain` attach line AND a captured call sequence +through `NuiInitialize` -> stream opens -> skeleton frame consumption during actual gameplay. If you +got init flags, the opened streams + resolutions, and the skeleton-vs-poll model each from a log +line, this step **passes**. + +**Failure branch (risk C - shim not the loaded module):** if `DllMain` never logs or DEA still binds +the system `Kinect10.dll`, the DLL search order was bypassed (fully-qualified `LoadLibrary` path, +SxS/manifest redirect, `KnownDLLs`, COM-by-CLSID activation, or a spice2x loader hook). Document how +the real DLL is being resolved (use **Process Monitor** to see the actual `Kinect10.dll` load path, +and **Dependencies**/`dumpbin /dependents` + the Step 2 linkage note). Workaround: switch to +Technique B (Detours/MinHook) hooking the resolved module, or - if COM-activated - register a proxy +CLSID. Record the resolution path and the workaround used. + +--- + +## 4. usbip-win binding test (gates todo 12 - device-level path) + +Goal: prove the real Windows Kinect stack (`kinectsensor.inf` driver + MS NUI runtime) will +**enumerate and bind** to a *virtual* USB device presenting the Kinect v1 identity and composite +topology, with **no physical Kinect**. This establishes what the MS driver requires beyond +libfreenect's Linux init (from todo 3). + +### 4a. Enable virtual-device drivers + +- Enable **test-signing** and/or disable **Secure Boot** so the (test-signed) `usbip-win` VHCI bus + driver loads: + ``` + bcdedit /set testsigning on + ``` + Reboot. (If Secure Boot blocks test-signing, disable Secure Boot in firmware first.) Record the + exact signing posture used - the driver must be installed the same way on the user's real machine. +- Install the `usbip-win` VHCI driver (`usbip.exe`/`usbipd` + the VHCI bus `.inf`) per its README. + +### 4b. Present the synthetic Kinect device + +- Stand up a `usbip` server exporting a **synthetic composite device** that advertises the Kinect v1 + identity and interface topology captured by **todo 3 (Linux spike)**: + - **VID/PID** of the Kinect v1 sensor (the NUI camera; `045E:02AE` for the Kinect-for-Xbox camera + interface - use the exact IDs the todo-3 descriptor capture recorded, including the audio/motor + PIDs for the composite set). + - The **composite topology**: camera + audio + motor interfaces as separate functions, matching the + descriptor set from todo 3. `kinectsensor.inf` binds per-interface; a single flat interface will + not match. +- `usbip attach` the device into the Windows VHCI so it appears in the local USB tree. + +### 4c. Verify binding + +- **Device Manager** - the sensor appears and binds to the Kinect driver (no yellow-bang) under the + expected device class. Record the driver name and INF (`kinectsensor.inf`). +- **MS NUI runtime enumerates it** - run the Kinect SDK sample (**KinectExplorer-D2D**) or call + `NuiGetSensorCount` -> `>= 1`, and `NuiCreateSensorByIndex(0, ...)` succeeds. (At this stage the + streams may error because no frame data is being served yet - that is expected; Step 5 serves + data.) +- **Record what the MS driver needs beyond libfreenect's Linux init** - compare against todo 3's + capture: does the Windows driver perform/require a **firmware upload** handshake (Kinect v1's + audio firmware / the two-stage boot where the bootloader PID changes to the running PID)? + Additional **control transfers**, **SET_CONFIGURATION**, per-interface **alt-settings**, specific + **power/`bmAttributes`** descriptor fields, or isochronous endpoint descriptors the Linux stack + tolerated but Windows demands? Capture Windows-side USB traffic with **Wireshark + USBPcap** while + the driver binds and record every transfer the MS driver initiates that the Linux init did not. + +**Pass/fail:** Device Manager shows the virtual sensor bound to `kinectsensor.inf` with no error AND +`NuiGetSensorCount >= 1` / `NuiCreateSensorByIndex` succeeds against the virtual device. Record the +delta list (what MS requires beyond libfreenect). If binding fails, record the exact driver error / +USB request that failed - that is the todo-12 work item. + +--- + +## 5. CRUX - synthetic-depth skeletonization on the real MS NUI runtime (hardware-free KILL-GATE) + +This is the **Windows half of the depth-fidelity kill-gate** (nui-contracts risk D / plan +"KILL-GATE"). It proves - with **no physical Kinect** - that the real MS NUI runtime can +skeletonize our **synthetic** depth. If it fails, the device-level approach is invalid and the +project must re-plan the depth model. + +### 5a. Build a canned synthetic articulated-depth sequence + +- Generate (offline, on any machine) a short looped sequence of **synthetic depth frames** in the + Kinect v1 packed format (`((depth_mm & 0x1FFF) << 3) | (playerIndex & 0x7)`, per nui-contracts + §2.2) at the resolution Step 3 found DEA/the SDK requests (settle from Step 3; default 640x480 or + 320x240 per nui-contracts §5 open item 1). The sequence must depict a **moving articulated human + silhouette** - e.g. a figure raising and lowering both arms over ~2-3 seconds, looping - with: + - a single filled, human-shaped, temporally-stable blob (largest connected component), + - body depth in ~800-4000mm, background = 0, player-index = 1 on the body (nui-contracts §2.4), + - enough articulation (arm/leg motion) that a working skeletonizer would output **moving joints**. + - Build it from nui-contracts §1/§2 rasterization (silhouette from a canned MediaPipe pose + sequence, or a hand-authored rig) so it is representative of what the real pipeline will emit. + Keep it deterministic and replayable (the record/replay harness, tools/record-replay). + +### 5b. Replay it into the real MS NUI runtime via the virtual device + +- Extend the Step 4 minimal virtual device so its **camera/depth endpoint serves the canned + synthetic depth sequence** on the Kinect v1 iso/bulk framing (reuse the todo-3 stream framing), + looping at ~30Hz. (Serve a static or black color frame if the SDK requires the color stream to be + open.) No webcam, no MediaPipe live - a pure canned replay. +- Attach the device (Step 4). The MS NUI runtime now receives synthetic depth as if from a real + sensor. + +### 5c. Capture skeleton output from a Kinect SDK sample + +- Run **SkeletonBasics-D2D** (or KinectExplorer-D2D) against the virtual device with skeleton + tracking enabled. These samples call the real `NuiSkeleton*` pipeline - the MS runtime's internal + skeletonizer - on the incoming depth. +- **Capture the skeleton output**: record the rendered skeleton overlay (video capture of the + sample window) AND, better, log the `NUI_SKELETON_FRAME` joint positions per frame from a small + instrumented consumer (or the shim's `NuiSkeletonGetNextFrame` log from Step 3) to a file. + +### 5d. The exact pass/fail + +- **PASS** if the real MS NUI runtime produces a **TRACKED skeleton whose joints MOVE in + correspondence with the synthetic sequence's articulation** (e.g. the wrists/elbows rise and fall + as the canned figure raises its arms), captured as joint-position logs and/or recorded overlay. + This proves synthetic depth is skeletonizable and **unblocks waves 4-11**. +- **FAIL** if the runtime reports NO tracked skeleton, or an all-`NOT_TRACKED`/frozen skeleton, or + joints that do not follow the synthetic motion. In this case **HALT and re-plan the depth model** + (the flat/billboard synthesis is insufficient for the MS skeletonizer - escalate to a + monocular-depth network producing a denser, more sensor-like depth map) before building the + mapping/synth/emitter waves. Do **not** claim the crux passed without captured moving-joint + skeleton output. +- If a **real Kinect is available**, additionally A/B real-sensor depth vs. the synthetic replay + through the same sample to gauge how close the synthetic depth must be (scorer/skeletonizer + z-sensitivity). Record the delta; it informs depthGain / depth-tier choices (nui-contracts §1.5, + §2.3). + +**This is the gate.** Nothing downstream on the device path is proven until this captures moving +joints from synthetic depth on the real runtime. + +--- + +## 6. Go/no-go per OS (fill after Steps 2-5 run on Windows) + +| Decision | Determined by | Result (fill on Windows) | +|---|---|---| +| Shipping Windows arch (x86/x64) | Step 2 `machine` | _unset - run dumpbin_ | +| Device-level path viable (todo 12) | Step 4 binding + Step 5 crux | _unset_ | +| NUI-shim fallback is PRIMARY or SECONDARY (todo 14) | Step 3 import surface + Step 5 crux | _unset_ | +| Depth model OK, or HALT + re-plan | **Step 5 crux PASS/FAIL** | _unset - CRUX UNPROVEN_ | + +- Device path requires **both** Step 4 (binds) **and** Step 5 (crux passes). If Step 5 fails, the + device path cannot prove IS-2 regardless of Step 4; HALT. +- The NUI-shim fallback (todo 14) is **unconditionally in scope**; this spike only sets whether it + is the PRIMARY Windows path (if the device path is not viable) or the secondary surface. The shim + proves playability (IS-3/IS-4) only - never IS-1/IS-2. + +--- + +## Results ledger (to be filled on the Windows box - empty here by design) + +All cells below are **UNSET**; this environment cannot produce them. + +- **Step 2 bitness:** `machine` = _____ (x86 expected); `magic` = _____. +- **Step 2 `Kinect10.dll` imports:** _____ (paste full list; archive `gamekdm_imports.txt`). +- **Step 2 linkage:** static import / dynamic `LoadLibrary` / COM-CLSID = _____. +- **Step 3 `DllMain` attach:** logged? _____ (shim is the loaded module Y/N; if N, resolution path). +- **Step 3 `NuiInitialize` flags:** 0x_____ = _____. +- **Step 3 streams opened:** type/resolution/flags per `NuiImageStreamOpen` = _____. +- **Step 3 skeleton model:** event / poll = _____; `NuiSkeletonCalculateBoneOrientations` called? ___. +- **Step 4 binding:** Device Manager bound to `kinectsensor.inf`? _____; `NuiGetSensorCount` = ___. +- **Step 4 MS-vs-libfreenect delta:** firmware upload / control transfers / power = _____. +- **Step 5 CRUX:** moving skeleton from synthetic depth? **PASS / FAIL** = _____ (attach capture). +- **Signing posture used (Step 4):** testsigning / Secure Boot = _____. + +Evidence goes to `.omo/evidence/task-4-webcam-kinect-emulator.*` (dumpbin outputs, `kinect10_shim.log`, +USBPcap capture, Step 5 skeleton log + overlay recording). diff --git a/tests/test_contract.cpp b/tests/test_contract.cpp new file mode 100644 index 0000000..d5f1ada --- /dev/null +++ b/tests/test_contract.cpp @@ -0,0 +1,88 @@ +#include + +#include "contract/contract.h" + +using namespace nui::contract; + +TEST(Contract, VersionIsSet) { + EXPECT_EQ(contract_version(), 1); + EXPECT_EQ(kContractVersion, 1u); +} + +TEST(Contract, GoldenSizes) { + EXPECT_EQ(sizeof(Vector4), 16u); + EXPECT_EQ(sizeof(JointData), 20u); + EXPECT_EQ(sizeof(SkeletonFrame), 408u); + EXPECT_EQ(sizeof(DepthBufferDescriptor), 20u); + EXPECT_EQ(sizeof(ColorBufferDescriptor), 20u); + EXPECT_EQ(sizeof(FrameData), 460u); + EXPECT_EQ(sizeof(FrameSlot), 468u); + EXPECT_EQ(sizeof(FrameContract), 1420u); + EXPECT_EQ(sizeof(ControlMessageHeader), 16u); + EXPECT_EQ(sizeof(HandshakeMessage), 24u); + EXPECT_EQ(sizeof(ConfigMessage), 32u); + EXPECT_EQ(sizeof(CalibrationMessage), 40u); + EXPECT_EQ(sizeof(HeartbeatMessage), 32u); +} + +TEST(Contract, GoldenOffsets) { + EXPECT_EQ(offsetof(SkeletonFrame, skeleton_tracking_id), 400u); + EXPECT_EQ(offsetof(SkeletonFrame, quality_flags), 404u); + EXPECT_EQ(offsetof(FrameData, skeleton), 12u); + EXPECT_EQ(offsetof(FrameData, depth), 420u); + EXPECT_EQ(offsetof(FrameData, color), 440u); + EXPECT_EQ(offsetof(FrameContract, slots), 16u); +} + +TEST(Contract, PublishThenReadReturnsLatestFrame) { + FrameContract contract{}; + contract.contract_version = kContractVersion; + + FrameData frame_a{}; + frame_a.frame_number = 1; + frame_a.timestamp_micros = 1000; + frame_a.skeleton.joints[0].position = {0.1f, 0.2f, 2.5f, 1.0f}; + frame_a.skeleton.joints[0].tracking_state = JointTrackingState::TRACKED; + frame_a.skeleton.skeleton_tracking_id = 7; + publish_frame(contract, frame_a); + + FrameData frame_b = frame_a; + frame_b.frame_number = 2; + frame_b.timestamp_micros = 1033; + frame_b.skeleton.joints[0].position.x = 0.15f; + publish_frame(contract, frame_b); + + FrameData out{}; + read_latest_frame(contract, out); + + EXPECT_EQ(out.frame_number, 2u); + EXPECT_EQ(out.timestamp_micros, 1033); + EXPECT_FLOAT_EQ(out.skeleton.joints[0].position.x, 0.15f); + EXPECT_EQ(out.skeleton.skeleton_tracking_id, 7u); +} + +TEST(Contract, PublishCyclesThroughAllSlotsNewestWins) { + FrameContract contract{}; + for (uint32_t i = 1; i <= kFrameSlotCount * 2; ++i) { + FrameData frame{}; + frame.frame_number = i; + publish_frame(contract, frame); + + FrameData out{}; + read_latest_frame(contract, out); + EXPECT_EQ(out.frame_number, i); + } +} + +TEST(Contract, ControlMessageHeaderCarriesContractVersion) { + HeartbeatMessage hb{}; + hb.header.message_type = ControlMessageType::HEARTBEAT; + hb.header.contract_version = kContractVersion; + hb.header.payload_size = sizeof(HeartbeatMessage); + hb.timestamp_micros = 42; + hb.sequence = 9; + + EXPECT_EQ(hb.header.message_type, ControlMessageType::HEARTBEAT); + EXPECT_EQ(hb.header.contract_version, kContractVersion); + EXPECT_EQ(hb.header.payload_size, sizeof(HeartbeatMessage)); +} diff --git a/tests/test_contract_py.py b/tests/test_contract_py.py new file mode 100644 index 0000000..38cb492 --- /dev/null +++ b/tests/test_contract_py.py @@ -0,0 +1,123 @@ +import ctypes +import os +import re +import subprocess +import sys + +import pytest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from tracker import contract as py # noqa: E402 + +DUMP_BINARY = os.path.join(ROOT, "build", "linux", "contract_layout_dump") + + +def _c_layout(): + if not os.path.exists(DUMP_BINARY): + pytest.skip(f"contract_layout_dump not built at {DUMP_BINARY}; run cmake --build first") + output = subprocess.run([DUMP_BINARY], capture_output=True, text=True, check=True).stdout + values = {} + for line in output.splitlines(): + match = re.match(r"^([A-Za-z0-9_(),]+)=(\d+)$", line) + assert match, f"unparseable contract_layout_dump line: {line!r}" + values[match.group(1)] = int(match.group(2)) + return values + + +@pytest.fixture(scope="module") +def c_layout(): + return _c_layout() + + +def test_contract_version_matches_c(c_layout): + assert py.CONTRACT_VERSION == c_layout["CONTRACT_VERSION"] + assert py.JOINT_COUNT == c_layout["JOINT_COUNT"] + assert py.FRAME_SLOT_COUNT == c_layout["FRAME_SLOT_COUNT"] + + +@pytest.mark.parametrize( + "py_type,c_name", + [ + (py.Vector4, "Vector4"), + (py.JointData, "JointData"), + (py.SkeletonFrame, "SkeletonFrame"), + (py.DepthBufferDescriptor, "DepthBufferDescriptor"), + (py.ColorBufferDescriptor, "ColorBufferDescriptor"), + (py.FrameData, "FrameData"), + (py.FrameSlot, "FrameSlot"), + (py.FrameContract, "FrameContract"), + (py.ControlMessageHeader, "ControlMessageHeader"), + (py.HandshakeMessage, "HandshakeMessage"), + (py.ConfigMessage, "ConfigMessage"), + (py.CalibrationMessage, "CalibrationMessage"), + (py.HeartbeatMessage, "HeartbeatMessage"), + ], +) +def test_struct_sizeof_matches_c(c_layout, py_type, c_name): + assert ctypes.sizeof(py_type) == c_layout[f"sizeof({c_name})"] + + +@pytest.mark.parametrize( + "py_type,c_name,field", + [ + (py.Vector4, "Vector4", "x"), + (py.Vector4, "Vector4", "y"), + (py.Vector4, "Vector4", "z"), + (py.Vector4, "Vector4", "w"), + (py.JointData, "JointData", "position"), + (py.JointData, "JointData", "tracking_state"), + (py.SkeletonFrame, "SkeletonFrame", "joints"), + (py.SkeletonFrame, "SkeletonFrame", "skeleton_tracking_id"), + (py.SkeletonFrame, "SkeletonFrame", "quality_flags"), + (py.DepthBufferDescriptor, "DepthBufferDescriptor", "width"), + (py.DepthBufferDescriptor, "DepthBufferDescriptor", "height"), + (py.DepthBufferDescriptor, "DepthBufferDescriptor", "pitch"), + (py.DepthBufferDescriptor, "DepthBufferDescriptor", "byte_offset"), + (py.ColorBufferDescriptor, "ColorBufferDescriptor", "width"), + (py.ColorBufferDescriptor, "ColorBufferDescriptor", "height"), + (py.ColorBufferDescriptor, "ColorBufferDescriptor", "pitch"), + (py.ColorBufferDescriptor, "ColorBufferDescriptor", "byte_offset"), + (py.FrameData, "FrameData", "frame_number"), + (py.FrameData, "FrameData", "timestamp_micros"), + (py.FrameData, "FrameData", "skeleton"), + (py.FrameData, "FrameData", "depth"), + (py.FrameData, "FrameData", "color"), + (py.FrameSlot, "FrameSlot", "sequence"), + (py.FrameSlot, "FrameSlot", "data"), + (py.FrameContract, "FrameContract", "contract_version"), + (py.FrameContract, "FrameContract", "reserved"), + (py.FrameContract, "FrameContract", "published_sequence"), + (py.FrameContract, "FrameContract", "slots"), + (py.ControlMessageHeader, "ControlMessageHeader", "message_type"), + (py.ControlMessageHeader, "ControlMessageHeader", "contract_version"), + (py.ControlMessageHeader, "ControlMessageHeader", "payload_size"), + (py.ControlMessageHeader, "ControlMessageHeader", "reserved"), + (py.HandshakeMessage, "HandshakeMessage", "header"), + (py.HandshakeMessage, "HandshakeMessage", "client_version"), + (py.HandshakeMessage, "HandshakeMessage", "capabilities"), + (py.ConfigMessage, "ConfigMessage", "header"), + (py.ConfigMessage, "ConfigMessage", "depth_width"), + (py.ConfigMessage, "ConfigMessage", "depth_height"), + (py.ConfigMessage, "ConfigMessage", "color_width"), + (py.ConfigMessage, "ConfigMessage", "color_height"), + (py.CalibrationMessage, "CalibrationMessage", "header"), + (py.CalibrationMessage, "CalibrationMessage", "z0_meters"), + (py.CalibrationMessage, "CalibrationMessage", "mirror"), + (py.CalibrationMessage, "CalibrationMessage", "floor_plane"), + (py.HeartbeatMessage, "HeartbeatMessage", "header"), + (py.HeartbeatMessage, "HeartbeatMessage", "timestamp_micros"), + (py.HeartbeatMessage, "HeartbeatMessage", "sequence"), + ], +) +def test_struct_offsetof_matches_c(c_layout, py_type, c_name, field): + py_offset = getattr(py_type, field).offset + assert py_offset == c_layout[f"offsetof({c_name},{field})"] + + +def test_frame_contract_total_size_fits_slots(): + header_size = ctypes.sizeof(ctypes.c_uint32) * 2 + ctypes.sizeof(ctypes.c_uint64) + assert ctypes.sizeof(py.FrameContract) == ( + header_size + py.FRAME_SLOT_COUNT * ctypes.sizeof(py.FrameSlot) + ) diff --git a/tests/test_core.cpp b/tests/test_core.cpp index 971cc4e..bbdd764 100644 --- a/tests/test_core.cpp +++ b/tests/test_core.cpp @@ -7,7 +7,7 @@ // Scaffold smoke test: proves libnui_core compiles, links, and its placeholder // symbols are callable. Real per-module suites replace/extend this in todos 2/6/7. TEST(ScaffoldSmoke, CoreSymbolsLinkAndReturnPlaceholders) { - EXPECT_EQ(nui::contract::contract_version(), 0); + EXPECT_EQ(nui::contract::contract_version(), static_cast(nui::contract::kContractVersion)); EXPECT_EQ(nui::mapping::kinect_joint_count(), 20); // Depth packing layout sanity: 1000mm, player 1 -> (1000<<3)|1. EXPECT_EQ(nui::synth::pack_depth(1000, 1), diff --git a/tracker/contract.py b/tracker/contract.py new file mode 100644 index 0000000..b2bde1d --- /dev/null +++ b/tracker/contract.py @@ -0,0 +1,167 @@ +"""ctypes mirror of core/contract/contract.h (plan todo 2). + +This module hand-mirrors the frozen, packed C struct layout so the Python +tracker and the C++ core agree byte-for-byte on the shared-memory frame +contract and the control-plane message schema. It is frozen the same way the +C header is: any field-shape change here must be paired with the matching C +change and a CONTRACT_VERSION bump, and tests/test_contract_py.py checks this +mirror against the C header's actual, freshly-compiled layout (never a +hardcoded golden copy on either side) so the two cannot silently drift apart. +""" + +import ctypes + +CONTRACT_VERSION = 1 +JOINT_COUNT = 20 +FRAME_SLOT_COUNT = 3 + + +class JointTrackingState: + NOT_TRACKED = 0 + INFERRED = 1 + TRACKED = 2 + + +class ControlMessageType: + HANDSHAKE_VERSION = 0 + CONFIG = 1 + CALIBRATION = 2 + HEARTBEAT = 3 + + +class Vector4(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("x", ctypes.c_float), + ("y", ctypes.c_float), + ("z", ctypes.c_float), + ("w", ctypes.c_float), + ] + + +class JointData(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("position", Vector4), + ("tracking_state", ctypes.c_uint32), + ] + + +class SkeletonFrame(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("joints", JointData * JOINT_COUNT), + ("skeleton_tracking_id", ctypes.c_uint32), + ("quality_flags", ctypes.c_uint32), + ] + + +class DepthBufferDescriptor(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("width", ctypes.c_uint32), + ("height", ctypes.c_uint32), + ("pitch", ctypes.c_uint32), + ("byte_offset", ctypes.c_uint64), + ] + + +class ColorBufferDescriptor(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("width", ctypes.c_uint32), + ("height", ctypes.c_uint32), + ("pitch", ctypes.c_uint32), + ("byte_offset", ctypes.c_uint64), + ] + + +class FrameData(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("frame_number", ctypes.c_uint32), + ("timestamp_micros", ctypes.c_int64), + ("skeleton", SkeletonFrame), + ("depth", DepthBufferDescriptor), + ("color", ColorBufferDescriptor), + ] + + +class FrameSlot(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("sequence", ctypes.c_uint64), + ("data", FrameData), + ] + + +class FrameContract(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("contract_version", ctypes.c_uint32), + ("reserved", ctypes.c_uint32), + ("published_sequence", ctypes.c_uint64), + ("slots", FrameSlot * FRAME_SLOT_COUNT), + ] + + +class ControlMessageHeader(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("message_type", ctypes.c_uint32), + ("contract_version", ctypes.c_uint32), + ("payload_size", ctypes.c_uint32), + ("reserved", ctypes.c_uint32), + ] + + +class HandshakeMessage(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("header", ControlMessageHeader), + ("client_version", ctypes.c_uint32), + ("capabilities", ctypes.c_uint32), + ] + + +class ConfigMessage(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("header", ControlMessageHeader), + ("depth_width", ctypes.c_uint32), + ("depth_height", ctypes.c_uint32), + ("color_width", ctypes.c_uint32), + ("color_height", ctypes.c_uint32), + ] + + +class CalibrationMessage(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("header", ControlMessageHeader), + ("z0_meters", ctypes.c_float), + ("mirror", ctypes.c_uint32), + ("floor_plane", ctypes.c_float * 4), + ] + + +class HeartbeatMessage(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" + _fields_ = [ + ("header", ControlMessageHeader), + ("timestamp_micros", ctypes.c_int64), + ("sequence", ctypes.c_uint64), + ]