Skip to content

Windows 11 support and Kinect for Windows SDK feature parity (supersedes #702) - #703

Open
kebasaa wants to merge 97 commits into
OpenKinect:masterfrom
kebasaa:sdk-parity
Open

kebasaa wants to merge 97 commits into
OpenKinect:masterfrom
kebasaa:sdk-parity

Conversation

@kebasaa

@kebasaa kebasaa commented Nov 24, 2026

Copy link
Copy Markdown

Summary

This PR replaces #702. It contains #702's ten commits unchanged and builds on them, so the two shouldn't be merged separately.

The Kinect for Windows SDK no longer works on Windows 11 with Memory integrity on: its camera driver (kinectcamera.sys) is blocked. #702 made libfreenect the replacement on Windows: every function binds to the in-box winusb.sys, and everything else runs in user mode.

This PR goes further. It brings libfreenect close to what the Kinect for Windows SDK offered, on Windows, Linux and macOS:

  • the device layer: firmware, motor, LED, IR emitter, model detection, hotplug;
  • the cameras: frame checks, modes, Microsoft's depth conversion, near mode, colour settings;
  • coordinate mapping;
  • the microphone array: Microsoft's audio firmware, a beamformer and source localisation;
  • an optional skeleton, hand and gesture tracker (libfreenect_nui, -DBUILD_NUI=ON, off by default).

Microsoft's files are never part of the repository or of a build. Where a feature needs them (the audio firmware UAC.BIN, the SDK's beamformer weights, the skeleton tracker's models), the installer downloads Microsoft's official Kinect Runtime 1.8 installer on the user's machine. It checks the signature and hashes and extracts only what it needs, after telling the user what is downloaded, from where, and that Microsoft's licence terms apply.

Everything was tested on Windows 11 with Memory integrity on and an Xbox 360 Kinect (model 1414). CI builds and runs the unit tests on Windows, Linux and macOS. Details are under "Testing".

What's included

The commits are in topic order, and every commit builds. Commit messages with a § number refer to the section of the reverse-engineering notes the change was implemented from (specifications only, no decompiled code).

1. Windows 11 foundation: #702's commits, unchanged (824a2f1 … f3d0a8f). The WinUSB driver installer, isochronous streaming over WinUSB, building without pthreads-win32 (#655, #647, #561), send_cmd resynchronisation, removal of the libusb0 INFs and libusbemu, and CI with a vcpkg manifest (#622, #660). See #702 for the details.

2. Device layer

  • Audio firmware: freenect-driver-install --firmware and fwfetcher.py --uac fetch Microsoft's UAC.BIN, and the loader handles both it and audios.bin. With UAC.BIN the microphone array becomes a standard USB Audio device, handled by the operating system's own driver on all three platforms.
  • Firmware loader: checks every bootloader reply, clears stalls, and reloads the firmware when the audio controller reboots.
  • Model detection: from the internal hub (1414, 1473, Kinect for Windows), instead of bcdDevice. Also the device serial.
  • Motor and accelerometer: correct state on all models, and the SDK's tilt limits as an opt-out policy (LIBFREENECT_TILT_RATE_LIMIT=0).
  • LED: fixes for the Kinect for Windows LIBUSB_ERROR_IO (Failed to set the LED of K4W or 1473 device: LIBUSB_ERROR_IO #580, LIBUSB_ERROR_IO audio device K4W (1517) #557; untested, no K4W available). LIBFREENECT_LED=off keeps the LED off.
  • IR emitter: freenect_set_ir_emitter(). The projector switches off when depth stops (IR projector does not turn off on exit.  #385).
  • Hotplug: Kinects arriving and leaving are reported, and an unplug no longer crashes.
  • Linux: udev rules for access without root, and firmware upload at plug-in through a systemd unit.
  • macOS: firmware upload at plug-in through a launchd agent.

3. Cameras

  • Frame checks: only complete frames are delivered, and the first two video frames are skipped.
  • Garbled streams: a stream that sends nothing but headerless packets is restarted.
  • Modes: depth at 320×240 and 80×60, and 1280×960 colour on the 1473 and Kinect for Windows. The alternate setting is chosen from the descriptor.
  • Depth in mm: see "Behaviour changes".
  • Near mode and IR brightness no longer overwrite each other.
  • Kinect for Windows colour settings: exposure, gain, white balance and the rest. They return -ENOTSUP on other models.
  • Frame timing: optional alignment of the depth and colour frame phases.
  • Diagnostics: streams that deliver nothing say why, with a hint for virtual machines.

4. Registration and coordinate mapping

  • The calibration is read once at open, with allocation and bounds checks.
  • New: libfreenect_coordinate_mapper.h, the SDK's mapping between depth, colour and camera space, at every resolution. It also exports and imports the calibration, so fakenect recordings stay mappable.

5. Audio

  • Microphone array: freenect_get_mic_geometry().
  • freenect_audio_dsp (on by default, no Microsoft data needed): a beamformer and source localisation for the four microphones. The default beam weights are designed from the microphone geometry. The SDK's own weights can be loaded at run time if the user fetched them. Optional echo cancellation and noise suppression come from SpeexDSP.
  • Linux: a PipeWire filter chain publishes one beamformed microphone.
  • macOS: an optional Core Audio plug-in does the same.
  • Example: freenect-micbeam.

6. Linux and macOS

  • The OpenGL viewers moved from GLUT to GLFW: native Wayland, and a clean exit on close and Ctrl+C.
  • freenect-v4l2 (optional) exposes the Kinect as V4L2 cameras through v4l2loopback.
  • The build is clean with -Wall -Wextra; CI builds with -Werror.

7. Python: wrappers/python is now a package that uv pip install ./wrappers/python (or pip) builds. It links libfreenect statically and covers the new APIs (mapping, audio DSP, tracker).

8. libfreenect_nui: the optional skeleton tracker, built only with -DBUILD_NUI=ON, as its own library. The core library and its ABI don't depend on it.

  • Tracking: 20 joints with tracked/inferred state, player index, floor plane and seated mode.
  • Hands: hands and fingers, two-hand gestures, a pointer, press, grip and swipes.
  • Motor framing: it can tilt the Kinect to keep a user in view.
  • Models: it uses Microsoft's body-part forest and head detector, fetched as described above. Each is checked by size and SHA-256 and never shipped.
  • Tools: freenect-nuitest runs it live and can record and replay depth.

9. CI: Windows x64 and ARM64, Ubuntu 24.04 (x86_64, arm64), Ubuntu rolling and 26.04, Debian 13, Raspberry Pi OS 13 (arm64, and armhf under QEMU), and macOS (Apple Silicon, Intel, universal). It runs the unit tests, the Python package tests and integration checks that need no Kinect, such as the PipeWire microphone and the launchd agent.

Behaviour changes

  • FREENECT_DEPTH_MM uses Microsoft's depth formula (the SDK's lookup table built from the device's own calibration) instead of libfreenect's old approximation. Values change slightly.
  • Depth range: FREENECT_DEPTH_MM is limited to 800–4000 mm by default, as in the SDK. freenect_set_depth_range() selects near mode (400–3000 mm) or no limit (FREENECT_DEPTH_RANGE_FULL).
  • Tilt limits: the SDK's limits apply by default: ±27°, at least 1 s between moves, and at most 15 moves in 20 s. LIBFREENECT_TILT_RATE_LIMIT=0 switches them off.
  • Frames: only complete frames are delivered (LIBFREENECT_INCOMPLETE_FRAMES=1 restores the old behaviour), and the first two video frames after a start are skipped.
  • Windows audio streaming: libfreenect's own audio streaming is still refused on Windows, as in Windows 11 support via the in-box WinUSB driver (driver installer, robust streaming, CI) #702. With UAC.BIN loaded, Windows handles the microphones itself.

Testing

Hardware: Windows 11 with Memory integrity on, an Xbox 360 Kinect (1414) with its power adapter, libusb 1.0.30 and MSVC 2026. A guided test script covers each area, and the results of every round are kept.

Area Result
Driver installer, UAC.BIN fetch and load WinUSB on camera, motor and audio. With UAC.BIN the Kinect appears in Windows Sound settings as a 4-channel microphone; the camera is unaffected
Cameras Depth and colour at 30 fps, IR, hi-res colour, depth ranges, frame-phase alignment
Motor, LED, emitter Tilt and accelerometer, LED states, projector off when depth stops and on close
Coordinate mapping Depth↔colour overlay lines up, with the calibration read from the device and from a saved file
Microphone array Recording through Windows; beams and source direction with the default and with the SDK's weights
Skeleton tracker (BUILD_NUI) Whole body, two hands, pointing and gestures, seated. The last round has a skeleton in 71–98 % of frames per test, with motor framing on
Hotplug, Ctrl+C, window close Recovered or exited cleanly every time

Unit tests: 23 on Linux and 21 on Windows, all passing. They cover depth and IR unpacking, frame reassembly, the depth lookup table against Microsoft's values, the coordinate mapper, colour settings, hotplug, the audio DSP, the tracker on synthetic scenes, and more.

Known limitations

Notes for reviewers

  • Size: this is a large PR. The commits are self-contained and in topic order, so reviewing commit by commit is easiest. If you'd prefer, I can split it into a series of PRs along the numbered areas above.
  • Optional parts: the tracker (BUILD_NUI), freenect-v4l2, the Core Audio plug-in and SpeexDSP are all optional, and the tracker is off by default.
  • Microsoft's data: nothing of Microsoft's is in the repository or in any build. It's fetched on the user's machine from Microsoft's official download, verified, and used only there.
  • Certificate trust: as in Windows 11 support via the in-box WinUSB driver (driver installer, robust streaming, CI) #702, the Windows installer trusts a one-off local certificate whose private key is destroyed after signing. --uninstall removes it.

c_sync, the C++ wrapper and the threaded examples needed
pthreads-win32 on Windows, and configuring failed without it
(OpenKinect#655, OpenKinect#647, OpenKinect#561).

Add platform/windows/pthread/pthread.h, a header-only subset of POSIX
threads built on native SRW locks, condition variables and
_beginthreadex. It covers exactly the calls the tree uses: create,
join, mutex init/lock/trylock/unlock/destroy, and cond
init/wait/signal/broadcast/destroy, including the static initialisers.
It needs no import library.

FindThreads.cmake still prefers a real pthreads-win32 when one is
installed. Otherwise it points THREADS_PTHREADS_INCLUDE_DIR at the
subset and leaves CMAKE_THREAD_LIBS_INIT empty, so no CMakeLists or
source file has to change.
- With MSVC, the static freenectstatic and freenect_sync_static
  libraries were written to freenect.lib and freenect_sync.lib, which
  are also the import libraries of freenect.dll and freenect_sync.dll.
  Whichever linked last won, and parallel builds failed with LNK1104.
  On MSVC the static libraries are now freenect_static.lib and
  freenect_sync_static.lib; other platforms keep their names.
- Findlibusb-1.0.cmake also accepts the library name libusb-1.0, which
  vcpkg and the official Windows binaries ship (libusb-1.0.lib). Before,
  CMake could not find libusb on Windows without -DLIBUSB_1_LIBRARY
  (OpenKinect#647).
- regtest opened its image files with "w", which is text mode on
  Windows, so every 0x0A byte became 0x0D 0x0A and all four images were
  corrupt. It now uses "wb".
With WinUSB, Microsoft's in-box driver, libfreenect streams from user
mode on Windows 11 with Memory integrity enabled, where the Kinect for
Windows SDK's kernel driver is blocked. This needs libusb 1.0.26 or
newer: WinUSB isochronous support arrived in 1.0.23, and 1.0.24 and
1.0.25 had a Windows isochronous regression.

- fnusb_start_iso() returned 0 even when no transfer could be
  submitted, as happens with a libusb0 driver, so streams stayed
  silently black. It now frees everything and returns the libusb error
  when nothing is in flight, warns when only some transfers start, and
  explains LIBUSB_ERROR_NOT_SUPPORTED (wrong driver, or Windows older
  than 8.1) and LIBUSB_ERROR_ACCESS.
- iso_callback() passed every packet to the stream parser without
  checking the packet's own status. Packets that failed or were never
  filled were parsed as data, causing "Invalid magic" errors and
  resyncs that also discarded good frames. They are now passed on as
  empty, so the parser counts them as lost through the sequence
  numbers. This applies to all platforms.
- fnusb_stop_iso() skips transfers that were never allocated, and waits
  at most 3 s (in 100 ms steps) for cancellations instead of forever.
  Transfers still outstanding after that are leaked rather than freed
  while libusb may still own them.
- Windows keeps 16 transfers of 32 packets in flight (64 ms per stream,
  up from 32 ms). PKTS_PER_XFER % 8 == 0, which WinUSB requires, and
  PKTS_PER_XFER * NUM_XFERS <= 1000 are now compile-time checks.
- freenect_init() logs the libusb version and warns on Windows below
  1.0.26.
- LIBFREENECT_USBDK=1 opts in to libusb's UsbDk backend on Windows.

Hardware test on Windows 11, Xbox 360 Kinect (1414), libusb 1.0.30:
camtest streams depth and video; with the failed-packet change, video
went from 7.4% to 0% of frames missing.
In a hardware test on Windows 11 (WinUSB, Xbox 1414 with audios.bin),
the audio isochronous streams reported LIBUSB_TRANSFER_STALL. The
outstanding transfers were never completed by the kernel, so the
process could not be terminated, and Windows hung during restart
because shutdown waits for that I/O. The machine had to be hard-reset.

Until the audio path is understood on Windows, freenect_start_audio()
returns -1 there with an explanation, unless
LIBFREENECT_WINDOWS_AUDIO_UNSAFE=1 is set. The check runs before
anything is allocated or submitted. Camera, motor, LED, accelerometer
and the firmware upload are unaffected, and stopped cleanly in the same
tests.

Also: if the audio OUT stream fails to start, stop the IN stream that
was already started. micview checks the result of
freenect_start_audio() and exits instead of running without audio.
In a hardware test on Windows 11 (Xbox 1414), the camera failed to
initialise with "send_cmd: Bad cmd 03 != 16" and kept failing on every
run. send_cmd() took the first reply the camera returned and failed
hard if its cmd or tag did not match; the camera's actual reply was
left unread and returned for the next command, so from then on every
command read the previous command's reply.

- Before sending, discard replies that are already waiting (up to 8),
  with a warning.
- After sending, skip replies whose cmd or tag does not match and keep
  waiting for the matching one (at most 8, then fail).
- Give up after 2 s of wall-clock time (GetTickCount64 or
  CLOCK_MONOTONIC) instead of polling forever. Counting polls does not
  work: on Windows each 1 ms sleep lasts about 15 ms.
- A failing IN transfer returns its own error code instead of the OUT
  transfer's result.

Tested against a simulated camera channel (the real flags.c with
fnusb_control stubbed): a stale cmd 0003 reply before cmd 0016, a
channel that stays one reply out of step, a late unrelated reply, and a
camera that never answers, which times out after 2000 ms. On the
Kinect, camtest started reliably in repeated runs afterwards.
On Windows 11 with Memory integrity enabled, the Kinect for Windows SDK
camera driver is blocked, and Zadig is a manual, per-device step.
freenect-driver-install binds every Kinect v1 function libfreenect
drives to Microsoft's in-box WinUSB driver in one command. It uses only
documented Windows APIs and adds no third-party dependency.

--install (Administrator):
- Writes %ProgramData%\libfreenect\driver\libfreenect-kinect.inf, which
  references only the in-box winusb.inf (Include/Needs WINUSB.NT), so no
  binaries or co-installers are shipped.
- Builds a catalog for it with the CryptCAT API. The member is hashed
  with SHA-1, because the driver store looks package files up by their
  SHA-1 hash and rejects a SHA-256-only catalog with
  ERROR_FILE_HASH_NOT_IN_CATALOG. The catalog signature is SHA-256.
- Creates a self-signed code-signing certificate, signs the catalog with
  it, and deletes the private key immediately, so the certificate that
  is trusted can never sign anything else.
- Adds the certificate to the local machine Root and TrustedPublisher
  stores, stages the package with SetupCopyOEMInf, and installs it on
  every present Kinect function (UpdateDriverForPlugAndPlayDevices,
  non-interactive). Functions that appear later, such as the camera and
  audio of the Xbox 1414 once the motor has a driver, pick it up from
  the driver store automatically.

--uninstall removes the Kinect device nodes, then every package
(recognised by its catalog name) and certificate the tool added, and
rescans, so no device is left bound to a deleted package. --list shows
the Kinect functions, their drivers and every device on the Kinect's
hub, with problem codes, and needs no elevation. --package-only DIR
builds and signs a package without changing the system.

Bound: camera 02AE/02BF, motor 02B0/02AF, audio controller 02AD/02BE,
and only interfaces 0 and 1 of 02BB/02C3, so the microphone-array
interfaces keep usbaudio.sys. CMake option BUILD_DRIVER_INSTALLER, on
by default on Windows. The README's Windows section now describes the
tool, libusb >= 1.0.26, and WinUSB instead of libusbK via Zadig.

Hardware test on Windows 11 with Memory integrity on, Xbox 1414:
--install, --list, --uninstall and reinstalling all work, and the
camera, motor and audio functions end up on WinUSB.
upload_firmware() searched only POSIX locations. On Windows it now also
searches %LOCALAPPDATA%\libfreenect, the directory of the executable,
and %ProgramData%\libfreenect; the existing locations keep their order.
The search is a plain list of directories, which also fixes two leaks
(the firmware buffer was never freed, and the FILE was not closed for
an empty file). A missing file returns -ENOENT and says where to put
it.

freenect-fwloader uploads the firmware to every connected Kinect whose
audio controller is still in its bootloader, using only the public API
(opening a device with FREENECT_DEVICE_AUDIO uploads and waits for
re-enumeration). --firmware FILE uses a specific image.

Hardware test on Windows 11, Xbox 1414: the firmware uploads and
launches; a second run finds it already running.
tiltdemo looped forever with no handler, so Ctrl+C killed it in the
middle of USB transfers. wavrecord caught only SIGINT and never stopped
audio or closed the device. On Windows, signal() never sees the console
window being closed.

examples/console_exit.h gives the console examples one shutdown path:
- POSIX: SIGINT, SIGTERM, SIGHUP and SIGQUIT request exit.
- Windows: SetConsoleCtrlHandler for Ctrl+C, Ctrl+Break, window close,
  logoff and shutdown; for the last three, the handler holds the
  process for up to 4 s until main() has stopped the streams and closed
  the device.
- fn_sleep_ms() sleeps in 100 ms steps and returns early on exit.

camtest and wavrecord poll with freenect_process_events_timeout()
(100 ms). wavrecord stops audio and closes the device before
freenect_shutdown(). tiltdemo calls freenect_sync_stop() on exit.
camtest accepts an optional run time in seconds ("freenect-camtest 20")
and then prints the depth and video frame rates.

Hardware test on Windows 11, Xbox 1414: camtest and tiltdemo stop on
Ctrl+C and when their window is closed.
platform/windows/inf ships libusb0 (libusb-win32) driver packages from
2010. libusb0 cannot do the isochronous transfers that video and depth
need with current libusb, and its catalogs are not accepted on current
Windows. freenect-driver-install replaces them.

platform/windows/libusb10emu is a libusb-1.0 emulation on top of
libusb-win32 that no CMakeLists.txt refers to.
platform/windows/README.TXT described it and is replaced by
platform/windows/README.md.
The workflow builds the library, the C sync and C++ wrappers and all
examples, including the OpenGL viewers, on:
- Windows x64 and ARM64 with MSVC, with libusb and freeglut from vcpkg;
- Ubuntu 24.04 on x86_64 and arm64;
- macOS on Apple Silicon.

Smoke tests that need no Kinect: freenect-fwloader must report that no
Kinect is present. On Windows x64, freenect-driver-install --list must
work, and --package-only must produce a catalog signed by the package
certificate with its key destroyed. The Windows jobs upload their
binaries as artifacts (OpenKinect#622).

vcpkg.json declares libusb, and freeglut for the examples behind the
"examples" feature, so a Windows build needs only the vcpkg toolchain
file (OpenKinect#660).
The Kinect's audio controller needs firmware after every power-up.
Microsoft's own image (UAC.BIN, installed as UACFirmware.bin by the
Kinect SDK) makes the four microphones a standard USB Audio device
that Windows' in-box usbaudio.sys handles. libfreenect cannot ship it,
so the installer now fetches it on the user's machine:

- Download KinectRuntime-v1.8-Setup.exe (116,273,144 bytes) from
  download.microsoft.com over HTTPS with WinHTTP.
- Require a valid Authenticode signature by Microsoft Corporation
  (WinVerifyTrust). A differing installer hash only produces a note,
  because Microsoft re-signs its downloads; the firmware itself is what
  gets checked.
- Extract UACFirmware without running the installer: the Burn
  bundle's payload cabinet (the second MSCF cabinet in the file),
  expanded with the Cabinet API (FDI), then the x64 drivers MSI "a0",
  whose embedded cabinet is read through the Windows Installer API
  (_Streams) and expanded again.
- Verify the firmware: 145,920 bytes, SHA-256
  4467ae36ad378c58477432729d74eed0f9d45d35213f4430a781d90f64cea3f9,
  magic 0xCA77F00D, base 0x00080000, entry 0x00080030.
- Install it as %ProgramData%\libfreenect\UACFirmware.bin, and delete
  the downloaded installer and all temporary files.

--install fetches it after installing the driver, unless --no-firmware
is given, and says what it downloads and that Microsoft's licence terms
apply. A failed download does not fail the driver install.
--fetch-firmware [--from INSTALLER] [DIR] fetches it on its own, from
an installer that is already on disk if --from is given. --uninstall
also removes the firmware.

libfreenect does not load UACFirmware.bin yet; that comes with the
loader changes.

Tested on Windows 11 without a Kinect: fetching from the downloaded
installer and from a fresh download from Microsoft (2 s) both produce
the verified firmware and leave no temporary files. A copy of the
installer with one byte changed is rejected (0x80096010) and writes
nothing.
libfreenect only ever loaded audios.bin, the Xbox 360 firmware.
Microsoft's firmware (UACFirmware.bin, which freenect-driver-install
now fetches) uses the same image format (magic 0xCA77F00D, base
0x80000, entry 0x80030), and makes the microphones a standard USB Audio
device that the operating system drives.

- upload_default_firmware() picks the image.
  LIBFREENECT_AUDIO_FIRMWARE=uac or =xbox allows only one. Without it,
  Windows prefers UACFirmware.bin, because libfreenect's audio streaming
  is disabled there, and other platforms prefer audios.bin so the audio
  API keeps working; either falls back to the other image. A missing
  first choice is no longer an error, and the image in use is logged.
- After the upload, the controller is found again by serial number, or
  by the same bus and port path if the firmware reports another serial,
  instead of giving up after 10 s. Its new PID (02BB/02C3 with
  Microsoft's firmware) is stored in usb_audio.PID, and its PID and
  interface count are logged.
- freenect_start_audio() refuses with an explanation when the
  controller has a standard USB Audio interface (fnusb_has_audio_class),
  that is, when it runs Microsoft's firmware: libfreenect's audio
  protocol does not apply, and the OS audio stack owns those interfaces.

Tested against a simulated audio bootloader (the real loader.c with
fnusb_bulk stubbed), with the real images. UACFirmware.bin is chosen
when it is the only image and, on Windows, when both are present; it
uploads as 9 pages from 0x80000 and executes at 0x80030. With
LIBFREENECT_AUDIO_FIRMWARE=xbox, audios.bin uploads as 29 pages, the
same command sequence as the earlier hardware run. A forced image that
is missing, or no image at all, fails with -ENOENT. Not yet tested
with a Kinect.
upload_firmware_from_memory() ignored the bootloader's reply to every
16 KB page and to the execute command, so a rejected page went
unnoticed until the audio controller failed to come back. get_reply()
also returned 0 (success) for a short reply, and only logged a non-zero
status.

- Every page and the execute command must now get a valid reply:
  12 bytes, magic 0x0a6fe000, matching tag, and status 0. Otherwise the
  upload is aborted.
- On any failure (command, data or reply), clear the halt on bulk OUT
  EP 0x01 and bulk IN EP 0x81 before returning. On a rejected command
  the firmware sends no status and stalls EP 0x01 (older images also
  stall EP 0x81), and without CLEAR_FEATURE(ENDPOINT_HALT) the next
  attempt fails too.
- fnusb_bulk() used timeout 0, which waits forever; it now gives up
  after 5 s. The firmware loader is its only user.

Tested against a simulated audio bootloader with fault injection (the
real loader.c, with fnusb_bulk and fnusb_clear_halt stubbed): a wrong
tag after page 3, EP 0x01 stalling during page 2, a non-zero status for
the execute command, and a short reply after page 1. Each aborts at
once, clears both halts, and sends nothing further; a normal upload
afterwards still succeeds. Normal uploads of UACFirmware.bin and
audios.bin are unchanged.
The Linux and macOS counterpart of freenect-driver-install
--fetch-firmware.

  python3 src/fwfetcher.py --uac [--from INSTALLER] [OUTPUT]

downloads Microsoft's Kinect for Windows Runtime v1.8 installer from
download.microsoft.com, or reads it from disk with --from, and writes
UACFirmware.bin, without running the installer. Only the standard
library is used:
- the Burn bundle's payload is the second cabinet in the file;
- a small cabinet reader expands it (all of its cabinets use MSZIP,
  that is raw deflate with the previous 32 KB as dictionary, which zlib
  handles);
- a minimal OLE compound-file reader finds the cabinet stream inside the
  x64 drivers MSI "a0";
- that cabinet yields UACFirmware.

Authenticode cannot be checked with the standard library, so the
firmware itself must match: 145,920 bytes, SHA-256
4467ae36ad378c58477432729d74eed0f9d45d35213f4430a781d90f64cea3f9. A
different installer hash only produces a note, because Microsoft
re-signs its downloads. A damaged installer gives an error message
instead of a traceback, and nothing is written. Needs Python 3.3+; the
audios.bin path is unchanged.

README: how to use Microsoft's firmware on Linux, macOS and Windows,
and that Microsoft's licence terms apply to it.

Tested with Python 3.13: from the downloaded installer, and from a fresh
download from Microsoft, both write the verified firmware. An installer
with corrupted compressed data is rejected without output. One with
only a header byte changed still yields the genuine firmware. A wrong
expected hash makes it refuse to write.
libfreenect guessed the model only when the camera was opened: a 02BF
camera, or a camera bcdDevice other than 267, meant "not a 1414" (motor
through the audio controller). Near mode was gated on the camera PID
separately.

Decide it the way Microsoft's runtime does (Kinect10 FUN_1800a9560 and
FUN_1800a96b0), from the sensor's internal hub and the Kinect function
on the hub's lowest port:

  hub 0409:005A (NEC)                        -> Xbox 360 model 1414
  hub 045E:02C2, first Kinect child 02BF, 02BE or 02C3
                                             -> Kinect for Windows
  hub 045E:02C2, any other Kinect child      -> Xbox 360 model 1473
  hub 045E:02C2 without a Kinect child       -> Kinect for Windows

If the hub is not visible or is neither of these (some virtual machine
passthroughs), fall back to the old heuristic: a 02BF camera is Kinect
for Windows, a camera bcdDevice other than 267 a 1473, anything else a
1414.

- src/kinect_type.c: fnusb_kinect_type(), a pure function with no libusb
  dependency, and fnusb_kinect_type_name().
- fnusb_open_subdevices() stores the result in dev->device_type for
  every open, including audio-only ones such as freenect-fwloader, and
  logs it ("Kinect model: Xbox 360 Kinect (model 1414), from hub
  0409:005A"). The 1473/K4W handling (motor and LED through the audio
  controller, zero-plane reply size 334, LED keep-alive) now keys off it.
- Near mode is allowed only for Kinect for Windows, as in the runtime.

Tested host-only (kinect_type.c compiled alone): every row of the rule
table for the eight Kinect PIDs, the runtime's fallbacks, and a sweep
of 2 cameras x 1024 bcdDevice values. That sweep shows the no-hub
fallback reproduces the old heuristic exactly. Not yet tested with a
Kinect; the 1414 test PC has hub 0409:005A.
Checked against the Kinect audio firmware's command handlers and
Microsoft's runtime (Kinect10).

1473 / Kinect for Windows (bulk commands on the audio controller):
- The 0x8032 state block puts the accelerometer x/y/z at 0x30/0x34/0x38
  (int32), both in the firmware's reply builder and in Kinect10.
  libfreenect read 0x10/0x14/0x18, which hold other values, so the
  accelerometer was wrong on these models (compare OpenKinect#376). The tilt is
  an int16 at 0x1C, and -64 means invalid (the previous angle is kept).
  The reply must be exactly 0x68 bytes.
- tilt_status comes from the moving flag (0x04 bit 0) and the
  last-move result code at 0x20 (1 = stall, reported as
  TILT_STATUS_LIMIT). Before, it was never set on these models.
- Stalled bulk pipes are cleared after any failed command. On a
  rejected command the firmware stalls the pipe instead of replying.
- LED: unknown values (e.g. LED_BLINK_RED_YELLOW) fell through to the
  public value LED_GREEN = 1, which means "off" to this firmware. They
  now map to blinking. Firmware values: 1 off, 2 blink green, 3 green,
  4 red; there is no yellow.
- The LED keep-alive no longer resets the audio controller. That reset
  re-enumerates the device and has been linked to LIBUSB_ERROR_IO
  (OpenKinect#580, OpenKinect#557). It now sends the LED command only when the firmware is
  running (2+ interfaces), and treats a failure as non-fatal.

Tilt policy, both paths, as in the SDK:
- Clamp to +-27 degrees (NUI_CAMERA_ELEVATION_MAXIMUM/MINIMUM), not +-31.
- Skip the move, returning 0, when the sensor is tipped more than about
  72 degrees (y/|g| < 0.309) or the accelerometer reads below 0.1 g.
- Rate limit: at least 1 s between moves and at most 15 moves per 20 s;
  otherwise -EAGAIN. Microsoft added this to protect the motor.
  LIBFREENECT_TILT_RATE_LIMIT=0 turns it off.

1414 (control requests on 02B0): at least 10 ms between motor control
transfers, as Kinect10 does.

fn_now_ms() and fn_sleep_ms() are shared monotonic-time helpers.

Tested host-only (the real tilt.c against a simulated motor on a fake
clock): 0x8032 parsing with decoy values at the old offsets, the
invalid-angle and status mapping, clamping, the rate limit, its window
and opt-out, the level check (tipped over and 0 g), the LED mapping,
and 1414 spacing and level check. All 25 checks pass. Not yet tested
with a Kinect; only a 1414 is available, so the 1473/K4W changes need
testers.
A switch to keep the LED dark, for example at night, without changing
any application:
- freenect_set_led() turns every request into LED_OFF (logged once at
  info level).
- freenect_open_device() switches the LED off as soon as the motor or
  the audio controller is reachable. The 1473/K4W audio firmware starts
  with it blinking.
- The 1473/K4W LED keep-alive sends "off" instead of "green".

README: a table of libfreenect's environment variables (LED, tilt rate
limit, firmware path and image, UsbDk, the Windows audio guard).

Tested host-only with the simulated motor: with the switch set, red and
blinking requests are sent as off on the 1473/K4W path (value 1) and on
the 1414 path (value 0), and clearing it restores normal behaviour.
libfreenect never sent the camera's laser command, so the IR projector
stayed in whatever state the camera left it (OpenKinect#385: the projector stays
on after programs exit). Microsoft's runtime sends GM command 0x0086
[1] right after every depth start and 0x0086 [0] after every depth stop,
on every Kinect v1 model; only its public "force emitter off" API is
limited to Kinect for Windows.

- fn_set_ir_emitter(): GM command 0x0086 with a 16-bit 1 or 0. A
  rejected command is a warning, not an error.
- freenect_start_depth() switches the projector on.
  freenect_stop_depth() switches it off.
- New public API freenect_set_ir_emitter(dev, on). It is remembered: 0
  keeps the projector off while depth runs, and is re-applied after
  every depth start, as the SDK's force-off does. It takes effect at
  once while depth is running.
- freenect_camera_teardown() returned right after stopping depth, so a
  running video stream was never stopped on close. It now stops both.

Tested against a simulated camera channel (the real flags.c): 0x0086
goes out with payload 1 and 0. The API only remembers the setting while
depth is stopped and sends it at once while depth runs. A camera that
does not answer gives an error after the 2 s send_cmd timeout. Not yet
tested with a Kinect.
udev rules (platform/linux/udev/51-kinect.rules) now cover every Kinect v1
USB function, 045e:02ae/02bf (camera), 02b0/02af (motor), 02ad/02be (audio
bootloader) and 02bb/02c3 (audio with firmware, also motor and LED on the
1473 and Kinect for Windows). Access goes to the logged-in user through
TAG+="uaccess" and to the plugdev group (SSH, headless Raspberry Pi),
instead of MODE="0666" for everyone.

When the audio bootloader appears, the rules start freenect-fwloader.service
(a hardened oneshot unit), which uploads the firmware so that snd-usb-audio
serves the microphone array with no application running. freenect-fwloader
gains --wait SECONDS (at most 60) because the audio controller can appear
before the camera.

The camera uses libusb_set_auto_detach_kernel_driver, so gspca_kinect is
detached on claim and re-attached on release. An optional modprobe.d
blacklist is installed as documentation.

The firmware search adds $XDG_DATA_HOME/libfreenect (default
~/.local/share/libfreenect) and each $XDG_DATA_DIRS entry, without
duplicates. fwfetcher.py --uac accepts a directory as OUTPUT and --user.

CMake installs the rules and unit (INSTALL_LINUX_INTEGRATION, ON by
default) to /usr/lib/udev/rules.d and /usr/lib/systemd/system for prefix
/usr, and /etc/udev/rules.d for /usr/local; CPack packages them with
postinst/postrm hooks that reload udev and systemd. CI verifies the rules
(udevadm verify), the unit (systemd-analyze verify), the staged install,
and the .deb's contents, install and removal.
tilt.c uses lround() since the motor rework (aa8dda6), which left
libfreenect.so with an undefined reference on Linux and broke the link of
every example there.
New API:
- freenect_set_hotplug_callback(ctx, cb, user) reports
  FREENECT_HOTPLUG_ARRIVED / FREENECT_HOTPLUG_LEFT with the camera serial
  (the one freenect_open_device_by_camera_serial() takes). It first
  reports the Kinects already connected. Callbacks run from
  freenect_process_events*() after event handling, so they may open and
  close devices.
- freenect_device_connected(dev) says whether an open device is still
  there.

Where libusb has hotplug support (Linux, macOS) its events trigger a
rescan; elsewhere (or with LIBFREENECT_HOTPLUG_POLL=1, for VMs and
containers) the cameras are scanned once a second and
freenect_process_events_timeout() waits at most one second. libusb
forbids synchronous I/O inside its hotplug callback, so the callback only
marks the scan as due. A camera is identified by bus and address, so a
Kinect that is replugged is a new arrival; serials are read once per
camera, through this context's own handle when it has the camera open
(a second WinUSB open fails).

When an open Kinect leaves, all its subdevices are marked disconnected,
its streams are stopped once (previously on every call), and with a
hotplug callback set freenect_process_events*() no longer fails because
of it; without one it returns < 0 as before. Control and bulk transfers
that fail with LIBUSB_ERROR_NO_DEVICE also mark the subdevice
disconnected (the audio handle is reset after the firmware reboot), and
control transfers get a 5 s timeout instead of none.

The camera serial lookup moves into fnusb_read_kinect_serial(), shared by
freenect_list_device_attributes() and the scan.

freenect-hotplug (examples/hotplug.c) prints arrivals and departures and
keeps depth streaming across replugging; it exits on Ctrl+C.

Unit tests (new test/, BUILD_TESTS, ctest): the table logic, and core.c's
hotplug path against a simulated USB layer (arrivals, departures, open
devices losing their Kinect, the polling timeout cap, return values). CI
runs them and freenect-hotplug in both modes.
The viewers (glview, regview, hiview, chunkview, micview, glpclview,
cppview, cpp_pcview) used GLUT, which on Linux needs X11 (XWayland under
Wayland). They now include examples/fn_glut.h, which implements the GLUT
calls they use on GLFW (examples/fn_glut.c): windows, display, reshape
(with the framebuffer size, so HiDPI is right), idle, keyboard (ASCII,
Esc = 27), mouse, drag, wheel as buttons 3/4, glutGet(GLUT_ELAPSED_TIME).
The viewers themselves only change their include. GLFW 3.4 prefers
Wayland; LIBFREENECT_GLFW_PLATFORM=x11|wayland picks one.

Closing a window, Ctrl+C or closing the terminal now reaches the viewer
as Esc, its normal way out, which stops the Kinect before exiting. A
viewer can be blocked (for example waiting for a frame from an unplugged
Kinect), so a watchdog ends the process 5 s after the close request in
any case (SIGALRM; on Windows a thread), and a second Ctrl+C ends it at
once.

FREENECT_GL_VIEWERS=AUTO (default: GLFW if found, else GLUT), GLFW, GLUT
or OFF, in cmake_modules/FreenectGLViewers.cmake, which also provides
freenect_gl_viewer() for examples/ and wrappers/cpp/. vcpkg's examples
feature now brings glfw3 instead of freeglut.

Tests: test_fn_glut (ctest; Linux, needs a display, skipped without one)
checks that Ctrl+C reaches the viewer as Esc and that a stuck viewer is
ended by the watchdog. CI runs it under Xvfb, checks that every viewer is
built with GLFW on Linux, macOS and Windows, and builds the GLUT fallback
on Linux.
The Kinect can be found, tilt and blink while its isochronous streams
deliver nothing, which is the usual symptom of USB passthrough in a VM
(OpenKinect#696) or of a troublesome controller, and so far
libfreenect said nothing about it.

Every isochronous stream now counts empty or failed packets in 2 s
windows (the first one after a start is a warm-up). At 95% or more it
warns that the stream delivers no data; at 20% or more it notes that it
is losing data; each once per stream start, with the counts. The hint
depends on whether this looks like a virtual machine: DMI vendor and
product on Linux, the BIOS registry values on Windows,
kern.hv_vmm_present on macOS, and WSL2 from the kernel release. The
CPUID hypervisor bit is not used, because Windows with core isolation
sets it on physical machines too.

README: a Troubleshooting section on power, cabling, USB controllers, VMs,
WSL2 and LIBFREENECT_HOTPLUG_POLL.

test_iso_diag (ctest): thresholds, warm-up, once-per-start reporting, and
that VM detection runs (it reports WSL2 in WSL and nothing on a physical
Windows 11 machine with core isolation on).
The plan's Linux targets that GitHub has no runners for now build in
containers: ubuntu:rolling, ubuntu:26.04 and debian:trixie on x64;
Raspberry Pi OS trixie on the arm64 runner (debian:trixie with Raspberry
Pi's repository added and its packages installed, which is how Pi OS is
put together); and armhf, Debian's ARMv7 port under QEMU, standing in for
32-bit Pi OS on a Pi 2 or newer (GitHub's arm64 runners can't run 32-bit
ARM code, and Pi OS's ARMv6 build for the oldest boards isn't covered).

Each runs .github/ci/linux-distro.sh: distribution packages only (libusb,
GLFW, Mesa), the library, examples, viewers and wrappers built with the
release's compiler, all unit tests (window tests under Xvfb), the
no-Kinect smoke tests, udevadm verify, and the .deb built, installed and
removed with dpkg.
A Linux tool that serves the Kinect's depth and colour streams as
ordinary V4L2 cameras, so that OpenCV, GStreamer, ffmpeg, OBS, browsers
and video-call programs can use them with libfreenect's handling of the
Kinect (depth in millimetres, hotplug, model-specific fixes).

- depth: Y16 (the value is millimetres, 0 = no data; default) or YUYV
  (a grey image, near = bright, 0.4-4.5 m) for programs that only show
  video; colour: YUYV (default) or RGB24; 640x480 at 30 fps
- writes only to V4L2 output devices (v4l2loopback): a real camera is
  refused after VIDIOC_QUERYCAP, and a format the device didn't accept
  is an error rather than garbage
- --serial picks a Kinect; when it's unplugged the tool waits for it to
  come back (hotplug API); Ctrl+C stops it
- --test-pattern writes moving images without a Kinect, to check a
  loopback setup

BUILD_V4L2_BRIDGE (Linux, ON; needs only linux/videodev2.h). The pixel
conversions are in examples/v4l2_convert.h with a ctest
(test_v4l2_convert: BT.601 values, depth to luma, Y16 byte order). CI
loads v4l2loopback on the x64 Ubuntu runner when it can, runs the test
pattern into two devices, and checks the formats with v4l2-ctl and three
captured frames per stream with ffmpeg; it skips with a notice if the
module can't be loaded. platform/linux/README.md documents the setup.
GCC 15 reported 124 warnings with -Wall -Wextra across the library,
wrappers, fakenect and examples. Now there are none, with and without
optimisation:

- fakenect/record.c called fclose(index_fp) exactly when index_fp was
  NULL (the index file could not be created), which crashes; it now just
  returns the error.
- registration.c compared a uint32_t map index with -1; the comparison
  is now with (uint32_t)-1, as the map stores it.
- loader.c compared the signed byte count with the header's size; the
  count is checked for < 0 first.
- c_sync compared int fields with enum arguments; cast explicitly.
- Two intentional switch fall-throughs (cameras.c, audio.c) are marked.
- cameras.c's unused invalid_mode is gone; loader.c keeps
  check_version_string() for reading the firmware version and marks it
  FN_UNUSED (new, in freenect_internal.h).
- Parameters that callbacks and API stubs (fakenect) don't use are
  marked with (void)name.

FREENECT_WERROR (OFF by default) builds with -Wall -Wextra -Werror under
GCC and Clang. The native Linux jobs and every container distro job turn
it on, so the release compilers of Ubuntu rolling, 26.04 and 24.04,
Debian trixie and Raspberry Pi OS (arm64, armhf) keep the build clean.
macOS will follow once Apple Clang's warnings are dealt with.
- launchd agent (platform/macos/launchd/org.openkinect.fwloader.plist,
  installed to share/libfreenect/macos): an IOKit match on the audio
  bootloader (045e:02ad, 045e:02be) starts freenect-fwloader, which
  uploads the firmware so that Core Audio offers the Kinect's 4-channel
  microphone with no application running. The new --launchd option
  receives the com.apple.iokit.matching event over XPC, which launchd
  requires (otherwise it restarts the job over and over); elsewhere it is
  refused.
- Firmware is also looked for in ~/Library/Application Support/libfreenect
  and /opt/homebrew/share/libfreenect; fwfetcher.py --uac --user writes to
  the former on macOS.
- platform/macos/README.md: building (also universal), the firmware, the
  agent's install and removal.

CI:
- macOS on Apple Silicon and on Intel (macos-15-intel); Apple Clang's
  -Wall -Wextra warnings are reported as annotations, before -Werror is
  turned on there too; the agent's plist is checked with plutil;
  freenect-fwloader --launchd runs.
- macOS universal: libusb 1.0.29 built from source for arm64 and x86_64,
  libfreenect built with CMAKE_OSX_ARCHITECTURES="arm64;x86_64",
  every binary checked with lipo, the tests run natively and, where
  Rosetta is available, as x86_64.
…tions

The Raspberry Pi OS jobs failed at apt-get update: trixie's apt verifies
with sqv, which rejects raspberrypi.gpg.key because the key's binding
signatures use SHA-1 ("SHA1 is not considered secure since 2026-02-01").
The same key (82B129927FA3303E) in Raspberry Pi's
raspberrypi-archive-keyring package is signed with SHA-512, so the script
now takes it from there: it reads the package's path from the archive's
Packages index over HTTPS, installs it with dpkg and points signed-by at
/usr/share/keyrings/raspberrypi-archive-keyring.pgp.

linux-distro.sh now reports a failure as a GitHub annotation naming the
step, with the end of apt's output or the first compiler errors, so the
cause can be read without the job log.

The armhf job registers QEMU with tonistiigi/binfmt directly instead of
docker/setup-qemu-action@v3, which still targets Node 20.
- freenect_get_device_serial(dev): the serial that identifies an open
  Kinect (the camera's; on the 1473 and Kinect for Windows, the audio
  controller's), read when the device is opened, the same one the hotplug
  callback and freenect_open_device_by_camera_serial() use.
- The build of the running UAC firmware is read with cmd 0x09 (+0x44 of
  its 0x200-byte reply, §40.2.2, §40.2.7) and logged. Build 390 (SDK v1.0
  beta 2, which some loaders install) has no LED command 0x10: it would be
  rejected and stall the pipes (§40.2.7.7), so the LED is no longer set
  with it, neither by freenect_set_led() (one notice instead) nor at open.
- An audio controller that reboots into its bootloader while the rest of
  the Kinect is still there is reopened, with its firmware uploaded again,
  instead of the whole device counting as disconnected; at most three
  times per open device, and not when the camera has gone too (unplugged).
  The audio-opening code moves into fnusb_open_audio() for this.
- fakenect gains freenect_set_hotplug_callback() (the recording arrives as
  one Kinect, "fakenect"), freenect_device_connected(),
  freenect_get_device_serial() and freenect_set_ir_emitter(), so programs
  using them, such as freenect-v4l2, run against recordings.
- test_core_hotplug covers the recovery (reopened: still connected,
  camera streams untouched; failing: gives up after three tries) and the
  serial API.
- CI: a newer push to a branch cancels the run it supersedes.
…v4l2 timing

- fakenect/parson.c: parson_strndup() copies exactly n bytes and
  terminates the string itself; memcpy instead of strncpy, which GCC 14
  (Debian trixie, Raspberry Pi OS) flags as -Wstringop-truncation under
  -Werror.
- iso_diag.c: the DMI/registry string helpers are only built where they
  are used (not on macOS, which asks the kernel); Apple Clang reported
  names_vm() as unused. That was its only warning, so the macOS jobs now
  build with FREENECT_WERROR=ON too, and report diagnostics as
  annotations.
- The v4l2loopback test failed with ffmpeg's EACCES (exit 243) once: with
  exclusive_caps=1 a loopback device only takes readers while something
  writes, and the test pattern could finish its 300 frames first. The
  writer now runs until the step stops it (within timeout 60), and every
  failure in the step becomes an annotation saying what failed.
Tracks for a while (default 30 s; ends by itself and on Ctrl+C) and
prints once a second the users, each one's tracked joints, head
position, clipping, both hands' states, holding and finger counts, and
the time per frame. At the end it writes a BMP: depth in grey, each user
in its own colour, skeletons in white (inferred joints grey), fingertips
red. --seated for seated tracking. Built with BUILD_NUI.
The skeleton grows from the SDK's 20 body joints to 32: each hand's palm,
thumb, index, middle, ring and little fingertip (joints 20-31), smoothed
with the body joints. The skeleton also carries each hand's state (open,
closed, pointing, gun) and whether it holds something.

The hands are analysed for every tracked user in freenect_nui_process;
freenect_nui_get_hands returns the cached result. Fingers are tracked
closer than about 1.6 m. Each fingertip is named from its angle around the
wrist-palm axis in the image plane: the thumb stands apart from the evenly
spread fingers at one end of the fan; the others are ordered from the
thumb's side (or from the body's midline when no thumb is seen). Two tips
far apart are a thumb and index (gun); two close together are two fingers.

freenect-nuitest draws palm-to-fingertip lines (the thumb in yellow) and
prints the fingers it sees by name. The tracker test checks that no finger
joints are reported at 2.3 and 3.3 m.
Palm orientation: each hand gets a direction (from where the forearm
enters the hand region to the centroid of the hand's pixels) and a palm
normal (plane fit over the palm, wrist excluded). A hand seen edge-on shows
only its narrow side, so when the palm is thin across the direction in the
image, the normal turns to the image-plane perpendicular. Smoothed over
frames; in freenect_nui_hand and as hand_orientation in the skeleton.

Two-hand manipulation (freenect_nui_get_manipulation): two fists, or open
palms facing each other, at least 15 cm in front of the shoulders hold a
virtual object. Its frame comes from the line between the palms and the
hands' common direction; each frame reports the rotation (quaternion),
scale and translation since the last one, and the totals since the grip
began. Starts after 3 frames of a grip, ends after 4 without; changes under
0.5 degrees, 0.3 % or 3 mm add up until they pass.

A finger pointing at the Kinect is found in depth: a thin protrusion more
than 5 cm in front of the hand's mean depth; it is the index, and one other
finger out of the outline is then the thumb (a gun aimed at the Kinect).
Fingertip corners are tested over about 3 cm of outline.

Clasped hands (freenect_nui_get_clasp, hands_clasped): hand joints within
16 cm are one region, analysed once: nothing out, or a two-hand gun with
its tip and direction.

Tests: test_nui_gestures (grips, begin and end, zoom, turn, tip, steering,
slow turns, movement, noise); test_nui_hands adds turned and tipped hands,
fingers at the Kinect and clasped hands. freenect-nuitest prints where the
palms face, clasped hands, and grabs with their turn, zoom and movement.
Triangle grip (FREENECT_NUI_GRIP_TRIANGLE): thumb and index out on both
hands (the gun state), the thumbs pointing towards each other, the index
fingers up. Apart zooms in, together zooms out; turning or tipping the
triangle turns the object, as with the other grips. The grip values are
now flags (ANY = 7), and a manipulation keeps the grip it began with: a
different grip counts as none, ends it and starts its own.

One hand as a pointer (freenect_nui_get_hand_pointers), like the SDK's
interaction stream: each hand has a zone, 60 x 45 cm in front of its
shoulder, active from 20 cm in front of the shoulder. The cursor is
smoothed more the slower the hand moves. Events per frame:
- press: a push of 12 cm towards the Kinect beyond the resting reach,
  which follows slow changes (leaning in is not a press) and settles for
  10 frames after the hand comes up; ends when back under half;
- grip: the hand closing while active (unseen frames change nothing);
  ends when it opens, leaves the zone or is lost;
- swipes: 30 cm within half a second, twice as much along the axis as
  across it, starting inside the zone (raising the hand is not a swipe),
  then paused for half a second.
The primary hand is the active one, or of two the one further forward.
While two hands manipulate an object or are clasped, there are no events.

Tests: the triangle grip, its zoom while turning, grip switching, and the
pointer (cursor, swipes and non-swipes, press and leaning, grip and drag,
quiet and lost hands) in test_nui_gestures; a rendered triangle in
test_nui_hands. freenect-nuitest prints the primary pointer and every
event.
…phone

With the UAC firmware running, the Kinect's 4 microphones are a 4-channel
ALSA input. Two ways to publish them as one beamformed microphone,
"Kinect beamformed microphone", for PipeWire, PulseAudio and JACK
applications:

- WirePlumber 0.5 (as Asahi Linux does for the MacBook arrays):
  51-freenect-kinect-mic.conf opens the Kinect (045e:02bb/02c3) as one raw
  4-channel input without ALSA card profiles, gives it a fixed name, and a
  node.software-dsp rule loads the filter graph kinect-mic.conf on it and
  hides the raw input. The graph runs freenect_beam.so, libfreenect's
  beamformer as a LADSPA plugin (4 in, 1 out; Mode, Angle, SDK weights,
  Noise suppression, AGC; read-only beam and talker angles), and a 90 Hz
  high-pass. The plugin works at 16 kHz or any multiple up to 96 kHz,
  decimating and interpolating itself (windowed-sinc, polyphase), and
  allocates nothing in run().

- WirePlumber 0.4 (Ubuntu 24.04): freenect-pipewire-mic, a PipeWire client
  that finds the Kinect's source by name, captures it (4 channels, no
  remixing), beamforms it and publishes the result as a source node, with
  a systemd user unit. The source stays while the Kinect is away (silence)
  and picks it up again when it returns.

test-pipewire-mic.sh runs a private PipeWire and WirePlumber with a fake
Kinect source playing a talker 30 degrees off axis, and checks that the
beam towards the talker is clearly louder than the beam away from it
(locally 0.161 against 0.048 in both ways, at 48 and 16 kHz; the program
reports the talker at -27 degrees for -30).
…rophone

KinectBeamMic.driver is a Core Audio server plug-in (user space, in
coreaudiod) with two devices on one clock: the input "Kinect Beamformed
Microphone" and a hidden sink. What the sink receives at a sample time, the
microphone delivers at that sample time (16 kHz, mono, float).

A plug-in cannot capture another device, so freenect-coreaudio-mic.app
("Kinect Beam Mic", a background app so that macOS asks for microphone
access under that name) captures the Kinect's 4-channel input, beamforms
it with libfreenect and plays the result into the sink. It follows the
Kinect being unplugged and plugged in, and has --list (the audio devices)
and --self-test (a tone through the plug-in, no Kinect needed). The launchd
agent org.openkinect.beam-mic.plist starts it at login.

Both bundles are signed ad hoc after the build. Not built or run on a Mac
here: CI loads the plug-in into coreaudiod and runs the self-test.
wrappers/python is now a Python package (pyproject.toml, scikit-build-core):
`uv pip install ./wrappers/python` (or pip, or uv build) compiles libfreenect
statically into the modules, so nothing else needs to be installed; on
Windows the package carries libusb-1.0.dll. libfreenect's own build with
-DBUILD_PYTHON3=ON builds the same modules against its shared libraries.
distutils (gone in Python 3.12), setup.py, Cython 0.x and Python 2 are
dropped.

- freenect: as before, plus init(subdevices), select_subdevices,
  device_connected, get_device_serial, set/get_depth_range,
  set_ir_emitter, set/get_color_setting (COLOR_*), stream timing,
  get_mic_geometry, audio_streaming_available, and CoordinateMapper (depth,
  colour and camera space, points and whole frames as NumPy arrays,
  calibration save and load, mirrored mode).
- freenect_audio: Beamformer (process (n, 4) int32 or float frames;
  automatic, adaptive or fixed beams; source angle and confidence in
  degrees; Microsoft's weights; noise suppression, AGC, echo cancellation).
- freenect_nui: Tracker (Frame with 32-joint Skeletons as NumPy arrays,
  player index, hands, clasp, two-hand manipulation, one-hand pointers,
  grips, tracked users), Smoother, bone orientations, joint names.

The CMake files use PROJECT_SOURCE_DIR/PROJECT_BINARY_DIR instead of
CMAKE_*_DIR so that libfreenect also builds as a subproject.

tests/test_bindings.py (unittest, no Kinect): the mapper against the
reference vectors, the beamformer finding a talker at +30 degrees and
favouring it, the tracker's API (with the model). 11/11 with uv on Windows
(Python 3.12) and Linux (3.13).
- Linux: build freenect-pipewire-mic (libpipewire-0.3-dev) and run
  test-pipewire-mic.sh with a private PipeWire and WirePlumber.
- macOS: check and sign-verify KinectBeamMic.driver and the helper app,
  load the plug-in into coreaudiod, check that "Kinect Beamformed
  Microphone" appears, run the helper's self-test (a warning, not a
  failure, if the runner gives no microphone access), and stop the helper
  with SIGTERM.
- Linux and macOS: uv pip install ./wrappers/python and run its tests.
Microsoft's head forest, as the SDK runs it in seated mode:
- the file (§30.3.2): big-endian as shipped (or native), version 2 and the
  format id checked, zlib as the fetchers install it; 3 trees of 16383
  heap-ordered 8-byte nodes, probes (byte - 127) * 256 / depth cells,
  14-bit thresholds, one- or two-probe tests, leaves at the bottom level;
- detection (§30.3.4): the 320x240 map 4x4 min-pooled to 80x60 (0 = 6000
  mm), the 3 trees averaged per cell into a head probability, a [1 2 1]
  blur, seeds at 80 grown over 4-neighbours within 80 mm steps, and
  candidates with the SDK's position, metric box and score (mass over the
  probability's spread, times the 0.138 m head-size prior);
- tracking (§30.3.5): greedy matching within 0.1 m (depth only when the
  boxes overlap), tentative tracks from score 0.05 and 4-50 cm boxes,
  confirmed after 10 hits (re-attached to a nearby lost track, keeping its
  id), lost after 30 misses, forgotten after 60; 16 output records,
  ranked.

freenect_nui_get_heads() returns them; the detector runs in seated mode
when the model is installed, or with FREENECT_NUI_HEADS. freenect-nuitest
and the Python Tracker (heads=, heads()) show them. Not fed into the
skeleton fit: how the SDK uses them there is only inferred.

test_nui_heads (with the model): the trees match the reference's figures
(two-probe nodes 3972/3826/3859, thresholds, mean leaves); a rendered
seated person gives one candidate at the head's front surface and none
elsewhere; the track is confirmed, keeps its id through a lean, a short
absence and a loss, is forgotten after 110 frames; an empty chair is no
head.
Speed (results bit-identical with any number of threads):
- pool.c, a small thread pool (Win32 threads or pthreads); each user's
  per-pixel forest runs over row chunks on it (up to 8 threads by default;
  freenect_nui_set_threads, LIBFREENECT_NUI_THREADS);
- joint proposals unproject the user's pixels once, grouped by cell in the
  same order as before, instead of once per joint, and the 20 joints run
  on the pool;
- LIBFREENECT_NUI_PROFILE prints the time of each stage at destroy.
On the tracker test's scenes (8 cores): 8.9 -> 3.5 ms per frame for one
or two users (classification 3.9 -> 1.3 ms); six people at 4 m in 6.0 ms
(5.0 on Windows), i.e. well within 30 fps.

Joint limits in the fit's refinement, one-sided: elbows and knees fold no
tighter than 25 and 35 degrees, and knees bend no further than 2 cm behind
the hip-ankle line along the direction the body faces.

Smoothing: besides the SDK's Holt filter, a One-Euro filter (smooth when
still, little lag when moving) and a constant-velocity Kalman filter per
joint and axis (freenect_nui_smoother_set_one_euro, _set_kalman, _holt).
History now also starts over when a slot's user changes.

Tests: test_nui_smooth (noise when still, lag and error at 0.5 m/s, a new
user in the slot), test_nui_fit (a knee proposal behind the leg, a wrist
folded onto the shoulder, a natural pose untouched), and test_nui_tracker
gains per-frame timing and a six-person scene. Python: Smoother(kind) and
Tracker.set_threads.
The hardware test showed the tracker taking walls, a cupboard and a desk
for users in a real room, which the synthetic scenes never did. To work on
real data without the Kinect:

- freenect-nuitest --record FILE keeps every depth frame losslessly (per
  row, zigzag varint differences, runs of equal pixels as one token);
- freenect-nuitest --replay FILE tracks a recording, as fast as it goes,
  with the recording's own seconds in the report; a damaged file is
  reported, not trusted.

test_nui_tracker gains a furnished room: a side wall near the camera, a
cupboard, and a desk the user's hand rests on. Walls and furniture must
not become users (they don't here; the real room differs), and the user
is tracked, the arm on the desk being the weak part (65 % PCK@10cm).
…tions

WirePlumber 0.4 (Ubuntu 24.04) reads WIREPLUMBER_CONFIG_DIR as a single
directory, so the test's list of two left it without a configuration.
Set the list only for 0.5; the program mode needs none of our rules.

The Python and PipeWire steps now put the end of their output into an
error annotation when they fail, since job logs need a sign-in.
Recordings of a minute were several hundred MB, too big to hand over.
Now each frame is kept at 320x240 (the top-left pixel of each 2x2
block), with the frame's distinct depth values as a table and the
pixels as indices into it, predicted from their neighbours (median edge
predictor) and Rice-coded with an adaptive parameter in three contexts.
About 15-40 KB per frame instead of about 300 KB, lossless at that
resolution. Replay doubles the pixels back to 640x480 and keeps the
recorded frame numbers, so its seconds match the recording's.
…ixes

FNDREC3 (examples/fndrec.h): each 320x240 frame coded with an adaptive
binary range coder, each pixel predicted from the same pixel in the
frame before where its neighbours did not change, else from its
neighbours (median edge predictor), with contexts for the predictor,
the local gradient and pixels that flickered. On a real 58 s recording:
19 MB instead of 39 MB, bit-exact. --record keeps every frame (30 fps)
and starts a new part (NAME.2.fnd, ...) at 18 MB; --replay reads all
parts, and a last frame cut off by stopping the recorder is the end, not
damage. FNDREC2 files can still be replayed.

The picture at the end: the line routine updated its error term between
the two steps and could miss its end point, running practically forever
(seen as a hang after a seated test); joints far off the picture or NaN
are not drawn.
From replaying two recordings of a real room (an empty room, then one
person walking in, stepping, coming to 1 m, arms spread; and seated):

- Floor: a horizontal plane with points under it is a table, not the
  floor; the floor is at least 35 cm below the Kinect, rolled at most
  10 degrees sideways, and has at least 120 points. The tabletop had
  been taken as the floor and cut off everyone's legs; seated, the lap.
- Background: farther depth must stay 3 frames before it replaces the
  background (edges flicker); a per-pixel confidence counts frames the
  pixel was the empty room. Pixels that are that room never belong to a
  user (a hand on the wall no longer pulls the wall in). Next to a user
  nothing new is learned; where a new user appears, it is forgotten
  (someone sitting there from the start).
- New users: once the background is known, only something that moved
  can become a user; it is verified at once if it is mostly in front of
  room seen empty, otherwise the forest has to confirm it, and if it
  does not, it becomes background (a chair, a door frame at the edge of
  the view had been a user taking a skeleton slot).
- A component two users claim is split only if it is wide enough for
  two people; otherwise it stays with one (a person had come in as two).
- Fit: a user cut off at the top or the sides (too close, arms up) is
  still tracked from a shoulder and the hips, once its upper body was
  seen.

Real recording, whole body: 1317 of 1708 frames with a skeleton (745
live before), one user id throughout, right skeletons at 1 m and arms
spread; seated: 1476 of 1484. All synthetic tests pass.
From the recordings of the third test round:

- Someone already standing close (1.1 m, head above the view) when
  tracking starts was rejected by the forest in the first second, stored
  as background, and never found again (two-hand test: no skeleton at
  all). Now movement is measured: the pixels of a user, away from its
  outline, that came nearer than in a reference depth up to 8 frames old,
  by more than 30 mm plus three of the Kinect's depth steps (noise grows
  with z^2). A candidate that keeps moving keeps being tried instead of
  being stored as background, and the fit may confirm it from a shoulder
  and the hips when the view cuts it off, as for an existing user. A
  piece of the view with such movement can become a candidate again.
  Furniture never comes nearer by itself, and a wall only gets farther
  where an arm leaves it, so neither counts as moving.
- A chair found at startup had been confirmed by the forest as a body:
  a new user must be at least 1 m tall (seated, from the seat up) unless
  the view cuts it off at the top.

Replays: two-hand 1485 of 2299 frames with a skeleton (0 before; the
rest is the head out of view at 1.1 m), pointing 1828 of 1906 with no
ghost user, whole body and seated unchanged (1306/1718, 1476/1478; the
earlier round 1317/1708, 1476/1484). All synthetic tests pass.
Framing: freenect_nui_suggest_tilt(mode) gives the change of tilt that
frames the nearest user whose skeleton fitted, the whole body
(FREENECT_NUI_FRAME_BODY: head to feet, the head first when not all
fits) or the head, arms and hands (FREENECT_NUI_FRAME_UPPER_BODY, also
in seated mode). A head above the view is placed 30 cm above the
shoulders; with no skeleton yet, a user cut off at the top gets a 6
degree step up. A move is suggested only when the same is wanted 10
frames in a row and not within 1.5 s of the last; the tracker never
drives the motor itself.

freenect_nui_tilt_changed(degrees), after the application moved the
motor: the last output is held while the view moves; once a quarter of
the view differs from before the move and it is still again, the
background (with its confidence), the users' pixels and the floor are
rotated into the new view, the fits start afresh (the user keeps its id
and skeleton) and the pointers reset. If the view never moved within
3 s (the motor refused: tipped over, rate limit), nothing is carried
over.

Without the head: a user that came in or keeps moving may be taken from
a shoulder or an elbow and the hips when the view cuts it off; the head
and a shoulder with 6 tracked joints are enough when the legs are out
of view. Bone lengths are no longer learned from proposals at the edge
of the view, and are learned again after 15 failed fits in a row.

Python: Tracker.suggest_tilt("body"|"hands"), Tracker.tilt_changed().

Tests: the renderer tilts its camera like the motor. A user at 1.2 m
(head out of view, upper body): two moves, +12 degrees, then the head
tracked, PCK@10cm 88 %, same id. The Kinect tilted down 18 degrees, a
user at 2.3 m (whole body): +14 degrees, PCK 98 %, same id. A move the
motor did not make: tracking unchanged. Replays of the real recordings:
the close two-hand one 1851 of 2299 frames with a skeleton (1485 before),
the others the same or slightly more.
--frame keeps the nearest tracked user framed with the tilt motor
(freenect_nui_suggest_tilt; the motor's limits stay in
freenect_set_tilt_degs) and prints each move. --tilt DEG first tilts
the Kinect to DEG. Recordings keep each move as an event record (frame,
0x80000004, int32 hundredths of a degree); a replay makes the same
moves, and with --frame prints what framing would suggest.
…ut of users

The first hardware test with the motor showed the framing running away up
to +27 degrees. The motor does not turn by the angle it is told (19
degrees asked gave 15, a move near the limit about 5 of 6.5), and the
background, floor and users were carried over by the commanded angle, so
walls and floor became users that touched the top of the view and asked
for more moves up.

- The move is measured in the depth image: the angle that best maps the
  view before the move onto the current one, from the points whose depth
  changes from row to row, ties going to the commanded angle. The move is
  over when that angle stops changing; a move under 0.75 degrees is none.
  freenect_nui_tilt_measured() reports it (NAN while settling); nuitest
  prints it; Python: Tracker.tilt_measured.
- After a move, what came into view well behind every user is the room
  at once; nearer it may be the head the move was made to see.
- A pixel more than 60 cm behind a user's median depth is not that user
  (the wall, joined through a chair or the outline).
- A user that never moved in 10 s and did not walk in is let go as room
  (a strip of wall along a depth edge, taken in the first frames); one
  2.1 m wide and still for 5 s is the wall a user left behind. A new user
  verified by the forest is at least 25 cm wide.
- Framing follows only users that moved or walked in, and stops after two
  moves the same way without seeing the user's top.
- Candidates: the motion needed grows more slowly with size (a close
  user moving the hands), and a user cut off at the bottom below a tracked
  head counts as tall enough (someone close, the Kinect tilted up).

Replays of the 2026-11-17 recordings make 2 to 4 suggestions instead of
the runaway; the earlier recordings track as before or better (two-hand
2029 of 2299, was 1851). All 23 tests pass on Linux, the tracker test on
Windows, 11 Python tests.
The direction estimate took a frame only above two absolute levels from
the runtime, E > 82.3 and a winning direction worth c > 0.2716. Speech
1.5 m away arrives through WASAPI at -55 to -65 dBFS (E 10..60), so only
the key click that starts the tool passed: the direction froze there
(-47.7, -35.8, -26.5 degrees in the hardware tests of 2026-11-13..17)
and its confidence fell to 0.

Keep the runtime's noise-floor test (E > 5.29 F), lower the absolute
level to just above the array's own noise (E > 2), and test the winning
direction's share of the frame (0.0594, what c > 0.2716 is at the
runtime's E = 82.3) instead of its level.

Replayed offline, the six recordings of 2026-11-13..17 now go left
(-38) -> front (-4) -> right (+38) at the step times. New test: a
-60 dBFS speaker who moves after a loud click (failed before at -47.7).
…to it

--tilt DEG sent the command and waited a fixed 2 s. The motor runs at
about 16 degrees per second and often stops short, so a run could start
before the Kinect was level (one hardware run read -64, the "moving"
value, when tracking began). Each run also left the Kinect wherever
framing had tilted it, up to +27 degrees.

Now --tilt polls the motor until it reports stopped for three readings,
sends the command once more when it stopped over 2 degrees short, and
waits out the 1 s rate limit instead of failing. At the end (also on
Ctrl+C, without waiting then) it tilts back to DEG. With 0 seconds it
only tilts and exits, without loading the models.
…ith its user

In the 2026-11-18 hand tests a cupboard 2 m away on the left kept a
skeleton for the whole run. It had moved in its first frames, while it
was being segmented, so the never-moved rule did not apply. Its outline
then stayed still, but the fitted head jumped 5 to 40 cm a frame; a
person whose outline is still holds the head within about 1 cm. Now a
user whose outline has been still for 1 s, and whose head then jumps
more than 4 cm in over two thirds of 90 frames, is rejected as room
(the cupboard: 82 %; a person with the head cut off at the top edge: up
to 50 %).

The cupboard's top was always out of view, so whenever the person's fit
had a bad frame, framing took the cupboard as the nearest user and
tilted up; the person then needed a move back down, and the Kinect went
back and forth between +20 and +27 degrees. Framing now stays with the
user it follows while that user is there, and for 2 s after.

Replays: the 2026-11-18 n2b recording loses both phantoms within 11 s
and asks for 13 moves instead of 36, the person tracked as before (91 s
against 93); the 11-13, 11-16 and 11-17 recordings and the other
11-18 ones replay as before.
In the 2026-11-18 whole-body test the person was lost and found again
under a new id eleven times. Each time their outline had joined one
component with most of the room (68,000 of 76,800 pixels, 2.8 m wide,
centred 2.5 m away), through the mixed depths along the outline or the
feet on the floor. That component's centre was more than 0.6 m from the
user's, so the user took nothing that frame, overlapped nothing the next,
and timed out.

Now a verified user that has moved (or came in), most of whose pixels
are in such a component, still takes it, but only the part near where
it was: last frame's box grown by 12 pixels, no more than 1 m in front
of its median depth and 1.2 m to either side of its centre. Furniture
the forest took for a person never moved, and is left to fall apart as
before.

For 3 s after a tilt nothing counts as having come in (a user at once):
the room carried into the new view is a few degrees off, and furniture
seemed to stand in front of it.

Replays: the 11-18 whole-body test keeps one id from 14 s to the end,
with a skeleton in 1664 of 2168 frames (1189 before); the seated test
keeps one id for all 77 s (2306 of 2311 frames, 2061 before); a phantom
in the 11-17 whole-body test is gone; the other 11-13 to 11-18
recordings replay as before.
astral-sh/setup-uv@v6 runs on Node 20, which GitHub has deprecated; v10.4.0
runs on Node 24 (the project publishes no moving major tags after v7, so
the release is pinned).

The macOS Python tests failed to import freenect: the module needed
@rpath/libfreenect.0.dylib and has no rpath. The package is meant to
link libfreenect statically, but freenect_sync_static linked the shared
freenect, which came along. Linux drops an unused shared library at link
time (--as-needed), macOS does not. freenect_sync_static now links
freenectstatic; a module linked like the package no longer needs
libfreenect.so.0 (checked with readelf, with --no-as-needed).
In the 2026-11-23 hardware test the whole-body run got no depth frame in
73 s: all 526,423 packets came without the "RB" header, from the start.
The runs before and after it were fine. A stream that sends 16000 such
packets in a row (about two seconds) now asks for a restart, and
freenect_process_events() stops and starts it, outside libusb's event
handling, at most three times while the device is open.

freenect-nuitest with 0 seconds (only tilting, the test script's levelling
step before that run) opens the motor alone and leaves the camera alone.
In the 2026-11-23 hand test the Kinect tilted 14 degrees up for a user
1.5 m away, the tracker concluded "the view did not move" and then lost
the skeleton for the rest of the run. The measured angle rose with the
motor to 7 degrees; past that, so much of the close view had changed that
no angle matched well, and "no better than not moving" was read as not
moving, although not moving matched just as badly (0.17).

It is now "no move" only when the view before the move still matches well
(0.5); otherwise the angle is unknown, and settling waits for as long as
the commanded move takes (2 frames a degree, plus the start), then takes
the last angle measured or 80 % of the commanded one (the motor stops
short), whichever is larger. In the replay of that run the move is
measured as +14 degrees; the other recordings replay as before.
Recordings kept the top-left pixel of each 2x2 block, while the tracker's
map (fn_nui_make_map) takes the largest of the four. Replays were close to
the live run but not the same: on 2026-11-23 a run that lost its user
live kept it in the replay. The file format and the reader are unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant