Xbox Cloud Gaming app for PS5 Homebrew
C
fix(stream, ui): eliminate 30fps drop, make touchpad mouse opt-in, add live log tooling
Rafael Abud Ferreirabf77b098377a
diff --git a/.agents/skills/ps5-deploy/SKILL.md b/.agents/skills/ps5-deploy/SKILL.mdnew file mode 100644index 0000000..f86d511--- /dev/null+++ b/.agents/skills/ps5-deploy/SKILL.md@@ -0,0 +1,23 @@+---+name: ps5-deploy+description: Fast and safe packaging, FTP transfer, console hygiene, and foreground launch of xCloud-PS5 on the PS5 console.+---++# PS5 Deploy Skill++Use this skill when you need to deploy the latest build of xCloud-PS5 to the PlayStation 5 console safely and cleanly.++## Execution Procedure++Run the unified developer tool:++```bash+python3 tools/ps5/ps5_dev.py deploy+```++This command automatically:+1. Stops any running instance (`PPSA99810`) via `ps5_console.py kill`.+2. Packages the title folder with active account credentials (`XC_INCLUDE_ACCOUNT=1 bash tools/ps5/package.sh build-ps5`).+3. Sends the updated package to the console over FTP.+4. Ensures console hygiene by purging any lingering `autoplay.txt`.+5. Launches the title in foreground interactive mode for the user.diff --git a/.agents/skills/ps5-live-log/SKILL.md b/.agents/skills/ps5-live-log/SKILL.mdnew file mode 100644index 0000000..a2740f5--- /dev/null+++ b/.agents/skills/ps5-live-log/SKILL.md@@ -0,0 +1,52 @@+---+name: ps5-live-log+description: Stream and monitor real-time live console logs from the PS5 over FTP without restarting the title, with colorized metrics and pattern filtering.+---++# PS5 Live Log Streaming Skill++Use this skill to observe, follow, and analyze `xcloud.log` from the PlayStation 5 in real time over FTP without interrupting or restarting running game streams or UI sessions.++## Quick Usage++### 1. Unified Dev Tool+```bash+# Print last 60 lines with syntax highlighting+python3 tools/ps5/ps5_dev.py log -n 60++# Stream and follow live log in real time (like tail -f)+python3 tools/ps5/ps5_dev.py log -f++# Follow live log and filter only stream metrics+python3 tools/ps5/ps5_dev.py log -f --filter "stream:"++# Follow live log and filter audio metrics or warnings+python3 tools/ps5/ps5_dev.py log -f --filter "audio|WARN|ERR"+```++### 2. Standalone Streamer (`log_stream.py`)+```bash+# Direct execution with custom host/port+python3 tools/ps5/log_stream.py --host 192.168.15.17 --port 2121 -f++# Filter with regex+python3 tools/ps5/log_stream.py -f --filter "rtt \d+ ms"+```++## Key Capabilities & Features++1. **Zero Session Disturbance**:+ - Uses FTP REST offset retrieval (`retrbinary` with `rest=offset`).+ - Does NOT kill, restart, or lock `eboot.bin` or `/data/psbox/xcloud.log`.+ - Transfers only newly appended bytes on each poll.++2. **Automatic Metric Highlighting**:+ - `[I] stream:` lines highlighted in Cyan with bold bitrate (`kbps`), REMB caps, RTT latency (`rtt XX ms`), on-screen latency, and dropped/skipped counts.+ - `[I] audio out:` and `[I] audio in:` lines highlighted in Magenta.+ - `[W]` warnings highlighted in Yellow.+ - `[E]` errors highlighted in Bold Red.+ - `AUTOPLAY` / `AUTOTEST` events highlighted in Bold Green.++3. **Robust Reconnection**:+ - Handles transient FTP connection drops or timeouts automatically.+ - Detects log truncations / app restarts and resets the read offset cleanly.diff --git a/.agents/skills/ps5-stream-test/SKILL.md b/.agents/skills/ps5-stream-test/SKILL.mdnew file mode 100644index 0000000..accd469--- /dev/null+++ b/.agents/skills/ps5-stream-test/SKILL.md@@ -0,0 +1,32 @@+---+name: ps5-stream-test+description: Autonomous PS5 UI and stream test execution, automatic PPM to PNG conversion, visual verification, and network/audio log analysis.+---++# PS5 Stream & UI Autonomous Test Skill++Use this skill to execute automated headless tests on the real PS5 console without requiring manual controller input.++## Execution Procedure++Run the test suite with a specific target:++```bash+# Example 1: UI test (screens, details, settings)+python3 tools/ps5/ps5_dev.py test gamesettingstest --duration 20++# Example 2: Stream game test (e.g. Balatro or Fortnite)+python3 tools/ps5/ps5_dev.py test BALATRO --duration 45++# Example 3: Smoke crash test+python3 tools/ps5/ps5_dev.py test crashtest --duration 30+```++## What this handles automatically:+1. Deploys fresh code and configures `autoplay.txt`.+2. Launches the test remotely on the console.+3. Downloads all captured `.ppm` screenshots to `build-ps5/autotest/`.+4. Automatically converts all `.ppm` files to `.png` with PIL.+5. Deletes `autoplay.txt` immediately (mandatory console hygiene).+6. Downloads `xcloud.log`, parses FPS, bitrate, packet loss, NACKs, dropped frames, decoder timings, and audio underruns.+7. Displays a consolidated report and relaunches the app in interactive mode.diff --git a/.agents/skills/ps5-verify/SKILL.md b/.agents/skills/ps5-verify/SKILL.mdnew file mode 100644index 0000000..a7c3576--- /dev/null+++ b/.agents/skills/ps5-verify/SKILL.md@@ -0,0 +1,22 @@+---+name: ps5-verify+description: Comprehensive multi-platform verification (Desktop SDL3, Desktop No-SDL, PS5, unit tests, selftests, and platform boundaries).+---++# PS5 Multi-Platform Verification Skill++Use this skill before committing code, creating PRs, or deploying to ensure zero regressions across Desktop and PS5 platforms.++## Execution Procedure++Run the multi-platform verification suite:++```bash+python3 tools/ps5/ps5_dev.py verify+```++This verifies sequentially or in parallel:+1. `build-desktop` (SDL3 app, tests, and headless `--selftest`)+2. `build-desktop-nosdl` (headless desktop engine and tests)+3. `build-ps5` (PS5 Vulkan application and `link.sh` eboot.bin staging)+4. `check-platform-boundaries.sh` (ensuring clean platform isolation and no leaky SCE calls)diff --git a/src/app/app_core.cpp b/src/app/app_core.cppindex 6961ff2..1918ead 100644--- a/src/app/app_core.cpp+++ b/src/app/app_core.cpp@@ -114,6 +114,7 @@ bool saveSettings(const ui::SettingsChoice& choice) {if (input::padMapValid(choice.padMap)) g_settings.padMap = choice.padMap; // the screen only lets a complete one outg_settings.gyroMode = choice.gyroMode;g_settings.gyroLevel = choice.gyroLevel;+ g_settings.touchpadMouse = choice.touchpadMouse;fullscreenChanged = g_settings.desktopFullscreen != choice.fullscreen;g_settings.desktopFullscreen = choice.fullscreen;g_settings.save(settingsPath()); // warns itself@@ -316,6 +317,7 @@ bool coreStartup() {choice.gyroMode = g_settings.gyroMode;choice.gyroLevel = g_settings.gyroLevel;choice.fullscreen = g_settings.desktopFullscreen;+ choice.touchpadMouse = g_settings.touchpadMouse;g_ui->setAllow1440(allow1440Locked());g_ui->setUpdateState(XC_APP_VERSION, {}, false); // Settings shows this version before any checkg_ui->setSettings(choice);diff --git a/src/app/settings.cpp b/src/app/settings.cppindex d5bec06..db5afcb 100644--- a/src/app/settings.cpp+++ b/src/app/settings.cpp@@ -90,6 +90,7 @@ bool Settings::load(const std::string& path) {keyboardPlayer = static_cast<int>(std::clamp<int64_t>((*j)["keyboardPlayer"].asInt(keyboardPlayer), 0, 3));gyroMode = static_cast<int>(std::clamp<int64_t>((*j)["gyroMode"].asInt(gyroMode), 0, 2));gyroLevel = static_cast<int>(std::clamp<int64_t>((*j)["gyroLevel"].asInt(gyroLevel), 1, 10));+ 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));skippedUpdate = (*j)["skippedUpdate"].str();@@ -128,6 +129,7 @@ bool Settings::load(const std::string& path) {p.padMap = readPadMapOr(obj["padMap"], padMap, id.c_str());p.gyroMode = static_cast<int>(std::clamp<int64_t>(obj["gyroMode"].asInt(gyroMode), 0, 2));p.gyroLevel = static_cast<int>(std::clamp<int64_t>(obj["gyroLevel"].asInt(gyroLevel), 1, 10));+ p.touchpadMouse = obj["touchpadMouse"].asBool(touchpadMouse);perGame[id] = p;}return true;@@ -156,6 +158,7 @@ GameProfile Settings::defaultProfile() const {p.padMap = padMap;p.gyroMode = gyroMode;p.gyroLevel = gyroLevel;+ p.touchpadMouse = touchpadMouse;return p;}@@ -218,6 +221,7 @@ bool Settings::save(const std::string& path) const {v.set("keyboardPlayer", keyboardPlayer);v.set("gyroMode", gyroMode);v.set("gyroLevel", gyroLevel);+ v.set("touchpadMouse", touchpadMouse);v.set("micGain", micGain);v.set("audioRoute", audioRoute);v.set("skippedUpdate", skippedUpdate);@@ -244,6 +248,7 @@ bool Settings::save(const std::string& path) const {obj.set("padMap", input::padMapJson(p.padMap));obj.set("gyroMode", p.gyroMode);obj.set("gyroLevel", p.gyroLevel);+ obj.set("touchpadMouse", p.touchpadMouse);pg.set(id, obj);}v.set("perGame", pg);diff --git a/src/app/settings.h b/src/app/settings.hindex 6031453..5f033d7 100644--- a/src/app/settings.h+++ b/src/app/settings.h@@ -35,6 +35,8 @@ struct GameProfile {// Gyro aiming: 0 off, 1 always, 2 while L2 is held; intensity 1..10int gyroMode = 0;int gyroLevel = 5;+ // Touchpad as mouse in games with native MKB support (OFF by default)+ bool touchpadMouse = false;};// Key to identify a game profile: productId first, else titleId.@@ -91,6 +93,7 @@ struct Settings {int keyboardPlayer = 0; // the player a USB keyboard and mouse play as (0..3; keys 1-4): 0 native with player 1, else that player's controllerint gyroMode = 0; // gyro aiming (input/gyro.h): 0 off, 1 always, 2 while L2 is heldint gyroLevel = 5; // its intensity, 1..10+ bool touchpadMouse = false; // touchpad as mouse in games with native MKB supportint micGain = 1; // 0: 50%, 1: 100%, 2: 150%int audioRoute = 0; // 0: TV/HDMI (Main), 1: DualSense Speaker / Headset (Pad)// The release the user said "Not now" to: not offered again on start.diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cppindex 1edf90d..4b4b371 100644--- a/src/app/stream_player.cpp+++ b/src/app/stream_player.cpp@@ -295,8 +295,8 @@ struct StreamPlayer::Impl {// When a burst of packets arrives after network jitter/retransmission,// fast-forward decode without drawing to drain the stale backlog in a few// milliseconds and present the newest live frame immediately.- // Under normal playback (backlog <= 3), every frame is drawn smoothly.- if (backlog >= 4 && skippedInRow < 15) {+ // Under normal playback (backlog <= 7), every frame is drawn smoothly.+ if (backlog >= 8 && skippedInRow < 15) {++skippedInRow;++droppedFrames;continue;diff --git a/src/app/stream_screen.cpp b/src/app/stream_screen.cppindex 2f94d3b..24eb408 100644--- a/src/app/stream_screen.cpp+++ b/src/app/stream_screen.cpp@@ -122,6 +122,7 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, bbool hasCustom = false;GameProfile prof = g_settings.profileForGame(tile.productId, tile.titleId, &hasCustom);hasCustomProfile_ = hasCustom;+ touchpadMouse_ = prof.touchpadMouse;streamResolution_ = prof.resolution;showStats_ = g_settings.streamStats;@@ -356,7 +357,7 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b}input::KbmInput touchKbm;bool touchDrag = false;- if (mouseKeyboard_ && !menu_.isOpen() && g_keyboardFor.empty() && !menuCombo) {+ if (mouseKeyboard_ && touchpadMouse_ && !menu_.isOpen() && g_keyboardFor.empty() && !menuCombo) {touchDrag = input::touchpadAsMouse(pad, platform::nowMs(), touchMouse_, touchKbm);} else {if (touchMouse_.prevButtons != 0) touchKbm.moved = true; // let go of any held touchpad mouse button@@ -388,7 +389,7 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b// Swiping up or right on the touchpad is the Xbox button (once// per swipe; the games never see the touchpad's touches). In MKB// games the touchpad moves the mouse while the menu is closed.- bool swipeOn = !mouseKeyboard_ || menu_.isOpen();+ bool swipeOn = (!mouseKeyboard_ || !touchpadMouse_) || menu_.isOpen();if (swipeOn && pad.touching && !pad.btnTouchpad && g_keyboardFor.empty()) {if (!swipe_.active) swipe_ = {true, false, pad.touchX, pad.touchY};float dx = pad.touchX - swipe_.x, dy = swipe_.y - pad.touchY; // dy > 0: updiff --git a/src/app/stream_screen.h b/src/app/stream_screen.hindex 5bd2074..7d24454 100644--- a/src/app/stream_screen.h+++ b/src/app/stream_screen.h@@ -81,7 +81,8 @@ private:input::PadMap padMap_ = input::defaultPadMap(); // this game's controller buttons, toward the game onlyint gyroMode_ = 0, gyroLevel_ = 5; // gyro aiming (input/gyro.h), this game'sbool highRefresh_ = false; // 120 Hz turned on for this stream- bool mouseKeyboard_ = false; // the game takes native mouse and keyboard (touchpad acts as a mouse)+ bool mouseKeyboard_ = false; // the game takes native mouse and keyboard+ bool touchpadMouse_ = false; // touchpad acts as a mouse (only when enabled in game's profile)input::KbmInput kbm_;int kbSlotAttached_ = -1; // the keyboard's slot as a controller, announcedinput::MouseStick mouseStick_;diff --git a/src/app/worker.cpp b/src/app/worker.cppindex 8ca27c9..e96e5b9 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -152,7 +152,9 @@ std::string stream(xcloud::GssvClient& gssv) {}}if (platform::nowMs() >= nextTick) {- nextTick += 1000;+ uint64_t tickNow = platform::nowMs();+ double dt = lastTickAt ? (tickNow - lastTickAt) / 1000.0 : 1.0;+ nextTick = tickNow + 1000;player.tick();auto st = player.stats();XC_LOGI("stream: %llu frames, %llu decoded, %llu skipped, %llu failed, %llu resets, %llu kf req, "@@ -180,7 +182,11 @@ std::string stream(xcloud::GssvClient& gssv) {ui::StreamInfo info;info.region = ui::prettyRegion(gssv.region().name);info.rttMs = st.rttMs;- info.fps = static_cast<double>(st.decodedFrames - last.decodedFrames - (st.droppedFrames - last.droppedFrames));+ info.fps = dt > 0.05+ ? std::max(0.0, static_cast<double>(st.decodedFrames - last.decodedFrames -+ (st.droppedFrames - last.droppedFrames)) /+ dt)+ : 60.0;info.mbps = st.rtpKbps / 1000.0;uint64_t lost = st.rtpLost - last.rtpLost, got = st.rtpPackets - last.rtpPackets;info.lossPct = got + lost ? 100.0 * lost / (got + lost) : 0;diff --git a/src/display/gpu.cpp b/src/display/gpu.cppindex ef576ba..ba38ce2 100644--- a/src/display/gpu.cpp+++ b/src/display/gpu.cpp@@ -170,7 +170,7 @@ std::atomic<int> g_upscaler{0}; // 0 FSR (EASU), 1 Anime4Kstd::atomic<bool> g_restore{false}; // Anime4K Restore before the upscaleuint32_t g_frame = 0;uint32_t g_swapImages = 2;-bool g_noPresentWait = false;+bool g_noPresentWait = true;PFN_vkWaitForPresentKHR vkWaitForPresentKHR = nullptr;// The last frame known on the screen: its present id and when (us).std::atomic<uint64_t> g_shownId{0}, g_shownAtUs{0};diff --git a/src/stream/rtcp_reporter.cpp b/src/stream/rtcp_reporter.cppindex 55e9cf5..484b546 100644--- a/src/stream/rtcp_reporter.cpp+++ b/src/stream/rtcp_reporter.cpp@@ -11,7 +11,7 @@ namespace xc::stream {namespace {constexpr uint64_t kReportIntervalUs = 500000;-constexpr uint32_t kMinBitrate = 1500000;+constexpr uint32_t kMinBitrate = 6000000;uint64_t nowUs() {return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(@@ -135,7 +135,7 @@ void RtcpReporter::report(uint64_t now, const rtc::message_callback& send) {if (loss > 0.10)est = std::max<uint32_t>(kMinBitrate, static_cast<uint32_t>(rate * (1.0 - 0.5 * loss)));else if (loss < 0.02)- est = std::min<uint32_t>(maxBitrate_, std::max<uint32_t>(est, kMinBitrate) + maxBitrate_ / 20);+ est = std::min<uint32_t>(maxBitrate_, std::max<uint32_t>(est, kMinBitrate) + maxBitrate_ / 10);estimate_ = est;uint8_t exp = 0;diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cppindex b5aa65d..eb51dc1 100644--- a/src/stream/stream_session.cpp+++ b/src/stream/stream_session.cpp@@ -20,6 +20,7 @@#include <condition_variable>#include <cstdio>#include <mutex>+#include <thread>#include <vector>namespace xc::stream {@@ -104,6 +105,7 @@ struct StreamSession::Impl {std::atomic<bool> closedNotified{false};std::atomic<uint32_t> inputSequence{1};uint64_t lastKeepaliveMs = 0;+ std::atomic<bool> keepaliveInFlight{false};uint64_t lastKeyframeMs = 0;VideoReceiveStats videoStats;std::shared_ptr<RtcpReporter> videoReporter;@@ -647,8 +649,13 @@ struct StreamSession::Impl {uint64_t now = platform::nowMs();if (now - lastKeepaliveMs >= 30000) {lastKeepaliveMs = now;- std::string err;- if (!gssv.keepalive(err)) XC_LOGW("%s", err.c_str());+ if (!keepaliveInFlight.exchange(true)) {+ std::thread([this] {+ std::string err;+ if (!gssv.keepalive(err)) XC_LOGW("%s", err.c_str());+ keepaliveInFlight = false;+ }).detach();+ }}if (opt.keyframeIntervalSec > 0 && now - lastKeyframeMs >= static_cast<uint64_t>(opt.keyframeIntervalSec) * 1000u) {lastKeyframeMs = now;diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cppindex c32fa83..48d1b66 100644--- a/src/ui/app_ui.cpp+++ b/src/ui/app_ui.cpp@@ -66,9 +66,9 @@ constexpr bool kSettingsGroupStart[kSettingRows] = {false, false, true, false, f// The game settings' rows on screen (ids: 0 profile, 1 upscaler, 2// sharpness, 3 block smoothing, 4 resolution, 5 dead zone, 6 triggers, 7// confirm, 8 120 Hz, 9 keyboard keys, 10 back to the default, 11 controller-// buttons, 12 gyro aiming).-constexpr int kGameRowOrder[13] = {0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10};-constexpr bool kGameGroupStart[13] = {false, true, false, true, false, false, true, false, false, false, false, false, true};+// buttons, 12 gyro aiming, 13 touchpad as mouse).+constexpr int kGameRowOrder[14] = {0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 13, 9, 10};+constexpr bool kGameGroupStart[14] = {false, true, false, true, false, false, true, false, false, false, false, false, false, true};// The keyboard keys' screen: two columns of inputs, then "Reset to default".constexpr int kKeysPerColumn = input::kKeyActions / 2;// Updates on a desktop: the newest release's page (the app doesn't install it there).@@ -250,7 +250,7 @@ std::vector<SettingsRowPos> visibleSettingsRows(const UiCaps& caps) {});}-std::vector<SettingsRowPos> visibleGameSettingsRows(const UiCaps& caps, bool custom) {+std::vector<SettingsRowPos> visibleGameSettingsRows(const UiCaps& caps, bool custom, bool mouseSupported) {return filterRows(kGameRowOrder, kGameGroupStart, [&](int row) {switch (row) {case 1: return caps.upscalers;@@ -260,6 +260,7 @@ std::vector<SettingsRowPos> visibleGameSettingsRows(const UiCaps& caps, bool cuscase 8: return caps.highRefresh;case 10: return custom;case 12: return caps.gyro;+ case 13: return caps.touchpad && mouseSupported;default: return true;}});@@ -1370,6 +1371,7 @@ void AppUi::setPerGameSettings(const std::map<std::string, app::GameProfile>& pevoid AppUi::openGameSettings() {gameSettingsOpen_ = true;gameSettingsRow_ = 0;+ activeGameMouseSupported_ = detail_.mouseKeyboard;std::string key = app::gameProfileKey(detail_.productId, detail_.titleId);auto it = perGameSettings_.find(key);if (it != perGameSettings_.end()) {@@ -1393,6 +1395,7 @@ void AppUi::openGameSettings() {activeGameProfile_.padMap = settings_.padMap;activeGameProfile_.gyroMode = gyroMode_;activeGameProfile_.gyroLevel = gyroLevel_;+ activeGameProfile_.touchpadMouse = settings_.touchpadMouse;}}@@ -1643,7 +1646,7 @@ void AppUi::setCaps(const UiCaps& caps) {tester_ = Tester::None;}testerRow_ = std::min(testerRow_, triggerTesterRows() - 1);- int gameRows = static_cast<int>(visibleGameSettingsRows(caps_, activeGameHasCustom_).size());+ int gameRows = static_cast<int>(visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_).size());gameSettingsRow_ = std::min(gameSettingsRow_, gameRows - 1);}@@ -2211,7 +2214,7 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {return;}// The rows on screen (gameSettingsRow_ is a position among them).- const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_);+ const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_, activeGameMouseSupported_);const int rowCount = static_cast<int>(rows.size());if (in.up) {gameSettingsRow_ = (gameSettingsRow_ + rowCount - 1) % rowCount;@@ -2283,6 +2286,11 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {activeGameHasCustom_ = true;dirty_ = true;break;+ case 13: // Touchpad as mouse (in games with mouse support)+ activeGameProfile_.touchpadMouse = !activeGameProfile_.touchpadMouse;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;default: break;}}@@ -2355,6 +2363,11 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {activeGameHasCustom_ = true;dirty_ = true;break;+ case 13:+ activeGameProfile_.touchpadMouse = !activeGameProfile_.touchpadMouse;+ activeGameHasCustom_ = true;+ dirty_ = true;+ break;case 9: // Keyboard keys: their own screen, on this game'sopenTester(Tester::Keys);settings_.keyMap = activeGameProfile_.keyMap;@@ -2380,6 +2393,7 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {activeGameProfile_.highRefresh = settings_.highRefresh;activeGameProfile_.gyroMode = gyroMode_;activeGameProfile_.gyroLevel = gyroLevel_;+ activeGameProfile_.touchpadMouse = settings_.touchpadMouse;gameSettingsRow_ = 0;dirty_ = true;break;@@ -4359,12 +4373,12 @@ void AppUi::drawGameSettings(Canvas& c) {title = title + " \xE2\x80\xA2 " + cut + "...";}}- constexpr int kModalW = 1140, kModalH = 930;- constexpr int kRowH = 50, kGap = 6, kGroupGap = 12;+ constexpr int kModalW = 1140, kModalH = 920;+ constexpr int kRowH = 46, kGap = 5, kGroupGap = 10;// The rows caps_ allows; the panel loses the height of those it hides// (the same as ever with all of them, "Reset to default" or not).- const auto rows = visibleGameSettingsRows(caps_, activeGameHasCustom_);- const auto most = visibleGameSettingsRows(caps_, true), all = visibleGameSettingsRows(UiCaps{}, true);+ 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; }));};@@ -4455,6 +4469,10 @@ void AppUi::drawGameSettings(Canvas& c) {: activeGameProfile_.gyroMode == 2 ? Str::GyroAiming: Str::Off);break;+ case 13:+ label = tr(Str::TouchpadMouse);+ value = tr(activeGameProfile_.touchpadMouse ? Str::Activated : Str::Deactivated);+ break;default: break;}diff --git a/src/ui/app_ui.h b/src/ui/app_ui.hindex e14b2d0..e7e286f 100644--- a/src/ui/app_ui.h+++ b/src/ui/app_ui.h@@ -129,6 +129,7 @@ struct SettingsChoice {int gyroMode = 0; // gyro aiming (input/gyro.h): 0 off, 1 always, 2 while L2 is heldint gyroLevel = 5; // intensity, 1..10bool fullscreen = true; // a desktop's window fullscreen (UiCaps::desktopWindow; F11 switches it too)+ bool touchpadMouse = false;};// What this system and its pads can do, filled in by the app from the pads'@@ -165,8 +166,9 @@ struct SettingsRowPos {// hidden (their setting stays as it is in settings.json).std::vector<SettingsRowPos> visibleSettingsRows(const UiCaps& caps);// The same for a game's settings (row ids as AppUi draws them); "Reset to-// default" only with a profile of its own (`custom`).-std::vector<SettingsRowPos> visibleGameSettingsRows(const UiCaps& caps, bool custom);+// default" only with a profile of its own (`custom`); `mouseSupported` shows+// the touchpad mouse option on pads with a touchpad.+std::vector<SettingsRowPos> visibleGameSettingsRows(const UiCaps& caps, bool custom, bool mouseSupported = false);// The largest stick dead zone Settings offers, in percent of the travel.constexpr int kMaxDeadzone = 30;@@ -548,6 +550,7 @@ private:SettingsChoice settings_;bool displayModeChanged_ = false; // the Display mode row changed: handle() sends the settingsbool circleConfirms_ = false;+ bool activeGameMouseSupported_ = false;PadSlots pads_{};std::map<std::string, Color> accents_; // tile art url -> its colourstd::vector<std::string> regions_;diff --git a/src/ui/strings.cpp b/src/ui/strings.cppindex 4ec8785..7d83125 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -306,6 +306,7 @@ constexpr Column kEnglish = {"My plan", // PlanMine"All plans", // PlanAll"Included with Game Pass %s", // IncludedWithPlan+ "Touchpad as mouse", // TouchpadMouse};constexpr Column kPortugueseBR = {@@ -582,6 +583,7 @@ constexpr Column kPortugueseBR = {"Meu plano", // PlanMine"Todos os planos", // PlanAll"Incluído no Game Pass %s", // IncludedWithPlan+ "Touchpad como mouse", // TouchpadMouse};constexpr Column kSpanish = {@@ -858,6 +860,7 @@ constexpr Column kSpanish = {"Mi plan", // PlanMine"Todos los planes", // PlanAll"Incluido con Game Pass %s", // IncludedWithPlan+ "Panel táctil como ratón", // TouchpadMouse};constexpr Column kFrench = {@@ -1134,6 +1137,7 @@ constexpr Column kFrench = {"Mon forfait", // PlanMine"Tous les forfaits", // PlanAll"Inclus avec Game Pass %s", // IncludedWithPlan+ "Pavé tactile comme souris", // TouchpadMouse};constexpr Column kGerman = {@@ -1410,6 +1414,7 @@ constexpr Column kGerman = {"Mein Abo", // PlanMine"Alle Abos", // PlanAll"In Game Pass %s enthalten", // IncludedWithPlan+ "Touchpad als Maus", // TouchpadMouse};constexpr Column kItalian = {@@ -1686,6 +1691,7 @@ constexpr Column kItalian = {"Il mio piano", // PlanMine"Tutti i piani", // PlanAll"Incluso con Game Pass %s", // IncludedWithPlan+ "Touchpad come mouse", // TouchpadMouse};constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,diff --git a/src/ui/strings.h b/src/ui/strings.hindex e46e8b1..2503546 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -283,6 +283,7 @@ enum class Str {PlanMine, // ... what the account's plan playsPlanAll, // ... every Game Pass planIncludedWithPlan, // game page: "%s" = "Ultimate" / "Premium" / "Essential"+ TouchpadMouse, // per-game setting: use touchpad as mouse in games with mouse supportCount};diff --git a/tests/test_main.cpp b/tests/test_main.cppindex b855247..7052b4a 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -351,6 +351,7 @@ static void testPerGameSettings() {CHECK(def.deadzoneLeft == 12 && def.deadzoneRight == 18 && def.triggerStrength == 3);CHECK(!def.circleConfirms);CHECK(!def.highRefresh); // off unless chosen+ CHECK(!def.touchpadMouse);// Unknown games return default profile with hasCustom = false.bool hasCustom = true;@@ -368,18 +369,19 @@ static void testPerGameSettings() {p1.triggerStrength = 1;p1.circleConfirms = true;p1.highRefresh = true;+ p1.touchpadMouse = true;s.perGame["GAME1"] = p1;// Now GAME1 returns custom profile, while GAME2 still returns defaults.auto prof1Custom = s.profileForGame("GAME1", "", &hasCustom);CHECK(hasCustom);CHECK(prof1Custom.sharpness == 3 && prof1Custom.upscaler == 3 && prof1Custom.circleConfirms);- CHECK(prof1Custom.deadzoneLeft == 5 && prof1Custom.triggerStrength == 1);+ CHECK(prof1Custom.deadzoneLeft == 5 && prof1Custom.triggerStrength == 1 && prof1Custom.touchpadMouse);hasCustom = true;auto prof2 = s.profileForGame("GAME2", "", &hasCustom);CHECK(!hasCustom);- CHECK(prof2.sharpness == 1 && !prof2.circleConfirms);+ CHECK(prof2.sharpness == 1 && !prof2.circleConfirms && !prof2.touchpadMouse);// Title ID fallback when productId is empty.s.perGame["CONSOLE_SERVER_1"] = p1;@@ -398,7 +400,7 @@ static void testPerGameSettings() {auto loadedP1 = reloaded.profileForGame("GAME1", "", &hasCustom);CHECK(hasCustom);CHECK(loadedP1.sharpness == 3 && loadedP1.upscaler == 3 && loadedP1.circleConfirms);- CHECK(loadedP1.highRefresh);+ CHECK(loadedP1.highRefresh && loadedP1.touchpadMouse);CHECK(loadedP1.deadzoneLeft == 5 && loadedP1.deadzoneRight == 8 && loadedP1.triggerStrength == 1);// Remove game profile restores default.@@ -1440,10 +1442,17 @@ static void testVisibleSettingsRows() {auto x = ids(ui::visibleSettingsRows(xbox));CHECK(std::find(x.begin(), x.end(), 4) != x.end() && std::find(x.begin(), x.end(), 6) == x.end());// A game's settings.+ CHECK((ids(ui::visibleGameSettingsRows(ps5, true, false)) == std::vector<int>{0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));+ CHECK((ids(ui::visibleGameSettingsRows(ps5, true, true)) == std::vector<int>{0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 13, 9, 10}));+ CHECK((groups(ui::visibleGameSettingsRows(ps5, true, true)) ==+ std::vector<bool>{false, true, false, true, false, false, true, false, false, false, false, false, false, true}));CHECK((ids(ui::visibleGameSettingsRows(ps5, true)) == std::vector<int>{0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));CHECK((groups(ui::visibleGameSettingsRows(ps5, true)) ==std::vector<bool>{false, true, false, true, false, false, true, false, false, false, false, false, true}));CHECK((ids(ui::visibleGameSettingsRows(ps5, false)) == std::vector<int>{0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 9}));+ ui::UiCaps noTouch = ps5;+ noTouch.touchpad = false;+ CHECK((ids(ui::visibleGameSettingsRows(noTouch, true, true)) == std::vector<int>{0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));auto game = ui::visibleGameSettingsRows(pc, false);CHECK((ids(game) == std::vector<int>{0, 4, 5, 7, 11, 9}));CHECK((groups(game) == std::vector<bool>{false, true, true, false, false, false}));diff --git a/tools/ps5/log_stream.py b/tools/ps5/log_stream.pynew file mode 100755index 0000000..1a95f9c--- /dev/null+++ b/tools/ps5/log_stream.py@@ -0,0 +1,244 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-3.0-or-later+# Copyright (C) 2026 RafaelNGP+"""+Real-time live log streamer for xCloud-PS5 over FTP.+Monitors /data/psbox/xcloud.log on the PlayStation 5 console without killing+or disturbing active stream sessions.+"""++import argparse+import io+import os+import re+import sys+import time+from ftplib import FTP, error_perm, error_reply++DEFAULT_HOST = os.environ.get("PS5_HOST", "192.168.15.17")+DEFAULT_PORT = int(os.environ.get("FTP_PORT", "2121"))++# ANSI Color Codes+RESET = "\033[0m"+BOLD = "\033[1m"+DIM = "\033[2m"+RED = "\033[31m"+GREEN = "\033[32m"+YELLOW = "\033[33m"+BLUE = "\033[34m"+MAGENTA = "\033[35m"+CYAN = "\033[36m"+WHITE = "\033[37m"+B_RED = "\033[1;31m"+B_GREEN = "\033[1;32m"+B_YELLOW = "\033[1;33m"+B_CYAN = "\033[1;36m"+B_MAGENTA = "\033[1;35m"+++def colorize_log_line(line: str, use_color: bool = True) -> str:+ if not use_color:+ return line++ # Error lines+ if " [E] " in line or line.startswith("[E] ") or "ERROR" in line or "error:" in line:+ return f"{B_RED}{line}{RESET}"++ # Warning lines+ if " [W] " in line or line.startswith("[W] ") or "WARN" in line:+ return f"{B_YELLOW}{line}{RESET}"++ # Autoplay / Autotest lines+ if "AUTOPLAY" in line or "AUTOTEST" in line:+ return f"{B_GREEN}{line}{RESET}"++ # Stream metrics+ if " [I] stream:" in line:+ # Highlight key metrics inside stream line+ # e.g.: 10788 kbps (remb 40000); 0 rumble; decode 5.5/18.1 ms, draw 11.2/11.8 ms, 0 late; rtt 17 ms; 1920x1080; on screen 47.3/57.2 ms+ styled = line+ # Tag+ styled = styled.replace(" [I] stream:", f" {B_CYAN}[I] stream:{RESET}")+ # Bitrate+ styled = re.sub(r"(\b\d+\s+kbps\b)", rf"{B_GREEN}\1{RESET}", styled)+ # REMB+ styled = re.sub(r"(\(remb\s+\d+\))", rf"{CYAN}\1{RESET}", styled)+ # Latency / RTT+ styled = re.sub(r"(\brtt\s+\d+\s+ms\b)", rf"{B_YELLOW}\1{RESET}", styled)+ styled = re.sub(r"(\bon screen\s+[\d\./]+\s+ms\b)", rf"{B_YELLOW}\1{RESET}", styled)+ # Drops / Skips / Nacks+ styled = re.sub(r"(\b\d+\s+skipped\b)", rf"{YELLOW}\1{RESET}", styled)+ styled = re.sub(r"(\b\d+\s+dropped\b)", rf"{YELLOW}\1{RESET}", styled)+ styled = re.sub(r"(\b\d+\s+nacks\b)", rf"{YELLOW}\1{RESET}", styled)+ return styled++ # Audio metrics+ if " [I] audio" in line:+ styled = line.replace(" [I] audio out:", f" {B_MAGENTA}[I] audio out:{RESET}")+ styled = styled.replace(" [I] audio in:", f" {B_MAGENTA}[I] audio in:{RESET}")+ return styled++ # Standard info+ if " [I] " in line:+ return f"{WHITE}{line}{RESET}"++ return line+++def connect_ftp(host: str, port: int, timeout: int = 5) -> FTP:+ ftp = FTP()+ ftp.connect(host, port, timeout=timeout)+ ftp.login()+ ftp.cwd("/data/psbox")+ return ftp+++def stream_logs(+ host: str = DEFAULT_HOST,+ port: int = DEFAULT_PORT,+ lines: int = 50,+ follow: bool = False,+ filter_pattern: str | None = None,+ use_color: bool = True,+ poll_interval: float = 0.5,+):+ filter_re = re.compile(filter_pattern, re.IGNORECASE) if filter_pattern else None++ try:+ ftp = connect_ftp(host, port)+ except Exception as e:+ print(f"{B_RED}Failed to connect to PS5 FTP ({host}:{port}): {e}{RESET}", file=sys.stderr)+ return 1++ try:+ try:+ file_size = ftp.size("xcloud.log")+ except Exception:+ file_size = None++ if file_size is None or file_size == 0:+ print(f"{YELLOW}xcloud.log is empty or not yet created on PS5.{RESET}")+ offset = 0+ else:+ # Read last ~64KB or full file to get initial lines+ fetch_bytes = min(file_size, max(65536, lines * 400))+ offset_init = file_size - fetch_bytes+ bio = io.BytesIO()+ ftp.retrbinary("RETR xcloud.log", bio.write, rest=offset_init)+ initial_text = bio.getvalue().decode("utf-8", errors="replace")+ initial_lines = initial_text.splitlines()++ # If we started at a nonzero offset, discard first partial line+ if offset_init > 0 and len(initial_lines) > 1:+ initial_lines = initial_lines[1:]++ display_lines = initial_lines[-lines:] if lines > 0 else initial_lines+ for line in display_lines:+ if filter_re and not filter_re.search(line):+ continue+ print(colorize_log_line(line, use_color))+ sys.stdout.flush()++ offset = file_size++ if not follow:+ ftp.quit()+ return 0++ # Follow mode loop+ remainder = ""+ while True:+ time.sleep(poll_interval)+ try:+ try:+ cur_size = ftp.size("xcloud.log")+ except Exception:+ # Reconnect on drop+ try:+ ftp.close()+ except Exception:+ pass+ ftp = connect_ftp(host, port)+ cur_size = ftp.size("xcloud.log")++ if cur_size is None:+ continue++ if cur_size < offset:+ # Log was truncated/restarted+ if use_color:+ print(f"\n{B_YELLOW}--- Log rotated or restarted ---{RESET}\n")+ else:+ print("\n--- Log rotated or restarted ---\n")+ offset = 0+ remainder = ""++ if cur_size > offset:+ bio = io.BytesIO()+ ftp.retrbinary("RETR xcloud.log", bio.write, rest=offset)+ offset = cur_size+ chunk = remainder + bio.getvalue().decode("utf-8", errors="replace")+ if "\n" in chunk:+ parts = chunk.split("\n")+ remainder = parts[-1]+ for line in parts[:-1]:+ line = line.rstrip("\r")+ if filter_re and not filter_re.search(line):+ continue+ print(colorize_log_line(line, use_color))+ sys.stdout.flush()+ else:+ remainder = chunk+ except KeyboardInterrupt:+ break+ except Exception as e:+ # Silently retry on transient FTP connection reset+ time.sleep(1)+ try:+ ftp.close()+ except Exception:+ pass+ try:+ ftp = connect_ftp(host, port)+ except Exception:+ pass++ except KeyboardInterrupt:+ pass+ finally:+ try:+ ftp.quit()+ except Exception:+ pass++ return 0+++def main():+ parser = argparse.ArgumentParser(+ description="Stream live xCloud-PS5 logs in real time from PS5 over FTP."+ )+ parser.add_argument("--host", default=DEFAULT_HOST, help="PS5 IP (default: $PS5_HOST or 192.168.15.17)")+ parser.add_argument("--port", type=int, default=DEFAULT_PORT, help="FTP Port (default: $FTP_PORT or 2121)")+ parser.add_argument("-n", "--lines", type=int, default=50, help="Initial number of lines to display (default: 50)")+ parser.add_argument("-f", "--follow", "--tail", action="store_true", dest="follow", help="Follow new log lines in real time")+ parser.add_argument("--filter", dest="filter_pattern", default=None, help="Regex/substring filter for log lines")+ parser.add_argument("--no-color", action="store_true", help="Disable colored output")+ parser.add_argument("--poll-interval", type=float, default=0.5, help="Polling interval in seconds (default: 0.5)")++ args = parser.parse_args()+ use_color = sys.stdout.isatty() and not args.no_color+ rc = stream_logs(+ host=args.host,+ port=args.port,+ lines=args.lines,+ follow=args.follow,+ filter_pattern=args.filter_pattern,+ use_color=use_color,+ poll_interval=args.poll_interval,+ )+ sys.exit(rc)+++if __name__ == "__main__":+ main()diff --git a/tools/ps5/ps5_dev.py b/tools/ps5/ps5_dev.pyindex 591df30..3e906cf 100755--- a/tools/ps5/ps5_dev.py+++ b/tools/ps5/ps5_dev.py@@ -157,13 +157,15 @@ def cmd_deploy(args):def convert_ppm_to_png(ppm_path: Path):+ if not ppm_path.exists() or ppm_path.stat().st_size == 0:+ return Nonetry:from PIL import Imagepng_path = ppm_path.with_suffix(".png")with Image.open(ppm_path) as img:img.save(png_path, "PNG")return png_path- except ImportError:+ except Exception:return None@@ -248,12 +250,15 @@ def cmd_test(args):ftp = get_ftp(host, port)ftp.cwd("/data/psbox")for name in ppm_names + ["xcloud.log"]:+ target_path = out_dir / nametry:- target_path = out_dir / namewith open(target_path, "wb") as f_out:ftp.retrbinary(f"RETR {name}", f_out.write)+ if target_path.exists() and target_path.stat().st_size == 0:+ target_path.unlink()except (error_perm, error_reply):- pass+ if target_path.exists() and target_path.stat().st_size == 0:+ target_path.unlink()ftp.quit()# 7. Convert PPM to PNG@@ -306,18 +311,19 @@ def cmd_test(args):def cmd_log(args):+ sys.path.insert(0, str(Path(__file__).resolve().parent))+ from log_stream import stream_logshost = args.host or DEFAULT_HOSTport = args.port or DEFAULT_PORT- ftp = get_ftp(host, port)- ftp.cwd("/data/psbox")- bio = io.BytesIO()- ftp.retrbinary("RETR xcloud.log", bio.write)- ftp.quit()- lines = bio.getvalue().decode("utf-8", errors="replace").splitlines()- n = args.lines or 50- for line in lines[-n:]:- print(line)- return 0+ use_color = sys.stdout.isatty() and not getattr(args, "no_color", False)+ return stream_logs(+ host=host,+ port=port,+ lines=args.lines,+ follow=args.follow,+ filter_pattern=args.filter_pattern,+ use_color=use_color,+ )def main():@@ -341,8 +347,11 @@ def main():test_p.add_argument("--no-interactive", dest="interactive", action="store_false", help="Leave app closed after test")# log- log_p = subparsers.add_parser("log", help="Fetch and print tail of console log")+ log_p = subparsers.add_parser("log", help="Fetch and stream console log in real time")log_p.add_argument("--lines", "-n", type=int, default=60, help="Number of lines to display")+ log_p.add_argument("-f", "--follow", "--tail", action="store_true", dest="follow", help="Follow new log lines in real time")+ log_p.add_argument("--filter", dest="filter_pattern", default=None, help="Regex/substring filter for log lines")+ log_p.add_argument("--no-color", action="store_true", help="Disable colored output")args = parser.parse_args()