diff --git a/.omo/plans/webcam-kinect-emulator.md b/.omo/plans/webcam-kinect-emulator.md index b7c0b87..3034939 100644 --- a/.omo/plans/webcam-kinect-emulator.md +++ b/.omo/plans/webcam-kinect-emulator.md @@ -186,7 +186,7 @@ Your next move: run the default-on high-accuracy review (in progress), then exec Commit: Y | feat(synth): packed depth+player-index+color rasterizer Recommended task executor category: deep-low - format + raster math from cited contracts. -- [ ] 8. Kinect v1 USB protocol emitter (device core) +- [x] 8. Kinect v1 USB protocol emitter (device core) What to do / Must NOT do: In `core/protocol/`, implement the OS-agnostic virtual Kinect: respond to the USB descriptors/control transfers/EEPROM-register reads the host driver needs to enumerate+init a Kinect v1 (per the todo-3 spike + libfreenect), and emit depth/color (+IR, + minimal audio-interface enumeration) over the device's iso/bulk endpoints, pulling frame data from the synth rasterizer (todo 7) via the contract. Expose a transport-agnostic "USB device backend" interface so the Linux (todo 9) and Windows (todo 12) attach shims plug in. Must NOT: emit a skeleton (the device never does - the host computes it); block the emit loop on the generator (use the newest-wins slot). Closes: GAP-1 (device byte stream) Parallelization: Wave 5 | Blocked by: 3,7 | Blocks: 9,12 diff --git a/CMakeLists.txt b/CMakeLists.txt index fd3a906..03ed7e5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,6 +15,10 @@ add_library(libnui_core STATIC core/mapping/mapping.cpp core/synth/mask_stabilizer.cpp core/synth/synth.cpp + core/protocol/commands.cpp + core/protocol/descriptors.cpp + core/protocol/protocol.cpp + core/protocol/streams.cpp ) # Keep the on-disk name libnui_core.a (not liblibnui_core.a). set_target_properties(libnui_core PROPERTIES PREFIX "" OUTPUT_NAME "libnui_core") @@ -50,6 +54,7 @@ if(NUI_CORE_BUILD_TESTS) tests/test_contract.cpp tests/test_mapping.cpp tests/test_synth.cpp + tests/test_protocol.cpp ) target_link_libraries(libnui_core_tests PRIVATE libnui_core GTest::gtest_main) diff --git a/core/protocol/commands.cpp b/core/protocol/commands.cpp new file mode 100644 index 0000000..794b67d --- /dev/null +++ b/core/protocol/commands.cpp @@ -0,0 +1,169 @@ +#include "protocol/wire.h" + +#include +#include +#include + +namespace nui::protocol { + +// Exact envelope provenance (fetched as raw source, no git operation): +// https://github.com/OpenKinect/libfreenect/blob/09a1f098/src/flags.c#L184-L302 +// cam_hdr: GM, uint16 LE payload WORD count, opcode, tag. Replies use RB. +std::optional encode_command(const CameraCommand& command) { + if ((command.magic != CameraMagic::command && command.magic != CameraMagic::reply) || + command.payload.size() % 2 != 0 || command.payload.size() > 1016) { + return std::nullopt; + } + Bytes bytes(8 + command.payload.size()); + wire::put16(bytes, 0, static_cast(command.magic)); + wire::put16(bytes, 2, static_cast(command.payload.size() / 2)); + wire::put16(bytes, 4, command.command); + wire::put16(bytes, 6, command.sequence); + std::copy(command.payload.begin(), command.payload.end(), bytes.begin() + 8); + return bytes; +} + +std::optional decode_command(const Bytes& bytes) { + if (bytes.size() < 8 || bytes.size() > 1024 || + bytes.size() != 8u + 2u * wire::u16(bytes, 2)) { + return std::nullopt; + } + const auto magic = static_cast(wire::u16(bytes, 0)); + if (magic != CameraMagic::command && magic != CameraMagic::reply) { + return std::nullopt; + } + return CameraCommand{magic, wire::u16(bytes, 4), wire::u16(bytes, 6), + Bytes(bytes.begin() + 8, bytes.end())}; +} + +TransferResult KinectV1Device::camera_control( + const ControlSetup& setup, const Bytes& out) { + if (setup.request != 0 || setup.value != 0 || setup.index != 0) { + return {TransferStatus::stall, {}}; + } + if (setup.request_type == 0xc0) { + Bytes reply = std::move(pending_reply_); + pending_reply_.clear(); + reply.resize(std::min(setup.length, reply.size())); + return {TransferStatus::completed, std::move(reply)}; + } + if (setup.request_type != 0x40) { + return {TransferStatus::stall, {}}; + } + // A new command supersedes any unread response, including on a stalled OUT. + pending_reply_.clear(); + const auto command = decode_command(out); + if (!command || command->magic != CameraMagic::command) { + return {TransferStatus::stall, {}}; + } + const auto payload = execute_command(*command); + if (!payload) { + return {TransferStatus::stall, {}}; + } + pending_reply_ = *encode_command( + {CameraMagic::reply, command->command, command->sequence, *payload}); + return {TransferStatus::completed, {}}; +} + +std::optional KinectV1Device::execute_command(const CameraCommand& command) { + const auto& payload = command.payload; + switch (command.command) { + case 0x02: { // read_register: status word followed by value + if (payload.size() != 2) return std::nullopt; + const auto found = registers_.find(wire::u16(payload, 0)); + if (found == registers_.end()) return std::nullopt; + Bytes reply(4, 0); + wire::put16(reply, 2, found->second); + return reply; + } + case 0x03: + if (payload.size() != 4 || + !write_register(wire::u16(payload, 0), wire::u16(payload, 2))) { + return std::nullopt; + } + return Bytes(2, 0); + case 0x04: { + if (payload.size() != 10 || + std::any_of(payload.begin(), payload.end(), [](uint8_t b) { return b != 0; })) { + return std::nullopt; + } + // cameras.c:794-836: 322 bytes INCLUDING status; four LE floats at +94. + Bytes reply(322, 0); + const std::array calibration{ + wire::kEmitterDistance, wire::kCameraDistance, + wire::kReferenceDistance, wire::kPixelSize}; + static_assert(sizeof(float) == 4 && std::numeric_limits::is_iec559); + for (std::size_t i = 0; i < calibration.size(); ++i) { + uint32_t bits; + std::memcpy(&bits, &calibration[i], sizeof(bits)); + wire::put32(reply, 94 + i * 4, bits); + } + return reply; + } + case 0x16: { + // cameras.c:664-791. During camera_init video mode is still zeroed; + // accept that query as well as medium/30. No other mode is advertised. + if (payload.size() != 10 || wire::u16(payload, 2) != 0 || + wire::u16(payload, 8) != 0 || + !((wire::u16(payload, 4) == 0 && wire::u16(payload, 6) == 0) || + (wire::u16(payload, 4) == 1 && wire::u16(payload, 6) == 30))) { + return std::nullopt; + } + switch (wire::u16(payload, 0)) { + case 0x00: { + Bytes reply(4, 0); + wire::put16(reply, 2, wire::kConstantShift); + return reply; + } + case 0x40: { + // No lens distortion in the virtual camera. Cancel libfreenect's + // +1 pixel offsets with dx_start/dy_start = -256 (registration.c:231, + // 273, 300). All polynomial derivatives are zero. + Bytes reply(118, 0); + wire::put32(reply, 2 + 5 * 4, 0xffffff00u); + wire::put32(reply, 2 + 10 * 4, 0xffffff00u); + return reply; + } + case 0x41: return Bytes(8, 0); // no crop or padded depth lines + default: return std::nullopt; + } + } + default: return std::nullopt; + } +} + +bool KinectV1Device::write_register(uint16_t reg, uint16_t value) { + // Supported wire modes: 640x480 11-bit depth, GRBG Bayer, 640x488 IR + // (10-bit packed), all 30 Hz. Reject unsupported writes before changing state. + const auto found = registers_.find(reg); + if (found == registers_.end()) return false; + switch (reg) { + case 0x05: + if (value != 0 && value != 1 && value != 3) return false; + video_ = {}; + break; + case 0x06: + if (value != 0 && value != 2) return false; + depth_ = {}; + break; + case 0x12: if (value != 3) return false; break; + case 0x13: case 0x0d: case 0x1a: + if (value != 1) return false; + break; + case 0x14: case 0x0e: case 0x1b: + if (value != 30) return false; + break; + case 0x0c: case 0x19: case 0x105: + if (value != 0) return false; + break; + case 0x17: case 0x47: case 0x48: + if (value > 1) return false; + break; + case 0x15: if (value < 1 || value > 50) return false; break; + default: return false; + } + found->second = value; + return true; +} + +} // namespace nui::protocol diff --git a/core/protocol/descriptors.cpp b/core/protocol/descriptors.cpp new file mode 100644 index 0000000..8c292dd --- /dev/null +++ b/core/protocol/descriptors.cpp @@ -0,0 +1,121 @@ +#include "protocol/wire.h" + +namespace nui::protocol::wire { +namespace { + +constexpr uint16_t kVendorMicrosoft = 0x045e; +constexpr uint16_t kProductCamera = 0x02ae; // PID_NUI_CAMERA, freenect_internal.h:139 +constexpr uint16_t kProductAudio = 0x02ad; // PID_NUI_AUDIO, freenect_internal.h:138 +constexpr uint16_t kProductMotor = 0x02b0; // PID_NUI_MOTOR, freenect_internal.h:140 +constexpr uint16_t kBcdDevice1414 = 0x010b; // 267, the 1414 discriminator, usb_libusb10.c:431 + +void append16(Bytes& bytes, uint16_t value) { + bytes.push_back(static_cast(value)); + bytes.push_back(static_cast(value >> 8)); +} + +Bytes device_descriptor(uint16_t product, uint16_t bcd_device) { + Bytes bytes{18, 0x01}; + append16(bytes, 0x0200); + bytes.insert(bytes.end(), {0xff, 0xff, 0xff, 64}); + append16(bytes, kVendorMicrosoft); + append16(bytes, product); + append16(bytes, bcd_device); + bytes.insert(bytes.end(), {0, 0, 0, 1}); + return bytes; +} + +void append_interface(Bytes& bytes, uint8_t number, uint8_t endpoints) { + bytes.insert(bytes.end(), + {9, 0x04, number, 0, endpoints, 0xff, 0xff, 0xff, 0}); +} + +void append_iso_in_endpoint(Bytes& bytes, uint8_t address, uint16_t max_packet) { + bytes.insert(bytes.end(), {7, 0x05, address, 0x01}); + append16(bytes, max_packet); + bytes.push_back(1); +} + +Bytes config_descriptor(Bytes body, uint8_t interfaces) { + Bytes bytes{9, 0x02}; + append16(bytes, static_cast(9 + body.size())); + bytes.insert(bytes.end(), {interfaces, 1, 0, 0x80, 50}); + bytes.insert(bytes.end(), body.begin(), body.end()); + return bytes; +} + +Bytes camera_config() { + Bytes body; + append_interface(body, 0, 2); + // Depth iso IN 0x82 and video iso IN 0x81 (cameras.c:871, :1021). The high- + // bandwidth iso packet size the host negotiates at runtime belongs to the + // attach shim (todo 9); the descriptor advertises the per-microframe buffer. + append_iso_in_endpoint(body, 0x82, 1760); + append_iso_in_endpoint(body, 0x81, 1920); + return config_descriptor(std::move(body), 1); +} + +Bytes audio_config() { + // Two interfaces so the host reads the audio device as already firmware- + // loaded and skips the bootloader upload (usb_libusb10.c:554-555). + Bytes body; + append_interface(body, 0, 0); + append_interface(body, 1, 0); + return config_descriptor(std::move(body), 2); +} + +Bytes motor_config() { + Bytes body; + append_interface(body, 0, 0); + return config_descriptor(std::move(body), 1); +} + +} // namespace + +std::optional descriptor(UsbFunction function, uint16_t type_index) { + const uint8_t type = static_cast(type_index >> 8); + const uint8_t index = static_cast(type_index); + if (index != 0) { + return std::nullopt; + } + if (type == 0x01) { + switch (function) { + case UsbFunction::camera: + return device_descriptor(kProductCamera, kBcdDevice1414); + case UsbFunction::audio: + return device_descriptor(kProductAudio, kBcdDevice1414); + case UsbFunction::motor: + return device_descriptor(kProductMotor, kBcdDevice1414); + } + } + if (type == 0x02) { + switch (function) { + case UsbFunction::camera: + return camera_config(); + case UsbFunction::audio: + return audio_config(); + case UsbFunction::motor: + return motor_config(); + } + } + return std::nullopt; +} + +bool endpoint_exists(UsbFunction function, uint16_t endpoint) { + return function == UsbFunction::camera && + (endpoint == 0x81 || endpoint == 0x82); +} + +uint8_t interface_count(UsbFunction function) { + switch (function) { + case UsbFunction::camera: + return 1; + case UsbFunction::audio: + return 2; + case UsbFunction::motor: + return 1; + } + return 0; +} + +} // namespace nui::protocol::wire diff --git a/core/protocol/protocol.cpp b/core/protocol/protocol.cpp new file mode 100644 index 0000000..bd8b77a --- /dev/null +++ b/core/protocol/protocol.cpp @@ -0,0 +1,86 @@ +#include "protocol/protocol.h" + +#include +#include + +#include "protocol/wire.h" + +namespace nui::protocol { +namespace { + +// Every register the host writes during Kinect v1 camera bring-up, so an +// out-of-table write is rejected as unsupported rather than silently stored. +// Depth start (libfreenect 09a1f098 src/cameras.c:880-899): 0x105,0x06,0x12, +// 0x13,0x14,0x17. Video/IR start (cameras.c:936-1050): 0x0c/0x0d/0x0e,0x47 +// (Bayer) and 0x19/0x1a/0x1b,0x48 (IR), 0x05. IR brightness 0x15 (flags.c:175). +std::map default_registers() { + std::map registers; + for (uint16_t reg : {0x05, 0x06, 0x0c, 0x0d, 0x0e, 0x12, 0x13, 0x14, 0x15, + 0x17, 0x19, 0x1a, 0x1b, 0x47, 0x48, 0x105}) { + registers[reg] = 0; + } + return registers; +} + +std::size_t function_index(UsbFunction function) { + return static_cast(function); +} + +} // namespace + +KinectV1Device::KinectV1Device(FrameSource source) + : source_(std::move(source)), registers_(default_registers()) {} + +void KinectV1Device::reset(UsbFunction function) { + if (function == UsbFunction::camera) { + registers_ = default_registers(); + depth_ = {}; + video_ = {}; + pending_reply_.clear(); + } + configurations_[function_index(function)] = 0; +} + +TransferResult KinectV1Device::answer_control_transfer( + UsbFunction function, const ControlSetup& setup, const Bytes& out) { + // bmRequestType bits 6:5 select the request type: 0 = standard (enumeration), + // 2 = vendor (the camera command channel send_cmd rides, cameras.c:213/221). + const uint8_t type = setup.request_type & 0x60; + if (type == 0x40) { + if (function != UsbFunction::camera) { + return {TransferStatus::stall, {}}; + } + return camera_control(setup, out); + } + if (type == 0x00) { + return standard_control(function, setup); + } + return {TransferStatus::stall, {}}; +} + +TransferResult KinectV1Device::standard_control( + UsbFunction function, const ControlSetup& setup) { + switch (setup.request) { + case 0x06: { // GET_DESCRIPTOR: wValue = (type << 8) | index + auto descriptor = wire::descriptor(function, setup.value); + if (!descriptor) { + return {TransferStatus::stall, {}}; + } + descriptor->resize(std::min(setup.length, descriptor->size())); + return {TransferStatus::completed, std::move(*descriptor)}; + } + case 0x08: // GET_CONFIGURATION + return {TransferStatus::completed, + Bytes{configurations_[function_index(function)]}}; + case 0x09: // SET_CONFIGURATION + configurations_[function_index(function)] = + static_cast(setup.value); + return {TransferStatus::completed, {}}; + case 0x0b: // SET_INTERFACE: the 1414 camera stays on alt 0 (cameras.c:318) + return {TransferStatus::completed, {}}; + default: + return {TransferStatus::stall, {}}; + } +} + +} // namespace nui::protocol diff --git a/core/protocol/protocol.h b/core/protocol/protocol.h new file mode 100644 index 0000000..edd3e18 --- /dev/null +++ b/core/protocol/protocol.h @@ -0,0 +1,96 @@ +#ifndef NUI_CORE_PROTOCOL_H +#define NUI_CORE_PROTOCOL_H + +#include +#include +#include +#include +#include +#include +#include + +#include "synth/synth.h" + +namespace nui::protocol { + +using Bytes = std::vector; + +// Values are wire values, not native structs copied onto USB. +enum class CameraMagic : uint16_t { command = 0x4d47, reply = 0x4252 }; +struct CameraCommand { + CameraMagic magic; + uint16_t command; + uint16_t sequence; + Bytes payload; +}; +std::optional encode_command(const CameraCommand& command); +std::optional decode_command(const Bytes& bytes); + +// Three sibling devices behind the attach shim's hub, not three interfaces +// of one composite device. The index is stable for per-device USB state. +enum class UsbFunction : uint8_t { camera, audio, motor }; +struct ControlSetup { + uint8_t request_type; + uint8_t request; + uint16_t value; + uint16_t index; + uint16_t length; +}; +enum class TransferStatus { completed, stall, idle, invalid_frame }; +struct TransferResult { + TransferStatus status; + Bytes data; +}; + +class UsbDeviceBackend { + public: + virtual ~UsbDeviceBackend() = default; + virtual TransferResult answer_control_transfer( + UsbFunction function, const ControlSetup& setup, const Bytes& out = {}) = 0; + virtual TransferResult next_packet(UsbFunction function, uint8_t endpoint) = 0; + virtual void reset(UsbFunction function) = 0; +}; + +struct SynthFrame { + contract::FrameData metadata{}; + synth::DepthFrame depth; + synth::BgraFrame color; +}; + +// The producer owns the newest-wins slot. This callback must return an immutable +// snapshot immediately (nullptr before the first frame), never wait for capture. +// Called only at frame boundaries; a packetized frame cannot tear on publication. +using FrameSource = std::function()>; + +class KinectV1Device final : public UsbDeviceBackend { + public: + explicit KinectV1Device(FrameSource source); + TransferResult answer_control_transfer( + UsbFunction function, const ControlSetup& setup, const Bytes& out = {}) override; + TransferResult next_packet(UsbFunction function, uint8_t endpoint) override; + void reset(UsbFunction function) override; + + private: + struct Stream { + Bytes bytes; + std::size_t offset = 0; + uint8_t sequence = 0; + uint32_t timestamp = 0; + std::optional frame_number; + }; + TransferResult camera_control(const ControlSetup& setup, const Bytes& out); + std::optional execute_command(const CameraCommand& command); + bool write_register(uint16_t reg, uint16_t value); + TransferResult standard_control(UsbFunction function, const ControlSetup& setup); + + FrameSource source_; + std::array configurations_{}; + std::map registers_; + Bytes pending_reply_; + Stream depth_; + Stream video_; + int8_t tilt_ = 0; +}; + +} // namespace nui::protocol +#endif // NUI_CORE_PROTOCOL_H diff --git a/core/protocol/streams.cpp b/core/protocol/streams.cpp new file mode 100644 index 0000000..4ba8d10 --- /dev/null +++ b/core/protocol/streams.cpp @@ -0,0 +1,195 @@ +#include +#include +#include +#include + +#include "protocol/protocol.h" +#include "protocol/wire.h" +#include "synth/synth.h" + +namespace nui::protocol { +namespace { + +constexpr uint32_t kDepthWidth = 640; +constexpr uint32_t kDepthHeight = 480; +constexpr uint32_t kColorWidth = 640; +constexpr uint32_t kColorHeight = 480; +constexpr uint32_t kInfraredWidth = 640; +constexpr uint32_t kInfraredHeight = 488; +constexpr std::size_t kDepthPayload = 1748; // DEPTH_PKTDSIZE, freenect_internal.h:131 +constexpr std::size_t kVideoPayload = 1908; // VIDEO_PKTDSIZE, freenect_internal.h:133 +constexpr uint16_t kRawNoValue = 2047; // FREENECT_DEPTH_RAW_NO_VALUE + +// Inverse of libfreenect's freenect_raw_to_mm (registration.c:315-325) under +// the synthetic 1414 calibration (wire.h). The host rebuilds raw->mm from the +// same EEPROM constants this device reports, so this inverse must use them too +// or the reconstructed depth drifts. parameter_coefficient=4, shift_scale=10, +// pixel_size_factor=1, S2D_CONST_OFFSET=0.375 are constants in that source. +uint16_t millimeters_to_raw(uint16_t millimeters) { + if (millimeters == 0) { + return kRawNoValue; + } + const double scaled = millimeters / 10.0; + const double metric = + (scaled - wire::kReferenceDistance) * wire::kEmitterDistance / scaled; + const double fixed_ref_x = metric / wire::kPixelSize; + const double raw = 4.0 * fixed_ref_x + 1.5 + 4.0 * wire::kConstantShift; + const long rounded = std::lround(raw); + if (rounded < 0 || rounded >= kRawNoValue) { + return kRawNoValue; + } + return static_cast(rounded); +} + +// MSB-first bit packing: the exact inverse of convert_packed11_to_16bit +// (cameras.c:345-375) generalised to any width <= 16. Each value's high bits +// enter the byte stream first, so 8 eleven-bit samples occupy 11 bytes. +void pack_bits(const std::vector& values, unsigned width, Bytes& out) { + const uint32_t mask = (1u << width) - 1u; + uint32_t buffer = 0; + unsigned bits = 0; + for (const uint16_t value : values) { + buffer = (buffer << width) | (value & mask); + bits += width; + while (bits >= 8) { + bits -= 8; + out.push_back(static_cast((buffer >> bits) & 0xff)); + } + } + if (bits > 0) { + out.push_back(static_cast((buffer << (8 - bits)) & 0xff)); + } +} + +uint16_t sample_depth(const synth::DepthFrame& source, uint32_t x, uint32_t y) { + if (source.size.width == 0 || source.size.height == 0 || + source.pixels.size() != static_cast(source.size.width) * + source.size.height) { + return 0; + } + const uint32_t source_x = x * source.size.width / kDepthWidth; + const uint32_t source_y = y * source.size.height / kDepthHeight; + return source.pixels[static_cast(source_y) * source.size.width + + source_x]; +} + +uint8_t bayer_grbg(const synth::BgraFrame& color, uint32_t x, uint32_t y) { + const std::size_t base = + (static_cast(y) * kColorWidth + x) * 4; + const uint8_t blue = color.pixels[base]; + const uint8_t green = color.pixels[base + 1]; + const uint8_t red = color.pixels[base + 2]; + const bool even_row = (y % 2) == 0; + const bool even_col = (x % 2) == 0; + if (even_row) { + return even_col ? green : red; + } + return even_col ? blue : green; +} + +Bytes build_depth(const SynthFrame& frame) { + std::vector raw(static_cast(kDepthWidth) * kDepthHeight); + for (uint32_t y = 0; y < kDepthHeight; ++y) { + for (uint32_t x = 0; x < kDepthWidth; ++x) { + const uint16_t packed = sample_depth(frame.depth, x, y); + raw[static_cast(y) * kDepthWidth + x] = + millimeters_to_raw(synth::NuiDepthPixelToDepth(packed)); + } + } + Bytes out; + out.reserve(static_cast(kDepthWidth) * kDepthHeight * 11 / 8); + pack_bits(raw, 11, out); + return out; +} + +Bytes build_video(const SynthFrame& frame, bool infrared) { + if (infrared) { + const auto image = synth::synthesize_infrared( + frame.color, {kInfraredWidth, kInfraredHeight}); + std::vector values(image.pixels.size()); + for (std::size_t i = 0; i < values.size(); ++i) { + values[i] = static_cast(image.pixels[i] >> 6); + } + Bytes out; + out.reserve(static_cast(kInfraredWidth) * kInfraredHeight * 10 / 8); + pack_bits(values, 10, out); + return out; + } + const auto color = + synth::passthrough_color(frame.color, {kColorWidth, kColorHeight}); + Bytes out(static_cast(kColorWidth) * kColorHeight); + for (uint32_t y = 0; y < kColorHeight; ++y) { + for (uint32_t x = 0; x < kColorWidth; ++x) { + out[static_cast(y) * kColorWidth + x] = bayer_grbg(color, x, y); + } + } + return out; +} + +} // namespace + +TransferResult KinectV1Device::next_packet(UsbFunction function, uint8_t endpoint) { + if (function != UsbFunction::camera) { + return {TransferStatus::stall, {}}; + } + Stream* stream = nullptr; + std::size_t payload_size = 0; + uint8_t base_flag = 0; + bool running = false; + bool infrared = false; + if (endpoint == 0x82) { + stream = &depth_; + payload_size = kDepthPayload; + base_flag = 0x70; // depth stream base flag, cameras.c:849 + running = registers_.at(0x06) == 0x02; + } else if (endpoint == 0x81) { + stream = &video_; + payload_size = kVideoPayload; + base_flag = 0x80; // video stream base flag, cameras.c:913 + infrared = registers_.at(0x05) == 0x03; + running = registers_.at(0x05) == 0x01 || registers_.at(0x05) == 0x03; + } else { + return {TransferStatus::invalid_frame, {}}; + } + + if (!running) { + *stream = {}; + return {TransferStatus::idle, {}}; + } + if (stream->bytes.empty()) { + const auto frame = source_(); + if (!frame) { + return {TransferStatus::idle, {}}; + } + stream->bytes = endpoint == 0x82 ? build_depth(*frame) + : build_video(*frame, infrared); + stream->offset = 0; + stream->timestamp += 1; + stream->frame_number = frame->metadata.frame_number; + } + + const std::size_t remaining = stream->bytes.size() - stream->offset; + const std::size_t payload = std::min(payload_size, remaining); + const bool end_of_frame = payload == remaining; + const uint8_t flag = + static_cast(base_flag | (end_of_frame ? 5 : (stream->offset == 0 ? 1 : 2))); + + Bytes packet(12 + payload); + packet[0] = 0x52; // 'R' + packet[1] = 0x42; // 'B', the iso packet magic checked at cameras.c:102 + packet[3] = flag; + packet[5] = stream->sequence; + wire::put32(packet, 8, stream->timestamp); + std::copy_n(stream->bytes.begin() + static_cast(stream->offset), + payload, packet.begin() + 12); + + stream->offset += payload; + ++stream->sequence; + if (end_of_frame) { + stream->bytes.clear(); + stream->offset = 0; + } + return {TransferStatus::completed, std::move(packet)}; +} + +} // namespace nui::protocol diff --git a/core/protocol/wire.h b/core/protocol/wire.h new file mode 100644 index 0000000..1dc48dc --- /dev/null +++ b/core/protocol/wire.h @@ -0,0 +1,34 @@ +#ifndef NUI_CORE_PROTOCOL_WIRE_H +#define NUI_CORE_PROTOCOL_WIRE_H + +#include "protocol/protocol.h" + +namespace nui::protocol::wire { + +inline uint16_t u16(const Bytes& bytes, std::size_t offset) { + return static_cast(bytes[offset] | (bytes[offset + 1] << 8)); +} +inline void put16(Bytes& bytes, std::size_t offset, uint16_t value) { + bytes[offset] = static_cast(value); + bytes[offset + 1] = static_cast(value >> 8); +} +inline void put32(Bytes& bytes, std::size_t offset, uint32_t value) { + for (unsigned i = 0; i < 4; ++i) { + bytes[offset + i] = static_cast(value >> (i * 8)); + } +} + +// Synthetic 1414 calibration, shared by EEPROM replies and metric->raw depth. +// Units and conversion: libfreenect 09a1f098 src/registration.c:315-325. +constexpr float kEmitterDistance = 7.5f; +constexpr float kCameraDistance = 2.4f; +constexpr float kReferenceDistance = 120.0f; +constexpr float kPixelSize = 0.1052f; +constexpr uint16_t kConstantShift = 200; + +std::optional descriptor(UsbFunction function, uint16_t type_index); +bool endpoint_exists(UsbFunction function, uint16_t endpoint); +uint8_t interface_count(UsbFunction function); + +} // namespace nui::protocol::wire +#endif // NUI_CORE_PROTOCOL_WIRE_H diff --git a/tests/test_protocol.cpp b/tests/test_protocol.cpp new file mode 100644 index 0000000..84e0cf9 --- /dev/null +++ b/tests/test_protocol.cpp @@ -0,0 +1,322 @@ +#include + +#include +#include +#include +#include + +#include "protocol/protocol.h" +#include "protocol/wire.h" +#include "synth/synth.h" + +namespace { + +using nui::protocol::Bytes; +using nui::protocol::CameraCommand; +using nui::protocol::CameraMagic; +using nui::protocol::ControlSetup; +using nui::protocol::KinectV1Device; +using nui::protocol::SynthFrame; +using nui::protocol::TransferStatus; +using nui::protocol::UsbFunction; + +constexpr uint32_t kDepthWidth = 640; +constexpr uint32_t kDepthHeight = 480; + +Bytes le16_words(std::initializer_list words) { + Bytes bytes; + for (const uint16_t word : words) { + bytes.push_back(static_cast(word)); + bytes.push_back(static_cast(word >> 8)); + } + return bytes; +} + +// Replica of host-side raw->mm (libfreenect registration.c:320-325) under the +// virtual calibration, to prove the reassembled disparity decodes to the depth +// the synth frame carried. +// Test-local copy of streams.cpp's millimeters_to_raw, so the reassembled +// disparity can be checked bit-exact against the depth the synth frame carried. +uint16_t expected_raw(uint16_t millimeters) { + if (millimeters == 0) { + return 2047; + } + const double scaled = millimeters / 10.0; + const double metric = + (scaled - nui::protocol::wire::kReferenceDistance) * + nui::protocol::wire::kEmitterDistance / scaled; + const double fixed_ref_x = metric / nui::protocol::wire::kPixelSize; + const double raw = + 4.0 * fixed_ref_x + 1.5 + 4.0 * nui::protocol::wire::kConstantShift; + const long rounded = std::lround(raw); + if (rounded < 0 || rounded >= 2047) { + return 2047; + } + return static_cast(rounded); +} + +double host_millimeters(uint16_t raw) { + const double fixed_ref_x = + ((raw - 4.0 * nui::protocol::wire::kConstantShift) / 4.0) - 0.375; + const double metric = fixed_ref_x * nui::protocol::wire::kPixelSize; + return 10.0 * ((metric * nui::protocol::wire::kReferenceDistance / + (nui::protocol::wire::kEmitterDistance - metric)) + + nui::protocol::wire::kReferenceDistance); +} + +std::vector unpack_msb_first(const Bytes& data, unsigned width, + std::size_t count) { + const uint32_t mask = (1u << width) - 1u; + uint32_t buffer = 0; + unsigned bits = 0; + std::size_t cursor = 0; + std::vector out; + out.reserve(count); + while (out.size() < count) { + while (bits < width) { + buffer = (buffer << 8) | data[cursor++]; + bits += 8; + } + bits -= width; + out.push_back(static_cast((buffer >> bits) & mask)); + } + return out; +} + +Bytes run_command(KinectV1Device& device, uint16_t command, const Bytes& payload) { + const auto out = nui::protocol::encode_command( + {CameraMagic::command, command, 0x1234, payload}); + EXPECT_TRUE(out.has_value()); + const ControlSetup write{0x40, 0, 0, 0, static_cast(out->size())}; + const auto wrote = device.answer_control_transfer(UsbFunction::camera, write, *out); + EXPECT_EQ(wrote.status, TransferStatus::completed); + const ControlSetup read{0xc0, 0, 0, 0, 512}; + const auto reply = device.answer_control_transfer(UsbFunction::camera, read, {}); + EXPECT_EQ(reply.status, TransferStatus::completed); + return reply.data; +} + +Bytes command_payload(KinectV1Device& device, uint16_t command, const Bytes& in) { + const auto decoded = nui::protocol::decode_command(run_command(device, command, in)); + EXPECT_TRUE(decoded.has_value()); + EXPECT_EQ(decoded->magic, CameraMagic::reply); + EXPECT_EQ(decoded->command, command); + EXPECT_EQ(decoded->sequence, 0x1234); + return decoded ? decoded->payload : Bytes{}; +} + +std::shared_ptr make_depth_frame() { + auto frame = std::make_shared(); + frame->metadata.frame_number = 7; + frame->depth.size = {kDepthWidth, kDepthHeight}; + frame->depth.pitch = kDepthWidth * 2; + frame->depth.pixels.resize(static_cast(kDepthWidth) * kDepthHeight); + for (uint32_t y = 0; y < kDepthHeight; ++y) { + const uint16_t millimeters = static_cast(900 + (y % 600) * 5); + for (uint32_t x = 0; x < kDepthWidth; ++x) { + frame->depth.pixels[static_cast(y) * kDepthWidth + x] = + nui::synth::pack_depth(millimeters, 1); + } + } + return frame; +} + +void start_depth_stream(KinectV1Device& device) { + for (const auto& pair : std::vector>{ + {0x105, 0}, {0x06, 0}, {0x12, 3}, {0x13, 1}, {0x14, 30}, {0x06, 2}, {0x17, 0}}) { + const auto reply = command_payload( + device, 0x03, le16_words({pair.first, pair.second})); + EXPECT_EQ(reply.size(), 2u); + } +} + +} // namespace + +TEST(protocol, CommandEnvelopeRoundTripsWithMagicSequenceAndLength) { + const Bytes payload = le16_words({0x0006, 0x0000}); + const auto encoded = nui::protocol::encode_command( + {CameraMagic::command, 0x02, 0x00ab, payload}); + ASSERT_TRUE(encoded.has_value()); + + const Bytes expected{0x47, 0x4d, 0x02, 0x00, 0x02, 0x00, + 0xab, 0x00, 0x06, 0x00, 0x00, 0x00}; + EXPECT_EQ(*encoded, expected); + + const auto decoded = nui::protocol::decode_command(*encoded); + ASSERT_TRUE(decoded.has_value()); + EXPECT_EQ(decoded->magic, CameraMagic::command); + EXPECT_EQ(decoded->command, 0x02); + EXPECT_EQ(decoded->sequence, 0x00ab); + EXPECT_EQ(decoded->payload, payload); +} + +TEST(protocol, DecodeRejectsTruncatedAndMislengthedEnvelopes) { + EXPECT_FALSE(nui::protocol::decode_command(Bytes{0x47, 0x4d, 0x01}).has_value()); + Bytes wrong_length{0x47, 0x4d, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00}; + EXPECT_FALSE(nui::protocol::decode_command(wrong_length).has_value()); +} + +TEST(protocol, KnownRegisterReadReturnsTheValueThatWasWritten) { + KinectV1Device device([] { return nullptr; }); + + const auto write_reply = command_payload(device, 0x03, le16_words({0x0012, 0x0003})); + ASSERT_EQ(write_reply.size(), 2u); + + const auto read_reply = command_payload(device, 0x02, le16_words({0x0012})); + ASSERT_EQ(read_reply.size(), 4u); + EXPECT_EQ(static_cast(read_reply[2] | (read_reply[3] << 8)), 0x0003); +} + +TEST(protocol, FixedParamQueriesReturnCorrectlySizedCalibrationBlocks) { + KinectV1Device device([] { return nullptr; }); + + const auto zero_plane = command_payload(device, 0x04, Bytes(10, 0)); + EXPECT_EQ(zero_plane.size(), 322u); + + const auto reg_info = + command_payload(device, 0x16, le16_words({0x40, 0, 1, 30, 0})); + EXPECT_EQ(reg_info.size(), 118u); + + const auto pad_info = + command_payload(device, 0x16, le16_words({0x41, 0, 1, 30, 0})); + EXPECT_EQ(pad_info.size(), 8u); + + const auto const_shift = + command_payload(device, 0x16, le16_words({0x00, 0, 1, 30, 0})); + ASSERT_EQ(const_shift.size(), 4u); + EXPECT_EQ(static_cast(const_shift[2] | (const_shift[3] << 8)), + nui::protocol::wire::kConstantShift); +} + +TEST(protocol, DepthFrameChunksIntoIsoPacketsThatReassembleToTheInputDepth) { + KinectV1Device device(make_depth_frame); + start_depth_stream(device); + + const std::size_t frame_bytes = + static_cast(kDepthWidth) * kDepthHeight * 11 / 8; + const std::size_t payload_size = 1748; + const std::size_t expected_packets = + (frame_bytes + payload_size - 1) / payload_size; + + Bytes reassembled; + std::size_t packet_index = 0; + uint8_t expected_sequence = 0; + while (true) { + const auto packet = device.next_packet(UsbFunction::camera, 0x82); + ASSERT_EQ(packet.status, TransferStatus::completed); + ASSERT_GE(packet.data.size(), 12u); + EXPECT_EQ(packet.data[0], 0x52); + EXPECT_EQ(packet.data[1], 0x42); + EXPECT_EQ(packet.data[5], expected_sequence++); + + const bool is_last = packet_index == expected_packets - 1; + const uint8_t expected_flag = + is_last ? 0x75 : (packet_index == 0 ? 0x71 : 0x72); + EXPECT_EQ(packet.data[3], expected_flag); + + const std::size_t data_len = packet.data.size() - 12; + EXPECT_EQ(data_len, is_last ? frame_bytes % payload_size : payload_size); + reassembled.insert(reassembled.end(), packet.data.begin() + 12, packet.data.end()); + if (is_last) { + break; + } + ++packet_index; + } + + ASSERT_EQ(packet_index + 1, expected_packets); + ASSERT_EQ(reassembled.size(), frame_bytes); + + const auto raw = unpack_msb_first( + reassembled, 11, static_cast(kDepthWidth) * kDepthHeight); + for (uint32_t y = 0; y < kDepthHeight; ++y) { + const uint16_t expected_mm = static_cast(900 + (y % 600) * 5); + const uint16_t sample = raw[static_cast(y) * kDepthWidth]; + EXPECT_EQ(sample, expected_raw(expected_mm)); + EXPECT_LT(sample, 2047); + EXPECT_NEAR(host_millimeters(sample), expected_mm, 40.0); + } +} + +TEST(protocol, NextDepthPacketStartsOnlyAfterTheStartRegisterIsWritten) { + KinectV1Device device(make_depth_frame); + EXPECT_EQ(device.next_packet(UsbFunction::camera, 0x82).status, TransferStatus::idle); + start_depth_stream(device); + EXPECT_EQ(device.next_packet(UsbFunction::camera, 0x82).status, + TransferStatus::completed); +} + +TEST(protocol, UnsupportedModeRegisterAndEndpointAndCommandAreRejected) { + KinectV1Device device([] { return nullptr; }); + const auto out_status = [&](uint16_t command, const Bytes& payload) { + const auto out = nui::protocol::encode_command( + {CameraMagic::command, command, 1, payload}); + return device + .answer_control_transfer( + UsbFunction::camera, {0x40, 0, 0, 0, static_cast(out->size())}, *out) + .status; + }; + + EXPECT_EQ(out_status(0x03, le16_words({0x0012, 0x0005})), TransferStatus::stall); + EXPECT_EQ(out_status(0x02, le16_words({0x0999})), TransferStatus::stall); + EXPECT_EQ(out_status(0x77, Bytes{}), TransferStatus::stall); + + EXPECT_EQ(device.next_packet(UsbFunction::camera, 0x83).status, + TransferStatus::invalid_frame); + EXPECT_EQ(device.next_packet(UsbFunction::audio, 0x81).status, + TransferStatus::stall); +} + +TEST(protocol, ColorStreamEmitsGrbgBayerThatReassembles) { + auto frame = std::make_shared(); + frame->color.size = {4, 4}; + frame->color.pitch = 16; + frame->color.pixels.assign(4 * 4 * 4, 0); + for (std::size_t pixel = 0; pixel < 16; ++pixel) { + frame->color.pixels[pixel * 4 + 0] = 10; // blue + frame->color.pixels[pixel * 4 + 1] = 20; // green + frame->color.pixels[pixel * 4 + 2] = 30; // red + frame->color.pixels[pixel * 4 + 3] = 255; + } + KinectV1Device device([frame] { return frame; }); + + for (const auto& pair : std::vector>{ + {0x0c, 0}, {0x0d, 1}, {0x0e, 30}, {0x05, 1}, {0x47, 0}}) { + device.answer_control_transfer( + UsbFunction::camera, {0x40, 0, 0, 0, 12}, + *nui::protocol::encode_command( + {CameraMagic::command, 0x03, 0, le16_words({pair.first, pair.second})})); + device.answer_control_transfer(UsbFunction::camera, {0xc0, 0, 0, 0, 512}, {}); + } + + Bytes reassembled; + while (true) { + const auto packet = device.next_packet(UsbFunction::camera, 0x81); + ASSERT_EQ(packet.status, TransferStatus::completed); + EXPECT_EQ(packet.data[1], 0x42); + reassembled.insert(reassembled.end(), packet.data.begin() + 12, packet.data.end()); + if (packet.data[3] == 0x85) { + break; + } + } + + ASSERT_EQ(reassembled.size(), static_cast(640) * 480); + EXPECT_EQ(reassembled[0], 20); // row0 col0: green in GRBG + EXPECT_EQ(reassembled[1], 30); // row0 col1: red + EXPECT_EQ(reassembled[640], 10); // row1 col0: blue +} + +TEST(protocol, DescriptorsAdvertiseTheKinectIdentityAndSiblingTopology) { + const auto camera = nui::protocol::wire::descriptor(UsbFunction::camera, 0x0100); + ASSERT_TRUE(camera.has_value()); + EXPECT_EQ(static_cast((*camera)[8] | ((*camera)[9] << 8)), 0x045e); + EXPECT_EQ(static_cast((*camera)[10] | ((*camera)[11] << 8)), 0x02ae); + EXPECT_EQ(static_cast((*camera)[12] | ((*camera)[13] << 8)), 0x010b); + + EXPECT_EQ(nui::protocol::wire::interface_count(UsbFunction::audio), 2); + EXPECT_TRUE(nui::protocol::wire::endpoint_exists(UsbFunction::camera, 0x82)); + EXPECT_FALSE(nui::protocol::wire::endpoint_exists(UsbFunction::motor, 0x82)); + + const auto config = nui::protocol::wire::descriptor(UsbFunction::camera, 0x0200); + ASSERT_TRUE(config.has_value()); + EXPECT_EQ((*config)[1], 0x02); +}