diff --git a/.omo/plans/webcam-kinect-emulator.md b/.omo/plans/webcam-kinect-emulator.md index e9ab27e..a4cb2cc 100644 --- a/.omo/plans/webcam-kinect-emulator.md +++ b/.omo/plans/webcam-kinect-emulator.md @@ -228,7 +228,8 @@ Your next move: run the default-on high-accuracy review (in progress), then exec Commit: Y | feat(calibration): T-pose scale/floor/mirror config Recommended task executor category: unspecified-high - contained feature with real edge cases. -- [ ] 12. Windows USB attach (virtual bus driver) +- [~] 12. Windows USB attach (virtual bus driver) + BLOCKED: no Windows/WDK here. Complete usbip-win runbook + PowerShell scripts delivered (attach/windows/); reuses the socket-verified attach/linux USB/IP server. Gap: build/attach/Device-Manager verification needs the user's Windows box; ISO-framing acceptance by Windows VHCI is the todo-13 question. What to do / Must NOT do: In `attach/windows/`, present the todo-8 emitter to Windows via usbip-win (or a UMDF/KMDF virtual USB bus driver) so the real MS Kinect driver (kinectsensor.inf) + `Kinect10.dll` see a Kinect. Document the test-signing / signature-enforcement steps. Must NOT: ship an unsigned driver as if production-ready - personal-use test-signing only, clearly documented. Closes: GAP-3 (Windows half) Parallelization: Wave 9 | Blocked by: 8,4 | Blocks: 13 @@ -238,7 +239,8 @@ Your next move: run the default-on high-accuracy review (in progress), then exec Commit: Y | feat(attach-windows): virtual usb bus attach + signing docs Recommended task executor category: deep-high - Windows driver work + signing, high risk. -- [ ] 13. Windows integration + DanceEvolution Arcade playability +- [~] 13. Windows integration + DanceEvolution Arcade playability + BLOCKED: requires the user's Windows box + DEA + webcam + a person dancing. Both Windows paths are built (device: attach/windows [~]build; shim: fallback/windows-nui Kinect10.dll export-verified). This is the F5 acceptance step; runbooks in docs/spike-windows.md + attach/windows + fallback/windows-nui. The depth-fidelity/skeletonization KILL-GATE on real MS NUI is UNPROVEN here (no Windows). What to do / Must NOT do: On the user's Windows box, verify DEA via the DEVICE path: tracker -> synth -> emitter -> Windows virtual-USB attach (todo 12). This DEVICE path is what proves IS-1 (the OS/runtime enumerates the sensor) and IS-2 (the real MS NUI runtime skeletonizes synthetic depth) in addition to gameplay (silhouette, tracked moves, directionally-correct scoring). SEPARATELY, the NUI-shim (todo 14) is an independent path that proves ONLY playability (IS-3/IS-4) via direct injection - it does NOT satisfy IS-1 or IS-2. If the DEVICE path (todo 12) cannot be achieved, HALT and re-plan rather than accepting shim gameplay as proof of IS-1/IS-2. Capture a gameplay recording for whichever path(s) run. Must NOT: claim IS-1/IS-2 proven from the shim path; claim playable without a recorded scoring session. Closes: GAP-7 (Windows validation), proves IS-1,2,3,4,7 on Windows Parallelization: Wave 10 | Blocked by: 12,5,7,11 (or 14) | Blocks: 18 @@ -248,7 +250,8 @@ Your next move: run the default-on high-accuracy review (in progress), then exec Commit: Y | test(e2e-windows): DEA playable via webcam virtual kinect Recommended task executor category: deep-high - cross-stack integration + the decisive feasibility proof. -- [ ] 14. Windows NUI-shim fallback (clean-room Kinect10.dll) +- [x] 14. Windows NUI-shim fallback (clean-room Kinect10.dll) + NOTE (exec): clean-room Kinect10.dll CROSS-COMPILED on Linux to x86 (DEA arch) + x64 real PE DLLs; 21/21 required NUI exports audited (undecorated __stdcall), ABI struct sizes static_assert-pinned both arches; consumes the shared FrameContract, reuses core/mapping+core/synth. [~] in-game/runtime pass needs Windows (todo 13/F5). What to do / Must NOT do: In `fallback/windows-nui/`, a clean-room drop-in `Kinect10.dll` implementing the NUI surface the spike (todo 4) found DEA imports: `NuiInitialize/Shutdown`, `NuiGetSensorCount`, `NuiCreateSensorByIndex/Id`, `INuiSensor`, `NuiSkeletonTrackingEnable/GetNextFrame`, `NuiImageStreamOpen/GetNextFrame/ReleaseFrame`, `INuiFrameTexture` COM object, `NuiTransformSmooth`, coordinate mappers - injecting skeleton (from todo 6) + depth/color (from todo 7) directly, honoring the ~30Hz event model. This fallback is UNCONDITIONALLY in scope (general-purpose goal); spike 4 sets whether it is the PRIMARY Windows path or the secondary surface, not whether it is built. Must NOT: fake fewer exports than DEA imports; get `__stdcall` decoration / struct packing / COM vtable order wrong (bit-for-bit per public NuiApi.h); open GPLv3 source (KinectFaker) while implementing - clean-room firewall. Closes: GAP-6 (Windows fallback) Parallelization: Wave 9 | Blocked by: 6,7,4 | Blocks: 13 (fallback path) diff --git a/attach/windows/README.md b/attach/windows/README.md index 9004112..d17f93a 100644 --- a/attach/windows/README.md +++ b/attach/windows/README.md @@ -1,6 +1,178 @@ -# attach/windows/ — Windows virtual USB bus attach (todo 12) +# attach/windows/ — Windows USB attach for the virtual Kinect v1 (todo 12) -Presents the `core/protocol` emitter to Windows via usbip-win (or a UMDF/KMDF virtual -USB bus driver) so the real MS Kinect driver (`kinectsensor.inf`) + `Kinect10.dll` see a -Kinect. Documents the test-signing / Secure-Boot steps (personal-use only). Placeholder -until todo 12. +Presents the OS-agnostic `core/protocol` emitter (`nui::protocol::KinectV1Device`) to Windows via +the **usbip-win VHCI client**, so the real Microsoft Kinect driver (`kinect*.inf`) binds to it and +the real `Kinect10.dll` NUI runtime enumerates it as a physical Kinect. It reuses the +`attach/linux` USB/IP **server** unchanged — that server is OS-agnostic (USB/IP protocol v1.1.1); +only the client (the Windows VHCI driver) and the MS driver binding differ per OS. + +The architecture, the decision to reuse USB/IP instead of writing a bespoke bus driver, the exact +device topology, and the one real risk (isochronous framing) are in +[`docs/approach.md`](docs/approach.md). Read it before running anything here. + +## Status in THIS environment: **`[~]` BLOCKED (no Windows, no WDK)** + +This directory was authored on a Linux/WSL2 host with **no Windows and no Windows Driver Kit**. +A Windows virtual USB bus driver (KMDF/UMDF) and the `usbip-win` VHCI driver both need the WDK + +MSVC and can only be built on Windows; mingw cannot build Windows kernel-mode drivers. **Nothing +in this directory was built or run.** No binding, no enumeration, and no DEA playability was +observed. Every build/attach/verify step below is for the **user's Windows box**. The reusable +server half is complete and socket-verified in `attach/linux/`. + +What is delivered and ready to use on Windows: + +| Deliverable | Path | What it does | +| --- | --- | --- | +| Approach + architecture + decision record | `docs/approach.md` | why USB/IP, topology, ISO risk, fallbacks | +| Attach map / device identities | `config/kinect-usbip.json` | server host:port + the three busids/VID:PIDs | +| Install a VHCI client | `scripts/Install-UsbIpWin.ps1` | installs usbip-win2 (signed) or usbip-win (test-signed) | +| Test-signing + cert (legacy client) | `scripts/Enable-TestSigning.ps1`, `scripts/Disable-TestSigning.ps1` | `bcdedit`, Secure-Boot check, PFX import | +| Attach / detach the sensor | `scripts/Attach-Kinect.ps1`, `scripts/Detach-Kinect.ps1` | three `usbip attach`, graceful detach | +| Verify binding | `scripts/Verify-KinectDevice.ps1` | PnP check that the MS Kinect driver bound, no yellow-bang | + +## Prerequisites + +On the **host** running the device emitter (any Linux box, a Linux VM, or WSL2 with a usable +networking stack — the same binary serves both OSes): + +```sh +cmake -S attach/linux -B attach/linux/build +cmake --build attach/linux/build +./attach/linux/build/kinect_attach serve --port 3240 # exports busids 1-1 camera, 1-2 audio, 1-3 motor +``` + +(For a real session the emitter is fed by the tracker/synth pipeline, plan todos 5/7/10; the +standalone `serve` uses a placeholder frame source and is enough to prove enumeration/binding.) + +On the **Windows box**: + +- Windows 10 x64 1903 (build 18362) or later (usbip-win2 requirement), or Windows 11. +- The **Kinect for Windows Runtime + SDK v1.8** installed — this provides the real Kinect USB + driver (`kinect*.inf`) and `Kinect10.dll`, which are what must bind to and enumerate the virtual + device. Without them there is nothing on the Windows side to recognize the sensor. +- The **Kinect for Windows Developer Toolkit v1.8** for the `KinectExplorer-D2D` / + `SkeletonBasics-D2D` samples used to confirm NUI enumeration. +- A USB/IP VHCI client (installed below). +- An elevated PowerShell for every script here. + +## Pick a client + +Two prebuilt USB/IP VHCI clients work; this directory supports both. + +- **usbip-win2 (vadimgrn) — RECOMMENDED.** UDE driver, **attestation/WHLK-signed**, ships an MSI. + Because it is properly signed it typically needs **no** test-signing and **no** Secure-Boot + change. Download the MSI from . Requires + Windows 10 1903+. +- **usbip-win (cezanne) — legacy fallback.** Test-signed VHCI driver (`vhci(ude)` or `vhci(wdm)`). + Requires **test-signing ON**, **Secure Boot OFF**, and its bundled `usbip_test.pfx` imported. + Download/extract a release zip from (e.g. + `usbip-win-0.3.5` or `0.3.6-dev`). Use this only if usbip-win2 does not work on the target OS. + +## Runbook + +### A. If using usbip-win2 (signed — the simple path) + +```powershell +# Elevated PowerShell on the Windows box. Create a System Restore Point first (USB hubs restart). +cd attach\windows\scripts +.\Install-UsbIpWin.ps1 -Client usbip-win2 -InstallerPath C:\path\to\USBip-.x64.msi +# (reboot only if Windows prompts; the signed UDE driver usually loads without test-signing) + +# With the attach/linux server running on the host (edit config\kinect-usbip.json 'host' if remote): +.\Attach-Kinect.ps1 # attaches busids 1-1, 1-2, 1-3 +.\Verify-KinectDevice.ps1 # confirms the three PIDs bound to the MS Kinect driver +``` + +If the signed driver still refuses to load (`usbip.exe` reports the driver blocked), fall through +to the test-signing steps in section B — they apply to any unsigned/test-signed driver. + +### B. If using usbip-win (legacy — test-signing required) + +Test-signing is the Windows posture that lets a driver **not** signed by a Microsoft-trusted CA +load. Windows x64 enforces driver signing; a self-built/test-signed VHCI driver is signed by a +test certificate, so the box must be in test-signing mode **and** trust that certificate, and +**Secure Boot must be off** (firmware enforces the same signing policy). This is a **personal-use +development posture, not production** — a test-signed driver is untrusted for signing purposes. + +```powershell +# Elevated PowerShell on the Windows box. +cd attach\windows\scripts + +# 1. Secure Boot OFF (in UEFI firmware), then enable test-signing + import the test cert. +.\Enable-TestSigning.ps1 -PfxPath C:\path\to\usbip-win-\usbip_test.pfx +# -> warns if Secure Boot is still ON; runs 'bcdedit /set testsigning on'; +# imports usbip_test.pfx (password: usbip) into LocalMachine Root AND TrustedPublisher. +# REBOOT. A "Test Mode" desktop watermark appears afterward — that is expected and harmless. + +# 2. Install the test-signed VHCI driver. +.\Install-UsbIpWin.ps1 -Client usbip-win -PackageDir C:\path\to\usbip-win- + +# 3. Attach + verify (server running on the host). +.\Attach-Kinect.ps1 +.\Verify-KinectDevice.ps1 +``` + +**Watermark:** with test-signing on you will see `Test Mode Windows ` in the lower-right +of the desktop. It is the expected signal that signature enforcement is relaxed; it does not +affect gameplay. + +### C. Verify (both paths) + +`Verify-KinectDevice.ps1` checks, via PnP, that `VID_045E&PID_02AE` (camera), `PID_02AD` (audio) +and `PID_02B0` (motor) are **present**, **bound with no Problem code**, and reports the binding +INF/service. The pass criteria for plan todo 12: + +1. **Device Manager** shows the Kinect devices bound to the **Microsoft Kinect driver** + (`kinect*.inf`), no yellow-bang. If `Verify-KinectDevice.ps1` reports the service/INF as + `usbip*`, the VHCI stub attached the device but the MS Kinect driver did not match its + descriptors — check that the real Kinect 1.8 runtime+driver are installed and that the + descriptors match (todo 13 / spike-windows.md Step 4 captures any delta the MS driver demands). +2. **The NUI runtime enumerates it:** launch `KinectExplorer-D2D` (it should list the sensor) or + run `SkeletonBasics-D2D` (it should open the sensor). Equivalently `NuiGetSensorCount() >= 1` + and `NuiCreateSensorByIndex(0, ...)` succeed. Streams may be empty until todo 13 serves depth — + that is expected at the binding stage. + +Capture a Device Manager screenshot and the KinectExplorer window to +`.omo/evidence/task-12-webcam-kinect-emulator.*`. + +### D. Detach / teardown + +```powershell +.\Detach-Kinect.ps1 -All # graceful device removal of all attached ports +# legacy client only, when fully done with the virtual Kinect: +# usbip.exe uninstall # remove the VHCI driver FIRST +.\Disable-TestSigning.ps1 # then turn test-signing back off; reboot; re-enable Secure Boot +``` + +Detaching while DEA or a Kinect SDK sample holds the sensor must surface a clean +**device-removed / sensor-unplugged** to the app (no BSOD) — that is todo 12's documented failure +scenario to confirm on Windows. + +## When to drop to the NUI-shim fallback (todo 14) + +If the device-level path cannot be made to work on the target Windows box — the MS Kinect driver +will not bind to the virtual descriptors, or the USB/IP ISO framing is rejected and extending the +shared server's ISO handling (see `docs/approach.md` §5) does not resolve it — switch to the +clean-room `Kinect10.dll` NUI shim in `fallback/windows-nui/` (plan todo 14). That shim injects +skeleton/depth directly and proves **playability** (IS-3/IS-4) but, per the plan, does **NOT** +satisfy IS-1 (OS enumerates the sensor) or IS-2 (the real MS NUI runtime skeletonizes synthetic +depth). Do not report IS-1/IS-2 as proven from the shim path; if the device path cannot be +achieved, the plan says to HALT and re-plan rather than accept shim gameplay as that proof. + +## Known constraints (documented, not hidden) + +- **Bitness.** spike-windows.md Step 2 settles whether DEA / `gamekdm.dll` is x86 or x64 and + therefore which arch the shipping Windows chain targets. The USB/IP attach here is + arch-agnostic at the wire level (it is a TCP client + a generic VHCI driver), so the same + scripts serve either bitness; the bitness constraint bites the NUI-shim (todo 14) and any + in-process code, not this attach path. usbip-win2 ships x64/ARM64; the legacy client ships + x86/x64. +- **Isochronous framing.** The shared server models the camera's ISO IN endpoints as single + packets without the USB/IP `iso_packet_descriptor` array (a documented simplification validated + against the Linux `vhci-hcd` client). Whether the Windows VHCI + MS Kinect driver accept that is + the open question todo 13 resolves; the fix, if needed, is in the shared `core/`+`attach/linux` + ISO path and is reused by Windows, not a Windows-only change (`docs/approach.md` §5). +- **No driver is built here.** These are install/attach/verify helpers that drive prebuilt + usbip-win releases and the MS Kinect driver. Building `usbip-win`/`usbip-win2` from source, or a + bespoke KMDF/UMDF bus driver, needs the WDK + MSVC on Windows and is out of this environment's + reach. diff --git a/attach/windows/config/kinect-usbip.json b/attach/windows/config/kinect-usbip.json new file mode 100644 index 0000000..382f71f --- /dev/null +++ b/attach/windows/config/kinect-usbip.json @@ -0,0 +1,16 @@ +{ + "_comment": "Virtual Kinect v1 USB/IP attach map for the Windows usbip-win VHCI client. These busids/VID:PIDs MUST match attach/linux/src/kinect_export.cpp and core/protocol/descriptors.cpp exactly; they are the real Kinect v1 sibling-device identities. The 'server' block points at the host running the OS-agnostic attach/linux UsbipServer (kinect_attach serve). Loopback 127.0.0.1 applies when the server runs on the same box via a Windows-local USB/IP stub or a co-located Linux VM/WSL2 with TCP reachable.", + "server": { + "host": "127.0.0.1", + "port": 3240 + }, + "protocolVersion": "0x0111", + "devices": [ + { "busid": "1-1", "function": "camera", "vid": "045E", "pid": "02AE", "bcdDevice": "010B", "required": true, + "note": "NUI Camera: depth iso IN 0x82, color/IR iso IN 0x81. The stream source Kinect10.dll opens; attaching this alone is not a complete sensor." }, + { "busid": "1-2", "function": "audio", "vid": "045E", "pid": "02AD", "bcdDevice": "010B", "required": true, + "note": "NUI Audio: 2 interfaces so the host reads it as already firmware-loaded and skips the bootloader upload (NUI audio-source enumeration)." }, + { "busid": "1-3", "function": "motor", "vid": "045E", "pid": "02B0", "bcdDevice": "010B", "required": true, + "note": "NUI Motor: tilt/LED/accelerometer. Required for the NUI runtime to treat the set as a complete Kinect." } + ] +} diff --git a/attach/windows/docs/approach.md b/attach/windows/docs/approach.md new file mode 100644 index 0000000..77ed5b7 --- /dev/null +++ b/attach/windows/docs/approach.md @@ -0,0 +1,144 @@ +# attach/windows/ — approach & architecture (todo 12) + +> **STATUS in this build environment: `[~]` BLOCKED.** This directory was authored on a +> Linux/WSL2 host with **no Windows and no Windows Driver Kit (WDK)**. A Windows virtual USB +> bus driver (KMDF/UMDF) and the `usbip-win` VHCI driver both require the WDK + MSVC and can +> only be built on Windows; mingw cannot build Windows kernel-mode drivers. **Nothing here was +> built or run.** Every build/attach/verify step below executes on the user's Windows box. +> The runbook that drives these steps is [`../README.md`](../README.md). + +## 1. What this todo must achieve + +Present the OS-agnostic virtual Kinect v1 device — `nui::protocol::KinectV1Device` in +`core/protocol/` — to Windows so that the **real Microsoft Kinect for Windows driver** +(`kinect*.inf` / the 1.8 runtime's USB function driver) binds to it and the real +`Kinect10.dll` NUI runtime enumerates and opens it as if a physical Kinect were plugged in. +Once that holds, plan todo 13 proves the crux (the MS NUI skeletonizer tracking synthetic +depth) and DanceEvolution Arcade plays. + +This closes plan **GAP-3 (Windows half)**: the Windows per-OS USB-attach shim. It is the +Windows sibling of the already-built, socket-verified `attach/linux/` lane. + +## 2. The decision: reuse the Linux USB/IP server, do not write a bespoke bus driver + +The plan phrased todo 12 as "usbip-win (or a UMDF/KMDF virtual USB bus driver)". Those are two +genuinely different mechanisms. The decision taken here is **usbip-win VHCI client against the +existing `attach/linux` USB/IP server**, with a from-scratch KMDF/UMDF bus driver recorded as +the rejected alternative. + +**Why the USB/IP path wins:** + +- **The wire protocol is OS-agnostic and already built + verified.** `attach/linux/` implements + a complete userspace USB/IP **server** (`UsbipServer`) speaking protocol version `0x0111` + (v1.1.1) — the exact protocol the kernel documents at + and the exact protocol + `usbip-win`/`usbip-win2` implement on the Windows client side. The server answers + `OP_REQ_DEVLIST`/`OP_REQ_IMPORT` and relays `USBIP_CMD_SUBMIT`/`USBIP_CMD_UNLINK` URB traffic + into the shared `core/protocol` `KinectV1Device`. A USB/IP client on **any** OS — the Linux + `vhci-hcd` kernel driver, or the Windows `usbip-win` VHCI driver — attaches to that same + server over TCP. **The Windows side needs zero new device logic**; it reuses the Linux + server byte-for-byte. Only the client (the VHCI driver) and the INF binding differ per OS. +- **No kernel driver to author, debug, or crash-test.** A bespoke KMDF/UMDF virtual USB bus + driver is a multi-month kernel project (PnP, power, URB translation, BSOD risk, WHQL/signing). + `usbip-win2`'s UDE driver is an existing, **attestation/WHLK-signed** implementation of exactly + that translation layer. Writing our own duplicates it with strictly more risk. +- **One device core, two attach shims — matches plan IS-5.** The architecture goal is an + OS-agnostic core with a thin per-OS attach shim. USB/IP realizes that literally: the shim on + each OS is "install a VHCI client and `attach` three busids". + +**The rejected alternative — bespoke KMDF/UMDF virtual USB bus driver:** this would enumerate a +root-hub-like bus with the three Kinect child devices directly in kernel/user mode on Windows, +with no TCP server. It is the only option if USB/IP proves unworkable for the Kinect's +isochronous camera endpoints under the MS driver (see §5, the one real risk). It is **not** +built here because (a) it needs the WDK (unavailable), (b) it duplicates `usbip-win2`'s UDE +driver, and (c) it cannot reuse the already-verified Linux wire code. If §5's ISO risk +materializes on Windows, the smaller fix is to extend the **shared** server's ISO framing (a +cross-lane change in `core/`+`attach/linux/`, owned by todos 8/9), not to write a Windows driver. + +## 3. The topology the MS Kinect driver expects + +The real Kinect v1 is a **composite set of three sibling USB devices** behind the sensor's +internal hub, each with its own VID/PID — not three interfaces of one device. `core/protocol` +and `attach/linux` already commit to the exact identities (from libfreenect, transcribed in +`core/protocol/descriptors.cpp` and `attach/linux/src/kinect_export.cpp`): + +| busid | Function | VID:PID | bcdDevice | What binds it on Windows | +| --- | --- | --- | --- | --- | +| `1-1` | NUI Camera (depth + color/IR iso IN endpoints `0x82`/`0x81`) | `045E:02AE` | `0x010B` (1414) | the MS Kinect **camera** driver/INF; the stream source `Kinect10.dll` opens | +| `1-2` | NUI Audio (2 interfaces → host reads it as firmware-loaded, skips bootloader) | `045E:02AD` | `0x010B` | the MS Kinect **audio** driver/INF (NUI audio-source enumeration) | +| `1-3` | NUI Motor (tilt/LED/accelerometer) | `045E:02B0` | `0x010B` | the MS Kinect **motor** driver/INF | + +All three must be attached for the NUI runtime to treat the set as a complete Kinect. The MS +driver binds **per device PID**; attaching only the camera leaves an incomplete sensor that +`NuiCreateSensorByIndex` may reject. The Windows attach therefore runs **three** +`usbip attach` calls, one per busid, against the one running server — exactly what the Linux +runbook does with `--busid 1-1 / 1-2 / 1-3`. + +## 4. End-to-end wiring on Windows + +``` + webcam ─► tracker/synth (todos 5/7) ─► core/protocol KinectV1Device (FrameSource) + │ + ▼ + attach/linux UsbipServer (TCP :3240) ◄── runs on Linux host, + (OS-agnostic USB/IP server, already built) a Linux VM/WSL2, or any + ▲ reachable box; it is the + USB/IP wire protocol v1.1.1 over TCP SAME binary for both OSes + │ + ┌──────────────────────────────────────┴───────────────────────────────┐ + │ Windows box │ + │ usbip-win / usbip-win2 VHCI (UDE) driver ── usbip.exe attach ─┐ │ + │ ▼ │ + │ virtual USB tree: 045E:02AE (1-1) 045E:02AD (1-2) 045E:02B0 (1-3) │ + │ │ │ + │ MS Kinect driver (kinect*.inf) binds per PID │ + │ │ │ + │ Kinect10.dll NuiGetSensorCount ≥ 1 ───► DEA / SDK │ + └───────────────────────────────────────────────────────────────────────┘ +``` + +The server can run on the same Windows box only if a Windows-local USB/IP **stub server** is +used; the simplest, already-verified configuration is the `attach/linux` server on a Linux host +or WSL2 instance reachable over TCP, with the Windows VHCI client attaching across the network +(loopback if co-located). Either way the server code is identical. + +## 5. The one real risk: isochronous camera framing (same gap in both lanes, not Windows-specific) + +The Kinect camera's depth/color endpoints are **isochronous IN** (`0x82`/`0x81`, advertised in +`core/protocol/descriptors.cpp`). The USB/IP protocol carries ISO transfers with a trailing +`iso_packet_descriptor` array and a non-`0xffffffff` `number_of_packets` +(kernel spec, `USBIP_CMD_SUBMIT`/`USBIP_RET_SUBMIT`). The shared server today answers each +`CMD_SUBMIT` as a single packet with **no ISO descriptor array modelled** — a documented +simplification in `attach/linux/` (correct for read-only IN endpoints where the client sends no +ISO descriptors, and validated for the Linux `vhci-hcd` client over sockets). + +Whether the Windows `usbip-win` VHCI driver and, above it, the MS Kinect camera driver accept +that simplified ISO framing — or demand true per-ISO-packet descriptors — is **the open question +todo 13 resolves on Windows** (spike-windows.md Step 4c explicitly says to capture, via +Wireshark+USBPcap, every transfer the MS driver initiates that the Linux init did not). If the +MS driver rejects the simplified framing: + +- The fix is to extend the **shared** server's ISO handling (emit `number_of_packets` + `iso_packet_descriptor` entries in `RET_SUBMIT`, split the frame across them). That is a + change in `core/protocol` + `attach/linux/` (todos 8/9), **reused by Windows for free** — not a + Windows-only code path. This todo's Windows artifacts do not change. +- Only if USB/IP itself cannot carry the Kinect ISO streams under the MS driver at all does the + bespoke KMDF/UMDF bus driver (§2 rejected alternative) become necessary; that is the documented + fallback-within-a-fallback and would be re-planned, not silently attempted. + +The **NUI-shim fallback (todo 14, `fallback/windows-nui/`)** is the independent escape hatch if +the device-level Windows path (this todo + todo 13) is impractical for any reason: a clean-room +`Kinect10.dll` injecting skeleton/depth directly, which proves playability (IS-3/IS-4) but — per +the plan — does **not** satisfy IS-1/IS-2. The README documents when to drop to it. + +## 6. What "done" means for this todo in each environment + +| Claim | Where provable | Status | +| --- | --- | --- | +| Reusable OS-agnostic USB/IP server exists and is socket-verified | Linux (this lane + `attach/linux`) | **DONE** (see `attach/linux/`) | +| Windows attach method, topology, binding, signing fully specified | here (docs + scripts + README) | **DONE** (this deliverable) | +| `usbip-win` VHCI driver installs; three busids attach; Device Manager shows the sensor under the MS Kinect driver; `NuiGetSensorCount ≥ 1` | **user's Windows box** | **`[~]` BLOCKED** — no Windows/WDK here | +| DEA plays via the device path | user's Windows box (todo 13) | out of scope for todo 12 | + +Everything in the first two rows is delivered in this directory. Everything in the last two rows +is the user's Windows-box work, scripted and documented so it is mechanical, not open-ended. diff --git a/attach/windows/scripts/Attach-Kinect.ps1 b/attach/windows/scripts/Attach-Kinect.ps1 new file mode 100644 index 0000000..b88ae9d --- /dev/null +++ b/attach/windows/scripts/Attach-Kinect.ps1 @@ -0,0 +1,75 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Attach the three virtual Kinect v1 busids (camera/audio/motor) from the attach/linux + UsbipServer into this Windows box's USB tree via the installed usbip-win VHCI client. + +.DESCRIPTION + [~] BLOCKED in the kinect build environment (no Windows). RUN THIS ON THE USER'S WINDOWS BOX, + elevated, AFTER: + 1. Install-UsbIpWin.ps1 installed a VHCI client (and, for the legacy client, Enable-TestSigning + + reboot). + 2. The OS-agnostic server is running on the host named in config\kinect-usbip.json: + kinect_attach serve --port 3240 (built from attach/linux on a Linux host/VM/WSL2) + + It reads config\kinect-usbip.json for the server host/port and the busid list, then runs one + 'usbip.exe attach -r -b ' per device. All three are required for the MS NUI + runtime to see a complete sensor. + +.PARAMETER UsbipExe + Path to usbip.exe. Defaults to 'usbip.exe' (on PATH after usbip-win2 install) or, if absent, + "C:\Program Files\USBip\usbip.exe". + +.PARAMETER ConfigPath + Path to kinect-usbip.json. Defaults to ..\config\kinect-usbip.json relative to this script. + +.PARAMETER ServerHost + Override the server host from the config (e.g. a Linux VM IP). ($Host is a PowerShell + automatic variable, so the parameter is named ServerHost.) +#> +[CmdletBinding()] +param( + [string]$UsbipExe, + [string]$ConfigPath, + [string]$ServerHost +) + +$ErrorActionPreference = 'Stop' + +function Resolve-Usbip([string]$explicit) { + if ($explicit) { return $explicit } + $onPath = Get-Command usbip.exe -ErrorAction SilentlyContinue + if ($onPath) { return $onPath.Source } + $default = Join-Path ${env:ProgramFiles} 'USBip\usbip.exe' + if (Test-Path $default) { return $default } + throw 'usbip.exe not found. Install a client with Install-UsbIpWin.ps1 or pass -UsbipExe.' +} + +if (-not $ConfigPath) { + $ConfigPath = Join-Path $PSScriptRoot '..\config\kinect-usbip.json' +} +if (-not (Test-Path $ConfigPath)) { throw "Config not found: $ConfigPath" } + +$config = Get-Content -Raw -Path $ConfigPath | ConvertFrom-Json +$targetHost = if ($ServerHost) { $ServerHost } else { $config.server.host } +$usbip = Resolve-Usbip $UsbipExe + +Write-Host "=== Attaching virtual Kinect v1 from $targetHost (server port $($config.server.port)) ===" -ForegroundColor Cyan +Write-Host "usbip client: $usbip" + +$failures = @() +foreach ($dev in $config.devices) { + Write-Host ("Attaching {0,-6} busid {1} ({2}:{3})" -f $dev.function, $dev.busid, $dev.vid, $dev.pid) -ForegroundColor Green + & $usbip attach -r $targetHost -b $dev.busid + if ($LASTEXITCODE -ne 0) { + $failures += $dev.busid + Write-Warning "attach failed for busid $($dev.busid) (function $($dev.function))." + } +} + +if ($failures.Count -gt 0) { + Write-Warning "Attach incomplete. Failed busids: $($failures -join ', '). Check: server running? firewall allows TCP $($config.server.port)? VHCI driver loaded (Device Manager)?" + exit 1 +} + +Write-Host 'All three Kinect busids attached. Run Verify-KinectDevice.ps1 to confirm the MS Kinect driver bound.' -ForegroundColor Cyan diff --git a/attach/windows/scripts/Detach-Kinect.ps1 b/attach/windows/scripts/Detach-Kinect.ps1 new file mode 100644 index 0000000..4935467 --- /dev/null +++ b/attach/windows/scripts/Detach-Kinect.ps1 @@ -0,0 +1,67 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Detach the virtual Kinect v1 busids from this Windows box's USB tree. + +.DESCRIPTION + [~] BLOCKED in the kinect build environment (no Windows). RUN THIS ON THE USER'S WINDOWS BOX, + elevated. 'usbip.exe detach' takes the VHCI PORT number, not the busid, so this lists the + attached ports first and detaches each (or pass -Port to detach one, or -All). + + Graceful removal: detaching while an app (DEA / a Kinect SDK sample) holds the sensor should + surface a clean device-removal to that app (sensor-unplugged), not a crash -- this is plan + todo 12's documented failure scenario to verify on Windows. + +.PARAMETER UsbipExe + Path to usbip.exe. Defaults as in Attach-Kinect.ps1. + +.PARAMETER Port + Detach a single VHCI port. + +.PARAMETER All + Detach every attached port. +#> +[CmdletBinding()] +param( + [string]$UsbipExe, + [int]$Port = -1, + [switch]$All +) + +$ErrorActionPreference = 'Stop' + +function Resolve-Usbip([string]$explicit) { + if ($explicit) { return $explicit } + $onPath = Get-Command usbip.exe -ErrorAction SilentlyContinue + if ($onPath) { return $onPath.Source } + $default = Join-Path ${env:ProgramFiles} 'USBip\usbip.exe' + if (Test-Path $default) { return $default } + throw 'usbip.exe not found. Pass -UsbipExe.' +} + +$usbip = Resolve-Usbip $UsbipExe + +if ($Port -ge 0) { + Write-Host "Detaching VHCI port $Port ..." -ForegroundColor Green + & $usbip detach -p $Port + exit $LASTEXITCODE +} + +if ($All) { + # usbip-win2 supports 'detach -all'; the legacy client needs per-port detach. + Write-Host 'Detaching all attached ports ...' -ForegroundColor Green + & $usbip detach -all + if ($LASTEXITCODE -ne 0) { + Write-Host "'detach -all' unsupported on this client; parsing 'usbip port' and detaching each ..." -ForegroundColor Yellow + $ports = (& $usbip port) | Select-String -Pattern 'Port\s+(\d+)' -AllMatches | + ForEach-Object { $_.Matches } | ForEach-Object { [int]$_.Groups[1].Value } + foreach ($p in $ports) { + Write-Host "Detaching port $p ..." -ForegroundColor Green + & $usbip detach -p $p + } + } + exit 0 +} + +Write-Host "Attached ports (pass -Port to detach one, or -All):" -ForegroundColor Cyan +& $usbip port diff --git a/attach/windows/scripts/Disable-TestSigning.ps1 b/attach/windows/scripts/Disable-TestSigning.ps1 new file mode 100644 index 0000000..3fc36ec --- /dev/null +++ b/attach/windows/scripts/Disable-TestSigning.ps1 @@ -0,0 +1,30 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Turn test-signing back off after you are done with the virtual Kinect (legacy usbip-win path). + +.DESCRIPTION + [~] BLOCKED in the kinect build environment (no Windows). RUN THIS ON THE USER'S WINDOWS BOX, + elevated. + + WARNING: Do NOT run this while the test-signed usbip-win VHCI driver is still installed and in + use. Disabling test-signing with a test-signed driver still bound will stop every USB device + attached through it from working. Detach all Kinect busids (Detach-Kinect.ps1) and uninstall + the VHCI driver ('usbip.exe uninstall') FIRST, then run this and reboot. +#> +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' + +$id = [Security.Principal.WindowsIdentity]::GetCurrent() +$principal = New-Object Security.Principal.WindowsPrincipal($id) +if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + throw 'This script must run in an elevated PowerShell (Run as Administrator).' +} + +Write-Host 'Disabling test-signing: bcdedit /set testsigning off' -ForegroundColor Green +bcdedit.exe /set testsigning off +if ($LASTEXITCODE -ne 0) { throw 'bcdedit /set testsigning off failed.' } + +Write-Host 'Done. Reboot to apply. Re-enable Secure Boot in firmware if you turned it off.' -ForegroundColor Cyan diff --git a/attach/windows/scripts/Enable-TestSigning.ps1 b/attach/windows/scripts/Enable-TestSigning.ps1 new file mode 100644 index 0000000..af4064f --- /dev/null +++ b/attach/windows/scripts/Enable-TestSigning.ps1 @@ -0,0 +1,77 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Enable Windows test-signing and import the usbip-win test certificate so a test-signed VHCI + driver loads. Personal-use only; this weakens driver-signature enforcement. + +.DESCRIPTION + [~] BLOCKED in the kinect build environment (no Windows). RUN THIS ON THE USER'S WINDOWS BOX, + elevated. Needed only for the legacy cezanne usbip-win (test-signed) client. The recommended + usbip-win2 UDE driver is attestation/WHLK-signed and typically needs NONE of this. + + What test-signing is and why it is needed: + Windows x64 refuses to load kernel-mode drivers that are not signed by a certificate chaining + to a Microsoft-trusted root. A self-built / test-signed VHCI driver is signed by a TEST + certificate, not a trusted CA, so Windows blocks it until the machine is put into test-signing + mode AND the test certificate is trusted. Secure Boot enforces the same policy in firmware and + must be OFF for test-signing to take effect. + + SECURITY / SCOPE: this is a personal-use development posture, NOT production. A test-signed + driver is unsigned for trust purposes. Re-enable Secure Boot and disable test-signing when done + (Disable-TestSigning.ps1) -- but NOT while the test-signed VHCI driver is still installed, or + every USB device bound through it stops working. + +.PARAMETER PfxPath + Path to usbip_test.pfx from the usbip-win release (password: usbip). Imported into the LOCAL + COMPUTER "Trusted Root Certification Authorities" and "Trusted Publishers" stores. +#> +[CmdletBinding()] +param( + [string]$PfxPath +) + +$ErrorActionPreference = 'Stop' + +function Assert-Admin { + $id = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = New-Object Security.Principal.WindowsPrincipal($id) + if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + throw 'This script must run in an elevated PowerShell (Run as Administrator).' + } +} + +Assert-Admin + +# 1. Secure Boot must be off for test-signing to take effect. +try { + $secureBoot = Confirm-SecureBootUEFI + if ($secureBoot) { + Write-Warning 'Secure Boot is ON. Test-signing will NOT take effect until you disable Secure Boot in UEFI/BIOS firmware.' + Write-Warning 'Reboot into firmware setup, turn Secure Boot off, then re-run this script.' + } else { + Write-Host 'Secure Boot is off -- good; test-signing can take effect.' -ForegroundColor Green + } +} catch { + Write-Host 'Could not query Secure Boot (legacy BIOS or cmdlet unavailable). If this is a UEFI box, verify Secure Boot is OFF manually.' -ForegroundColor Yellow +} + +# 2. Enable test-signing. +Write-Host 'Enabling test-signing: bcdedit /set testsigning on' -ForegroundColor Green +bcdedit.exe /set testsigning on +if ($LASTEXITCODE -ne 0) { throw 'bcdedit /set testsigning on failed (not elevated, or BitLocker/Secure Boot blocking).' } + +# 3. Import the test certificate into the LOCAL COMPUTER stores (both are required). +if ($PfxPath) { + if (-not (Test-Path $PfxPath)) { throw "PFX not found: $PfxPath" } + $pwd = ConvertTo-SecureString -String 'usbip' -AsPlainText -Force + Write-Host "Importing $PfxPath into LocalMachine\Root and LocalMachine\TrustedPublisher ..." -ForegroundColor Green + Import-PfxCertificate -FilePath $PfxPath -CertStoreLocation 'Cert:\LocalMachine\Root' -Password $pwd | Out-Null + Import-PfxCertificate -FilePath $PfxPath -CertStoreLocation 'Cert:\LocalMachine\TrustedPublisher' -Password $pwd | Out-Null + Write-Host 'Test certificate imported into both required local-computer stores.' -ForegroundColor Green +} else { + Write-Host 'No -PfxPath given. For the legacy usbip-win client, import usbip_test.pfx (password: usbip) into BOTH' -ForegroundColor Yellow + Write-Host 'LocalMachine "Trusted Root Certification Authorities" AND "Trusted Publishers" before installing the driver.' -ForegroundColor Yellow +} + +Write-Host '' +Write-Host 'REBOOT NOW for test-signing to take effect. A "Test Mode" watermark will appear on the desktop -- expected.' -ForegroundColor Cyan diff --git a/attach/windows/scripts/Install-UsbIpWin.ps1 b/attach/windows/scripts/Install-UsbIpWin.ps1 new file mode 100644 index 0000000..3ca24a6 --- /dev/null +++ b/attach/windows/scripts/Install-UsbIpWin.ps1 @@ -0,0 +1,108 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Install a USB/IP VHCI client on this Windows box so it can attach the virtual Kinect v1 + exported by the OS-agnostic attach/linux UsbipServer. Personal-use / test-signing only. + +.DESCRIPTION + [~] BLOCKED in the kinect build environment (no Windows, no WDK). RUN THIS ON THE USER'S + WINDOWS BOX, from an elevated PowerShell (Run as Administrator). + + Two supported clients (pick one with -Client): + * usbip-win2 (vadimgrn) -- RECOMMENDED. UDE driver, attestation/WHLK-signed, ships an MSI + installer. May not require test-signing at all. Download the MSI from + https://github.com/vadimgrn/usbip-win2/releases and pass its path with -InstallerPath. + * usbip-win (cezanne) -- legacy. Test-signed VHCI driver; REQUIRES test-signing ON and the + bundled test certificate installed (see Enable-TestSigning.ps1). Download the release zip + from https://github.com/cezanne/usbip-win/releases and extract it; pass the folder with + -PackageDir. + + This script does NOT build either driver (that needs the WDK). It installs a prebuilt release. + +.PARAMETER Client + 'usbip-win2' (default) or 'usbip-win'. + +.PARAMETER InstallerPath + usbip-win2 only: path to the downloaded USBip MSI. + +.PARAMETER PackageDir + usbip-win only: folder containing the extracted release + (usbip.exe, usbip_vhci_ude.inf/.sys/.cat or usbip_vhci.inf/.sys/.cat, usbip_test.pfx). + +.EXAMPLE + # Recommended, signed driver: + .\Install-UsbIpWin.ps1 -Client usbip-win2 -InstallerPath .\USBip-0.9.x.x64.msi + +.EXAMPLE + # Legacy, test-signed driver (run Enable-TestSigning.ps1 first): + .\Install-UsbIpWin.ps1 -Client usbip-win -PackageDir .\usbip-win-0.3.6-dev +#> +[CmdletBinding()] +param( + [ValidateSet('usbip-win2', 'usbip-win')] + [string]$Client = 'usbip-win2', + [string]$InstallerPath, + [string]$PackageDir +) + +$ErrorActionPreference = 'Stop' + +function Assert-Admin { + $id = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = New-Object Security.Principal.WindowsPrincipal($id) + if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + throw 'This script must run in an elevated PowerShell (Run as Administrator).' + } +} + +Assert-Admin + +Write-Host '=== Virtual Kinect v1 -- USB/IP VHCI client install ===' -ForegroundColor Cyan +Write-Host 'Create a System Restore Point first (installing a bus/host-controller driver restarts USB hubs).' -ForegroundColor Yellow + +switch ($Client) { + 'usbip-win2' { + if (-not $InstallerPath -or -not (Test-Path $InstallerPath)) { + throw "usbip-win2 needs -InstallerPath . Download it from https://github.com/vadimgrn/usbip-win2/releases" + } + Write-Host "Installing usbip-win2 from $InstallerPath ..." -ForegroundColor Green + $proc = Start-Process msiexec.exe -ArgumentList @('/i', "`"$InstallerPath`"", '/passive', '/norestart') -Wait -PassThru + if ($proc.ExitCode -ne 0 -and $proc.ExitCode -ne 3010) { + throw "msiexec returned $($proc.ExitCode)." + } + Write-Host 'usbip-win2 installed. usbip.exe is on PATH under "C:\Program Files\USBip".' -ForegroundColor Green + Write-Host 'If its UDE driver is attestation-signed, test-signing is NOT required. If Windows still refuses to load it,' + Write-Host 'run Enable-TestSigning.ps1 and reboot. Do NOT disable test-signing while a test-signed VHCI driver is installed.' + } + 'usbip-win' { + if (-not $PackageDir -or -not (Test-Path $PackageDir)) { + throw "usbip-win needs -PackageDir . Download from https://github.com/cezanne/usbip-win/releases" + } + $usbip = Join-Path $PackageDir 'usbip.exe' + if (-not (Test-Path $usbip)) { throw "usbip.exe not found in $PackageDir." } + + $udeInf = Join-Path $PackageDir 'usbip_vhci_ude.inf' + $wdmInf = Join-Path $PackageDir 'usbip_vhci.inf' + Write-Host 'Reminder: Enable-TestSigning.ps1 must have been run + rebooted, and usbip_test.pfx imported,' -ForegroundColor Yellow + Write-Host 'into BOTH "Trusted Root Certification Authorities" AND "Trusted Publishers" of the LOCAL COMPUTER store.' -ForegroundColor Yellow + + Write-Host "Installing the usbip-win VHCI driver via '$usbip install' ..." -ForegroundColor Green + & $usbip install + if ($LASTEXITCODE -ne 0) { + # Fall back to manual pnputil add-driver (UDE first, then WDM). + if (Test-Path $udeInf) { + Write-Host 'usbip install failed; adding usbip_vhci_ude.inf via pnputil ...' -ForegroundColor Yellow + pnputil /add-driver $udeInf /install + } elseif (Test-Path $wdmInf) { + Write-Host 'usbip install failed; adding usbip_vhci.inf via pnputil ...' -ForegroundColor Yellow + pnputil /add-driver $wdmInf /install + } else { + throw 'No usbip_vhci_ude.inf or usbip_vhci.inf found to install.' + } + Write-Host 'If the device did not appear, finish via Device Manager > Action > Add legacy hardware > Have Disk > choose this folder.' + } + Write-Host "usbip-win VHCI client installed. Use '$usbip' for attach/detach." -ForegroundColor Green + } +} + +Write-Host 'Next: start the attach/linux server on the host, then run Attach-Kinect.ps1.' -ForegroundColor Cyan diff --git a/attach/windows/scripts/Verify-KinectDevice.ps1 b/attach/windows/scripts/Verify-KinectDevice.ps1 new file mode 100644 index 0000000..9bfe78d --- /dev/null +++ b/attach/windows/scripts/Verify-KinectDevice.ps1 @@ -0,0 +1,70 @@ +#requires -Version 5.1 +<# +.SYNOPSIS + Verify the attached virtual Kinect v1 enumerated and bound to the real MS Kinect driver. + +.DESCRIPTION + [~] BLOCKED in the kinect build environment (no Windows). RUN THIS ON THE USER'S WINDOWS BOX, + elevated, AFTER Attach-Kinect.ps1. It checks, via PnP, that the three Kinect PIDs are present, + bound (no yellow-bang / Problem code 0), and reports the binding driver/INF. It does NOT call + the NUI API (that is C++); it tells you what to confirm with the Kinect SDK sample. + + Pass criteria for plan todo 12 (acceptance, human-assisted on Windows): + * Device Manager shows the Kinect under the MS Kinect driver (this script's PnP check), AND + * the Kinect SDK's KinectExplorer / SkeletonBasics sample enumerates the sensor + (NuiGetSensorCount >= 1, NuiCreateSensorByIndex(0,...) succeeds) -- run it manually. +#> +[CmdletBinding()] +param() + +$ErrorActionPreference = 'Stop' + +# The three real Kinect v1 sibling PIDs (must match config\kinect-usbip.json / core/protocol). +$targets = @( + @{ Function = 'camera'; Vid = '045E'; Pid = '02AE' }, + @{ Function = 'audio'; Vid = '045E'; Pid = '02AD' }, + @{ Function = 'motor'; Vid = '045E'; Pid = '02B0' } +) + +Write-Host '=== Virtual Kinect v1 -- PnP verification ===' -ForegroundColor Cyan + +$allBound = $true +foreach ($t in $targets) { + $hwidFrag = "VID_$($t.Vid)&PID_$($t.Pid)" + $devs = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | + Where-Object { $_.InstanceId -match $hwidFrag } + + if (-not $devs) { + Write-Warning ("{0,-6} {1}: NOT PRESENT. Did Attach-Kinect.ps1 attach busid for this function?" -f $t.Function, $hwidFrag) + $allBound = $false + continue + } + + foreach ($d in $devs) { + $driver = (Get-PnpDeviceProperty -InstanceId $d.InstanceId -KeyName 'DEVPKEY_Device_DriverInfPath' -ErrorAction SilentlyContinue).Data + $service = (Get-PnpDeviceProperty -InstanceId $d.InstanceId -KeyName 'DEVPKEY_Device_Service' -ErrorAction SilentlyContinue).Data + $problem = (Get-PnpDeviceProperty -InstanceId $d.InstanceId -KeyName 'DEVPKEY_Device_ProblemCode' -ErrorAction SilentlyContinue).Data + $ok = ($d.Status -eq 'OK') -and (-not $problem -or $problem -eq 0) + $color = if ($ok) { 'Green' } else { 'Yellow' } + Write-Host ("{0,-6} {1}: status={2} problem={3} inf={4} service={5}" -f ` + $t.Function, $hwidFrag, $d.Status, $problem, $driver, $service) -ForegroundColor $color + if (-not $ok) { + $allBound = $false + Write-Warning " -> not cleanly bound. If service/INF is 'usbip*' the VHCI stub bound it but the MS Kinect driver did not match -- check the device descriptors / that the real Kinect 1.8 runtime+driver are installed." + } + } +} + +Write-Host '' +if ($allBound) { + Write-Host 'All three Kinect sibling devices present and bound (no Problem code).' -ForegroundColor Green + Write-Host 'Confirm the INF above is the Microsoft Kinect driver (kinect*.inf), NOT a generic/usbip stub.' +} else { + Write-Warning 'One or more Kinect devices missing or not cleanly bound -- see warnings above.' +} + +Write-Host '' +Write-Host 'Now confirm the NUI runtime enumerates it:' -ForegroundColor Cyan +Write-Host ' * Launch KinectExplorer-D2D (Kinect Developer Toolkit 1.8): the sensor should appear.' +Write-Host ' * Or run SkeletonBasics-D2D: it should open the sensor (streams may be empty until todo 13 serves depth).' +Write-Host ' * Capture a Device Manager screenshot + the KinectExplorer window to .omo\evidence\task-12-webcam-kinect-emulator.*' diff --git a/fallback/windows-nui/CMakeLists.txt b/fallback/windows-nui/CMakeLists.txt new file mode 100644 index 0000000..abb7d8d --- /dev/null +++ b/fallback/windows-nui/CMakeLists.txt @@ -0,0 +1,44 @@ +cmake_minimum_required(VERSION 3.16) +project(kinect_virtual_nui_shim CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +set(CORE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../core") + +add_library(kinect10 SHARED + "${CMAKE_CURRENT_SOURCE_DIR}/src/exports.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/src/sensor.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/src/sensor_com.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/src/frame_source.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/src/frame_texture.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/src/coordmap.cpp" + "${CORE_DIR}/mapping/mapping.cpp" + "${CORE_DIR}/synth/synth.cpp" + "${CORE_DIR}/synth/mask_stabilizer.cpp" + "${CORE_DIR}/contract/contract.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Kinect10.def" +) + +set_target_properties(kinect10 PROPERTIES + OUTPUT_NAME "Kinect10" + PREFIX "" +) + +target_include_directories(kinect10 PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/include" + "${CMAKE_CURRENT_SOURCE_DIR}/src" + "${CORE_DIR}" +) + +target_compile_options(kinect10 PRIVATE -O2 -Wall -Wextra) + +target_link_options(kinect10 PRIVATE + -static + -static-libgcc + -static-libstdc++ + -Wl,--enable-stdcall-fixup + -Wl,--kill-at +) + +target_link_libraries(kinect10 PRIVATE ole32 oleaut32 uuid) diff --git a/fallback/windows-nui/Kinect10.def b/fallback/windows-nui/Kinect10.def new file mode 100644 index 0000000..2363239 --- /dev/null +++ b/fallback/windows-nui/Kinect10.def @@ -0,0 +1,23 @@ +LIBRARY Kinect10 +EXPORTS + NuiGetSensorCount + NuiCreateSensorByIndex + NuiCreateSensorById + NuiInitialize + NuiShutdown + NuiSetDeviceStatusCallback + NuiSkeletonTrackingEnable + NuiSkeletonTrackingDisable + NuiSkeletonGetNextFrame + NuiSkeletonSetTrackedSkeletons + NuiTransformSmooth + NuiTransformDepthImageToSkeleton + NuiImageStreamOpen + NuiImageStreamGetNextFrame + NuiImageStreamReleaseFrame + NuiImageStreamSetImageFrameFlags + NuiImageStreamGetImageFrameFlags + NuiImageGetColorPixelCoordinatesFromDepthPixel + NuiCameraElevationSetAngle + NuiCameraElevationGetAngle + NuiSetFrameEndEvent diff --git a/fallback/windows-nui/README.md b/fallback/windows-nui/README.md index e4fc31b..3067f08 100644 --- a/fallback/windows-nui/README.md +++ b/fallback/windows-nui/README.md @@ -1,6 +1,147 @@ # fallback/windows-nui/ — clean-room Kinect10.dll NUI shim (todo 14) -A clean-room drop-in `Kinect10.dll` implementing the NUI surface DEA imports, injecting -skeleton (`core/mapping`) + depth/color (`core/synth`) directly on the ~30Hz event model. -**Clean-room firewall: derived solely from the public NuiApi.h + spike-4's observed -import list — never from KinectFaker's GPLv3 source.** Placeholder until todo 14. +A clean-room drop-in `Kinect10.dll` that implements the Kinect for Windows 1.8 +NUI export surface a Kinect v1 app (DanceEvolution Arcade first) imports, sourcing +skeleton and depth/color directly from the shared core engine instead of a real +sensor. It is the library-layer Windows fallback (plan GAP-6); the device-level +USB path (todos 8/9/12) is the primary route, and this shim is the independent +surface that proves playability (IS-3/IS-4) by direct injection into the real MS +NUI runtime's consumer — i.e. it feeds the game, not the host skeletonizer. + +## Clean-room firewall + +Every struct, enum value, packing rule, COM vtable, and exported-function +signature in `include/nui_abi.h` and `include/nui_interfaces.h` is derived SOLELY +from public Microsoft Kinect SDK 1.8 header knowledge (`NuiApi.h`, +`NuiSkeleton.h`, `NuiImageCamera.h`, `NuiSensor.h`) as distilled into +`.omo/design/nui-contracts.md`. **No GPLv3 third-party source (e.g. KinectFaker) +was read or copied.** These declarations are ABI/interoperability facts required +for a drop-in replacement; all synthesis logic is the shared core +(`core/mapping`, `core/synth`) reused unmodified. + +## Architecture + +``` + tracker (Python, todo 5) Kinect10.dll shim (this module) game + MediaPipe → core/mapping+synth ┌─────────────────────────────────┐ (DEA / SDK sample) + → FrameContract shared memory ──────────►│ FrameSource (seqlock reader) │ + (core/contract/contract.h) │ │ │ + │ producer thread @ ~30 Hz │ + │ core/mapping → NUI_SKELETON_* │◄── NuiSkeletonGetNextFrame + │ core/synth → depth/color/IR │◄── NuiImageStream* + │ SetEvent(app skeleton/image ev) │ + └─────────────────────────────────┘ +``` + +- **Single producer, newest-wins.** The shim is a *consumer* of the exact + `FrameContract` triple buffer the tracker publishes (`core/contract`), read with + the same seqlock protocol (`src/frame_source.cpp`). The USB emitter and this + shim are two consumers of one producer, so skeleton/depth stay identical across + both Windows paths. +- **~30 Hz event model** (`src/sensor.cpp`, nui-contracts §3). One producer thread + ticks on a steady `QueryPerformanceCounter` clock, converts the latest + `FrameData` into a `NUI_SKELETON_FRAME` plus per-stream `INuiFrameTexture`s under + a `CRITICAL_SECTION`, then signals the app's manual-reset event handles. + `NuiSkeletonGetNextFrame` / `NuiImageStreamGetNextFrame` are fast copies / + pointer hand-offs that wait on those events with the caller's timeout, honoring + `E_NUI_FRAME_NO_DATA` / `SUPPRESS_NO_FRAME_DATA` / `TITLE_SETS_TRACKED_SKELETONS` + and resetting the skeleton event once the newest frame is delivered. +- **Core reuse** (compiled into the DLL): `core/mapping` drives `NuiTransformSmooth` + (per-skeleton, per-joint Holt filters keyed by tracking id) and + `NuiTransformDepthImageToSkeleton`; `core/synth` provides the packed-depth + helpers, `passthrough_color`, and `synthesize_infrared` used to fill the image + streams. `core/contract` is the shared-memory layout. +- **COM objects.** `INuiSensor` (`src/sensor_com.cpp`) returned by + `NuiCreateSensorByIndex/ById` delegates every method to the same + `VirtualKinectSensor` the flat exports drive. `INuiFrameTexture` + (`src/frame_texture.cpp`) implements `LockRect`/`GetLevelDesc`/`BufferLen`/ + `Pitch`/`UnlockRect` with pitch and size matching the reported `NUI_SURFACE_DESC` + (packed depth → `width*2`, BGRA color → `width*4`). Unimplemented optional + methods (audio DMO, coordinate-mapper interface) return `E_NOTIMPL`, never crash. + +## Integration seam + +The shim opens a named shared-memory region (`OpenFileMappingW`) named by the +environment variable **`KINECT_SHIM_SHM`** (default `kinect_virtual_frames`). The +tracker must publish its `FrameContractPublisher` region under the same name on +Windows. When the region is absent or empty, the producer still ticks at 30 Hz and +publishes a no-player frame (`dwTrackingID = 0`, zeroed depth/color), so the host +app never blocks and `NuiSkeletonGetNextFrame` reports no tracked skeleton rather +than hanging. + +## Exported NUI surface (21 functions, undecorated) + +`NuiGetSensorCount`, `NuiCreateSensorByIndex`, `NuiCreateSensorById`, +`NuiInitialize`, `NuiShutdown`, `NuiSetDeviceStatusCallback`, +`NuiSkeletonTrackingEnable`, `NuiSkeletonTrackingDisable`, +`NuiSkeletonGetNextFrame`, `NuiSkeletonSetTrackedSkeletons`, `NuiTransformSmooth`, +`NuiTransformDepthImageToSkeleton`, `NuiImageStreamOpen`, +`NuiImageStreamGetNextFrame`, `NuiImageStreamReleaseFrame`, +`NuiImageStreamSetImageFrameFlags`, `NuiImageStreamGetImageFrameFlags`, +`NuiImageGetColorPixelCoordinatesFromDepthPixel`, `NuiCameraElevationSetAngle`, +`NuiCameraElevationGetAngle`, `NuiSetFrameEndEvent`. + +This is a **superset** of the minimum DEA imports named in the plan; the exact DEA +import list comes from spike todo 4 (`dumpbin /imports gamekdm.dll`), which is +Windows-gated. Over-exporting is safe (a drop-in must export *no fewer* than the +game imports); if the spike reveals an additional symbol, add it to `Kinect10.def` +and a stub in `src/exports.cpp`. + +### Decoration + +`__stdcall`/`WINAPI` is used throughout, but the export *names* are undecorated +(`NuiInitialize`, not `_NuiInitialize@4`) to match the real `Kinect10.dll` that the +game's import table binds to. This is achieved with `Kinect10.def` (plain names) + +`-Wl,--enable-stdcall-fixup,--kill-at`. On x64 there is no `@N` decoration; the +same `.def` drives both arches. + +## Cross-build (on this Linux/WSL2 box, no Windows needed) + +Provisioned mingw-w64 cross-compilers live at `$HOME/.local/mingw-root/usr/bin` +(`i686-w64-mingw32-g++-posix` for 32-bit — DEA's likely arch — and +`x86_64-w64-mingw32-g++-win32` for 64-bit). Build both DLLs and audit exports: + +```sh +cd fallback/windows-nui +bash build.sh # builds build/Kinect10-x86.dll and build/Kinect10-x64.dll +``` + +`build.sh` cross-compiles the six shim sources plus the four reused core sources +into each DLL, links `ole32`/`oleaut32`/`uuid` statically, and dumps the export +name table for both arches. Override `MINGW_BIN`, `CXX32`, `CXX64` to retarget. + +Equivalent CMake path (authoritative MSVC build is run on the user's Windows box): + +```sh +cmake -S . -B build-x86 -DCMAKE_TOOLCHAIN_FILE=toolchain-mingw-x86.cmake +cmake --build build-x86 +cmake -S . -B build-x64 -DCMAKE_TOOLCHAIN_FILE=toolchain-mingw-x64.cmake +cmake --build build-x64 +``` + +### Export audit (what was verified here) + +Both DLLs are real PE images (`file`: `PE32 … Intel i386` and +`PE32+ … x86-64`), and the export name table (`objdump -p … | grep '+base['`) +lists all 21 symbols above, undecorated, on **both** arches — 0 missing, 0 extra, +0 decorated. Full output: `.omo/evidence/task-14-webcam-kinect-emulator.log`. + +## [~] Runtime gate — BLOCKED, deferred to the user's Windows box + +This Linux/WSL2 host cannot *run* a Kinect v1 app or the MS NUI runtime, so the +following are **not** verified here and are the acceptance surface for todo 13/F5 +on Windows: + +- **In-game / runtime pass.** Placing `Kinect10.dll` beside a Kinect SDK 1.8 + sample (SkeletonBasics-D2D) or `gamekdm.dll` and confirming it tracks without a + sensor. Unverified here. +- **INuiSensor vtable byte-order.** The flat C exports are the primary, Linux- + auditable surface and most 1.8 titles bind them. The large `INuiSensor` vtable's + exact method order can only be byte-verified against a real app on Windows; it is + reproduced from public `NuiSensor.h` ordering and both COM and flat paths share + one implementation. +- **Spike-4 import reconciliation.** Confirm the exported set covers DEA's actual + `Kinect10.dll` imports and the requested stream resolution/bitness. +- **Tracker↔shim shared-memory name on Windows.** Python `multiprocessing` + shared-memory naming must be wired to `KINECT_SHIM_SHM`; verify end to end on + Windows. diff --git a/fallback/windows-nui/build.sh b/fallback/windows-nui/build.sh new file mode 100755 index 0000000..24420ce --- /dev/null +++ b/fallback/windows-nui/build.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CORE="$(cd "${HERE}/../../core" && pwd)" +OUT="${HERE}/build" +MINGW_BIN="${MINGW_BIN:-$HOME/.local/mingw-root/usr/bin}" +export PATH="${MINGW_BIN}:${PATH}" + +CXX64="${CXX64:-x86_64-w64-mingw32-g++-win32}" +CXX32="${CXX32:-i686-w64-mingw32-g++-posix}" +OBJDUMP64="${OBJDUMP64:-x86_64-w64-mingw32-objdump}" +OBJDUMP32="${OBJDUMP32:-i686-w64-mingw32-objdump}" + +SRCS=( + "${HERE}/src/exports.cpp" + "${HERE}/src/sensor.cpp" + "${HERE}/src/sensor_com.cpp" + "${HERE}/src/frame_source.cpp" + "${HERE}/src/frame_texture.cpp" + "${HERE}/src/coordmap.cpp" + "${CORE}/mapping/mapping.cpp" + "${CORE}/synth/synth.cpp" + "${CORE}/synth/mask_stabilizer.cpp" + "${CORE}/contract/contract.cpp" +) + +INCLUDES=(-I"${HERE}/include" -I"${HERE}/src" -I"${CORE}") +COMMON_FLAGS=(-std=c++17 -O2 -Wall -Wextra -shared -static -static-libgcc -static-libstdc++) +LINK_FLAGS=(-Wl,--enable-stdcall-fixup -Wl,--kill-at -lole32 -loleaut32 -luuid) + +mkdir -p "${OUT}" + +build_one() { + local cxx="$1" arch="$2" + local dll="${OUT}/Kinect10-${arch}.dll" + echo "=== Building ${arch}: ${cxx} ===" + "${cxx}" "${COMMON_FLAGS[@]}" "${INCLUDES[@]}" \ + "${SRCS[@]}" "${HERE}/Kinect10.def" \ + -o "${dll}" "${LINK_FLAGS[@]}" + echo "built ${dll}" +} + +audit_one() { + local objdump="$1" arch="$2" + local dll="${OUT}/Kinect10-${arch}.dll" + echo "=== ${arch} file type ===" + file "${dll}" + echo "=== ${arch} export name table ===" + "${objdump}" -p "${dll}" | grep -E '\+base\[' | grep -oE 'Nui[A-Za-z]+' | sort | nl +} + +build_one "${CXX32}" "x86" +build_one "${CXX64}" "x64" +audit_one "${OBJDUMP32}" "x86" +audit_one "${OBJDUMP64}" "x64" +echo "=== DONE ===" diff --git a/fallback/windows-nui/include/nui_abi.h b/fallback/windows-nui/include/nui_abi.h new file mode 100644 index 0000000..d2a4cd2 --- /dev/null +++ b/fallback/windows-nui/include/nui_abi.h @@ -0,0 +1,239 @@ +#ifndef FALLBACK_WINDOWS_NUI_NUI_ABI_H +#define FALLBACK_WINDOWS_NUI_NUI_ABI_H + +// Clean-room declaration of the Kinect for Windows 1.8 NUI ABI surface. +// +// CLEAN-ROOM PROVENANCE: every type, enum value, struct field order, and packing +// rule below is reproduced SOLELY from public Microsoft Kinect for Windows SDK 1.8 +// header knowledge (NuiApi.h / NuiSkeleton.h / NuiImageCamera.h / NuiSensor.h) as +// distilled into .omo/design/nui-contracts.md. No GPL-licensed third-party source +// (e.g. KinectFaker) was read or copied. These declarations are ABI/interoperability +// facts required for a drop-in replacement of the real Kinect10.dll; all synthesis +// logic lives in the shared core (core/mapping, core/synth) and the src/ files here. +// +// ALIGNMENT: the real NUI headers use DEFAULT (natural) struct alignment, NOT +// #pragma pack(1). MinGW-w64 targets the Microsoft x86/x64 struct-layout ABI, so +// leaving these structs at default alignment reproduces the MSVC layout bit-for-bit. +// (This is distinct from core/contract/contract.h, which is pack(1) on purpose for +// the cross-language IPC region.) + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// NUI Vector4: homogeneous 3D point, x/y/z metres, w normally 1.0 (NuiSkeleton.h). +typedef struct _Vector4 { + FLOAT x; + FLOAT y; + FLOAT z; + FLOAT w; +} Vector4; + +#define NUI_SKELETON_COUNT 6 +#define NUI_SKELETON_POSITION_COUNT 20 +#define NUI_SKELETON_MAX_TRACKED_COUNT 2 + +// Packed depth word bit layout (NuiImageCamera.h), nui-contracts.md §2.2. +#define NUI_IMAGE_PLAYER_INDEX_SHIFT 3 +#define NUI_IMAGE_PLAYER_INDEX_MASK ((1 << NUI_IMAGE_PLAYER_INDEX_SHIFT) - 1) +#define NUI_IMAGE_DEPTH_MINIMUM (800 << NUI_IMAGE_PLAYER_INDEX_SHIFT) +#define NUI_IMAGE_DEPTH_MAXIMUM (4000 << NUI_IMAGE_PLAYER_INDEX_SHIFT) +#define NUI_IMAGE_DEPTH_NO_VALUE 0 + +// NuiInitialize subsystem flags (NuiApi.h). +#define NUI_INITIALIZE_FLAG_USES_AUDIO 0x10000000 +#define NUI_INITIALIZE_FLAG_USES_DEPTH_AND_PLAYER_INDEX 0x00000001 +#define NUI_INITIALIZE_FLAG_USES_COLOR 0x00000002 +#define NUI_INITIALIZE_FLAG_USES_SKELETON 0x00000008 +#define NUI_INITIALIZE_FLAG_USES_DEPTH 0x00000020 + +// NuiSkeletonTrackingEnable flags (NuiApi.h). +#define NUI_SKELETON_TRACKING_FLAG_SUPPRESS_NO_FRAME_DATA 0x00000001 +#define NUI_SKELETON_TRACKING_FLAG_TITLE_SETS_TRACKED_SKELETONS 0x00000002 +#define NUI_SKELETON_TRACKING_FLAG_ENABLE_SEATED_SUPPORT 0x00000004 +#define NUI_SKELETON_TRACKING_FLAG_ENABLE_IN_NEAR_RANGE 0x00000008 + +// NUI_SKELETON_FRAME.dwFlags / per-skeleton quality flags (NuiSkeleton.h). +#define NUI_SKELETON_FRAME_FLAG_SEATED_SUPPORT_ENABLED 0x00000001 +#define NUI_SKELETON_QUALITY_CLIPPED_RIGHT 0x00000001 +#define NUI_SKELETON_QUALITY_CLIPPED_LEFT 0x00000002 +#define NUI_SKELETON_QUALITY_CLIPPED_TOP 0x00000004 +#define NUI_SKELETON_QUALITY_CLIPPED_BOTTOM 0x00000008 + +// HRESULT values the NUI API returns beyond the standard ones (NuiApi.h). +#ifndef E_NUI_FRAME_NO_DATA +#define E_NUI_DEVICE_NOT_CONNECTED ((HRESULT)0x83010001L) +#define E_NUI_DEVICE_NOT_READY ((HRESULT)0x83010002L) +#define E_NUI_ALREADY_INITIALIZED ((HRESULT)0x83010003L) +#define E_NUI_NO_MORE_ITEMS ((HRESULT)0x83010004L) +#define E_NUI_FRAME_NO_DATA ((HRESULT)0x83010005L) +#define E_NUI_STREAM_NOT_ENABLED ((HRESULT)0x83010006L) +#define E_NUI_DATABASE_NOT_FOUND ((HRESULT)0x8301000DL) +#define E_NUI_DATABASE_VERSION_MISMATCH ((HRESULT)0x8301000EL) +#define E_NUI_NOTCONNECTED ((HRESULT)0x83010001L) +#endif + +// NUI_IMAGE_TYPE (NuiImageCamera.h). +typedef enum _NUI_IMAGE_TYPE { + NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX = 0, + NUI_IMAGE_TYPE_COLOR = 1, + NUI_IMAGE_TYPE_COLOR_YUV = 2, + NUI_IMAGE_TYPE_COLOR_RAW_YUV = 3, + NUI_IMAGE_TYPE_DEPTH = 4, + NUI_IMAGE_TYPE_COLOR_INFRARED = 5, + NUI_IMAGE_TYPE_COLOR_RAW_BAYER = 6, +} NUI_IMAGE_TYPE; + +// NUI_IMAGE_RESOLUTION (NuiImageCamera.h). +typedef enum _NUI_IMAGE_RESOLUTION { + NUI_IMAGE_RESOLUTION_INVALID = -1, + NUI_IMAGE_RESOLUTION_80x60 = 0, + NUI_IMAGE_RESOLUTION_320x240 = 1, + NUI_IMAGE_RESOLUTION_640x480 = 2, + NUI_IMAGE_RESOLUTION_1280x960 = 3, +} NUI_IMAGE_RESOLUTION; + +// NUI_IMAGE_DIGITAL_ZOOM (NuiImageCamera.h). +typedef enum _NUI_IMAGE_DIGITAL_ZOOM { + NUI_IMAGE_DIGITAL_ZOOM_1X = 0, +} NUI_IMAGE_DIGITAL_ZOOM; + +// NUI_SKELETON_POSITION_INDEX (NuiSkeleton.h). Values 0..19 in this exact order; +// this order matches core/contract SkeletonFrame.joints[] by construction. +typedef enum _NUI_SKELETON_POSITION_INDEX { + NUI_SKELETON_POSITION_HIP_CENTER = 0, + NUI_SKELETON_POSITION_SPINE = 1, + NUI_SKELETON_POSITION_SHOULDER_CENTER = 2, + NUI_SKELETON_POSITION_HEAD = 3, + NUI_SKELETON_POSITION_SHOULDER_LEFT = 4, + NUI_SKELETON_POSITION_ELBOW_LEFT = 5, + NUI_SKELETON_POSITION_WRIST_LEFT = 6, + NUI_SKELETON_POSITION_HAND_LEFT = 7, + NUI_SKELETON_POSITION_SHOULDER_RIGHT = 8, + NUI_SKELETON_POSITION_ELBOW_RIGHT = 9, + NUI_SKELETON_POSITION_WRIST_RIGHT = 10, + NUI_SKELETON_POSITION_HAND_RIGHT = 11, + NUI_SKELETON_POSITION_HIP_LEFT = 12, + NUI_SKELETON_POSITION_KNEE_LEFT = 13, + NUI_SKELETON_POSITION_ANKLE_LEFT = 14, + NUI_SKELETON_POSITION_FOOT_LEFT = 15, + NUI_SKELETON_POSITION_HIP_RIGHT = 16, + NUI_SKELETON_POSITION_KNEE_RIGHT = 17, + NUI_SKELETON_POSITION_ANKLE_RIGHT = 18, + NUI_SKELETON_POSITION_FOOT_RIGHT = 19, +} NUI_SKELETON_POSITION_INDEX; + +// NUI_SKELETON_TRACKING_STATE (per-skeleton, NuiSkeleton.h). +typedef enum _NUI_SKELETON_TRACKING_STATE { + NUI_SKELETON_NOT_TRACKED = 0, + NUI_SKELETON_POSITION_ONLY = 1, + NUI_SKELETON_TRACKED = 2, +} NUI_SKELETON_TRACKING_STATE; + +// NUI_SKELETON_POSITION_TRACKING_STATE (per-joint, NuiSkeleton.h). Matches +// core/contract JointTrackingState values. +typedef enum _NUI_SKELETON_POSITION_TRACKING_STATE { + NUI_SKELETON_POSITION_NOT_TRACKED = 0, + NUI_SKELETON_POSITION_INFERRED = 1, + NUI_SKELETON_POSITION_TRACKED = 2, +} NUI_SKELETON_POSITION_TRACKING_STATE; + +// NUI_SKELETON_DATA (NuiSkeleton.h). Default alignment; 12-byte header of DWORDs, +// then Position, then the position array, then the per-joint state array, then +// dwQualityFlags. +typedef struct _NUI_SKELETON_DATA { + NUI_SKELETON_TRACKING_STATE eTrackingState; + DWORD dwTrackingID; + DWORD dwEnrollmentIndex; + DWORD dwUserIndex; + Vector4 Position; + Vector4 SkeletonPositions[NUI_SKELETON_POSITION_COUNT]; + NUI_SKELETON_POSITION_TRACKING_STATE + eSkeletonPositionTrackingState[NUI_SKELETON_POSITION_COUNT]; + DWORD dwQualityFlags; +} NUI_SKELETON_DATA; + +// NUI_SKELETON_FRAME (NuiSkeleton.h). +typedef struct _NUI_SKELETON_FRAME { + LARGE_INTEGER liTimeStamp; + DWORD dwFrameNumber; + DWORD dwFlags; + Vector4 vFloorClipPlane; + Vector4 vNormalToGravity; + NUI_SKELETON_DATA SkeletonData[NUI_SKELETON_COUNT]; +} NUI_SKELETON_FRAME; + +// NUI_TRANSFORM_SMOOTH_PARAMETERS (NuiSkeleton.h), nui-contracts.md §1.6. +typedef struct _NUI_TRANSFORM_SMOOTH_PARAMETERS { + FLOAT fSmoothing; + FLOAT fCorrection; + FLOAT fPrediction; + FLOAT fJitterRadius; + FLOAT fMaxDeviationRadius; +} NUI_TRANSFORM_SMOOTH_PARAMETERS; + +// NUI_LOCKED_RECT (NuiImageCamera.h), nui-contracts.md §3.5. +typedef struct _NUI_LOCKED_RECT { + INT Pitch; + INT size; + BYTE* pBits; +} NUI_LOCKED_RECT; + +// NUI_SURFACE_DESC (NuiImageCamera.h). +typedef struct _NUI_SURFACE_DESC { + UINT Width; + UINT Height; +} NUI_SURFACE_DESC; + +// NUI_IMAGE_VIEW_AREA (NuiImageCamera.h). +typedef struct _NUI_IMAGE_VIEW_AREA { + NUI_IMAGE_DIGITAL_ZOOM eDigitalZoom; + LONG lCenterX; + LONG lCenterY; +} NUI_IMAGE_VIEW_AREA; + +// Forward declaration of the frame-texture COM interface. +struct INuiFrameTexture; + +// NUI_IMAGE_FRAME (NuiImageCamera.h), nui-contracts.md §3.5. +typedef struct _NUI_IMAGE_FRAME { + LARGE_INTEGER liTimeStamp; + DWORD dwFrameNumber; + NUI_IMAGE_TYPE eImageType; + NUI_IMAGE_RESOLUTION eResolution; + struct INuiFrameTexture* pFrameTexture; + DWORD dwFrameFlags; + NUI_IMAGE_VIEW_AREA ViewArea; +} NUI_IMAGE_FRAME; + +// NUI_DEPTH_IMAGE_PIXEL (unpacked depth, NuiImageCamera.h), nui-contracts.md §2.2. +typedef struct _NUI_DEPTH_IMAGE_PIXEL { + USHORT playerIndex; + USHORT depth; +} NUI_DEPTH_IMAGE_PIXEL; + +// Device-status callback signature (NuiApi.h): called on connect/disconnect. +typedef void(CALLBACK* NuiStatusProc)(HRESULT hrStatus, + const OLECHAR* instanceName, + const OLECHAR* uniqueDeviceName, + void* pUserData); + +#ifdef __cplusplus +} // extern "C" + +// Architecture-independent layout pins (no pointer members): these sizes are +// identical under MSVC x86/x64 and MinGW x86/x64 and must match the real NUI +// structs bit-for-bit. A drift fails the cross-build rather than the game. +static_assert(sizeof(Vector4) == 16, "Vector4 ABI size"); +static_assert(sizeof(NUI_SKELETON_DATA) == 436, "NUI_SKELETON_DATA ABI size"); +static_assert(sizeof(NUI_SKELETON_FRAME) == 2664, "NUI_SKELETON_FRAME ABI size"); +static_assert(sizeof(NUI_TRANSFORM_SMOOTH_PARAMETERS) == 20, + "NUI_TRANSFORM_SMOOTH_PARAMETERS ABI size"); +static_assert(sizeof(NUI_SURFACE_DESC) == 8, "NUI_SURFACE_DESC ABI size"); +static_assert(sizeof(NUI_IMAGE_VIEW_AREA) == 12, "NUI_IMAGE_VIEW_AREA ABI size"); +static_assert(sizeof(NUI_DEPTH_IMAGE_PIXEL) == 4, "NUI_DEPTH_IMAGE_PIXEL ABI size"); +#endif + +#endif // FALLBACK_WINDOWS_NUI_NUI_ABI_H diff --git a/fallback/windows-nui/include/nui_interfaces.h b/fallback/windows-nui/include/nui_interfaces.h new file mode 100644 index 0000000..d424218 --- /dev/null +++ b/fallback/windows-nui/include/nui_interfaces.h @@ -0,0 +1,121 @@ +#ifndef FALLBACK_WINDOWS_NUI_NUI_INTERFACES_H +#define FALLBACK_WINDOWS_NUI_NUI_INTERFACES_H + +// Clean-room COM interface declarations for INuiFrameTexture and INuiSensor. +// +// CLEAN-ROOM PROVENANCE: vtable method order and signatures are reproduced from +// public Kinect for Windows SDK 1.8 header knowledge (NuiImageCamera.h declares +// INuiFrameTexture; NuiSensor.h declares INuiSensor) per nui-contracts.md §3.5. +// No GPL third-party source was consulted. STDMETHODCALLTYPE is __stdcall, so the +// vtable binary layout matches the real Kinect10.dll for a drop-in replacement. +// +// RUNTIME-GATE NOTE: the INuiFrameTexture method order is pinned by nui-contracts +// §3.5 and is low-risk. The INuiSensor vtable is large; its exact method ordering +// can only be byte-verified on Windows against a real Kinect app (the [~] runtime +// gate). The flat C exports in nui_exports.h are the primary, Linux-auditable ABI +// surface; most Kinect v1.8 titles (DEA included, per spike todo 4) bind the flat +// API, and the sensor interface here delegates to the same VirtualKinectSensor the +// flat exports drive, so behaviour is identical whichever path a title uses. + +#include + +#include "nui_abi.h" + +struct INuiCoordinateMapper; +struct INuiColorCameraSettings; + +#ifdef __cplusplus + +struct INuiFrameTexture : public IUnknown { + virtual int STDMETHODCALLTYPE BufferLen() = 0; + virtual int STDMETHODCALLTYPE Pitch() = 0; + virtual HRESULT STDMETHODCALLTYPE LockRect(UINT Level, + NUI_LOCKED_RECT* pLockedRect, + RECT* pRect, + DWORD Flags) = 0; + virtual HRESULT STDMETHODCALLTYPE GetLevelDesc(UINT Level, + NUI_SURFACE_DESC* pDesc) = 0; + virtual HRESULT STDMETHODCALLTYPE UnlockRect(UINT Level) = 0; +}; + +struct INuiSensor : public IUnknown { + virtual HRESULT STDMETHODCALLTYPE NuiInitialize(DWORD dwFlags) = 0; + virtual void STDMETHODCALLTYPE NuiShutdown() = 0; + virtual HRESULT STDMETHODCALLTYPE NuiSetFrameEndEvent(HANDLE hEvent, + DWORD dwFrameEventFlag) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiImageStreamOpen(NUI_IMAGE_TYPE eImageType, + NUI_IMAGE_RESOLUTION eResolution, + DWORD dwImageFrameFlags, + DWORD dwFrameLimit, + HANDLE hNextFrameEvent, + HANDLE* phStreamHandle) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiImageStreamSetImageFrameFlags(HANDLE hStream, DWORD dwImageFrameFlags) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiImageStreamGetImageFrameFlags(HANDLE hStream, DWORD* pdwImageFrameFlags) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiImageStreamGetNextFrame(HANDLE hStream, + DWORD dwMillisecondsToWait, + const NUI_IMAGE_FRAME** ppcImageFrame) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiImageStreamReleaseFrame(HANDLE hStream, + const NUI_IMAGE_FRAME* pImageFrame) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiImageGetColorPixelCoordinatesFromDepthPixel(NUI_IMAGE_RESOLUTION eColorResolution, + const NUI_IMAGE_VIEW_AREA* pcViewArea, + LONG lDepthX, + LONG lDepthY, + USHORT usDepthValue, + LONG* plColorX, + LONG* plColorY) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution( + NUI_IMAGE_RESOLUTION eColorResolution, + NUI_IMAGE_RESOLUTION eDepthResolution, + const NUI_IMAGE_VIEW_AREA* pcViewArea, + LONG lDepthX, + LONG lDepthY, + USHORT usDepthValue, + LONG* plColorX, + LONG* plColorY) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiGetColorPixelCoordinateFrameFromDepthPixelFrameAtResolution( + NUI_IMAGE_RESOLUTION eColorResolution, + NUI_IMAGE_RESOLUTION eDepthResolution, + DWORD cDepthValues, + USHORT* pDepthValues, + DWORD cColorCoordinates, + LONG* pColorCoordinates) = 0; + virtual HRESULT STDMETHODCALLTYPE NuiCameraElevationSetAngle(LONG lAngleDegrees) = 0; + virtual HRESULT STDMETHODCALLTYPE NuiCameraElevationGetAngle(LONG* plAngleDegrees) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiSkeletonTrackingEnable(HANDLE hNextFrameEvent, DWORD dwFlags) = 0; + virtual HRESULT STDMETHODCALLTYPE NuiSkeletonTrackingDisable() = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiSkeletonSetTrackedSkeletons(DWORD* pTrackingIDs) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiSkeletonGetNextFrame(DWORD dwMillisecondsToWait, + NUI_SKELETON_FRAME* pSkeletonFrame) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiTransformSmooth(NUI_SKELETON_FRAME* pSkeletonFrame, + const NUI_TRANSFORM_SMOOTH_PARAMETERS* pSmoothingParams) = 0; + virtual HRESULT STDMETHODCALLTYPE NuiGetAudioSource(IUnknown** ppDmo) = 0; + virtual int STDMETHODCALLTYPE NuiInstanceIndex() = 0; + virtual BSTR STDMETHODCALLTYPE NuiDeviceConnectionId() = 0; + virtual BSTR STDMETHODCALLTYPE NuiUniqueId() = 0; + virtual BSTR STDMETHODCALLTYPE NuiAudioArrayId() = 0; + virtual HRESULT STDMETHODCALLTYPE NuiStatus() = 0; + virtual DWORD STDMETHODCALLTYPE NuiInitializationFlags() = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiGetCoordinateMapper(INuiCoordinateMapper** ppCoordinateMapper) = 0; + virtual HRESULT STDMETHODCALLTYPE + NuiImageFrameGetDepthImagePixelFrameTexture(HANDLE hStream, + const NUI_IMAGE_FRAME* pImageFrame, + BOOL* pNearMode, + INuiFrameTexture** ppFrameTexture) = 0; +}; + +#endif // __cplusplus + +#endif // FALLBACK_WINDOWS_NUI_NUI_INTERFACES_H diff --git a/fallback/windows-nui/src/coordmap.cpp b/fallback/windows-nui/src/coordmap.cpp new file mode 100644 index 0000000..ece30f4 --- /dev/null +++ b/fallback/windows-nui/src/coordmap.cpp @@ -0,0 +1,112 @@ +#include "coordmap.h" + +#include +#include + +#include "core_alias.h" +#include "sensor.h" + +namespace nui_shim { +namespace { + +constexpr uint32_t kBaseDepthWidth = 320; +constexpr uint32_t kBaseDepthHeight = 240; + +CRITICAL_SECTION g_smooth_lock; +INIT_ONCE g_smooth_once = INIT_ONCE_STATIC_INIT; + +BOOL CALLBACK InitSmoothLock(PINIT_ONCE, PVOID, PVOID*) { + InitializeCriticalSection(&g_smooth_lock); + return TRUE; +} + +CRITICAL_SECTION& SmoothLock() { + InitOnceExecuteOnce(&g_smooth_once, InitSmoothLock, nullptr, nullptr); + return g_smooth_lock; +} + +struct SkeletonFilters { + mapping::SmoothingParameters params; + mapping::HoltSmoothingFilter joints[NUI_SKELETON_POSITION_COUNT]; +}; + +bool ParamsEqual(const mapping::SmoothingParameters& a, + const mapping::SmoothingParameters& b) { + return a.smoothing == b.smoothing && a.correction == b.correction && + a.prediction == b.prediction && a.jitter_radius == b.jitter_radius && + a.max_deviation_radius == b.max_deviation_radius; +} + +} + +Vector4 TransformDepthImageToSkeleton(LONG depth_x, LONG depth_y, USHORT depth) { + const mapping::DepthImagePoint point{static_cast(depth_x), + static_cast(depth_y), depth}; + const contract::Vector4 v = mapping::depth_image_to_skeleton( + point, static_cast(kBaseDepthWidth), + static_cast(kBaseDepthHeight)); + return {v.x, v.y, v.z, v.w}; +} + +void TransformSmooth(NUI_SKELETON_FRAME* frame, + const NUI_TRANSFORM_SMOOTH_PARAMETERS* params) { + if (frame == nullptr) { + return; + } + mapping::SmoothingParameters smoothing; + if (params != nullptr) { + smoothing = {params->fSmoothing, params->fCorrection, params->fPrediction, + params->fJitterRadius, params->fMaxDeviationRadius}; + } + + EnterCriticalSection(&SmoothLock()); + static std::map filters_by_id; + + for (auto& skeleton : frame->SkeletonData) { + if (skeleton.eTrackingState != NUI_SKELETON_TRACKED) { + filters_by_id.erase(skeleton.dwTrackingID); + continue; + } + auto it = filters_by_id.find(skeleton.dwTrackingID); + if (it == filters_by_id.end() || !ParamsEqual(it->second.params, smoothing)) { + SkeletonFilters fresh; + fresh.params = smoothing; + for (auto& filter : fresh.joints) { + filter = mapping::HoltSmoothingFilter(smoothing); + } + it = filters_by_id.insert_or_assign(skeleton.dwTrackingID, + std::move(fresh)).first; + } + for (int j = 0; j < NUI_SKELETON_POSITION_COUNT; ++j) { + const Vector4& in = skeleton.SkeletonPositions[j]; + const contract::Vector4 raw{in.x, in.y, in.z, in.w}; + const contract::Vector4 out = it->second.joints[j].update(raw); + skeleton.SkeletonPositions[j] = {out.x, out.y, out.z, out.w}; + } + skeleton.Position = + skeleton.SkeletonPositions[NUI_SKELETON_POSITION_HIP_CENTER]; + } + LeaveCriticalSection(&SmoothLock()); +} + +HRESULT ColorCoordinatesFromDepthPixel(NUI_IMAGE_RESOLUTION color_resolution, + LONG depth_x, + LONG depth_y, + LONG* color_x, + LONG* color_y) { + if (color_x == nullptr || color_y == nullptr) { + return E_POINTER; + } + uint32_t color_w = 0; + uint32_t color_h = 0; + if (!resolution_to_size(color_resolution, color_w, color_h)) { + return E_INVALIDARG; + } + *color_x = depth_x * static_cast(color_w) / + static_cast(kBaseDepthWidth); + *color_y = depth_y * static_cast(color_h) / + static_cast(kBaseDepthHeight); + return S_OK; +} + +} diff --git a/fallback/windows-nui/src/coordmap.h b/fallback/windows-nui/src/coordmap.h new file mode 100644 index 0000000..55e8d1e --- /dev/null +++ b/fallback/windows-nui/src/coordmap.h @@ -0,0 +1,23 @@ +#ifndef FALLBACK_WINDOWS_NUI_COORDMAP_H +#define FALLBACK_WINDOWS_NUI_COORDMAP_H + +#include + +#include "nui_abi.h" + +namespace nui_shim { + +Vector4 TransformDepthImageToSkeleton(LONG depth_x, LONG depth_y, USHORT depth); + +void TransformSmooth(NUI_SKELETON_FRAME* frame, + const NUI_TRANSFORM_SMOOTH_PARAMETERS* params); + +HRESULT ColorCoordinatesFromDepthPixel(NUI_IMAGE_RESOLUTION color_resolution, + LONG depth_x, + LONG depth_y, + LONG* color_x, + LONG* color_y); + +} + +#endif diff --git a/fallback/windows-nui/src/core_alias.h b/fallback/windows-nui/src/core_alias.h new file mode 100644 index 0000000..4a9143a --- /dev/null +++ b/fallback/windows-nui/src/core_alias.h @@ -0,0 +1,14 @@ +#ifndef FALLBACK_WINDOWS_NUI_CORE_ALIAS_H +#define FALLBACK_WINDOWS_NUI_CORE_ALIAS_H + +#include "contract/contract.h" +#include "mapping/mapping.h" +#include "synth/synth.h" + +namespace nui_shim { +namespace contract = ::nui::contract; +namespace mapping = ::nui::mapping; +namespace synth = ::nui::synth; +} + +#endif diff --git a/fallback/windows-nui/src/exports.cpp b/fallback/windows-nui/src/exports.cpp new file mode 100644 index 0000000..54f26cc --- /dev/null +++ b/fallback/windows-nui/src/exports.cpp @@ -0,0 +1,169 @@ +#include + +#include "coordmap.h" +#include "nui_abi.h" +#include "nui_interfaces.h" +#include "sensor.h" +#include "sensor_com.h" + +using namespace nui_shim; + +namespace { +NuiStatusProc g_status_callback = nullptr; +void* g_status_user_data = nullptr; +} + +extern "C" { + +HRESULT WINAPI NuiGetSensorCount(int* pCount) { + if (pCount == nullptr) { + return E_POINTER; + } + *pCount = 1; + return S_OK; +} + +HRESULT WINAPI NuiCreateSensorByIndex(int index, INuiSensor** ppNuiSensor) { + if (ppNuiSensor == nullptr) { + return E_POINTER; + } + if (index != 0) { + return E_NUI_DEVICE_NOT_CONNECTED; + } + *ppNuiSensor = new NuiSensorCom(EnsureGlobalSensor()); + return S_OK; +} + +HRESULT WINAPI NuiCreateSensorById(const OLECHAR*, INuiSensor** ppNuiSensor) { + if (ppNuiSensor == nullptr) { + return E_POINTER; + } + *ppNuiSensor = new NuiSensorCom(EnsureGlobalSensor()); + return S_OK; +} + +HRESULT WINAPI NuiInitialize(DWORD dwFlags) { + return EnsureGlobalSensor()->Initialize(dwFlags); +} + +void WINAPI NuiShutdown(void) { + if (VirtualKinectSensor* sensor = GlobalSensor()) { + sensor->Shutdown(); + } +} + +HRESULT WINAPI NuiSetDeviceStatusCallback(NuiStatusProc callback, + void* pUserData) { + g_status_callback = callback; + g_status_user_data = pUserData; + if (callback != nullptr) { + callback(S_OK, L"VirtualKinect0", L"VirtualKinect0", pUserData); + } + return S_OK; +} + +HRESULT WINAPI NuiSkeletonTrackingEnable(HANDLE hNextFrameEvent, DWORD dwFlags) { + return EnsureGlobalSensor()->SkeletonTrackingEnable(hNextFrameEvent, dwFlags); +} + +HRESULT WINAPI NuiSkeletonTrackingDisable(void) { + return EnsureGlobalSensor()->SkeletonTrackingDisable(); +} + +HRESULT WINAPI NuiSkeletonGetNextFrame(DWORD dwMillisecondsToWait, + NUI_SKELETON_FRAME* pSkeletonFrame) { + return EnsureGlobalSensor()->SkeletonGetNextFrame(dwMillisecondsToWait, + pSkeletonFrame); +} + +HRESULT WINAPI NuiSkeletonSetTrackedSkeletons(DWORD*) { return S_OK; } + +HRESULT WINAPI NuiTransformSmooth( + NUI_SKELETON_FRAME* pSkeletonFrame, + const NUI_TRANSFORM_SMOOTH_PARAMETERS* pSmoothingParams) { + if (pSkeletonFrame == nullptr) { + return E_POINTER; + } + TransformSmooth(pSkeletonFrame, pSmoothingParams); + return S_OK; +} + +HRESULT WINAPI NuiImageStreamOpen(NUI_IMAGE_TYPE eImageType, + NUI_IMAGE_RESOLUTION eResolution, + DWORD dwImageFrameFlags, + DWORD dwFrameLimit, + HANDLE hNextFrameEvent, + HANDLE* phStreamHandle) { + return EnsureGlobalSensor()->ImageStreamOpen(eImageType, eResolution, + dwImageFrameFlags, dwFrameLimit, + hNextFrameEvent, phStreamHandle); +} + +HRESULT WINAPI NuiImageStreamGetNextFrame(HANDLE hStream, + DWORD dwMillisecondsToWait, + const NUI_IMAGE_FRAME** ppcImageFrame) { + return EnsureGlobalSensor()->ImageStreamGetNextFrame( + hStream, dwMillisecondsToWait, ppcImageFrame); +} + +HRESULT WINAPI NuiImageStreamReleaseFrame(HANDLE hStream, + const NUI_IMAGE_FRAME* pImageFrame) { + return EnsureGlobalSensor()->ImageStreamReleaseFrame(hStream, pImageFrame); +} + +HRESULT WINAPI NuiImageStreamSetImageFrameFlags(HANDLE, DWORD) { return S_OK; } + +HRESULT WINAPI NuiImageStreamGetImageFrameFlags(HANDLE, + DWORD* pdwImageFrameFlags) { + if (pdwImageFrameFlags == nullptr) { + return E_POINTER; + } + *pdwImageFrameFlags = 0; + return S_OK; +} + +HRESULT WINAPI NuiCameraElevationSetAngle(LONG) { return S_OK; } + +HRESULT WINAPI NuiCameraElevationGetAngle(LONG* plAngleDegrees) { + if (plAngleDegrees == nullptr) { + return E_POINTER; + } + *plAngleDegrees = 0; + return S_OK; +} + +HRESULT WINAPI NuiImageGetColorPixelCoordinatesFromDepthPixel( + NUI_IMAGE_RESOLUTION eColorResolution, + const NUI_IMAGE_VIEW_AREA*, + LONG lDepthX, + LONG lDepthY, + USHORT, + LONG* plColorX, + LONG* plColorY) { + return ColorCoordinatesFromDepthPixel(eColorResolution, lDepthX, lDepthY, + plColorX, plColorY); +} + +Vector4 WINAPI NuiTransformDepthImageToSkeleton(LONG lDepthX, + LONG lDepthY, + USHORT usDepthValue) { + return TransformDepthImageToSkeleton(lDepthX, lDepthY, usDepthValue); +} + +HRESULT WINAPI NuiSetFrameEndEvent(HANDLE, DWORD) { return S_OK; } + +} + +BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD reason, LPVOID) { + switch (reason) { + case DLL_PROCESS_ATTACH: + DisableThreadLibraryCalls(hinstDLL); + break; + case DLL_PROCESS_DETACH: + DestroyGlobalSensor(); + break; + default: + break; + } + return TRUE; +} diff --git a/fallback/windows-nui/src/frame_source.cpp b/fallback/windows-nui/src/frame_source.cpp new file mode 100644 index 0000000..2b862c3 --- /dev/null +++ b/fallback/windows-nui/src/frame_source.cpp @@ -0,0 +1,120 @@ +#include "frame_source.h" + +#include + +namespace nui_shim { +namespace { + +constexpr std::size_t kMaxReadRetries = 8; + +std::size_t region_size(uint32_t depth_w, + uint32_t depth_h, + uint32_t color_w, + uint32_t color_h) { + const std::size_t contract_size = sizeof(contract::FrameContract); + const std::size_t depth_bytes = + static_cast(depth_w) * depth_h * sizeof(uint16_t); + const std::size_t color_bytes = + static_cast(color_w) * color_h * 4u; + return contract_size + + contract::kFrameSlotCount * (depth_bytes + color_bytes); +} + +} + +FrameSource::FrameSource() = default; + +FrameSource::~FrameSource() { close(); } + +bool FrameSource::open(const wchar_t* mapping_name) { + close(); + mapping_ = OpenFileMappingW(FILE_MAP_READ, FALSE, mapping_name); + if (mapping_ == nullptr) { + return false; + } + base_ = static_cast(MapViewOfFile(mapping_, FILE_MAP_READ, 0, 0, 0)); + if (base_ == nullptr) { + CloseHandle(mapping_); + mapping_ = nullptr; + return false; + } + return true; +} + +bool FrameSource::is_open() const { return base_ != nullptr; } + +void FrameSource::close() { + if (base_ != nullptr) { + UnmapViewOfFile(base_); + base_ = nullptr; + } + if (mapping_ != nullptr) { + CloseHandle(mapping_); + mapping_ = nullptr; + } + last_sequence_ = 0; +} + +bool FrameSource::read_latest(SourceFrame& out) { + if (base_ == nullptr) { + return false; + } + const auto* fc = reinterpret_cast(base_); + if (fc->contract_version != contract::kContractVersion) { + return false; + } + + for (std::size_t attempt = 0; attempt < kMaxReadRetries; ++attempt) { + const uint64_t published = fc->published_sequence; + if (published == 0) { + return false; + } + const std::size_t slot_index = published % contract::kFrameSlotCount; + const contract::FrameSlot& slot = fc->slots[slot_index]; + + const uint64_t seq_before = slot.sequence; + if (seq_before & 1u) { + continue; + } + + contract::FrameData meta = slot.data; + + const std::size_t depth_count = + static_cast(meta.depth.width) * meta.depth.height; + const std::size_t color_count = + static_cast(meta.color.width) * meta.color.height; + + std::vector depth(depth_count); + std::vector color(color_count * 4u); + + if (depth_count != 0 && + meta.depth.byte_offset + depth_count * sizeof(uint16_t) <= + region_size(meta.depth.width, meta.depth.height, meta.color.width, + meta.color.height)) { + std::memcpy(depth.data(), base_ + meta.depth.byte_offset, + depth_count * sizeof(uint16_t)); + } + if (color_count != 0 && + meta.color.byte_offset + color_count * 4u <= + region_size(meta.depth.width, meta.depth.height, meta.color.width, + meta.color.height)) { + std::memcpy(color.data(), base_ + meta.color.byte_offset, + color_count * 4u); + } + + const uint64_t seq_after = slot.sequence; + if (seq_before != seq_after || (seq_after & 1u)) { + continue; + } + + out.meta = meta; + out.depth_pixels = std::move(depth); + out.color_pixels = std::move(color); + out.has_player = meta.skeleton.skeleton_tracking_id != 0; + last_sequence_ = published; + return true; + } + return false; +} + +} diff --git a/fallback/windows-nui/src/frame_source.h b/fallback/windows-nui/src/frame_source.h new file mode 100644 index 0000000..88e5adb --- /dev/null +++ b/fallback/windows-nui/src/frame_source.h @@ -0,0 +1,39 @@ +#ifndef FALLBACK_WINDOWS_NUI_FRAME_SOURCE_H +#define FALLBACK_WINDOWS_NUI_FRAME_SOURCE_H + +#include + +#include +#include + +#include "core_alias.h" + +namespace nui_shim { + +struct SourceFrame { + contract::FrameData meta; + std::vector depth_pixels; + std::vector color_pixels; + bool has_player; +}; + +class FrameSource { + public: + FrameSource(); + ~FrameSource(); + + bool open(const wchar_t* mapping_name); + bool is_open() const; + void close(); + + bool read_latest(SourceFrame& out); + + private: + HANDLE mapping_ = nullptr; + uint8_t* base_ = nullptr; + uint64_t last_sequence_ = 0; +}; + +} + +#endif diff --git a/fallback/windows-nui/src/frame_texture.cpp b/fallback/windows-nui/src/frame_texture.cpp new file mode 100644 index 0000000..1ae2ad4 --- /dev/null +++ b/fallback/windows-nui/src/frame_texture.cpp @@ -0,0 +1,94 @@ +#include "frame_texture.h" + +#include + +namespace nui_shim { + +NuiFrameTexture::NuiFrameTexture(uint32_t width, + uint32_t height, + uint32_t bytes_per_pixel) + : width_(width), + height_(height), + bytes_per_pixel_(bytes_per_pixel), + bits_(static_cast(width) * height * bytes_per_pixel, 0) {} + +void NuiFrameTexture::set_bits(const uint8_t* data, std::size_t size) { + const std::size_t n = size < bits_.size() ? size : bits_.size(); + if (data != nullptr && n != 0) { + std::memcpy(bits_.data(), data, n); + } + if (n < bits_.size()) { + std::memset(bits_.data() + n, 0, bits_.size() - n); + } +} + +uint8_t* NuiFrameTexture::data() { return bits_.data(); } + +HRESULT STDMETHODCALLTYPE NuiFrameTexture::QueryInterface(REFIID riid, + void** ppv) { + if (ppv == nullptr) { + return E_POINTER; + } + if (IsEqualIID(riid, IID_IUnknown)) { + *ppv = static_cast(this); + AddRef(); + return S_OK; + } + *ppv = nullptr; + return E_NOINTERFACE; +} + +ULONG STDMETHODCALLTYPE NuiFrameTexture::AddRef() { + return static_cast(InterlockedIncrement(&ref_count_)); +} + +ULONG STDMETHODCALLTYPE NuiFrameTexture::Release() { + const LONG count = InterlockedDecrement(&ref_count_); + if (count == 0) { + delete this; + } + return static_cast(count); +} + +int STDMETHODCALLTYPE NuiFrameTexture::BufferLen() { + return static_cast(bits_.size()); +} + +int STDMETHODCALLTYPE NuiFrameTexture::Pitch() { + return static_cast(width_ * bytes_per_pixel_); +} + +HRESULT STDMETHODCALLTYPE NuiFrameTexture::LockRect(UINT Level, + NUI_LOCKED_RECT* pLockedRect, + RECT*, + DWORD) { + if (pLockedRect == nullptr) { + return E_POINTER; + } + if (Level != 0) { + return E_INVALIDARG; + } + pLockedRect->Pitch = static_cast(width_ * bytes_per_pixel_); + pLockedRect->size = static_cast(bits_.size()); + pLockedRect->pBits = bits_.data(); + return S_OK; +} + +HRESULT STDMETHODCALLTYPE NuiFrameTexture::GetLevelDesc(UINT Level, + NUI_SURFACE_DESC* pDesc) { + if (pDesc == nullptr) { + return E_POINTER; + } + if (Level != 0) { + return E_INVALIDARG; + } + pDesc->Width = width_; + pDesc->Height = height_; + return S_OK; +} + +HRESULT STDMETHODCALLTYPE NuiFrameTexture::UnlockRect(UINT Level) { + return Level == 0 ? S_OK : E_INVALIDARG; +} + +} diff --git a/fallback/windows-nui/src/frame_texture.h b/fallback/windows-nui/src/frame_texture.h new file mode 100644 index 0000000..d350a93 --- /dev/null +++ b/fallback/windows-nui/src/frame_texture.h @@ -0,0 +1,45 @@ +#ifndef FALLBACK_WINDOWS_NUI_FRAME_TEXTURE_H +#define FALLBACK_WINDOWS_NUI_FRAME_TEXTURE_H + +#include + +#include +#include + +#include "nui_abi.h" +#include "nui_interfaces.h" + +namespace nui_shim { + +class NuiFrameTexture : public INuiFrameTexture { + public: + NuiFrameTexture(uint32_t width, uint32_t height, uint32_t bytes_per_pixel); + + void set_bits(const uint8_t* data, std::size_t size); + uint8_t* data(); + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override; + ULONG STDMETHODCALLTYPE AddRef() override; + ULONG STDMETHODCALLTYPE Release() override; + + int STDMETHODCALLTYPE BufferLen() override; + int STDMETHODCALLTYPE Pitch() override; + HRESULT STDMETHODCALLTYPE LockRect(UINT Level, + NUI_LOCKED_RECT* pLockedRect, + RECT* pRect, + DWORD Flags) override; + HRESULT STDMETHODCALLTYPE GetLevelDesc(UINT Level, + NUI_SURFACE_DESC* pDesc) override; + HRESULT STDMETHODCALLTYPE UnlockRect(UINT Level) override; + + private: + LONG ref_count_ = 1; + uint32_t width_; + uint32_t height_; + uint32_t bytes_per_pixel_; + std::vector bits_; +}; + +} + +#endif diff --git a/fallback/windows-nui/src/sensor.cpp b/fallback/windows-nui/src/sensor.cpp new file mode 100644 index 0000000..5014d0b --- /dev/null +++ b/fallback/windows-nui/src/sensor.cpp @@ -0,0 +1,550 @@ +#include "sensor.h" + +#include +#include +#include +#include + +namespace nui_shim { +namespace { + +constexpr wchar_t kDefaultMappingName[] = L"kinect_virtual_frames"; +constexpr DWORD kPlayerIndexMask = 0x7u; + +VirtualKinectSensor* g_sensor = nullptr; +CRITICAL_SECTION g_sensor_lock; +INIT_ONCE g_sensor_lock_once = INIT_ONCE_STATIC_INIT; + +BOOL CALLBACK InitSensorLock(PINIT_ONCE, PVOID, PVOID*) { + InitializeCriticalSection(&g_sensor_lock); + return TRUE; +} + +CRITICAL_SECTION& SensorLock() { + InitOnceExecuteOnce(&g_sensor_lock_once, InitSensorLock, nullptr, nullptr); + return g_sensor_lock; +} + +std::wstring MappingName() { + wchar_t buffer[256]; + DWORD n = GetEnvironmentVariableW(L"KINECT_SHIM_SHM", buffer, 256); + if (n > 0 && n < 256) { + return std::wstring(buffer, n); + } + return std::wstring(kDefaultMappingName); +} + +std::vector ResizeDepthNearest(const std::vector& src, + uint32_t sw, + uint32_t sh, + uint32_t dw, + uint32_t dh) { + std::vector out(static_cast(dw) * dh, 0); + if (sw == 0 || sh == 0 || dw == 0 || dh == 0 || + src.size() != static_cast(sw) * sh) { + return out; + } + for (uint32_t y = 0; y < dh; ++y) { + const uint32_t sy = std::min(static_cast( + static_cast(y) * sh / dh), + sh - 1); + for (uint32_t x = 0; x < dw; ++x) { + const uint32_t sx = std::min(static_cast( + static_cast(x) * sw / dw), + sw - 1); + out[static_cast(y) * dw + x] = + src[static_cast(sy) * sw + sx]; + } + } + return out; +} + +NUI_SKELETON_POSITION_TRACKING_STATE MapJointState( + contract::JointTrackingState s) { + switch (s) { + case contract::JointTrackingState::TRACKED: + return NUI_SKELETON_POSITION_TRACKED; + case contract::JointTrackingState::INFERRED: + return NUI_SKELETON_POSITION_INFERRED; + case contract::JointTrackingState::NOT_TRACKED: + return NUI_SKELETON_POSITION_NOT_TRACKED; + } + return NUI_SKELETON_POSITION_NOT_TRACKED; +} + +} + +bool resolution_to_size(NUI_IMAGE_RESOLUTION resolution, + uint32_t& width, + uint32_t& height) { + switch (resolution) { + case NUI_IMAGE_RESOLUTION_80x60: + width = 80; + height = 60; + return true; + case NUI_IMAGE_RESOLUTION_320x240: + width = 320; + height = 240; + return true; + case NUI_IMAGE_RESOLUTION_640x480: + width = 640; + height = 480; + return true; + case NUI_IMAGE_RESOLUTION_1280x960: + width = 1280; + height = 960; + return true; + default: + return false; + } +} + +VirtualKinectSensor::VirtualKinectSensor() { + InitializeCriticalSection(&lock_); +} + +VirtualKinectSensor::~VirtualKinectSensor() { + Shutdown(); + DeleteCriticalSection(&lock_); +} + +HRESULT VirtualKinectSensor::Initialize(DWORD dwFlags) { + if (initialized_) { + return E_NUI_ALREADY_INITIALIZED; + } + init_flags_ = dwFlags; + source_.open(MappingName().c_str()); + + stop_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + skeleton_ready_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + initialized_ = true; + + producer_thread_ = + CreateThread(nullptr, 0, &VirtualKinectSensor::ProducerThunk, this, 0, + nullptr); + if (producer_thread_ == nullptr) { + initialized_ = false; + return E_FAIL; + } + return S_OK; +} + +void VirtualKinectSensor::Shutdown() { + if (!initialized_) { + return; + } + initialized_ = false; + if (stop_event_ != nullptr) { + SetEvent(stop_event_); + } + if (producer_thread_ != nullptr) { + WaitForSingleObject(producer_thread_, 2000); + CloseHandle(producer_thread_); + producer_thread_ = nullptr; + } + + EnterCriticalSection(&lock_); + for (auto& stream : streams_) { + for (auto* texture : stream.ring) { + if (texture != nullptr) { + texture->Release(); + } + } + stream = ImageStream{}; + } + skeleton_enabled_ = false; + has_skeleton_ = false; + LeaveCriticalSection(&lock_); + + source_.close(); + if (stop_event_ != nullptr) { + CloseHandle(stop_event_); + stop_event_ = nullptr; + } + if (skeleton_ready_event_ != nullptr) { + CloseHandle(skeleton_ready_event_); + skeleton_ready_event_ = nullptr; + } +} + +DWORD VirtualKinectSensor::InitializationFlags() const { return init_flags_; } + +HRESULT VirtualKinectSensor::Status() const { + return initialized_ ? S_OK : E_NUI_DEVICE_NOT_READY; +} + +HRESULT VirtualKinectSensor::SkeletonTrackingEnable(HANDLE hNextFrameEvent, + DWORD dwFlags) { + EnterCriticalSection(&lock_); + skeleton_enabled_ = true; + skeleton_flags_ = dwFlags; + skeleton_app_event_ = hNextFrameEvent; + LeaveCriticalSection(&lock_); + return S_OK; +} + +HRESULT VirtualKinectSensor::SkeletonTrackingDisable() { + EnterCriticalSection(&lock_); + skeleton_enabled_ = false; + skeleton_app_event_ = nullptr; + LeaveCriticalSection(&lock_); + return S_OK; +} + +HRESULT VirtualKinectSensor::SkeletonGetNextFrame( + DWORD dwMillisecondsToWait, + NUI_SKELETON_FRAME* pSkeletonFrame) { + if (pSkeletonFrame == nullptr) { + return E_POINTER; + } + if (!skeleton_enabled_) { + return E_NUI_STREAM_NOT_ENABLED; + } + + const DWORD wait = WaitForSingleObject(skeleton_ready_event_, + dwMillisecondsToWait); + if (wait != WAIT_OBJECT_0) { + if (skeleton_flags_ & + NUI_SKELETON_TRACKING_FLAG_TITLE_SETS_TRACKED_SKELETONS) { + return S_FALSE; + } + return E_NUI_FRAME_NO_DATA; + } + + EnterCriticalSection(&lock_); + if (!has_skeleton_) { + LeaveCriticalSection(&lock_); + return E_NUI_FRAME_NO_DATA; + } + *pSkeletonFrame = latest_skeleton_; + last_delivered_skeleton_frame_ = latest_skeleton_.dwFrameNumber; + ResetEvent(skeleton_ready_event_); + LeaveCriticalSection(&lock_); + return S_OK; +} + +HRESULT VirtualKinectSensor::ImageStreamOpen(NUI_IMAGE_TYPE eImageType, + NUI_IMAGE_RESOLUTION eResolution, + DWORD, + DWORD dwFrameLimit, + HANDLE hNextFrameEvent, + HANDLE* phStreamHandle) { + if (phStreamHandle == nullptr) { + return E_POINTER; + } + uint32_t width = 0; + uint32_t height = 0; + if (!resolution_to_size(eResolution, width, height)) { + return E_INVALIDARG; + } + + uint32_t bpp = 2; + switch (eImageType) { + case NUI_IMAGE_TYPE_COLOR: + case NUI_IMAGE_TYPE_COLOR_YUV: + case NUI_IMAGE_TYPE_COLOR_RAW_YUV: + bpp = 4; + break; + case NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX: + case NUI_IMAGE_TYPE_DEPTH: + case NUI_IMAGE_TYPE_COLOR_INFRARED: + bpp = 2; + break; + default: + return E_INVALIDARG; + } + + EnterCriticalSection(&lock_); + ImageStream* slot = nullptr; + for (auto& stream : streams_) { + if (stream.open && stream.type == eImageType) { + slot = &stream; + break; + } + } + if (slot == nullptr) { + for (auto& stream : streams_) { + if (!stream.open) { + slot = &stream; + break; + } + } + } + if (slot == nullptr) { + LeaveCriticalSection(&lock_); + return E_NUI_DEVICE_NOT_READY; + } + + for (auto* texture : slot->ring) { + if (texture != nullptr) { + texture->Release(); + } + } + + slot->open = true; + slot->type = eImageType; + slot->resolution = eResolution; + slot->width = width; + slot->height = height; + slot->bytes_per_pixel = bpp; + slot->app_event = hNextFrameEvent; + slot->ring_size = std::clamp( + dwFrameLimit == 0 ? 2 : dwFrameLimit, 2, 4); + slot->ring.assign(slot->ring_size, nullptr); + slot->frames.assign(slot->ring_size, NUI_IMAGE_FRAME{}); + for (std::size_t i = 0; i < slot->ring_size; ++i) { + slot->ring[i] = new NuiFrameTexture(width, height, bpp); + } + slot->write_index = 0; + slot->latest_index = 0; + slot->has_frame = false; + slot->outstanding = false; + + *phStreamHandle = reinterpret_cast(slot); + LeaveCriticalSection(&lock_); + return S_OK; +} + +ImageStream* VirtualKinectSensor::StreamFromHandle(HANDLE hStream) { + for (auto& stream : streams_) { + if (stream.open && reinterpret_cast(&stream) == hStream) { + return &stream; + } + } + return nullptr; +} + +HRESULT VirtualKinectSensor::ImageStreamGetNextFrame( + HANDLE hStream, + DWORD dwMillisecondsToWait, + const NUI_IMAGE_FRAME** ppcImageFrame) { + if (ppcImageFrame == nullptr) { + return E_POINTER; + } + ImageStream* stream = nullptr; + HANDLE app_event = nullptr; + EnterCriticalSection(&lock_); + stream = StreamFromHandle(hStream); + if (stream != nullptr) { + app_event = stream->app_event; + } + LeaveCriticalSection(&lock_); + if (stream == nullptr) { + return E_INVALIDARG; + } + + if (app_event != nullptr) { + const DWORD wait = WaitForSingleObject(app_event, dwMillisecondsToWait); + if (wait != WAIT_OBJECT_0) { + return E_NUI_FRAME_NO_DATA; + } + } + + EnterCriticalSection(&lock_); + if (!stream->has_frame) { + LeaveCriticalSection(&lock_); + return E_NUI_FRAME_NO_DATA; + } + stream->outstanding = true; + *ppcImageFrame = &stream->frames[stream->latest_index]; + LeaveCriticalSection(&lock_); + return S_OK; +} + +HRESULT VirtualKinectSensor::ImageStreamReleaseFrame( + HANDLE hStream, + const NUI_IMAGE_FRAME* pImageFrame) { + if (pImageFrame == nullptr) { + return E_INVALIDARG; + } + EnterCriticalSection(&lock_); + ImageStream* stream = StreamFromHandle(hStream); + if (stream == nullptr) { + LeaveCriticalSection(&lock_); + return E_INVALIDARG; + } + if (pImageFrame->pFrameTexture == nullptr) { + LeaveCriticalSection(&lock_); + return E_NOINTERFACE; + } + stream->outstanding = false; + LeaveCriticalSection(&lock_); + return S_OK; +} + +void VirtualKinectSensor::BuildSkeletonFrame(const SourceFrame& src) { + NUI_SKELETON_FRAME frame{}; + LARGE_INTEGER ts; + ts.QuadPart = src.meta.timestamp_micros / 1000; + frame.liTimeStamp = ts; + frame.dwFrameNumber = src.meta.frame_number; + frame.dwFlags = 0; + + for (auto& data : frame.SkeletonData) { + data.eTrackingState = NUI_SKELETON_NOT_TRACKED; + data.dwTrackingID = 0; + for (auto& state : data.eSkeletonPositionTrackingState) { + state = NUI_SKELETON_POSITION_NOT_TRACKED; + } + } + + if (src.has_player) { + NUI_SKELETON_DATA& data = frame.SkeletonData[0]; + data.eTrackingState = NUI_SKELETON_TRACKED; + data.dwTrackingID = src.meta.skeleton.skeleton_tracking_id; + data.dwEnrollmentIndex = 0; + data.dwUserIndex = 0; + data.dwQualityFlags = src.meta.skeleton.quality_flags; + const contract::Vector4& hip = + src.meta.skeleton.joints[NUI_SKELETON_POSITION_HIP_CENTER].position; + data.Position = {hip.x, hip.y, hip.z, hip.w}; + for (std::size_t j = 0; j < contract::kJointCount; ++j) { + const contract::JointData& joint = src.meta.skeleton.joints[j]; + data.SkeletonPositions[j] = {joint.position.x, joint.position.y, + joint.position.z, joint.position.w}; + data.eSkeletonPositionTrackingState[j] = + MapJointState(joint.tracking_state); + } + } + + latest_skeleton_ = frame; + has_skeleton_ = true; +} + +void VirtualKinectSensor::FillStreams(const SourceFrame& src) { + for (auto& stream : streams_) { + if (!stream.open || stream.outstanding) { + continue; + } + const std::size_t next = (stream.has_frame) + ? (stream.latest_index + 1) % stream.ring_size + : stream.write_index; + NuiFrameTexture* texture = stream.ring[next]; + if (texture == nullptr) { + continue; + } + + if (stream.type == NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX || + stream.type == NUI_IMAGE_TYPE_DEPTH) { + std::vector depth = ResizeDepthNearest( + src.depth_pixels, src.meta.depth.width, src.meta.depth.height, + stream.width, stream.height); + if (stream.type == NUI_IMAGE_TYPE_DEPTH) { + for (auto& pixel : depth) { + pixel = static_cast(pixel & ~kPlayerIndexMask); + } + } + texture->set_bits(reinterpret_cast(depth.data()), + depth.size() * sizeof(uint16_t)); + } else if (stream.type == NUI_IMAGE_TYPE_COLOR_INFRARED) { + synth::BgraFrame source_color{ + {src.meta.color.width, src.meta.color.height}, + src.meta.color.width * 4u, + src.color_pixels}; + synth::InfraredFrame ir = synth::synthesize_infrared( + source_color, {stream.width, stream.height}); + texture->set_bits(reinterpret_cast(ir.pixels.data()), + ir.pixels.size() * sizeof(uint16_t)); + } else { + synth::BgraFrame source_color{ + {src.meta.color.width, src.meta.color.height}, + src.meta.color.width * 4u, + src.color_pixels}; + synth::BgraFrame color = synth::passthrough_color( + source_color, {stream.width, stream.height}); + texture->set_bits(color.pixels.data(), color.pixels.size()); + } + + NUI_IMAGE_FRAME& image = stream.frames[next]; + LARGE_INTEGER ts; + ts.QuadPart = src.meta.timestamp_micros / 1000; + image.liTimeStamp = ts; + image.dwFrameNumber = src.meta.frame_number; + image.eImageType = stream.type; + image.eResolution = stream.resolution; + image.pFrameTexture = texture; + image.dwFrameFlags = 0; + image.ViewArea.eDigitalZoom = NUI_IMAGE_DIGITAL_ZOOM_1X; + image.ViewArea.lCenterX = 0; + image.ViewArea.lCenterY = 0; + + stream.latest_index = next; + stream.write_index = (next + 1) % stream.ring_size; + stream.has_frame = true; + if (stream.app_event != nullptr) { + SetEvent(stream.app_event); + } + } +} + +void VirtualKinectSensor::ProducerLoop() { + LARGE_INTEGER frequency; + LARGE_INTEGER start; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&start); + uint32_t frame_number = 0; + + while (WaitForSingleObject(stop_event_, 0) != WAIT_OBJECT_0) { + LARGE_INTEGER now; + QueryPerformanceCounter(&now); + const int64_t micros = + (now.QuadPart - start.QuadPart) * 1000000 / frequency.QuadPart; + + SourceFrame src; + const bool got = source_.is_open() && source_.read_latest(src); + if (!got) { + src = SourceFrame{}; + src.has_player = false; + src.meta.depth.width = 640; + src.meta.depth.height = 480; + src.meta.color.width = 640; + src.meta.color.height = 480; + src.depth_pixels.assign(640u * 480u, 0); + src.color_pixels.assign(640u * 480u * 4u, 0); + } + ++frame_number; + src.meta.frame_number = frame_number; + src.meta.timestamp_micros = micros; + + EnterCriticalSection(&lock_); + if (skeleton_enabled_) { + BuildSkeletonFrame(src); + SetEvent(skeleton_ready_event_); + if (skeleton_app_event_ != nullptr) { + SetEvent(skeleton_app_event_); + } + } + FillStreams(src); + LeaveCriticalSection(&lock_); + + WaitForSingleObject(stop_event_, kFramePeriodMs); + } +} + +DWORD WINAPI VirtualKinectSensor::ProducerThunk(LPVOID param) { + static_cast(param)->ProducerLoop(); + return 0; +} + +VirtualKinectSensor* GlobalSensor() { return g_sensor; } + +VirtualKinectSensor* EnsureGlobalSensor() { + EnterCriticalSection(&SensorLock()); + if (g_sensor == nullptr) { + g_sensor = new VirtualKinectSensor(); + } + VirtualKinectSensor* sensor = g_sensor; + LeaveCriticalSection(&SensorLock()); + return sensor; +} + +void DestroyGlobalSensor() { + EnterCriticalSection(&SensorLock()); + if (g_sensor != nullptr) { + delete g_sensor; + g_sensor = nullptr; + } + LeaveCriticalSection(&SensorLock()); +} + +} diff --git a/fallback/windows-nui/src/sensor.h b/fallback/windows-nui/src/sensor.h new file mode 100644 index 0000000..0918328 --- /dev/null +++ b/fallback/windows-nui/src/sensor.h @@ -0,0 +1,100 @@ +#ifndef FALLBACK_WINDOWS_NUI_SENSOR_H +#define FALLBACK_WINDOWS_NUI_SENSOR_H + +#include + +#include +#include +#include + +#include "core_alias.h" +#include "frame_source.h" +#include "frame_texture.h" +#include "nui_abi.h" +#include "nui_interfaces.h" + +namespace nui_shim { + +constexpr DWORD kFramePeriodMs = 33; +constexpr std::size_t kMaxStreams = 4; + +bool resolution_to_size(NUI_IMAGE_RESOLUTION resolution, + uint32_t& width, + uint32_t& height); + +struct ImageStream { + bool open = false; + NUI_IMAGE_TYPE type = NUI_IMAGE_TYPE_DEPTH_AND_PLAYER_INDEX; + NUI_IMAGE_RESOLUTION resolution = NUI_IMAGE_RESOLUTION_640x480; + uint32_t width = 0; + uint32_t height = 0; + uint32_t bytes_per_pixel = 2; + HANDLE app_event = nullptr; + std::vector ring; + std::vector frames; + std::size_t ring_size = 2; + std::size_t write_index = 0; + std::size_t latest_index = 0; + bool has_frame = false; + bool outstanding = false; +}; + +class VirtualKinectSensor { + public: + VirtualKinectSensor(); + ~VirtualKinectSensor(); + + HRESULT Initialize(DWORD dwFlags); + void Shutdown(); + DWORD InitializationFlags() const; + HRESULT Status() const; + + HRESULT SkeletonTrackingEnable(HANDLE hNextFrameEvent, DWORD dwFlags); + HRESULT SkeletonTrackingDisable(); + HRESULT SkeletonGetNextFrame(DWORD dwMillisecondsToWait, + NUI_SKELETON_FRAME* pSkeletonFrame); + + HRESULT ImageStreamOpen(NUI_IMAGE_TYPE eImageType, + NUI_IMAGE_RESOLUTION eResolution, + DWORD dwImageFrameFlags, + DWORD dwFrameLimit, + HANDLE hNextFrameEvent, + HANDLE* phStreamHandle); + HRESULT ImageStreamGetNextFrame(HANDLE hStream, + DWORD dwMillisecondsToWait, + const NUI_IMAGE_FRAME** ppcImageFrame); + HRESULT ImageStreamReleaseFrame(HANDLE hStream, + const NUI_IMAGE_FRAME* pImageFrame); + + private: + void ProducerLoop(); + static DWORD WINAPI ProducerThunk(LPVOID param); + void BuildSkeletonFrame(const SourceFrame& src); + void FillStreams(const SourceFrame& src); + ImageStream* StreamFromHandle(HANDLE hStream); + + CRITICAL_SECTION lock_; + FrameSource source_; + HANDLE producer_thread_ = nullptr; + HANDLE stop_event_ = nullptr; + bool initialized_ = false; + DWORD init_flags_ = 0; + + bool skeleton_enabled_ = false; + DWORD skeleton_flags_ = 0; + HANDLE skeleton_app_event_ = nullptr; + HANDLE skeleton_ready_event_ = nullptr; + NUI_SKELETON_FRAME latest_skeleton_{}; + bool has_skeleton_ = false; + uint32_t last_delivered_skeleton_frame_ = 0; + + std::array streams_{}; +}; + +VirtualKinectSensor* GlobalSensor(); +VirtualKinectSensor* EnsureGlobalSensor(); +void DestroyGlobalSensor(); + +} + +#endif diff --git a/fallback/windows-nui/src/sensor_com.cpp b/fallback/windows-nui/src/sensor_com.cpp new file mode 100644 index 0000000..4c2cdb3 --- /dev/null +++ b/fallback/windows-nui/src/sensor_com.cpp @@ -0,0 +1,218 @@ +#include "sensor_com.h" + +#include "coordmap.h" + +namespace nui_shim { + +NuiSensorCom::NuiSensorCom(VirtualKinectSensor* sensor) : sensor_(sensor) {} + +HRESULT STDMETHODCALLTYPE NuiSensorCom::QueryInterface(REFIID riid, void** ppv) { + if (ppv == nullptr) { + return E_POINTER; + } + if (IsEqualIID(riid, IID_IUnknown)) { + *ppv = static_cast(this); + AddRef(); + return S_OK; + } + *ppv = nullptr; + return E_NOINTERFACE; +} + +ULONG STDMETHODCALLTYPE NuiSensorCom::AddRef() { + return static_cast(InterlockedIncrement(&ref_count_)); +} + +ULONG STDMETHODCALLTYPE NuiSensorCom::Release() { + const LONG count = InterlockedDecrement(&ref_count_); + if (count == 0) { + delete this; + } + return static_cast(count); +} + +HRESULT STDMETHODCALLTYPE NuiSensorCom::NuiInitialize(DWORD dwFlags) { + return sensor_->Initialize(dwFlags); +} + +void STDMETHODCALLTYPE NuiSensorCom::NuiShutdown() { sensor_->Shutdown(); } + +HRESULT STDMETHODCALLTYPE NuiSensorCom::NuiSetFrameEndEvent(HANDLE, DWORD) { + return S_OK; +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiImageStreamOpen(NUI_IMAGE_TYPE eImageType, + NUI_IMAGE_RESOLUTION eResolution, + DWORD dwImageFrameFlags, + DWORD dwFrameLimit, + HANDLE hNextFrameEvent, + HANDLE* phStreamHandle) { + return sensor_->ImageStreamOpen(eImageType, eResolution, dwImageFrameFlags, + dwFrameLimit, hNextFrameEvent, + phStreamHandle); +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiImageStreamSetImageFrameFlags(HANDLE, DWORD) { + return S_OK; +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiImageStreamGetImageFrameFlags(HANDLE, DWORD* pdwImageFrameFlags) { + if (pdwImageFrameFlags == nullptr) { + return E_POINTER; + } + *pdwImageFrameFlags = 0; + return S_OK; +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiImageStreamGetNextFrame(HANDLE hStream, + DWORD dwMillisecondsToWait, + const NUI_IMAGE_FRAME** ppcImageFrame) { + return sensor_->ImageStreamGetNextFrame(hStream, dwMillisecondsToWait, + ppcImageFrame); +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiImageStreamReleaseFrame(HANDLE hStream, + const NUI_IMAGE_FRAME* pImageFrame) { + return sensor_->ImageStreamReleaseFrame(hStream, pImageFrame); +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiImageGetColorPixelCoordinatesFromDepthPixel( + NUI_IMAGE_RESOLUTION eColorResolution, + const NUI_IMAGE_VIEW_AREA*, + LONG lDepthX, + LONG lDepthY, + USHORT, + LONG* plColorX, + LONG* plColorY) { + return ColorCoordinatesFromDepthPixel(eColorResolution, lDepthX, lDepthY, + plColorX, plColorY); +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution( + NUI_IMAGE_RESOLUTION eColorResolution, + NUI_IMAGE_RESOLUTION, + const NUI_IMAGE_VIEW_AREA*, + LONG lDepthX, + LONG lDepthY, + USHORT, + LONG* plColorX, + LONG* plColorY) { + return ColorCoordinatesFromDepthPixel(eColorResolution, lDepthX, lDepthY, + plColorX, plColorY); +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiGetColorPixelCoordinateFrameFromDepthPixelFrameAtResolution( + NUI_IMAGE_RESOLUTION, + NUI_IMAGE_RESOLUTION, + DWORD, + USHORT*, + DWORD, + LONG*) { + return E_NOTIMPL; +} + +HRESULT STDMETHODCALLTYPE NuiSensorCom::NuiCameraElevationSetAngle(LONG) { + return S_OK; +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiCameraElevationGetAngle(LONG* plAngleDegrees) { + if (plAngleDegrees == nullptr) { + return E_POINTER; + } + *plAngleDegrees = 0; + return S_OK; +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiSkeletonTrackingEnable(HANDLE hNextFrameEvent, DWORD dwFlags) { + return sensor_->SkeletonTrackingEnable(hNextFrameEvent, dwFlags); +} + +HRESULT STDMETHODCALLTYPE NuiSensorCom::NuiSkeletonTrackingDisable() { + return sensor_->SkeletonTrackingDisable(); +} + +HRESULT STDMETHODCALLTYPE NuiSensorCom::NuiSkeletonSetTrackedSkeletons(DWORD*) { + return S_OK; +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiSkeletonGetNextFrame(DWORD dwMillisecondsToWait, + NUI_SKELETON_FRAME* pSkeletonFrame) { + return sensor_->SkeletonGetNextFrame(dwMillisecondsToWait, pSkeletonFrame); +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiTransformSmooth(NUI_SKELETON_FRAME* pSkeletonFrame, + const NUI_TRANSFORM_SMOOTH_PARAMETERS* pSmoothingParams) { + if (pSkeletonFrame == nullptr) { + return E_POINTER; + } + TransformSmooth(pSkeletonFrame, pSmoothingParams); + return S_OK; +} + +HRESULT STDMETHODCALLTYPE NuiSensorCom::NuiGetAudioSource(IUnknown** ppDmo) { + if (ppDmo != nullptr) { + *ppDmo = nullptr; + } + return E_NOTIMPL; +} + +int STDMETHODCALLTYPE NuiSensorCom::NuiInstanceIndex() { return 0; } + +BSTR STDMETHODCALLTYPE NuiSensorCom::NuiDeviceConnectionId() { + return SysAllocString(L"USB\\VID_045E&PID_02AE\\VirtualKinect0"); +} + +BSTR STDMETHODCALLTYPE NuiSensorCom::NuiUniqueId() { + return SysAllocString(L"VirtualKinect0"); +} + +BSTR STDMETHODCALLTYPE NuiSensorCom::NuiAudioArrayId() { + return SysAllocString(L"VirtualKinectAudio0"); +} + +HRESULT STDMETHODCALLTYPE NuiSensorCom::NuiStatus() { return sensor_->Status(); } + +DWORD STDMETHODCALLTYPE NuiSensorCom::NuiInitializationFlags() { + return sensor_->InitializationFlags(); +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiGetCoordinateMapper(INuiCoordinateMapper** ppCoordinateMapper) { + if (ppCoordinateMapper != nullptr) { + *ppCoordinateMapper = nullptr; + } + return E_NOTIMPL; +} + +HRESULT STDMETHODCALLTYPE +NuiSensorCom::NuiImageFrameGetDepthImagePixelFrameTexture( + HANDLE, + const NUI_IMAGE_FRAME* pImageFrame, + BOOL* pNearMode, + INuiFrameTexture** ppFrameTexture) { + if (ppFrameTexture == nullptr || pImageFrame == nullptr) { + return E_POINTER; + } + if (pNearMode != nullptr) { + *pNearMode = FALSE; + } + *ppFrameTexture = pImageFrame->pFrameTexture; + if (*ppFrameTexture != nullptr) { + (*ppFrameTexture)->AddRef(); + } + return S_OK; +} + +} diff --git a/fallback/windows-nui/src/sensor_com.h b/fallback/windows-nui/src/sensor_com.h new file mode 100644 index 0000000..882b2de --- /dev/null +++ b/fallback/windows-nui/src/sensor_com.h @@ -0,0 +1,102 @@ +#ifndef FALLBACK_WINDOWS_NUI_SENSOR_COM_H +#define FALLBACK_WINDOWS_NUI_SENSOR_COM_H + +#include + +#include "nui_abi.h" +#include "nui_interfaces.h" +#include "sensor.h" + +namespace nui_shim { + +class NuiSensorCom : public INuiSensor { + public: + explicit NuiSensorCom(VirtualKinectSensor* sensor); + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override; + ULONG STDMETHODCALLTYPE AddRef() override; + ULONG STDMETHODCALLTYPE Release() override; + + HRESULT STDMETHODCALLTYPE NuiInitialize(DWORD dwFlags) override; + void STDMETHODCALLTYPE NuiShutdown() override; + HRESULT STDMETHODCALLTYPE NuiSetFrameEndEvent(HANDLE hEvent, + DWORD dwFrameEventFlag) override; + HRESULT STDMETHODCALLTYPE + NuiImageStreamOpen(NUI_IMAGE_TYPE eImageType, + NUI_IMAGE_RESOLUTION eResolution, + DWORD dwImageFrameFlags, + DWORD dwFrameLimit, + HANDLE hNextFrameEvent, + HANDLE* phStreamHandle) override; + HRESULT STDMETHODCALLTYPE + NuiImageStreamSetImageFrameFlags(HANDLE hStream, DWORD dwImageFrameFlags) override; + HRESULT STDMETHODCALLTYPE + NuiImageStreamGetImageFrameFlags(HANDLE hStream, DWORD* pdwImageFrameFlags) override; + HRESULT STDMETHODCALLTYPE + NuiImageStreamGetNextFrame(HANDLE hStream, + DWORD dwMillisecondsToWait, + const NUI_IMAGE_FRAME** ppcImageFrame) override; + HRESULT STDMETHODCALLTYPE + NuiImageStreamReleaseFrame(HANDLE hStream, + const NUI_IMAGE_FRAME* pImageFrame) override; + HRESULT STDMETHODCALLTYPE + NuiImageGetColorPixelCoordinatesFromDepthPixel(NUI_IMAGE_RESOLUTION eColorResolution, + const NUI_IMAGE_VIEW_AREA* pcViewArea, + LONG lDepthX, + LONG lDepthY, + USHORT usDepthValue, + LONG* plColorX, + LONG* plColorY) override; + HRESULT STDMETHODCALLTYPE + NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution( + NUI_IMAGE_RESOLUTION eColorResolution, + NUI_IMAGE_RESOLUTION eDepthResolution, + const NUI_IMAGE_VIEW_AREA* pcViewArea, + LONG lDepthX, + LONG lDepthY, + USHORT usDepthValue, + LONG* plColorX, + LONG* plColorY) override; + HRESULT STDMETHODCALLTYPE + NuiGetColorPixelCoordinateFrameFromDepthPixelFrameAtResolution( + NUI_IMAGE_RESOLUTION eColorResolution, + NUI_IMAGE_RESOLUTION eDepthResolution, + DWORD cDepthValues, + USHORT* pDepthValues, + DWORD cColorCoordinates, + LONG* pColorCoordinates) override; + HRESULT STDMETHODCALLTYPE NuiCameraElevationSetAngle(LONG lAngleDegrees) override; + HRESULT STDMETHODCALLTYPE NuiCameraElevationGetAngle(LONG* plAngleDegrees) override; + HRESULT STDMETHODCALLTYPE NuiSkeletonTrackingEnable(HANDLE hNextFrameEvent, + DWORD dwFlags) override; + HRESULT STDMETHODCALLTYPE NuiSkeletonTrackingDisable() override; + HRESULT STDMETHODCALLTYPE NuiSkeletonSetTrackedSkeletons(DWORD* pTrackingIDs) override; + HRESULT STDMETHODCALLTYPE + NuiSkeletonGetNextFrame(DWORD dwMillisecondsToWait, + NUI_SKELETON_FRAME* pSkeletonFrame) override; + HRESULT STDMETHODCALLTYPE + NuiTransformSmooth(NUI_SKELETON_FRAME* pSkeletonFrame, + const NUI_TRANSFORM_SMOOTH_PARAMETERS* pSmoothingParams) override; + HRESULT STDMETHODCALLTYPE NuiGetAudioSource(IUnknown** ppDmo) override; + int STDMETHODCALLTYPE NuiInstanceIndex() override; + BSTR STDMETHODCALLTYPE NuiDeviceConnectionId() override; + BSTR STDMETHODCALLTYPE NuiUniqueId() override; + BSTR STDMETHODCALLTYPE NuiAudioArrayId() override; + HRESULT STDMETHODCALLTYPE NuiStatus() override; + DWORD STDMETHODCALLTYPE NuiInitializationFlags() override; + HRESULT STDMETHODCALLTYPE + NuiGetCoordinateMapper(INuiCoordinateMapper** ppCoordinateMapper) override; + HRESULT STDMETHODCALLTYPE + NuiImageFrameGetDepthImagePixelFrameTexture(HANDLE hStream, + const NUI_IMAGE_FRAME* pImageFrame, + BOOL* pNearMode, + INuiFrameTexture** ppFrameTexture) override; + + private: + LONG ref_count_ = 1; + VirtualKinectSensor* sensor_; +}; + +} + +#endif diff --git a/fallback/windows-nui/toolchain-mingw-x64.cmake b/fallback/windows-nui/toolchain-mingw-x64.cmake new file mode 100644 index 0000000..8d59f58 --- /dev/null +++ b/fallback/windows-nui/toolchain-mingw-x64.cmake @@ -0,0 +1,11 @@ +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_SYSTEM_PROCESSOR x86_64) + +set(MINGW_PREFIX x86_64-w64-mingw32) +set(CMAKE_C_COMPILER ${MINGW_PREFIX}-gcc-win32) +set(CMAKE_CXX_COMPILER ${MINGW_PREFIX}-g++-win32) +set(CMAKE_RC_COMPILER ${MINGW_PREFIX}-windres) + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/fallback/windows-nui/toolchain-mingw-x86.cmake b/fallback/windows-nui/toolchain-mingw-x86.cmake new file mode 100644 index 0000000..e01144d --- /dev/null +++ b/fallback/windows-nui/toolchain-mingw-x86.cmake @@ -0,0 +1,11 @@ +set(CMAKE_SYSTEM_NAME Windows) +set(CMAKE_SYSTEM_PROCESSOR x86) + +set(MINGW_PREFIX i686-w64-mingw32) +set(CMAKE_C_COMPILER ${MINGW_PREFIX}-gcc-posix) +set(CMAKE_CXX_COMPILER ${MINGW_PREFIX}-g++-posix) +set(CMAKE_RC_COMPILER ${MINGW_PREFIX}-windres) + +set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) +set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) +set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)