diff --git a/Cargo.lock b/Cargo.lock index 8258564..e1e6582 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -503,6 +503,10 @@ dependencies = [ "odin-core", ] +[[package]] +name = "muninn-move-tracker" +version = "0.1.0" + [[package]] name = "num-traits" version = "0.2.19" diff --git a/Cargo.toml b/Cargo.toml index e73a4eb..29cdaed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ members = [ "crates/idunn-daemon", "crates/muninn-daemon", + "crates/muninn-move-tracker", "crates/odin-core", ] resolver = "3" diff --git a/crates/muninn-move-tracker/Cargo.toml b/crates/muninn-move-tracker/Cargo.toml new file mode 100644 index 0000000..678dd52 --- /dev/null +++ b/crates/muninn-move-tracker/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "muninn-move-tracker" +version = "0.1.0" +edition = "2024" +description = "Muninn-owned Rust orchestration and CPU mirror for PS Move marker candidate extraction" + +[lib] +name = "muninn_move_tracker" +crate-type = ["rlib", "cdylib", "staticlib"] + +[dependencies] diff --git a/crates/muninn-move-tracker/README.md b/crates/muninn-move-tracker/README.md new file mode 100644 index 0000000..faf77fe --- /dev/null +++ b/crates/muninn-move-tracker/README.md @@ -0,0 +1,28 @@ +# Muninn Move Tracker + +Muninn owns PS Move sensor stream exposure. This crate is Muninn's first native +optical marker candidate extractor: Rust owns orchestration, FFI, validation, +and the CPU mirror; the compute shader owns the parallel image reduction stage. + +This crate deliberately stops at per-frame marker candidates. Final pose, +stereo triangulation, controller association, IMU fusion, prediction, and +calibration remain separate later owners. Mimir consumes Muninn-emitted typed +candidate/observation streams; it does not own raw optical extraction. + +## Current Contract + +- Input: one luma frame (`Y8`) with width, height, stride, source hash, and frame + sequence. +- GPU stage: one 16px tile per thread group, emitting at most one candidate per + tile. +- Output: `MoveMarkerCandidate` records containing weighted centroid, radius, + area, peak/mean luma, and score. +- Rust mirror: deterministic CPU implementation and FFI wrappers for tests and + non-GPU smoke paths. +- FFI prefix: `muninn_move_tracker_*`. +- Shader IDs are carried as `uint2` low/high pairs to avoid making 64-bit HLSL + integer support a dependency of the first extraction pass. + +This is the first stage required for PlayStation-class wand tracking. The +remaining stack needs calibrated camera rays, controlled sphere colors/exposure, +multi-camera association, triangulation, IMU fusion, and latency prediction. diff --git a/crates/muninn-move-tracker/shaders/MoveSphereCandidate.comp.hlsl b/crates/muninn-move-tracker/shaders/MoveSphereCandidate.comp.hlsl new file mode 100644 index 0000000..9cda916 --- /dev/null +++ b/crates/muninn-move-tracker/shaders/MoveSphereCandidate.comp.hlsl @@ -0,0 +1,104 @@ +// Muninn PS Move sphere candidate extraction. +// One thread group owns one image tile. The shader emits at most one bright +// marker candidate per 16px tile; Rust owns dispatch sizing and downstream ranking. + +struct MoveSphereCandidate +{ + uint2 sourceIdHash; + uint2 frameSequence; + uint tileX; + uint tileY; + float centerXPx; + float centerYPx; + float radiusPx; + uint areaPx; + float meanLuma; + uint peakLuma; + float score; +}; + +cbuffer MoveTrackerConfig : register(b0) +{ + uint width; + uint height; + uint strideBytes; + uint tileSize; + uint thresholdMin; + uint minAreaPx; + uint maxCandidates; + uint _pad0; + uint2 sourceIdHash; + uint2 frameSequence; +}; + +ByteAddressBuffer frameY8 : register(t0); +RWStructuredBuffer candidates : register(u0); +RWByteAddressBuffer candidateCounter : register(u1); + +groupshared uint gArea; +groupshared uint gSumX; +groupshared uint gSumY; +groupshared uint gSumW; +groupshared uint gPeak; + +[numthreads(16, 16, 1)] +void main(uint3 groupId : SV_GroupID, uint3 groupThreadId : SV_GroupThreadID) +{ + if (groupThreadId.x == 0 && groupThreadId.y == 0) + { + gArea = 0; + gSumX = 0; + gSumY = 0; + gSumW = 0; + gPeak = 0; + } + GroupMemoryBarrierWithGroupSync(); + + uint x = groupId.x * tileSize + groupThreadId.x; + uint y = groupId.y * tileSize + groupThreadId.y; + if (groupThreadId.x < tileSize && groupThreadId.y < tileSize && x < width && y < height) + { + uint byteOffset = y * strideBytes + x; + uint packed = frameY8.Load(byteOffset & ~3u); + uint shift = (byteOffset & 3u) * 8u; + uint luma = (packed >> shift) & 0xffu; + if (luma >= thresholdMin) + { + uint weight = luma - thresholdMin + 1u; + InterlockedAdd(gArea, 1u); + InterlockedAdd(gSumX, x * weight); + InterlockedAdd(gSumY, y * weight); + InterlockedAdd(gSumW, weight); + InterlockedMax(gPeak, luma); + } + } + + GroupMemoryBarrierWithGroupSync(); + + if (groupThreadId.x == 0 && groupThreadId.y == 0 && gArea >= minAreaPx && gSumW > 0) + { + uint index; + candidateCounter.InterlockedAdd(0, 1, index); + if (index < maxCandidates) + { + float area = (float)gArea; + float tilePixels = (float)(tileSize * tileSize); + float areaScore = min(1.0, area / tilePixels); + float brightnessScore = (float)gPeak / 255.0; + + MoveSphereCandidate candidate; + candidate.sourceIdHash = sourceIdHash; + candidate.frameSequence = frameSequence; + candidate.tileX = groupId.x; + candidate.tileY = groupId.y; + candidate.centerXPx = (float)gSumX / (float)gSumW; + candidate.centerYPx = (float)gSumY / (float)gSumW; + candidate.radiusPx = sqrt(area / 3.14159265358979323846); + candidate.areaPx = gArea; + candidate.meanLuma = (float)thresholdMin + (((float)gSumW / area) - 1.0); + candidate.peakLuma = gPeak; + candidate.score = brightnessScore * (0.65 + areaScore * 0.35); + candidates[index] = candidate; + } + } +} diff --git a/crates/muninn-move-tracker/src/lib.rs b/crates/muninn-move-tracker/src/lib.rs new file mode 100644 index 0000000..0b2d373 --- /dev/null +++ b/crates/muninn-move-tracker/src/lib.rs @@ -0,0 +1,308 @@ +#![deny(unsafe_op_in_unsafe_fn)] + +use core::ffi::c_int; + +pub const MUNINN_MOVE_TRACKER_OK: c_int = 0; +pub const MUNINN_MOVE_TRACKER_NULL: c_int = -1; +pub const MUNINN_MOVE_TRACKER_INVALID: c_int = -2; + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MoveTrackerConfig { + pub width: u32, + pub height: u32, + pub stride_bytes: u32, + pub tile_size: u32, + pub threshold_min: u8, + pub min_area_px: u32, + pub max_candidates: u32, + pub source_id_hash: u64, + pub frame_sequence: u64, +} + +impl Default for MoveTrackerConfig { + fn default() -> Self { + Self { + width: 320, + height: 240, + stride_bytes: 320, + tile_size: 16, + threshold_min: 180, + min_area_px: 4, + max_candidates: 64, + source_id_hash: 0, + frame_sequence: 0, + } + } +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MoveTrackerDispatchPlan { + pub group_size_x: u32, + pub group_size_y: u32, + pub groups_x: u32, + pub groups_y: u32, + pub max_candidates: u32, +} + +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct MoveMarkerCandidate { + pub source_id_hash: u64, + pub frame_sequence: u64, + pub tile_x: u32, + pub tile_y: u32, + pub center_x_px: f32, + pub center_y_px: f32, + pub radius_px: f32, + pub area_px: u32, + pub mean_luma: f32, + pub peak_luma: u32, + pub score: f32, +} + +pub fn dispatch_plan(config: MoveTrackerConfig) -> Option { + if !config_is_valid(config) { + return None; + } + + let tile = config.tile_size; + Some(MoveTrackerDispatchPlan { + group_size_x: tile, + group_size_y: tile, + groups_x: config.width.div_ceil(tile), + groups_y: config.height.div_ceil(tile), + max_candidates: config.max_candidates, + }) +} + +pub fn extract_luma_candidates( + frame: &[u8], + config: MoveTrackerConfig, +) -> Option> { + if !config_is_valid(config) { + return None; + } + + let required = required_frame_bytes(config)?; + if frame.len() < required { + return None; + } + + let mut candidates = Vec::new(); + let tile = config.tile_size; + let groups_x = config.width.div_ceil(tile); + let groups_y = config.height.div_ceil(tile); + + for tile_y in 0..groups_y { + for tile_x in 0..groups_x { + if candidates.len() >= config.max_candidates as usize { + return Some(candidates); + } + + if let Some(candidate) = extract_tile(frame, config, tile_x, tile_y) { + candidates.push(candidate); + } + } + } + + candidates.sort_by(|left, right| { + right + .score + .partial_cmp(&left.score) + .unwrap_or(core::cmp::Ordering::Equal) + }); + Some(candidates) +} + +fn extract_tile( + frame: &[u8], + config: MoveTrackerConfig, + tile_x: u32, + tile_y: u32, +) -> Option { + let x0 = tile_x * config.tile_size; + let y0 = tile_y * config.tile_size; + let x1 = (x0 + config.tile_size).min(config.width); + let y1 = (y0 + config.tile_size).min(config.height); + let threshold = u32::from(config.threshold_min); + let mut area = 0u32; + let mut sum_x = 0u64; + let mut sum_y = 0u64; + let mut sum_w = 0u64; + let mut peak = 0u32; + + for y in y0..y1 { + let row = y as usize * config.stride_bytes as usize; + for x in x0..x1 { + let luma = u32::from(frame[row + x as usize]); + if luma < threshold { + continue; + } + + area += 1; + peak = peak.max(luma); + let weight = u64::from(luma - threshold + 1); + sum_x += u64::from(x) * weight; + sum_y += u64::from(y) * weight; + sum_w += weight; + } + } + + if area < config.min_area_px || sum_w == 0 { + return None; + } + + let center_x = sum_x as f32 / sum_w as f32; + let center_y = sum_y as f32 / sum_w as f32; + let radius = (area as f32 / core::f32::consts::PI).sqrt(); + let mean_luma = threshold as f32 + ((sum_w as f32 / area as f32) - 1.0); + let area_score = (area as f32 / (config.tile_size * config.tile_size) as f32).min(1.0); + let brightness_score = peak as f32 / 255.0; + + Some(MoveMarkerCandidate { + source_id_hash: config.source_id_hash, + frame_sequence: config.frame_sequence, + tile_x, + tile_y, + center_x_px: center_x, + center_y_px: center_y, + radius_px: radius, + area_px: area, + mean_luma, + peak_luma: peak, + score: brightness_score * (0.65 + area_score * 0.35), + }) +} + +fn config_is_valid(config: MoveTrackerConfig) -> bool { + config.width > 0 + && config.height > 0 + && config.stride_bytes >= config.width + && config.tile_size == 16 + && config.min_area_px > 0 + && config.max_candidates > 0 +} + +fn required_frame_bytes(config: MoveTrackerConfig) -> Option { + let rows = usize::try_from(config.height).ok()?; + let stride = usize::try_from(config.stride_bytes).ok()?; + rows.checked_mul(stride) +} + +#[unsafe(no_mangle)] +pub extern "C" fn muninn_move_tracker_dispatch_plan( + config: MoveTrackerConfig, + out_plan: *mut MoveTrackerDispatchPlan, +) -> c_int { + if out_plan.is_null() { + return MUNINN_MOVE_TRACKER_NULL; + } + + let Some(plan) = dispatch_plan(config) else { + return MUNINN_MOVE_TRACKER_INVALID; + }; + + unsafe { + *out_plan = plan; + } + MUNINN_MOVE_TRACKER_OK +} + +#[unsafe(no_mangle)] +pub extern "C" fn muninn_move_tracker_extract_luma_cpu( + config: MoveTrackerConfig, + frame: *const u8, + frame_len: usize, + out_candidates: *mut MoveMarkerCandidate, + out_capacity: usize, + out_count: *mut usize, +) -> c_int { + if frame.is_null() || out_candidates.is_null() || out_count.is_null() { + return MUNINN_MOVE_TRACKER_NULL; + } + + let frame = unsafe { core::slice::from_raw_parts(frame, frame_len) }; + let Some(candidates) = extract_luma_candidates(frame, config) else { + return MUNINN_MOVE_TRACKER_INVALID; + }; + + let written = candidates.len().min(out_capacity); + unsafe { + core::ptr::copy_nonoverlapping(candidates.as_ptr(), out_candidates, written); + *out_count = written; + } + MUNINN_MOVE_TRACKER_OK +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dispatch_plan_covers_partial_tiles() { + let config = MoveTrackerConfig { + width: 33, + height: 17, + stride_bytes: 40, + tile_size: 16, + ..MoveTrackerConfig::default() + }; + + let plan = dispatch_plan(config).expect("valid plan"); + assert_eq!(3, plan.groups_x); + assert_eq!(2, plan.groups_y); + assert_eq!(16, plan.group_size_x); + assert_eq!(16, plan.group_size_y); + } + + #[test] + fn extracts_weighted_marker_candidate() { + let config = MoveTrackerConfig { + width: 32, + height: 24, + stride_bytes: 32, + tile_size: 16, + threshold_min: 180, + min_area_px: 3, + max_candidates: 8, + source_id_hash: 42, + frame_sequence: 7, + }; + let mut frame = vec![0u8; (config.stride_bytes * config.height) as usize]; + for (x, y, luma) in [ + (10u32, 8u32, 230u8), + (11, 8, 250), + (10, 9, 240), + (11, 9, 255), + ] { + frame[(y * config.stride_bytes + x) as usize] = luma; + } + + let candidates = extract_luma_candidates(&frame, config).expect("candidates"); + assert_eq!(1, candidates.len()); + let candidate = candidates[0]; + assert_eq!(42, candidate.source_id_hash); + assert_eq!(7, candidate.frame_sequence); + assert_eq!(0, candidate.tile_x); + assert_eq!(0, candidate.tile_y); + assert_eq!(4, candidate.area_px); + assert_eq!(255, candidate.peak_luma); + assert!(candidate.center_x_px > 10.4 && candidate.center_x_px < 10.7); + assert!(candidate.center_y_px > 8.4 && candidate.center_y_px < 8.7); + assert!(candidate.score > 0.65); + } + + #[test] + fn rejects_short_frames_and_empty_config() { + assert!(extract_luma_candidates(&[], MoveTrackerConfig::default()).is_none()); + assert!( + dispatch_plan(MoveTrackerConfig { + width: 0, + ..MoveTrackerConfig::default() + }) + .is_none() + ); + } +} diff --git a/crates/odin-core/src/documents.rs b/crates/odin-core/src/documents.rs index 47793b7..4e86033 100644 --- a/crates/odin-core/src/documents.rs +++ b/crates/odin-core/src/documents.rs @@ -22,6 +22,7 @@ pub const IDUNN_OPERATOR_ALARM_SCHEMA: &str = "idunn.operator_alarm.v1"; pub const MUNINN_TELEMETRY_SURFACE_SCHEMA: &str = "muninn.telemetry_surface.v1"; pub const MUNINN_CAPTURE_STREAM_SCHEMA: &str = "muninn.capture_stream.v1"; pub const MUNINN_OBS_STREAM_CATALOG_SCHEMA: &str = "muninn.obs_stream_catalog.v1"; +pub const MUNINN_MOVE_MARKER_CANDIDATE_SCHEMA: &str = "muninn.move_marker_candidate.v1"; #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[cultcache(type = "odin.snapshot", schema = "odin.snapshot.v1")] @@ -297,7 +298,10 @@ pub struct IdunnDeploymentRequestRecord { } #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "idunn.deployment_result", schema = "idunn.deployment_result.v1")] +#[cultcache( + type = "idunn.deployment_result", + schema = "idunn.deployment_result.v1" +)] pub struct IdunnDeploymentResultRecord { #[cultcache(key = 0)] pub result_id: String, @@ -409,6 +413,44 @@ pub struct MuninnObsStreamCatalogRecord { pub updated_at: String, } +#[derive(Clone, Debug, PartialEq, DatabaseEntry)] +#[cultcache( + type = "muninn.move_marker_candidate", + schema = "muninn.move_marker_candidate.v1" +)] +pub struct MuninnMoveMarkerCandidateRecord { + #[cultcache(key = 0)] + pub stream_id: String, + #[cultcache(key = 1)] + pub host_id: String, + #[cultcache(key = 2)] + pub camera_id: String, + #[cultcache(key = 3)] + pub frame_sequence: u64, + #[cultcache(key = 4)] + pub source_id_hash: u64, + #[cultcache(key = 5)] + pub tile_x: u32, + #[cultcache(key = 6)] + pub tile_y: u32, + #[cultcache(key = 7)] + pub center_x_px: f32, + #[cultcache(key = 8)] + pub center_y_px: f32, + #[cultcache(key = 9)] + pub radius_px: f32, + #[cultcache(key = 10)] + pub area_px: u32, + #[cultcache(key = 11)] + pub mean_luma: f32, + #[cultcache(key = 12)] + pub peak_luma: u32, + #[cultcache(key = 13)] + pub score: f32, + #[cultcache(key = 14)] + pub observed_at: String, +} + cultmesh_rs::cultmesh_documents!(OdinDocuments { OdinSnapshotRecord => ODIN_SNAPSHOT_SCHEMA, OdinVerseRecord => ODIN_VERSE_SCHEMA, @@ -431,6 +473,7 @@ cultmesh_rs::cultmesh_documents!(OdinDocuments { MuninnTelemetrySurfaceRecord => MUNINN_TELEMETRY_SURFACE_SCHEMA, MuninnCaptureStreamRecord => MUNINN_CAPTURE_STREAM_SCHEMA, MuninnObsStreamCatalogRecord => MUNINN_OBS_STREAM_CATALOG_SCHEMA, + MuninnMoveMarkerCandidateRecord => MUNINN_MOVE_MARKER_CANDIDATE_SCHEMA, }); #[derive(Clone, Debug, Default, PartialEq, Eq)] diff --git a/docs/architecture.md b/docs/architecture.md index 6cda721..0565b16 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -113,6 +113,13 @@ Odin discovery truth, or Idunn keepalive policy. Active stream records such as `muninn.capture_stream.v1` are evidence of requested streams, not permission for startup to burn capture resources. +Move optical marker extraction belongs to Muninn because it is sensor stream +exposure, not Mimir fusion or Odin registry truth. The native helper lives at +`crates/muninn-move-tracker`; Muninn may publish per-frame candidates as +`muninn.move_marker_candidate.v1`. Mimir consumes those candidate streams into +tracking buffers and later fusion. Odin indexes the schema and projection +surface only. + Bifrost is the bridge for Persona speech and other public/owner-facing crossings. When a Persona interpreter decides a Persona speaks, the accepted side effect is a Bifrost CultMesh command or document that names actor, diff --git a/docs/muninn.md b/docs/muninn.md index 2f65c8b..7cef094 100644 --- a/docs/muninn.md +++ b/docs/muninn.md @@ -12,8 +12,8 @@ microphones, cameras, and future sensors. and explicit activation of requested local streams. - Inputs: cheap local probes, operator or Verse activation requests, and local capture tools such as FFmpeg or WASAPI helpers. -- Outputs: `muninn.telemetry_surface.v1` and active `muninn.capture_stream.v1` - records. +- Outputs: `muninn.telemetry_surface.v1`, active `muninn.capture_stream.v1`, + and Move optical `muninn.move_marker_candidate.v1` records. - Forbidden writers: daemon startup, Idunn keepalive, Mimir ingest, OBS, Odin, Gjallar, and renderer bodies must not start capture by implication. @@ -60,3 +60,16 @@ wasapi-loopback-capture.ps1 -Output stdout -Device Realtek -SampleRate 48000 -Ch render-device hint. Current helper builds may ignore the hint and use the default render endpoint, but they must accept the argument so Muninn's generated mux command remains executable. + +## Move Marker Candidates + +`crates/muninn-move-tracker` is Muninn's native/Rust PS Move optical candidate +extractor. It owns dispatch planning, FFI, configuration validation, a CPU +mirror, and the HLSL 16px-tile luma reduction shader. It emits marker +candidates only: weighted centroid, radius, area, peak/mean luma, and score for +one camera frame. + +Muninn owns publishing those candidates as `muninn.move_marker_candidate.v1`. +Mimir is a consumer of the resulting sensor stream. Odin may discover and +project the schema, but Odin does not own raw capture, candidate extraction, +calibration, triangulation, IMU fusion, prediction, or final 6DoF pose.