Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

In-game menu, PS5 system keyboard for game text fields, stream tiers mid-session

Rafael Abud Ferreira59dd736e07e3
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 2e8761f..2e3a2d9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -63,6 +63,7 @@ add_library(xcloud_ui STATIC
src/ui/font.cpp
src/ui/image_cache.cpp
src/ui/app_ui.cpp
+ src/ui/stream_menu.cpp
src/ui/brand.cpp
src/app/library.cpp
src/app/settings.cpp
@@ -72,7 +73,7 @@ target_include_directories(xcloud_ui PUBLIC extern/stb extern/qrcodegen)
target_link_libraries(xcloud_ui PUBLIC xcloud_core)
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)
+ 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.
add_library(xcloud_app STATIC
diff --git a/src/app/cli_main.cpp b/src/app/cli_main.cpp
index fc044a0..035a7af 100644
--- a/src/app/cli_main.cpp
+++ b/src/app/cli_main.cpp
@@ -26,6 +26,7 @@
#include "util/log.h"
#include "ui/app_ui.h"
#include "ui/brand.h"
+#include "ui/stream_menu.h"
#include "ui/strings.h"
#include "xcloud/gssv.h"
#include "xcloud/prices.h"
@@ -589,6 +590,55 @@ int main(int argc, char** argv) {
press([](ui::NavInput& n) { n.accept = true; });
save("settings_resolution");
return 0;
+ } else if (cmd == "ui-menu" && argi < argc) {
+ // Offline: the in-game menu and the statistics line over a made-up
+ // game picture, blended as display::setOverlay() does.
+ ui::Fonts fonts;
+ if (!fonts.load("assets/fonts")) return 1;
+ ui::StreamMenu menu(fonts);
+ ui::StreamInfo info;
+ info.region = "Brazil South";
+ info.rttMs = 23;
+ info.fps = 60;
+ info.mbps = 12.4;
+ info.lossPct = 0.2;
+ info.decodeMs = 4.1;
+ info.width = 1920;
+ info.height = 1080;
+ auto save = [&](const std::string& name, const ui::Canvas& over, int ox, int oy, int alpha) {
+ ui::Canvas frame(1920, 1080);
+ frame.gradientH({0, 0, 1920, 1080}, ui::rgba(40, 90, 160), ui::rgba(200, 120, 40));
+ uint32_t* px = frame.data();
+ for (int y = 0; y < over.height(); ++y)
+ for (int x = 0; x < over.width(); ++x) {
+ uint32_t& d = px[(oy + y) * 1920 + ox + x];
+ uint32_t o = over.data()[y * over.width() + x];
+ uint32_t out = 0xFF000000u;
+ for (int sh = 0; sh < 24; sh += 8)
+ out |= ((((o >> sh) & 0xFF) * alpha + ((d >> sh) & 0xFF) * (255 - alpha)) / 255) << sh;
+ d = out;
+ }
+ std::string path = std::string(argv[argi]) + "/" + name + ".png";
+ stbi_write_png(path.c_str(), 1920, 1080, 4, frame.data(), 1920 * 4);
+ std::printf("wrote %s\n", path.c_str());
+ };
+ menu.open(0, true);
+ save("menu", menu.renderMenu(info), ui::StreamMenu::kMenuX, ui::StreamMenu::kMenuY, 235);
+ ui::NavInput n;
+ n.down = true;
+ menu.handle(n);
+ menu.handle(n);
+ n = {};
+ n.right = true;
+ menu.handle(n); // 1080p -> 1440p
+ n = {};
+ n.accept = true;
+ menu.handle(n);
+ save("menu_resolution", menu.renderMenu(info), ui::StreamMenu::kMenuX, ui::StreamMenu::kMenuY, 235);
+ save("stats", menu.renderStats(info), ui::StreamMenu::kStatsX, ui::StreamMenu::kStatsY, 200);
+ ui::setLanguage(ui::Language::PortugueseBR);
+ save("menu_pt", menu.renderMenu(info), ui::StreamMenu::kMenuX, ui::StreamMenu::kMenuY, 235);
+ return 0;
} else if (cmd == "ui-badges" && argi < argc) {
// Offline: "Your games" with every badge, hiding, sorting and the
// search filters, with made-up games. PNGs into the given directory.
diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cpp
index 4ae78b4..93b259a 100644
--- a/src/app/ps5_main.cpp
+++ b/src/app/ps5_main.cpp
@@ -15,6 +15,7 @@
#include "net/http.h"
#include "platform/platform.h"
#include "ui/app_ui.h"
+#include "ui/stream_menu.h"
#include "ui/strings.h"
#include "util/json.h"
#include "util/log.h"
@@ -70,13 +71,63 @@ void stopHydration() {
std::mutex g_playerMutex;
app::StreamPlayer* g_player = nullptr;
+// The stream's numbers for the in-game menu, refreshed every second by the
+// worker; the sequence number tells the main thread something changed.
+std::mutex g_infoMutex;
+ui::StreamInfo g_streamInfo;
+std::atomic<uint32_t> g_infoSeq{0};
+
+// The console keyboard answering a game's text field (main thread): the
+// request it answers, and the stream that asked.
+std::string g_keyboardFor;
+const app::StreamPlayer* g_keyboardPlayer = nullptr;
+
+platform::KeyboardKind keyboardKind(int inputScope) {
+ switch (inputScope) {
+ case 1: return platform::KeyboardKind::Url;
+ case 5: return platform::KeyboardKind::Email;
+ case 29:
+ case 32: return platform::KeyboardKind::Number;
+ case 31: return platform::KeyboardKind::Password;
+ default: return platform::KeyboardKind::Text;
+ }
+}
+
+// Opens the keyboard for the game's next text request and sends back what
+// was typed. `player` null: the stream is gone, a keyboard still up is
+// closed by the player and its text dropped.
+void updateTextInput(app::StreamPlayer* player) {
+ if (!g_keyboardFor.empty()) {
+ std::string text;
+ platform::KeyboardStatus st = platform::pollSystemKeyboard(text);
+ if (st == platform::KeyboardStatus::Open) return;
+ if (player && player == g_keyboardPlayer)
+ player->answerTextInput(g_keyboardFor, st == platform::KeyboardStatus::Accepted, text);
+ g_keyboardFor.clear();
+ g_keyboardPlayer = nullptr;
+ return;
+ }
+ stream::TextInputRequest req;
+ if (!player || !player->takeTextInput(req)) return;
+ std::string title = req.title.empty() ? req.description : req.title;
+ size_t max = req.maxLength > 0 ? static_cast<size_t>(req.maxLength) : 256;
+ if (platform::openSystemKeyboard(title, req.defaultText, max, keyboardKind(req.inputScope))) {
+ g_keyboardFor = req.id;
+ g_keyboardPlayer = player;
+ } else {
+ player->answerTextInput(req.id, false, std::string());
+ }
+}
+
// --- Unattended test mode (tools/ps5/autotest.sh) ----------------------------
// <dataDir>/autoplay.txt holds "<titleId> <seconds> [option]". The app signs
// in, plays that title for that long (pressing A at 15 s and 20 s), saves
// decoded frames and logs "AUTOPLAY END". Options, comma-separated: nosimd,
// dump, repeat, idle (no A presses), threads=N (H.264 decoder threads),
// rumbletest (rumbles the pad for 1.5 s at start), detailtest (opens a game to
-// buy far down the list instead of playing, saves detail.ppm).
+// buy far down the list instead of playing, saves detail.ppm), imetest (opens
+// the system keyboard on the home screen), menutest (in the game: the menu,
+// 720p, back to 1080p).
// The title "BENCH" decodes <dataDir>/sample.h264 instead.
std::string g_autoplayTitle;
@@ -86,6 +137,8 @@ int g_autoplayRuns = 1;
bool g_autoplayIdle = false;
bool g_autoplayDetailTest = false; // open a game to buy far down the list, save its page
bool g_autoplayLibraryTest = false; // open "Your games", save it at 4 s and 25 s
+bool g_autoplayImeTest = false; // open the system keyboard on the home screen
+bool g_autoplayMenuTest = false; // in the game: open the menu, switch to 720p
int g_decodeThreads = 1;
std::atomic<bool> g_syntheticA{false};
@@ -109,6 +162,8 @@ void loadAutoplay() {
if (opt == "rumbletest") input::setRumble(200, 200, 1500);
if (opt == "detailtest") g_autoplayDetailTest = true;
if (opt == "librarytest") g_autoplayLibraryTest = true;
+ if (opt == "imetest") g_autoplayImeTest = true;
+ if (opt == "menutest") g_autoplayMenuTest = true;
if (opt.rfind("threads=", 0) == 0) g_decodeThreads = std::atoi(opt.c_str() + 8);
}
g_autoplayTitle = title;
@@ -184,6 +239,7 @@ std::string stream(xcloud::GssvClient& gssv) {
bool snapshot1 = false, snapshot2 = false;
bool autoplayDone = false;
int bestRtt = -1; // lowest round trip seen: the region's latency
+ app::StreamPlayer::Stats last{};
while (player.running() && !g_cancel) {
uint64_t elapsed = platform::nowMs() - started;
if (!g_autoplayTitle.empty()) {
@@ -209,7 +265,7 @@ std::string stream(xcloud::GssvClient& gssv) {
XC_LOGI("stream: %llu frames, %llu decoded, %llu skipped, %llu failed, %llu resets, %llu kf req, "
"%llu queued, %llu audio; rtp %llu pkts, %llu lost, %llu recovered, %llu nacks, "
"%llu frames dropped; %llu kbps (remb %llu); %llu rumble; decode %.1f/%.1f ms, draw %.1f/%.1f ms, %llu late; "
- "rtt %d ms",
+ "rtt %d ms; %dx%d",
static_cast<unsigned long long>(st.videoFrames), static_cast<unsigned long long>(st.decodedFrames),
static_cast<unsigned long long>(st.droppedFrames), static_cast<unsigned long long>(st.decodeFailures),
static_cast<unsigned long long>(st.queueResets), static_cast<unsigned long long>(st.keyframeRequests),
@@ -219,8 +275,24 @@ std::string stream(xcloud::GssvClient& gssv) {
static_cast<unsigned long long>(st.rtpDroppedFrames), static_cast<unsigned long long>(st.rtpKbps),
static_cast<unsigned long long>(st.rembKbps), static_cast<unsigned long long>(st.vibrations),
st.decodeAvgUs / 1000.0, st.decodeMaxUs / 1000.0, st.drawAvgUs / 1000.0, st.drawMaxUs / 1000.0,
- static_cast<unsigned long long>(st.lateFrames), st.rttMs);
+ static_cast<unsigned long long>(st.lateFrames), st.rttMs, st.width, st.height);
if (st.rttMs > 0 && (bestRtt < 0 || st.rttMs < bestRtt)) bestRtt = st.rttMs;
+ {
+ ui::StreamInfo info;
+ info.region = ui::prettyRegion(gssv.region().name);
+ info.rttMs = st.rttMs;
+ info.fps = static_cast<double>(st.decodedFrames - last.decodedFrames - (st.droppedFrames - last.droppedFrames));
+ info.mbps = st.rtpKbps / 1000.0;
+ uint64_t lost = st.rtpLost - last.rtpLost, got = st.rtpPackets - last.rtpPackets;
+ info.lossPct = got + lost ? 100.0 * lost / (got + lost) : 0;
+ info.decodeMs = st.decodeAvgUs / 1000.0;
+ info.width = st.width;
+ info.height = st.height;
+ std::lock_guard<std::mutex> lock(g_infoMutex);
+ g_streamInfo = info;
+ ++g_infoSeq;
+ }
+ last = st;
}
platform::sleepMs(100);
}
@@ -492,7 +564,8 @@ void loadLibrary(xcloud::GssvClient& gssv) {
library->loadPlatforms(xblAuth, changed, &g_stopHydration);
library->hydrate(changed, &g_stopHydration);
});
- if (!g_autoplayTitle.empty() && g_autoplayTitle != "BENCH" && !g_autoplayDetailTest && !g_autoplayLibraryTest) {
+ if (!g_autoplayTitle.empty() && g_autoplayTitle != "BENCH" && !g_autoplayDetailTest && !g_autoplayLibraryTest &&
+ !g_autoplayImeTest) {
platform::sleepMs(6000); // leave the home screen up for ui.ppm
ui::GameTile tile;
tile.titleId = g_autoplayTitle;
@@ -656,7 +729,13 @@ int main(int argc, char** argv) {
// Never return from main: the app is closed from the home screen.
input::ControllerState prev{}, pad{};
Repeater up, down, left, right;
- uint64_t exitHeldSince = 0;
+ // The in-game menu and what is laid over the game.
+ ui::StreamMenu menu(fonts);
+ const app::StreamPlayer* overlayPlayer = nullptr;
+ int streamResolution = 0; // as SettingsChoice::resolution
+ bool showStats = false, overlayShown = false;
+ bool padReleased = true; // false from the menu/keyboard until the buttons are let go
+ uint32_t overlaySeq = 0; // g_infoSeq + 1 when drawn; 0 = redraw
uint64_t homeSince = 0, launchSince = 0;
bool uiSaved = false, launchSaved = false;
for (;;) {
@@ -664,27 +743,7 @@ int main(int argc, char** argv) {
// Autoplay runs unattended: the physical pad must not interfere.
if (!g_autoplayTitle.empty()) pad = input::ControllerState{};
uint64_t now = platform::nowMs();
-
- if (g_ui->screen() == ui::Screen::Streaming) {
- {
- std::lock_guard<std::mutex> lock(g_playerMutex);
- if (g_player) {
- input::ControllerState sent = pad;
- if (g_syntheticA) sent.btnA = true;
- g_player->sendInput(sent);
- }
- }
- // OPTIONS + TOUCHPAD held for a second leaves the game.
- if (pad.btnOptions && pad.btnTouchpad) {
- if (!exitHeldSince) exitHeldSince = now;
- if (now - exitHeldSince > 1000) g_cancel = true;
- } else {
- exitHeldSince = 0;
- }
- prev = pad;
- platform::sleepMs(8); // ~120 Hz input
- continue;
- }
+ if (!g_keyboardFor.empty() && g_ui->screen() != ui::Screen::Streaming) updateTextInput(nullptr);
ui::NavInput nav;
nav.up = up.update(pad.dpadUp || pad.leftStickY < -0.6f, now);
@@ -703,7 +762,105 @@ int main(int argc, char** argv) {
nav.r2 = pad.triggerR2 > 0.5f && prev.triggerR2 <= 0.5f;
nav.touchpad = pad.btnTouchpad;
nav.nowMs = now;
+ bool menuCombo = pad.btnOptions && pad.btnTouchpad && !(prev.btnOptions && prev.btnTouchpad);
prev = pad;
+ if (g_autoplayMenuTest && g_ui->screen() == ui::Screen::Streaming) {
+ // Menu, down twice to the resolution, left to 720p, accept; at
+ // 35 s right (back to 1080p) and accept.
+ static uint64_t since = 0;
+ static int step = 0;
+ if (!since) since = now;
+ const uint64_t at[] = {12000, 13000, 13500, 14000, 14500, 35000, 35500};
+ if (step < 7 && now - since >= at[step]) {
+ nav = ui::NavInput{};
+ if (step == 0) menuCombo = true;
+ if (step == 1 || step == 2) nav.down = true;
+ if (step == 3) nav.left = true;
+ if (step == 4 || step == 6) nav.accept = true;
+ if (step == 5) nav.right = true;
+ XC_LOGI("autoplay: menu step %d", step);
+ ++step;
+ }
+ }
+
+ if (g_ui->screen() == ui::Screen::Streaming) {
+ std::lock_guard<std::mutex> lock(g_playerMutex);
+ if (g_player != overlayPlayer) { // a new stream
+ overlayPlayer = g_player;
+ menu.close();
+ std::lock_guard<std::mutex> settingsLock(g_settingsMutex);
+ streamResolution = g_settings.resolution == "720p" ? 1 : g_settings.resolution == "1440p" ? 2 : 0;
+ showStats = g_settings.streamStats;
+ overlaySeq = 0;
+ }
+ if (g_player) {
+ updateTextInput(g_player);
+ // OPTIONS + TOUCHPAD opens the menu (and closes it again).
+ bool wasOpen = menu.isOpen();
+ if (!wasOpen && menuCombo && g_keyboardFor.empty()) {
+ menu.open(streamResolution, showStats);
+ overlaySeq = 0;
+ } else if (wasOpen) {
+ switch (menu.handle(nav)) {
+ case ui::MenuAction::Leave: g_cancel = true; break;
+ case ui::MenuAction::Refresh: g_player->requestKeyframe(); break;
+ case ui::MenuAction::Resolution:
+ streamResolution = menu.resolution();
+ g_player->requestResolution(streamResolution == 1 ? "720HQ"
+ : streamResolution == 2 ? "1440"
+ : "1080HQ");
+ break;
+ case ui::MenuAction::Stats: {
+ showStats = menu.statsOn();
+ std::lock_guard<std::mutex> settingsLock(g_settingsMutex);
+ g_settings.streamStats = showStats;
+ g_settings.save(settingsPath());
+ break;
+ }
+ default: break;
+ }
+ overlaySeq = 0;
+ }
+ input::ControllerState sent = pad;
+ if (g_syntheticA) sent.btnA = true;
+ // The menu and the keyboard have the pad while they are up,
+ // and the buttons that closed them until they are let go.
+ bool held = pad.dpadUp || pad.dpadDown || pad.dpadLeft || pad.dpadRight || pad.btnA || pad.btnB ||
+ pad.btnX || pad.btnY || pad.btnOptions || pad.btnTouchpad;
+ if (menu.isOpen() || !g_keyboardFor.empty()) padReleased = false;
+ else if (!held) padReleased = true;
+ if (!padReleased || menuCombo) sent = input::ControllerState{};
+ g_player->sendInput(sent);
+ }
+ // The overlay: the menu, else the statistics line, redrawn when
+ // the numbers or the menu change.
+ uint32_t seq = g_infoSeq;
+ if (overlaySeq != seq + 1) {
+ overlaySeq = seq + 1;
+ ui::StreamInfo info;
+ {
+ std::lock_guard<std::mutex> infoLock(g_infoMutex);
+ info = g_streamInfo;
+ }
+ if (menu.isOpen()) {
+ ui::Canvas c = menu.renderMenu(info);
+ display::setOverlay(c.data(), ui::StreamMenu::kMenuX, ui::StreamMenu::kMenuY, c.width(), c.height(), 235);
+ } else if (showStats && seq) {
+ ui::Canvas c = menu.renderStats(info);
+ display::setOverlay(c.data(), ui::StreamMenu::kStatsX, ui::StreamMenu::kStatsY, c.width(), c.height(), 200);
+ } else {
+ display::setOverlay(nullptr, 0, 0, 0, 0, 0);
+ }
+ overlayShown = true;
+ }
+ platform::sleepMs(8); // ~120 Hz input
+ continue;
+ }
+ if (overlayShown) {
+ display::setOverlay(nullptr, 0, 0, 0, 0, 0);
+ overlayShown = false;
+ menu.close();
+ }
ui::UiEvent ev = g_ui->handle(nav);
switch (ev.action) {
@@ -789,6 +946,20 @@ int main(int argc, char** argv) {
XC_LOGI("AUTOPLAY END: library test");
}
}
+ if (g_autoplayImeTest && uiSaved) {
+ static uint64_t openedAt = 0;
+ std::string typed;
+ if (!openedAt) {
+ openedAt = now;
+ bool ok = platform::openSystemKeyboard("PSBox test", "hello", 64);
+ XC_LOGI("autoplay: system keyboard %s", ok ? "opened" : "unavailable");
+ if (!ok) g_autoplayImeTest = false;
+ } else if (auto st = platform::pollSystemKeyboard(typed); st != platform::KeyboardStatus::Open) {
+ XC_LOGI("AUTOPLAY END: keyboard %s, %zu bytes", st == platform::KeyboardStatus::Accepted ? "accepted" : "closed",
+ typed.size());
+ g_autoplayImeTest = false;
+ }
+ }
if (g_autoplayDetailTest && uiSaved) {
// A game to buy far down the list (no prefetched details): its
// page must fill in on its own.
diff --git a/src/app/settings.cpp b/src/app/settings.cpp
index 88c7e35..0c2fe7c 100644
--- a/src/app/settings.cpp
+++ b/src/app/settings.cpp
@@ -20,6 +20,7 @@ bool Settings::load(const std::string& path) {
for (const auto& id : (*j)["hidden"].items())
if (!id.str().empty()) hidden.push_back(id.str());
librarySort = (*j)["librarySort"].str(librarySort);
+ streamStats = (*j)["streamStats"].asBool(streamStats);
regionRtt.clear();
for (const auto& [name, ms] : (*j)["regionRtt"].members())
if (ms.asInt() > 0) regionRtt[name] = static_cast<int>(ms.asInt());
@@ -38,6 +39,7 @@ bool Settings::save(const std::string& path) const {
for (const auto& id : hidden) hiddenIds.push(id);
v.set("hidden", hiddenIds);
v.set("librarySort", librarySort);
+ v.set("streamStats", streamStats);
return platform::writeFileAtomic(path, v.dump());
}
diff --git a/src/app/settings.h b/src/app/settings.h
index d9ea3be..3ab74be 100644
--- a/src/app/settings.h
+++ b/src/app/settings.h
@@ -19,6 +19,8 @@ struct Settings {
// ("recent", "az", "console").
std::vector<std::string> hidden;
std::string librarySort = "recent";
+ // The statistics line over the game (in-game menu).
+ bool streamStats = false;
bool load(const std::string& path);
bool save(const std::string& path) const;
diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cpp
index ed7c46d..c591db6 100644
--- a/src/app/stream_player.cpp
+++ b/src/app/stream_player.cpp
@@ -18,6 +18,7 @@
#include <condition_variable>
#include <deque>
#include <mutex>
+#include <set>
#include <thread>
#include <vector>
@@ -49,6 +50,7 @@ struct StreamPlayer::Impl {
std::atomic<uint64_t> videoFrames{0}, decodedFrames{0}, droppedFrames{0}, audioPackets{0};
std::atomic<uint64_t> decodeFailures{0}, queueResets{0}, keyframeRequests{0};
std::atomic<bool> keyframeWanted{false};
+ std::atomic<uint32_t> pictureSize{0}; // width << 16 | height
std::atomic<uint64_t> vibrations{0}, lateFrames{0};
std::atomic<uint64_t> decodeUs{0}, decodeCalls{0}, decodeMaxUs{0}, drawUs{0}, drawCalls{0}, drawMaxUs{0};
int decodeThreads = 1;
@@ -65,6 +67,9 @@ struct StreamPlayer::Impl {
std::string snapshotPath;
std::string screenPath; // video thread only
uint64_t lastKeyframeRequestMs = 0;
+ // The game's text requests not yet taken, and those it withdrew (mutex).
+ std::deque<stream::TextInputRequest> textRequests;
+ std::set<std::string> textWithdrawn;
explicit Impl(xcloud::GssvClient& g) : gssv(g) {}
@@ -147,6 +152,7 @@ struct StreamPlayer::Impl {
continue;
}
++decodedFrames;
+ pictureSize = (static_cast<uint32_t>(pic.width) << 16) | static_cast<uint32_t>(pic.height);
bool screenshot = saveSnapshotIfAsked(pic);
if (backlog > 2) { // behind: skip drawing to catch up
++droppedFrames;
@@ -225,12 +231,24 @@ struct StreamPlayer::Impl {
platform::notify(ui::trf(ui::Str::IdleWarning, std::to_string(seconds)));
};
cb.closed = [this](const std::string& reason) { end(reason); };
+ // With the console's keyboard, the game's text fields use it;
+ // otherwise the server draws the Xbox keyboard into the picture.
+ if (platform::systemKeyboardAvailable()) {
+ cb.textInput = [this](const stream::TextInputRequest& req) {
+ std::lock_guard<std::mutex> lock(mutex);
+ textRequests.push_back(req);
+ };
+ cb.textInputCancelled = [this](const std::string& id) {
+ std::lock_guard<std::mutex> lock(mutex);
+ textWithdrawn.insert(id);
+ };
+ }
stream::StreamOptions opts;
// Each setting asks for the best tier of its resolution, like the
// xbox.com client: the HQ tiers (higher bitrate) and 1440p need Game
// Pass Ultimate and a market where Microsoft enabled them; elsewhere
- // the service ignores the request and streams the plain tier.
+ // the plain tier the session asks for first holds.
switch (gssv.resolution()) {
case xcloud::Resolution::P1440: opts.resolutionAlias = "1440"; break;
case xcloud::Resolution::P1080: opts.resolutionAlias = "1080HQ"; break;
@@ -361,6 +379,36 @@ void StreamPlayer::sendInput(const input::ControllerState& p) {
impl_->session->sendGamepad(f);
}
+bool StreamPlayer::takeTextInput(stream::TextInputRequest& out) {
+ std::lock_guard<std::mutex> lock(impl_->mutex);
+ while (!impl_->textRequests.empty()) {
+ out = std::move(impl_->textRequests.front());
+ impl_->textRequests.pop_front();
+ if (!impl_->textWithdrawn.count(out.id)) return true;
+ }
+ return false;
+}
+
+bool StreamPlayer::textInputWithdrawn(const std::string& id) {
+ std::lock_guard<std::mutex> lock(impl_->mutex);
+ return impl_->textWithdrawn.count(id) != 0;
+}
+
+void StreamPlayer::answerTextInput(const std::string& id, bool accepted, const std::string& text) {
+ if (textInputWithdrawn(id) || !impl_->session) return;
+ XC_LOGI("text input %s", accepted ? "sent" : "cancelled");
+ if (accepted)
+ impl_->session->completeTextInput(id, text);
+ else
+ impl_->session->cancelTextInput(id);
+}
+
+void StreamPlayer::requestKeyframe() { impl_->keyframeWanted = true; }
+
+void StreamPlayer::requestResolution(const std::string& alias) {
+ if (impl_->session) impl_->session->requestResolution(alias);
+}
+
void StreamPlayer::tick() { impl_->tick(); }
void StreamPlayer::dumpVideo(const std::string& path, int seconds) {
@@ -389,6 +437,8 @@ StreamPlayer::Stats StreamPlayer::stats() const {
st.keyframeRequests = impl_->keyframeRequests;
st.vibrations = impl_->vibrations;
st.lateFrames = impl_->lateFrames;
+ st.width = static_cast<int>(impl_->pictureSize >> 16);
+ st.height = static_cast<int>(impl_->pictureSize & 0xFFFF);
// Timings since the previous call.
uint64_t dc = impl_->decodeCalls.exchange(0), du = impl_->decodeUs.exchange(0);
uint64_t rc = impl_->drawCalls.exchange(0), ru = impl_->drawUs.exchange(0);
diff --git a/src/app/stream_player.h b/src/app/stream_player.h
index 6168571..13709c6 100644
--- a/src/app/stream_player.h
+++ b/src/app/stream_player.h
@@ -6,6 +6,7 @@
#pragma once
#include "input/controller.h"
+#include "stream/stream_session.h"
#include "xcloud/gssv.h"
#include <memory>
@@ -24,6 +25,17 @@ public:
std::string endReason() const;
// From the input thread, once per polled pad state.
void sendInput(const input::ControllerState& pad);
+ // The game's requests for text, oldest first (main thread): false when
+ // none. Each one is answered once with answerTextInput() (accepted false
+ // = cancelled); textInputWithdrawn() turns true when the game gave up
+ // waiting, and the answer is then dropped.
+ bool takeTextInput(stream::TextInputRequest& out);
+ bool textInputWithdrawn(const std::string& id);
+ void answerTextInput(const std::string& id, bool accepted, const std::string& text);
+ // A new key frame (a clean picture), as after packet loss.
+ void requestKeyframe();
+ // Another stream tier mid-session: "720", "720HQ", "1080", "1080HQ", "1440".
+ void requestResolution(const std::string& alias);
// Keepalives etc.; about once a second from the thread owning `gssv`.
void tick();
void stop();
@@ -38,8 +50,9 @@ public:
// RTP: packets lost, recovered by NACK, frames the jitter buffer dropped.
uint64_t rtpPackets = 0, rtpLost = 0, rtpRecovered = 0, rtpNacks = 0, rtpDroppedFrames = 0;
uint64_t rtpKbps = 0, rembKbps = 0, vibrations = 0;
- uint64_t lateFrames = 0;
- int rttMs = -1; // to the stream server // decoded, not drawn: both flips still queued
+ uint64_t lateFrames = 0; // decoded, not drawn: both flips still queued
+ int rttMs = -1; // to the stream server
+ int width = 0, height = 0; // of the last decoded picture
// Since the previous stats() call (so call it from one place only).
uint64_t decodeAvgUs = 0, decodeMaxUs = 0, drawAvgUs = 0, drawMaxUs = 0;
};
diff --git a/src/display/display.cpp b/src/display/display.cpp
index 6f64a29..6ad1224 100644
--- a/src/display/display.cpp
+++ b/src/display/display.cpp
@@ -10,6 +10,7 @@
#include <condition_variable>
#include <cstring>
#include <functional>
+#include <memory>
#include <mutex>
#include <thread>
#include <vector>
@@ -210,6 +211,14 @@ const TileOrder& tileOrder() {
return t;
}
+struct Overlay {
+ std::vector<uint32_t> px;
+ int x, y, w, h;
+ uint32_t alpha;
+};
+std::mutex g_overlayMutex;
+std::shared_ptr<const Overlay> g_overlay;
+
struct YuvJob {
const uint8_t *y, *u, *v;
int strideY, strideU, strideV;
@@ -222,6 +231,7 @@ struct YuvJob {
// and halfway between two luma rows.
std::vector<uint16_t> cx0, cx1, cy0, cy1;
std::vector<uint8_t> wx, wy;
+ const Overlay* overlay = nullptr;
};
inline uint8_t clamp8(int v) { return static_cast<uint8_t>(v < 0 ? 0 : v > 255 ? 255 : v); }
@@ -231,6 +241,11 @@ void convertTiles(const YuvJob& job, unsigned first, unsigned last) {
for (unsigned t = first; t < last; ++t) {
unsigned tx = t % kTilesX, ty = t / kTilesX;
auto* out = reinterpret_cast<uint32_t*>(job.base + static_cast<size_t>(t) * 0x10000);
+ // Only the tiles under the overlay look at it.
+ const Overlay* ov = job.overlay;
+ if (ov && (static_cast<int>(tx * 128) >= ov->x + ov->w || static_cast<int>(tx * 128 + 128) <= ov->x ||
+ static_cast<int>(ty * 128) >= ov->y + ov->h || static_cast<int>(ty * 128 + 128) <= ov->y))
+ ov = nullptr;
for (unsigned i = 0; i < 16384; ++i) {
unsigned x = tx * 128 + order.dx[i];
unsigned y = ty * 128 + order.dy[i];
@@ -253,6 +268,16 @@ void convertTiles(const YuvJob& job, unsigned first, unsigned last) {
uint32_t r = clamp8((c + 1836 * e + 512) >> 10);
uint32_t g = clamp8((c - 218 * d - 546 * e + 512) >> 10);
uint32_t b = clamp8((c + 2163 * d + 512) >> 10);
+ if (ov) {
+ int ox = static_cast<int>(x) - ov->x, oy = static_cast<int>(y) - ov->y;
+ if (ox >= 0 && oy >= 0 && ox < ov->w && oy < ov->h) {
+ uint32_t p = ov->px[static_cast<size_t>(oy) * ov->w + ox];
+ uint32_t a = ov->alpha, na = 255 - a;
+ r = ((p & 0xFF) * a + r * na) / 255;
+ g = (((p >> 8) & 0xFF) * a + g * na) / 255;
+ b = (((p >> 16) & 0xFF) * a + b * na) / 255;
+ }
+ }
out[i] = 0xFF000000u | (b << 16) | (g << 8) | r;
}
}
@@ -398,10 +423,26 @@ bool drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v, int stride
job.width = width;
job.height = height;
job.base = static_cast<uint8_t*>(g_mappedMemory) + (g_currentBuffer * kFrameBytes);
+ std::shared_ptr<const Overlay> overlay;
+ {
+ std::lock_guard<std::mutex> lock(g_overlayMutex);
+ overlay = g_overlay;
+ }
+ job.overlay = overlay.get();
tilePool().run([](unsigned first, unsigned last) { convertTiles(job, first, last); });
+ job.overlay = nullptr;
return true;
}
+void setOverlay(const uint32_t* pixels, int x, int y, int w, int h, uint8_t opacity) {
+ std::shared_ptr<const Overlay> next;
+ if (pixels && w > 0 && h > 0)
+ next = std::make_shared<const Overlay>(
+ Overlay{std::vector<uint32_t>(pixels, pixels + static_cast<size_t>(w) * h), x, y, w, h, opacity});
+ std::lock_guard<std::mutex> lock(g_overlayMutex);
+ g_overlay = std::move(next);
+}
+
} // namespace xc::display
#else
@@ -417,6 +458,7 @@ void shutdown() {}
void present() {}
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 setOverlay(const uint32_t*, int, int, int, int, uint8_t) {}
bool readBackRgb(std::vector<uint8_t>&) { return false; }
} // namespace xc::display
diff --git a/src/display/display.h b/src/display/display.h
index 16a621f..782875b 100644
--- a/src/display/display.h
+++ b/src/display/display.h
@@ -29,6 +29,11 @@ void drawRgba(const uint32_t* pixels);
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 wait);
+// A picture laid over every video frame drawYuv420() draws from now on (the
+// in-game menu, the statistics): `w` x `h` RGBA pixels at (x, y), blended at
+// `opacity`. Null `pixels` removes it. Any thread.
+void setOverlay(const uint32_t* pixels, int x, int y, int w, int h, uint8_t opacity);
+
// The back buffer last drawn, untiled, as 8-bit RGB rows (diagnostics:
// what the TV shows). False without a display.
bool readBackRgb(std::vector<uint8_t>& rgb);
diff --git a/src/platform/host/platform_host.cpp b/src/platform/host/platform_host.cpp
index fe93276..f30c16b 100644
--- a/src/platform/host/platform_host.cpp
+++ b/src/platform/host/platform_host.cpp
@@ -87,4 +87,8 @@ void probeNetworking() {}
void notify(const std::string& text) { std::printf("\n>>> %s\n\n", text.c_str()); }
+bool systemKeyboardAvailable() { return false; }
+bool openSystemKeyboard(const std::string&, const std::string&, size_t, KeyboardKind) { return false; }
+KeyboardStatus pollSystemKeyboard(std::string&) { return KeyboardStatus::Closed; }
+
} // namespace xc::platform
diff --git a/src/platform/platform.h b/src/platform/platform.h
index 65949a2..6e47c68 100644
--- a/src/platform/platform.h
+++ b/src/platform/platform.h
@@ -48,6 +48,17 @@ bool startThread(Thread& t, std::function<void()> fn, size_t stackBytes = 8u <<
// Short on-screen message (PS5 system notification / host stdout).
void notify(const std::string& text);
+// The console's own on-screen keyboard (sceImeDialog), one at a time.
+// openSystemKeyboard() is false where there is none (the host, or a console
+// that refuses the module); pollSystemKeyboard() then reports Closed.
+enum class KeyboardStatus { Closed, Open, Accepted, Cancelled };
+enum class KeyboardKind { Text, Password, Number, Email, Url };
+bool systemKeyboardAvailable();
+bool openSystemKeyboard(const std::string& title, const std::string& text, size_t maxLength,
+ KeyboardKind kind = KeyboardKind::Text);
+// Accepted/Cancelled once, when the player closes it; `text` (UTF-8) on Accepted.
+KeyboardStatus pollSystemKeyboard(std::string& text);
+
bool readFile(const std::string& path, std::string& out);
bool writeFileAtomic(const std::string& path, const std::string& data);
diff --git a/src/platform/ps5/keyboard_ps5.cpp b/src/platform/ps5/keyboard_ps5.cpp
new file mode 100644
index 0000000..b053783
--- /dev/null
+++ b/src/platform/ps5/keyboard_ps5.cpp
@@ -0,0 +1,193 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// The system on-screen keyboard (sceImeDialog).
+//
+// An app's imports from a module it didn't load stay unresolved, and the
+// app can't see /system/common/lib: the modules are loaded on first use from
+// the sandbox's view of it (/<random word>/common/lib), then the imports bind
+// on their first call. (sceKernelDlsym answers ESRCH for every name here.)
+#include "platform/platform.h"
+#include "util/log.h"
+
+#include <cstdint>
+#include <cstring>
+#include <string>
+#include <vector>
+
+extern "C" {
+int sceKernelLoadStartModule(const char* path, size_t argc, const void* argv, uint32_t flags, void* opt, int* res);
+const char* sceKernelGetFsSandboxRandomWord(void);
+// Linked imports, bound on first call once the modules are loaded.
+int sceCommonDialogInitialize(void);
+int sceImeDialogInit(const void* param, void* extended);
+int sceImeDialogGetStatus(void);
+int sceImeDialogGetResult(void* result);
+int sceImeDialogTerm(void);
+int sceUserServiceGetInitialUser(int32_t* userId);
+}
+
+namespace xc::platform {
+
+namespace {
+
+// sceImeDialogInit's parameters, as in the PS4 SDK (the console's wchar_t is
+// 16 bits).
+struct ImeDialogParam {
+ int32_t userId;
+ int32_t type; // 0 default, 2 URL, 3 e-mail, 4 number
+ uint64_t supportedLanguages;
+ int32_t enterLabel;
+ int32_t inputMethod;
+ void* filter;
+ uint32_t option; // 0x4 password
+ uint32_t maxTextLength;
+ char16_t* inputTextBuffer;
+ float posx, posy;
+ int32_t horizontalAlignment, verticalAlignment; // 1 = centre
+ const char16_t* placeholder;
+ const char16_t* title;
+ int8_t reserved[16];
+};
+static_assert(sizeof(ImeDialogParam) == 96);
+
+struct DialogResult {
+ int32_t endStatus; // 0 ok, 1 cancel, 2 abort
+ int8_t reserved[60];
+};
+
+int g_available = -1; // unknown until the first use
+bool g_open = false;
+std::u16string g_title;
+std::vector<char16_t> g_buffer;
+
+// An app sees the system libraries under /<random word>/common/lib.
+std::string systemLib(const char* name) {
+ const char* word = sceKernelGetFsSandboxRandomWord();
+ return std::string("/") + (word ? word : "") + "/common/lib/" + name;
+}
+
+int load(const char* path) {
+ int res = 0;
+ int handle = sceKernelLoadStartModule(path, 0, nullptr, 0, nullptr, &res);
+ XC_LOGI("keyboard: load %s -> 0x%08x", path, static_cast<unsigned>(handle));
+ return handle;
+}
+
+bool resolve() {
+ if (g_available >= 0) return g_available;
+ g_available = 0;
+
+ // The dialogs sit on libSceCommonDialog, which wants initialising first.
+ int common = load(systemLib("libSceCommonDialog.sprx").c_str());
+ if (common < 0) common = load("libSceCommonDialog.sprx");
+ if (common >= 0) {
+ int rc = sceCommonDialogInitialize();
+ XC_LOGI("keyboard: sceCommonDialogInitialize -> 0x%08x", static_cast<unsigned>(rc));
+ }
+
+ int ime = load(systemLib("libSceImeDialog.sprx").c_str());
+ if (ime < 0) ime = load("libSceImeDialog.sprx");
+ g_available = ime >= 0;
+ return g_available;
+}
+
+std::u16string toUtf16(const std::string& s) {
+ std::u16string out;
+ for (size_t i = 0; i < s.size();) {
+ uint32_t c = static_cast<uint8_t>(s[i]);
+ int extra = c >= 0xF0 ? 3 : c >= 0xE0 ? 2 : c >= 0xC0 ? 1 : 0;
+ if (extra) c &= 0x3F >> extra;
+ ++i;
+ for (int k = 0; k < extra && i < s.size(); ++k, ++i) c = (c << 6) | (static_cast<uint8_t>(s[i]) & 0x3F);
+ if (c >= 0x10000) {
+ c -= 0x10000;
+ out.push_back(static_cast<char16_t>(0xD800 + (c >> 10)));
+ out.push_back(static_cast<char16_t>(0xDC00 + (c & 0x3FF)));
+ } else {
+ out.push_back(static_cast<char16_t>(c));
+ }
+ }
+ return out;
+}
+
+std::string toUtf8(const char16_t* s) {
+ std::string out;
+ for (; *s; ++s) {
+ uint32_t c = *s;
+ if (c >= 0xD800 && c < 0xDC00 && s[1] >= 0xDC00 && s[1] < 0xE000) {
+ c = 0x10000 + ((c - 0xD800) << 10) + (s[1] - 0xDC00);
+ ++s;
+ }
+ if (c < 0x80) {
+ out += static_cast<char>(c);
+ } else if (c < 0x800) {
+ out += static_cast<char>(0xC0 | (c >> 6));
+ out += static_cast<char>(0x80 | (c & 0x3F));
+ } else if (c < 0x10000) {
+ out += static_cast<char>(0xE0 | (c >> 12));
+ out += static_cast<char>(0x80 | ((c >> 6) & 0x3F));
+ out += static_cast<char>(0x80 | (c & 0x3F));
+ } else {
+ out += static_cast<char>(0xF0 | (c >> 18));
+ out += static_cast<char>(0x80 | ((c >> 12) & 0x3F));
+ out += static_cast<char>(0x80 | ((c >> 6) & 0x3F));
+ out += static_cast<char>(0x80 | (c & 0x3F));
+ }
+ }
+ return out;
+}
+
+} // namespace
+
+bool systemKeyboardAvailable() { return resolve(); }
+
+bool openSystemKeyboard(const std::string& title, const std::string& text, size_t maxLength, KeyboardKind kind) {
+ if (g_open || !resolve()) return false;
+ if (maxLength == 0 || maxLength > 2048) maxLength = 2048;
+ g_title = toUtf16(title);
+ std::u16string initial = toUtf16(text);
+ if (initial.size() > maxLength) initial.resize(maxLength);
+ g_buffer.assign(maxLength + 1, 0);
+ std::memcpy(g_buffer.data(), initial.data(), initial.size() * sizeof(char16_t));
+
+ ImeDialogParam p{};
+ int32_t user = -1;
+ sceUserServiceGetInitialUser(&user);
+ p.userId = user;
+ p.supportedLanguages = 0;
+ switch (kind) {
+ case KeyboardKind::Text: break;
+ case KeyboardKind::Password: p.option = 0x4; break;
+ case KeyboardKind::Number: p.type = 4; break;
+ case KeyboardKind::Email: p.type = 3; break;
+ case KeyboardKind::Url: p.type = 2; break;
+ }
+ p.maxTextLength = static_cast<uint32_t>(maxLength);
+ p.inputTextBuffer = g_buffer.data();
+ p.posx = 1920 / 2.0f;
+ p.posy = 1080 / 2.0f;
+ p.horizontalAlignment = 1;
+ p.verticalAlignment = 1;
+ p.title = g_title.c_str();
+ int rc = sceImeDialogInit(&p, nullptr);
+ XC_LOGI("keyboard: sceImeDialogInit -> 0x%08x", static_cast<unsigned>(rc));
+ if (rc != 0) return false;
+ g_open = true;
+ return true;
+}
+
+KeyboardStatus pollSystemKeyboard(std::string& text) {
+ if (!g_open) return KeyboardStatus::Closed;
+ int status = sceImeDialogGetStatus();
+ if (status == 1) return KeyboardStatus::Open; // running
+ DialogResult r{};
+ int rc = sceImeDialogGetResult(&r);
+ sceImeDialogTerm();
+ g_open = false;
+ XC_LOGI("keyboard: closed (status %d, result 0x%08x, end %d)", status, static_cast<unsigned>(rc), r.endStatus);
+ if (status != 2 || rc != 0 || r.endStatus != 0) return KeyboardStatus::Cancelled;
+ text = toUtf8(g_buffer.data());
+ return KeyboardStatus::Accepted;
+}
+
+} // namespace xc::platform
diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cpp
index 9bbf690..c1bb6df 100644
--- a/src/stream/stream_session.cpp
+++ b/src/stream/stream_session.cpp
@@ -30,6 +30,8 @@ namespace {
constexpr const char* kControlAccessKey = "4BDB3609-C1F1-4195-9B37-FEFF45DA8B8E";
constexpr const char* kHandshakeId = "be0bfc6d-1e83-4c8a-90ed-fa8601c5a179";
constexpr const char* kClientAppInstallId = "c97d7ee0-73b2-4239-bf1d-9d805a338429";
+// SystemUiType of the system UIs this client draws itself.
+constexpr int kShowVirtualKeyboard = 10;
std::string uuid4() {
uint8_t b[16];
@@ -197,6 +199,32 @@ struct StreamSession::Impl {
sendText(message, v.dump());
}
+ void cancelTransaction(const std::string& id) {
+ json::Value v = json::Value::object();
+ v.set("type", "ReceiverCancel");
+ v.set("id", id);
+ v.set("cv", "");
+ sendText(message, v.dump());
+ }
+
+ void sendResolution(const std::string& alias) {
+ // The HQ tiers and 1440 need Game Pass Ultimate in a market where
+ // they're enabled; elsewhere the service ignores them and keeps what
+ // it had (1080 at the start). The plain tier first, then: measured,
+ // "720" switches in a few seconds, "720HQ" is ignored in Brazil.
+ std::string base = alias == "1440" ? "1080" : alias;
+ if (base.size() > 2 && base.compare(base.size() - 2, 2, "HQ") == 0) base.resize(base.size() - 2);
+ auto send = [this](const std::string& a) {
+ json::Value res = json::Value::object();
+ res.set("message", "userRequestedResolutionUpdate");
+ res.set("resolutionAlias", a);
+ sendText(control, res.dump());
+ XC_LOGI("requested stream resolution %s", a.c_str());
+ };
+ send(base);
+ if (alias != base) send(alias);
+ }
+
void sendClientConfig() {
json::Value ver = json::Value::array();
ver.push(0);
@@ -204,7 +232,9 @@ struct StreamSession::Impl {
ver.push(0);
json::Value ui = json::Value::object();
ui.set("version", ver);
- ui.set("systemUis", json::Value::array());
+ json::Value systemUis = json::Value::array();
+ if (cb.textInput) systemUis.push(kShowVirtualKeyboard);
+ ui.set("systemUis", systemUis);
sendText(message, messageEnvelope("/streaming/systemUi/configuration", ui));
json::Value install = json::Value::object();
@@ -252,13 +282,7 @@ struct StreamSession::Impl {
sendGamepadChanged(0, true);
sendGamepadChanged(0, false);
sendGamepadChanged(0, true);
- if (!opt.resolutionAlias.empty()) {
- json::Value res = json::Value::object();
- res.set("message", "userRequestedResolutionUpdate");
- res.set("resolutionAlias", opt.resolutionAlias);
- sendText(control, res.dump());
- XC_LOGI("requested stream resolution %s", opt.resolutionAlias.c_str());
- }
+ if (!opt.resolutionAlias.empty()) sendResolution(opt.resolutionAlias);
sendBinary(input, clientMetadataReport(0, nowMs(), static_cast<uint8_t>(std::getenv("XC_TOUCH_POINTS") ? std::atoi(std::getenv("XC_TOUCH_POINTS")) : 1)));
sendClientConfig();
@@ -282,6 +306,11 @@ struct StreamSession::Impl {
onHandshakeAck();
return;
}
+ if (type == "SenderCancel") {
+ XC_LOGI("message channel: the server withdrew %s", (*j)["id"].str().c_str());
+ if (cb.textInputCancelled) cb.textInputCancelled((*j)["id"].str());
+ return;
+ }
if (type != "Message" && type != "TransactionStart") {
XC_LOGD("message channel: %s", text.substr(0, 300).c_str());
return;
@@ -307,6 +336,19 @@ struct StreamSession::Impl {
} else {
fail(reason.empty() ? "the server ended the session" : "the server ended the session (" + reason + ")");
}
+ } else if (target == "/streaming/systemUi/messages/ShowVirtualKeyboard" && cb.textInput) {
+ auto content = json::parse((*j)["content"].str());
+ TextInputRequest req;
+ req.id = id;
+ if (content) {
+ req.title = (*content)["TitleText"].str();
+ req.description = (*content)["DescriptionText"].str();
+ req.defaultText = (*content)["DefaultText"].str();
+ req.inputScope = static_cast<int>((*content)["InputScope"].asInt());
+ req.maxLength = static_cast<int>((*content)["MaxLength"].asInt());
+ }
+ XC_LOGI("the game asks for text (scope %d, up to %d characters)", req.inputScope, req.maxLength);
+ cb.textInput(req);
} else if (target == "/streaming/systemUi/messages/ShowMessageDialog") {
// No dialog UI yet: log it and pick the first (default) button.
auto content = json::parse((*j)["content"].str());
@@ -605,6 +647,16 @@ void StreamSession::requestKeyframe() {
XC_LOGW("keyframe request: %s", e.what());
}
}
+void StreamSession::completeTextInput(const std::string& id, const std::string& text) {
+ json::Value v = json::Value::object();
+ v.set("Text", text);
+ impl_->completeTransaction(id, v);
+}
+
+void StreamSession::cancelTextInput(const std::string& id) { impl_->cancelTransaction(id); }
+
+void StreamSession::requestResolution(const std::string& alias) { impl_->sendResolution(alias); }
+
void StreamSession::tick() { impl_->tick(); }
void StreamSession::close() { impl_->close(); }
int StreamSession::rttMs() const {
diff --git a/src/stream/stream_session.h b/src/stream/stream_session.h
index aec3d09..3b54e42 100644
--- a/src/stream/stream_session.h
+++ b/src/stream/stream_session.h
@@ -19,6 +19,15 @@
namespace xc::stream {
+// The game asks for text (a name, a chat line): the server's
+// "ShowVirtualKeyboard". Answer with completeTextInput() or cancelTextInput().
+struct TextInputRequest {
+ std::string id; // the transaction
+ std::string title, description, defaultText;
+ int inputScope = 0; // 0 default, 1 URL, 5 e-mail, 29 number, 31 password, 32 phone, 50 search
+ int maxLength = 0; // 0: no limit
+};
+
struct StreamCallbacks {
std::function<void(const uint8_t* data, size_t len, uint32_t rtpTimestamp)> video;
std::function<void(const uint8_t* data, size_t len, uint32_t rtpTimestamp)> audio;
@@ -26,6 +35,10 @@ struct StreamCallbacks {
// The server will end the session for inactivity in `seconds` unless
// input arrives.
std::function<void(int seconds)> idleWarning;
+ // Set: the game's keyboard requests come here (else the server draws its
+ // own); `textInputCancelled` when the game withdraws one.
+ std::function<void(const TextInputRequest&)> textInput;
+ std::function<void(const std::string& id)> textInputCancelled;
// The stream ended (server disconnect, connection lost). Called once.
std::function<void(const std::string& reason)> closed;
};
@@ -38,7 +51,8 @@ struct StreamOptions {
// Stream tier requested on the control channel after connecting, as the
// xbox.com client does ("userRequestedResolutionUpdate"): "720", "720HQ",
// "1080", "1080HQ" or "1440" (the HQ tiers and 1440 need Game Pass
- // Ultimate). Empty: don't send, the service picks.
+ // Ultimate; the plain tier is asked for first, so it holds where they
+ // aren't granted). Empty: don't send, the service picks.
std::string resolutionAlias;
// Test hook: drop this percentage of video RTP packets before the jitter
// buffer, to exercise NACK / key frame recovery.
@@ -64,6 +78,10 @@ public:
void sendGamepad(const GamepadFrame& frame);
void requestKeyframe();
+ void completeTextInput(const std::string& id, const std::string& text);
+ void cancelTextInput(const std::string& id);
+ // Another stream tier mid-session (StreamOptions::resolutionAlias).
+ void requestResolution(const std::string& alias);
// Sends keepalives and periodic key frame requests; call about once a
// second from the thread that owns the GssvClient.
void tick();
diff --git a/src/ui/stream_menu.cpp b/src/ui/stream_menu.cpp
new file mode 100644
index 0000000..86121c7
--- /dev/null
+++ b/src/ui/stream_menu.cpp
@@ -0,0 +1,154 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+#include "ui/stream_menu.h"
+
+#include "ui/strings.h"
+
+#include <cstdio>
+
+namespace xc::ui {
+
+namespace {
+
+constexpr Color kPanel = rgba(24, 24, 24);
+constexpr Color kWhite = rgba(255, 255, 255);
+constexpr Color kGray = rgba(190, 190, 190);
+constexpr Color kDim = rgba(140, 140, 140);
+constexpr Color kDark = rgba(20, 20, 20);
+constexpr Color kGreen = rgba(16, 124, 16);
+
+// Left to right on the resolution row: SettingsChoice::resolution values.
+constexpr int kResolutionOrder[] = {1, 0, 2};
+const char* resolutionName(int r) { return r == 1 ? "720p" : r == 2 ? "1440p" : "1080p"; }
+
+std::string fmt(const char* f, double v) {
+ char b[32];
+ std::snprintf(b, sizeof b, f, v);
+ return b;
+}
+
+} // namespace
+
+void StreamMenu::open(int resolution, bool stats) {
+ open_ = true;
+ stats_ = stats;
+ selected_ = Resume;
+ resolution_ = applied_ = resolution;
+ resolutionAsked_ = false;
+}
+
+MenuAction StreamMenu::handle(const NavInput& in) {
+ if (!open_) return MenuAction::None;
+ if (in.back || in.options) {
+ open_ = false;
+ return MenuAction::Close;
+ }
+ if (in.up) selected_ = (selected_ + ItemCount - 1) % ItemCount;
+ if (in.down) selected_ = (selected_ + 1) % ItemCount;
+ if (selected_ == Resolution && (in.left || in.right)) {
+ int pos = 0;
+ for (int i = 0; i < 3; ++i)
+ if (kResolutionOrder[i] == resolution_) pos = i;
+ pos = in.left ? (pos + 2) % 3 : (pos + 1) % 3;
+ resolution_ = kResolutionOrder[pos];
+ }
+ if (selected_ == Stats && (in.left || in.right)) {
+ stats_ = !stats_;
+ return MenuAction::Stats;
+ }
+ if (!in.accept) return MenuAction::None;
+ switch (selected_) {
+ case Resume: open_ = false; return MenuAction::Close;
+ case Stats: stats_ = !stats_; return MenuAction::Stats;
+ case Resolution:
+ applied_ = resolution_;
+ resolutionAsked_ = true;
+ return MenuAction::Resolution;
+ case Refresh: return MenuAction::Refresh;
+ case Leave: open_ = false; return MenuAction::Leave;
+ default: return MenuAction::None;
+ }
+}
+
+Canvas StreamMenu::renderMenu(const StreamInfo& info) const {
+ Canvas c(kMenuW, kMenuH);
+ c.clear(kPanel);
+ c.fillRect({0, 0, kMenuW, 6}, kGreen);
+ constexpr int kPad = 40;
+ fonts_.bold.draw(c, tr(Str::MenuTitle), kPad, 40, 34, kWhite);
+
+ // The items: the selected one white, like the Xbox guide.
+ constexpr int kRowH = 60, kTop = 110, kPx = 24;
+ for (int i = 0; i < ItemCount; ++i) {
+ Rect row{kPad - 16, kTop + i * kRowH, kMenuW - 2 * (kPad - 16), kRowH - 8};
+ bool sel = i == selected_;
+ if (sel) c.fillRect(row, kWhite, 8);
+ Color fg = sel ? kDark : kWhite;
+ int ty = fonts_.semibold.centeredY(row.y, row.h, kPx);
+ const char* label = i == Resume ? tr(Str::MenuResume)
+ : i == Stats ? tr(Str::MenuStats)
+ : i == Resolution ? tr(Str::MenuResolution)
+ : i == Refresh ? tr(Str::MenuRefresh)
+ : tr(Str::MenuLeave);
+ fonts_.semibold.draw(c, label, row.x + 16, ty, kPx, fg);
+ std::string value;
+ if (i == Stats) value = tr(stats_ ? Str::On : Str::Off);
+ if (i == Resolution) {
+ value = resolutionName(resolution_);
+ if (sel) value = "< " + value + " >";
+ }
+ if (!value.empty()) {
+ int w = fonts_.semibold.measure(value, kPx);
+ fonts_.semibold.draw(c, value, row.x + row.w - 16 - w, ty, kPx, sel ? kDark : kGray);
+ }
+ }
+ int y = kTop + ItemCount * kRowH;
+ if (resolutionAsked_) fonts_.regular.draw(c, tr(Str::ResolutionNote), kPad, y, 18, kDim);
+ y += 40;
+
+ // The connection.
+ c.fillRect({kPad, y, kMenuW - 2 * kPad, 2}, rgba(60, 60, 60));
+ y += 22;
+ auto line = [&](Str label, const std::string& value) {
+ fonts_.regular.draw(c, tr(label), kPad, y, 22, kGray);
+ int w = fonts_.semibold.measure(value, 22);
+ fonts_.semibold.draw(c, value, kMenuW - kPad - w, y, 22, kWhite);
+ y += 36;
+ };
+ const std::string none = "-";
+ line(Str::StatRegion, info.region.empty() ? none : info.region);
+ line(Str::StatLatency, info.rttMs > 0 ? std::to_string(info.rttMs) + " ms" : none);
+ line(Str::StatBitrate, info.mbps > 0 ? fmt("%.1f Mbps", info.mbps) : none);
+ std::string frames = info.fps > 0 ? fmt("%.0f fps", info.fps) : none;
+ if (info.width > 0) frames = std::to_string(info.width) + "x" + std::to_string(info.height) + " " + frames;
+ line(Str::StatFrameRate, frames);
+ line(Str::StatLoss, fmt("%.1f %%", info.lossPct));
+ line(Str::StatDecode, info.decodeMs > 0 ? fmt("%.1f ms", info.decodeMs) : none);
+
+ // Cross selects, Circle goes back to the game.
+ int hy = kMenuH - 56, x = kPad;
+ c.fillCircle(x + 14, hy + 13, 14, rgba(255, 255, 255, 40));
+ c.line(x + 8, hy + 7, x + 20, hy + 19, 2.5f, rgba(124, 178, 232));
+ c.line(x + 20, hy + 7, x + 8, hy + 19, 2.5f, rgba(124, 178, 232));
+ x = fonts_.semibold.draw(c, tr(Str::Select), x + 38, hy, 22, kGray) + 36;
+ c.fillCircle(x + 14, hy + 13, 14, rgba(255, 255, 255, 40));
+ c.strokeArc(x + 14, hy + 13, 6.5f, 2.5f, 0, 6.2832f, rgba(255, 102, 102));
+ fonts_.semibold.draw(c, tr(Str::Back), x + 38, hy, 22, kGray);
+ return c;
+}
+
+Canvas StreamMenu::renderStats(const StreamInfo& info) const {
+ std::string text;
+ if (info.height > 0) text += std::to_string(info.height) + "p ";
+ text += fmt("%.0f fps", info.fps) + " " + fmt("%.1f Mbps", info.mbps);
+ if (info.rttMs > 0) text += " " + std::to_string(info.rttMs) + " ms";
+ text += " " + fmt("%.1f%%", info.lossPct);
+ constexpr int kPx = 20, kH = 36;
+ int w = fonts_.semibold.measure(text, kPx) + 28;
+ Canvas c(w, kH);
+ c.clear(kPanel);
+ fonts_.semibold.draw(c, text, 14, fonts_.semibold.centeredY(0, kH, kPx), kPx, kWhite);
+ return c;
+}
+
+} // namespace xc::ui
diff --git a/src/ui/stream_menu.h b/src/ui/stream_menu.h
new file mode 100644
index 0000000..4a3f374
--- /dev/null
+++ b/src/ui/stream_menu.h
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// What is drawn over a running game: the in-game menu (OPTIONS + TOUCHPAD)
+// and the statistics line. Each is drawn into its own small canvas, which
+// display::setOverlay() lays over the video.
+#pragma once
+
+#include "ui/app_ui.h"
+#include "ui/canvas.h"
+#include "ui/font.h"
+
+#include <string>
+
+namespace xc::ui {
+
+// The stream's numbers over the last second.
+struct StreamInfo {
+ std::string region;
+ int rttMs = -1;
+ double fps = 0, mbps = 0, lossPct = 0, decodeMs = 0;
+ int width = 0, height = 0; // of the decoded picture
+};
+
+enum class MenuAction { None, Close, Leave, Refresh, Resolution, Stats };
+
+class StreamMenu {
+public:
+ static constexpr int kMenuW = 620, kMenuH = 780;
+ static constexpr int kMenuX = 80, kMenuY = (1080 - kMenuH) / 2;
+ static constexpr int kStatsX = 32, kStatsY = 28;
+
+ explicit StreamMenu(const Fonts& fonts) : fonts_(fonts) {}
+
+ // `resolution` as SettingsChoice::resolution (0 = 1080p, 1 = 720p, 2 = 1440p).
+ void open(int resolution, bool stats);
+ void close() { open_ = false; }
+ bool isOpen() const { return open_; }
+ MenuAction handle(const NavInput& in);
+ int resolution() const { return resolution_; }
+ bool statsOn() const { return stats_; }
+
+ Canvas renderMenu(const StreamInfo& info) const;
+ Canvas renderStats(const StreamInfo& info) const;
+
+private:
+ enum Item { Resume, Stats, Resolution, Refresh, Leave, ItemCount };
+
+ const Fonts& fonts_;
+ bool open_ = false, stats_ = false;
+ int selected_ = Resume;
+ int resolution_ = 0, applied_ = 0;
+ bool resolutionAsked_ = false;
+};
+
+} // namespace xc::ui
diff --git a/src/ui/strings.cpp b/src/ui/strings.cpp
index 29d7294..45e9932 100644
--- a/src/ui/strings.cpp
+++ b/src/ui/strings.cpp
@@ -54,7 +54,7 @@ constexpr Column kEnglish = {
"You're in the queue. Estimated wait: %s", // InQueue
"Connecting...", // Connecting
"Starting the stream...", // StartingStream
- "Hold OPTIONS + TOUCHPAD to leave the game", // LeaveHint
+ "Press OPTIONS + TOUCHPAD for the game menu", // LeaveHint
"Stream ended", // StreamEnded
"Something went wrong", // ErrorTitle
"Signed in as %s", // SignedInAs
@@ -114,6 +114,21 @@ constexpr Column kEnglish = {
"1 game", // OneGame
"Sections", // Sections
"Updating the game list...", // UpdatingList
+ "Game menu", // MenuTitle
+ "Resume", // MenuResume
+ "Statistics", // MenuStats
+ "On", // On
+ "Off", // Off
+ "Stream resolution", // MenuResolution
+ "Refresh the picture", // MenuRefresh
+ "Leave game", // MenuLeave
+ "Latency", // StatLatency
+ "Bitrate", // StatBitrate
+ "Frame rate", // StatFrameRate
+ "Packet loss", // StatLoss
+ "Region", // StatRegion
+ "Decoding", // StatDecode
+ "The server may keep the current quality", // ResolutionNote
};
constexpr Column kPortugueseBR = {
@@ -138,7 +153,7 @@ constexpr Column kPortugueseBR = {
"Você está na fila. Espera estimada: %s",
"Conectando...",
"Iniciando o streaming...",
- "Segure OPTIONS + TOUCHPAD para sair do jogo",
+ "Pressione OPTIONS + TOUCHPAD para abrir o menu do jogo",
"Streaming encerrado",
"Algo deu errado",
"Conectado como %s",
@@ -198,6 +213,21 @@ constexpr Column kPortugueseBR = {
"1 jogo",
"Seções",
"Atualizando a lista de jogos...",
+ "Menu do jogo",
+ "Continuar",
+ "Estatísticas",
+ "Ligado",
+ "Desligado",
+ "Resolução do stream",
+ "Atualizar a imagem",
+ "Sair do jogo",
+ "Latência",
+ "Taxa de bits",
+ "Quadros por segundo",
+ "Perda de pacotes",
+ "Região",
+ "Decodificação",
+ "O servidor pode manter a qualidade atual",
};
constexpr Column kSpanish = {
@@ -222,7 +252,7 @@ constexpr Column kSpanish = {
"Estás en la cola. Espera estimada: %s",
"Conectando...",
"Iniciando el streaming...",
- "Mantén OPTIONS + TOUCHPAD para salir del juego",
+ "Pulsa OPTIONS + TOUCHPAD para abrir el menú del juego",
"Streaming finalizado",
"Algo salió mal",
"Sesión iniciada como %s",
@@ -282,6 +312,21 @@ constexpr Column kSpanish = {
"1 juego",
"Secciones",
"Actualizando la lista de juegos...",
+ "Menú del juego",
+ "Continuar",
+ "Estadísticas",
+ "Activado",
+ "Desactivado",
+ "Resolución del stream",
+ "Actualizar la imagen",
+ "Salir del juego",
+ "Latencia",
+ "Tasa de bits",
+ "Fotogramas por segundo",
+ "Pérdida de paquetes",
+ "Región",
+ "Decodificación",
+ "El servidor puede mantener la calidad actual",
};
constexpr Column kFrench = {
@@ -306,7 +351,7 @@ constexpr Column kFrench = {
"Vous êtes dans la file d'attente. Attente estimée : %s",
"Connexion...",
"Démarrage du streaming...",
- "Maintenez OPTIONS + PAVÉ TACTILE pour quitter le jeu",
+ "Appuyez sur OPTIONS + PAVÉ TACTILE pour le menu du jeu",
"Streaming terminé",
"Un problème est survenu",
"Connecté en tant que %s",
@@ -366,6 +411,21 @@ constexpr Column kFrench = {
"1 jeu",
"Sections",
"Mise \xC3\xA0 jour de la liste des jeux...",
+ "Menu du jeu",
+ "Reprendre",
+ "Statistiques",
+ "Activé",
+ "Désactivé",
+ "Résolution du stream",
+ "Actualiser l'image",
+ "Quitter le jeu",
+ "Latence",
+ "Débit",
+ "Images par seconde",
+ "Perte de paquets",
+ "Région",
+ "Décodage",
+ "Le serveur peut conserver la qualité actuelle",
};
constexpr Column kGerman = {
@@ -390,7 +450,7 @@ constexpr Column kGerman = {
"Du bist in der Warteschlange. Geschätzte Wartezeit: %s",
"Verbindung wird hergestellt...",
"Streaming wird gestartet...",
- "OPTIONS + TOUCHPAD gedrückt halten, um das Spiel zu verlassen",
+ "OPTIONS + TOUCHPAD drücken, um das Spielmenü zu öffnen",
"Streaming beendet",
"Etwas ist schiefgelaufen",
"Angemeldet als %s",
@@ -450,6 +510,21 @@ constexpr Column kGerman = {
"1 Spiel",
"Abschnitte",
"Spieleliste wird aktualisiert...",
+ "Spielmenü",
+ "Fortsetzen",
+ "Statistiken",
+ "An",
+ "Aus",
+ "Stream-Auflösung",
+ "Bild aktualisieren",
+ "Spiel verlassen",
+ "Latenz",
+ "Bitrate",
+ "Bilder pro Sekunde",
+ "Paketverlust",
+ "Region",
+ "Dekodierung",
+ "Der Server behält eventuell die aktuelle Qualität bei",
};
constexpr Column kItalian = {
@@ -474,7 +549,7 @@ constexpr Column kItalian = {
"Sei in coda. Attesa stimata: %s",
"Connessione...",
"Avvio dello streaming...",
- "Tieni premuti OPTIONS + TOUCHPAD per uscire dal gioco",
+ "Premi OPTIONS + TOUCHPAD per il menu di gioco",
"Streaming terminato",
"Si è verificato un problema",
"Accesso effettuato come %s",
@@ -534,6 +609,21 @@ constexpr Column kItalian = {
"1 gioco",
"Sezioni",
"Aggiornamento dell'elenco dei giochi...",
+ "Menu di gioco",
+ "Riprendi",
+ "Statistiche",
+ "Attivo",
+ "Disattivo",
+ "Risoluzione dello stream",
+ "Aggiorna l'immagine",
+ "Esci dal gioco",
+ "Latenza",
+ "Bitrate",
+ "Fotogrammi al secondo",
+ "Perdita di pacchetti",
+ "Regione",
+ "Decodifica",
+ "Il server potrebbe mantenere la qualità attuale",
};
constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,
diff --git a/src/ui/strings.h b/src/ui/strings.h
index b907833..11b218e 100644
--- a/src/ui/strings.h
+++ b/src/ui/strings.h
@@ -91,6 +91,21 @@ enum class Str {
OneGame, // GamesCount for exactly one
Sections, // hint for L2 / R2: jump between sections
UpdatingList, // the lists refresh in the background
+ MenuTitle, // the in-game menu
+ MenuResume,
+ MenuStats, // show the statistics over the game
+ On,
+ Off,
+ MenuResolution,
+ MenuRefresh, // ask for a new picture (key frame)
+ MenuLeave,
+ StatLatency,
+ StatBitrate,
+ StatFrameRate,
+ StatLoss,
+ StatRegion,
+ StatDecode,
+ ResolutionNote, // the server may not grant the tier asked for
Count
};
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 0f41ef2..6edf7cf 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -5,6 +5,7 @@
#include "stream/input_packet.h"
#include "stream/stream_session.h"
#include "ui/app_ui.h"
+#include "ui/stream_menu.h"
#include "ui/strings.h"
#include "util/json.h"
#include "xcloud/prices.h"
@@ -166,7 +167,38 @@ static void testPrices() {
CHECK(formatPrice(4, "XYZ") == "XYZ 4.00");
}
+static void testStreamMenu() {
+ using xc::ui::MenuAction;
+ xc::ui::Fonts fonts; // not loaded: handle() never draws
+ xc::ui::StreamMenu menu(fonts);
+ auto press = [&](void (*set)(xc::ui::NavInput&)) {
+ xc::ui::NavInput n;
+ set(n);
+ return menu.handle(n);
+ };
+ CHECK(press([](xc::ui::NavInput& n) { n.accept = true; }) == MenuAction::None); // closed
+ menu.open(0, false);
+ CHECK(menu.isOpen());
+ press([](xc::ui::NavInput& n) { n.down = true; });
+ CHECK(press([](xc::ui::NavInput& n) { n.right = true; }) == MenuAction::Stats);
+ CHECK(menu.statsOn());
+ press([](xc::ui::NavInput& n) { n.down = true; });
+ press([](xc::ui::NavInput& n) { n.left = true; }); // 1080p -> 720p
+ CHECK(menu.resolution() == 1);
+ press([](xc::ui::NavInput& n) { n.left = true; }); // wraps to 1440p
+ CHECK(menu.resolution() == 2);
+ CHECK(press([](xc::ui::NavInput& n) { n.accept = true; }) == MenuAction::Resolution);
+ press([](xc::ui::NavInput& n) { n.up = true; });
+ press([](xc::ui::NavInput& n) { n.up = true; });
+ press([](xc::ui::NavInput& n) { n.up = true; }); // wraps to "Leave game"
+ CHECK(press([](xc::ui::NavInput& n) { n.accept = true; }) == MenuAction::Leave);
+ CHECK(!menu.isOpen());
+ menu.open(1, true);
+ CHECK(press([](xc::ui::NavInput& n) { n.back = true; }) == MenuAction::Close);
+}
+
int main() {
+ testStreamMenu();
testStrings();
testRegions();
testPrices();