Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

feat: 120Hz/VRR, Audio PLC, unreliable input channel, Favourites row, game language, and playtime limit

Rafael Abud Ferreira307a1a019913
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 521646a..d4d90dd 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2026 RafaelNGP
cmake_minimum_required(VERSION 3.20)
-project(xcloud_ps5 VERSION 1.1.0 LANGUAGES C CXX)
+project(xcloud_ps5 VERSION 1.2.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
diff --git a/ps5/sce_sys/param.json b/ps5/sce_sys/param.json
index cff3fd0..1f1fb7c 100644
--- a/ps5/sce_sys/param.json
+++ b/ps5/sce_sys/param.json
@@ -10,7 +10,7 @@
"conceptId": "99810",
"contentBadgeType": 1,
"contentId": "UP9000-PPSA99810_00-XCLOUDPS5CLI0000",
- "contentVersion": "01.100.000",
+ "contentVersion": "01.200.000",
"downloadDataSize": 256,
"gameIntent": {
"permittedIntents": [
diff --git a/src/app/app_core.cpp b/src/app/app_core.cpp
index 1918ead..568f2ad 100644
--- a/src/app/app_core.cpp
+++ b/src/app/app_core.cpp
@@ -327,7 +327,8 @@ bool coreStartup() {
g_ui->setRegionLatency(g_settings.regionRtt);
g_ui->setPrefs(g_settings.hidden, g_settings.librarySort == "az" ? ui::LibrarySort::AZ
: g_settings.librarySort == "console" ? ui::LibrarySort::Console
- : ui::LibrarySort::Recent);
+ : ui::LibrarySort::Recent,
+ g_settings.favorites);
}
g_ui->setCaps(uiCaps());
g_core->canvas.emplace(display::kWidth, display::kHeight);
@@ -669,11 +670,13 @@ bool Core::frame() {
case ui::Action::PrefsChanged: {
std::lock_guard<std::mutex> lock(g_settingsMutex);
g_settings.hidden = ev.hidden;
+ g_settings.favorites = ev.favorites;
g_settings.librarySort = ev.librarySort == ui::LibrarySort::AZ ? "az"
: ev.librarySort == ui::LibrarySort::Console ? "console"
: "recent";
g_settings.save(settingsPath()); // warns itself
- XC_LOGI("prefs saved: %zu hidden, sort %s", g_settings.hidden.size(), g_settings.librarySort.c_str());
+ XC_LOGI("prefs saved: %zu hidden, %zu favorites, sort %s", g_settings.hidden.size(), g_settings.favorites.size(), g_settings.librarySort.c_str());
+ updateLibraryFavorites(g_settings.favorites);
break;
}
case ui::Action::GameSettingsChanged: {
diff --git a/src/app/app_state.h b/src/app/app_state.h
index 6518797..04b8784 100644
--- a/src/app/app_state.h
+++ b/src/app/app_state.h
@@ -41,6 +41,8 @@ void worker();
void startWorker();
// The update pop-up's "Not now": that release isn't offered again on start.
void skipOfferedUpdate();
+// Updates the running library's favorites list and refreshes UI rows.
+void updateLibraryFavorites(const std::vector<std::string>& favorites);
// The running stream, for the input thread.
extern std::mutex g_playerMutex;
diff --git a/src/app/library.cpp b/src/app/library.cpp
index 813a380..36fae9b 100644
--- a/src/app/library.cpp
+++ b/src/app/library.cpp
@@ -250,6 +250,23 @@ std::vector<ui::GameRow> Library::rows() const {
}
}
+ // Insert "Favorites" row at the top of the library if any are marked
+ if (!favorites_.empty()) {
+ ui::GameRow favRow;
+ favRow.title = ui::tr(ui::Str::Favorites);
+ favRow.gamePassBadges = false;
+ favRow.isGrid = false;
+ for (const auto& pid : favorites_) {
+ ui::GameTile t = tile(pid);
+ if (!t.productId.empty() && !t.titleId.empty() && !xcloud::isNonGameAddon(t.titleId, t.name)) {
+ favRow.tiles.push_back(std::move(t));
+ }
+ }
+ if (!favRow.tiles.empty()) {
+ rows.insert(rows.begin(), std::move(favRow));
+ }
+ }
+
return rows;
}
diff --git a/src/app/library.h b/src/app/library.h
index 70ef3a6..5727915 100644
--- a/src/app/library.h
+++ b/src/app/library.h
@@ -45,6 +45,8 @@ public:
void setCachePath(std::string path) { cachePath_ = std::move(path); }
// The account's Game Pass plan ("Ultimate", "Premium", "Essential", ...).
void setSubscription(std::string sub) { subscription_ = std::move(sub); }
+ // Games marked as favourite (product IDs)
+ void setFavorites(std::vector<std::string> favs) { favorites_ = std::move(favs); }
// Calls `changed` after each row arrives; false only when nothing loaded.
bool load(xcloud::GssvClient& gssv, const std::string& language, const Changed& changed, std::string& err);
@@ -137,6 +139,7 @@ private:
mutable std::set<std::string> sharedXbox_; // Xbox title ids two products share (cross-gen pairs)
mutable size_t siblingsFor_ = 0;
std::vector<ui::GameTile> friendsTiles_;
+ std::vector<std::string> favorites_;
};
} // namespace xc::app
diff --git a/src/app/settings.cpp b/src/app/settings.cpp
index f36ed24..0d1ab47 100644
--- a/src/app/settings.cpp
+++ b/src/app/settings.cpp
@@ -56,6 +56,9 @@ bool Settings::load(const std::string& path) {
hidden.clear();
for (const auto& id : (*j)["hidden"].items())
if (!id.str().empty()) hidden.push_back(id.str());
+ favorites.clear();
+ for (const auto& id : (*j)["favorites"].items())
+ if (!id.str().empty()) favorites.push_back(id.str());
librarySort = (*j)["librarySort"].str(librarySort);
streamStats = (*j)["streamStats"].asBool(streamStats);
sharpness = static_cast<int>(std::clamp<int64_t>((*j)["sharpness"].asInt(sharpness), 0, 3));
@@ -134,6 +137,7 @@ bool Settings::load(const std::string& path) {
p.gyroMode = static_cast<int>(std::clamp<int64_t>(obj["gyroMode"].asInt(gyroMode), 0, 2));
p.gyroLevel = static_cast<int>(std::clamp<int64_t>(obj["gyroLevel"].asInt(gyroLevel), 1, 10));
p.touchpadMouse = obj["touchpadMouse"].asBool(touchpadMouse);
+ p.locale = obj["locale"].str();
perGame[id] = p;
}
return true;
@@ -197,6 +201,9 @@ bool Settings::save(const std::string& path) const {
json::Value hiddenIds = json::Value::array();
for (const auto& id : hidden) hiddenIds.push(id);
v.set("hidden", hiddenIds);
+ json::Value favIds = json::Value::array();
+ for (const auto& id : favorites) favIds.push(id);
+ v.set("favorites", favIds);
v.set("librarySort", librarySort);
v.set("streamStats", streamStats);
v.set("sharpness", sharpness);
@@ -253,6 +260,7 @@ bool Settings::save(const std::string& path) const {
obj.set("gyroMode", p.gyroMode);
obj.set("gyroLevel", p.gyroLevel);
obj.set("touchpadMouse", p.touchpadMouse);
+ if (!p.locale.empty()) obj.set("locale", p.locale);
pg.set(id, obj);
}
v.set("perGame", pg);
diff --git a/src/app/settings.h b/src/app/settings.h
index 116ceb3..83c0235 100644
--- a/src/app/settings.h
+++ b/src/app/settings.h
@@ -37,6 +37,8 @@ struct GameProfile {
int gyroLevel = 5;
// Touchpad as mouse in games with native MKB support (OFF by default)
bool touchpadMouse = false;
+ // Per-game audio/subtitle language: "" = system default, else e.g. "en-US", "pt-BR"
+ std::string locale;
};
// Key to identify a game profile: productId first, else titleId.
@@ -55,6 +57,7 @@ struct Settings {
// Games hidden with Square (product ids), and the "Your games" order
// ("recent", "az", "console").
std::vector<std::string> hidden;
+ std::vector<std::string> favorites; // Games marked as favourite (product ids)
std::string librarySort = "recent";
// The statistics line over the game (in-game menu).
bool streamStats = false;
diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cpp
index 8af25ed..e89ecc6 100644
--- a/src/app/stream_player.cpp
+++ b/src/app/stream_player.cpp
@@ -68,8 +68,12 @@ struct StreamPlayer::Impl {
std::atomic<bool> running{false};
std::string endReason;
platform::Thread videoThread, audioThread;
+ struct QueuedAudioPacket {
+ std::vector<uint8_t> data;
+ uint32_t rtpTimestamp = 0;
+ };
std::mutex audioMutex_;
- std::deque<std::vector<uint8_t>> audioPackets_;
+ std::deque<QueuedAudioPacket> audioPackets_;
std::condition_variable audioCv;
media::AudioDecoder audioDecoder;
@@ -175,8 +179,11 @@ struct StreamPlayer::Impl {
}
void audioLoop() {
- std::vector<uint8_t> packet;
+ QueuedAudioPacket packet;
bool first = true;
+ uint32_t lastRtpTimestamp = 0;
+ uint64_t concealedPackets = 0;
+ constexpr uint32_t kOpusFrameSamples = 960; // 20 ms at 48 kHz
while (running) {
{
std::unique_lock<std::mutex> lock(audioMutex_);
@@ -185,8 +192,27 @@ struct StreamPlayer::Impl {
packet = std::move(audioPackets_.front());
audioPackets_.pop_front();
}
+ if (lastRtpTimestamp != 0) {
+ uint32_t diff = packet.rtpTimestamp - lastRtpTimestamp;
+ // Detect packet loss from RTP timestamp gap (conceal up to 5 lost frames)
+ if (diff > kOpusFrameSamples && diff <= kOpusFrameSamples * 6) {
+ uint32_t lostCount = (diff + kOpusFrameSamples / 2) / kOpusFrameSamples - 1;
+ for (uint32_t i = 0; i < lostCount; ++i) {
+ pcm.clear();
+ audioDecoder.conceal(pcm, kOpusFrameSamples);
+ if (!pcm.empty()) media::audioPush(pcm.data(), pcm.size() / 2);
+ ++concealedPackets;
+ }
+ if (concealedPackets <= 5 || concealedPackets % 50 == 0) {
+ XC_LOGI("audio plc: concealed %u lost packet(s) (%llu total concealed)",
+ lostCount, static_cast<unsigned long long>(concealedPackets));
+ }
+ }
+ }
+ lastRtpTimestamp = packet.rtpTimestamp;
+
pcm.clear();
- if (audioDecoder.decode(packet.data(), packet.size(), pcm)) media::audioPush(pcm.data(), pcm.size() / 2);
+ if (audioDecoder.decode(packet.data.data(), packet.data.size(), pcm)) media::audioPush(pcm.data(), pcm.size() / 2);
if (first) {
first = false;
XC_LOGI("first audio packet decoded: %zu samples", pcm.size() / 2);
@@ -388,10 +414,10 @@ struct StreamPlayer::Impl {
frames.push_back({std::vector<uint8_t>(d, d + n), rtpTimestamp, stream::clockMs(), platform::nowUs()});
cv.notify_one();
};
- cb.audio = [this](const uint8_t* d, size_t n, uint32_t) {
- if (++audioPackets == 1) XC_LOGI("first audio packet: %zu bytes", n);
+ cb.audio = [this](const uint8_t* d, size_t n, uint32_t rtpTimestamp) {
+ if (++audioPackets == 1) XC_LOGI("first audio packet: %zu bytes (timestamp %u)", n, rtpTimestamp);
std::lock_guard<std::mutex> lock(audioMutex_);
- if (audioPackets_.size() < 50) audioPackets_.emplace_back(d, d + n);
+ if (audioPackets_.size() < 50) audioPackets_.push_back({std::vector<uint8_t>(d, d + n), rtpTimestamp});
audioCv.notify_one();
};
// xCloud's motors are 0..100 percent, like the web client's
diff --git a/src/app/stream_screen.cpp b/src/app/stream_screen.cpp
index 24eb408..c41d378 100644
--- a/src/app/stream_screen.cpp
+++ b/src/app/stream_screen.cpp
@@ -148,9 +148,10 @@ void StreamScreen::update(const input::ControllerState& pad, ui::NavInput nav, b
input::setTriggerFeel(prof.triggerStrength, prof.triggerHz, prof.triggerResistance, prof.triggerPulses);
input::setCircleConfirms(prof.circleConfirms);
if (g_ui) g_ui->setCircleConfirms(prof.circleConfirms);
- // 120 Hz (VRR) for this game's stream only: the menus stay at 60 Hz
- // (OLED TVs may flicker under VRR when little is drawn).
- highRefresh_ = prof.highRefresh && display::setHighRefresh(true);
+ // 120 Hz (VRR) for this game's stream: active when enabled in profile,
+ // or defaulted on when the display supports switching refresh (menus stay at 60 Hz).
+ bool want120 = prof.highRefresh || (!hasCustom && display::canSwitchRefresh());
+ highRefresh_ = want120 && display::setHighRefresh(true);
media::audioSetRoute(static_cast<media::AudioRoute>(g_settings.audioRoute));
if (g_player) {
diff --git a/src/app/worker.cpp b/src/app/worker.cpp
index fd3fa05..96fe0f1 100644
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@ -58,6 +58,25 @@ bool g_gameClosedOnServer = false;
// Titles that would not start in the automatic region, and where they did
// (for the rest of this run).
std::map<std::string, std::string> g_regionFallback;
+std::shared_ptr<app::Library> s_library;
+std::mutex s_libraryMutex;
+int64_t s_playtimeRemainingSeconds = -1;
+
+} // namespace
+
+void updateLibraryFavorites(const std::vector<std::string>& favorites) {
+ std::shared_ptr<app::Library> lib;
+ {
+ std::lock_guard<std::mutex> lock(s_libraryMutex);
+ lib = s_library;
+ }
+ if (lib) {
+ lib->setFavorites(favorites);
+ g_ui->setRows(lib->rows());
+ }
+}
+
+namespace {
// Streams until the player ends or the user leaves; returns a status line.
// The cloud title being played, for crash markers (set by play()).
@@ -223,6 +242,9 @@ std::string stream(xcloud::GssvClient& gssv) {
session.kbps += st.rtpKbps;
if (st.rttMs > 0) session.rttSum += static_cast<uint64_t>(st.rttMs), ++session.rttCount;
}
+ if (s_playtimeRemainingSeconds >= 0) {
+ info.playtimeHours = static_cast<int>((s_playtimeRemainingSeconds + 3599) / 3600);
+ }
std::lock_guard<std::mutex> lock(g_infoMutex);
g_streamInfo = info;
++g_infoSeq;
@@ -287,10 +309,12 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game
g_ui->showLaunching(game, regionName.empty() ? ui::tr(ui::Str::Connecting)
: ui::trf(ui::Str::TryingRegion, ui::prettyRegion(regionName)));
std::string err;
+ std::string streamLocale = ui::gameLocale();
{
std::lock_guard<std::mutex> lock(g_settingsMutex);
bool hasCustom = false;
GameProfile prof = g_settings.profileForGame(game.productId, game.titleId, &hasCustom);
+ if (!prof.locale.empty()) streamLocale = prof.locale;
std::string res;
if (!g_autoplay.resolution.empty()) {
res = g_autoplay.resolution;
@@ -330,12 +354,17 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game
if (r.name == wanted) region = &r;
if (region) gssv.setRegion(*region);
XC_LOGI("stream settings: %s%s, region %s, locale %s", res.c_str(),
- hasCustom ? " (per-game)" : "", region ? region->name.c_str() : "?", ui::gameLocale());
+ hasCustom ? " (per-game)" : "", region ? region->name.c_str() : "?", streamLocale.c_str());
}
// For a crash marker: what is being started (a console's id stays out).
g_stageTitle = game.titleId;
crash::setStage(gssv.isHome() ? "starting own Xbox" : ("starting " + game.titleId).c_str());
- if (!gssv.startSession(game.titleId, ui::gameLocale(), err)) return err;
+ if (!gssv.startSession(game.titleId, streamLocale, err)) {
+ if (err.find("0x87DD043A") != std::string::npos || err.find("MonthlyLimitExceeded") != std::string::npos) {
+ return std::string(ui::tr(ui::Str::MonthlyLimitExceeded));
+ }
+ return err;
+ }
if (game.heroUrl.empty() && !game.productId.empty()) {
// Picked before the background hydration reached it: fetch the hero
// art for the loading screen while the session queues.
@@ -393,7 +422,12 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game
if (st.state == xcloud::SessionState::Provisioning && gssv.isHome())
g_ui->setLaunchStatus(ui::tr(ui::Str::WakingConsole)); // a sleeping Xbox takes ~10 s
if (st.state == xcloud::SessionState::Failed) {
- result = "the session failed: " + st.errorCode + " " + st.errorMessage;
+ if (st.errorCode == "0x87DD043A" || st.errorCode == "MonthlyLimitExceeded" ||
+ st.raw.find("0x87DD043A") != std::string::npos || st.raw.find("MonthlyLimitExceeded") != std::string::npos) {
+ result = ui::tr(ui::Str::MonthlyLimitExceeded);
+ } else {
+ result = "the session failed: " + st.errorCode + " " + st.errorMessage;
+ }
break;
}
if (st.state == xcloud::SessionState::ReadyToConnect && !connected) {
@@ -611,6 +645,8 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {
g_ui->setProfile(am.profile().gamertag, am.profile().gamerpicUrl, am.profile().gamerscore);
g_subscription = am.profile().subscription;
if (!g_subscription.empty()) g_ui->setSubscription(g_subscription);
+ s_playtimeRemainingSeconds = am.profile().playtimeRemainingSeconds;
+ g_ui->setPlaytime(am.profile().playtimeRemainingSeconds, am.profile().playtimeMaxSeconds);
{
std::lock_guard<std::mutex> lock(g_argMutex);
g_xblAuth = am.profile().xblAuthorization;
@@ -633,8 +669,16 @@ void loadLibrary(xcloud::GssvClient& gssv) {
g_ui->showSplash(ui::tr(ui::Str::LoadingGames));
stopHydration();
auto library = std::make_shared<app::Library>();
+ {
+ std::lock_guard<std::mutex> lock(s_libraryMutex);
+ s_library = library;
+ }
library->setCachePath(platform::dataDir() + "/library.json");
library->setSubscription(g_subscription);
+ {
+ std::lock_guard<std::mutex> lock(g_settingsMutex);
+ library->setFavorites(g_settings.favorites);
+ }
setPriceMarket(gssv.session().market.empty() ? "US" : gssv.session().market, ui::catalogLanguage());
setQueueClient(&gssv);
bool shown = false;
@@ -788,6 +832,8 @@ void worker() {
g_ui->setOwned({}, {}, false);
g_ui->setSearchPools({}, {});
g_ui->setSubscription("");
+ s_playtimeRemainingSeconds = -1;
+ g_ui->setPlaytime(-1, -1);
XC_LOGI("signed out: library and its cache cleared");
signInAndLoad(am, gssv);
if (!g_quit) loadConsoles(am, home);
diff --git a/src/auth/auth_manager.cpp b/src/auth/auth_manager.cpp
index 36dd59b..08b0875 100644
--- a/src/auth/auth_manager.cpp
+++ b/src/auth/auth_manager.cpp
@@ -9,8 +9,10 @@
#include <algorithm>
#include <cerrno>
+#include <cstdint>
#include <cstdio>
#include <cstdlib>
+#include <functional>
namespace xc::auth {
@@ -130,9 +132,102 @@ bool AuthManager::xboxChain(xcloud::GssvClient& gssv, std::string& err) {
XC_LOGW("profile XSTS: %s", perr.c_str());
}
- fetchSubscription(user);
if (!xstsToken(user, rp::kGssv, gssvXsts_, err)) return false;
- return gssv.login(gssvXsts_, err);
+ if (!gssv.login(gssvXsts_, err)) return false;
+ fetchSubscription(user, gssv.session().market);
+ return true;
+}
+
+namespace {
+
+static uint64_t readVarint(const uint8_t*& ptr, const uint8_t* end, bool& ok) {
+ uint64_t val = 0;
+ int shift = 0;
+ while (ptr < end && shift < 64) {
+ uint8_t b = *ptr++;
+ val |= static_cast<uint64_t>(b & 0x7F) << shift;
+ if ((b & 0x80) == 0) {
+ ok = true;
+ return val;
+ }
+ shift += 7;
+ }
+ ok = false;
+ return 0;
+}
+
+static void parseProtobufPlaytime(const uint8_t* ptr, const uint8_t* end, int depth, int64_t& remaining, int64_t& max) {
+ if (depth > 6) return;
+ while (ptr < end) {
+ bool ok = false;
+ uint64_t tag = readVarint(ptr, end, ok);
+ if (!ok) break;
+ uint32_t fieldNum = static_cast<uint32_t>(tag >> 3);
+ uint32_t wireType = static_cast<uint32_t>(tag & 0x7);
+ if (wireType == 0) { // Varint
+ uint64_t v = readVarint(ptr, end, ok);
+ if (!ok) break;
+ if (fieldNum == 1 && remaining < 0) remaining = static_cast<int64_t>(v);
+ else if (fieldNum == 2 && max < 0) max = static_cast<int64_t>(v);
+ } else if (wireType == 1) { // 64-bit
+ if (ptr + 8 > end) break;
+ ptr += 8;
+ } else if (wireType == 2) { // Length-delimited
+ uint64_t len = readVarint(ptr, end, ok);
+ if (!ok || ptr + len > end) break;
+ parseProtobufPlaytime(ptr, ptr + len, depth + 1, remaining, max);
+ ptr += len;
+ } else if (wireType == 5) { // 32-bit
+ if (ptr + 4 > end) break;
+ ptr += 4;
+ } else {
+ break;
+ }
+ }
+}
+
+} // namespace
+
+bool parsePlaytimeLimit(const std::string& body, int64_t& remaining, int64_t& max) {
+ remaining = -1;
+ max = -1;
+ if (body.empty()) return false;
+
+ // 1. Try JSON
+ auto j = json::parse(body);
+ if (j) {
+ std::function<void(const json::Value&)> walk = [&](const json::Value& val) {
+ if (val.isObject()) {
+ for (const auto& [k, v] : val.members()) {
+ if (k == "remainingGameplayTimeInSeconds" || k == "remainingGameplayTime") {
+ if (v.isNumber()) remaining = v.asInt();
+ else if (v.isString()) remaining = std::strtoll(v.str().c_str(), nullptr, 10);
+ } else if (k == "maxGameplayTimeInSeconds" || k == "maxGameplayTime") {
+ if (v.isNumber()) max = v.asInt();
+ else if (v.isString()) max = std::strtoll(v.str().c_str(), nullptr, 10);
+ }
+ walk(v);
+ }
+ } else if (val.isArray()) {
+ for (const auto& elem : val.items()) walk(elem);
+ }
+ };
+ walk(*j);
+ if (remaining >= 0) {
+ if (max > 0 && max < remaining) std::swap(remaining, max);
+ return true;
+ }
+ }
+
+ // 2. Minimal Protobuf reader
+ const uint8_t* ubody = reinterpret_cast<const uint8_t*>(body.data());
+ parseProtobufPlaytime(ubody, ubody + body.size(), 0, remaining, max);
+ if (remaining >= 0) {
+ if (max > 0 && max < remaining) std::swap(remaining, max);
+ return true;
+ }
+
+ return false;
}
std::string subscriptionPlan(const std::string& body) {
@@ -177,7 +272,7 @@ std::string subscriptionRenewal(const std::string& body, int64_t nowUnix) {
return {};
}
-void AuthManager::fetchSubscription(const XblToken& userToken) {
+void AuthManager::fetchSubscription(const XblToken& userToken, const std::string& market) {
// What xbox.com shows on the profile: the store service's entitlements
// for the Game Pass products. Optional: a failure only leaves the plan
// unknown (the UI then shows "Game Pass" from the titles).
@@ -198,13 +293,39 @@ void AuthManager::fetchSubscription(const XblToken& userToken) {
auto r = net::perform(req);
if (!r.ok()) {
XC_LOGW("subscription: entitlements: %s", r.status ? ("HTTP " + std::to_string(r.status)).c_str() : r.error.c_str());
+ } else {
+ if (std::getenv("XC_DUMP_SUBSCRIPTION")) std::printf("%s\n", r.body.c_str()); // diagnostics (CLI)
+ profile_.subscription = subscriptionPlan(r.body);
+ std::string renewal = subscriptionRenewal(r.body, unixNow());
+ XC_LOGI("subscription: %s%s%s%s", profile_.subscription.empty() ? "none" : profile_.subscription.c_str(),
+ renewal.empty() ? "" : " (", renewal.c_str(), renewal.empty() ? "" : ")");
+ }
+
+ fetchPlaytimeLimit(mp, market);
+}
+
+void AuthManager::fetchPlaytimeLimit(const XblToken& mp, const std::string& market) {
+ net::Request req;
+ req.method = "GET";
+ std::string m = market.empty() ? "US" : market;
+ req.url = "https://contentaccess.exp.xboxservices.com/all/v1?market=" + m + "&offering=xgpuweb";
+ req.headers = {
+ {"Authorization", mp.authorizationHeader()},
+ {"Accept", "application/json, application/x-protobuf"},
+ {"X-MS-API-Version", "1.0"},
+ {"MS-CV", "PSBoxPlaytime.1"}
+ };
+ auto r = net::perform(req);
+ if (!r.ok()) {
+ XC_LOGW("playtime limit: %s", r.status ? ("HTTP " + std::to_string(r.status)).c_str() : r.error.c_str());
return;
}
- if (std::getenv("XC_DUMP_SUBSCRIPTION")) std::printf("%s\n", r.body.c_str()); // diagnostics (CLI)
- profile_.subscription = subscriptionPlan(r.body);
- std::string renewal = subscriptionRenewal(r.body, unixNow());
- XC_LOGI("subscription: %s%s%s%s", profile_.subscription.empty() ? "none" : profile_.subscription.c_str(),
- renewal.empty() ? "" : " (", renewal.c_str(), renewal.empty() ? "" : ")");
+ parsePlaytimeLimit(r.body, profile_.playtimeRemainingSeconds, profile_.playtimeMaxSeconds);
+ if (profile_.playtimeRemainingSeconds >= 0) {
+ XC_LOGI("playtime limit: %lld h remaining of %lld h",
+ static_cast<long long>(profile_.playtimeRemainingSeconds / 3600),
+ static_cast<long long>(profile_.playtimeMaxSeconds / 3600));
+ }
}
bool AuthManager::loginOffering(xcloud::GssvClient& other, std::string& err) const {
diff --git a/src/auth/auth_manager.h b/src/auth/auth_manager.h
index cb2d3a1..375de7d 100644
--- a/src/auth/auth_manager.h
+++ b/src/auth/auth_manager.h
@@ -23,6 +23,9 @@ struct Profile {
// The Game Pass plan: "Ultimate", "Premium", "Essential", "PC"; empty
// when none or unknown (the store service didn't answer).
std::string subscription;
+ // Cloud playtime remaining and max in seconds (-1 when uncapped/unknown).
+ int64_t playtimeRemainingSeconds = -1;
+ int64_t playtimeMaxSeconds = -1;
// "XBL3.0 x=...;token" for services on http://xboxlive.com (titlehub...).
// Memory only: never logged or saved.
std::string xblAuthorization;
@@ -33,6 +36,8 @@ std::string subscriptionPlan(const std::string& entitlementsJson);
// For the log: whether that plan renews, or in how many days it ends (no
// date: the log may go into public reports). Empty when unknown.
std::string subscriptionRenewal(const std::string& entitlementsJson, int64_t nowUnix);
+// Parses playtime limit from JSON or Protobuf response
+bool parsePlaytimeLimit(const std::string& body, int64_t& remaining, int64_t& max);
class AuthManager {
public:
@@ -70,7 +75,8 @@ private:
bool deviceCodeSignIn(const DeviceCodeCallback& onCode, std::string& err, const std::atomic<bool>* cancel);
bool xboxChain(xcloud::GssvClient& gssv, std::string& err);
void fetchGamerpic(const XblToken& xsts);
- void fetchSubscription(const XblToken& userToken);
+ void fetchSubscription(const XblToken& userToken, const std::string& market);
+ void fetchPlaytimeLimit(const XblToken& mp, const std::string& market);
std::string storePath_;
MsaClient msa_;
diff --git a/src/display/gpu.cpp b/src/display/gpu.cpp
index 2e9b839..0375846 100644
--- a/src/display/gpu.cpp
+++ b/src/display/gpu.cpp
@@ -38,6 +38,7 @@ extern "C" VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(Vk
__attribute__((weak));
// RADV with tools/ps5/patches (weak: absent from an unpatched RADV or desktop).
extern "C" int wsi_videoout_set_high_refresh(bool on) __attribute__((weak));
+extern "C" int wsi_videoout_set_flip_rate(int rate) __attribute__((weak));
namespace xc::display::gpu {
@@ -1235,8 +1236,9 @@ bool lastShown(uint64_t& id, uint64_t& atUs) {
bool setHighRefresh(bool on) {
if (!wsi_videoout_set_high_refresh) return false;
+ if (on && wsi_videoout_set_flip_rate) wsi_videoout_set_flip_rate(0);
int rc = wsi_videoout_set_high_refresh(on);
- if (rc == 0) XC_LOGI("gpu: output at %s Hz", on ? "119.88" : "59.94");
+ if (rc == 0) XC_LOGI("gpu: output at %s Hz (VRR flip rate unpegged)", on ? "119.88" : "59.94");
else XC_LOGW("gpu: %s Hz refused (%d)", on ? "119.88" : "59.94", rc);
return rc == 0;
}
diff --git a/src/media/decoder.cpp b/src/media/decoder.cpp
index ca34518..3e2af1f 100644
--- a/src/media/decoder.cpp
+++ b/src/media/decoder.cpp
@@ -224,6 +224,36 @@ bool AudioDecoder::init() {
return true;
}
+void AudioDecoder::resetPlc() {
+ history_.clear();
+ plcDecay_ = 1.0f;
+ lastWasConcealed_ = false;
+}
+
+void AudioDecoder::conceal(std::vector<float>& out, size_t frames) {
+ if (frames == 0) return;
+ size_t base = out.size();
+ out.resize(base + frames * 2);
+ size_t histFrames = history_.size() / 2;
+ if (histFrames == 0) {
+ std::fill(out.begin() + static_cast<long>(base), out.end(), 0.0f);
+ return;
+ }
+ // Repeat recent waveform period with smooth decaying attenuation
+ size_t period = std::min(frames, histFrames);
+ size_t histStart = (histFrames - period) * 2;
+ for (size_t i = 0; i < frames; ++i) {
+ size_t srcIdx = histStart + (i % period) * 2;
+ float progress = static_cast<float>(i) / static_cast<float>(frames);
+ float decay = plcDecay_ * (1.0f - 0.4f * progress);
+ if (decay < 0.0f) decay = 0.0f;
+ out[base + 2 * i] = history_[srcIdx] * decay;
+ out[base + 2 * i + 1] = history_[srcIdx + 1] * decay;
+ }
+ plcDecay_ = std::max(0.0f, plcDecay_ * 0.6f);
+ lastWasConcealed_ = true;
+}
+
bool AudioDecoder::decode(const uint8_t* data, size_t len, std::vector<float>& out) {
// An empty packet is "end of stream" to libavcodec: every packet after
// it would be refused (no sound for the rest of the session).
@@ -237,6 +267,7 @@ bool AudioDecoder::decode(const uint8_t* data, size_t len, std::vector<float>& o
}
if (rc < 0) return false;
bool any = false;
+ size_t startSize = out.size();
while (avcodec_receive_frame(ctx_, frame_) == 0) {
int n = frame_->nb_samples;
int ch = frame_->ch_layout.nb_channels;
@@ -252,6 +283,27 @@ bool AudioDecoder::decode(const uint8_t* data, size_t len, std::vector<float>& o
}
any = true;
}
+ if (any) {
+ size_t decodedFloats = out.size() - startSize;
+ if (lastWasConcealed_) {
+ // Smoothly ramp in newly decoded audio over the first ~2 ms (96 stereo frames)
+ // to eliminate DC step pops after concealed frames.
+ size_t rampFrames = std::min<size_t>(96, decodedFloats / 2);
+ for (size_t i = 0; i < rampFrames; ++i) {
+ float ramp = static_cast<float>(i) / static_cast<float>(rampFrames);
+ out[startSize + 2 * i] *= ramp;
+ out[startSize + 2 * i + 1] *= ramp;
+ }
+ lastWasConcealed_ = false;
+ }
+ plcDecay_ = 1.0f;
+ // Keep up to 100 ms of history for PLC synthesis
+ history_.insert(history_.end(), out.begin() + static_cast<long>(startSize), out.end());
+ constexpr size_t kMaxHistoryFloats = kSampleRate * 2 * 100 / 1000;
+ if (history_.size() > kMaxHistoryFloats) {
+ history_.erase(history_.begin(), history_.begin() + static_cast<long>(history_.size() - kMaxHistoryFloats));
+ }
+ }
return any;
}
diff --git a/src/media/decoder.h b/src/media/decoder.h
index 8f69303..88b3cfd 100644
--- a/src/media/decoder.h
+++ b/src/media/decoder.h
@@ -81,11 +81,18 @@ public:
bool init();
// One Opus packet in; appends interleaved float stereo samples.
bool decode(const uint8_t* data, size_t len, std::vector<float>& out);
+ // Packet Loss Concealment (PLC): extrapolates audio across lost network frames.
+ void conceal(std::vector<float>& out, size_t frames = 960);
+ // Reset PLC state on stream start/reconnect.
+ void resetPlc();
private:
AVCodecContext* ctx_ = nullptr;
AVFrame* frame_ = nullptr;
AVPacket* packet_ = nullptr;
+ std::vector<float> history_;
+ float plcDecay_ = 1.0f;
+ bool lastWasConcealed_ = false;
};
} // namespace xc::media
diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cpp
index 9e6096b..c5f2dea 100644
--- a/src/stream/stream_session.cpp
+++ b/src/stream/stream_session.cpp
@@ -398,9 +398,13 @@ struct StreamSession::Impl {
// --- set-up ---------------------------------------------------------------
- std::shared_ptr<rtc::DataChannel> makeChannel(const char* label, const char* protocol) {
+ std::shared_ptr<rtc::DataChannel> makeChannel(const char* label, const char* protocol,
+ bool unordered = false,
+ std::optional<unsigned int> maxRetransmits = std::nullopt) {
rtc::DataChannelInit init;
init.protocol = protocol;
+ init.reliability.unordered = unordered;
+ init.reliability.maxRetransmits = maxRetransmits;
auto ch = pc->createDataChannel(label, init);
ch->onOpen([label] { XC_LOGI("data channel %s open", label); });
ch->onClosed([this, label] {
@@ -436,10 +440,12 @@ struct StreamSession::Impl {
});
// Same channels, in the same order, as the web client.
+ // Input channel is configured unordered and unreliable (0 retransmissions)
+ // to eliminate Head-of-Line Blocking input latency under network jitter/loss.
chat = makeChannel("chat", "chatV1");
chat->onMessage([](rtc::message_variant m) { XC_LOGI("chat channel: %s", asText(m).c_str()); });
control = makeChannel("control", "controlV1");
- input = makeChannel("input", "1.0");
+ input = makeChannel("input", "1.0", /*unordered=*/true, /*maxRetransmits=*/0);
message = makeChannel("message", "messageV1");
message->onOpen([this] {
diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cpp
index 48d1b66..36b6999 100644
--- a/src/ui/app_ui.cpp
+++ b/src/ui/app_ui.cpp
@@ -66,9 +66,9 @@ constexpr bool kSettingsGroupStart[kSettingRows] = {false, false, true, false, f
// The game settings' rows on screen (ids: 0 profile, 1 upscaler, 2
// sharpness, 3 block smoothing, 4 resolution, 5 dead zone, 6 triggers, 7
// confirm, 8 120 Hz, 9 keyboard keys, 10 back to the default, 11 controller
-// buttons, 12 gyro aiming, 13 touchpad as mouse).
-constexpr int kGameRowOrder[14] = {0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 13, 9, 10};
-constexpr bool kGameGroupStart[14] = {false, true, false, true, false, false, true, false, false, false, false, false, false, true};
+// buttons, 12 gyro aiming, 13 touchpad as mouse, 14 game language).
+constexpr int kGameRowOrder[15] = {0, 4, 8, 14, 1, 2, 3, 5, 6, 7, 12, 11, 13, 9, 10};
+constexpr bool kGameGroupStart[15] = {false, true, false, false, true, false, false, true, false, false, false, false, false, false, true};
// The keyboard keys' screen: two columns of inputs, then "Reset to default".
constexpr int kKeysPerColumn = input::kKeyActions / 2;
// Updates on a desktop: the newest release's page (the app doesn't install it there).
@@ -580,17 +580,26 @@ void AppUi::drawLoadingBar(Canvas& c, int x, int y, int w, uint64_t nowMs) {
animating_ = true;
}
-void AppUi::setPrefs(const std::vector<std::string>& hidden, LibrarySort sort) {
+void AppUi::setPrefs(const std::vector<std::string>& hidden, LibrarySort sort, const std::vector<std::string>& favorites) {
std::lock_guard<std::mutex> lock(mutex_);
hidden_ = std::set<std::string>(hidden.begin(), hidden.end());
+ favorites_ = std::set<std::string>(favorites.begin(), favorites.end());
librarySort_ = sort;
rebuild();
}
+void AppUi::setPlaytime(int64_t remainingSeconds, int64_t maxSeconds) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ playtimeRemaining_ = remainingSeconds;
+ playtimeMax_ = maxSeconds;
+ dirty_ = true;
+}
+
void AppUi::prefsEvent(UiEvent& ev) const {
// Caller holds mutex_.
ev.action = Action::PrefsChanged;
ev.hidden.assign(hidden_.begin(), hidden_.end());
+ ev.favorites.assign(favorites_.begin(), favorites_.end());
ev.librarySort = librarySort_;
}
@@ -606,6 +615,18 @@ void AppUi::toggleHidden(const GameTile& tile, UiEvent& ev) {
prefsEvent(ev);
}
+void AppUi::toggleFavorite(const GameTile& tile, UiEvent& ev) {
+ // Caller holds mutex_.
+ if (tile.productId.empty()) return;
+ bool fav = !favorites_.count(tile.productId);
+ if (fav) favorites_.insert(tile.productId);
+ else favorites_.erase(tile.productId);
+ toast_ = tr(fav ? Str::AddedToFavorites : Str::RemovedFromFavorites);
+ toastUntil_ = 0;
+ prefsEvent(ev);
+ dirty_ = true;
+}
+
void AppUi::setSearchPools(std::vector<GameTile> gamePass, std::vector<GameTile> library) {
std::lock_guard<std::mutex> lock(mutex_);
gamePassPool_ = std::move(gamePass);
@@ -2291,6 +2312,19 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {
activeGameHasCustom_ = true;
dirty_ = true;
break;
+ case 14: { // Game Language
+ static const std::pair<const char*, const char*> kLocales[] = {
+ {"", ""}, {"en-US", "English (US)"}, {"pt-BR", "Português (Brasil)"},
+ {"es-ES", "Español"}, {"fr-FR", "Français"}, {"de-DE", "Deutsch"},
+ {"it-IT", "Italiano"}, {"ja-JP", "日本語"}
+ };
+ int pos = 0;
+ for (int k = 0; k < 8; ++k) if (kLocales[k].first == activeGameProfile_.locale) pos = k;
+ activeGameProfile_.locale = kLocales[(pos + 8 + dir) % 8].first;
+ activeGameHasCustom_ = true;
+ dirty_ = true;
+ break;
+ }
default: break;
}
}
@@ -2368,6 +2402,19 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {
activeGameHasCustom_ = true;
dirty_ = true;
break;
+ case 14: {
+ static const std::pair<const char*, const char*> kLocales[] = {
+ {"", ""}, {"en-US", "English (US)"}, {"pt-BR", "Português (Brasil)"},
+ {"es-ES", "Español"}, {"fr-FR", "Français"}, {"de-DE", "Deutsch"},
+ {"it-IT", "Italiano"}, {"ja-JP", "日本語"}
+ };
+ int pos = 0;
+ for (int k = 0; k < 8; ++k) if (kLocales[k].first == activeGameProfile_.locale) pos = k;
+ activeGameProfile_.locale = kLocales[(pos + 1) % 8].first;
+ activeGameHasCustom_ = true;
+ dirty_ = true;
+ break;
+ }
case 9: // Keyboard keys: their own screen, on this game's
openTester(Tester::Keys);
settings_.keyMap = activeGameProfile_.keyMap;
@@ -2377,6 +2424,7 @@ void AppUi::handleGameSettings(const NavInput& in, UiEvent& ev) {
break;
case 10: // Reset to default
activeGameHasCustom_ = false;
+ activeGameProfile_.locale.clear();
activeGameProfile_.keyMap = settings_.keyMap;
activeGameProfile_.padMap = settings_.padMap;
activeGameProfile_.sharpness = settings_.sharpness;
@@ -2561,6 +2609,7 @@ UiEvent AppUi::handle(const NavInput& in) {
ev.game = detail_;
}
if (in.square) toggleHidden(detail_, ev); // the page stays open
+ if (in.triangle) toggleFavorite(detail_, ev);
if (in.back) {
screen_ = Screen::Home;
dirty_ = true;
@@ -2716,6 +2765,17 @@ void AppUi::drawTopBar(Canvas& c) {
int nx = right - nw;
fonts_.semibold.draw(c, n, nx, fonts_.semibold.centeredY(kLineY, kLineH, kLinePx), kLinePx, kGray);
drawGamerscoreBadge(c, nx - 13.0f, midY, 8.5f);
+ right = nx - 26;
+ }
+ if (playtimeRemaining_ >= 0) {
+ int hours = static_cast<int>((playtimeRemaining_ + 3599) / 3600);
+ std::string pt = trf(Str::HoursRemaining, std::to_string(hours));
+ int pw = fonts_.semibold.measure(pt, kLinePx);
+ int px = right - pw;
+ bool warn = playtimeRemaining_ <= 7200;
+ Color col = warn ? rgba(255, 160, 40) : kGray;
+ fonts_.semibold.draw(c, pt, px, fonts_.semibold.centeredY(kLineY, kLineH, kLinePx), kLinePx, col);
+ right = px - 16;
}
}
}
@@ -3650,10 +3710,12 @@ void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {
if (g->freeInStore)
drawHints(c, {{kIconCross, tr(Str::Play)},
{kIconOptions, tr(Str::GameSettings)},
+ {kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)},
{kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)},
{kIconCircle, tr(Str::Back)}});
else
drawHints(c, {{kIconOptions, tr(Str::GameSettings)},
+ {kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)},
{kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)},
{kIconCircle, tr(Str::Back)}});
drawToast(c, nowMs);
@@ -3668,6 +3730,7 @@ void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {
drawLock(c, note.x + 52, note.y + note.h / 2);
fonts_.semibold.draw(c, msg, note.x + 90, note.y + 22, 28, kGray);
drawHints(c, {{kIconOptions, tr(Str::GameSettings)},
+ {kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)},
{kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)},
{kIconCircle, tr(Str::Back)}});
drawToast(c, nowMs);
@@ -3693,6 +3756,7 @@ void AppUi::drawDetails(Canvas& c, uint64_t nowMs) {
}
drawHints(c, {{kIconCross, tr(Str::Play)},
{kIconOptions, tr(Str::GameSettings)},
+ {kIconTriangle, tr(favorites_.count(g->productId) ? Str::RemoveFavorite : Str::AddFavorite)},
{kIconSquare, tr(hidden_.count(g->productId) ? Str::Unhide : Str::Hide)},
{kIconCircle, tr(Str::Back)}});
drawToast(c, nowMs);
@@ -4373,7 +4437,7 @@ void AppUi::drawGameSettings(Canvas& c) {
title = title + " \xE2\x80\xA2 " + cut + "...";
}
}
- constexpr int kModalW = 1140, kModalH = 920;
+ constexpr int kModalW = 1140, kModalH = 960;
constexpr int kRowH = 46, kGap = 5, kGroupGap = 10;
// The rows caps_ allows; the panel loses the height of those it hides
// (the same as ever with all of them, "Reset to default" or not).
@@ -4473,6 +4537,26 @@ void AppUi::drawGameSettings(Canvas& c) {
label = tr(Str::TouchpadMouse);
value = tr(activeGameProfile_.touchpadMouse ? Str::Activated : Str::Deactivated);
break;
+ case 14: {
+ static const std::pair<const char*, const char*> kLocales[] = {
+ {"", ""}, {"en-US", "English (US)"}, {"pt-BR", "Português (Brasil)"},
+ {"es-ES", "Español"}, {"fr-FR", "Français"}, {"de-DE", "Deutsch"},
+ {"it-IT", "Italiano"}, {"ja-JP", "日本語"}
+ };
+ label = tr(Str::GameLanguage);
+ if (activeGameProfile_.locale.empty()) {
+ value = tr(Str::ProfileDefault);
+ } else {
+ for (const auto& [code, name] : kLocales) {
+ if (activeGameProfile_.locale == code) {
+ value = name;
+ break;
+ }
+ }
+ if (value.empty()) value = activeGameProfile_.locale;
+ }
+ break;
+ }
default: break;
}
diff --git a/src/ui/app_ui.h b/src/ui/app_ui.h
index e7e286f..75556e0 100644
--- a/src/ui/app_ui.h
+++ b/src/ui/app_ui.h
@@ -208,8 +208,9 @@ struct UiEvent {
SettingsChoice settings; // SettingsChanged
app::GameProfile gameProfile; // GameSettingsChanged
bool hasGameProfile = false;
- // PrefsChanged: hidden games (product ids) and the "Your games" order.
+ // PrefsChanged: hidden games (product ids), favorites, and the "Your games" order.
std::vector<std::string> hidden;
+ std::vector<std::string> favorites;
LibrarySort librarySort = LibrarySort::Recent;
std::string reportWhat; // Report: the error on screen (empty from Settings)
std::string url; // OpenUrl
@@ -256,10 +257,12 @@ public:
void setSearchPools(std::vector<GameTile> gamePass, std::vector<GameTile> library);
// Measured round trip to each region, ms (shown in Settings).
void setRegionLatency(std::map<std::string, int> ms);
+ // Cloud playtime limit telemetry (remaining and max in seconds, -1 unknown)
+ void setPlaytime(int64_t remainingSeconds, int64_t maxSeconds);
// Store prices, formatted: productId -> {now, regular (empty unless on sale)}.
void setPrices(const std::map<std::string, PriceInfo>& prices);
- // Saved preferences: hidden games and the "Your games" order.
- void setPrefs(const std::vector<std::string>& hidden, LibrarySort sort);
+ // Saved preferences: hidden games, the "Your games" order, and favorites.
+ void setPrefs(const std::vector<std::string>& hidden, LibrarySort sort, const std::vector<std::string>& favorites = {});
// Games to buy on screen (or about to be) whose price hasn't been asked
// for yet; with `background`, any other game to buy once those are done
// (never while streaming). Marks them asked.
@@ -428,6 +431,8 @@ private:
void setRowsLocked(std::vector<GameRow> rows);
// Hides / shows a game; fills `ev` so the app saves it.
void toggleHidden(const GameTile& tile, UiEvent& ev);
+ // Toggles favourite status of a game; fills `ev` so the app saves it.
+ void toggleFavorite(const GameTile& tile, UiEvent& ev);
void prefsEvent(UiEvent& ev) const;
// The filter buttons of the current tab's search.
// The search's filters, in two rows: Free, Lowest price (in "Your games"
@@ -504,6 +509,7 @@ private:
std::string status_;
std::string code_, codeUrl_;
std::string gamertag_, gamerpicUrl_, gamerscore_, subscription_;
+ int64_t playtimeRemaining_ = -1, playtimeMax_ = -1;
std::vector<GameRow> rows_;
int focusRow_ = 0;
std::vector<int> focusCol_;
@@ -518,7 +524,7 @@ private:
// As received, before hiding and sorting (rebuild() derives the above).
std::vector<GameRow> allRows_;
std::vector<GameTile> allOwned_, allPurchasable_;
- std::set<std::string> hidden_;
+ std::set<std::string> hidden_, favorites_;
bool loading_ = false;
size_t loadingDone_ = 0, loadingTotal_ = 0;
void drawLoadingBar(Canvas& c, int x, int y, int w, uint64_t nowMs);
diff --git a/src/ui/stream_menu.cpp b/src/ui/stream_menu.cpp
index 83cbf64..b420aab 100644
--- a/src/ui/stream_menu.cpp
+++ b/src/ui/stream_menu.cpp
@@ -276,6 +276,7 @@ Canvas StreamMenu::renderMenu(const StreamInfo& info) const {
line(Str::StatLoss, fmt("%.1f %%", info.lossPct));
line(Str::StatDecode, info.decodeMs > 0 ? fmt("%.1f ms", info.decodeMs) : none);
line(Str::StatOnScreen, info.onScreenMs > 0 ? fmt("%.1f ms", info.onScreenMs) : none);
+ if (info.playtimeHours >= 0) line(Str::PlaytimeRemaining, trf(Str::HoursRemaining, std::to_string(info.playtimeHours)));
// The controllers: numbered pads, each connected one with its user.
y += 8;
diff --git a/src/ui/stream_menu.h b/src/ui/stream_menu.h
index 23b5c2a..0e66b45 100644
--- a/src/ui/stream_menu.h
+++ b/src/ui/stream_menu.h
@@ -23,6 +23,7 @@ struct StreamInfo {
int width = 0, height = 0; // of the decoded picture
double qp = -1; // the pictures' average quantiser (lower: finer); -1 unknown
bool degraded = false; // frames lost / video stalled / round trip far up, in the last seconds
+ int playtimeHours = -1; // cloud playtime remaining (-1 unknown/uncapped)
};
// Close: the menu went away (Circle, OPTIONS, or the Xbox button): a fresh key frame is asked for.
diff --git a/src/ui/strings.cpp b/src/ui/strings.cpp
index 7d83125..78c690e 100644
--- a/src/ui/strings.cpp
+++ b/src/ui/strings.cpp
@@ -307,6 +307,16 @@ constexpr Column kEnglish = {
"All plans", // PlanAll
"Included with Game Pass %s", // IncludedWithPlan
"Touchpad as mouse", // TouchpadMouse
+ "Favourites", // Favorites
+ "Add to favourites", // AddFavorite
+ "Remove from favourites", // RemoveFavorite
+ "Added to favourites", // AddedToFavorites
+ "Removed from favourites", // RemovedFromFavorites
+ "Game language", // GameLanguage
+ "Monthly cloud gaming limit reached", // MonthlyLimitExceeded
+ "Playtime remaining", // PlaytimeRemaining
+ "%s h remaining", // HoursRemaining
+ "Less than 2 h remaining", // PlaytimeWarning
};
constexpr Column kPortugueseBR = {
@@ -584,6 +594,16 @@ constexpr Column kPortugueseBR = {
"Todos os planos", // PlanAll
"Incluído no Game Pass %s", // IncludedWithPlan
"Touchpad como mouse", // TouchpadMouse
+ "Favoritos", // Favorites
+ "Adicionar aos favoritos", // AddFavorite
+ "Remover dos favoritos", // RemoveFavorite
+ "Adicionado aos favoritos", // AddedToFavorites
+ "Removido dos favoritos", // RemovedFromFavorites
+ "Idioma do jogo", // GameLanguage
+ "Limite mensal de jogo em nuvem atingido", // MonthlyLimitExceeded
+ "Tempo de jogo restante", // PlaytimeRemaining
+ "%s h restantes", // HoursRemaining
+ "Menos de 2 h restantes", // PlaytimeWarning
};
constexpr Column kSpanish = {
@@ -861,6 +881,16 @@ constexpr Column kSpanish = {
"Todos los planes", // PlanAll
"Incluido con Game Pass %s", // IncludedWithPlan
"Panel táctil como ratón", // TouchpadMouse
+ "Favoritos", // Favorites
+ "Añadir a favoritos", // AddFavorite
+ "Quitar de favoritos", // RemoveFavorite
+ "Añadido a favoritos", // AddedToFavorites
+ "Eliminado de favoritos", // RemovedFromFavorites
+ "Idioma del juego", // GameLanguage
+ "Límite mensual de juego en la nube alcanzado", // MonthlyLimitExceeded
+ "Tiempo de juego restante", // PlaytimeRemaining
+ "%s h restantes", // HoursRemaining
+ "Menos de 2 h restantes", // PlaytimeWarning
};
constexpr Column kFrench = {
@@ -1138,6 +1168,16 @@ constexpr Column kFrench = {
"Tous les forfaits", // PlanAll
"Inclus avec Game Pass %s", // IncludedWithPlan
"Pavé tactile comme souris", // TouchpadMouse
+ "Favoris", // Favorites
+ "Ajouter aux favoris", // AddFavorite
+ "Retirer des favoris", // RemoveFavorite
+ "Ajouté aux favoris", // AddedToFavorites
+ "Retiré des favoris", // RemovedFromFavorites
+ "Langue du jeu", // GameLanguage
+ "Limite mensuelle de jeu dans le cloud atteinte", // MonthlyLimitExceeded
+ "Temps de jeu restant", // PlaytimeRemaining
+ "%s h restantes", // HoursRemaining
+ "Moins de 2 h restantes", // PlaytimeWarning
};
constexpr Column kGerman = {
@@ -1415,6 +1455,16 @@ constexpr Column kGerman = {
"Alle Abos", // PlanAll
"In Game Pass %s enthalten", // IncludedWithPlan
"Touchpad als Maus", // TouchpadMouse
+ "Favoriten", // Favorites
+ "Zu Favoriten hinzufügen", // AddFavorite
+ "Aus Favoriten entfernen", // RemoveFavorite
+ "Zu Favoriten hinzugefügt", // AddedToFavorites
+ "Aus Favoriten entfernt", // RemovedFromFavorites
+ "Spiel-Sprache", // GameLanguage
+ "Monatliches Cloud-Gaming-Limit erreicht", // MonthlyLimitExceeded
+ "Verbleibende Spielzeit", // PlaytimeRemaining
+ "%s Std. verbleibend", // HoursRemaining
+ "Weniger als 2 Std. verbleibend", // PlaytimeWarning
};
constexpr Column kItalian = {
@@ -1692,6 +1742,16 @@ constexpr Column kItalian = {
"Tutti i piani", // PlanAll
"Incluso con Game Pass %s", // IncludedWithPlan
"Touchpad come mouse", // TouchpadMouse
+ "Preferiti", // Favorites
+ "Aggiungi ai preferiti", // AddFavorite
+ "Rimuovi dai preferiti", // RemoveFavorite
+ "Aggiunto ai preferiti", // AddedToFavorites
+ "Rimosso dai preferiti", // RemovedFromFavorites
+ "Lingua del gioco", // GameLanguage
+ "Limite mensile di gioco su cloud raggiunto", // MonthlyLimitExceeded
+ "Tempo di gioco rimanente", // PlaytimeRemaining
+ "%s ore rimanenti", // HoursRemaining
+ "Meno di 2 ore rimanenti", // PlaytimeWarning
};
constexpr std::array<const Column*, kLangs> kTable = {&kEnglish, &kPortugueseBR, &kSpanish,
diff --git a/src/ui/strings.h b/src/ui/strings.h
index 2503546..95817dd 100644
--- a/src/ui/strings.h
+++ b/src/ui/strings.h
@@ -284,6 +284,16 @@ enum class Str {
PlanAll, // ... every Game Pass plan
IncludedWithPlan, // game page: "%s" = "Ultimate" / "Premium" / "Essential"
TouchpadMouse, // per-game setting: use touchpad as mouse in games with mouse support
+ Favorites, // home screen row: Favourites
+ AddFavorite, // details action hint: Add to favourites
+ RemoveFavorite, // details action hint: Remove from favourites
+ AddedToFavorites, // toast: Added to favourites
+ RemovedFromFavorites, // toast: Removed from favourites
+ GameLanguage, // per-game setting row: Game language
+ MonthlyLimitExceeded, // session error: Monthly cloud gaming limit reached
+ PlaytimeRemaining, // telemetry / top bar: playtime remaining
+ HoursRemaining, // "%s h remaining" / "%s h restantes"
+ PlaytimeWarning, // warning when < 2 hours remaining
Count
};
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 7052b4a..392f68b 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -370,6 +370,8 @@ static void testPerGameSettings() {
p1.circleConfirms = true;
p1.highRefresh = true;
p1.touchpadMouse = true;
+ p1.locale = "pt-BR";
+ s.favorites = {"GAME1", "GAME3"};
s.perGame["GAME1"] = p1;
// Now GAME1 returns custom profile, while GAME2 still returns defaults.
@@ -377,17 +379,18 @@ static void testPerGameSettings() {
CHECK(hasCustom);
CHECK(prof1Custom.sharpness == 3 && prof1Custom.upscaler == 3 && prof1Custom.circleConfirms);
CHECK(prof1Custom.deadzoneLeft == 5 && prof1Custom.triggerStrength == 1 && prof1Custom.touchpadMouse);
+ CHECK(prof1Custom.locale == "pt-BR");
hasCustom = true;
auto prof2 = s.profileForGame("GAME2", "", &hasCustom);
CHECK(!hasCustom);
- CHECK(prof2.sharpness == 1 && !prof2.circleConfirms && !prof2.touchpadMouse);
+ CHECK(prof2.sharpness == 1 && !prof2.circleConfirms && !prof2.touchpadMouse && prof2.locale.empty());
// Title ID fallback when productId is empty.
s.perGame["CONSOLE_SERVER_1"] = p1;
auto consoleProf = s.profileForGame("", "CONSOLE_SERVER_1", &hasCustom);
CHECK(hasCustom);
- CHECK(consoleProf.sharpness == 3 && consoleProf.circleConfirms);
+ CHECK(consoleProf.sharpness == 3 && consoleProf.circleConfirms && consoleProf.locale == "pt-BR");
// Save to disk and reload.
CHECK(s.desktopFullscreen); // a desktop window starts fullscreen unless chosen otherwise
@@ -396,22 +399,51 @@ static void testPerGameSettings() {
xc::app::Settings reloaded;
CHECK(reloaded.load(path));
CHECK(!reloaded.desktopFullscreen);
+ CHECK(reloaded.favorites.size() == 2 && reloaded.favorites[0] == "GAME1" && reloaded.favorites[1] == "GAME3");
CHECK(reloaded.perGame.size() == 2);
auto loadedP1 = reloaded.profileForGame("GAME1", "", &hasCustom);
CHECK(hasCustom);
CHECK(loadedP1.sharpness == 3 && loadedP1.upscaler == 3 && loadedP1.circleConfirms);
- CHECK(loadedP1.highRefresh && loadedP1.touchpadMouse);
+ CHECK(loadedP1.highRefresh && loadedP1.touchpadMouse && loadedP1.locale == "pt-BR");
CHECK(loadedP1.deadzoneLeft == 5 && loadedP1.deadzoneRight == 8 && loadedP1.triggerStrength == 1);
// Remove game profile restores default.
reloaded.perGame.erase("GAME1");
auto afterErase = reloaded.profileForGame("GAME1", "", &hasCustom);
CHECK(!hasCustom);
- CHECK(afterErase.sharpness == reloaded.sharpness);
+ CHECK(afterErase.sharpness == reloaded.sharpness && afterErase.locale.empty());
std::remove(path.c_str());
}
+static void testPlaytimeLimit() {
+ int64_t rem = -1, max = -1;
+
+ // 1. Valid JSON format
+ std::string jsonStr = R"({"remainingGameplayTimeInSeconds": 36000, "maxGameplayTimeInSeconds": 54000})";
+ CHECK(auth::parsePlaytimeLimit(jsonStr, rem, max));
+ CHECK(rem == 36000 && max == 54000);
+
+ // 2. Nested JSON format
+ std::string nestedJson = R"({"user": {"limits": {"remainingGameplayTimeInSeconds": 7200, "maxGameplayTimeInSeconds": 18000}}})";
+ CHECK(auth::parsePlaytimeLimit(nestedJson, rem, max));
+ CHECK(rem == 7200 && max == 18000);
+
+ // 3. String-encoded numbers in JSON
+ std::string strJson = R"({"remainingGameplayTimeInSeconds": "18000", "maxGameplayTimeInSeconds": "36000"})";
+ CHECK(auth::parsePlaytimeLimit(strJson, rem, max));
+ CHECK(rem == 18000 && max == 36000);
+
+ // 4. Protobuf wire format (tag 1 varint 18000, tag 2 varint 54000)
+ std::string proto = std::string("\x08\xD0\x8C\x01\x10\xF0\xA5\x03", 8);
+ CHECK(auth::parsePlaytimeLimit(proto, rem, max));
+ CHECK(rem == 18000 && max == 54000);
+
+ // 5. Empty and invalid inputs
+ CHECK(!auth::parsePlaytimeLimit("", rem, max));
+ CHECK(!auth::parsePlaytimeLimit("not a valid payload", rem, max));
+}
+
static void testStreamMenu() {
using xc::ui::MenuAction;
xc::ui::Fonts fonts; // not loaded: handle() never draws
@@ -1442,20 +1474,20 @@ static void testVisibleSettingsRows() {
auto x = ids(ui::visibleSettingsRows(xbox));
CHECK(std::find(x.begin(), x.end(), 4) != x.end() && std::find(x.begin(), x.end(), 6) == x.end());
// A game's settings.
- CHECK((ids(ui::visibleGameSettingsRows(ps5, true, false)) == std::vector<int>{0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));
- CHECK((ids(ui::visibleGameSettingsRows(ps5, true, true)) == std::vector<int>{0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 13, 9, 10}));
+ CHECK((ids(ui::visibleGameSettingsRows(ps5, true, false)) == std::vector<int>{0, 4, 8, 14, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));
+ CHECK((ids(ui::visibleGameSettingsRows(ps5, true, true)) == std::vector<int>{0, 4, 8, 14, 1, 2, 3, 5, 6, 7, 12, 11, 13, 9, 10}));
CHECK((groups(ui::visibleGameSettingsRows(ps5, true, true)) ==
- std::vector<bool>{false, true, false, true, false, false, true, false, false, false, false, false, false, true}));
- CHECK((ids(ui::visibleGameSettingsRows(ps5, true)) == std::vector<int>{0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));
+ std::vector<bool>{false, true, false, false, true, false, false, true, false, false, false, false, false, false, true}));
+ CHECK((ids(ui::visibleGameSettingsRows(ps5, true)) == std::vector<int>{0, 4, 8, 14, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));
CHECK((groups(ui::visibleGameSettingsRows(ps5, true)) ==
- std::vector<bool>{false, true, false, true, false, false, true, false, false, false, false, false, true}));
- CHECK((ids(ui::visibleGameSettingsRows(ps5, false)) == std::vector<int>{0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 9}));
+ std::vector<bool>{false, true, false, false, true, false, false, true, false, false, false, false, false, true}));
+ CHECK((ids(ui::visibleGameSettingsRows(ps5, false)) == std::vector<int>{0, 4, 8, 14, 1, 2, 3, 5, 6, 7, 12, 11, 9}));
ui::UiCaps noTouch = ps5;
noTouch.touchpad = false;
- CHECK((ids(ui::visibleGameSettingsRows(noTouch, true, true)) == std::vector<int>{0, 4, 8, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));
+ CHECK((ids(ui::visibleGameSettingsRows(noTouch, true, true)) == std::vector<int>{0, 4, 8, 14, 1, 2, 3, 5, 6, 7, 12, 11, 9, 10}));
auto game = ui::visibleGameSettingsRows(pc, false);
- CHECK((ids(game) == std::vector<int>{0, 4, 5, 7, 11, 9}));
- CHECK((groups(game) == std::vector<bool>{false, true, true, false, false, false}));
+ CHECK((ids(game) == std::vector<int>{0, 4, 14, 5, 7, 11, 9}));
+ CHECK((groups(game) == std::vector<bool>{false, true, false, true, false, false, false}));
}
// The controller's glyphs by pad kind (ui/pad_glyphs.h).
@@ -1792,6 +1824,7 @@ int main() {
testSettingsMigration();
testMicGain();
testPerGameSettings();
+ testPlaytimeLimit();
testStrings();
testRegions();
testPrices();