Xbox Cloud Gaming app for PS5 Homebrew
C
psbox: the Linux desktop app on SDL3, with a self-test
Rafael Abud Ferreirabd70d4d6521f
diff --git a/CMakeLists.txt b/CMakeLists.txtindex c6d322c..3eed823 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -183,26 +183,51 @@ else()add_test(NAME unit COMMAND xcloud-tests)endif()-# --- Desktop input and sound on SDL3 (controllers, keyboard / mouse, audio) ----# The SDL backends of controller.h, kbm.h, input_ext.h, audio_out.h and-# audio_in.h, for the desktop app in place of the null ones (controller_null,-# kbm_null, audio_*_null: not both). Only where SDL3 is found and the desktop-# app is wanted: xcloud-cli, xcloud-tests and psbox-headless stay SDL-free.-if(NOT XCLOUD_PS5 AND (NOT DEFINED XCLOUD_DESKTOP_APP OR XCLOUD_DESKTOP_APP))- if(NOT TARGET SDL3::SDL3)- find_package(SDL3 CONFIG QUIET)+# --- The desktop app on SDL3 (psbox) ----------------------------------------+# cmake/deps/sdl3.cmake decides (XCLOUD_DESKTOP_APP); xcloud-cli, xcloud-tests+# and psbox-headless stay SDL-free either way.+if(NOT XCLOUD_PS5)+ include(cmake/deps/sdl3.cmake)+endif()+if(XC_DESKTOP_APP)+ # The SDL backends of controller.h, kbm.h, input_ext.h, audio_out.h and+ # audio_in.h, in place of the null ones (controller_null, kbm_null,+ # audio_*_null: not both).+ add_library(xcloud_backends_sdl_io OBJECT+ src/input/sdl_input.cpp+ src/input/controller_sdl.cpp+ src/input/kbm_sdl.cpp+ src/media/audio_out_sdl.cpp+ src/media/audio_in_sdl.cpp+ )+ target_link_libraries(xcloud_backends_sdl_io PUBLIC xcloud_core xcloud_media SDL3::SDL3)++ # The window, its renderer and events, the self-test; no hardware+ # decoder yet (FFmpeg decodes).+ add_library(xcloud_backends_desktop OBJECT+ src/display/display_sdl.cpp+ src/app/shell_desktop.cpp+ src/app/desktop_selftest.cpp+ src/media/hw_decoder_null.cpp+ )+ target_link_libraries(xcloud_backends_desktop PUBLIC xcloud_core xcloud_media xcloud_ui SDL3::SDL3)+ if(NOT MSVC)+ target_compile_options(xcloud_backends_sdl_io PRIVATE -Wall -Wextra -Wno-unused-parameter)+ target_compile_options(xcloud_backends_desktop PRIVATE -Wall -Wextra -Wno-unused-parameter)endif()- if(TARGET SDL3::SDL3)- add_library(xcloud_backends_sdl_io OBJECT- src/input/sdl_input.cpp- src/input/controller_sdl.cpp- src/input/kbm_sdl.cpp- src/media/audio_out_sdl.cpp- src/media/audio_in_sdl.cpp- )- target_link_libraries(xcloud_backends_sdl_io PUBLIC xcloud_core xcloud_media SDL3::SDL3)- if(NOT MSVC)- target_compile_options(xcloud_backends_sdl_io PRIVATE -Wall -Wextra -Wno-unused-parameter)- endif()++ # WIN32: a GUI app on Windows (SDL_main.h gives it its entry point).+ add_executable(psbox WIN32+ $<TARGET_OBJECTS:xcloud_appcore>+ src/app/desktop_main.cpp+ )+ target_link_libraries(psbox PRIVATE xcloud_backends_desktop xcloud_backends_sdl_io xcloud_stream xcloud_media+ xcloud_ui xc_ffmpeg datachannel-static SDL3::SDL3)+ if(NOT MSVC)+ target_compile_options(psbox PRIVATE -Wall -Wextra -Wno-unused-parameter)endif()+ # The fonts and certificates beside the executable (platform::assetDir()).+ add_custom_command(TARGET psbox POST_BUILD+ COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/assets" "$<TARGET_FILE_DIR:psbox>/assets"+ COMMENT "Copying assets/ beside psbox")endif()diff --git a/cmake/deps/sdl3.cmake b/cmake/deps/sdl3.cmakenew file mode 100644index 0000000..939e27d--- /dev/null+++ b/cmake/deps/sdl3.cmake@@ -0,0 +1,31 @@+# SPDX-License-Identifier: GPL-3.0-or-later+# Copyright (C) 2026 RafaelNGP+# SDL3 for the desktop app (psbox): the window, renderer, pads, keyboard,+# mouse and sound. XCLOUD_DESKTOP_APP:+# AUTO (default) the app is built when SDL3 (3.2 or newer) is found+# ON SDL3 is required: configuring fails without it+# OFF SDL is never looked for (psbox-headless, xcloud-cli and+# xcloud-tests never need it either way)+# Sets XC_DESKTOP_APP and, when on, the SDL3::SDL3 target.+set(XCLOUD_DESKTOP_APP AUTO CACHE STRING "Build the SDL3 desktop app psbox: AUTO, ON or OFF")+set_property(CACHE XCLOUD_DESKTOP_APP PROPERTY STRINGS AUTO ON OFF)++string(TOUPPER "${XCLOUD_DESKTOP_APP}" _xc_desktop)+set(XC_DESKTOP_APP OFF)+if(XCLOUD_PS5 OR _xc_desktop MATCHES "^(OFF|0|NO|FALSE|N)$")+ message(STATUS "Desktop app (psbox): off")+elseif(_xc_desktop MATCHES "^(ON|1|YES|TRUE|Y)$")+ find_package(SDL3 3.2 CONFIG REQUIRED)+ set(XC_DESKTOP_APP ON)+else()+ find_package(SDL3 3.2 CONFIG QUIET)+ if(TARGET SDL3::SDL3)+ set(XC_DESKTOP_APP ON)+ else()+ message(STATUS "Desktop app (psbox): SDL3 not found, not built (XCLOUD_DESKTOP_APP=ON to require it)")+ endif()+endif()+if(XC_DESKTOP_APP)+ message(STATUS "Desktop app (psbox): SDL3 ${SDL3_VERSION}")+endif()+unset(_xc_desktop)diff --git a/src/app/app_core.cpp b/src/app/app_core.cppindex b680efe..470d43c 100644--- a/src/app/app_core.cpp+++ b/src/app/app_core.cpp@@ -117,30 +117,6 @@ bool saveSettings(const ui::SettingsChoice& choice) {return languageChanged;}-// What the screens offer (ui::UiCaps): the pads' features (input_ext.h),-// the display's and the platform's. The PS5 offers every option as it-// always has: its pads are DualSense, and what its display can't honour at-// the moment does nothing there, as before (an upscaler on the CPU-// fallback; 120 Hz then decided at start-up).-ui::UiCaps uiCaps() {- const shell::Caps sc = shell::caps();- const display::DisplayCaps dc = display::caps();- const input::PadCaps pc = input::anyPadCaps();- ui::UiCaps c;- c.lightBar = pc.lightBar;- c.triggerRumble = pc.triggerRumble;- c.adaptiveTriggers = pc.adaptiveTriggers;- c.gyro = pc.gyro;- c.touchpad = pc.touchpad;- c.upscalers = sc.console || dc.upscalers;- c.sharpen = sc.console || dc.sharpen;- c.deband = sc.console || dc.deband;- c.highRefresh = sc.console || dc.highRefreshSwitch;- c.console = sc.console;- c.openUrl = sc.openUrl;- c.selfUpdate = sc.selfUpdate;- return c;-}// --- Input ---------------------------------------------------------------------@@ -221,6 +197,31 @@ std::unique_ptr<Core> g_core;} // namespace+// What the screens offer (ui::UiCaps): the pads' features (input_ext.h),+// the display's and the platform's. The PS5 offers every option as it+// always has: its pads are DualSense, and what its display can't honour at+// the moment does nothing there, as before (an upscaler on the CPU+// fallback; 120 Hz then decided at start-up).+ui::UiCaps uiCaps() {+ const shell::Caps sc = shell::caps();+ const display::DisplayCaps dc = display::caps();+ const input::PadCaps pc = input::anyPadCaps();+ ui::UiCaps c;+ c.lightBar = pc.lightBar;+ c.triggerRumble = pc.triggerRumble;+ c.adaptiveTriggers = pc.adaptiveTriggers;+ c.gyro = pc.gyro;+ c.touchpad = pc.touchpad;+ c.upscalers = sc.console || dc.upscalers;+ c.sharpen = sc.console || dc.sharpen;+ c.deband = sc.console || dc.deband;+ c.highRefresh = sc.console || dc.highRefreshSwitch;+ c.console = sc.console;+ c.openUrl = sc.openUrl;+ c.selfUpdate = sc.selfUpdate;+ return c;+}+bool coreStartup() {platform::init();log::setFile((platform::dataDir() + "/xcloud.log").c_str());diff --git a/src/app/app_core.h b/src/app/app_core.hindex 59a86f4..e3935e1 100644--- a/src/app/app_core.h+++ b/src/app/app_core.h@@ -6,6 +6,8 @@// backends it links (docs/multiplatform.md).#pragma once+#include "ui/app_ui.h"+namespace xc::app {// Everything up to the main loop, the worker thread started; false when the@@ -18,5 +20,8 @@ bool coreFrame();void coreShutdown();// The three in turn; the process's exit code.int runApp();+// What the screens offer here (the pads', display's and shell's+// capabilities): every option on the PS5.+ui::UiCaps uiCaps();} // namespace xc::appdiff --git a/src/app/desktop_main.cpp b/src/app/desktop_main.cppnew file mode 100644index 0000000..8110d4f--- /dev/null+++ b/src/app/desktop_main.cpp@@ -0,0 +1,59 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// psbox, the desktop app (SDL3): the app core (app_core.cpp) with the SDL+// display, input and sound backends and shell_desktop.cpp. SDL_main.h gives+// Windows its GUI entry point (M2); elsewhere this is main().+#include "app/app_core.h"+#include "app/desktop_selftest.h"+#include "display/display_sdl.h"++#include <SDL3/SDL.h>+#include <SDL3/SDL_main.h>++#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <string>++namespace {++void usage(std::FILE* to) {+ std::fprintf(to,+ "usage: psbox [--data-dir <dir>] [--fullscreen | --windowed] [--selftest <dir>]\n"+ " --data-dir <dir> sign-in, settings and caches there (default $XCLOUD_DATA_DIR,\n"+ " else $XDG_DATA_HOME/psbox)\n"+ " --fullscreen start fullscreen (F11 or Alt+Enter switches)\n"+ " --windowed start in a window (the default)\n"+ " --selftest <dir> check the window, screens, input and sound; screenshots in <dir>\n");+}++} // namespace++int main(int argc, char* argv[]) {+ std::string selftest;+ for (int i = 1; i < argc; ++i) {+ const char* a = argv[i];+ bool hasValue = i + 1 < argc;+ if (!std::strcmp(a, "--data-dir") && hasValue) {+ SDL_setenv_unsafe("XCLOUD_DATA_DIR", argv[++i], 1); // platform::dataDir() reads it+ } else if (!std::strcmp(a, "--fullscreen")) {+ xc::display::sdlStartFullscreen(true);+ } else if (!std::strcmp(a, "--windowed")) {+ xc::display::sdlStartFullscreen(false);+ } else if (!std::strcmp(a, "--selftest") && hasValue) {+ selftest = argv[++i];+ } else if (!std::strcmp(a, "--help") || !std::strcmp(a, "-h")) {+ usage(stdout);+ return 0;+ } else {+ std::fprintf(stderr, "psbox: unknown argument '%s'\n", a);+ usage(stderr);+ return 2;+ }+ }+ int code = selftest.empty() ? xc::app::runApp() : xc::app::desktopSelftest(selftest);+ // Not a return from main: the worker's threads may still run, and the+ // static destructors would free what they use (as on the PS5).+ std::fflush(nullptr);+ std::_Exit(code);+}diff --git a/src/app/desktop_selftest.cpp b/src/app/desktop_selftest.cppnew file mode 100644index 0000000..81732cb--- /dev/null+++ b/src/app/desktop_selftest.cpp@@ -0,0 +1,262 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// 'psbox --selftest <dir>' (desktop_selftest.h): the desktop app's own+// parts, each through the same calls the app makes, checked and saved as+// screenshots read back from the renderer. No account, no network: the data+// folder is <dir> unless XCLOUD_DATA_DIR says otherwise.+#include "app/desktop_selftest.h"++#include "app/app_core.h"+#include "app/shell.h"+#include "display/display.h"+#include "display/display_sdl.h"+#include "input/controller.h"+#include "input/input_ext.h"+#include "media/audio_in.h"+#include "media/audio_out.h"+#include "platform/platform.h"+#include "ui/app_ui.h"+#include "ui/canvas.h"+#include "ui/font.h"+#include "ui/image_cache.h"+#include "ui/stream_menu.h"+#include "util/log.h"++#include <SDL3/SDL.h>++#if defined(__GNUC__)+#pragma GCC diagnostic push+#pragma GCC diagnostic ignored "-Wmissing-field-initializers"+#endif+#define STB_IMAGE_WRITE_IMPLEMENTATION+#include "stb_image_write.h"+#if defined(__GNUC__)+#pragma GCC diagnostic pop+#endif++#include <algorithm>+#include <atomic>+#include <cstdio>+#include <cstdlib>+#include <filesystem>+#include <vector>++namespace xc::app {++namespace {++int g_failures = 0;++void check(bool ok, const char* what) {+ std::printf("selftest: %-52s %s\n", what, ok ? "ok" : "FAILED");+ std::fflush(stdout);+ if (!ok) ++g_failures;+}++struct Shot {+ std::vector<uint8_t> rgb;+ int w = 0, h = 0;+ const uint8_t* at(int x, int y) const { return &rgb[(static_cast<size_t>(y) * w + x) * 3]; }+};++// What the window shows now, read back and saved as <dir>/<name>.+bool screenshot(const std::string& dir, const char* name, Shot& shot) {+ display::pump();+ if (!display::readBackRgb(shot.rgb, shot.w, shot.h)) return false;+ std::string path = dir + "/" + name;+ return stbi_write_png(path.c_str(), shot.w, shot.h, 3, shot.rgb.data(), shot.w * 3) != 0;+}++// Not one flat colour (a blank or failed read back).+bool varied(const Shot& s) {+ if (s.rgb.empty()) return false;+ const uint8_t* first = s.rgb.data();+ size_t differing = 0;+ for (size_t i = 0; i + 2 < s.rgb.size(); i += 3 * 97)+ if (std::abs(s.rgb[i] - first[0]) + std::abs(s.rgb[i + 1] - first[1]) + std::abs(s.rgb[i + 2] - first[2]) > 24)+ ++differing;+ return differing > 100;+}++void drawCanvas(const ui::Canvas& c) {+ std::lock_guard<std::mutex> lock(display::frameMutex());+ display::drawRgba(c.data());+ display::present();+}++// SMPTE-like bars: white, yellow, cyan, green, magenta, red, blue, black.+constexpr uint8_t kBars[8][3] = {{235, 235, 235}, {235, 235, 16}, {16, 235, 235}, {16, 235, 16},+ {235, 16, 235}, {235, 16, 16}, {16, 16, 235}, {16, 16, 16}};++struct Yuv {+ int w = static_cast<int>(display::kWidth), h = static_cast<int>(display::kHeight);+ std::vector<uint8_t> y, u, v;+};++// The bars as a BT.709 limited-range 4:2:0 frame (what the decoder hands over).+Yuv colourBars() {+ Yuv f;+ f.y.resize(static_cast<size_t>(f.w) * f.h);+ f.u.resize(static_cast<size_t>(f.w / 2) * (f.h / 2));+ f.v.resize(f.u.size());+ uint8_t ys[8], us[8], vs[8];+ for (int b = 0; b < 8; ++b) {+ // The limited-range RGB above back to 0..1, then BT.709.+ double r = (kBars[b][0] - 16) / 219.0, g = (kBars[b][1] - 16) / 219.0, bl = (kBars[b][2] - 16) / 219.0;+ double yf = 0.2126 * r + 0.7152 * g + 0.0722 * bl;+ ys[b] = static_cast<uint8_t>(16 + 219 * yf + 0.5);+ us[b] = static_cast<uint8_t>(128 + 224 * (bl - yf) / 1.8556 + 0.5);+ vs[b] = static_cast<uint8_t>(128 + 224 * (r - yf) / 1.5748 + 0.5);+ }+ for (int yy = 0; yy < f.h; ++yy)+ for (int x = 0; x < f.w; ++x) f.y[static_cast<size_t>(yy) * f.w + x] = ys[x * 8 / f.w];+ for (int yy = 0; yy < f.h / 2; ++yy)+ for (int x = 0; x < f.w / 2; ++x) {+ f.u[static_cast<size_t>(yy) * (f.w / 2) + x] = us[x * 16 / f.w];+ f.v[static_cast<size_t>(yy) * (f.w / 2) + x] = vs[x * 16 / f.w];+ }+ return f;+}++void drawVideo(const Yuv& f) {+ std::lock_guard<std::mutex> lock(display::frameMutex());+ display::drawYuv420(f.y.data(), f.u.data(), f.v.data(), f.w, f.w / 2, f.w / 2, f.w, f.h, false);+ display::present();+}++// The bar's colour, full range (what the screen shows of the limited-range bars).+bool barMatches(const Shot& s, int bar, int y) {+ int x = bar * s.w / 8 + s.w / 16;+ const uint8_t* p = s.at(x, y * s.h / static_cast<int>(display::kHeight));+ for (int c = 0; c < 3; ++c) {+ int want = std::clamp((kBars[bar][c] - 16) * 255 / 219, 0, 255);+ if (std::abs(p[c] - want) > 24) return false;+ }+ return true;+}++} // namespace++int desktopSelftest(const std::string& dir) {+ std::error_code ec;+ std::filesystem::create_directories(dir, ec);+ if (!std::getenv("XCLOUD_DATA_DIR")) SDL_setenv_unsafe("XCLOUD_DATA_DIR", dir.c_str(), 1);+ platform::init();+ log::setFile((dir + "/selftest.log").c_str());+ XC_LOGI("=== psbox self-test ===");++ // SDL and the window, as the app brings them up.+ shell::beforeSettings();+ shell::beforeDisplay(Settings{});+ bool display = display::init(true);+ check(display, "window and renderer");+ if (!display) return 1;+ std::printf("selftest: SDL video driver %s, renderer %s\n", SDL_GetCurrentVideoDriver(), display::sdlRendererName());++ // Input: the window's hooks, the pads plugged in (none on a test machine).+ check(shell::afterDisplay(true), "input hooks on the window");+ input::init();+ shell::pumpEvents();+ int pads = 0;+ SDL_free(SDL_GetGamepads(&pads));+ input::PadCaps pc = input::padCaps(0);+ std::printf("selftest: %d gamepad(s); slot 0 kind %d\n", pads, static_cast<int>(pc.kind));+ check(pads > 0 || pc.kind == input::PadKind::None, "no gamepad -> slot 0 empty");+ input::kbmSetCaptured(true);+ input::kbmSetCaptured(false);++ // The screens, with this machine's capabilities.+ ui::Fonts fonts;+ check(fonts.load(platform::assetDir() + "/fonts"), "fonts (assets beside the executable)");+ ui::ImageCache images([] {}, 16u << 20);+ ui::AppUi ui(fonts, images);+ const ui::UiCaps caps = uiCaps();+ ui.setCaps(caps);+ ui.setSettings(ui::SettingsChoice{});+ ui.setUpdateState(XC_APP_VERSION, {}, false);+ check(!caps.console && caps.openUrl && !caps.selfUpdate && !caps.highRefresh && !caps.upscalers,+ "desktop capabilities");+ ui::Canvas canvas(static_cast<int>(display::kWidth), static_cast<int>(display::kHeight));++ Shot shot;+ ui.showSignIn("PSBX-TEST", "https://www.microsoft.com/link");+ ui.render(canvas, platform::nowMs());+ drawCanvas(canvas);+ check(screenshot(dir, "1-signin.png", shot) && varied(shot), "sign-in screen (1-signin.png)");++ ui.showHome();+ ui::NavInput nav;+ nav.options = true;+ nav.nowMs = platform::nowMs();+ ui.handle(nav);+ check(ui.screen() == ui::Screen::Settings, "Settings opens from the home screen");+ auto rows = ui::visibleSettingsRows(caps);+ bool hidden = std::none_of(rows.begin(), rows.end(), [&](const ui::SettingsRowPos& r) {+ return (r.row == 6 && !caps.lightBar) || (r.row == 9 && !caps.highRefresh) ||+ (r.row == 4 && !caps.triggerRumble && !caps.adaptiveTriggers);+ });+ std::printf("selftest: Settings shows %zu of %d rows\n", rows.size(), ui::kSettingRows);+ check(hidden && rows.size() < static_cast<size_t>(ui::kSettingRows), "Settings hides light bar / 120 Hz rows");+ ui.render(canvas, platform::nowMs());+ drawCanvas(canvas);+ check(screenshot(dir, "2-settings.png", shot) && varied(shot), "Settings screen (2-settings.png)");++ // A video frame through the mailbox, then under the game menu.+ Yuv bars = colourBars();+ drawVideo(bars);+ bool barsOk = screenshot(dir, "3-video.png", shot);+ for (int b = 0; b < 8 && barsOk; ++b) barsOk = barMatches(shot, b, 540);+ check(barsOk, "colour bars through drawYuv420 + pump (3-video.png)");+ check(display::lastPresentId() > 0, "present ids counted");++ ui::StreamMenu menu(fonts);+ menu.setCapabilities(caps);+ menu.open(0, false);+ ui::StreamInfo info;+ info.region = "selftest";+ info.width = bars.w, info.height = bars.h;+ ui::Canvas mc = menu.renderMenu(info);+ display::setOverlay(mc.data(), ui::StreamMenu::kMenuX, ui::StreamMenu::kMenuY, mc.width(), mc.height(), 235);+ drawVideo(bars);+ bool overlayOk = screenshot(dir, "4-overlay.png", shot);+ // Beside the menu the bars are untouched; under it they are covered.+ for (int b = 3; b < 8 && overlayOk; ++b) overlayOk = barMatches(shot, b, 540);+ overlayOk = overlayOk && !barMatches(shot, 1, 540);+ check(overlayOk, "game menu over the video (4-overlay.png)");+ display::setOverlay(nullptr, 0, 0, 0, 0, 0);++ // Sound out: 200 ms of a tone into the device, then closed.+ bool out = media::audioStart();+ if (out) {+ std::vector<float> tone(480 * 2);+ for (int chunk = 0, t = 0; chunk < 20; ++chunk) {+ for (size_t i = 0; i < 480; ++i, ++t) tone[i * 2] = tone[i * 2 + 1] = 0.1f * ((t / 55) % 2 ? 1.0f : -1.0f);+ media::audioPush(tone.data(), 480);+ platform::sleepMs(10);+ }+ media::audioStop();+ }+ check(out, "sound out: start, 200 ms, stop");+ // Sound in: the microphone opened and closed.+ {+ media::AudioIn mic;+ std::atomic<int> frames{0};+ bool in = mic.open([&](const int16_t*, size_t) { ++frames; });+ if (in) {+ platform::sleepMs(200);+ mic.close();+ }+ std::printf("selftest: microphone frames in 200 ms: %d\n", frames.load());+ check(in, "sound in: open, close");+ }++ shell::beforeShutdown();+ input::shutdown();+ display::shutdown();+ std::printf("selftest: %s (%d failed)\n", g_failures ? "FAILED" : "all passed", g_failures);+ XC_LOGI("self-test: %d failed", g_failures);+ log::setFile(nullptr);+ return g_failures ? 1 : 0;+}++} // namespace xc::appdiff --git a/src/app/desktop_selftest.h b/src/app/desktop_selftest.hnew file mode 100644index 0000000..b2b0146--- /dev/null+++ b/src/app/desktop_selftest.h@@ -0,0 +1,17 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// 'psbox --selftest <dir>': the desktop app's parts checked without an+// account or the network (SDL_VIDEO_DRIVER=offscreen and+// SDL_AUDIO_DRIVER=dummy work): the window and renderer, screenshots of the+// sign-in and Settings screens, a colour-bar video frame alone and under+// the game menu, the input hooks, the sound out and in.+#pragma once++#include <string>++namespace xc::app {++// Screenshots into `dir` (PNG); 0 when every check passed.+int desktopSelftest(const std::string& dir);++} // namespace xc::appdiff --git a/src/app/shell_desktop.cpp b/src/app/shell_desktop.cppnew file mode 100644index 0000000..148264c--- /dev/null+++ b/src/app/shell_desktop.cpp@@ -0,0 +1,110 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// app/shell.h for the desktop app (SDL3): SDL comes up before the display,+// the window (display_sdl.cpp) goes to the input backend, and each pass+// empties SDL's event queue: closing the window (or Ctrl+C, which SDL turns+// into a quit event) ends the app in order, F11 / Alt+Enter switch+// fullscreen, every event goes on to the input backend (pads, keyboard,+// mouse). Notices are toasts in the window; links open in the browser; no+// update is installed (Settings opens the release page).+#include "app/shell.h"++#include "display/display_sdl.h"+#include "input/input_ext.h"+#include "platform/toasts.h"+#include "util/log.h"++#include <SDL3/SDL.h>++#include <atomic>+#include <cstdio>+#include <cstdlib>++namespace xc::app::shell {++namespace {+bool g_quit = false; // main thread+std::atomic<bool> g_focus{true}; // the window has the keyboard+} // namespace++void beforeSettings() {+ platform::enableToasts(true); // platform::notify() -> a toast in the window+}++void beforeDisplay(const Settings&) {+ // The display, the pads and the sound start their own parts; the event+ // loop is ours.+ if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_GAMEPAD | SDL_INIT_AUDIO | SDL_INIT_EVENTS))+ XC_LOGE("SDL: %s", SDL_GetError());+}++bool afterDisplay(bool haveDisplay) {+ if (!haveDisplay) {+ XC_LOGE("no window could be opened: closing");+ return false;+ }+ input::sdlInputInit(display::sdlWindow());+ return true;+}++std::vector<std::string> iconFontPaths() { return {}; } // the UI draws its own icons++bool pumpEvents() {+ SDL_Event ev;+ while (SDL_PollEvent(&ev)) {+ switch (ev.type) {+ case SDL_EVENT_QUIT:+ case SDL_EVENT_WINDOW_CLOSE_REQUESTED:+ if (!g_quit) XC_LOGI("the window was closed");+ g_quit = true;+ break;+ case SDL_EVENT_WINDOW_FOCUS_LOST:+ g_focus = false;+ input::kbmSetCaptured(false); // the mouse is the system's again at once+ break;+ case SDL_EVENT_WINDOW_FOCUS_GAINED: g_focus = true; break;+ case SDL_EVENT_WINDOW_EXPOSED:+ case SDL_EVENT_WINDOW_RESTORED:+ case SDL_EVENT_WINDOW_SHOWN:+ case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:+ case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:+ display::sdlRepaint();+ break;+ case SDL_EVENT_KEY_DOWN:+ // F11 / Alt+Enter: fullscreen. Not passed on (Enter would accept).+ if (ev.key.key == SDLK_F11 || (ev.key.key == SDLK_RETURN && (ev.key.mod & SDL_KMOD_ALT))) {+ if (!ev.key.repeat) display::sdlToggleFullscreen();+ continue;+ }+ break;+ default: break;+ }+ input::sdlInputEvent(ev);+ }+ return !g_quit;+}++bool hasFocus() { return g_focus; }+bool canSelfUpdate() { return false; }+bool isInstalledCopy(const std::string&) { return false; }++void beforeShutdown() {+ input::kbmSetCaptured(false);+ input::sdlInputShutdown();+}++Caps caps() { return {false, true, false}; }++bool openUrl(const std::string& url) {+ if (SDL_OpenURL(url.c_str())) return true;+ XC_LOGW("browser: %s", SDL_GetError());+ return false;+}++void restartOrExit() {+ // Never asked (no update is installed here).+ std::fflush(nullptr);+ std::_Exit(0);+}++} // namespace xc::app::shelldiff --git a/src/display/display_sdl.cpp b/src/display/display_sdl.cppnew file mode 100644index 0000000..ea97039--- /dev/null+++ b/src/display/display_sdl.cpp@@ -0,0 +1,369 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// display.h on SDL3's renderer (the desktop app): a resizable window showing+// the app's 1920x1080 picture letterboxed. SDL's render calls are only made+// on the main thread, so the threads that draw (the menu on the main thread,+// the video thread while streaming) hand their picture over instead: draw+// into a back frame under frameMutex(), present() swaps it into a one-slot+// mailbox (the newest wins, nobody waits for the screen), and pump(), each+// pass of the main loop, uploads the mailbox's frame (YUV straight into an+// IYUV texture, the GPU converts it) with the overlay and presents it,+// paced by vsync. No upscalers, sharpening or block smoothing here: caps()+// says so and their setters do nothing.+#include "display/display.h"+#include "display/display_sdl.h"++#include "platform/platform.h"+#include "util/log.h"++#include <SDL3/SDL.h>++#include <atomic>+#include <chrono>+#include <condition_variable>+#include <cstring>+#include <utility>++namespace xc::display {++namespace {++enum class Kind { None, Menu, Video };++// A picture handed from a drawing thread to the main thread.+struct Frame {+ Kind kind = Kind::None;+ std::vector<uint32_t> rgba; // Menu: kWidth x kHeight, 0xAABBGGRR+ std::vector<uint8_t> y, u, v; // Video: the planes, rows packed+ int width = 0, height = 0; // Video+ uint64_t id = 0; // present()'s count when handed over+};++struct Overlay {+ std::vector<uint32_t> pixels;+ int x = 0, y = 0, w = 0, h = 0;+ uint8_t opacity = 0;+ bool on = false;+};++// Main thread only.+SDL_Window* g_window = nullptr;+SDL_Renderer* g_renderer = nullptr;+SDL_Texture* g_uiTex = nullptr;+SDL_Texture* g_videoTex = nullptr;+int g_videoW = 0, g_videoH = 0;+SDL_Texture* g_overlayTex = nullptr;+int g_overlayW = 0, g_overlayH = 0;+SDL_Texture* g_readTex = nullptr; // readBackRgb()'s target+SDL_ThreadID g_mainThread = 0;+bool g_startFullscreen = false;+bool g_shown = false; // the window shows from its first picture on+Frame g_front; // the picture on screen+Overlay g_overlayShown;+bool g_frontPending = false, g_overlayPending = false; // not uploaded yet++std::mutex g_frameMutex; // display.h's: held around a draw and its present()+Frame g_back; // being drawn (under g_frameMutex)++std::mutex g_mailboxMutex;+std::condition_variable g_mailboxCv;+Frame g_mailbox; // the newest picture handed over+bool g_mailboxFull = false;+uint64_t g_handed = 0;+std::atomic<uint64_t> g_lastHanded{0};++std::mutex g_overlayMutex;+Overlay g_overlay;+bool g_overlayChanged = false;++std::atomic<bool> g_repaint{false};+std::mutex g_shownMutex;+uint64_t g_shownId = 0, g_shownAtUs = 0; // the last video frame presented++bool onMainThread() { return g_mainThread != 0 && SDL_GetCurrentThreadID() == g_mainThread; }++// The video texture at the stream's size: BT.709 limited range, what the+// decoder gives (the GPU converts it).+bool videoTexture(int w, int h) {+ if (g_videoTex && g_videoW == w && g_videoH == h) return true;+ if (g_videoTex) SDL_DestroyTexture(g_videoTex);+ SDL_PropertiesID p = SDL_CreateProperties();+ SDL_SetNumberProperty(p, SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER, SDL_PIXELFORMAT_IYUV);+ SDL_SetNumberProperty(p, SDL_PROP_TEXTURE_CREATE_ACCESS_NUMBER, SDL_TEXTUREACCESS_STREAMING);+ SDL_SetNumberProperty(p, SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, w);+ SDL_SetNumberProperty(p, SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, h);+ SDL_SetNumberProperty(p, SDL_PROP_TEXTURE_CREATE_COLORSPACE_NUMBER, SDL_COLORSPACE_BT709_LIMITED);+ g_videoTex = SDL_CreateTextureWithProperties(g_renderer, p);+ SDL_DestroyProperties(p);+ if (!g_videoTex) {+ g_videoW = g_videoH = 0;+ XC_LOGE("display: video texture %dx%d: %s", w, h, SDL_GetError());+ return false;+ }+ SDL_SetTextureScaleMode(g_videoTex, SDL_SCALEMODE_LINEAR);+ g_videoW = w, g_videoH = h;+ XC_LOGI("display: video texture %dx%d (BT.709 limited)", w, h);+ return true;+}++// What pump() took from the mailbox and the overlay, into the textures.+void upload() {+ if (g_frontPending) {+ g_frontPending = false;+ if (g_front.kind == Kind::Menu) {+ SDL_UpdateTexture(g_uiTex, nullptr, g_front.rgba.data(), static_cast<int>(kWidth * 4));+ } else if (g_front.kind == Kind::Video && videoTexture(g_front.width, g_front.height)) {+ int cw = (g_front.width + 1) / 2;+ SDL_UpdateYUVTexture(g_videoTex, nullptr, g_front.y.data(), g_front.width, g_front.u.data(), cw,+ g_front.v.data(), cw);+ }+ }+ if (g_overlayPending) {+ g_overlayPending = false;+ const Overlay& o = g_overlayShown;+ if (o.on) {+ if (!g_overlayTex || g_overlayW != o.w || g_overlayH != o.h) {+ if (g_overlayTex) SDL_DestroyTexture(g_overlayTex);+ g_overlayTex = SDL_CreateTexture(g_renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, o.w, o.h);+ g_overlayW = g_overlayTex ? o.w : 0, g_overlayH = g_overlayTex ? o.h : 0;+ if (g_overlayTex) SDL_SetTextureBlendMode(g_overlayTex, SDL_BLENDMODE_BLEND);+ }+ if (g_overlayTex) {+ SDL_UpdateTexture(g_overlayTex, nullptr, o.pixels.data(), o.w * 4);+ SDL_SetTextureAlphaMod(g_overlayTex, o.opacity);+ }+ }+ }+}++// The picture on the current target, in the 1920x1080 logical space.+void renderScene() {+ SDL_SetRenderDrawColor(g_renderer, 0, 0, 0, 255);+ SDL_RenderClear(g_renderer);+ const SDL_FRect full{0, 0, static_cast<float>(kWidth), static_cast<float>(kHeight)};+ if (g_front.kind == Kind::Menu) {+ SDL_RenderTexture(g_renderer, g_uiTex, nullptr, &full);+ } else if (g_front.kind == Kind::Video && g_videoTex) {+ SDL_RenderTexture(g_renderer, g_videoTex, nullptr, &full);+ const Overlay& o = g_overlayShown;+ if (o.on && g_overlayTex) {+ SDL_FRect d{static_cast<float>(o.x), static_cast<float>(o.y), static_cast<float>(o.w), static_cast<float>(o.h)};+ SDL_RenderTexture(g_renderer, g_overlayTex, nullptr, &d);+ }+ }+}++} // namespace++void sdlStartFullscreen(bool on) { g_startFullscreen = on; }+SDL_Window* sdlWindow() { return g_window; }+const char* sdlRendererName() { return g_renderer ? SDL_GetRendererName(g_renderer) : ""; }+void sdlRepaint() { g_repaint = true; }++void sdlToggleFullscreen() {+ if (!g_window) return;+ bool full = (SDL_GetWindowFlags(g_window) & SDL_WINDOW_FULLSCREEN) != 0;+ if (!SDL_SetWindowFullscreen(g_window, !full)) XC_LOGW("display: fullscreen: %s", SDL_GetError());+ XC_LOGI("display: %s", full ? "windowed" : "fullscreen");+ g_repaint = true;+}++std::mutex& frameMutex() { return g_frameMutex; }++bool init(bool) {+ if (!SDL_InitSubSystem(SDL_INIT_VIDEO)) {+ XC_LOGE("display: SDL video: %s", SDL_GetError());+ return false;+ }+ g_mainThread = SDL_GetCurrentThreadID();+ SDL_WindowFlags flags = SDL_WINDOW_RESIZABLE | SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_HIDDEN;+ if (g_startFullscreen) flags |= SDL_WINDOW_FULLSCREEN;+ g_window = SDL_CreateWindow("PSBox Cloud Gaming", 1600, 900, flags);+ if (!g_window) {+ XC_LOGE("display: window: %s", SDL_GetError());+ SDL_QuitSubSystem(SDL_INIT_VIDEO);+ return false;+ }+ SDL_SetWindowMinimumSize(g_window, 640, 360);+ g_renderer = SDL_CreateRenderer(g_window, nullptr);+ if (!g_renderer) {+ XC_LOGE("display: renderer: %s", SDL_GetError());+ shutdown();+ return false;+ }+ if (!SDL_SetRenderVSync(g_renderer, 1)) XC_LOGW("display: no vsync (%s)", SDL_GetError());+ SDL_SetRenderLogicalPresentation(g_renderer, kWidth, kHeight, SDL_LOGICAL_PRESENTATION_LETTERBOX);+ g_uiTex = SDL_CreateTexture(g_renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, kWidth, kHeight);+ if (!g_uiTex) {+ XC_LOGE("display: UI texture: %s", SDL_GetError());+ shutdown();+ return false;+ }+ SDL_SetTextureScaleMode(g_uiTex, SDL_SCALEMODE_LINEAR);+ XC_LOGI("display: SDL %d.%d.%d, video driver %s, renderer %s%s", SDL_VERSIONNUM_MAJOR(SDL_GetVersion()),+ SDL_VERSIONNUM_MINOR(SDL_GetVersion()), SDL_VERSIONNUM_MICRO(SDL_GetVersion()), SDL_GetCurrentVideoDriver(),+ SDL_GetRendererName(g_renderer), g_startFullscreen ? ", fullscreen" : "");+ return true;+}++void shutdown() {+ if (!g_window) return;+ for (SDL_Texture** t : {&g_uiTex, &g_videoTex, &g_overlayTex, &g_readTex})+ if (*t) SDL_DestroyTexture(*t), *t = nullptr;+ if (g_renderer) SDL_DestroyRenderer(g_renderer), g_renderer = nullptr;+ SDL_DestroyWindow(g_window);+ g_window = nullptr;+ g_videoW = g_videoH = g_overlayW = g_overlayH = 0;+ SDL_QuitSubSystem(SDL_INIT_VIDEO);+}++void drawRgba(const uint32_t* pixels) {+ g_back.kind = Kind::Menu;+ g_back.rgba.assign(pixels, pixels + static_cast<size_t>(kWidth) * kHeight);+}++bool drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v, int strideY, int strideU, int strideV,+ int width, int height, bool) {+ // Never waits for the screen: the mailbox keeps the newest frame.+ if (width <= 0 || height <= 0) return false;+ const int cw = (width + 1) / 2, ch = (height + 1) / 2;+ g_back.kind = Kind::Video;+ g_back.width = width, g_back.height = height;+ g_back.y.resize(static_cast<size_t>(width) * height);+ g_back.u.resize(static_cast<size_t>(cw) * ch);+ g_back.v.resize(static_cast<size_t>(cw) * ch);+ for (int r = 0; r < height; ++r)+ std::memcpy(&g_back.y[static_cast<size_t>(r) * width], y + static_cast<size_t>(r) * strideY, width);+ for (int r = 0; r < ch; ++r) {+ std::memcpy(&g_back.u[static_cast<size_t>(r) * cw], u + static_cast<size_t>(r) * strideU, cw);+ std::memcpy(&g_back.v[static_cast<size_t>(r) * cw], v + static_cast<size_t>(r) * strideV, cw);+ }+ return true;+}++void present() {+ std::lock_guard<std::mutex> lock(g_mailboxMutex);+ if (g_back.kind == Kind::None) return;+ g_back.id = ++g_handed;+ g_lastHanded = g_handed;+ std::swap(g_back, g_mailbox); // a frame pump() didn't take is dropped+ g_back.kind = Kind::None; // its buffers kept for the next draw+ g_mailboxFull = true;+ g_mailboxCv.notify_all();+}++void pump() {+ if (!g_renderer || !onMainThread()) return;+ {+ std::lock_guard<std::mutex> lock(g_mailboxMutex);+ if (g_mailboxFull) {+ std::swap(g_front, g_mailbox);+ g_mailboxFull = false;+ g_frontPending = true;+ }+ }+ {+ std::lock_guard<std::mutex> lock(g_overlayMutex);+ if (g_overlayChanged) {+ std::swap(g_overlayShown, g_overlay);+ g_overlayChanged = false;+ g_overlayPending = true;+ }+ }+ // Minimized or covered: nothing drawn, the mailbox still emptied (the+ // newest frame goes up once the window shows again).+ if (g_shown && (SDL_GetWindowFlags(g_window) & (SDL_WINDOW_MINIMIZED | SDL_WINDOW_OCCLUDED))) return;+ bool repaint = g_repaint.exchange(false);+ if (!g_frontPending && !g_overlayPending && !repaint) return;+ if (g_front.kind == Kind::None) return;+ upload();+ renderScene();+ if (!g_shown) {+ SDL_ShowWindow(g_window);+ g_shown = true;+ }+ SDL_RenderPresent(g_renderer);+ if (g_front.kind == Kind::Video) {+ std::lock_guard<std::mutex> lock(g_shownMutex);+ g_shownId = g_front.id;+ g_shownAtUs = platform::nowUs();+ }+}++void idleWait(uint32_t ms) {+ std::unique_lock<std::mutex> lock(g_mailboxMutex);+ g_mailboxCv.wait_for(lock, std::chrono::milliseconds(ms), [] { return g_mailboxFull; });+}++void setOverlay(const uint32_t* pixels, int x, int y, int w, int h, uint8_t opacity) {+ Overlay next;+ if (pixels && w > 0 && h > 0) {+ next.pixels.assign(pixels, pixels + static_cast<size_t>(w) * h);+ next.x = x, next.y = y, next.w = w, next.h = h;+ next.opacity = opacity;+ next.on = true;+ }+ std::lock_guard<std::mutex> lock(g_overlayMutex);+ g_overlay = std::move(next);+ g_overlayChanged = true;+ g_mailboxCv.notify_all();+}++void setSharpness(int) {}+void setDeband(int) {}+void setUpscaler(int) {}+void setRestore(bool) {}+DisplayCaps caps() {+ DisplayCaps c;+ c.presentTiming = true; // the frame handed over, and when pump() presented it+ return c;+}+void setSwapImages(int) {}+void setPresentWait(bool) {}+bool setHighRefresh(bool) { return false; }+bool canSwitchRefresh() { return false; }+bool bringUpTest(int) {+ XC_LOGW("display: vktest is the PS5's GPU check");+ return false;+}++uint64_t lastPresentId() { return g_lastHanded; }++bool lastShown(uint64_t& id, uint64_t& atUs) {+ std::lock_guard<std::mutex> lock(g_shownMutex);+ if (!g_shownId) return false;+ id = g_shownId, atUs = g_shownAtUs;+ return true;+}++bool readBackRgb(std::vector<uint8_t>& rgb, int& width, int& height) {+ // The renderer is the main thread's: the video thread's snapshots get nothing.+ if (!g_renderer || !onMainThread() || g_front.kind == Kind::None) return false;+ upload();+ if (!g_readTex)+ g_readTex = SDL_CreateTexture(g_renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, kWidth, kHeight);+ if (!g_readTex || !SDL_SetRenderTarget(g_renderer, g_readTex)) {+ XC_LOGW("display: read back: %s", SDL_GetError());+ return false;+ }+ renderScene();+ SDL_Surface* read = SDL_RenderReadPixels(g_renderer, nullptr);+ SDL_SetRenderTarget(g_renderer, nullptr);+ g_repaint = true; // the window's picture drawn again at the next pump()+ if (!read) {+ XC_LOGW("display: read back: %s", SDL_GetError());+ return false;+ }+ SDL_Surface* conv = SDL_ConvertSurface(read, SDL_PIXELFORMAT_RGB24);+ SDL_DestroySurface(read);+ if (!conv) return false;+ width = conv->w, height = conv->h;+ rgb.resize(static_cast<size_t>(width) * height * 3);+ for (int r = 0; r < height; ++r)+ std::memcpy(&rgb[static_cast<size_t>(r) * width * 3], static_cast<const uint8_t*>(conv->pixels) + r * conv->pitch,+ static_cast<size_t>(width) * 3);+ SDL_DestroySurface(conv);+ return true;+}++} // namespace xc::displaydiff --git a/src/display/display_sdl.h b/src/display/display_sdl.hnew file mode 100644index 0000000..46a98a6--- /dev/null+++ b/src/display/display_sdl.h@@ -0,0 +1,23 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// Between display_sdl.cpp (display.h on SDL3's renderer) and the desktop+// shell and its self-test: the window they share. Main thread only.+#pragma once++struct SDL_Window;++namespace xc::display {++// Before init(): the window opens fullscreen (desktop resolution) or not.+void sdlStartFullscreen(bool on);+// The app's window once init() made it; null before (or without one).+SDL_Window* sdlWindow();+// The renderer's name ("vulkan", "opengl", "software"...), for the log.+const char* sdlRendererName();+// The window was resized, shown again or uncovered: the last picture is+// presented again at the next pump().+void sdlRepaint();+// F11 / Alt+Enter: fullscreen on or off.+void sdlToggleFullscreen();++} // namespace xc::display