Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

feat(cloud-time): the account's cloud hours, time-up message, in-game notices (#342)

Rafael Abud Ferreira051c2cc5f56b
diff --git a/src/app/autoplay.cpp b/src/app/autoplay.cpp
index f4f9426..408fff5 100644
--- a/src/app/autoplay.cpp
+++ b/src/app/autoplay.cpp
@@ -36,6 +36,7 @@ bool settingsShot = false; // "settingstest": save the screen now
bool bitrateShot = false; // "bitratetest": save the screen now
bool donationShot = false; // "donationtest": save the screen now
bool reportShot = false; // "reporttest": save report.ppm now
+const char* cloudTimeShot = nullptr; // "cloudtimetest": save this capture now
bool signInCheckShot = false; // "checksignintest": save the screen now
bool freeUiShot = false, freeDetailsShot = false; // "freetest": save free account screenshots
const char* keysShot = nullptr; // "keystest": the screen to save now
@@ -107,6 +108,8 @@ void loadAutoplay() {
if (opt == "fnplay") g_autoplay.fnPlay = true;
if (opt == "legacy") g_autoplay.legacy = true;
if (opt == "imgtest") g_autoplay.imgTest = true;
+ if (opt == "cloudtimetest") g_autoplay.cloudTimeTest = true;
+ if (opt.rfind("cloudleft=", 0) == 0) g_autoplay.cloudLeft = std::atoll(opt.c_str() + 10);
// Threads pinned by role (platform.h), to measure it again.
if (opt == "pin") platform::setNoThreadPinning(false);
if (opt == "rumbletest") input::setRumble(200, 200, 1500);
@@ -1004,6 +1007,73 @@ void autoplayNav(ui::NavInput& nav, bool& menuCombo, uint64_t now) {
}
}
+ if (g_autoplay.cloudTimeTest && uiSaved) {
+ // The account's cloud time as a limited account shows it: the badge
+ // under the brand, then low (orange), then the error when it ran out.
+ static uint64_t since = 0;
+ static int step = 0;
+ if (!since) since = now;
+ if (step == 0 && now - since > 500) {
+ g_ui->setPlaytime(15000, 54000); // 4 h 10 min of 15 h
+ ++step;
+ } else if (step == 1 && now - since > 2500) {
+ cloudTimeShot = "cloudtime_home.ppm";
+ g_ui->setPlaytime(5400, 54000); // 1 h 30 min: under 2 h
+ ++step;
+ } else if (step == 2 && now - since > 4500) {
+ cloudTimeShot = "cloudtime_low.ppm";
+ g_ui->setPlaytime(0, 54000); // none left
+ ++step;
+ } else if (step == 3 && now - since > 6500) {
+ cloudTimeShot = "cloudtime_zero.ppm";
+ g_ui->setPlaytime(-1, -1, true); // an unlimited account
+ ++step;
+ } else if (step == 4 && now - since > 8500) {
+ cloudTimeShot = "cloudtime_unlimited.ppm";
+ // The game menu with the time left, then under 15 minutes.
+ auto saveMenu = [](const char* name, const ui::Canvas& c) {
+ std::string ppm = "P6\n" + std::to_string(c.width()) + " " + std::to_string(c.height()) + "\n255\n";
+ ppm.reserve(ppm.size() + static_cast<size_t>(c.width() * c.height() * 3));
+ for (size_t i = 0; i < static_cast<size_t>(c.width() * c.height()); ++i) {
+ uint32_t p = c.data()[i];
+ ppm += static_cast<char>(p & 0xFF);
+ ppm += static_cast<char>((p >> 8) & 0xFF);
+ ppm += static_cast<char>((p >> 16) & 0xFF);
+ }
+ platform::writeFileAtomic(platform::dataDir() + "/" + name, ppm);
+ XC_LOGI("AUTOPLAY: %s saved", name);
+ };
+ ui::StreamInfo info;
+ info.region = "Brazil South";
+ info.rttMs = 12;
+ info.fps = 60.0;
+ info.mbps = 20.0;
+ info.width = 1920;
+ info.height = 1080;
+ ui::PadSlots pads{};
+ pads[0].connected = true;
+ pads[0].name = "DualSense Controller";
+ ui::StreamMenu menu(g_ui->fonts());
+ menu.open(0, false, 1, 1, 0, false, true, false, 2, 15, false, 0.5f, false, 100);
+ menu.setPads(pads);
+ info.cloudTimeSeconds = 47 * 60 + 20;
+ saveMenu("cloudtime_menu.ppm", menu.renderMenu(info));
+ info.cloudTimeSeconds = 4 * 60 + 50;
+ saveMenu("cloudtime_menu_low.ppm", menu.renderMenu(info));
+ ui::GameTile tile;
+ g_ui->firstTile(tile);
+ g_ui->showPlayError(ui::tr(ui::Str::CloudTimeUp), tile, "https://www.xbox.com/play");
+ ++step;
+ } else if (step == 5 && now - since > 11000) {
+ cloudTimeShot = "cloudtime_error.ppm";
+ g_ui->setPlaytime(-1, -1);
+ g_ui->showHome();
+ g_autoplay.cloudTimeTest = false;
+ XC_LOGI("AUTOPLAY END: cloud time test");
+ ++step;
+ }
+ }
+
if (g_autoplay.reportTest && uiSaved) {
static uint64_t since = 0;
static int step = 0;
@@ -1211,6 +1281,11 @@ void autoplayScreens(const ui::Canvas& canvas, uint64_t now) {
saveCanvas("donation.ppm");
XC_LOGI("AUTOPLAY END: donation screenshot saved");
}
+ if (cloudTimeShot) {
+ saveCanvas(cloudTimeShot);
+ XC_LOGI("AUTOPLAY: %s saved", cloudTimeShot);
+ cloudTimeShot = nullptr;
+ }
if (reportShot) {
reportShot = false;
saveCanvas("report.ppm");
diff --git a/src/app/autoplay.h b/src/app/autoplay.h
index ea61a81..d68e534 100644
--- a/src/app/autoplay.h
+++ b/src/app/autoplay.h
@@ -64,6 +64,8 @@ struct Autoplay {
bool fnPlay = false; // fnplay: Fortnite gameplay for measurements (Play once, then the camera turns and the player runs)
bool legacy = false; // legacy: the stream as it was tuned before 2026-11-04 (the A/B baseline)
bool imgTest = false; // imgtest: 25 s before the end, one picture drawn with each look (img_*.ppm)
+ int64_t cloudLeft = -1; // cloudleft=N: a stream counts down from N seconds left (the menu, the notices)
+ bool cloudTimeTest = false; // cloudtimetest: the cloud time line (4 h 10 of 15 h, 1 h 30, none, unlimited), the game menu with it, the time-up error
bool cpuDisplay = false; // the CPU display even where the GPU comes up
int upscaler = -1; // ai: Anime4K instead of the setting
bool restore = false; // restore: Anime4K Restore before the upscale
diff --git a/src/app/worker.cpp b/src/app/worker.cpp
index aaec27e..b4c5b12 100644
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@ -11,6 +11,7 @@
#include "app/stream_player.h"
#include "net/http.h"
#include "platform/platform.h"
+#include "ui/cloud_time.h"
#include "ui/strings.h"
#include "util/log.h"
#include "xcloud/catalog.h"
@@ -263,7 +264,8 @@ void signInAndLoad(auth::AuthManager& am, xcloud::GssvClient& gssv) {
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);
+ g_ui->setPlaytime(am.profile().playtimeRemainingSeconds, am.profile().playtimeMaxSeconds,
+ am.profile().playtimeUnlimited);
{
std::lock_guard<std::mutex> lock(g_argMutex);
g_xblAuth = am.profile().xblAuthorization;
@@ -694,6 +696,7 @@ void worker() {
automatic = g_settings.region.empty();
}
std::string region = automatic && g_regionFallback.count(tile.titleId) ? g_regionFallback[tile.titleId] : "";
+ const int64_t cloudTimeBefore = s_playtimeRemainingSeconds;
std::string result = play(am, gssv, tile, failed, region);
XC_LOGI("%s", result.c_str());
// Some games fail to start in one region only (Dead Cells in
@@ -721,6 +724,19 @@ void worker() {
if (!failed) g_regionFallback[tile.titleId] = next;
}
}
+ // A limited account's cloud time after the stream: the service
+ // asked again, against what the stream counted down (the
+ // service may not have counted the session yet).
+ if (cloudTimeBefore >= 0) {
+ const int64_t counted = s_playtimeRemainingSeconds;
+ am.refreshCloudTime();
+ const auto& p = am.profile();
+ s_playtimeRemainingSeconds =
+ p.playtimeUnlimited ? -1 : ui::CloudTimeClock::reconcile(counted, p.playtimeRemainingSeconds, cloudTimeBefore);
+ g_ui->setPlaytime(s_playtimeRemainingSeconds, p.playtimeMaxSeconds, p.playtimeUnlimited);
+ XC_LOGI("cloud time after the stream: %s left (counted %s)",
+ ui::formatCloudTime(s_playtimeRemainingSeconds).c_str(), ui::formatCloudTime(counted).c_str());
+ }
bool isEntitlementErr = result.find("NoEntitlement") != std::string::npos ||
result.find("NotEntitled") != std::string::npos ||
result.find("PurchasableProductRequired") != std::string::npos ||
@@ -752,6 +768,21 @@ void worker() {
g_ui->showError(ui::tr(ui::Str::ConnectionIntercepted));
} else if (isDnsOrSinkholeError(result)) {
g_ui->showError(ui::tr(ui::Str::DnsBlockedNanoDns));
+ } else if (result.find("OutOfStreamingTime") != std::string::npos ||
+ result == ui::tr(ui::Str::MonthlyLimitExceeded)) {
+ // The cloud time ran out (Xbox's monthly limits since
+ // November 2026), the stream ended for it or refused
+ // at the start: what it is and where to see the
+ // options (xbox.com: no hours to buy in the app), not
+ // "could not start". The hours asked for again when
+ // the account had no limit known (asked above if so).
+ g_ui->showPlayError(ui::tr(ui::Str::CloudTimeUp), tile, "https://www.xbox.com/play");
+ if (cloudTimeBefore < 0) {
+ am.refreshCloudTime();
+ const auto& p = am.profile();
+ s_playtimeRemainingSeconds = p.playtimeUnlimited ? -1 : p.playtimeRemainingSeconds;
+ g_ui->setPlaytime(p.playtimeRemainingSeconds, p.playtimeMaxSeconds, p.playtimeUnlimited);
+ }
} else {
g_ui->showPlayError(result.rfind("ERROR: ", 0) == 0 ? result.substr(7) : result, tile);
}
diff --git a/src/app/worker_stream.cpp b/src/app/worker_stream.cpp
index ee540e3..1bf7212 100644
--- a/src/app/worker_stream.cpp
+++ b/src/app/worker_stream.cpp
@@ -10,6 +10,7 @@
#include "media/audio_out.h"
#include "media/audio_queue.h"
#include "platform/platform.h"
+#include "ui/cloud_time.h"
#include "ui/strings.h"
#include "util/log.h"
#include "xcloud/catalog.h"
@@ -85,7 +86,7 @@ namespace {
std::string g_stageTitle;
std::string g_stageProduct;
-std::string stream(xcloud::GssvClient& gssv) {
+std::string stream(xcloud::GssvClient& gssv, const auth::CloudTimeQuery& cloudQuery) {
crash::setStage(gssv.isHome() ? "streaming own Xbox" : ("streaming " + g_stageTitle).c_str());
g_gameClosedOnServer = false;
app::StreamPlayer player(gssv);
@@ -141,6 +142,44 @@ std::string stream(xcloud::GssvClient& gssv) {
const uint64_t started = platform::nowMs();
uint64_t nextTick = started;
+ // The account's cloud time (a limited account's, in the cloud): counted
+ // down for the game menu, a notice at 15 and at 5 minutes left (Xbox
+ // ends the stream at none, issue #342), and the service asked again every
+ // 10 minutes from a thread of its own (the loop never waits on it).
+ ui::CloudTimeClock cloud;
+ const bool cloudTest = g_autoplay.cloudLeft >= 0;
+ if (!gssv.isHome()) cloud.start(cloudTest ? g_autoplay.cloudLeft : s_playtimeRemainingSeconds, started);
+ if (cloud.limited()) XC_LOGI("cloud time: %s left at the start", ui::formatCloudTime(cloud.left(started)).c_str());
+ struct CloudAsk {
+ platform::Thread thread;
+ std::atomic<bool> done{false};
+ std::atomic<int64_t> remaining{-1};
+ } ask;
+ const uint64_t kAskEveryMs = cloudTest ? 20000 : 600000;
+ uint64_t nextAsk = started + kAskEveryMs;
+ auto cloudTimeStep = [&](uint64_t nowMs) {
+ if (!cloud.limited()) return;
+ if (const int64_t due = cloud.noticeDue(nowMs); due > 0)
+ platform::notify(ui::trf(ui::Str::CloudTimeWarn, ui::formatCloudTime(due)),
+ "cloud time: " + ui::formatCloudTime(due) + " left (notification)");
+ if (ask.done) {
+ ask.thread.join();
+ ask.done = false;
+ const int64_t counted = cloud.left(nowMs);
+ cloud.answer(ask.remaining, nowMs);
+ XC_LOGI("cloud time: the service says %s, counted %s: %s left",
+ ask.remaining < 0 ? "no limit or nothing" : ui::formatCloudTime(ask.remaining).c_str(),
+ ui::formatCloudTime(counted).c_str(), ui::formatCloudTime(cloud.left(nowMs)).c_str());
+ }
+ if (!ask.thread.joinable() && nowMs >= nextAsk && !cloudQuery.marketplace.token.empty()) {
+ nextAsk = nowMs + kAskEveryMs;
+ platform::startThread(ask.thread, [&ask, cloudQuery] {
+ auth::ContentAccessPlaytime t;
+ ask.remaining = auth::queryCloudTime(cloudQuery, t, 8000) ? t.accountRemaining : -1;
+ ask.done = true;
+ }, 1u << 20);
+ }
+ };
bool snapshot1 = false, snapshot2 = false, snapshot3 = false, snapshot4 = false;
uint64_t nextPeriodicShot = 150000;
int periodicShotIdx = 5;
@@ -206,6 +245,8 @@ std::string stream(xcloud::GssvClient& gssv) {
while (player.running() && !g_cancel) {
beat("loop");
uint64_t elapsed = platform::nowMs() - started;
+ beat("the cloud time");
+ cloudTimeStep(started + elapsed);
if (!g_autoplay.title.empty()) {
if (elapsed >= static_cast<uint64_t>(g_autoplay.seconds) * 1000u) {
autoplayDone = true;
@@ -348,9 +389,7 @@ 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);
- }
+ info.cloudTimeSeconds = cloud.left(platform::nowMs());
info.playtimeSeconds = prevPlaytime + session.seconds;
player.getRecentFrametimes(info.frametimes);
std::lock_guard<std::mutex> lock(g_infoMutex);
@@ -364,6 +403,12 @@ std::string stream(xcloud::GssvClient& gssv) {
}
watch.stop = true;
if (watch.thread.joinable()) watch.thread.join();
+ if (ask.thread.joinable()) ask.thread.join(); // 8 s at most
+ if (cloud.limited()) {
+ if (ask.done) cloud.answer(ask.remaining, platform::nowMs());
+ if (!cloudTest) s_playtimeRemainingSeconds = cloud.left(platform::nowMs());
+ XC_LOGI("cloud time: %s left at the end", ui::formatCloudTime(cloud.left(platform::nowMs())).c_str());
+ }
{
std::lock_guard<std::mutex> lock(g_playerMutex);
g_player = nullptr;
@@ -620,7 +665,7 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game
playQueueReadyAlert(true);
}
g_ui->setLaunchStatus(ui::tr(ui::Str::StartingStream));
- result = stream(gssv);
+ result = stream(gssv, am.cloudTimeQuery());
failed = result.rfind("ERROR", 0) == 0;
break;
}
diff --git a/src/auth/auth_manager.cpp b/src/auth/auth_manager.cpp
index f23750f..5cf8b96 100644
--- a/src/auth/auth_manager.cpp
+++ b/src/auth/auth_manager.cpp
@@ -8,6 +8,8 @@
#include "util/log.h"
#include <algorithm>
+#include <vector>
+#include <map>
#include <cerrno>
#include <cstdint>
#include <cstdio>
@@ -182,94 +184,220 @@ bool AuthManager::ensureFresh(xcloud::GssvClient* gssv, std::string& err, bool f
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;
+// Content Access (contentaccess.exp.xboxservices.com/all/v1), protobuf:
+// 1: passes by user {1: PUID, 2: passes}
+// 2: products {1: product ID, 2: {2 (repeated): {1: PUID, 2: access}}}
+// access {1: user access types, 2: aggregate access types,
+// 11: streaming gameplay {1: program, 2: remaining s, 4: max s}}
+// The cloud time is the product's (the layout as owenselles/CloudNow decodes
+// it): the account's own allowance shows as the same remaining / max on all of
+// its limited products.
+struct PbReader {
+ const uint8_t* p = nullptr;
+ const uint8_t* end = nullptr;
+ bool ok = true;
+ uint64_t value = 0; // the last varint field's
+ uint64_t varint() {
+ uint64_t v = 0;
+ for (int shift = 0; shift < 64 && p < end; shift += 7) {
+ const uint8_t b = *p++;
+ v |= static_cast<uint64_t>(b & 0x7F) << shift;
+ if (!(b & 0x80)) return v;
}
- shift += 7;
+ ok = false;
+ return 0;
}
- 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;
+ // The next field: its number and wire type, `sub` the bytes of a
+ // length-delimited one; the reader moves past it in every case.
+ bool next(uint32_t& field, uint32_t& wire, PbReader& sub) {
+ if (!ok || p >= end) return false;
+ const uint64_t tag = varint();
+ if (!ok) return false;
+ field = static_cast<uint32_t>(tag >> 3);
+ wire = static_cast<uint32_t>(tag & 7);
+ sub = PbReader{p, p};
+ switch (wire) {
+ case 0: value = varint(); return ok;
+ case 1:
+ if (end - p < 8) return ok = false;
+ p += 8;
+ return true;
+ case 5:
+ if (end - p < 4) return ok = false;
+ p += 4;
+ return true;
+ case 2: {
+ const uint64_t n = varint();
+ if (!ok || n > static_cast<uint64_t>(end - p)) return ok = false;
+ sub = PbReader{p, p + n};
+ p += n;
+ return true;
+ }
+ default: return ok = false;
+ }
+ }
+ static std::string text(const PbReader& sub) {
+ return std::string(reinterpret_cast<const char*>(sub.p), static_cast<size_t>(sub.end - sub.p));
+ }
+};
+
+// One user's access to a product: its streaming time, when it has one.
+void readProductAccess(PbReader r, int64_t& remaining, int64_t& max) {
+ uint32_t f = 0, w = 0;
+ PbReader sub;
+ while (r.next(f, w, sub)) {
+ if (f != 11 || w != 2) continue;
+ PbReader g = sub, unused;
+ while (g.next(f, w, unused)) {
+ if (w == 0 && f == 2) remaining = static_cast<int64_t>(g.value);
+ else if (w == 0 && f == 4) max = static_cast<int64_t>(g.value);
}
}
}
-} // 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);
+bool parseContentAccessProto(const std::string& body, ContentAccessPlaytime& out) {
+ const auto* begin = reinterpret_cast<const uint8_t*>(body.data());
+ PbReader top{begin, begin + body.size()};
+ std::string puid; // the user: the first one with passes
+ std::vector<PbReader> products;
+ uint32_t f = 0, w = 0;
+ PbReader sub;
+ int fields = 0;
+ while (top.next(f, w, sub)) {
+ ++fields;
+ if (w != 2) continue;
+ if (f == 1 && puid.empty()) {
+ PbReader e = sub, v;
+ while (e.next(f, w, v))
+ if (f == 1 && w == 2) puid = PbReader::text(v);
+ } else if (f == 2) {
+ products.push_back(sub);
+ }
+ }
+ if (!top.ok || fields == 0 || (puid.empty() && products.empty())) return false;
+ // The account's record, after the products ({1: PUID, 2: {bucket: {2:
+ // remaining, 3: updated, 4: max, 5: ?}}}): its cloud time, when limited.
+ top = PbReader{begin, begin + body.size()};
+ while (top.next(f, w, sub)) {
+ if (f != 3 || w != 2) continue;
+ PbReader rec = sub, v;
+ std::string who;
+ std::vector<PbReader> buckets;
+ while (rec.next(f, w, v)) {
+ if (f == 1 && w == 2) who = PbReader::text(v);
+ if (f == 2 && w == 2) buckets.push_back(v);
+ }
+ if (!puid.empty() && who != puid) continue;
+ for (PbReader b : buckets) {
+ PbReader entry;
+ while (b.next(f, w, entry)) {
+ if (w != 2) continue;
+ const uint32_t bucket = f;
+ int64_t remaining = -1, max = -1;
+ PbReader g = entry, unused;
+ while (g.next(f, w, unused)) {
+ auto seconds = [](uint64_t x) {
+ return x >= static_cast<uint64_t>(INT64_MAX) ? ContentAccessPlaytime::kUnlimited : static_cast<int64_t>(x);
+ };
+ if (w == 0 && f == 2) remaining = seconds(g.value);
+ else if (w == 0 && f == 4) max = seconds(g.value);
+ }
+ out.accountBuckets[static_cast<int>(bucket)] = {remaining, max};
+ }
+ }
+ }
+ for (PbReader prod : products) {
+ std::string productId;
+ int64_t remaining = -1, max = -1;
+ PbReader v;
+ while (prod.next(f, w, v)) {
+ if (f == 1 && w == 2) productId = PbReader::text(v);
+ if (f != 2 || w != 2) continue;
+ PbReader data = v, entry;
+ while (data.next(f, w, entry)) {
+ if (f != 2 || w != 2) continue;
+ PbReader e = entry, x, access;
+ std::string who;
+ bool haveAccess = false;
+ while (e.next(f, w, x)) {
+ if (f == 1 && w == 2) who = PbReader::text(x);
+ if (f == 2 && w == 2) access = x, haveAccess = true;
}
- } else if (val.isArray()) {
- for (const auto& elem : val.items()) walk(elem);
+ if (haveAccess && (puid.empty() || who == puid)) readProductAccess(access, remaining, max);
}
+ }
+ ++out.products;
+ if (remaining >= 0 || max >= 0) out.byProduct[productId] = {remaining, max};
+ }
+ return true;
+}
+
+void collectJson(const json::Value& val, ContentAccessPlaytime& out) {
+ if (val.isObject()) {
+ int64_t remaining = -1, max = -1;
+ auto num = [](const json::Value& v) {
+ return v.isString() ? static_cast<int64_t>(std::strtoll(v.str().c_str(), nullptr, 10)) : v.asInt();
};
- walk(*j);
- if (remaining >= 0) {
- if (max > 0 && max < remaining) std::swap(remaining, max);
- return true;
+ for (const auto& [k, v] : val.members()) {
+ if (k == "remainingGameplayTimeInSeconds" || k == "remainingGameplayTime") remaining = num(v);
+ else if (k == "maxGameplayTimeInSeconds" || k == "maxGameplayTime") max = num(v);
+ else collectJson(v, out);
}
+ if (remaining >= 0 || max >= 0) {
+ std::string id = val["productId"].str("#" + std::to_string(out.byProduct.size()));
+ out.byProduct[id] = {remaining, max};
+ ++out.products;
+ }
+ } else if (val.isArray()) {
+ for (const auto& e : val.items()) collectJson(e, out);
}
+}
- // 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;
+} // namespace
+
+bool parseContentAccessPlaytime(const std::string& body, ContentAccessPlaytime& out) {
+ out = {};
+ if (body.empty()) return false;
+ if (auto j = json::parse(body)) {
+ collectJson(*j, out);
+ } else if (!parseContentAccessProto(body, out)) {
+ return false;
}
+ // The account's allowance: one remaining / max shared by (nearly) all of
+ // its limited products, a few of them at least.
+ std::map<std::pair<int64_t, int64_t>, int> counts;
+ for (const auto& [id, t] : out.byProduct)
+ if (t.second > 0) ++counts[t], ++out.limited;
+ for (const auto& [t, n] : counts)
+ if (n > out.commonCount) out.commonCount = n, out.common = t;
+ if (out.limited >= 3 && out.commonCount * 5 >= out.limited * 4) {
+ out.accountRemaining = out.common.first;
+ out.accountMax = out.common.second;
+ }
+ // The account's own record wins: its first bucket that carries a time
+ // (2 so far); all bits set there means no limit.
+ for (const auto& [bucket, t] : out.accountBuckets) {
+ if (t.first < 0 && t.second < 0) continue;
+ if (t.first == ContentAccessPlaytime::kUnlimited || t.second == ContentAccessPlaytime::kUnlimited) {
+ out.unlimited = true;
+ out.accountRemaining = out.accountMax = -1;
+ } else {
+ out.unlimited = false;
+ out.accountRemaining = t.first;
+ out.accountMax = t.second;
+ }
+ break;
+ }
+ return true;
+}
- return false;
+bool parsePlaytimeLimit(const std::string& body, int64_t& remaining, int64_t& max) {
+ ContentAccessPlaytime t;
+ remaining = max = -1;
+ if (!parseContentAccessPlaytime(body, t) || t.accountRemaining < 0) return false;
+ remaining = t.accountRemaining;
+ max = t.accountMax;
+ return true;
}
std::string subscriptionPlan(const std::string& body) {
@@ -325,6 +453,7 @@ void AuthManager::fetchSubscription(const XblToken& userToken, const std::string
return;
}
marketplaceXsts_ = mp;
+ market_ = market;
net::Request req;
req.method = "POST";
req.url = "https://emerald.xboxservices.com/xboxcomfd/entitlements/bulk?locale=en-US";
@@ -347,13 +476,18 @@ void AuthManager::fetchSubscription(const XblToken& userToken, const std::string
fetchPlaytimeLimit(mp, market);
}
-void AuthManager::fetchPlaytimeLimit(const XblToken& mp, const std::string& market) {
+void AuthManager::refreshCloudTime() {
+ if (!marketplaceXsts_.token.empty()) fetchPlaytimeLimit(marketplaceXsts_, market_);
+}
+
+bool queryCloudTime(const CloudTimeQuery& q, ContentAccessPlaytime& out, int timeoutMs) {
net::Request req;
req.method = "GET";
- std::string m = market.empty() ? "US" : market;
+ req.timeoutMs = timeoutMs;
+ std::string m = q.market.empty() ? "US" : q.market;
req.url = "https://contentaccess.exp.xboxservices.com/all/v1?market=" + m + "&offering=xgpuweb";
req.headers = {
- {"Authorization", mp.authorizationHeader()},
+ {"Authorization", q.marketplace.authorizationHeader()},
{"Accept", "application/json, application/x-protobuf"},
{"X-MS-API-Version", "1.0"},
{"MS-CV", "PSBoxPlaytime.1"}
@@ -361,14 +495,57 @@ void AuthManager::fetchPlaytimeLimit(const XblToken& mp, const std::string& mark
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;
+ return false;
}
- 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));
+ // Diagnostics: the answer kept as it came when asked (a file named
+ // contentaccess.request in the data folder; removed once done).
+ if (std::string asked; platform::readFile(platform::dataDir() + "/contentaccess.request", asked)) {
+ std::remove((platform::dataDir() + "/contentaccess.request").c_str());
+ platform::writeFileAtomic(platform::dataDir() + "/contentaccess.bin", r.body);
+ XC_LOGI("cloud time: the answer saved to contentaccess.bin (%s)", r.header("content-type").c_str());
}
+ if (!parseContentAccessPlaytime(r.body, out)) {
+ XC_LOGW("cloud time: an answer of %zu bytes not understood", r.body.size());
+ return false;
+ }
+ out.bytes = r.body.size();
+ return true;
+}
+
+void AuthManager::fetchPlaytimeLimit(const XblToken& mp, const std::string& market) {
+ ContentAccessPlaytime t;
+ if (!queryCloudTime({mp, market}, t)) return;
+ profile_.playtimeRemainingSeconds = t.accountRemaining;
+ profile_.playtimeMaxSeconds = t.accountMax;
+ profile_.playtimeUnlimited = t.unlimited;
+ profile_.productPlaytime = t.byProduct;
+ // What the service says, for the log: how many products carry a time
+ // limit and the remaining / max they share most.
+ std::map<std::pair<int64_t, int64_t>, int> counts;
+ for (const auto& [id, v] : t.byProduct) ++counts[v];
+ std::vector<std::pair<int, std::pair<int64_t, int64_t>>> ranked;
+ for (const auto& [v, n] : counts) ranked.push_back({n, v});
+ std::sort(ranked.rbegin(), ranked.rend());
+ std::string common;
+ auto hm = [](int64_t s) {
+ if (s < 0) return std::string("-");
+ char b[32];
+ std::snprintf(b, sizeof b, "%lldh%02lld", static_cast<long long>(s / 3600), static_cast<long long>(s % 3600 / 60));
+ return std::string(b);
+ };
+ for (size_t i = 0; i < ranked.size() && i < 3; ++i)
+ common += (i ? ", " : "") + hm(ranked[i].second.first) + " of " + hm(ranked[i].second.second) + " x" +
+ std::to_string(ranked[i].first);
+ std::string buckets;
+ auto hmu = [&](int64_t s) { return s == ContentAccessPlaytime::kUnlimited ? std::string("unlimited") : hm(s); };
+ for (const auto& [b, v] : t.accountBuckets)
+ buckets += (buckets.empty() ? "" : ", ") + std::to_string(b) + ": " + hmu(v.first) + " of " + hmu(v.second);
+ XC_LOGI("cloud time: %zu bytes, %d products, %zu with time data (%d with a maximum)%s%s; account record [%s]: %s",
+ t.bytes, t.products, t.byProduct.size(), t.limited, common.empty() ? "" : ": ", common.c_str(),
+ buckets.c_str(),
+ t.unlimited ? "unlimited"
+ : t.accountRemaining >= 0 ? (hm(t.accountRemaining) + " left of " + hm(t.accountMax)).c_str()
+ : "no limit seen");
}
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 0555b98..9a05f2d 100644
--- a/src/auth/auth_manager.h
+++ b/src/auth/auth_manager.h
@@ -10,7 +10,9 @@
#include "xcloud/gssv.h"
#include <atomic>
+#include <cstdint>
#include <functional>
+#include <map>
#include <string>
namespace xc::auth {
@@ -26,6 +28,9 @@ struct Profile {
// Cloud playtime remaining and max in seconds (-1 when uncapped/unknown).
int64_t playtimeRemainingSeconds = -1;
int64_t playtimeMaxSeconds = -1;
+ bool playtimeUnlimited = false; // the service says the account has no limit
+ // Each product's cloud time (remaining, max seconds; -1 absent), by product ID.
+ std::map<std::string, std::pair<int64_t, int64_t>> productPlaytime;
// "XBL3.0 x=...;token" for services on http://xboxlive.com (titlehub...).
// Memory only: never logged or saved.
std::string xblAuthorization;
@@ -36,8 +41,35 @@ 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
+// The cloud streaming time in a Content Access answer (protobuf, or JSON):
+// each product's remaining and maximum seconds (-1 when absent), and the
+// account's allowance when (nearly) all of its limited products share one.
+struct ContentAccessPlaytime {
+ int products = 0, limited = 0; // products seen, those with a maximum
+ std::map<std::string, std::pair<int64_t, int64_t>> byProduct; // product ID -> remaining, max
+ std::pair<int64_t, int64_t> common{-1, -1}; // the most frequent remaining / max
+ int commonCount = 0;
+ // The account's own record (top-level field 3): its time buckets by
+ // field number, remaining / max seconds (-1 absent; kUnlimited for
+ // "no limit", sent as all bits set).
+ static constexpr int64_t kUnlimited = INT64_MAX;
+ std::map<int, std::pair<int64_t, int64_t>> accountBuckets;
+ int64_t accountRemaining = -1, accountMax = -1; // -1: no limit seen
+ bool unlimited = false; // the account's record says so
+ size_t bytes = 0; // the answer's size (queryCloudTime)
+};
+bool parseContentAccessPlaytime(const std::string& body, ContentAccessPlaytime& out);
+// Just the account's allowance (false and -1 when there is none to tell).
bool parsePlaytimeLimit(const std::string& body, int64_t& remaining, int64_t& max);
+// What asking for the cloud time needs, copied: a stream asks again from
+// its own thread while the sign-in carries on.
+struct CloudTimeQuery {
+ XblToken marketplace;
+ std::string market;
+};
+// Asks Content Access for the account's cloud time; false when the service
+// did not answer or the answer was not understood.
+bool queryCloudTime(const CloudTimeQuery& q, ContentAccessPlaytime& out, int timeoutMs = 20000);
// The tokens are renewed this long before they expire.
constexpr int64_t kRefreshMarginSec = 600;
@@ -69,6 +101,10 @@ public:
// /connect step of cloud sessions.
bool consoleTransferToken(std::string& out, std::string& err);
+ // The cloud time asked for again (after a stream).
+ void refreshCloudTime();
+ CloudTimeQuery cloudTimeQuery() const { return {marketplaceXsts_, market_}; }
+
// After signIn(): logs `other` (another offering, such as "xhome" for
// the user's own consoles) in with the same Xbox token.
bool loginOffering(xcloud::GssvClient& other, std::string& err) const;
@@ -100,6 +136,7 @@ private:
void fetchGamerpic(const XblToken& xsts);
void fetchSubscription(const XblToken& userToken, const std::string& market);
void fetchPlaytimeLimit(const XblToken& mp, const std::string& market);
+ std::string market_; // the last sign-in's, for refreshCloudTime()
std::string storePath_;
MsaClient msa_;
diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cpp
index deed568..ebb3d67 100644
--- a/src/ui/app_ui.cpp
+++ b/src/ui/app_ui.cpp
@@ -450,10 +450,11 @@ void AppUi::setPrefs(const std::vector<std::string>& hidden, LibrarySort sort, c
rebuild(true);
}
-void AppUi::setPlaytime(int64_t remainingSeconds, int64_t maxSeconds) {
+void AppUi::setPlaytime(int64_t remainingSeconds, int64_t maxSeconds, bool unlimited) {
std::lock_guard<std::mutex> lock(mutex_);
- playtimeRemaining_ = remainingSeconds;
- playtimeMax_ = maxSeconds;
+ playtimeRemaining_ = unlimited ? -1 : remainingSeconds;
+ playtimeMax_ = unlimited ? -1 : maxSeconds;
+ playtimeUnlimited_ = unlimited;
dirty_ = true;
}
diff --git a/src/ui/app_ui.h b/src/ui/app_ui.h
index e3a4da6..7124d8a 100644
--- a/src/ui/app_ui.h
+++ b/src/ui/app_ui.h
@@ -322,9 +322,9 @@ 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).
- // Purely informative; never blocks launch or gameplay.
- void setPlaytime(int64_t remainingSeconds, int64_t maxSeconds);
+ // The account's cloud time: remaining and max in seconds (-1 unknown), or
+ // `unlimited`. Purely informative; never blocks launch or gameplay.
+ void setPlaytime(int64_t remainingSeconds, int64_t maxSeconds, bool unlimited = false);
// Store prices, formatted: productId -> {now, regular (empty unless on sale)}.
void setPrices(const std::map<std::string, PriceInfo>& prices);
// Saved preferences: hidden games, the "Your games" order, favorites, and wishlist.
@@ -517,6 +517,7 @@ private:
void drawTopBar(Canvas& c);
void drawLogo(Canvas& c, float cx, float cy, float r);
void drawGamerscoreBadge(Canvas& c, float cx, float cy, float r);
+ void drawCloudTime(Canvas& c, int x, int y);
using Hint = std::pair<int, const char*>;
void drawHints(Canvas& c, const std::vector<Hint>& hints);
void drawSpinner(Canvas& c, float cx, float cy, float r, uint64_t nowMs);
@@ -642,6 +643,7 @@ private:
std::string code_, codeUrl_;
std::string gamertag_, gamerpicUrl_, gamerscore_, subscription_;
int64_t playtimeRemaining_ = -1, playtimeMax_ = -1;
+ bool playtimeUnlimited_ = false;
std::vector<GameRow> rows_;
int focusRow_ = 0;
std::vector<int> focusCol_;
diff --git a/src/ui/app_ui_render.cpp b/src/ui/app_ui_render.cpp
index 3d83ed4..30df525 100644
--- a/src/ui/app_ui_render.cpp
+++ b/src/ui/app_ui_render.cpp
@@ -1,6 +1,9 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2026 RafaelNGP
#include "ui/app_ui_internal.h"
+#include "ui/cloud_time.h"
+
+#include <algorithm>
namespace xc::ui {
@@ -46,20 +49,41 @@ void AppUi::drawGamerscoreBadge(Canvas& c, float cx, float cy, float r) {
c.line(cx + r * 0.05f, cy, cx + ring + t * 0.5f, cy, t, kBg);
}
+// The account's cloud time (Xbox limits it each month since November 2026),
+// under the brand name: the left side, the account's own (name, score, plan)
+// being on the right. What is left of the month's hours and a bar; orange
+// from 2 h left, red at none. An unlimited account says so; nothing when it
+// is not known.
+void AppUi::drawCloudTime(Canvas& c, int x, int y) {
+ constexpr int kPx = 15, kLineH = 20;
+ const int ty = fonts_.semibold.centeredY(y, kLineH, kPx);
+ const float iconY = y + kLineH / 2.0f;
+ if (playtimeUnlimited_) {
+ drawClockIcon(c, x + 7.0f, iconY, 7.0f, kGray);
+ fonts_.semibold.draw(c, tr(Str::CloudTimeUnlimited), x + 20, ty, kPx, kGray);
+ return;
+ }
+ if (playtimeRemaining_ < 0) return;
+ const Color col = playtimeRemaining_ <= 0 ? rgba(240, 100, 100)
+ : playtimeRemaining_ < 7260 ? rgba(255, 160, 40)
+ : kGray;
+ drawClockIcon(c, x + 7.0f, iconY, 7.0f, col);
+ int end = fonts_.semibold.draw(c, trf(Str::CloudTimeLeft, formatCloudTime(playtimeRemaining_)), x + 20, ty, kPx, col);
+ if (playtimeMax_ <= 0) return;
+ end = fonts_.semibold.draw(c, " " + trf(Str::CloudTimeOf, formatCloudTime(playtimeMax_)), end, ty, kPx, kDim);
+ // As wide as the brand name, or the line when that is longer.
+ const int w = std::max(fonts_.semibold.measure(tr(Str::CloudGaming), 22), end - x);
+ const Rect bar{x, y + kLineH + 4, w, 4};
+ c.fillRect(bar, rgba(255, 255, 255, 36), 2);
+ const double f = std::clamp(static_cast<double>(playtimeRemaining_) / static_cast<double>(playtimeMax_), 0.0, 1.0);
+ if (const int fw = static_cast<int>(w * f + 0.5); fw > 0) c.fillRect({x, bar.y, std::max(fw, 4), bar.h}, col, 2);
+}
+
void AppUi::drawTopBar(Canvas& c) {
drawLogo(c, kMargin + 22, 72, 22);
fonts_.semibold.draw(c, tr(Str::CloudGaming), kMargin + 64, 60, 22, kWhite);
- // Cloud playtime remaining badge positioned under the "PSBox Cloud Gaming" brand mark.
- // Purely informative; hidden from the active UI for now until Xbox Cloud Gaming enforces limits.
- constexpr bool kShowPlaytimeBadge = false;
- if (kShowPlaytimeBadge && playtimeRemaining_ >= 0) {
- int hours = static_cast<int>((playtimeRemaining_ + 3599) / 3600);
- std::string pt = trf(Str::HoursRemaining, std::to_string(hours));
- bool warn = playtimeRemaining_ <= 7200;
- Color col = warn ? rgba(255, 160, 40) : kGray;
- fonts_.semibold.draw(c, pt, kMargin + 64, 86, 14, col);
- }
+ drawCloudTime(c, kMargin + 64, 86);
int x = kW - kMargin;
constexpr int kAvatar = 52;
diff --git a/src/ui/cloud_time.h b/src/ui/cloud_time.h
new file mode 100644
index 0000000..960037e
--- /dev/null
+++ b/src/ui/cloud_time.h
@@ -0,0 +1,88 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// The account's Xbox cloud time (limited each month since November 2026):
+// how it is written on screen, and how a stream counts it down.
+#pragma once
+
+#include "ui/canvas.h"
+
+#include <algorithm>
+#include <cstdint>
+#include <string>
+
+namespace xc::ui {
+
+// "4 h 10 min", "47 min", "< 1 min": whole minutes, rounded down, so never
+// more than is left.
+inline std::string formatCloudTime(int64_t seconds) {
+ if (seconds <= 0) return "0 min";
+ if (seconds < 60) return "< 1 min";
+ const int64_t hours = seconds / 3600, minutes = seconds % 3600 / 60;
+ if (!hours) return std::to_string(minutes) + " min";
+ if (!minutes) return std::to_string(hours) + " h";
+ return std::to_string(hours) + " h " + std::to_string(minutes) + " min";
+}
+
+// A clock face of radius `r`: its ring and two hands.
+inline void drawClockIcon(Canvas& c, float cx, float cy, float r, Color color) {
+ const float t = r * 0.26f;
+ c.strokeArc(cx, cy, r - t / 2, t, 0.0f, 6.2832f, color);
+ c.line(cx, cy, cx, cy - r * 0.52f, t, color);
+ c.line(cx, cy, cx + r * 0.42f, cy, t, color);
+}
+
+// The time left during a stream. The service answers once at the start; the
+// clock counts down from there and takes a later answer as reconcile() says.
+// The notices: one when 15 minutes are left, one at 5.
+class CloudTimeClock {
+public:
+ static constexpr int64_t kNotices[2] = {15 * 60, 5 * 60};
+
+ // The time left after some play: `counted` by the clock, `answer` the
+ // service's latest, `before` its answer from before that play (-1: none
+ // known). An answer over `before` brought new hours (a new month, hours
+ // bought); otherwise the lower of the two, as the service may count a
+ // session only once it ends: never more than is left.
+ static int64_t reconcile(int64_t counted, int64_t answer, int64_t before) {
+ if (answer < 0) return counted;
+ if (counted < 0 || answer > before) return answer;
+ return std::min(counted, answer);
+ }
+
+ // `remaining` < 0: the account has no limit, or it is not known.
+ void start(int64_t remaining, uint64_t nowMs) {
+ base_ = start_ = remaining;
+ baseMs_ = nowMs;
+ next_ = 0;
+ }
+ bool limited() const { return base_ >= 0; }
+ int64_t left(uint64_t nowMs) const {
+ if (base_ < 0) return -1;
+ const int64_t gone = static_cast<int64_t>((nowMs - baseMs_) / 1000);
+ return std::max<int64_t>(0, base_ - gone);
+ }
+ void answer(int64_t remaining, uint64_t nowMs) {
+ const int64_t counted = left(nowMs), now = reconcile(counted, remaining, start_);
+ if (remaining > start_) start_ = remaining;
+ if (now == counted) return;
+ base_ = now;
+ baseMs_ = nowMs;
+ }
+ // The time to tell the player about now, once per notice, when the time
+ // shown (whole minutes) reaches it; a stream that starts under 15
+ // minutes gets one right away. -1 when none is due.
+ int64_t noticeDue(uint64_t nowMs) {
+ const int64_t l = left(nowMs);
+ if (l <= 0) return -1;
+ bool due = false;
+ while (next_ < 2 && l < kNotices[next_] + 60) ++next_, due = true;
+ return due ? l : -1;
+ }
+
+private:
+ int64_t base_ = -1, start_ = -1; // the count's base; the service's answer it started from
+ uint64_t baseMs_ = 0;
+ int next_ = 0; // the next of kNotices still to come
+};
+
+} // namespace xc::ui
diff --git a/src/ui/i18n/strings_de.inc b/src/ui/i18n/strings_de.inc
index df3f497..30ff313 100644
--- a/src/ui/i18n/strings_de.inc
+++ b/src/ui/i18n/strings_de.inc
@@ -416,5 +416,10 @@ constexpr Column kGerman = {
"Um kostenlose Spiele außer Fortnite ohne Game Pass zu streamen, aktivieren Sie 'Preview-Funktionen' in den App-Einstellungen und auf xbox.com/play.", // F2pPreviewRequiredDesc
"Dieses Konto muss 'Preview-Funktionen' im Profil auf xbox.com/play aktivieren, um werbefinanziertes Free-to-Play-Streaming freizuschalten.", // F2pPreviewAccountNeededDesc
"Spieler", // MenuPlayer
+ "Ihre Xbox-Cloud-Spielzeit ist aufgebraucht, deshalb hat der Xbox-Dienst die Sitzung beendet. Seit November 2026 begrenzt Xbox das Cloud-Gaming pro Monat: 15 Std. mit Game Pass Ultimate, 10 Std. mit Premium und 5 Std. mit Essential. Mehr Zeit: Ihre Optionen finden Sie auf xbox.com, oder Sie warten auf die Stunden des nächsten Monats.", // CloudTimeUp
"Die Sitzung wurde wegen Inaktivität beendet", // EndedIdle
+ "%s verbleibend", // CloudTimeLeft
+ "von %s", // CloudTimeOf
+ "Unbegrenzte Cloud-Zeit", // CloudTimeUnlimited
+ "Noch %s Xbox-Cloud-Spielzeit in diesem Monat", // CloudTimeWarn
};
diff --git a/src/ui/i18n/strings_en.inc b/src/ui/i18n/strings_en.inc
index daaa690..02ef942 100644
--- a/src/ui/i18n/strings_en.inc
+++ b/src/ui/i18n/strings_en.inc
@@ -416,5 +416,10 @@ constexpr Column kEnglish = {
"To stream free-to-play games beyond Fortnite without Game Pass, enable 'Preview Features' in app Settings and on xbox.com/play.", // F2pPreviewRequiredDesc
"This account needs to enable 'Preview Features' in its profile on xbox.com/play to unlock ad-supported free-to-play streaming.", // F2pPreviewAccountNeededDesc
"Player", // MenuPlayer
+ "Your Xbox cloud gaming time has run out, so the Xbox service ended the session. Since November 2026, Xbox limits cloud play each month: 15 h with Game Pass Ultimate, 10 h with Premium and 5 h with Essential. To get more time, see your options at xbox.com, or new hours come next month.", // CloudTimeUp
"The stream ended after a while without input", // EndedIdle
+ "%s left", // CloudTimeLeft
+ "of %s", // CloudTimeOf
+ "Unlimited cloud time", // CloudTimeUnlimited
+ "%s of your Xbox cloud gaming time left this month", // CloudTimeWarn
};
diff --git a/src/ui/i18n/strings_es.inc b/src/ui/i18n/strings_es.inc
index 045a151..78fef26 100644
--- a/src/ui/i18n/strings_es.inc
+++ b/src/ui/i18n/strings_es.inc
@@ -416,5 +416,10 @@ constexpr Column kSpanish = {
"Para transmitir juegos gratuitos además de Fortnite en cuentas sin Game Pass, activa 'Funciones Preview' en Ajustes y en xbox.com/play.", // F2pPreviewRequiredDesc
"Esta cuenta necesita habilitar 'Funciones Preview' en su perfil en xbox.com/play para desbloquear el streaming con anuncios de juegos gratuitos.", // F2pPreviewAccountNeededDesc
"Jugador", // MenuPlayer
+ "Se acabó tu tiempo de juego en la nube de Xbox, así que el servicio de Xbox cerró la sesión. Desde noviembre de 2026, Xbox limita el juego en la nube cada mes: 15 h con Game Pass Ultimate, 10 h con Premium y 5 h con Essential. Para tener más tiempo, mira las opciones en xbox.com, o espera las horas del próximo mes.", // CloudTimeUp
"La sesión terminó por inactividad", // EndedIdle
+ "%s restantes", // CloudTimeLeft
+ "de %s", // CloudTimeOf
+ "Tiempo en la nube ilimitado", // CloudTimeUnlimited
+ "Te quedan %s de tu tiempo de juego en la nube de Xbox este mes", // CloudTimeWarn
};
diff --git a/src/ui/i18n/strings_fr.inc b/src/ui/i18n/strings_fr.inc
index b1d0168..180a611 100644
--- a/src/ui/i18n/strings_fr.inc
+++ b/src/ui/i18n/strings_fr.inc
@@ -416,5 +416,10 @@ constexpr Column kFrench = {
"Pour jouer aux jeux gratuits autres que Fortnite sans Game Pass, activez les 'Fonctionnalités Preview' dans les Paramètres et sur xbox.com/play.", // F2pPreviewRequiredDesc
"Ce compte doit activer les 'Fonctionnalités Preview' sur son profil sur xbox.com/play pour débloquer le streaming gratuit avec publicités.", // F2pPreviewAccountNeededDesc
"Joueur", // MenuPlayer
+ "Votre temps de jeu dans le cloud Xbox est écoulé : le service Xbox a fermé la session. Depuis novembre 2026, Xbox limite le jeu dans le cloud chaque mois : 15 h avec le Game Pass Ultimate, 10 h avec Premium et 5 h avec Essential. Pour avoir plus de temps, consultez les options sur xbox.com, ou attendez les heures du mois prochain.", // CloudTimeUp
"La session s’est terminée pour inactivité", // EndedIdle
+ "%s restantes", // CloudTimeLeft
+ "sur %s", // CloudTimeOf
+ "Temps cloud illimité", // CloudTimeUnlimited
+ "Il vous reste %s de temps de jeu dans le cloud Xbox ce mois-ci", // CloudTimeWarn
};
diff --git a/src/ui/i18n/strings_it.inc b/src/ui/i18n/strings_it.inc
index 0df08ec..2e77a44 100644
--- a/src/ui/i18n/strings_it.inc
+++ b/src/ui/i18n/strings_it.inc
@@ -416,5 +416,10 @@ constexpr Column kItalian = {
"Per giocare a titoli gratuiti oltre a Fortnite senza Game Pass, abilita 'Funzionalità Preview' nelle Impostazioni e su xbox.com/play.", // F2pPreviewRequiredDesc
"Questo account deve abilitare le 'Funzionalità Preview' nel profilo su xbox.com/play per sbloccare lo streaming gratuito supportato da annunci.", // F2pPreviewAccountNeededDesc
"Giocatore", // MenuPlayer
+ "Il tuo tempo di gioco nel cloud Xbox è esaurito, quindi il servizio Xbox ha chiuso la sessione. Da novembre 2026 Xbox limita il gioco nel cloud ogni mese: 15 ore con Game Pass Ultimate, 10 con Premium e 5 con Essential. Per avere più tempo, vedi le opzioni su xbox.com, o attendi le ore del mese prossimo.", // CloudTimeUp
"La sessione è terminata per inattività", // EndedIdle
+ "%s rimanenti", // CloudTimeLeft
+ "di %s", // CloudTimeOf
+ "Tempo cloud illimitato", // CloudTimeUnlimited
+ "Restano %s del tuo tempo di gioco nel cloud Xbox questo mese", // CloudTimeWarn
};
diff --git a/src/ui/i18n/strings_pt_br.inc b/src/ui/i18n/strings_pt_br.inc
index bcaa489..d639a8c 100644
--- a/src/ui/i18n/strings_pt_br.inc
+++ b/src/ui/i18n/strings_pt_br.inc
@@ -416,5 +416,10 @@ constexpr Column kPortugueseBR = {
"Para transmitir jogos gratuitos além de Fortnite em contas sem Game Pass, ative os 'Recursos Preview' nas Configurações do app e no site xbox.com/play.", // F2pPreviewRequiredDesc
"Esta conta precisa habilitar os 'Recursos Preview' no perfil em xbox.com/play para liberar o streaming com anúncios de jogos gratuitos.", // F2pPreviewAccountNeededDesc
"Jogador", // MenuPlayer
+ "Seu tempo de jogo na nuvem do Xbox acabou, então o serviço do Xbox encerrou a sessão. Desde novembro de 2026, o Xbox limita o jogo na nuvem por mês: 15 h no Game Pass Ultimate, 10 h no Premium e 5 h no Essential. Para ter mais tempo, veja as opções em xbox.com, ou espere as horas do próximo mês.", // CloudTimeUp
"O streaming foi encerrado por inatividade", // EndedIdle
+ "%s restantes", // CloudTimeLeft
+ "de %s", // CloudTimeOf
+ "Tempo de nuvem ilimitado", // CloudTimeUnlimited
+ "Restam %s do seu tempo de jogo na nuvem do Xbox neste mês", // CloudTimeWarn
};
diff --git a/src/ui/stream_menu.cpp b/src/ui/stream_menu.cpp
index 4609e08..d4dfacb 100644
--- a/src/ui/stream_menu.cpp
+++ b/src/ui/stream_menu.cpp
@@ -2,6 +2,8 @@
// Copyright (C) 2026 RafaelNGP
#include "ui/stream_menu.h"
+#include "ui/cloud_time.h"
+
#include "ui/strings.h"
#include "ui/input_mode.h"
#include "ui/pad_glyphs.h"
@@ -381,7 +383,21 @@ Canvas StreamMenu::renderMenu(const StreamInfo& info) const {
return c;
}
- fonts_.bold.draw(c, tr(Str::MenuTitle), kPad, 34, 30, kWhite);
+ const int titleEnd = fonts_.bold.draw(c, tr(Str::MenuTitle), kPad, 34, 30, kWhite);
+ // The account's cloud time left, right of the title (a limited account
+ // only): orange from 15 minutes shown, when the notices start; red at none.
+ if (info.cloudTimeSeconds >= 0) {
+ const std::string left = trf(Str::CloudTimeLeft, formatCloudTime(info.cloudTimeSeconds));
+ const int w = fonts_.semibold.measure(left, 17);
+ const int x = kMenuW - kPad - w;
+ if (x - 24 > titleEnd + 16) {
+ const Color col = info.cloudTimeSeconds <= 0 ? rgba(240, 100, 100)
+ : info.cloudTimeSeconds < 16 * 60 ? rgba(255, 160, 40)
+ : kGray;
+ drawClockIcon(c, x - 14.0f, 34 + 15.0f, 8.0f, col);
+ fonts_.semibold.draw(c, left, x, fonts_.semibold.centeredY(34, 30, 17), 17, col);
+ }
+ }
// The items: the selected one white, like the Xbox guide.
constexpr int kRowH = 37, kTop = 78, kPx = 19;
diff --git a/src/ui/stream_menu.h b/src/ui/stream_menu.h
index 8152bbc..86d9172 100644
--- a/src/ui/stream_menu.h
+++ b/src/ui/stream_menu.h
@@ -24,7 +24,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)
+ int64_t cloudTimeSeconds = -1; // the account's cloud time left (-1: no limit, or not known)
uint64_t playtimeSeconds = 0; // total playtime for this title in seconds
std::vector<float> frametimes; // presentation frametimes (ms)
};
diff --git a/src/ui/strings.h b/src/ui/strings.h
index d1ad7d1..9edb6b4 100644
--- a/src/ui/strings.h
+++ b/src/ui/strings.h
@@ -425,7 +425,12 @@ enum class Str {
F2pPreviewRequiredDesc,
F2pPreviewAccountNeededDesc,
MenuPlayer, // game menu, a USB controller's: the player it plays as
+ CloudTimeUp, // the server ended the stream: the account's (or game's) cloud time ran out
EndedIdle, // toast: the server ended the stream after a while without input
+ CloudTimeLeft, // top bar / game menu: "%s" = the cloud time left ("4 h 10 min")
+ CloudTimeOf, // top bar, after CloudTimeLeft: "%s" = the month's hours
+ CloudTimeUnlimited, // top bar: the account has no cloud time limit
+ CloudTimeWarn, // notification while streaming: "%s" = the cloud time left
Count
};
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 5559dcb..c0534fd 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -31,6 +31,7 @@
#include "ui/pad_glyphs.h"
#include "ui/input_mode.h"
#include "ui/stream_menu.h"
+#include "ui/cloud_time.h"
#include "ui/strings.h"
#include "ui/app_ui_internal.h"
#include "util/json.h"
@@ -516,59 +517,142 @@ static void testPerGameSettings() {
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);
+// Protobuf wire format for the Content Access tests.
+static std::string pbVarint(uint64_t v) {
+ std::string s;
+ do {
+ uint8_t b = v & 0x7F;
+ v >>= 7;
+ s += static_cast<char>(b | (v ? 0x80 : 0));
+ } while (v);
+ return s;
+}
+static std::string pbInt(int field, uint64_t v) { return pbVarint(static_cast<uint64_t>(field) << 3) + pbVarint(v); }
+static std::string pbMsg(int field, const std::string& body) {
+ return pbVarint((static_cast<uint64_t>(field) << 3) | 2) + pbVarint(body.size()) + body;
+}
+// A product as Content Access sends it: its ID, then for each user (PUID)
+// the access types and, when timed, the streaming gameplay time.
+static std::string pbProduct(const std::string& id, const std::string& puid, int64_t remaining, int64_t max) {
+ std::string streaming = pbInt(1, 2);
+ if (remaining >= 0) streaming += pbInt(2, static_cast<uint64_t>(remaining));
+ if (max >= 0) streaming += pbInt(4, static_cast<uint64_t>(max));
+ std::string access = pbInt(1, 1) + pbInt(2, 1788310800u) + pbMsg(11, streaming); // aggregate types: a big bit mask
+ return pbMsg(2, pbMsg(1, id) + pbMsg(2, pbMsg(2, pbMsg(1, puid) + pbMsg(2, access))));
+}
- // 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);
+static void testCloudTimeClock() {
+ using xc::ui::CloudTimeClock;
+ using xc::ui::formatCloudTime;
+ // Whole minutes, rounded down.
+ CHECK(formatCloudTime(15000) == "4 h 10 min");
+ CHECK(formatCloudTime(54000) == "15 h");
+ CHECK(formatCloudTime(2879) == "47 min");
+ CHECK(formatCloudTime(59) == "< 1 min");
+ CHECK(formatCloudTime(0) == "0 min");
+ // After a session: an answer the service has not counted yet keeps the
+ // count; one over the earlier answer is new hours; none keeps the count.
+ CHECK((CloudTimeClock::reconcile(3000, 6600, 6600) == 3000));
+ CHECK((CloudTimeClock::reconcile(3000, 2000, 6600) == 2000));
+ CHECK((CloudTimeClock::reconcile(3000, 54000, 6600) == 54000));
+ CHECK((CloudTimeClock::reconcile(3000, -1, 6600) == 3000));
+ CHECK((CloudTimeClock::reconcile(-1, 900, -1) == 900));
+
+ CloudTimeClock c;
+ c.start(-1, 0);
+ CHECK(!c.limited());
+ CHECK(c.left(60000) == -1);
+ CHECK(c.noticeDue(60000) == -1);
+
+ c.start(16 * 60, 0); // 16 min left
+ CHECK(c.left(0) == 16 * 60);
+ CHECK(c.noticeDue(0) == -1);
+ CHECK(c.left(30500) == 16 * 60 - 30);
+ CHECK(c.noticeDue(60000) == 15 * 60); // 15 min: the first notice, once
+ CHECK(c.noticeDue(61000) == -1);
+ c.answer(16 * 60, 120000); // stale: the service had not counted the stream
+ CHECK(c.left(120000) == 14 * 60);
+ c.answer(10 * 60, 120000); // lower: taken
+ CHECK(c.left(120000) == 10 * 60);
+ CHECK(c.noticeDue(420000) == 5 * 60); // 5 min
+ CHECK(c.noticeDue(500000) == -1);
+ CHECK(c.left(10000000) == 0);
+ c.answer(15 * 3600, 10000000); // hours bought: over the start's answer
+ CHECK(c.left(10000000) == 15 * 3600);
+
+ c.start(10 * 60, 0); // a stream that starts under 15 minutes: one notice now
+ CHECK(c.noticeDue(0) == 10 * 60);
+ CHECK(c.noticeDue(1000) == -1);
+ CHECK(c.noticeDue(300000) == 5 * 60);
+ c.start(4 * 60, 0); // under 5: just the one
+ CHECK(c.noticeDue(0) == 4 * 60);
+ CHECK(c.noticeDue(60000) == -1);
+ c.start(5 * 60 + 10, 0); // "5 min" already shown: not said twice
+ CHECK(c.noticeDue(0) == 5 * 60 + 10);
+ CHECK(c.noticeDue(10000) == -1);
+ c.start(16 * 60 + 30, 0); // the notice when "15 min" first shows
+ CHECK(c.noticeDue(30000) == -1);
+ CHECK(c.noticeDue(31000) == 15 * 60 + 59);
+}
- // 5. Empty and invalid inputs
+static void testPlaytimeLimit() {
+ int64_t rem = -1, max = -1;
+ const std::string passes = pbMsg(1, pbMsg(1, "puid-1") + pbMsg(2, pbMsg(1, pbMsg(1, "CFQ7TTC0KHS0") + pbMsg(2, pbInt(1, 0)))));
+
+ // 1. The account's allowance: the same remaining / max on its limited
+ // products (15 h a month, 9 h 30 left), not the access bit masks.
+ std::string body = passes + pbProduct("9NBLGGH4R315", "puid-1", 34200, 54000) +
+ pbProduct("BT5P2X999VH2", "puid-1", 34200, 54000) + pbProduct("9PNCL2R6G8D0", "puid-1", 34200, 54000) +
+ pbProduct("9NZQPT0MWTD0", "puid-1", -1, -1);
+ auth::ContentAccessPlaytime t;
+ CHECK(auth::parseContentAccessPlaytime(body, t));
+ CHECK(t.products == 4 && t.limited == 3 && t.byProduct.size() == 3);
+ CHECK(t.accountRemaining == 34200 && t.accountMax == 54000);
+ CHECK(t.byProduct["BT5P2X999VH2"].first == 34200 && t.byProduct["BT5P2X999VH2"].second == 54000);
+ CHECK(auth::parsePlaytimeLimit(body, rem, max) && rem == 34200 && max == 54000);
+
+ // 2. One timed product (a game's own free time): no account allowance.
+ std::string one = passes + pbProduct("BT5P2X999VH2", "puid-1", 0, 3600) + pbProduct("9NZQPT0MWTD0", "puid-1", -1, -1);
+ CHECK(auth::parseContentAccessPlaytime(one, t));
+ CHECK(t.limited == 1 && t.accountRemaining == -1 && t.byProduct["BT5P2X999VH2"].first == 0);
+ CHECK(!auth::parsePlaytimeLimit(one, rem, max) && rem == -1 && max == -1);
+
+ // 3. Another user's access (a family member) is not this account's.
+ std::string other = passes + pbProduct("A", "puid-2", 100, 200) + pbProduct("B", "puid-2", 100, 200) +
+ pbProduct("C", "puid-2", 100, 200);
+ CHECK(auth::parseContentAccessPlaytime(other, t) && t.byProduct.empty() && t.accountRemaining == -1);
+
+ // 4. JSON: the same rule over its objects.
+ std::string json = R"({"products":[{"productId":"A","remainingGameplayTimeInSeconds":7200,"maxGameplayTimeInSeconds":18000},
+ {"productId":"B","remainingGameplayTimeInSeconds":"7200","maxGameplayTimeInSeconds":"18000"},
+ {"productId":"C","remainingGameplayTimeInSeconds":7200,"maxGameplayTimeInSeconds":18000}]})";
+ CHECK(auth::parsePlaytimeLimit(json, rem, max) && rem == 7200 && max == 18000);
+
+ // 5. The account's own record (top-level field 3): its first bucket.
+ auto account = [&](uint64_t remaining, uint64_t max) {
+ std::string bucket = pbInt(2, remaining) + pbInt(3, 1791335750u) + pbInt(4, max) + pbInt(5, 1);
+ std::string other = pbInt(3, 1791335750u) + pbInt(5, 1);
+ return pbMsg(3, pbMsg(1, "puid-1") + pbMsg(2, pbMsg(2, bucket) + pbMsg(3, other) + pbMsg(4, other)));
+ };
+ // As this console's Ultimate account answered on 2026-11-04: no limit
+ // (all bits set), and no product with a time of its own.
+ std::string unlimited = passes + pbProduct("9NZQPT0MWTD0", "puid-1", -1, -1) + account(~0ull, ~0ull);
+ CHECK(auth::parseContentAccessPlaytime(unlimited, t));
+ CHECK(t.unlimited && t.accountRemaining == -1 && t.accountBuckets.size() == 3);
+ CHECK(t.accountBuckets[2].first == auth::ContentAccessPlaytime::kUnlimited && t.accountBuckets[3].first == -1);
+ CHECK(!auth::parsePlaytimeLimit(unlimited, rem, max));
+ // A limited account: 15 h a month, 4 h 10 min left; the record wins over
+ // the products' own times.
+ std::string limited = passes + pbProduct("A", "puid-1", 100, 200) + pbProduct("B", "puid-1", 100, 200) +
+ pbProduct("C", "puid-1", 100, 200) + account(15000, 54000);
+ CHECK(auth::parseContentAccessPlaytime(limited, t) && !t.unlimited);
+ CHECK(t.accountRemaining == 15000 && t.accountMax == 54000);
+ CHECK(auth::parsePlaytimeLimit(limited, rem, max) && rem == 15000 && max == 54000);
+
+ // 6. Empty and invalid answers.
CHECK(!auth::parsePlaytimeLimit("", rem, max));
CHECK(!auth::parsePlaytimeLimit("not a valid payload", rem, max));
-
- // 6. Zero playtime remains purely informational
- std::string zeroJson = R"({"remainingGameplayTimeInSeconds": 0, "maxGameplayTimeInSeconds": 18000})";
- CHECK(auth::parsePlaytimeLimit(zeroJson, rem, max));
- CHECK(rem == 0 && max == 18000);
-
- // 7. Client-side launch is never blocked by zero or low remaining playtime
- ui::Fonts fonts;
- ui::ImageCache images([] {});
- ui::AppUi app(fonts, images);
- app.setSubscription("GamePass");
- ui::GameTile tile;
- tile.titleId = "TEST_TITLE_1";
- tile.productId = "TEST_PROD_1";
- tile.playable = true;
- ui::GameRow row;
- row.title = "Popular";
- row.tiles = {tile};
- app.setRows({row});
- app.setPlaytime(0, 18000); // 0 seconds remaining
- app.showHome();
- ui::NavInput in;
- in.accept = true;
- app.handle(in); // Home -> Details
- ui::UiEvent ev = app.handle(in); // Details -> Play
- CHECK(ev.action == ui::Action::Play);
- CHECK(ev.game.titleId == "TEST_TITLE_1");
+ CHECK(!auth::parseContentAccessPlaytime(std::string("\x0a\x05\x01", 3), t)); // length past the end
}
static void testFreeAccountPlayability() {
@@ -7094,6 +7178,7 @@ int main() {
testMicGain();
testPerGameSettings();
testPlaytimeLimit();
+ testCloudTimeClock();
testStrings();
testRegions();
testPrices();