feat(calibration,contract,tracker): T-pose calibration + seqlock fix + articulated-depth wiring (wave 8a; todos 11,20,21 done)
ci / Linux C++ core (cmake + ctest) (push) Canceled after 0s
ci / Python tracker (pytest) (push) Canceled after 0s

This commit is contained in:
kinect-bot committed 2026-11-25 05:47:19 -05:00
1 parent b1638944cb
commit 0af22f1783
16 files changed
+733 -49

No files matched your search

+3 -3
View File
@@ -218,7 +218,7 @@ Your next move: run the default-on high-accuracy review (in progress), then exec
Commit: Y | test(e2e-linux): webcam->virtual kinect stream+skeleton validation
Recommended task executor category: deep-low - end-to-end integration debugging on Linux.
- [ ] 11. Calibration + config
- [x] 11. Calibration + config
What to do / Must NOT do: In `core/calibration/`, add a one-time calibration (T-pose) fixing Z0 (root depth / scale via shoulder-width target), floor plane, camera mirror bit, and player-space scaling; persist a config file (resolutions, depthGain, smoothing params, mirror, Z0). Add a confirm step for the mirror bit (raise-right-arm check). Must NOT: bake machine-specific constants into source - keep them in config.
Closes: GAP-5
Parallelization: Wave 8 | Blocked by: 10 | Blocks: 13
@@ -305,11 +305,11 @@ Your next move: run the default-on high-accuracy review (in progress), then exec
Closes: follow-up from the Wave 3 verifier (CI hygiene; non-blocking).
Recommended task executor category: quick
- [ ] 20. Fix seqlock sequence mismatch between contract.cpp and the tracker publisher
- [x] 20. Fix seqlock sequence mismatch between contract.cpp and the tracker publisher
What to do: core/contract/contract.cpp read_latest_frame assumes slot.sequence == published*2, but tracker/publisher.py increments each slot's own prior value; align the reference reader and producer to ONE seqlock convention so publish_frame/read_latest_frame and the live pipeline agree. Add/extend a test.
Closes: defect found in todo 10 integration.
Recommended task executor category: deep-low
- [ ] 21. Wire tracker/synth depth through core/mapping Z0 placement (articulated, not flat)
- [x] 21. Wire tracker/synth depth through core/mapping Z0 placement (articulated, not flat)
What to do: tracker/publisher.py passes MediaPipe raw hip-centered world-Z straight through, so live depth pegs flat at the 800mm floor instead of articulated per-joint depth (Z0 + depthGain*worldZ) from core/mapping (todo 6). Route live depth through the mapping Z0/depthGain placement so the OpenNI2/e2e depth is articulated across the body. Re-run the todo-10 e2e and show per-pixel depth spread (not pegged).
Closes: fidelity defect found in todo 10 integration.
Recommended task executor category: deep-low
+12
View File
@@ -11,6 +11,7 @@ set(CMAKE_CXX_EXTENSIONS OFF)
# these sources are compile/link placeholders today.
# ---------------------------------------------------------------------------
add_library(libnui_core STATIC
core/calibration/calibration.cpp
core/contract/contract.cpp
core/mapping/mapping.cpp
core/synth/mask_stabilizer.cpp
@@ -32,6 +33,9 @@ target_include_directories(libnui_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/core)
add_executable(contract_layout_dump core/contract/contract_layout_dump.cpp)
target_link_libraries(contract_layout_dump PRIVATE libnui_core)
add_executable(contract_reader_probe tests/contract_reader_probe.cpp)
target_link_libraries(contract_reader_probe PRIVATE libnui_core)
# ---------------------------------------------------------------------------
# Tests: GoogleTest via FetchContent + CTest.
# ---------------------------------------------------------------------------
@@ -51,6 +55,7 @@ if(NUI_CORE_BUILD_TESTS)
enable_testing()
add_executable(libnui_core_tests
tests/test_core.cpp
tests/test_calibration.cpp
tests/test_contract.cpp
tests/test_mapping.cpp
tests/test_synth.cpp
@@ -60,4 +65,11 @@ if(NUI_CORE_BUILD_TESTS)
include(GoogleTest)
gtest_discover_tests(libnui_core_tests)
add_test(
NAME Contract.PythonProducerCppReaderInterop
COMMAND
${CMAKE_CURRENT_SOURCE_DIR}/tracker/.venv/bin/python
${CMAKE_CURRENT_SOURCE_DIR}/tests/contract_interop_driver.py
$<TARGET_FILE:contract_reader_probe>
)
endif()
+133
View File
@@ -0,0 +1,133 @@
#include "calibration/calibration.h"
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
namespace nui::calibration {
namespace {
constexpr float kProjectionScale = 3.501e-3f;
constexpr float kMinZ = 0.8f;
constexpr float kMaxZ = 4.0f;
bool finite(float value) {
return std::isfinite(value);
}
} // namespace
bool confirm_mirror_raise_right_arm(
const RaiseRightArmObservation& observation,
bool& mirror,
std::string& error) {
const bool right_raised =
observation.right_wrist_v < observation.right_shoulder_v;
const bool left_lowered =
observation.left_wrist_v >= observation.left_shoulder_v;
if (!observation.person_detected || !right_raised || !left_lowered) {
error = "mirror confirmation requires only the right arm raised";
return false;
}
mirror = observation.right_wrist_u < observation.right_shoulder_u;
error.clear();
return true;
}
bool calibrate_tpose(
const TposeObservation& observation,
CalibrationConfig& output,
std::string& error) {
if (!observation.person_detected) {
error = "T-pose calibration requires one detected person";
return false;
}
if (!finite(observation.root_depth_meters) ||
!finite(observation.normalized_shoulder_width) ||
observation.normalized_shoulder_width <= 0.0f) {
error = "T-pose calibration observation is invalid";
return false;
}
CalibrationConfig candidate{};
candidate.mapping.z0_meters =
std::clamp(observation.root_depth_meters, kMinZ, kMaxZ);
candidate.mapping.depth_gain = 1.0f;
candidate.mapping.mirror = observation.mirror;
candidate.player_scale = kTargetShoulderWidthMeters /
(observation.normalized_shoulder_width * 320.0f *
kProjectionScale * candidate.mapping.z0_meters);
candidate.floor_plane = observation.floor_plane;
for (const float value : candidate.floor_plane) {
if (!finite(value)) {
error = "T-pose floor plane is invalid";
return false;
}
}
output = candidate;
error.clear();
return true;
}
bool save_config(
const CalibrationConfig& config,
const std::string& path,
std::string& error) {
std::ofstream file(path, std::ios::trunc);
if (!file) {
error = "could not open calibration config for writing";
return false;
}
file << std::setprecision(9)
<< "depth_width " << config.mapping.depth_width << '\n'
<< "depth_height " << config.mapping.depth_height << '\n'
<< "z0_meters " << config.mapping.z0_meters << '\n'
<< "depth_gain " << config.mapping.depth_gain << '\n'
<< "mirror " << config.mapping.mirror << '\n'
<< "player_scale " << config.player_scale << '\n'
<< "smoothing " << config.smoothing.smoothing << ' '
<< config.smoothing.correction << ' ' << config.smoothing.prediction
<< ' ' << config.smoothing.jitter_radius << ' '
<< config.smoothing.max_deviation_radius << '\n'
<< "floor_plane " << config.floor_plane[0] << ' '
<< config.floor_plane[1] << ' ' << config.floor_plane[2] << ' '
<< config.floor_plane[3] << '\n';
if (!file) {
error = "could not write calibration config";
return false;
}
error.clear();
return true;
}
bool load_config(
const std::string& path,
CalibrationConfig& output,
std::string& error) {
std::ifstream file(path);
CalibrationConfig candidate{};
std::string key;
if (!file ||
!(file >> key >> candidate.mapping.depth_width) || key != "depth_width" ||
!(file >> key >> candidate.mapping.depth_height) || key != "depth_height" ||
!(file >> key >> candidate.mapping.z0_meters) || key != "z0_meters" ||
!(file >> key >> candidate.mapping.depth_gain) || key != "depth_gain" ||
!(file >> key >> candidate.mapping.mirror) || key != "mirror" ||
!(file >> key >> candidate.player_scale) || key != "player_scale" ||
!(file >> key >> candidate.smoothing.smoothing >>
candidate.smoothing.correction >> candidate.smoothing.prediction >>
candidate.smoothing.jitter_radius >>
candidate.smoothing.max_deviation_radius) || key != "smoothing" ||
!(file >> key >> candidate.floor_plane[0] >> candidate.floor_plane[1] >>
candidate.floor_plane[2] >> candidate.floor_plane[3]) ||
key != "floor_plane") {
error = "could not parse calibration config";
return false;
}
output = candidate;
error.clear();
return true;
}
} // namespace nui::calibration
+64
View File
@@ -0,0 +1,64 @@
#ifndef NUI_CORE_CALIBRATION_H
#define NUI_CORE_CALIBRATION_H
#include <array>
#include <string>
#include "mapping/mapping.h"
namespace nui::calibration {
struct TposeObservation {
bool person_detected = false;
float root_depth_meters = 2.5f;
float normalized_shoulder_width = 0.0f;
std::array<float, 4> floor_plane{0.0f, 1.0f, 0.0f, 0.0f};
bool mirror = true;
};
struct RaiseRightArmObservation {
bool person_detected = false;
float right_shoulder_u = 0.0f;
float right_wrist_u = 0.0f;
float right_shoulder_v = 0.0f;
float right_wrist_v = 0.0f;
float left_shoulder_v = 0.0f;
float left_wrist_v = 0.0f;
};
struct CalibrationConfig {
mapping::MappingConfig mapping{};
mapping::SmoothingParameters smoothing{};
float player_scale = 1.0f;
std::array<float, 4> floor_plane{0.0f, 1.0f, 0.0f, 0.0f};
};
constexpr float kTargetShoulderWidthMeters = 0.40f;
// Mirror-confirm step: the subject raises only the anatomical right arm. A
// raw camera image places that arm on image-left, requiring the global mirror.
bool confirm_mirror_raise_right_arm(
const RaiseRightArmObservation& observation,
bool& mirror,
std::string& error);
// Produces the one-time T-pose calibration. The shoulder span establishes the
// player-space scale and Z0 preserves the observed root placement.
bool calibrate_tpose(
const TposeObservation& observation,
CalibrationConfig& output,
std::string& error);
bool save_config(
const CalibrationConfig& config,
const std::string& path,
std::string& error);
bool load_config(
const std::string& path,
CalibrationConfig& output,
std::string& error);
} // namespace nui::calibration
#endif // NUI_CORE_CALIBRATION_H
+6 -5
View File
@@ -8,9 +8,9 @@ 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.sequence;
slot.data = data;
slot.sequence = next_sequence * 2;
++slot.sequence;
contract.published_sequence = next_sequence;
}
@@ -19,12 +19,13 @@ void read_latest_frame(const FrameContract& contract, FrameData& out) {
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
if (seq_before & 1) {
continue; // mid-write
}
FrameData snapshot = slot.data;
const uint64_t seq_after = slot.sequence;
if (seq_after == seq_before) {
if (seq_after == seq_before &&
contract.published_sequence == published) {
out = snapshot;
return;
}
+6 -4
View File
@@ -147,9 +147,10 @@ static_assert(offsetof(FrameData, skeleton) == 12, "FrameData.skeleton golden of
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).
// One triple-buffer slot: a sequence counter guarding `data`. Each slot owns
// its generation: odd means its producer is writing and even means stable.
// A reader accepts only an unchanged even value before and after its copy;
// it must not derive this value from published_sequence because slots wrap.
struct FrameSlot {
uint64_t sequence;
FrameData data;
@@ -260,7 +261,8 @@ static_assert(offsetof(HeartbeatMessage, sequence) == 24, "HeartbeatMessage.sequ
// --- 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).
// oldest-but-one slot (single-writer only; never call concurrently). The slot
// sequence advances by one to odd before the write and one to even after it.
void publish_frame(FrameContract& contract, const FrameData& data);
// Snapshots the newest published frame into `out`. Retries internally against
+41
View File
@@ -0,0 +1,41 @@
"""CTest driver proving the C++ reader consumes Python publisher generations."""
from __future__ import annotations
import os
import subprocess
import sys
import uuid
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from tracker.fake_pose import make_fake_pose # noqa: E402
from tracker.publisher import FrameContractPublisher # noqa: E402
def main() -> int:
probe = sys.argv[1]
name = f"kinect_seqlock_{uuid.uuid4().hex}"
with FrameContractPublisher(
depth_size=(32, 24),
color_size=(32, 24),
name=name,
) as publisher:
for index in range(9):
publisher.publish(
make_fake_pose(index, image_width=32, image_height=24),
None,
)
result = subprocess.run(
[probe, name],
check=True,
capture_output=True,
text=True,
)
print(result.stdout, end="")
return 0 if "published=9 frame=9 slot_sequence=6" in result.stdout else 1
if __name__ == "__main__":
raise SystemExit(main())
+45
View File
@@ -0,0 +1,45 @@
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <cstdio>
#include <string>
#include "contract/contract.h"
int main(int argc, char** argv) {
if (argc != 2) {
return 2;
}
const std::string name = "/" + std::string(argv[1]);
const int fd = shm_open(name.c_str(), O_RDONLY, 0);
if (fd < 0) {
return 3;
}
void* map = mmap(
nullptr,
sizeof(nui::contract::FrameContract),
PROT_READ,
MAP_SHARED,
fd,
0);
if (map == MAP_FAILED) {
close(fd);
return 4;
}
const auto* contract =
static_cast<const nui::contract::FrameContract*>(map);
nui::contract::FrameData frame{};
nui::contract::read_latest_frame(*contract, frame);
std::printf(
"published=%llu frame=%u slot_sequence=%llu\n",
static_cast<unsigned long long>(contract->published_sequence),
frame.frame_number,
static_cast<unsigned long long>(
contract->slots[
contract->published_sequence % nui::contract::kFrameSlotCount]
.sequence));
munmap(map, sizeof(nui::contract::FrameContract));
close(fd);
return 0;
}
+90
View File
@@ -0,0 +1,90 @@
#include <gtest/gtest.h>
#include <cstdio>
#include "calibration/calibration.h"
namespace {
float reconstructed_shoulder_width(
const nui::calibration::CalibrationConfig& config,
float normalized_shoulder_width) {
return normalized_shoulder_width * 320.0f * 3.501e-3f *
config.mapping.z0_meters * config.player_scale;
}
} // namespace
TEST(calibration, TposeProducesTargetReconstructedShoulderWidth) {
nui::calibration::TposeObservation fixture{};
fixture.person_detected = true;
fixture.root_depth_meters = 2.4f;
fixture.normalized_shoulder_width = 0.18f;
fixture.floor_plane = {0.0f, 1.0f, 0.0f, -1.1f};
fixture.mirror = false;
nui::calibration::CalibrationConfig config{};
std::string error;
ASSERT_TRUE(nui::calibration::calibrate_tpose(fixture, config, error));
EXPECT_NEAR(config.mapping.z0_meters, 2.4f, 1e-6f);
EXPECT_FALSE(config.mapping.mirror);
EXPECT_NEAR(
reconstructed_shoulder_width(config, fixture.normalized_shoulder_width),
nui::calibration::kTargetShoulderWidthMeters,
1e-5f);
}
TEST(calibration, RaisedRightArmConfirmsRawCameraMirror) {
const nui::calibration::RaiseRightArmObservation fixture{
true, 0.40f, 0.30f, 0.45f, 0.20f, 0.45f, 0.70f};
bool mirror = false;
std::string error;
ASSERT_TRUE(nui::calibration::confirm_mirror_raise_right_arm(
fixture, mirror, error));
EXPECT_TRUE(mirror);
}
TEST(calibration, SavedConfigReloadsWithIdenticalTransforms) {
nui::calibration::TposeObservation fixture{};
fixture.person_detected = true;
fixture.root_depth_meters = 2.6f;
fixture.normalized_shoulder_width = 0.17f;
fixture.floor_plane = {0.0f, 1.0f, 0.0f, -0.9f};
fixture.mirror = true;
nui::calibration::CalibrationConfig original{};
std::string error;
ASSERT_TRUE(nui::calibration::calibrate_tpose(fixture, original, error));
const std::string path = "/tmp/kinect_calibration_test.cfg";
ASSERT_TRUE(nui::calibration::save_config(original, path, error));
nui::calibration::CalibrationConfig loaded{};
ASSERT_TRUE(nui::calibration::load_config(path, loaded, error));
std::remove(path.c_str());
EXPECT_EQ(loaded.mapping.depth_width, original.mapping.depth_width);
EXPECT_EQ(loaded.mapping.depth_height, original.mapping.depth_height);
EXPECT_FLOAT_EQ(loaded.mapping.z0_meters, original.mapping.z0_meters);
EXPECT_FLOAT_EQ(loaded.mapping.depth_gain, original.mapping.depth_gain);
EXPECT_EQ(loaded.mapping.mirror, original.mapping.mirror);
EXPECT_FLOAT_EQ(loaded.player_scale, original.player_scale);
EXPECT_EQ(loaded.floor_plane, original.floor_plane);
EXPECT_EQ(loaded.smoothing.smoothing, original.smoothing.smoothing);
EXPECT_EQ(loaded.smoothing.correction, original.smoothing.correction);
EXPECT_EQ(loaded.smoothing.prediction, original.smoothing.prediction);
EXPECT_EQ(loaded.smoothing.jitter_radius, original.smoothing.jitter_radius);
EXPECT_EQ(
loaded.smoothing.max_deviation_radius,
original.smoothing.max_deviation_radius);
}
TEST(calibration, NoPersonReturnsErrorWithoutWritingConfig) {
nui::calibration::TposeObservation fixture{};
nui::calibration::CalibrationConfig config{};
config.mapping.z0_meters = 1.75f;
std::string error;
EXPECT_FALSE(nui::calibration::calibrate_tpose(fixture, config, error));
EXPECT_FALSE(error.empty());
EXPECT_FLOAT_EQ(config.mapping.z0_meters, 1.75f);
}
+17
View File
@@ -74,6 +74,23 @@ TEST(Contract, PublishCyclesThroughAllSlotsNewestWins) {
}
}
TEST(Contract, RelativeSlotGenerationsReadLikePythonProducer) {
FrameContract contract{};
for (uint32_t i = 1; i <= kFrameSlotCount * 3; ++i) {
const uint64_t published = contract.published_sequence + 1;
FrameSlot& slot = contract.slots[published % kFrameSlotCount];
++slot.sequence;
slot.data.frame_number = i;
++slot.sequence;
contract.published_sequence = published;
FrameData out{};
read_latest_frame(contract, out);
EXPECT_EQ(out.frame_number, i);
EXPECT_EQ(slot.sequence % 2, 0u);
}
}
TEST(Contract, ControlMessageHeaderCarriesContractVersion) {
HeartbeatMessage hb{};
hb.header.message_type = ControlMessageType::HEARTBEAT;
+28 -10
View File
@@ -20,6 +20,7 @@ sys.path.insert(0, ROOT)
from tracker import contract as c # noqa: E402
from tracker import control # noqa: E402
from tracker.fake_pose import FakeFrameSource, FakePoseProvider, make_fake_pose # noqa: E402
from tracker.joint_mapping import map_pose_to_kinect_joints # noqa: E402
from tracker.publisher import ( # noqa: E402
PROVISIONAL_BODY_DEPTH_MM,
FrameContractPublisher,
@@ -60,12 +61,12 @@ def test_publish_and_read_back_fake_pose(publisher):
assert frame.frame_number == 1
assert frame.skeleton.skeleton_tracking_id == 1
mapped = map_pose_to_kinect_joints(pose, (160, 120))
for j in range(c.JOINT_COUNT):
wx, wy, wz = pose.world_landmarks[j]
joint = frame.skeleton.joints[j]
assert joint.position.x == pytest.approx(wx, abs=1e-5)
assert joint.position.y == pytest.approx(wy, abs=1e-5)
assert joint.position.z == pytest.approx(wz, abs=1e-5)
assert joint.position.x == pytest.approx(mapped[j][0], abs=1e-5)
assert joint.position.y == pytest.approx(mapped[j][1], abs=1e-5)
assert joint.position.z == pytest.approx(mapped[j][2], abs=1e-5)
assert joint.position.w == pytest.approx(1.0)
assert joint.tracking_state == c.JointTrackingState.TRACKED
@@ -87,6 +88,20 @@ def test_publish_and_read_back_fake_pose(publisher):
assert int(color_out[:, :, 0].max()) == 200
def test_joint_depth_uses_z0_placement_and_has_body_relief(publisher):
pose = make_fake_pose(frame_index=0, image_width=160, image_height=120)
publisher.publish(pose, None)
frame = publisher.read_latest_frame()
depths_mm = [
round(frame.skeleton.joints[index].position.z * 1000)
for index in range(c.JOINT_COUNT)
]
assert min(depths_mm) >= 800
assert max(depths_mm) <= 4000
assert max(depths_mm) - min(depths_mm) >= 100
def test_no_person_publishes_no_body_frame(publisher):
seq = publisher.publish(None, None)
assert seq == 1
@@ -104,16 +119,19 @@ def test_no_person_publishes_no_body_frame(publisher):
def test_low_visibility_marks_inferred_and_not_tracked(publisher):
# Joints 4/5/6 (SHOULDER_LEFT/ELBOW_LEFT/WRIST_LEFT) map directly from a
# single MediaPipe landmark each (11/13/15, nui-contracts.md section 1.2),
# so their tracking state follows that one landmark's visibility exactly.
pose = make_fake_pose(image_width=160, image_height=120)
pose.visibility[0] = 0.0
pose.visibility[1] = 0.2
pose.visibility[2] = 0.9
pose.visibility[11] = 0.0
pose.visibility[13] = 0.2
pose.visibility[15] = 0.9
publisher.publish(pose, None)
frame = publisher.read_latest_frame()
assert frame.skeleton.joints[0].tracking_state == c.JointTrackingState.NOT_TRACKED
assert frame.skeleton.joints[1].tracking_state == c.JointTrackingState.INFERRED
assert frame.skeleton.joints[2].tracking_state == c.JointTrackingState.TRACKED
assert frame.skeleton.joints[4].tracking_state == c.JointTrackingState.NOT_TRACKED
assert frame.skeleton.joints[5].tracking_state == c.JointTrackingState.INFERRED
assert frame.skeleton.joints[6].tracking_state == c.JointTrackingState.TRACKED
def test_sequence_increments_newest_wins(publisher):
+31
View File
@@ -0,0 +1,31 @@
cmake_minimum_required(VERSION 3.20)
project(nui_e2e_depth_stats LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(OPENNI2_ROOT "$ENV{HOME}/.local/openni2-root" CACHE PATH
"User-space OpenNI2 package root")
set(OPENNI2_INCLUDE_DIR
"${OPENNI2_ROOT}/usr/include/openni2" CACHE PATH
"Directory containing OpenNI.h")
set(OPENNI2_LIBRARY
"${OPENNI2_ROOT}/usr/lib/x86_64-linux-gnu/libOpenNI2.so" CACHE FILEPATH
"OpenNI2 shared library")
foreach(required_path
"${OPENNI2_INCLUDE_DIR}/OpenNI.h"
"${OPENNI2_LIBRARY}")
if(NOT EXISTS "${required_path}")
message(FATAL_ERROR "Required OpenNI2 file not found: ${required_path}")
endif()
endforeach()
add_executable(depth_stats_consumer depth_stats_consumer.cpp)
target_include_directories(depth_stats_consumer PRIVATE "${OPENNI2_INCLUDE_DIR}")
target_link_libraries(depth_stats_consumer PRIVATE "${OPENNI2_LIBRARY}")
target_compile_options(depth_stats_consumer PRIVATE -Wall -Wextra -Wpedantic -Werror)
set_target_properties(depth_stats_consumer PROPERTIES
BUILD_RPATH "${OPENNI2_ROOT}/usr/lib/x86_64-linux-gnu"
)
@@ -0,0 +1,84 @@
#include <OpenNI.h>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
namespace {
int fail(const char* step) {
std::fprintf(stderr, "%s failed: %s\n", step, openni::OpenNI::getExtendedError());
return 1;
}
} // namespace
// Companion to fallback/linux-openni2/tools/openni2_depth_consumer.cpp: reads
// the same live SynthKinect OpenNI2 stream and additionally reports the
// in-band per-pixel MEAN depth per frame (plan todo 21 evidence: proves the
// articulated body surface has a real depth distribution, not a single flat
// value repeated across every body pixel).
int main(int argc, char** argv) {
const int frame_count = argc > 1 ? std::atoi(argv[1]) : 12;
if (openni::OpenNI::initialize() != openni::STATUS_OK) {
return fail("OpenNI::initialize");
}
openni::Device device;
if (device.open(openni::ANY_DEVICE) != openni::STATUS_OK) {
openni::OpenNI::shutdown();
return fail("Device::open");
}
openni::VideoStream depth;
if (depth.create(device, openni::SENSOR_DEPTH) != openni::STATUS_OK ||
depth.start() != openni::STATUS_OK) {
device.close();
openni::OpenNI::shutdown();
return fail("VideoStream::create/start");
}
for (int i = 0; i < frame_count; ++i) {
openni::VideoFrameRef frame;
if (depth.readFrame(&frame) != openni::STATUS_OK || !frame.isValid()) {
std::fprintf(stderr, "readFrame failed at index %d\n", i);
depth.stop();
depth.destroy();
device.close();
openni::OpenNI::shutdown();
return 1;
}
const auto* pixels = static_cast<const openni::DepthPixel*>(frame.getData());
const int width = frame.getWidth();
const int height = frame.getHeight();
uint16_t min_mm = 0xFFFF;
uint16_t max_mm = 0;
double sum_mm = 0.0;
int count = 0;
for (int index = 0; index < width * height; ++index) {
const uint16_t value = pixels[index];
if (value == 0) {
continue;
}
++count;
sum_mm += value;
if (value < min_mm) {
min_mm = value;
}
if (value > max_mm) {
max_mm = value;
}
}
const double mean_mm = count > 0 ? sum_mm / count : 0.0;
std::printf(
"depthstats[%02d] count=%d min_mm=%u max_mm=%u mean_mm=%.1f spread_mm=%d\n",
i, count, count > 0 ? min_mm : 0, max_mm, mean_mm,
count > 0 ? static_cast<int>(max_mm) - static_cast<int>(min_mm) : 0);
frame.release();
}
depth.stop();
depth.destroy();
device.close();
openni::OpenNI::shutdown();
return 0;
}
+48 -2
View File
@@ -18,14 +18,18 @@ Orchestrates (no pytest, no mocks - every step is the real binary/process):
publishing real MediaPipe pose+mask frames into the frozen IPC contract.
4. openni2_depth_consumer, which dlopens the driver through OpenNI2 and
reports per-frame body-pixel centroid + in-band depth stats.
5. depth_stats_consumer, a second independent OpenNI2 consumer reporting
per-frame in-band depth min/max/mean (plan todo 21 evidence).
Exits non-zero (and the consumer's own FAIL line names the failed check) if
the consumer does not observe >=10 in-band, moving depth frames.
Exits non-zero if the depth consumer does not observe >=10 in-band, moving
depth frames, or if depth_stats_consumer never observes a per-frame spread of
at least MIN_ARTICULATED_SPREAD_MM (depth is pegged flat, not articulated).
"""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import sys
@@ -36,9 +40,14 @@ SHM_NAME = "virtual_kinect_frames"
SHM_PATH = f"/dev/shm/{SHM_NAME}"
VIDEO_PATH = "/tmp/kinect_e2e/dance.avi"
DRIVER_BUILD_DIR = os.path.join(ROOT, "fallback", "linux-openni2", "build")
STATS_BUILD_DIR = os.path.join(ROOT, "tools", "e2e_linux_validation", "build")
TRACKER_VENV_PYTHON = os.path.join(ROOT, "tracker", ".venv", "bin", "python")
GL_LIBS_DIR = os.path.expanduser("~/.cache/kinect/gllibs")
OPENNI2_LIB_DIR = os.path.expanduser("~/.local/openni2-root/usr/lib/x86_64-linux-gnu")
MIN_ARTICULATED_SPREAD_MM = 100
DEPTHSTATS_LINE = re.compile(
r"depthstats\[\d+\] count=(\d+) min_mm=(\d+) max_mm=(\d+) mean_mm=([\d.]+) spread_mm=(\d+)"
)
def run(cmd: list[str], **kwargs) -> subprocess.CompletedProcess:
@@ -72,6 +81,36 @@ def build_driver() -> None:
raise RuntimeError("cmake build failed")
def build_stats_consumer() -> None:
configure = run([
"cmake", "-S", os.path.join(ROOT, "tools", "e2e_linux_validation"), "-B", STATS_BUILD_DIR,
])
if configure.returncode != 0:
raise RuntimeError("depth_stats_consumer cmake configure failed")
build = run(["cmake", "--build", STATS_BUILD_DIR])
if build.returncode != 0:
raise RuntimeError("depth_stats_consumer cmake build failed")
def assert_depth_is_articulated(stats_stdout: str) -> None:
"""Fails loudly unless a real per-frame depth min/max/mean spread was
observed (plan todo 21: an articulated body surface, not the flat
800mm-floor placeholder it replaces)."""
matches = DEPTHSTATS_LINE.findall(stats_stdout)
if not matches:
raise RuntimeError("depth_stats_consumer produced no depthstats lines")
best_spread = max(int(spread) for _count, _min, _max, _mean, spread in matches)
if best_spread < MIN_ARTICULATED_SPREAD_MM:
raise RuntimeError(
f"depth is not articulated: max observed spread {best_spread}mm "
f"< required {MIN_ARTICULATED_SPREAD_MM}mm (min==max would mean a flat body)"
)
print(
f"ARTICULATED DEPTH CONFIRMED: max per-frame spread {best_spread}mm "
f"across {len(matches)} frames"
)
def wait_for_shm(timeout_s: float) -> bool:
deadline = time.monotonic() + timeout_s
while time.monotonic() < deadline:
@@ -87,6 +126,7 @@ def main() -> int:
generate_video()
build_driver()
build_stats_consumer()
tracker_env = dict(os.environ)
tracker_env["LD_LIBRARY_PATH"] = GL_LIBS_DIR + os.pathsep + tracker_env.get("LD_LIBRARY_PATH", "")
@@ -115,6 +155,12 @@ def main() -> int:
consumer_env = dict(os.environ)
consumer_env["LD_LIBRARY_PATH"] = OPENNI2_LIB_DIR + os.pathsep + consumer_env.get("LD_LIBRARY_PATH", "")
consumer = run([consumer_path, "12"], env=consumer_env, timeout=30)
stats_path = os.path.join(STATS_BUILD_DIR, "depth_stats_consumer")
stats_result = run([stats_path, "12"], env=consumer_env, timeout=30)
if stats_result.returncode != 0:
raise RuntimeError(f"depth_stats_consumer exit {stats_result.returncode}")
assert_depth_is_articulated(stats_result.stdout)
finally:
if tracker_proc.poll() is None:
tracker_proc.terminate()
+99
View File
@@ -0,0 +1,99 @@
"""MediaPipe-33 -> Kinect-20 joint placement, mirroring core/mapping exactly
(plan todos 6 and 21).
Reduces MediaPipe's 33 landmarks to the 20 Kinect joints core/mapping.cpp
selects, places each joint at `clamp(Z0 + depthGain * worldZ, 0.8, 4.0)`
(nui-contracts.md section 1.5), then back-projects through Kinect's documented
depth-camera inverse transform (nui-contracts.md section 1.1). This gives each
joint a real, distinct depth instead of a flat per-frame constant, so the C++
synth rasterizer (which interpolates depth from these projected joints) emits
an articulated body surface.
"""
from __future__ import annotations
from .contract import JointTrackingState
from .pose import PoseResult
VIS_TRACKED = 0.5
VIS_INFERRED = 0.1
DEFAULT_Z0_METERS = 2.5
DEFAULT_DEPTH_GAIN = 1.0
MIN_PLACED_Z_METERS = 0.8
MAX_PLACED_Z_METERS = 4.0
DEPTH_PROJECTION_SCALE = 3.501e-3
def tracking_state_for(visibility: float) -> int:
if visibility >= VIS_TRACKED:
return JointTrackingState.TRACKED
if visibility >= VIS_INFERRED:
return JointTrackingState.INFERRED
return JointTrackingState.NOT_TRACKED
def _mix_landmarks(
first: tuple[float, float, float, float],
second: tuple[float, float, float, float],
amount: float,
) -> tuple[float, float, float, float]:
return (
first[0] + (second[0] - first[0]) * amount,
first[1] + (second[1] - first[1]) * amount,
first[2] + (second[2] - first[2]) * amount,
min(first[3], second[3]),
)
def _kinect_joint_landmarks(
pose: PoseResult,
) -> tuple[tuple[float, float, float, float], ...]:
source = tuple(
(
pose.landmarks[index][0],
pose.landmarks[index][1],
pose.world_landmarks[index][2],
pose.visibility[index],
)
for index in range(len(pose.landmarks))
)
hips = _mix_landmarks(source[23], source[24], 0.5)
shoulders = _mix_landmarks(source[11], source[12], 0.5)
ears = _mix_landmarks(source[7], source[8], 0.5)
head = _mix_landmarks(shoulders, ears, 1.3) if ears[3] >= VIS_TRACKED else source[0]
left_hand = _mix_landmarks(source[19], source[17], 0.5)
right_hand = _mix_landmarks(source[20], source[18], 0.5)
return (
hips,
_mix_landmarks(hips, shoulders, 0.45),
shoulders,
head,
source[11], source[13], source[15],
left_hand if left_hand[3] >= VIS_TRACKED else source[15],
source[12], source[14], source[16],
right_hand if right_hand[3] >= VIS_TRACKED else source[16],
source[23], source[25], source[27], source[31],
source[24], source[26], source[28], source[32],
)
def map_pose_to_kinect_joints(
pose: PoseResult,
depth_size: tuple[int, int],
z0_meters: float = DEFAULT_Z0_METERS,
depth_gain: float = DEFAULT_DEPTH_GAIN,
mirror: bool = True,
) -> tuple[tuple[float, float, float, float, int], ...]:
"""Apply core/mapping's joint selection and exact Z0 placement formula."""
width, height = depth_size
joints = []
for u, v, world_z, visibility in _kinect_joint_landmarks(pose):
projected_u = 1.0 - min(max(u, 0.0), 1.0) if mirror else min(max(u, 0.0), 1.0)
projected_v = min(max(v, 0.0), 1.0)
z = min(max(z0_meters + depth_gain * world_z, MIN_PLACED_Z_METERS), MAX_PLACED_Z_METERS)
depth_x = round(projected_u * width)
depth_y = round(projected_v * height)
x = (depth_x - width / 2.0) * (320.0 / width) * DEPTH_PROJECTION_SCALE * z
y = -(depth_y - height / 2.0) * (240.0 / height) * DEPTH_PROJECTION_SCALE * z
joints.append((x, y, z, 1.0, tracking_state_for(visibility)))
return tuple(joints)
+26 -25
View File
@@ -18,11 +18,11 @@ 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.
Scope boundary: the skeleton joints written here are a *provisional* pass-through
of the raw MediaPipe world landmarks, and the depth buffer is a flat
mask->silhouette placeholder. The real MediaPipe-33 -> Kinect-20 mapping (todo
6) and the articulated synthetic-depth rasterizer (todo 7) replace these; todo 5
owns only moving a pose through the contract at a steady cadence.
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
@@ -43,12 +43,9 @@ from .contract import (
FrameData,
JointTrackingState,
)
from .joint_mapping import DEFAULT_DEPTH_GAIN, DEFAULT_Z0_METERS, map_pose_to_kinect_joints
from .pose import PoseResult
# Visibility thresholds -> per-joint tracking state (NUI tracking-state field).
VIS_TRACKED = 0.5
VIS_INFERRED = 0.1
# 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.
@@ -62,14 +59,6 @@ def pack_depth_word(depth_mm: int, player: int) -> int:
return ((depth_mm & 0x1FFF) << 3) | (player & 0x7)
def tracking_state_for(visibility: float) -> int:
if visibility >= VIS_TRACKED:
return JointTrackingState.TRACKED
if visibility >= VIS_INFERRED:
return JointTrackingState.INFERRED
return JointTrackingState.NOT_TRACKED
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]
@@ -87,6 +76,9 @@ class FrameContractPublisher:
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
@@ -100,6 +92,9 @@ class FrameContractPublisher:
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
@@ -150,16 +145,22 @@ class FrameContractPublisher:
joint.tracking_state = JointTrackingState.NOT_TRACKED
return
any_tracked = any(v >= VIS_INFERRED for v in pose.visibility[:JOINT_COUNT])
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 in range(JOINT_COUNT):
wx, wy, wz = pose.world_landmarks[j]
for j, mapped in enumerate(joints):
joint = skel.joints[j]
joint.position.x = float(wx)
joint.position.y = float(wy)
joint.position.z = float(wz)
joint.position.w = 1.0
joint.tracking_state = tracking_state_for(pose.visibility[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