diff --git a/README.md b/README.md index 35a1e75..a5eace6 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ and forwards guest controllers back into it. | --- | --- | --- | | Receive guest input | XInput (RPT delivers guest pads to the focused window); optional, opt-in Steam Input when built with the Steamworks SDK | `coop_host.exe` | | Forward input to game | DLL injection + XInput hook (SafetyHook) — game sees *only* our pad | `coop_hook.dll` | -| Forward mouse + keyboard | Opt-in MKB subsystem: host streams its window's clicks/keys, the hook posts the matching window messages and synthesizes `GetAsyncKeyState`/`GetKeyboardState`/`GetCursorPos` for polling games | `coop_hook.dll` + `coop_host.exe` | +| Forward mouse + keyboard | Opt-in MKB subsystem: host streams its window's clicks/keys; the hook posts the matching window messages, synthesizes `GetAsyncKeyState`/`GetKeyboardState`/`GetCursorPos` for polling games, augments `IDirectInputDevice8::GetDeviceState` for **DirectInput** games, and synthesizes `WM_INPUT` + `GetRawInputData` for **Raw Input** games | `coop_hook.dll` + `coop_host.exe` | | Keep game running unfocused | Hook spoofs focus so the game polls while the host holds OS focus | `coop_hook.dll` | | Mirror video (default) | Windows Graphics Capture of the game window, letterboxed into the host window | `coop_host.exe` | | Mirror video (hooked) | Injected Present / OpenGL hook copies the backbuffer into a shared keyed-mutex texture the host samples (lower latency, no capture border) | `coop_hook.dll` + `coop_host.exe` | @@ -110,14 +110,6 @@ default** and covers anything the hooked path doesn't. ### Current Tasks -- **Mouse + keyboard forwarding for Raw Input / DirectInput games.** The MKB - subsystem forwards via window messages (`PostMessage`) plus synthesized - `GetAsyncKeyState` / `GetKeyboardState` / `GetCursorPos`, which covers message-loop - and polling games. Games that read keyboard/mouse via **Raw Input** (`WM_INPUT` / - `GetRawInputData`, e.g. Trails through Daybreak) or **DirectInput** - (`IDirectInputDevice8::GetDeviceState/GetDeviceData`) don't see it. Add hooks for - those paths to synthesize the forwarded input there too. - - **Validate the Vulkan backend against a real game.** Exercise the Vulkan capture path end-to-end on a shipping title — **Sphere Spectacle** (Steam appid 1123040, `start steam://rungameid/1123040`) — not just `coop_mock_game`. Cover **both** early-presence @@ -192,6 +184,13 @@ ctest --test-dir build -C Debug --output-on-failure - **`hook_selftest`** — in-process check of the IPC + XInput hook core (no game, no controller needed). +- **`dinput_hook_test`** — in-process self-test of the **DirectInput** forwarding path. Reuses + `mkb_hook.cpp`, installs the MKB hooks (which vtable-swap `IDirectInputDevice8::GetDeviceState` + via a kept-alive probe device), forwards a synthetic key + mouse button through the MKB ring, + pumps it, then creates a *real* DirectInput keyboard + mouse device and asserts `GetDeviceState` + returns the forwarded input (the key at its DIK scan-code, the left mouse button). Skips cleanly + if DirectInput can't acquire a device. (The Raw Input path is operator-validated against a real + game — an in-process WM_INPUT round-trip is too brittle to assert reliably.) - **`audio_ring_test`** — unit test of the shared audio ring (lock-free SPSC push/pop, wrap-around, format handshake, overrun/drop). No device needed. - **`audio_mix_test`** — unit test of the multi-stream mixer math (decode / sum / @@ -649,3 +648,17 @@ Non-obvious things that cost time and constrain the design: in-process XInput interception, which hides controllers from `XInputGetState` unless they're bound to the running appid's action set — defaulting to it silently broke forwarding. XInput is primary; Steam Input is opt-in. +- **Forwarding keyboard/mouse means covering three read paths, each differently.** Games read + keyboard/mouse three ways and a forwarder has to satisfy all of them from one synthesized state. + (1) **Message-loop** games get `PostMessage`d `WM_KEYDOWN`/`WM_*BUTTON*`. (2) **Polling** games + get synthesized `GetAsyncKeyState`/`GetKeyboardState`/`GetCursorPos`. (3) **DirectInput** games + call `IDirectInputDevice8::GetDeviceState` — a COM method, so it's hooked by **vtable swap, not + inline** (the x86 COM-prologue trap), reading the vtable from a kept-alive *probe* device we + create (the game made its devices before we injected, but all DI devices share one vtable); + dispatch on `cbData` (256 = keyboard `BYTE[256]` indexed by **DIK scan-code**, not VK — map with + `MapVirtualKey(VK_TO_VSC)`; `sizeof(DIMOUSESTATE)` = mouse). (4) **Raw Input** games read + `WM_INPUT` → `GetRawInputData`, but get **no `WM_INPUT` while unfocused** — so we *synthesize* it: + post `WM_INPUT` with `lParam` = the address of one of our `RAWINPUT` slots, and the hooked + `GetRawInputData` serves that slot's data back (`RID_HEADER` and `RID_INPUT`). Relative raw mouse + *movement* isn't in the position-based MKB event stream, so raw-input forwarding covers keys + + buttons, not free-look — a known limitation. diff --git a/hook/CMakeLists.txt b/hook/CMakeLists.txt index 4579e86..927dbc6 100644 --- a/hook/CMakeLists.txt +++ b/hook/CMakeLists.txt @@ -29,6 +29,7 @@ target_link_libraries(coop_hook PRIVATE user32 ole32 mmdevapi + dxguid d3d11 d3d9 dxgi) diff --git a/hook/src/mkb_hook.cpp b/hook/src/mkb_hook.cpp index 5fbdf2c..b1ede67 100644 --- a/hook/src/mkb_hook.cpp +++ b/hook/src/mkb_hook.cpp @@ -4,10 +4,14 @@ #include +#define DIRECTINPUT_VERSION 0x0800 +#include + #include #include "hook_guard.hpp" #include "hook_registry.hpp" +#include "vtable_hook.hpp" namespace coop::hook { @@ -36,6 +40,32 @@ int g_id_kbstate = -1; int g_id_cursor = -1; bool g_installed = false; +// --- DirectInput forwarding ------------------------------------------------- +// Many games read keyboard/mouse via IDirectInputDevice8::GetDeviceState instead of the polling +// APIs above. All DI devices share one vtable (same coclass), so a single vtable swap -- read from +// a kept-alive probe device -- intercepts the game's existing devices too (it may have created them +// before we injected). We must use a vtable swap, not an inline hook (the x86 COM-prologue trap). +VtableHook g_vh_di_getstate; +IDirectInput8W* g_di_probe = nullptr; +IDirectInputDevice8W* g_di_probe_kbd = nullptr; +int g_id_di_getstate = -1; +// IDirectInputDevice8 vtable: IUnknown 0-2, GetCapabilities 3, EnumObjects 4, GetProperty 5, +// SetProperty 6, Acquire 7, Unacquire 8, GetDeviceState 9, GetDeviceData 10. +constexpr unsigned kIdx_IDirectInputDevice8_GetDeviceState = 9; +std::atomic g_di_mouse_last_x{0}; // last forwarded cursor, for relative DI mouse deltas +std::atomic g_di_mouse_last_y{0}; +std::atomic g_di_mouse_primed{false}; + +// --- Raw Input forwarding --------------------------------------------------- +// Games that read via Raw Input (RegisterRawInputDevices + WM_INPUT -> GetRawInputData) get no +// WM_INPUT while unfocused, so we synthesize it: mkb_pump posts WM_INPUT with lParam = the address +// of a synthetic RAWINPUT slot, and this hook serves that slot's data when the game reads it back. +safetyhook::InlineHook g_hk_getrawinputdata; // user32!GetRawInputData +int g_id_rawinput = -1; +constexpr int kRawSlots = 64; // small ring of synthetic events (games consume WM_INPUT promptly) +RAWINPUT g_raw_slots[kRawSlots] = {}; +std::atomic g_raw_head{0}; + // --- Synthesized-state detours (let polling games see forwarded input) ------ SHORT WINAPI hk_GetAsyncKeyState(int vkey) @@ -85,6 +115,158 @@ BOOL WINAPI hk_GetCursorPos(LPPOINT pt) return r; } +// --- DirectInput GetDeviceState detour -------------------------------------- + +// Win32 virtual-key -> DirectInput key index (DIK_*, a set-1 scan code). Good for the common keys +// (letters/digits/WASD/space/enter); a few extended keys (arrows) differ by the extended bit. +BYTE vk_to_dik(int vk) +{ + return static_cast(MapVirtualKeyW(static_cast(vk), MAPVK_VK_TO_VSC) & 0xFF); +} + +using DI_GetDeviceStateFn = HRESULT(STDMETHODCALLTYPE*)(IDirectInputDevice8W*, DWORD, LPVOID); + +HRESULT STDMETHODCALLTYPE hk_DI_GetDeviceState(IDirectInputDevice8W* self, DWORD cb, LPVOID data) +{ + DetourGate::Guard guard(g_gate); + const HRESULT hr = g_vh_di_getstate.original()(self, cb, data); + if (FAILED(hr) || data == nullptr || !g_active.load(std::memory_order_relaxed)) + { + return hr; + } + hook_note_call(g_id_di_getstate); + if (cb == 256) // keyboard: BYTE[256] indexed by DIK (scan code); high bit = pressed + { + BYTE* keys = static_cast(data); + for (int vk = 0; vk < 256; ++vk) + { + if (g_key_down[vk].load(std::memory_order_relaxed)) + { + const BYTE dik = vk_to_dik(vk); + if (dik != 0) + { + keys[dik] |= 0x80; + } + } + } + } + else if (cb == sizeof(DIMOUSESTATE) || cb == sizeof(DIMOUSESTATE2)) // mouse (DIMOUSESTATE2 is a superset) + { + auto* m = static_cast(data); // the shared lead fields (lX/lY/lZ/rgbButtons) + if (g_have_cursor.load(std::memory_order_relaxed)) + { + const long x = g_cursor_x.load(std::memory_order_relaxed); + const long y = g_cursor_y.load(std::memory_order_relaxed); + if (g_di_mouse_primed.load(std::memory_order_relaxed)) // relative delta from our cursor + { + m->lX += x - g_di_mouse_last_x.load(std::memory_order_relaxed); + m->lY += y - g_di_mouse_last_y.load(std::memory_order_relaxed); + } + g_di_mouse_last_x.store(x, std::memory_order_relaxed); + g_di_mouse_last_y.store(y, std::memory_order_relaxed); + g_di_mouse_primed.store(true, std::memory_order_relaxed); + } + if (g_key_down[VK_LBUTTON].load(std::memory_order_relaxed)) + { + m->rgbButtons[0] |= 0x80; + } + if (g_key_down[VK_RBUTTON].load(std::memory_order_relaxed)) + { + m->rgbButtons[1] |= 0x80; + } + if (g_key_down[VK_MBUTTON].load(std::memory_order_relaxed)) + { + m->rgbButtons[2] |= 0x80; + } + } + return hr; +} + +// --- Raw Input GetRawInputData detour --------------------------------------- + +// True if `h` is one of our synthetic RAWINPUT handles (an address inside g_raw_slots). +bool is_our_raw(HRAWINPUT h) +{ + auto* p = reinterpret_cast(h); + return p >= &g_raw_slots[0] && p < &g_raw_slots[kRawSlots]; +} + +UINT WINAPI hk_GetRawInputData(HRAWINPUT hri, UINT cmd, LPVOID pData, PUINT pcbSize, UINT cbHeader) +{ + DetourGate::Guard guard(g_gate); + if (g_active.load(std::memory_order_relaxed) && is_our_raw(hri)) + { + hook_note_call(g_id_rawinput); + const RAWINPUT* ri = reinterpret_cast(hri); + const UINT body = ri->header.dwType == RIM_TYPEMOUSE ? sizeof(RAWMOUSE) : sizeof(RAWKEYBOARD); + const UINT full = sizeof(RAWINPUTHEADER) + body; + if (pcbSize == nullptr) + { + return static_cast(-1); + } + if (cmd == RID_HEADER) + { + if (pData == nullptr) + { + *pcbSize = sizeof(RAWINPUTHEADER); + return 0; + } + if (*pcbSize < sizeof(RAWINPUTHEADER)) + { + return static_cast(-1); + } + memcpy(pData, &ri->header, sizeof(RAWINPUTHEADER)); + return sizeof(RAWINPUTHEADER); + } + // RID_INPUT: the full header + body. + if (pData == nullptr) + { + *pcbSize = full; + return 0; + } + if (*pcbSize < full) + { + return static_cast(-1); + } + memcpy(pData, ri, full); + return full; + } + return g_hk_getrawinputdata.stdcall(hri, cmd, pData, pcbSize, cbHeader); +} + +// Post a synthetic Raw Input event to `hwnd` (a WM_INPUT carrying one of our g_raw_slots). +void post_raw_key(HWND hwnd, UINT vk, bool down) +{ + if (hwnd == nullptr || !g_hk_getrawinputdata) + { + return; + } + RAWINPUT& ri = g_raw_slots[g_raw_head.fetch_add(1, std::memory_order_relaxed) % kRawSlots]; + ZeroMemory(&ri, sizeof(ri)); + ri.header.dwType = RIM_TYPEKEYBOARD; + ri.header.dwSize = sizeof(RAWINPUTHEADER) + sizeof(RAWKEYBOARD); + ri.data.keyboard.MakeCode = static_cast(MapVirtualKeyW(vk, MAPVK_VK_TO_VSC)); + ri.data.keyboard.Flags = static_cast(down ? RI_KEY_MAKE : RI_KEY_BREAK); + ri.data.keyboard.VKey = static_cast(vk); + ri.data.keyboard.Message = down ? WM_KEYDOWN : WM_KEYUP; + PostMessageW(hwnd, WM_INPUT, RIM_INPUT, reinterpret_cast(&ri)); +} + +void post_raw_mouse(HWND hwnd, USHORT button_flags) +{ + if (hwnd == nullptr || !g_hk_getrawinputdata) + { + return; + } + RAWINPUT& ri = g_raw_slots[g_raw_head.fetch_add(1, std::memory_order_relaxed) % kRawSlots]; + ZeroMemory(&ri, sizeof(ri)); + ri.header.dwType = RIM_TYPEMOUSE; + ri.header.dwSize = sizeof(RAWINPUTHEADER) + sizeof(RAWMOUSE); + ri.data.mouse.usFlags = MOUSE_MOVE_RELATIVE; + ri.data.mouse.usButtonFlags = button_flags; + PostMessageW(hwnd, WM_INPUT, RIM_INPUT, reinterpret_cast(&ri)); +} + // --- Target window + message synthesis -------------------------------------- struct FindCtx @@ -184,6 +366,21 @@ void handle_mouse(const MkbEvent& ev, bool down, HWND hwnd) msg = down ? WM_MBUTTONDOWN : WM_MBUTTONUP; } PostMessageW(hwnd, msg, mouse_button_wparam(), MAKELPARAM(ev.x, ev.y)); + // Also feed Raw Input games (button event; relative move isn't in the MKB event stream). + USHORT rflags = 0; + if (ev.code == 0) + { + rflags = down ? RI_MOUSE_LEFT_BUTTON_DOWN : RI_MOUSE_LEFT_BUTTON_UP; + } + else if (ev.code == 1) + { + rflags = down ? RI_MOUSE_RIGHT_BUTTON_DOWN : RI_MOUSE_RIGHT_BUTTON_UP; + } + else + { + rflags = down ? RI_MOUSE_MIDDLE_BUTTON_DOWN : RI_MOUSE_MIDDLE_BUTTON_UP; + } + post_raw_mouse(hwnd, rflags); } void handle_wheel(const MkbEvent& ev, HWND hwnd) @@ -217,6 +414,50 @@ void install_user32_hook(HMODULE user32, const char* name, void* detour, safetyh } } +// Install the DirectInput GetDeviceState hook: build a kept-alive probe device (its vtable is +// shared by every DI device, including ones the game made before we injected) and swap the slot. +// Returns false (and is retried from mkb_pump) until dinput8.dll is loaded. COM must be initialized +// on the calling thread (the worker thread is). +bool install_dinput_hook() +{ + if (g_vh_di_getstate) + { + return true; + } + HMODULE di = GetModuleHandleW(L"dinput8.dll"); + if (di == nullptr) + { + return false; // not a DirectInput game (yet) + } + using PFN_DI8Create = HRESULT(WINAPI*)(HINSTANCE, DWORD, REFIID, LPVOID*, LPUNKNOWN); + auto create = reinterpret_cast(GetProcAddress(di, "DirectInput8Create")); + if (create == nullptr) + { + return false; + } + if (g_di_probe == nullptr) + { + if (FAILED(create(GetModuleHandleW(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8W, + reinterpret_cast(&g_di_probe), nullptr)) || + g_di_probe == nullptr) + { + return false; + } + } + if (g_di_probe_kbd == nullptr) + { + if (FAILED(g_di_probe->CreateDevice(GUID_SysKeyboard, &g_di_probe_kbd, nullptr)) || + g_di_probe_kbd == nullptr) + { + return false; + } + } + const bool ok = g_vh_di_getstate.install(g_di_probe_kbd, kIdx_IDirectInputDevice8_GetDeviceState, + reinterpret_cast(&hk_DI_GetDeviceState)); + hook_set_installed(g_id_di_getstate, ok); + return ok; +} + } // namespace bool install_mkb_hooks(IpcClient& ipc) @@ -232,6 +473,8 @@ bool install_mkb_hooks(IpcClient& ipc) g_id_async = hook_register("GetAsyncKeyState", HookSubsys_Mkb); g_id_kbstate = hook_register("GetKeyboardState", HookSubsys_Mkb); g_id_cursor = hook_register("GetCursorPos", HookSubsys_Mkb); + g_id_di_getstate = hook_register("IDirectInputDevice8::GetDeviceState", HookSubsys_Mkb); + g_id_rawinput = hook_register("GetRawInputData", HookSubsys_Mkb); } // Fresh synthesized state so a previous session leaves no stuck keys. @@ -248,6 +491,14 @@ bool install_mkb_hooks(IpcClient& ipc) install_user32_hook(user32, "GetKeyboardState", reinterpret_cast(&hk_GetKeyboardState), g_hk_kbstate, g_id_kbstate); install_user32_hook(user32, "GetCursorPos", reinterpret_cast(&hk_GetCursorPos), g_hk_cursor, g_id_cursor); + // Raw Input: synthesize WM_INPUT (in mkb_pump) + serve it from this hook, for games that read + // keyboard/mouse via GetRawInputData. GetRawInputData has a clean prologue -> inline hook is OK. + install_user32_hook(user32, "GetRawInputData", reinterpret_cast(&hk_GetRawInputData), + g_hk_getrawinputdata, g_id_rawinput); + // DirectInput: vtable-swap GetDeviceState (best-effort -- dinput8.dll may load later, retried + // from mkb_pump). The probe is built once and kept alive (avoids COM churn on a re-enable). + g_di_mouse_primed.store(false, std::memory_order_relaxed); + install_dinput_hook(); g_active.store(true, std::memory_order_release); hook_set_installed(g_id_pump, true); @@ -266,7 +517,11 @@ void remove_mkb_hooks() g_hk_async = {}; // InlineHook destructor restores the original bytes -> no new detour starts g_hk_kbstate = {}; g_hk_cursor = {}; - g_gate.drain(); // wait for any in-flight polling detour before clearing the synth state + g_hk_getrawinputdata = {}; // restore GetRawInputData + g_vh_di_getstate.remove(); // restore the DI GetDeviceState slot (probe kept alive for re-enable) + g_gate.drain(); // wait for any in-flight polling / DI / raw detour before clearing state + hook_set_installed(g_id_di_getstate, false); + hook_set_installed(g_id_rawinput, false); for (int vk = 0; vk < 256; ++vk) { g_key_down[vk].store(false, std::memory_order_relaxed); // no stuck keys @@ -286,6 +541,10 @@ void mkb_pump(IpcClient& ipc) { return; } + if (!g_vh_di_getstate) + { + install_dinput_hook(); // dinput8.dll can load after we installed; keep retrying cheaply + } HWND hwnd = static_cast(g_target.load(std::memory_order_relaxed)); if (hwnd == nullptr || !IsWindow(hwnd)) @@ -306,6 +565,7 @@ void mkb_pump(IpcClient& ipc) { PostMessageW(hwnd, WM_KEYDOWN, ev.code, key_lparam(ev.code, false)); } + post_raw_key(hwnd, ev.code, true); // also feed Raw Input games break; case Mkb_KeyUp: set_key(ev.code, false); @@ -313,6 +573,7 @@ void mkb_pump(IpcClient& ipc) { PostMessageW(hwnd, WM_KEYUP, ev.code, key_lparam(ev.code, true)); } + post_raw_key(hwnd, ev.code, false); break; case Mkb_Char: if (hwnd != nullptr) diff --git a/hook/src/vtable_hook.hpp b/hook/src/vtable_hook.hpp new file mode 100644 index 0000000..b4b8bb4 --- /dev/null +++ b/hook/src/vtable_hook.hpp @@ -0,0 +1,68 @@ +// Hook a single COM vtable slot by overwriting its function pointer; the original is called +// through the saved pointer. We use this instead of SafetyHook's inline hooks for COM methods +// because, on x86, MMDevApi/AudioSes/DirectInput prologues use dynamic stack alignment +// (`and esp,-8`) with EBP-relative argument access, which SafetyHook's trampoline relocation +// mishandles -> the original runs with garbage args and faults. Swapping the vtable entry leaves +// the original code untouched, so it runs with a pristine stack regardless of prologue shape. +// Every instance of a COM coclass shares one vtable, so a single swap intercepts all of them. +// See the project's stdcall-x86 note. (audio_hook.cpp has its own equivalent; this is the shared +// copy for the input-side COM hooks.) +#pragma once + +#include + +namespace coop::hook +{ + +class VtableHook +{ +public: + bool install(void* com_object, unsigned index, void* detour) + { + if (m_vtable != nullptr) + { + return true; // already installed (shared vtable covers every instance) + } + auto** vtable = *reinterpret_cast(com_object); + DWORD old_protect = 0; + if (!VirtualProtect(&vtable[index], sizeof(void*), PAGE_READWRITE, &old_protect)) + { + return false; + } + m_original = vtable[index]; + vtable[index] = detour; // aligned pointer store -> atomic vs. a concurrent caller + VirtualProtect(&vtable[index], sizeof(void*), old_protect, &old_protect); + m_vtable = vtable; + m_index = index; + return true; + } + + void remove() + { + if (m_vtable == nullptr) + { + return; + } + DWORD old_protect = 0; + if (VirtualProtect(&m_vtable[m_index], sizeof(void*), PAGE_READWRITE, &old_protect)) + { + m_vtable[m_index] = m_original; + VirtualProtect(&m_vtable[m_index], sizeof(void*), old_protect, &old_protect); + } + m_vtable = nullptr; + // Keep m_original valid: a detour already running on the game's thread may still call + // original() after we restore the slot. The original lives in the loaded module, so the + // pointer stays valid; a re-install re-reads it. + m_index = 0; + } + + template Fn original() const { return reinterpret_cast(m_original); } + explicit operator bool() const { return m_vtable != nullptr; } + +private: + void** m_vtable = nullptr; + unsigned m_index = 0; + void* m_original = nullptr; +}; + +} // namespace coop::hook diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index df992c4..e06c5c1 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -14,6 +14,24 @@ target_link_libraries(hook_selftest PRIVATE add_test(NAME hook_selftest COMMAND hook_selftest) +# In-process self-test for the DirectInput forwarding path: reuses mkb_hook.cpp, installs the MKB +# hooks (which vtable-swap IDirectInputDevice8::GetDeviceState), forwards a synthetic key + mouse +# button through the ring, then creates a real DI keyboard + mouse device and asserts GetDeviceState +# returns the forwarded input. Skips cleanly if DirectInput can't acquire a device. +add_executable(dinput_hook_test + dinput_hook_test.cpp + ${CMAKE_SOURCE_DIR}/hook/src/mkb_hook.cpp + ${CMAKE_SOURCE_DIR}/hook/src/hook_registry.cpp) +target_include_directories(dinput_hook_test PRIVATE ${CMAKE_SOURCE_DIR}/hook/src) +target_link_libraries(dinput_hook_test PRIVATE + coop_common + safetyhook::safetyhook + user32 + dinput8 + dxguid + ole32) +add_test(NAME dinput_hook_test COMMAND dinput_hook_test) + # Unit test for the shared audio ring (lock-free SPSC push/pop, wrap-around, # format handshake, overrun policy). Header-only, no hook or audio device. add_executable(audio_ring_test audio_ring_test.cpp) @@ -242,6 +260,7 @@ add_test(NAME ui_fit_test COMMAND ui_fit_test) # test's "coop_tone.exe alongside me" lookup keeps working. coop_output_subdir(tests hook_selftest + dinput_hook_test audio_ring_test mkb_ring_test mkb_map_test diff --git a/tests/dinput_hook_test.cpp b/tests/dinput_hook_test.cpp new file mode 100644 index 0000000..2ef5b69 --- /dev/null +++ b/tests/dinput_hook_test.cpp @@ -0,0 +1,158 @@ +// In-process self-test for the DirectInput forwarding path of the MKB subsystem. +// +// Drives the REAL shipping code (mkb_hook.cpp): creates the IPC block + MKB ring, installs the MKB +// hooks (which vtable-swap IDirectInputDevice8::GetDeviceState via a probe device), pushes a +// synthetic key + mouse-button event through the ring, pumps it (so the hook's synthesized state is +// set), then creates its *own* DirectInput keyboard + mouse device and calls GetDeviceState -- and +// asserts the forwarded input shows up in the returned device state. This process plays host + game. +// Skips cleanly if DirectInput can't acquire a device (e.g. no input stack on a CI box). +#include +#include + +#include + +#include + +#define DIRECTINPUT_VERSION 0x0800 +#include + +#include "coop/protocol.hpp" +#include "coop/shared_memory.hpp" +#include "ipc_client.hpp" +#include "mkb_hook.hpp" + +using namespace coop; + +namespace +{ +int g_failures = 0; +void check(bool ok, const char* what) +{ + std::printf("%s %s\n", ok ? " ok:" : "FAIL:", what); + if (!ok) + { + ++g_failures; + } +} + +// A hidden window so DirectInput devices can SetCooperativeLevel/Acquire. +HWND make_window() +{ + WNDCLASSEXW wc{}; + wc.cbSize = sizeof(wc); + wc.lpfnWndProc = DefWindowProcW; + wc.hInstance = GetModuleHandleW(nullptr); + wc.lpszClassName = L"coop_dinput_test"; + RegisterClassExW(&wc); + return CreateWindowExW(0, wc.lpszClassName, L"", WS_OVERLAPPEDWINDOW, 0, 0, 16, 16, nullptr, nullptr, + wc.hInstance, nullptr); +} + +// Create + acquire a DI device of `kind` (GUID_SysKeyboard / GUID_SysMouse) with `fmt`. Returns null +// on any failure (treated as a skip). +IDirectInputDevice8W* make_device(IDirectInput8W* di, const GUID& kind, const DIDATAFORMAT* fmt, HWND hwnd) +{ + IDirectInputDevice8W* dev = nullptr; + if (FAILED(di->CreateDevice(kind, &dev, nullptr)) || dev == nullptr) + { + return nullptr; + } + if (FAILED(dev->SetDataFormat(fmt)) || + FAILED(dev->SetCooperativeLevel(hwnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)) || FAILED(dev->Acquire())) + { + dev->Release(); + return nullptr; + } + return dev; +} +} // namespace + +int main() +{ + const bool com = SUCCEEDED(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED)); + + // Host side: the IPC block + a couple of forwarded events. + SharedMemory shm; + if (!shm.create(shared_memory_name(GetCurrentProcessId()), sizeof(SharedBlock))) + { + std::printf("Could not create shared memory -- skipping.\n"); + return 0; + } + auto* block = shm.as(); + block->version = kProtocolVersion; + block->sequence.store(0, std::memory_order_relaxed); + block->magic = kProtocolMagic; + + hook::IpcClient ipc; + check(ipc.connect(10, 5), "IPC client connect"); + check(hook::install_mkb_hooks(ipc), "install MKB hooks"); + + // Forward 'A' down and a left-mouse-button down, then pump them into the hook's synth state. + const UINT vk = 'A'; + MkbEvent key{Mkb_KeyDown, vk, 0, 0}; + MkbEvent mouse{Mkb_MouseDown, 0 /*left*/, 100, 80}; + push_mkb_event(block->mkb, key); + push_mkb_event(block->mkb, mouse); + hook::mkb_pump(ipc); + + HWND hwnd = make_window(); + + IDirectInput8W* di = nullptr; + if (FAILED(DirectInput8Create(GetModuleHandleW(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8W, + reinterpret_cast(&di), nullptr)) || + di == nullptr) + { + std::printf("DirectInput8Create failed -- skipping.\n"); + hook::remove_mkb_hooks(); + return 0; + } + + // Keyboard: GetDeviceState must show our forwarded key (at its DIK = scan code). + if (IDirectInputDevice8W* kbd = make_device(di, GUID_SysKeyboard, &c_dfDIKeyboard, hwnd)) + { + BYTE keys[256] = {}; + const HRESULT hr = kbd->GetDeviceState(sizeof(keys), keys); + const BYTE dik = static_cast(MapVirtualKeyW(vk, MAPVK_VK_TO_VSC) & 0xFF); + std::printf(" keyboard GetDeviceState hr=0x%08lX dik=0x%02X state=0x%02X\n", + static_cast(hr), dik, keys[dik]); + check(SUCCEEDED(hr), "keyboard GetDeviceState succeeded"); + check((keys[dik] & 0x80) != 0, "forwarded 'A' appears in the DirectInput keyboard state"); + kbd->Unacquire(); + kbd->Release(); + } + else + { + std::printf(" keyboard device unavailable -- skipping keyboard assertion.\n"); + } + + // Mouse: GetDeviceState must show our forwarded left button. + if (IDirectInputDevice8W* ms = make_device(di, GUID_SysMouse, &c_dfDIMouse, hwnd)) + { + DIMOUSESTATE m{}; + const HRESULT hr = ms->GetDeviceState(sizeof(m), &m); + std::printf(" mouse GetDeviceState hr=0x%08lX btn0=0x%02X\n", static_cast(hr), + static_cast(static_cast(m.rgbButtons[0]))); + check(SUCCEEDED(hr), "mouse GetDeviceState succeeded"); + check((m.rgbButtons[0] & 0x80) != 0, "forwarded left button appears in the DirectInput mouse state"); + ms->Unacquire(); + ms->Release(); + } + else + { + std::printf(" mouse device unavailable -- skipping mouse assertion.\n"); + } + + di->Release(); + hook::remove_mkb_hooks(); + if (hwnd != nullptr) + { + DestroyWindow(hwnd); + } + if (com) + { + CoUninitialize(); + } + + std::printf(g_failures == 0 ? "PASS dinput_hook_test\n" : "FAILED dinput_hook_test (%d)\n", g_failures); + return g_failures == 0 ? 0 : 1; +}