feat(attach-linux,fallback-openni2): usbip shim (socket-verified) + OpenNI2 SynthKinect driver (depth verified via real consumer) (wave 6; todo 15 done, 9 partial)
ci / Linux C++ core (cmake + ctest) (push) Canceled after 0s
ci / Python tracker (pytest) (push) Canceled after 0s

This commit is contained in:
kinect-bot committed 2026-11-25 05:09:31 -05:00
1 parent cb311381a2
commit 76f3b6447f
19 files changed
+2241 -8

No files matched your search

+4 -2
View File
@@ -196,7 +196,8 @@ Your next move: run the default-on high-accuracy review (in progress), then exec
Commit: Y | feat(protocol): kinect v1 virtual usb device emitter
Recommended task executor category: deep-high - protocol fidelity is central and failure-prone.
- [ ] 9. Linux USB attach (usbip/vhci)
- [~] 9. Linux USB attach (usbip/vhci)
PARTIAL/BLOCKED: USB/IP server protocol VERIFIED via live socket round-trip (OP_REQ_DEVLIST/IMPORT/CMD_SUBMIT -> byte-correct Kinect v1 descriptor) + shim compiles; final vhci KERNEL attach [~] blocked (no usbip userspace, vhci unloaded, no sudo; confirmed not installable for this WSL2 kernel).
What to do / Must NOT do: In `attach/linux/`, bind the todo-8 emitter as a virtual USB device via USB/IP (userspace server speaking the Kinect descriptors) attached through `vhci-hcd`, or raw-gadget if simpler; provide attach/detach lifecycle + a CLI. Must NOT: require out-of-tree kernel modules beyond stock usbip/vhci.
Closes: GAP-3 (Linux half)
Parallelization: Wave 6 | Blocked by: 8,3 | Blocks: 10
@@ -256,7 +257,8 @@ Your next move: run the default-on high-accuracy review (in progress), then exec
Commit: Y | feat(fallback-nui): clean-room kinect10.dll shim
Recommended task executor category: deep-high - ABI-exact Windows DLL, large cohesive surface.
- [ ] 15. Linux OpenNI2 virtual-device fallback / general emulator
- [x] 15. Linux OpenNI2 virtual-device fallback / general emulator
NOTE (exec): VERIFIED on Linux - an independent OpenNI2 consumer (stock libOpenNI2) opened our custom 'SynthKinect' driver and read a 320x240 depth frame, 31075 in-band (800-4000mm) body pixels matching the synth rasterizer. Color implemented-but-unverified; skeleton [~] (NiTE2 EOL/absent).
What to do / Must NOT do: In `fallback/linux-openni2/`, an OpenNI2 device-driver module exposing the synth streams (depth/color + the mask) as an OpenNI2 device, so OpenNI/NiTE apps work even without the usbip path; doubles as the Linux general-emulator surface (IS-9). UNCONDITIONALLY in scope (general-purpose goal); spike 3 sets priority/order, not whether it is built. Must NOT: duplicate synth logic - consume `core/synth`; bundle NiTE2 (EOL/not redistributable).
Closes: GAP-6 (Linux fallback)
Parallelization: Wave 6 | Blocked by: 7,2 | Blocks: none
+34
View File
@@ -0,0 +1,34 @@
cmake_minimum_required(VERSION 3.20)
project(kinect_attach_linux LANGUAGES CXX)
if(NOT UNIX)
message(FATAL_ERROR "attach/linux is Linux-only (USB/IP + vhci-hcd + POSIX sockets); do not build it elsewhere.")
endif()
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
# Standalone build: links the protocol core from ../../core without touching
# that project's CMakeLists.txt or its build/linux output directory. Tests
# are disabled for this embed so configuring here never fetches googletest
# (the core project's own test target is irrelevant to this shim).
set(NUI_CORE_BUILD_TESTS OFF CACHE BOOL "" FORCE)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../.. ${CMAKE_CURRENT_BINARY_DIR}/core)
add_library(kinect_attach_linux_lib STATIC
src/usbip_protocol.cpp
src/usbip_server.cpp
src/vhci_lifecycle.cpp
src/kinect_export.cpp
)
target_include_directories(kinect_attach_linux_lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(kinect_attach_linux_lib PUBLIC libnui_core)
add_executable(kinect_attach src/main.cpp)
target_link_libraries(kinect_attach PRIVATE kinect_attach_linux_lib)
enable_testing()
add_executable(kinect_attach_linux_tests tests/test_usbip_protocol.cpp)
target_link_libraries(kinect_attach_linux_tests PRIVATE kinect_attach_linux_lib)
add_test(NAME usbip_protocol_roundtrip COMMAND kinect_attach_linux_tests)
+138 -3
View File
@@ -1,5 +1,140 @@
# attach/linux/ — Linux USB attach via usbip/vhci (todo 9)
Binds the `core/protocol` emitter as a virtual USB device through USB/IP + `vhci-hcd`
(or raw-gadget), with attach/detach lifecycle + CLI. No out-of-tree kernel modules
beyond stock usbip/vhci. Placeholder until todo 9.
Presents the `core/protocol` emitter (`nui::protocol::KinectV1Device`, a
`UsbDeviceBackend`) as a Linux USB/IP-exportable virtual Kinect v1: a
userspace USB/IP **server** speaking the Kinect's three sibling-device
descriptors (camera `1-1`, audio `1-2`, motor `1-3` — see
`core/protocol/wire.h`) plus control transfers and iso-style stream packets,
attachable through the stock `vhci-hcd` kernel driver + `usbip` client CLI.
No out-of-tree kernel modules.
## Status in THIS environment: runtime attach is **[~] BLOCKED**
Verified on this box (2026-11-25, same findings as `docs/spike-linux.md`
todo 3):
| Check | Result |
| --- | --- |
| `uname -r` | `6.6.87.2-microsoft-standard-WSL2` |
| `modprobe -n -v vhci-hcd` | resolves the full chain (`usb-common` → `usbcore` → `usbip-core` → `vhci-hcd`), so the module **exists** in this kernel |
| `lsmod \| grep vhci` | **not loaded** (exit 1) |
| `/sys/devices/platform/vhci_hcd*` | **does not exist** (module never loaded → no vhci sysfs attach points) |
| `command -v usbip` | **absent** (exit 1) — no usbip userspace client is installed |
| `sudo -n true` | **requires interactive auth** — no non-interactive sudo available to this session |
**Bounded no-sudo installability check** (this task's own probe, run before
writing this doc): `apt-get download usbip` → `E: Unable to locate package
usbip` (no such package name on this Ubuntu release). `apt-get download
linux-tools-generic` succeeds (no sudo needed — `apt-get download` writes to
the cwd), but extracting it (`dpkg-deb -x`) shows it is an **empty
meta-package**: its only payload is `usr/share/doc/...` (changelog +
copyright), zero binaries. The real `usbip` binary ships inside a
kernel-version-specific package (`linux-tools-<exact-uname-r>` /
`linux-tools-<flavour>`), which does not exist for a custom WSL2 kernel
string (`6.6.87.2-microsoft-standard-WSL2` is not an Ubuntu package suffix).
**Conclusion: usbip userspace is not installable here even with sudo**,
because no matching `linux-tools-*` package is published for this kernel;
the no-sudo path was checked first and independently fails for the same
underlying reason (no matching package, not merely a permissions problem).
Runtime attach (`lsusb` showing `045e:02ae`/`02ad`/`02b0`, or
`freenect-glview`/an OpenNI viewer opening the device) **cannot be exercised
in this environment**. The code in this directory is complete and compiles;
only the live USB-level verification is blocked.
## What is implemented
- `include/attach_linux/usbip_protocol.h` + `src/usbip_protocol.cpp` — USB/IP
wire protocol encode/decode (`OP_REQ_DEVLIST`/`OP_REP_DEVLIST`,
`OP_REQ_IMPORT`/`OP_REP_IMPORT`, `USBIP_CMD_SUBMIT`/`USBIP_RET_SUBMIT`,
`USBIP_CMD_UNLINK`/`USBIP_RET_UNLINK`), transcribed from
<https://www.kernel.org/doc/html/latest/usb/usbip_protocol.html>
(retrieved 2026-11-25; protocol v1.1.1 / wire value `0x0111`). No sockets —
unit-tested as pure byte-buffer transforms.
- `include/attach_linux/usbip_server.h` + `src/usbip_server.cpp` — a
POSIX-socket `UsbipServer` that answers the device-list/import handshake
and then relays `USBIP_CMD_SUBMIT`/`USBIP_CMD_UNLINK` traffic into a
`nui::protocol::UsbDeviceBackend&`, one control + bulk/iso-style session
per connection.
- `include/attach_linux/kinect_export.h` + `src/kinect_export.cpp` — the
three exported-device descriptors (camera/audio/motor busids matching
`core/protocol/wire.h`'s VID/PID/bcdDevice) and a placeholder single-frame
`FrameSource` for standalone CLI testing (real frame data comes from the
tracker/synth pipeline at a higher integration layer — out of this todo's
scope).
- `include/attach_linux/vhci_lifecycle.h` + `src/vhci_lifecycle.cpp` —
thin wrappers around the stock `usbip` **client** CLI (`usbip attach`,
`usbip detach`, `usbip port`) and `modprobe vhci-hcd`; this shim is the
server half only, per todo 9's "no out-of-tree kernel modules beyond stock
usbip/vhci".
- `src/main.cpp` — the `kinect_attach` CLI: `serve`, `attach`, `detach`,
`list`, `--help`.
- `tests/test_usbip_protocol.cpp` — assert-based round-trip tests for every
encode/decode pair above, run via `ctest`.
## Build (achievable here)
```sh
cmake -S attach/linux -B attach/linux/build
cmake --build attach/linux/build
ctest --test-dir attach/linux/build
```
This is a standalone CMake project: it does **not** touch the root
`CMakeLists.txt` or `build/linux`. It pulls in `core/`'s `libnui_core` via
its own `add_subdirectory(../../core)` with `NUI_CORE_BUILD_TESTS=OFF`, so
configuring here never fetches googletest.
## Prerequisites to actually attach (once available)
1. **Install the usbip userspace** (needs a kernel whose `linux-tools-*`
package exists, or a from-source build of `tools/usb/usbip` against this
kernel's headers):
```sh
sudo apt-get install -y usbip # Ubuntu/Debian, if the package exists for your kernel
# or, if not packaged for your exact kernel string (WSL2's usual case):
# build tools/usb/usbip from a matching Linux kernel source tree
```
2. **Load vhci-hcd** (needs root):
```sh
sudo modprobe vhci-hcd
ls /sys/devices/platform/vhci_hcd.0 # must now exist
```
**WSL2 caveat**: even after a successful `modprobe`, WSL2's init can lack
the udev/sysfs plumbing `usbip` expects for hot-plug notification; if
`usbip attach` hangs or the imported device never appears under `lsusb`,
that plumbing gap — not this shim — is the next thing to debug. A
native-Linux host sidesteps it entirely.
## Run / attach / detach (once prerequisites are met)
```sh
# Terminal 1: start the server (defaults to port 3240, the usbip client's own default).
./attach/linux/build/kinect_attach serve --port 3240
# Terminal 2: attach the camera device through vhci-hcd.
sudo modprobe vhci-hcd
./attach/linux/build/kinect_attach attach --host 127.0.0.1 --port 3240 --busid 1-1
lsusb | grep 045e # expect 045e:02ae
# ... use the device (freenect-glview / an OpenNI2 viewer against it) ...
# Find the vhci port it landed on, then detach.
./attach/linux/build/kinect_attach list
./attach/linux/build/kinect_attach detach --vhci-port <N>
```
Repeat `attach` with `--busid 1-2` / `--busid 1-3` to also attach the audio
and motor sibling devices.
## Known simplifications (documented, not hidden)
- The placeholder `FrameSource` in `kinect_export.cpp` always returns one
all-background frame; it is for compiling/smoke-testing this shim only,
not a substitute for the tracker/synth pipeline (todos 5/7/10).
- Each `USBIP_CMD_SUBMIT` against a camera iso endpoint is answered with one
`UsbDeviceBackend::next_packet()` call (one USB/IP-tunnelled packet per
request), with no ISO packet descriptor array modelled — correct for this
server's read-only (IN) iso endpoints, where the client never sends ISO
descriptors on the wire it is requesting from (the OUT-direction case,
which never applies to these endpoints, is intentionally unhandled).
@@ -0,0 +1,34 @@
#ifndef NUI_ATTACH_LINUX_KINECT_EXPORT_H
#define NUI_ATTACH_LINUX_KINECT_EXPORT_H
#include <array>
#include "attach_linux/usbip_protocol.h"
#include "protocol/protocol.h"
namespace attach::linux_attach {
// The three USB/IP-exportable busids for one virtual Kinect v1 (camera,
// audio, motor — core/protocol/wire.h's three sibling USB functions), in
// UsbFunction enum order, with the EXACT descriptor fields
// core/protocol/descriptors.cpp (wire::device_descriptor/config_descriptor)
// already commits the device to over control transfers.
struct ExportSet {
std::array<usbip::ExportedDevice, 3> devices;
};
ExportSet default_export_set(uint32_t busnum);
nui::protocol::UsbFunction function_for_busid(const ExportSet& set, const std::string& busid);
const usbip::ExportedDevice* device_for_busid(const ExportSet& set, const std::string& busid);
// A placeholder frame source for the standalone `serve` CLI command: a
// single all-background (zero depth, black color) 640x480 frame, re-returned
// on every call. Real frame data comes from wiring this device to the
// tracker/synth pipeline (plan todos 5/7/10) at a higher integration layer
// that this attach shim does not own.
std::shared_ptr<const nui::protocol::SynthFrame> placeholder_frame_source();
} // namespace attach::linux_attach
#endif // NUI_ATTACH_LINUX_KINECT_EXPORT_H
@@ -0,0 +1,183 @@
#ifndef NUI_ATTACH_LINUX_USBIP_PROTOCOL_H
#define NUI_ATTACH_LINUX_USBIP_PROTOCOL_H
// USB/IP wire protocol (server side: "export" a USB device to a usbip client
// bound to vhci-hcd). All multi-byte fields are network byte order (big
// endian), per the Linux kernel documentation this was transcribed from:
// https://www.kernel.org/doc/html/latest/usb/usbip_protocol.html
// (retrieved 2026-11-25; protocol version v1.1.1, wire value 0x0111).
//
// This header only encodes/decodes byte buffers; it has no socket I/O so it
// can be unit-tested without a network stack (see tests/test_usbip_protocol).
#include <array>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
namespace attach::usbip {
using Bytes = std::vector<uint8_t>;
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
constexpr uint16_t kProtocolVersion = 0x0111;
// OP_* codes (control connection: device list + import handshake).
constexpr uint16_t kOpReqDevlist = 0x8005;
constexpr uint16_t kOpRepDevlist = 0x0005;
constexpr uint16_t kOpReqImport = 0x8003;
constexpr uint16_t kOpRepImport = 0x0003;
// USBIP_CMD_*/USBIP_RET_* basic-header 'command' values (data connection:
// URB submit/unlink after a successful import).
constexpr uint32_t kCmdSubmit = 0x00000001;
constexpr uint32_t kCmdUnlink = 0x00000002;
constexpr uint32_t kRetSubmit = 0x00000003;
constexpr uint32_t kRetUnlink = 0x00000004;
constexpr uint32_t kDirOut = 0;
constexpr uint32_t kDirIn = 1;
// usbip_header_basic / usbip_header are always this size before the
// variable-length transfer_buffer + iso_packet_descriptor tail (both
// USBIP_CMD_SUBMIT and USBIP_RET_SUBMIT share this fixed prefix length).
constexpr std::size_t kHeaderBasicSize = 20;
constexpr std::size_t kSubmitHeaderSize = 0x30; // 48
constexpr std::size_t kUnlinkHeaderSize = 0x30; // 48 (basic + unlink_seqnum + 24 pad)
// Linux errno values the server reports back to the client in RET_SUBMIT's
// status field (negative, per URB/errno convention) when a control transfer
// stalls or an endpoint/transfer is invalid. usbip itself just forwards
// whatever the real USB stack returned; a virtual device picks the same
// codes a real stalled endpoint would produce.
constexpr int32_t kErrnoPipeStall = -32; // -EPIPE
constexpr int32_t kErrnoNoDevice = -19; // -ENODEV
constexpr int32_t kErrnoConnReset = -104; // -ECONNRESET (RET_UNLINK success)
// ---------------------------------------------------------------------------
// OP_REQ_DEVLIST / OP_REP_DEVLIST / OP_REQ_IMPORT / OP_REP_IMPORT
// ---------------------------------------------------------------------------
// Common 8-byte prefix of every OP_* message: version(2) + code(2) + status(4).
struct OpHeader {
uint16_t version;
uint16_t code;
uint32_t status;
};
std::optional<OpHeader> decode_op_header(const Bytes& bytes);
Bytes encode_op_header(uint16_t code, uint32_t status);
// One USB interface's class/subclass/protocol triad, as carried in
// OP_REP_DEVLIST (4 bytes per interface including a zero pad byte).
struct InterfaceDescriptor {
uint8_t interface_class;
uint8_t interface_subclass;
uint8_t interface_protocol;
};
// Describes one USB/IP-exportable device (one Kinect v1 sibling function:
// camera, audio, or motor — see core/protocol/wire.h for the real values).
struct ExportedDevice {
std::string path; // synthetic sysfs-like path, <= 255 bytes, NUL-padded to 256
std::string busid; // e.g. "1-1", <= 31 bytes, NUL-padded to 32
uint32_t busnum;
uint32_t devnum;
uint32_t speed; // Linux enum usb_device_speed; Kinect v1 negotiates HIGH (3)
uint16_t id_vendor;
uint16_t id_product;
uint16_t bcd_device;
uint8_t device_class;
uint8_t device_subclass;
uint8_t device_protocol;
uint8_t configuration_value;
uint8_t num_configurations;
std::vector<InterfaceDescriptor> interfaces; // bNumInterfaces entries
};
// Appends one device's OP_REP_DEVLIST entry (path[256] + busid[32] + the
// fixed device fields + bNumInterfaces * 4-byte interface entries).
void append_device_entry(Bytes& out, const ExportedDevice& device);
Bytes encode_rep_devlist(const std::vector<ExportedDevice>& devices);
// Decodes the busid out of an OP_REQ_IMPORT body (the 32 bytes after the
// 8-byte OP header).
std::optional<std::string> decode_req_import_busid(const Bytes& body);
// OP_REP_IMPORT: status 0 + the device's import-reply fields (no interface
// list, unlike devlist) on success; status 1 with nothing else on failure.
Bytes encode_rep_import_ok(const ExportedDevice& device);
Bytes encode_rep_import_error();
// ---------------------------------------------------------------------------
// usbip_header_basic + USBIP_CMD_SUBMIT / USBIP_RET_SUBMIT /
// USBIP_CMD_UNLINK / USBIP_RET_UNLINK (the data-connection URB traffic)
// ---------------------------------------------------------------------------
struct HeaderBasic {
uint32_t command;
uint32_t seqnum;
uint32_t devid; // client: (busnum << 16) | devnum; server reply: 0
uint32_t direction; // kDirOut / kDirIn; server reply: 0
uint32_t ep; // endpoint number without the direction bit; server reply: 0
};
std::optional<HeaderBasic> decode_header_basic(const Bytes& bytes, std::size_t offset = 0);
void append_header_basic(Bytes& out, const HeaderBasic& basic);
// The 8-byte raw USB control setup packet, little-endian per the USB spec
// (USBIP_CMD_SUBMIT's 'setup' field carries it verbatim, untouched by the
// big-endian byte-order rule that governs the rest of the USB/IP header).
struct SetupPacket {
uint8_t request_type;
uint8_t request;
uint16_t value;
uint16_t index;
uint16_t length;
};
SetupPacket decode_setup(const std::array<uint8_t, 8>& raw);
std::array<uint8_t, 8> encode_setup(const SetupPacket& setup);
struct CmdSubmit {
HeaderBasic basic;
uint32_t transfer_flags;
uint32_t transfer_buffer_length;
int32_t start_frame;
uint32_t number_of_packets;
uint32_t interval;
std::array<uint8_t, 8> setup;
Bytes transfer_buffer; // present (length transfer_buffer_length) iff direction == OUT
};
// Decodes one full USBIP_CMD_SUBMIT packet (header + OUT payload if any).
// ISO packet descriptors (trailing the OUT buffer) are not modelled: the
// Kinect camera's iso endpoints are read-only (IN) from the host's point of
// view, so a CMD_SUBMIT against them never carries ISO descriptors in or out
// of this decode path; this is a documented simplification, not a protocol
// gap for the direction this server actually serves.
std::optional<CmdSubmit> decode_cmd_submit(const Bytes& bytes);
// Encodes USBIP_RET_SUBMIT. `basic` must already have devid/direction/ep set
// to zero per the server-reply convention; this function sets `command`.
Bytes encode_ret_submit(
uint32_t seqnum,
int32_t status,
const Bytes& transfer_buffer,
int32_t start_frame = 0,
uint32_t number_of_packets = 0xffffffffu,
int32_t error_count = 0);
struct CmdUnlink {
HeaderBasic basic;
uint32_t unlink_seqnum;
};
std::optional<CmdUnlink> decode_cmd_unlink(const Bytes& bytes);
Bytes encode_ret_unlink(uint32_t seqnum, int32_t status);
} // namespace attach::usbip
#endif // NUI_ATTACH_LINUX_USBIP_PROTOCOL_H
@@ -0,0 +1,47 @@
#ifndef NUI_ATTACH_LINUX_USBIP_SERVER_H
#define NUI_ATTACH_LINUX_USBIP_SERVER_H
#include <atomic>
#include <cstdint>
#include "attach_linux/kinect_export.h"
#include "protocol/protocol.h"
namespace attach::linux_attach {
// Default usbip TCP port (tools/usb/usbip's own default; the client's
// `usbip attach -r <host>` assumes it unless told otherwise).
constexpr uint16_t kDefaultPort = 3240;
// A userspace USB/IP server: answers OP_REQ_DEVLIST/OP_REQ_IMPORT over a
// listening TCP socket, then on the same connection relays
// USBIP_CMD_SUBMIT/USBIP_CMD_UNLINK traffic from the usbip kernel client
// (vhci-hcd) into `backend`, one connection at a time (usbip's own kernel
// module and the real `usbipd` both serve one importer per exported device
// at a time; this mirrors that).
class UsbipServer {
public:
UsbipServer(nui::protocol::UsbDeviceBackend& backend, ExportSet devices);
// Binds `port` and serves forever (blocks) until `stop()` is called from
// another thread or signal handler. Returns a process-exit-style code:
// 0 on a clean stop, nonzero if the listening socket could not be set up.
int run(uint16_t port);
void stop();
private:
int accept_loop(int listen_fd);
void serve_connection(int client_fd);
bool handle_control_phase(int client_fd, nui::protocol::UsbFunction& function, std::string& busid);
void session_loop(int client_fd, nui::protocol::UsbFunction function);
nui::protocol::UsbDeviceBackend& backend_;
ExportSet devices_;
std::atomic<bool> stop_requested_{false};
int listen_fd_ = -1;
};
} // namespace attach::linux_attach
#endif // NUI_ATTACH_LINUX_USBIP_SERVER_H
@@ -0,0 +1,30 @@
#ifndef NUI_ATTACH_LINUX_VHCI_LIFECYCLE_H
#define NUI_ATTACH_LINUX_VHCI_LIFECYCLE_H
#include <cstdint>
#include <optional>
#include <string>
namespace attach::linux_attach {
struct CommandResult {
bool succeeded;
int exit_code;
std::string output;
};
// Each wraps the stock `usbip` client CLI (not reimplemented here: the
// client side of USB/IP is the kernel vhci-hcd driver plus the usbip
// userspace tool, both out of this shim's scope per todo 9's "no out-of-tree
// kernel modules beyond stock usbip/vhci"). This shim is the SERVER half
// (UsbipServer); these functions only drive the matching client commands.
CommandResult usbip_attach(const std::string& host, uint16_t port, const std::string& busid);
CommandResult usbip_detach(int vhci_port);
CommandResult usbip_list_ports();
CommandResult modprobe_vhci();
std::optional<int> parse_attached_port(const std::string& usbip_attach_output);
} // namespace attach::linux_attach
#endif // NUI_ATTACH_LINUX_VHCI_LIFECYCLE_H
+114
View File
@@ -0,0 +1,114 @@
#include "attach_linux/kinect_export.h"
#include "contract/contract.h"
#include "synth/synth.h"
namespace attach::linux_attach {
namespace {
using nui::protocol::UsbFunction;
constexpr uint16_t kVendorMicrosoft = 0x045e;
constexpr uint16_t kProductCamera = 0x02ae;
constexpr uint16_t kProductAudio = 0x02ad;
constexpr uint16_t kProductMotor = 0x02b0;
constexpr uint16_t kBcdDevice1414 = 0x010b;
constexpr uint32_t kSpeedHigh = 3; // Linux enum usb_device_speed::USB_SPEED_HIGH
usbip::ExportedDevice camera_device(uint32_t busnum) {
return usbip::ExportedDevice{
"/virtual/kinect-v1/camera",
"1-1",
busnum,
1,
kSpeedHigh,
kVendorMicrosoft,
kProductCamera,
kBcdDevice1414,
0xff,
0xff,
0xff,
1,
1,
{usbip::InterfaceDescriptor{0xff, 0xff, 0xff}},
};
}
usbip::ExportedDevice audio_device(uint32_t busnum) {
return usbip::ExportedDevice{
"/virtual/kinect-v1/audio",
"1-2",
busnum,
2,
kSpeedHigh,
kVendorMicrosoft,
kProductAudio,
kBcdDevice1414,
0xff,
0xff,
0xff,
1,
1,
{usbip::InterfaceDescriptor{0xff, 0xff, 0xff}, usbip::InterfaceDescriptor{0xff, 0xff, 0xff}},
};
}
usbip::ExportedDevice motor_device(uint32_t busnum) {
return usbip::ExportedDevice{
"/virtual/kinect-v1/motor",
"1-3",
busnum,
3,
kSpeedHigh,
kVendorMicrosoft,
kProductMotor,
kBcdDevice1414,
0xff,
0xff,
0xff,
1,
1,
{usbip::InterfaceDescriptor{0xff, 0xff, 0xff}},
};
}
} // namespace
ExportSet default_export_set(uint32_t busnum) {
return ExportSet{{camera_device(busnum), audio_device(busnum), motor_device(busnum)}};
}
UsbFunction function_for_busid(const ExportSet& set, const std::string& busid) {
for (std::size_t i = 0; i < set.devices.size(); ++i) {
if (set.devices[i].busid == busid) {
return static_cast<UsbFunction>(i);
}
}
return UsbFunction::camera;
}
const usbip::ExportedDevice* device_for_busid(const ExportSet& set, const std::string& busid) {
for (const auto& device : set.devices) {
if (device.busid == busid) {
return &device;
}
}
return nullptr;
}
std::shared_ptr<const nui::protocol::SynthFrame> placeholder_frame_source() {
static const std::shared_ptr<const nui::protocol::SynthFrame> frame = [] {
auto built = std::make_shared<nui::protocol::SynthFrame>();
nui::synth::DepthRasterizer rasterizer;
built->depth = rasterizer.rasterize(
nui::synth::SegmentationMask{},
nui::contract::SkeletonFrame{},
nui::synth::DepthRasterRequest{{640, 480}, 0});
built->color = nui::synth::passthrough_color(nui::synth::BgraFrame{}, {640, 480});
built->metadata.frame_number = 0;
return built;
}();
return frame;
}
} // namespace attach::linux_attach
+132
View File
@@ -0,0 +1,132 @@
#include <csignal>
#include <cstring>
#include <iostream>
#include <thread>
#include "attach_linux/kinect_export.h"
#include "attach_linux/usbip_server.h"
#include "attach_linux/vhci_lifecycle.h"
namespace {
using attach::linux_attach::UsbipServer;
void print_usage(std::ostream& out) {
out << "kinect-attach - USB/IP server + vhci attach lifecycle for the virtual Kinect v1\n\n"
<< "Usage:\n"
<< " kinect-attach serve [--port PORT]\n"
<< " Run the USB/IP server (exports busids 1-1 camera, 1-2 audio, 1-3 motor).\n"
<< " kinect-attach attach --host HOST [--port PORT] --busid BUSID\n"
<< " Load vhci-hcd if needed, then run 'usbip attach' against a running server.\n"
<< " kinect-attach detach --vhci-port PORT\n"
<< " Run 'usbip detach' for the given vhci port.\n"
<< " kinect-attach list\n"
<< " Run 'usbip port' to list attached vhci ports.\n"
<< " kinect-attach --help\n";
}
std::optional<std::string> flag_value(int argc, char** argv, const std::string& name) {
for (int i = 0; i < argc - 1; ++i) {
if (argv[i] == name) {
return std::string(argv[i + 1]);
}
}
return std::nullopt;
}
UsbipServer* g_server_for_signal = nullptr;
void handle_sigint(int) {
if (g_server_for_signal) {
g_server_for_signal->stop();
}
}
int run_serve(int argc, char** argv) {
uint16_t port = attach::linux_attach::kDefaultPort;
if (const auto value = flag_value(argc, argv, "--port")) {
port = static_cast<uint16_t>(std::stoi(*value));
}
auto frame_source = attach::linux_attach::placeholder_frame_source();
nui::protocol::KinectV1Device device([frame_source] { return frame_source; });
const auto devices = attach::linux_attach::default_export_set(1);
UsbipServer server(device, devices);
g_server_for_signal = &server;
std::signal(SIGINT, handle_sigint);
std::signal(SIGTERM, handle_sigint);
std::cerr << "kinect-attach: serving USB/IP on port " << port
<< " (busids 1-1 camera, 1-2 audio, 1-3 motor)\n";
return server.run(port);
}
int run_attach(int argc, char** argv) {
const auto host = flag_value(argc, argv, "--host");
const auto busid = flag_value(argc, argv, "--busid");
if (!host || !busid) {
std::cerr << "attach requires --host and --busid\n";
return 2;
}
uint16_t port = attach::linux_attach::kDefaultPort;
if (const auto value = flag_value(argc, argv, "--port")) {
port = static_cast<uint16_t>(std::stoi(*value));
}
const auto probe = attach::linux_attach::usbip_list_ports();
if (!probe.succeeded) {
std::cerr << "'usbip port' failed (is the usbip userspace installed and vhci-hcd loaded?): "
<< probe.output;
}
const auto result = attach::linux_attach::usbip_attach(*host, port, *busid);
std::cout << result.output;
return result.succeeded ? 0 : 1;
}
int run_detach(int argc, char** argv) {
const auto vhci_port = flag_value(argc, argv, "--vhci-port");
if (!vhci_port) {
std::cerr << "detach requires --vhci-port\n";
return 2;
}
const auto result = attach::linux_attach::usbip_detach(std::stoi(*vhci_port));
std::cout << result.output;
return result.succeeded ? 0 : 1;
}
int run_list() {
const auto result = attach::linux_attach::usbip_list_ports();
std::cout << result.output;
return result.succeeded ? 0 : 1;
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
print_usage(std::cerr);
return 2;
}
const std::string command = argv[1];
if (command == "--help" || command == "-h" || command == "help") {
print_usage(std::cout);
return 0;
}
if (command == "serve") {
return run_serve(argc - 2, argv + 2);
}
if (command == "attach") {
return run_attach(argc - 2, argv + 2);
}
if (command == "detach") {
return run_detach(argc - 2, argv + 2);
}
if (command == "list") {
return run_list();
}
std::cerr << "unknown command: " << command << "\n";
print_usage(std::cerr);
return 2;
}
+235
View File
@@ -0,0 +1,235 @@
#include "attach_linux/usbip_protocol.h"
#include <algorithm>
#include <cstring>
namespace attach::usbip {
namespace {
void put_be16(Bytes& out, std::size_t offset, uint16_t value) {
out[offset] = static_cast<uint8_t>(value >> 8);
out[offset + 1] = static_cast<uint8_t>(value);
}
void put_be32(Bytes& out, std::size_t offset, uint32_t value) {
for (int i = 0; i < 4; ++i) {
out[offset + i] = static_cast<uint8_t>(value >> (8 * (3 - i)));
}
}
uint16_t get_be16(const Bytes& bytes, std::size_t offset) {
return static_cast<uint16_t>((bytes[offset] << 8) | bytes[offset + 1]);
}
uint32_t get_be32(const Bytes& bytes, std::size_t offset) {
return (static_cast<uint32_t>(bytes[offset]) << 24) |
(static_cast<uint32_t>(bytes[offset + 1]) << 16) |
(static_cast<uint32_t>(bytes[offset + 2]) << 8) |
static_cast<uint32_t>(bytes[offset + 3]);
}
void put_padded_string(Bytes& out, std::size_t offset, const std::string& value, std::size_t field_size) {
const std::size_t copy_len = std::min(value.size(), field_size - 1);
std::copy_n(value.begin(), copy_len, out.begin() + static_cast<std::ptrdiff_t>(offset));
}
void append_device_fixed_fields(Bytes& out, const ExportedDevice& device) {
const std::size_t base = out.size();
Bytes fixed(0x14, 0);
put_be32(fixed, 0x00, device.busnum);
put_be32(fixed, 0x04, device.devnum);
put_be32(fixed, 0x08, device.speed);
put_be16(fixed, 0x0c, device.id_vendor);
put_be16(fixed, 0x0e, device.id_product);
put_be16(fixed, 0x10, device.bcd_device);
fixed[0x12] = device.device_class;
fixed[0x13] = device.device_subclass;
out.insert(out.end(), fixed.begin(), fixed.end());
out.push_back(device.device_protocol);
out.push_back(device.configuration_value);
out.push_back(device.num_configurations);
out.push_back(static_cast<uint8_t>(device.interfaces.size()));
(void)base;
}
} // namespace
std::optional<OpHeader> decode_op_header(const Bytes& bytes) {
if (bytes.size() < 8) {
return std::nullopt;
}
return OpHeader{get_be16(bytes, 0), get_be16(bytes, 2), get_be32(bytes, 4)};
}
Bytes encode_op_header(uint16_t code, uint32_t status) {
Bytes out(8, 0);
put_be16(out, 0, kProtocolVersion);
put_be16(out, 2, code);
put_be32(out, 4, status);
return out;
}
void append_device_entry(Bytes& out, const ExportedDevice& device) {
const std::size_t path_offset = out.size();
out.resize(out.size() + 256, 0);
put_padded_string(out, path_offset, device.path, 256);
const std::size_t busid_offset = out.size();
out.resize(out.size() + 32, 0);
put_padded_string(out, busid_offset, device.busid, 32);
append_device_fixed_fields(out, device);
for (const auto& iface : device.interfaces) {
out.push_back(iface.interface_class);
out.push_back(iface.interface_subclass);
out.push_back(iface.interface_protocol);
out.push_back(0);
}
}
Bytes encode_rep_devlist(const std::vector<ExportedDevice>& devices) {
Bytes out = encode_op_header(kOpRepDevlist, 0);
Bytes count(4, 0);
put_be32(count, 0, static_cast<uint32_t>(devices.size()));
out.insert(out.end(), count.begin(), count.end());
for (const auto& device : devices) {
append_device_entry(out, device);
}
return out;
}
std::optional<std::string> decode_req_import_busid(const Bytes& body) {
if (body.size() < 32) {
return std::nullopt;
}
const auto nul = std::find(body.begin(), body.begin() + 32, uint8_t{0});
return std::string(body.begin(), nul);
}
Bytes encode_rep_import_ok(const ExportedDevice& device) {
Bytes out = encode_op_header(kOpRepImport, 0);
const std::size_t path_offset = out.size();
out.resize(out.size() + 256, 0);
put_padded_string(out, path_offset, device.path, 256);
const std::size_t busid_offset = out.size();
out.resize(out.size() + 32, 0);
put_padded_string(out, busid_offset, device.busid, 32);
append_device_fixed_fields(out, device);
return out;
}
Bytes encode_rep_import_error() {
return encode_op_header(kOpRepImport, 1);
}
std::optional<HeaderBasic> decode_header_basic(const Bytes& bytes, std::size_t offset) {
if (bytes.size() < offset + kHeaderBasicSize) {
return std::nullopt;
}
return HeaderBasic{
get_be32(bytes, offset + 0x00),
get_be32(bytes, offset + 0x04),
get_be32(bytes, offset + 0x08),
get_be32(bytes, offset + 0x0c),
get_be32(bytes, offset + 0x10),
};
}
void append_header_basic(Bytes& out, const HeaderBasic& basic) {
const std::size_t base = out.size();
out.resize(out.size() + kHeaderBasicSize, 0);
put_be32(out, base + 0x00, basic.command);
put_be32(out, base + 0x04, basic.seqnum);
put_be32(out, base + 0x08, basic.devid);
put_be32(out, base + 0x0c, basic.direction);
put_be32(out, base + 0x10, basic.ep);
}
SetupPacket decode_setup(const std::array<uint8_t, 8>& raw) {
return SetupPacket{
raw[0],
raw[1],
static_cast<uint16_t>(raw[2] | (raw[3] << 8)),
static_cast<uint16_t>(raw[4] | (raw[5] << 8)),
static_cast<uint16_t>(raw[6] | (raw[7] << 8)),
};
}
std::array<uint8_t, 8> encode_setup(const SetupPacket& setup) {
return {
setup.request_type,
setup.request,
static_cast<uint8_t>(setup.value),
static_cast<uint8_t>(setup.value >> 8),
static_cast<uint8_t>(setup.index),
static_cast<uint8_t>(setup.index >> 8),
static_cast<uint8_t>(setup.length),
static_cast<uint8_t>(setup.length >> 8),
};
}
std::optional<CmdSubmit> decode_cmd_submit(const Bytes& bytes) {
const auto basic = decode_header_basic(bytes, 0);
if (!basic || basic->command != kCmdSubmit || bytes.size() < kSubmitHeaderSize) {
return std::nullopt;
}
CmdSubmit submit{};
submit.basic = *basic;
submit.transfer_flags = get_be32(bytes, 0x14);
submit.transfer_buffer_length = get_be32(bytes, 0x18);
submit.start_frame = static_cast<int32_t>(get_be32(bytes, 0x1c));
submit.number_of_packets = get_be32(bytes, 0x20);
submit.interval = get_be32(bytes, 0x24);
std::copy_n(bytes.begin() + 0x28, 8, submit.setup.begin());
if (submit.basic.direction == kDirOut) {
if (bytes.size() < kSubmitHeaderSize + submit.transfer_buffer_length) {
return std::nullopt;
}
submit.transfer_buffer.assign(
bytes.begin() + static_cast<std::ptrdiff_t>(kSubmitHeaderSize),
bytes.begin() + static_cast<std::ptrdiff_t>(kSubmitHeaderSize + submit.transfer_buffer_length));
}
return submit;
}
Bytes encode_ret_submit(
uint32_t seqnum,
int32_t status,
const Bytes& transfer_buffer,
int32_t start_frame,
uint32_t number_of_packets,
int32_t error_count) {
Bytes out;
append_header_basic(out, HeaderBasic{kRetSubmit, seqnum, 0, 0, 0});
Bytes tail(0x1c, 0);
put_be32(tail, 0x00, static_cast<uint32_t>(status));
put_be32(tail, 0x04, static_cast<uint32_t>(transfer_buffer.size()));
put_be32(tail, 0x08, static_cast<uint32_t>(start_frame));
put_be32(tail, 0x0c, number_of_packets);
put_be32(tail, 0x10, static_cast<uint32_t>(error_count));
out.insert(out.end(), tail.begin(), tail.end());
out.insert(out.end(), transfer_buffer.begin(), transfer_buffer.end());
return out;
}
std::optional<CmdUnlink> decode_cmd_unlink(const Bytes& bytes) {
const auto basic = decode_header_basic(bytes, 0);
if (!basic || basic->command != kCmdUnlink || bytes.size() < kUnlinkHeaderSize) {
return std::nullopt;
}
return CmdUnlink{*basic, get_be32(bytes, 0x14)};
}
Bytes encode_ret_unlink(uint32_t seqnum, int32_t status) {
Bytes out;
append_header_basic(out, HeaderBasic{kRetUnlink, seqnum, 0, 0, 0});
out.resize(out.size() + 0x1c, 0);
put_be32(out, kHeaderBasicSize, static_cast<uint32_t>(status));
return out;
}
} // namespace attach::usbip
+239
View File
@@ -0,0 +1,239 @@
#include "attach_linux/usbip_server.h"
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
namespace attach::linux_attach {
namespace {
using nui::protocol::TransferStatus;
using nui::protocol::UsbFunction;
bool read_exact(int fd, void* buffer, std::size_t length) {
auto* cursor = static_cast<uint8_t*>(buffer);
std::size_t remaining = length;
while (remaining > 0) {
const ssize_t got = ::recv(fd, cursor, remaining, 0);
if (got <= 0) {
return false;
}
cursor += got;
remaining -= static_cast<std::size_t>(got);
}
return true;
}
bool write_exact(int fd, const void* buffer, std::size_t length) {
const auto* cursor = static_cast<const uint8_t*>(buffer);
std::size_t remaining = length;
while (remaining > 0) {
const ssize_t sent = ::send(fd, cursor, remaining, MSG_NOSIGNAL);
if (sent <= 0) {
return false;
}
cursor += sent;
remaining -= static_cast<std::size_t>(sent);
}
return true;
}
int32_t status_for(TransferStatus status) {
switch (status) {
case TransferStatus::completed:
return 0;
case TransferStatus::stall:
return usbip::kErrnoPipeStall;
case TransferStatus::idle:
return 0;
case TransferStatus::invalid_frame:
return usbip::kErrnoNoDevice;
}
return usbip::kErrnoNoDevice;
}
uint8_t endpoint_address(const usbip::HeaderBasic& basic) {
return static_cast<uint8_t>(basic.ep | (basic.direction == usbip::kDirIn ? 0x80 : 0x00));
}
} // namespace
UsbipServer::UsbipServer(nui::protocol::UsbDeviceBackend& backend, ExportSet devices)
: backend_(backend), devices_(devices) {}
void UsbipServer::stop() {
stop_requested_ = true;
if (listen_fd_ >= 0) {
::shutdown(listen_fd_, SHUT_RDWR);
}
}
int UsbipServer::run(uint16_t port) {
const int listen_fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0) {
return 1;
}
const int reuse = 1;
::setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
if (::bind(listen_fd, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0) {
::close(listen_fd);
return 2;
}
if (::listen(listen_fd, 4) != 0) {
::close(listen_fd);
return 3;
}
listen_fd_ = listen_fd;
const int result = accept_loop(listen_fd);
::close(listen_fd);
listen_fd_ = -1;
return result;
}
int UsbipServer::accept_loop(int listen_fd) {
while (!stop_requested_) {
const int client_fd = ::accept(listen_fd, nullptr, nullptr);
if (client_fd < 0) {
if (stop_requested_) {
return 0;
}
continue;
}
const int nodelay = 1;
::setsockopt(client_fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay));
serve_connection(client_fd);
::close(client_fd);
}
return 0;
}
void UsbipServer::serve_connection(int client_fd) {
UsbFunction function = UsbFunction::camera;
std::string busid;
if (!handle_control_phase(client_fd, function, busid)) {
return;
}
session_loop(client_fd, function);
}
bool UsbipServer::handle_control_phase(int client_fd, UsbFunction& function, std::string& busid) {
uint8_t header[8];
if (!read_exact(client_fd, header, sizeof(header))) {
return false;
}
const auto op = usbip::decode_op_header(usbip::Bytes(header, header + sizeof(header)));
if (!op) {
return false;
}
if (op->code == usbip::kOpReqDevlist) {
const auto reply = usbip::encode_rep_devlist({devices_.devices.begin(), devices_.devices.end()});
write_exact(client_fd, reply.data(), reply.size());
return false; // OP_REQ_DEVLIST closes the connection per protocol.
}
if (op->code != usbip::kOpReqImport) {
return false;
}
uint8_t body[32];
if (!read_exact(client_fd, body, sizeof(body))) {
return false;
}
const auto requested_busid = usbip::decode_req_import_busid(usbip::Bytes(body, body + sizeof(body)));
const auto* device = requested_busid ? device_for_busid(devices_, *requested_busid) : nullptr;
if (!device) {
const auto reply = usbip::encode_rep_import_error();
write_exact(client_fd, reply.data(), reply.size());
return false;
}
const auto reply = usbip::encode_rep_import_ok(*device);
if (!write_exact(client_fd, reply.data(), reply.size())) {
return false;
}
busid = *requested_busid;
function = function_for_busid(devices_, busid);
return true;
}
void UsbipServer::session_loop(int client_fd, UsbFunction function) {
while (!stop_requested_) {
uint8_t header[usbip::kSubmitHeaderSize];
if (!read_exact(client_fd, header, usbip::kHeaderBasicSize)) {
return;
}
const auto basic = usbip::decode_header_basic(usbip::Bytes(header, header + usbip::kHeaderBasicSize));
if (!basic) {
return;
}
if (basic->command == usbip::kCmdUnlink) {
if (!read_exact(client_fd, header + usbip::kHeaderBasicSize,
usbip::kUnlinkHeaderSize - usbip::kHeaderBasicSize)) {
return;
}
const auto unlink = usbip::decode_cmd_unlink(
usbip::Bytes(header, header + usbip::kUnlinkHeaderSize));
if (!unlink) {
return;
}
const auto reply = usbip::encode_ret_unlink(unlink->basic.seqnum, usbip::kErrnoConnReset);
if (!write_exact(client_fd, reply.data(), reply.size())) {
return;
}
continue;
}
if (basic->command != usbip::kCmdSubmit) {
return;
}
if (!read_exact(client_fd, header + usbip::kHeaderBasicSize,
usbip::kSubmitHeaderSize - usbip::kHeaderBasicSize)) {
return;
}
usbip::Bytes full(header, header + usbip::kSubmitHeaderSize);
const auto peek = usbip::decode_cmd_submit(full);
if (!peek) {
return;
}
if (peek->basic.direction == usbip::kDirOut && peek->transfer_buffer_length > 0) {
usbip::Bytes out_payload(peek->transfer_buffer_length);
if (!read_exact(client_fd, out_payload.data(), out_payload.size())) {
return;
}
full.insert(full.end(), out_payload.begin(), out_payload.end());
}
const auto submit = usbip::decode_cmd_submit(full);
if (!submit) {
return;
}
const uint8_t endpoint = endpoint_address(submit->basic);
nui::protocol::TransferResult result;
if (submit->basic.ep == 0) {
const auto setup = usbip::decode_setup(submit->setup);
const nui::protocol::ControlSetup control_setup{
setup.request_type, setup.request, setup.value, setup.index, setup.length};
result = backend_.answer_control_transfer(function, control_setup, submit->transfer_buffer);
} else {
result = backend_.next_packet(function, endpoint);
}
const auto reply = usbip::encode_ret_submit(
submit->basic.seqnum, status_for(result.status),
submit->basic.direction == usbip::kDirIn ? result.data : usbip::Bytes{});
if (!write_exact(client_fd, reply.data(), reply.size())) {
return;
}
}
}
} // namespace attach::linux_attach
+70
View File
@@ -0,0 +1,70 @@
#include "attach_linux/vhci_lifecycle.h"
#include <sys/wait.h>
#include <array>
#include <cstdio>
#include <regex>
namespace attach::linux_attach {
namespace {
CommandResult run_shell(const std::string& command) {
std::string output;
FILE* pipe = ::popen((command + " 2>&1").c_str(), "r");
if (!pipe) {
return CommandResult{false, -1, "failed to spawn: " + command};
}
std::array<char, 4096> buffer{};
std::size_t read_bytes = 0;
while ((read_bytes = std::fread(buffer.data(), 1, buffer.size(), pipe)) > 0) {
output.append(buffer.data(), read_bytes);
}
const int status = ::pclose(pipe);
const int exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
return CommandResult{exit_code == 0, exit_code, output};
}
std::string shell_quote(const std::string& value) {
std::string quoted = "'";
for (const char c : value) {
quoted += (c == '\'') ? "'\\''" : std::string(1, c);
}
quoted += "'";
return quoted;
}
} // namespace
CommandResult usbip_attach(const std::string& host, uint16_t port, const std::string& busid) {
const std::string remote = host + ":" + std::to_string(port);
return run_shell("usbip attach -r " + shell_quote(remote) + " -b " + shell_quote(busid));
}
CommandResult usbip_detach(int vhci_port) {
return run_shell("usbip detach -p " + std::to_string(vhci_port));
}
CommandResult usbip_list_ports() {
return run_shell("usbip port");
}
CommandResult modprobe_vhci() {
return run_shell("modprobe vhci-hcd");
}
std::optional<int> parse_attached_port(const std::string& usbip_attach_output) {
// The usbip(8) client prints "succeeded" lines without a port number on
// most builds and relies on a follow-up `usbip port` listing to discover
// which vhci port it landed on; some builds instead print "...port N".
// Try the direct form first, else return nullopt so the caller falls back
// to `usbip_list_ports()`.
static const std::regex port_pattern(R"(port\s+(\d+))", std::regex::icase);
std::smatch match;
if (std::regex_search(usbip_attach_output, match, port_pattern)) {
return std::stoi(match[1].str());
}
return std::nullopt;
}
} // namespace attach::linux_attach
+125
View File
@@ -0,0 +1,125 @@
#include <cassert>
#include <iostream>
#include "attach_linux/kinect_export.h"
#include "attach_linux/usbip_protocol.h"
namespace {
void test_op_header_roundtrip() {
const auto encoded = attach::usbip::encode_op_header(attach::usbip::kOpReqDevlist, 0);
const auto decoded = attach::usbip::decode_op_header(encoded);
assert(decoded.has_value());
assert(decoded->version == attach::usbip::kProtocolVersion);
assert(decoded->code == attach::usbip::kOpReqDevlist);
assert(decoded->status == 0);
}
void test_rep_devlist_layout() {
const auto devices = attach::linux_attach::default_export_set(7);
const auto encoded = attach::usbip::encode_rep_devlist(
{devices.devices.begin(), devices.devices.end()});
const auto header = attach::usbip::decode_op_header(encoded);
assert(header.has_value());
assert(header->code == attach::usbip::kOpRepDevlist);
// 8-byte OP header + 4-byte device count + 3 entries, each
// 256 (path) + 32 (busid) + 0x14 fixed + 4 tail bytes + 4 bytes per interface.
const std::size_t camera_entry = 256 + 32 + 0x14 + 4 + 1 * 4;
const std::size_t audio_entry = 256 + 32 + 0x14 + 4 + 2 * 4;
const std::size_t motor_entry = 256 + 32 + 0x14 + 4 + 1 * 4;
assert(encoded.size() == 8 + 4 + camera_entry + audio_entry + motor_entry);
}
void test_import_busid_roundtrip() {
attach::usbip::Bytes body(32, 0);
const std::string busid = "1-1";
std::copy(busid.begin(), busid.end(), body.begin());
const auto decoded = attach::usbip::decode_req_import_busid(body);
assert(decoded.has_value());
assert(*decoded == busid);
}
void test_header_basic_roundtrip() {
attach::usbip::Bytes out;
const attach::usbip::HeaderBasic basic{
attach::usbip::kCmdSubmit, 42, (1u << 16) | 1u, attach::usbip::kDirIn, 2};
attach::usbip::append_header_basic(out, basic);
const auto decoded = attach::usbip::decode_header_basic(out);
assert(decoded.has_value());
assert(decoded->command == basic.command);
assert(decoded->seqnum == basic.seqnum);
assert(decoded->devid == basic.devid);
assert(decoded->direction == basic.direction);
assert(decoded->ep == basic.ep);
}
void test_setup_roundtrip() {
const attach::usbip::SetupPacket setup{0xc0, 0x06, 0x0100, 0x0000, 0x0012};
const auto encoded = attach::usbip::encode_setup(setup);
const auto decoded = attach::usbip::decode_setup(encoded);
assert(decoded.request_type == setup.request_type);
assert(decoded.request == setup.request);
assert(decoded.value == setup.value);
assert(decoded.index == setup.index);
assert(decoded.length == setup.length);
}
void test_cmd_submit_roundtrip_out_direction() {
attach::usbip::Bytes packet;
attach::usbip::append_header_basic(
packet, attach::usbip::HeaderBasic{
attach::usbip::kCmdSubmit, 3, (1u << 16) | 1u, attach::usbip::kDirOut, 0});
// transfer_flags, transfer_buffer_length, start_frame, number_of_packets,
// interval: 5 fields of 4 bytes each (offsets 0x14..0x28).
packet.resize(packet.size() + 5 * 4, 0);
const attach::usbip::Bytes payload = {0x4d, 0x47, 0x00, 0x04, 0x00, 0x02, 0x00, 0x00};
packet[0x1b] = static_cast<uint8_t>(payload.size()); // transfer_buffer_length, big-endian
const auto setup_bytes = attach::usbip::encode_setup(
attach::usbip::SetupPacket{0x40, 0, 0, 0, 8});
packet.insert(packet.end(), setup_bytes.begin(), setup_bytes.end());
packet.insert(packet.end(), payload.begin(), payload.end());
const auto decoded = attach::usbip::decode_cmd_submit(packet);
assert(decoded.has_value());
assert(decoded->basic.direction == attach::usbip::kDirOut);
assert(decoded->transfer_buffer_length == payload.size());
assert(decoded->transfer_buffer == payload);
}
void test_ret_submit_in_direction_carries_payload() {
const attach::usbip::Bytes payload = {1, 2, 3, 4};
const auto encoded = attach::usbip::encode_ret_submit(9, 0, payload);
const auto basic = attach::usbip::decode_header_basic(encoded);
assert(basic.has_value());
assert(basic->command == attach::usbip::kRetSubmit);
assert(basic->seqnum == 9);
assert(encoded.size() == attach::usbip::kHeaderBasicSize + 0x1c + payload.size());
}
void test_cmd_unlink_roundtrip() {
attach::usbip::Bytes packet;
attach::usbip::append_header_basic(
packet, attach::usbip::HeaderBasic{attach::usbip::kCmdUnlink, 5, 0, 0, 0});
packet.resize(packet.size() + 4, 0);
packet[packet.size() - 1] = 11; // unlink_seqnum = 11
packet.resize(attach::usbip::kUnlinkHeaderSize, 0);
const auto decoded = attach::usbip::decode_cmd_unlink(packet);
assert(decoded.has_value());
assert(decoded->unlink_seqnum == 11);
}
} // namespace
int main() {
test_op_header_roundtrip();
test_rep_devlist_layout();
test_import_busid_roundtrip();
test_header_basic_roundtrip();
test_setup_roundtrip();
test_cmd_submit_roundtrip_out_direction();
test_ret_submit_in_direction_carries_payload();
test_cmd_unlink_roundtrip();
std::cout << "usbip_protocol_roundtrip: all assertions passed\n";
return 0;
}
+79
View File
@@ -0,0 +1,79 @@
cmake_minimum_required(VERSION 3.20)
project(nui_openni2_virtual_device LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(OPENNI2_ROOT "$ENV{HOME}/.local/openni2-root" CACHE PATH
"User-space OpenNI2 package root")
set(OPENNI2_INCLUDE_DIR
"${OPENNI2_ROOT}/usr/include/openni2" CACHE PATH
"Directory containing OpenNI.h")
set(OPENNI2_LIBRARY
"${OPENNI2_ROOT}/usr/lib/x86_64-linux-gnu/libOpenNI2.so" CACHE FILEPATH
"OpenNI2 shared library")
foreach(required_path
"${OPENNI2_INCLUDE_DIR}/OpenNI.h"
"${OPENNI2_LIBRARY}")
if(NOT EXISTS "${required_path}")
message(FATAL_ERROR "Required OpenNI2 file not found: ${required_path}")
endif()
endforeach()
set(REPOSITORY_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../..")
add_library(SynthKinectDriver MODULE
src/openni2_synth_driver.cpp
"${REPOSITORY_ROOT}/core/mapping/mapping.cpp"
"${REPOSITORY_ROOT}/core/synth/mask_stabilizer.cpp"
"${REPOSITORY_ROOT}/core/synth/synth.cpp"
)
target_include_directories(SynthKinectDriver PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/vendor/openni2"
"${OPENNI2_INCLUDE_DIR}"
"${REPOSITORY_ROOT}/core"
)
target_compile_options(SynthKinectDriver PRIVATE
-Wall -Wextra -Wpedantic -Werror
)
# This provisioned libOpenNI2.so build has no OPENNI2_DRIVERS_PATH env var and
# never finds its own etc/openni2/OpenNI.ini override (it only checks the
# absolute system path /etc/openni2/OpenNI.ini, which does not exist without
# a package install); its driver scanner also globs strictly for "*.so.0",
# not plain "*.so". So the module is built with that exact suffix, matching
# the stock drivers (libDummyDevice.so.0, libPS1080.so.0, ...).
set_target_properties(SynthKinectDriver PROPERTIES
PREFIX "lib"
OUTPUT_NAME "SynthKinect"
SUFFIX ".so.0"
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/OpenNI2/Drivers"
)
# Deploy step: the host's own default driver repository (relative to its
# libOpenNI2.so) is the only path it actually scans, so an OpenNI2 app can
# find this module only once it is placed there too - mirroring how a real
# OpenNI2 driver gets installed.
add_custom_command(TARGET SynthKinectDriver POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy
"$<TARGET_FILE:SynthKinectDriver>"
"${OPENNI2_ROOT}/usr/lib/x86_64-linux-gnu/OpenNI2/Drivers/libSynthKinect.so.0"
)
add_executable(openni2_depth_consumer
tools/openni2_depth_consumer.cpp
)
target_include_directories(openni2_depth_consumer PRIVATE
"${OPENNI2_INCLUDE_DIR}"
)
target_link_libraries(openni2_depth_consumer PRIVATE
"${OPENNI2_LIBRARY}"
)
target_compile_options(openni2_depth_consumer PRIVATE
-Wall -Wextra -Wpedantic -Werror
)
set_target_properties(openni2_depth_consumer PROPERTIES
BUILD_RPATH "${OPENNI2_ROOT}/usr/lib/x86_64-linux-gnu"
)
+31 -3
View File
@@ -1,6 +1,34 @@
# fallback/linux-openni2/ — OpenNI2 virtual device fallback (todo 15)
An OpenNI2 device-driver module (OniDriverApi) exposing the `core/synth` streams as an
OpenNI2 device, so OpenNI/NiTE apps work without the usbip path; doubles as the Linux
general-emulator surface. Consumes `core/synth` (never duplicates it); never bundles
NiTE2. Placeholder until todo 15.
OpenNI2 device ("SynthKinect"), so OpenNI apps work without the usbip path; doubles as
the Linux general-emulator surface. Consumes `core/synth`/`core/mapping` directly
(never duplicates them); never bundles NiTE2 - skeleton tracking stays out of scope
here (see `.omo/evidence/task-15-webcam-kinect-emulator.log`).
## Layout
- `vendor/openni2/Driver/{OniDriverAPI.h,OniDriverTypes.h}` - fetched via raw HTTPS
from `github.com/structureio/OpenNI2` (Apache-2.0); the custom-driver ABI headers
are not in the OpenNI2 `-dev` package.
- `src/openni2_synth_driver.cpp` - the driver: a depth stream
(`ONI_PIXEL_FORMAT_DEPTH_1_MM`, 320x240@30fps) and a color stream
(`ONI_PIXEL_FORMAT_RGB888`), both sourced from `core/synth::DepthRasterizer` /
`nui::synth::passthrough_color` over a fixed human-silhouette fixture.
- `tools/openni2_depth_consumer.cpp` - an independent headless consumer using the
public `openni::Device`/`VideoStream`/`VideoFrameRef` C++ API to prove a real
OpenNI2 stack accepts the synthetic depth.
## Build + verify
```
cmake -S fallback/linux-openni2 -B fallback/linux-openni2/build
cmake --build fallback/linux-openni2/build
LD_LIBRARY_PATH=$HOME/.local/openni2-root/usr/lib/x86_64-linux-gnu \
fallback/linux-openni2/build/openni2_depth_consumer
```
The build step also deploys `libSynthKinect.so.0` into the provisioned
`$HOME/.local/openni2-root` install's own default driver directory - this
particular `libOpenNI2.so` build only scans `<lib dir>/OpenNI2/Drivers` for
files matching `*.so.0` (no `OPENNI2_DRIVERS_PATH` env var, and its
`/etc/openni2/OpenNI.ini` lookup uses an absolute system path that does not
exist without a package install). See the evidence log for the full
investigation and a captured run with real depth numbers.
@@ -0,0 +1,384 @@
// OpenNI2 virtual-device driver (plan todo 15): exposes core/synth's synthetic
// depth (and a best-effort color passthrough) as a real OniDriverApi module,
// so an unmodified OpenNI2 consumer can open "SynthKinect" and read frames.
//
// ABI reference: structureio/OpenNI2 Include/Driver/OniDriverAPI.h (vendored
// under vendor/openni2/) and Source/Drivers/DummyDevice (structural
// reference, not copied). This file never bundles NiTE2 and never
// duplicates core/synth - it only calls into it.
//
// XnLib is PrimeSense-internal plumbing this module does not vendor; the
// ONI_EXPORT_DRIVER macro only needs a trivial new/delete stand-in for the
// driver singleton's lifetime, so XN_NEW/XN_DELETE are defined locally
// instead of pulling in XnLib.
#define XN_NEW(type, ...) new type(__VA_ARGS__)
#define XN_DELETE(ptr) delete (ptr)
#include "Driver/OniDriverAPI.h"
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstring>
#include <thread>
#include <vector>
#include "contract/contract.h"
#include "mapping/mapping.h"
#include "synth/mask_stabilizer.h"
#include "synth/synth.h"
namespace {
using nui::synth::BgraFrame;
using nui::synth::BinaryMask;
using nui::synth::DepthRasterizer;
using nui::synth::ImageSize;
using nui::synth::SegmentationMask;
constexpr int kDepthWidth = 320;
constexpr int kDepthHeight = 240;
constexpr int kFps = 30;
// A fixed human-shaped fixture: an elliptical silhouette plus 20 joints
// (same depth_image_to_skeleton construction core/synth's own tests use)
// scattered inside it at in-band depths, so the driver's output is backed
// by the real synth rasterizer rather than a hand-rolled test pattern.
SegmentationMask fixture_mask(ImageSize size) {
SegmentationMask mask{size, std::vector<float>(
static_cast<std::size_t>(size.width) *
size.height,
0.0f)};
const float cx = size.width * 0.5f;
const float cy = size.height * 0.52f;
const float rx = size.width * 0.28f;
const float ry = size.height * 0.46f;
for (uint32_t y = 0; y < size.height; ++y) {
for (uint32_t x = 0; x < size.width; ++x) {
const float dx = (static_cast<float>(x) - cx) / rx;
const float dy = (static_cast<float>(y) - cy) / ry;
if (dx * dx + dy * dy <= 1.0f) {
mask.confidence[static_cast<std::size_t>(y) * size.width + x] = 1.0f;
}
}
}
return mask;
}
nui::contract::SkeletonFrame fixture_skeleton(ImageSize size) {
// 20 joint pixel positions laid out head-to-feet, scaled to the requested
// resolution, mirroring the shape used by tests/test_synth.cpp.
constexpr std::array<std::pair<float, float>, nui::contract::kJointCount>
kRelativePositions{{
{0.31f, 0.25f}, {0.38f, 0.29f}, {0.44f, 0.25f}, {0.50f, 0.21f},
{0.25f, 0.29f}, {0.28f, 0.38f}, {0.31f, 0.46f}, {0.34f, 0.50f},
{0.56f, 0.29f}, {0.59f, 0.38f}, {0.62f, 0.46f}, {0.65f, 0.50f},
{0.38f, 0.54f}, {0.34f, 0.62f}, {0.31f, 0.75f}, {0.28f, 0.83f},
{0.50f, 0.54f}, {0.53f, 0.62f}, {0.56f, 0.75f}, {0.59f, 0.83f},
}};
nui::contract::SkeletonFrame skeleton{};
for (std::size_t index = 0; index < kRelativePositions.size(); ++index) {
const int x = static_cast<int>(kRelativePositions[index].first * size.width);
const int y = static_cast<int>(kRelativePositions[index].second * size.height);
const uint16_t depth_mm = static_cast<uint16_t>(1500 + index * 25);
skeleton.joints[index].position = nui::mapping::depth_image_to_skeleton(
{x, y, static_cast<uint16_t>(depth_mm << 3)},
static_cast<int>(size.width),
static_cast<int>(size.height));
skeleton.joints[index].position.w = 1.0f;
skeleton.joints[index].tracking_state =
nui::contract::JointTrackingState::TRACKED;
}
skeleton.skeleton_tracking_id = 1;
return skeleton;
}
// Synthetic "webcam" passthrough source: a plain gradient, standing in for
// the live BGRA frame tracker/synth would otherwise supply.
BgraFrame fixture_color_source(ImageSize size) {
BgraFrame frame{size, size.width * 4,
std::vector<uint8_t>(
static_cast<std::size_t>(size.width) * size.height * 4,
0)};
for (uint32_t y = 0; y < size.height; ++y) {
for (uint32_t x = 0; x < size.width; ++x) {
const std::size_t index =
(static_cast<std::size_t>(y) * size.width + x) * 4;
frame.pixels[index + 0] =
static_cast<uint8_t>(255 * x / size.width); // B
frame.pixels[index + 1] =
static_cast<uint8_t>(255 * y / size.height); // G
frame.pixels[index + 2] = 128; // R
frame.pixels[index + 3] = 255; // A
}
}
return frame;
}
class SynthStreamBase : public oni::driver::StreamBase {
public:
~SynthStreamBase() override { stop(); }
OniStatus start() override {
if (running_.exchange(true)) {
return ONI_STATUS_OK;
}
worker_ = std::thread(&SynthStreamBase::mainloop, this);
return ONI_STATUS_OK;
}
void stop() override {
if (!running_.exchange(false)) {
return;
}
if (worker_.joinable()) {
worker_.join();
}
}
OniStatus getProperty(int propertyId, void* data, int* dataSize) override {
if (propertyId == ONI_STREAM_PROPERTY_VIDEO_MODE) {
if (*dataSize != static_cast<int>(sizeof(OniVideoMode))) {
return ONI_STATUS_ERROR;
}
*static_cast<OniVideoMode*>(data) = video_mode();
return ONI_STATUS_OK;
}
return ONI_STATUS_NOT_IMPLEMENTED;
}
protected:
virtual OniVideoMode video_mode() const = 0;
virtual OniSensorType sensor_type() const = 0;
// Fills pFrame->data (already sized to getRequiredFrameSize()) and
// returns the stride in bytes.
virtual int fill(OniFrame* frame) = 0;
void mainloop() {
int frame_index = 1;
const auto start_time = std::chrono::steady_clock::now();
while (running_.load()) {
OniFrame* frame = getServices().acquireFrame();
if (frame == nullptr) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000 / kFps));
continue;
}
const OniVideoMode mode = video_mode();
frame->sensorType = sensor_type();
frame->videoMode = mode;
frame->width = mode.resolutionX;
frame->height = mode.resolutionY;
frame->cropOriginX = 0;
frame->cropOriginY = 0;
frame->croppingEnabled = FALSE;
frame->frameIndex = frame_index++;
frame->stride = fill(frame);
frame->timestamp = static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - start_time)
.count());
raiseNewFrame(frame);
getServices().releaseFrame(frame);
std::this_thread::sleep_for(std::chrono::milliseconds(1000 / kFps));
}
}
std::atomic<bool> running_{false};
std::thread worker_;
};
class SynthDepthStream : public SynthStreamBase {
public:
SynthDepthStream()
: size_{kDepthWidth, kDepthHeight},
mask_(fixture_mask(size_)),
skeleton_(fixture_skeleton(size_)) {}
protected:
OniVideoMode video_mode() const override {
return OniVideoMode{ONI_PIXEL_FORMAT_DEPTH_1_MM,
static_cast<int>(size_.width),
static_cast<int>(size_.height), kFps};
}
OniSensorType sensor_type() const override { return ONI_SENSOR_DEPTH; }
int fill(OniFrame* frame) override {
const auto depth = rasterizer_.rasterize(
mask_, skeleton_, {size_, /*skeleton_slot=*/0});
auto* pixels = static_cast<OniDepthPixel*>(frame->data);
const std::size_t count = depth.pixels.size();
for (std::size_t index = 0; index < count; ++index) {
// Expose plain metric depth (mm) - standard OpenNI contract - rather
// than our internal Kinect-style packed word.
pixels[index] = nui::synth::NuiDepthPixelToDepth(depth.pixels[index]);
}
return static_cast<int>(size_.width * sizeof(OniDepthPixel));
}
private:
ImageSize size_;
SegmentationMask mask_;
nui::contract::SkeletonFrame skeleton_;
DepthRasterizer rasterizer_;
};
class SynthColorStream : public SynthStreamBase {
public:
explicit SynthColorStream(ImageSize size)
: size_{size}, source_(fixture_color_source(size)) {}
protected:
OniVideoMode video_mode() const override {
return OniVideoMode{ONI_PIXEL_FORMAT_RGB888,
static_cast<int>(size_.width),
static_cast<int>(size_.height), kFps};
}
OniSensorType sensor_type() const override { return ONI_SENSOR_COLOR; }
int fill(OniFrame* frame) override {
const auto bgra = nui::synth::passthrough_color(source_, size_);
auto* pixels = static_cast<OniRGB888Pixel*>(frame->data);
const std::size_t count =
static_cast<std::size_t>(size_.width) * size_.height;
for (std::size_t index = 0; index < count; ++index) {
const std::size_t bgra_index = index * 4;
pixels[index].b = bgra.pixels[bgra_index + 0];
pixels[index].g = bgra.pixels[bgra_index + 1];
pixels[index].r = bgra.pixels[bgra_index + 2];
}
return static_cast<int>(size_.width * sizeof(OniRGB888Pixel));
}
private:
ImageSize size_;
BgraFrame source_;
};
class SynthKinectDevice : public oni::driver::DeviceBase {
public:
SynthKinectDevice(OniDeviceInfo* info, oni::driver::DriverServices& services)
: info_(info), services_(services) {
depth_video_modes_[0] = OniVideoMode{ONI_PIXEL_FORMAT_DEPTH_1_MM,
kDepthWidth, kDepthHeight, kFps};
color_video_modes_[0] =
OniVideoMode{ONI_PIXEL_FORMAT_RGB888, kDepthWidth, kDepthHeight, kFps};
sensors_[0] = OniSensorInfo{ONI_SENSOR_DEPTH, 1, depth_video_modes_};
sensors_[1] = OniSensorInfo{ONI_SENSOR_COLOR, 1, color_video_modes_};
}
OniDeviceInfo* info() const { return info_; }
OniStatus getSensorInfoList(OniSensorInfo** sensors, int* count) override {
*sensors = sensors_;
*count = 2;
return ONI_STATUS_OK;
}
oni::driver::StreamBase* createStream(OniSensorType sensorType) override {
if (sensorType == ONI_SENSOR_DEPTH) {
return new SynthDepthStream();
}
if (sensorType == ONI_SENSOR_COLOR) {
return new SynthColorStream(ImageSize{kDepthWidth, kDepthHeight});
}
services_.errorLoggerAppend(
"SynthKinectDevice: unsupported sensor type %d", sensorType);
return nullptr;
}
void destroyStream(oni::driver::StreamBase* stream) override {
delete stream;
}
OniStatus getProperty(int propertyId, void* data, int* dataSize) override {
if (propertyId == ONI_DEVICE_PROPERTY_DRIVER_VERSION &&
*dataSize == static_cast<int>(sizeof(OniVersion))) {
*static_cast<OniVersion*>(data) = OniVersion{1, 0, 0, 0};
return ONI_STATUS_OK;
}
return ONI_STATUS_NOT_IMPLEMENTED;
}
private:
OniDeviceInfo* info_;
oni::driver::DriverServices& services_;
OniVideoMode depth_video_modes_[1];
OniVideoMode color_video_modes_[1];
OniSensorInfo sensors_[2];
};
constexpr char kDeviceUri[] = "SynthKinect";
class SynthKinectDriver : public oni::driver::DriverBase {
public:
explicit SynthKinectDriver(OniDriverServices* services)
: DriverBase(services) {}
// There is no real hardware to hotplug-detect: ANY_DEVICE enumeration
// only sees devices that called deviceConnected(), so the synthetic
// device is registered as soon as the driver initializes rather than
// waiting for a tryDevice() probe against a specific uri.
OniStatus initialize(
oni::driver::DeviceConnectedCallback connected,
oni::driver::DeviceDisconnectedCallback disconnected,
oni::driver::DeviceStateChangedCallback stateChanged,
void* cookie) override {
const OniStatus status =
DriverBase::initialize(connected, disconnected, stateChanged, cookie);
if (status != ONI_STATUS_OK) {
return status;
}
return tryDevice(kDeviceUri);
}
oni::driver::DeviceBase* deviceOpen(const char* uri,
const char* /*mode*/) override {
if (std::strcmp(uri, kDeviceUri) != 0) {
getServices().errorLoggerAppend("SynthKinectDriver: unknown uri '%s'",
uri);
return nullptr;
}
if (device_ != nullptr) {
return device_;
}
device_ = new SynthKinectDevice(&info_, getServices());
return device_;
}
void deviceClose(oni::driver::DeviceBase* device) override {
if (device == device_) {
delete device_;
device_ = nullptr;
}
}
OniStatus tryDevice(const char* uri) override {
if (std::strcmp(uri, kDeviceUri) != 0) {
return ONI_STATUS_ERROR;
}
std::strncpy(info_.uri, kDeviceUri, ONI_MAX_STR - 1);
std::strncpy(info_.vendor, "nui-synth", ONI_MAX_STR - 1);
std::strncpy(info_.name, "SynthKinect Virtual Depth", ONI_MAX_STR - 1);
info_.usbVendorId = 0;
info_.usbProductId = 0;
deviceConnected(&info_);
return ONI_STATUS_OK;
}
void shutdown() override {
delete device_;
device_ = nullptr;
}
private:
OniDeviceInfo info_{};
SynthKinectDevice* device_ = nullptr;
};
} // namespace
ONI_EXPORT_DRIVER(SynthKinectDriver);
@@ -0,0 +1,99 @@
#include <OpenNI.h>
#include <cstdint>
#include <cstdio>
namespace {
int fail(const char* step) {
std::fprintf(stderr, "%s failed: %s\n", step, openni::OpenNI::getExtendedError());
return 1;
}
}
int main() {
if (openni::OpenNI::initialize() != openni::STATUS_OK) {
return fail("OpenNI::initialize");
}
openni::Device device;
if (device.open(openni::ANY_DEVICE) != openni::STATUS_OK) {
openni::OpenNI::shutdown();
return fail("Device::open");
}
openni::VideoStream depth;
if (depth.create(device, openni::SENSOR_DEPTH) != openni::STATUS_OK) {
device.close();
openni::OpenNI::shutdown();
return fail("VideoStream::create(SENSOR_DEPTH)");
}
if (depth.start() != openni::STATUS_OK) {
depth.destroy();
device.close();
openni::OpenNI::shutdown();
return fail("VideoStream::start");
}
openni::VideoFrameRef frame;
const openni::Status read_status = depth.readFrame(&frame);
int result = 0;
if (read_status != openni::STATUS_OK || !frame.isValid()) {
std::fprintf(stderr, "readFrame failed or invalid frame\n");
result = 1;
} else {
const int width = frame.getWidth();
const int height = frame.getHeight();
const auto* pixels = static_cast<const openni::DepthPixel*>(frame.getData());
const int pixel_count = width * height;
long long sum = 0;
int in_band_count = 0;
int non_zero_count = 0;
uint16_t sample_min = 0xFFFF;
uint16_t sample_max = 0;
for (int i = 0; i < pixel_count; ++i) {
const uint16_t value = pixels[i];
if (value != 0) {
++non_zero_count;
sum += value;
if (value < sample_min) sample_min = value;
if (value > sample_max) sample_max = value;
if (value >= 800 && value <= 4000) {
++in_band_count;
}
}
}
std::printf("device_uri=%s\n", device.getDeviceInfo().getUri());
std::printf("frame_width=%d frame_height=%d\n", width, height);
std::printf("non_zero_pixels=%d in_band_pixels=%d total_pixels=%d\n",
non_zero_count, in_band_count, pixel_count);
if (non_zero_count > 0) {
std::printf("depth_min_mm=%u depth_max_mm=%u depth_mean_mm=%lld\n",
sample_min, sample_max, sum / non_zero_count);
std::printf("sample_pixel[%d,%d]=%u mm\n", width / 2, height / 2,
pixels[(height / 2) * width + width / 2]);
}
const bool has_body = non_zero_count > 0;
const bool body_in_band = non_zero_count > 0 && in_band_count == non_zero_count;
const bool correct_geometry = width == 320 && height == 240;
if (!has_body || !body_in_band || !correct_geometry) {
std::fprintf(stderr,
"FAIL: has_body=%d body_in_band=%d correct_geometry=%d\n",
has_body, body_in_band, correct_geometry);
result = 1;
} else {
std::printf("PASS: real OpenNI2 consumer read in-band synthetic depth\n");
}
}
frame.release();
depth.stop();
depth.destroy();
device.close();
openni::OpenNI::shutdown();
return result;
}
@@ -0,0 +1,222 @@
/*****************************************************************************
* *
* OpenNI 2.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* Licensed under the Apache License, Version 2.0. *
* *
* Vendored from structureio/OpenNI2 Include/Driver/OniDriverAPI.h. *
*****************************************************************************/
#ifndef _ONI_DRIVER_API_H_
#define _ONI_DRIVER_API_H_
#include "OniPlatform.h"
#include "OniCTypes.h"
#include "OniCProperties.h"
#include "OniDriverTypes.h"
#include <stdarg.h>
namespace oni { namespace driver {
class DeviceBase;
class StreamBase;
typedef void (ONI_CALLBACK_TYPE* DeviceConnectedCallback)(const OniDeviceInfo*, void*);
typedef void (ONI_CALLBACK_TYPE* DeviceDisconnectedCallback)(const OniDeviceInfo*, void*);
typedef void (ONI_CALLBACK_TYPE* DeviceStateChangedCallback)(const OniDeviceInfo*, int, void*);
typedef void (ONI_CALLBACK_TYPE* NewFrameCallback)(StreamBase*, OniFrame*, void*);
typedef void (ONI_CALLBACK_TYPE* PropertyChangedCallback)(void*, int, const void*, int, void*);
class StreamServices : public OniStreamServices
{
public:
int getDefaultRequiredFrameSize() { return OniStreamServices::getDefaultRequiredFrameSize(streamServices); }
OniFrame* acquireFrame() { return OniStreamServices::acquireFrame(streamServices); }
void addFrameRef(OniFrame* frame) { OniStreamServices::addFrameRef(streamServices, frame); }
void releaseFrame(OniFrame* frame) { OniStreamServices::releaseFrame(streamServices, frame); }
};
class StreamBase
{
public:
StreamBase() : m_services(NULL), m_newFrameCallback(NULL), m_newFrameCookie(NULL),
m_propertyChangedCallback(NULL), m_propertyChangedCookie(NULL) {}
virtual ~StreamBase() {}
virtual void setServices(StreamServices* services) { m_services = services; }
virtual OniStatus setProperty(int, const void*, int) { return ONI_STATUS_NOT_IMPLEMENTED; }
virtual OniStatus getProperty(int, void*, int*) { return ONI_STATUS_NOT_IMPLEMENTED; }
virtual OniBool isPropertySupported(int) { return FALSE; }
virtual OniStatus invoke(int, void*, int) { return ONI_STATUS_NOT_IMPLEMENTED; }
virtual OniBool isCommandSupported(int) { return FALSE; }
virtual int getRequiredFrameSize() { return getServices().getDefaultRequiredFrameSize(); }
virtual OniStatus start() = 0;
virtual void stop() = 0;
virtual void setNewFrameCallback(NewFrameCallback callback, void* cookie)
{
m_newFrameCallback = callback;
m_newFrameCookie = cookie;
}
virtual void setPropertyChangedCallback(PropertyChangedCallback callback, void* cookie)
{
m_propertyChangedCallback = callback;
m_propertyChangedCookie = cookie;
}
virtual void notifyAllProperties() {}
virtual OniStatus convertDepthToColorCoordinates(
StreamBase*, int, int, OniDepthPixel, int*, int*)
{
return ONI_STATUS_NOT_SUPPORTED;
}
protected:
void raiseNewFrame(OniFrame* frame)
{
m_newFrameCallback(this, frame, m_newFrameCookie);
}
void raisePropertyChanged(int propertyId, const void* data, int dataSize)
{
m_propertyChangedCallback(this, propertyId, data, dataSize, m_propertyChangedCookie);
}
StreamServices& getServices() { return *m_services; }
private:
StreamServices* m_services;
NewFrameCallback m_newFrameCallback;
void* m_newFrameCookie;
PropertyChangedCallback m_propertyChangedCallback;
void* m_propertyChangedCookie;
};
class DeviceBase
{
public:
virtual ~DeviceBase() {}
virtual OniStatus getSensorInfoList(OniSensorInfo**, int*) = 0;
virtual StreamBase* createStream(OniSensorType) = 0;
virtual void destroyStream(StreamBase*) = 0;
virtual OniStatus setProperty(int, const void*, int) { return ONI_STATUS_NOT_IMPLEMENTED; }
virtual OniStatus getProperty(int, void*, int*) { return ONI_STATUS_NOT_IMPLEMENTED; }
virtual OniBool isPropertySupported(int) { return FALSE; }
virtual OniStatus invoke(int, void*, int) { return ONI_STATUS_NOT_IMPLEMENTED; }
virtual OniBool isCommandSupported(int) { return FALSE; }
virtual OniStatus tryManualTrigger() { return ONI_STATUS_OK; }
virtual void setPropertyChangedCallback(PropertyChangedCallback callback, void* cookie)
{
m_propertyChangedCallback = callback;
m_propertyChangedCookie = cookie;
}
virtual void notifyAllProperties() {}
virtual OniBool isImageRegistrationModeSupported(OniImageRegistrationMode mode)
{
return mode == ONI_IMAGE_REGISTRATION_OFF;
}
protected:
void raisePropertyChanged(int propertyId, const void* data, int dataSize)
{
m_propertyChangedCallback(this, propertyId, data, dataSize, m_propertyChangedCookie);
}
private:
PropertyChangedCallback m_propertyChangedCallback;
void* m_propertyChangedCookie;
};
class DriverServices
{
public:
explicit DriverServices(OniDriverServices* services) : m_services(services) {}
void errorLoggerAppend(const char* format, ...)
{
va_list args;
va_start(args, format);
m_services->errorLoggerAppend(m_services->driverServices, format, args);
va_end(args);
}
void errorLoggerClear() { m_services->errorLoggerClear(m_services->driverServices); }
void log(int severity, const char* file, int line, const char* mask, const char* message)
{
m_services->log(m_services->driverServices, severity, file, line, mask, message);
}
private:
OniDriverServices* m_services;
};
class DriverBase
{
public:
explicit DriverBase(OniDriverServices* services) : m_services(services) {}
virtual ~DriverBase() {}
virtual OniStatus initialize(
DeviceConnectedCallback connected,
DeviceDisconnectedCallback disconnected,
DeviceStateChangedCallback stateChanged,
void* cookie)
{
m_connected = connected;
m_disconnected = disconnected;
m_stateChanged = stateChanged;
m_cookie = cookie;
return ONI_STATUS_OK;
}
virtual DeviceBase* deviceOpen(const char*, const char*) = 0;
virtual void deviceClose(DeviceBase*) = 0;
virtual void shutdown() = 0;
virtual OniStatus tryDevice(const char*) { return ONI_STATUS_ERROR; }
virtual void* enableFrameSync(StreamBase**, int) { return NULL; }
virtual void disableFrameSync(void*) {}
protected:
void deviceConnected(const OniDeviceInfo* info) { m_connected(info, m_cookie); }
void deviceDisconnected(const OniDeviceInfo* info) { m_disconnected(info, m_cookie); }
void deviceStateChanged(const OniDeviceInfo* info, int state) { m_stateChanged(info, state, m_cookie); }
DriverServices& getServices() { return m_services; }
private:
DeviceConnectedCallback m_connected;
DeviceDisconnectedCallback m_disconnected;
DeviceStateChangedCallback m_stateChanged;
void* m_cookie;
DriverServices m_services;
};
}} // namespace oni::driver
#define ONI_EXPORT_DRIVER(DriverClass) \
oni::driver::DriverBase* g_pDriver = NULL; \
ONI_C_API_EXPORT void oniDriverCreate(OniDriverServices* s) { g_pDriver = XN_NEW(DriverClass, s); } \
ONI_C_API_EXPORT void oniDriverDestroy() { g_pDriver->shutdown(); XN_DELETE(g_pDriver); g_pDriver = NULL; } \
ONI_C_API_EXPORT OniStatus oniDriverInitialize(oni::driver::DeviceConnectedCallback c, oni::driver::DeviceDisconnectedCallback d, oni::driver::DeviceStateChangedCallback sc, void* p) { return g_pDriver->initialize(c, d, sc, p); } \
ONI_C_API_EXPORT OniStatus oniDriverTryDevice(const char* u) { return g_pDriver->tryDevice(u); } \
ONI_C_API_EXPORT oni::driver::DeviceBase* oniDriverDeviceOpen(const char* u, const char* m) { return g_pDriver->deviceOpen(u, m); } \
ONI_C_API_EXPORT void oniDriverDeviceClose(oni::driver::DeviceBase* d) { g_pDriver->deviceClose(d); } \
ONI_C_API_EXPORT OniStatus oniDriverDeviceGetSensorInfoList(oni::driver::DeviceBase* d, OniSensorInfo** s, int* n) { return d->getSensorInfoList(s, n); } \
ONI_C_API_EXPORT oni::driver::StreamBase* oniDriverDeviceCreateStream(oni::driver::DeviceBase* d, OniSensorType t) { return d->createStream(t); } \
ONI_C_API_EXPORT void oniDriverDeviceDestroyStream(oni::driver::DeviceBase* d, oni::driver::StreamBase* s) { d->destroyStream(s); } \
ONI_C_API_EXPORT OniStatus oniDriverDeviceSetProperty(oni::driver::DeviceBase* d, int p, const void* v, int z) { return d->setProperty(p, v, z); } \
ONI_C_API_EXPORT OniStatus oniDriverDeviceGetProperty(oni::driver::DeviceBase* d, int p, void* v, int* z) { return d->getProperty(p, v, z); } \
ONI_C_API_EXPORT OniBool oniDriverDeviceIsPropertySupported(oni::driver::DeviceBase* d, int p) { return d->isPropertySupported(p); } \
ONI_C_API_EXPORT void oniDriverDeviceSetPropertyChangedCallback(oni::driver::DeviceBase* d, oni::driver::PropertyChangedCallback c, void* p) { d->setPropertyChangedCallback(c, p); } \
ONI_C_API_EXPORT void oniDriverDeviceNotifyAllProperties(oni::driver::DeviceBase* d) { d->notifyAllProperties(); } \
ONI_C_API_EXPORT OniStatus oniDriverDeviceInvoke(oni::driver::DeviceBase* d, int c, void* v, int z) { return d->invoke(c, v, z); } \
ONI_C_API_EXPORT OniBool oniDriverDeviceIsCommandSupported(oni::driver::DeviceBase* d, int c) { return d->isCommandSupported(c); } \
ONI_C_API_EXPORT OniStatus oniDriverDeviceTryManualTrigger(oni::driver::DeviceBase* d) { return d->tryManualTrigger(); } \
ONI_C_API_EXPORT OniBool oniDriverDeviceIsImageRegistrationModeSupported(oni::driver::DeviceBase* d, OniImageRegistrationMode m) { return d->isImageRegistrationModeSupported(m); } \
ONI_C_API_EXPORT void oniDriverStreamSetServices(oni::driver::StreamBase* s, OniStreamServices* v) { s->setServices((oni::driver::StreamServices*)v); } \
ONI_C_API_EXPORT OniStatus oniDriverStreamSetProperty(oni::driver::StreamBase* s, int p, const void* v, int z) { return s->setProperty(p, v, z); } \
ONI_C_API_EXPORT OniStatus oniDriverStreamGetProperty(oni::driver::StreamBase* s, int p, void* v, int* z) { return s->getProperty(p, v, z); } \
ONI_C_API_EXPORT OniBool oniDriverStreamIsPropertySupported(oni::driver::StreamBase* s, int p) { return s->isPropertySupported(p); } \
ONI_C_API_EXPORT void oniDriverStreamSetPropertyChangedCallback(oni::driver::StreamBase* s, oni::driver::PropertyChangedCallback c, void* p) { s->setPropertyChangedCallback(c, p); } \
ONI_C_API_EXPORT void oniDriverStreamNotifyAllProperties(oni::driver::StreamBase* s) { s->notifyAllProperties(); } \
ONI_C_API_EXPORT OniStatus oniDriverStreamInvoke(oni::driver::StreamBase* s, int c, void* v, int z) { return s->invoke(c, v, z); } \
ONI_C_API_EXPORT OniBool oniDriverStreamIsCommandSupported(oni::driver::StreamBase* s, int c) { return s->isCommandSupported(c); } \
ONI_C_API_EXPORT OniStatus oniDriverStreamStart(oni::driver::StreamBase* s) { return s->start(); } \
ONI_C_API_EXPORT void oniDriverStreamStop(oni::driver::StreamBase* s) { s->stop(); } \
ONI_C_API_EXPORT int oniDriverStreamGetRequiredFrameSize(oni::driver::StreamBase* s) { return s->getRequiredFrameSize(); } \
ONI_C_API_EXPORT void oniDriverStreamSetNewFrameCallback(oni::driver::StreamBase* s, oni::driver::NewFrameCallback c, void* p) { s->setNewFrameCallback(c, p); } \
ONI_C_API_EXPORT OniStatus oniDriverStreamConvertDepthToColorCoordinates(oni::driver::StreamBase* d, oni::driver::StreamBase* c, int x, int y, OniDepthPixel z, int* cx, int* cy) { return d->convertDepthToColorCoordinates(c, x, y, z, cx, cy); } \
ONI_C_API_EXPORT void* oniDriverEnableFrameSync(oni::driver::StreamBase** s, int n) { return g_pDriver->enableFrameSync(s, n); } \
ONI_C_API_EXPORT void oniDriverDisableFrameSync(void* g) { g_pDriver->disableFrameSync(g); }
#endif // _ONI_DRIVER_API_H_
@@ -0,0 +1,41 @@
/*****************************************************************************
* *
* OpenNI 2.x Alpha *
* Copyright (C) 2012 PrimeSense Ltd. *
* *
* Licensed under the Apache License, Version 2.0. *
* *
*****************************************************************************/
#ifndef _ONI_DRIVER_TYPES_H_
#define _ONI_DRIVER_TYPES_H_
#include <OniCTypes.h>
#include <stdarg.h>
#define ONI_STREAM_PROPERTY_PRIVATE_BASE XN_MAX_UINT16
typedef struct
{
int dataSize;
void* data;
} OniGeneralBuffer;
struct OniDriverServices
{
void* driverServices;
void (ONI_CALLBACK_TYPE* errorLoggerAppend)(void* driverServices, const char* format, va_list args);
void (ONI_CALLBACK_TYPE* errorLoggerClear)(void* driverServices);
void (ONI_CALLBACK_TYPE* log)(void* driverServices, int severity, const char* file, int line, const char* mask, const char* message);
};
struct OniStreamServices
{
void* streamServices;
int (ONI_CALLBACK_TYPE* getDefaultRequiredFrameSize)(void* streamServices);
OniFrame* (ONI_CALLBACK_TYPE* acquireFrame)(void* streamServices);
void (ONI_CALLBACK_TYPE* addFrameRef)(void* streamServices, OniFrame* pframe);
void (ONI_CALLBACK_TYPE* releaseFrame)(void* streamServices, OniFrame* pframe);
};
#endif // _ONI_DRIVER_TYPES_H_