feat(mapping,tracker,tools): NUI mapping+smoothing, MediaPipe tracker, record/replay harness, mock NUI host (wave 3)
This commit is contained in:
1 parent
712d60eaa4
commit
4a66699d82
25 files changed
+2697
-31
No files matched your search
@@ -18,6 +18,8 @@ compile_commands.json
|
|||||||
|
|
||||||
# ---- Python ----
|
# ---- Python ----
|
||||||
.venv/
|
.venv/
|
||||||
|
# MediaPipe .task model bundles (large, re-downloadable; see tracker/README.md)
|
||||||
|
tracker/models/
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
@@ -33,3 +35,5 @@ __pycache__/
|
|||||||
.omo/drafts/
|
.omo/drafts/
|
||||||
.omo/ulw-execute/
|
.omo/ulw-execute/
|
||||||
.omo/evidence/
|
.omo/evidence/
|
||||||
|
tracker/.venv/
|
||||||
|
*.task
|
||||||
+5
-1
@@ -44,7 +44,11 @@ if(NUI_CORE_BUILD_TESTS)
|
|||||||
FetchContent_MakeAvailable(googletest)
|
FetchContent_MakeAvailable(googletest)
|
||||||
|
|
||||||
enable_testing()
|
enable_testing()
|
||||||
add_executable(libnui_core_tests tests/test_core.cpp tests/test_contract.cpp)
|
add_executable(libnui_core_tests
|
||||||
|
tests/test_core.cpp
|
||||||
|
tests/test_contract.cpp
|
||||||
|
tests/test_mapping.cpp
|
||||||
|
)
|
||||||
target_link_libraries(libnui_core_tests PRIVATE libnui_core GTest::gtest_main)
|
target_link_libraries(libnui_core_tests PRIVATE libnui_core GTest::gtest_main)
|
||||||
|
|
||||||
include(GoogleTest)
|
include(GoogleTest)
|
||||||
|
|||||||
+258
-4
@@ -1,10 +1,264 @@
|
|||||||
#include "mapping/mapping.h"
|
#include "mapping/mapping.h"
|
||||||
|
|
||||||
namespace nui::mapping {
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
|
||||||
int kinect_joint_count() {
|
namespace nui::mapping {
|
||||||
// Kinect v1 NUI skeleton has 20 joints; real mapping logic lands in todo 6.
|
namespace {
|
||||||
return 20;
|
|
||||||
|
constexpr float kDepthProjectionScale = 3.501e-3f;
|
||||||
|
constexpr float kMinX = -2.2f;
|
||||||
|
constexpr float kMaxX = 2.2f;
|
||||||
|
constexpr float kMinY = -1.6f;
|
||||||
|
constexpr float kMaxY = 1.6f;
|
||||||
|
constexpr float kMinPlacedZ = 0.8f;
|
||||||
|
constexpr float kMaxZ = 4.0f;
|
||||||
|
constexpr float kTrackedVisibility = 0.5f;
|
||||||
|
|
||||||
|
using LandmarkArray =
|
||||||
|
std::array<MediaPipeLandmark, kMediaPipeLandmarkCount>;
|
||||||
|
|
||||||
|
MediaPipeLandmark interpolate(
|
||||||
|
const MediaPipeLandmark& from,
|
||||||
|
const MediaPipeLandmark& to,
|
||||||
|
float amount) {
|
||||||
|
return {
|
||||||
|
from.u + (to.u - from.u) * amount,
|
||||||
|
from.v + (to.v - from.v) * amount,
|
||||||
|
std::min(from.visibility, to.visibility),
|
||||||
|
from.world_z + (to.world_z - from.world_z) * amount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
MediaPipeLandmark midpoint(
|
||||||
|
const MediaPipeLandmark& first,
|
||||||
|
const MediaPipeLandmark& second) {
|
||||||
|
return interpolate(first, second, 0.5f);
|
||||||
|
}
|
||||||
|
|
||||||
|
MediaPipeLandmark hand_landmark(
|
||||||
|
const LandmarkArray& landmarks,
|
||||||
|
std::size_t index_mcp,
|
||||||
|
std::size_t pinky_mcp,
|
||||||
|
std::size_t wrist) {
|
||||||
|
const auto hand = midpoint(landmarks[index_mcp], landmarks[pinky_mcp]);
|
||||||
|
return hand.visibility >= kTrackedVisibility ? hand : landmarks[wrist];
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<MediaPipeLandmark, contract::kJointCount> make_joint_landmarks(
|
||||||
|
const LandmarkArray& landmarks) {
|
||||||
|
std::array<MediaPipeLandmark, contract::kJointCount> joints{};
|
||||||
|
joints[0] = midpoint(landmarks[23], landmarks[24]);
|
||||||
|
joints[2] = midpoint(landmarks[11], landmarks[12]);
|
||||||
|
joints[1] = interpolate(joints[0], joints[2], 0.45f);
|
||||||
|
|
||||||
|
const auto ears = midpoint(landmarks[7], landmarks[8]);
|
||||||
|
joints[3] = ears.visibility >= kTrackedVisibility
|
||||||
|
? interpolate(joints[2], ears, 1.3f)
|
||||||
|
: landmarks[0];
|
||||||
|
|
||||||
|
joints[4] = landmarks[11];
|
||||||
|
joints[5] = landmarks[13];
|
||||||
|
joints[6] = landmarks[15];
|
||||||
|
joints[7] = hand_landmark(landmarks, 19, 17, 15);
|
||||||
|
joints[8] = landmarks[12];
|
||||||
|
joints[9] = landmarks[14];
|
||||||
|
joints[10] = landmarks[16];
|
||||||
|
joints[11] = hand_landmark(landmarks, 20, 18, 16);
|
||||||
|
joints[12] = landmarks[23];
|
||||||
|
joints[13] = landmarks[25];
|
||||||
|
joints[14] = landmarks[27];
|
||||||
|
joints[15] = landmarks[31];
|
||||||
|
joints[16] = landmarks[24];
|
||||||
|
joints[17] = landmarks[26];
|
||||||
|
joints[18] = landmarks[28];
|
||||||
|
joints[19] = landmarks[32];
|
||||||
|
return joints;
|
||||||
|
}
|
||||||
|
|
||||||
|
contract::Vector4 clamp_position(contract::Vector4 position) {
|
||||||
|
position.x = std::clamp(position.x, kMinX, kMaxX);
|
||||||
|
position.y = std::clamp(position.y, kMinY, kMaxY);
|
||||||
|
position.z = std::clamp(position.z, 0.0f, kMaxZ);
|
||||||
|
position.w = 1.0f;
|
||||||
|
return position;
|
||||||
|
}
|
||||||
|
|
||||||
|
float distance(
|
||||||
|
const contract::Vector4& first,
|
||||||
|
const contract::Vector4& second) {
|
||||||
|
const float x = first.x - second.x;
|
||||||
|
const float y = first.y - second.y;
|
||||||
|
const float z = first.z - second.z;
|
||||||
|
return std::sqrt(x * x + y * y + z * z);
|
||||||
|
}
|
||||||
|
|
||||||
|
contract::Vector4 blend(
|
||||||
|
const contract::Vector4& first,
|
||||||
|
const contract::Vector4& second,
|
||||||
|
float first_weight) {
|
||||||
|
const float second_weight = 1.0f - first_weight;
|
||||||
|
return {
|
||||||
|
first.x * first_weight + second.x * second_weight,
|
||||||
|
first.y * first_weight + second.y * second_weight,
|
||||||
|
first.z * first_weight + second.z * second_weight,
|
||||||
|
1.0f,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
contract::Vector4 add(
|
||||||
|
const contract::Vector4& first,
|
||||||
|
const contract::Vector4& second,
|
||||||
|
float second_scale = 1.0f) {
|
||||||
|
return {
|
||||||
|
first.x + second.x * second_scale,
|
||||||
|
first.y + second.y * second_scale,
|
||||||
|
first.z + second.z * second_scale,
|
||||||
|
1.0f,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
contract::Vector4 depth_image_to_skeleton(
|
||||||
|
const DepthImagePoint& point,
|
||||||
|
int depth_width,
|
||||||
|
int depth_height) {
|
||||||
|
const float z = static_cast<float>(point.packed_depth >> 3) / 1000.0f;
|
||||||
|
const float x =
|
||||||
|
(static_cast<float>(point.x) - static_cast<float>(depth_width) / 2.0f) *
|
||||||
|
(320.0f / static_cast<float>(depth_width)) *
|
||||||
|
kDepthProjectionScale * z;
|
||||||
|
const float y =
|
||||||
|
-(static_cast<float>(point.y) - static_cast<float>(depth_height) / 2.0f) *
|
||||||
|
(240.0f / static_cast<float>(depth_height)) *
|
||||||
|
kDepthProjectionScale * z;
|
||||||
|
return clamp_position({x, y, z, 1.0f});
|
||||||
|
}
|
||||||
|
|
||||||
|
DepthImagePoint skeleton_to_depth_image(
|
||||||
|
const contract::Vector4& point,
|
||||||
|
int depth_width,
|
||||||
|
int depth_height) {
|
||||||
|
const auto position = clamp_position(point);
|
||||||
|
const float safe_z = std::max(position.z, 0.001f);
|
||||||
|
const float x =
|
||||||
|
static_cast<float>(depth_width) / 2.0f +
|
||||||
|
position.x / (kDepthProjectionScale * safe_z) *
|
||||||
|
(static_cast<float>(depth_width) / 320.0f);
|
||||||
|
const float y =
|
||||||
|
static_cast<float>(depth_height) / 2.0f -
|
||||||
|
position.y / (kDepthProjectionScale * safe_z) *
|
||||||
|
(static_cast<float>(depth_height) / 240.0f);
|
||||||
|
const int depth_mm = std::clamp(
|
||||||
|
static_cast<int>(std::lround(position.z * 1000.0f)), 0, 4000);
|
||||||
|
return {
|
||||||
|
std::clamp(
|
||||||
|
static_cast<int>(std::lround(x)), 0, depth_width),
|
||||||
|
std::clamp(
|
||||||
|
static_cast<int>(std::lround(y)), 0, depth_height),
|
||||||
|
static_cast<uint16_t>(depth_mm << 3),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
HoltSmoothingFilter::HoltSmoothingFilter(SmoothingParameters parameters)
|
||||||
|
: parameters_(parameters) {}
|
||||||
|
|
||||||
|
contract::Vector4 HoltSmoothingFilter::update(
|
||||||
|
const contract::Vector4& raw_position) {
|
||||||
|
const auto raw = clamp_position(raw_position);
|
||||||
|
if (!initialized_) {
|
||||||
|
filtered_ = raw;
|
||||||
|
trend_ = {0.0f, 0.0f, 0.0f, 0.0f};
|
||||||
|
output_ = raw;
|
||||||
|
initialized_ = true;
|
||||||
|
return output_;
|
||||||
|
}
|
||||||
|
|
||||||
|
const float raw_distance = distance(raw, filtered_);
|
||||||
|
const float jitter_weight =
|
||||||
|
parameters_.jitter_radius > 0.0f
|
||||||
|
? std::clamp(raw_distance / parameters_.jitter_radius, 0.0f, 1.0f)
|
||||||
|
: 1.0f;
|
||||||
|
const auto raw_damped = blend(raw, filtered_, jitter_weight);
|
||||||
|
const auto previous_filtered = filtered_;
|
||||||
|
filtered_ = blend(
|
||||||
|
raw_damped,
|
||||||
|
add(previous_filtered, trend_),
|
||||||
|
1.0f - parameters_.smoothing);
|
||||||
|
|
||||||
|
const auto filtered_delta = add(filtered_, previous_filtered, -1.0f);
|
||||||
|
trend_ = blend(
|
||||||
|
filtered_delta,
|
||||||
|
trend_,
|
||||||
|
parameters_.correction);
|
||||||
|
auto predicted = add(filtered_, trend_, parameters_.prediction);
|
||||||
|
|
||||||
|
const float deviation = distance(predicted, raw);
|
||||||
|
if (deviation > parameters_.max_deviation_radius && deviation > 0.0f) {
|
||||||
|
const auto predicted_delta = add(predicted, raw, -1.0f);
|
||||||
|
predicted = add(
|
||||||
|
raw,
|
||||||
|
predicted_delta,
|
||||||
|
parameters_.max_deviation_radius / deviation);
|
||||||
|
}
|
||||||
|
output_ = clamp_position(predicted);
|
||||||
|
return output_;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool HoltSmoothingFilter::initialized() const {
|
||||||
|
return initialized_;
|
||||||
|
}
|
||||||
|
|
||||||
|
const contract::Vector4& HoltSmoothingFilter::output() const {
|
||||||
|
return output_;
|
||||||
|
}
|
||||||
|
|
||||||
|
SkeletonMapper::SkeletonMapper(
|
||||||
|
MappingConfig config,
|
||||||
|
SmoothingParameters smoothing_parameters)
|
||||||
|
: config_(config) {
|
||||||
|
filters_.fill(HoltSmoothingFilter(smoothing_parameters));
|
||||||
|
}
|
||||||
|
|
||||||
|
contract::SkeletonFrame SkeletonMapper::map(
|
||||||
|
const LandmarkArray& landmarks) {
|
||||||
|
const auto joint_landmarks = make_joint_landmarks(landmarks);
|
||||||
|
contract::SkeletonFrame frame{};
|
||||||
|
frame.skeleton_tracking_id = 1;
|
||||||
|
|
||||||
|
for (std::size_t index = 0; index < joint_landmarks.size(); ++index) {
|
||||||
|
const auto& landmark = joint_landmarks[index];
|
||||||
|
const bool tracked = landmark.visibility >= kTrackedVisibility;
|
||||||
|
frame.joints[index].tracking_state =
|
||||||
|
tracked ? contract::JointTrackingState::TRACKED
|
||||||
|
: contract::JointTrackingState::INFERRED;
|
||||||
|
|
||||||
|
if (!tracked && filters_[index].initialized()) {
|
||||||
|
frame.joints[index].position = filters_[index].output();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const float u = std::clamp(landmark.u, 0.0f, 1.0f);
|
||||||
|
const float v = std::clamp(landmark.v, 0.0f, 1.0f);
|
||||||
|
const float projected_u = config_.mirror ? 1.0f - u : u;
|
||||||
|
const float z = std::clamp(
|
||||||
|
config_.z0_meters + config_.depth_gain * landmark.world_z,
|
||||||
|
kMinPlacedZ,
|
||||||
|
kMaxZ);
|
||||||
|
const DepthImagePoint depth_point{
|
||||||
|
static_cast<int>(std::lround(
|
||||||
|
projected_u * static_cast<float>(config_.depth_width))),
|
||||||
|
static_cast<int>(std::lround(
|
||||||
|
v * static_cast<float>(config_.depth_height))),
|
||||||
|
static_cast<uint16_t>(
|
||||||
|
static_cast<int>(std::lround(z * 1000.0f)) << 3),
|
||||||
|
};
|
||||||
|
const auto raw = depth_image_to_skeleton(
|
||||||
|
depth_point, config_.depth_width, config_.depth_height);
|
||||||
|
frame.joints[index].position = filters_[index].update(raw);
|
||||||
|
}
|
||||||
|
return frame;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace nui::mapping
|
} // namespace nui::mapping
|
||||||
+77
-4
@@ -1,13 +1,86 @@
|
|||||||
#ifndef NUI_CORE_MAPPING_H
|
#ifndef NUI_CORE_MAPPING_H
|
||||||
#define NUI_CORE_MAPPING_H
|
#define NUI_CORE_MAPPING_H
|
||||||
|
|
||||||
// Placeholder for NUI intrinsics + MediaPipe-33 -> Kinect-20 map + Holt smoothing
|
#include <array>
|
||||||
// (plan todo 6). Pure, TDD with golden vectors.
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
#include "contract/contract.h"
|
||||||
|
|
||||||
namespace nui::mapping {
|
namespace nui::mapping {
|
||||||
|
|
||||||
// Returns the number of Kinect v1 skeleton joints this module will map to (20).
|
constexpr std::size_t kMediaPipeLandmarkCount = 33;
|
||||||
int kinect_joint_count();
|
constexpr int kDefaultDepthWidth = 640;
|
||||||
|
constexpr int kDefaultDepthHeight = 480;
|
||||||
|
|
||||||
|
struct DepthImagePoint {
|
||||||
|
int x;
|
||||||
|
int y;
|
||||||
|
uint16_t packed_depth;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct MediaPipeLandmark {
|
||||||
|
float u;
|
||||||
|
float v;
|
||||||
|
float visibility;
|
||||||
|
float world_z;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct MappingConfig {
|
||||||
|
int depth_width = kDefaultDepthWidth;
|
||||||
|
int depth_height = kDefaultDepthHeight;
|
||||||
|
float z0_meters = 2.5f;
|
||||||
|
float depth_gain = 0.0f;
|
||||||
|
bool mirror = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SmoothingParameters {
|
||||||
|
float smoothing = 0.6f;
|
||||||
|
float correction = 0.4f;
|
||||||
|
float prediction = 0.4f;
|
||||||
|
float jitter_radius = 0.04f;
|
||||||
|
float max_deviation_radius = 0.07f;
|
||||||
|
};
|
||||||
|
|
||||||
|
contract::Vector4 depth_image_to_skeleton(
|
||||||
|
const DepthImagePoint& point,
|
||||||
|
int depth_width = kDefaultDepthWidth,
|
||||||
|
int depth_height = kDefaultDepthHeight);
|
||||||
|
|
||||||
|
DepthImagePoint skeleton_to_depth_image(
|
||||||
|
const contract::Vector4& point,
|
||||||
|
int depth_width = kDefaultDepthWidth,
|
||||||
|
int depth_height = kDefaultDepthHeight);
|
||||||
|
|
||||||
|
class HoltSmoothingFilter {
|
||||||
|
public:
|
||||||
|
explicit HoltSmoothingFilter(SmoothingParameters parameters = {});
|
||||||
|
|
||||||
|
contract::Vector4 update(const contract::Vector4& raw);
|
||||||
|
bool initialized() const;
|
||||||
|
const contract::Vector4& output() const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
SmoothingParameters parameters_;
|
||||||
|
contract::Vector4 filtered_{};
|
||||||
|
contract::Vector4 trend_{};
|
||||||
|
contract::Vector4 output_{};
|
||||||
|
bool initialized_ = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
class SkeletonMapper {
|
||||||
|
public:
|
||||||
|
explicit SkeletonMapper(
|
||||||
|
MappingConfig config = {},
|
||||||
|
SmoothingParameters smoothing_parameters = {});
|
||||||
|
|
||||||
|
contract::SkeletonFrame map(
|
||||||
|
const std::array<MediaPipeLandmark, kMediaPipeLandmarkCount>& landmarks);
|
||||||
|
|
||||||
|
private:
|
||||||
|
MappingConfig config_;
|
||||||
|
std::array<HoltSmoothingFilter, contract::kJointCount> filters_;
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace nui::mapping
|
} // namespace nui::mapping
|
||||||
|
|
||||||
|
|||||||
+1
-5
@@ -1,14 +1,10 @@
|
|||||||
#include <gtest/gtest.h>
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
#include "contract/contract.h"
|
#include "contract/contract.h"
|
||||||
#include "mapping/mapping.h"
|
|
||||||
#include "synth/synth.h"
|
#include "synth/synth.h"
|
||||||
|
|
||||||
// Scaffold smoke test: proves libnui_core compiles, links, and its placeholder
|
TEST(ScaffoldSmoke, CoreSymbolsLinkAndReturnExpectedValues) {
|
||||||
// symbols are callable. Real per-module suites replace/extend this in todos 2/6/7.
|
|
||||||
TEST(ScaffoldSmoke, CoreSymbolsLinkAndReturnPlaceholders) {
|
|
||||||
EXPECT_EQ(nui::contract::contract_version(), static_cast<int>(nui::contract::kContractVersion));
|
EXPECT_EQ(nui::contract::contract_version(), static_cast<int>(nui::contract::kContractVersion));
|
||||||
EXPECT_EQ(nui::mapping::kinect_joint_count(), 20);
|
|
||||||
// Depth packing layout sanity: 1000mm, player 1 -> (1000<<3)|1.
|
// Depth packing layout sanity: 1000mm, player 1 -> (1000<<3)|1.
|
||||||
EXPECT_EQ(nui::synth::pack_depth(1000, 1),
|
EXPECT_EQ(nui::synth::pack_depth(1000, 1),
|
||||||
static_cast<uint16_t>((1000 << 3) | 1));
|
static_cast<uint16_t>((1000 << 3) | 1));
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cmath>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "mapping/mapping.h"
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using nui::contract::JointTrackingState;
|
||||||
|
using nui::contract::Vector4;
|
||||||
|
using nui::mapping::DepthImagePoint;
|
||||||
|
using nui::mapping::MediaPipeLandmark;
|
||||||
|
|
||||||
|
float distance(const Vector4& first, const Vector4& second) {
|
||||||
|
const float x = first.x - second.x;
|
||||||
|
const float y = first.y - second.y;
|
||||||
|
const float z = first.z - second.z;
|
||||||
|
return std::sqrt(x * x + y * y + z * z);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::array<MediaPipeLandmark, nui::mapping::kMediaPipeLandmarkCount>
|
||||||
|
golden_landmarks() {
|
||||||
|
std::array<MediaPipeLandmark, nui::mapping::kMediaPipeLandmarkCount>
|
||||||
|
landmarks{};
|
||||||
|
for (std::size_t index = 0; index < landmarks.size(); ++index) {
|
||||||
|
landmarks[index] = {
|
||||||
|
0.2f + static_cast<float>(index) * 0.015f,
|
||||||
|
0.1f + static_cast<float>(index) * 0.02f,
|
||||||
|
1.0f,
|
||||||
|
0.0f,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return landmarks;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(mapping, ForwardInverseRoundTripStaysBelowOneMillimeter) {
|
||||||
|
const std::array<DepthImagePoint, 5> depth_points{{
|
||||||
|
{0, 0, static_cast<uint16_t>(800 << 3)},
|
||||||
|
{137, 91, static_cast<uint16_t>(1250 << 3)},
|
||||||
|
{320, 240, static_cast<uint16_t>(2500 << 3)},
|
||||||
|
{434, 171, static_cast<uint16_t>(2500 << 3)},
|
||||||
|
{630, 468, static_cast<uint16_t>(4000 << 3)},
|
||||||
|
}};
|
||||||
|
|
||||||
|
for (const auto& depth_point : depth_points) {
|
||||||
|
const auto skeleton =
|
||||||
|
nui::mapping::depth_image_to_skeleton(depth_point);
|
||||||
|
const auto projected =
|
||||||
|
nui::mapping::skeleton_to_depth_image(skeleton);
|
||||||
|
const auto round_tripped =
|
||||||
|
nui::mapping::depth_image_to_skeleton(projected);
|
||||||
|
|
||||||
|
SCOPED_TRACE(
|
||||||
|
"depth point " + std::to_string(depth_point.x) + "," +
|
||||||
|
std::to_string(depth_point.y));
|
||||||
|
EXPECT_LT(distance(skeleton, round_tripped), 0.001f);
|
||||||
|
EXPECT_EQ(projected.x, depth_point.x);
|
||||||
|
EXPECT_EQ(projected.y, depth_point.y);
|
||||||
|
EXPECT_EQ(projected.packed_depth, depth_point.packed_depth);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(mapping, LandmarkFixtureMapsAllTwentyJointsToGoldenPositions) {
|
||||||
|
const std::array<Vector4, nui::contract::kJointCount> expected{{
|
||||||
|
{0.14879250f, -0.14879250f, 2.5f, 1.0f},
|
||||||
|
{-0.07877250f, 0.07877250f, 2.5f, 1.0f},
|
||||||
|
{-0.35885250f, 0.35885250f, 2.5f, 1.0f},
|
||||||
|
{-0.57766500f, 0.57766500f, 2.5f, 1.0f},
|
||||||
|
{-0.37635750f, 0.37635750f, 2.5f, 1.0f},
|
||||||
|
{-0.29320875f, 0.29320875f, 2.5f, 1.0f},
|
||||||
|
{-0.21006000f, 0.21006000f, 2.5f, 1.0f},
|
||||||
|
{-0.08314875f, 0.08314875f, 2.5f, 1.0f},
|
||||||
|
{-0.33697125f, 0.33697125f, 2.5f, 1.0f},
|
||||||
|
{-0.25382250f, 0.25382250f, 2.5f, 1.0f},
|
||||||
|
{-0.16629750f, 0.16629750f, 2.5f, 1.0f},
|
||||||
|
{-0.04376250f, 0.04376250f, 2.5f, 1.0f},
|
||||||
|
{0.12691125f, -0.12691125f, 2.5f, 1.0f},
|
||||||
|
{0.21006000f, -0.21006000f, 2.5f, 1.0f},
|
||||||
|
{0.29320875f, -0.29320875f, 2.5f, 1.0f},
|
||||||
|
{0.46388250f, -0.46388250f, 2.5f, 1.0f},
|
||||||
|
{0.16629750f, -0.16629750f, 2.5f, 1.0f},
|
||||||
|
{0.25382250f, -0.25382250f, 2.5f, 1.0f},
|
||||||
|
{0.33697125f, -0.33697125f, 2.5f, 1.0f},
|
||||||
|
{0.50326875f, -0.50326875f, 2.5f, 1.0f},
|
||||||
|
}};
|
||||||
|
nui::mapping::MappingConfig config{};
|
||||||
|
config.mirror = false;
|
||||||
|
nui::mapping::SkeletonMapper mapper(config);
|
||||||
|
|
||||||
|
const auto frame = mapper.map(golden_landmarks());
|
||||||
|
|
||||||
|
for (std::size_t index = 0; index < expected.size(); ++index) {
|
||||||
|
SCOPED_TRACE("joint " + std::to_string(index));
|
||||||
|
EXPECT_NEAR(frame.joints[index].position.x, expected[index].x, 1e-6f);
|
||||||
|
EXPECT_NEAR(frame.joints[index].position.y, expected[index].y, 1e-6f);
|
||||||
|
EXPECT_FLOAT_EQ(frame.joints[index].position.z, expected[index].z);
|
||||||
|
EXPECT_EQ(
|
||||||
|
frame.joints[index].tracking_state,
|
||||||
|
JointTrackingState::TRACKED);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(mapping, GlobalMirrorIsAppliedExactlyOnce) {
|
||||||
|
auto landmarks = golden_landmarks();
|
||||||
|
nui::mapping::MappingConfig unmirrored_config{};
|
||||||
|
unmirrored_config.mirror = false;
|
||||||
|
nui::mapping::SkeletonMapper unmirrored(unmirrored_config);
|
||||||
|
nui::mapping::SkeletonMapper mirrored;
|
||||||
|
|
||||||
|
const auto unmirrored_frame = unmirrored.map(landmarks);
|
||||||
|
const auto mirrored_frame = mirrored.map(landmarks);
|
||||||
|
|
||||||
|
for (std::size_t index = 0; index < nui::contract::kJointCount; ++index) {
|
||||||
|
SCOPED_TRACE("joint " + std::to_string(index));
|
||||||
|
EXPECT_NEAR(
|
||||||
|
mirrored_frame.joints[index].position.x,
|
||||||
|
-unmirrored_frame.joints[index].position.x,
|
||||||
|
0.0044f);
|
||||||
|
EXPECT_FLOAT_EQ(
|
||||||
|
mirrored_frame.joints[index].position.y,
|
||||||
|
unmirrored_frame.joints[index].position.y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(mapping, OutOfRangeLandmarksAndDepthAreClamped) {
|
||||||
|
auto landmarks = golden_landmarks();
|
||||||
|
for (auto& landmark : landmarks) {
|
||||||
|
landmark.u = 20.0f;
|
||||||
|
landmark.v = -20.0f;
|
||||||
|
landmark.world_z = 100.0f;
|
||||||
|
}
|
||||||
|
nui::mapping::MappingConfig config{};
|
||||||
|
config.depth_gain = 10.0f;
|
||||||
|
config.mirror = false;
|
||||||
|
nui::mapping::SkeletonMapper mapper(config);
|
||||||
|
|
||||||
|
const auto frame = mapper.map(landmarks);
|
||||||
|
|
||||||
|
for (const auto& joint : frame.joints) {
|
||||||
|
EXPECT_GE(joint.position.x, -2.2f);
|
||||||
|
EXPECT_LE(joint.position.x, 2.2f);
|
||||||
|
EXPECT_GE(joint.position.y, -1.6f);
|
||||||
|
EXPECT_LE(joint.position.y, 1.6f);
|
||||||
|
EXPECT_GE(joint.position.z, 0.0f);
|
||||||
|
EXPECT_LE(joint.position.z, 4.0f);
|
||||||
|
EXPECT_FLOAT_EQ(joint.position.z, 4.0f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(mapping, HoltFilterMatchesPrecomputedGoldenSequence) {
|
||||||
|
nui::mapping::HoltSmoothingFilter filter;
|
||||||
|
const std::array<float, 5> raw_x{{0.0f, 0.02f, 0.04f, 0.10f, 0.12f}};
|
||||||
|
const std::array<float, 5> expected_x{{
|
||||||
|
0.000000000f,
|
||||||
|
0.004640000f,
|
||||||
|
0.020531200f,
|
||||||
|
0.062115328f,
|
||||||
|
0.102407352f,
|
||||||
|
}};
|
||||||
|
|
||||||
|
for (std::size_t index = 0; index < raw_x.size(); ++index) {
|
||||||
|
const auto output = filter.update({raw_x[index], 0.0f, 2.5f, 1.0f});
|
||||||
|
SCOPED_TRACE("sample " + std::to_string(index));
|
||||||
|
EXPECT_NEAR(output.x, expected_x[index], 1e-7f);
|
||||||
|
EXPECT_FLOAT_EQ(output.y, 0.0f);
|
||||||
|
EXPECT_FLOAT_EQ(output.z, 2.5f);
|
||||||
|
EXPECT_FLOAT_EQ(output.w, 1.0f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(mapping, OccludedJointIsInferredAndHoldsLastSmoothedPosition) {
|
||||||
|
auto landmarks = golden_landmarks();
|
||||||
|
nui::mapping::MappingConfig config{};
|
||||||
|
config.mirror = false;
|
||||||
|
nui::mapping::SkeletonMapper mapper(config);
|
||||||
|
const auto visible_frame = mapper.map(landmarks);
|
||||||
|
const auto last_wrist = visible_frame.joints[6].position;
|
||||||
|
landmarks[15] = {0.0f, 0.0f, 0.0f, -100.0f};
|
||||||
|
|
||||||
|
const auto occluded_frame = mapper.map(landmarks);
|
||||||
|
|
||||||
|
EXPECT_EQ(
|
||||||
|
occluded_frame.joints[6].tracking_state,
|
||||||
|
JointTrackingState::INFERRED);
|
||||||
|
EXPECT_FLOAT_EQ(occluded_frame.joints[6].position.x, last_wrist.x);
|
||||||
|
EXPECT_FLOAT_EQ(occluded_frame.joints[6].position.y, last_wrist.y);
|
||||||
|
EXPECT_FLOAT_EQ(occluded_frame.joints[6].position.z, last_wrist.z);
|
||||||
|
EXPECT_FLOAT_EQ(occluded_frame.joints[6].position.w, 1.0f);
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
"""pytest suite for the record/replay harness (plan todo 16).
|
||||||
|
|
||||||
|
Proves the harness records a synthetic frame sequence, replays it byte-identically
|
||||||
|
on a fake clock (no wall-clock sleeps), keeps frame numbers monotonic, reproduces
|
||||||
|
the exact recorded sequence back into the frame contract, and rejects a truncated
|
||||||
|
or corrupt fixture cleanly.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
sys.path.insert(0, os.path.join(ROOT, "tools", "record-replay"))
|
||||||
|
|
||||||
|
import vkrr # noqa: E402
|
||||||
|
from vkrr.fixture import _HEADER # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def _record_synthetic(count, step_micros=33_333, base_micros=1_000_000):
|
||||||
|
buffer = vkrr.ContractFrameBuffer()
|
||||||
|
recorder = vkrr.Recorder()
|
||||||
|
originals = []
|
||||||
|
for index in range(count):
|
||||||
|
frame = vkrr.build_synthetic_frame(
|
||||||
|
frame_number=index,
|
||||||
|
timestamp_micros=base_micros + index * step_micros,
|
||||||
|
seed=7,
|
||||||
|
)
|
||||||
|
originals.append(bytes(frame))
|
||||||
|
buffer.publish(frame)
|
||||||
|
assert recorder.poll(buffer) is True
|
||||||
|
return recorder, originals
|
||||||
|
|
||||||
|
|
||||||
|
def test_record_replay_is_byte_identical_and_monotonic(tmp_path):
|
||||||
|
recorder, originals = _record_synthetic(12)
|
||||||
|
fixture = str(tmp_path / "session.vkrr")
|
||||||
|
assert recorder.write(fixture) == 12
|
||||||
|
|
||||||
|
clock = vkrr.FakeClock()
|
||||||
|
replayer = vkrr.Replayer.from_fixture(fixture, clock)
|
||||||
|
|
||||||
|
replayed = []
|
||||||
|
replayer.replay(lambda sequence, frame: replayed.append((sequence, bytes(frame))))
|
||||||
|
|
||||||
|
assert [payload for _seq, payload in replayed] == originals
|
||||||
|
|
||||||
|
frame_numbers = [
|
||||||
|
struct.unpack_from("<I", payload, 0)[0] for _seq, payload in replayed
|
||||||
|
]
|
||||||
|
assert frame_numbers == list(range(12))
|
||||||
|
assert all(b < a for b, a in zip(frame_numbers, frame_numbers[1:]))
|
||||||
|
|
||||||
|
sequences = [seq for seq, _payload in replayed]
|
||||||
|
assert sequences == list(range(1, 13))
|
||||||
|
|
||||||
|
assert clock.now_micros() == 1_000_000 + 11 * 33_333
|
||||||
|
|
||||||
|
|
||||||
|
def test_replay_reproduces_exact_sequence_into_contract(tmp_path):
|
||||||
|
recorder, originals = _record_synthetic(8)
|
||||||
|
fixture = str(tmp_path / "session.vkrr")
|
||||||
|
recorder.write(fixture)
|
||||||
|
|
||||||
|
buffer = vkrr.ContractFrameBuffer()
|
||||||
|
rerecorder = vkrr.Recorder()
|
||||||
|
|
||||||
|
def sink(_sequence, frame):
|
||||||
|
buffer.publish(frame)
|
||||||
|
assert rerecorder.poll(buffer) is True
|
||||||
|
|
||||||
|
vkrr.Replayer.from_fixture(fixture).replay(sink)
|
||||||
|
|
||||||
|
assert [bytes(frame) for _seq, frame in rerecorder.frames] == originals
|
||||||
|
|
||||||
|
|
||||||
|
def test_newest_wins_drops_unpolled_intermediate_frame():
|
||||||
|
buffer = vkrr.ContractFrameBuffer()
|
||||||
|
recorder = vkrr.Recorder()
|
||||||
|
|
||||||
|
buffer.publish(vkrr.build_synthetic_frame(0, 0))
|
||||||
|
buffer.publish(vkrr.build_synthetic_frame(1, 33_333))
|
||||||
|
assert recorder.poll(buffer) is True
|
||||||
|
assert len(recorder.frames) == 1
|
||||||
|
|
||||||
|
sequence, frame = recorder.frames[0]
|
||||||
|
assert sequence == 2
|
||||||
|
assert frame.frame_number == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_truncated_record_payload_errors_cleanly(tmp_path):
|
||||||
|
recorder, _ = _record_synthetic(4)
|
||||||
|
fixture = str(tmp_path / "session.vkrr")
|
||||||
|
recorder.write(fixture)
|
||||||
|
|
||||||
|
full = os.path.getsize(fixture)
|
||||||
|
os.truncate(fixture, full - 10)
|
||||||
|
|
||||||
|
with pytest.raises(vkrr.TruncatedFixtureError):
|
||||||
|
vkrr.read_fixture(fixture)
|
||||||
|
|
||||||
|
|
||||||
|
def test_truncated_header_errors_cleanly(tmp_path):
|
||||||
|
recorder, _ = _record_synthetic(1)
|
||||||
|
fixture = str(tmp_path / "session.vkrr")
|
||||||
|
recorder.write(fixture)
|
||||||
|
os.truncate(fixture, _HEADER.size - 3)
|
||||||
|
|
||||||
|
with pytest.raises(vkrr.TruncatedFixtureError):
|
||||||
|
vkrr.read_fixture(fixture)
|
||||||
|
|
||||||
|
|
||||||
|
def test_bad_magic_errors_cleanly(tmp_path):
|
||||||
|
fixture = tmp_path / "bad.vkrr"
|
||||||
|
fixture.write_bytes(_HEADER.pack(b"XXXX", vkrr.FORMAT_VERSION, 1, 460, 0))
|
||||||
|
|
||||||
|
with pytest.raises(vkrr.FixtureFormatError):
|
||||||
|
vkrr.read_fixture(str(fixture))
|
||||||
|
|
||||||
|
|
||||||
|
def test_trailing_bytes_errors_cleanly(tmp_path):
|
||||||
|
recorder, _ = _record_synthetic(2)
|
||||||
|
fixture = str(tmp_path / "session.vkrr")
|
||||||
|
recorder.write(fixture)
|
||||||
|
with open(fixture, "ab") as handle:
|
||||||
|
handle.write(b"\x00\x00")
|
||||||
|
|
||||||
|
with pytest.raises(vkrr.FixtureFormatError):
|
||||||
|
vkrr.read_fixture(fixture)
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_fixture_roundtrips(tmp_path):
|
||||||
|
fixture = str(tmp_path / "empty.vkrr")
|
||||||
|
assert vkrr.write_fixture(fixture, []) == 0
|
||||||
|
|
||||||
|
header, frames = vkrr.read_fixture(fixture)
|
||||||
|
assert header.frame_count == 0
|
||||||
|
assert frames == []
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
"""Data-path tests for the webcam tracker (plan todo 5).
|
||||||
|
|
||||||
|
These exercise landmarks -> contract packing -> shared-memory publish -> read
|
||||||
|
back entirely with the fake pose provider, so the IPC path is verified without
|
||||||
|
MediaPipe. A live MediaPipe run is a separate smoke script, not a unit test.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import ctypes
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
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.publisher import ( # noqa: E402
|
||||||
|
PROVISIONAL_BODY_DEPTH_MM,
|
||||||
|
FrameContractPublisher,
|
||||||
|
pack_depth_word,
|
||||||
|
)
|
||||||
|
from tracker.tracker import Tracker # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def publisher():
|
||||||
|
pub = FrameContractPublisher(depth_size=(160, 120), color_size=(160, 120))
|
||||||
|
try:
|
||||||
|
yield pub
|
||||||
|
finally:
|
||||||
|
pub.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_region_layout_and_version(publisher):
|
||||||
|
expected = ctypes.sizeof(c.FrameContract) + c.FRAME_SLOT_COUNT * (
|
||||||
|
publisher.depth_bytes + publisher.color_bytes
|
||||||
|
)
|
||||||
|
assert publisher.region_size == expected
|
||||||
|
assert publisher.contract.contract_version == c.CONTRACT_VERSION
|
||||||
|
assert publisher.contract.published_sequence == 0
|
||||||
|
assert publisher.read_latest_frame() is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_publish_and_read_back_fake_pose(publisher):
|
||||||
|
pose = make_fake_pose(frame_index=0, image_width=160, image_height=120)
|
||||||
|
color = np.full((120, 160, 3), 200, dtype=np.uint8)
|
||||||
|
|
||||||
|
seq = publisher.publish(pose, color)
|
||||||
|
assert seq == 1
|
||||||
|
assert publisher.contract.published_sequence == 1
|
||||||
|
|
||||||
|
frame = publisher.read_latest_frame()
|
||||||
|
assert frame is not None
|
||||||
|
assert frame.frame_number == 1
|
||||||
|
assert frame.skeleton.skeleton_tracking_id == 1
|
||||||
|
|
||||||
|
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.w == pytest.approx(1.0)
|
||||||
|
assert joint.tracking_state == c.JointTrackingState.TRACKED
|
||||||
|
|
||||||
|
assert frame.depth.width == 160 and frame.depth.height == 120
|
||||||
|
assert frame.color.width == 160 and frame.color.height == 120
|
||||||
|
assert frame.depth.pitch == 160 * 2
|
||||||
|
assert frame.color.pitch == 160 * 4
|
||||||
|
|
||||||
|
slot = publisher.latest_slot_index()
|
||||||
|
depth = publisher.read_depth(slot)
|
||||||
|
body_word = pack_depth_word(PROVISIONAL_BODY_DEPTH_MM, 1)
|
||||||
|
assert int(depth.max()) == body_word
|
||||||
|
assert np.count_nonzero(depth) > 0
|
||||||
|
assert np.count_nonzero(depth == 0) > 0
|
||||||
|
|
||||||
|
color_out = publisher.read_color(slot)
|
||||||
|
assert color_out.shape == (120, 160, 4)
|
||||||
|
assert np.all(color_out[:, :, 3] == 255)
|
||||||
|
assert int(color_out[:, :, 0].max()) == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_person_publishes_no_body_frame(publisher):
|
||||||
|
seq = publisher.publish(None, None)
|
||||||
|
assert seq == 1
|
||||||
|
|
||||||
|
frame = publisher.read_latest_frame()
|
||||||
|
assert frame is not None
|
||||||
|
assert frame.skeleton.skeleton_tracking_id == 0
|
||||||
|
for j in range(c.JOINT_COUNT):
|
||||||
|
joint = frame.skeleton.joints[j]
|
||||||
|
assert joint.tracking_state == c.JointTrackingState.NOT_TRACKED
|
||||||
|
assert joint.position.x == 0.0 and joint.position.y == 0.0 and joint.position.z == 0.0
|
||||||
|
|
||||||
|
depth = publisher.read_depth(publisher.latest_slot_index())
|
||||||
|
assert int(depth.max()) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_low_visibility_marks_inferred_and_not_tracked(publisher):
|
||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def test_sequence_increments_newest_wins(publisher):
|
||||||
|
for i in range(7):
|
||||||
|
publisher.publish(make_fake_pose(frame_index=i, image_width=160, image_height=120), None)
|
||||||
|
assert publisher.contract.published_sequence == 7
|
||||||
|
frame = publisher.read_latest_frame()
|
||||||
|
assert frame.frame_number == 7
|
||||||
|
|
||||||
|
|
||||||
|
def test_tracker_loop_paces_to_monotonic_clock():
|
||||||
|
publisher = FrameContractPublisher(depth_size=(80, 60), color_size=(80, 60))
|
||||||
|
source = FakeFrameSource(n_frames=None, width=80, height=60)
|
||||||
|
provider = FakePoseProvider(image_width=80, image_height=60)
|
||||||
|
tracker = Tracker(source, provider, publisher, target_fps=50.0)
|
||||||
|
|
||||||
|
period = 1.0 / 50.0
|
||||||
|
start = time.monotonic()
|
||||||
|
published = tracker.run(max_frames=5)
|
||||||
|
elapsed = time.monotonic() - start
|
||||||
|
try:
|
||||||
|
assert published == 5
|
||||||
|
assert publisher.contract.published_sequence == 5
|
||||||
|
assert elapsed >= 4 * period * 0.7
|
||||||
|
frame = publisher.read_latest_frame()
|
||||||
|
assert frame.skeleton.skeleton_tracking_id == 1
|
||||||
|
finally:
|
||||||
|
source.release()
|
||||||
|
publisher.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_tracker_loop_stops_at_source_end_without_crash():
|
||||||
|
publisher = FrameContractPublisher(depth_size=(80, 60), color_size=(80, 60))
|
||||||
|
source = FakeFrameSource(n_frames=4, width=80, height=60)
|
||||||
|
provider = FakePoseProvider(image_width=80, image_height=60, no_person=True)
|
||||||
|
tracker = Tracker(source, provider, publisher, target_fps=200.0)
|
||||||
|
try:
|
||||||
|
published = tracker.run(max_frames=1000)
|
||||||
|
assert published >= 1
|
||||||
|
frame = publisher.read_latest_frame()
|
||||||
|
assert frame.skeleton.skeleton_tracking_id == 0
|
||||||
|
finally:
|
||||||
|
source.release()
|
||||||
|
publisher.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_control_messages_roundtrip():
|
||||||
|
a, b = socket.socketpair()
|
||||||
|
try:
|
||||||
|
a.sendall(control.build_handshake(client_version=c.CONTRACT_VERSION, capabilities=7))
|
||||||
|
raw = b.recv(ctypes.sizeof(c.HandshakeMessage))
|
||||||
|
msg = control.parse_message(raw)
|
||||||
|
assert isinstance(msg, c.HandshakeMessage)
|
||||||
|
assert msg.header.message_type == c.ControlMessageType.HANDSHAKE_VERSION
|
||||||
|
assert msg.header.contract_version == c.CONTRACT_VERSION
|
||||||
|
assert msg.capabilities == 7
|
||||||
|
|
||||||
|
a.sendall(control.build_heartbeat(sequence=42, timestamp_micros=123456))
|
||||||
|
raw = b.recv(ctypes.sizeof(c.HeartbeatMessage))
|
||||||
|
hb = control.parse_message(raw)
|
||||||
|
assert isinstance(hb, c.HeartbeatMessage)
|
||||||
|
assert hb.header.message_type == c.ControlMessageType.HEARTBEAT
|
||||||
|
assert hb.sequence == 42
|
||||||
|
assert hb.timestamp_micros == 123456
|
||||||
|
finally:
|
||||||
|
a.close()
|
||||||
|
b.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_control_server_handshake_then_heartbeat(tmp_path):
|
||||||
|
sock_path = str(tmp_path / "control.sock")
|
||||||
|
server = control.ControlPlaneServer(sock_path)
|
||||||
|
server.start()
|
||||||
|
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
client.settimeout(2.0)
|
||||||
|
try:
|
||||||
|
deadline = time.monotonic() + 2.0
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
client.connect(sock_path)
|
||||||
|
break
|
||||||
|
except (FileNotFoundError, ConnectionRefusedError):
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
pytest.fail("could not connect to control server")
|
||||||
|
|
||||||
|
raw = client.recv(ctypes.sizeof(c.HandshakeMessage))
|
||||||
|
msg = control.parse_message(raw)
|
||||||
|
assert isinstance(msg, c.HandshakeMessage)
|
||||||
|
|
||||||
|
assert server.send_heartbeat(99) is True
|
||||||
|
raw = client.recv(ctypes.sizeof(c.HeartbeatMessage))
|
||||||
|
hb = control.parse_message(raw)
|
||||||
|
assert isinstance(hb, c.HeartbeatMessage)
|
||||||
|
assert hb.sequence == 99
|
||||||
|
finally:
|
||||||
|
client.close()
|
||||||
|
server.close()
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# Standalone, Windows-only build for the mock NUI host (plan todo 16).
|
||||||
|
#
|
||||||
|
# DELIBERATELY NOT referenced by the repository root CMakeLists.txt: this target
|
||||||
|
# needs windows.h and the Kinect for Windows SDK 1.8 import library, so it can
|
||||||
|
# only be configured on Windows with MSVC. The Linux core build never sees it.
|
||||||
|
#
|
||||||
|
# Build (on a Windows box with the Kinect SDK 1.8 installed):
|
||||||
|
# cmake -S tools/mock-nui-host -B build/mock-nui-host -A Win32
|
||||||
|
# cmake --build build/mock-nui-host --config Release
|
||||||
|
# Use -A Win32 to match a 32-bit shim/game, or -A x64 for 64-bit.
|
||||||
|
|
||||||
|
cmake_minimum_required(VERSION 3.20)
|
||||||
|
project(mock_nui_host LANGUAGES CXX)
|
||||||
|
|
||||||
|
if(NOT WIN32)
|
||||||
|
message(FATAL_ERROR "mock-nui-host is Windows-only (needs the Kinect SDK 1.8); do not build it on Linux.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
set(CMAKE_CXX_STANDARD 17)
|
||||||
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
|
|
||||||
|
add_executable(mock_nui_host mock_nui_host.cpp)
|
||||||
|
|
||||||
|
# Kinect for Windows SDK 1.8 (KINECTSDK10_DIR is set by the SDK installer).
|
||||||
|
set(KINECT_SDK_DIR "$ENV{KINECTSDK10_DIR}" CACHE PATH "Kinect for Windows SDK 1.8 root")
|
||||||
|
if(NOT KINECT_SDK_DIR)
|
||||||
|
message(FATAL_ERROR "KINECTSDK10_DIR not set; install the Kinect for Windows SDK 1.8.")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
|
||||||
|
set(KINECT_ARCH "amd64")
|
||||||
|
else()
|
||||||
|
set(KINECT_ARCH "x86")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
target_include_directories(mock_nui_host PRIVATE "${KINECT_SDK_DIR}/inc")
|
||||||
|
target_link_libraries(mock_nui_host PRIVATE "${KINECT_SDK_DIR}/lib/${KINECT_ARCH}/Kinect10.lib")
|
||||||
@@ -1,4 +1,51 @@
|
|||||||
# tools/mock-nui-host/ — mock NUI host (todo 16)
|
# tools/mock-nui-host/ — mock NUI host (plan todo 16)
|
||||||
|
|
||||||
Windows mock host that links the SDK headers and drives the full NUI call sequence to test
|
Status: **[~] blocked — Windows + MSVC + Kinect for Windows SDK 1.8 required to build.**
|
||||||
the `fallback/windows-nui` shim without the game. Placeholder until todo 16.
|
This is code-only on this Linux/WSL2 box; it is **not** wired into the Linux CMake build
|
||||||
|
(the repository root `CMakeLists.txt` never references it) because it needs `windows.h` and
|
||||||
|
the Kinect SDK 1.8 import library, neither of which exists here.
|
||||||
|
|
||||||
|
## What it is
|
||||||
|
|
||||||
|
A scripted NUI consumer that links the public Kinect SDK 1.8 headers and drives the **full
|
||||||
|
NUI call sequence** against whatever `Kinect10.dll` is loaded — the clean-room shim from
|
||||||
|
`fallback/windows-nui/` (todo 14) or the real runtime — so the shim can be exercised with
|
||||||
|
**no sensor and no game**. It is the Windows counterpart of the Python record/replay harness.
|
||||||
|
|
||||||
|
It drives and validates, per `.omo/design/nui-contracts.md` §3:
|
||||||
|
|
||||||
|
- `NuiInitialize(USES_DEPTH_AND_PLAYER_INDEX | USES_COLOR | USES_SKELETON)` → `NuiShutdown`
|
||||||
|
- `NuiSkeletonTrackingEnable` + a manual-reset skeleton event
|
||||||
|
- `NuiImageStreamOpen` for depth+player-index and color (640×480, `dwFrameLimit=2`) + events
|
||||||
|
- the event loop: `WaitForMultipleObjects` on the three frame-ready events (bounded wait, no
|
||||||
|
fixed sleep), then `NuiSkeletonGetNextFrame`, `NuiImageStreamGetNextFrame` →
|
||||||
|
`INuiFrameTexture::LockRect`/`UnlockRect` → `NuiImageStreamReleaseFrame`
|
||||||
|
- `NuiTransformSmooth` on each skeleton frame
|
||||||
|
- asserts: skeleton/depth/color frames arrive, frame numbers and timestamps are monotonic
|
||||||
|
(§3.6), and the locked texture pitch matches the requested resolution (§3.5)
|
||||||
|
|
||||||
|
It exits `0` (prints `RESULT: PASS`) only when every stream delivered frames and the
|
||||||
|
invariants held; otherwise non-zero with the failing call/`HRESULT` on stderr.
|
||||||
|
|
||||||
|
## Clean-room note
|
||||||
|
|
||||||
|
Every NUI name, flag, enum and struct here comes from the **public** Kinect SDK 1.8 headers
|
||||||
|
(`NuiApi.h` / `NuiImageCamera.h` / `NuiSkeleton.h`). No GPLv3 source (KinectFaker etc.) was
|
||||||
|
consulted — the same clean-room firewall that governs the todo-14 shim.
|
||||||
|
|
||||||
|
## Build (on Windows only)
|
||||||
|
|
||||||
|
```bat
|
||||||
|
:: with the Kinect for Windows SDK 1.8 installed (sets KINECTSDK10_DIR)
|
||||||
|
cmake -S tools/mock-nui-host -B build/mock-nui-host -A Win32 :: or -A x64
|
||||||
|
cmake --build build/mock-nui-host --config Release
|
||||||
|
```
|
||||||
|
|
||||||
|
Place the shim's `Kinect10.dll` beside the built `mock_nui_host.exe` (or rely on the real
|
||||||
|
runtime) and run it.
|
||||||
|
|
||||||
|
## Why [~] blocked here
|
||||||
|
|
||||||
|
This repo is developed on Linux/WSL2, which has no Windows Kinect SDK, no MSVC and cannot link
|
||||||
|
`Kinect10.lib`. The source + build script are complete and committed; the build/run step is
|
||||||
|
deferred to the user's Windows box (same gate as todos 12/13/14).
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
// Mock NUI host for the clean-room Kinect10.dll shim (plan todo 16; Windows-only).
|
||||||
|
//
|
||||||
|
// Drives the full Kinect for Windows 1.8 NUI call sequence against whatever
|
||||||
|
// Kinect10.dll is loaded (the fallback/windows-nui shim from todo 14, or the
|
||||||
|
// real runtime), so the shim can be exercised with no sensor and no game. It is
|
||||||
|
// the Windows counterpart of the Python record/replay harness: a scripted NUI
|
||||||
|
// consumer that asserts the shim honours the event/timing/buffer contract in
|
||||||
|
// .omo/design/nui-contracts.md section 3.
|
||||||
|
//
|
||||||
|
// Clean-room note: every NUI name, flag, enum and struct used here is taken from
|
||||||
|
// the PUBLIC Kinect SDK 1.8 headers (NuiApi.h / NuiImageCamera.h / NuiSkeleton.h).
|
||||||
|
// No GPLv3 source (KinectFaker etc.) was consulted.
|
||||||
|
//
|
||||||
|
// BUILD: Windows + MSVC + Kinect for Windows SDK 1.8 ONLY. This file is NOT part
|
||||||
|
// of the Linux CMake build (it needs windows.h and the Kinect SDK import lib);
|
||||||
|
// see README.md for the [~] blocked status and the standalone build command.
|
||||||
|
|
||||||
|
#include <windows.h>
|
||||||
|
|
||||||
|
#include <NuiApi.h>
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <cstdio>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr int kTicksToObserve = 60; // ~2 s at 30 Hz
|
||||||
|
constexpr DWORD kFrameWaitMs = 100; // bounded wait per nui-contracts.md section 3.3
|
||||||
|
constexpr DWORD kDepthWidth = 640;
|
||||||
|
constexpr DWORD kDepthHeight = 480;
|
||||||
|
|
||||||
|
struct HostStats {
|
||||||
|
int skeleton_frames = 0;
|
||||||
|
int tracked_skeletons = 0;
|
||||||
|
int depth_frames = 0;
|
||||||
|
int color_frames = 0;
|
||||||
|
DWORD last_skeleton_frame_number = 0;
|
||||||
|
LARGE_INTEGER last_skeleton_timestamp = {};
|
||||||
|
bool frame_numbers_monotonic = true;
|
||||||
|
bool timestamps_monotonic = true;
|
||||||
|
bool errored = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
bool Check(HRESULT hr, const char* what, HostStats& stats) {
|
||||||
|
if (FAILED(hr)) {
|
||||||
|
std::fprintf(stderr, "[mock-nui-host] %s failed: hr=0x%08lX\n", what,
|
||||||
|
static_cast<unsigned long>(hr));
|
||||||
|
stats.errored = true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pulls the newest skeleton frame and validates the section-3.6 frame-number /
|
||||||
|
// timestamp invariants (one monotonic counter; monotonic QPC-style stamp).
|
||||||
|
void ConsumeSkeletonFrame(HostStats& stats) {
|
||||||
|
NUI_SKELETON_FRAME frame = {};
|
||||||
|
HRESULT hr = NuiSkeletonGetNextFrame(0, &frame);
|
||||||
|
if (hr == E_NUI_FRAME_NO_DATA) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!Check(hr, "NuiSkeletonGetNextFrame", stats)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
++stats.skeleton_frames;
|
||||||
|
|
||||||
|
if (stats.skeleton_frames > 1) {
|
||||||
|
if (frame.dwFrameNumber < stats.last_skeleton_frame_number) {
|
||||||
|
stats.frame_numbers_monotonic = false;
|
||||||
|
}
|
||||||
|
if (frame.liTimeStamp.QuadPart < stats.last_skeleton_timestamp.QuadPart) {
|
||||||
|
stats.timestamps_monotonic = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stats.last_skeleton_frame_number = frame.dwFrameNumber;
|
||||||
|
stats.last_skeleton_timestamp = frame.liTimeStamp;
|
||||||
|
|
||||||
|
// Smooth exactly as a real consumer would (NUI_TRANSFORM_SMOOTH_PARAMETERS),
|
||||||
|
// confirming the shim accepts the documented smoothing entry point.
|
||||||
|
NUI_TRANSFORM_SMOOTH_PARAMETERS smooth = {0.5f, 0.5f, 0.5f, 0.05f, 0.04f};
|
||||||
|
NuiTransformSmooth(&frame, &smooth);
|
||||||
|
|
||||||
|
for (int i = 0; i < NUI_SKELETON_COUNT; ++i) {
|
||||||
|
if (frame.SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED) {
|
||||||
|
++stats.tracked_skeletons;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pulls one image frame, locks the texture, validates the reported pitch/size
|
||||||
|
// against the requested resolution (section 3.5), then releases it.
|
||||||
|
void ConsumeImageFrame(HANDLE stream, const char* label, DWORD expected_pitch,
|
||||||
|
int& counter, HostStats& stats) {
|
||||||
|
NUI_IMAGE_FRAME frame = {};
|
||||||
|
HRESULT hr = NuiImageStreamGetNextFrame(stream, 0, &frame);
|
||||||
|
if (hr == E_NUI_FRAME_NO_DATA) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!Check(hr, "NuiImageStreamGetNextFrame", stats)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
INuiFrameTexture* texture = frame.pFrameTexture;
|
||||||
|
NUI_LOCKED_RECT locked = {};
|
||||||
|
if (texture != nullptr && Check(texture->LockRect(0, &locked, nullptr, 0),
|
||||||
|
"INuiFrameTexture::LockRect", stats)) {
|
||||||
|
if (locked.Pitch != static_cast<INT>(expected_pitch)) {
|
||||||
|
std::fprintf(stderr,
|
||||||
|
"[mock-nui-host] %s pitch %d != expected %lu (section 3.5)\n",
|
||||||
|
label, locked.Pitch, static_cast<unsigned long>(expected_pitch));
|
||||||
|
stats.errored = true;
|
||||||
|
}
|
||||||
|
texture->UnlockRect(0);
|
||||||
|
++counter;
|
||||||
|
}
|
||||||
|
|
||||||
|
Check(NuiImageStreamReleaseFrame(stream, &frame), "NuiImageStreamReleaseFrame", stats);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
HostStats stats;
|
||||||
|
|
||||||
|
HRESULT hr = NuiInitialize(NUI_INITIALIZE_FLAG_USES_DEPTH_AND_PLAYER_INDEX |
|
||||||
|
NUI_INITIALIZE_FLAG_USES_COLOR |
|
||||||
|
NUI_INITIALIZE_FLAG_USES_SKELETON);
|
||||||
|
if (!Check(hr, "NuiInitialize", stats)) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Manual-reset events the producer signals per new frame (section 3.2/3.3).
|
||||||
|
HANDLE skeleton_event = CreateEvent(nullptr, TRUE, FALSE, nullptr);
|
||||||
|
HANDLE depth_event = CreateEvent(nullptr, TRUE, FALSE, nullptr);
|
||||||
|
HANDLE color_event = CreateEvent(nullptr, TRUE, FALSE, nullptr);
|
||||||
|
|
||||||
|
HANDLE depth_stream = nullptr;
|
||||||
|
HANDLE color_stream = nullptr;
|
||||||
|
|
||||||
|
bool ok = Check(NuiSkeletonTrackingEnable(skeleton_event, 0),
|
||||||
|
"NuiSkeletonTrackingEnable", stats);
|
||||||
|
ok = ok && Check(NuiImageStreamOpen(NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX,
|
||||||
|
NUI_IMAGE_RESOLUTION_640x480, 0, 2, depth_event,
|
||||||
|
&depth_stream),
|
||||||
|
"NuiImageStreamOpen(depth)", stats);
|
||||||
|
ok = ok && Check(NuiImageStreamOpen(NUI_IMAGE_TYPE_COLOR, NUI_IMAGE_RESOLUTION_640x480,
|
||||||
|
0, 2, color_event, &color_stream),
|
||||||
|
"NuiImageStreamOpen(color)", stats);
|
||||||
|
|
||||||
|
if (ok) {
|
||||||
|
HANDLE events[3] = {skeleton_event, depth_event, color_event};
|
||||||
|
for (int tick = 0; tick < kTicksToObserve && !stats.errored; ++tick) {
|
||||||
|
DWORD signaled = WaitForMultipleObjects(3, events, FALSE, kFrameWaitMs);
|
||||||
|
if (signaled == WAIT_TIMEOUT) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Drain every signaled stream this tick; manual-reset events are reset
|
||||||
|
// by the DLL (skeleton) or the app (image) per section 3.3.
|
||||||
|
if (WaitForSingleObject(skeleton_event, 0) == WAIT_OBJECT_0) {
|
||||||
|
ConsumeSkeletonFrame(stats);
|
||||||
|
}
|
||||||
|
if (WaitForSingleObject(depth_event, 0) == WAIT_OBJECT_0) {
|
||||||
|
ResetEvent(depth_event);
|
||||||
|
ConsumeImageFrame(depth_stream, "depth", kDepthWidth * 2, stats.depth_frames,
|
||||||
|
stats);
|
||||||
|
}
|
||||||
|
if (WaitForSingleObject(color_event, 0) == WAIT_OBJECT_0) {
|
||||||
|
ResetEvent(color_event);
|
||||||
|
ConsumeImageFrame(color_stream, "color", kDepthWidth * 4, stats.color_frames,
|
||||||
|
stats);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
NuiShutdown();
|
||||||
|
CloseHandle(skeleton_event);
|
||||||
|
CloseHandle(depth_event);
|
||||||
|
CloseHandle(color_event);
|
||||||
|
|
||||||
|
std::printf("[mock-nui-host] skeleton_frames=%d tracked=%d depth_frames=%d color_frames=%d\n",
|
||||||
|
stats.skeleton_frames, stats.tracked_skeletons, stats.depth_frames,
|
||||||
|
stats.color_frames);
|
||||||
|
std::printf("[mock-nui-host] frame_numbers_monotonic=%d timestamps_monotonic=%d\n",
|
||||||
|
stats.frame_numbers_monotonic ? 1 : 0, stats.timestamps_monotonic ? 1 : 0);
|
||||||
|
|
||||||
|
bool passed = ok && !stats.errored && stats.skeleton_frames > 0 &&
|
||||||
|
stats.depth_frames > 0 && stats.color_frames > 0 &&
|
||||||
|
stats.frame_numbers_monotonic && stats.timestamps_monotonic;
|
||||||
|
std::printf("[mock-nui-host] RESULT: %s\n", passed ? "PASS" : "FAIL");
|
||||||
|
return passed ? 0 : 1;
|
||||||
|
}
|
||||||
@@ -1,4 +1,65 @@
|
|||||||
# tools/record-replay/ — record/replay harness (todo 16)
|
# tools/record-replay/ — record/replay harness (plan todo 16)
|
||||||
|
|
||||||
Captures tracker/synth output to a fixture file and replays it deterministically into the
|
A deterministic, dependency-free (pure-Python + the frozen `ctypes` contract) harness that
|
||||||
emitter/shim on a **fake clock** (no wall-clock sleeps). Placeholder until todo 16.
|
**records** frames published to the shared-memory IPC frame contract into a fixture file and
|
||||||
|
**replays** them back — into the emitter/shim or any consumer — on a **fake clock**, with no
|
||||||
|
wall-clock sleeps. It is the project's top test asset: it lets the emitter/shim be exercised
|
||||||
|
with no webcam/tracker and reproduces any failure frame-for-frame.
|
||||||
|
|
||||||
|
## Package `vkrr`
|
||||||
|
|
||||||
|
```
|
||||||
|
vkrr/
|
||||||
|
clock.py FakeClock — monotonic virtual time in microseconds; replay's only time source
|
||||||
|
buffer.py ContractFrameBuffer — Python mirror of the C triple-buffer publish/read protocol
|
||||||
|
fixture.py VKRR fixture format: write_fixture / read_fixture + clean truncation/format errors
|
||||||
|
harness.py Recorder (newest-wins capture) + Replayer (fake-clock replay) + synthetic frames
|
||||||
|
__main__.py `python -m vkrr` demo: record -> replay -> prove byte-identical, no wall sleeps
|
||||||
|
```
|
||||||
|
|
||||||
|
The harness builds on `tracker/contract.py` (the frozen, versioned IPC contract, todo 2): a
|
||||||
|
recorded frame is the `FrameData` struct — SkeletonFrame + depth/color buffer descriptors +
|
||||||
|
frame number + QPC-style timestamp — paired with its publish sequence number.
|
||||||
|
|
||||||
|
## Fixture format (`.vkrr`)
|
||||||
|
|
||||||
|
Fixed-width, little-endian, self-describing so a truncated or contract-drifted file is rejected
|
||||||
|
cleanly instead of replayed as garbage:
|
||||||
|
|
||||||
|
```
|
||||||
|
header : magic b"VKRR" | format_version u32 | contract_version u32 | frame_data_size u32 | frame_count u32
|
||||||
|
record : sequence u64 | frame_data (sizeof(FrameData) bytes) # repeated frame_count times
|
||||||
|
```
|
||||||
|
|
||||||
|
`read_fixture` raises `TruncatedFixtureError` on a short header/record and `FixtureFormatError`
|
||||||
|
on bad magic, an unsupported format version, a `frame_data_size` mismatch (contract drift), or
|
||||||
|
trailing bytes.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```python
|
||||||
|
import vkrr
|
||||||
|
|
||||||
|
# record frames published to the contract (newest-wins, like the triple buffer)
|
||||||
|
buffer, recorder = vkrr.ContractFrameBuffer(), vkrr.Recorder()
|
||||||
|
buffer.publish(frame_data); recorder.poll(buffer)
|
||||||
|
recorder.write("session.vkrr")
|
||||||
|
|
||||||
|
# replay deterministically into any consumer on a fake clock (no sleeps)
|
||||||
|
clock = vkrr.FakeClock()
|
||||||
|
vkrr.Replayer.from_fixture("session.vkrr", clock).replay(lambda seq, frame: consume(frame))
|
||||||
|
# or back into the frame contract:
|
||||||
|
vkrr.Replayer.from_fixture("session.vkrr").replay_into(vkrr.ContractFrameBuffer())
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
`tests/test_record_replay.py` (run from the repo root):
|
||||||
|
|
||||||
|
```
|
||||||
|
.venv/bin/pytest -q tests/test_record_replay.py
|
||||||
|
```
|
||||||
|
|
||||||
|
It records a synthetic sequence, replays it, asserts byte-identical frames out and monotonic
|
||||||
|
frame numbers, reproduces the exact recorded sequence back into the contract, and asserts a
|
||||||
|
truncated/corrupt fixture errors cleanly.
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
"""Virtual-Kinect record/replay harness (plan todo 16).
|
||||||
|
|
||||||
|
Records frames published to the shared-memory IPC frame contract into a
|
||||||
|
deterministic fixture file and replays them back - into the emitter/shim or any
|
||||||
|
consumer - on a fake clock, with no wall-clock sleeps. The fixture is byte-exact
|
||||||
|
so a replay reproduces the recorded frame sequence bit-for-bit, and a truncated
|
||||||
|
or contract-drifted fixture is rejected cleanly.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .buffer import ContractFrameBuffer, copy_frame
|
||||||
|
from .clock import FakeClock
|
||||||
|
from .fixture import (
|
||||||
|
FORMAT_VERSION,
|
||||||
|
MAGIC,
|
||||||
|
FixtureError,
|
||||||
|
FixtureFormatError,
|
||||||
|
FixtureHeader,
|
||||||
|
RecordedFrame,
|
||||||
|
TruncatedFixtureError,
|
||||||
|
read_fixture,
|
||||||
|
write_fixture,
|
||||||
|
)
|
||||||
|
from .harness import Recorder, Replayer, build_synthetic_frame
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ContractFrameBuffer",
|
||||||
|
"copy_frame",
|
||||||
|
"FakeClock",
|
||||||
|
"FORMAT_VERSION",
|
||||||
|
"MAGIC",
|
||||||
|
"FixtureError",
|
||||||
|
"FixtureFormatError",
|
||||||
|
"FixtureHeader",
|
||||||
|
"RecordedFrame",
|
||||||
|
"TruncatedFixtureError",
|
||||||
|
"read_fixture",
|
||||||
|
"write_fixture",
|
||||||
|
"Recorder",
|
||||||
|
"Replayer",
|
||||||
|
"build_synthetic_frame",
|
||||||
|
]
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""Runnable record/replay demo: ``python -m vkrr [fixture_path]`` (plan todo 16).
|
||||||
|
|
||||||
|
Records a short synthetic frame sequence, writes a fixture, replays it on a fake
|
||||||
|
clock, and prints a summary proving the replay is byte-identical and the fake
|
||||||
|
clock advanced without any wall-clock wait.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
|
||||||
|
from . import (
|
||||||
|
ContractFrameBuffer,
|
||||||
|
FakeClock,
|
||||||
|
Recorder,
|
||||||
|
Replayer,
|
||||||
|
build_synthetic_frame,
|
||||||
|
read_fixture,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str]) -> int:
|
||||||
|
path = argv[1] if len(argv) > 1 else tempfile.mktemp(suffix=".vkrr")
|
||||||
|
buffer = ContractFrameBuffer()
|
||||||
|
recorder = Recorder()
|
||||||
|
frame_count = 30
|
||||||
|
for index in range(frame_count):
|
||||||
|
buffer.publish(build_synthetic_frame(index, 1_000_000 + index * 33_333, seed=7))
|
||||||
|
recorder.poll(buffer)
|
||||||
|
recorder.write(path)
|
||||||
|
|
||||||
|
originals = [bytes(frame) for _seq, frame in recorder.frames]
|
||||||
|
header, _ = read_fixture(path)
|
||||||
|
|
||||||
|
clock = FakeClock()
|
||||||
|
wall_start = time.monotonic()
|
||||||
|
replayed = Replayer.from_fixture(path, clock).replay(lambda _s, _f: None)
|
||||||
|
wall_elapsed_ms = (time.monotonic() - wall_start) * 1000.0
|
||||||
|
|
||||||
|
replayed_bytes = [bytes(frame) for _seq, frame in replayed]
|
||||||
|
identical = replayed_bytes == originals
|
||||||
|
|
||||||
|
print(f"fixture : {path}")
|
||||||
|
print(f"format/contract : v{header.format_version} / contract v{header.contract_version}")
|
||||||
|
print(f"recorded frames : {header.frame_count}")
|
||||||
|
print(f"byte-identical : {identical}")
|
||||||
|
print(f"virtual clock adv : {clock.now_micros() - 1_000_000} us over {frame_count} frames")
|
||||||
|
print(f"wall time : {wall_elapsed_ms:.3f} ms (fake clock, no sleeps)")
|
||||||
|
return 0 if identical else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main(sys.argv))
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"""Python mirror of the C triple-buffer publish/read protocol (plan todo 16).
|
||||||
|
|
||||||
|
Mirrors ``nui::contract::publish_frame`` / ``read_latest_frame`` from
|
||||||
|
core/contract/contract.h against the ctypes ``FrameContract`` in
|
||||||
|
tracker/contract.py, so the harness can record frames out of (and replay them
|
||||||
|
back into) the real shared-memory frame contract, not a parallel copy of it.
|
||||||
|
|
||||||
|
Semantics match the header: a single writer publishes by writing the slot one
|
||||||
|
ahead of the last published slot and then bumping ``published_sequence``; a
|
||||||
|
reader takes ``slots[published_sequence % FRAME_SLOT_COUNT]`` as newest. Only
|
||||||
|
one writer may call ``publish``.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ctypes
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
_REPO_ROOT = os.path.dirname(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
)
|
||||||
|
if _REPO_ROOT not in sys.path:
|
||||||
|
sys.path.insert(0, _REPO_ROOT)
|
||||||
|
|
||||||
|
from tracker.contract import ( # noqa: E402
|
||||||
|
CONTRACT_VERSION,
|
||||||
|
FRAME_SLOT_COUNT,
|
||||||
|
FrameContract,
|
||||||
|
FrameData,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def copy_frame(frame: FrameData) -> FrameData:
|
||||||
|
"""Return an independent byte-for-byte copy of ``frame``."""
|
||||||
|
return FrameData.from_buffer_copy(bytes(frame))
|
||||||
|
|
||||||
|
|
||||||
|
class ContractFrameBuffer:
|
||||||
|
"""Single-writer / multi-reader triple buffer over a ctypes ``FrameContract``."""
|
||||||
|
|
||||||
|
__slots__ = ("_contract",)
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._contract = FrameContract()
|
||||||
|
self._contract.contract_version = CONTRACT_VERSION
|
||||||
|
|
||||||
|
@property
|
||||||
|
def published_sequence(self) -> int:
|
||||||
|
return self._contract.published_sequence
|
||||||
|
|
||||||
|
def publish(self, frame: FrameData) -> int:
|
||||||
|
"""Publish ``frame`` as the newest slot; returns its sequence number."""
|
||||||
|
contract = self._contract
|
||||||
|
next_sequence = contract.published_sequence + 1
|
||||||
|
slot = contract.slots[next_sequence % FRAME_SLOT_COUNT]
|
||||||
|
slot.sequence = next_sequence
|
||||||
|
ctypes.memmove(ctypes.byref(slot.data), ctypes.byref(frame), ctypes.sizeof(FrameData))
|
||||||
|
contract.published_sequence = next_sequence
|
||||||
|
return next_sequence
|
||||||
|
|
||||||
|
def read_latest(self) -> tuple[int, FrameData]:
|
||||||
|
"""Snapshot the newest published frame as ``(sequence, FrameData copy)``."""
|
||||||
|
contract = self._contract
|
||||||
|
sequence = contract.published_sequence
|
||||||
|
slot = contract.slots[sequence % FRAME_SLOT_COUNT]
|
||||||
|
return int(slot.sequence), copy_frame(slot.data)
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Deterministic fake clock for the record/replay harness (plan todo 16).
|
||||||
|
|
||||||
|
Replay is driven by this clock, never by ``time.sleep`` / wall-clock waits, so a
|
||||||
|
replayed session reproduces the exact recorded frame sequence and timing in zero
|
||||||
|
real time (the plan's "NO real sleeps/waits in tests" guardrail). The clock only
|
||||||
|
ever moves forward; a backwards move is a bug (recorded Kinect timestamps are
|
||||||
|
monotonic per nui-contracts.md §3.6) and raises rather than silently reordering.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
class FakeClock:
|
||||||
|
"""A monotonic virtual clock measured in microseconds.
|
||||||
|
|
||||||
|
It carries no real time at all: ``advance``/``set`` are the only way the
|
||||||
|
value moves, so replay pacing is fully deterministic and instantaneous.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__slots__ = ("_now",)
|
||||||
|
|
||||||
|
def __init__(self, start_micros: int = 0) -> None:
|
||||||
|
if start_micros < 0:
|
||||||
|
raise ValueError(f"start_micros must be >= 0, got {start_micros}")
|
||||||
|
self._now = int(start_micros)
|
||||||
|
|
||||||
|
def now_micros(self) -> int:
|
||||||
|
"""Current virtual time, microseconds."""
|
||||||
|
return self._now
|
||||||
|
|
||||||
|
def advance(self, delta_micros: int) -> int:
|
||||||
|
"""Move the clock forward by ``delta_micros`` (must be >= 0)."""
|
||||||
|
delta = int(delta_micros)
|
||||||
|
if delta < 0:
|
||||||
|
raise ValueError(f"cannot advance a monotonic clock backwards: {delta}")
|
||||||
|
self._now += delta
|
||||||
|
return self._now
|
||||||
|
|
||||||
|
def set(self, micros: int) -> int:
|
||||||
|
"""Jump the clock to ``micros`` (must not be earlier than now)."""
|
||||||
|
target = int(micros)
|
||||||
|
if target < self._now:
|
||||||
|
raise ValueError(
|
||||||
|
f"cannot move a monotonic clock backwards: now={self._now} target={target}"
|
||||||
|
)
|
||||||
|
self._now = target
|
||||||
|
return self._now
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""Deterministic fixture file format for recorded Kinect frames (plan todo 16).
|
||||||
|
|
||||||
|
A fixture is a simple framed binary file capturing a sequence of
|
||||||
|
``(sequence, FrameData)`` records, where ``FrameData`` (tracker/contract.py)
|
||||||
|
already carries the SkeletonFrame, the depth/color buffer descriptors, the
|
||||||
|
frame number and the QPC-style timestamp. The on-disk layout is fixed-width and
|
||||||
|
self-describing so a truncated or drifted fixture is detected and rejected
|
||||||
|
cleanly rather than replayed as garbage:
|
||||||
|
|
||||||
|
header (little-endian):
|
||||||
|
magic 4s b"VKRR"
|
||||||
|
format_version I FORMAT_VERSION
|
||||||
|
contract_version I tracker.contract.CONTRACT_VERSION at record time
|
||||||
|
frame_data_size I sizeof(FrameData); guards against contract drift
|
||||||
|
frame_count I number of records that follow
|
||||||
|
record (repeated frame_count times):
|
||||||
|
sequence Q publish sequence number
|
||||||
|
frame_data {frame_data_size} bytes of FrameData
|
||||||
|
|
||||||
|
The format is byte-exact: replaying a fixture reproduces the recorded frames
|
||||||
|
bit-for-bit, which is what the harness asserts.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import struct
|
||||||
|
from typing import BinaryIO, Iterable, List, NamedTuple, Tuple
|
||||||
|
|
||||||
|
from .buffer import copy_frame
|
||||||
|
from tracker.contract import CONTRACT_VERSION, FrameData
|
||||||
|
|
||||||
|
MAGIC = b"VKRR"
|
||||||
|
FORMAT_VERSION = 1
|
||||||
|
|
||||||
|
_HEADER = struct.Struct("<4sIIII")
|
||||||
|
_RECORD_PREFIX = struct.Struct("<Q")
|
||||||
|
|
||||||
|
|
||||||
|
class FixtureError(Exception):
|
||||||
|
"""Base class for fixture read failures."""
|
||||||
|
|
||||||
|
|
||||||
|
class FixtureFormatError(FixtureError):
|
||||||
|
"""The fixture is not a valid/compatible VKRR fixture (bad magic, version, drift)."""
|
||||||
|
|
||||||
|
|
||||||
|
class TruncatedFixtureError(FixtureError):
|
||||||
|
"""The fixture ended mid-header or mid-record."""
|
||||||
|
|
||||||
|
|
||||||
|
class FixtureHeader(NamedTuple):
|
||||||
|
format_version: int
|
||||||
|
contract_version: int
|
||||||
|
frame_data_size: int
|
||||||
|
frame_count: int
|
||||||
|
|
||||||
|
|
||||||
|
RecordedFrame = Tuple[int, FrameData]
|
||||||
|
|
||||||
|
|
||||||
|
def _frame_data_size() -> int:
|
||||||
|
import ctypes
|
||||||
|
|
||||||
|
return ctypes.sizeof(FrameData)
|
||||||
|
|
||||||
|
|
||||||
|
def write_fixture(path: str, frames: Iterable[RecordedFrame]) -> int:
|
||||||
|
"""Write ``frames`` to ``path`` as a VKRR fixture; returns the record count."""
|
||||||
|
frame_data_size = _frame_data_size()
|
||||||
|
materialized: List[RecordedFrame] = list(frames)
|
||||||
|
with open(path, "wb") as handle:
|
||||||
|
handle.write(
|
||||||
|
_HEADER.pack(MAGIC, FORMAT_VERSION, CONTRACT_VERSION, frame_data_size, len(materialized))
|
||||||
|
)
|
||||||
|
for sequence, frame in materialized:
|
||||||
|
payload = bytes(frame)
|
||||||
|
if len(payload) != frame_data_size:
|
||||||
|
raise FixtureFormatError(
|
||||||
|
f"frame payload is {len(payload)} bytes, expected {frame_data_size}"
|
||||||
|
)
|
||||||
|
handle.write(_RECORD_PREFIX.pack(sequence))
|
||||||
|
handle.write(payload)
|
||||||
|
return len(materialized)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_exact(handle: BinaryIO, count: int, what: str) -> bytes:
|
||||||
|
data = handle.read(count)
|
||||||
|
if len(data) != count:
|
||||||
|
raise TruncatedFixtureError(
|
||||||
|
f"fixture truncated reading {what}: wanted {count} bytes, got {len(data)}"
|
||||||
|
)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def read_fixture(path: str) -> Tuple[FixtureHeader, List[RecordedFrame]]:
|
||||||
|
"""Read and validate a VKRR fixture; returns ``(header, [(sequence, FrameData), ...])``."""
|
||||||
|
expected_size = _frame_data_size()
|
||||||
|
with open(path, "rb") as handle:
|
||||||
|
header_bytes = _read_exact(handle, _HEADER.size, "header")
|
||||||
|
magic, format_version, contract_version, frame_data_size, frame_count = _HEADER.unpack(
|
||||||
|
header_bytes
|
||||||
|
)
|
||||||
|
if magic != MAGIC:
|
||||||
|
raise FixtureFormatError(f"bad magic {magic!r}, expected {MAGIC!r}")
|
||||||
|
if format_version != FORMAT_VERSION:
|
||||||
|
raise FixtureFormatError(
|
||||||
|
f"unsupported fixture format version {format_version}, expected {FORMAT_VERSION}"
|
||||||
|
)
|
||||||
|
if frame_data_size != expected_size:
|
||||||
|
raise FixtureFormatError(
|
||||||
|
f"fixture frame_data_size {frame_data_size} != current FrameData size "
|
||||||
|
f"{expected_size} (contract drift)"
|
||||||
|
)
|
||||||
|
frames: List[RecordedFrame] = []
|
||||||
|
for index in range(frame_count):
|
||||||
|
(sequence,) = _RECORD_PREFIX.unpack(
|
||||||
|
_read_exact(handle, _RECORD_PREFIX.size, f"record {index} prefix")
|
||||||
|
)
|
||||||
|
payload = _read_exact(handle, frame_data_size, f"record {index} payload")
|
||||||
|
frames.append((sequence, FrameData.from_buffer_copy(payload)))
|
||||||
|
trailing = handle.read(1)
|
||||||
|
if trailing:
|
||||||
|
raise FixtureFormatError(
|
||||||
|
f"fixture has trailing bytes after {frame_count} records (corrupt)"
|
||||||
|
)
|
||||||
|
return FixtureHeader(format_version, contract_version, frame_data_size, frame_count), frames
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""Record and replay Kinect frames deterministically on a fake clock (plan todo 16).
|
||||||
|
|
||||||
|
The Recorder captures frames published to the shared-memory frame contract
|
||||||
|
(newest-wins: only strictly-advancing publish sequences are kept, mirroring the
|
||||||
|
triple buffer dropping intermediate frames a consumer never read). The Replayer
|
||||||
|
feeds recorded frames back - into a consumer callback or a ``ContractFrameBuffer``
|
||||||
|
- pacing the replay with a ``FakeClock`` advanced to each frame's recorded
|
||||||
|
timestamp, so a replayed session reproduces the exact recorded sequence with no
|
||||||
|
wall-clock sleeps.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Callable, List, Optional, Sequence
|
||||||
|
|
||||||
|
from .buffer import ContractFrameBuffer, copy_frame
|
||||||
|
from .clock import FakeClock
|
||||||
|
from .fixture import RecordedFrame, read_fixture, write_fixture
|
||||||
|
from tracker.contract import (
|
||||||
|
JOINT_COUNT,
|
||||||
|
ColorBufferDescriptor,
|
||||||
|
DepthBufferDescriptor,
|
||||||
|
FrameData,
|
||||||
|
JointData,
|
||||||
|
JointTrackingState,
|
||||||
|
SkeletonFrame,
|
||||||
|
Vector4,
|
||||||
|
)
|
||||||
|
|
||||||
|
FrameSink = Callable[[int, FrameData], None]
|
||||||
|
|
||||||
|
|
||||||
|
class Recorder:
|
||||||
|
"""Captures a newest-wins stream of published frames into a fixture."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._frames: List[RecordedFrame] = []
|
||||||
|
self._last_sequence = -1
|
||||||
|
|
||||||
|
def capture(self, sequence: int, frame: FrameData) -> bool:
|
||||||
|
"""Record ``frame`` if ``sequence`` advances; returns whether it was kept."""
|
||||||
|
if sequence <= self._last_sequence:
|
||||||
|
return False
|
||||||
|
self._last_sequence = sequence
|
||||||
|
self._frames.append((sequence, copy_frame(frame)))
|
||||||
|
return True
|
||||||
|
|
||||||
|
def poll(self, buffer: ContractFrameBuffer) -> bool:
|
||||||
|
"""Read the newest frame from ``buffer`` and capture it (newest-wins)."""
|
||||||
|
sequence, frame = buffer.read_latest()
|
||||||
|
return self.capture(sequence, frame)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def frames(self) -> List[RecordedFrame]:
|
||||||
|
return self._frames
|
||||||
|
|
||||||
|
def write(self, path: str) -> int:
|
||||||
|
"""Flush the captured frames to a fixture file; returns the record count."""
|
||||||
|
return write_fixture(path, self._frames)
|
||||||
|
|
||||||
|
|
||||||
|
class Replayer:
|
||||||
|
"""Replays recorded frames deterministically on a fake clock."""
|
||||||
|
|
||||||
|
def __init__(self, frames: Sequence[RecordedFrame], clock: Optional[FakeClock] = None) -> None:
|
||||||
|
self._frames = list(frames)
|
||||||
|
self._clock = clock if clock is not None else FakeClock()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_fixture(cls, path: str, clock: Optional[FakeClock] = None) -> "Replayer":
|
||||||
|
_header, frames = read_fixture(path)
|
||||||
|
return cls(frames, clock)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def clock(self) -> FakeClock:
|
||||||
|
return self._clock
|
||||||
|
|
||||||
|
def replay(self, sink: FrameSink) -> List[RecordedFrame]:
|
||||||
|
"""Drive ``sink(sequence, frame)`` for every frame, pacing on the fake clock.
|
||||||
|
|
||||||
|
The clock is advanced to each frame's recorded timestamp (never via a
|
||||||
|
real sleep); it starts at the first frame's timestamp so recorded
|
||||||
|
timestamps need only be monotonic, not zero-based.
|
||||||
|
"""
|
||||||
|
replayed: List[RecordedFrame] = []
|
||||||
|
for index, (sequence, frame) in enumerate(self._frames):
|
||||||
|
timestamp = int(frame.timestamp_micros)
|
||||||
|
if index == 0:
|
||||||
|
self._clock.set(max(timestamp, self._clock.now_micros()))
|
||||||
|
else:
|
||||||
|
self._clock.set(timestamp)
|
||||||
|
emitted = copy_frame(frame)
|
||||||
|
sink(sequence, emitted)
|
||||||
|
replayed.append((sequence, emitted))
|
||||||
|
return replayed
|
||||||
|
|
||||||
|
def replay_into(self, buffer: ContractFrameBuffer) -> List[RecordedFrame]:
|
||||||
|
"""Replay every recorded frame back into a ``ContractFrameBuffer``."""
|
||||||
|
return self.replay(lambda _sequence, frame: buffer.publish(frame))
|
||||||
|
|
||||||
|
|
||||||
|
def build_synthetic_frame(frame_number: int, timestamp_micros: int, seed: int = 0) -> FrameData:
|
||||||
|
"""Construct a deterministic synthetic ``FrameData`` for tests and demos."""
|
||||||
|
skeleton = SkeletonFrame()
|
||||||
|
for joint_index in range(JOINT_COUNT):
|
||||||
|
base = float(seed + frame_number + joint_index)
|
||||||
|
skeleton.joints[joint_index] = JointData(
|
||||||
|
position=Vector4(
|
||||||
|
x=base * 0.011,
|
||||||
|
y=base * 0.022,
|
||||||
|
z=1.5 + (joint_index % 5) * 0.1,
|
||||||
|
w=1.0,
|
||||||
|
),
|
||||||
|
tracking_state=(
|
||||||
|
JointTrackingState.TRACKED
|
||||||
|
if joint_index % 4
|
||||||
|
else JointTrackingState.INFERRED
|
||||||
|
),
|
||||||
|
)
|
||||||
|
skeleton.skeleton_tracking_id = 1 + (frame_number % 6)
|
||||||
|
skeleton.quality_flags = frame_number & 0x3
|
||||||
|
|
||||||
|
depth = DepthBufferDescriptor(width=640, height=480, pitch=640 * 2, byte_offset=0)
|
||||||
|
color = ColorBufferDescriptor(
|
||||||
|
width=640, height=480, pitch=640 * 4, byte_offset=640 * 480 * 2
|
||||||
|
)
|
||||||
|
return FrameData(
|
||||||
|
frame_number=frame_number,
|
||||||
|
timestamp_micros=timestamp_micros,
|
||||||
|
skeleton=skeleton,
|
||||||
|
depth=depth,
|
||||||
|
color=color,
|
||||||
|
)
|
||||||
+118
-6
@@ -1,8 +1,120 @@
|
|||||||
# tracker/ — webcam pose + segmentation tracker (todo 5)
|
# tracker/ — webcam pose + segmentation tracker (plan todo 5)
|
||||||
|
|
||||||
Python: OpenCV webcam capture -> MediaPipe Pose (Full/Heavy) -> 33 landmarks +
|
Python pipeline: OpenCV capture (webcam **or** video file) → MediaPipe Pose
|
||||||
world-landmarks + visibility + segmentation mask, published to the shared-memory
|
Landmarker (33 normalized landmarks + 33 world landmarks in metres + per-landmark
|
||||||
contract at the newest-wins slot each frame, plus control-plane handshake/heartbeat.
|
visibility + segmentation mask) → published to the frozen shared-memory IPC
|
||||||
|
contract (`tracker/contract.py`, mirror of `core/contract/contract.h`) at the
|
||||||
|
newest-wins slot each frame, plus a control-plane handshake/heartbeat.
|
||||||
|
|
||||||
Dependencies are declared in `pyproject.toml` but **not installed by todo 1** — the
|
## Layout
|
||||||
OpenCV/MediaPipe install and the real pipeline arrive in todo 5.
|
|
||||||
|
| file | role |
|
||||||
|
|------|------|
|
||||||
|
| `pose.py` | `PoseResult`, `PoseProvider` seam, `MediaPipePoseProvider` (Tasks API, VIDEO mode) |
|
||||||
|
| `publisher.py` | `FrameContractPublisher` — shared-memory triple-buffer producer (seqlock publish) |
|
||||||
|
| `control.py` | handshake + heartbeat control plane over a unix socket |
|
||||||
|
| `tracker.py` | capture + background inference + monotonic-clock publish loop + CLI |
|
||||||
|
| `fake_pose.py` | synthetic providers/sources that drive the data path without MediaPipe |
|
||||||
|
|
||||||
|
## Design (satisfies the plan's MUST-NOTs)
|
||||||
|
|
||||||
|
- **Inference never blocks the publish path.** Capture + inference run on a
|
||||||
|
background thread and cache the latest `(frame, PoseResult)`; the publish loop
|
||||||
|
publishes whatever is latest, re-publishing the previous pose when inference is
|
||||||
|
slower than the cadence.
|
||||||
|
- **No fixed sleeps.** The publish loop paces to a monotonic frame clock
|
||||||
|
(`deadline = start + n·period`) and waits exactly until the next deadline.
|
||||||
|
- **Scope boundary.** The 20 contract joints 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.
|
||||||
|
|
||||||
|
## Environment setup (this host: Python 3.14, no sudo/apt-install)
|
||||||
|
|
||||||
|
The system Python is 3.14, which has **no MediaPipe wheel**, and `python3-venv`'s
|
||||||
|
`ensurepip` is missing. The working route is user-space [`uv`](https://github.com/astral-sh/uv):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pip install --user --break-system-packages uv
|
||||||
|
export PATH="$HOME/.local/bin:$PATH"
|
||||||
|
uv python install 3.12
|
||||||
|
uv venv --python 3.12 tracker/.venv
|
||||||
|
uv pip install --python tracker/.venv numpy pytest opencv-python-headless mediapipe
|
||||||
|
```
|
||||||
|
|
||||||
|
Installed here: Python 3.12.16, numpy 2.5.5, opencv-python-headless 5.1.0,
|
||||||
|
mediapipe 1.2.3.
|
||||||
|
|
||||||
|
### MediaPipe model bundles
|
||||||
|
|
||||||
|
mediapipe ≥ 1.x ships only the Tasks API (no legacy `mp.solutions.pose`); it loads
|
||||||
|
a `.task` bundle. Download the tiers into `tracker/models/` (git-ignored):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
base="https://storage.googleapis.com/mediapipe-models/pose_landmarker"
|
||||||
|
for t in lite full heavy; do
|
||||||
|
curl -fsSL -o tracker/models/pose_landmarker_$t.task \
|
||||||
|
"$base/pose_landmarker_$t/float16/latest/pose_landmarker_$t.task"
|
||||||
|
done
|
||||||
|
```
|
||||||
|
|
||||||
|
### System GL library (user-space workaround)
|
||||||
|
|
||||||
|
mediapipe 1.2.3's C bindings need `libGLESv2.so.2`, which is absent on this box and
|
||||||
|
cannot be `apt install`ed without sudo. It was supplied user-space (no sudo) via:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd /tmp && apt-get download libgles2 && dpkg-deb -x libgles2_*.deb ext
|
||||||
|
mkdir -p ~/.cache/kinect/gllibs && cp -a ext/usr/lib/*/libGLESv2.so.2* ~/.cache/kinect/gllibs/
|
||||||
|
export LD_LIBRARY_PATH="$HOME/.cache/kinect/gllibs:$LD_LIBRARY_PATH"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
export LD_LIBRARY_PATH="$HOME/.cache/kinect/gllibs:$LD_LIBRARY_PATH"
|
||||||
|
# webcam:
|
||||||
|
tracker/.venv/bin/python -m tracker.tracker --source 0 --model full
|
||||||
|
# recorded file:
|
||||||
|
tracker/.venv/bin/python -m tracker.tracker --source clip.avi --model full --max-frames 300
|
||||||
|
# benchmark the tiers and exit:
|
||||||
|
tracker/.venv/bin/python -m tracker.tracker --source clip.avi --measure-fps
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tests & measured evidence
|
||||||
|
|
||||||
|
```sh
|
||||||
|
tracker/.venv/bin/python -m pytest tests/test_tracker.py -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Data-path suite is green (9/9): fake-pose → contract packing → shared-memory
|
||||||
|
publish → read-back, plus the no-person (low-visibility / no-body) frame and the
|
||||||
|
control-plane handshake/heartbeat round-trip. Full repo Python suite: 73 passed.
|
||||||
|
|
||||||
|
Live MediaPipe smoke (recorded 256×256 synthetic-humanoid clip, CPU/XNNPACK):
|
||||||
|
real 33-landmark detection (x∈[0.21,0.79], y∈[0.21,0.93]), world landmarks in
|
||||||
|
metres, a 256×256 segmentation mask, `tracking_id=1`, depth body pixels published,
|
||||||
|
publish cadence ~31.6 fps. Measured inference fps on this CPU:
|
||||||
|
|
||||||
|
| tier | fps (256×256, CPU) |
|
||||||
|
|------|--------------------|
|
||||||
|
| lite | ~80 |
|
||||||
|
| full | ~62 |
|
||||||
|
| heavy | ~20 |
|
||||||
|
|
||||||
|
→ **full** is the selected tier (comfortably ≥25 fps on CPU at this resolution;
|
||||||
|
heavy drops below 25). Measured at 256×256; fps at 640×480 will be lower and
|
||||||
|
should be re-measured against the real capture resolution. Evidence:
|
||||||
|
`.omo/evidence/task-5-webcam-kinect-emulator.log`.
|
||||||
|
|
||||||
|
## Blocked / not verified here [~]
|
||||||
|
|
||||||
|
- **Live webcam device**: this headless WSL2 box has no camera; the pipeline was
|
||||||
|
validated against a recorded video file (as the plan prescribes for
|
||||||
|
determinism). Running against `--source 0` on real hardware is unverified.
|
||||||
|
- **GPU inference tier**: no GPU on this host; all fps numbers are CPU/XNNPACK.
|
||||||
|
- **fps at 640×480**: measured at 256×480→256×256 only; re-measure at the host's
|
||||||
|
requested capture/stream resolution before committing to the `full` tier.
|
||||||
|
- **libGLESv2.so.2**: required a user-space deb-extraction workaround (above); a
|
||||||
|
proper deploy should install the system `libgles2` package.
|
||||||
+16
-5
@@ -1,12 +1,23 @@
|
|||||||
"""Webcam -> virtual Kinect tracker package (plan todo 5).
|
"""Webcam -> virtual Kinect tracker package (plan todo 5).
|
||||||
|
|
||||||
Currently a package placeholder. Runtime dependencies (opencv-python, mediapipe, numpy)
|
Captures webcam/video frames, runs MediaPipe Pose, and publishes Kinect-style
|
||||||
are declared in pyproject.toml but intentionally NOT installed by todo 1.
|
frames over the frozen shared-memory IPC contract (`tracker.contract`). The
|
||||||
|
pipeline is built around the `tracker.pose.PoseProvider` seam so a fake provider
|
||||||
|
can drive the data path in tests without MediaPipe.
|
||||||
|
|
||||||
|
Modules:
|
||||||
|
* `contract` - ctypes mirror of core/contract/contract.h (todo 2).
|
||||||
|
* `pose` - PoseResult + PoseProvider + MediaPipePoseProvider.
|
||||||
|
* `publisher` - FrameContractPublisher (shared-memory triple-buffer producer).
|
||||||
|
* `control` - handshake/heartbeat control plane over a unix socket.
|
||||||
|
* `tracker` - capture + inference loop with monotonic-clock pacing + CLI.
|
||||||
|
* `fake_pose` - synthetic providers/sources for the data-path tests.
|
||||||
|
|
||||||
|
Imports are kept light here so `tracker.contract` is usable without numpy/cv2.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__version__ = "0.0.1"
|
__version__ = "0.1.0"
|
||||||
|
|
||||||
|
|
||||||
def tracker_info() -> dict:
|
def tracker_info() -> dict:
|
||||||
"""Return static metadata about the tracker package (placeholder for todo 5)."""
|
return {"name": "virtual-kinect-tracker", "version": __version__, "stage": "todo5-pipeline"}
|
||||||
return {"name": "virtual-kinect-tracker", "version": __version__, "stage": "scaffold"}
|
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
"""Control-plane handshake + heartbeat over a unix socket (plan todo 5).
|
||||||
|
|
||||||
|
The control side carries ONLY handshake/config/calibration/heartbeat messages
|
||||||
|
(never per-frame data, which travels through the shared-memory FrameContract).
|
||||||
|
This module serialises the frozen `ControlMessage*` ctypes structs and provides
|
||||||
|
a tiny non-blocking server the tracker runs alongside the publish loop: it
|
||||||
|
accepts a consumer connection, sends a handshake once, and emits a heartbeat
|
||||||
|
carrying the last published sequence as frames are published.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ctypes
|
||||||
|
import socket
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from .contract import (
|
||||||
|
CONTRACT_VERSION,
|
||||||
|
ControlMessageHeader,
|
||||||
|
ControlMessageType,
|
||||||
|
HandshakeMessage,
|
||||||
|
HeartbeatMessage,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def now_micros() -> int:
|
||||||
|
return time.monotonic_ns() // 1000
|
||||||
|
|
||||||
|
|
||||||
|
def build_handshake(client_version: int = CONTRACT_VERSION, capabilities: int = 0) -> bytes:
|
||||||
|
msg = HandshakeMessage()
|
||||||
|
msg.header.message_type = ControlMessageType.HANDSHAKE_VERSION
|
||||||
|
msg.header.contract_version = CONTRACT_VERSION
|
||||||
|
msg.header.payload_size = ctypes.sizeof(HandshakeMessage)
|
||||||
|
msg.header.reserved = 0
|
||||||
|
msg.client_version = client_version
|
||||||
|
msg.capabilities = capabilities
|
||||||
|
return bytes(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def build_heartbeat(sequence: int, timestamp_micros: Optional[int] = None) -> bytes:
|
||||||
|
msg = HeartbeatMessage()
|
||||||
|
msg.header.message_type = ControlMessageType.HEARTBEAT
|
||||||
|
msg.header.contract_version = CONTRACT_VERSION
|
||||||
|
msg.header.payload_size = ctypes.sizeof(HeartbeatMessage)
|
||||||
|
msg.header.reserved = 0
|
||||||
|
msg.timestamp_micros = now_micros() if timestamp_micros is None else timestamp_micros
|
||||||
|
msg.sequence = sequence
|
||||||
|
return bytes(msg)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_header(buf: bytes) -> ControlMessageHeader:
|
||||||
|
return ControlMessageHeader.from_buffer_copy(buf[: ctypes.sizeof(ControlMessageHeader)])
|
||||||
|
|
||||||
|
|
||||||
|
def parse_message(buf: bytes):
|
||||||
|
header = parse_header(buf)
|
||||||
|
if header.message_type == ControlMessageType.HANDSHAKE_VERSION:
|
||||||
|
return HandshakeMessage.from_buffer_copy(buf[: ctypes.sizeof(HandshakeMessage)])
|
||||||
|
if header.message_type == ControlMessageType.HEARTBEAT:
|
||||||
|
return HeartbeatMessage.from_buffer_copy(buf[: ctypes.sizeof(HeartbeatMessage)])
|
||||||
|
return header
|
||||||
|
|
||||||
|
|
||||||
|
class ControlPlaneServer:
|
||||||
|
"""Accepts one consumer on a unix socket; sends handshake then heartbeats.
|
||||||
|
|
||||||
|
Non-blocking by design: `send_heartbeat` is a no-op until a consumer
|
||||||
|
connects, so the publish loop never stalls on the control plane.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, socket_path: str) -> None:
|
||||||
|
self.socket_path = socket_path
|
||||||
|
self._listener: Optional[socket.socket] = None
|
||||||
|
self._conn: Optional[socket.socket] = None
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._stop = threading.Event()
|
||||||
|
self._thread: Optional[threading.Thread] = None
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
import os
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.unlink(self.socket_path)
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
self._listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||||
|
self._listener.bind(self.socket_path)
|
||||||
|
self._listener.listen(1)
|
||||||
|
self._listener.settimeout(0.5)
|
||||||
|
self._thread = threading.Thread(target=self._accept_loop, name="control-accept", daemon=True)
|
||||||
|
self._thread.start()
|
||||||
|
|
||||||
|
def _accept_loop(self) -> None:
|
||||||
|
while not self._stop.is_set():
|
||||||
|
try:
|
||||||
|
conn, _ = self._listener.accept()
|
||||||
|
except socket.timeout:
|
||||||
|
continue
|
||||||
|
except OSError:
|
||||||
|
break
|
||||||
|
with self._lock:
|
||||||
|
old = self._conn
|
||||||
|
self._conn = conn
|
||||||
|
if old is not None:
|
||||||
|
old.close()
|
||||||
|
try:
|
||||||
|
conn.sendall(build_handshake())
|
||||||
|
except OSError:
|
||||||
|
with self._lock:
|
||||||
|
if self._conn is conn:
|
||||||
|
self._conn = None
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def send_heartbeat(self, sequence: int) -> bool:
|
||||||
|
with self._lock:
|
||||||
|
conn = self._conn
|
||||||
|
if conn is None:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
conn.sendall(build_heartbeat(sequence))
|
||||||
|
return True
|
||||||
|
except OSError:
|
||||||
|
with self._lock:
|
||||||
|
if self._conn is conn:
|
||||||
|
self._conn = None
|
||||||
|
conn.close()
|
||||||
|
return False
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
if self._listener is not None:
|
||||||
|
self._listener.close()
|
||||||
|
with self._lock:
|
||||||
|
if self._conn is not None:
|
||||||
|
self._conn.close()
|
||||||
|
self._conn = None
|
||||||
|
if self._thread is not None:
|
||||||
|
self._thread.join(timeout=1.0)
|
||||||
|
import os
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.unlink(self.socket_path)
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
"""Synthetic pose + frame sources for testing the data path (plan todo 5).
|
||||||
|
|
||||||
|
`FakePoseProvider` emits deterministic 33-landmark `PoseResult`s (with a filled
|
||||||
|
segmentation mask) so the landmarks -> contract packing -> shared-memory publish
|
||||||
|
path can be verified without MediaPipe. It can also emit a "no person" frame
|
||||||
|
(returns None) to exercise the low-visibility / no-body publish branch.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from .pose import LANDMARK_COUNT, PoseProvider, PoseResult
|
||||||
|
|
||||||
|
|
||||||
|
def make_fake_pose(
|
||||||
|
frame_index: int = 0,
|
||||||
|
image_width: int = 640,
|
||||||
|
image_height: int = 480,
|
||||||
|
visibility: float = 0.9,
|
||||||
|
mask_box: tuple[float, float, float, float] = (0.3, 0.1, 0.7, 0.95),
|
||||||
|
) -> PoseResult:
|
||||||
|
"""Build one deterministic pose: landmarks on a vertical line that sways with
|
||||||
|
`frame_index`, world landmarks in a plausible metric range, and a rectangular
|
||||||
|
body mask (fractions of the image: x0, y0, x1, y1)."""
|
||||||
|
sway = 0.05 * np.sin(frame_index * 0.2)
|
||||||
|
landmarks: list[tuple[float, float, float, float]] = []
|
||||||
|
world_landmarks: list[tuple[float, float, float]] = []
|
||||||
|
vis: list[float] = []
|
||||||
|
for i in range(LANDMARK_COUNT):
|
||||||
|
t = i / (LANDMARK_COUNT - 1)
|
||||||
|
x = 0.5 + sway + 0.1 * np.cos(t * np.pi)
|
||||||
|
y = 0.1 + 0.8 * t
|
||||||
|
z = -0.2 + 0.4 * t
|
||||||
|
landmarks.append((float(x), float(y), float(z), visibility))
|
||||||
|
world_landmarks.append((float((x - 0.5) * 1.2), float((0.5 - y) * 1.6), float(1.5 + z)))
|
||||||
|
vis.append(visibility)
|
||||||
|
|
||||||
|
mask = np.zeros((image_height, image_width), dtype=np.float32)
|
||||||
|
x0, y0, x1, y1 = mask_box
|
||||||
|
mask[int(y0 * image_height):int(y1 * image_height), int(x0 * image_width):int(x1 * image_width)] = 1.0
|
||||||
|
|
||||||
|
return PoseResult(
|
||||||
|
landmarks=landmarks,
|
||||||
|
world_landmarks=world_landmarks,
|
||||||
|
visibility=vis,
|
||||||
|
image_width=image_width,
|
||||||
|
image_height=image_height,
|
||||||
|
mask=mask,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class FakePoseProvider(PoseProvider):
|
||||||
|
"""Deterministic provider. `detect_every` frames yield a pose; the rest yield
|
||||||
|
None (no person), so a run exercises both the body and no-body branches."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
image_width: int = 640,
|
||||||
|
image_height: int = 480,
|
||||||
|
detect_every: int = 1,
|
||||||
|
no_person: bool = False,
|
||||||
|
) -> None:
|
||||||
|
self.image_width = image_width
|
||||||
|
self.image_height = image_height
|
||||||
|
self.detect_every = detect_every
|
||||||
|
self.no_person = no_person
|
||||||
|
self._count = 0
|
||||||
|
|
||||||
|
def process(self, frame_bgr, timestamp_ms=None):
|
||||||
|
idx = self._count
|
||||||
|
self._count += 1
|
||||||
|
if self.no_person or (self.detect_every > 1 and idx % self.detect_every != 0):
|
||||||
|
return None
|
||||||
|
return make_fake_pose(idx, self.image_width, self.image_height)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeFrameSource:
|
||||||
|
"""Yields synthetic BGR frames; `n_frames=None` streams forever (for pacing
|
||||||
|
tests), otherwise signals end-of-stream after `n_frames`."""
|
||||||
|
|
||||||
|
def __init__(self, n_frames=None, width: int = 640, height: int = 480) -> None:
|
||||||
|
self.n_frames = n_frames
|
||||||
|
self.width = width
|
||||||
|
self.height = height
|
||||||
|
self._i = 0
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
if self.n_frames is not None and self._i >= self.n_frames:
|
||||||
|
return None
|
||||||
|
frame = np.full((self.height, self.width, 3), self._i % 256, dtype=np.uint8)
|
||||||
|
self._i += 1
|
||||||
|
return frame
|
||||||
|
|
||||||
|
def release(self) -> None:
|
||||||
|
pass
|
||||||
+182
@@ -0,0 +1,182 @@
|
|||||||
|
"""Pose data model + provider interface (plan todo 5).
|
||||||
|
|
||||||
|
The tracker is built around a small `PoseProvider` seam: the real pipeline uses
|
||||||
|
`MediaPipePoseProvider` (OpenCV frame -> MediaPipe Pose Landmarker), while tests
|
||||||
|
swap in `tracker.fake_pose.FakePoseProvider`. Everything downstream (the
|
||||||
|
shared-memory publisher, the control plane) consumes only `PoseResult`, so the
|
||||||
|
data path can be exercised end-to-end without MediaPipe installed.
|
||||||
|
|
||||||
|
`PoseResult` carries the *raw* MediaPipe output described by the plan:
|
||||||
|
* 33 normalized landmarks (x, y, z, visibility) in [0, 1] image space,
|
||||||
|
* 33 world landmarks (x, y, z) in meters (hip-centered, MediaPipe convention),
|
||||||
|
* per-landmark visibility,
|
||||||
|
* the segmentation mask (float32 HxW in [0, 1]) or None.
|
||||||
|
|
||||||
|
The MediaPipe-33 -> Kinect-20 joint *mapping* and the articulated synthetic
|
||||||
|
depth rasterizer are deliberately NOT here - they are plan todos 6 and 7. This
|
||||||
|
module and the publisher only move the raw pose through the frozen IPC contract.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import abc
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Optional, Sequence
|
||||||
|
|
||||||
|
try: # numpy is required for the mask; the skeleton path itself does not need it.
|
||||||
|
import numpy as np
|
||||||
|
except ImportError: # pragma: no cover - numpy is a hard dep of the tracker
|
||||||
|
np = None # type: ignore
|
||||||
|
|
||||||
|
# MediaPipe Pose emits 33 landmarks; see the Pose Landmarker landmark table.
|
||||||
|
LANDMARK_COUNT = 33
|
||||||
|
|
||||||
|
# Landmark index -> name, for readable debugging / downstream mapping (todo 6).
|
||||||
|
LANDMARK_NAMES: tuple[str, ...] = (
|
||||||
|
"nose", "left_eye_inner", "left_eye", "left_eye_outer", "right_eye_inner",
|
||||||
|
"right_eye", "right_eye_outer", "left_ear", "right_ear", "mouth_left",
|
||||||
|
"mouth_right", "left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
|
||||||
|
"left_wrist", "right_wrist", "left_pinky", "right_pinky", "left_index",
|
||||||
|
"right_index", "left_thumb", "right_thumb", "left_hip", "right_hip",
|
||||||
|
"left_knee", "right_knee", "left_ankle", "right_ankle", "left_heel",
|
||||||
|
"right_heel", "left_foot_index", "right_foot_index",
|
||||||
|
)
|
||||||
|
assert len(LANDMARK_NAMES) == LANDMARK_COUNT
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PoseResult:
|
||||||
|
"""One frame of raw MediaPipe pose output.
|
||||||
|
|
||||||
|
`landmarks` and `world_landmarks` always have exactly `LANDMARK_COUNT`
|
||||||
|
entries so the publisher can pack a fixed-shape frame without branching on
|
||||||
|
length. A frame with no detected person is represented by `pose=None` at the
|
||||||
|
provider seam, never by an empty `PoseResult`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
landmarks: Sequence[tuple[float, float, float, float]] # 33 x (x, y, z, visibility), normalized [0,1]
|
||||||
|
world_landmarks: Sequence[tuple[float, float, float]] # 33 x (x, y, z), meters
|
||||||
|
visibility: Sequence[float] # 33 x visibility [0,1]
|
||||||
|
image_width: int
|
||||||
|
image_height: int
|
||||||
|
mask: Optional["np.ndarray"] = None # HxW float32 in [0,1], or None
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if len(self.landmarks) != LANDMARK_COUNT:
|
||||||
|
raise ValueError(f"expected {LANDMARK_COUNT} landmarks, got {len(self.landmarks)}")
|
||||||
|
if len(self.world_landmarks) != LANDMARK_COUNT:
|
||||||
|
raise ValueError(f"expected {LANDMARK_COUNT} world landmarks, got {len(self.world_landmarks)}")
|
||||||
|
if len(self.visibility) != LANDMARK_COUNT:
|
||||||
|
raise ValueError(f"expected {LANDMARK_COUNT} visibility values, got {len(self.visibility)}")
|
||||||
|
|
||||||
|
|
||||||
|
class PoseProvider(abc.ABC):
|
||||||
|
"""Turns a BGR image frame into a `PoseResult`, or None when no person is found."""
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def process(self, frame_bgr: "np.ndarray", timestamp_ms: Optional[int] = None) -> Optional[PoseResult]:
|
||||||
|
"""Run inference on one BGR frame. Returns None if no pose was detected."""
|
||||||
|
|
||||||
|
def close(self) -> None: # noqa: B027 - optional override
|
||||||
|
"""Release any held resources. Default is a no-op."""
|
||||||
|
|
||||||
|
|
||||||
|
# Model tier -> bundled Pose Landmarker model file name (plan references the
|
||||||
|
# Lite/Full/Heavy tiers; the tier is selected from measured fps, see tracker.py).
|
||||||
|
MODEL_FILES = {
|
||||||
|
"lite": "pose_landmarker_lite.task",
|
||||||
|
"full": "pose_landmarker_full.task",
|
||||||
|
"heavy": "pose_landmarker_heavy.task",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class MediaPipePoseProvider(PoseProvider):
|
||||||
|
"""Real provider: MediaPipe Tasks `PoseLandmarker` (VIDEO running mode).
|
||||||
|
|
||||||
|
mediapipe >= 1.x ships only the Tasks API (no legacy `mp.solutions.pose`),
|
||||||
|
which loads a `.task` model bundle. `model` may be a tier name ("lite" /
|
||||||
|
"full" / "heavy", resolved against `models_dir`) or an explicit file path.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
model: str = "full",
|
||||||
|
models_dir: Optional[str] = None,
|
||||||
|
min_detection_confidence: float = 0.5,
|
||||||
|
min_tracking_confidence: float = 0.5,
|
||||||
|
min_presence_confidence: float = 0.5,
|
||||||
|
output_segmentation_masks: bool = True,
|
||||||
|
) -> None:
|
||||||
|
import os
|
||||||
|
|
||||||
|
import cv2 # noqa: F401 - imported here so the import error surfaces early
|
||||||
|
import mediapipe as mp
|
||||||
|
from mediapipe.tasks import python as mp_python
|
||||||
|
from mediapipe.tasks.python import vision
|
||||||
|
|
||||||
|
self._cv2 = cv2
|
||||||
|
self._mp = mp
|
||||||
|
|
||||||
|
if model in MODEL_FILES:
|
||||||
|
base = models_dir or os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
|
||||||
|
model_path = os.path.join(base, MODEL_FILES[model])
|
||||||
|
else:
|
||||||
|
model_path = model
|
||||||
|
if not os.path.exists(model_path):
|
||||||
|
raise FileNotFoundError(
|
||||||
|
f"Pose Landmarker model not found: {model_path}. "
|
||||||
|
f"Download a .task bundle (lite/full/heavy) into tracker/models/."
|
||||||
|
)
|
||||||
|
self.model_path = model_path
|
||||||
|
|
||||||
|
options = vision.PoseLandmarkerOptions(
|
||||||
|
base_options=mp_python.BaseOptions(model_asset_path=model_path),
|
||||||
|
running_mode=vision.RunningMode.VIDEO,
|
||||||
|
num_poses=1,
|
||||||
|
min_pose_detection_confidence=min_detection_confidence,
|
||||||
|
min_pose_presence_confidence=min_presence_confidence,
|
||||||
|
min_tracking_confidence=min_tracking_confidence,
|
||||||
|
output_segmentation_masks=output_segmentation_masks,
|
||||||
|
)
|
||||||
|
self._landmarker = vision.PoseLandmarker.create_from_options(options)
|
||||||
|
self._last_ts_ms = -1
|
||||||
|
|
||||||
|
def process(self, frame_bgr: "np.ndarray", timestamp_ms: Optional[int] = None) -> Optional[PoseResult]:
|
||||||
|
h, w = frame_bgr.shape[:2]
|
||||||
|
rgb = self._cv2.cvtColor(frame_bgr, self._cv2.COLOR_BGR2RGB)
|
||||||
|
mp_image = self._mp.Image(image_format=self._mp.ImageFormat.SRGB, data=rgb)
|
||||||
|
|
||||||
|
# VIDEO mode requires strictly-increasing timestamps.
|
||||||
|
ts = int(timestamp_ms) if timestamp_ms is not None else self._last_ts_ms + 1
|
||||||
|
if ts <= self._last_ts_ms:
|
||||||
|
ts = self._last_ts_ms + 1
|
||||||
|
self._last_ts_ms = ts
|
||||||
|
|
||||||
|
result = self._landmarker.detect_for_video(mp_image, ts)
|
||||||
|
if not result.pose_landmarks:
|
||||||
|
return None
|
||||||
|
|
||||||
|
norm = result.pose_landmarks[0]
|
||||||
|
world = result.pose_world_landmarks[0] if result.pose_world_landmarks else norm
|
||||||
|
|
||||||
|
landmarks = [(lm.x, lm.y, lm.z, getattr(lm, "visibility", 0.0) or 0.0) for lm in norm]
|
||||||
|
world_landmarks = [(lm.x, lm.y, lm.z) for lm in world]
|
||||||
|
visibility = [getattr(lm, "visibility", 0.0) or 0.0 for lm in norm]
|
||||||
|
|
||||||
|
mask = None
|
||||||
|
if result.segmentation_masks:
|
||||||
|
mask = np.ascontiguousarray(result.segmentation_masks[0].numpy_view(), dtype=np.float32)
|
||||||
|
if mask.ndim == 3 and mask.shape[-1] == 1:
|
||||||
|
mask = mask[..., 0]
|
||||||
|
|
||||||
|
return PoseResult(
|
||||||
|
landmarks=landmarks,
|
||||||
|
world_landmarks=world_landmarks,
|
||||||
|
visibility=visibility,
|
||||||
|
image_width=w,
|
||||||
|
image_height=h,
|
||||||
|
mask=mask,
|
||||||
|
)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
self._landmarker.close()
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
"""Shared-memory frame publisher for the frozen IPC contract (plan todo 5).
|
||||||
|
|
||||||
|
`FrameContractPublisher` owns one shared-memory region laid out as:
|
||||||
|
|
||||||
|
[ FrameContract header + 3 FrameSlots ][ slot0 depth ][ slot0 color ]
|
||||||
|
[ slot1 depth ][ slot1 color ]
|
||||||
|
[ slot2 depth ][ slot2 color ]
|
||||||
|
|
||||||
|
and publishes one `PoseResult` per call into the triple buffer using the
|
||||||
|
seqlock protocol documented in `core/contract/contract.h`:
|
||||||
|
|
||||||
|
* write the slot *one ahead* of `published_sequence`,
|
||||||
|
* bump that slot's `sequence` to odd before writing `data`, back to even
|
||||||
|
after (so a reader that sees an odd or changed sequence retries),
|
||||||
|
* then publish by bumping `FrameContract.published_sequence`.
|
||||||
|
|
||||||
|
This is the *producer* side the C++ core reads with `read_latest_frame`. A
|
||||||
|
matching in-process `read_latest_frame` lives here too so the data path can be
|
||||||
|
round-tripped in a pytest without the C++ build.
|
||||||
|
|
||||||
|
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.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ctypes
|
||||||
|
import gc
|
||||||
|
import time
|
||||||
|
from multiprocessing import shared_memory
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from .contract import (
|
||||||
|
CONTRACT_VERSION,
|
||||||
|
FRAME_SLOT_COUNT,
|
||||||
|
JOINT_COUNT,
|
||||||
|
FrameContract,
|
||||||
|
FrameData,
|
||||||
|
JointTrackingState,
|
||||||
|
)
|
||||||
|
from .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.
|
||||||
|
PROVISIONAL_BODY_DEPTH_MM = 2000
|
||||||
|
MASK_BODY_THRESHOLD = 0.5
|
||||||
|
PLAYER_INDEX = 1
|
||||||
|
|
||||||
|
|
||||||
|
def pack_depth_word(depth_mm: int, player: int) -> int:
|
||||||
|
"""Kinect v1 packed depth word: (mm & 0x1FFF) << 3 | (player & 0x7)."""
|
||||||
|
return ((depth_mm & 0x1FFF) << 3) | (player & 0x7)
|
||||||
|
|
||||||
|
|
||||||
|
def 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]
|
||||||
|
if ih == out_h and iw == out_w:
|
||||||
|
return arr
|
||||||
|
ys = (np.arange(out_h) * ih // out_h).clip(0, ih - 1)
|
||||||
|
xs = (np.arange(out_w) * iw // out_w).clip(0, iw - 1)
|
||||||
|
return arr[ys][:, xs]
|
||||||
|
|
||||||
|
|
||||||
|
class FrameContractPublisher:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
depth_size: tuple[int, int] = (640, 480),
|
||||||
|
color_size: tuple[int, int] = (640, 480),
|
||||||
|
name: Optional[str] = None,
|
||||||
|
create: bool = True,
|
||||||
|
) -> None:
|
||||||
|
self.depth_w, self.depth_h = depth_size
|
||||||
|
self.color_w, self.color_h = color_size
|
||||||
|
self.depth_bytes = self.depth_w * self.depth_h * 2 # 16-bit packed depth word
|
||||||
|
self.color_bytes = self.color_w * self.color_h * 4 # BGRA
|
||||||
|
self._contract_size = ctypes.sizeof(FrameContract)
|
||||||
|
self._slot_pixel_bytes = self.depth_bytes + self.color_bytes
|
||||||
|
self.region_size = self._contract_size + FRAME_SLOT_COUNT * self._slot_pixel_bytes
|
||||||
|
|
||||||
|
self.shm = shared_memory.SharedMemory(create=create, size=self.region_size, name=name)
|
||||||
|
self.name = self.shm.name
|
||||||
|
self._buf = self.shm.buf
|
||||||
|
self._create = create
|
||||||
|
self.contract = FrameContract.from_buffer(self._buf)
|
||||||
|
if create:
|
||||||
|
self.contract.contract_version = CONTRACT_VERSION
|
||||||
|
self.contract.reserved = 0
|
||||||
|
self.contract.published_sequence = 0
|
||||||
|
for i in range(FRAME_SLOT_COUNT):
|
||||||
|
self.contract.slots[i].sequence = 0
|
||||||
|
|
||||||
|
self._frame_number = 0
|
||||||
|
self._t0_ns = time.monotonic_ns()
|
||||||
|
|
||||||
|
def _depth_offset(self, slot_idx: int) -> int:
|
||||||
|
return self._contract_size + slot_idx * self._slot_pixel_bytes
|
||||||
|
|
||||||
|
def _color_offset(self, slot_idx: int) -> int:
|
||||||
|
return self._depth_offset(slot_idx) + self.depth_bytes
|
||||||
|
|
||||||
|
def publish(self, pose: Optional[PoseResult], color_bgr: Optional[np.ndarray] = None) -> int:
|
||||||
|
"""Publish one frame; returns the new published_sequence. Never blocks."""
|
||||||
|
next_seq = self.contract.published_sequence + 1
|
||||||
|
slot_idx = next_seq % FRAME_SLOT_COUNT
|
||||||
|
slot = self.contract.slots[slot_idx]
|
||||||
|
|
||||||
|
slot.sequence += 1 # odd => writing in progress
|
||||||
|
data = slot.data
|
||||||
|
self._frame_number += 1
|
||||||
|
data.frame_number = self._frame_number
|
||||||
|
data.timestamp_micros = (time.monotonic_ns() - self._t0_ns) // 1000
|
||||||
|
|
||||||
|
self._write_skeleton(data, pose)
|
||||||
|
self._write_descriptors(data, slot_idx)
|
||||||
|
self._write_depth(slot_idx, pose)
|
||||||
|
self._write_color(slot_idx, color_bgr)
|
||||||
|
|
||||||
|
slot.sequence += 1 # even => write complete
|
||||||
|
self.contract.published_sequence = next_seq
|
||||||
|
return next_seq
|
||||||
|
|
||||||
|
def _write_skeleton(self, data: FrameData, pose: Optional[PoseResult]) -> None:
|
||||||
|
skel = data.skeleton
|
||||||
|
skel.quality_flags = 0
|
||||||
|
if pose is None:
|
||||||
|
skel.skeleton_tracking_id = 0
|
||||||
|
for j in range(JOINT_COUNT):
|
||||||
|
joint = skel.joints[j]
|
||||||
|
joint.position.x = joint.position.y = joint.position.z = 0.0
|
||||||
|
joint.position.w = 1.0
|
||||||
|
joint.tracking_state = JointTrackingState.NOT_TRACKED
|
||||||
|
return
|
||||||
|
|
||||||
|
any_tracked = any(v >= VIS_INFERRED for v in pose.visibility[:JOINT_COUNT])
|
||||||
|
skel.skeleton_tracking_id = PLAYER_INDEX if any_tracked else 0
|
||||||
|
for j in range(JOINT_COUNT):
|
||||||
|
wx, wy, wz = pose.world_landmarks[j]
|
||||||
|
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])
|
||||||
|
|
||||||
|
def _write_descriptors(self, data: FrameData, slot_idx: int) -> None:
|
||||||
|
data.depth.width = self.depth_w
|
||||||
|
data.depth.height = self.depth_h
|
||||||
|
data.depth.pitch = self.depth_w * 2
|
||||||
|
data.depth.byte_offset = self._depth_offset(slot_idx)
|
||||||
|
data.color.width = self.color_w
|
||||||
|
data.color.height = self.color_h
|
||||||
|
data.color.pitch = self.color_w * 4
|
||||||
|
data.color.byte_offset = self._color_offset(slot_idx)
|
||||||
|
|
||||||
|
def _write_depth(self, slot_idx: int, pose: Optional[PoseResult]) -> None:
|
||||||
|
off = self._depth_offset(slot_idx)
|
||||||
|
depth = np.zeros((self.depth_h, self.depth_w), dtype=np.uint16)
|
||||||
|
if pose is not None and pose.mask is not None:
|
||||||
|
mask = _resize_nearest(pose.mask, self.depth_h, self.depth_w)
|
||||||
|
body = mask >= MASK_BODY_THRESHOLD
|
||||||
|
depth[body] = pack_depth_word(PROVISIONAL_BODY_DEPTH_MM, PLAYER_INDEX)
|
||||||
|
self._buf[off:off + self.depth_bytes] = np.ascontiguousarray(depth).tobytes()
|
||||||
|
|
||||||
|
def _write_color(self, slot_idx: int, color_bgr: Optional[np.ndarray]) -> None:
|
||||||
|
off = self._color_offset(slot_idx)
|
||||||
|
if color_bgr is None:
|
||||||
|
self._buf[off:off + self.color_bytes] = bytes(self.color_bytes)
|
||||||
|
return
|
||||||
|
resized = _resize_nearest(color_bgr, self.color_h, self.color_w)
|
||||||
|
alpha = np.full((self.color_h, self.color_w, 1), 255, dtype=np.uint8)
|
||||||
|
bgra = np.concatenate([resized.astype(np.uint8), alpha], axis=2)
|
||||||
|
self._buf[off:off + self.color_bytes] = np.ascontiguousarray(bgra).tobytes()
|
||||||
|
|
||||||
|
def read_latest_frame(self) -> Optional[FrameData]:
|
||||||
|
"""Seqlock snapshot of the newest published frame; None if nothing published."""
|
||||||
|
for _ in range(16):
|
||||||
|
pub = self.contract.published_sequence
|
||||||
|
if pub == 0:
|
||||||
|
return None
|
||||||
|
slot = self.contract.slots[pub % FRAME_SLOT_COUNT]
|
||||||
|
s1 = slot.sequence
|
||||||
|
if s1 & 1:
|
||||||
|
continue
|
||||||
|
snapshot = FrameData.from_buffer_copy(slot.data)
|
||||||
|
if slot.sequence == s1 and self.contract.published_sequence == pub:
|
||||||
|
return snapshot
|
||||||
|
raise RuntimeError("read_latest_frame could not get a stable snapshot")
|
||||||
|
|
||||||
|
def read_depth(self, slot_idx: int) -> np.ndarray:
|
||||||
|
off = self._depth_offset(slot_idx)
|
||||||
|
raw = bytes(self._buf[off:off + self.depth_bytes])
|
||||||
|
return np.frombuffer(raw, dtype=np.uint16).reshape(self.depth_h, self.depth_w).copy()
|
||||||
|
|
||||||
|
def read_color(self, slot_idx: int) -> np.ndarray:
|
||||||
|
off = self._color_offset(slot_idx)
|
||||||
|
raw = bytes(self._buf[off:off + self.color_bytes])
|
||||||
|
return np.frombuffer(raw, dtype=np.uint8).reshape(self.color_h, self.color_w, 4).copy()
|
||||||
|
|
||||||
|
def latest_slot_index(self) -> int:
|
||||||
|
return self.contract.published_sequence % FRAME_SLOT_COUNT
|
||||||
|
|
||||||
|
def close(self, unlink: Optional[bool] = None) -> None:
|
||||||
|
if self.contract is not None:
|
||||||
|
self.contract = None
|
||||||
|
self._buf = None
|
||||||
|
gc.collect()
|
||||||
|
self.shm.close()
|
||||||
|
if unlink if unlink is not None else self._create:
|
||||||
|
try:
|
||||||
|
self.shm.unlink()
|
||||||
|
except FileNotFoundError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __enter__(self) -> "FrameContractPublisher":
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *exc: object) -> None:
|
||||||
|
self.close()
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
"""Webcam -> MediaPipe pose -> IPC publish loop (plan todo 5).
|
||||||
|
|
||||||
|
Architecture (satisfies the plan's MUST-NOTs):
|
||||||
|
|
||||||
|
* Capture + inference run on a background thread and cache the latest
|
||||||
|
`(frame, PoseResult)`. The publish loop NEVER blocks on inference - it
|
||||||
|
publishes whatever pose is latest, re-publishing the previous one when
|
||||||
|
inference has not produced a new result yet.
|
||||||
|
* The publish loop paces to a monotonic frame clock (deadline = start +
|
||||||
|
n*period). There are no fixed per-frame sleeps; it waits exactly until the
|
||||||
|
next deadline, so cadence is held regardless of inference jitter.
|
||||||
|
|
||||||
|
The real pipeline (`MediaPipePoseProvider` + `CvFrameSource`) and the test
|
||||||
|
pipeline (`FakePoseProvider` + `FakeFrameSource`) share this loop through the
|
||||||
|
`PoseProvider` seam and a duck-typed frame source (`read()` -> BGR frame | None).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import Optional, Protocol
|
||||||
|
|
||||||
|
from .control import ControlPlaneServer
|
||||||
|
from .pose import PoseProvider, PoseResult
|
||||||
|
from .publisher import FrameContractPublisher
|
||||||
|
|
||||||
|
|
||||||
|
class FrameSource(Protocol):
|
||||||
|
def read(self): ...
|
||||||
|
def release(self) -> None: ...
|
||||||
|
|
||||||
|
|
||||||
|
class CvFrameSource:
|
||||||
|
"""OpenCV capture from a webcam index or a video file path."""
|
||||||
|
|
||||||
|
def __init__(self, source) -> None:
|
||||||
|
import cv2
|
||||||
|
|
||||||
|
self._cap = cv2.VideoCapture(int(source) if str(source).isdigit() else source)
|
||||||
|
if not self._cap.isOpened():
|
||||||
|
raise RuntimeError(f"could not open capture source: {source!r}")
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
ok, frame = self._cap.read()
|
||||||
|
return frame if ok else None
|
||||||
|
|
||||||
|
def release(self) -> None:
|
||||||
|
self._cap.release()
|
||||||
|
|
||||||
|
|
||||||
|
class Tracker:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
source: FrameSource,
|
||||||
|
provider: PoseProvider,
|
||||||
|
publisher: FrameContractPublisher,
|
||||||
|
control: Optional[ControlPlaneServer] = None,
|
||||||
|
target_fps: float = 30.0,
|
||||||
|
) -> None:
|
||||||
|
self.source = source
|
||||||
|
self.provider = provider
|
||||||
|
self.publisher = publisher
|
||||||
|
self.control = control
|
||||||
|
self.target_fps = target_fps
|
||||||
|
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._latest_pose: Optional[PoseResult] = None
|
||||||
|
self._latest_frame = None
|
||||||
|
self._stop = threading.Event()
|
||||||
|
self._source_done = threading.Event()
|
||||||
|
self._worker: Optional[threading.Thread] = None
|
||||||
|
|
||||||
|
def _inference_worker(self) -> None:
|
||||||
|
t0 = time.monotonic()
|
||||||
|
while not self._stop.is_set():
|
||||||
|
frame = self.source.read()
|
||||||
|
if frame is None:
|
||||||
|
self._source_done.set()
|
||||||
|
return
|
||||||
|
ts_ms = int((time.monotonic() - t0) * 1000)
|
||||||
|
pose = self.provider.process(frame, timestamp_ms=ts_ms)
|
||||||
|
with self._lock:
|
||||||
|
self._latest_frame = frame
|
||||||
|
self._latest_pose = pose
|
||||||
|
|
||||||
|
def run(self, max_frames: Optional[int] = None, max_seconds: Optional[float] = None) -> int:
|
||||||
|
self._worker = threading.Thread(target=self._inference_worker, name="inference", daemon=True)
|
||||||
|
self._worker.start()
|
||||||
|
|
||||||
|
period = 1.0 / self.target_fps
|
||||||
|
start = time.monotonic()
|
||||||
|
published = 0
|
||||||
|
while not self._stop.is_set():
|
||||||
|
deadline = start + published * period
|
||||||
|
now = time.monotonic()
|
||||||
|
if now < deadline:
|
||||||
|
self._stop.wait(deadline - now)
|
||||||
|
if self._stop.is_set():
|
||||||
|
break
|
||||||
|
with self._lock:
|
||||||
|
pose = self._latest_pose
|
||||||
|
frame = self._latest_frame
|
||||||
|
seq = self.publisher.publish(pose, frame)
|
||||||
|
if self.control is not None:
|
||||||
|
self.control.send_heartbeat(seq)
|
||||||
|
published += 1
|
||||||
|
|
||||||
|
if max_frames is not None and published >= max_frames:
|
||||||
|
break
|
||||||
|
if max_seconds is not None and (time.monotonic() - start) >= max_seconds:
|
||||||
|
break
|
||||||
|
if self._source_done.is_set():
|
||||||
|
break
|
||||||
|
|
||||||
|
self.stop()
|
||||||
|
return published
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
self._stop.set()
|
||||||
|
if self._worker is not None:
|
||||||
|
self._worker.join(timeout=1.0)
|
||||||
|
|
||||||
|
|
||||||
|
def measure_fps(provider: PoseProvider, frame, iterations: int = 60) -> float:
|
||||||
|
"""Time `iterations` inferences on one frame; returns achieved fps."""
|
||||||
|
for _ in range(3):
|
||||||
|
provider.process(frame, timestamp_ms=None)
|
||||||
|
start = time.monotonic()
|
||||||
|
for _ in range(iterations):
|
||||||
|
provider.process(frame, timestamp_ms=None)
|
||||||
|
elapsed = time.monotonic() - start
|
||||||
|
return iterations / elapsed if elapsed > 0 else float("inf")
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_size(text: str) -> tuple[int, int]:
|
||||||
|
w, h = text.lower().split("x")
|
||||||
|
return int(w), int(h)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: Optional[list[str]] = None) -> int:
|
||||||
|
parser = argparse.ArgumentParser(description="Webcam -> MediaPipe pose -> Kinect IPC contract publisher")
|
||||||
|
parser.add_argument("--source", default="0", help="webcam index (e.g. 0) or video file path")
|
||||||
|
parser.add_argument("--model", default="full", help="pose model tier (lite/full/heavy) or .task path")
|
||||||
|
parser.add_argument("--models-dir", default=None, help="directory holding the .task model bundles")
|
||||||
|
parser.add_argument("--target-fps", type=float, default=30.0)
|
||||||
|
parser.add_argument("--depth-size", type=_parse_size, default=(640, 480))
|
||||||
|
parser.add_argument("--color-size", type=_parse_size, default=(640, 480))
|
||||||
|
parser.add_argument("--shm-name", default="virtual_kinect_frames")
|
||||||
|
parser.add_argument("--control-socket", default=None, help="unix socket path for the control plane")
|
||||||
|
parser.add_argument("--max-frames", type=int, default=None)
|
||||||
|
parser.add_argument("--max-seconds", type=float, default=None)
|
||||||
|
parser.add_argument("--measure-fps", action="store_true", help="benchmark lite/full/heavy and exit")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
from .pose import MediaPipePoseProvider
|
||||||
|
|
||||||
|
if args.measure_fps:
|
||||||
|
source = CvFrameSource(args.source)
|
||||||
|
frame = source.read()
|
||||||
|
source.release()
|
||||||
|
if frame is None:
|
||||||
|
print("measure-fps: could not read a frame from source")
|
||||||
|
return 1
|
||||||
|
for tier in ("lite", "full", "heavy"):
|
||||||
|
provider = MediaPipePoseProvider(model=tier, models_dir=args.models_dir)
|
||||||
|
fps = measure_fps(provider, frame)
|
||||||
|
provider.close()
|
||||||
|
print(f"{tier}: {fps:.1f} fps")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
source = CvFrameSource(args.source)
|
||||||
|
provider = MediaPipePoseProvider(model=args.model, models_dir=args.models_dir)
|
||||||
|
publisher = FrameContractPublisher(
|
||||||
|
depth_size=args.depth_size, color_size=args.color_size, name=args.shm_name
|
||||||
|
)
|
||||||
|
control = None
|
||||||
|
if args.control_socket:
|
||||||
|
control = ControlPlaneServer(args.control_socket)
|
||||||
|
control.start()
|
||||||
|
|
||||||
|
tracker = Tracker(source, provider, publisher, control=control, target_fps=args.target_fps)
|
||||||
|
try:
|
||||||
|
published = tracker.run(max_frames=args.max_frames, max_seconds=args.max_seconds)
|
||||||
|
print(f"published {published} frames to shm {publisher.name!r}")
|
||||||
|
finally:
|
||||||
|
tracker.stop()
|
||||||
|
source.release()
|
||||||
|
provider.close()
|
||||||
|
publisher.close()
|
||||||
|
if control is not None:
|
||||||
|
control.close()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Reference in new issue
Block a user