Xbox Cloud Gaming app for PS5 Homebrew
C
App core shared by every platform: coreStartup / coreFrame / coreShutdown, PS5-only steps behind shell::, psbox-headless
Rafael Abud Ferreira3ebe85df28ab
diff --git a/CMakeLists.txt b/CMakeLists.txtindex f8a1e58..17727a3 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -97,17 +97,29 @@ target_compile_definitions(xcloud_ui PUBLIC XC_APP_VERSION="${PROJECT_VERSION}")target_include_directories(xcloud_ui PUBLIC extern/stb extern/qrcodegen)target_link_libraries(xcloud_ui PUBLIC xcloud_core)+# --- The app: start-up, main loop, worker thread, streaming --------------------+# The same objects in every front end, each linking them with its platform's+# backends and shell (docs/multiplatform.md).+add_library(xcloud_appcore OBJECT+ src/app/app_state.cpp+ src/app/app_core.cpp+ src/app/worker.cpp+ src/app/stream_screen.cpp+ src/app/price_loop.cpp+ src/app/autoplay.cpp+ src/app/stream_player.cpp+)+target_link_libraries(xcloud_appcore PUBLIC xcloud_stream xcloud_media xcloud_ui)+if(XCLOUD_PS5)target_sources(xcloud_core PRIVATE src/platform/ps5/platform_ps5.cpp src/platform/ps5/libc_compat.c src/platform/ps5/net_probe.cpp src/platform/ps5/keyboard_ps5.cpp)- # The app itself: linked into eboot.bin by tools/ps5/link.sh.+ # The app itself, with the PS5's backends: linked into eboot.bin by+ # tools/ps5/link.sh.add_library(xcloud_app STATIC- src/app/app_core.cpp- src/app/worker.cpp- src/app/stream_screen.cpp- src/app/price_loop.cpp- src/app/autoplay.cpp- src/app/stream_player.cpp+ $<TARGET_OBJECTS:xcloud_appcore>+ src/app/ps5_main.cpp+ src/app/shell_ps5.cppsrc/display/display_ps5.cppsrc/display/gpu.cppsrc/media/hw_decoder_ps5.cpp@@ -133,6 +145,19 @@ else()target_compile_options(xcloud_backends_null PRIVATE -Wall -Wextra -Wno-unused-parameter)endif()+ # The app with the null backends and no window: keeps the shared app+ # building and starting on the desktop (no SDL; the desktop app is next).+ add_executable(psbox-headless+ $<TARGET_OBJECTS:xcloud_appcore>+ src/app/headless_main.cpp+ src/app/shell_null.cpp+ )+ target_link_libraries(psbox-headless PRIVATE xcloud_backends_null xcloud_stream xcloud_media xcloud_ui xc_ffmpeg+ datachannel-static)+ if(NOT MSVC)+ target_compile_options(psbox-headless PRIVATE -Wall -Wextra -Wno-unused-parameter)+ endif()+add_executable(xcloud-cli src/app/cli_main.cpp)target_link_libraries(xcloud-cli PRIVATE xcloud_stream xcloud_media xcloud_ui xc_ffmpeg)diff --git a/src/app/app_core.cpp b/src/app/app_core.cppindex 622b16e..19c406b 100644--- a/src/app/app_core.cpp+++ b/src/app/app_core.cpp@@ -1,17 +1,21 @@// SPDX-License-Identifier: GPL-3.0-or-later// Copyright (C) 2026 RafaelNGP-// PS5 front end: main() sets things up, then the main thread reads the pad,-// drives the UI (ui::AppUi) and draws it. The rest lives beside it:-// worker.cpp (all the network work, on its own thread), stream_screen.cpp-// (the game's menu, gestures and controllers while streaming),-// price_loop.cpp (store prices) and autoplay.cpp (the unattended tests).+// The app every platform runs (app_core.h): coreStartup() sets things up,+// then each coreFrame() reads the pad, drives the UI (ui::AppUi) and draws+// it, on the main thread. The rest lives beside it: worker.cpp (all the+// network work, on its own thread), stream_screen.cpp (the game's menu,+// gestures and controllers while streaming), price_loop.cpp (store prices)+// and autoplay.cpp (the unattended tests). What only some platforms do is+// behind app/shell.h.+#include "app/app_core.h"+#include "app/app_state.h"#include "app/autoplay.h"#include "app/crash_guard.h"#include "app/report.h"#include "app/settings.h"+#include "app/shell.h"#include "app/stream_screen.h"-#include "app/updater.h"#include "display/display.h"#include "input/controller.h"#include "input/kbm.h"@@ -29,42 +33,15 @@#include <cstdio>#include <cstdlib>#include <memory>+#include <optional>#include <sys/stat.h>-#include <unistd.h>#include <mutex>#include <string>#include <thread>#include <utility>-extern "C" int sceSystemServiceHideSplashScreen(void);-extern "C" const char* sceKernelGetFsSandboxRandomWord(void);-namespace xc::app {-std::unique_ptr<ui::AppUi> g_ui;-std::mutex g_settingsMutex;-Settings g_settings;-std::string settingsPath() { return platform::dataDir() + "/settings.json"; }-bool allow1440Locked() { return std::max(g_settings.maxHeightCloud, g_settings.maxHeightHome) >= 1440; }-std::atomic<int> g_command{kSignIn};-std::atomic<bool> g_cancel{false};-std::mutex g_argMutex;-ui::GameTile g_playTile;-std::mutex g_playerMutex;-StreamPlayer* g_player = nullptr;-std::mutex g_infoMutex;-ui::StreamInfo g_streamInfo;-std::atomic<uint32_t> g_infoSeq{0};-std::atomic<bool> g_playingHome{false};-std::atomic<bool> g_tierPicked{false};-std::atomic<uint64_t> g_xboxButtonUntil{0};-std::atomic<bool> g_restartWanted{false};--} // namespace xc::app--using namespace xc;-using namespace xc::app;-namespace {std::unique_ptr<ui::ImageCache> g_images;@@ -166,12 +143,59 @@ private:uint64_t since_ = 0, next_ = 0;};-} // namespace+// What main() kept on its stack when it ran the loop itself: made by+// coreStartup(), carried from one pass to the next.+struct Core {+ explicit Core(bool withDisplay) : haveDisplay(withDisplay) {}+ bool frame();++ // 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).+ int keyboardIconSlot() const {+ if (!kbmConnected) return -1;+ int player;+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ player = g_settings.keyboardPlayer;+ }+ if (player < 0 || player >= input::kMaxPads) return -1;+ bool keyboardLast = !input::padConnected(player) || keyboardActiveAt > input::padActiveAt(player);+ return keyboardLast ? player : -1;+ }+ static uint64_t now0() { return platform::nowMs(); }++ const bool haveDisplay;+ ui::Fonts fonts; // the UI keeps a reference: lives as long as the app+ std::optional<ui::Canvas> canvas; // made once the UI has its settings+ std::optional<StreamScreen> streamScreen; // the game's menu and what is laid over it; made once the worker runs+ input::ControllerState prev{}, pad{};+ bool appMenuKeyBefore = false, homeKeyBefore = false; // F12 / Home held at the last pass+ uint8_t mouseButtonsBefore = 0; // the mouse buttons at the last pass (a press chooses a key)+ std::vector<uint8_t> swallowedKeys; // keys pressed to be chosen, kept from the screens until let go+ bool kbmConnected = false; // a USB keyboard or mouse in use+ uint64_t keyboardActiveAt = 0; // when a key or the mouse was last used (ms)+ int keyboardIconShown = -2; // as last drawn in the players' row+ Repeater up, down, left, right, dpadLeft, dpadRight;+ // Smooth scrolling: rows / cards still to move (fractions carry over),+ // the touchpad's last point, and its speed for the glide after release.+ struct {+ float rows = 0, cards = 0;+ bool touching = false;+ float x = 0, y = 0;+ float vRows = 0, vCards = 0; // per second+ uint64_t lastMs = 0;+ } scroll;+ uint64_t padsCheckedAt = 0;+ unsigned padChecks = 0;+ uint64_t lightBarAt = 0;+ bool lightBarSet = false; // false from the menu/keyboard until the buttons are let go+ ui::Screen stageScreen = ui::Screen::Splash;+};+std::unique_ptr<Core> g_core;-int main(int argc, char** argv) {- (void)argc;- (void)argv;+} // namespace+bool coreStartup() {platform::init();log::setFile((platform::dataDir() + "/xcloud.log").c_str());if (!platform::dataDirNote().empty())@@ -186,10 +210,7 @@ int main(int argc, char** argv) {g_lastCrash.crash.empty() ? "" : " — ", g_lastCrash.crash.c_str());crash::install(crashMarkerPath());loadAutoplay();- // An update cut short: the old files went back, and the old eboot.bin- // is the one to run.- if (recoverUpdate(platform::appDir())) platform::restartApp();- importStoreLeftovers(platform::dataDir(), "/data/prosperostore/previous/PPSA99810");+ shell::beforeSettings(); // the PS5: an update cut short rolled back, a store update's files brought backstruct stat settingsStat;if (!g_settings.load(settingsPath()) && ::stat(settingsPath().c_str(), &settingsStat) == 0) {// Unreadable (cut short?): kept aside, not overwritten by the defaults.@@ -200,39 +221,25 @@ int main(int argc, char** argv) {ui::setLanguage(ui::languageFromCode(g_settings.language));XC_LOGI("settings: language %s, %s, region %s", g_settings.language.c_str(), g_settings.resolution.c_str(),g_settings.region.empty() ? "auto" : g_settings.region.c_str());- sceSystemServiceHideSplashScreen();- // 120 Hz output: param.json declares it (the console grants the mode only- // then), and RADV asks for it when the param.json it reads says so. Off- // (the default: OLED TVs may flicker under VRR in the menus), RADV reads- // one that doesn't. Decided once per start, as RADV opens VideoOut once.- // With the patched RADV the output starts at 60 Hz and each game's stream- // turns 120 Hz on (StreamScreen); without it, the setting decides here.- if (!g_settings.highRefresh || display::canSwitchRefresh()) {- std::string path = platform::dataDir() + "/videoout-60hz.json";- platform::writeFileAtomic(path, "{\"attribute3\": 0}\n");- ::setenv("PS5_VIDEOOUT_PARAM_JSON", path.c_str(), 1);- }- XC_LOGI("display: 120 Hz output %s", !g_settings.highRefresh ? "off"- : display::canSwitchRefresh() ? "in games" : "on");+ shell::beforeDisplay(g_settings); // the PS5: the splash screen hidden, the video mode (120 Hz) settledif (g_autoplay.vkTest) {bool ok = display::bringUpTest(300);XC_LOGI("AUTOPLAY END: vktest %s", ok ? "ran" : "failed");- for (;;) platform::sleepMs(1000);+ while (shell::pumpEvents()) platform::sleepMs(1000); // the PS5 stays here, as it never quits+ return false;}bool haveDisplay = display::init(!g_autoplay.cpuDisplay);if (!input::init()) XC_LOGE("controller init failed");input::kbmInit(input::padUserId(0)); // USB keyboards and mice (logs what it found)- ui::Fonts fonts;+ g_core = std::make_unique<Core>(haveDisplay);+ ui::Fonts& fonts = g_core->fonts;if (!fonts.load(platform::assetDir() + "/fonts")) XC_LOGE("fonts missing in %s", platform::assetDir().c_str());{// The console's icon font (keyboard and mouse...): read where the// system keeps it, not shipped with the app.- const char* word = sceKernelGetFsSandboxRandomWord();- std::string sandbox = std::string("/") + (word ? word : "");- bool ok = fonts.loadIcons({"/system_ex/common_ex/font2/PS4Icon.ttf", sandbox + "/common_ex/font2/PS4Icon.ttf",- sandbox + "_ex/common_ex/font2/PS4Icon.ttf"});+ bool ok = fonts.loadIcons(shell::iconFontPaths());XC_LOGI("system icon font: %s", ok ? "loaded" : "not found (drawn icons)");}g_images = std::make_unique<ui::ImageCache>(@@ -275,7 +282,7 @@ int main(int argc, char** argv) {: g_settings.librarySort == "console" ? ui::LibrarySort::Console: ui::LibrarySort::Recent);}- ui::Canvas canvas(display::kWidth, display::kHeight);+ g_core->canvas.emplace(display::kWidth, display::kHeight);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.@@ -288,390 +295,368 @@ int main(int argc, char** argv) {if (g_autoplay.testCa) net::addTrustedCa(platform::dataDir() + "/test-ca.pem");std::thread(worker).detach();}-- // Never return from main: the app is closed from the home screen.- input::ControllerState prev{}, pad{};- bool appMenuKeyBefore = false, homeKeyBefore = false; // F12 / Home held at the last pass- uint8_t mouseButtonsBefore = 0; // the mouse buttons at the last pass (a press chooses a key)- std::vector<uint8_t> swallowedKeys; // keys pressed to be chosen, kept from the screens until let go- bool kbmConnected = false; // a USB keyboard or mouse in use- uint64_t keyboardActiveAt = 0; // when a key or the mouse was last used (ms)- // 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).- auto keyboardIconSlot = [&]() -> int {- if (!kbmConnected) return -1;- int player;- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- player = g_settings.keyboardPlayer;- }- if (player < 0 || player >= input::kMaxPads) return -1;- bool keyboardLast = !input::padConnected(player) || keyboardActiveAt > input::padActiveAt(player);- return keyboardLast ? player : -1;- };- int keyboardIconShown = -2; // as last drawn in the players' row- auto now0 = [] { return platform::nowMs(); };- Repeater up, down, left, right, dpadLeft, dpadRight;- // Smooth scrolling: rows / cards still to move (fractions carry over),- // the touchpad's last point, and its speed for the glide after release.- struct {- float rows = 0, cards = 0;- bool touching = false;- float x = 0, y = 0;- float vRows = 0, vCards = 0; // per second- uint64_t lastMs = 0;- } scroll;- StreamScreen streamScreen(fonts); // the game's menu and what is laid over it- uint64_t padsCheckedAt = 0;- unsigned padChecks = 0;- uint64_t lightBarAt = 0;- bool lightBarSet = false; // false from the menu/keyboard until the buttons are let go+ g_core->streamScreen.emplace(fonts);crash::startWatchdog(15000); // a main loop stuck for 15 s leaves a marker- ui::Screen stageScreen = ui::Screen::Splash;- for (;;) {- crash::heartbeat();- if (ui::Screen sc = g_ui->screen(); sc != stageScreen) {- // What the app is doing, for a crash marker (the worker names- // the stream itself).- stageScreen = sc;- static const char* const kNames[] = {"splash", "sign-in", "home", "game page", "launching",- "streaming", "error", "settings", "updating"};- size_t i = static_cast<size_t>(sc);- if (sc != ui::Screen::Streaming && sc != ui::Screen::Launching && i < std::size(kNames)) crash::setStage(kNames[i]);- // After a crash: its report, once the app is up again.- if (g_lastCrash.found && !g_autoplay.crashTest && (sc == ui::Screen::Home || sc == ui::Screen::Error)) {- g_lastCrash.found = false;- openReport("Closed unexpectedly: " + g_lastCrash.kind + " while " + g_lastCrash.stage, true,- ui::tr(ui::Str::CrashedLastTime), g_lastCrash.crash);- }- }- // A Microsoft service refused for the console's clock: said once, even- // if signing in worked (only some content then fails to load). Only- // for refusals while the app is in use: those of the sign-in (its- // error already says it, and the date may be fixed before Retry) are- // left behind; prices and images ask again on the home screen.- static bool clockTold = false;- static unsigned clockSeen = 0;- if (!clockTold && net::clockRefusals() != clockSeen) {- clockSeen = net::clockRefusals();- ui::Screen now = g_ui->screen();- if (now == ui::Screen::Home || now == ui::Screen::Details || now == ui::Screen::Settings) {- clockTold = true;- platform::notify(ui::trf(ui::Str::ClockWrongNotice, net::todayText()), "the console's clock looks wrong (notification)");- }- }- if (g_restartWanted) {- // After an update: the new version, started in place of this one.- if (!g_autoplay.noRestart) platform::restartApp();- // It couldn't start again by itself: closed, the next start is the new version.- platform::notify(ui::tr(ui::Str::UpdateReopen), "update installed, restart failed: closing");- platform::sleepMs(2000);- // Not std::exit: its destructors would free what the background- // threads still use (a crash, then a false "closed unexpectedly").- // The log is already on disk (flushed by line).- _exit(0);+ return true;+}++bool Core::frame() {+ if (!shell::pumpEvents()) return false;+ crash::heartbeat();+ if (ui::Screen sc = g_ui->screen(); sc != stageScreen) {+ // What the app is doing, for a crash marker (the worker names+ // the stream itself).+ stageScreen = sc;+ static const char* const kNames[] = {"splash", "sign-in", "home", "game page", "launching",+ "streaming", "error", "settings", "updating"};+ size_t i = static_cast<size_t>(sc);+ if (sc != ui::Screen::Streaming && sc != ui::Screen::Launching && i < std::size(kNames)) crash::setStage(kNames[i]);+ // After a crash: its report, once the app is up again.+ if (g_lastCrash.found && !g_autoplay.crashTest && (sc == ui::Screen::Home || sc == ui::Screen::Error)) {+ g_lastCrash.found = false;+ openReport("Closed unexpectedly: " + g_lastCrash.kind + " while " + g_lastCrash.stage, true,+ ui::tr(ui::Str::CrashedLastTime), g_lastCrash.crash);}- // Gyro aiming moves the aim in a game, not the app's menu.- input::setGyroActive(g_ui->screen() == ui::Screen::Streaming && !streamScreen.menuOpen());- input::poll(pad);- autoplayPad(pad);- // 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();- bool inGame = g_ui->screen() == ui::Screen::Streaming;- {- // The hints follow the device last used: a key or the mouse- // switches them to the keyboard's keys, the controller back.- bool keyPressed = std::any_of(kbm.keys.begin(), kbm.keys.end(), [](const input::KeyEvent& k) { return k.pressed; });- bool padUsed = pad.btnA || pad.btnB || pad.btnX || pad.btnY || pad.dpadUp || pad.dpadDown || pad.dpadLeft ||- pad.dpadRight || pad.btnL1 || pad.btnR1 || pad.btnOptions || pad.btnTouchpad ||- std::abs(pad.leftStickX) > 0.5f || std::abs(pad.leftStickY) > 0.5f ||- std::abs(pad.rightStickX) > 0.5f || std::abs(pad.rightStickY) > 0.5f;- bool keyboard = ui::g_keyboardHints;- if (keyPressed || kbm.moved) keyboard = true, keyboardActiveAt = now0();- else if (padUsed) keyboard = false;- if (keyboard != ui::g_keyboardHints) {- ui::g_keyboardHints = keyboard;- g_ui->invalidate();- streamScreen.redrawMenu();- }+ }+ // A Microsoft service refused for the console's clock: said once, even+ // if signing in worked (only some content then fails to load). Only+ // for refusals while the app is in use: those of the sign-in (its+ // error already says it, and the date may be fixed before Retry) are+ // left behind; prices and images ask again on the home screen.+ static bool clockTold = false;+ static unsigned clockSeen = 0;+ if (!clockTold && net::clockRefusals() != clockSeen) {+ clockSeen = net::clockRefusals();+ ui::Screen now = g_ui->screen();+ if (now == ui::Screen::Home || now == ui::Screen::Details || now == ui::Screen::Settings) {+ clockTold = true;+ platform::notify(ui::trf(ui::Str::ClockWrongNotice, net::todayText()), "the console's clock looks wrong (notification)");}- // Keys 1-4 (off a game, or with the app's menu open in one): the- // player the keyboard and mouse play as. 1 native with player 1;- // 2-4 that player's controller (3 or 4 with two players: just its slot).- // The keyboard keys' screen waiting for a key: the next key or mouse- // button pressed is the one chosen (not a move through the screens);- // keys pressed for it stay out of the screens until let go.- bool capturing = g_ui->capturingKey();- if (capturing) {- for (const auto& k : kbm.keys)- if (k.pressed) g_ui->captureKey(k.vk), swallowedKeys.push_back(k.vk);- for (int b = 0; b < 5; ++b)- if ((kbm.buttons & ~mouseButtonsBefore) & (1 << b)) g_ui->captureKey(static_cast<uint8_t>(input::kMouseLeft + b));+ }+ // After an update: the new version, started in place of this one.+ if (g_restartWanted) shell::restartOrExit();+ // Gyro aiming moves the aim in a game, not the app's menu.+ input::setGyroActive(g_ui->screen() == ui::Screen::Streaming && !streamScreen->menuOpen());+ input::poll(pad);+ autoplayPad(pad);+ // 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();+ bool inGame = g_ui->screen() == ui::Screen::Streaming;+ {+ // The hints follow the device last used: a key or the mouse+ // switches them to the keyboard's keys, the controller back.+ bool keyPressed = std::any_of(kbm.keys.begin(), kbm.keys.end(), [](const input::KeyEvent& k) { return k.pressed; });+ bool padUsed = pad.btnA || pad.btnB || pad.btnX || pad.btnY || pad.dpadUp || pad.dpadDown || pad.dpadLeft ||+ pad.dpadRight || pad.btnL1 || pad.btnR1 || pad.btnOptions || pad.btnTouchpad ||+ std::abs(pad.leftStickX) > 0.5f || std::abs(pad.leftStickY) > 0.5f ||+ std::abs(pad.rightStickX) > 0.5f || std::abs(pad.rightStickY) > 0.5f;+ bool keyboard = ui::g_keyboardHints;+ if (keyPressed || kbm.moved) keyboard = true, keyboardActiveAt = now0();+ else if (padUsed) keyboard = false;+ if (keyboard != ui::g_keyboardHints) {+ ui::g_keyboardHints = keyboard;+ g_ui->invalidate();+ streamScreen->redrawMenu();}- mouseButtonsBefore = kbm.buttons;- std::erase_if(swallowedKeys, [&](uint8_t vk) { return !std::binary_search(kbm.held.begin(), kbm.held.end(), vk); });- if ((!inGame || streamScreen.menuOpen()) && !capturing) {- for (const auto& k : kbm.keys) {- if (!k.pressed || k.vk < '1' || k.vk > '4') continue;- int player = k.vk - '1';- {- std::lock_guard<std::mutex> lock(g_settingsMutex);- g_settings.keyboardPlayer = player;- g_settings.save(settingsPath());- }- platform::notify(ui::trf(ui::Str::KeyboardPlayer, std::to_string(player + 1)),- "keyboard: player " + std::to_string(player + 1));- padsCheckedAt = 0; // the players' row at once+ }+ // Keys 1-4 (off a game, or with the app's menu open in one): the+ // player the keyboard and mouse play as. 1 native with player 1;+ // 2-4 that player's controller (3 or 4 with two players: just its slot).+ // The keyboard keys' screen waiting for a key: the next key or mouse+ // button pressed is the one chosen (not a move through the screens);+ // keys pressed for it stay out of the screens until let go.+ bool capturing = g_ui->capturingKey();+ if (capturing) {+ for (const auto& k : kbm.keys)+ if (k.pressed) g_ui->captureKey(k.vk), swallowedKeys.push_back(k.vk);+ for (int b = 0; b < 5; ++b)+ if ((kbm.buttons & ~mouseButtonsBefore) & (1 << b)) g_ui->captureKey(static_cast<uint8_t>(input::kMouseLeft + b));+ }+ mouseButtonsBefore = kbm.buttons;+ std::erase_if(swallowedKeys, [&](uint8_t vk) { return !std::binary_search(kbm.held.begin(), kbm.held.end(), vk); });+ if ((!inGame || streamScreen->menuOpen()) && !capturing) {+ for (const auto& k : kbm.keys) {+ if (!k.pressed || k.vk < '1' || k.vk > '4') continue;+ int player = k.vk - '1';+ {+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ g_settings.keyboardPlayer = player;+ g_settings.save(settingsPath());}+ platform::notify(ui::trf(ui::Str::KeyboardPlayer, std::to_string(player + 1)),+ "keyboard: player " + std::to_string(player + 1));+ padsCheckedAt = 0; // the players' row at once}- // Home: the Xbox button in a game (as the touchpad swiped up).- bool homeKey = std::binary_search(kbm.held.begin(), kbm.held.end(), uint8_t{0x24});- if (inGame && homeKey && !homeKeyBefore && !streamScreen.menuOpen()) g_xboxButtonUntil = now0() + 250;- homeKeyBefore = homeKey;- bool appMenuKey = std::binary_search(kbm.held.begin(), kbm.held.end(), input::kVkAppMenu);- bool appMenuPressed = appMenuKey && !appMenuKeyBefore;- appMenuKeyBefore = appMenuKey;- if ((!inGame || streamScreen.menuOpen()) && !capturing) {- std::vector<uint8_t> navKeys;- for (uint8_t vk : kbm.held)- if (std::find(swallowedKeys.begin(), swallowedKeys.end(), vk) == swallowedKeys.end()) navKeys.push_back(vk);- input::keyboardToPad(navKeys, pad);+ }+ // Home: the Xbox button in a game (as the touchpad swiped up).+ bool homeKey = std::binary_search(kbm.held.begin(), kbm.held.end(), uint8_t{0x24});+ if (inGame && homeKey && !homeKeyBefore && !streamScreen->menuOpen()) g_xboxButtonUntil = now0() + 250;+ homeKeyBefore = homeKey;+ bool appMenuKey = std::binary_search(kbm.held.begin(), kbm.held.end(), input::kVkAppMenu);+ bool appMenuPressed = appMenuKey && !appMenuKeyBefore;+ appMenuKeyBefore = appMenuKey;+ if ((!inGame || streamScreen->menuOpen()) && !capturing) {+ std::vector<uint8_t> navKeys;+ for (uint8_t vk : kbm.held)+ if (std::find(swallowedKeys.begin(), swallowedKeys.end(), vk) == swallowedKeys.end()) navKeys.push_back(vk);+ input::keyboardToPad(navKeys, pad);+ }+ kbmConnected = kbm.keyboard || kbm.mouse || g_autoplay.kbHints;+ if (int shown = keyboardIconSlot(); shown != keyboardIconShown) {+ keyboardIconShown = shown;+ padsCheckedAt = 0; // the players' row at once, as the device in use changes+ }+ streamScreen->setKbm(std::move(kbm));+ {+ // The triggers' resistance: in a game and in its Settings tester only.+ float l2, r2;+ input::setTriggerResistanceActive(g_ui->screen() == ui::Screen::Streaming || g_ui->triggerTest(l2, r2));+ }+ uint64_t now = platform::nowMs();+ if (now - lightBarAt >= 50) { // the light bar: the game in focus, the user's colour or off+ lightBarAt = now;+ int mode;+ ui::Color c;+ if (!g_ui->settingsLightBar(mode, c)) { // Settings shows a choice at once, before it is saved+ std::lock_guard<std::mutex> lock(g_settingsMutex);+ mode = g_settings.lightBarMode;+ c = g_settings.lightBarColour;}- kbmConnected = kbm.keyboard || kbm.mouse || g_autoplay.kbHints;- if (int shown = keyboardIconSlot(); shown != keyboardIconShown) {- keyboardIconShown = shown;- padsCheckedAt = 0; // the players' row at once, as the device in use changes+ if (mode == 2) {+ if (lightBarSet) input::resetLightBar(0);+ lightBarSet = false;+ } else if (mode == 1 || g_ui->accentColor(c)) {+ static ui::Color logged = 0;+ if (!g_autoplay.title.empty() && c != logged) XC_LOGI("light bar: #%06X", c & 0xFFFFFF), logged = c;+ input::setLightBar(static_cast<uint8_t>(c), static_cast<uint8_t>(c >> 8), static_cast<uint8_t>(c >> 16));+ lightBarSet = true;}- streamScreen.setKbm(std::move(kbm));- {- // The triggers' resistance: in a game and in its Settings tester only.- float l2, r2;- input::setTriggerResistanceActive(g_ui->screen() == ui::Screen::Streaming || g_ui->triggerTest(l2, r2));+ }+ if (now - padsCheckedAt >= 500) { // other players signing in or out+ padsCheckedAt = now;+ if (++padChecks % 2 == 0) input::refreshPads();+ // Off the stream nobody reads pads 1..3: poll them for their state.+ if (g_ui->screen() != ui::Screen::Streaming) {+ input::ControllerState ignored;+ for (int i = 1; i < input::kMaxPads; ++i) input::pollPad(i, ignored);}- uint64_t now = platform::nowMs();- if (now - lightBarAt >= 50) { // the light bar: the game in focus, the user's colour or off- lightBarAt = now;- int mode;- ui::Color c;- if (!g_ui->settingsLightBar(mode, c)) { // Settings shows a choice at once, before it is saved- std::lock_guard<std::mutex> lock(g_settingsMutex);- mode = g_settings.lightBarMode;- c = g_settings.lightBarColour;- }- if (mode == 2) {- if (lightBarSet) input::resetLightBar(0);- lightBarSet = false;- } else if (mode == 1 || g_ui->accentColor(c)) {- static ui::Color logged = 0;- if (!g_autoplay.title.empty() && c != logged) XC_LOGI("light bar: #%06X", c & 0xFFFFFF), logged = c;- input::setLightBar(static_cast<uint8_t>(c), static_cast<uint8_t>(c >> 8), static_cast<uint8_t>(c >> 16));- lightBarSet = true;- }+ ui::PadSlots slots;+ for (int i = 0; i < input::kMaxPads; ++i)+ slots[static_cast<size_t>(i)] = {input::padConnected(i), input::padUserName(i)};+ // The keyboard: in a slot of its own as another player's+ // controller (Settings), else on player 1's while it's the device in use.+ if (int kb = keyboardIconSlot(); kb >= 0) {+ slots[static_cast<size_t>(kb)].keyboard = true;+ slots[static_cast<size_t>(kb)].connected = true;}- if (now - padsCheckedAt >= 500) { // other players signing in or out- padsCheckedAt = now;- if (++padChecks % 2 == 0) input::refreshPads();- // Off the stream nobody reads pads 1..3: poll them for their state.- if (g_ui->screen() != ui::Screen::Streaming) {- input::ControllerState ignored;- for (int i = 1; i < input::kMaxPads; ++i) input::pollPad(i, ignored);- }- ui::PadSlots slots;- for (int i = 0; i < input::kMaxPads; ++i)- slots[static_cast<size_t>(i)] = {input::padConnected(i), input::padUserName(i)};- // The keyboard: in a slot of its own as another player's- // controller (Settings), else on player 1's while it's the device in use.- if (int kb = keyboardIconSlot(); kb >= 0) {- slots[static_cast<size_t>(kb)].keyboard = true;- slots[static_cast<size_t>(kb)].connected = true;+ g_ui->setPads(slots);+ streamScreen->setPads(slots);+ }++ ui::NavInput nav;+ nav.up = up.update(pad.dpadUp || pad.leftStickY < -0.6f, now);+ nav.down = down.update(pad.dpadDown || pad.leftStickY > 0.6f, now);+ nav.left = left.update(pad.dpadLeft || pad.leftStickX < -0.6f, now);+ nav.right = right.update(pad.dpadRight || pad.leftStickX > 0.6f, now);+ nav.accept = pad.btnA && !prev.btnA;+ nav.back = pad.btnB && !prev.btnB;+ nav.options = pad.btnOptions && !prev.btnOptions;+ nav.l1 = pad.btnL1 && !prev.btnL1;+ nav.r1 = pad.btnR1 && !prev.btnR1;+ nav.square = pad.btnX && !prev.btnX; // Square (Xbox X)+ nav.triangle = pad.btnY && !prev.btnY; // Triangle (Xbox Y)+ nav.r3 = pad.btnR3 && !prev.btnR3;+ nav.l2 = pad.triggerL2 > 0.5f && prev.triggerL2 <= 0.5f;+ nav.r2 = pad.triggerR2 > 0.5f && prev.triggerR2 <= 0.5f;+ nav.touchpad = pad.btnTouchpad;+ nav.stickX = pad.leftStickX;+ nav.stickY = pad.leftStickY;+ nav.dpadLeft = dpadLeft.update(pad.dpadLeft, now);+ nav.dpadRight = dpadRight.update(pad.dpadRight, now);+ nav.rawLX = pad.rawLeftX, nav.rawLY = pad.rawLeftY, nav.rawRX = pad.rawRightX, nav.rawRY = pad.rawRightY;+ nav.l2Analog = pad.triggerL2, nav.r2Analog = pad.triggerR2;+ // Smooth scrolling. The right stick: a speed that follows how far it+ // is pushed (up to ~12 rows / 16 cards a second). The touchpad,+ // touched (not pressed): the list follows the finger (its height ~6+ // rows, its width ~8 cards; the finger up scrolls up), then glides on+ // and slows down after release, like two fingers on a laptop's.+ {+ float dt = scroll.lastMs ? std::min(0.1f, (now - scroll.lastMs) / 1000.0f) : 0.0f;+ scroll.lastMs = now;+ auto speed = [](float v, float top) {+ float m = (std::abs(v) - 0.15f) / 0.85f;+ return m <= 0 ? 0.0f : (v < 0 ? -1.0f : 1.0f) * top * m * m;+ };+ scroll.rows += speed(pad.rightStickY, 12) * dt;+ scroll.cards += speed(pad.rightStickX, 16) * dt;+ constexpr float kRowsPerPad = 6, kCardsPerPad = 8;+ bool touch = pad.touching && !pad.btnTouchpad && g_ui->screen() == ui::Screen::Home;+ if (touch && scroll.touching) {+ float dr = (pad.touchY - scroll.y) * kRowsPerPad, dc = (pad.touchX - scroll.x) * kCardsPerPad;+ scroll.rows += dr;+ scroll.cards += dc;+ if (dt > 0) { // the finger's speed, smoothed+ scroll.vRows = 0.6f * scroll.vRows + 0.4f * dr / dt;+ scroll.vCards = 0.6f * scroll.vCards + 0.4f * dc / dt;}- g_ui->setPads(slots);- streamScreen.setPads(slots);+ } else if (!touch && dt > 0) { // the glide, slowing down+ scroll.rows += scroll.vRows * dt;+ scroll.cards += scroll.vCards * dt;+ float decay = std::exp(-4.0f * dt);+ scroll.vRows *= decay;+ scroll.vCards *= decay;+ if (std::abs(scroll.vRows) < 0.8f) scroll.vRows = 0;+ if (std::abs(scroll.vCards) < 0.8f) scroll.vCards = 0;}+ if (touch && !scroll.touching) scroll.vRows = scroll.vCards = 0; // a new touch stops a glide+ scroll.touching = touch;+ scroll.x = pad.touchX, scroll.y = pad.touchY;+ if (g_ui->screen() != ui::Screen::Home) scroll.rows = scroll.cards = scroll.vRows = scroll.vCards = 0;+ nav.scrollRows = static_cast<int>(scroll.rows);+ nav.scrollCards = static_cast<int>(scroll.cards);+ scroll.rows -= static_cast<float>(nav.scrollRows);+ scroll.cards -= static_cast<float>(nav.scrollCards);+ }+ nav.nowMs = now;+ bool menuCombo = (pad.btnOptions && pad.btnTouchpad && !(prev.btnOptions && prev.btnTouchpad)) ||+ (inGame && appMenuPressed);+ prev = pad;+ autoplayNav(nav, menuCombo, now);+ if (g_ui->screen() == ui::Screen::Streaming) {+ streamScreen->update(pad, nav, menuCombo);+ platform::sleepMs(8); // ~120 Hz input+ return true;+ }+ streamScreen->idle();- ui::NavInput nav;- nav.up = up.update(pad.dpadUp || pad.leftStickY < -0.6f, now);- nav.down = down.update(pad.dpadDown || pad.leftStickY > 0.6f, now);- nav.left = left.update(pad.dpadLeft || pad.leftStickX < -0.6f, now);- nav.right = right.update(pad.dpadRight || pad.leftStickX > 0.6f, now);- nav.accept = pad.btnA && !prev.btnA;- nav.back = pad.btnB && !prev.btnB;- nav.options = pad.btnOptions && !prev.btnOptions;- nav.l1 = pad.btnL1 && !prev.btnL1;- nav.r1 = pad.btnR1 && !prev.btnR1;- nav.square = pad.btnX && !prev.btnX; // Square (Xbox X)- nav.triangle = pad.btnY && !prev.btnY; // Triangle (Xbox Y)- nav.r3 = pad.btnR3 && !prev.btnR3;- nav.l2 = pad.triggerL2 > 0.5f && prev.triggerL2 <= 0.5f;- nav.r2 = pad.triggerR2 > 0.5f && prev.triggerR2 <= 0.5f;- nav.touchpad = pad.btnTouchpad;- nav.stickX = pad.leftStickX;- nav.stickY = pad.leftStickY;- nav.dpadLeft = dpadLeft.update(pad.dpadLeft, now);- nav.dpadRight = dpadRight.update(pad.dpadRight, now);- nav.rawLX = pad.rawLeftX, nav.rawLY = pad.rawLeftY, nav.rawRX = pad.rawRightX, nav.rawRY = pad.rawRightY;- nav.l2Analog = pad.triggerL2, nav.r2Analog = pad.triggerR2;- // Smooth scrolling. The right stick: a speed that follows how far it- // is pushed (up to ~12 rows / 16 cards a second). The touchpad,- // touched (not pressed): the list follows the finger (its height ~6- // rows, its width ~8 cards; the finger up scrolls up), then glides on- // and slows down after release, like two fingers on a laptop's.- {- float dt = scroll.lastMs ? std::min(0.1f, (now - scroll.lastMs) / 1000.0f) : 0.0f;- scroll.lastMs = now;- auto speed = [](float v, float top) {- float m = (std::abs(v) - 0.15f) / 0.85f;- return m <= 0 ? 0.0f : (v < 0 ? -1.0f : 1.0f) * top * m * m;- };- scroll.rows += speed(pad.rightStickY, 12) * dt;- scroll.cards += speed(pad.rightStickX, 16) * dt;- constexpr float kRowsPerPad = 6, kCardsPerPad = 8;- bool touch = pad.touching && !pad.btnTouchpad && g_ui->screen() == ui::Screen::Home;- if (touch && scroll.touching) {- float dr = (pad.touchY - scroll.y) * kRowsPerPad, dc = (pad.touchX - scroll.x) * kCardsPerPad;- scroll.rows += dr;- scroll.cards += dc;- if (dt > 0) { // the finger's speed, smoothed- scroll.vRows = 0.6f * scroll.vRows + 0.4f * dr / dt;- scroll.vCards = 0.6f * scroll.vCards + 0.4f * dc / dt;- }- } else if (!touch && dt > 0) { // the glide, slowing down- scroll.rows += scroll.vRows * dt;- scroll.cards += scroll.vCards * dt;- float decay = std::exp(-4.0f * dt);- scroll.vRows *= decay;- scroll.vCards *= decay;- if (std::abs(scroll.vRows) < 0.8f) scroll.vRows = 0;- if (std::abs(scroll.vCards) < 0.8f) scroll.vCards = 0;- }- if (touch && !scroll.touching) scroll.vRows = scroll.vCards = 0; // a new touch stops a glide- scroll.touching = touch;- scroll.x = pad.touchX, scroll.y = pad.touchY;- if (g_ui->screen() != ui::Screen::Home) scroll.rows = scroll.cards = scroll.vRows = scroll.vCards = 0;- nav.scrollRows = static_cast<int>(scroll.rows);- nav.scrollCards = static_cast<int>(scroll.cards);- scroll.rows -= static_cast<float>(nav.scrollRows);- scroll.cards -= static_cast<float>(nav.scrollCards);+ ui::UiEvent ev = g_ui->handle(nav);+ int strength, hz, resistance;+ bool pulses;+ if (g_ui->settingsTriggerFeel(strength, hz, resistance, pulses)) {+ // Settings: the triggers' feel as chosen there, at once; their+ // tester makes them vibrate as far as they are pressed.+ input::setTriggerFeel(strength, hz, resistance, pulses);+ float l2, r2;+ static bool testing = false;+ input::setTriggerLogging(g_ui->triggerTest(l2, r2));+ if (g_ui->triggerTest(l2, r2)) {+ input::setTriggerRumble(static_cast<uint8_t>(std::lround(l2 * 255)), static_cast<uint8_t>(std::lround(r2 * 255)), 500);+ testing = true;+ } else if (testing) {+ input::setTriggerRumble(0, 0, 0);+ testing = false;}- nav.nowMs = now;- bool menuCombo = (pad.btnOptions && pad.btnTouchpad && !(prev.btnOptions && prev.btnTouchpad)) ||- (inGame && appMenuPressed);- prev = pad;- autoplayNav(nav, menuCombo, now);- if (g_ui->screen() == ui::Screen::Streaming) {- streamScreen.update(pad, nav, menuCombo);- platform::sleepMs(8); // ~120 Hz input- continue;+ }+ if (bool circle = g_ui->circleConfirms(); circle != input::circleConfirms()) {+ // The confirm button just changed in Settings: the pad follows at+ // once, and a button still held from choosing it isn't a new press.+ input::setCircleConfirms(circle);+ 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;}- streamScreen.idle();-- ui::UiEvent ev = g_ui->handle(nav);- int strength, hz, resistance;- bool pulses;- if (g_ui->settingsTriggerFeel(strength, hz, resistance, pulses)) {- // Settings: the triggers' feel as chosen there, at once; their- // tester makes them vibrate as far as they are pressed.- input::setTriggerFeel(strength, hz, resistance, pulses);- float l2, r2;- static bool testing = false;- input::setTriggerLogging(g_ui->triggerTest(l2, r2));- if (g_ui->triggerTest(l2, r2)) {- input::setTriggerRumble(static_cast<uint8_t>(std::lround(l2 * 255)), static_cast<uint8_t>(std::lround(r2 * 255)), 500);- testing = true;- } else if (testing) {- input::setTriggerRumble(0, 0, 0);- testing = false;- }+ 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;}- if (bool circle = g_ui->circleConfirms(); circle != input::circleConfirms()) {- // The confirm button just changed in Settings: the pad follows at- // once, and a button still held from choosing it isn't a new press.- input::setCircleConfirms(circle);- std::swap(prev.btnA, prev.btnB);- XC_LOGI("confirm button: %s", circle ? "circle" : "cross");+ 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.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, sort %s", g_settings.hidden.size(), g_settings.librarySort.c_str());+ break;}- 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::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.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, sort %s", g_settings.hidden.size(), g_settings.librarySort.c_str());- 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::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());}- 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::None: break;+ 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::None: break;+ }- autoplayScreens(canvas, now);+ autoplayScreens(*canvas, now);- if (haveDisplay && g_ui->needsRedraw(now)) {- uint64_t t0 = platform::nowMs();- g_ui->render(canvas, now);- uint64_t t1 = platform::nowMs();- static int logged = 0;- if (logged < 5 && g_ui->screen() == ui::Screen::Home) {- ++logged;- XC_LOGI("ui render %llu ms", static_cast<unsigned long long>(t1 - t0));- }- std::lock_guard<std::mutex> lock(display::frameMutex());- if (g_ui->screen() != ui::Screen::Streaming) {- display::drawRgba(canvas.data());- display::present(); // paced by the next draw waiting for a free buffer- }- } else {- platform::sleepMs(8);+ if (haveDisplay && g_ui->needsRedraw(now)) {+ uint64_t t0 = platform::nowMs();+ g_ui->render(*canvas, now);+ uint64_t t1 = platform::nowMs();+ static int logged = 0;+ if (logged < 5 && g_ui->screen() == ui::Screen::Home) {+ ++logged;+ XC_LOGI("ui render %llu ms", static_cast<unsigned long long>(t1 - t0));}+ std::lock_guard<std::mutex> lock(display::frameMutex());+ if (g_ui->screen() != ui::Screen::Streaming) {+ display::drawRgba(canvas->data());+ display::present(); // paced by the next draw waiting for a free buffer+ }+ } else {+ platform::sleepMs(8);}+ return true;}++bool coreFrame() { return g_core->frame(); }++void coreShutdown() {+ // Not on the PS5, whose loop never ends. The worker isn't stopped (it+ // may be waiting on the network): the caller leaves with _exit().+ XC_LOGI("=== PSBox Cloud Gaming closing ===");+ input::shutdown();+ display::shutdown();+ platform::shutdown();+}++int runApp() {+ if (!coreStartup()) return 1;+ while (coreFrame()) {+ }+ coreShutdown();+ return 0;+}++} // namespace xc::appdiff --git a/src/app/app_core.h b/src/app/app_core.hnew file mode 100644index 0000000..59a86f4--- /dev/null+++ b/src/app/app_core.h@@ -0,0 +1,22 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// The app every platform runs (app_core.cpp), on the main thread: the+// start-up, then one pass of the main loop at a time. Each platform's main()+// calls runApp(); what differs between them is behind app/shell.h and the+// backends it links (docs/multiplatform.md).+#pragma once++namespace xc::app {++// Everything up to the main loop, the worker thread started; false when the+// app is to close at once.+bool coreStartup();+// One pass: input, the UI or the game's stream, drawing. False once the app+// is closed (never on the PS5: the system ends it).+bool coreFrame();+// After the last pass.+void coreShutdown();+// The three in turn; the process's exit code.+int runApp();++} // namespace xc::appdiff --git a/src/app/app_state.cpp b/src/app/app_state.cppnew file mode 100644index 0000000..7271709--- /dev/null+++ b/src/app/app_state.cpp@@ -0,0 +1,31 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// The state the app's threads share (app_state.h).+#include "app/app_state.h"++#include "platform/platform.h"++#include <algorithm>++namespace xc::app {++std::unique_ptr<ui::AppUi> g_ui;+std::mutex g_settingsMutex;+Settings g_settings;+std::string settingsPath() { return platform::dataDir() + "/settings.json"; }+bool allow1440Locked() { return std::max(g_settings.maxHeightCloud, g_settings.maxHeightHome) >= 1440; }+std::atomic<int> g_command{kSignIn};+std::atomic<bool> g_cancel{false};+std::mutex g_argMutex;+ui::GameTile g_playTile;+std::mutex g_playerMutex;+StreamPlayer* g_player = nullptr;+std::mutex g_infoMutex;+ui::StreamInfo g_streamInfo;+std::atomic<uint32_t> g_infoSeq{0};+std::atomic<bool> g_playingHome{false};+std::atomic<bool> g_tierPicked{false};+std::atomic<uint64_t> g_xboxButtonUntil{0};+std::atomic<bool> g_restartWanted{false};++} // namespace xc::appdiff --git a/src/app/app_state.h b/src/app/app_state.hindex 717bd88..7366de2 100644--- a/src/app/app_state.h+++ b/src/app/app_state.h@@ -3,7 +3,7 @@// What the app's pieces share: app_core.cpp (the main thread: pad, UI,// drawing), worker.cpp (the worker thread: all the network work),// stream_screen.cpp (the streaming screen) and price_loop.cpp. Defined in-// app_core.cpp.+// app_state.cpp.#pragma once#include "app/settings.h"diff --git a/src/app/headless_main.cpp b/src/app/headless_main.cppnew file mode 100644index 0000000..08895bd--- /dev/null+++ b/src/app/headless_main.cpp@@ -0,0 +1,18 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// psbox-headless: the app (app_core.cpp) on a desktop with the null+// backends and shell_null.cpp: no window, controller, sound or hardware+// decoder. It keeps the shared app building and starting off the PS5 until+// the desktop app exists (docs/multiplatform.md). Ctrl+C closes it.+#include "app/app_core.h"++#include <cstdio>+#include <unistd.h>++int main() {+ int code = xc::app::runApp();+ // Not a return from main: the worker's threads still run, and the+ // static destructors would free what they use (as on the PS5).+ std::fflush(nullptr);+ _exit(code);+}diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppnew file mode 100644index 0000000..bfa8632--- /dev/null+++ b/src/app/ps5_main.cpp@@ -0,0 +1,12 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// The PS5's entry point: the app (app_core.cpp) on the main thread, with the+// PS5 backends and shell_ps5.cpp. Never returns: the app is closed from the+// home screen.+#include "app/app_core.h"++int main(int argc, char** argv) {+ (void)argc;+ (void)argv;+ return xc::app::runApp();+}diff --git a/src/app/shell.h b/src/app/shell.hnew file mode 100644index 0000000..09655ce--- /dev/null+++ b/src/app/shell.h@@ -0,0 +1,38 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// The parts of start-up and of the app's life that only some platforms+// have, as free functions each front end's shell defines, picked at link+// time like the backends: shell_ps5.cpp on the console, shell_null.cpp for a+// desktop build without a window (psbox-headless). See docs/multiplatform.md.+#pragma once++#include "app/settings.h"++#include <string>+#include <vector>++namespace xc::app::shell {++// Before settings.json is read: an update cut short is rolled back (and the+// app started again), a store update's leftovers brought back.+void beforeSettings();+// Once the settings are read, before the display comes up: the PS5 hides+// its splash screen and settles the video mode (120 Hz).+void beforeDisplay(const Settings& settings);+// Where the system's icon font may be (keyboard and mouse glyphs), first+// choice first; empty when there is none (the UI draws its own icons).+std::vector<std::string> iconFontPaths();+// Each pass of the main loop: the system's events. False once the user+// closed the app (never on the PS5, where the system ends it).+bool pumpEvents();+// Whether this build installs an update itself; elsewhere a newer release+// is only noted in the log, never offered.+bool canSelfUpdate();+// Whether the running app is the copy in `dir` (where an update goes): one+// started from elsewhere wouldn't be the one replaced.+bool isInstalledCopy(const std::string& dir);+// After an update: the new version started in place of this one, else the+// app closed (its next start is the new one).+[[noreturn]] void restartOrExit();++} // namespace xc::app::shelldiff --git a/src/app/shell_null.cpp b/src/app/shell_null.cppnew file mode 100644index 0000000..2756842--- /dev/null+++ b/src/app/shell_null.cpp@@ -0,0 +1,43 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// app/shell.h for a desktop build without a window (psbox-headless): no+// splash screen or video mode to set up, no system icon font, no updating+// itself. Ctrl+C or SIGTERM closes the app.+#include "app/shell.h"++#include <atomic>+#include <csignal>+#include <cstdio>+#include <unistd.h>++namespace xc::app::shell {++namespace {+std::atomic<bool> g_quit{false};+void onQuit(int) { g_quit = true; }+} // namespace++void beforeSettings() {}+void beforeDisplay(const Settings&) {}+std::vector<std::string> iconFontPaths() { return {}; }++bool pumpEvents() {+ static const bool hooked = [] {+ std::signal(SIGINT, onQuit);+ std::signal(SIGTERM, onQuit);+ return true;+ }();+ (void)hooked;+ return !g_quit;+}++bool canSelfUpdate() { return false; }+bool isInstalledCopy(const std::string&) { return false; }++void restartOrExit() {+ // Never asked (no update is installed here); closed as the PS5 does.+ std::fflush(nullptr);+ _exit(0);+}++} // namespace xc::app::shelldiff --git a/src/app/shell_ps5.cpp b/src/app/shell_ps5.cppnew file mode 100644index 0000000..26fe285--- /dev/null+++ b/src/app/shell_ps5.cpp@@ -0,0 +1,76 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// app/shell.h on the PS5.+#include "app/shell.h"++#include "app/autoplay.h"+#include "app/updater.h"+#include "display/display.h"+#include "platform/platform.h"+#include "ui/strings.h"+#include "util/log.h"++#include <cstdlib>+#include <sys/stat.h>+#include <unistd.h>++extern "C" int sceSystemServiceHideSplashScreen(void);+extern "C" const char* sceKernelGetFsSandboxRandomWord(void);++namespace xc::app::shell {++void beforeSettings() {+ // An update cut short: the old files went back, and the old eboot.bin+ // is the one to run.+ if (recoverUpdate(platform::appDir())) platform::restartApp();+ importStoreLeftovers(platform::dataDir(), "/data/prosperostore/previous/PPSA99810");+}++void beforeDisplay(const Settings& settings) {+ sceSystemServiceHideSplashScreen();+ // 120 Hz output: param.json declares it (the console grants the mode only+ // then), and RADV asks for it when the param.json it reads says so. Off+ // (the default: OLED TVs may flicker under VRR in the menus), RADV reads+ // one that doesn't. Decided once per start, as RADV opens VideoOut once.+ // With the patched RADV the output starts at 60 Hz and each game's stream+ // turns 120 Hz on (StreamScreen); without it, the setting decides here.+ if (!settings.highRefresh || display::canSwitchRefresh()) {+ std::string path = platform::dataDir() + "/videoout-60hz.json";+ platform::writeFileAtomic(path, "{\"attribute3\": 0}\n");+ ::setenv("PS5_VIDEOOUT_PARAM_JSON", path.c_str(), 1);+ }+ XC_LOGI("display: 120 Hz output %s", !settings.highRefresh ? "off"+ : display::canSwitchRefresh() ? "in games" : "on");+}++std::vector<std::string> iconFontPaths() {+ const char* word = sceKernelGetFsSandboxRandomWord();+ std::string sandbox = std::string("/") + (word ? word : "");+ return {"/system_ex/common_ex/font2/PS4Icon.ttf", sandbox + "/common_ex/font2/PS4Icon.ttf",+ sandbox + "_ex/common_ex/font2/PS4Icon.ttf"};+}++// The system closes the app (from the home screen): nothing to read here.+bool pumpEvents() { return true; }++bool canSelfUpdate() { return true; }++bool isInstalledCopy(const std::string& dir) {+ // /app0 is the folder the system started the app from.+ struct stat here {}, running {};+ return ::stat((dir + "/eboot.bin").c_str(), &here) == 0 && ::stat("/app0/eboot.bin", &running) == 0 &&+ here.st_ino == running.st_ino;+}++void restartOrExit() {+ if (!g_autoplay.noRestart) platform::restartApp();+ // It couldn't start again by itself: closed, the next start is the new version.+ platform::notify(ui::tr(ui::Str::UpdateReopen), "update installed, restart failed: closing");+ platform::sleepMs(2000);+ // Not std::exit: its destructors would free what the background+ // threads still use (a crash, then a false "closed unexpectedly").+ // The log is already on disk (flushed by line).+ _exit(0);+}++} // namespace xc::app::shelldiff --git a/src/app/worker.cpp b/src/app/worker.cppindex 5b34ffe..401057a 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -7,6 +7,7 @@#include "app/autoplay.h"#include "app/crash_guard.h"#include "app/library.h"+#include "app/shell.h"#include "app/stream_player.h"#include "app/update_check.h"#include "app/updater.h"@@ -22,7 +23,6 @@#include <cstdlib>#include <map>-#include <sys/stat.h>#include <unistd.h>#include <memory>#include <thread>@@ -427,6 +427,11 @@ void checkForUpdate() {XC_LOGI("latest release: %s (this is %s)", found ? r.tag.c_str() : err.c_str(), XC_APP_VERSION);bool offer = found && isNewerVersion(r.tag, XC_APP_VERSION) && !r.zipUrl.empty() && !r.sigUrl.empty();if (found && isNewerVersion(r.tag, XC_APP_VERSION) && !offer) XC_LOGW("%s has no signed package", r.tag.c_str());+ if (offer && !shell::canSelfUpdate()) {+ // This build doesn't install updates itself (only the PS5's does).+ XC_LOGI("%s is out: this build doesn't update itself", r.tag.c_str());+ offer = false;+ }{std::lock_guard<std::mutex> lock(g_releaseMutex);g_release = offer ? r : Release{};@@ -454,9 +459,7 @@ void runUpdate() {// Only where the app runs from: installed elsewhere, it would write next// to the wrong eboot.bin.std::string dir = platform::appDir(), err;- struct stat here {}, running {};- bool ok = ::stat((dir + "/eboot.bin").c_str(), &here) == 0 && ::stat("/app0/eboot.bin", &running) == 0 &&- here.st_ino == running.st_ino;+ bool ok = shell::isInstalledCopy(dir);if (!ok) err = "the app doesn't run from " + dir;int lastPct = -1;ok = ok && installRelease(r, dir, XC_APP_VERSION, [&](UpdateStep step, double f) {