Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

App core: display::pump()/idleWait(), shell hooks for the desktop, orderly quit

Rafael Abud Ferreiraea3adcd200fa
diff --git a/src/app/app_core.cpp b/src/app/app_core.cpp
index 053cfd2..b71ba5d 100644
--- a/src/app/app_core.cpp
+++ b/src/app/app_core.cpp
@@ -230,6 +230,7 @@ bool coreStartup() {
return false;
}
bool haveDisplay = display::init(!g_autoplay.cpuDisplay);
+ if (!shell::afterDisplay(haveDisplay)) return false; // the desktop: its window to the input backend
if (!input::init()) XC_LOGE("controller init failed");
input::kbmInit(input::padUserId(0)); // USB keyboards and mice (logs what it found)
@@ -293,7 +294,7 @@ bool coreStartup() {
} else {
if (g_autoplay.badCa) XC_LOGI("AUTOPLAY END: missing CA bundle, built-in copy %s", net::usingBuiltinCa() ? "used" : "NOT used");
if (g_autoplay.testCa) net::addTrustedCa(platform::dataDir() + "/test-ca.pem");
- std::thread(worker).detach();
+ startWorker();
}
g_core->streamScreen.emplace(fonts);
crash::startWatchdog(15000); // a main loop stuck for 15 s leaves a marker
@@ -525,7 +526,8 @@ bool Core::frame() {
autoplayNav(nav, menuCombo, now);
if (g_ui->screen() == ui::Screen::Streaming) {
streamScreen->update(pad, nav, menuCombo);
- platform::sleepMs(8); // ~120 Hz input
+ display::idleWait(8); // ~120 Hz input (the PS5 sleeps 8 ms; the desktop wakes for a frame)
+ display::pump(); // the desktop shows the newest video frame here
return true;
}
streamScreen->idle();
@@ -637,19 +639,35 @@ bool Core::frame() {
} else {
platform::sleepMs(8);
}
+ display::pump(); // the desktop shows the menu here (paced by its vsync); nothing on the PS5
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(). The
- // desktop app stops it and the stream first (docs/multiplatform.md, M1).
+ // Not on the PS5, whose loop never ends. Before the backends close, the
+ // threads that use them stop: the worker leaves its loop (a stream
+ // stopped and its xCloud session closed, so the account's slot is free;
+ // the library's loading ended), then the price loop. Each wait is
+ // bounded (a request may hang on the network); the caller leaves with
+ // _exit() afterwards, so no static destructor races a thread still
+ // running.
XC_LOGI("=== PSBox Cloud Gaming closing ===");
+ const uint64_t start = platform::nowMs();
+ requestQuit();
+ bool workerDone = waitForWorker(5000);
+ uint64_t spent = platform::nowMs() - start;
+ bool pricesDone = stopPriceLoop(spent < 5000 ? static_cast<uint32_t>(5000 - spent) : 200);
+ if (!workerDone || !pricesDone)
+ XC_LOGW("closing: %s%s%s still busy, left to the exit", workerDone ? "" : "the worker",
+ !workerDone && !pricesDone ? " and " : "", pricesDone ? "" : "the price loop");
+ shell::beforeShutdown();
input::shutdown();
display::shutdown();
platform::shutdown();
+ XC_LOGI("closed in %llu ms", static_cast<unsigned long long>(platform::nowMs() - start));
+ log::setFile(nullptr); // the log closed (every line was already flushed)
}
int runApp() {
diff --git a/src/app/app_state.cpp b/src/app/app_state.cpp
index 7271709..3e9c2ac 100644
--- a/src/app/app_state.cpp
+++ b/src/app/app_state.cpp
@@ -27,5 +27,6 @@ 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};
+std::atomic<bool> g_quit{false};
} // namespace xc::app
diff --git a/src/app/app_state.h b/src/app/app_state.h
index 7366de2..6518797 100644
--- a/src/app/app_state.h
+++ b/src/app/app_state.h
@@ -37,6 +37,8 @@ extern std::atomic<bool> g_cancel;
extern std::mutex g_argMutex;
extern ui::GameTile g_playTile; // what kPlay plays
void worker();
+// The worker thread started (detached), as coreStartup() does.
+void startWorker();
// The update pop-up's "Not now": that release isn't offered again on start.
void skipOfferedUpdate();
@@ -55,8 +57,22 @@ extern std::atomic<uint64_t> g_xboxButtonUntil; // the Xbox button, held until
// call that does it takes the app down when made from another thread).
extern std::atomic<bool> g_restartWanted;
+// --- Closing (desktop: the PS5 is closed by the system, never by the app) ------
+// The app is closing: the worker leaves its loop after what it is doing is
+// cancelled (g_cancel): a stream is stopped and its xCloud session closed,
+// so the account's streaming slot is free at once.
+extern std::atomic<bool> g_quit;
+void requestQuit();
+// After requestQuit(): true once the worker has left its loop (with the
+// threads it started), false if `ms` went by first (a request hanging on
+// the network). True at once when it never started.
+bool waitForWorker(uint32_t ms);
+
// --- Store prices (price_loop.cpp) -----------------------------------------------
void startPriceLoop();
+// Closing: the price loop told to end; true once it has (joined) within
+// `ms`, else it is left to the process's exit.
+bool stopPriceLoop(uint32_t ms);
void setPriceMarket(const std::string& market, const std::string& language);
// The signed-in xCloud client (a copy), for the open game page's queue
// estimate; nullptr after signing out.
diff --git a/src/app/price_loop.cpp b/src/app/price_loop.cpp
index 54cd7d4..9360cf7 100644
--- a/src/app/price_loop.cpp
+++ b/src/app/price_loop.cpp
@@ -24,6 +24,7 @@ std::string g_priceMarket, g_priceLanguage; // set by setPriceMarket() (empty:
std::unique_ptr<xcloud::GssvClient> g_queueClient; // g_priceMutex
platform::Thread g_priceThread;
std::atomic<bool> g_stopPrices{false};
+std::atomic<bool> g_pricesEnded{false}; // the loop returned: joining won't wait
constexpr int64_t kPriceTtlSeconds = 24 * 3600;
std::string pricesPath() { return platform::dataDir() + "/prices.json"; }
@@ -41,7 +42,22 @@ void priceLoop();
} // namespace
-void startPriceLoop() { platform::startThread(g_priceThread, priceLoop); }
+void startPriceLoop() {
+ platform::startThread(g_priceThread, [] {
+ priceLoop();
+ g_pricesEnded = true;
+ });
+}
+
+bool stopPriceLoop(uint32_t ms) {
+ g_stopPrices = true;
+ if (!g_priceThread.joinable()) return true;
+ // Its pauses check the flag every 300 ms; a request may take longer.
+ for (uint64_t start = platform::nowMs(); !g_pricesEnded && platform::nowMs() - start < ms;) platform::sleepMs(20);
+ if (!g_pricesEnded) return false;
+ g_priceThread.join();
+ return true;
+}
void setPriceMarket(const std::string& market, const std::string& language) {
std::lock_guard<std::mutex> lock(g_priceMutex);
diff --git a/src/app/shell.h b/src/app/shell.h
index 09655ce..cba9d16 100644
--- a/src/app/shell.h
+++ b/src/app/shell.h
@@ -2,8 +2,10 @@
// 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.
+// time like the backends: shell_ps5.cpp on the console, shell_desktop.cpp in
+// the desktop app (SDL3: the window's events, the browser), shell_null.cpp
+// for a desktop build without a window (psbox-headless). See
+// docs/multiplatform.md.
#pragma once
#include "app/settings.h"
@@ -19,12 +21,19 @@ 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);
+// Right after display::init(): the desktop app hands its window to the
+// input backend. False when the app can't run without the display that
+// failed (the desktop app has nothing to show then): it closes.
+bool afterDisplay(bool haveDisplay);
// 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 the app's window has the keyboard's focus (always on the PS5):
+// the mouse is only held for a game while it has.
+bool hasFocus();
// Whether this build installs an update itself; elsewhere a newer release
// is only noted in the log, never offered.
bool canSelfUpdate();
@@ -34,5 +43,18 @@ 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();
+// coreShutdown(), once the worker has stopped and before the backends
+// close (never on the PS5): the desktop app lets go of its input hooks.
+void beforeShutdown();
+
+// What kind of system this is, for what the screens say and offer.
+struct Caps {
+ bool console = false; // the PS5: "this console", the paths of its menus
+ bool openUrl = false; // openUrl() works: a link on screen opens in the browser
+ bool selfUpdate = false; // canSelfUpdate()
+};
+Caps caps();
+// Opens `url` in the system's browser; false where there is none (PS5).
+bool openUrl(const std::string& url);
} // namespace xc::app::shell
diff --git a/src/app/shell_null.cpp b/src/app/shell_null.cpp
index 2756842..664ebbe 100644
--- a/src/app/shell_null.cpp
+++ b/src/app/shell_null.cpp
@@ -19,6 +19,7 @@ void onQuit(int) { g_quit = true; }
void beforeSettings() {}
void beforeDisplay(const Settings&) {}
+bool afterDisplay(bool) { return true; }
std::vector<std::string> iconFontPaths() { return {}; }
bool pumpEvents() {
@@ -31,8 +32,12 @@ bool pumpEvents() {
return !g_quit;
}
+bool hasFocus() { return true; }
bool canSelfUpdate() { return false; }
bool isInstalledCopy(const std::string&) { return false; }
+void beforeShutdown() {}
+Caps caps() { return {false, false, false}; }
+bool openUrl(const std::string&) { return false; }
void restartOrExit() {
// Never asked (no update is installed here); closed as the PS5 does.
diff --git a/src/app/shell_ps5.cpp b/src/app/shell_ps5.cpp
index 26fe285..fe7cfce 100644
--- a/src/app/shell_ps5.cpp
+++ b/src/app/shell_ps5.cpp
@@ -43,6 +43,9 @@ void beforeDisplay(const Settings& settings) {
: display::canSwitchRefresh() ? "in games" : "on");
}
+// A display that didn't come up isn't the end here (as before): the app runs on.
+bool afterDisplay(bool) { return true; }
+
std::vector<std::string> iconFontPaths() {
const char* word = sceKernelGetFsSandboxRandomWord();
std::string sandbox = std::string("/") + (word ? word : "");
@@ -52,8 +55,14 @@ std::vector<std::string> iconFontPaths() {
// The system closes the app (from the home screen): nothing to read here.
bool pumpEvents() { return true; }
+bool hasFocus() { return true; }
bool canSelfUpdate() { return true; }
+// Never called: the PS5's loop doesn't end.
+void beforeShutdown() {}
+Caps caps() { return {true, false, true}; }
+// No browser to send a link to: the screens show a QR code instead.
+bool openUrl(const std::string&) { return false; }
bool isInstalledCopy(const std::string& dir) {
// /app0 is the folder the system started the app from.
diff --git a/src/app/worker.cpp b/src/app/worker.cpp
index 6a172c3..626c08b 100644
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@ -21,6 +21,8 @@
#include "xcloud/gssv.h"
#include "xcloud/regions.h"
+#include <chrono>
+#include <condition_variable>
#include <cstdlib>
#include <map>
#include <unistd.h>
@@ -678,6 +680,41 @@ void loadLibrary(xcloud::GssvClient& gssv) {
} // namespace
+namespace {
+
+// The worker's life, for closing: 0 not started, 1 running, 2 left its loop.
+std::mutex g_workerStateMutex;
+std::condition_variable g_workerStateCv;
+int g_workerState = 0;
+
+void setWorkerState(int state) {
+ {
+ std::lock_guard<std::mutex> lock(g_workerStateMutex);
+ g_workerState = state;
+ }
+ g_workerStateCv.notify_all();
+}
+
+} // namespace
+
+void startWorker() {
+ setWorkerState(1);
+ std::thread([] {
+ worker();
+ setWorkerState(2);
+ }).detach();
+}
+
+void requestQuit() {
+ g_quit = true;
+ g_cancel = true; // what the worker is doing (a stream, a sign-in waiting) ends
+}
+
+bool waitForWorker(uint32_t ms) {
+ std::unique_lock<std::mutex> lock(g_workerStateMutex);
+ return g_workerStateCv.wait_for(lock, std::chrono::milliseconds(ms), [] { return g_workerState != 1; });
+}
+
void worker() {
if (g_autoplay.title == "BENCH") {
platform::Thread t; // same big stack as the stream's video thread
@@ -704,10 +741,11 @@ void worker() {
for (;;) {
int cmd = g_command.exchange(kNone);
g_cancel = false;
+ if (g_quit) break; // closing (desktop): the command before it was cancelled
switch (cmd) {
case kSignIn:
signInAndLoad(am, gssv);
- loadConsoles(am, home); // empty when the sign-in failed
+ if (!g_quit) loadConsoles(am, home); // empty when the sign-in failed
break;
case kConsoles: loadConsoles(am, home); break;
case kUpdate: runUpdate(); break;
@@ -731,7 +769,7 @@ void worker() {
g_ui->setSubscription("");
XC_LOGI("signed out: library and its cache cleared");
signInAndLoad(am, gssv);
- loadConsoles(am, home);
+ if (!g_quit) loadConsoles(am, home);
break;
case kPlay: {
ui::GameTile tile;
@@ -780,7 +818,7 @@ void worker() {
g_ui->showHome(endedToast(result));
g_playingHome = false;
autoplayFinished(result);
- loadConsoles(am, home); // its state changed
+ if (!g_quit) loadConsoles(am, home); // its state changed
break;
}
bool automatic;
@@ -834,6 +872,10 @@ void worker() {
default: platform::sleepMs(50); break;
}
}
+ // Closing: the stream (if any) was stopped and its session closed by
+ // play() as it returned; the library's background loading ends too.
+ stopHydration();
+ XC_LOGI("worker: stopped");
}
} // namespace xc::app
diff --git a/src/display/display.h b/src/display/display.h
index 3abfcb7..2d64f7a 100644
--- a/src/display/display.h
+++ b/src/display/display.h
@@ -14,7 +14,8 @@ constexpr unsigned kHeight = 1080;
// The GPU (display/gpu.h: FSR upscaling to the 4K display) when `preferGpu`
// and it comes up, else the CPU path below. The backend is picked at link
-// time: display_ps5.cpp on the console, display_null.cpp (no screen) elsewhere.
+// time: display_ps5.cpp on the console, display_sdl.cpp in the desktop app,
+// display_null.cpp (no screen) for psbox-headless and the tests.
bool init(bool preferGpu = true);
void shutdown();
// Held by whoever draws a frame (UI thread or video thread).
@@ -25,6 +26,17 @@ void present();
// (multi-threaded). Call present() afterwards.
void drawRgba(const uint32_t* pixels);
+// Each pass of the main loop, on the menus and while streaming (main
+// thread). Where the frames are drawn by the main thread alone (the
+// desktop's SDL_Renderer), the newest one present() handed over (the video
+// thread's, with its overlay, or the menu) is uploaded and shown here. A
+// no-op where present() shows the frame itself (PS5, null).
+void pump();
+// The streaming loop's pause between passes (~120 Hz input): `ms`, as the
+// PS5 sleeps; the desktop wakes early for a new video frame or an input
+// event.
+void idleWait(uint32_t ms);
+
// Converts a BT.709 limited-range YUV 4:2:0 picture to the back buffer,
// scaled to the full screen (multi-threaded). Call present() afterwards.
// With two flips still queued it waits for a vblank, or, without `wait`,
diff --git a/src/display/display_null.cpp b/src/display/display_null.cpp
index 339e421..642ff3f 100644
--- a/src/display/display_null.cpp
+++ b/src/display/display_null.cpp
@@ -18,6 +18,8 @@ void shutdown() {}
void present() { platform::sleepMs(16); }
bool drawYuv420(const uint8_t*, const uint8_t*, const uint8_t*, int, int, int, int, int, bool) { return true; }
void drawRgba(const uint32_t*) {}
+void pump() {}
+void idleWait(uint32_t ms) { platform::sleepMs(ms); }
void setOverlay(const uint32_t*, int, int, int, int, uint8_t) {}
void setSharpness(int) {}
void setDeband(int) {}
diff --git a/src/display/display_ps5.cpp b/src/display/display_ps5.cpp
index 1e6eafd..2614804 100644
--- a/src/display/display_ps5.cpp
+++ b/src/display/display_ps5.cpp
@@ -524,6 +524,10 @@ bool bringUpTest(int frames) {
return ok;
}
+// present() shows each frame itself; the streaming loop sleeps as it always has.
+void pump() {}
+void idleWait(uint32_t ms) { platform::sleepMs(ms); }
+
uint64_t lastPresentId() { return gpu::ready() ? gpu::lastPresentId() : 0; }
bool lastShown(uint64_t& id, uint64_t& atUs) { return gpu::ready() && gpu::lastShown(id, atUs); }