Xbox Cloud Gaming app for PS5 Homebrew
C
Touchpad swipe for the Xbox button; a leaner game menu; own-Xbox reconnect
Rafael Abud Ferreira6b738075312c
diff --git a/ps5/release/README.txt b/ps5/release/README.txtindex 8d6f5bb..ffdda7e 100644--- a/ps5/release/README.txt+++ b/ps5/release/README.txt@@ -62,16 +62,19 @@ In game: the DualSense acts as an Xbox controllerGame menu----------OPTIONS + TOUCHPAD during a game: resume, the statistics line over the-game, upscaling (FSR, or AI: Anime4K, crisper outlines and text but-it also sharpens compression noise), sharpness (off / low / medium /-high: sharpens the picture's edges), block smoothing (off / low / high: smooths the squares+OPTIONS + TOUCHPAD during a game: the Xbox button (opens the Xbox+guide), the statistics line over the game, upscaling (FSR, or AI:+Anime4K, crisper outlines and text but it also sharpens compression+noise), sharpness (off / low / medium / high: sharpens the picture's+edges), block smoothing (off / low / high: smooths the squarescompression leaves in dark, flat areas; low keeps textures best),stream resolution (720p / 1080p / 1440p, changed in a few seconds),-refresh the picture, and leave the game. It also shows the-connection (region, latency, bitrate, frame rate, packet loss, and how-long a frame takes from the network to the TV) and the controllers in-use.+and leave the game. Circle closes it (and asks for a clean picture).+It also shows the connection (region, latency, bitrate, frame rate,+packet loss, and how long a frame takes from the network to the TV)+and the controllers in use.++Swiping up or right on the touchpad is the Xbox button too.If the connection drops for a moment, the stream reconnects by itselfand the game goes on where it was.@@ -109,7 +112,8 @@ screen, games and apps, on the PS5. On the Xbox, turn on Settings >Devices & connections > Remote features, and choose the Sleep powermode so it wakes up by itself (it takes about ten seconds).-In the game menu, "Xbox button" opens the Xbox's own guide. To stop,+The Xbox button (game menu, or a swipe on the touchpad) opens the+Xbox's own guide. To stop,use "End the stream" in the game menu (or stop it from the guide).Turning the Xbox off from the guide in the middle of a stream can leaveits Remote Play stuck: the app then says so, and holding the console'sdiff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex b7a0071..3b699bd 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -288,6 +288,7 @@ std::string stream(xcloud::GssvClient& gssv) {}g_ui->showStreaming();platform::notify(ui::tr(ui::Str::LeaveHint));+ if (gssv.isHome()) platform::notify(ui::tr(ui::Str::SwipeHint));const uint64_t started = platform::nowMs();uint64_t nextTick = started;@@ -765,6 +766,7 @@ void worker() {// again, it often wakes.std::string result;g_playingHome = true;+ int rejoins = 0;for (int attempt = 0; attempt < 3 && !g_cancel; ++attempt) {if (attempt) {g_ui->setLaunchStatus(ui::tr(ui::Str::WakingConsole));@@ -772,6 +774,16 @@ void worker() {}result = play(am, home, tile, failed);XC_LOGI("%s", result.c_str());+ // The connection dropped mid-stream: a new session on+ // the same Xbox picks up where it was (twice at most).+ if (!failed && !g_cancel && result.find("couldn't be restored") != std::string::npos &&+ rejoins < 2) {+ ++rejoins;+ XC_LOGI("own Xbox: connection lost, new session (%d)", rejoins);+ platform::notify(ui::tr(ui::Str::Reconnecting));+ attempt = -1; // a new start, not a wake-up retry+ continue;+ }if (!failed || result.find("WaitingForServerToRegister") == std::string::npos) break;}if (failed && result.find("Cloud Streaming Service to be ready") != std::string::npos)@@ -939,6 +951,10 @@ int main(int argc, char** argv) {int streamResolution = 0; // as SettingsChoice::resolutionbool showStats = false, overlayShown = false;bool touchEnabled = false; // touch input announced on (StreamPlayer::setTouchEnabled)+ struct {+ bool active = false, fired = false;+ float x = 0, y = 0; // where the finger came down+ } swipe;int sharpness = 0; // 0..3, as Settings::sharpnessint deband = 1; // 0..2, as Settings::debandint upscaler = 0; // as Settings::upscaler@@ -1092,9 +1108,10 @@ int main(int argc, char** argv) {case ui::MenuAction::XboxButton:// A short press, once the menu is gone: the Xbox guide opens.g_xboxButtonUntil = platform::nowMs() + 250;+ g_player->requestKeyframe();XC_LOGI("menu: Xbox button");break;- case ui::MenuAction::Refresh: g_player->requestKeyframe(); break;+ case ui::MenuAction::Close: g_player->requestKeyframe(); break; // a clean picture back in the gamecase ui::MenuAction::Resolution:streamResolution = menu.resolution();g_player->requestResolution(streamResolution == 1 ? "720HQ"@@ -1154,6 +1171,20 @@ 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{};+ // Swiping up or right on the touchpad is the Xbox button (once+ // per swipe; the games never see the touchpad's touches).+ if (pad.touching && !menu.isOpen() && g_keyboardFor.empty()) {+ if (!swipe.active) swipe = {true, false, pad.touchX, pad.touchY};+ float dx = pad.touchX - swipe.x, dy = swipe.y - pad.touchY; // dy > 0: up+ bool right = dx > 0.30f && std::abs(dy) < 0.30f, up = dy > 0.40f && std::abs(dx) < 0.30f;+ if (!swipe.fired && (right || up)) {+ swipe.fired = true;+ g_xboxButtonUntil = platform::nowMs() + 250;+ XC_LOGI("touchpad swipe %s: Xbox button", right ? "right" : "up");+ }+ } else {+ swipe.active = false;+ }if (platform::nowMs() < g_xboxButtonUntil) sent.btnNexus = true;g_player->sendInput(sent);// The other players' controllers, straight to the game.diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cppindex a238e5f..61f391e 100644--- a/src/app/stream_player.cpp+++ b/src/app/stream_player.cpp@@ -51,7 +51,7 @@ struct StreamPlayer::Impl {std::atomic<bool> titleFocused{true};int reconnectAttempts = 0;std::atomic<uint32_t> reconnects{0};- uint64_t lastRtpPackets = 0;+ uint64_t lastRtpPackets = 0, lastAudioPackets = 0;int silentTicks = 0;std::mutex mutex;@@ -409,6 +409,15 @@ struct StreamPlayer::Impl {XC_LOGW("reconnect %d: no session state (%s)", reconnectAttempts, err.c_str());return; // the network may not be back yet}+ if (status.state == xcloud::SessionState::Provisioning ||+ status.state == xcloud::SessionState::WaitingForResources) {+ // Being set up again: wait. A home Xbox's session that dropped+ // stays there for good: a new session is started instead (the+ // caller does it; the game goes on on the console meanwhile).+ XC_LOGI("reconnect %d: session %s, waiting", reconnectAttempts, status.raw.c_str());+ if (gssv.isHome() && reconnectAttempts >= 4) end("the connection was lost and couldn't be restored");+ return;+ }if (status.state != xcloud::SessionState::Provisioned && status.state != xcloud::SessionState::ReadyToConnect) {end("the session ended on the server while reconnecting (" + status.raw + ")");return;@@ -438,6 +447,7 @@ struct StreamPlayer::Impl {reconnectAttempts = 0;silentTicks = 0;lastRtpPackets = 0;+ lastAudioPackets = 0;++reconnects;keyframeWanted = true;platform::notify(ui::tr(ui::Str::Reconnected));@@ -506,11 +516,18 @@ struct StreamPlayer::Impl {s->tick();// xCloud sends video all the time, even for a still picture: three// seconds without a packet is a dead connection, long before WebRTC- // notices.+ // notices. With the sound still coming, the connection is alive and+ // the picture only paused (a home Xbox does it while a game starts+ // and switches display modes): up to 15 s then.uint64_t packets = s->videoStats().packets;+ uint64_t audio = audioPackets;+ bool audioAlive = audio != lastAudioPackets;+ lastAudioPackets = audio;silentTicks = packets == lastRtpPackets ? silentTicks + 1 : 0;lastRtpPackets = packets;- if (silentTicks >= 3 && !reconnecting.exchange(true)) XC_LOGW("no video for 3 s: reconnecting");+ int limit = audioAlive ? 15 : 3;+ if (silentTicks >= limit && !reconnecting.exchange(true))+ XC_LOGW("no video for %d s%s: reconnecting", silentTicks, audioAlive ? " (sound still coming)" : "");}void stop() {diff --git a/src/input/controller.cpp b/src/input/controller.cppindex 52bbd61..ec48412 100644--- a/src/input/controller.cpp+++ b/src/input/controller.cpp@@ -390,6 +390,13 @@ bool pollPad(int index, ControllerState& out) {out.triggerL2 = normTrigger(pad.l2);out.triggerR2 = normTrigger(pad.r2);+ // The DualSense touchpad reports 0..1919 x 0..1079.+ if (pad.touchData.touchNum > 0) {+ out.touching = true;+ out.touchX = std::clamp(pad.touchData.touch[0].x / 1919.0f, 0.0f, 1.0f);+ out.touchY = std::clamp(pad.touchData.touch[0].y / 1079.0f, 0.0f, 1.0f);+ }+return true;}diff --git a/src/input/controller.h b/src/input/controller.hindex 8c944f0..755ce41 100644--- a/src/input/controller.h+++ b/src/input/controller.h@@ -39,6 +39,10 @@ struct ControllerState {// Triggers [0.0 .. 1.0]float triggerL2 = 0.0f;float triggerR2 = 0.0f;++ // A finger on the touchpad, at (touchX, touchY) in [0, 1] from the top left.+ bool touching = false;+ float touchX = 0.0f, touchY = 0.0f;};// Up to four DualSense: pad 0 belongs to the user who started the app, thediff --git a/src/ui/stream_menu.cpp b/src/ui/stream_menu.cppindex c35e51c..d535480 100644--- a/src/ui/stream_menu.cpp+++ b/src/ui/stream_menu.cpp@@ -36,7 +36,7 @@ void StreamMenu::open(int resolution, bool stats, int sharpness, int deband, intsharpness_ = sharpness;deband_ = deband;upscaler_ = upscaler;- selected_ = Resume;+ selected_ = XboxButton;resolution_ = applied_ = resolution;resolutionAsked_ = false;}@@ -74,14 +74,12 @@ 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_;resolutionAsked_ = true;return MenuAction::Resolution;- case Refresh: return MenuAction::Refresh;case Leave: open_ = false; return MenuAction::Leave;default: return MenuAction::None;}@@ -95,21 +93,19 @@ 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 = 50, kTop = 108, kPx = 24;+ constexpr int kRowH = 54, 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_;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 == XboxButton ? tr(Str::MenuXboxButton)+ const char* label = 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);diff --git a/src/ui/stream_menu.h b/src/ui/stream_menu.hindex d4ff238..744e21d 100644--- a/src/ui/stream_menu.h+++ b/src/ui/stream_menu.h@@ -23,11 +23,12 @@ struct StreamInfo {int width = 0, height = 0; // of the decoded picture};-enum class MenuAction { None, Close, Leave, Refresh, Resolution, Stats, Sharpness, Deband, Upscaler, XboxButton };+// Close: the menu went away (Circle, OPTIONS, or the Xbox button): a fresh key frame is asked for.+enum class MenuAction { None, Close, Leave, Resolution, Stats, Sharpness, Deband, Upscaler, XboxButton };class StreamMenu {public:- static constexpr int kMenuW = 620, kMenuH = 1064;+ static constexpr int kMenuW = 620, kMenuH = 992;static constexpr int kMenuX = 80, kMenuY = (1080 - kMenuH) / 2;static constexpr int kStatsX = 32, kStatsY = 28;@@ -56,11 +57,11 @@ public:Canvas renderStats(const StreamInfo& info) const;private:- enum Item { Resume, XboxButton, Stats, Upscaler, Sharpness, Deband, Resolution, Refresh, Leave, ItemCount };+ enum Item { XboxButton, Stats, Upscaler, Sharpness, Deband, Resolution, Leave, ItemCount };const Fonts& fonts_;bool open_ = false, stats_ = false;- int selected_ = Resume;+ int selected_ = XboxButton;int resolution_ = 0, applied_ = 0;int sharpness_ = 0, deband_ = 1, upscaler_ = 0;bool resolutionAsked_ = false;diff --git a/src/ui/strings.cpp b/src/ui/strings.cppindex 966997d..7fe3502 100644--- a/src/ui/strings.cpp+++ b/src/ui/strings.cpp@@ -115,12 +115,10 @@ constexpr Column kEnglish = {"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@@ -177,6 +175,7 @@ constexpr Column kEnglish = {"Another device took over the stream", // EndedByOtherDevice"The Xbox was turned off", // EndedXboxOff"%s got the request but its Remote Play didn't start. Restart it: hold the power button on the console for 10 seconds, turn it back on, then try again.", // StreamingStuck+ "Swipe up or right on the touchpad for the Xbox button", // SwipeHint};constexpr Column kPortugueseBR = {@@ -262,12 +261,10 @@ constexpr Column kPortugueseBR = {"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",@@ -324,6 +321,7 @@ constexpr Column kPortugueseBR = {"Outro aparelho assumiu a transmissão","O Xbox foi desligado","%s recebeu o pedido, mas o jogo remoto dele não iniciou. Reinicie o console: segure o botão de ligar do Xbox por 10 segundos, ligue de novo e tente outra vez.",+ "Deslize para cima ou para a direita no touchpad: botão Xbox",};constexpr Column kSpanish = {@@ -409,12 +407,10 @@ constexpr Column kSpanish = {"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",@@ -471,6 +467,7 @@ constexpr Column kSpanish = {"Otro dispositivo tomó la transmisión","La Xbox se apagó","%s recibió la solicitud, pero su juego remoto no se inició. Reiníciala: mantén pulsado el botón de encendido de la consola 10 segundos, enciéndela de nuevo y vuelve a intentarlo.",+ "Desliza hacia arriba o a la derecha en el panel táctil: botón Xbox",};constexpr Column kFrench = {@@ -556,12 +553,10 @@ constexpr Column kFrench = {"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",@@ -618,6 +613,7 @@ constexpr Column kFrench = {"Un autre appareil a repris la diffusion","La Xbox a été éteinte","%s a reçu la demande, mais son jeu à distance n'a pas démarré. Redémarrez-la : maintenez le bouton d'alimentation de la console 10 secondes, rallumez-la, puis réessayez.",+ "Glissez vers le haut ou la droite sur le pavé tactile : bouton Xbox",};constexpr Column kGerman = {@@ -703,12 +699,10 @@ constexpr Column kGerman = {"Abschnitte","Spieleliste wird aktualisiert...","Spielmenü",- "Fortsetzen","Statistiken","An","Aus","Stream-Auflösung",- "Bild aktualisieren","Spiel verlassen","Latenz","Bitrate",@@ -765,6 +759,7 @@ constexpr Column kGerman = {"Ein anderes Gerät hat das Streaming übernommen","Die Xbox wurde ausgeschaltet","%s hat die Anfrage erhalten, aber Remote Play ist nicht gestartet. Starte sie neu: Halte die Ein/Aus-Taste der Konsole 10 Sekunden gedrückt, schalte sie wieder ein und versuche es erneut.",+ "Wische auf dem Touchpad nach oben oder rechts: Xbox-Taste",};constexpr Column kItalian = {@@ -850,12 +845,10 @@ constexpr Column kItalian = {"Sezioni","Aggiornamento dell'elenco dei giochi...","Menu di gioco",- "Riprendi","Statistiche","Attivo","Disattivo","Risoluzione dello stream",- "Aggiorna l'immagine","Esci dal gioco","Latenza","Bitrate",@@ -912,6 +905,7 @@ constexpr Column kItalian = {"Un altro dispositivo ha preso lo streaming","La Xbox è stata spenta","%s ha ricevuto la richiesta, ma il gioco remoto non è partito. Riavviala: tieni premuto il pulsante di accensione della console per 10 secondi, riaccendila e riprova.",+ "Scorri verso l'alto o a destra sul touchpad: pulsante Xbox",};constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,diff --git a/src/ui/strings.h b/src/ui/strings.hindex ab4242b..d956dba 100644--- a/src/ui/strings.h+++ b/src/ui/strings.h@@ -92,12 +92,10 @@ enum class Str {Sections, // hint for L2 / R2: jump between sectionsUpdatingList, // the lists refresh in the backgroundMenuTitle, // the in-game menu- MenuResume,MenuStats, // show the statistics over the gameOn,Off,MenuResolution,- MenuRefresh, // ask for a new picture (key frame)MenuLeave,StatLatency,StatBitrate,@@ -154,6 +152,7 @@ enum class Str {EndedByOtherDevice, // toast: another device took the stream overEndedXboxOff, // toast: the Xbox was turned off during the streamStreamingStuck, // "%s" = the console: its Remote Play service didn't start+ SwipeHint, // at the start of a stream from the user's own XboxCount};diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 80b896b..7b841a7 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -222,12 +222,10 @@ static void testStreamMenu() {CHECK(press([](xc::ui::NavInput& n) { n.accept = true; }) == MenuAction::None); // closedmenu.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(press([](xc::ui::NavInput& n) { n.accept = true; }) == MenuAction::XboxButton); // first; it closesCHECK(!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; });@@ -245,7 +243,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 < 7; ++i) press([](xc::ui::NavInput& n) { n.up = true; }); // wraps to "Leave game"+ press([](xc::ui::NavInput& n) { n.down = true; }); // "Leave game", lastCHECK(press([](xc::ui::NavInput& n) { n.accept = true; }) == MenuAction::Leave);CHECK(!menu.isOpen());menu.open(1, true);