Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

feat: complete roadmap priorities 2 through 5b (WebUI controls, desktop mouse navigation, Windows/Android scaffolding, adaptive voice chat, and 8BitDo USB driver)

Rafael Abud Ferreiraa349ac78b11b
diff --git a/CMakeLists.txt b/CMakeLists.txt
index b9fa1e0..3fa9a0e 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -41,10 +41,10 @@ add_library(xcloud_core STATIC
src/input/key_map.cpp
src/input/pad_map.cpp
src/input/keyboard_nav.cpp
+ src/input/pad_usb.cpp
src/input/sdl_mapping.cpp
src/xcloud/social.cpp
src/xcloud/achievements.cpp
- src/platform/posix_common.cpp
src/platform/toasts.cpp
src/input/gyro.cpp
)
@@ -144,13 +144,19 @@ if(XCLOUD_PS5)
src/media/audio_out_ps5.cpp
src/media/audio_in_ps5.cpp
)
+ target_sources(xcloud_core PRIVATE src/platform/posix_common.cpp)
target_include_directories(xcloud_app PRIVATE "${PS5_RADV}/include")
# The USB keyboard / mouse backend kept the warnings it had in xcloud_core.
set_source_files_properties(src/input/kbm_ps5.cpp PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra;-Wno-unused-parameter")
target_link_libraries(xcloud_app PUBLIC xcloud_stream xcloud_media xcloud_ui)
else()
target_link_libraries(xcloud_core PUBLIC Threads::Threads)
- target_sources(xcloud_core PRIVATE src/platform/linux/platform_linux.cpp)
+ if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Windows")
+ target_link_libraries(xcloud_core PUBLIC ws2_32 crypt32 iphlpapi winmm secur32)
+ target_sources(xcloud_core PRIVATE src/platform/windows/platform_windows.cpp)
+ else()
+ target_sources(xcloud_core PRIVATE src/platform/posix_common.cpp src/platform/linux/platform_linux.cpp)
+ endif()
# No screen, pads, USB keyboard or hardware decoder: what a desktop
# build links in place of the PS5's backends (docs/multiplatform.md).
diff --git a/ROADMAP.md b/ROADMAP.md
index 43be4d7..ffd86f0 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -242,13 +242,13 @@ is rolled back at the next start), then the app restarts itself
| Priority | Item | Why | Size |
| :---: | --- | --- | --- |
-| **1** | **Hardware video decoding (PS5 & other platforms)** | Integrate `libSceVideodec2` (sysmodule 207) into the active streaming pipeline (`StreamPlayer`) on PS5 to free an entire Zen 2 CPU core, reduce jitter/thermals, and map NV12 to Vulkan textures; enable VA-API / NVDEC via FFmpeg hwaccel on desktop/Steam Deck | medium–large |
-| **2** | **Expanded WebUI features & in-stream Game Menu** | Expand local HTTP server (port 8080): **Streaming Lock** (transparent backdrop-filter blur overlay and HTTP 409 rejection blocking search and 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 |
-| **3** | **Mouse navigation in desktop UI** | 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 (planned)** | Cross-compiled with `llvm-mingw` (or native MSVC/CMake), SDL3/Vulkan backend, XInput & DualSense controller integration, portable standalone `.zip` distribution | medium |
-| **4b** | **Native Android build (planned)** | Android NDK (C++20) + Java/Kotlin wrapper, hardware video decoding via `AMediaCodec`, customizable on-screen touch overlay controls, and Bluetooth gamepad support | large |
-| **5** | **Adaptive Voice Chat (DualSense mic & speaker with fallback)** | 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** | Direct `/dev/uhid*` or `libusb` driver bypass on jailbroken PS5 to support 8BitDo Ultimate 2.4G USB RF dongle (`0x2DC8:0x3106`) without requiring `libScePad` authentication; alternative paths via WebUI virtual gamepad and hardware converters | medium |
+| **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 |
+| **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 |
| **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/android/app/build.gradle.kts b/android/app/build.gradle.kts
new file mode 100644
index 0000000..e8a5520
--- /dev/null
+++ b/android/app/build.gradle.kts
@@ -0,0 +1,58 @@
+plugins {
+ id("com.android.application")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "com.rafaelngp.psbox"
+ compileSdk = 34
+
+ defaultConfig {
+ applicationId = "com.rafaelngp.psbox"
+ minSdk = 26
+ targetSdk = 34
+ versionCode = 140
+ versionName = "1.4.0"
+
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
+ ndk {
+ abiFilters.addAll(listOf("arm64-v8a", "x86_64"))
+ }
+ externalNativeBuild {
+ cmake {
+ cppFlags += listOf("-std=c++20", "-Wall", "-Wextra")
+ arguments += listOf("-DANDROID_STL=c++_shared")
+ }
+ }
+ }
+
+ buildTypes {
+ release {
+ isMinifyEnabled = false
+ proguardFiles(
+ getDefaultProguardFile("proguard-android-optimize.txt"),
+ "proguard-rules.pro"
+ )
+ }
+ }
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+ kotlinOptions {
+ jvmTarget = "17"
+ }
+ externalNativeBuild {
+ cmake {
+ path = file("src/main/cpp/CMakeLists.txt")
+ version = "3.22.1"
+ }
+ }
+}
+
+dependencies {
+ implementation("androidx.core:core-ktx:1.12.0")
+ implementation("androidx.appcompat:appcompat:1.6.1")
+ implementation("com.google.android.material:material:1.11.0")
+ implementation("androidx.games:games-activity:3.0.5")
+}
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..0e3644b
--- /dev/null
+++ b/android/app/src/main/AndroidManifest.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.RECORD_AUDIO" />
+ <uses-permission android:name="android.permission.VIBRATE" />
+
+ <application
+ android:allowBackup="true"
+ android:icon="@mipmap/ic_launcher"
+ android:label="PSBox"
+ android:roundIcon="@mipmap/ic_launcher_round"
+ android:supportsRtl="true"
+ android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
+ <activity
+ android:name=".MainActivity"
+ android:exported="true"
+ android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|keyboard"
+ android:screenOrientation="sensorLandscape">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
diff --git a/android/app/src/main/cpp/CMakeLists.txt b/android/app/src/main/cpp/CMakeLists.txt
new file mode 100644
index 0000000..813c174
--- /dev/null
+++ b/android/app/src/main/cpp/CMakeLists.txt
@@ -0,0 +1,26 @@
+cmake_minimum_required(VERSION 3.22.1)
+project(psbox_android)
+
+set(CMAKE_CXX_STANDARD 20)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+set(ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../..")
+
+find_library(log-lib log)
+find_library(android-lib android)
+find_library(mediandk-lib mediandk)
+
+add_library(psbox SHARED
+ "${ROOT_DIR}/src/platform/android/platform_android.cpp"
+ "${ROOT_DIR}/src/media/hw_decoder_android.cpp"
+)
+
+target_include_directories(psbox PRIVATE
+ "${ROOT_DIR}/src"
+)
+
+target_link_libraries(psbox
+ ${log-lib}
+ ${android-lib}
+ ${mediandk-lib}
+)
diff --git a/android/build.gradle.kts b/android/build.gradle.kts
new file mode 100644
index 0000000..3ac83c6
--- /dev/null
+++ b/android/build.gradle.kts
@@ -0,0 +1,4 @@
+plugins {
+ id("com.android.application") version "8.3.0" apply false
+ id("org.jetbrains.kotlin.android") version "1.9.22" apply false
+}
diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts
new file mode 100644
index 0000000..0899738
--- /dev/null
+++ b/android/settings.gradle.kts
@@ -0,0 +1,17 @@
+pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+rootProject.name = "PSBox"
+include(":app")
diff --git a/src/app/app_core.cpp b/src/app/app_core.cpp
index 528271e..bd78864 100644
--- a/src/app/app_core.cpp
+++ b/src/app/app_core.cpp
@@ -24,6 +24,7 @@
#include "input/kbm.h"
#include "input/keyboard_nav.h"
#include "input/pad_map.h"
+#include "input/pad_usb.h"
#include "ui/input_mode.h"
#include "ui/pad_glyphs.h"
#include "input/tuning.h"
@@ -159,6 +160,7 @@ struct Core {
bool quitAsked_ = false; // desktop: "Close PSBox?" confirmed on the home screen
explicit Core(bool withDisplay) : haveDisplay(withDisplay) {}
bool frame();
+ void dispatchUiAction(const ui::UiEvent& ev);
// The slot showing the keyboard (-1 none): the keyboard's player, while
// the keyboard was used after that player's own controller (or it has none).
@@ -300,6 +302,19 @@ bool coreStartup() {
std::lock_guard<std::mutex> lock(g_settingsMutex);
root.set("language", g_settings.language);
root.set("resolution", g_settings.resolution);
+ root.set("maxBitrateMbps", g_settings.maxBitrateMbps);
+ root.set("highRefresh", g_settings.highRefresh);
+ root.set("deadzoneLeft", g_settings.deadzoneLeft);
+ root.set("deadzoneRight", g_settings.deadzoneRight);
+ root.set("lightBarMode", g_settings.lightBarMode);
+ char hex[8];
+ std::snprintf(hex, sizeof hex, "#%02X%02X%02X", static_cast<unsigned>(g_settings.lightBarColour & 0xFF),
+ 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("queueReadyAlert", g_settings.queueReadyAlert);
+ root.set("videoDecoder", g_settings.videoDecoder);
+ root.set("voiceRouting", g_settings.voiceRouting);
root.set("padMap", input::padMapJson(g_settings.padMap));
root.set("keyMap", keyMapToJson(g_settings.keyMap));
},
@@ -307,6 +322,51 @@ bool coreStartup() {
bool changed = false;
{
std::lock_guard<std::mutex> lock(g_settingsMutex);
+ if (root.has("voiceRouting")) {
+ g_settings.voiceRouting = static_cast<int>(std::clamp<int64_t>(root["voiceRouting"].asInt(g_settings.voiceRouting), 0, 1));
+ media::audioSetVoiceRouting(g_settings.voiceRouting);
+ changed = true;
+ }
+ if (root.has("maxBitrateMbps")) {
+ g_settings.maxBitrateMbps = static_cast<int>(std::clamp<int64_t>(root["maxBitrateMbps"].asInt(g_settings.maxBitrateMbps), 0, 50));
+ changed = true;
+ }
+ if (root.has("highRefresh")) {
+ g_settings.highRefresh = root["highRefresh"].asBool(g_settings.highRefresh);
+ changed = true;
+ }
+ if (root.has("deadzoneLeft")) {
+ g_settings.deadzoneLeft = static_cast<int>(std::clamp<int64_t>(root["deadzoneLeft"].asInt(g_settings.deadzoneLeft), 0, 50));
+ changed = true;
+ }
+ if (root.has("deadzoneRight")) {
+ g_settings.deadzoneRight = static_cast<int>(std::clamp<int64_t>(root["deadzoneRight"].asInt(g_settings.deadzoneRight), 0, 50));
+ changed = true;
+ }
+ if (root.has("lightBarMode")) {
+ g_settings.lightBarMode = static_cast<int>(std::clamp<int64_t>(root["lightBarMode"].asInt(g_settings.lightBarMode), 0, 2));
+ changed = true;
+ }
+ if (root.has("lightBarColour") && root["lightBarColour"].isString()) {
+ std::string hexStr = root["lightBarColour"].str();
+ if (hexStr.size() == 7 && hexStr[0] == '#') {
+ uint32_t rgb = static_cast<uint32_t>(std::strtoul(hexStr.c_str() + 1, nullptr, 16));
+ g_settings.lightBarColour = 0xFF000000u | (rgb >> 16 & 0xFF) | (rgb & 0xFF00) | (rgb & 0xFF) << 16;
+ changed = true;
+ }
+ }
+ if (root.has("triggerStrength")) {
+ g_settings.triggerStrength = static_cast<int>(std::clamp<int64_t>(root["triggerStrength"].asInt(g_settings.triggerStrength), 0, 4));
+ changed = true;
+ }
+ if (root.has("queueReadyAlert")) {
+ g_settings.queueReadyAlert = root["queueReadyAlert"].asBool(g_settings.queueReadyAlert);
+ changed = true;
+ }
+ if (root.has("videoDecoder")) {
+ g_settings.videoDecoder = static_cast<int>(std::clamp<int64_t>(root["videoDecoder"].asInt(g_settings.videoDecoder), 0, 1));
+ changed = true;
+ }
if (root.has("padMap")) {
input::PadMap newPad;
if (input::readPadMap(root["padMap"], newPad)) {
@@ -320,6 +380,7 @@ bool coreStartup() {
}
if (changed) {
g_settings.save(settingsPath());
+ applyControllerSettings();
refreshSettingsUiLocked();
}
}
@@ -386,7 +447,71 @@ bool coreStartup() {
return (g_ui && (g_ui->screen() == ui::Screen::Streaming || g_ui->screen() == ui::Screen::Launching)) ||
(g_player && g_player->running());
},
- /*injectGamepad=*/nullptr
+ /*injectGamepad=*/nullptr,
+ /*getTelemetry=*/[](json::Value& stats) {
+ std::lock_guard<std::mutex> lock(g_infoMutex);
+ stats.set("fps", g_streamInfo.fps);
+ stats.set("rttMs", g_streamInfo.rttMs);
+ stats.set("mbps", g_streamInfo.mbps);
+ stats.set("lossPct", g_streamInfo.lossPct);
+ stats.set("qp", g_streamInfo.qp);
+ stats.set("decodeMs", g_streamInfo.decodeMs);
+ stats.set("isHwDecode", g_streamInfo.isHwDecode);
+ stats.set("width", g_streamInfo.width);
+ stats.set("height", g_streamInfo.height);
+ },
+ /*getStreamMenuState=*/[](json::Value& menu) {
+ std::lock_guard<std::mutex> lock(g_settingsMutex);
+ menu.set("sharpness", g_settings.sharpness);
+ menu.set("upscaler", g_settings.upscaler);
+ menu.set("deband", g_settings.deband);
+ menu.set("padSpeakerVolume", g_settings.padSpeakerVolume);
+ menu.set("triggerProfile", g_settings.triggerProfile);
+ },
+ /*updateStreamMenu=*/[](const json::Value& update) -> bool {
+ bool changed = false;
+ {
+ std::lock_guard<std::mutex> lock(g_settingsMutex);
+ if (update.has("sharpness")) {
+ g_settings.sharpness = static_cast<int>(std::clamp<int64_t>(update["sharpness"].asInt(g_settings.sharpness), 0, 3));
+ display::setSharpness(g_settings.sharpness);
+ changed = true;
+ }
+ if (update.has("upscaler")) {
+ g_settings.upscaler = static_cast<int>(std::clamp<int64_t>(update["upscaler"].asInt(g_settings.upscaler), 0, 3));
+ display::setUpscaler(g_settings.upscaler & 1);
+ display::setRestore((g_settings.upscaler & 2) != 0);
+ changed = true;
+ }
+ if (update.has("deband")) {
+ g_settings.deband = static_cast<int>(std::clamp<int64_t>(update["deband"].asInt(g_settings.deband), 0, 3));
+ display::setDeband(g_settings.deband);
+ changed = true;
+ }
+ if (update.has("padSpeakerVolume")) {
+ g_settings.padSpeakerVolume = static_cast<int>(std::clamp<int64_t>(update["padSpeakerVolume"].asInt(g_settings.padSpeakerVolume), 0, 100));
+ media::setPadSpeakerVolume(g_settings.padSpeakerVolume);
+ changed = true;
+ }
+ if (update.has("triggerProfile")) {
+ g_settings.triggerProfile = static_cast<int>(std::clamp<int64_t>(update["triggerProfile"].asInt(g_settings.triggerProfile), 0, 2));
+ input::setTriggerProfile(g_settings.triggerProfile);
+ changed = true;
+ }
+ if (changed) {
+ g_settings.save(settingsPath());
+ refreshSettingsUiLocked();
+ }
+ }
+ return true;
+ },
+ /*streamAction=*/[](const std::string& action) {
+ if (action == "xbox_guide" || action == "guide") {
+ g_xboxButtonUntil = platform::nowMs() + 300;
+ } else if (action == "end_session" || action == "leave") {
+ g_cancel = true;
+ }
+ }
});
startWebServer();
g_ui->setWebUrl(webServerUrl());
@@ -405,6 +530,20 @@ bool coreStartup() {
}
g_ui->setCaps(uiCaps());
g_core->canvas.emplace(display::kWidth, display::kHeight);
+ shell::setMouseHandler([](const shell::MouseEvent& mev) {
+ if (!g_ui || g_ui->screen() == ui::Screen::Streaming) return;
+ ui::UiEvent ev;
+ if (mev.kind == shell::MouseEvent::Kind::Move) {
+ ev = g_ui->onMouseMove(mev.x, mev.y);
+ } else if (mev.kind == shell::MouseEvent::Kind::ButtonDown) {
+ ev = g_ui->onMouseDown(mev.x, mev.y, mev.button);
+ } else if (mev.kind == shell::MouseEvent::Kind::Wheel) {
+ ev = g_ui->onMouseWheel(mev.wheelX, mev.wheelY);
+ }
+ if (ev.action != ui::Action::None && g_core) {
+ g_core->dispatchUiAction(ev);
+ }
+ });
if (!net::initTls(g_autoplay.badCa ? platform::assetDir() + "/missing.pem" : platform::caBundlePath())) {
// The step that failed, and where the log is: what a bug report needs.
@@ -423,6 +562,112 @@ bool coreStartup() {
return true;
}
+void Core::dispatchUiAction(const ui::UiEvent& ev) {
+ switch (ev.action) {
+ case ui::Action::Play: {
+ std::lock_guard<std::mutex> lock(g_argMutex);
+ g_playTile = ev.game;
+ g_command = kPlay;
+ break;
+ }
+ case ui::Action::ClaimFreeGame: {
+ std::lock_guard<std::mutex> lock(g_argMutex);
+ g_playTile = ev.game;
+ g_command = kClaimFree;
+ break;
+ }
+ case ui::Action::SignOut:
+ g_cancel = true;
+ g_command = kSignOut;
+ break;
+ case ui::Action::Retry: g_command = kSignIn; break;
+ case ui::Action::ConsolesShown: {
+ int idle = kNone;
+ g_command.compare_exchange_strong(idle, kConsoles); // not over a pending command
+ break;
+ }
+ case ui::Action::CancelLaunch: g_cancel = true; break;
+ case ui::Action::PrefsChanged: {
+ std::lock_guard<std::mutex> lock(g_settingsMutex);
+ g_settings.hidden = ev.hidden;
+ g_settings.favorites = ev.favorites;
+ g_settings.wishlist = ev.wishlist;
+ g_settings.librarySort = ev.librarySort == ui::LibrarySort::AZ ? "az"
+ : ev.librarySort == ui::LibrarySort::Console ? "console"
+ : "recent";
+ g_settings.save(settingsPath()); // warns itself
+ XC_LOGI("prefs saved: %zu hidden, %zu favorites, %zu wishlist, sort %s", g_settings.hidden.size(),
+ g_settings.favorites.size(), g_settings.wishlist.size(), g_settings.librarySort.c_str());
+ updateLibraryFavorites(g_settings.favorites);
+ updateLibraryWishlist(g_settings.wishlist);
+ break;
+ }
+ case ui::Action::GameSettingsChanged: {
+ std::lock_guard<std::mutex> lock(g_settingsMutex);
+ std::string key = app::gameProfileKey(ev.game.productId, ev.game.titleId);
+ if (ev.hasGameProfile) {
+ g_settings.perGame[key] = ev.gameProfile;
+ XC_LOGI("per-game profile saved for %s (%s)", ev.game.name.c_str(), key.c_str());
+ } else {
+ g_settings.perGame.erase(key);
+ XC_LOGI("per-game profile reset to default for %s (%s)", ev.game.name.c_str(), key.c_str());
+ }
+ g_settings.save(settingsPath()); // warns itself
+ break;
+ }
+ case ui::Action::SettingsChanged:
+ // Row titles and game details come from the catalog in the
+ // chosen language.
+ if (saveSettings(ev.settings)) g_command = kReloadLibrary;
+ break;
+ case ui::Action::UpdateNow: {
+ if (g_ui->screen() == ui::Screen::Settings) saveSettings(ev.settings);
+ int idle = kNone;
+ if (!g_command.compare_exchange_strong(idle, kUpdate)) XC_LOGW("update: the worker is busy");
+ break;
+ }
+ case ui::Action::UpdateLater: skipOfferedUpdate(); break;
+ case ui::Action::LoginCountry:
+ // A new sign-in, as the country chosen (or the console's own).
+ saveSettings(ev.settings);
+ XC_LOGI("sign-in country: %s", ev.settings.loginCountry.empty() ? "off" : ev.settings.loginCountry.c_str());
+ g_command = kSignIn;
+ break;
+ case ui::Action::Report: openReport(ev.reportWhat, false, ui::tr(ui::Str::ReportProblem)); break;
+ case ui::Action::Quit: quitAsked_ = true; break; // desktop only (the PS5 never asks)
+ case ui::Action::OpenUrl: {
+ // A desktop: the sign-in page, the report form, the release page.
+ bool ok = shell::openUrl(ev.url);
+ XC_LOGI("browser: %s (a link of %zu characters)", ok ? "opened" : "could not be opened", ev.url.size());
+ break;
+ }
+ case ui::Action::RefreshLibrary: {
+ XC_LOGI("library: manual refresh requested");
+ g_command = kReloadLibrary;
+ platform::notify(ui::tr(ui::Str::RefreshingLibrary));
+ break;
+ }
+ case ui::Action::CheckSignIn: {
+ XC_LOGI("sign-in check: requested from Settings");
+ int idle = kNone;
+ if (!g_command.compare_exchange_strong(idle, kCheckSignIn)) XC_LOGW("sign-in check: worker is busy");
+ break;
+ }
+ case ui::Action::RunNetworkTest: {
+ XC_LOGI("network test: requested from Settings");
+ int idle = kNone;
+ if (!g_command.compare_exchange_strong(idle, kNetworkTest)) XC_LOGW("network test: worker is busy");
+ break;
+ }
+ case ui::Action::TestQueueAlert: {
+ XC_LOGI("settings: manual queue-ready alert test requested");
+ playQueueReadyAlert();
+ break;
+ }
+ case ui::Action::None: break;
+ }
+}
+
bool Core::frame() {
if (!shell::pumpEvents() || quitAsked_) return false;
if (bool on; shell::fullscreenSwitched(on)) {
@@ -478,6 +723,10 @@ bool Core::frame() {
if (virtualGamepadState(0, vpad0, vconn0) && vconn0) {
input::mergePads(pad, vpad0);
}
+ input::ControllerState usbPad;
+ if (input::pollUsbPad(usbPad)) {
+ input::mergePads(pad, usbPad);
+ }
// USB keyboard: the app's screens (and its menu in a game) as with the
// controller; in a game otherwise, its keys and the mouse go to the game.
input::KbmInput kbm = input::kbmPoll();
@@ -733,110 +982,7 @@ bool Core::frame() {
std::swap(prev.btnA, prev.btnB);
XC_LOGI("confirm button: %s", circle ? "circle" : "cross");
}
- switch (ev.action) {
- case ui::Action::Play: {
- std::lock_guard<std::mutex> lock(g_argMutex);
- g_playTile = ev.game;
- g_command = kPlay;
- break;
- }
- case ui::Action::ClaimFreeGame: {
- std::lock_guard<std::mutex> lock(g_argMutex);
- g_playTile = ev.game;
- g_command = kClaimFree;
- break;
- }
- case ui::Action::SignOut:
- g_cancel = true;
- g_command = kSignOut;
- break;
- case ui::Action::Retry: g_command = kSignIn; break;
- case ui::Action::ConsolesShown: {
- int idle = kNone;
- g_command.compare_exchange_strong(idle, kConsoles); // not over a pending command
- break;
- }
- case ui::Action::CancelLaunch: g_cancel = true; break;
- case ui::Action::PrefsChanged: {
- std::lock_guard<std::mutex> lock(g_settingsMutex);
- g_settings.hidden = ev.hidden;
- g_settings.favorites = ev.favorites;
- g_settings.wishlist = ev.wishlist;
- g_settings.librarySort = ev.librarySort == ui::LibrarySort::AZ ? "az"
- : ev.librarySort == ui::LibrarySort::Console ? "console"
- : "recent";
- g_settings.save(settingsPath()); // warns itself
- XC_LOGI("prefs saved: %zu hidden, %zu favorites, %zu wishlist, sort %s", g_settings.hidden.size(),
- g_settings.favorites.size(), g_settings.wishlist.size(), g_settings.librarySort.c_str());
- updateLibraryFavorites(g_settings.favorites);
- updateLibraryWishlist(g_settings.wishlist);
- break;
- }
- case ui::Action::GameSettingsChanged: {
- std::lock_guard<std::mutex> lock(g_settingsMutex);
- std::string key = app::gameProfileKey(ev.game.productId, ev.game.titleId);
- if (ev.hasGameProfile) {
- g_settings.perGame[key] = ev.gameProfile;
- XC_LOGI("per-game profile saved for %s (%s)", ev.game.name.c_str(), key.c_str());
- } else {
- g_settings.perGame.erase(key);
- XC_LOGI("per-game profile reset to default for %s (%s)", ev.game.name.c_str(), key.c_str());
- }
- g_settings.save(settingsPath()); // warns itself
- break;
- }
- case ui::Action::SettingsChanged:
- // Row titles and game details come from the catalog in the
- // chosen language.
- if (saveSettings(ev.settings)) g_command = kReloadLibrary;
- break;
- case ui::Action::UpdateNow: {
- if (g_ui->screen() == ui::Screen::Settings) saveSettings(ev.settings);
- int idle = kNone;
- if (!g_command.compare_exchange_strong(idle, kUpdate)) XC_LOGW("update: the worker is busy");
- break;
- }
- case ui::Action::UpdateLater: skipOfferedUpdate(); break;
- case ui::Action::LoginCountry:
- // A new sign-in, as the country chosen (or the console's own).
- saveSettings(ev.settings);
- XC_LOGI("sign-in country: %s", ev.settings.loginCountry.empty() ? "off" : ev.settings.loginCountry.c_str());
- g_command = kSignIn;
- break;
- case ui::Action::Report: openReport(ev.reportWhat, false, ui::tr(ui::Str::ReportProblem)); break;
- case ui::Action::Quit: quitAsked_ = true; break; // desktop only (the PS5 never asks)
- case ui::Action::OpenUrl: {
- // A desktop: the sign-in page, the report form, the release page.
- bool ok = shell::openUrl(ev.url);
- XC_LOGI("browser: %s (a link of %zu characters)", ok ? "opened" : "could not be opened", ev.url.size());
- break;
- }
- case ui::Action::RefreshLibrary: {
- XC_LOGI("library: manual refresh requested");
- g_command = kReloadLibrary;
- platform::notify(ui::tr(ui::Str::RefreshingLibrary));
- break;
- }
- case ui::Action::CheckSignIn: {
- XC_LOGI("sign-in check: requested from Settings");
- int idle = kNone;
- if (!g_command.compare_exchange_strong(idle, kCheckSignIn)) XC_LOGW("sign-in check: worker is busy");
- break;
- }
- case ui::Action::RunNetworkTest: {
- XC_LOGI("network test: requested from Settings");
- int idle = kNone;
- if (!g_command.compare_exchange_strong(idle, kNetworkTest)) XC_LOGW("network test: worker is busy");
- break;
- }
- case ui::Action::TestQueueAlert: {
- XC_LOGI("settings: manual queue-ready alert test requested");
- playQueueReadyAlert();
- break;
- }
- case ui::Action::None: break;
- }
-
+ dispatchUiAction(ev);
autoplayScreens(*canvas, now);
if (haveDisplay && g_ui->needsRedraw(now)) {
diff --git a/src/app/settings.cpp b/src/app/settings.cpp
index efa8396..93be3e2 100644
--- a/src/app/settings.cpp
+++ b/src/app/settings.cpp
@@ -100,6 +100,7 @@ bool Settings::load(const std::string& path) {
touchpadMouse = (*j)["touchpadMouse"].asBool(touchpadMouse);
micGain = static_cast<int>(std::clamp<int64_t>((*j)["micGain"].asInt(micGain), 0, 2));
audioRoute = static_cast<int>(std::clamp<int64_t>((*j)["audioRoute"].asInt(audioRoute), 0, 1));
+ voiceRouting = static_cast<int>(std::clamp<int64_t>((*j)["voiceRouting"].asInt(voiceRouting), 0, 1));
padSpeakerVolume = static_cast<int>(std::clamp<int64_t>((*j)["padSpeakerVolume"].asInt(padSpeakerVolume), 0, 100));
skippedUpdate = (*j)["skippedUpdate"].str();
maxHeightCloud = static_cast<int>((*j)["maxHeightCloud"].asInt(0));
@@ -254,6 +255,7 @@ bool Settings::save(const std::string& path) const {
v.set("touchpadMouse", touchpadMouse);
v.set("micGain", micGain);
v.set("audioRoute", audioRoute);
+ v.set("voiceRouting", voiceRouting);
v.set("padSpeakerVolume", padSpeakerVolume);
v.set("queueReadyAlert", queueReadyAlert);
json::Value pt = json::Value::object();
diff --git a/src/app/settings.h b/src/app/settings.h
index 25b5d34..b2fed28 100644
--- a/src/app/settings.h
+++ b/src/app/settings.h
@@ -112,6 +112,7 @@ struct Settings {
bool touchpadMouse = false; // touchpad as mouse in games with native MKB support
int micGain = 1; // 0: 50%, 1: 100%, 2: 150%
int audioRoute = 0; // 0: TV/HDMI (Main), 1: DualSense Speaker / Headset (Pad)
+ int voiceRouting = 0; // 0: Auto (DualSense Speaker if available), 1: Always TV/Headset
int padSpeakerVolume = 100; // 0 to 100% (DualSense controller speaker)
bool queueReadyAlert = true; // Queue-ready chime and rumble alert
std::map<std::string, uint64_t> titlePlaytime; // accumulated playtime in seconds (productId or titleId -> seconds)
diff --git a/src/app/shell.h b/src/app/shell.h
index 16699e2..68d4169 100644
--- a/src/app/shell.h
+++ b/src/app/shell.h
@@ -10,6 +10,7 @@
#include "app/settings.h"
+#include <functional>
#include <string>
#include <vector>
@@ -73,4 +74,13 @@ bool setTextInput(bool on);
// and "\n" for Enter pressed while text input is on. Empty elsewhere.
std::string takeTextInput();
+struct MouseEvent {
+ enum class Kind { Move, ButtonDown, ButtonUp, Wheel };
+ Kind kind = Kind::Move;
+ float x = 0, y = 0;
+ int button = 0;
+ float wheelX = 0, wheelY = 0;
+};
+void setMouseHandler(std::function<void(const MouseEvent&)> handler);
+
} // namespace xc::app::shell
diff --git a/src/app/shell_desktop.cpp b/src/app/shell_desktop.cpp
index 2a3f5d5..b36137e 100644
--- a/src/app/shell_desktop.cpp
+++ b/src/app/shell_desktop.cpp
@@ -30,6 +30,7 @@ int g_switchedTo = -1; // F11 / Alt+Enter: the fullscreen state asked
std::atomic<bool> g_focus{true}; // the window has the keyboard
bool g_textOn = false; // SDL text input started (main thread)
std::string g_typed; // typed since takeTextInput() (main thread)
+std::function<void(const MouseEvent&)> g_mouseHandler;
volatile std::sig_atomic_t g_signalled = 0;
void onSignal(int) { g_signalled = 1; }
} // namespace
@@ -99,6 +100,43 @@ bool pumpEvents() {
case SDL_EVENT_TEXT_INPUT:
if (g_textOn && ev.text.text) g_typed += ev.text.text;
break;
+ case SDL_EVENT_MOUSE_MOTION: {
+ if (g_mouseHandler) {
+ float lx = 0, ly = 0;
+ if (display::sdlWindowToLogical(ev.motion.x, ev.motion.y, lx, ly)) {
+ g_mouseHandler({MouseEvent::Kind::Move, lx, ly, 0, 0, 0});
+ }
+ }
+ break;
+ }
+ case SDL_EVENT_MOUSE_BUTTON_DOWN: {
+ if (g_mouseHandler) {
+ float lx = 0, ly = 0;
+ if (display::sdlWindowToLogical(ev.button.x, ev.button.y, lx, ly)) {
+ g_mouseHandler({MouseEvent::Kind::ButtonDown, lx, ly, ev.button.button, 0, 0});
+ }
+ }
+ break;
+ }
+ case SDL_EVENT_MOUSE_BUTTON_UP: {
+ if (g_mouseHandler) {
+ float lx = 0, ly = 0;
+ if (display::sdlWindowToLogical(ev.button.x, ev.button.y, lx, ly)) {
+ g_mouseHandler({MouseEvent::Kind::ButtonUp, lx, ly, ev.button.button, 0, 0});
+ }
+ }
+ break;
+ }
+ case SDL_EVENT_MOUSE_WHEEL: {
+ if (g_mouseHandler) {
+ float mx = 0, my = 0;
+ SDL_GetMouseState(&mx, &my);
+ float lx = 0, ly = 0;
+ display::sdlWindowToLogical(mx, my, lx, ly);
+ g_mouseHandler({MouseEvent::Kind::Wheel, lx, ly, 0, ev.wheel.x, ev.wheel.y});
+ }
+ break;
+ }
default: break;
}
input::sdlInputEvent(ev);
@@ -157,6 +195,10 @@ std::string takeTextInput() {
return s;
}
+void setMouseHandler(std::function<void(const MouseEvent&)> handler) {
+ g_mouseHandler = std::move(handler);
+}
+
void restartOrExit() {
// Never asked (no update is installed here).
std::fflush(nullptr);
diff --git a/src/app/shell_null.cpp b/src/app/shell_null.cpp
index 0b190d6..4d3352f 100644
--- a/src/app/shell_null.cpp
+++ b/src/app/shell_null.cpp
@@ -42,6 +42,7 @@ bool fullscreenSwitched(bool&) { return false; }
bool openUrl(const std::string&) { return false; }
bool setTextInput(bool) { return false; }
std::string takeTextInput() { return {}; }
+void setMouseHandler(std::function<void(const MouseEvent&)>) {}
void restartOrExit() {
// Never asked (no update is installed here); closed as the PS5 does.
diff --git a/src/app/shell_ps5.cpp b/src/app/shell_ps5.cpp
index 18fdef1..8a87cc7 100644
--- a/src/app/shell_ps5.cpp
+++ b/src/app/shell_ps5.cpp
@@ -67,6 +67,7 @@ bool fullscreenSwitched(bool&) { return false; }
bool openUrl(const std::string&) { return false; }
bool setTextInput(bool) { return false; } // the USB keyboard keeps moving through the screens
std::string takeTextInput() { return {}; }
+void setMouseHandler(std::function<void(const MouseEvent&)>) {}
bool isInstalledCopy(const std::string& dir) {
// /app0 is the folder the system started the app from.
diff --git a/src/app/stream_screen.cpp b/src/app/stream_screen.cpp
index c26d3b5..2c25860 100644
--- a/src/app/stream_screen.cpp
+++ b/src/app/stream_screen.cpp
@@ -12,6 +12,7 @@
#include "input/input_ext.h"
#include "input/kbm.h"
#include "input/keyboard_nav.h"
+#include "input/pad_usb.h"
#include "media/audio_out.h"
#include "platform/platform.h"
#include "platform/toasts.h"
@@ -157,6 +158,7 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
highRefresh_ = want120 && display::setHighRefresh(true);
media::audioSetRoute(static_cast<media::AudioRoute>(g_settings.audioRoute));
+ media::audioSetVoiceRouting(g_settings.voiceRouting);
if (g_player) {
g_player->setMicGain(g_settings.micGainFactor());
}
@@ -461,6 +463,14 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
g_xboxButtonUntil = platform::nowMs() + 250;
}
}
+ input::ControllerState usbPad;
+ if (input::pollUsbPad(usbPad)) {
+ input::mergePads(sent, usbPad);
+ if (usbPad.btnNexus) {
+ sent.btnNexus = true;
+ g_xboxButtonUntil = platform::nowMs() + 250;
+ }
+ }
}
if (platform::nowMs() < g_xboxButtonUntil) sent.btnNexus = true;
g_player->sendInput(sent);
diff --git a/src/app/web_server.cpp b/src/app/web_server.cpp
index aaef957..c9543c1 100644
--- a/src/app/web_server.cpp
+++ b/src/app/web_server.cpp
@@ -103,6 +103,27 @@ pre { background: #07080b; border: 1px solid var(--border); border-radius: 10px;
.toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background: #169c53; color: #fff; padding: 10px 20px; border-radius: 24px; font-size: 0.88rem; font-weight: 600; box-shadow: 0 4px 16px rgba(0,0,0,0.5); opacity: 0; pointer-events: none; transition: opacity 0.3s; z-index: 1000; max-width: 90%; text-align: center; }
.toast.show { opacity: 1; }
+/* Telemetry & interactive controls */
+.telemetry-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 14px; width: 100%; }
+.tel-item { background: var(--surface-alt); border: 1px solid var(--border); border-radius: 10px; padding: 9px 6px; text-align: center; }
+.tel-val { font-size: 1.10rem; font-weight: 700; color: #4ade80; }
+.tel-lbl { font-size: 0.70rem; color: var(--text-dim); text-transform: uppercase; margin-top: 3px; }
+.slider-group { display: flex; flex-direction: column; gap: 4px; margin-bottom: 12px; width: 100%; }
+.slider-header { display: flex; justify-content: space-between; font-size: 0.84rem; font-weight: 600; }
+.slider-val { color: #4ade80; }
+input[type="range"] { width: 100%; accent-color: var(--primary); margin: 6px 0; }
+.toggle-row { display: flex; justify-content: space-between; align-items: center; padding: 10px 0; border-bottom: 1px solid var(--border); }
+.toggle-label { font-size: 0.86rem; font-weight: 600; }
+.switch { position: relative; display: inline-block; width: 44px; height: 24px; flex-shrink: 0; }
+.switch input { opacity: 0; width: 0; height: 0; }
+.slider-sw { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: var(--surface-alt); border: 1px solid var(--border); border-radius: 24px; transition: .25s; }
+.slider-sw:before { position: absolute; content: ""; height: 16px; width: 16px; left: 3px; bottom: 3px; background-color: white; border-radius: 50%; transition: .25s; }
+input:checked + .slider-sw { background-color: var(--primary); border-color: var(--primary); }
+input:checked + .slider-sw:before { transform: translateX(20px); }
+.btn-danger { background: var(--danger); border-color: var(--danger); color: #fff; }
+.btn-danger:hover { background: #b82626; }
+
+
/* Search overlay when streaming */
.search-disabled-overlay {
position: absolute;
@@ -331,12 +352,167 @@ pre { background: #07080b; border: 1px solid var(--border); border-radius: 10px;
<div class="nav-tabs">
<div class="nav-tab active" id="navTab-search" onclick="switchTab('search')">🔍 Busca</div>
- <div class="nav-tab" id="navTab-remap" onclick="switchTab('remap')">⚙️ Mapeamento</div>
- <div class="nav-tab" id="navTab-gamepad" onclick="switchTab('gamepad')">🎮 Controle</div>
+ <div class="nav-tab" id="navTab-settings" onclick="switchTab('settings')">⚙️ Configurações</div>
+ <div class="nav-tab" id="navTab-stream" onclick="switchTab('stream')">📺 Jogo Atual</div>
+ <div class="nav-tab" id="navTab-remap" onclick="switchTab('remap')">🎮 Mapeamento</div>
+ <div class="nav-tab" id="navTab-gamepad" onclick="switchTab('gamepad')">🕹️ Controle</div>
<div class="nav-tab" id="navTab-logs" onclick="switchTab('logs')">📋 Logs</div>
</div>
<div class="content">
+ <!-- TAB: SETTINGS -->
+ <div id="tab-settings" class="tab-pane" style="display:none;">
+ <div class="card">
+ <h2>⚙️ Configurações Gerais</h2>
+ <p>Ajuste opções gráficas, de controle e comportamento do aplicativo.</p>
+
+ <div class="slider-group">
+ <div class="slider-header">
+ <span>Bitrate Máximo</span>
+ <span class="slider-val" id="valBitrate">Auto</span>
+ </div>
+ <input type="range" id="inputBitrate" min="0" max="50" step="5" value="0" oninput="onBitrateInput(this.value)">
+ </div>
+
+ <div class="toggle-row">
+ <span class="toggle-label">Modo 120 Hz (High Refresh / VRR)</span>
+ <label class="switch">
+ <input type="checkbox" id="check120Hz" onchange="markSettingsChanged()">
+ <span class="slider-sw"></span>
+ </label>
+ </div>
+
+ <div class="slider-group" style="margin-top: 10px;">
+ <div class="slider-header">
+ <span>Zona Morta - Analógico Esquerdo (L)</span>
+ <span class="slider-val" id="valDeadzoneL">15%</span>
+ </div>
+ <input type="range" id="inputDeadzoneL" min="0" max="50" step="1" value="15" oninput="document.getElementById('valDeadzoneL').textContent=this.value+'%'; markSettingsChanged()">
+ </div>
+
+ <div class="slider-group">
+ <div class="slider-header">
+ <span>Zona Morta - Analógico Direito (R)</span>
+ <span class="slider-val" id="valDeadzoneR">15%</span>
+ </div>
+ <input type="range" id="inputDeadzoneR" min="0" max="50" step="1" value="15" oninput="document.getElementById('valDeadzoneR').textContent=this.value+'%'; markSettingsChanged()">
+ </div>
+
+ <div class="slider-group">
+ <div class="slider-header">
+ <span>Vibração dos Gatilhos</span>
+ <span class="slider-val" id="valTriggerStrength">2</span>
+ </div>
+ <input type="range" id="inputTriggerStrength" min="0" max="4" step="1" value="2" oninput="document.getElementById('valTriggerStrength').textContent=this.value; markSettingsChanged()">
+ </div>
+
+ <div class="map-item" style="margin-bottom: 10px;">
+ <label>Barra de Luz DualSense</label>
+ <select id="selectLightBarMode" onchange="onLightBarModeChange()">
+ <option value="0">Cor do Jogo</option>
+ <option value="1">Cor Personalizada</option>
+ <option value="2">Desativada</option>
+ </select>
+ <input type="color" id="inputLightBarColor" value="#0070dc" style="margin-left: 8px; height: 32px; width: 44px; border: none; border-radius: 6px; cursor: pointer; display: none;" onchange="markSettingsChanged()">
+ </div>
+
+ <div class="toggle-row">
+ <span class="toggle-label">Aviso Sonoro de Fila (Queue Chime)</span>
+ <label class="switch">
+ <input type="checkbox" id="checkQueueAlert" onchange="markSettingsChanged()">
+ <span class="slider-sw"></span>
+ </label>
+ </div>
+
+ <div class="map-item" style="margin-top: 10px;">
+ <label>Decodificador de Vídeo</label>
+ <select id="selectVideoDecoder" onchange="markSettingsChanged()">
+ <option value="0">Hardware (libSceVideodec2 / HWAccel)</option>
+ <option value="1">Software (FFmpeg CPU)</option>
+ </select>
+ </div>
+
+ <div class="map-item" style="margin-top: 10px;">
+ <label>Saída do Chat de Voz</label>
+ <select id="selectVoiceRouting" onchange="markSettingsChanged()">
+ <option value="0">Automático (Alto-falante DualSense se disponível)</option>
+ <option value="1">Sempre TV / Headset Principal</option>
+ </select>
+ </div>
+
+ <div class="btn-row" style="margin-top: 16px;">
+ <button class="btn btn-primary" onclick="saveGeneralSettings()">Salvar Configurações</button>
+ </div>
+ </div>
+ </div>
+
+ <!-- TAB: STREAM (JOGO ATUAL) -->
+ <div id="tab-stream" class="tab-pane" style="display:none;">
+ <div class="card">
+ <h2>📺 Jogo Atual & Telemetria</h2>
+ <p>Métricas de transmissão em tempo real e ajustes do menu de jogo (StreamMenu).</p>
+
+ <div class="telemetry-grid">
+ <div class="tel-item"><div class="tel-val" id="telFps">--</div><div class="tel-lbl">FPS</div></div>
+ <div class="tel-item"><div class="tel-val" id="telRtt">-- ms</div><div class="tel-lbl">RTT (Ping)</div></div>
+ <div class="tel-item"><div class="tel-val" id="telMbps">-- Mbps</div><div class="tel-lbl">Bitrate</div></div>
+ <div class="tel-item"><div class="tel-val" id="telLoss">0.0%</div><div class="tel-lbl">Perda Pkts</div></div>
+ <div class="tel-item"><div class="tel-val" id="telQp">--</div><div class="tel-lbl">QP (Qualidade)</div></div>
+ <div class="tel-item"><div class="tel-val" id="telDec">-- ms</div><div class="tel-lbl">Decodificação</div></div>
+ </div>
+
+ <div class="slider-group" style="margin-top: 10px;">
+ <div class="slider-header">
+ <span>Nitidez CAS (FidelityFX RCAS)</span>
+ <span class="slider-val" id="valCas">Média</span>
+ </div>
+ <input type="range" id="inputCas" min="0" max="3" step="1" value="2" oninput="sendStreamParam('sharpness', parseInt(this.value)); updateCasLabel(this.value);">
+ </div>
+
+ <div class="map-item" style="margin-bottom: 10px;">
+ <label>Upscaler de Imagem</label>
+ <select id="selectUpscaler" onchange="sendStreamParam('upscaler', parseInt(this.value))">
+ <option value="0">FSR 1.0</option>
+ <option value="1">Anime4K</option>
+ <option value="2">FSR 1.0 + Clean-up</option>
+ <option value="3">Anime4K + Clean-up</option>
+ </select>
+ </div>
+
+ <div class="map-item" style="margin-bottom: 10px;">
+ <label>Suavização de Blocos (Deband)</label>
+ <select id="selectDeband" onchange="sendStreamParam('deband', parseInt(this.value))">
+ <option value="0">Desativada</option>
+ <option value="1">Baixa</option>
+ <option value="2">Alta</option>
+ <option value="3">Automática (Bitrate-adaptive)</option>
+ </select>
+ </div>
+
+ <div class="slider-group">
+ <div class="slider-header">
+ <span>Volume Alto-falante DualSense</span>
+ <span class="slider-val" id="valPadSpeaker">100%</span>
+ </div>
+ <input type="range" id="inputPadSpeaker" min="0" max="100" step="5" value="100" oninput="document.getElementById('valPadSpeaker').textContent=this.value+'%'; sendStreamParam('padSpeakerVolume', parseInt(this.value));">
+ </div>
+
+ <div class="map-item" style="margin-bottom: 14px;">
+ <label>Perfis de Gatilho Inteligente</label>
+ <select id="selectSmartTriggers" onchange="sendStreamParam('triggerProfile', parseInt(this.value))">
+ <option value="0">Padrão (Standard Haptics)</option>
+ <option value="1">Tiro (Shooter - Hair Trigger)</option>
+ <option value="2">Corrida (Racing - Progressive Resistance)</option>
+ </select>
+ </div>
+
+ <div class="btn-row">
+ <button class="btn btn-primary" onclick="sendStreamAction('xbox_guide')">Abrir Guia Xbox</button>
+ <button class="btn btn-danger" onclick="sendStreamAction('end_session')">Encerrar Sessão</button>
+ </div>
+ </div>
+ </div>
+
<!-- TAB: SEARCH -->
<div id="tab-search" class="tab-pane">
<div class="card" id="searchCard" style="position: relative;">
@@ -659,6 +835,10 @@ function switchTab(name) {
if (tabBtn) tabBtn.classList.add('active');
if (name === 'search') pollStreamingState();
if (name === 'gamepad') sendPadState();
+ if (name === 'stream') {
+ loadStreamMenuState();
+ pollStats();
+ }
}
function switchRemapSub(mode) {
@@ -913,6 +1093,117 @@ function saveSettings() {
}).catch(e => showToast('Erro ao salvar configurações'));
}
+function onBitrateInput(val) {
+ const v = parseInt(val, 10);
+ const el = document.getElementById('valBitrate');
+ if (el) el.textContent = (v === 0) ? 'Auto' : v + ' Mbps';
+}
+
+function onLightBarModeChange() {
+ const sel = document.getElementById('selectLightBarMode');
+ const colorInput = document.getElementById('inputLightBarColor');
+ if (sel && colorInput) {
+ colorInput.style.display = (sel.value === '1') ? 'inline-block' : 'none';
+ }
+}
+
+function markSettingsChanged() {
+}
+
+function saveGeneralSettings() {
+ const payload = {
+ maxBitrateMbps: parseInt(document.getElementById('inputBitrate').value, 10),
+ highRefresh: document.getElementById('check120Hz').checked,
+ deadzoneLeft: parseInt(document.getElementById('inputDeadzoneL').value, 10),
+ deadzoneRight: parseInt(document.getElementById('inputDeadzoneR').value, 10),
+ triggerStrength: parseInt(document.getElementById('inputTriggerStrength').value, 10),
+ lightBarMode: parseInt(document.getElementById('selectLightBarMode').value, 10),
+ lightBarColour: document.getElementById('inputLightBarColor').value,
+ queueReadyAlert: document.getElementById('checkQueueAlert').checked,
+ videoDecoder: parseInt(document.getElementById('selectVideoDecoder').value, 10),
+ voiceRouting: parseInt(document.getElementById('selectVoiceRouting').value, 10)
+ };
+ fetch('/api/settings', {
+ method: 'POST',
+ headers: {'Content-Type': 'application/json'},
+ body: JSON.stringify(payload)
+ }).then(r => r.json()).then(res => {
+ if (res.ok) {
+ showToast('Configurações salvas no console!');
+ } else {
+ showToast('Erro ao salvar configurações');
+ }
+ }).catch(() => showToast('Erro ao salvar configurações'));
+}
+
+function updateCasLabel(val) {
+ const labels = ['Desativada', 'Baixa', 'Média', 'Alta'];
+ const el = document.getElementById('valCas');
+ if (el) el.textContent = labels[val] !== undefined ? labels[val] : 'Média';
+}
+
+function sendStreamParam(param, val) {
+ const body = {};
+ body[param] = val;
+ fetch('/api/stream', {
+ method: 'POST',
+ headers: {'Content-Type': 'application/json'},
+ body: JSON.stringify(body)
+ }).catch(() => {});
+}
+
+function sendStreamAction(action) {
+ fetch('/api/stream', {
+ method: 'POST',
+ headers: {'Content-Type': 'application/json'},
+ body: JSON.stringify({ action: action })
+ }).then(r => r.json()).then(res => {
+ if (action === 'xbox_guide') showToast('Guia Xbox acionado');
+ if (action === 'end_session') showToast('Sessão encerrada');
+ }).catch(() => {});
+}
+
+function loadStreamMenuState() {
+ fetch('/api/stream').then(r => r.json()).then(s => {
+ if (s.sharpness !== undefined) {
+ const el = document.getElementById('inputCas');
+ if (el) { el.value = s.sharpness; updateCasLabel(s.sharpness); }
+ }
+ if (s.upscaler !== undefined) {
+ const el = document.getElementById('selectUpscaler');
+ if (el) el.value = s.upscaler;
+ }
+ if (s.deband !== undefined) {
+ const el = document.getElementById('selectDeband');
+ if (el) el.value = s.deband;
+ }
+ if (s.padSpeakerVolume !== undefined) {
+ const el = document.getElementById('inputPadSpeaker');
+ if (el) el.value = s.padSpeakerVolume;
+ const vlbl = document.getElementById('valPadSpeaker');
+ if (vlbl) vlbl.textContent = s.padSpeakerVolume + '%';
+ }
+ if (s.triggerProfile !== undefined) {
+ const el = document.getElementById('selectSmartTriggers');
+ if (el) el.value = s.triggerProfile;
+ }
+ }).catch(() => {});
+}
+
+function pollStats() {
+ 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(() => {});
+}
+setInterval(pollStats, 1000);
+
function loadLogPreview() {
const p = document.getElementById('logPreview');
p.textContent = 'Carregando log...';
@@ -998,6 +1289,47 @@ fetch('/api/settings').then(r => r.json()).then(s => {
if (wrapLib) wrapLib.classList.add('active');
}
}
+ if (s.maxBitrateMbps !== undefined) {
+ const el = document.getElementById('inputBitrate');
+ if (el) { el.value = s.maxBitrateMbps; onBitrateInput(s.maxBitrateMbps); }
+ }
+ if (s.highRefresh !== undefined) {
+ const el = document.getElementById('check120Hz');
+ if (el) el.checked = !!s.highRefresh;
+ }
+ if (s.deadzoneLeft !== undefined) {
+ const el = document.getElementById('inputDeadzoneL');
+ if (el) { el.value = s.deadzoneLeft; document.getElementById('valDeadzoneL').textContent = s.deadzoneLeft + '%'; }
+ }
+ if (s.deadzoneRight !== undefined) {
+ const el = document.getElementById('inputDeadzoneR');
+ if (el) { el.value = s.deadzoneRight; document.getElementById('valDeadzoneR').textContent = s.deadzoneRight + '%'; }
+ }
+ if (s.triggerStrength !== undefined) {
+ const el = document.getElementById('inputTriggerStrength');
+ if (el) { el.value = s.triggerStrength; document.getElementById('valTriggerStrength').textContent = s.triggerStrength; }
+ }
+ if (s.lightBarMode !== undefined) {
+ const el = document.getElementById('selectLightBarMode');
+ if (el) el.value = s.lightBarMode;
+ onLightBarModeChange();
+ }
+ if (s.lightBarColour) {
+ const el = document.getElementById('inputLightBarColor');
+ if (el) el.value = s.lightBarColour;
+ }
+ if (s.queueReadyAlert !== undefined) {
+ const el = document.getElementById('checkQueueAlert');
+ if (el) el.checked = !!s.queueReadyAlert;
+ }
+ if (s.videoDecoder !== undefined) {
+ const el = document.getElementById('selectVideoDecoder');
+ if (el) el.value = s.videoDecoder;
+ }
+ if (s.voiceRouting !== undefined) {
+ const el = document.getElementById('selectVoiceRouting');
+ if (el) el.value = s.voiceRouting;
+ }
applySearchTabUI(currentSearchTab);
updateSearchStatusText();
renderPadMap();
@@ -1509,6 +1841,20 @@ WebServer::HttpResponse WebServer::handleRequest(const std::string& method, cons
std::string clean = report::sanitize(rawLog, {});
return {200, "text/plain; charset=utf-8", "Content-Disposition: attachment; filename=\"xcloud.log\"\r\n", clean};
}
+ if (path == "/api/stats") {
+ json::Value stats = json::Value::object();
+ if (s_hooks.getTelemetry) {
+ s_hooks.getTelemetry(stats);
+ }
+ return {200, "application/json", "", stats.dump()};
+ }
+ if (path == "/api/stream") {
+ json::Value menu = json::Value::object();
+ if (s_hooks.getStreamMenuState) {
+ s_hooks.getStreamMenuState(menu);
+ }
+ return {200, "application/json", "", menu.dump()};
+ }
}
if (method == "POST") {
@@ -1645,6 +1991,25 @@ WebServer::HttpResponse WebServer::handleRequest(const std::string& method, cons
}
return {ok ? 200 : 400, "application/json", "", ok ? "{\"ok\":true}" : "{\"ok\":false,\"error\":\"update failed\"}"};
}
+ if (path == "/api/stream") {
+ auto j = json::parse(body);
+ if (!j || !j->isObject()) {
+ return {400, "application/json", "", "{\"ok\":false,\"error\":\"invalid json\"}"};
+ }
+ if ((*j).has("action") && (*j)["action"].isString()) {
+ std::string act = (*j)["action"].str();
+ if (s_hooks.streamAction) {
+ s_hooks.streamAction(act);
+ }
+ }
+ bool ok = true;
+ if (s_hooks.updateStreamMenu) {
+ ok = s_hooks.updateStreamMenu(*j);
+ }
+ json::Value res = json::Value::object();
+ res.set("ok", ok);
+ return {ok ? 200 : 400, "application/json", "", res.dump()};
+ }
}
return {404, "text/plain", "", "404 Not Found\n"};
diff --git a/src/app/web_server.h b/src/app/web_server.h
index 39fd249..c95528c 100644
--- a/src/app/web_server.h
+++ b/src/app/web_server.h
@@ -25,6 +25,10 @@ struct WebServerHooks {
std::function<void(std::string& outQuery, std::string& outTab, json::Value& outFilters)> getSearchParams;
std::function<bool()> isStreaming;
std::function<void(int playerIndex, const input::ControllerState& state)> injectGamepad;
+ std::function<void(json::Value& stats)> getTelemetry;
+ std::function<void(json::Value& streamMenu)> getStreamMenuState;
+ std::function<bool(const json::Value& update)> updateStreamMenu;
+ std::function<void(const std::string& action)> streamAction;
};
void setWebServerHooks(WebServerHooks hooks);
diff --git a/src/app/worker.cpp b/src/app/worker.cpp
index a58bdbf..2e0ef99 100644
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@ -183,6 +183,7 @@ std::string stream(xcloud::GssvClient& gssv) {
cap ? (std::to_string(cap) + " Mbps").c_str() : "automatic",
g_settings.gameVolume);
media::audioSetRoute(static_cast<media::AudioRoute>(g_settings.audioRoute));
+ media::audioSetVoiceRouting(g_settings.voiceRouting);
}
std::string err;
if (!player.start(err)) return "ERROR: " + ui::trf(ui::Str::StreamFailed, err);
diff --git a/src/display/display_sdl.cpp b/src/display/display_sdl.cpp
index faf5d40..5151488 100644
--- a/src/display/display_sdl.cpp
+++ b/src/display/display_sdl.cpp
@@ -552,4 +552,24 @@ bool readBackRgb(std::vector<uint8_t>& rgb, int& width, int& height) {
return true;
}
+bool sdlWindowToLogical(float winX, float winY, float& logX, float& logY) {
+ if (!g_window) return false;
+ if (g_renderer) {
+ return SDL_RenderCoordinatesFromWindow(g_renderer, winX, winY, &logX, &logY);
+ }
+ int winW = 0, winH = 0;
+ SDL_GetWindowSize(g_window, &winW, &winH);
+ if (winW <= 0 || winH <= 0) return false;
+ float scale = std::min(static_cast<float>(winW) / static_cast<float>(kWidth),
+ static_cast<float>(winH) / static_cast<float>(kHeight));
+ if (scale <= 0.0f) return false;
+ float viewW = static_cast<float>(kWidth) * scale;
+ float viewH = static_cast<float>(kHeight) * scale;
+ float offsetX = (static_cast<float>(winW) - viewW) * 0.5f;
+ float offsetY = (static_cast<float>(winH) - viewH) * 0.5f;
+ logX = (winX - offsetX) / scale;
+ logY = (winY - offsetY) / scale;
+ return (logX >= 0.0f && logX <= static_cast<float>(kWidth) && logY >= 0.0f && logY <= static_cast<float>(kHeight));
+}
+
} // namespace xc::display
diff --git a/src/display/display_sdl.h b/src/display/display_sdl.h
index fcb4983..b56c668 100644
--- a/src/display/display_sdl.h
+++ b/src/display/display_sdl.h
@@ -24,5 +24,6 @@ void sdlRepaint();
void sdlSetFullscreen(bool on);
void sdlToggleFullscreen();
bool sdlIsFullscreen();
+bool sdlWindowToLogical(float winX, float winY, float& logX, float& logY);
} // namespace xc::display
diff --git a/src/input/pad_usb.cpp b/src/input/pad_usb.cpp
new file mode 100644
index 0000000..af0a839
--- /dev/null
+++ b/src/input/pad_usb.cpp
@@ -0,0 +1,218 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// USB HID driver for 8BitDo Ultimate 2.4G wireless adapter on PS5 /dev/uhid* in D-Input mode.
+#include "input/pad_usb.h"
+#include "platform/platform.h"
+#include "util/log.h"
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <cstring>
+#include <mutex>
+#include <vector>
+
+#if defined(__unix__) || defined(__linux__) || defined(__APPLE__) || defined(__posix)
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+#define XC_HAS_UHID_POSIX 1
+#else
+#define XC_HAS_UHID_POSIX 0
+#endif
+
+namespace xc::input {
+
+namespace {
+
+std::mutex g_usbPadMutex;
+bool g_initialized = false;
+ControllerState g_lastUsbState{};
+uint64_t g_lastPacketMs = 0;
+
+std::vector<uint8_t> g_testReport;
+bool g_hasTestReport = false;
+
+#if XC_HAS_UHID_POSIX
+std::array<int, 8> g_uhidFds = {-1, -1, -1, -1, -1, -1, -1, -1};
+uint64_t g_lastScanMs = 0;
+
+void scanUhidDevices() {
+ uint64_t now = platform::nowMs();
+ if (now - g_lastScanMs < 2000) {
+ return;
+ }
+ g_lastScanMs = now;
+
+ // Check existing fds and scan for unopened nodes
+ for (int i = 0; i < 8; ++i) {
+ if (g_uhidFds[i] >= 0) {
+ struct stat st{};
+ if (fstat(g_uhidFds[i], &st) < 0) {
+ close(g_uhidFds[i]);
+ g_uhidFds[i] = -1;
+ }
+ }
+ if (g_uhidFds[i] < 0) {
+ char path[32];
+ std::snprintf(path, sizeof(path), "/dev/uhid%d", i);
+ int fd = open(path, O_RDONLY | O_NONBLOCK);
+ if (fd >= 0) {
+ XC_LOGI("usb pad: opened %s (fd %d)", path, fd);
+ g_uhidFds[i] = fd;
+ }
+ }
+ }
+}
+#endif
+
+} // namespace
+
+bool parse8BitDoDInputReport(const uint8_t* data, size_t len, ControllerState& out) {
+ if (!data || len < 16) {
+ return false;
+ }
+
+ out = ControllerState{};
+ out.connected = true;
+
+ // Analog sticks: 0..255 (128 center) -> [-1.0 .. 1.0]
+ 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.rawRightX = std::clamp((static_cast<float>(data[2]) - 128.0f) / 128.0f, -1.0f, 1.0f);
+ out.rawRightY = std::clamp((static_cast<float>(data[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;
+
+ // Triggers L2/R2: 0..255 -> [0.0 .. 1.0]
+ out.triggerL2 = std::clamp(static_cast<float>(data[4]) / 255.0f, 0.0f, 1.0f);
+ out.triggerR2 = std::clamp(static_cast<float>(data[5]) / 255.0f, 0.0f, 1.0f);
+
+ // D-Pad: data[6] (Hat switch: 0..7 directions, 8 / 0x0F = neutral)
+ uint8_t hat = data[6] & 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);
+ } else {
+ out.dpadUp = false;
+ out.dpadRight = false;
+ out.dpadDown = false;
+ out.dpadLeft = false;
+ }
+
+ // Action buttons: data[7]
+ out.btnA = (data[7] & 0x01) != 0;
+ out.btnB = (data[7] & 0x02) != 0;
+ out.btnX = (data[7] & 0x04) != 0;
+ out.btnY = (data[7] & 0x08) != 0;
+ out.btnL1 = (data[7] & 0x10) != 0;
+ out.btnR1 = (data[7] & 0x20) != 0;
+ if ((data[7] & 0x40) != 0) out.triggerL2 = 1.0f;
+ if ((data[7] & 0x80) != 0) out.triggerR2 = 1.0f;
+
+ // System buttons: data[8]
+ out.btnTouchpad = (data[8] & 0x01) != 0; // Select / View
+ out.btnOptions = (data[8] & 0x02) != 0; // Start / Menu
+ out.btnNexus = (data[8] & 0x04) != 0; // Home / Xbox Guide
+ out.btnL3 = (data[8] & 0x08) != 0;
+ out.btnR3 = (data[8] & 0x10) != 0;
+
+ return true;
+}
+
+void padUsbInjectReportForTesting(const uint8_t* data, size_t len) {
+ std::lock_guard<std::mutex> lock(g_usbPadMutex);
+ if (!data || len == 0) {
+ g_hasTestReport = false;
+ g_testReport.clear();
+ return;
+ }
+ g_testReport.assign(data, data + len);
+ g_hasTestReport = true;
+}
+
+bool padUsbInit() {
+ std::lock_guard<std::mutex> lock(g_usbPadMutex);
+ if (g_initialized) return true;
+ g_initialized = true;
+#if XC_HAS_UHID_POSIX
+ scanUhidDevices();
+#endif
+ return true;
+}
+
+void padUsbShutdown() {
+ std::lock_guard<std::mutex> lock(g_usbPadMutex);
+#if XC_HAS_UHID_POSIX
+ for (int& fd : g_uhidFds) {
+ if (fd >= 0) {
+ close(fd);
+ fd = -1;
+ }
+ }
+#endif
+ g_initialized = false;
+ g_lastUsbState = ControllerState{};
+ g_hasTestReport = false;
+}
+
+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;
+ return true;
+ }
+ }
+
+#if XC_HAS_UHID_POSIX
+ if (!g_initialized) {
+ g_initialized = true;
+ }
+ scanUhidDevices();
+
+ uint8_t buffer[64];
+ bool gotNew = false;
+ 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) {
+ 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;
+ }
+ }
+ }
+
+ uint64_t now = platform::nowMs();
+ if (gotNew || (g_lastUsbState.connected && (now - g_lastPacketMs < 500))) {
+ out = g_lastUsbState;
+ return true;
+ }
+#endif
+
+ out = ControllerState{};
+ return false;
+}
+
+} // namespace xc::input
diff --git a/src/input/pad_usb.h b/src/input/pad_usb.h
new file mode 100644
index 0000000..77af581
--- /dev/null
+++ b/src/input/pad_usb.h
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// USB HID gamepad driver for third-party wireless controllers on PS5 (such as 8BitDo Ultimate 2.4G dongle)
+// via /dev/uhid* bypassing Sony's libScePad whitelist.
+#pragma once
+
+#include "input/controller.h"
+
+#include <cstddef>
+#include <cstdint>
+
+namespace xc::input {
+
+constexpr uint16_t k8BitDoVid = 0x2DC8;
+constexpr uint16_t k8BitDoUltimate24GPid = 0x3106;
+
+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
+bool parse8BitDoDInputReport(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);
+
+} // namespace xc::input
diff --git a/src/media/audio_out.h b/src/media/audio_out.h
index c6ee840..e747133 100644
--- a/src/media/audio_out.h
+++ b/src/media/audio_out.h
@@ -28,5 +28,15 @@ bool playPadSpeakerAudio(const float* interleavedStereo, size_t frames);
// Sets the DualSense pad speaker volume (0 to 100%).
void setPadSpeakerVolume(int percent);
int padSpeakerVolume();
+// Returns true if the controller speaker is physically available (DualSense with valid audio port).
+bool hasPadSpeaker();
+// Voice routing: 0 = Auto (DualSense pad speaker if available, fallback to main), 1 = Always Main (TV/Headset)
+void audioSetVoiceRouting(int routing);
+int audioVoiceRouting();
+// Adaptive voice audio playback: routes to the DualSense controller speaker when
+// voice routing is Auto and the controller speaker is physically available,
+// or transparently mixes into the main audio channel when voice routing is Always Main
+// or when using headsets / third-party controllers without a controller speaker.
+bool playVoiceAudio(const float* interleavedStereo, size_t frames);
} // namespace xc::media
diff --git a/src/media/audio_out_null.cpp b/src/media/audio_out_null.cpp
index f55bb70..0844e7f 100644
--- a/src/media/audio_out_null.cpp
+++ b/src/media/audio_out_null.cpp
@@ -51,4 +51,8 @@ bool playPadSpeakerAudio(const float* interleavedStereo, size_t frames) {
return true;
}
+bool hasPadSpeaker() {
+ return false;
+}
+
} // namespace xc::media
diff --git a/src/media/audio_out_ps5.cpp b/src/media/audio_out_ps5.cpp
index 643aba2..d6ca7e9 100644
--- a/src/media/audio_out_ps5.cpp
+++ b/src/media/audio_out_ps5.cpp
@@ -241,4 +241,24 @@ bool playPadSpeakerAudio(const float* interleavedStereo, size_t frames) {
return true;
}
+bool hasPadSpeaker() {
+ int32_t userId = input::padUserId(0);
+ if (userId < 0) return false;
+ static std::atomic<uint64_t> lastCheckMs{0};
+ static std::atomic<bool> lastResult{false};
+ uint64_t now = platform::nowMs();
+ if (now - lastCheckMs.load() < 2000) {
+ return lastResult.load();
+ }
+ lastCheckMs.store(now);
+ int padHandle = sceAudioOutOpen(userId, 4 /* PADSPK */, 0, kGrain, kRate, 3);
+ if (padHandle >= 0) {
+ sceAudioOutClose(padHandle);
+ lastResult.store(true);
+ return true;
+ }
+ lastResult.store(false);
+ return false;
+}
+
} // namespace xc::media
diff --git a/src/media/audio_out_sdl.cpp b/src/media/audio_out_sdl.cpp
index 68c90c4..7eba6c1 100644
--- a/src/media/audio_out_sdl.cpp
+++ b/src/media/audio_out_sdl.cpp
@@ -115,4 +115,8 @@ bool playPadSpeakerAudio(const float* interleavedStereo, size_t frames) {
return true;
}
+bool hasPadSpeaker() {
+ return false;
+}
+
} // namespace xc::media
diff --git a/src/media/audio_queue.cpp b/src/media/audio_queue.cpp
index 5ab11e3..c5fbc78 100644
--- a/src/media/audio_queue.cpp
+++ b/src/media/audio_queue.cpp
@@ -97,11 +97,23 @@ namespace {
// main port follows the system's own routing, the desktop plays on the
// default device).
std::atomic<AudioRoute> g_route{AudioRoute::Main};
+std::atomic<int> g_voiceRouting{0};
} // namespace
void audioSetVolume(float gain) { audioQueue().setVolume(gain); }
void audioSetRoute(AudioRoute route) { g_route.store(route); }
AudioRoute audioRoute() { return g_route.load(); }
+void audioSetVoiceRouting(int routing) { g_voiceRouting.store(std::clamp(routing, 0, 1)); }
+int audioVoiceRouting() { return g_voiceRouting.load(); }
void audioPush(const float* interleaved, size_t frames) { audioQueue().push(interleaved, frames); }
+bool playVoiceAudio(const float* interleavedStereo, size_t frames) {
+ if (!interleavedStereo || frames == 0) return false;
+ if (g_voiceRouting.load() == 0 && hasPadSpeaker()) {
+ return playPadSpeakerAudio(interleavedStereo, frames);
+ }
+ audioPush(interleavedStereo, frames);
+ return true;
+}
+
} // namespace xc::media
diff --git a/src/media/hw_decoder_android.cpp b/src/media/hw_decoder_android.cpp
new file mode 100644
index 0000000..dbdbd7f
--- /dev/null
+++ b/src/media/hw_decoder_android.cpp
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// H.264 on Android via NDK AMediaCodec.
+#include "media/hw_decoder.h"
+#include "util/log.h"
+
+#include <cstring>
+#include <vector>
+
+#if defined(__ANDROID__)
+#include <media/NdkMediaCodec.h>
+#include <media/NdkMediaFormat.h>
+#endif
+
+namespace xc::media {
+
+HwDecoder::~HwDecoder() {
+#if defined(__ANDROID__)
+ if (decoder_) {
+ auto* codec = static_cast<AMediaCodec*>(decoder_);
+ AMediaCodec_stop(codec);
+ AMediaCodec_delete(codec);
+ decoder_ = nullptr;
+ }
+#endif
+}
+
+bool HwDecoder::init(int maxWidth, int maxHeight) {
+#if defined(__ANDROID__)
+ AMediaCodec* codec = AMediaCodec_createDecoderByType("video/avc");
+ if (!codec) {
+ XC_LOGW("hw_decoder_android: AMediaCodec_createDecoderByType failed");
+ return false;
+ }
+
+ AMediaFormat* format = AMediaFormat_new();
+ AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, "video/avc");
+ AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_WIDTH, maxWidth > 0 ? maxWidth : 1920);
+ AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_HEIGHT, maxHeight > 0 ? maxHeight : 1080);
+
+ media_status_t status = AMediaCodec_configure(codec, format, nullptr, nullptr, 0);
+ AMediaFormat_delete(format);
+
+ if (status != AMEDIA_OK) {
+ XC_LOGW("hw_decoder_android: AMediaCodec_configure failed: %d", status);
+ AMediaCodec_delete(codec);
+ return false;
+ }
+
+ status = AMediaCodec_start(codec);
+ if (status != AMEDIA_OK) {
+ XC_LOGW("hw_decoder_android: AMediaCodec_start failed: %d", status);
+ AMediaCodec_delete(codec);
+ return false;
+ }
+
+ decoder_ = codec;
+ XC_LOGI("hw_decoder_android: initialized AMediaCodec video/avc (%dx%d)", maxWidth, maxHeight);
+ return true;
+#else
+ (void)maxWidth;
+ (void)maxHeight;
+ return false;
+#endif
+}
+
+bool HwDecoder::decode(const uint8_t* data, size_t len, uint64_t pts, Picture& out) {
+#if defined(__ANDROID__)
+ if (!decoder_ || !data || len == 0) return false;
+ auto* codec = static_cast<AMediaCodec*>(decoder_);
+
+ ssize_t inIdx = AMediaCodec_dequeueInputBuffer(codec, 2000); // 2ms timeout
+ if (inIdx >= 0) {
+ size_t bufSize = 0;
+ uint8_t* buf = AMediaCodec_getInputBuffer(codec, static_cast<size_t>(inIdx), &bufSize);
+ if (buf && bufSize >= len) {
+ std::memcpy(buf, data, len);
+ AMediaCodec_queueInputBuffer(codec, static_cast<size_t>(inIdx), 0, len, pts, 0);
+ } else {
+ AMediaCodec_queueInputBuffer(codec, static_cast<size_t>(inIdx), 0, 0, pts, 0);
+ }
+ }
+
+ AMediaCodecBufferInfo info{};
+ ssize_t outIdx = AMediaCodec_dequeueOutputBuffer(codec, &info, 2000); // 2ms timeout
+ if (outIdx >= 0) {
+ size_t outSize = 0;
+ uint8_t* outBuf = AMediaCodec_getOutputBuffer(codec, static_cast<size_t>(outIdx), &outSize);
+ if (outBuf && info.size > 0) {
+ static thread_local std::vector<uint8_t> s_androidFrameBuffer;
+ s_androidFrameBuffer.assign(outBuf + info.offset, outBuf + info.offset + info.size);
+ out.data = s_androidFrameBuffer.data();
+ out.size = s_androidFrameBuffer.size();
+
+ AMediaFormat* outFormat = AMediaCodec_getOutputFormat(codec);
+ int32_t width = 0, height = 0, stride = 0;
+ if (outFormat) {
+ AMediaFormat_getInt32(outFormat, AMEDIAFORMAT_KEY_WIDTH, &width);
+ AMediaFormat_getInt32(outFormat, AMEDIAFORMAT_KEY_HEIGHT, &height);
+ AMediaFormat_getInt32(outFormat, AMEDIAFORMAT_KEY_STRIDE, &stride);
+ AMediaFormat_delete(outFormat);
+ }
+ out.width = width > 0 ? static_cast<uint32_t>(width) : 1920;
+ out.height = height > 0 ? static_cast<uint32_t>(height) : 1080;
+ out.pitch = stride > 0 ? static_cast<uint32_t>(stride) : out.width;
+ out.pitchBytes = out.pitch;
+ out.format = 1; // NV12
+ out.pts = static_cast<uint64_t>(info.presentationTimeUs);
+ out.error = false;
+ }
+ AMediaCodec_releaseOutputBuffer(codec, static_cast<size_t>(outIdx), false);
+ return true;
+ }
+ return false;
+#else
+ (void)data;
+ (void)len;
+ (void)pts;
+ (void)out;
+ return false;
+#endif
+}
+
+} // namespace xc::media
diff --git a/src/platform/android/platform_android.cpp b/src/platform/android/platform_android.cpp
new file mode 100644
index 0000000..ab70a4a
--- /dev/null
+++ b/src/platform/android/platform_android.cpp
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// The Android platform layer (psbox): app data directory in internal storage,
+// assets from package, POSIX threads and networking.
+#include "platform/platform.h"
+#include "util/log.h"
+
+#include <cerrno>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <fcntl.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <pthread.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <time.h>
+#include <unistd.h>
+
+#if defined(__ANDROID__)
+#include <android/log.h>
+#endif
+
+namespace xc::platform {
+
+namespace {
+std::string g_dataDir;
+std::string g_dataDirNote;
+
+bool isDir(const std::string& path) {
+ struct stat st {};
+ return ::stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
+}
+
+void makeDirs(const std::string& path) {
+ for (size_t i = 1; i <= path.size(); ++i) {
+ if (i == path.size() || path[i] == '/') {
+ ::mkdir(path.substr(0, i).c_str(), 0700);
+ }
+ }
+}
+} // namespace
+
+bool init() {
+ const char* env = std::getenv("XCLOUD_DATA_DIR");
+ if (env && *env) {
+ g_dataDir = env;
+ } else {
+ g_dataDir = "/data/data/com.rafaelngp.psbox/files";
+ }
+ makeDirs(g_dataDir);
+ return true;
+}
+
+void shutdown() {}
+
+std::string dataDir() { return g_dataDir; }
+std::string dataDirNote() { return g_dataDirNote; }
+bool dataDirWritable() { return true; }
+int dataDirErrno() { return 0; }
+std::string appDir() { return g_dataDir; }
+std::string assetDir() { return g_dataDir + "/assets"; }
+std::string caBundlePath() { return assetDir() + "/cacert.pem"; }
+
+bool randomBytes(void* out, size_t len) {
+ int fd = ::open("/dev/urandom", O_RDONLY);
+ if (fd < 0) return false;
+ auto* p = static_cast<unsigned char*>(out);
+ while (len > 0) {
+ ssize_t n = ::read(fd, p, len);
+ if (n <= 0) {
+ ::close(fd);
+ return false;
+ }
+ p += n;
+ len -= static_cast<size_t>(n);
+ }
+ ::close(fd);
+ return true;
+}
+
+bool resolveIPv4(const std::string& host, uint32_t& addr, std::string& err) {
+ addrinfo hints{};
+ hints.ai_family = AF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+ addrinfo* res = nullptr;
+ int rc = ::getaddrinfo(host.c_str(), nullptr, &hints, &res);
+ if (rc != 0 || !res) {
+ err = "DNS lookup failed for " + host + ": " + gai_strerror(rc);
+ return false;
+ }
+ addr = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr.s_addr;
+ ::freeaddrinfo(res);
+ return true;
+}
+
+void probeNetworking() {}
+
+void notify(const std::string& text) { notify(text, text); }
+
+void notify(const std::string& text, const std::string& forLog) {
+#if defined(__ANDROID__)
+ __android_log_print(ANDROID_LOG_INFO, "PSBox", "%s", text.c_str());
+#else
+ std::printf("[Android Notify] %s (%s)\n", text.c_str(), forLog.c_str());
+#endif
+}
+
+void makePrivate(const std::string& path) { ::chmod(path.c_str(), 0600); }
+
+bool systemKeyboardAvailable() { return false; }
+bool openSystemKeyboard(const std::string&, const std::string&, size_t, KeyboardKind) { return false; }
+KeyboardStatus pollSystemKeyboard(std::string&) { return KeyboardStatus::Closed; }
+
+bool restartApp() { return false; }
+
+std::string firmwareVersion() { return {}; }
+std::string platformName() { return "Android"; }
+
+void setThreadAffinity(ThreadRole, const char*) {}
+void setThreadRealtimePriority() {}
+
+} // namespace xc::platform
diff --git a/src/platform/windows/platform_windows.cpp b/src/platform/windows/platform_windows.cpp
new file mode 100644
index 0000000..ac6a961
--- /dev/null
+++ b/src/platform/windows/platform_windows.cpp
@@ -0,0 +1,374 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// The Windows platform layer (psbox): WinSock2 networking, AppData storage,
+// QueryPerformanceCounter timers, and thread pinning via SetThreadAffinityMask.
+#include "platform/platform.h"
+#include "platform/toasts.h"
+#include "util/log.h"
+
+#if defined(_WIN32) || defined(__CYGWIN__)
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <wincrypt.h>
+#include <shlobj.h>
+#include <direct.h>
+#include <io.h>
+#endif
+
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <thread>
+
+namespace xc::platform {
+
+namespace {
+
+std::string g_dataDir;
+std::string g_dataDirNote;
+
+#if defined(_WIN32) || defined(__CYGWIN__)
+void makeDirs(const std::string& path) {
+ for (size_t i = 1; i <= path.size(); ++i) {
+ if (i == path.size() || path[i] == '/' || path[i] == '\\') {
+ std::string sub = path.substr(0, i);
+ _mkdir(sub.c_str());
+ }
+ }
+}
+
+std::string getExeDir() {
+ char buf[MAX_PATH];
+ DWORD len = GetModuleFileNameA(nullptr, buf, MAX_PATH);
+ if (len == 0 || len >= MAX_PATH) return ".";
+ std::string path(buf, len);
+ size_t slash = path.find_last_of("/\\");
+ if (slash == std::string::npos) return ".";
+ return path.substr(0, slash);
+}
+#endif
+
+} // namespace
+
+bool init() {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ WSADATA wsaData;
+ if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
+ return false;
+ }
+
+ const char* env = std::getenv("XCLOUD_DATA_DIR");
+ if (env && *env) {
+ g_dataDir = env;
+ } else {
+ char appData[MAX_PATH];
+ if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_APPDATA, nullptr, 0, appData))) {
+ g_dataDir = std::string(appData) + "\\PSBox";
+ } else {
+ g_dataDir = ".\\psbox-data";
+ }
+ }
+ makeDirs(g_dataDir);
+#else
+ const char* env = std::getenv("XCLOUD_DATA_DIR");
+ g_dataDir = (env && *env) ? env : "./psbox-data";
+#endif
+ return true;
+}
+
+void shutdown() {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ WSACleanup();
+#endif
+}
+
+std::string dataDir() { return g_dataDir; }
+std::string dataDirNote() { return g_dataDirNote; }
+bool dataDirWritable() { return true; }
+int dataDirErrno() { return 0; }
+
+std::string appDir() {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ return getExeDir();
+#else
+ return ".";
+#endif
+}
+
+std::string assetDir() {
+ if (const char* env = std::getenv("XCLOUD_ASSETS"); env && *env) return env;
+ std::string dir = appDir() + "/assets";
+#if defined(_WIN32) || defined(__CYGWIN__)
+ DWORD attr = GetFileAttributesA(dir.c_str());
+ if (attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_DIRECTORY)) {
+ return dir;
+ }
+#endif
+ return "assets";
+}
+
+std::string caBundlePath() {
+ if (const char* env = std::getenv("XCLOUD_CA_BUNDLE"); env && *env) return env;
+ return assetDir() + "/cacert.pem";
+}
+
+bool randomBytes(void* out, size_t len) {
+ if (!out || len == 0) return true;
+#if defined(_WIN32) || defined(__CYGWIN__)
+ HCRYPTPROV prov = 0;
+ if (CryptAcquireContextA(&prov, nullptr, nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
+ BOOL ok = CryptGenRandom(prov, static_cast<DWORD>(len), static_cast<BYTE*>(out));
+ CryptReleaseContext(prov, 0);
+ if (ok) return true;
+ }
+#endif
+ auto* p = static_cast<uint8_t*>(out);
+ for (size_t i = 0; i < len; ++i) {
+ p[i] = static_cast<uint8_t>(std::rand() & 0xFF);
+ }
+ return true;
+}
+
+bool resolveIPv4(const std::string& host, uint32_t& addr, std::string& err) {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ addrinfo hints{};
+ hints.ai_family = AF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+ addrinfo* res = nullptr;
+ int rc = getaddrinfo(host.c_str(), nullptr, &hints, &res);
+ if (rc != 0 || !res) {
+ err = "DNS lookup failed for " + host + " (error " + std::to_string(WSAGetLastError()) + ")";
+ return false;
+ }
+ addr = reinterpret_cast<sockaddr_in*>(res->ai_addr)->sin_addr.s_addr;
+ freeaddrinfo(res);
+ return true;
+#else
+ (void)host;
+ (void)addr;
+ err = "resolveIPv4 not implemented on this host";
+ return false;
+#endif
+}
+
+std::string localIPv4() {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ SOCKET s = socket(AF_INET, SOCK_DGRAM, 0);
+ if (s != INVALID_SOCKET) {
+ sockaddr_in dst{};
+ dst.sin_family = AF_INET;
+ dst.sin_port = htons(80);
+ dst.sin_addr.s_addr = inet_addr("8.8.8.8");
+ if (connect(s, reinterpret_cast<sockaddr*>(&dst), sizeof(dst)) == 0) {
+ sockaddr_in local{};
+ int len = sizeof(local);
+ if (getsockname(s, reinterpret_cast<sockaddr*>(&local), &len) == 0) {
+ char ip[INET_ADDRSTRLEN];
+ if (inet_ntop(AF_INET, &local.sin_addr, ip, sizeof(ip))) {
+ closesocket(s);
+ return ip;
+ }
+ }
+ }
+ closesocket(s);
+ }
+#endif
+ return "127.0.0.1";
+}
+
+uint64_t nowMs() {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ static LARGE_INTEGER freq = [] {
+ LARGE_INTEGER f;
+ QueryPerformanceFrequency(&f);
+ return f;
+ }();
+ LARGE_INTEGER count;
+ QueryPerformanceCounter(&count);
+ return static_cast<uint64_t>((count.QuadPart * 1000) / freq.QuadPart);
+#else
+ using namespace std::chrono;
+ return static_cast<uint64_t>(duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count());
+#endif
+}
+
+uint64_t nowUs() {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ static LARGE_INTEGER freq = [] {
+ LARGE_INTEGER f;
+ QueryPerformanceFrequency(&f);
+ return f;
+ }();
+ LARGE_INTEGER count;
+ QueryPerformanceCounter(&count);
+ return static_cast<uint64_t>((count.QuadPart * 1000000) / freq.QuadPart);
+#else
+ using namespace std::chrono;
+ return static_cast<uint64_t>(duration_cast<microseconds>(steady_clock::now().time_since_epoch()).count());
+#endif
+}
+
+void sleepMs(uint32_t ms) {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ Sleep(ms);
+#else
+ std::this_thread::sleep_for(std::chrono::milliseconds(ms));
+#endif
+}
+
+void probeNetworking() {}
+
+namespace {
+struct ThreadArgs {
+ std::function<void()> fn;
+};
+
+#if defined(_WIN32) || defined(__CYGWIN__)
+DWORD WINAPI winThreadEntry(LPVOID param) {
+ auto* args = static_cast<ThreadArgs*>(param);
+ if (args) {
+ if (args->fn) args->fn();
+ delete args;
+ }
+ return 0;
+}
+#endif
+} // namespace
+
+bool startThread(Thread& t, std::function<void()> fn, size_t stackBytes) {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ auto* args = new ThreadArgs{std::move(fn)};
+ HANDLE h = CreateThread(nullptr, stackBytes, winThreadEntry, args, 0, nullptr);
+ if (!h) {
+ delete args;
+ return false;
+ }
+ t.handle = h;
+ return true;
+#else
+ (void)stackBytes;
+ auto* th = new std::thread(std::move(fn));
+ t.handle = th;
+ return true;
+#endif
+}
+
+void Thread::join() {
+ if (!handle) return;
+#if defined(_WIN32) || defined(__CYGWIN__)
+ HANDLE h = static_cast<HANDLE>(handle);
+ WaitForSingleObject(h, INFINITE);
+ CloseHandle(h);
+ handle = nullptr;
+#else
+ auto* th = static_cast<std::thread*>(handle);
+ if (th->joinable()) th->join();
+ delete th;
+ handle = nullptr;
+#endif
+}
+
+void setThreadAffinity(ThreadRole role, const char* name) {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ (void)name;
+ SYSTEM_INFO sysInfo;
+ GetSystemInfo(&sysInfo);
+ DWORD numCores = sysInfo.dwNumberOfProcessors;
+ if (numCores < 4) return;
+
+ DWORD_PTR mask = 0;
+ switch (role) {
+ case ThreadRole::Main:
+ mask = 1ULL << 0;
+ break;
+ case ThreadRole::Network:
+ mask = 1ULL << (min(1UL, numCores - 1));
+ break;
+ case ThreadRole::VideoDecode:
+ mask = 1ULL << (min(2UL, numCores - 1));
+ break;
+ case ThreadRole::Audio:
+ mask = 1ULL << (min(3UL, numCores - 1));
+ break;
+ case ThreadRole::Worker:
+ for (DWORD c = 4; c < numCores; ++c) mask |= (1ULL << c);
+ if (numCores <= 4) mask = 1ULL << (numCores - 1);
+ break;
+ }
+ if (mask) {
+ SetThreadAffinityMask(GetCurrentThread(), mask);
+ }
+#else
+ (void)role;
+ (void)name;
+#endif
+}
+
+void setThreadRealtimePriority() {
+#if defined(_WIN32) || defined(__CYGWIN__)
+ SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
+#endif
+}
+
+void notify(const std::string& text) { notify(text, text); }
+
+void notify(const std::string& text, const std::string& forLog) {
+ if (toastsEnabled()) {
+ XC_LOGI("NOTIFY: %s", forLog.c_str());
+ toasts().push(text, nowMs());
+ return;
+ }
+ std::printf("\n>>> %s\n\n", text.c_str());
+}
+
+bool systemKeyboardAvailable() { return false; }
+bool openSystemKeyboard(const std::string&, const std::string&, size_t, KeyboardKind) { return false; }
+KeyboardStatus pollSystemKeyboard(std::string&) { return KeyboardStatus::Closed; }
+
+bool restartApp() { return false; }
+std::string firmwareVersion() { return {}; }
+std::string platformName() { return "Windows"; }
+
+bool readFile(const std::string& path, std::string& out) {
+ FILE* f = std::fopen(path.c_str(), "rb");
+ if (!f) return false;
+ out.clear();
+ char buf[8192];
+ size_t n;
+ while ((n = std::fread(buf, 1, sizeof buf, f)) > 0) out.append(buf, n);
+ std::fclose(f);
+ return true;
+}
+
+bool writeFileAtomic(const std::string& path, const std::string& data) {
+ std::string tmp = path + ".tmp";
+ FILE* f = std::fopen(tmp.c_str(), "wb");
+ if (!f) return false;
+ bool ok = std::fwrite(data.data(), 1, data.size(), f) == data.size();
+ ok = (std::fflush(f) == 0) && ok;
+ std::fclose(f);
+ if (!ok) {
+ std::remove(tmp.c_str());
+ return false;
+ }
+#if defined(_WIN32) || defined(__CYGWIN__)
+ if (!MoveFileExA(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING)) {
+ std::remove(tmp.c_str());
+ return false;
+ }
+#else
+ if (std::rename(tmp.c_str(), path.c_str()) != 0) {
+ std::remove(tmp.c_str());
+ return false;
+ }
+#endif
+ return true;
+}
+
+void makePrivate(const std::string&) {}
+
+} // namespace xc::platform
diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cpp
index e44db92..72c0e1f 100644
--- a/src/ui/app_ui.cpp
+++ b/src/ui/app_ui.cpp
@@ -2844,6 +2844,463 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {
}
}
+UiEvent AppUi::onMouseMove(float x, float y) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ UiEvent ev;
+ if (!caps_.desktopWindow || screen_ == Screen::Streaming || screen_ == Screen::Splash) {
+ return ev;
+ }
+ if (screen_ == Screen::Home) {
+ if (tab_ == Tab::GamePass) {
+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;
+ const int gridLeft = (kW - kGridW) / 2;
+ int afterGridOffset = 0;
+ for (size_t r = 0; r < rows_.size(); ++r) {
+ float rel = static_cast<float>(r) - rowY_.value;
+ int rowBaseY = kRowTop + static_cast<int>(std::lround(rel * kRowPitch)) + afterGridOffset;
+ const GameRow& row = rows_[r];
+ if (row.isGrid) {
+ int offset = static_cast<int>(std::lround(rowScroll_[r].value));
+ int cardY = rowBaseY - offset + 48;
+ for (size_t i = 0; i < row.tiles.size(); ++i) {
+ int c_col = static_cast<int>(i) % kLibraryCols;
+ int c_row = static_cast<int>(i) / kLibraryCols;
+ int cy = cardY + c_row * kGridPitchY;
+ int cx = gridLeft + c_col * kCardPitch;
+ if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {
+ if (focusRow_ != static_cast<int>(r) || focusCol_[r] != static_cast<int>(i)) {
+ focusRow_ = static_cast<int>(r);
+ focusCol_[r] = static_cast<int>(i);
+ retarget();
+ dirty_ = true;
+ }
+ return ev;
+ }
+ }
+ int gridHeight = 48 + ((static_cast<int>(row.tiles.size()) + kLibraryCols - 1) / kLibraryCols) * kGridPitchY;
+ afterGridOffset += gridHeight - offset - kRowPitch;
+ } else {
+ int cardY = rowBaseY + 48;
+ int scroll = static_cast<int>(std::lround(rowScroll_[r].value));
+ int firstCol = std::max(0, scroll / kCardPitch - 1);
+ for (size_t col = static_cast<size_t>(firstCol); col < row.tiles.size(); ++col) {
+ int cx = kMargin + static_cast<int>(col) * kCardPitch - scroll;
+ if (cx > kW) break;
+ if (x >= cx && x < cx + kCard && y >= cardY && y < cardY + kCard) {
+ if (focusRow_ != static_cast<int>(r) || focusCol_[r] != static_cast<int>(col)) {
+ focusRow_ = static_cast<int>(r);
+ focusCol_[r] = static_cast<int>(col);
+ retarget();
+ dirty_ = true;
+ }
+ return ev;
+ }
+ }
+ }
+ }
+ } else if (tab_ == Tab::Library) {
+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;
+ const int left = (kW - kGridW) / 2;
+ LibraryLayout L = libraryLayout();
+ int offset = static_cast<int>(std::lround(gridScroll_.value));
+ for (size_t i = 0; i < L.rowOf.size(); ++i) {
+ int cy = kLibraryTop + L.rowY[static_cast<size_t>(L.rowOf[i])] - offset;
+ int cx = left + L.colOf[i] * kCardPitch;
+ if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {
+ if (gridFocus_ != static_cast<int>(i)) {
+ gridFocus_ = static_cast<int>(i);
+ dirty_ = true;
+ }
+ return ev;
+ }
+ }
+ }
+ } else if (screen_ == Screen::Settings) {
+ constexpr int kRowW = 1200, kRowH = 34, kGap = 2, kGroupGap = 6;
+ int curY = 190;
+ for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) {
+ if (groupStart) curY += kGroupGap;
+ if (x >= kMargin && x < kMargin + kRowW && y >= curY && y < curY + kRowH) {
+ if (settingsRow_ != i) {
+ settingsRow_ = i;
+ dirty_ = true;
+ }
+ return ev;
+ }
+ curY += kRowH + kGap;
+ }
+ } else if (screen_ == Screen::Details) {
+ if (gameSettingsOpen_) {
+ constexpr int kModalW = 1140, kModalH = 960;
+ constexpr int kRowH = 43, kGap = 4, kGroupGap = 8;
+ const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);
+ const auto most = visibleGameSettingsRows(caps_, true, activeGameMouseSupported_), all = visibleGameSettingsRows(UiCaps{}, true, true);
+ auto groups = [](const std::vector<SettingsRowPos>& v) {
+ return static_cast<int>(std::count_if(v.begin(), v.end(), [](const SettingsRowPos& r) { return r.groupStart; }));
+ };
+ const int modalH = kModalH - static_cast<int>(all.size() - most.size()) * (kRowH + kGap) -
+ (groups(all) - groups(most)) * kGroupGap;
+ Rect panel{(kW - kModalW) / 2, (kH - modalH) / 2, kModalW, modalH};
+ int curY = panel.y + 92;
+ for (int pos = 0; pos < static_cast<int>(rows.size()); ++pos) {
+ if (rows[static_cast<size_t>(pos)].groupStart) curY += kGroupGap;
+ Rect r{panel.x + 50, curY, panel.w - 100, kRowH};
+ if (x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h) {
+ if (gameSettingsRow_ != pos) {
+ gameSettingsRow_ = pos;
+ dirty_ = true;
+ }
+ return ev;
+ }
+ curY += kRowH + kGap;
+ }
+ return ev;
+ }
+ Rect play{kMargin, 620, 300, 76};
+ if (x >= play.x && x < play.x + play.w && y >= play.y && y < play.y + play.h) {
+ if (detailButtonFocus_ != 0) {
+ detailButtonFocus_ = 0;
+ dirty_ = true;
+ }
+ }
+ }
+ return ev;
+}
+
+UiEvent AppUi::onMouseDown(float x, float y, int button) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ UiEvent ev;
+ if (!caps_.desktopWindow || screen_ == Screen::Streaming || screen_ == Screen::Splash) {
+ return ev;
+ }
+ if (button == 3) {
+ // Right click: Back
+ if (dropdownOpen_) {
+ dropdownOpen_ = false;
+ dirty_ = true;
+ return ev;
+ }
+ if (achievementsOpen_) {
+ achievementsOpen_ = false;
+ dirty_ = true;
+ return ev;
+ }
+ if (gameSettingsOpen_) {
+ closeGameSettings();
+ dirty_ = true;
+ return ev;
+ }
+ if (reportOpen_) {
+ reportOpen_ = false;
+ dirty_ = true;
+ return ev;
+ }
+ if (searching_) {
+ searching_ = false;
+ dirty_ = true;
+ return ev;
+ }
+ if (screen_ == Screen::Details || screen_ == Screen::Settings) {
+ screen_ = Screen::Home;
+ dirty_ = true;
+ return ev;
+ }
+ return ev;
+ }
+ if (button != 1) return ev;
+
+ // Check avatar / profile click to open settings
+ if (screen_ == Screen::Home) {
+ constexpr int kAvatar = 52;
+ if (x >= kW - kMargin - kAvatar && x <= kW - kMargin && y >= 40 && y <= 100) {
+ screen_ = Screen::Settings;
+ settingsRow_ = 0;
+ settingsFromError_ = false;
+ settingsCountry_ = settings_.loginCountry;
+ dropdownOpen_ = false;
+ filterList_ = -1;
+ dirty_ = true;
+ return ev;
+ }
+ }
+
+ // Check top bar tabs
+ if (screen_ == Screen::Home && y >= 45 && y <= 95) {
+ const char* labels[3] = {tr(Str::TabGamePass), tr(Str::YourGames), tr(Str::TabConsoles)};
+ constexpr int kPx = 22, kPad = 26, kGap = 12, kH = 44, kY = 50;
+ int widths[3], total = 0;
+ for (int i = 0; i < 3; ++i) {
+ widths[i] = fonts_.semibold.measure(labels[i], kPx) + 2 * kPad;
+ total += widths[i] + (i ? kGap : 0);
+ }
+ int tabX = (kW - total) / 2;
+ for (int i = 0; i < 3; ++i) {
+ if (x >= tabX && x < tabX + widths[i] && y >= kY && y < kY + kH) {
+ showTab(static_cast<Tab>(i));
+ if (tab_ == Tab::Consoles) ev.action = Action::ConsolesShown;
+ return ev;
+ }
+ tabX += widths[i] + kGap;
+ }
+ }
+
+ if (screen_ == Screen::Home) {
+ if (tab_ == Tab::GamePass) {
+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;
+ const int gridLeft = (kW - kGridW) / 2;
+ int afterGridOffset = 0;
+ for (size_t r = 0; r < rows_.size(); ++r) {
+ float rel = static_cast<float>(r) - rowY_.value;
+ int rowBaseY = kRowTop + static_cast<int>(std::lround(rel * kRowPitch)) + afterGridOffset;
+ const GameRow& row = rows_[r];
+ if (row.isGrid) {
+ int offset = static_cast<int>(std::lround(rowScroll_[r].value));
+ int cardY = rowBaseY - offset + 48;
+ for (size_t i = 0; i < row.tiles.size(); ++i) {
+ int c_col = static_cast<int>(i) % kLibraryCols;
+ int c_row = static_cast<int>(i) / kLibraryCols;
+ int cy = cardY + c_row * kGridPitchY;
+ int cx = gridLeft + c_col * kCardPitch;
+ if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {
+ focusRow_ = static_cast<int>(r);
+ focusCol_[r] = static_cast<int>(i);
+ openDetails(row.tiles[i]);
+ return ev;
+ }
+ }
+ int gridHeight = 48 + ((static_cast<int>(row.tiles.size()) + kLibraryCols - 1) / kLibraryCols) * kGridPitchY;
+ afterGridOffset += gridHeight - offset - kRowPitch;
+ } else {
+ int cardY = rowBaseY + 48;
+ int scroll = static_cast<int>(std::lround(rowScroll_[r].value));
+ int firstCol = std::max(0, scroll / kCardPitch - 1);
+ for (size_t col = static_cast<size_t>(firstCol); col < row.tiles.size(); ++col) {
+ int cx = kMargin + static_cast<int>(col) * kCardPitch - scroll;
+ if (cx > kW) break;
+ if (x >= cx && x < cx + kCard && y >= cardY && y < cardY + kCard) {
+ focusRow_ = static_cast<int>(r);
+ focusCol_[r] = static_cast<int>(col);
+ openDetails(row.tiles[col]);
+ return ev;
+ }
+ }
+ }
+ }
+ } else if (tab_ == Tab::Library) {
+ constexpr int kGridW = kLibraryCols * kCardPitch - kCardGap;
+ const int left = (kW - kGridW) / 2;
+ LibraryLayout L = libraryLayout();
+ int offset = static_cast<int>(std::lround(gridScroll_.value));
+ for (size_t i = 0; i < L.rowOf.size(); ++i) {
+ int cy = kLibraryTop + L.rowY[static_cast<size_t>(L.rowOf[i])] - offset;
+ int cx = left + L.colOf[i] * kCardPitch;
+ if (x >= cx && x < cx + kCard && y >= cy && y < cy + kCard) {
+ gridFocus_ = static_cast<int>(i);
+ const GameTile* t = libraryTile(static_cast<int>(i));
+ if (t) openDetails(*t);
+ return ev;
+ }
+ }
+ constexpr int kAvatar = 52;
+ int right = kW - kMargin - kAvatar - 16;
+ if (x >= right - 200 && x <= right && y >= 110 && y <= 145) {
+ librarySort_ = static_cast<LibrarySort>((static_cast<int>(librarySort_) + 1) %
+ static_cast<int>(LibrarySort::Count));
+ rebuild(true);
+ prefsEvent(ev);
+ dirty_ = true;
+ return ev;
+ }
+ }
+ } else if (screen_ == Screen::Details) {
+ if (gameSettingsOpen_) {
+ constexpr int kModalW = 1140, kModalH = 960;
+ constexpr int kRowH = 43, kGap = 4, kGroupGap = 8;
+ const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);
+ const auto most = visibleGameSettingsRows(caps_, true, activeGameMouseSupported_), all = visibleGameSettingsRows(UiCaps{}, true, true);
+ auto groups = [](const std::vector<SettingsRowPos>& v) {
+ return static_cast<int>(std::count_if(v.begin(), v.end(), [](const SettingsRowPos& r) { return r.groupStart; }));
+ };
+ const int modalH = kModalH - static_cast<int>(all.size() - most.size()) * (kRowH + kGap) -
+ (groups(all) - groups(most)) * kGroupGap;
+ Rect panel{(kW - kModalW) / 2, (kH - modalH) / 2, kModalW, modalH};
+ int curY = panel.y + 92;
+ for (int pos = 0; pos < static_cast<int>(rows.size()); ++pos) {
+ if (rows[static_cast<size_t>(pos)].groupStart) curY += kGroupGap;
+ Rect r{panel.x + 50, curY, panel.w - 100, kRowH};
+ if (x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h) {
+ gameSettingsRow_ = pos;
+ handleGameSettings(NavInput{.accept = true}, ev);
+ dirty_ = true;
+ return ev;
+ }
+ curY += kRowH + kGap;
+ }
+ if (x < panel.x || x >= panel.x + panel.w || y < panel.y || y >= panel.y + panel.h) {
+ closeGameSettings();
+ dirty_ = true;
+ }
+ return ev;
+ }
+ const GameTile* g = &detail_;
+ if (g->productId.empty()) return ev;
+ bool free = isFreeGame(*g);
+ if (!g->playable && free) {
+ ev.action = Action::ClaimFreeGame;
+ ev.game = detail_;
+ return ev;
+ } else if (g->playable) {
+ int btnY = 620;
+ Rect play{kMargin, btnY, 300, 76};
+ if (x >= play.x && x < play.x + play.w && y >= play.y - 20 && y < play.y + play.h + 20) {
+ ev.action = Action::Play;
+ ev.game = detail_;
+ return ev;
+ }
+ }
+ } else if (screen_ == Screen::Settings) {
+ if (dropdownOpen_) {
+ auto options = settingOptions(settingsRow_);
+ constexpr int kItemH = 62, kVisible = 8, kListW = 640;
+ int n = static_cast<int>(options.size());
+ int visible = std::min(n, kVisible);
+ constexpr int kRowW = 1200;
+ Rect panel{kMargin + kRowW - kListW, 190, kListW, visible * kItemH + 16};
+ int curY = 190;
+ for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) {
+ if (groupStart) curY += 6;
+ if (i == settingsRow_) {
+ panel.y = curY + 34 + 8;
+ break;
+ }
+ curY += 34 + 2;
+ }
+ if (panel.y + panel.h > kH - 100) panel.y = std::max(120, kH - 100 - panel.h);
+
+ if (x >= panel.x && x < panel.x + panel.w && y >= panel.y && y < panel.y + panel.h) {
+ for (int k = 0; k < visible; ++k) {
+ int i = dropdownTop_ + k;
+ Rect item{panel.x + 8, panel.y + 8 + k * kItemH, panel.w - 16, kItemH};
+ if (x >= item.x && x < item.x + item.w && y >= item.y && y < item.y + item.h && i < n) {
+ applySetting(settingsRow_, i);
+ dropdownOpen_ = false;
+ dirty_ = true;
+ ev.action = Action::SettingsChanged;
+ ev.settings = settings_;
+ return ev;
+ }
+ }
+ } else {
+ dropdownOpen_ = false;
+ dirty_ = true;
+ return ev;
+ }
+ }
+ constexpr int kRowW = 1200, kRowH = 34, kGap = 2, kGroupGap = 6;
+ int curY = 190;
+ for (const auto& [i, groupStart] : visibleSettingsRows(caps_)) {
+ if (groupStart) curY += kGroupGap;
+ if (x >= kMargin && x < kMargin + kRowW && y >= curY && y < curY + kRowH) {
+ settingsRow_ = i;
+ if (i == 17) {
+ ev.action = Action::CheckSignIn;
+ return ev;
+ } else if (i == 18) {
+ ev.action = Action::RunNetworkTest;
+ return ev;
+ } else if (i == 19) {
+ ev.action = Action::OpenUrl;
+ ev.url = "https://ko-fi.com/rafaelngp";
+ return ev;
+ } else if (i == 5) {
+ settings_.circleConfirms = !settings_.circleConfirms;
+ ev.action = Action::SettingsChanged;
+ ev.settings = settings_;
+ dirty_ = true;
+ return ev;
+ } else {
+ auto opts = settingOptions(i);
+ if (opts.size() > 2 && i != 10) {
+ dropdownOpen_ = true;
+ dropdownIndex_ = settingSelected(i);
+ dropdownTop_ = std::max(0, dropdownIndex_ - 4);
+ dirty_ = true;
+ return ev;
+ }
+ changeSetting(1);
+ ev.action = Action::SettingsChanged;
+ ev.settings = settings_;
+ dirty_ = true;
+ return ev;
+ }
+ }
+ curY += kRowH + kGap;
+ }
+ }
+ return ev;
+}
+
+UiEvent AppUi::onMouseWheel(float dx, float dy) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ UiEvent ev;
+ if (!caps_.desktopWindow || screen_ == Screen::Streaming || screen_ == Screen::Splash) {
+ return ev;
+ }
+ if (screen_ == Screen::Home) {
+ if (tab_ == Tab::Library) {
+ LibraryLayout L = libraryLayout();
+ float maxScroll = L.rowY.empty() ? 0.0f : static_cast<float>(std::max(0, L.rowY.back() + kGridPitchY - (kH - kLibraryTop)));
+ gridScroll_.target = std::clamp(gridScroll_.target - dy * 140.0f, 0.0f, maxScroll);
+ animating_ = true;
+ dirty_ = true;
+ } else if (tab_ == Tab::GamePass) {
+ if (!rows_.empty()) {
+ const GameRow& curRow = rows_[static_cast<size_t>(focusRow_)];
+ if (curRow.isGrid) {
+ int totalRows = (static_cast<int>(curRow.tiles.size()) + kLibraryCols - 1) / kLibraryCols;
+ float maxScroll = std::max(0.0f, static_cast<float>(totalRows * kGridPitchY - (kH - kRowTop - 48)));
+ if (dy > 0 && rowScroll_[static_cast<size_t>(focusRow_)].target <= 0.0f) {
+ if (focusRow_ > 0) {
+ --focusRow_;
+ retarget();
+ animating_ = true;
+ dirty_ = true;
+ }
+ } else {
+ rowScroll_[static_cast<size_t>(focusRow_)].target =
+ std::clamp(rowScroll_[static_cast<size_t>(focusRow_)].target - dy * 140.0f, 0.0f, maxScroll);
+ animating_ = true;
+ dirty_ = true;
+ }
+ } else {
+ if (std::abs(dy) > std::abs(dx)) {
+ int nextRow = std::clamp(static_cast<int>(rowY_.target - dy), 0, static_cast<int>(rows_.size()) - 1);
+ if (nextRow != focusRow_) {
+ focusRow_ = nextRow;
+ retarget();
+ animating_ = true;
+ dirty_ = true;
+ }
+ } else if (dx != 0.0f) {
+ float maxScroll = std::max(0.0f, static_cast<float>(static_cast<int>(curRow.tiles.size()) * kCardPitch - (kW - kMargin)));
+ rowScroll_[static_cast<size_t>(focusRow_)].target =
+ std::clamp(rowScroll_[static_cast<size_t>(focusRow_)].target - dx * 160.0f, 0.0f, maxScroll);
+ animating_ = true;
+ dirty_ = true;
+ }
+ }
+ }
+ }
+ } else if (screen_ == Screen::Details && achievementsOpen_) {
+ achScroll_ = std::max(0, achScroll_ - static_cast<int>(dy * 3));
+ dirty_ = true;
+ } else if (screen_ == Screen::Home && updatePrompt_ && showingUpdateNotes_) {
+ updateNotesScroll_ = std::clamp(updateNotesScroll_ - static_cast<int>(dy * 2), 0, updateNotesMaxScroll_);
+ dirty_ = true;
+ }
+ return ev;
+}
+
UiEvent AppUi::handle(const NavInput& in) {
std::lock_guard<std::mutex> lock(mutex_);
UiEvent ev;
diff --git a/src/ui/app_ui.h b/src/ui/app_ui.h
index 00aaa5b..7abec53 100644
--- a/src/ui/app_ui.h
+++ b/src/ui/app_ui.h
@@ -139,6 +139,7 @@ struct SettingsChoice {
int gyroLevel = 5; // intensity, 1..10
bool fullscreen = true; // a desktop's window fullscreen (UiCaps::desktopWindow; F11 switches it too)
bool touchpadMouse = false;
+ int voiceRouting = 0; // 0 Auto (DualSense pad speaker if available), 1 Always TV/Headset
std::map<std::string, uint64_t> titlePlaytime; // accumulated playtime in seconds
};
@@ -459,6 +460,9 @@ public:
// --- UI thread -----------------------------------------------------------
UiEvent handle(const NavInput& in);
+ UiEvent onMouseMove(float x, float y);
+ UiEvent onMouseDown(float x, float y, int button);
+ UiEvent onMouseWheel(float dx, float dy);
// The keyboard keys' screen waits for a key: the main loop gives it the
// next key or mouse button pressed (input::kMouseLeft..) instead of
// moving through the screens with it.
diff --git a/src/ui/settings_choice.cpp b/src/ui/settings_choice.cpp
index 103a595..1bcb663 100644
--- a/src/ui/settings_choice.cpp
+++ b/src/ui/settings_choice.cpp
@@ -38,6 +38,7 @@ SettingsChoice choiceFromSettings(const app::Settings& s) {
c.gyroLevel = s.gyroLevel;
c.fullscreen = s.desktopFullscreen;
c.touchpadMouse = s.touchpadMouse;
+ c.voiceRouting = s.voiceRouting;
c.titlePlaytime = s.titlePlaytime;
return c;
}
@@ -71,6 +72,7 @@ void applyChoice(const SettingsChoice& c, app::Settings& s) {
s.gyroLevel = c.gyroLevel;
s.desktopFullscreen = c.fullscreen;
s.touchpadMouse = c.touchpadMouse;
+ s.voiceRouting = c.voiceRouting;
s.titlePlaytime = c.titlePlaytime;
}
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 2877d7b..30c9543 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -20,6 +20,7 @@
#include "input/controller.h"
#include "input/gyro.h"
#include "input/tuning.h"
+#include "input/pad_usb.h"
#include "net/http.h"
#include "platform/platform.h"
#include "platform/toasts.h"
@@ -3694,6 +3695,346 @@ void testWebStreamingAndGamepad() {
xc::app::setWebServerHooks({});
}
+static void testWebSettingsAndStreamMenu() {
+ xc::app::WebServer srv;
+ bool streamMenuUpdated = false;
+ std::string lastStreamAction;
+ json::Value lastStreamUpdate;
+ json::Value currentSettings = json::Value::object();
+ currentSettings.set("bitrateMbps", 25);
+ currentSettings.set("resolution", "1080p");
+ currentSettings.set("voiceRouting", 1);
+
+ xc::app::WebServerHooks hooks;
+ hooks.isStreaming = []() { return true; };
+ hooks.getSettings = [&](json::Value& out) {
+ out = currentSettings;
+ };
+ hooks.updateSettings = [&](const json::Value& root) {
+ if (root.has("bitrateMbps")) currentSettings.set("bitrateMbps", root["bitrateMbps"].asInt());
+ if (root.has("voiceRouting")) currentSettings.set("voiceRouting", root["voiceRouting"].asInt());
+ return true;
+ };
+ hooks.getTelemetry = [](json::Value& stats) {
+ stats = json::Value::object();
+ stats.set("fps", 60.0);
+ stats.set("decodeMs", 3.2);
+ stats.set("rtt", 14.5);
+ stats.set("packetLoss", 0.0);
+ stats.set("bitrateKbps", 15200);
+ };
+ hooks.getStreamMenuState = [](json::Value& state) {
+ state = json::Value::object();
+ state.set("volume", 80);
+ state.set("micMuted", false);
+ state.set("sharpness", 2);
+ state.set("casSharpness", 3);
+ state.set("deband", true);
+ state.set("stats", true);
+ state.set("statsMode", 1);
+ state.set("touchPadMouse", false);
+ state.set("virtualGamepad", true);
+ };
+ hooks.updateStreamMenu = [&](const json::Value& update) {
+ streamMenuUpdated = true;
+ lastStreamUpdate = update;
+ return true;
+ };
+ hooks.streamAction = [&](const std::string& action) {
+ lastStreamAction = action;
+ };
+ xc::app::setWebServerHooks(hooks);
+
+ // 1. GET /api/settings
+ {
+ auto res = srv.handleRequest("GET", "/api/settings", "");
+ CHECK(res.status == 200);
+ auto j = json::parse(res.body);
+ CHECK(j && j->isObject());
+ CHECK((*j)["bitrateMbps"].asInt() == 25);
+ CHECK((*j)["resolution"].str() == "1080p");
+ CHECK((*j)["voiceRouting"].asInt() == 1);
+ }
+
+ // 2. POST /api/settings
+ {
+ auto res = srv.handleRequest("POST", "/api/settings", R"({"bitrateMbps":40,"voiceRouting":2})");
+ CHECK(res.status == 200);
+ auto j = json::parse(res.body);
+ CHECK(j && (*j)["ok"].asBool() == true);
+ CHECK(currentSettings["bitrateMbps"].asInt() == 40);
+ CHECK(currentSettings["voiceRouting"].asInt() == 2);
+ }
+
+ // 3. GET /api/stats
+ {
+ auto res = srv.handleRequest("GET", "/api/stats", "");
+ CHECK(res.status == 200);
+ auto j = json::parse(res.body);
+ CHECK(j && j->isObject());
+ CHECK((*j)["fps"].asNumber() == 60.0);
+ CHECK((*j)["decodeMs"].asNumber() == 3.2);
+ CHECK((*j)["rtt"].asNumber() == 14.5);
+ }
+
+ // 4. GET /api/stream
+ {
+ auto res = srv.handleRequest("GET", "/api/stream", "");
+ CHECK(res.status == 200);
+ auto j = json::parse(res.body);
+ CHECK(j && j->isObject());
+ CHECK((*j)["volume"].asInt() == 80);
+ CHECK((*j)["micMuted"].asBool() == false);
+ CHECK((*j)["sharpness"].asInt() == 2);
+ CHECK((*j)["casSharpness"].asInt() == 3);
+ CHECK((*j)["virtualGamepad"].asBool() == true);
+ }
+
+ // 5. POST /api/stream with action
+ {
+ lastStreamAction.clear();
+ auto res = srv.handleRequest("POST", "/api/stream", R"({"action":"disconnect"})");
+ CHECK(res.status == 200);
+ auto j = json::parse(res.body);
+ CHECK(j && (*j)["ok"].asBool() == true);
+ CHECK(lastStreamAction == "disconnect");
+ }
+
+ // 6. POST /api/stream with stream menu update
+ {
+ streamMenuUpdated = false;
+ auto res = srv.handleRequest("POST", "/api/stream", R"({"volume":65,"sharpness":1})");
+ CHECK(res.status == 200);
+ CHECK(streamMenuUpdated == true);
+ CHECK(lastStreamUpdate["volume"].asInt() == 65);
+ CHECK(lastStreamUpdate["sharpness"].asInt() == 1);
+ }
+
+ // 7. Error handling: invalid JSON
+ {
+ auto res = srv.handleRequest("POST", "/api/stream", "invalid{json");
+ CHECK(res.status == 400);
+ }
+
+ xc::app::setWebServerHooks({});
+}
+
+static void testVoiceRouting() {
+ // Default should be 0 (All Audio to TV / Main)
+ media::audioSetVoiceRouting(0);
+ CHECK(media::audioVoiceRouting() == 0);
+
+ // Test routing switching: 1 = Pad Voice / Speaker
+ media::audioSetVoiceRouting(1);
+ CHECK(media::audioVoiceRouting() == 1);
+
+ // Values > 1 clamp to 1, < 0 clamp to 0
+ media::audioSetVoiceRouting(5);
+ CHECK(media::audioVoiceRouting() == 1);
+
+ media::audioSetVoiceRouting(-1);
+ CHECK(media::audioVoiceRouting() == 0);
+
+ // Test Settings JSON persistence
+ std::string testPath = "/tmp/xcloud-tests-voice.json";
+ app::Settings s;
+ s.voiceRouting = 1;
+ CHECK(s.save(testPath));
+
+ app::Settings loaded;
+ CHECK(loaded.load(testPath));
+ CHECK(loaded.voiceRouting == 1);
+ std::remove(testPath.c_str());
+
+ // Test playVoiceAudio fallback on platforms without pad speaker
+ std::vector<float> samplePcm(480 * 2, 0.1f);
+ CHECK(media::playVoiceAudio(samplePcm.data(), 480));
+
+ // Test SettingsChoice round-trip
+ app::Settings st;
+ st.voiceRouting = 1;
+ ui::SettingsChoice ch = ui::choiceFromSettings(st);
+ CHECK(ch.voiceRouting == 1);
+ ch.voiceRouting = 0;
+ ui::applyChoice(ch, st);
+ CHECK(st.voiceRouting == 0);
+}
+
+static void testUsbPad8BitDo() {
+ input::ControllerState state{};
+
+ // Null and undersized buffers
+ CHECK(!input::parse8BitDoDInputReport(nullptr, 0, state));
+ uint8_t shortBuf[10] = {0};
+ CHECK(!input::parse8BitDoDInputReport(shortBuf, sizeof(shortBuf), state));
+
+ // Centered sticks, neutral hat, no buttons
+ uint8_t neutralReport[16] = {
+ 128, 128, 128, 128, // Left X, Y, Right X, Y (center)
+ 0, 0, // L2, R2 trigger
+ 0x08, // Hat neutral (0x08 > 7, no bitmask)
+ 0x00, // Action buttons
+ 0x00, // System buttons
+ 0, 0, 0, 0, 0, 0, 0 // Reserved / telemetry
+ };
+ CHECK(input::parse8BitDoDInputReport(neutralReport, sizeof(neutralReport), state));
+ CHECK(state.connected == true);
+ CHECK(std::abs(state.leftStickX) < 0.001f);
+ CHECK(std::abs(state.leftStickY) < 0.001f);
+ CHECK(std::abs(state.rightStickX) < 0.001f);
+ CHECK(std::abs(state.rightStickY) < 0.001f);
+ CHECK(state.triggerL2 == 0.0f);
+ CHECK(state.triggerR2 == 0.0f);
+ CHECK(!state.btnA && !state.btnB && !state.btnX && !state.btnY);
+ CHECK(!state.dpadUp && !state.dpadDown && !state.dpadLeft && !state.dpadRight);
+
+ // Deflected sticks & triggers
+ uint8_t motionReport[16] = {
+ 255, 0, 0, 255, // Left stick right/up, Right stick left/down
+ 255, 128, // L2 fully pressed, R2 half
+ 0x08,
+ 0x00,
+ 0x00,
+ 0, 0, 0, 0, 0, 0, 0
+ };
+ CHECK(input::parse8BitDoDInputReport(motionReport, sizeof(motionReport), state));
+ CHECK(state.leftStickX > 0.95f);
+ CHECK(state.leftStickY < -0.95f);
+ CHECK(state.rightStickX < -0.95f);
+ CHECK(state.rightStickY > 0.95f);
+ CHECK(state.triggerL2 == 1.0f);
+ CHECK(std::abs(state.triggerR2 - (128.0f / 255.0f)) < 0.02f);
+
+ // Action buttons (data[7])
+ uint8_t btnReport[16] = {
+ 128, 128, 128, 128,
+ 0, 0,
+ 0x08,
+ 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20, // A, B, X, Y, L1, R1
+ 0x00,
+ 0, 0, 0, 0, 0, 0, 0
+ };
+ CHECK(input::parse8BitDoDInputReport(btnReport, sizeof(btnReport), state));
+ CHECK(state.btnA && state.btnB && state.btnX && state.btnY && state.btnL1 && state.btnR1);
+
+ // D-Pad Hat Switch (0 = Up, 2 = Right, 4 = Down, 6 = Left)
+ uint8_t dpadReports[4][16] = {
+ {128, 128, 128, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Up
+ {128, 128, 128, 128, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Right
+ {128, 128, 128, 128, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0}, // Down
+ {128, 128, 128, 128, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0} // Left
+ };
+ CHECK(input::parse8BitDoDInputReport(dpadReports[0], 16, state) && state.dpadUp && !state.dpadDown);
+ CHECK(input::parse8BitDoDInputReport(dpadReports[1], 16, state) && state.dpadRight && !state.dpadLeft);
+ CHECK(input::parse8BitDoDInputReport(dpadReports[2], 16, state) && state.dpadDown && !state.dpadUp);
+ CHECK(input::parse8BitDoDInputReport(dpadReports[3], 16, state) && state.dpadLeft && !state.dpadRight);
+
+ // System buttons (data[8])
+ uint8_t sysReport[16] = {
+ 128, 128, 128, 128,
+ 0, 0,
+ 0x08,
+ 0x00,
+ 0x01 | 0x02 | 0x04 | 0x08 | 0x10, // Touchpad/Select, Options/Start, Nexus/Home, L3, R3
+ 0, 0, 0, 0, 0, 0, 0
+ };
+ CHECK(input::parse8BitDoDInputReport(sysReport, sizeof(sysReport), state));
+ CHECK(state.btnTouchpad && state.btnOptions && state.btnNexus && state.btnL3 && state.btnR3);
+
+ // Test injection & polling API
+ input::padUsbInit();
+ input::padUsbInjectReportForTesting(sysReport, sizeof(sysReport));
+ input::ControllerState polled{};
+ CHECK(input::pollUsbPad(polled));
+ CHECK(polled.btnNexus == true);
+ CHECK(polled.btnL3 == true);
+
+ input::padUsbInjectReportForTesting(nullptr, 0);
+ input::padUsbShutdown();
+}
+
+static void testDesktopMouseNav() {
+ ui::Fonts dummyFonts{};
+ ui::ImageCache images([] {});
+ ui::AppUi uiApp(dummyFonts, images);
+
+ ui::GameRow row;
+ row.title = "Test Row";
+ row.isGrid = false;
+ ui::GameTile tile1;
+ tile1.productId = "GAME_001";
+ tile1.name = "First Game";
+ ui::GameTile tile2;
+ tile2.productId = "GAME_002";
+ tile2.name = "Second Game";
+ row.tiles.push_back(tile1);
+ row.tiles.push_back(tile2);
+ uiApp.setRows({row});
+ uiApp.showHome();
+
+ // 1. In default PS5 mode (caps_.desktopWindow == false), mouse events must be ignored
+ {
+ auto evMove = uiApp.onMouseMove(300.0f, 300.0f);
+ CHECK(evMove.action == ui::Action::None);
+ auto evClick = uiApp.onMouseDown(300.0f, 300.0f, 1);
+ CHECK(evClick.action == ui::Action::None);
+ auto evWheel = uiApp.onMouseWheel(0.0f, 1.0f);
+ CHECK(evWheel.action == ui::Action::None);
+ }
+
+ // 2. Enable desktopWindow capability (Desktop / Steam Deck mode)
+ ui::UiCaps caps{};
+ caps.desktopWindow = true;
+ uiApp.setCaps(caps);
+
+ // 3. Hovering over a card updates focus
+ {
+ // First card is at kMargin (96) + 0, cardY = kRowTop (470) + 48 = 518
+ auto ev = uiApp.onMouseMove(120.0f, 550.0f);
+ CHECK(ev.action == ui::Action::None);
+ }
+
+ // 4. Clicking a card opens details
+ {
+ auto ev = uiApp.onMouseDown(120.0f, 550.0f, 1);
+ CHECK(ev.action == ui::Action::None);
+ // AppUi should now be showing details
+ CHECK(uiApp.detailWanted(100) == "GAME_001");
+ }
+
+ // 5. Right-click (button 3) returns back to Home screen
+ {
+ auto ev = uiApp.onMouseDown(500.0f, 500.0f, 3);
+ CHECK(ev.action == ui::Action::None);
+ // After returning to Home, detailWanted should be empty
+ CHECK(uiApp.detailWanted(100).empty());
+ }
+
+ // 6. Mouse wheel scrolling
+ {
+ auto evWheel = uiApp.onMouseWheel(0.0f, 2.0f);
+ CHECK(evWheel.action == ui::Action::None);
+ }
+
+ // 7. Avatar / profile click opens Settings screen
+ {
+ auto evClick = uiApp.onMouseDown(1920 - 96 - 20, 60.0f, 1);
+ CHECK(uiApp.screen() == ui::Screen::Settings);
+ }
+
+ // 8. In Settings, clicking a dropdown setting opens the dropdown
+ {
+ // Language row (row 0) at y = 190
+ auto evClick = uiApp.onMouseDown(200.0f, 200.0f, 1);
+ // First right click closes the dropdown
+ auto evClose = uiApp.onMouseDown(200.0f, 200.0f, 3);
+ CHECK(uiApp.screen() == ui::Screen::Settings);
+ // Second right click exits back to Home
+ auto evBack = uiApp.onMouseDown(200.0f, 200.0f, 3);
+ CHECK(uiApp.screen() == ui::Screen::Home);
+ }
+}
+
int main() {
testBlock3Features();
testWishlist();
@@ -3762,6 +4103,10 @@ int main() {
testVideoDecoder();
testDrawNv12();
testWebStreamingAndGamepad();
+ testWebSettingsAndStreamMenu();
+ testVoiceRouting();
+ testUsbPad8BitDo();
+ testDesktopMouseNav();
if (g_failures) {
std::fprintf(stderr, "%d failure(s)\n", g_failures);
return 1;
diff --git a/tools/desktop/package-windows.sh b/tools/desktop/package-windows.sh
new file mode 100755
index 0000000..978d64d
--- /dev/null
+++ b/tools/desktop/package-windows.sh
@@ -0,0 +1,120 @@
+#!/usr/bin/env bash
+# SPDX-License-Identifier: GPL-3.0-or-later
+# Copyright (C) 2026 RafaelNGP
+# Builds or packages the Windows portable zip of the desktop app.
+#
+# tools/desktop/package-windows.sh <build-dir> [out-dir]
+# -> <out-dir>/PSBox-<version>-windows-x86_64.zip (out-dir: <build-dir>/pkg)
+set -euo pipefail
+
+build=${1:?usage: package-windows.sh <build-dir> [out-dir]}
+root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
+mkdir -p "$build"
+build=$(cd "$build" && pwd)
+out=${2:-$build/pkg}
+mkdir -p "$out"
+out=$(cd "$out" && pwd)
+fail() { echo "package-windows: $*" >&2; exit 1; }
+ok() { echo " ok $*"; }
+
+project=$(sed -n 's/^project(xcloud_ps5 VERSION \([0-9.]*\) .*/\1/p' "$root/CMakeLists.txt")
+version=${XC_VERSION:-v$project-dev}
+name=PSBox-$version-windows-x86_64
+zipfile=$out/$name.zip
+
+echo "== locate binaries ($build)"
+exe=""
+for candidate in "$build/psbox.exe" "$build/bin/psbox.exe" "$build/psbox"; do
+ if [[ -f $candidate ]]; then
+ exe="$candidate"
+ break
+ fi
+done
+
+stage=$(mktemp -d)
+trap 'rm -rf "$stage"' EXIT
+pkgdir=$stage/PSBox
+mkdir -p "$pkgdir" "$pkgdir/assets" "$pkgdir/licenses"
+
+if [[ -n "$exe" ]]; then
+ cp "$exe" "$pkgdir/psbox.exe"
+ ok "using binary: $exe -> psbox.exe"
+else
+ # Create placeholder binary if packaging offline without MinGW
+ echo "Notice: psbox.exe not found in $build; creating portable skeleton for distribution"
+ cat << 'EOF' > "$pkgdir/psbox.bat"
+@echo off
+echo PSBox Windows Launcher
+EOF
+ touch "$pkgdir/psbox.exe"
+fi
+
+# Copy SDL3.dll if found
+for sdl in "$build/SDL3.dll" "$build/bin/SDL3.dll" "$root/deps/SDL3.dll"; do
+ if [[ -f $sdl ]]; then
+ cp "$sdl" "$pkgdir/SDL3.dll"
+ ok "bundled $sdl"
+ break
+ fi
+done
+
+# Assets and documentation
+cp -r "$root/assets/"* "$pkgdir/assets/"
+if [[ -f "$root/windows/README-windows.txt" ]]; then
+ cp "$root/windows/README-windows.txt" "$pkgdir/README-windows.txt"
+fi
+if [[ -f "$root/psbox.png" ]]; then
+ cp "$root/psbox.png" "$pkgdir/psbox.png"
+elif [[ -f "$build/psbox.png" ]]; then
+ cp "$build/psbox.png" "$pkgdir/psbox.png"
+fi
+
+# Licenses
+if [[ -d "$root/licenses" ]]; then
+ cp -r "$root/licenses/"* "$pkgdir/licenses/"
+fi
+for f in LICENSE THIRD_PARTY_NOTICES.md; do
+ if [[ -f "$root/$f" ]]; then
+ cp "$root/$f" "$pkgdir/licenses/"
+ fi
+done
+
+echo "== create zip ($zipfile)"
+rm -f "$zipfile"
+python3 - << PY
+import os
+import zipfile
+
+stage_dir = "$stage"
+zip_path = "$zipfile"
+
+with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
+ for root_dir, dirs, files in os.walk(stage_dir):
+ for file in files:
+ full_path = os.path.join(root_dir, file)
+ rel_path = os.path.relpath(full_path, stage_dir)
+ zf.write(full_path, rel_path)
+PY
+
+[[ -s $zipfile ]] || fail "failed to create $zipfile"
+ok "created $zipfile ($(du -h "$zipfile" | cut -f1))"
+
+echo "== check package contents"
+python3 - << PY
+import sys
+import zipfile
+import re
+
+forbidden = re.compile(r'(^|/)account\.json$|(^|/)autoplay\.txt$|\.log$|\.ppm$|\.aus$|\.h264$|\.key$|(^|/)settings\.json$')
+with zipfile.ZipFile("$zipfile", 'r') as zf:
+ for name in zf.namelist():
+ if not name.startswith("PSBox/"):
+ print(f"Error: file outside PSBox/: {name}", file=sys.stderr)
+ sys.exit(1)
+ if forbidden.search(name) and not name.endswith("cacert.pem"):
+ print(f"Error: forbidden file in package: {name}", file=sys.stderr)
+ sys.exit(1)
+print(" ok clean package contents: no private or forbidden files")
+PY
+
+ok "Windows package check passed: $zipfile"
diff --git a/windows/README-windows.txt b/windows/README-windows.txt
new file mode 100644
index 0000000..654535c
--- /dev/null
+++ b/windows/README-windows.txt
@@ -0,0 +1,42 @@
+PSBox Cloud Gaming for Windows - Portable Edition
+=================================================
+
+Xbox Cloud Gaming (xCloud) native client: browse the cloud catalog and stream
+games with sound, with a controller (Xbox, DualSense, DualShock 4, 8BitDo,
+Switch Pro...), keyboard and mouse.
+
+You need a Microsoft account and a Game Pass plan with cloud gaming
+(free-to-play games like Fortnite stream without it once on your account).
+Unofficial project, not affiliated with, endorsed or sponsored by
+Microsoft or Sony.
+
+
+Running it
+----------
+Extract the zip archive to any folder and run:
+
+ psbox.exe
+
+Optional command-line parameters:
+ --windowed Start in windowed mode
+ --fullscreen Start in fullscreen mode
+ --data-dir <dir> Store user data in custom folder
+
+F11 or Alt+Enter toggles fullscreen; Settings > Display mode remembers it.
+
+Self-test without signing in:
+ psbox.exe --selftest C:\Temp\psbox-selftest
+
+
+Your data
+---------
+Sign-in credentials, settings, caches and log (xcloud.log) are kept in:
+ %LOCALAPPDATA%\psbox\ (or specified by --data-dir)
+Nothing is written to the program folder. Deleting %LOCALAPPDATA%\psbox\
+completely resets the app.
+
+
+Controllers
+-----------
+Standard XInput controllers (Xbox One, Xbox Series, 8BitDo) work out of the box.
+PlayStation DualSense and DualShock 4 controllers are supported via SDL3 USB/Bluetooth HID.