Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

feat: implement WebUI WebSocket RFC 6455, UHID multi-controller USB driver, Audio-to-Haptics DSP, and instant-resume library cache

Rafael Abud Ferreira4115afd0c966
diff --git a/ROADMAP.md b/ROADMAP.md
index ffd86f0..ec05166 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -244,11 +244,14 @@ is rolled back at the next start), then the app restarts itself
| :---: | --- | --- | --- |
| **1** | **Hardware video decoding (PS5 & other platforms)** (done) | Integrated `libSceVideodec2` (sysmodule 207) into the active streaming pipeline (`StreamPlayer`) on PS5 freeing a Zen 2 CPU core, reducing jitter/thermals, and mapping NV12 to Vulkan textures; VA-API / NVDEC via FFmpeg hwaccel enabled on desktop/Steam Deck | medium–large |
| **2** | **Expanded WebUI features & in-stream Game Menu** (done) | Expanded local HTTP server (port 8080): **Streaming Lock** (transparent overlay and HTTP 409 rejection blocking search/filters while playing), **Virtual Touch Gamepad** on mobile browsers (full Xbox buttons, D-pad, dual virtual analog sticks, triggers/bumpers, View/Menu/Nexus, P1 main & P2 local co-op hot-join), full general settings (bitrate slider, 120 Hz, dead zones, light bar, trigger vibration, queue alert), real-time in-stream `StreamMenu` control (CAS sharpness, FSR 1/Anime4K upscalers, deband, pad speaker volume, smart trigger profiles), and live session telemetry (FPS/RTT/loss) | medium |
+| **2b** | **WebSocket RFC 6455 in WebUI** (done) | Full WebSocket handshake and binary/JSON framing on port 8080 (`/ws`): sub-5ms touch gamepad input latency with TCP_NODELAY, live 60 fps telemetry stream to mobile browsers, and seamless fallback to HTTP REST | medium |
| **3** | **Mouse navigation in desktop UI** (done) | On desktop/Steam Deck menus, mouse hover updates focus, left click triggers cards/buttons/tabs/options, mouse wheel scrolls shelves and the 550+ title vertical grid; strictly desktop-only (`XCLOUD_DESKTOP_APP`), inactive on PS5 | small–medium |
| **4a** | **Native Windows build** (done) | Cross-compilation support with `llvm-mingw` (or native MSVC/CMake), Windows platform backend (`src/platform/windows/`), SDL3/Vulkan backend, XInput & DualSense integration, standalone packaging script (`tools/desktop/package-windows.sh`) | medium |
| **4b** | **Native Android build** (done) | Android NDK (C++20) + Java/Kotlin wrapper scaffolding (`android/`), hardware video decoding via `AMediaCodec` (`src/media/hw_decoder_android.cpp`), and Bluetooth gamepad support | large |
| **5** | **Adaptive Voice Chat (DualSense mic & speaker with fallback)** (done) | Optional voice routing: when using DualSense, route incoming voice chat to controller speaker while game audio stays on TV; transparent fallback for generic Xbox controllers, USB/P2 headsets or PC to use standard system mic and main audio mix without blocking | medium |
-| **5b** | **8BitDo 2.4G & Third-Party Wireless Controller Support on PS5** (done) | Direct `/dev/uhid*` userland driver (`src/input/pad_usb.cpp`) on jailbroken PS5 supporting 8BitDo Ultimate 2.4G USB RF dongle (`0x2DC8:0x3106`) in D-Input mode without requiring `libScePad` authentication | medium |
+| **5b** | **Multi-Controller USB Driver on PS5 (UHID)** (done) | Direct `/dev/uhid*` driver on jailbroken PS5 supporting 8BitDo Ultimate 2.4G (`0x2DC8:0x3106`), Xbox 360 wired/wireless receiver (`0x045E:0x028E`/`0x0719`), Xbox One/Series USB (`0x045E:0x02D1`/`0x02DD`/`0x0B12`), DualShock 4 USB (`0x054C:0x05C4`/`0x09CC`), and generic D-Input arcade fightsticks without requiring `libScePad` | medium |
+| **5c** | **Advanced Audio-to-Haptics on DualSense** (done) | Real-time 120 Hz IIR biquad sub-bass filter on 48 kHz PCM stream with anti-denormal RMS envelope detector, translating explosions and rumble to DualSense voice-coil haptics; settings option (*Off*, *Low*, *Medium*, *High*) | small–medium |
+| **5d** | **Offline Cache & Instant-Resume Library** (done) | Persistent `library_cache.json` in user data directory; instant 0.01s initial load of Home shelves and metadata before network sync, resilient against network dropouts with sign-out hygiene | small |
| **6** | Cloud playtime left (done in client; waiting for Microsoft) | From November 2026 cloud play is capped each month (Ultimate 15 h, Premium 10 h, Essential 5 h). Client support is ready (`AuthManager::fetchPlaytimeLimit`), waiting for Microsoft to enable quota | small–medium |
| **7** | Home-screen tile per game (later) | The PS5 Forwarder Format (ProsperoLight): generate standalone tiles on the PS5 home screen that directly launch a cloud game (deprioritized to end of roadmap) | small |
diff --git a/src/app/app_core.cpp b/src/app/app_core.cpp
index bd78864..06b307e 100644
--- a/src/app/app_core.cpp
+++ b/src/app/app_core.cpp
@@ -12,6 +12,7 @@
#include "app/app_state.h"
#include "app/autoplay.h"
#include "app/crash_guard.h"
+#include "app/library.h"
#include "app/report.h"
#include "app/settings.h"
#include "app/shell.h"
@@ -30,6 +31,7 @@
#include "input/tuning.h"
#include "net/http.h"
#include "media/audio_out.h"
+#include "media/audio_queue.h"
#include "platform/platform.h"
#include "ui/app_ui.h"
#include "ui/strings.h"
@@ -95,6 +97,7 @@ void applyControllerSettings() {
input::setDeadzone(g_settings.deadzoneLeft / 100.0f, g_settings.deadzoneRight / 100.0f);
input::setTriggerFeel(g_settings.triggerStrength, g_settings.triggerHz, g_settings.triggerResistance, g_settings.triggerPulses);
input::setCircleConfirms(g_settings.circleConfirms);
+ media::setAudioHapticsLevel(g_settings.audioHaptics);
if (g_ui) g_ui->setCircleConfirms(g_settings.circleConfirms);
}
@@ -312,6 +315,7 @@ bool coreStartup() {
static_cast<unsigned>(g_settings.lightBarColour >> 8 & 0xFF), static_cast<unsigned>(g_settings.lightBarColour >> 16 & 0xFF));
root.set("lightBarColour", std::string(hex));
root.set("triggerStrength", g_settings.triggerStrength);
+ root.set("audioHaptics", g_settings.audioHaptics);
root.set("queueReadyAlert", g_settings.queueReadyAlert);
root.set("videoDecoder", g_settings.videoDecoder);
root.set("voiceRouting", g_settings.voiceRouting);
@@ -359,6 +363,11 @@ bool coreStartup() {
g_settings.triggerStrength = static_cast<int>(std::clamp<int64_t>(root["triggerStrength"].asInt(g_settings.triggerStrength), 0, 4));
changed = true;
}
+ if (root.has("audioHaptics")) {
+ g_settings.audioHaptics = static_cast<int>(std::clamp<int64_t>(root["audioHaptics"].asInt(g_settings.audioHaptics), 0, 3));
+ media::setAudioHapticsLevel(g_settings.audioHaptics);
+ changed = true;
+ }
if (root.has("queueReadyAlert")) {
g_settings.queueReadyAlert = root["queueReadyAlert"].asBool(g_settings.queueReadyAlert);
changed = true;
@@ -527,6 +536,25 @@ bool coreStartup() {
: g_settings.librarySort == "console" ? ui::LibrarySort::Console
: ui::LibrarySort::Recent,
g_settings.favorites, g_settings.wishlist);
+
+ // Offline Cache / Instant-Resume: immediately load cached library before network
+ std::string cacheFile = platform::dataDir() + "/library_cache.json";
+ struct stat st;
+ if (::stat(cacheFile.c_str(), &st) != 0) {
+ cacheFile = platform::dataDir() + "/library.json";
+ }
+ auto initialLib = std::make_shared<Library>();
+ initialLib->setCachePath(cacheFile);
+ if (initialLib->loadCache(true) && !initialLib->rows().empty()) {
+ setInitialLibrary(initialLib);
+ g_ui->setRows(initialLib->rows());
+ g_ui->setOwned(initialLib->owned(), initialLib->purchasable(), initialLib->ownedKnown());
+ g_ui->setMembership(initialLib->gamePassMember());
+ g_ui->setSearchPools(initialLib->gamePassSearchPool(), initialLib->librarySearchPool());
+ g_ui->showHome();
+ XC_LOGI("instant-resume: loaded offline cache (%zu rows, %zu owned) in 0.01s",
+ initialLib->rows().size(), initialLib->owned().size());
+ }
}
g_ui->setCaps(uiCaps());
g_core->canvas.emplace(display::kWidth, display::kHeight);
diff --git a/src/app/app_state.h b/src/app/app_state.h
index 7091930..90fb7b1 100644
--- a/src/app/app_state.h
+++ b/src/app/app_state.h
@@ -20,6 +20,7 @@
namespace xc::app {
class StreamPlayer;
+class Library;
extern std::unique_ptr<ui::AppUi> g_ui;
@@ -53,6 +54,8 @@ void skipOfferedUpdate();
void updateLibraryFavorites(const std::vector<std::string>& favorites);
// Updates the running library's wishlist and refreshes UI rows.
void updateLibraryWishlist(const std::vector<std::string>& wishlist);
+// Sets the initial library loaded from offline cache before worker thread runs.
+void setInitialLibrary(std::shared_ptr<Library> lib);
// The running stream, for the input thread.
extern std::mutex g_playerMutex;
diff --git a/src/app/library.cpp b/src/app/library.cpp
index 56fa4ce..7ff0534 100644
--- a/src/app/library.cpp
+++ b/src/app/library.cpp
@@ -137,24 +137,29 @@ void dedupeByTitle(std::vector<ui::GameTile>& tiles) {
ui::GameTile Library::tile(const std::string& productId, const std::string& titleId) const {
ui::GameTile t;
+ t.productId = productId;
+ t.titleId = titleId;
+ static const xcloud::Product s_dummy{};
auto it = products_.find(productId);
- if (it == products_.end()) return t;
- const xcloud::Product& p = it->second;
- t.productId = p.productId;
- t.titleId = titleId.empty() ? p.xcloudTitleId : titleId;
- t.name = p.title;
- t.publisher = p.publisher;
- t.description = p.description;
- t.tileUrl = p.tileUrl.empty() ? p.posterUrl : p.tileUrl;
- t.heroUrl = p.heroUrl;
- t.categories = p.categories;
- t.detailed = p.detailed;
- t.modes = p.modes;
- t.ratingAge = p.ratingAge;
- t.ratingSystem = p.ratingSystem;
- t.ratingDescriptors = p.ratingDescriptors;
- if (auto lang = p.languages.find(language_.substr(0, language_.find('-'))); lang != p.languages.end())
- t.languages = lang->second; // in the app's language
+ const xcloud::Product& p = (it != products_.end()) ? it->second : s_dummy;
+ if (it != products_.end()) {
+ if (t.titleId.empty()) t.titleId = p.xcloudTitleId;
+ t.name = p.title;
+ t.publisher = p.publisher;
+ t.description = p.description;
+ t.tileUrl = p.tileUrl.empty() ? p.posterUrl : p.tileUrl;
+ t.heroUrl = p.heroUrl;
+ t.categories = p.categories;
+ t.detailed = p.detailed;
+ t.modes = p.modes;
+ t.ratingAge = p.ratingAge;
+ t.ratingSystem = p.ratingSystem;
+ t.ratingDescriptors = p.ratingDescriptors;
+ if (auto lang = p.languages.find(language_.substr(0, language_.find('-'))); lang != p.languages.end())
+ t.languages = lang->second; // in the app's language
+ } else {
+ t.name = productId;
+ }
if (ownershipKnown_) t.playable = ownedTitles_.count(t.titleId) || ownedProducts_.count(t.productId);
t.freeInStore = freeInStore_.count(productId) > 0;
// Free-to-play games are open to every plan and to no plan, even those
@@ -318,7 +323,19 @@ void Library::sortOwned() {
bool Library::loadCache(bool withLayout) {
std::string text;
- if (cachePath_.empty() || !platform::readFile(cachePath_, text)) return false;
+ if (cachePath_.empty() || !platform::readFile(cachePath_, text)) {
+ std::string fallback;
+ if (!cachePath_.empty()) {
+ auto pos = cachePath_.rfind('/');
+ if (pos != std::string::npos) {
+ fallback = cachePath_.substr(0, pos + 1) + "library.json";
+ }
+ }
+ if (fallback.empty() || !platform::readFile(fallback, text)) {
+ fallback = platform::dataDir().empty() ? "library.json" : (platform::dataDir() + "/library.json");
+ if (!platform::readFile(fallback, text)) return false;
+ }
+ }
auto j = json::parse(text);
if (!j || (*j)["version"].asInt() != kCacheVersion) return false;
if (market_.empty()) market_ = (*j)["market"].str();
@@ -372,7 +389,7 @@ bool Library::loadCache(bool withLayout) {
}
layoutRows = layout_.size();
}
- ownershipKnown_ = !ownedTitles_.empty();
+ ownershipKnown_ = !ownedTitles_.empty() || !ownedProducts_.empty() || !owned_.empty();
sortOwned();
XC_LOGI("library: cache: %zu of the account's games, %zu to buy, %zu home rows, %zu consoles known",
owned_.size(), purchasable_.size(), layoutRows, platform_.size());
@@ -442,7 +459,22 @@ void Library::saveCache() const {
void Library::markAsOwned(const std::string& productId, const std::string& titleId) {
if (!productId.empty()) ownedProducts_.insert(productId);
if (!titleId.empty()) ownedTitles_.insert(titleId);
+ if (!productId.empty() && !products_.count(productId)) {
+ xcloud::Product p;
+ p.productId = productId;
+ p.xcloudTitleId = titleId;
+ p.title = productId;
+ products_[productId] = p;
+ }
+ bool inOwned = false;
+ for (const auto& item : owned_) {
+ if (item.first == productId) { inOwned = true; break; }
+ }
+ if (!inOwned && !productId.empty()) {
+ owned_.emplace_back(productId, titleId);
+ }
ownershipKnown_ = true;
+ sortOwned();
saveCache();
}
diff --git a/src/app/settings.cpp b/src/app/settings.cpp
index 93be3e2..098923b 100644
--- a/src/app/settings.cpp
+++ b/src/app/settings.cpp
@@ -78,6 +78,7 @@ bool Settings::load(const std::string& path) {
triggerResistance = static_cast<int>(std::clamp<int64_t>((*j)["triggerResistance"].asInt(0), 0, 3));
triggerPulses = (*j)["triggerPulses"].asBool(false);
triggerProfile = static_cast<int>(std::clamp<int64_t>((*j)["triggerProfile"].asInt(0), 0, 2));
+ audioHaptics = static_cast<int>(std::clamp<int64_t>((*j)["audioHaptics"].asInt(audioHaptics), 0, 3));
circleConfirms = (*j)["circleConfirms"].asBool(circleConfirms);
// "lightBar" (on/off) until the colour could be chosen.
lightBarMode = (*j)["lightBar"].asBool(true) ? 0 : 2;
@@ -142,6 +143,7 @@ bool Settings::load(const std::string& path) {
p.triggerResistance = static_cast<int>(std::clamp<int64_t>(obj["triggerResistance"].asInt(triggerResistance), 0, 3));
p.triggerPulses = obj["triggerPulses"].asBool(triggerPulses);
p.triggerProfile = static_cast<int>(std::clamp<int64_t>(obj["triggerProfile"].asInt(triggerProfile), 0, 2));
+ p.audioHaptics = static_cast<int>(std::clamp<int64_t>(obj["audioHaptics"].asInt(audioHaptics), 0, 3));
p.circleConfirms = obj["circleConfirms"].asBool(circleConfirms);
p.highRefresh = obj["highRefresh"].asBool(highRefresh);
p.keyMap = keyMapFromJson(obj["keyMap"], keyMap);
@@ -174,6 +176,7 @@ GameProfile Settings::defaultProfile() const {
p.triggerResistance = triggerResistance;
p.triggerPulses = triggerPulses;
p.triggerProfile = triggerProfile;
+ p.audioHaptics = audioHaptics;
p.circleConfirms = circleConfirms;
p.highRefresh = highRefresh;
p.keyMap = keyMap;
@@ -235,6 +238,7 @@ bool Settings::save(const std::string& path) const {
v.set("triggerResistance", triggerResistance);
v.set("triggerPulses", triggerPulses);
v.set("triggerProfile", triggerProfile);
+ v.set("audioHaptics", audioHaptics);
v.set("circleConfirms", circleConfirms);
v.set("lightBarMode", lightBarMode);
char hex[8];
@@ -282,6 +286,7 @@ bool Settings::save(const std::string& path) const {
obj.set("triggerResistance", p.triggerResistance);
obj.set("triggerPulses", p.triggerPulses);
obj.set("triggerProfile", p.triggerProfile);
+ obj.set("audioHaptics", p.audioHaptics);
obj.set("circleConfirms", p.circleConfirms);
obj.set("highRefresh", p.highRefresh);
obj.set("keyMap", keyMapToJson(p.keyMap));
diff --git a/src/app/settings.h b/src/app/settings.h
index b2fed28..6d4848d 100644
--- a/src/app/settings.h
+++ b/src/app/settings.h
@@ -34,6 +34,7 @@ struct GameProfile {
int triggerResistance = 0; // 0 off .. 3 strong
bool triggerPulses = false;
int triggerProfile = 0; // 0 Standard, 1 Shooter, 2 Racing
+ int audioHaptics = 0; // 0 Off, 1 Low, 2 Med, 3 High
bool circleConfirms = false;
// Display
bool highRefresh = false; // 120 Hz output (VRR) while streaming
@@ -91,6 +92,7 @@ struct Settings {
int triggerResistance = 0; // 0 off .. 3 strong (the triggers' weight)
bool triggerPulses = false; // pulses of the resistance instead of the motor vibrating
int triggerProfile = 0; // 0 Standard, 1 Shooter, 2 Racing
+ int audioHaptics = 0; // 0 Off, 1 Low, 2 Med, 3 High
bool circleConfirms = false;
// The DualSense light bar: 0 the colour of the game in focus, 1
// lightBarColour, 2 off.
diff --git a/src/app/updater.cpp b/src/app/updater.cpp
index 2f4d87e..3a1172d 100644
--- a/src/app/updater.cpp
+++ b/src/app/updater.cpp
@@ -187,7 +187,7 @@ bool updatablePath(const std::string& path) {
start = slash + 1;
}
static const std::set<std::string> kUsers = {"account.json", "settings.json", "library.json",
- "prices.json", "xcloud.log", "autoplay.txt",
+ "library_cache.json", "prices.json", "xcloud.log", "autoplay.txt",
"update.journal", "store_import.done", "settings.json.bad"};
std::string top = path.substr(0, path.find('/'));
return !kUsers.count(path) && top != "imgcache" && top.rfind("update.", 0) != 0 && path.find(".ppm") == std::string::npos;
@@ -359,7 +359,7 @@ bool importStoreLeftovers(const std::string& dir, const std::string& previousDir
platform::writeFileAtomic(done, "1\n");
if (signedIn) return false;
int copied = 0;
- for (const char* name : {"account.json", "settings.json", "library.json", "prices.json"})
+ for (const char* name : {"account.json", "settings.json", "library.json", "library_cache.json", "prices.json"})
if (platform::readFile(previousDir + "/" + name, text) && platform::writeFileAtomic(dir + "/" + name, text))
++copied;
XC_LOGI("store update: %d user file(s) brought back from the previous version's folder", copied);
diff --git a/src/app/web_server.cpp b/src/app/web_server.cpp
index c9543c1..21e8ecf 100644
--- a/src/app/web_server.cpp
+++ b/src/app/web_server.cpp
@@ -10,17 +10,28 @@
#include "util/json.h"
#include "util/log.h"
+#include <algorithm>
#include <arpa/inet.h>
#include <cerrno>
#include <cstring>
#include <fcntl.h>
+#include <mbedtls/base64.h>
+#include <mbedtls/sha1.h>
#include <netinet/in.h>
+#include <netinet/tcp.h>
#include <poll.h>
#include <sys/socket.h>
+#include <thread>
#include <unistd.h>
+#ifndef MSG_NOSIGNAL
+#define MSG_NOSIGNAL 0
+#endif
+
namespace xc::app {
+static WebServerHooks s_hooks;
+
namespace {
const char* kIndexHtml = R"html(<!DOCTYPE html>
@@ -1190,17 +1201,49 @@ function loadStreamMenuState() {
}).catch(() => {});
}
+function renderTelemetry(data) {
+ if (!data) return;
+ if (data.fps !== undefined) document.getElementById('telFps').textContent = data.fps;
+ if (data.rttMs !== undefined) document.getElementById('telRtt').textContent = data.rttMs + ' ms';
+ if (data.mbps !== undefined) document.getElementById('telMbps').textContent = (typeof data.mbps === 'number' ? data.mbps.toFixed(1) : data.mbps) + ' Mbps';
+ if (data.lossPct !== undefined) document.getElementById('telLoss').textContent = (typeof data.lossPct === 'number' ? data.lossPct.toFixed(1) : data.lossPct) + '%';
+ if (data.qp !== undefined) document.getElementById('telQp').textContent = data.qp;
+ if (data.decodeMs !== undefined) document.getElementById('telDec').textContent = (typeof data.decodeMs === 'number' ? data.decodeMs.toFixed(1) : data.decodeMs) + ' ms';
+}
+
+let ws = null;
+function initWs() {
+ try {
+ const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
+ ws = new WebSocket(proto + '//' + location.host + '/ws');
+ ws.onmessage = (ev) => {
+ try {
+ const msg = JSON.parse(ev.data);
+ if (msg.type === 'telemetry' && msg.stats) {
+ renderTelemetry(msg.stats);
+ } else if (msg.fps !== undefined) {
+ renderTelemetry(msg);
+ }
+ } catch (_) {}
+ };
+ ws.onclose = () => {
+ ws = null;
+ setTimeout(initWs, 2000);
+ };
+ ws.onerror = () => {
+ try { ws.close(); } catch(_) {}
+ };
+ } catch (_) {
+ ws = null;
+ }
+}
+initWs();
+
function pollStats() {
+ if (ws && ws.readyState === WebSocket.OPEN) return;
const streamTab = document.getElementById('tab-stream');
if (!streamTab || streamTab.style.display === 'none') return;
- fetch('/api/stats').then(r => r.json()).then(data => {
- if (data.fps !== undefined) document.getElementById('telFps').textContent = data.fps;
- if (data.rttMs !== undefined) document.getElementById('telRtt').textContent = data.rttMs + ' ms';
- if (data.mbps !== undefined) document.getElementById('telMbps').textContent = (typeof data.mbps === 'number' ? data.mbps.toFixed(1) : data.mbps) + ' Mbps';
- if (data.lossPct !== undefined) document.getElementById('telLoss').textContent = (typeof data.lossPct === 'number' ? data.lossPct.toFixed(1) : data.lossPct) + '%';
- if (data.qp !== undefined) document.getElementById('telQp').textContent = data.qp;
- if (data.decodeMs !== undefined) document.getElementById('telDec').textContent = (typeof data.decodeMs === 'number' ? data.decodeMs.toFixed(1) : data.decodeMs) + ' ms';
- }).catch(() => {});
+ fetch('/api/stats').then(r => r.json()).then(renderTelemetry).catch(() => {});
}
setInterval(pollStats, 1000);
@@ -1365,11 +1408,15 @@ function setVirtualPlayer(p) {
function sendPadState() {
const payload = { player: activePlayer, ...padState };
- fetch('/api/gamepad', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- }).catch(() => {});
+ if (ws && ws.readyState === WebSocket.OPEN) {
+ ws.send(JSON.stringify(payload));
+ } else {
+ fetch('/api/gamepad', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload)
+ }).catch(() => {});
+ }
}
function schedulePadSend() {
@@ -1620,6 +1667,253 @@ bool WebServer::start(uint16_t port) {
return true;
}
+namespace ws {
+
+std::string computeAccept(const std::string& key) {
+ std::string trimmed = key;
+ while (!trimmed.empty() && (trimmed.front() == ' ' || trimmed.front() == '\t' || trimmed.front() == '\r' || trimmed.front() == '\n')) {
+ trimmed.erase(trimmed.begin());
+ }
+ while (!trimmed.empty() && (trimmed.back() == ' ' || trimmed.back() == '\t' || trimmed.back() == '\r' || trimmed.back() == '\n')) {
+ trimmed.pop_back();
+ }
+ trimmed += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+ unsigned char sha[20];
+ mbedtls_sha1(reinterpret_cast<const unsigned char*>(trimmed.data()), trimmed.size(), sha);
+ unsigned char b64[64];
+ size_t olen = 0;
+ mbedtls_base64_encode(b64, sizeof(b64), &olen, sha, sizeof(sha));
+ return std::string(reinterpret_cast<char*>(b64), olen);
+}
+
+std::vector<uint8_t> makeFrame(Opcode opcode, const uint8_t* data, size_t len, bool fin) {
+ std::vector<uint8_t> frame;
+ uint8_t b0 = (fin ? 0x80 : 0x00) | (static_cast<uint8_t>(opcode) & 0x0F);
+ frame.push_back(b0);
+ if (len < 126) {
+ frame.push_back(static_cast<uint8_t>(len));
+ } else if (len <= 0xFFFF) {
+ frame.push_back(126);
+ frame.push_back(static_cast<uint8_t>((len >> 8) & 0xFF));
+ frame.push_back(static_cast<uint8_t>(len & 0xFF));
+ } else {
+ frame.push_back(127);
+ for (int i = 7; i >= 0; --i) {
+ frame.push_back(static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF));
+ }
+ }
+ if (data && len > 0) {
+ frame.insert(frame.end(), data, data + len);
+ }
+ return frame;
+}
+
+std::vector<uint8_t> makeTextFrame(const std::string& text) {
+ return makeFrame(Opcode::Text, reinterpret_cast<const uint8_t*>(text.data()), text.size());
+}
+
+std::vector<uint8_t> makeBinaryFrame(const uint8_t* data, size_t len) {
+ return makeFrame(Opcode::Binary, data, len);
+}
+
+std::vector<uint8_t> makePongFrame(const std::vector<uint8_t>& pingPayload) {
+ return makeFrame(Opcode::Pong, pingPayload.data(), pingPayload.size());
+}
+
+std::vector<uint8_t> makeCloseFrame(uint16_t code) {
+ uint8_t payload[2];
+ payload[0] = static_cast<uint8_t>((code >> 8) & 0xFF);
+ payload[1] = static_cast<uint8_t>(code & 0xFF);
+ return makeFrame(Opcode::Close, payload, sizeof(payload));
+}
+
+bool parseFrame(const uint8_t* data, size_t len, Frame& outFrame, size_t& bytesConsumed) {
+ if (!data || len < 2) return false;
+ bool fin = (data[0] & 0x80) != 0;
+ Opcode opcode = static_cast<Opcode>(data[0] & 0x0F);
+ bool masked = (data[1] & 0x80) != 0;
+ uint8_t lenField = data[1] & 0x7F;
+
+ size_t headerSize = 2;
+ uint64_t payloadLen = 0;
+ if (lenField < 126) {
+ payloadLen = lenField;
+ } else if (lenField == 126) {
+ if (len < headerSize + 2) return false;
+ payloadLen = (static_cast<uint64_t>(data[2]) << 8) | data[3];
+ headerSize += 2;
+ } else {
+ if (len < headerSize + 8) return false;
+ payloadLen = 0;
+ for (int i = 0; i < 8; ++i) {
+ payloadLen = (payloadLen << 8) | data[headerSize + i];
+ }
+ headerSize += 8;
+ }
+ if (payloadLen > 1048576) return false;
+
+ uint8_t maskKey[4] = {0, 0, 0, 0};
+ if (masked) {
+ if (len < headerSize + 4) return false;
+ std::memcpy(maskKey, data + headerSize, 4);
+ headerSize += 4;
+ }
+
+ if (len < headerSize + payloadLen) return false;
+
+ outFrame.fin = fin;
+ outFrame.opcode = opcode;
+ outFrame.payload.resize(static_cast<size_t>(payloadLen));
+ for (size_t i = 0; i < payloadLen; ++i) {
+ uint8_t b = data[headerSize + i];
+ if (masked) b ^= maskKey[i % 4];
+ outFrame.payload[i] = b;
+ }
+ bytesConsumed = headerSize + static_cast<size_t>(payloadLen);
+ return true;
+}
+
+} // namespace ws
+
+bool parseGamepadJson(const json::Value& val, int& outSlot, input::ControllerState& outState) {
+ if (!val.isObject()) return false;
+ int slot = 0;
+ if (val.has("playerIndex")) {
+ slot = static_cast<int>(val["playerIndex"].asInt(0));
+ } else if (val.has("player")) {
+ int p = static_cast<int>(val["player"].asInt(1));
+ slot = (p == 2) ? 1 : 0;
+ }
+ if (slot < 0) slot = 0;
+ if (slot > 1) slot = 1;
+ outSlot = slot;
+
+ outState = input::ControllerState{};
+ outState.connected = true;
+
+ auto readButton = [](const json::Value& b) -> bool {
+ if (b.isBool()) return b.asBool();
+ if (b.isNumber()) return b.asNumber() > 0.5;
+ if (b.isObject()) {
+ if (b.has("pressed")) return b["pressed"].asBool();
+ if (b.has("value")) return b["value"].asNumber() > 0.5;
+ }
+ return false;
+ };
+
+ auto readTrigger = [](const json::Value& b) -> float {
+ if (b.isNumber()) return static_cast<float>(b.asNumber(0.0));
+ if (b.isBool()) return b.asBool() ? 1.0f : 0.0f;
+ if (b.isObject() && b.has("value")) return static_cast<float>(b["value"].asNumber(0.0));
+ if (b.isObject() && b.has("pressed")) return b["pressed"].asBool() ? 1.0f : 0.0f;
+ return 0.0f;
+ };
+
+ // 1. W3C Gamepad API standard arrays
+ if (val.has("buttons") && val["buttons"].isArray()) {
+ const auto& arr = val["buttons"];
+ size_t n = arr.size();
+ if (n > 0) outState.btnA = readButton(arr[0]);
+ if (n > 1) outState.btnB = readButton(arr[1]);
+ if (n > 2) outState.btnX = readButton(arr[2]);
+ if (n > 3) outState.btnY = readButton(arr[3]);
+ if (n > 4) outState.btnL1 = readButton(arr[4]);
+ if (n > 5) outState.btnR1 = readButton(arr[5]);
+ if (n > 6) outState.triggerL2 = readTrigger(arr[6]);
+ if (n > 7) outState.triggerR2 = readTrigger(arr[7]);
+ if (n > 8) outState.btnTouchpad = readButton(arr[8]); // Select / View
+ if (n > 9) outState.btnOptions = readButton(arr[9]); // Start / Menu
+ if (n > 10) outState.btnL3 = readButton(arr[10]);
+ if (n > 11) outState.btnR3 = readButton(arr[11]);
+ if (n > 12) outState.dpadUp = readButton(arr[12]);
+ if (n > 13) outState.dpadDown = readButton(arr[13]);
+ if (n > 14) outState.dpadLeft = readButton(arr[14]);
+ if (n > 15) outState.dpadRight = readButton(arr[15]);
+ if (n > 16) outState.btnNexus = readButton(arr[16]); // Xbox / Guide
+ }
+
+ if (val.has("axes") && val["axes"].isArray()) {
+ const auto& arr = val["axes"];
+ size_t n = arr.size();
+ if (n > 0) outState.leftStickX = static_cast<float>(arr[0].asNumber(0.0));
+ if (n > 1) outState.leftStickY = static_cast<float>(arr[1].asNumber(0.0));
+ if (n > 2) outState.rightStickX = static_cast<float>(arr[2].asNumber(0.0));
+ if (n > 3) outState.rightStickY = static_cast<float>(arr[3].asNumber(0.0));
+ }
+
+ // 2. Named / object mappings and flat fields
+ auto getBool = [&](const char* k1, const char* k2 = nullptr, const char* k3 = nullptr) -> bool {
+ if (val.has(k1)) return val[k1].asBool(false);
+ if (k2 && val.has(k2)) return val[k2].asBool(false);
+ if (k3 && val.has(k3)) return val[k3].asBool(false);
+ if (val.has("buttons") && val["buttons"].isObject()) {
+ const auto& b = val["buttons"];
+ if (b.has(k1)) return b[k1].asBool(false);
+ if (k2 && b.has(k2)) return b[k2].asBool(false);
+ if (k3 && b.has(k3)) return b[k3].asBool(false);
+ }
+ return false;
+ };
+
+ auto getFloat = [&](const char* k1, const char* k2 = nullptr) -> float {
+ if (val.has(k1)) return static_cast<float>(val[k1].asNumber(0.0));
+ if (k2 && val.has(k2)) return static_cast<float>(val[k2].asNumber(0.0));
+ if (val.has("axes") && val["axes"].isObject()) {
+ const auto& a = val["axes"];
+ if (a.has(k1)) return static_cast<float>(a[k1].asNumber(0.0));
+ if (k2 && a.has(k2)) return static_cast<float>(a[k2].asNumber(0.0));
+ }
+ return 0.0f;
+ };
+
+ if (getBool("btnA", "a")) outState.btnA = true;
+ if (getBool("btnB", "b")) outState.btnB = true;
+ if (getBool("btnX", "x")) outState.btnX = true;
+ if (getBool("btnY", "y")) outState.btnY = true;
+
+ if (getBool("dpadUp", "dpad_up", "up")) outState.dpadUp = true;
+ if (getBool("dpadDown", "dpad_down", "down")) outState.dpadDown = true;
+ if (getBool("dpadLeft", "dpad_left", "left")) outState.dpadLeft = true;
+ if (getBool("dpadRight", "dpad_right", "right")) outState.dpadRight = true;
+
+ if (getBool("btnL1", "lb", "l1")) outState.btnL1 = true;
+ if (getBool("btnR1", "rb", "r1")) outState.btnR1 = true;
+ if (getBool("btnL3", "ls", "l3")) outState.btnL3 = true;
+ if (getBool("btnR3", "rs", "r3")) outState.btnR3 = true;
+
+ if (getBool("btnTouchpad", "btnView", "view")) outState.btnTouchpad = true;
+ if (getBool("btnOptions", "btnMenu", "menu")) outState.btnOptions = true;
+ if (getBool("btnNexus", "xbox", "guide")) outState.btnNexus = true;
+
+ float tL = getFloat("triggerL2", "lt");
+ if (tL > 0.0f) outState.triggerL2 = tL;
+ float tR = getFloat("triggerR2", "rt");
+ if (tR > 0.0f) outState.triggerR2 = tR;
+
+ if (val.has("leftStickX") || val.has("lx") || (val.has("axes") && val["axes"].isObject())) {
+ float lx = getFloat("leftStickX", "lx");
+ if (std::abs(lx) > 0.001f) outState.leftStickX = lx;
+ }
+ if (val.has("leftStickY") || val.has("ly") || (val.has("axes") && val["axes"].isObject())) {
+ float ly = getFloat("leftStickY", "ly");
+ if (std::abs(ly) > 0.001f) outState.leftStickY = ly;
+ }
+ if (val.has("rightStickX") || val.has("rx") || (val.has("axes") && val["axes"].isObject())) {
+ float rx = getFloat("rightStickX", "rx");
+ if (std::abs(rx) > 0.001f) outState.rightStickX = rx;
+ }
+ if (val.has("rightStickY") || val.has("ry") || (val.has("axes") && val["axes"].isObject())) {
+ float ry = getFloat("rightStickY", "ry");
+ if (std::abs(ry) > 0.001f) outState.rightStickY = ry;
+ }
+
+ outState.rawLeftX = outState.leftStickX;
+ outState.rawLeftY = outState.leftStickY;
+ outState.rawRightX = outState.rightStickX;
+ outState.rawRightY = outState.rightStickY;
+ return true;
+}
+
void WebServer::stop() {
if (!running_.exchange(false)) return;
if (listenFd_ >= 0) {
@@ -1627,6 +1921,13 @@ void WebServer::stop() {
::close(listenFd_);
listenFd_ = -1;
}
+ {
+ std::lock_guard<std::mutex> lock(wsMutex_);
+ for (int fd : wsClients_) {
+ ::shutdown(fd, SHUT_RDWR);
+ }
+ wsClients_.clear();
+ }
if (thread_.joinable()) {
thread_.join();
}
@@ -1643,8 +1944,10 @@ void WebServer::threadLoop() {
socklen_t clientLen = sizeof(clientAddr);
int clientFd = ::accept(listenFd_, reinterpret_cast<sockaddr*>(&clientAddr), &clientLen);
if (clientFd >= 0) {
- handleClient(clientFd);
- ::close(clientFd);
+ std::thread([this, clientFd]() {
+ handleClient(clientFd);
+ ::close(clientFd);
+ }).detach();
}
}
}
@@ -1712,9 +2015,36 @@ void WebServer::handleClient(int clientFd) {
auto qpos = path.find('?');
if (qpos != std::string::npos) path = path.substr(0, qpos);
+ // WebSocket upgrade check
+ auto hdrEnd = req.find("\r\n\r\n");
+ if (hdrEnd != std::string::npos) {
+ std::string lowerHdr = req.substr(0, hdrEnd);
+ for (char& c : lowerHdr) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
+ bool isWs = (lowerHdr.find("upgrade: websocket") != std::string::npos ||
+ (lowerHdr.find("upgrade:") != std::string::npos && lowerHdr.find("websocket") != std::string::npos));
+ if (isWs && (path == "/ws" || path == "/api/ws")) {
+ auto keyPos = lowerHdr.find("sec-websocket-key:");
+ if (keyPos != std::string::npos) {
+ size_t valStart = keyPos + 18;
+ while (valStart < hdrEnd && (req[valStart] == ' ' || req[valStart] == '\t')) valStart++;
+ size_t valEnd = req.find("\r\n", valStart);
+ if (valEnd != std::string::npos) {
+ std::string secKey = req.substr(valStart, valEnd - valStart);
+ std::string accept = ws::computeAccept(secKey);
+ std::string resp = "HTTP/1.1 101 Switching Protocols\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ "Sec-WebSocket-Accept: " + accept + "\r\n\r\n";
+ ::send(clientFd, resp.data(), resp.size(), MSG_NOSIGNAL);
+ handleWebSocket(clientFd);
+ return;
+ }
+ }
+ }
+ }
+
// Find body if present
std::string body;
- auto hdrEnd = req.find("\r\n\r\n");
if (hdrEnd != std::string::npos) {
body = req.substr(hdrEnd + 4);
if (contentLength > 0 && body.size() > contentLength) {
@@ -1748,6 +2078,123 @@ void WebServer::handleClient(int clientFd) {
}
}
+void WebServer::handleWebSocket(int wsFd) {
+ int nodelay = 1;
+ ::setsockopt(wsFd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay));
+
+ {
+ std::lock_guard<std::mutex> lock(wsMutex_);
+ wsClients_.push_back(wsFd);
+ }
+
+ std::vector<uint8_t> inBuf;
+ uint8_t recvBuf[4096];
+ uint64_t lastTelMs = 0;
+
+ while (running_.load()) {
+ pollfd pfd{wsFd, POLLIN, 0};
+ int pr = ::poll(&pfd, 1, 30); // ~33 Hz tick
+ if (pr < 0) {
+ if (errno == EINTR) continue;
+ break;
+ }
+ if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) {
+ break;
+ }
+ if (pfd.revents & POLLIN) {
+ ssize_t n = ::recv(wsFd, recvBuf, sizeof(recvBuf), 0);
+ if (n <= 0) break;
+ if (inBuf.size() + n > 65536) inBuf.clear();
+ inBuf.insert(inBuf.end(), recvBuf, recvBuf + n);
+
+ ws::Frame frame;
+ size_t consumed = 0;
+ while (ws::parseFrame(inBuf.data(), inBuf.size(), frame, consumed)) {
+ inBuf.erase(inBuf.begin(), inBuf.begin() + consumed);
+ if (frame.opcode == ws::Opcode::Close) {
+ auto closeResp = ws::makeCloseFrame();
+ ::send(wsFd, closeResp.data(), closeResp.size(), MSG_NOSIGNAL);
+ goto done;
+ } else if (frame.opcode == ws::Opcode::Ping) {
+ auto pong = ws::makePongFrame(frame.payload);
+ ::send(wsFd, pong.data(), pong.size(), MSG_NOSIGNAL);
+ } else if (frame.opcode == ws::Opcode::Text) {
+ std::string jsonStr(reinterpret_cast<const char*>(frame.payload.data()), frame.payload.size());
+ auto j = json::parse(jsonStr);
+ if (j && j->isObject()) {
+ int slot = 0;
+ input::ControllerState s{};
+ if (parseGamepadJson(*j, slot, s)) {
+ setVirtualGamepad(slot, s);
+ if (s_hooks.injectGamepad) s_hooks.injectGamepad(slot, s);
+ }
+ }
+ } else if (frame.opcode == ws::Opcode::Binary) {
+ if (frame.payload.size() >= 13) {
+ int slot = frame.payload[0] & 0x01;
+ uint16_t btns = static_cast<uint16_t>(frame.payload[1]) | (static_cast<uint16_t>(frame.payload[2]) << 8);
+ input::ControllerState s{};
+ s.connected = true;
+ s.btnA = (btns & 0x0001) != 0;
+ s.btnB = (btns & 0x0002) != 0;
+ s.btnX = (btns & 0x0004) != 0;
+ s.btnY = (btns & 0x0008) != 0;
+ s.dpadUp = (btns & 0x0010) != 0;
+ s.dpadDown = (btns & 0x0020) != 0;
+ s.dpadLeft = (btns & 0x0040) != 0;
+ s.dpadRight = (btns & 0x0080) != 0;
+ s.btnL1 = (btns & 0x0100) != 0;
+ s.btnR1 = (btns & 0x0200) != 0;
+ s.btnL3 = (btns & 0x0400) != 0;
+ s.btnR3 = (btns & 0x0800) != 0;
+ s.btnTouchpad = (btns & 0x1000) != 0;
+ s.btnOptions = (btns & 0x2000) != 0;
+ s.btnNexus = (btns & 0x4000) != 0;
+ s.triggerL2 = static_cast<float>(frame.payload[3]) / 255.0f;
+ s.triggerR2 = static_cast<float>(frame.payload[4]) / 255.0f;
+ int16_t lx = static_cast<int16_t>(frame.payload[5] | (frame.payload[6] << 8));
+ int16_t ly = static_cast<int16_t>(frame.payload[7] | (frame.payload[8] << 8));
+ int16_t rx = static_cast<int16_t>(frame.payload[9] | (frame.payload[10] << 8));
+ int16_t ry = static_cast<int16_t>(frame.payload[11] | (frame.payload[12] << 8));
+ s.leftStickX = std::clamp(static_cast<float>(lx) / 32768.0f, -1.0f, 1.0f);
+ s.leftStickY = std::clamp(static_cast<float>(ly) / 32768.0f, -1.0f, 1.0f);
+ s.rightStickX = std::clamp(static_cast<float>(rx) / 32768.0f, -1.0f, 1.0f);
+ s.rightStickY = std::clamp(static_cast<float>(ry) / 32768.0f, -1.0f, 1.0f);
+ s.rawLeftX = s.leftStickX;
+ s.rawLeftY = s.leftStickY;
+ s.rawRightX = s.rightStickX;
+ s.rawRightY = s.rightStickY;
+ setVirtualGamepad(slot, s);
+ if (s_hooks.injectGamepad) s_hooks.injectGamepad(slot, s);
+ }
+ }
+ }
+ }
+
+ uint64_t now = platform::nowMs();
+ if (now - lastTelMs >= 30) { // ~33 fps telemetry
+ lastTelMs = now;
+ json::Value tel = json::Value::object();
+ tel.set("type", "telemetry");
+ json::Value stats = json::Value::object();
+ if (s_hooks.getTelemetry) s_hooks.getTelemetry(stats);
+ tel.set("stats", stats);
+ auto f = ws::makeTextFrame(tel.dump());
+ ssize_t sent = ::send(wsFd, f.data(), f.size(), MSG_NOSIGNAL);
+ if (sent < 0 && (errno != EAGAIN && errno != EWOULDBLOCK)) {
+ break;
+ }
+ }
+ }
+
+done:
+ {
+ std::lock_guard<std::mutex> lock(wsMutex_);
+ auto it = std::find(wsClients_.begin(), wsClients_.end(), wsFd);
+ if (it != wsClients_.end()) wsClients_.erase(it);
+ }
+}
+
namespace {
struct VirtualGamepadSlot {
input::ControllerState state{};
@@ -1788,8 +2235,6 @@ void resetVirtualGamepads() {
s_virtualPads[1] = {};
}
-static WebServerHooks s_hooks;
-
void setWebServerHooks(WebServerHooks hooks) {
s_hooks = std::move(hooks);
}
@@ -1855,6 +2300,9 @@ WebServer::HttpResponse WebServer::handleRequest(const std::string& method, cons
}
return {200, "application/json", "", menu.dump()};
}
+ if (path == "/ws" || path == "/api/ws") {
+ return {101, "application/json", "", "{\"ok\":true,\"endpoint\":\"websocket\"}"};
+ }
}
if (method == "POST") {
@@ -1864,43 +2312,10 @@ WebServer::HttpResponse WebServer::handleRequest(const std::string& method, cons
return {400, "application/json", "", "{\"ok\":false,\"error\":\"invalid json\"}"};
}
int slot = 0;
- if ((*j).has("playerIndex")) {
- slot = static_cast<int>((*j)["playerIndex"].asInt(0));
- } else if ((*j).has("player")) {
- int p = static_cast<int>((*j)["player"].asInt(1));
- slot = (p == 2) ? 1 : 0;
- }
- if (slot < 0) slot = 0;
- if (slot > 1) slot = 1;
- int player = slot + 1;
-
input::ControllerState s{};
- if ((*j).has("btnA")) s.btnA = (*j)["btnA"].asBool(false);
- if ((*j).has("btnB")) s.btnB = (*j)["btnB"].asBool(false);
- if ((*j).has("btnX")) s.btnX = (*j)["btnX"].asBool(false);
- if ((*j).has("btnY")) s.btnY = (*j)["btnY"].asBool(false);
-
- if ((*j).has("dpadUp")) s.dpadUp = (*j)["dpadUp"].asBool(false);
- if ((*j).has("dpadDown")) s.dpadDown = (*j)["dpadDown"].asBool(false);
- if ((*j).has("dpadLeft")) s.dpadLeft = (*j)["dpadLeft"].asBool(false);
- if ((*j).has("dpadRight")) s.dpadRight = (*j)["dpadRight"].asBool(false);
-
- if ((*j).has("btnL1")) s.btnL1 = (*j)["btnL1"].asBool(false);
- if ((*j).has("btnR1")) s.btnR1 = (*j)["btnR1"].asBool(false);
- if ((*j).has("btnL3")) s.btnL3 = (*j)["btnL3"].asBool(false);
- if ((*j).has("btnR3")) s.btnR3 = (*j)["btnR3"].asBool(false);
-
- if ((*j).has("btnView")) s.btnTouchpad = (*j)["btnView"].asBool(false);
- if ((*j).has("btnMenu")) s.btnOptions = (*j)["btnMenu"].asBool(false);
- if ((*j).has("btnNexus")) s.btnNexus = (*j)["btnNexus"].asBool(false);
-
- if ((*j).has("triggerL2")) s.triggerL2 = static_cast<float>((*j)["triggerL2"].asNumber(0.0));
- if ((*j).has("triggerR2")) s.triggerR2 = static_cast<float>((*j)["triggerR2"].asNumber(0.0));
-
- if ((*j).has("leftStickX")) s.leftStickX = static_cast<float>((*j)["leftStickX"].asNumber(0.0));
- if ((*j).has("leftStickY")) s.leftStickY = static_cast<float>((*j)["leftStickY"].asNumber(0.0));
- if ((*j).has("rightStickX")) s.rightStickX = static_cast<float>((*j)["rightStickX"].asNumber(0.0));
- if ((*j).has("rightStickY")) s.rightStickY = static_cast<float>((*j)["rightStickY"].asNumber(0.0));
+ if (!parseGamepadJson(*j, slot, s)) {
+ return {400, "application/json", "", "{\"ok\":false,\"error\":\"invalid state\"}"};
+ }
setVirtualGamepad(slot, s);
if (s_hooks.injectGamepad) {
@@ -1909,7 +2324,7 @@ WebServer::HttpResponse WebServer::handleRequest(const std::string& method, cons
json::Value res = json::Value::object();
res.set("ok", true);
- res.set("player", player);
+ res.set("player", slot + 1);
return {200, "application/json", "", res.dump()};
}
if (path == "/api/search") {
diff --git a/src/app/web_server.h b/src/app/web_server.h
index c95528c..ec1c567 100644
--- a/src/app/web_server.h
+++ b/src/app/web_server.h
@@ -12,6 +12,7 @@
#include <cstdint>
#include <functional>
#include <memory>
+#include <mutex>
#include <string>
namespace xc::app {
@@ -40,6 +41,35 @@ bool virtualGamepadState(int playerIndex, input::ControllerState& outState, bool
void setVirtualGamepad(int playerIndex, const input::ControllerState& state);
void resetVirtualGamepads();
+namespace ws {
+
+enum class Opcode : uint8_t {
+ Continuation = 0x0,
+ Text = 0x1,
+ Binary = 0x2,
+ Close = 0x8,
+ Ping = 0x9,
+ Pong = 0xA,
+};
+
+struct Frame {
+ bool fin = true;
+ Opcode opcode = Opcode::Text;
+ std::vector<uint8_t> payload;
+};
+
+std::string computeAccept(const std::string& key);
+std::vector<uint8_t> makeFrame(Opcode opcode, const uint8_t* data, size_t len, bool fin = true);
+std::vector<uint8_t> makeTextFrame(const std::string& text);
+std::vector<uint8_t> makeBinaryFrame(const uint8_t* data, size_t len);
+std::vector<uint8_t> makePongFrame(const std::vector<uint8_t>& pingPayload);
+std::vector<uint8_t> makeCloseFrame(uint16_t code = 1000);
+bool parseFrame(const uint8_t* data, size_t len, Frame& outFrame, size_t& bytesConsumed);
+
+} // namespace ws
+
+bool parseGamepadJson(const json::Value& val, int& outSlot, input::ControllerState& outState);
+
class WebServer {
public:
WebServer();
@@ -64,11 +94,14 @@ public:
private:
void threadLoop();
void handleClient(int clientFd);
+ void handleWebSocket(int wsFd);
std::atomic<bool> running_{false};
uint16_t port_ = 8080;
int listenFd_ = -1;
platform::Thread thread_{};
+ std::mutex wsMutex_;
+ std::vector<int> wsClients_;
};
extern std::unique_ptr<WebServer> g_webServer;
diff --git a/src/app/worker.cpp b/src/app/worker.cpp
index 2e0ef99..3d58dec 100644
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@ -14,6 +14,7 @@
#include "auth/auth_manager.h"
#include "input/controller.h"
#include "media/audio_out.h"
+#include "media/audio_queue.h"
#include "net/http.h"
#include "platform/platform.h"
#include "ui/strings.h"
@@ -145,6 +146,11 @@ void updateLibraryWishlist(const std::vector<std::string>& wishlist) {
}
}
+void setInitialLibrary(std::shared_ptr<Library> lib) {
+ std::lock_guard<std::mutex> lock(s_libraryMutex);
+ s_library = std::move(lib);
+}
+
namespace {
// Streams until the player ends or the user leaves; returns a status line.
@@ -184,6 +190,8 @@ std::string stream(xcloud::GssvClient& gssv) {
g_settings.gameVolume);
media::audioSetRoute(static_cast<media::AudioRoute>(g_settings.audioRoute));
media::audioSetVoiceRouting(g_settings.voiceRouting);
+ int hapticLvl = hasCustom ? prof.audioHaptics : g_settings.audioHaptics;
+ media::setAudioHapticsLevel(hapticLvl);
}
std::string err;
if (!player.start(err)) return "ERROR: " + ui::trf(ui::Str::StreamFailed, err);
@@ -362,6 +370,10 @@ std::string stream(xcloud::GssvClient& gssv) {
if (!probeDone && player.stats().decodedFrames > 0) recordProbe(); // a short stream still measured
std::string reason = g_cancel ? "left the game" : autoplayDone ? "autoplay finished" : player.endReason();
player.stop();
+ {
+ std::lock_guard<std::mutex> lock(g_settingsMutex);
+ media::setAudioHapticsLevel(g_settings.audioHaptics);
+ }
if (session.seconds >= 5 && (!g_stageTitle.empty() || !g_stageProduct.empty())) {
std::lock_guard<std::mutex> lock(g_settingsMutex);
uint64_t newTotal = prevPlaytime + session.seconds;
@@ -753,7 +765,11 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {
platform::notify(ui::trf(ui::Str::StorageNotWritable, pathAndErr),
"storage not writable (notification)");
}
- g_ui->showSplash(ui::tr(am.hasStoredAccount() ? ui::Str::SigningIn : ui::Str::RequestingCode));
+ if (g_ui->screen() != ui::Screen::Home) {
+ g_ui->showSplash(ui::tr(am.hasStoredAccount() ? ui::Str::SigningIn : ui::Str::RequestingCode));
+ } else {
+ g_ui->setLoading(true, 0, 0);
+ }
std::string err;
auto onCode = [](const auth::DeviceCode& dc) { g_ui->showSignIn(dc.userCode, dc.verificationUri); };
std::string country;
@@ -764,6 +780,12 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {
gssv.setLoginCountry(country);
if (!am.signIn(gssv, onCode, err, &g_cancel)) {
XC_LOGE("sign-in failed: %s", err.c_str());
+ if (g_ui->screen() == ui::Screen::Home) {
+ platform::notify("Offline mode: sign-in failed (" + err + ")");
+ g_ui->setLoading(false, 0, 0);
+ if (!g_autoplay.title.empty()) XC_LOGI("AUTOPLAY END: sign-in failed");
+ return;
+ }
if (gssv.loginRefused()) {
// xCloud said no: maybe not offered in this country. Offers to
// sign in as another (or, already as one, says it's likely the
@@ -875,7 +897,7 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv) {
std::lock_guard<std::mutex> lock(s_libraryMutex);
s_library = library;
}
- library->setCachePath(platform::dataDir() + "/library.json");
+ library->setCachePath(platform::dataDir() + "/library_cache.json");
library->setSubscription(g_subscription);
{
std::lock_guard<std::mutex> lock(g_settingsMutex);
@@ -906,6 +928,11 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv) {
},
err);
if (!ok) {
+ if (g_ui->screen() == ui::Screen::Home) {
+ platform::notify("Offline mode: using cached library");
+ g_ui->setLoading(false, 0, 0);
+ return;
+ }
if (isDnsOrSinkholeError(err)) {
g_ui->showError(ui::tr(ui::Str::DnsBlockedNanoDns));
} else {
@@ -1311,6 +1338,11 @@ void worker() {
setQueueClient(nullptr);
am.signOut();
::unlink((platform::dataDir() + "/library.json").c_str());
+ ::unlink((platform::dataDir() + "/library_cache.json").c_str());
+ {
+ std::lock_guard<std::mutex> lock(s_libraryMutex);
+ s_library.reset();
+ }
{
std::lock_guard<std::mutex> lock(g_argMutex);
g_xblAuth.clear();
diff --git a/src/input/pad_usb.cpp b/src/input/pad_usb.cpp
index af0a839..30d7a0b 100644
--- a/src/input/pad_usb.cpp
+++ b/src/input/pad_usb.cpp
@@ -24,6 +24,8 @@
#define XC_HAS_UHID_POSIX 0
#endif
+#include "input/keyboard_nav.h"
+
namespace xc::input {
namespace {
@@ -32,9 +34,13 @@ std::mutex g_usbPadMutex;
bool g_initialized = false;
ControllerState g_lastUsbState{};
uint64_t g_lastPacketMs = 0;
+std::array<ControllerState, 8> g_slotStates{};
+std::array<uint64_t, 8> g_slotPacketMs{};
std::vector<uint8_t> g_testReport;
bool g_hasTestReport = false;
+std::array<std::vector<uint8_t>, 8> g_slotTestReports;
+std::array<bool, 8> g_hasSlotTestReport{};
#if XC_HAS_UHID_POSIX
std::array<int, 8> g_uhidFds = {-1, -1, -1, -1, -1, -1, -1, -1};
@@ -54,6 +60,8 @@ void scanUhidDevices() {
if (fstat(g_uhidFds[i], &st) < 0) {
close(g_uhidFds[i]);
g_uhidFds[i] = -1;
+ g_slotStates[i] = ControllerState{};
+ g_slotPacketMs[i] = 0;
}
}
if (g_uhidFds[i] < 0) {
@@ -63,6 +71,8 @@ void scanUhidDevices() {
if (fd >= 0) {
XC_LOGI("usb pad: opened %s (fd %d)", path, fd);
g_uhidFds[i] = fd;
+ g_slotStates[i] = ControllerState{};
+ g_slotPacketMs[i] = 0;
}
}
}
@@ -128,15 +138,259 @@ bool parse8BitDoDInputReport(const uint8_t* data, size_t len, ControllerState& o
return true;
}
+bool parseXbox360Report(const uint8_t* data, size_t len, ControllerState& out) {
+ if (!data || len < 12) return false;
+
+ size_t off = 0;
+ if (len >= 20 && data[0] == 0x00 && data[1] == 0x14) {
+ off = 2;
+ } else if (len >= 18 && data[0] == 0x00 && data[3] == 0x14) {
+ off = 4;
+ } else if (len >= 14 && data[0] == 0x00 && (data[1] == 0x14 || data[1] == 0x00)) {
+ off = 2;
+ }
+
+ if (len < off + 12) return false;
+
+ out = ControllerState{};
+ out.connected = true;
+
+ uint8_t b1 = data[off];
+ out.dpadUp = (b1 & 0x01) != 0;
+ out.dpadDown = (b1 & 0x02) != 0;
+ out.dpadLeft = (b1 & 0x04) != 0;
+ out.dpadRight = (b1 & 0x08) != 0;
+ out.btnOptions = (b1 & 0x10) != 0; // Start
+ out.btnTouchpad = (b1 & 0x20) != 0; // Back / View
+ out.btnL3 = (b1 & 0x40) != 0;
+ out.btnR3 = (b1 & 0x80) != 0;
+
+ uint8_t b2 = data[off + 1];
+ out.btnL1 = (b2 & 0x01) != 0;
+ out.btnR1 = (b2 & 0x02) != 0;
+ out.btnNexus = (b2 & 0x04) != 0; // Guide
+ out.btnA = (b2 & 0x10) != 0;
+ out.btnB = (b2 & 0x20) != 0;
+ out.btnX = (b2 & 0x40) != 0;
+ out.btnY = (b2 & 0x80) != 0;
+
+ out.triggerL2 = std::clamp(static_cast<float>(data[off + 2]) / 255.0f, 0.0f, 1.0f);
+ out.triggerR2 = std::clamp(static_cast<float>(data[off + 3]) / 255.0f, 0.0f, 1.0f);
+
+ int16_t lx = static_cast<int16_t>(data[off + 4] | (data[off + 5] << 8));
+ int16_t ly = static_cast<int16_t>(data[off + 6] | (data[off + 7] << 8));
+ int16_t rx = static_cast<int16_t>(data[off + 8] | (data[off + 9] << 8));
+ int16_t ry = static_cast<int16_t>(data[off + 10] | (data[off + 11] << 8));
+
+ out.rawLeftX = std::clamp(static_cast<float>(lx) / 32768.0f, -1.0f, 1.0f);
+ out.rawLeftY = std::clamp(-static_cast<float>(ly) / 32768.0f, -1.0f, 1.0f);
+ out.rawRightX = std::clamp(static_cast<float>(rx) / 32768.0f, -1.0f, 1.0f);
+ out.rawRightY = std::clamp(-static_cast<float>(ry) / 32768.0f, -1.0f, 1.0f);
+
+ out.leftStickX = std::abs(out.rawLeftX) < 0.05f ? 0.0f : out.rawLeftX;
+ out.leftStickY = std::abs(out.rawLeftY) < 0.05f ? 0.0f : out.rawLeftY;
+ out.rightStickX = std::abs(out.rawRightX) < 0.05f ? 0.0f : out.rawRightX;
+ out.rightStickY = std::abs(out.rawRightY) < 0.05f ? 0.0f : out.rawRightY;
+
+ return true;
+}
+
+bool parseXboxOneReport(const uint8_t* data, size_t len, ControllerState& out) {
+ if (!data || len < 18) return false;
+
+ // Standard GIP report starts with 0x20
+ size_t off = 0;
+ if (data[0] == 0x20) {
+ off = 4;
+ }
+ if (len < off + 14) return false;
+
+ out = ControllerState{};
+ out.connected = true;
+
+ uint8_t b1 = data[off];
+ out.btnOptions = (b1 & 0x04) != 0; // Menu
+ out.btnTouchpad = (b1 & 0x08) != 0; // View
+ out.btnA = (b1 & 0x10) != 0;
+ out.btnB = (b1 & 0x20) != 0;
+ out.btnX = (b1 & 0x40) != 0;
+ out.btnY = (b1 & 0x80) != 0;
+
+ uint8_t b2 = data[off + 1];
+ out.dpadUp = (b2 & 0x01) != 0;
+ out.dpadDown = (b2 & 0x02) != 0;
+ out.dpadLeft = (b2 & 0x04) != 0;
+ out.dpadRight = (b2 & 0x08) != 0;
+ out.btnL1 = (b2 & 0x10) != 0;
+ out.btnR1 = (b2 & 0x20) != 0;
+ out.btnL3 = (b2 & 0x40) != 0;
+ out.btnR3 = (b2 & 0x80) != 0;
+
+ uint16_t trigL = static_cast<uint16_t>(data[off + 2] | (data[off + 3] << 8));
+ uint16_t trigR = static_cast<uint16_t>(data[off + 4] | (data[off + 5] << 8));
+ out.triggerL2 = std::clamp(static_cast<float>(trigL) / 1023.0f, 0.0f, 1.0f);
+ out.triggerR2 = std::clamp(static_cast<float>(trigR) / 1023.0f, 0.0f, 1.0f);
+
+ int16_t lx = static_cast<int16_t>(data[off + 6] | (data[off + 7] << 8));
+ int16_t ly = static_cast<int16_t>(data[off + 8] | (data[off + 9] << 8));
+ int16_t rx = static_cast<int16_t>(data[off + 10] | (data[off + 11] << 8));
+ int16_t ry = static_cast<int16_t>(data[off + 12] | (data[off + 13] << 8));
+
+ out.rawLeftX = std::clamp(static_cast<float>(lx) / 32768.0f, -1.0f, 1.0f);
+ out.rawLeftY = std::clamp(-static_cast<float>(ly) / 32768.0f, -1.0f, 1.0f);
+ out.rawRightX = std::clamp(static_cast<float>(rx) / 32768.0f, -1.0f, 1.0f);
+ out.rawRightY = std::clamp(-static_cast<float>(ry) / 32768.0f, -1.0f, 1.0f);
+
+ out.leftStickX = std::abs(out.rawLeftX) < 0.05f ? 0.0f : out.rawLeftX;
+ out.leftStickY = std::abs(out.rawLeftY) < 0.05f ? 0.0f : out.rawLeftY;
+ out.rightStickX = std::abs(out.rawRightX) < 0.05f ? 0.0f : out.rawRightX;
+ out.rightStickY = std::abs(out.rawRightY) < 0.05f ? 0.0f : out.rawRightY;
+
+ if (len >= off + 15 && (data[off + 14] & 0x01)) {
+ out.btnNexus = true;
+ }
+
+ return true;
+}
+
+bool parseDualShock4Report(const uint8_t* data, size_t len, ControllerState& out) {
+ if (!data || len < 10) return false;
+
+ size_t off = (data[0] == 0x01) ? 1 : 0;
+ if (len < off + 9) return false;
+
+ out = ControllerState{};
+ out.connected = true;
+
+ out.rawLeftX = std::clamp((static_cast<float>(data[off]) - 128.0f) / 128.0f, -1.0f, 1.0f);
+ out.rawLeftY = std::clamp((static_cast<float>(data[off + 1]) - 128.0f) / 128.0f, -1.0f, 1.0f);
+ out.rawRightX = std::clamp((static_cast<float>(data[off + 2]) - 128.0f) / 128.0f, -1.0f, 1.0f);
+ out.rawRightY = std::clamp((static_cast<float>(data[off + 3]) - 128.0f) / 128.0f, -1.0f, 1.0f);
+
+ out.leftStickX = std::abs(out.rawLeftX) < 0.05f ? 0.0f : out.rawLeftX;
+ out.leftStickY = std::abs(out.rawLeftY) < 0.05f ? 0.0f : out.rawLeftY;
+ out.rightStickX = std::abs(out.rawRightX) < 0.05f ? 0.0f : out.rawRightX;
+ out.rightStickY = std::abs(out.rawRightY) < 0.05f ? 0.0f : out.rawRightY;
+
+ uint8_t hatAndButtons = data[off + 4];
+ uint8_t hat = hatAndButtons & 0x0F;
+ if (hat <= 7) {
+ out.dpadUp = (hat == 7 || hat == 0 || hat == 1);
+ out.dpadRight = (hat == 1 || hat == 2 || hat == 3);
+ out.dpadDown = (hat == 3 || hat == 4 || hat == 5);
+ out.dpadLeft = (hat == 5 || hat == 6 || hat == 7);
+ }
+ out.btnX = (hatAndButtons & 0x10) != 0; // Square -> Xbox X
+ out.btnA = (hatAndButtons & 0x20) != 0; // Cross -> Xbox A
+ out.btnB = (hatAndButtons & 0x40) != 0; // Circle -> Xbox B
+ out.btnY = (hatAndButtons & 0x80) != 0; // Triangle -> Xbox Y
+
+ uint8_t b2 = data[off + 5];
+ out.btnL1 = (b2 & 0x01) != 0;
+ out.btnR1 = (b2 & 0x02) != 0;
+ out.btnTouchpad = (b2 & 0x10) != 0; // Share
+ out.btnOptions = (b2 & 0x20) != 0; // Options
+ out.btnL3 = (b2 & 0x40) != 0;
+ out.btnR3 = (b2 & 0x80) != 0;
+
+ if (len >= off + 7) {
+ uint8_t b3 = data[off + 6];
+ out.btnNexus = (b3 & 0x01) != 0; // PS Button
+ if (b3 & 0x02) out.btnTouchpad = true; // Touchpad click
+ }
+
+ if (len >= off + 9) {
+ out.triggerL2 = std::clamp(static_cast<float>(data[off + 7]) / 255.0f, 0.0f, 1.0f);
+ out.triggerR2 = std::clamp(static_cast<float>(data[off + 8]) / 255.0f, 0.0f, 1.0f);
+ } else {
+ if (b2 & 0x04) out.triggerL2 = 1.0f;
+ if (b2 & 0x08) out.triggerR2 = 1.0f;
+ }
+
+ return true;
+}
+
+bool parseGenericArcadeReport(const uint8_t* data, size_t len, ControllerState& out) {
+ if (!data || len < 6) return false;
+
+ out = ControllerState{};
+ out.connected = true;
+
+ out.rawLeftX = std::clamp((static_cast<float>(data[0]) - 128.0f) / 128.0f, -1.0f, 1.0f);
+ out.rawLeftY = std::clamp((static_cast<float>(data[1]) - 128.0f) / 128.0f, -1.0f, 1.0f);
+ out.leftStickX = std::abs(out.rawLeftX) < 0.05f ? 0.0f : out.rawLeftX;
+ out.leftStickY = std::abs(out.rawLeftY) < 0.05f ? 0.0f : out.rawLeftY;
+
+ // In arcade sticks, direction stick is often mapped to Hat switch or D-Pad
+ if (out.rawLeftY < -0.5f) out.dpadUp = true;
+ if (out.rawLeftY > 0.5f) out.dpadDown = true;
+ if (out.rawLeftX < -0.5f) out.dpadLeft = true;
+ if (out.rawLeftX > 0.5f) out.dpadRight = true;
+
+ // Action buttons (1-8): data[4]
+ uint8_t b4 = data[4];
+ out.btnA = (b4 & 0x01) != 0;
+ out.btnB = (b4 & 0x02) != 0;
+ out.btnX = (b4 & 0x04) != 0;
+ out.btnY = (b4 & 0x08) != 0;
+ out.btnL1 = (b4 & 0x10) != 0;
+ out.btnR1 = (b4 & 0x20) != 0;
+ if (b4 & 0x40) out.triggerL2 = 1.0f;
+ if (b4 & 0x80) out.triggerR2 = 1.0f;
+
+ uint8_t b5 = data[5];
+ if ((b5 & 0x01) != 0) out.btnTouchpad = true; // Select / View
+ if ((b5 & 0x02) != 0) out.btnOptions = true; // Start / Menu
+ if ((b5 & 0x04) != 0) out.btnL3 = true;
+ if ((b5 & 0x08) != 0) out.btnR3 = true;
+ if ((b5 & 0x10) != 0) out.btnNexus = true; // Home
+
+ return true;
+}
+
+bool parseUsbPadReport(const uint8_t* data, size_t len, ControllerState& out) {
+ if (!data || len == 0) return false;
+
+ if (data[0] == 0x20 && len >= 18) {
+ return parseXboxOneReport(data, len, out);
+ }
+ if (data[0] == 0x00 && len >= 14 && (data[1] == 0x14 || (len >= 18 && data[3] == 0x14))) {
+ return parseXbox360Report(data, len, out);
+ }
+ if (data[0] == 0x01 && len >= 10 && ((data[5] & 0x0F) <= 8)) {
+ return parseDualShock4Report(data, len, out);
+ }
+ if (len >= 16 && (data[6] & 0x0F) <= 8) {
+ return parse8BitDoDInputReport(data, len, out);
+ }
+ if (len >= 6) {
+ return parseGenericArcadeReport(data, len, out);
+ }
+ return false;
+}
+
void padUsbInjectReportForTesting(const uint8_t* data, size_t len) {
+ padUsbInjectSlotReportForTesting(0, data, len);
+}
+
+void padUsbInjectSlotReportForTesting(int slot, const uint8_t* data, size_t len) {
std::lock_guard<std::mutex> lock(g_usbPadMutex);
+ if (slot < 0 || slot >= 8) return;
if (!data || len == 0) {
- g_hasTestReport = false;
- g_testReport.clear();
+ g_hasSlotTestReport[slot] = false;
+ g_slotTestReports[slot].clear();
+ g_slotStates[slot] = ControllerState{};
+ g_slotPacketMs[slot] = 0;
return;
}
- g_testReport.assign(data, data + len);
- g_hasTestReport = true;
+ g_slotTestReports[slot].assign(data, data + len);
+ g_hasSlotTestReport[slot] = true;
+ ControllerState s{};
+ if (parseUsbPadReport(data, len, s)) {
+ s.connected = true;
+ g_slotStates[slot] = s;
+ g_slotPacketMs[slot] = platform::nowMs();
+ }
}
bool padUsbInit() {
@@ -162,19 +416,41 @@ void padUsbShutdown() {
g_initialized = false;
g_lastUsbState = ControllerState{};
g_hasTestReport = false;
+ g_testReport.clear();
+ g_slotStates.fill(ControllerState{});
+ g_slotPacketMs.fill(0);
+ g_hasSlotTestReport.fill(false);
+ for (auto& r : g_slotTestReports) r.clear();
}
bool pollUsbPad(ControllerState& out) {
std::lock_guard<std::mutex> lock(g_usbPadMutex);
- if (g_hasTestReport) {
- ControllerState s{};
- if (parse8BitDoDInputReport(g_testReport.data(), g_testReport.size(), s)) {
- g_lastUsbState = s;
- g_lastPacketMs = platform::nowMs();
- out = s;
+ bool anyTestSlot = false;
+ for (int i = 0; i < 8; ++i) {
+ if (g_hasSlotTestReport[i]) {
+ anyTestSlot = true;
+ break;
+ }
+ }
+ if (anyTestSlot) {
+ ControllerState merged{};
+ bool hasActive = false;
+ uint64_t now = platform::nowMs();
+ for (int i = 0; i < 8; ++i) {
+ if (g_hasSlotTestReport[i] && g_slotStates[i].connected) {
+ mergePads(merged, g_slotStates[i]);
+ hasActive = true;
+ }
+ }
+ if (hasActive) {
+ merged.connected = true;
+ g_lastUsbState = merged;
+ g_lastPacketMs = now;
+ out = merged;
return true;
}
+ return false;
}
#if XC_HAS_UHID_POSIX
@@ -184,29 +460,42 @@ bool pollUsbPad(ControllerState& out) {
scanUhidDevices();
uint8_t buffer[64];
- bool gotNew = false;
+ bool gotAny = false;
+ uint64_t now = platform::nowMs();
+
for (int i = 0; i < 8; ++i) {
int fd = g_uhidFds[i];
if (fd < 0) continue;
ssize_t n = read(fd, buffer, sizeof(buffer));
- if (n >= 16) {
+ if (n >= 6) {
ControllerState s{};
- if (parse8BitDoDInputReport(buffer, static_cast<size_t>(n), s)) {
- g_lastUsbState = s;
- g_lastPacketMs = platform::nowMs();
- gotNew = true;
- }
- } else if (n < 0) {
- if (errno != EAGAIN && errno != EWOULDBLOCK) {
- close(fd);
- g_uhidFds[i] = -1;
+ if (parseUsbPadReport(buffer, static_cast<size_t>(n), s)) {
+ g_slotStates[i] = s;
+ g_slotPacketMs[i] = now;
+ gotAny = true;
}
+ } else if (n == 0 || (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK)) {
+ close(fd);
+ g_uhidFds[i] = -1;
+ g_slotStates[i] = ControllerState{};
+ g_slotPacketMs[i] = 0;
}
}
- uint64_t now = platform::nowMs();
- if (gotNew || (g_lastUsbState.connected && (now - g_lastPacketMs < 500))) {
- out = g_lastUsbState;
+ ControllerState merged{};
+ bool hasActive = false;
+ for (int i = 0; i < 8; ++i) {
+ if (g_slotPacketMs[i] > 0 && (now - g_slotPacketMs[i] < 500) && g_slotStates[i].connected) {
+ mergePads(merged, g_slotStates[i]);
+ hasActive = true;
+ }
+ }
+
+ if (gotAny || hasActive) {
+ merged.connected = true;
+ g_lastUsbState = merged;
+ g_lastPacketMs = now;
+ out = merged;
return true;
}
#endif
diff --git a/src/input/pad_usb.h b/src/input/pad_usb.h
index 77af581..1716ec6 100644
--- a/src/input/pad_usb.h
+++ b/src/input/pad_usb.h
@@ -14,24 +14,45 @@ namespace xc::input {
constexpr uint16_t k8BitDoVid = 0x2DC8;
constexpr uint16_t k8BitDoUltimate24GPid = 0x3106;
+constexpr uint16_t kXbox360WiredVid = 0x045E;
+constexpr uint16_t kXbox360WiredPid = 0x028E;
+constexpr uint16_t kXbox360WirelessVid = 0x045E;
+constexpr uint16_t kXbox360WirelessPid1 = 0x0719;
+constexpr uint16_t kXbox360WirelessPid2 = 0x0291;
+
+constexpr uint16_t kXboxOneVid = 0x045E;
+constexpr uint16_t kXboxOnePid1 = 0x02D1;
+constexpr uint16_t kXboxOnePid2 = 0x02DD;
+constexpr uint16_t kXboxSeriesPid = 0x0B12;
+
+constexpr uint16_t kDualShock4Vid = 0x054C;
+constexpr uint16_t kDualShock4Pid1 = 0x05C4;
+constexpr uint16_t kDualShock4Pid2 = 0x09CC;
+
bool padUsbInit();
void padUsbShutdown();
bool pollUsbPad(ControllerState& out);
-// Parses raw 16-byte D-Input report from 8BitDo Ultimate 2.4G USB RF adapter:
-// byte 0: Left Stick X (0..255, center 128)
-// byte 1: Left Stick Y (0..255, center 128)
-// byte 2: Right Stick X (0..255, center 128)
-// byte 3: Right Stick Y (0..255, center 128)
-// byte 4: Left Trigger L2 (0..255)
-// byte 5: Right Trigger R2 (0..255)
-// byte 6: D-pad (hat switch 0..7 or bitmask)
-// byte 7: Buttons (A, B, X, Y, L1, R1, L2, R2)
-// byte 8: System Buttons (View/Select, Menu/Start, Nexus/Home, L3, R3)
-// bytes 9..15: telemetry/reserved
+// Parses raw 16-byte D-Input report from 8BitDo Ultimate 2.4G USB RF adapter
bool parse8BitDoDInputReport(const uint8_t* data, size_t len, ControllerState& out);
+// Parses Xbox 360 USB wired / wireless receiver reports (X-Input 14..20+ bytes)
+bool parseXbox360Report(const uint8_t* data, size_t len, ControllerState& out);
+
+// Parses Xbox One / Series USB reports (GIP 0x20 packets)
+bool parseXboxOneReport(const uint8_t* data, size_t len, ControllerState& out);
+
+// Parses DualShock 4 USB reports (64 bytes report 0x01)
+bool parseDualShock4Report(const uint8_t* data, size_t len, ControllerState& out);
+
+// Parses Generic Standard HID 14/16-button fightsticks and arcade sticks
+bool parseGenericArcadeReport(const uint8_t* data, size_t len, ControllerState& out);
+
+// Auto-detects device type and parses any supported USB HID report
+bool parseUsbPadReport(const uint8_t* data, size_t len, ControllerState& out);
+
// Test helper to inject reports in unit tests
void padUsbInjectReportForTesting(const uint8_t* data, size_t len);
+void padUsbInjectSlotReportForTesting(int slot, const uint8_t* data, size_t len);
} // namespace xc::input
diff --git a/src/media/audio_out_ps5.cpp b/src/media/audio_out_ps5.cpp
index d6ca7e9..c4f48f0 100644
--- a/src/media/audio_out_ps5.cpp
+++ b/src/media/audio_out_ps5.cpp
@@ -42,7 +42,6 @@ void loop() {
platform::setThreadRealtimePriority();
std::vector<float> grain(kGrain * 2);
AudioQueue& queue = audioQueue();
- float lowPass = 0.0f;
while (g_running) {
queue.pull(grain.data(), kGrain); // silence past what is queued
int h = g_handle;
@@ -51,19 +50,10 @@ void loop() {
continue;
}
- // Audio-to-Haptics: detect deep sub-bass impacts (cutoff ~100 Hz at 48 kHz)
- if (input::audioHapticsEnabled()) {
- float energy = 0.0f;
- for (unsigned i = 0; i < kGrain; ++i) {
- float mono = 0.5f * (grain[i * 2] + grain[i * 2 + 1]);
- lowPass += 0.013f * (mono - lowPass);
- energy += lowPass * lowPass;
- }
- energy /= static_cast<float>(kGrain);
- if (energy > 0.06f) {
- uint8_t kick = static_cast<uint8_t>(std::clamp((energy - 0.06f) * 1400.0f, 40.0f, 180.0f));
- input::setAudioHaptics(kick, 60);
- }
+ // Audio-to-Haptics on DualSense: 2nd-order IIR biquad lowpass filter & envelope kick
+ int hapticsLvl = media::audioHapticsLevel();
+ if (hapticsLvl > 0) {
+ media::audioToHaptics().process(grain.data(), kGrain, hapticsLvl);
}
// Blocks until the hardware wants the next grain (5.3 ms).
diff --git a/src/media/audio_out_sdl.cpp b/src/media/audio_out_sdl.cpp
index 7eba6c1..32e37d6 100644
--- a/src/media/audio_out_sdl.cpp
+++ b/src/media/audio_out_sdl.cpp
@@ -34,6 +34,10 @@ void SDLCALL feed(void*, SDL_AudioStream* stream, int needed, int) {
size_t frames = (static_cast<size_t>(needed) + 2 * sizeof(float) - 1) / (2 * sizeof(float));
if (g_buffer.size() < frames * 2) g_buffer.resize(frames * 2);
audioQueue().pull(g_buffer.data(), frames);
+ int hapticsLvl = audioHapticsLevel();
+ if (hapticsLvl > 0) {
+ audioToHaptics().process(g_buffer.data(), frames, hapticsLvl);
+ }
SDL_PutAudioStreamData(stream, g_buffer.data(), static_cast<int>(frames * 2 * sizeof(float)));
}
diff --git a/src/media/audio_queue.cpp b/src/media/audio_queue.cpp
index c5fbc78..7c86e67 100644
--- a/src/media/audio_queue.cpp
+++ b/src/media/audio_queue.cpp
@@ -4,10 +4,13 @@
// backend shares: pushing, the volume, the route.
#include "media/audio_queue.h"
+#include "input/controller.h"
#include "media/audio_out.h"
+#include "platform/platform.h"
#include "util/log.h"
#include <algorithm>
+#include <cmath>
namespace xc::media {
@@ -116,4 +119,103 @@ bool playVoiceAudio(const float* interleavedStereo, size_t frames) {
return true;
}
+static std::atomic<int> g_audioHapticsLevel{0};
+
+void setAudioHapticsLevel(int level) {
+ g_audioHapticsLevel.store(level, std::memory_order_relaxed);
+ input::setAudioHapticsEnabled(level > 0);
+}
+
+int audioHapticsLevel() {
+ return g_audioHapticsLevel.load(std::memory_order_relaxed);
+}
+
+AudioToHaptics& audioToHaptics() {
+ static AudioToHaptics s_instance;
+ return s_instance;
+}
+
+AudioToHaptics::AudioToHaptics() {
+ init(48000.0f, 120.0f);
+}
+
+void AudioToHaptics::init(float sampleRate, float cutoffHz) {
+ float w0 = 2.0f * 3.14159265358979323846f * cutoffHz / sampleRate;
+ float cosw0 = std::cos(w0);
+ float sinw0 = std::sin(w0);
+ float alpha = sinw0 / (2.0f * 0.70710678f);
+
+ float b0 = (1.0f - cosw0) * 0.5f;
+ float b1 = 1.0f - cosw0;
+ float b2 = (1.0f - cosw0) * 0.5f;
+ float a0 = 1.0f + alpha;
+ float a1 = -2.0f * cosw0;
+ float a2 = 1.0f - alpha;
+
+ b0_ = b0 / a0;
+ b1_ = b1 / a0;
+ b2_ = b2 / a0;
+ a1_ = a1 / a0;
+ a2_ = a2 / a0;
+
+ decay_ = std::exp(-1.0f / (sampleRate * 0.100f));
+ reset();
+}
+
+void AudioToHaptics::reset() {
+ x1_ = x2_ = y1_ = y2_ = 0.0f;
+ env_ = 0.0f;
+ lastKickMs_ = 0;
+}
+
+float AudioToHaptics::processSample(float inMono) {
+ float out = b0_ * inMono + b1_ * x1_ + b2_ * x2_ - a1_ * y1_ - a2_ * y2_;
+ x2_ = x1_;
+ x1_ = inMono;
+ y2_ = y1_;
+ y1_ = out;
+ if (std::abs(y1_) < 1e-15f) y1_ = 0.0f;
+ if (std::abs(y2_) < 1e-15f) y2_ = 0.0f;
+ return out;
+}
+
+void AudioToHaptics::process(const float* interleavedStereo, size_t frames, int level) {
+ if (level <= 0 || !interleavedStereo || frames == 0) return;
+
+ for (size_t i = 0; i < frames; ++i) {
+ float mono = 0.5f * (interleavedStereo[i * 2] + interleavedStereo[i * 2 + 1]);
+ float low = processSample(mono);
+ float e = low * low;
+ if (e > env_) {
+ env_ = e;
+ } else {
+ env_ *= decay_;
+ if (env_ < 1e-9f) env_ = 0.0f;
+ }
+ }
+
+ float thresh = 0.05f;
+ float mult = 1500.0f;
+ float minKick = 45.0f;
+ float maxKick = 190.0f;
+ if (level == 1) { // Baixo
+ thresh = 0.08f;
+ mult = 1200.0f;
+ minKick = 35.0f;
+ maxKick = 130.0f;
+ } else if (level == 3) { // Alto
+ thresh = 0.025f;
+ mult = 1800.0f;
+ minKick = 60.0f;
+ maxKick = 255.0f;
+ }
+
+ uint64_t now = platform::nowMs();
+ if (env_ > thresh && now >= lastKickMs_ + 55) {
+ uint8_t kick = static_cast<uint8_t>(std::clamp((env_ - thresh) * mult, minKick, maxKick));
+ input::setAudioHaptics(kick, 60);
+ lastKickMs_ = now;
+ }
+}
+
} // namespace xc::media
diff --git a/src/media/audio_queue.h b/src/media/audio_queue.h
index 89717f9..42b3d36 100644
--- a/src/media/audio_queue.h
+++ b/src/media/audio_queue.h
@@ -61,4 +61,27 @@ private:
// opens / closes it with its device.
AudioQueue& audioQueue();
+class AudioToHaptics {
+public:
+ AudioToHaptics();
+ void init(float sampleRate = 48000.0f, float cutoffHz = 120.0f);
+ void reset();
+ float processSample(float inMono);
+ void process(const float* interleavedStereo, size_t frames, int level);
+ float envelope() const { return env_; }
+
+private:
+ float b0_ = 0.0f, b1_ = 0.0f, b2_ = 0.0f;
+ float a1_ = 0.0f, a2_ = 0.0f;
+ float x1_ = 0.0f, x2_ = 0.0f;
+ float y1_ = 0.0f, y2_ = 0.0f;
+ float env_ = 0.0f;
+ float decay_ = 0.999f;
+ uint64_t lastKickMs_ = 0;
+};
+
+void setAudioHapticsLevel(int level);
+int audioHapticsLevel();
+AudioToHaptics& audioToHaptics();
+
} // namespace xc::media
diff --git a/src/platform/ps5/platform_ps5.cpp b/src/platform/ps5/platform_ps5.cpp
index 55e7411..fe471d2 100644
--- a/src/platform/ps5/platform_ps5.cpp
+++ b/src/platform/ps5/platform_ps5.cpp
@@ -83,7 +83,7 @@ void migrateLegacy() {
std::string text;
if (readFile(done, text)) return;
int moved = 0;
- for (const char* name : {"account.json", "settings.json", "library.json", "prices.json"}) {
+ for (const char* name : {"account.json", "settings.json", "library.json", "library_cache.json", "prices.json"}) {
std::string mine;
if (readFile(legacy + "/" + name, text) && !readFile(data + "/" + name, mine) &&
writeFileAtomic(data + "/" + name, text))
diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cpp
index 72c0e1f..10ce04c 100644
--- a/src/ui/app_ui.cpp
+++ b/src/ui/app_ui.cpp
@@ -62,16 +62,17 @@ constexpr int kResolutionOrder[3] = {1, 0, 2};
// stream (resolution, a desktop's display mode, 120 Hz, bitrate, region, network test);
// the controller, keyboard and queue-ready alert; support and updates last. A group starts at each
// kSettingsGroupStart.
-constexpr int kSettingsCount = 20;
-constexpr int kSettingsOrder[kSettingsCount] = {0, 8, 17, 1, 20, 13, 9, 10, 2, 18, 14, 12, 3, 15, 4, 5, 6, 16, 19, 7};
+constexpr int kSettingsCount = 21;
+constexpr int kSettingsOrder[kSettingsCount] = {0, 8, 17, 1, 20, 13, 9, 10, 2, 18, 14, 12, 3, 15, 4, 21, 5, 6, 16, 19, 7};
constexpr bool kSettingsGroupStart[kSettingsCount] = {false, false, false, true, false, false, false, false, false, false,
- true, false, false, false, false, false, false, false, true, false};
+ true, false, false, false, false, false, false, false, false, true, false};
// The game settings' rows on screen (ids: 0 profile, 1 upscaler, 2
// sharpness, 3 block smoothing, 4 resolution, 5 dead zone, 6 triggers, 7
// confirm, 8 120 Hz, 9 keyboard keys, 10 back to the default, 11 controller
-// buttons, 12 gyro aiming, 13 touchpad as mouse, 14 game language, 15 video decoder).
-constexpr int kGameRowOrder[16] = {0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 7, 12, 11, 13, 9, 10};
-constexpr bool kGameGroupStart[16] = {false, true, false, false, false, true, false, false, true, false, false, false, false, false, false, true};
+// buttons, 12 gyro aiming, 13 touchpad as mouse, 14 game language, 15 video decoder, 16 audio-to-haptics).
+constexpr int kGameRowCount = 17;
+constexpr int kGameRowOrder[kGameRowCount] = {0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 13, 9, 10};
+constexpr bool kGameGroupStart[kGameRowCount] = {false, true, false, false, false, true, false, false, true, false, false, false, false, false, false, false, true};
// The keyboard keys' screen: two columns of inputs, then "Reset to default".
constexpr int kKeysPerColumn = input::kKeyActions / 2;
// Updates on a desktop: the newest release's page (the app doesn't install it there).
@@ -244,6 +245,7 @@ std::vector<SettingsRowPos> visibleSettingsRows(const UiCaps& caps) {
return filterRows(kSettingsOrder, kSettingsGroupStart, [&](int row) {
switch (row) {
case 4: return caps.triggerRumble || caps.adaptiveTriggers; // trigger vibration and its tester
+ case 21: return caps.triggerRumble || caps.adaptiveTriggers; // audio-to-haptics
case 6: return caps.lightBar;
case 9: return caps.highRefresh;
case 13: return caps.desktopWindow;
@@ -267,6 +269,7 @@ std::vector<SettingsRowPos> visibleGameSettingsRows(const UiCaps& caps, bool cus
case 2: return caps.sharpen;
case 3: return caps.deband;
case 6: return caps.triggerRumble || caps.adaptiveTriggers;
+ case 16: return caps.triggerRumble || caps.adaptiveTriggers; // audio-to-haptics
case 8: return caps.highRefresh;
case 10: return custom;
case 12: return caps.gyro;
@@ -1718,6 +1721,7 @@ void AppUi::openGameSettings() {
activeGameProfile_.triggerHz = settings_.triggerHz;
activeGameProfile_.triggerResistance = settings_.triggerResistance;
activeGameProfile_.triggerPulses = settings_.triggerPulses;
+ activeGameProfile_.audioHaptics = settings_.audioHaptics;
activeGameProfile_.circleConfirms = settings_.circleConfirms;
activeGameProfile_.highRefresh = settings_.highRefresh;
activeGameProfile_.keyMap = settings_.keyMap;
@@ -1854,6 +1858,8 @@ std::vector<std::string> AppUi::settingOptions(int row) const {
out = {tr(Str::SupportKoFi)};
} else if (row == 20) {
out = {tr(Str::VideoDecoderHw), tr(Str::VideoDecoderSw)};
+ } else if (row == 21) {
+ out = {tr(Str::Off), tr(Str::SharpLow), tr(Str::SharpMedium), tr(Str::SharpHigh)};
} else if (row == 8) {
out.push_back(loginCountryOffText());
for (const char* country : kLoginCountries) out.push_back(loginCountryName(country));
@@ -1883,6 +1889,7 @@ int AppUi::settingSelected(int row) const {
if (row == 15) return std::clamp(settings_.gyroMode, 0, 2);
if (row == 16) return settings_.queueReadyAlert ? 1 : 0;
if (row == 20) return std::clamp(settings_.videoDecoder, 0, 1);
+ if (row == 21) return std::clamp(settings_.audioHaptics, 0, 3);
if (row == 10) {
if (settings_.maxBitrateMbps <= 0) return 0;
int closest = 1;
@@ -1945,6 +1952,8 @@ void AppUi::applySetting(int row, int index) {
settings_.queueReadyAlert = (index == 1);
} else if (row == 20) {
settings_.videoDecoder = index;
+ } else if (row == 21) {
+ settings_.audioHaptics = std::clamp(index, 0, 3);
} else if (row == 8) {
settings_.loginCountry = index == 0 ? std::string() : kLoginCountries[index - 1];
} else {
@@ -2660,6 +2669,11 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {
activeGameHasCustom_ = true;
dirty_ = true;
break;
+ case 16: // Audio-to-Haptics (0..3)
+ activeGameProfile_.audioHaptics = std::clamp(activeGameProfile_.audioHaptics + dir, 0, 3);
+ activeGameHasCustom_ = true;
+ dirty_ = true;
+ break;
case 7: // Confirm button
activeGameProfile_.circleConfirms = !activeGameProfile_.circleConfirms;
activeGameHasCustom_ = true;
@@ -2756,6 +2770,11 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {
dirty_ = true;
break;
}
+ case 16:
+ activeGameProfile_.audioHaptics = (activeGameProfile_.audioHaptics + 1) % 4;
+ activeGameHasCustom_ = true;
+ dirty_ = true;
+ break;
case 7:
activeGameProfile_.circleConfirms = !activeGameProfile_.circleConfirms;
activeGameHasCustom_ = true;
@@ -2817,6 +2836,7 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {
activeGameProfile_.triggerResistance = settings_.triggerResistance;
activeGameProfile_.triggerPulses = settings_.triggerPulses;
activeGameProfile_.triggerProfile = settings_.triggerProfile;
+ activeGameProfile_.audioHaptics = settings_.audioHaptics;
activeGameProfile_.circleConfirms = settings_.circleConfirms;
activeGameProfile_.highRefresh = settings_.highRefresh;
activeGameProfile_.gyroMode = gyroMode_;
@@ -5028,7 +5048,7 @@ void AppUi::drawSettings(Canvas& c) {
tr(Str::KeyboardKeys), tr(Str::DisplayMode), tr(Str::ControllerButtons),
tr(Str::Gyro), tr(Str::QueueReadyNotification),
tr(Str::CheckSignIn), tr(Str::NetworkTest), tr(Str::SupportProject),
- tr(Str::VideoDecoder)};
+ tr(Str::VideoDecoder), tr(Str::AudioHaptics)};
constexpr int kRowW = 1200, kRowH = 34, kGap = 2, kGroupGap = 6, kRowPx = 23;
Rect rows[kSettingRows]; // by row id
int y = 190;
@@ -5119,6 +5139,7 @@ void AppUi::drawSettings(Canvas& c) {
Str::SettingDescNetworkTest,
Str::SettingDescSupportProject,
Str::SettingDescVideoDecoder,
+ Str::SettingDescAudioHaptics,
};
if (settingsRow_ >= 0 && settingsRow_ < kSettingRows) {
int dy = 925;
@@ -6176,6 +6197,12 @@ void AppUi::drawGameSettings(Canvas& c) {
value = tr(kStrengths[std::clamp(activeGameProfile_.triggerStrength, 0, 4)]);
break;
}
+ case 16: {
+ label = tr(Str::AudioHaptics);
+ static constexpr Str kHapticsLevels[] = {Str::Off, Str::SharpLow, Str::SharpMedium, Str::SharpHigh};
+ value = tr(kHapticsLevels[std::clamp(activeGameProfile_.audioHaptics, 0, 3)]);
+ break;
+ }
case 7:
label = tr(Str::ConfirmButton);
break;
diff --git a/src/ui/app_ui.h b/src/ui/app_ui.h
index 7abec53..bcc95b9 100644
--- a/src/ui/app_ui.h
+++ b/src/ui/app_ui.h
@@ -122,6 +122,7 @@ struct SettingsChoice {
int triggerResistance = 0; // 0 off .. 3 strong
bool triggerPulses = false; // force pulses instead of the motor vibrating
int triggerProfile = 0; // 0 Standard, 1 Shooter, 2 Racing
+ int audioHaptics = 0; // 0 Off, 1 Low, 2 Med, 3 High
bool circleConfirms = false; // Circle is Xbox A (and Cross is B)
int lightBarMode = 0; // 0 the game's colour, 1 lightBarColour, 2 off
Color lightBarColour = rgba(0, 112, 220);
@@ -194,10 +195,10 @@ std::vector<SettingsRowPos> visibleGameSettingsRows(const UiCaps& caps, bool cus
// The largest stick dead zone Settings offers, in percent of the travel.
constexpr int kMaxDeadzone = 30;
-constexpr int kSettingRows = 21; // language, resolution, region, dead zone, triggers, confirm, light bar, updates,
+constexpr int kSettingRows = 22; // language, resolution, region, dead zone, triggers, confirm, light bar, updates,
// sign-in country, 120 Hz output, bitrate cap, game volume, keyboard keys,
// display mode (a desktop's window), controller buttons, gyro aiming, queue chime,
- // check sign-in, network test, support project, video decoder
+ // check sign-in, network test, support project, video decoder, audio-to-haptics
struct SignInStage {
std::string name;
diff --git a/src/ui/settings_choice.cpp b/src/ui/settings_choice.cpp
index 1bcb663..54ac017 100644
--- a/src/ui/settings_choice.cpp
+++ b/src/ui/settings_choice.cpp
@@ -21,6 +21,7 @@ SettingsChoice choiceFromSettings(const app::Settings& s) {
c.triggerResistance = s.triggerResistance;
c.triggerPulses = s.triggerPulses;
c.triggerProfile = s.triggerProfile;
+ c.audioHaptics = s.audioHaptics;
c.circleConfirms = s.circleConfirms;
c.lightBarMode = s.lightBarMode;
c.lightBarColour = s.lightBarColour;
@@ -55,6 +56,7 @@ void applyChoice(const SettingsChoice& c, app::Settings& s) {
s.triggerResistance = c.triggerResistance;
s.triggerPulses = c.triggerPulses;
s.triggerProfile = c.triggerProfile;
+ s.audioHaptics = c.audioHaptics;
s.circleConfirms = c.circleConfirms;
s.lightBarMode = c.lightBarMode;
s.lightBarColour = c.lightBarColour;
diff --git a/src/ui/strings.cpp b/src/ui/strings.cpp
index 691ae08..409b078 100644
--- a/src/ui/strings.cpp
+++ b/src/ui/strings.cpp
@@ -415,6 +415,8 @@ constexpr Column kEnglish = {
"Hardware (Recommended)", // VideoDecoderHw
"Software (CPU)", // VideoDecoderSw
"Selects hardware decoding (libSceVideodec2 on PS5, HWAccel on Desktop) or CPU software decoding", // SettingDescVideoDecoder
+ "Audio-to-Haptics", // AudioHaptics
+ "Converts low-frequency game audio into DualSense haptic rumble kicks", // SettingDescAudioHaptics
};
constexpr Column kPortugueseBR = {
@@ -800,6 +802,8 @@ constexpr Column kPortugueseBR = {
"Hardware (Recomendado)", // VideoDecoderHw
"Software (CPU)", // VideoDecoderSw
"Seleciona decodificação por hardware (libSceVideodec2 no PS5, HWAccel no Desktop) ou por software (CPU)", // SettingDescVideoDecoder
+ "Áudio para Vibração Háptica", // AudioHaptics
+ "Converte graves do áudio em vibração háptica no DualSense", // SettingDescAudioHaptics
};
constexpr Column kSpanish = {
@@ -1185,6 +1189,8 @@ constexpr Column kSpanish = {
"Hardware (Recomendado)", // VideoDecoderHw
"Software (CPU)", // VideoDecoderSw
"Selecciona decodificación por hardware (libSceVideodec2 en PS5, HWAccel en Desktop) o software (CPU)", // SettingDescVideoDecoder
+ "Audio a Vibración Háptica", // AudioHaptics
+ "Convierte frecuencias graves del audio en vibración háptica en DualSense", // SettingDescAudioHaptics
};
constexpr Column kFrench = {
@@ -1570,6 +1576,8 @@ constexpr Column kFrench = {
"Matériel (Recommandé)", // VideoDecoderHw
"Logiciel (CPU)", // VideoDecoderSw
"Sélectionne le décodage matériel (libSceVideodec2 sur PS5, HWAccel sur Desktop) ou logiciel (CPU)", // SettingDescVideoDecoder
+ "Audio vers vibration haptique", // AudioHaptics
+ "Convertit les basses fréquences audio en vibrations haptiques sur DualSense", // SettingDescAudioHaptics
};
constexpr Column kGerman = {
@@ -1955,6 +1963,8 @@ constexpr Column kGerman = {
"Hardware (Empfohlen)", // VideoDecoderHw
"Software (CPU)", // VideoDecoderSw
"Wählt Hardware-Dekodierung (libSceVideodec2 auf PS5, HWAccel auf Desktop) oder Software-Dekodierung (CPU)", // SettingDescVideoDecoder
+ "Audio-zu-Haptik", // AudioHaptics
+ "Wandelt tiefe Audiofrequenzen in DualSense-Haptik-Vibrationen um", // SettingDescAudioHaptics
};
constexpr Column kItalian = {
@@ -2340,6 +2350,8 @@ constexpr Column kItalian = {
"Hardware (Consigliato)", // VideoDecoderHw
"Software (CPU)", // VideoDecoderSw
"Seleziona decodifica hardware (libSceVideodec2 su PS5, HWAccel su Desktop) o software (CPU)", // SettingDescVideoDecoder
+ "Audio a vibrazione aptica", // AudioHaptics
+ "Converte le basse frequenze audio in vibrazioni aptiche su DualSense", // SettingDescAudioHaptics
};
constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,
diff --git a/src/ui/strings.h b/src/ui/strings.h
index fcc30c2..373b18f 100644
--- a/src/ui/strings.h
+++ b/src/ui/strings.h
@@ -392,6 +392,8 @@ enum class Str {
VideoDecoderHw,
VideoDecoderSw,
SettingDescVideoDecoder,
+ AudioHaptics,
+ SettingDescAudioHaptics,
Count
};
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 30c9543..4ce6d08 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -2068,8 +2068,8 @@ static void testVisibleSettingsRows() {
};
const ui::UiCaps ps5;
auto all = ui::visibleSettingsRows(ps5);
- CHECK((ids(all) == std::vector<int>{0, 8, 17, 1, 20, 9, 10, 2, 18, 14, 12, 3, 15, 4, 5, 6, 16, 19, 7}));
- CHECK((groups(all) == std::vector<bool>{false, false, false, true, false, false, false, false, false, true, false, false, false, false, false, false, false, true, false}));
+ CHECK((ids(all) == std::vector<int>{0, 8, 17, 1, 20, 9, 10, 2, 18, 14, 12, 3, 15, 4, 21, 5, 6, 16, 19, 7}));
+ CHECK((groups(all) == std::vector<bool>{false, false, false, true, false, false, false, false, false, true, false, false, false, false, false, false, false, false, true, false}));
ui::UiCaps pc;
pc.lightBar = pc.triggerRumble = pc.adaptiveTriggers = pc.gyro = pc.touchpad = false;
pc.upscalers = pc.sharpen = pc.deband = pc.highRefresh = pc.console = pc.selfUpdate = false;
@@ -2088,23 +2088,24 @@ static void testVisibleSettingsRows() {
auto x = ids(ui::visibleSettingsRows(xbox));
CHECK(std::find(x.begin(), x.end(), 4) != x.end() && std::find(x.begin(), x.end(), 6) == x.end());
// A game's settings.
- CHECK((ids(ui::visibleGameSettingsRows(ps5, true, false)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));
- CHECK((ids(ui::visibleGameSettingsRows(ps5, true, true)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 7, 12, 11, 13, 9, 10}));
+ CHECK((ids(ui::visibleGameSettingsRows(ps5, true, false)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 9, 10}));
+ CHECK((ids(ui::visibleGameSettingsRows(ps5, true, true)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 13, 9, 10}));
CHECK((groups(ui::visibleGameSettingsRows(ps5, true, true)) ==
- std::vector<bool>{false, true, false, false, false, true, false, false, true, false, false, false, false, false, false, true}));
- CHECK((ids(ui::visibleGameSettingsRows(ps5, false)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 7, 12, 11, 9}));
+ std::vector<bool>{false, true, false, false, false, true, false, false, true, false, false, false, false, false, false, false, true}));
+ CHECK((ids(ui::visibleGameSettingsRows(ps5, false)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 9}));
ui::UiCaps noTouch = ps5;
noTouch.touchpad = false;
- CHECK((ids(ui::visibleGameSettingsRows(noTouch, true, true)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));
+ CHECK((ids(ui::visibleGameSettingsRows(noTouch, true, true)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 9, 10}));
auto game = ui::visibleGameSettingsRows(pc, false);
CHECK((ids(game) == std::vector<int>{0, 4, 15, 14, 5, 7, 11, 9}));
CHECK((groups(game) == std::vector<bool>{false, true, false, false, true, false, false, false}));
// How far down the autoplay tests walk to each row (autoplay.cpp's downsTo).
CHECK(ui::settingsRowPosition(ps5, 1) == 3 && ui::settingsRowPosition(ps5, 3) == 11);
- CHECK(ui::settingsRowPosition(ps5, 16) == 16);
- CHECK(ui::settingsRowPosition(ps5, 5) == 14 && ui::settingsRowPosition(ps5, 6) == 15);
+ CHECK(ui::settingsRowPosition(ps5, 16) == 17);
+ CHECK(ui::settingsRowPosition(ps5, 5) == 15 && ui::settingsRowPosition(ps5, 6) == 16);
CHECK(ui::settingsRowPosition(ps5, 12) == 10 && ui::settingsRowPosition(ps5, 14) == 9);
- CHECK(ui::settingsRowPosition(ps5, 7) == 18 && ui::settingsRowPosition(ps5, 19) == 17 && ui::settingsRowPosition(ps5, 2) == 7);
+ CHECK(ui::settingsRowPosition(ps5, 7) == 19 && ui::settingsRowPosition(ps5, 19) == 18 && ui::settingsRowPosition(ps5, 2) == 7);
+ CHECK(ui::settingsRowPosition(ps5, 21) == 14);
CHECK(ui::settingsRowPosition(pc, 5) == 11 && ui::settingsRowPosition(pc, 6) == -1 && ui::settingsRowPosition(pc, 4) == -1);
}
@@ -4035,6 +4036,418 @@ static void testDesktopMouseNav() {
}
}
+static void testWebSocketRFC6455() {
+ // 1. RFC 6455 Handshake Accept Key test vector
+ // Standard test vector from RFC 6455 Section 4.2.2:
+ // Key: "dGhlIHNhbXBsZSBub25jZQ==" -> Accept: "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
+ std::string accept = app::ws::computeAccept("dGhlIHNhbXBsZSBub25jZQ==");
+ CHECK(accept == "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
+
+ // 2. Unmasked Text Frame
+ std::string textMsg = "{\"type\":\"ping\"}";
+ std::vector<uint8_t> frameText = app::ws::makeTextFrame(textMsg);
+ app::ws::Frame parsed;
+ size_t consumed = 0;
+ CHECK(app::ws::parseFrame(frameText.data(), frameText.size(), parsed, consumed));
+ CHECK(consumed == frameText.size());
+ CHECK(parsed.fin);
+ CHECK(parsed.opcode == app::ws::Opcode::Text);
+ CHECK(std::string(parsed.payload.begin(), parsed.payload.end()) == textMsg);
+
+ // 3. Masked Text Frame (as sent from client / browser)
+ uint8_t maskKey[4] = {0x37, 0xfa, 0x21, 0x3d};
+ std::string rawPayload = "Hello WebSocket";
+ std::vector<uint8_t> maskedFrame;
+ maskedFrame.push_back(static_cast<uint8_t>(0x81)); // FIN + Text
+ maskedFrame.push_back(static_cast<uint8_t>(0x80 | rawPayload.size())); // Masked + len
+ for (int i = 0; i < 4; ++i) maskedFrame.push_back(maskKey[i]);
+ for (size_t i = 0; i < rawPayload.size(); ++i) {
+ maskedFrame.push_back(static_cast<uint8_t>(rawPayload[i] ^ maskKey[i % 4]));
+ }
+ CHECK(app::ws::parseFrame(maskedFrame.data(), maskedFrame.size(), parsed, consumed));
+ CHECK(consumed == maskedFrame.size());
+ CHECK(std::string(parsed.payload.begin(), parsed.payload.end()) == rawPayload);
+
+ // 4. Binary Frame
+ std::vector<uint8_t> binData = {0x00, 0x01, 0x02, 0x03, 0x04, 0xFF, 0xFE};
+ std::vector<uint8_t> frameBin = app::ws::makeBinaryFrame(binData.data(), binData.size());
+ CHECK(app::ws::parseFrame(frameBin.data(), frameBin.size(), parsed, consumed));
+ CHECK(parsed.opcode == app::ws::Opcode::Binary);
+ CHECK(parsed.payload == binData);
+
+ // 5. Ping & Pong Frames
+ std::string pingStr = "heartbeat";
+ std::vector<uint8_t> pingPayload(pingStr.begin(), pingStr.end());
+ std::vector<uint8_t> framePing = app::ws::makeFrame(app::ws::Opcode::Ping, pingPayload.data(), pingPayload.size(), true);
+ CHECK(app::ws::parseFrame(framePing.data(), framePing.size(), parsed, consumed));
+ CHECK(parsed.opcode == app::ws::Opcode::Ping);
+ CHECK(parsed.payload == pingPayload);
+
+ std::vector<uint8_t> framePong = app::ws::makePongFrame(pingPayload);
+ CHECK(app::ws::parseFrame(framePong.data(), framePong.size(), parsed, consumed));
+ CHECK(parsed.opcode == app::ws::Opcode::Pong);
+ CHECK(parsed.payload == pingPayload);
+
+ // 6. Close Frame
+ std::vector<uint8_t> frameClose = app::ws::makeCloseFrame(1000);
+ CHECK(app::ws::parseFrame(frameClose.data(), frameClose.size(), parsed, consumed));
+ CHECK(parsed.opcode == app::ws::Opcode::Close);
+
+ // 7. parseGamepadJson test
+ std::string gpJson = R"({
+ "buttons": {
+ "a": true, "b": false, "x": true, "y": false,
+ "lb": true, "rb": false, "view": true, "menu": false,
+ "dpad_up": true, "dpad_down": false, "dpad_left": false, "dpad_right": true
+ },
+ "axes": {
+ "lx": -0.5, "ly": 0.75, "rx": 0.25, "ry": -0.8,
+ "lt": 0.6, "rt": 1.0
+ }
+ })";
+ auto j = json::parse(gpJson);
+ CHECK(j.has_value());
+ int slot = -1;
+ input::ControllerState cs{};
+ CHECK(app::parseGamepadJson(*j, slot, cs));
+ CHECK(slot == 0);
+ CHECK(cs.btnA == true);
+ CHECK(cs.btnB == false);
+ CHECK(cs.btnX == true);
+ CHECK(cs.btnY == false);
+ CHECK(cs.btnL1 == true);
+ CHECK(cs.btnR1 == false);
+ CHECK(cs.btnTouchpad == true);
+ CHECK(cs.btnOptions == false);
+ CHECK(cs.dpadUp == true);
+ CHECK(cs.dpadRight == true);
+ CHECK(std::abs(cs.leftStickX - (-0.5f)) < 0.01f);
+ CHECK(std::abs(cs.leftStickY - 0.75f) < 0.01f);
+ CHECK(std::abs(cs.rightStickX - 0.25f) < 0.01f);
+ CHECK(std::abs(cs.rightStickY - (-0.8f)) < 0.01f);
+ CHECK(std::abs(cs.triggerL2 - 0.6f) < 0.01f);
+ CHECK(std::abs(cs.triggerR2 - 1.0f) < 0.01f);
+
+ // 8. W3C Gamepad API standard arrays
+ std::string w3cJson = R"({
+ "player": 2,
+ "buttons": [
+ {"pressed": true, "value": 1.0},
+ {"pressed": false, "value": 0.0},
+ {"pressed": true, "value": 1.0},
+ {"pressed": false, "value": 0.0},
+ {"pressed": true, "value": 1.0},
+ {"pressed": false, "value": 0.0},
+ {"pressed": true, "value": 0.85},
+ {"pressed": true, "value": 0.95},
+ {"pressed": true, "value": 1.0},
+ {"pressed": false, "value": 0.0},
+ {"pressed": false, "value": 0.0},
+ {"pressed": true, "value": 1.0},
+ {"pressed": true, "value": 1.0},
+ {"pressed": false, "value": 0.0},
+ {"pressed": false, "value": 0.0},
+ {"pressed": true, "value": 1.0},
+ {"pressed": true, "value": 1.0}
+ ],
+ "axes": [0.45, -0.65, -0.3, 0.8]
+ })";
+ auto jW3c = json::parse(w3cJson);
+ CHECK(jW3c.has_value());
+ int w3cSlot = -1;
+ input::ControllerState csW3c{};
+ CHECK(app::parseGamepadJson(*jW3c, w3cSlot, csW3c));
+ CHECK(w3cSlot == 1); // player 2 -> slot 1
+ CHECK(csW3c.btnA == true);
+ CHECK(csW3c.btnB == false);
+ CHECK(csW3c.btnX == true);
+ CHECK(csW3c.btnY == false);
+ CHECK(csW3c.btnL1 == true);
+ CHECK(csW3c.btnR1 == false);
+ CHECK(std::abs(csW3c.triggerL2 - 0.85f) < 0.01f);
+ CHECK(std::abs(csW3c.triggerR2 - 0.95f) < 0.01f);
+ CHECK(csW3c.btnTouchpad == true); // index 8 View
+ CHECK(csW3c.btnOptions == false); // index 9 Menu
+ CHECK(csW3c.btnL3 == false); // index 10
+ CHECK(csW3c.btnR3 == true); // index 11
+ CHECK(csW3c.dpadUp == true); // index 12
+ CHECK(csW3c.dpadDown == false); // index 13
+ CHECK(csW3c.dpadLeft == false); // index 14
+ CHECK(csW3c.dpadRight == true); // index 15
+ CHECK(csW3c.btnNexus == true); // index 16 Guide
+ CHECK(std::abs(csW3c.leftStickX - 0.45f) < 0.01f);
+ CHECK(std::abs(csW3c.leftStickY - (-0.65f)) < 0.01f);
+ CHECK(std::abs(csW3c.rightStickX - (-0.3f)) < 0.01f);
+ CHECK(std::abs(csW3c.rightStickY - 0.8f) < 0.01f);
+}
+
+static void testExpandedUsbControllers() {
+ // 1. Xbox 360 controller report decoding (14 bytes)
+ uint8_t x360[14] = {
+ 0x00, 0x14,
+ 0x11, // A (0x10) | DPAD_UP (0x01)
+ 0x12, // Start (0x10) | RB (0x02)
+ 128, // LT (50%)
+ 255, // RT (100%)
+ 0x00, 0x40, // LX = +16384 (~0.5)
+ 0x00, 0xC0, // LY = -16384 (-0.5 raw -> +0.5 normalised)
+ 0x00, 0x00, 0x00, 0x00
+ };
+ input::ControllerState cs360{};
+ CHECK(input::parseXbox360Report(x360, sizeof(x360), cs360));
+ CHECK(cs360.btnA == true);
+ CHECK(cs360.dpadUp == true);
+ CHECK(cs360.btnOptions == true);
+ CHECK(cs360.btnR1 == true);
+ CHECK(std::abs(cs360.triggerL2 - 0.5019f) < 0.01f);
+ CHECK(std::abs(cs360.triggerR2 - 1.0f) < 0.01f);
+ CHECK(std::abs(cs360.leftStickX - 0.5f) < 0.02f);
+ CHECK(std::abs(cs360.leftStickY - 0.5f) < 0.02f);
+
+ // 2. Xbox One / Series controller report decoding (18 bytes min, 0x20 header)
+ uint8_t xone[18] = {
+ 0x20, 0x00, 0x01, 0x0c,
+ 0x50, // A (0x10) | X (0x40)
+ 0x01, // D-pad Up
+ 0x00, 0x02, // LT = 512 (~0.5)
+ 0xFF, 0x03, // RT = 1023 (1.0)
+ 0x00, 0x40, // LX = +16384 (0.5)
+ 0x00, 0x80, // LY = -32768 (1.0)
+ 0x00, 0x00, 0x00, 0x00
+ };
+ input::ControllerState csOne{};
+ CHECK(input::parseXboxOneReport(xone, sizeof(xone), csOne));
+ CHECK(csOne.btnA == true);
+ CHECK(csOne.btnX == true);
+ CHECK(csOne.btnB == false);
+ CHECK(csOne.dpadUp == true);
+ CHECK(std::abs(csOne.triggerL2 - 0.5f) < 0.02f);
+ CHECK(std::abs(csOne.triggerR2 - 1.0f) < 0.01f);
+ CHECK(std::abs(csOne.leftStickX - 0.5f) < 0.02f);
+ CHECK(std::abs(csOne.leftStickY - 1.0f) < 0.02f);
+
+ // 3. DualShock 4 controller report decoding (10 bytes min)
+ uint8_t ds4[10] = {
+ 0x01,
+ 255, // LX full right (+1.0)
+ 0, // LY full up (-1.0 -> inverted is -1.0)
+ 128, 128,
+ 0x20 | 0x02, // Cross (Xbox A) | D-pad East (Right)
+ 0x02 | 0x20, // R1 (RB) | Options (Menu)
+ 0x00,
+ 0, 255 // RT = 1.0
+ };
+ input::ControllerState csDs4{};
+ CHECK(input::parseDualShock4Report(ds4, sizeof(ds4), csDs4));
+ CHECK(csDs4.btnA == true);
+ CHECK(csDs4.dpadRight == true);
+ CHECK(csDs4.btnR1 == true);
+ CHECK(csDs4.btnOptions == true);
+ CHECK(std::abs(csDs4.triggerR2 - 1.0f) < 0.01f);
+ CHECK(std::abs(csDs4.leftStickX - 1.0f) < 0.02f);
+
+ // 4. Generic Arcade Stick (6 bytes min)
+ uint8_t arcade[6] = {
+ 0, // Left
+ 128, // Center Y
+ 128, 128,
+ 0x01 | 0x04, // Button 1 (A) | Button 3 (X)
+ 0x01 // Button 9 (Select/View)
+ };
+ input::ControllerState csArcade{};
+ CHECK(input::parseGenericArcadeReport(arcade, sizeof(arcade), csArcade));
+ CHECK(csArcade.btnA == true);
+ CHECK(csArcade.btnX == true);
+ CHECK(csArcade.btnTouchpad == true);
+ CHECK(csArcade.dpadLeft == true);
+
+ // 5. parseUsbPadReport auto-detection
+ input::ControllerState csAuto{};
+ CHECK(input::parseUsbPadReport(x360, sizeof(x360), csAuto));
+ CHECK(csAuto.btnA == true);
+ CHECK(csAuto.btnR1 == true);
+
+ CHECK(input::parseUsbPadReport(xone, sizeof(xone), csAuto));
+ CHECK(csAuto.btnA == true);
+ CHECK(csAuto.btnX == true);
+
+ CHECK(input::parseUsbPadReport(ds4, sizeof(ds4), csAuto));
+ // 6. Wireless receiver on non-zero slot (slot 1)
+ uint8_t x360WirelessSlot1[18] = {
+ 0x00, 0x01, 0x00, 0x14,
+ 0x01, // b1: D-pad Up (0x01)
+ 0x12, // b2: A (0x10) | RB (0x02)
+ 0, 255, // LT=0, RT=255
+ 0x00, 0x40, // LX = +16384 (0.5)
+ 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+ };
+ input::ControllerState csWireless{};
+ CHECK(input::parseXbox360Report(x360WirelessSlot1, sizeof(x360WirelessSlot1), csWireless));
+ CHECK(csWireless.dpadUp == true);
+ CHECK(csWireless.btnA == true);
+ CHECK(csWireless.btnR1 == true);
+ CHECK(std::abs(csWireless.triggerR2 - 1.0f) < 0.01f);
+ CHECK(input::parseUsbPadReport(x360WirelessSlot1, sizeof(x360WirelessSlot1), csWireless));
+ CHECK(csWireless.dpadUp == true);
+ CHECK(csWireless.btnA == true);
+
+ // 7. Multi-slot simultaneous UHID injection & merging (Xbox 360 on slot 0 + DS4 on slot 1)
+ input::padUsbInit();
+ input::padUsbInjectSlotReportForTesting(0, x360, sizeof(x360));
+ input::padUsbInjectSlotReportForTesting(1, ds4, sizeof(ds4));
+
+ input::ControllerState mergedSlots{};
+ CHECK(input::pollUsbPad(mergedSlots));
+ CHECK(mergedSlots.connected);
+ CHECK(mergedSlots.btnA == true); // From slot 0 (x360) and slot 1 (ds4)
+ CHECK(mergedSlots.btnR1 == true); // From slot 0 & slot 1
+ CHECK(mergedSlots.dpadUp == true); // From slot 0
+ CHECK(mergedSlots.dpadRight == true); // From slot 1
+ CHECK(std::abs(mergedSlots.leftStickX - 1.0f) < 0.02f); // Further(0.5, 1.0) -> 1.0
+ CHECK(std::abs(mergedSlots.triggerR2 - 1.0f) < 0.01f);
+
+ // Unplug slot 0 -> slot 1 remains active
+ input::padUsbInjectSlotReportForTesting(0, nullptr, 0);
+ input::ControllerState slot1Only{};
+ CHECK(input::pollUsbPad(slot1Only));
+ CHECK(slot1Only.connected);
+ CHECK(slot1Only.dpadUp == false); // Slot 0 gone
+ CHECK(slot1Only.dpadRight == true); // Slot 1 still present
+ CHECK(slot1Only.btnR1 == true);
+
+ input::padUsbShutdown();
+}
+
+static void testAudioToHaptics() {
+ media::AudioToHaptics filter;
+ filter.init(48000.0f, 120.0f);
+
+ // 1. Frequency response: 50 Hz sine wave (sub-bass in passband)
+ constexpr size_t kSamples = 960; // 20 ms
+ std::vector<float> sine50(kSamples * 2);
+ for (size_t i = 0; i < kSamples; ++i) {
+ float s = std::sin(2.0f * 3.14159265f * 50.0f * i / 48000.0f);
+ sine50[i * 2] = s;
+ sine50[i * 2 + 1] = s;
+ }
+ float energyPass = 0.0f;
+ for (size_t i = 0; i < kSamples; ++i) {
+ float filtered = filter.processSample(sine50[i * 2]);
+ if (i >= 480) energyPass += filtered * filtered;
+ }
+ energyPass /= 480.0f;
+ CHECK(energyPass > 0.35f); // High passband transmission
+
+ // 2. Frequency response: 1000 Hz sine wave (treble in stopband)
+ filter.reset();
+ std::vector<float> sine1000(kSamples * 2);
+ for (size_t i = 0; i < kSamples; ++i) {
+ float s = std::sin(2.0f * 3.14159265f * 1000.0f * i / 48000.0f);
+ sine1000[i * 2] = s;
+ sine1000[i * 2 + 1] = s;
+ }
+ float energyStop = 0.0f;
+ for (size_t i = 0; i < kSamples; ++i) {
+ float filtered = filter.processSample(sine1000[i * 2]);
+ if (i >= 480) energyStop += filtered * filtered;
+ }
+ energyStop /= 480.0f;
+ CHECK(energyStop < 0.005f); // > 20 dB strong high-frequency attenuation
+
+ // 3. Envelope decay (~100 ms decay test)
+ filter.reset();
+ constexpr size_t kBurstSamples = 2400; // 50 ms of 50 Hz sub-bass burst
+ std::vector<float> burst(kBurstSamples * 2);
+ for (size_t i = 0; i < kBurstSamples; ++i) {
+ float s = std::sin(2.0f * 3.14159265f * 50.0f * i / 48000.0f);
+ burst[i * 2] = s;
+ burst[i * 2 + 1] = s;
+ }
+ filter.process(burst.data(), kBurstSamples, 2);
+ float envPeak = filter.envelope();
+ CHECK(envPeak > 0.0f);
+ std::vector<float> silence(4800 * 2, 0.0f); // 100 ms of silence
+ filter.process(silence.data(), 4800, 2);
+ float envDecayed = filter.envelope();
+ CHECK(envDecayed < envPeak * 0.40f); // Decayed significantly over ~100 ms
+
+ // 4. Sensitivity levels & kick activation
+ media::setAudioHapticsLevel(0);
+ CHECK(media::audioHapticsLevel() == 0);
+ CHECK(!input::audioHapticsEnabled());
+
+ media::setAudioHapticsLevel(2); // Medium
+ CHECK(media::audioHapticsLevel() == 2);
+ CHECK(input::audioHapticsEnabled());
+
+ // 5. Settings and GameProfile serialization roundtrip
+ app::Settings s;
+ s.audioHaptics = 3; // Alto
+ app::GameProfile gp = s.defaultProfile();
+ CHECK(gp.audioHaptics == 3);
+ gp.audioHaptics = 1; // Baixo
+ s.perGame["TEST_GAME"] = gp;
+
+ std::string testPath = "/tmp/test_haptics_settings.json";
+ CHECK(s.save(testPath));
+
+ app::Settings sLoaded;
+ CHECK(sLoaded.load(testPath));
+ CHECK(sLoaded.audioHaptics == 3);
+ CHECK(sLoaded.perGame["TEST_GAME"].audioHaptics == 1);
+ ::unlink(testPath.c_str());
+}
+
+static void testLibraryOfflineCache() {
+ std::string cacheFile = "/tmp/test_library_cache.json";
+ ::unlink(cacheFile.c_str());
+
+ // 1. Populate a library instance and save cache
+ {
+ app::Library lib;
+ lib.setCachePath(cacheFile);
+ lib.markAsOwned("PROD_1001", "TITLE_1001");
+ lib.markAsOwned("PROD_1002", "TITLE_1002");
+ CHECK(lib.ownedKnown());
+ CHECK(lib.owned().size() == 2);
+ lib.saveCache();
+ }
+
+ // 2. Instant-resume load from library_cache.json without network
+ {
+ app::Library libResume;
+ libResume.setCachePath(cacheFile);
+ CHECK(libResume.loadCache(true));
+ CHECK(libResume.ownedKnown());
+ CHECK(libResume.owned().size() == 2);
+ }
+
+ // 3. Fallback to library.json when cachePath doesn't exist
+ std::string legacyFile = "/tmp/library.json";
+ ::rename(cacheFile.c_str(), legacyFile.c_str());
+ {
+ app::Library libFallback;
+ libFallback.setCachePath(cacheFile); // pointing to non-existent library_cache.json
+ CHECK(libFallback.loadCache(true)); // should successfully fall back to library.json
+ CHECK(libFallback.ownedKnown());
+ CHECK(libFallback.owned().size() == 2);
+ }
+ ::unlink(legacyFile.c_str());
+
+ // 4. Empty cache robustness test
+ std::string emptyCacheFile = "/tmp/test_empty_cache.json";
+ ::unlink(emptyCacheFile.c_str());
+ {
+ app::Library libEmpty;
+ libEmpty.setCachePath(emptyCacheFile);
+ CHECK(!libEmpty.loadCache(true)); // no file
+ platform::writeFileAtomic(emptyCacheFile, "{}");
+ CHECK(!libEmpty.loadCache(true)); // version mismatch
+ }
+ ::unlink(emptyCacheFile.c_str());
+}
+
int main() {
testBlock3Features();
testWishlist();
@@ -4107,6 +4520,10 @@ int main() {
testVoiceRouting();
testUsbPad8BitDo();
testDesktopMouseNav();
+ testWebSocketRFC6455();
+ testExpandedUsbControllers();
+ testAudioToHaptics();
+ testLibraryOfflineCache();
if (g_failures) {
std::fprintf(stderr, "%d failure(s)\n", g_failures);
return 1;