Xbox Cloud Gaming app for PS5 Homebrew
C
Own Xbox: the Xbox button, ending the stream, and an Xbox that is off
Rafael Abud Ferreirab2a763c18618
diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex 8f64fbf..435dfcf 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -177,6 +177,8 @@ int g_autoplayDeband = -1; // deband=0..2: instead of the settingint g_autoplaySharpness = -1; // sharp=0..3: instead of the settingstd::string g_autoplayResolution; // res=720p|1080p|1440p: instead of the settingstd::atomic<bool> g_syntheticA{false};+std::atomic<bool> g_playingHome{false}; // the stream is the user's own Xbox+std::atomic<uint64_t> g_xboxButtonUntil{0}; // the game menu's Xbox button, held until then (ms)void loadAutoplay() {std::string text;@@ -428,12 +430,27 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game}bool connected = false;std::string result = "timed out waiting for the session";+ // A console that is off for good (not asleep) never comes out of+ // Provisioning: give up after a minute (the cloud's queue may take long).+ const uint64_t provisioningSince = platform::nowMs();+ int pollErrors = 0;for (int i = 0; i < 900 && !g_cancel; ++i) {+ if (gssv.isHome() && platform::nowMs() - provisioningSince > 60000) {+ result = "ConsoleDidNotWake: no answer in 60 s";+ break;+ }xcloud::SessionStatus st;if (!gssv.sessionState(st, err)) {+ // A network hiccup (a TLS timeout) is asked again; three in a row end it.+ if (++pollErrors < 3) {+ XC_LOGW("%s (asking again)", err.c_str());+ platform::sleepMs(1000);+ continue;+ }result = err;break;}+ pollErrors = 0;XC_LOGI("session state: %s", st.raw.c_str());if (st.state == xcloud::SessionState::WaitingForResources)g_ui->setLaunchStatus(ui::trf(ui::Str::InQueue, formatWait(gssv.waitTimeSeconds())));@@ -556,6 +573,14 @@ void priceLoop() {}}}+// The note on the home screen after a stream: who ended it, when known.+std::string endedToast(const std::string& result) {+ if (result.find("KickForStopCommand") != std::string::npos) return ui::tr(ui::Str::EndedOnXbox);+ if (result.find("KickByNewSession") != std::string::npos) return ui::tr(ui::Str::EndedByOtherDevice);+ if (result.find("KickForServerShutdown") != std::string::npos) return ui::tr(ui::Str::EndedXboxOff);+ return ui::tr(ui::Str::StreamEnded);+}+// "My consoles": the account's own Xbox consoles (Remote Play, the xhome// offering, logged in with the same Xbox token).void loadConsoles(auth::AuthManager& am, xcloud::GssvClient& home) {@@ -569,7 +594,9 @@ void loadConsoles(auth::AuthManager& am, xcloud::GssvClient& home) {}std::vector<ui::ConsoleTile> tiles;for (const auto& c : consoles) tiles.push_back({c.serverId, c.deviceName, c.consoleType, c.powerState});- XC_LOGI("consoles: %zu", tiles.size()); // not their names or ids+ std::string states;+ for (const auto& c : consoles) states += (states.empty() ? "" : ", ") + c.powerState;+ XC_LOGI("consoles: %zu (%s)", tiles.size(), states.c_str()); // not their names or idsg_ui->setConsoles(std::move(tiles), true);}@@ -737,6 +764,7 @@ void worker() {// at once ("... State WaitingForServerToRegister"): asked// again, it often wakes.std::string result;+ g_playingHome = true;for (int attempt = 0; attempt < 3 && !g_cancel; ++attempt) {if (attempt) {g_ui->setLaunchStatus(ui::tr(ui::Str::WakingConsole));@@ -746,12 +774,14 @@ void worker() {XC_LOGI("%s", result.c_str());if (!failed || result.find("WaitingForServerToRegister") == std::string::npos) break;}- if (failed && result.find("WaitingForServerToRegister") != std::string::npos)+ if (failed && (result.find("WaitingForServerToRegister") != std::string::npos ||+ result.find("ConsoleDidNotWake") != std::string::npos))g_ui->showPlayError(ui::trf(ui::Str::WakeFailed, tile.name), tile);else if (failed)g_ui->showPlayError(result.rfind("ERROR: ", 0) == 0 ? result.substr(7) : result, tile);else- g_ui->showHome(ui::tr(ui::Str::StreamEnded));+ g_ui->showHome(endedToast(result));+ g_playingHome = false;autoplayFinished(result);loadConsoles(am, home); // its state changedbreak;@@ -800,7 +830,7 @@ void worker() {g_ui->showError(result.rfind("ERROR: ", 0) == 0 ? result.substr(7) : result);}else- g_ui->showHome(ui::tr(ui::Str::StreamEnded));+ g_ui->showHome(endedToast(result));autoplayFinished(result);break;}@@ -1049,11 +1079,16 @@ int main(int argc, char** argv) {bool wasOpen = menu.isOpen();if (!wasOpen && menuCombo && g_keyboardFor.empty()) {menu.setCircleConfirms(g_settings.circleConfirms);- menu.open(streamResolution, showStats, sharpness, deband, upscaler);+ menu.open(streamResolution, showStats, sharpness, deband, upscaler, g_playingHome);overlaySeq = 0;} else if (wasOpen) {switch (menu.handle(nav)) {case ui::MenuAction::Leave: g_cancel = true; break;+ case ui::MenuAction::XboxButton:+ // A short press, once the menu is gone: the Xbox guide opens.+ g_xboxButtonUntil = platform::nowMs() + 250;+ XC_LOGI("menu: Xbox button");+ break;case ui::MenuAction::Refresh: g_player->requestKeyframe(); break;case ui::MenuAction::Resolution:streamResolution = menu.resolution();@@ -1114,6 +1149,7 @@ int main(int argc, char** argv) {if (menu.isOpen() || !g_keyboardFor.empty()) padReleased = false;else if (!held) padReleased = true;if (!padReleased || menuCombo) sent = input::ControllerState{};+ if (platform::nowMs() < g_xboxButtonUntil) sent.btnNexus = true;g_player->sendInput(sent);// The other players' controllers, straight to the game.for (int i = 1; i < input::kMaxPads; ++i) {diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cppindex 4eab779..a238e5f 100644--- a/src/app/stream_player.cpp+++ b/src/app/stream_player.cpp@@ -563,6 +563,7 @@ void StreamPlayer::sendInput(const input::ControllerState& p, int index) {set(p.btnR3, stream::kRightThumb);set(p.btnOptions, stream::kMenu);set(p.btnTouchpad, stream::kView);+ set(p.btnNexus, stream::kNexus);f.leftX = p.leftStickX;f.leftY = -p.leftStickY; // pad: +down; wire: +upf.rightX = p.rightStickX;diff --git a/src/input/controller.h b/src/input/controller.hindex dfd279a..8c944f0 100644--- a/src/input/controller.h+++ b/src/input/controller.h@@ -28,6 +28,7 @@ struct ControllerState {bool btnOptions = false; // Menubool btnTouchpad = false; // View / Select+ bool btnNexus = false; // the Xbox button (from the game menu; the PS button stays the system's)// Analog axes [-1.0 .. 1.0]float leftStickX = 0.0f;diff --git a/src/ui/stream_menu.cpp b/src/ui/stream_menu.cppindex 7a39670..c35e51c 100644--- a/src/ui/stream_menu.cpp+++ b/src/ui/stream_menu.cpp@@ -29,8 +29,9 @@ std::string fmt(const char* f, double v) {} // namespace-void StreamMenu::open(int resolution, bool stats, int sharpness, int deband, int upscaler) {+void StreamMenu::open(int resolution, bool stats, int sharpness, int deband, int upscaler, bool homeConsole) {open_ = true;+ homeConsole_ = homeConsole;stats_ = stats;sharpness_ = sharpness;deband_ = deband;@@ -74,6 +75,7 @@ MenuAction StreamMenu::handle(const NavInput& in) {if (!in.accept) return MenuAction::None;switch (selected_) {case Resume: open_ = false; return MenuAction::Close;+ case XboxButton: open_ = false; return MenuAction::XboxButton;case Stats: stats_ = !stats_; return MenuAction::Stats;case Resolution:applied_ = resolution_;@@ -93,7 +95,7 @@ Canvas StreamMenu::renderMenu(const StreamInfo& info) const {fonts_.bold.draw(c, tr(Str::MenuTitle), kPad, 40, 34, kWhite);// The items: the selected one white, like the Xbox guide.- constexpr int kRowH = 54, kTop = 108, kPx = 24;+ constexpr int kRowH = 50, kTop = 108, 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_;@@ -101,12 +103,14 @@ Canvas StreamMenu::renderMenu(const StreamInfo& info) const {Color fg = sel ? kDark : kWhite;int ty = fonts_.semibold.centeredY(row.y, row.h, kPx);const char* label = i == Resume ? tr(Str::MenuResume)+ : i == XboxButton ? tr(Str::MenuXboxButton): i == Stats ? tr(Str::MenuStats): i == Sharpness ? tr(Str::MenuSharpness): i == Deband ? tr(Str::MenuDeband): i == Upscaler ? tr(Str::MenuUpscaler): i == Resolution ? tr(Str::MenuResolution): i == Refresh ? tr(Str::MenuRefresh)+ : homeConsole_ ? tr(Str::MenuEndStream): tr(Str::MenuLeave);fonts_.semibold.draw(c, label, row.x + 16, ty, kPx, fg);std::string value;diff --git a/src/ui/stream_menu.h b/src/ui/stream_menu.hindex 35ea005..d4ff238 100644--- a/src/ui/stream_menu.h+++ b/src/ui/stream_menu.h@@ -23,11 +23,11 @@ struct StreamInfo {int width = 0, height = 0; // of the decoded picture};-enum class MenuAction { None, Close, Leave, Refresh, Resolution, Stats, Sharpness, Deband, Upscaler };+enum class MenuAction { None, Close, Leave, Refresh, Resolution, Stats, Sharpness, Deband, Upscaler, XboxButton };class StreamMenu {public:- static constexpr int kMenuW = 620, kMenuH = 1046;+ static constexpr int kMenuW = 620, kMenuH = 1064;static constexpr int kMenuX = 80, kMenuY = (1080 - kMenuH) / 2;static constexpr int kStatsX = 32, kStatsY = 28;@@ -37,7 +37,8 @@ public:// `sharpness` 0 = off, 1..3 = low, medium, high; `deband` 0..2 = off,// low, high.// `upscaler` 0 = FSR, 1 = Anime4K.- void open(int resolution, bool stats, int sharpness = 0, int deband = 1, int upscaler = 0);+ // `homeConsole`: the user's own Xbox ("End the stream" instead of "Leave the game").+ void open(int resolution, bool stats, int sharpness = 0, int deband = 1, int upscaler = 0, bool homeConsole = false);void close() { open_ = false; }bool isOpen() const { return open_; }MenuAction handle(const NavInput& in);@@ -55,7 +56,7 @@ public:Canvas renderStats(const StreamInfo& info) const;private:- enum Item { Resume, Stats, Upscaler, Sharpness, Deband, Resolution, Refresh, Leave, ItemCount };+ enum Item { Resume, XboxButton, Stats, Upscaler, Sharpness, Deband, Resolution, Refresh, Leave, ItemCount };const Fonts& fonts_;bool open_ = false, stats_ = false;@@ -64,6 +65,7 @@ private:int sharpness_ = 0, deband_ = 1, upscaler_ = 0;bool resolutionAsked_ = false;bool circleConfirms_ = false;+ bool homeConsole_ = false;PadSlots pads_{};};diff --git a/src/ui/strings.cpp b/src/ui/strings.cppindex 35270ae..cbc9a13 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -171,6 +171,11 @@ constexpr Column kEnglish = {"Settings > General > Power options: choose Sleep, so it wakes up by itself.", // ConsoleStep3"Scan for Microsoft's help", // ScanForHelp"Search again", // SearchAgain+ "Xbox button", // MenuXboxButton+ "End the stream", // MenuEndStream+ "The stream was ended on the Xbox", // EndedOnXbox+ "Another device took over the stream", // EndedByOtherDevice+ "The Xbox was turned off", // EndedXboxOff};constexpr Column kPortugueseBR = {@@ -312,6 +317,11 @@ constexpr Column kPortugueseBR = {"Configurações > Geral > Opções de energia: escolha Suspensão, para ele acordar sozinho.","Escaneie para a ajuda da Microsoft","Procurar de novo",+ "Botão Xbox",+ "Encerrar transmissão",+ "A transmissão foi encerrada no Xbox",+ "Outro aparelho assumiu a transmissão",+ "O Xbox foi desligado",};constexpr Column kSpanish = {@@ -453,6 +463,11 @@ constexpr Column kSpanish = {"Configuración > General > Opciones de energía: elige Suspensión, para que se encienda sola.","Escanea para ver la ayuda de Microsoft","Buscar de nuevo",+ "Botón Xbox",+ "Terminar la transmisión",+ "La transmisión se terminó en la Xbox",+ "Otro dispositivo tomó la transmisión",+ "La Xbox se apagó",};constexpr Column kFrench = {@@ -594,6 +609,11 @@ constexpr Column kFrench = {"Paramètres > Général > Options d'alimentation : choisissez Veille, pour qu'elle se réveille seule.","Scannez pour l'aide de Microsoft","Rechercher à nouveau",+ "Bouton Xbox",+ "Arrêter la diffusion",+ "La diffusion a été arrêtée sur la Xbox",+ "Un autre appareil a repris la diffusion",+ "La Xbox a été éteinte",};constexpr Column kGerman = {@@ -735,6 +755,11 @@ constexpr Column kGerman = {"Einstellungen > Allgemein > Energieoptionen: Ruhezustand wählen, damit sie von selbst aufwacht.","Scannen für die Hilfe von Microsoft","Erneut suchen",+ "Xbox-Taste",+ "Streaming beenden",+ "Das Streaming wurde auf der Xbox beendet",+ "Ein anderes Gerät hat das Streaming übernommen",+ "Die Xbox wurde ausgeschaltet",};constexpr Column kItalian = {@@ -876,6 +901,11 @@ constexpr Column kItalian = {"Impostazioni > Generale > Opzioni di alimentazione: scegli Sospensione, così si accende da sola.","Scansiona per l'aiuto di Microsoft","Cerca di nuovo",+ "Pulsante Xbox",+ "Termina lo streaming",+ "Lo streaming è stato terminato sulla Xbox",+ "Un altro dispositivo ha preso lo streaming",+ "La Xbox è stata spenta",};constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,diff --git a/src/ui/strings.h b/src/ui/strings.hindex 89544d8..d9c20b9 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -148,6 +148,11 @@ enum class Str {ConsoleStep3,ScanForHelp, // under the QR code of Microsoft's Remote Play helpSearchAgain, // refresh the console list+ MenuXboxButton, // game menu: press the Xbox button (opens the Xbox guide)+ MenuEndStream, // game menu on the user's own Xbox: instead of "Leave the game"+ EndedOnXbox, // toast: the Xbox ended the stream+ EndedByOtherDevice, // toast: another device took the stream over+ EndedXboxOff, // toast: the Xbox was turned off during the streamCount};diff --git a/src/xcloud/gssv.cpp b/src/xcloud/gssv.cppindex 67effdd..4f9aed9 100644--- a/src/xcloud/gssv.cpp+++ b/src/xcloud/gssv.cpp@@ -356,6 +356,13 @@ bool GssvClient::listConsoles(std::vector<Console>& out, std::string& err) {return false;}for (const auto& c : (*j)["results"].items()) {+ static bool keysLogged = false; // which fields the service sends (names only)+ if (!keysLogged) {+ keysLogged = true;+ std::string keys;+ for (const auto& [k, v] : c.members()) keys += k + (v.isString() ? "" : "*") + " ";+ XC_LOGI("console fields: %s", keys.c_str());+ }Console con;con.serverId = c["serverId"].str();con.deviceName = c["deviceName"].str();@@ -543,8 +550,8 @@ bool GssvClient::keepalive(std::string& err) {void GssvClient::stopSession() {if (sessionPath_.empty()) return;- net::perform(authed(resolution_, login_, "DELETE", sessionUrl("")));- XC_LOGI("session stopped: %s", sessionPath_.c_str());+ auto r = net::perform(authed(resolution_, login_, "DELETE", sessionUrl("")));+ XC_LOGI("session stopped: %s (%s)", sessionPath_.c_str(), r.ok() ? "ok" : describe(r).c_str());sessionPath_.clear();}diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 9f2a349..80b896b 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -223,6 +223,11 @@ static void testStreamMenu() {menu.open(0, false);CHECK(menu.isOpen());press([](xc::ui::NavInput& n) { n.down = true; });+ CHECK(press([](xc::ui::NavInput& n) { n.accept = true; }) == MenuAction::XboxButton); // and it closes+ CHECK(!menu.isOpen());+ menu.open(0, false);+ press([](xc::ui::NavInput& n) { n.down = true; });+ 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; });@@ -240,7 +245,7 @@ static void testStreamMenu() {press([](xc::ui::NavInput& n) { n.left = true; }); // wraps to 1440pCHECK(menu.resolution() == 2);CHECK(press([](xc::ui::NavInput& n) { n.accept = true; }) == MenuAction::Resolution);- for (int i = 0; i < 6; ++i) press([](xc::ui::NavInput& n) { n.up = true; }); // wraps to "Leave game"+ for (int i = 0; i < 7; ++i) 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);