Skip to content

About

Virtual USB devices over USB/IP that the OS sees as real hardware: a wired Xbox 360 controller and a USB microphone. Windows via usbip-win2; Linux via vhci-hcd, or uinput without root (controller only). Device layer of Airhand; Rust library, C API and sidecar CLI.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

airhand-dock

Virtual USB devices for remote control, attached over USB/IP. A program feeds a virtual device and the operating system sees real hardware, without a driver of our own: a virtual wired Xbox 360 controller works in every game, through XInput, DirectInput, Windows.Gaming.Input, SDL, Steam Input or Linux evdev; a virtual USB microphone is a recording device for every program, through the OS's own audio class driver.

airhand-dock is the device layer of Airhand (the host plugs a controller and a microphone for the person at the other end), and a standalone library, C API and command line tool for any program that needs the same.

Windows 10 1903+ / 11 (x64, ARM64) Linux
OS side usbip-win2 (signed kernel driver) vhci-hcd (in the mainline kernel); without root, uinput
Privileges none root for vhci-hcd; otherwise access to /dev/uinput
Devices Xbox 360 controller (wired, 045E:028E); microphone (USB Audio Class 1.0) same (through uinput: the controller only)

How it works

flowchart LR
    app["Your program<br>(Rust / C / any language via the sidecar)"]
    dock["airhand-dock<br>device model + USB/IP link"]
    os["OS virtual host controller<br>usbip-win2 · vhci-hcd"]
    stack["OS USB stack<br>xusb22 · xpad · XInput · SDL"]
    app -- "set_state(), write()" --> dock
    dock -- "rumble, LED, mic volume" --> app
    dock <-- "USB/IP: loopback TCP / socket pair" --> os
    os <--> stack
Loading

USB/IP carries USB requests over a byte stream. airhand-dock is the USB/IP server: it answers the host's requests (descriptors, configuration, interrupt and isochronous transfers) from a device model running in your process. The OS's USB/IP client plugs the device into a virtual host controller, where it is enumerated like real hardware. Isochronous streams (the microphone) are paced on a frame clock the dock keeps, one packet per 1 ms frame, as a real bus would:

  • Windows: the device is offered on a loopback TCP port, and usbip-win2's driver is asked (through its IOCTL interface) to attach 127.0.0.1:<port>/<busid>. Only the kernel's own connection may import it.
  • Linux: no TCP at all. One end of a socket pair is handed straight to vhci-hcd through sysfs.
  • Linux without root (uinput): vhci-hcd's attach file is root's, so a program running as the desktop user cannot use it. The dock then plays the USB host as well: a thread on the other end of the socket pair speaks USB/IP to the device and does what the kernel's xpad driver would, turning reports into evdev events of a uinput device and force feedback into rumble. Programs see the same input device (name, ids, buttons, axes, rumble). Only devices the dock has a driver for (the Xbox 360 controller) can be plugged this way; not the microphone.
  • Export (any OS): devices are only offered on a USB/IP server; attach them yourself, e.g. with usbip attach on another machine.

Performance

  • No allocation and no copy beyond the report itself per input report: the state change completes the host's pending interrupt request right away, from the calling thread, under one uncontended lock, with one send of header plus report (no extra threads, queues or timers).
  • Reports are sent only when the state changes; the host's request stays pending (a NAK, as on real hardware) until then.
  • Small replies leave immediately (TCP_NODELAY); usbip-win2 runs in its low-latency receive mode (WSK event callbacks, no receive thread per device).
  • Measured on Linux (WSL2, vhci-hcd): ≈ 55 µs from set_state until a user-space reader of the kernel's device node has the report, including the kernel's own USB/IP threads and usbfs.

Quick start

1. Install the OS side

Windows: install usbip-win2 (0.9.7.0 or later; any release works through its usbip.exe if its IOCTL layout is unknown to this build). Nothing else; airhand-dock talks to the driver directly and needs no administrator rights.

Linux: as root, sudo modprobe vhci-hcd (add vhci-hcd to /etc/modules-load.d/ to keep it). As a normal user, the uinput backend needs access to /dev/uinput. Many desktops already grant it to the user at the seat (Steam's steam-devices rules do); otherwise add a udev rule:

$ echo 'KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput"' \
    | sudo tee /etc/udev/rules.d/60-airhand-dock-uinput.rules
$ sudo udevadm control --reload && sudo udevadm trigger --name-match=uinput

2. Try it

Download the archive for your platform from Releases:

$ airhand-dock status
backend:   usbip-win2
available: yes
driver:    usbip-win2 (0.9.8.1 request layout)

$ airhand-dock demo --seconds 20     # the left stick circles, A blinks; open joy.cpl or a game
$ airhand-dock demo --mic            # "airhand-dock Demo Microphone" beeps at 440 Hz; record from it

Using it

Rust

[dependencies]
airhand-dock = { git = "https://github.com/sqlpxc/airhand-dock", tag = "v0.3.0" }
use airhand_dock::{Buttons, Dock, GamepadState, Xbox360};

let dock = Dock::new()?;                  // usbip-win2 on Windows; vhci-hcd (root) or uinput on Linux
let pad = Xbox360::new();
pad.on_output(|out| {
    // Rumble from the game (and the player number Windows assigned, from the LED).
    println!("rumble {} / {}, player {:?}", out.large_motor, out.small_motor, out.player());
});
let plugged = dock.plug(&pad)?;           // blocks until the OS has the device

pad.set_state(&GamepadState {             // same layout as XINPUT_GAMEPAD
    buttons: Buttons::A | Buttons::DPAD_UP,
    left_trigger: 255,
    left_x: -32768,
    ..Default::default()
});

drop(plugged);                            // unplugs the pad

A microphone: write 16-bit PCM into it and every program can record it. Samples wait in a queue that empties in real time whether or not a program records, as a real microphone's sound is lost when nobody listens; so the latency is what you keep queued, and a dry queue is silence.

use airhand_dock::{Dock, Microphone, MicrophoneConfig};

let mic = Microphone::with_config(
    MicrophoneConfig::default()           // 48 kHz mono, 200 ms of queue
        .product("My Microphone")         // "Microphone (My Microphone)" on Windows
        .serial("MYMIC1"),                // recognized again wherever it is plugged
)?;
let plugged = Dock::new()?.plug(&mic)?;
loop {
    if mic.queued() < 48 * 40 {           // keep ~40 ms queued
        mic.write(&next_10ms_of_audio()); // interleaved i16 (or write_f32)
    }
    std::thread::sleep(std::time::Duration::from_millis(5));
}

mic.is_streaming() says whether a program is recording; mic.controls() gives the mute and volume the host set (Windows' "Levels"), which are already applied to what it receives.

Dock::status(BackendKind::Auto) tells, without side effects, whether the backend is usable and why not: reason is an ErrorKind a program can act on (BackendUnavailable: offer to install usbip-win2; PermissionDenied: explain the uinput rule), problem the English text.

C and other languages (C ABI)

Each release archive contains include/airhand_dock.h, the shared library (airhand_dock.dll + import library airhand_dock.dll.lib, or libairhand_dock.so) and a static library (airhand_dock.lib, libairhand_dock.a).

ahd_dock *dock;
ahd_x360 *pad;
if (ahd_dock_open(NULL, &dock) != AHD_OK || ahd_x360_plug(dock, NULL, &pad) != AHD_OK) {
    char msg[256];
    ahd_last_error(msg, sizeof msg);
    /* ... */
}
ahd_x360_state s = {0};
s.buttons = AHD_X360_A;
ahd_x360_set_state(pad, &s);
ahd_x360_unplug(pad);
ahd_dock_close(dock);

The microphone is ahd_mic_plug, ahd_mic_write (interleaved int16_t frames), ahd_mic_get_status and ahd_mic_unplug. A complete example of both devices is examples/c/x360_demo.c. Linking the static library also needs these system libraries:

  • Windows (static C runtime, /MT; define AHD_STATIC): kernel32 ntdll userenv ws2_32 dbghelp synchronization
  • Linux: -lgcc_s -lutil -lrt -lpthread -lm -ldl -lc

Any program (sidecar process)

airhand-dock serve drives devices through a line protocol on stdin/stdout, so a program in any language can use it by spawning a process; closing stdin unplugs everything.

> hello
< ok 2 0.3.0 usbip-win2
> plug x360
< ok 1 1734-1 3 127.0.0.1:47240
> set 1 0x1000 0 255 0 32767 0 0
< event output 1 128 64 6 1
> plug mic name=My Microphone
< ok 2 1734-2 4 127.0.0.1:47240
> pcm 2 e80318fc...
> unplug 1
< ok

The full protocol is in docs/sidecar.md.

Integrating with Airhand

Airhand's host can use the Rust crate directly (same edition, windows-sys 0.61 like Airhand, no async runtime): plug an Xbox360 when a controller session asks for a gamepad, map the controller's gamepad input onto GamepadState, send Xbox360Output (rumble) back over the session, and drop the Plugged handle when the session ends. The controller's microphone goes into a Microphone the same way. On Windows this works from the host process running as SYSTEM; Dock::status drives the "install usbip-win2" hint. See docs/integration.md.

Repository layout

Path Contents
crates/airhand-dock The library: USB device model (usb), USB/IP protocol and link (usbip), OS backends (usbip-win2, vhci-hcd, uinput, export), devices (devices: Xbox 360 controller, microphone), Dock
crates/airhand-dock-ffi C ABI: airhand_dock.{dll,so,lib,a}, include/airhand_dock.h
crates/airhand-dock-cli The airhand-dock command: status, demo, serve
examples/c C example, also the C ABI test in CI
docs Architecture, sidecar protocol, integration

Adding devices

Keyboards, mice and cameras are planned. A device is an implementation of usb::UsbDevice (descriptors plus a few hooks, isochronous ones included); the USB/IP link, the backends, the dock and the C ABI do not change for it. See docs/architecture.md.

Security

  • Windows: the USB/IP server listens on loopback only and admits imports only from the kernel (the connection's owner must be the System process), so other local programs cannot read or take over the devices. DockOptions::restrict_importers turns this off for debugging.
  • Every dock uses a random USB/IP bus number, so re-attach attempts the driver keeps for an earlier (crashed) process never match a new device; such attempts are cancelled when they arrive.
  • The export backend serves anyone who can reach its address: keep it on loopback unless you mean it.

Building and testing

cargo test --workspace                     # unit tests + a USB/IP client over loopback TCP
cargo clippy --workspace --all-targets -- -D warnings

# Linux, against the real kernel (needs root and vhci-hcd): enumeration, input reports, rumble,
# unlink, unplug and latency, through both the socket pair and the TCP server path; the microphone
# bound by snd-usb-audio and recorded with arecord (alsa-utils)
sudo modprobe vhci-hcd
cargo test -p airhand-dock --test vhci_e2e --no-run   # prints "Executable tests/vhci_e2e.rs (<path>)"
sudo <path> --ignored --nocapture --test-threads=1

# Linux, the uinput backend: evdev events, ids, force feedback, unplug and latency
sudo modprobe uinput evdev
cargo test -p airhand-dock --test uinput_e2e --no-run
sudo <path> --ignored --nocapture --test-threads=1

Releases are built by .github/workflows/release.yml when a vX.Y.Z (or vX.Y.Z-rc.N) tag is pushed: Windows x64 / ARM64 and Linux x64 / arm64 archives plus SHA256SUMS.txt.

Commit messages

Conventional Commits, in English: type(scope): subject, e.g. feat(x360): report the player number, fix(windows): cancel stale re-attach attempts. Scopes: usb, usbip, windows, linux, uinput, x360, mic, ffi, cli, deps (or none).

Acknowledgements

  • usbip-win2 by Vadym Hrynchyshyn: the signed Windows USB/IP client this project builds on. Its IOCTL structures are mirrored (and tested) per release, and its issue #200 explained how class drivers age isochronous data.
  • VIIPER and GKMD showed that virtual controllers over usbip-win2 work, and were used to cross-check the Xbox 360 descriptors and the driver's request layouts. No code was copied.

License

MIT

About

Virtual USB devices over USB/IP that the OS sees as real hardware: a wired Xbox 360 controller and a USB microphone. Windows via usbip-win2; Linux via vhci-hcd, or uinput without root (controller only). Device layer of Airhand; Rust library, C API and sidecar CLI.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages