Skip to content

Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.

C++

feat(moonlight): input for a Moonlight session (S3)

Veyra Goal Agente3967fa3cfa3
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 290c2e57..4260c031 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -787,6 +787,9 @@ if(VEYRA_BUILD_QML_UI AND Qt6_FOUND)
# AUTOMOC: QmlPlayerBridge declares Q_OBJECT, so its meta-object has to be
# generated. Without this the library links but every signal is unresolved.
set_target_properties(veyra_qml_bridge PROPERTIES AUTOMOC ON)
+ if(VEYRA_ENABLE_MOONLIGHT)
+ target_sources(veyra_qml_bridge PRIVATE src/ui/MoonlightInputCapture.cpp include/veyra/ui/MoonlightInputCapture.h)
+ endif()
target_compile_features(veyra_qml_bridge PRIVATE cxx_std_20)
target_include_directories(veyra_qml_bridge PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/src ${FFMPEG_INCLUDE_DIRS}
${CMAKE_CURRENT_SOURCE_DIR}/apps/veyra/ui)
diff --git a/docs/MOONLIGHT_EXECUTION_2026-10-01.md b/docs/MOONLIGHT_EXECUTION_2026-10-01.md
index 77fa74e1..5b039b19 100644
--- a/docs/MOONLIGHT_EXECUTION_2026-10-01.md
+++ b/docs/MOONLIGHT_EXECUTION_2026-10-01.md
@@ -13,7 +13,7 @@
| S0 | 依赖固定(`scripts/moonlight/dependency-lock.json` + 校验脚本)、CMake 开关、许可记录 | 完成 |
| S1 | 协议层(Qt 无关):XML、加密、HTTP(S)、主机请求、配对、身份存储 | 完成,离线测试 69 项通过 |
| S2 | 会话来源:`LiStartConnection`、视频解码、音频、遥测、引擎接入 | 代码完成(S2a),只做了编译与离线检查,未连过任何主机 |
-| S3 | 输入:手柄、键鼠捕获、保留键 | 未开始 |
+| S3 | 输入:手柄、键鼠捕获、保留键 | 代码完成,转换逻辑有离线测试(130 项),未连过主机;接入界面在 S4 |
| S4 | 前端:首页卡片、PC 串流页、配对对话框、设置、串流中 UI | 未开始 |
| S5 | 质量:HDR、AV1、丢包与重连、稳定性 | 未开始 |
@@ -51,6 +51,16 @@
- 验证:`veyra_moonlight_protocol_tests` 87 项通过;整个 `veyra_qml_ui` 链接成功;`veyra_qml_data_tests`、`veyra_qml_easing_tests`、`veyra_ui_contract_tests`、`veyra_effect_chain_tests`、`veyra_repair_contract_tests`、`veyra_preset_library_tests` 通过。
- **未验证**:任何真实串流(连接、解码、音频、HDR、丢包恢复);解码流水线还没有离线单测;`connect()` 会阻塞引擎线程直到启动完成,首帧最多等 20 秒;软解回落只出 8 位,HDR 需要硬解;手柄震动与输入是空实现(S3);断线重连未做(S5)。
+## S3 记录(输入)
+
+- 手柄:沿用 PS5 用的 SDL 手柄读取(`ControllerInput`),`moonlight::mapPad` 转成 GameStream 帧:按位置映射(南键=A),摇杆 Y 取反(SDL 向下为正,主机向上为正;-32768 不溢出),扳机 0–255;状态变化才发送,失焦或设备丢失发全零以释放。只有 1 号手柄;首次发送前发一次到达事件(Xbox 类型,模拟量扳机 + 震动),旧主机回"不支持"也能工作。
+- 震动:主机的 rumble 回调存下来,`takeFeedback()` 交给 SDL;因为主机只在变化时通知、SDL 的震动有时长,非零值每 2 秒重发一次。
+- 键鼠:`moonlight::InputRouter` 把窗口消息转成主机事件(Win32 虚拟键码加 0x8000;Shift/Ctrl/Alt 按扫描码与扩展位分左右;关闭 Num Lock 的小键盘导航键按小键盘键发送;字符消息与 Alt 菜单被吞掉;长按重复由主机自己处理)。`MoonlightInputCapture`(Qt)用原生事件过滤器在 Qt 之前接管,鼠标用原始相对位移,光标隐藏并限制在窗口内,失焦自动释放并让主机松开所有键、鼠标键与手柄。
+- 保留键:Ctrl+Alt+Shift+Z 释放捕获,+Q 结束串流,+S 切换统计;这些键不会发给主机。
+- 未捕获:Windows 键、Alt+Tab、Ctrl+Alt+Del 仍归系统(Moonlight 客户端用低级钩子,这里先不用)。
+- 不含:陀螺仪与触摸板、电池状态、扳机震动、手柄退出组合键、多手柄。
+- 发送都在 `libMutex` 下检查 `streaming`,和 `LiStopConnection` 不会重叠。
+
## 下一步
S3 输入(手柄、键鼠、保留键)与 S4 前端(桥接接口、主机与应用列表、配对对话框、串流页与设置)。
diff --git a/include/veyra/engine/EngineController.h b/include/veyra/engine/EngineController.h
index 4f33ca7d..73cffef9 100644
--- a/include/veyra/engine/EngineController.h
+++ b/include/veyra/engine/EngineController.h
@@ -133,6 +133,14 @@ public:
#endif
#ifdef VEYRA_ENABLE_MOONLIGHT
void openMoonlight(HWND, source::MoonlightConnectDesc, PlayerOptions);
+ // Input for the running Moonlight session; all are no-ops when none is streaming.
+ void moonlightController(const remoteplay::ControllerState&);
+ remoteplay::ControllerFeedback moonlightFeedback();
+ void moonlightKey(uint32_t virtualKey, uint32_t scanCode, bool extended, bool down);
+ void moonlightMouseMove(int dx, int dy);
+ void moonlightMouseButton(int button, bool down);
+ void moonlightScroll(int delta, bool horizontal);
+ void moonlightReleaseInput();
#endif
void stop();
void comparison(int mode,bool base,float split=.5f){comparisonMode_=mode;comparisonBase_=base;comparisonSplit_=std::clamp(split,0.0f,1.0f);}
diff --git a/include/veyra/moonlight/InputMap.h b/include/veyra/moonlight/InputMap.h
new file mode 100644
index 00000000..fcfaf399
--- /dev/null
+++ b/include/veyra/moonlight/InputMap.h
@@ -0,0 +1,156 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Pure input translation for a Moonlight session: SDL gamepad state to the
+// GameStream pad frame, Win32 key messages to the codes the host expects, and the
+// reserved hotkeys that are never forwarded. No library calls here, so it can be
+// tested offline; the session source static_asserts the constants against
+// moonlight-common-c.
+#pragma once
+#include <algorithm>
+#include <cstdint>
+
+#include "veyra/remoteplay/Types.h"
+
+namespace veyra::moonlight {
+
+// Button flags of LiSendMultiControllerEvent (Xbox layout).
+constexpr uint32_t kPadUp = 0x0001, kPadDown = 0x0002, kPadLeft = 0x0004, kPadRight = 0x0008;
+constexpr uint32_t kPadStart = 0x0010, kPadBack = 0x0020, kPadLeftStick = 0x0040, kPadRightStick = 0x0080;
+constexpr uint32_t kPadLeftBumper = 0x0100, kPadRightBumper = 0x0200, kPadGuide = 0x0400;
+constexpr uint32_t kPadA = 0x1000, kPadB = 0x2000, kPadX = 0x4000, kPadY = 0x8000;
+constexpr uint32_t kPadTouchpad = 0x100000, kPadMisc = 0x200000;
+
+struct PadFrame {
+ uint32_t buttons = 0;
+ uint8_t leftTrigger = 0, rightTrigger = 0;
+ int16_t leftX = 0, leftY = 0, rightX = 0, rightY = 0;
+ bool operator==(const PadFrame&) const = default;
+};
+
+// GameStream sticks are "up is positive"; SDL's are "down is positive".
+inline int16_t flipAxis(int16_t value) { return value == INT16_MIN ? INT16_MAX : int16_t(-value); }
+
+// The positional layout is kept: the south face button is A whatever is printed on it.
+// A frame from an unfocused or lost device is all zeros, which releases everything.
+inline PadFrame mapPad(const remoteplay::ControllerState& state) {
+ PadFrame frame;
+ if (!state.inputActive) return frame;
+ using B = remoteplay::ControllerState;
+ struct Pair { uint32_t from, to; };
+ static constexpr Pair table[] = {
+ {B::Cross, kPadA}, {B::Circle, kPadB}, {B::Square, kPadX}, {B::Triangle, kPadY},
+ {B::Left, kPadLeft}, {B::Right, kPadRight}, {B::Up, kPadUp}, {B::Down, kPadDown},
+ {B::L1, kPadLeftBumper}, {B::R1, kPadRightBumper}, {B::L3, kPadLeftStick}, {B::R3, kPadRightStick},
+ {B::Options, kPadStart}, {B::Share, kPadBack}, {B::PS, kPadGuide}, {B::Touchpad, kPadTouchpad},
+ };
+ for (const auto& pair : table)
+ if (state.buttons & pair.from) frame.buttons |= pair.to;
+ frame.leftTrigger = state.l2;
+ frame.rightTrigger = state.r2;
+ frame.leftX = state.leftX;
+ frame.leftY = flipAxis(state.leftY);
+ frame.rightX = state.rightX;
+ frame.rightY = flipAxis(state.rightY);
+ return frame;
+}
+
+// --- keyboard ---------------------------------------------------------------------------
+
+constexpr uint8_t kModShift = 0x01, kModCtrl = 0x02, kModAlt = 0x04, kModMeta = 0x08;
+
+// The host takes Windows virtual-key codes with bit 15 set. The plain VK_SHIFT / VK_CONTROL /
+// VK_MENU that WM_KEYDOWN reports are resolved to their left and right keys, and the keypad
+// keys that a Num Lock-off keyboard reports as navigation keys are sent as the keypad keys
+// they are (extended navigation keys stay navigation keys).
+// Bit 15 marks a Windows virtual-key code.
+constexpr int16_t hostCode(uint32_t vk) { return int16_t(uint16_t(0x8000u | vk)); }
+
+struct HostKey {
+ int16_t code = 0;
+ uint8_t modifier = 0; // which modifier this key is, if any
+};
+
+inline HostKey hostKey(uint32_t vk, uint32_t scanCode, bool extended) {
+ switch (vk) {
+ case 0x10: return scanCode == 0x36 ? HostKey{hostCode(0xA1), kModShift} : HostKey{hostCode(0xA0), kModShift};
+ case 0xA0: return {hostCode(0xA0), kModShift};
+ case 0xA1: return {hostCode(0xA1), kModShift};
+ case 0x11: return extended ? HostKey{hostCode(0xA3), kModCtrl} : HostKey{hostCode(0xA2), kModCtrl};
+ case 0xA2: return {hostCode(0xA2), kModCtrl};
+ case 0xA3: return {hostCode(0xA3), kModCtrl};
+ case 0x12: return extended ? HostKey{hostCode(0xA5), kModAlt} : HostKey{hostCode(0xA4), kModAlt};
+ case 0xA4: return {hostCode(0xA4), kModAlt};
+ case 0xA5: return {hostCode(0xA5), kModAlt};
+ case 0x5B: return {hostCode(0x5B), kModMeta};
+ case 0x5C: return {hostCode(0x5C), kModMeta};
+ default: break;
+ }
+ if (!extended) {
+ switch (vk) {
+ case 0x2D: return {hostCode(0x60), 0}; // Insert -> Numpad0
+ case 0x23: return {hostCode(0x61), 0}; // End -> Numpad1
+ case 0x28: return {hostCode(0x62), 0}; // Down -> Numpad2
+ case 0x22: return {hostCode(0x63), 0}; // PageDn -> Numpad3
+ case 0x25: return {hostCode(0x64), 0}; // Left -> Numpad4
+ case 0x0C: return {hostCode(0x65), 0}; // Clear -> Numpad5
+ case 0x27: return {hostCode(0x66), 0}; // Right -> Numpad6
+ case 0x24: return {hostCode(0x67), 0}; // Home -> Numpad7
+ case 0x26: return {hostCode(0x68), 0}; // Up -> Numpad8
+ case 0x21: return {hostCode(0x69), 0}; // PageUp -> Numpad9
+ case 0x2E: return {hostCode(0x6E), 0}; // Delete -> Decimal
+ default: break;
+ }
+ }
+ return {hostCode((vk & 0xFF)), 0};
+}
+
+// Keys held on the host, so they can all be released when capture ends.
+class HeldKeys {
+public:
+ // Returns false for a repeat of a key that is already down (auto-repeat is the host's job).
+ bool press(int16_t code, uint8_t modifier) {
+ for (int i = 0; i < count_; ++i)
+ if (codes_[i] == code) return false;
+ if (count_ < kMax) { codes_[count_] = code; mods_[count_] = modifier; ++count_; }
+ if (modifier) held_ |= modifier;
+ return true;
+ }
+ bool release(int16_t code) {
+ for (int i = 0; i < count_; ++i) {
+ if (codes_[i] != code) continue;
+ codes_[i] = codes_[count_ - 1]; mods_[i] = mods_[count_ - 1]; --count_;
+ held_ = 0;
+ for (int k = 0; k < count_; ++k) held_ |= mods_[k];
+ return true;
+ }
+ return false;
+ }
+ uint8_t modifiers() const { return held_; }
+ int count() const { return count_; }
+ int16_t at(int index) const { return codes_[index]; }
+ void clear() { count_ = 0; held_ = 0; }
+private:
+ static constexpr int kMax = 32;
+ int16_t codes_[kMax]{};
+ uint8_t mods_[kMax]{};
+ int count_ = 0;
+ uint8_t held_ = 0;
+};
+
+// Ctrl+Alt+Shift+<key> is handled by the app and never sent to the host.
+enum class Reserved { None, ReleaseCapture, Quit, ToggleStats };
+
+inline Reserved reservedHotkey(uint32_t vk, uint8_t modifiers) {
+ constexpr uint8_t all = kModShift | kModCtrl | kModAlt;
+ if ((modifiers & all) != all) return Reserved::None;
+ switch (vk) {
+ case 'Z': return Reserved::ReleaseCapture;
+ case 'Q': return Reserved::Quit;
+ case 'S': return Reserved::ToggleStats;
+ default: return Reserved::None;
+ }
+}
+
+// A raw mouse delta can exceed what one host event carries; split it.
+inline int16_t clampDelta(long value) { return int16_t(std::clamp<long>(value, -32767, 32767)); }
+
+} // namespace veyra::moonlight
diff --git a/include/veyra/moonlight/InputRouter.h b/include/veyra/moonlight/InputRouter.h
new file mode 100644
index 00000000..5aa1614a
--- /dev/null
+++ b/include/veyra/moonlight/InputRouter.h
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: GPL-3.0-only
+// Turns the Win32 input messages of a captured window into host input events. No Qt and no
+// library calls: events go to an InputSink, so the whole translation (key codes, modifier
+// tracking, reserved hotkeys, buttons, wheel) is tested with synthesized messages.
+#pragma once
+#include <windows.h>
+#include <windowsx.h>
+
+#include <cstdint>
+
+#include "veyra/moonlight/InputMap.h"
+
+namespace veyra::moonlight {
+
+class InputSink {
+public:
+ virtual ~InputSink() = default;
+ virtual void key(uint32_t virtualKey, uint32_t scanCode, bool extended, bool down) = 0;
+ virtual void mouseMove(int dx, int dy) = 0;
+ virtual void mouseButton(int button, bool down) = 0; // 1 left, 2 middle, 3 right, 4 X1, 5 X2
+ virtual void scroll(int delta, bool horizontal) = 0;
+};
+
+class InputRouter {
+public:
+ explicit InputRouter(InputSink& sink) : sink_(sink) {}
+
+ // True when the message was consumed (it must not reach the UI underneath).
+ bool message(UINT msg, WPARAM wParam, LPARAM lParam) {
+ switch (msg) {
+ case WM_KEYDOWN: case WM_SYSKEYDOWN: return key(wParam, lParam, true);
+ case WM_KEYUP: case WM_SYSKEYUP: return key(wParam, lParam, false);
+ case WM_CHAR: case WM_SYSCHAR: case WM_DEADCHAR: case WM_SYSDEADCHAR: case WM_UNICHAR: case WM_IME_CHAR:
+ return true; // typed text reaches the host as key events, not as characters
+ case WM_SYSCOMMAND:
+ return (wParam & 0xFFF0) == SC_KEYMENU; // Alt or Alt+Space must not open the window menu
+ case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: return button(1, true);
+ case WM_LBUTTONUP: return button(1, false);
+ case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: return button(2, true);
+ case WM_MBUTTONUP: return button(2, false);
+ case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: return button(3, true);
+ case WM_RBUTTONUP: return button(3, false);
+ case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: return button(GET_XBUTTON_WPARAM(wParam) == XBUTTON1 ? 4 : 5, true);
+ case WM_XBUTTONUP: return button(GET_XBUTTON_WPARAM(wParam) == XBUTTON1 ? 4 : 5, false);
+ case WM_MOUSEWHEEL: sink_.scroll(GET_WHEEL_DELTA_WPARAM(wParam), false); return true;
+ case WM_MOUSEHWHEEL: sink_.scroll(GET_WHEEL_DELTA_WPARAM(wParam), true); return true;
+ case WM_MOUSEMOVE: return true; // movement comes from raw input (relative, unaccelerated by the window)
+ default: return false;
+ }
+ }
+
+ // Relative movement from a WM_INPUT mouse report.
+ void rawMouse(long dx, long dy) { sink_.mouseMove(int(dx), int(dy)); }
+
+ // Set when the last key press was one of the app's own hotkeys; cleared by taking it.
+ Reserved takeReserved() {
+ const Reserved r = reserved_;
+ reserved_ = Reserved::None;
+ return r;
+ }
+
+ // Forget what is held (capture ended; the session releases the host side itself).
+ void reset() { held_.clear(); reserved_ = Reserved::None; }
+
+private:
+ bool key(WPARAM wParam, LPARAM lParam, bool down) {
+ const uint32_t vk = uint32_t(wParam);
+ const uint32_t scan = uint32_t((lParam >> 16) & 0xFF);
+ const bool extended = ((lParam >> 24) & 1) != 0;
+ const HostKey host = hostKey(vk, scan, extended);
+ if (down) {
+ if (vk != 0x10 && vk != 0x11 && vk != 0x12) { // a modifier alone is never a hotkey
+ const Reserved r = reservedHotkey(vk, held_.modifiers());
+ if (r != Reserved::None) { reserved_ = r; swallowedUp_ = vk; return true; }
+ }
+ held_.press(host.code, host.modifier);
+ } else {
+ if (swallowedUp_ == vk) { swallowedUp_ = 0; return true; } // the matching key-up of a hotkey
+ held_.release(host.code);
+ }
+ sink_.key(vk, scan, extended, down);
+ return true;
+ }
+
+ bool button(int which, bool down) {
+ sink_.mouseButton(which, down);
+ return true;
+ }
+
+ InputSink& sink_;
+ HeldKeys held_;
+ Reserved reserved_ = Reserved::None;
+ uint32_t swallowedUp_ = 0;
+};
+
+} // namespace veyra::moonlight
diff --git a/include/veyra/source/MoonlightSessionSource.h b/include/veyra/source/MoonlightSessionSource.h
index 38767d5e..fe7fdfde 100644
--- a/include/veyra/source/MoonlightSessionSource.h
+++ b/include/veyra/source/MoonlightSessionSource.h
@@ -21,7 +21,9 @@
#include <thread>
#include "veyra/moonlight/Client.h"
+#include "veyra/moonlight/InputMap.h"
#include "veyra/moonlight/StreamConfig.h"
+#include "veyra/remoteplay/Types.h"
#include "veyra/sink/CaptureAudioSession.h"
#include "veyra/source/IFrameSource.h"
@@ -111,6 +113,20 @@ public:
void videoPresented(double ptsMs, int64_t host100ns);
void videoReset(bool resetAudio = true) { audio_.videoReset(resetAudio); }
+ // --- input: callable from any thread, ignored unless the stream is up ---------------------
+ // Controller 0 only. The pad state is sent when it changes; a device or focus loss (an
+ // inactive state) releases everything on the host.
+ void controller(const remoteplay::ControllerState& state);
+ // Rumble the host asked for (and the last non-zero value again every 2 s, since the host
+ // only reports changes and SDL rumble has to be renewed).
+ remoteplay::ControllerFeedback takeFeedback();
+ void keyboard(uint32_t virtualKey, uint32_t scanCode, bool extended, bool down);
+ void mouseMove(int dx, int dy);
+ void mouseButton(int button, bool down); // 1 left, 2 middle, 3 right, 4 X1, 5 X2
+ void scroll(int delta, bool horizontal); // WHEEL_DELTA units (120 per notch)
+ // Releases every key, mouse button and the pad on the host (capture lost, focus lost, end).
+ void releaseInput();
+
// The C callbacks of moonlight-common-c land here (static trampolines in the .cpp).
struct Callbacks;
diff --git a/include/veyra/ui/MoonlightInputCapture.h b/include/veyra/ui/MoonlightInputCapture.h
new file mode 100644
index 00000000..2a9a4750
--- /dev/null
+++ b/include/veyra/ui/MoonlightInputCapture.h
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#pragma once
+// Keyboard and mouse capture for a Moonlight session. While captured, the app window's keyboard
+// and mouse messages go to the host instead of the UI: the native event filter sees them before Qt
+// does. The mouse is read as raw relative movement, the cursor is hidden and kept inside the
+// window. Ctrl+Alt+Shift+Z releases the capture, +Q asks to end the session, +S toggles the stats.
+// Not captured: the Windows key, Alt+Tab and Ctrl+Alt+Del (the system keeps them; losing the focus
+// releases the capture and everything held on the host).
+#include <QAbstractNativeEventFilter>
+#include <QObject>
+#include <windows.h>
+
+#include "veyra/moonlight/InputRouter.h"
+
+namespace veyra::engine { class EngineController; }
+
+namespace veyra::ui {
+
+class MoonlightInputCapture final : public QObject, public QAbstractNativeEventFilter, private moonlight::InputSink {
+ Q_OBJECT
+public:
+ explicit MoonlightInputCapture(engine::EngineController& engine, QObject* parent = nullptr);
+ ~MoonlightInputCapture() override;
+
+ void setWindow(HWND topLevel) { window_ = topLevel; }
+ bool captured() const { return captured_; }
+ // Returns false when it cannot start (no window, or the window is not in the foreground).
+ bool capture(bool on);
+
+ bool nativeEventFilter(const QByteArray& eventType, void* message, qintptr* result) override;
+
+signals:
+ void capturedChanged(bool captured);
+ void releaseRequested(); // Ctrl+Alt+Shift+Z was pressed (capture is already released)
+ void quitRequested(); // Ctrl+Alt+Shift+Q
+ void statsRequested(); // Ctrl+Alt+Shift+S
+
+private:
+ void key(uint32_t virtualKey, uint32_t scanCode, bool extended, bool down) override;
+ void mouseMove(int dx, int dy) override;
+ void mouseButton(int button, bool down) override;
+ void scroll(int delta, bool horizontal) override;
+ void clipToWindow();
+
+ engine::EngineController& engine_;
+ moonlight::InputRouter router_;
+ HWND window_ = nullptr;
+ bool captured_ = false;
+};
+
+} // namespace veyra::ui
diff --git a/src/engine/EngineController.cpp b/src/engine/EngineController.cpp
index 831d70bb..89167277 100644
--- a/src/engine/EngineController.cpp
+++ b/src/engine/EngineController.cpp
@@ -96,6 +96,18 @@ void EngineController::remotePlayController(const remoteplay::ControllerState& s
void EngineController::remotePlayLoginPin(std::string pin){std::lock_guard lock(mutex_);if(activeRemote_)activeRemote_->loginPin(std::move(pin));}
#endif
#ifdef VEYRA_ENABLE_MOONLIGHT
+// Input goes straight to the session: the shared pointer is copied under the lock, the send is not.
+#define VEYRA_MOONLIGHT_INPUT(call) std::shared_ptr<source::MoonlightSessionSource> m;{std::lock_guard lock(mutex_);m=activeMoonlight_;}if(m)m->call
+void EngineController::moonlightController(const remoteplay::ControllerState& state){VEYRA_MOONLIGHT_INPUT(controller(state));}
+remoteplay::ControllerFeedback EngineController::moonlightFeedback(){std::shared_ptr<source::MoonlightSessionSource> m;{std::lock_guard lock(mutex_);m=activeMoonlight_;}return m?m->takeFeedback():remoteplay::ControllerFeedback{};}
+void EngineController::moonlightKey(uint32_t vk,uint32_t scan,bool extended,bool down){VEYRA_MOONLIGHT_INPUT(keyboard(vk,scan,extended,down));}
+void EngineController::moonlightMouseMove(int dx,int dy){VEYRA_MOONLIGHT_INPUT(mouseMove(dx,dy));}
+void EngineController::moonlightMouseButton(int button,bool down){VEYRA_MOONLIGHT_INPUT(mouseButton(button,down));}
+void EngineController::moonlightScroll(int delta,bool horizontal){VEYRA_MOONLIGHT_INPUT(scroll(delta,horizontal));}
+void EngineController::moonlightReleaseInput(){VEYRA_MOONLIGHT_INPUT(releaseInput());}
+#undef VEYRA_MOONLIGHT_INPUT
+#endif
+#ifdef VEYRA_ENABLE_MOONLIGHT
void EngineController::openMoonlight(HWND window,source::MoonlightConnectDesc desc,PlayerOptions opts){
auto request=std::make_shared<source::MoonlightConnectDesc>(std::move(desc));
{std::lock_guard lock(mutex_);snapshot_={};activeFlow_.reset();previewView_={};fgMultiFrameMaxCap_=0;xessMaxInterpolatedFramesCap_=0;fsrMaxGeneratedFramesCap_=0;snapshot_.sessionId=++sessionId_;snapshot_.transport=TransportState::Opening;snapshot_.moonlightActive=true;snapshot_.capture=true;savePath_.clear();desired_=opts.snapshot();desiredNodeOrder_=opts.nodeOrder;desired_.revision=++nextRevision_;snapshot_.desired=desired_;opts=PlayerOptions::from(desired_,desiredNodeOrder_);}
diff --git a/src/source/MoonlightSessionSource.cpp b/src/source/MoonlightSessionSource.cpp
index f92648b6..dddaf7aa 100644
--- a/src/source/MoonlightSessionSource.cpp
+++ b/src/source/MoonlightSessionSource.cpp
@@ -39,6 +39,14 @@ static_assert(moonlight::kFormatH264 == VIDEO_FORMAT_H264 && moonlight::kFormatH
static_assert(moonlight::kServerH264 == SCM_H264 && moonlight::kServerHevc == SCM_HEVC && moonlight::kServerHevcMain10 == SCM_HEVC_MAIN10 &&
moonlight::kServerAv1Main8 == SCM_AV1_MAIN8 && moonlight::kServerAv1Main10 == SCM_AV1_MAIN10,
"SCM constants differ from moonlight-common-c");
+static_assert(moonlight::kPadUp == UP_FLAG && moonlight::kPadDown == DOWN_FLAG && moonlight::kPadLeft == LEFT_FLAG && moonlight::kPadRight == RIGHT_FLAG &&
+ moonlight::kPadStart == PLAY_FLAG && moonlight::kPadBack == BACK_FLAG && moonlight::kPadLeftStick == LS_CLK_FLAG && moonlight::kPadRightStick == RS_CLK_FLAG &&
+ moonlight::kPadLeftBumper == LB_FLAG && moonlight::kPadRightBumper == RB_FLAG && moonlight::kPadGuide == SPECIAL_FLAG &&
+ moonlight::kPadA == A_FLAG && moonlight::kPadB == B_FLAG && moonlight::kPadX == X_FLAG && moonlight::kPadY == Y_FLAG &&
+ moonlight::kPadTouchpad == TOUCHPAD_FLAG && moonlight::kPadMisc == MISC_FLAG,
+ "controller button flags differ from moonlight-common-c");
+static_assert(moonlight::kModShift == MODIFIER_SHIFT && moonlight::kModCtrl == MODIFIER_CTRL && moonlight::kModAlt == MODIFIER_ALT && moonlight::kModMeta == MODIFIER_META,
+ "keyboard modifier flags differ from moonlight-common-c");
namespace {
@@ -160,6 +168,16 @@ struct MoonlightSessionSource::Impl {
// The library allows its statistics calls only between LiStartConnection and LiStopConnection:
// stats() holds this while it calls them, close() takes it to clear `streaming` first.
std::mutex libMutex;
+ // Input state, guarded by libMutex as well: a send must not overlap LiStopConnection.
+ moonlight::HeldKeys keys;
+ unsigned mouseButtons = 0; // bit per button 1..5
+ moonlight::PadFrame pad;
+ bool padArrived = false;
+ std::mutex feedbackMutex;
+ remoteplay::ControllerFeedback feedback;
+ bool feedbackPending = false;
+ uint16_t rumbleLow = 0, rumbleHigh = 0;
+ Clock::time_point feedbackSent{};
std::mutex statsMutex;
double hostLatencyMs = 0, receiveMs = 0, queueMs = 0, decodeMs = 0, receivedFps = 0, decodedFps = 0;
std::chrono::steady_clock::time_point rateStart = Clock::now();
@@ -172,6 +190,20 @@ struct MoonlightSessionSource::Impl {
};
struct MoonlightSessionSource::Callbacks {
+ // Releases what is held on the host. The caller holds libMutex and has checked `streaming`.
+ static void releaseInputLocked(Impl& impl) {
+ for (int i = 0; i < impl.keys.count(); ++i)
+ LiSendKeyboardEvent(impl.keys.at(i), KEY_ACTION_UP, 0);
+ impl.keys.clear();
+ for (int button = 1; button <= 5; ++button)
+ if (impl.mouseButtons & (1u << button)) LiSendMouseButtonEvent(BUTTON_ACTION_RELEASE, button);
+ impl.mouseButtons = 0;
+ if (impl.padArrived && !(impl.pad == moonlight::PadFrame{})) {
+ LiSendMultiControllerEvent(0, int16_t(impl.desc.options.gamepadMask), 0, 0, 0, 0, 0, 0, 0);
+ impl.pad = {};
+ }
+ }
+
// -- connection -------------------------------------------------------------------------
static void stageStarting(int stage) { log::info("moonlight", std::format("stage starting: {}", LiGetStageName(stage))); }
static void stageComplete(int stage) { log::info("moonlight", std::format("stage complete: {}", LiGetStageName(stage))); }
@@ -206,7 +238,15 @@ struct MoonlightSessionSource::Callbacks {
while (!text.empty() && (text.back() == '\n' || text.back() == '\r')) text.pop_back();
if (!text.empty()) log::info("moonlight-lib", text);
}
- static void rumble(unsigned short, unsigned short, unsigned short) {} // input/feedback: stage S3
+ static void rumble(unsigned short controller, unsigned short low, unsigned short high) {
+ if (controller != 0) return;
+ auto* self = g_active.load();
+ if (!self || !self->p_) return;
+ std::lock_guard lock(self->p_->feedbackMutex);
+ self->p_->rumbleLow = low;
+ self->p_->rumbleHigh = high;
+ self->p_->feedbackPending = true;
+ }
static void connectionStatus(int status) {
log::info("moonlight", status == CONN_STATUS_POOR ? "connection status: poor" : "connection status: okay");
}
@@ -710,7 +750,9 @@ void MoonlightSessionSource::close() noexcept {
bool wasStreaming = false;
{
std::lock_guard lib(p_->libMutex);
- wasStreaming = p_->streaming.exchange(false);
+ wasStreaming = p_->streaming.load();
+ if (wasStreaming) Callbacks::releaseInputLocked(*p_);
+ p_->streaming = false;
}
if (wasStreaming) LiStopConnection();
}
@@ -768,6 +810,97 @@ MoonlightStats MoonlightSessionSource::stats() const {
uint64_t MoonlightSessionSource::unitsReceived() const { return p_ ? p_->units.load() : 0; }
+// --- input ----------------------------------------------------------------------------------
+// Every send happens under libMutex after checking `streaming`: close() clears `streaming` under the
+// same mutex before LiStopConnection, so no send can overlap the teardown.
+
+namespace {
+constexpr uint32_t kPadSupported = moonlight::kPadUp | moonlight::kPadDown | moonlight::kPadLeft | moonlight::kPadRight |
+ moonlight::kPadStart | moonlight::kPadBack | moonlight::kPadLeftStick | moonlight::kPadRightStick |
+ moonlight::kPadLeftBumper | moonlight::kPadRightBumper | moonlight::kPadGuide | moonlight::kPadA | moonlight::kPadB | moonlight::kPadX | moonlight::kPadY;
+}
+
+void MoonlightSessionSource::controller(const remoteplay::ControllerState& state) {
+ if (!p_) return;
+ const moonlight::PadFrame frame = moonlight::mapPad(state);
+ std::lock_guard lib(p_->libMutex);
+ if (!p_->streaming.load() || (p_->desc.options.gamepadMask & 1) == 0) return;
+ if (!p_->padArrived) {
+ // Older hosts answer "unsupported" and work without the arrival event.
+ LiSendControllerArrivalEvent(0, uint16_t(p_->desc.options.gamepadMask), LI_CTYPE_XBOX, kPadSupported, LI_CCAP_ANALOG_TRIGGERS | LI_CCAP_RUMBLE);
+ p_->padArrived = true;
+ p_->pad = {};
+ p_->pad.buttons = ~frame.buttons; // forces the first frame out
+ }
+ if (frame == p_->pad) return;
+ p_->pad = frame;
+ LiSendMultiControllerEvent(0, int16_t(p_->desc.options.gamepadMask), int(frame.buttons), frame.leftTrigger, frame.rightTrigger,
+ frame.leftX, frame.leftY, frame.rightX, frame.rightY);
+}
+
+remoteplay::ControllerFeedback MoonlightSessionSource::takeFeedback() {
+ remoteplay::ControllerFeedback out;
+ if (!p_) return out;
+ std::lock_guard lock(p_->feedbackMutex);
+ const auto now = Clock::now();
+ const bool active = p_->rumbleLow != 0 || p_->rumbleHigh != 0;
+ if (p_->feedbackPending || (active && now - p_->feedbackSent >= std::chrono::seconds(2))) {
+ out.rumble = true;
+ out.left = uint8_t((p_->rumbleLow + 128) / 257);
+ out.right = uint8_t((p_->rumbleHigh + 128) / 257);
+ p_->feedbackPending = false;
+ p_->feedbackSent = now;
+ }
+ return out;
+}
+
+void MoonlightSessionSource::keyboard(uint32_t virtualKey, uint32_t scanCode, bool extended, bool down) {
+ if (!p_) return;
+ const moonlight::HostKey key = moonlight::hostKey(virtualKey, scanCode, extended);
+ std::lock_guard lib(p_->libMutex);
+ if (!p_->streaming.load()) return;
+ if (down) {
+ if (!p_->keys.press(key.code, key.modifier)) return; // auto-repeat: the host repeats by itself
+ LiSendKeyboardEvent(key.code, KEY_ACTION_DOWN, char(p_->keys.modifiers()));
+ } else {
+ if (!p_->keys.release(key.code)) return;
+ LiSendKeyboardEvent(key.code, KEY_ACTION_UP, char(p_->keys.modifiers()));
+ }
+}
+
+void MoonlightSessionSource::mouseMove(int dx, int dy) {
+ if (!p_ || (dx == 0 && dy == 0)) return;
+ std::lock_guard lib(p_->libMutex);
+ if (!p_->streaming.load()) return;
+ LiSendMouseMoveEvent(moonlight::clampDelta(dx), moonlight::clampDelta(dy));
+}
+
+void MoonlightSessionSource::mouseButton(int button, bool down) {
+ if (!p_ || button < 1 || button > 5) return;
+ std::lock_guard lib(p_->libMutex);
+ if (!p_->streaming.load()) return;
+ const unsigned bit = 1u << button;
+ if (down == ((p_->mouseButtons & bit) != 0)) return;
+ p_->mouseButtons ^= bit;
+ LiSendMouseButtonEvent(down ? BUTTON_ACTION_PRESS : BUTTON_ACTION_RELEASE, button);
+}
+
+void MoonlightSessionSource::scroll(int delta, bool horizontal) {
+ if (!p_ || delta == 0) return;
+ std::lock_guard lib(p_->libMutex);
+ if (!p_->streaming.load()) return;
+ const short amount = short(std::clamp(delta, -32767, 32767));
+ if (horizontal) LiSendHighResHScrollEvent(amount);
+ else LiSendHighResScrollEvent(amount);
+}
+
+void MoonlightSessionSource::releaseInput() {
+ if (!p_) return;
+ std::lock_guard lib(p_->libMutex);
+ if (!p_->streaming.load()) return;
+ Callbacks::releaseInputLocked(*p_);
+}
+
uint64_t MoonlightSessionSource::skipped() const {
std::lock_guard lock(mutex_);
return skipped_;
diff --git a/src/ui/MoonlightInputCapture.cpp b/src/ui/MoonlightInputCapture.cpp
new file mode 100644
index 00000000..2352054b
--- /dev/null
+++ b/src/ui/MoonlightInputCapture.cpp
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: GPL-3.0-only
+#include "veyra/ui/MoonlightInputCapture.h"
+
+#include <QCoreApplication>
+#include <QGuiApplication>
+
+#include "veyra/Log.h"
+#include "veyra/engine/EngineController.h"
+
+namespace veyra::ui {
+
+MoonlightInputCapture::MoonlightInputCapture(engine::EngineController& engine, QObject* parent)
+ : QObject(parent), engine_(engine), router_(*this) {
+ QCoreApplication::instance()->installNativeEventFilter(this);
+ // Focus lost (Alt+Tab, another window on top): give the keyboard and mouse back at once.
+ connect(qGuiApp, &QGuiApplication::applicationStateChanged, this, [this](Qt::ApplicationState state) {
+ if (state != Qt::ApplicationActive && captured_) capture(false);
+ });
+}
+
+MoonlightInputCapture::~MoonlightInputCapture() {
+ capture(false);
+ if (auto* app = QCoreApplication::instance()) app->removeNativeEventFilter(this);
+}
+
+bool MoonlightInputCapture::capture(bool on) {
+ if (on == captured_) return true;
+ if (on) {
+ if (!window_ || GetForegroundWindow() != window_) return false;
+ RAWINPUTDEVICE device{0x01, 0x02, 0, window_}; // generic desktop / mouse
+ if (!RegisterRawInputDevices(&device, 1, sizeof(device))) {
+ veyra::log::warn("moonlight-input", "RegisterRawInputDevices failed; mouse capture not started");
+ return false;
+ }
+ captured_ = true;
+ router_.reset();
+ clipToWindow();
+ SetCursor(nullptr);
+ } else {
+ captured_ = false;
+ RAWINPUTDEVICE device{0x01, 0x02, RIDEV_REMOVE, nullptr};
+ RegisterRawInputDevices(&device, 1, sizeof(device));
+ ClipCursor(nullptr);
+ SetCursor(LoadCursorW(nullptr, IDC_ARROW));
+ router_.reset();
+ engine_.moonlightReleaseInput(); // nothing stays pressed on the host
+ }
+ emit capturedChanged(captured_);
+ return true;
+}
+
+void MoonlightInputCapture::clipToWindow() {
+ RECT client{};
+ if (!window_ || !GetClientRect(window_, &client)) return;
+ POINT topLeft{client.left, client.top}, bottomRight{client.right, client.bottom};
+ ClientToScreen(window_, &topLeft);
+ ClientToScreen(window_, &bottomRight);
+ const RECT screen{topLeft.x, topLeft.y, bottomRight.x, bottomRight.y};
+ ClipCursor(&screen);
+}
+
+bool MoonlightInputCapture::nativeEventFilter(const QByteArray& eventType, void* message, qintptr* result) {
+ if (!captured_ || eventType != "windows_generic_MSG") return false;
+ const MSG* msg = static_cast<const MSG*>(message);
+ if (!msg->hwnd || GetAncestor(msg->hwnd, GA_ROOT) != window_) return false;
+
+ switch (msg->message) {
+ case WM_INPUT: {
+ alignas(8) BYTE buffer[128];
+ UINT size = sizeof(buffer);
+ const UINT got = GetRawInputData(reinterpret_cast<HRAWINPUT>(msg->lParam), RID_INPUT, buffer, &size, sizeof(RAWINPUTHEADER));
+ if (got != UINT(-1)) {
+ const auto* raw = reinterpret_cast<const RAWINPUT*>(buffer);
+ if (raw->header.dwType == RIM_TYPEMOUSE && (raw->data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE) == 0)
+ router_.rawMouse(raw->data.mouse.lLastX, raw->data.mouse.lLastY);
+ }
+ if (result) *result = 0;
+ return true;
+ }
+ case WM_SETCURSOR:
+ SetCursor(nullptr);
+ if (result) *result = TRUE;
+ return true;
+ case WM_SIZE: case WM_MOVE:
+ clipToWindow();
+ return false; // the UI still needs the resize
+ case WM_ACTIVATE:
+ if (LOWORD(msg->wParam) == WA_INACTIVE) capture(false);
+ return false;
+ case WM_KILLFOCUS:
+ capture(false);
+ return false;
+ default:
+ break;
+ }
+
+ const bool consumed = router_.message(msg->message, msg->wParam, msg->lParam);
+ if (consumed && result) *result = 0;
+ if (const auto reserved = router_.takeReserved(); reserved != moonlight::Reserved::None) {
+ switch (reserved) {
+ case moonlight::Reserved::ReleaseCapture: capture(false); emit releaseRequested(); break;
+ case moonlight::Reserved::Quit: capture(false); emit quitRequested(); break;
+ case moonlight::Reserved::ToggleStats: emit statsRequested(); break;
+ case moonlight::Reserved::None: break;
+ }
+ }
+ return consumed;
+}
+
+void MoonlightInputCapture::key(uint32_t virtualKey, uint32_t scanCode, bool extended, bool down) { engine_.moonlightKey(virtualKey, scanCode, extended, down); }
+void MoonlightInputCapture::mouseMove(int dx, int dy) { engine_.moonlightMouseMove(dx, dy); }
+void MoonlightInputCapture::mouseButton(int button, bool down) { engine_.moonlightMouseButton(button, down); }
+void MoonlightInputCapture::scroll(int delta, bool horizontal) { engine_.moonlightScroll(delta, horizontal); }
+
+} // namespace veyra::ui
diff --git a/tests/moonlight/ProtocolTests.cpp b/tests/moonlight/ProtocolTests.cpp
index 01a13845..0747c212 100644
--- a/tests/moonlight/ProtocolTests.cpp
+++ b/tests/moonlight/ProtocolTests.cpp
@@ -24,6 +24,8 @@
#include <mutex>
#include <string>
#include <thread>
+#include <utility>
+#include <vector>
#include "veyra/moonlight/Client.h"
#include "veyra/moonlight/Crypto.h"
@@ -31,6 +33,8 @@
#include "veyra/moonlight/IdentityStore.h"
#include "veyra/moonlight/Pairing.h"
#include "veyra/moonlight/StreamConfig.h"
+#include "veyra/moonlight/InputMap.h"
+#include "veyra/moonlight/InputRouter.h"
#include "veyra/moonlight/Xml.h"
using namespace veyra::moonlight;
@@ -548,6 +552,114 @@ void protocolTests() {
} catch (const std::exception& e) { ++g_failures; std::printf("FAIL exception: %s\n", e.what()); }
}
+struct RecordingSink final : InputSink {
+ struct Key { uint32_t vk, scan; bool extended, down; };
+ std::vector<Key> keys;
+ std::vector<std::pair<int, bool>> buttons;
+ std::vector<std::pair<int, int>> moves, scrolls;
+ void key(uint32_t vk, uint32_t scan, bool extended, bool down) override { keys.push_back({vk, scan, extended, down}); }
+ void mouseMove(int dx, int dy) override { moves.emplace_back(dx, dy); }
+ void mouseButton(int button, bool down) override { buttons.emplace_back(button, down); }
+ void scroll(int delta, bool horizontal) override { scrolls.emplace_back(delta, horizontal ? 1 : 0); }
+};
+
+LPARAM keyParam(unsigned scan, bool extended, bool up = false) {
+ return LPARAM(1u | (scan << 16) | (extended ? 1u << 24 : 0u) | (up ? (3u << 30) : 0u));
+}
+
+void routerTests() {
+ RecordingSink sink;
+ InputRouter router(sink);
+ check(router.message(WM_KEYDOWN, 'A', keyParam(0x1E, false)) && sink.keys.size() == 1 && sink.keys[0].vk == 'A' && sink.keys[0].down, "a key press reaches the sink and is consumed");
+ check(router.message(WM_KEYUP, 'A', keyParam(0x1E, false, true)) && sink.keys.size() == 2 && !sink.keys[1].down, "and its release");
+ check(router.message(WM_CHAR, 'a', 0) && sink.keys.size() == 2, "characters are consumed but not forwarded");
+ check(router.message(WM_SYSCOMMAND, SC_KEYMENU, 0) && !router.message(WM_SYSCOMMAND, SC_CLOSE, 0), "the Alt menu is swallowed, other system commands are not");
+ check(!router.message(WM_PAINT, 0, 0) && !router.message(WM_SIZE, 0, 0), "unrelated messages pass through");
+
+ check(router.message(WM_LBUTTONDOWN, MK_LBUTTON, 0) && router.message(WM_LBUTTONUP, 0, 0) && sink.buttons.size() == 2 && sink.buttons[0] == std::make_pair(1, true) && sink.buttons[1] == std::make_pair(1, false), "left button");
+ router.message(WM_RBUTTONDOWN, MK_RBUTTON, 0);
+ router.message(WM_MBUTTONDOWN, MK_MBUTTON, 0);
+ router.message(WM_XBUTTONDOWN, MAKEWPARAM(0, XBUTTON1), 0);
+ router.message(WM_XBUTTONDOWN, MAKEWPARAM(0, XBUTTON2), 0);
+ check(sink.buttons[2].first == 3 && sink.buttons[3].first == 2 && sink.buttons[4].first == 4 && sink.buttons[5].first == 5, "right, middle and the two side buttons");
+ router.message(WM_LBUTTONDBLCLK, MK_LBUTTON, 0);
+ check(sink.buttons.back() == std::make_pair(1, true), "a double click is another press");
+ check(router.message(WM_MOUSEMOVE, 0, MAKELPARAM(10, 10)) && sink.moves.empty(), "window mouse moves are consumed; movement comes from raw input");
+ router.rawMouse(7, -3);
+ check(sink.moves.size() == 1 && sink.moves[0] == std::make_pair(7, -3), "raw movement is forwarded");
+ router.message(WM_MOUSEWHEEL, MAKEWPARAM(0, WORD(short(-240))), 0);
+ router.message(WM_MOUSEHWHEEL, MAKEWPARAM(0, WORD(short(120))), 0);
+ check(sink.scrolls.size() == 2 && sink.scrolls[0] == std::make_pair(-240, 0) && sink.scrolls[1] == std::make_pair(120, 1), "wheel and horizontal wheel");
+
+ // Reserved hotkey: Ctrl+Alt+Shift+Z is taken by the app; the modifiers still reached the host
+ // (the session releases them when the capture ends), the Z never does.
+ RecordingSink other;
+ InputRouter hotkeys(other);
+ hotkeys.message(WM_KEYDOWN, 0x11, keyParam(0x1D, false));
+ hotkeys.message(WM_SYSKEYDOWN, 0x12, keyParam(0x38, false));
+ hotkeys.message(WM_KEYDOWN, 0x10, keyParam(0x2A, false));
+ check(hotkeys.takeReserved() == Reserved::None, "modifiers alone are not a hotkey");
+ check(hotkeys.message(WM_KEYDOWN, 'Z', keyParam(0x2C, false)) && hotkeys.takeReserved() == Reserved::ReleaseCapture, "Ctrl+Alt+Shift+Z is reported");
+ check(hotkeys.takeReserved() == Reserved::None, "and only once");
+ const size_t before = other.keys.size();
+ hotkeys.message(WM_KEYUP, 'Z', keyParam(0x2C, false, true));
+ check(other.keys.size() == before, "the hotkey's key-up is not forwarded either");
+ bool zSent = false;
+ for (const auto& k : other.keys) zSent = zSent || k.vk == 'Z';
+ check(!zSent, "the hotkey key itself never reaches the host");
+ hotkeys.reset();
+ hotkeys.message(WM_KEYDOWN, 'Z', keyParam(0x2C, false));
+ check(other.keys.back().vk == 'Z' && hotkeys.takeReserved() == Reserved::None, "after a reset Z is an ordinary key");
+}
+
+void inputTests() {
+ using veyra::remoteplay::ControllerState;
+ {
+ ControllerState s;
+ s.inputActive = true;
+ s.buttons = ControllerState::Cross | ControllerState::Triangle | ControllerState::L1 | ControllerState::Options | ControllerState::Share | ControllerState::Down;
+ s.l2 = 200; s.r2 = 7; s.leftX = 1000; s.leftY = 32767; s.rightX = -5; s.rightY = -32768;
+ const PadFrame f = mapPad(s);
+ check(f.buttons == (kPadA | kPadY | kPadLeftBumper | kPadStart | kPadBack | kPadDown), "pad buttons keep the positional layout");
+ check(f.leftTrigger == 200 && f.rightTrigger == 7, "triggers pass through");
+ check(f.leftX == 1000 && f.leftY == -32767, "stick Y is flipped (SDL down-positive to host up-positive)");
+ check(f.rightX == -5 && f.rightY == 32767, "the most negative stick value flips without overflow");
+ s.inputActive = false;
+ check(mapPad(s) == PadFrame{}, "an inactive pad (focus or device lost) releases everything");
+ check(flipAxis(0) == 0 && flipAxis(INT16_MAX) == -INT16_MAX, "flipAxis is symmetric");
+ }
+ {
+ check(hostKey('A', 0x1E, false).code == hostCode('A'), "letters keep their virtual-key code with bit 15 set");
+ check(hostKey(0x10, 0x2A, false).code == hostCode(0xA0) && hostKey(0x10, 0x36, false).code == hostCode(0xA1), "VK_SHIFT resolves by scan code to left or right");
+ check(hostKey(0x11, 0x1D, false).code == hostCode(0xA2) && hostKey(0x11, 0x1D, true).code == hostCode(0xA3), "VK_CONTROL resolves by the extended flag");
+ check(hostKey(0x12, 0x38, false).code == hostCode(0xA4) && hostKey(0x12, 0x38, true).code == hostCode(0xA5), "VK_MENU resolves by the extended flag (AltGr is right Alt)");
+ check(hostKey(0x10, 0x2A, false).modifier == kModShift && hostKey(0x5B, 0x5B, true).modifier == kModMeta && hostKey('A', 0x1E, false).modifier == 0, "modifier bits");
+ check(hostKey(0x26, 0x48, false).code == hostCode(0x68), "keypad Up with Num Lock off is sent as Numpad8");
+ check(hostKey(0x26, 0x48, true).code == hostCode(0x26), "the arrow key stays an arrow key");
+ check(hostKey(0x2E, 0x53, false).code == hostCode(0x6E), "keypad Delete with Num Lock off is sent as the decimal key");
+ }
+ {
+ HeldKeys held;
+ const HostKey shift = hostKey(0x10, 0x2A, false), a = hostKey('A', 0x1E, false);
+ check(held.press(shift.code, shift.modifier) && held.modifiers() == kModShift, "shift goes down");
+ check(held.press(a.code, 0) && held.count() == 2, "a second key goes down");
+ check(!held.press(a.code, 0) && held.count() == 2, "auto-repeat of a held key is not a new press");
+ check(held.release(shift.code) && held.modifiers() == 0, "releasing shift clears the modifier");
+ check(!held.release(shift.code), "releasing a key that is not held does nothing");
+ held.clear();
+ check(held.count() == 0 && held.modifiers() == 0, "clear drops everything");
+ }
+ {
+ constexpr uint8_t all = kModShift | kModCtrl | kModAlt;
+ check(reservedHotkey('Z', all) == Reserved::ReleaseCapture, "Ctrl+Alt+Shift+Z releases the capture");
+ check(reservedHotkey('Q', all) == Reserved::Quit, "Ctrl+Alt+Shift+Q quits");
+ check(reservedHotkey('S', all) == Reserved::ToggleStats, "Ctrl+Alt+Shift+S toggles the stats");
+ check(reservedHotkey('Z', kModCtrl | kModAlt) == Reserved::None, "Ctrl+Alt+Z alone is forwarded to the host");
+ check(reservedHotkey('A', all) == Reserved::None, "other keys are forwarded");
+ check(clampDelta(100000) == 32767 && clampDelta(-100000) == -32767 && clampDelta(-3) == -3, "mouse deltas are clamped");
+ }
+}
+
} // namespace
int main() {
@@ -555,6 +667,8 @@ int main() {
cryptoTests();
storeTests();
streamConfigTests();
+ inputTests();
+ routerTests();
protocolTests();
std::printf("moonlight protocol tests: %d checks, %d failures\n", g_checks, g_failures);
return g_failures == 0 ? 0 : 1;