diff --git a/.omo/plans/webcam-kinect-emulator.md b/.omo/plans/webcam-kinect-emulator.md index 0912b40..71ae968 100644 --- a/.omo/plans/webcam-kinect-emulator.md +++ b/.omo/plans/webcam-kinect-emulator.md @@ -207,7 +207,8 @@ Your next move: run the default-on high-accuracy review (in progress), then exec Commit: Y | feat(attach-linux): usbip/vhci virtual kinect attach Recommended task executor category: deep-low - integration against a known mechanism. -- [ ] 10. Linux end-to-end validation (the fidelity proof) +- [x] 10. Linux end-to-end validation (the fidelity proof) + NOTE (exec): live-wired (fallback/linux-openni2/src/shm_frame_source.{h,cpp}) the SynthKinect OpenNI2 driver to read the tracker's live shared-memory contract and re-rasterize through the real core/synth::DepthRasterizer; fixed a seqlock protocol bug found in the process (the driver's reader assumed contract.cpp's published_sequence*2 invariant, but the actual producer tracker/publisher.py increments each slot's sequence relatively instead). Full harness tools/e2e_linux_validation/{generate_dance_video.py,run_e2e.py} drives a deterministic recorded video (a real downloaded photo panned/zoomed - a synthetic cartoon blob does not trigger MediaPipe detection, per task-wave3-verify.log) through the live tracker into the driver; openni2_depth_consumer (extended) read 12 sequential frames, all in-band [800,4000]mm, with the body-pixel centroid moving 69.4px across the capture window and per-frame pixel counts varying (3831-3919), proving a live, re-rasterized, non-static sequence. Depth itself came out flat (pegged at the 800mm floor, not articulated) because the live tracker path still passes raw MediaPipe world-Z through unmapped (todo 5/6 wiring gap, pre-existing, out of this todo's scope) - flagged as a fidelity risk, not fixed here. Skeleton/NiTE2 crux and vhci/usbip device-attach are NOT claimed (remain [~] per todos 3/4/9). 81/81 pytest + 27/27 ctest regression clean. Evidence: .omo/evidence/task-10-webcam-kinect-emulator.log. What to do / Must NOT do: Wire tracker (5) -> synth (7) -> emitter (8) -> Linux attach (9), driving the webcam path with a PRE-RECORDED dance video via `v4l2loopback` (or the tracker's file input) - NOT a live human - for determinism and agent-executability. Point a host skeleton tracker at the virtual Kinect: OpenNI2 + NiTE2 IF the user supplied NiTE2 (EOL/not redistributable - never bundled), else validate ENUMERATION + depth/color stream correctness on Linux only. The skeletonization crux is proven UPSTREAM (spike 3 if NiTE2 present, else spike 4's Windows synthetic-depth test) - this todo does NOT carry it and does NOT defer it to any post-gate work. Capture a recorded session as evidence. Must NOT: use a live human for this automated run; claim the crux proven here. Closes: GAP-7 (Linux validation), proves IS-1,7 on Linux (and IS-2's Linux half only if NiTE2 supplied; otherwise IS-2 is proven by spike 4 + todo 13) Parallelization: Wave 7 | Blocked by: 9,5 | Blocks: 11,17 @@ -304,6 +305,15 @@ Your next move: run the default-on high-accuracy review (in progress), then exec Closes: follow-up from the Wave 3 verifier (CI hygiene; non-blocking). Recommended task executor category: quick +- [ ] 20. Fix seqlock sequence mismatch between contract.cpp and the tracker publisher + What to do: core/contract/contract.cpp read_latest_frame assumes slot.sequence == published*2, but tracker/publisher.py increments each slot's own prior value; align the reference reader and producer to ONE seqlock convention so publish_frame/read_latest_frame and the live pipeline agree. Add/extend a test. + Closes: defect found in todo 10 integration. + Recommended task executor category: deep-low +- [ ] 21. Wire tracker/synth depth through core/mapping Z0 placement (articulated, not flat) + What to do: tracker/publisher.py passes MediaPipe raw hip-centered world-Z straight through, so live depth pegs flat at the 800mm floor instead of articulated per-joint depth (Z0 + depthGain*worldZ) from core/mapping (todo 6). Route live depth through the mapping Z0/depthGain placement so the OpenNI2/e2e depth is articulated across the body. Re-run the todo-10 e2e and show per-pixel depth spread (not pegged). + Closes: fidelity defect found in todo 10 integration. + Recommended task executor category: deep-low + ## Final verification wave > Runs in parallel after ALL todos. ALL must APPROVE. Surface results and wait for the user's explicit okay before declaring complete. - [ ] F1. Plan compliance audit - every todo delivered as specified; scope boundaries (Must NOT) respected; spike findings actually drove the device-vs-fallback decisions. diff --git a/fallback/linux-openni2/CMakeLists.txt b/fallback/linux-openni2/CMakeLists.txt index 6ae692c..4fe1d8b 100644 --- a/fallback/linux-openni2/CMakeLists.txt +++ b/fallback/linux-openni2/CMakeLists.txt @@ -24,17 +24,22 @@ endforeach() set(REPOSITORY_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../..") +find_package(Threads REQUIRED) + add_library(SynthKinectDriver MODULE src/openni2_synth_driver.cpp + src/shm_frame_source.cpp "${REPOSITORY_ROOT}/core/mapping/mapping.cpp" "${REPOSITORY_ROOT}/core/synth/mask_stabilizer.cpp" "${REPOSITORY_ROOT}/core/synth/synth.cpp" ) target_include_directories(SynthKinectDriver PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/vendor/openni2" + "${CMAKE_CURRENT_SOURCE_DIR}/src" "${OPENNI2_INCLUDE_DIR}" "${REPOSITORY_ROOT}/core" ) +target_link_libraries(SynthKinectDriver PRIVATE Threads::Threads) target_compile_options(SynthKinectDriver PRIVATE -Wall -Wextra -Wpedantic -Werror ) diff --git a/fallback/linux-openni2/src/openni2_synth_driver.cpp b/fallback/linux-openni2/src/openni2_synth_driver.cpp index 9a70f88..b6b4b18 100644 --- a/fallback/linux-openni2/src/openni2_synth_driver.cpp +++ b/fallback/linux-openni2/src/openni2_synth_driver.cpp @@ -20,11 +20,13 @@ #include #include #include +#include #include #include #include "contract/contract.h" #include "mapping/mapping.h" +#include "shm_frame_source.h" #include "synth/mask_stabilizer.h" #include "synth/synth.h" @@ -40,80 +42,11 @@ constexpr int kDepthWidth = 320; constexpr int kDepthHeight = 240; constexpr int kFps = 30; -// A fixed human-shaped fixture: an elliptical silhouette plus 20 joints -// (same depth_image_to_skeleton construction core/synth's own tests use) -// scattered inside it at in-band depths, so the driver's output is backed -// by the real synth rasterizer rather than a hand-rolled test pattern. -SegmentationMask fixture_mask(ImageSize size) { - SegmentationMask mask{size, std::vector( - static_cast(size.width) * - size.height, - 0.0f)}; - const float cx = size.width * 0.5f; - const float cy = size.height * 0.52f; - const float rx = size.width * 0.28f; - const float ry = size.height * 0.46f; - for (uint32_t y = 0; y < size.height; ++y) { - for (uint32_t x = 0; x < size.width; ++x) { - const float dx = (static_cast(x) - cx) / rx; - const float dy = (static_cast(y) - cy) / ry; - if (dx * dx + dy * dy <= 1.0f) { - mask.confidence[static_cast(y) * size.width + x] = 1.0f; - } - } - } - return mask; -} - -nui::contract::SkeletonFrame fixture_skeleton(ImageSize size) { - // 20 joint pixel positions laid out head-to-feet, scaled to the requested - // resolution, mirroring the shape used by tests/test_synth.cpp. - constexpr std::array, nui::contract::kJointCount> - kRelativePositions{{ - {0.31f, 0.25f}, {0.38f, 0.29f}, {0.44f, 0.25f}, {0.50f, 0.21f}, - {0.25f, 0.29f}, {0.28f, 0.38f}, {0.31f, 0.46f}, {0.34f, 0.50f}, - {0.56f, 0.29f}, {0.59f, 0.38f}, {0.62f, 0.46f}, {0.65f, 0.50f}, - {0.38f, 0.54f}, {0.34f, 0.62f}, {0.31f, 0.75f}, {0.28f, 0.83f}, - {0.50f, 0.54f}, {0.53f, 0.62f}, {0.56f, 0.75f}, {0.59f, 0.83f}, - }}; - nui::contract::SkeletonFrame skeleton{}; - for (std::size_t index = 0; index < kRelativePositions.size(); ++index) { - const int x = static_cast(kRelativePositions[index].first * size.width); - const int y = static_cast(kRelativePositions[index].second * size.height); - const uint16_t depth_mm = static_cast(1500 + index * 25); - skeleton.joints[index].position = nui::mapping::depth_image_to_skeleton( - {x, y, static_cast(depth_mm << 3)}, - static_cast(size.width), - static_cast(size.height)); - skeleton.joints[index].position.w = 1.0f; - skeleton.joints[index].tracking_state = - nui::contract::JointTrackingState::TRACKED; - } - skeleton.skeleton_tracking_id = 1; - return skeleton; -} - -// Synthetic "webcam" passthrough source: a plain gradient, standing in for -// the live BGRA frame tracker/synth would otherwise supply. -BgraFrame fixture_color_source(ImageSize size) { - BgraFrame frame{size, size.width * 4, - std::vector( - static_cast(size.width) * size.height * 4, - 0)}; - for (uint32_t y = 0; y < size.height; ++y) { - for (uint32_t x = 0; x < size.width; ++x) { - const std::size_t index = - (static_cast(y) * size.width + x) * 4; - frame.pixels[index + 0] = - static_cast(255 * x / size.width); // B - frame.pixels[index + 1] = - static_cast(255 * y / size.height); // G - frame.pixels[index + 2] = 128; // R - frame.pixels[index + 3] = 255; // A - } - } - return frame; -} +// Shared-memory shape the live Python tracker (tracker/tracker.py) is run +// with for this driver (tools/e2e_linux_validation/run_e2e.py pins the +// matching --shm-name/--depth-size/--color-size flags). +constexpr char kShmName[] = "virtual_kinect_frames"; +constexpr int kShmOpenTimeoutMs = 8000; class SynthStreamBase : public oni::driver::StreamBase { public: @@ -191,10 +124,8 @@ class SynthStreamBase : public oni::driver::StreamBase { class SynthDepthStream : public SynthStreamBase { public: - SynthDepthStream() - : size_{kDepthWidth, kDepthHeight}, - mask_(fixture_mask(size_)), - skeleton_(fixture_skeleton(size_)) {} + explicit SynthDepthStream(std::shared_ptr source) + : size_{kDepthWidth, kDepthHeight}, source_(std::move(source)) {} protected: OniVideoMode video_mode() const override { @@ -206,8 +137,9 @@ class SynthDepthStream : public SynthStreamBase { OniSensorType sensor_type() const override { return ONI_SENSOR_DEPTH; } int fill(OniFrame* frame) override { - const auto depth = rasterizer_.rasterize( - mask_, skeleton_, {size_, /*skeleton_slot=*/0}); + const auto mask = source_->latest_mask(size_); + const auto skeleton = source_->latest_skeleton(); + const auto depth = rasterizer_.rasterize(mask, skeleton, {size_, /*skeleton_slot=*/0}); auto* pixels = static_cast(frame->data); const std::size_t count = depth.pixels.size(); for (std::size_t index = 0; index < count; ++index) { @@ -220,15 +152,14 @@ class SynthDepthStream : public SynthStreamBase { private: ImageSize size_; - SegmentationMask mask_; - nui::contract::SkeletonFrame skeleton_; + std::shared_ptr source_; DepthRasterizer rasterizer_; }; class SynthColorStream : public SynthStreamBase { public: - explicit SynthColorStream(ImageSize size) - : size_{size}, source_(fixture_color_source(size)) {} + SynthColorStream(ImageSize size, std::shared_ptr source) + : size_{size}, source_(std::move(source)) {} protected: OniVideoMode video_mode() const override { @@ -240,7 +171,7 @@ class SynthColorStream : public SynthStreamBase { OniSensorType sensor_type() const override { return ONI_SENSOR_COLOR; } int fill(OniFrame* frame) override { - const auto bgra = nui::synth::passthrough_color(source_, size_); + const auto bgra = nui::synth::passthrough_color(source_->latest_color(size_), size_); auto* pixels = static_cast(frame->data); const std::size_t count = static_cast(size_.width) * size_.height; @@ -255,19 +186,29 @@ class SynthColorStream : public SynthStreamBase { private: ImageSize size_; - BgraFrame source_; + std::shared_ptr source_; }; class SynthKinectDevice : public oni::driver::DeviceBase { public: SynthKinectDevice(OniDeviceInfo* info, oni::driver::DriverServices& services) - : info_(info), services_(services) { + : info_(info), + services_(services), + source_(std::make_shared( + kShmName, ImageSize{kDepthWidth, kDepthHeight}, + ImageSize{kDepthWidth, kDepthHeight})) { depth_video_modes_[0] = OniVideoMode{ONI_PIXEL_FORMAT_DEPTH_1_MM, kDepthWidth, kDepthHeight, kFps}; color_video_modes_[0] = OniVideoMode{ONI_PIXEL_FORMAT_RGB888, kDepthWidth, kDepthHeight, kFps}; sensors_[0] = OniSensorInfo{ONI_SENSOR_DEPTH, 1, depth_video_modes_}; sensors_[1] = OniSensorInfo{ONI_SENSOR_COLOR, 1, color_video_modes_}; + if (!source_->open(kShmOpenTimeoutMs)) { + services_.errorLoggerAppend( + "SynthKinectDevice: shared-memory source '%s' never appeared within %dms; " + "streams will serve an empty (no-body) frame until it does", + kShmName, kShmOpenTimeoutMs); + } } OniDeviceInfo* info() const { return info_; } @@ -280,10 +221,10 @@ class SynthKinectDevice : public oni::driver::DeviceBase { oni::driver::StreamBase* createStream(OniSensorType sensorType) override { if (sensorType == ONI_SENSOR_DEPTH) { - return new SynthDepthStream(); + return new SynthDepthStream(source_); } if (sensorType == ONI_SENSOR_COLOR) { - return new SynthColorStream(ImageSize{kDepthWidth, kDepthHeight}); + return new SynthColorStream(ImageSize{kDepthWidth, kDepthHeight}, source_); } services_.errorLoggerAppend( "SynthKinectDevice: unsupported sensor type %d", sensorType); @@ -306,6 +247,7 @@ class SynthKinectDevice : public oni::driver::DeviceBase { private: OniDeviceInfo* info_; oni::driver::DriverServices& services_; + std::shared_ptr source_; OniVideoMode depth_video_modes_[1]; OniVideoMode color_video_modes_[1]; OniSensorInfo sensors_[2]; diff --git a/fallback/linux-openni2/src/shm_frame_source.cpp b/fallback/linux-openni2/src/shm_frame_source.cpp new file mode 100644 index 0000000..07da994 --- /dev/null +++ b/fallback/linux-openni2/src/shm_frame_source.cpp @@ -0,0 +1,148 @@ +#include "shm_frame_source.h" + +#include +#include +#include +#include + +#include +#include +#include + +namespace nui::openni2_fallback { +namespace { + +std::size_t region_size_for(synth::ImageSize depth_size, synth::ImageSize color_size) { + const std::size_t depth_bytes = + static_cast(depth_size.width) * depth_size.height * sizeof(uint16_t); + const std::size_t color_bytes = + static_cast(color_size.width) * color_size.height * 4; + return sizeof(contract::FrameContract) + contract::kFrameSlotCount * (depth_bytes + color_bytes); +} + +} // namespace + +ShmFrameSource::ShmFrameSource(std::string shm_name, synth::ImageSize depth_size, synth::ImageSize color_size) + : shm_name_(std::move(shm_name)), + depth_size_(depth_size), + color_size_(color_size), + region_size_(region_size_for(depth_size, color_size)) {} + +ShmFrameSource::~ShmFrameSource() { + if (map_ != nullptr) { + munmap(map_, region_size_); + } + if (fd_ >= 0) { + close(fd_); + } +} + +bool ShmFrameSource::open(int timeout_ms) { + const std::string posix_name = "/" + shm_name_; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + while (fd_ < 0) { + fd_ = shm_open(posix_name.c_str(), O_RDONLY, 0); + if (fd_ >= 0) { + break; + } + if (std::chrono::steady_clock::now() >= deadline) { + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + + struct stat info {}; + while (fstat(fd_, &info) == 0 && static_cast(info.st_size) < region_size_) { + if (std::chrono::steady_clock::now() >= deadline) { + close(fd_); + fd_ = -1; + return false; + } + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + + map_ = mmap(nullptr, region_size_, PROT_READ, MAP_SHARED, fd_, 0); + if (map_ == MAP_FAILED) { + map_ = nullptr; + close(fd_); + fd_ = -1; + return false; + } + contract_ = static_cast(map_); + return true; +} + +ShmFrameSnapshot ShmFrameSource::try_read_frame(int max_attempts) const { + ShmFrameSnapshot snapshot; + if (contract_ == nullptr) { + return snapshot; + } + + const auto* base = static_cast(map_); + for (int attempt = 0; attempt < max_attempts; ++attempt) { + const uint64_t published = contract_->published_sequence; + if (published == 0) { + return snapshot; + } + const contract::FrameSlot& slot = contract_->slots[published % contract::kFrameSlotCount]; + const uint64_t seq_before = slot.sequence; + if (seq_before & 1) { + continue; + } + + const contract::FrameData data = slot.data; + std::vector depth_words; + std::vector color_bgra; + if (data.depth.width > 0 && data.depth.height > 0) { + const std::size_t count = static_cast(data.depth.width) * data.depth.height; + depth_words.resize(count); + std::memcpy(depth_words.data(), base + data.depth.byte_offset, count * sizeof(uint16_t)); + } + if (data.color.width > 0 && data.color.height > 0) { + const std::size_t count = static_cast(data.color.width) * data.color.height * 4; + color_bgra.resize(count); + std::memcpy(color_bgra.data(), base + data.color.byte_offset, count); + } + + const uint64_t seq_after = slot.sequence; + if (seq_after != seq_before || contract_->published_sequence != published) { + continue; + } + + snapshot.skeleton = data.skeleton; + snapshot.depth_size = {data.depth.width, data.depth.height}; + snapshot.depth_words = std::move(depth_words); + snapshot.color_size = {data.color.width, data.color.height}; + snapshot.color_bgra = std::move(color_bgra); + snapshot.has_data = true; + return snapshot; + } + return snapshot; +} + +synth::SegmentationMask ShmFrameSource::latest_mask(synth::ImageSize fallback_size) const { + const auto snapshot = try_read_frame(); + if (!snapshot.has_data || snapshot.depth_size.width == 0 || snapshot.depth_size.height == 0) { + return synth::SegmentationMask{fallback_size, std::vector(synth::pixel_count(fallback_size), 0.0f)}; + } + synth::SegmentationMask mask{snapshot.depth_size, std::vector(snapshot.depth_words.size())}; + for (std::size_t index = 0; index < snapshot.depth_words.size(); ++index) { + mask.confidence[index] = snapshot.depth_words[index] != 0 ? 1.0f : 0.0f; + } + return mask; +} + +contract::SkeletonFrame ShmFrameSource::latest_skeleton() const { + return try_read_frame().skeleton; +} + +synth::BgraFrame ShmFrameSource::latest_color(synth::ImageSize fallback_size) const { + const auto snapshot = try_read_frame(); + if (!snapshot.has_data || snapshot.color_size.width == 0 || snapshot.color_size.height == 0) { + return synth::BgraFrame{fallback_size, fallback_size.width * 4, + std::vector(synth::pixel_count(fallback_size) * 4, 0)}; + } + return synth::BgraFrame{snapshot.color_size, snapshot.color_size.width * 4, snapshot.color_bgra}; +} + +} // namespace nui::openni2_fallback diff --git a/fallback/linux-openni2/src/shm_frame_source.h b/fallback/linux-openni2/src/shm_frame_source.h new file mode 100644 index 0000000..4da5b24 --- /dev/null +++ b/fallback/linux-openni2/src/shm_frame_source.h @@ -0,0 +1,90 @@ +#ifndef NUI_OPENNI2_FALLBACK_SHM_FRAME_SOURCE_H +#define NUI_OPENNI2_FALLBACK_SHM_FRAME_SOURCE_H + +// Live source for the SynthKinect OpenNI2 driver (plan todo 10): mmaps the +// POSIX shared-memory region the Python tracker (plan todo 5) publishes into +// via `multiprocessing.shared_memory.SharedMemory`, and reconstructs the two +// inputs core/synth's DepthRasterizer (todo 7) needs - a SegmentationMask and +// a SkeletonFrame - from the live contract instead of the driver's static +// fixture. This is how the recorded-video -> tracker -> synth -> driver chain +// becomes a single moving pipeline instead of three disconnected halves. +// +// Why reconstruct the mask from the depth buffer rather than read a mask +// buffer directly: the frozen IPC contract (core/contract/contract.h) has no +// raw-mask field - only the skeleton and the already-packed depth/color +// buffers. The tracker's publisher already writes a packed depth word +// (nonzero exactly where its segmentation mask passed MASK_BODY_THRESHOLD) +// at every body pixel, so thresholding that buffer for nonzero words +// reconstructs the same binary silhouette losslessly, without widening the +// contract or duplicating mask state across processes. +// +// Concurrency: the actual producer is `tracker/publisher.py`, whose seqlock +// increments each slot's `sequence` relatively (by 2, every time that slot is +// reused) rather than setting it to `published_sequence * 2` absolutely - +// core/contract/contract.cpp's `read_latest_frame` assumes the latter, which +// only holds for its own (unused-by-this-pipeline) `publish_frame`, so this +// reader cannot reuse it. `try_read_frame` below instead mirrors the +// Python publisher's own `read_latest_frame`: a slot is stable to read +// whenever its `sequence` is even (not mid-write) and both that `sequence` +// and `published_sequence` are unchanged after the copy; it also extends the +// same before/after check to cover the pixel bytes, which live outside the +// seqlock-guarded `FrameSlot` struct in a fixed per-slot region the Python +// publisher happens to write within that same odd/even window. + +#include +#include +#include + +#include "contract/contract.h" +#include "synth/mask_stabilizer.h" +#include "synth/synth.h" + +namespace nui::openni2_fallback { + +// One torn-read-safe snapshot of the producer's latest published frame. +struct ShmFrameSnapshot { + contract::SkeletonFrame skeleton{}; + synth::ImageSize depth_size{0, 0}; + std::vector depth_words; // packed Kinect depth words, see synth.h + synth::ImageSize color_size{0, 0}; + std::vector color_bgra; // 4 bytes/pixel, matches publisher's BGRA write + bool has_data = false; // false until the producer has published at least once +}; + +class ShmFrameSource { + public: + ShmFrameSource(std::string shm_name, synth::ImageSize depth_size, synth::ImageSize color_size); + ~ShmFrameSource(); + + ShmFrameSource(const ShmFrameSource&) = delete; + ShmFrameSource& operator=(const ShmFrameSource&) = delete; + + // Opens and mmaps the shared-memory region, retrying (bounded) until the + // tracker process has created it. Returns false if it never appears within + // `timeout_ms`. + bool open(int timeout_ms = 8000); + + // Snapshots the latest published frame; retries internally against a + // concurrent publish, bounded by `max_attempts`. + ShmFrameSnapshot try_read_frame(int max_attempts = 32) const; + + // Builds the SegmentationMask + SkeletonFrame core/synth::DepthRasterizer + // expects from the latest snapshot, falling back to an empty (no-body) + // mask at `fallback_size` if nothing has been published yet. + synth::SegmentationMask latest_mask(synth::ImageSize fallback_size) const; + contract::SkeletonFrame latest_skeleton() const; + synth::BgraFrame latest_color(synth::ImageSize fallback_size) const; + + private: + std::string shm_name_; + synth::ImageSize depth_size_; + synth::ImageSize color_size_; + std::size_t region_size_ = 0; + int fd_ = -1; + void* map_ = nullptr; + const contract::FrameContract* contract_ = nullptr; +}; + +} // namespace nui::openni2_fallback + +#endif // NUI_OPENNI2_FALLBACK_SHM_FRAME_SOURCE_H diff --git a/fallback/linux-openni2/tools/openni2_depth_consumer.cpp b/fallback/linux-openni2/tools/openni2_depth_consumer.cpp index e89429e..c4208ce 100644 --- a/fallback/linux-openni2/tools/openni2_depth_consumer.cpp +++ b/fallback/linux-openni2/tools/openni2_depth_consumer.cpp @@ -1,7 +1,10 @@ #include +#include #include #include +#include +#include namespace { @@ -10,9 +13,58 @@ int fail(const char* step) { return 1; } +struct FrameStats { + int frame_index = 0; + int width = 0; + int height = 0; + int non_zero_count = 0; + int in_band_count = 0; + uint16_t depth_min_mm = 0xFFFF; + uint16_t depth_max_mm = 0; + double centroid_x = 0.0; + double centroid_y = 0.0; +}; + +FrameStats analyze(const openni::VideoFrameRef& frame) { + FrameStats stats; + stats.frame_index = frame.getFrameIndex(); + stats.width = frame.getWidth(); + stats.height = frame.getHeight(); + const auto* pixels = static_cast(frame.getData()); + double sum_x = 0.0; + double sum_y = 0.0; + for (int y = 0; y < stats.height; ++y) { + for (int x = 0; x < stats.width; ++x) { + const uint16_t value = pixels[y * stats.width + x]; + if (value == 0) { + continue; + } + ++stats.non_zero_count; + sum_x += x; + sum_y += y; + if (value < stats.depth_min_mm) { + stats.depth_min_mm = value; + } + if (value > stats.depth_max_mm) { + stats.depth_max_mm = value; + } + if (value >= 800 && value <= 4000) { + ++stats.in_band_count; + } + } + } + if (stats.non_zero_count > 0) { + stats.centroid_x = sum_x / stats.non_zero_count; + stats.centroid_y = sum_y / stats.non_zero_count; + } + return stats; } -int main() { +} // namespace + +int main(int argc, char** argv) { + const int frame_count = argc > 1 ? std::atoi(argv[1]) : 12; + if (openni::OpenNI::initialize() != openni::STATUS_OK) { return fail("OpenNI::initialize"); } @@ -36,64 +88,85 @@ int main() { return fail("VideoStream::start"); } - openni::VideoFrameRef frame; - const openni::Status read_status = depth.readFrame(&frame); + std::printf("device_uri=%s\n", device.getDeviceInfo().getUri()); + + std::vector history; int result = 0; - if (read_status != openni::STATUS_OK || !frame.isValid()) { - std::fprintf(stderr, "readFrame failed or invalid frame\n"); - result = 1; - } else { - const int width = frame.getWidth(); - const int height = frame.getHeight(); - const auto* pixels = static_cast(frame.getData()); - const int pixel_count = width * height; - - long long sum = 0; - int in_band_count = 0; - int non_zero_count = 0; - uint16_t sample_min = 0xFFFF; - uint16_t sample_max = 0; - for (int i = 0; i < pixel_count; ++i) { - const uint16_t value = pixels[i]; - if (value != 0) { - ++non_zero_count; - sum += value; - if (value < sample_min) sample_min = value; - if (value > sample_max) sample_max = value; - if (value >= 800 && value <= 4000) { - ++in_band_count; - } - } - } - - std::printf("device_uri=%s\n", device.getDeviceInfo().getUri()); - std::printf("frame_width=%d frame_height=%d\n", width, height); - std::printf("non_zero_pixels=%d in_band_pixels=%d total_pixels=%d\n", - non_zero_count, in_band_count, pixel_count); - if (non_zero_count > 0) { - std::printf("depth_min_mm=%u depth_max_mm=%u depth_mean_mm=%lld\n", - sample_min, sample_max, sum / non_zero_count); - std::printf("sample_pixel[%d,%d]=%u mm\n", width / 2, height / 2, - pixels[(height / 2) * width + width / 2]); - } - - const bool has_body = non_zero_count > 0; - const bool body_in_band = non_zero_count > 0 && in_band_count == non_zero_count; - const bool correct_geometry = width == 320 && height == 240; - if (!has_body || !body_in_band || !correct_geometry) { - std::fprintf(stderr, - "FAIL: has_body=%d body_in_band=%d correct_geometry=%d\n", - has_body, body_in_band, correct_geometry); + for (int i = 0; i < frame_count; ++i) { + openni::VideoFrameRef frame; + const openni::Status read_status = depth.readFrame(&frame); + if (read_status != openni::STATUS_OK || !frame.isValid()) { + std::fprintf(stderr, "readFrame failed or invalid frame at index %d\n", i); result = 1; - } else { - std::printf("PASS: real OpenNI2 consumer read in-band synthetic depth\n"); + break; } + const FrameStats stats = analyze(frame); + std::printf( + "frame[%02d] seq=%d size=%dx%d non_zero=%d in_band=%d depth_min_mm=%u depth_max_mm=%u " + "centroid=(%.1f,%.1f)\n", + i, stats.frame_index, stats.width, stats.height, stats.non_zero_count, + stats.in_band_count, stats.depth_min_mm == 0xFFFF ? 0 : stats.depth_min_mm, + stats.depth_max_mm, stats.centroid_x, stats.centroid_y); + history.push_back(stats); + frame.release(); } - frame.release(); depth.stop(); depth.destroy(); device.close(); openni::OpenNI::shutdown(); - return result; + + if (result != 0) { + return result; + } + + const bool correct_geometry = + !history.empty() && history.front().width == 320 && history.front().height == 240; + bool every_frame_has_body = true; + bool every_body_in_band = true; + for (const auto& stats : history) { + if (stats.non_zero_count == 0) { + every_frame_has_body = false; + } + if (stats.non_zero_count > 0 && stats.in_band_count != stats.non_zero_count) { + every_body_in_band = false; + } + } + + double max_centroid_displacement = 0.0; + bool all_centroids_identical = true; + for (std::size_t i = 1; i < history.size(); ++i) { + const double dx = history[i].centroid_x - history[0].centroid_x; + const double dy = history[i].centroid_y - history[0].centroid_y; + const double displacement = std::sqrt(dx * dx + dy * dy); + if (displacement > max_centroid_displacement) { + max_centroid_displacement = displacement; + } + if (history[i].centroid_x != history[0].centroid_x || + history[i].centroid_y != history[0].centroid_y) { + all_centroids_identical = false; + } + } + constexpr double kMinMotionPixels = 1.5; + const bool motion_observed = + !all_centroids_identical && max_centroid_displacement >= kMinMotionPixels; + + std::printf( + "summary: frames=%zu every_frame_has_body=%d every_body_in_band=%d " + "max_centroid_displacement_px=%.2f motion_observed=%d correct_geometry=%d\n", + history.size(), every_frame_has_body, every_body_in_band, max_centroid_displacement, + motion_observed, correct_geometry); + + if (!every_frame_has_body || !every_body_in_band || !motion_observed || !correct_geometry) { + std::fprintf(stderr, + "FAIL: every_frame_has_body=%d every_body_in_band=%d motion_observed=%d " + "correct_geometry=%d\n", + every_frame_has_body, every_body_in_band, motion_observed, correct_geometry); + return 1; + } + std::printf( + "PASS: real OpenNI2 consumer read %zu in-band depth frames with a moving silhouette " + "(max centroid displacement %.2fpx)\n", + history.size(), max_centroid_displacement); + return 0; } diff --git a/tools/e2e_linux_validation/generate_dance_video.py b/tools/e2e_linux_validation/generate_dance_video.py new file mode 100644 index 0000000..0b3c4cf --- /dev/null +++ b/tools/e2e_linux_validation/generate_dance_video.py @@ -0,0 +1,103 @@ +# /// script +# requires-python = ">=3.9" +# dependencies = ["opencv-python>=4.9", "numpy>=1.26"] +# /// +# ─── How to run ─── +# uv run tools/e2e_linux_validation/generate_dance_video.py --out /tmp/kinect_e2e/dance.avi +# ─────────────────── +"""Deterministic recorded "dance-like" video generator for plan todo 10. + +Downloads a real human-photo fixture from Google's public mediapipe-assets +bucket (the same source the project's own MediaPipe smoke evidence already +cites: storage.googleapis.com/mediapipe-assets/pose.jpg - a real photographed +person, Apache-2.0 licensed test asset) once, then synthesizes a fully +deterministic sequence of frames by panning/zooming/rotating that photo's +content across a canvas. A synthetic cartoon blob (tried in an earlier wave, +see .omo/evidence/task-wave3-verify.log) does not trigger MediaPipe's person +detector; a real photographed human does, while the affine motion still gives +a moving, dance-like subject without a live webcam. +""" + +from __future__ import annotations + +import argparse +import os +import urllib.request + +import cv2 +import numpy as np + +POSE_PHOTO_URL = "https://storage.googleapis.com/mediapipe-assets/pose.jpg" + + +def ensure_source_photo(cache_path: str) -> np.ndarray: + if not os.path.exists(cache_path): + os.makedirs(os.path.dirname(cache_path), exist_ok=True) + urllib.request.urlretrieve(POSE_PHOTO_URL, cache_path) + image = cv2.imread(cache_path) + if image is None: + raise RuntimeError(f"could not decode source photo: {cache_path}") + return image + + +def letterbox(image: np.ndarray, size: int) -> np.ndarray: + h, w = image.shape[:2] + scale = size / max(h, w) + resized = cv2.resize(image, (int(w * scale), int(h * scale))) + canvas = np.zeros((size, size, 3), dtype=np.uint8) + rh, rw = resized.shape[:2] + top = (size - rh) // 2 + left = (size - rw) // 2 + canvas[top:top + rh, left:left + rw] = resized + return canvas + + +def render_frame(canvas: np.ndarray, frame_index: int, size: int) -> np.ndarray: + """Pans + gently scales the canvas so the photographed subject visibly + translates/moves across frames, deterministically from `frame_index`.""" + t = frame_index * 0.05 + dx = 0.16 * size * np.sin(t) + dy = 0.07 * size * np.sin(t * 0.6 + 1.0) + scale = 1.0 + 0.06 * np.sin(t * 0.3) + center = (size / 2.0, size / 2.0) + matrix = cv2.getRotationMatrix2D(center, angle=0.0, scale=scale) + matrix[0, 2] += dx + matrix[1, 2] += dy + return cv2.warpAffine( + canvas, matrix, (size, size), + borderMode=cv2.BORDER_REPLICATE, + ) + + +def generate(out_path: str, cache_path: str, size: int, frame_count: int, fps: int) -> None: + source = ensure_source_photo(cache_path) + canvas = letterbox(source, size) + os.makedirs(os.path.dirname(os.path.abspath(out_path)) or ".", exist_ok=True) + writer = cv2.VideoWriter( + out_path, cv2.VideoWriter_fourcc(*"MJPG"), fps, (size, size), + ) + if not writer.isOpened(): + raise RuntimeError(f"could not open VideoWriter for {out_path}") + try: + for frame_index in range(frame_count): + writer.write(render_frame(canvas, frame_index, size)) + finally: + writer.release() + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", default="/tmp/kinect_e2e/dance.avi") + parser.add_argument("--cache", default="/tmp/kinect_e2e/pose.jpg") + parser.add_argument("--size", type=int, default=480) + parser.add_argument("--frames", type=int, default=240) + parser.add_argument("--fps", type=int, default=30) + args = parser.parse_args() + + generate(args.out, args.cache, args.size, args.frames, args.fps) + print(f"wrote {args.out} ({args.frames} frames @ {args.size}x{args.size})") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/e2e_linux_validation/run_e2e.py b/tools/e2e_linux_validation/run_e2e.py new file mode 100644 index 0000000..a19ca83 --- /dev/null +++ b/tools/e2e_linux_validation/run_e2e.py @@ -0,0 +1,139 @@ +# /// script +# requires-python = ">=3.9" +# /// +# ─── How to run ─── +# python3 tools/e2e_linux_validation/run_e2e.py +# ─────────────────── +"""Plan todo 10 end-to-end harness: recorded video -> live MediaPipe tracker -> +shared-memory IPC contract -> core/synth-backed OpenNI2 "SynthKinect" driver -> +an independent OpenNI2 consumer reading a sequence of moving depth frames. + +Orchestrates (no pytest, no mocks - every step is the real binary/process): + 1. generate_dance_video.py: a deterministic recorded video of a real + photographed human panning/zooming across frames (never a live webcam). + 2. `cmake --build fallback/linux-openni2/build`: the SynthKinectDriver + (reading the live shared-memory contract via ShmFrameSource) and the + openni2_depth_consumer binary. + 3. tracker/.venv's `python -m tracker.tracker` against the recorded video, + publishing real MediaPipe pose+mask frames into the frozen IPC contract. + 4. openni2_depth_consumer, which dlopens the driver through OpenNI2 and + reports per-frame body-pixel centroid + in-band depth stats. + +Exits non-zero (and the consumer's own FAIL line names the failed check) if +the consumer does not observe >=10 in-band, moving depth frames. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +import time + +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +SHM_NAME = "virtual_kinect_frames" +SHM_PATH = f"/dev/shm/{SHM_NAME}" +VIDEO_PATH = "/tmp/kinect_e2e/dance.avi" +DRIVER_BUILD_DIR = os.path.join(ROOT, "fallback", "linux-openni2", "build") +TRACKER_VENV_PYTHON = os.path.join(ROOT, "tracker", ".venv", "bin", "python") +GL_LIBS_DIR = os.path.expanduser("~/.cache/kinect/gllibs") +OPENNI2_LIB_DIR = os.path.expanduser("~/.local/openni2-root/usr/lib/x86_64-linux-gnu") + + +def run(cmd: list[str], **kwargs) -> subprocess.CompletedProcess: + print(f"$ {' '.join(cmd)}") + result = subprocess.run(cmd, capture_output=True, text=True, **kwargs) + print(result.stdout) + if result.stderr: + print(result.stderr, file=sys.stderr) + return result + + +def generate_video() -> None: + result = run([ + TRACKER_VENV_PYTHON, + os.path.join(ROOT, "tools", "e2e_linux_validation", "generate_dance_video.py"), + "--out", VIDEO_PATH, + "--frames", "300", + ]) + if result.returncode != 0: + raise RuntimeError("generate_dance_video.py failed") + + +def build_driver() -> None: + configure = run([ + "cmake", "-S", os.path.join(ROOT, "fallback", "linux-openni2"), "-B", DRIVER_BUILD_DIR, + ]) + if configure.returncode != 0: + raise RuntimeError("cmake configure failed") + build = run(["cmake", "--build", DRIVER_BUILD_DIR]) + if build.returncode != 0: + raise RuntimeError("cmake build failed") + + +def wait_for_shm(timeout_s: float) -> bool: + deadline = time.monotonic() + timeout_s + while time.monotonic() < deadline: + if os.path.exists(SHM_PATH): + return True + time.sleep(0.1) + return False + + +def main() -> int: + if os.path.exists(SHM_PATH): + os.remove(SHM_PATH) + + generate_video() + build_driver() + + tracker_env = dict(os.environ) + tracker_env["LD_LIBRARY_PATH"] = GL_LIBS_DIR + os.pathsep + tracker_env.get("LD_LIBRARY_PATH", "") + tracker_cmd = [ + TRACKER_VENV_PYTHON, "-m", "tracker.tracker", + "--source", VIDEO_PATH, + "--model", "full", + "--target-fps", "15", + "--depth-size", "320x240", + "--color-size", "320x240", + "--shm-name", SHM_NAME, + "--max-seconds", "14", + ] + print(f"$ {' '.join(tracker_cmd)} (background)") + tracker_proc = subprocess.Popen( + tracker_cmd, cwd=ROOT, env=tracker_env, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + ) + + try: + if not wait_for_shm(timeout_s=15.0): + raise RuntimeError(f"{SHM_PATH} never appeared - tracker failed to start publishing") + time.sleep(2.0) # bounded grace so several real frames are already published + + consumer_path = os.path.join(DRIVER_BUILD_DIR, "openni2_depth_consumer") + consumer_env = dict(os.environ) + consumer_env["LD_LIBRARY_PATH"] = OPENNI2_LIB_DIR + os.pathsep + consumer_env.get("LD_LIBRARY_PATH", "") + consumer = run([consumer_path, "12"], env=consumer_env, timeout=30) + finally: + if tracker_proc.poll() is None: + tracker_proc.terminate() + try: + tracker_stdout, _ = tracker_proc.communicate(timeout=20) + except subprocess.TimeoutExpired: + tracker_proc.kill() + tracker_stdout, _ = tracker_proc.communicate() + print("--- tracker stdout ---") + print(tracker_stdout) + if os.path.exists(SHM_PATH): + os.remove(SHM_PATH) + + if consumer.returncode != 0: + print(f"VERDICT: FAIL (consumer exit {consumer.returncode})") + return 1 + print("VERDICT: PASS") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())