Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

Fix video artifacts with a NACK jitter buffer; rumble; new controls; 1440p

Rafael Abud Ferreirae4abe268e489
diff --git a/CMakeLists.txt b/CMakeLists.txt
index e3d207f..34a8970 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -38,6 +38,7 @@ include(cmake/deps/libdatachannel.cmake)
# --- WebRTC streaming: SDP/ICE, data channels, input reports ----------------
add_library(xcloud_stream STATIC
+ src/stream/h264_receiver.cpp
src/stream/input_packet.cpp
src/stream/stream_session.cpp
)
diff --git a/README.md b/README.md
index 679ec92..a4eb3bf 100644
--- a/README.md
+++ b/README.md
@@ -25,9 +25,12 @@ an Xbox controller.
added, Most popular on cloud, Leaving soon and All games.
- WebRTC streaming (libdatachannel on Mbed TLS) with H.264 and Opus decoded by
FFmpeg on the CPU.
-- Settings (Triangle on the home screen): language (English, Português
- (Brasil), Español, Français, Deutsch, Italiano), stream resolution (1080p or
- 720p for slower connections) and server region.
+- Settings (OPTIONS on the home screen): language (English, Português
+ (Brasil), Español, Français, Deutsch, Italiano), stream resolution (1080p,
+ 720p for slower connections, or 1440p, experimental: only where Microsoft
+ offers it) and server region. Hold TOUCHPAD for 5 seconds to sign out.
+- Lost video packets are re-requested (RTCP NACK) and damaged frames are
+ never shown; DualSense rumble follows the game.
- Custom PS5 Home art (selection and launch backgrounds), generated from the
same code as the icon by `tools/ps5/home-art.sh`.
diff --git a/ps5/release/README.txt b/ps5/release/README.txt
index 37fe202..f53f8fb 100644
--- a/ps5/release/README.txt
+++ b/ps5/release/README.txt
@@ -40,14 +40,14 @@ that code. Your password is never typed on the console.
The sign-in is saved in /data/homebrew/@TITLE_ID@/account.json. That
file gives access to your Microsoft account: never share it, and never
-attach it to a bug report. "Sign out" (OPTIONS on the home screen)
-deletes it.
+attach it to a bug report. Signing out (hold TOUCHPAD for 5 seconds
+on the home screen) deletes it.
Controls
--------
Menus: D-pad or left stick to move, Cross to select, Circle to go back,
- Triangle for Settings, OPTIONS to sign out.
+ OPTIONS for Settings, hold TOUCHPAD for 5 seconds to sign out.
In game: the DualSense acts as an Xbox controller
(Cross = A, Circle = B, Square = X, Triangle = Y,
OPTIONS = Menu, TOUCHPAD = View).
@@ -56,9 +56,10 @@ In game: the DualSense acts as an Xbox controller
Settings
--------
-Triangle on the home screen: language (English, Portugues (Brasil),
-Espanol, Francais, Deutsch, Italiano), stream resolution (1080p, or 720p
-for slower connections) and server region (Automatic, or a specific
+OPTIONS on the home screen: language (English, Portugues (Brasil),
+Espanol, Francais, Deutsch, Italiano), stream resolution (1080p, 720p
+for slower connections, or 1440p - experimental, only granted where
+Microsoft offers it, otherwise you still get 1080p) and server region (Automatic, or a specific
Azure region). Saved in /data/homebrew/@TITLE_ID@/settings.json.
diff --git a/src/app/cli_main.cpp b/src/app/cli_main.cpp
index 522245e..0b49598 100644
--- a/src/app/cli_main.cpp
+++ b/src/app/cli_main.cpp
@@ -207,11 +207,19 @@ int cmdStream(auth::AuthManager& am, const std::string& titleId, int seconds, co
if (platform::nowMs() >= nextReport) {
nextReport += 1000;
session.tick();
- std::printf("video %llu frames (%llu key) %.1f MB, audio %llu packets (%.1f s decoded)\n",
+ const auto& rtp = session.videoStats();
+ std::printf("video %llu frames (%llu key) %.1f MB, audio %llu packets (%.1f s decoded); "
+ "rtp %llu pkts, %llu lost, %llu recovered, %llu nacks, %llu dropped, %llu kf req\n",
static_cast<unsigned long long>(videoFrames.load()),
static_cast<unsigned long long>(keyFrames.load()), videoBytes.load() / 1048576.0,
static_cast<unsigned long long>(audioPackets.load()),
- audioSamples.load() / double(media::AudioDecoder::kSampleRate));
+ audioSamples.load() / double(media::AudioDecoder::kSampleRate),
+ static_cast<unsigned long long>(rtp.packets.load()),
+ static_cast<unsigned long long>(rtp.lost.load()),
+ static_cast<unsigned long long>(rtp.recovered.load()),
+ static_cast<unsigned long long>(rtp.nacks.load()),
+ static_cast<unsigned long long>(rtp.framesDropped.load()),
+ static_cast<unsigned long long>(rtp.keyframeRequests.load()));
std::fflush(stdout);
}
platform::sleepMs(16);
@@ -324,7 +332,7 @@ int cmdUiPreview(auth::AuthManager& am, const std::string& dir) {
app.setRegions(regions, gssv.region().name);
app.showHome();
ui::NavInput tri;
- tri.triangle = true;
+ tri.options = true;
app.handle(tri);
save("settings");
ui::NavInput down2;
@@ -345,6 +353,17 @@ int cmdUiPreview(auth::AuthManager& am, const std::string& dir) {
library.hydrate(onRows);
app.showHome();
save("home_pt", 3000);
+ // Sign-out hold feedback, 2 s into the 5 s hold.
+ ui::NavInput hold;
+ hold.touchpad = true;
+ hold.nowMs = 100000;
+ app.handle(hold);
+ hold.nowMs = 102000;
+ app.handle(hold);
+ app.render(canvas, 102000);
+ std::string holdPath = dir + "/signout_hold.png";
+ stbi_write_png(holdPath.c_str(), canvas.width(), canvas.height(), 4, canvas.data(), canvas.width() * 4);
+ std::printf("wrote %s\n", holdPath.c_str());
ui::setLanguage(ui::Language::English);
return 0;
}
@@ -412,11 +431,14 @@ int main(int argc, char** argv) {
std::vector<const char*> pos;
xcloud::Resolution res = xcloud::Resolution::P1080;
stream::StreamOptions opts;
+ if (const char* loss = std::getenv("XC_SIM_LOSS")) opts.simulatedVideoLoss = std::atoi(loss);
std::string region;
for (; argi < argc; ++argi) {
std::string a = argv[argi];
if (a.rfind("--region=", 0) == 0) region = a.substr(9);
else if (a == "--720p") res = xcloud::Resolution::P720;
+ else if (a == "--qhd-display") res = xcloud::Resolution::P1440;
+ else if (a.rfind("--tier=", 0) == 0) opts.resolutionAlias = a.substr(7);
else pos.push_back(argv[argi]);
}
int seconds = pos.size() > 1 ? std::atoi(pos[1]) : 30;
diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cpp
index 6d4fdde..c99dc5c 100644
--- a/src/app/ps5_main.cpp
+++ b/src/app/ps5_main.cpp
@@ -175,11 +175,15 @@ std::string stream(xcloud::GssvClient& gssv) {
player.tick();
auto st = player.stats();
XC_LOGI("stream: %llu frames, %llu decoded, %llu skipped, %llu failed, %llu resets, %llu kf req, "
- "%llu queued, %llu audio",
+ "%llu queued, %llu audio; rtp %llu pkts, %llu lost, %llu recovered, %llu nacks, "
+ "%llu frames dropped",
static_cast<unsigned long long>(st.videoFrames), static_cast<unsigned long long>(st.decodedFrames),
static_cast<unsigned long long>(st.droppedFrames), static_cast<unsigned long long>(st.decodeFailures),
static_cast<unsigned long long>(st.queueResets), static_cast<unsigned long long>(st.keyframeRequests),
- static_cast<unsigned long long>(st.queued), static_cast<unsigned long long>(st.audioPackets));
+ static_cast<unsigned long long>(st.queued), static_cast<unsigned long long>(st.audioPackets),
+ static_cast<unsigned long long>(st.rtpPackets), static_cast<unsigned long long>(st.rtpLost),
+ static_cast<unsigned long long>(st.rtpRecovered), static_cast<unsigned long long>(st.rtpNacks),
+ static_cast<unsigned long long>(st.rtpDroppedFrames));
}
platform::sleepMs(100);
}
@@ -202,7 +206,9 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game
std::string err;
{
std::lock_guard<std::mutex> lock(g_settingsMutex);
- gssv.setResolution(g_settings.resolution == "720p" ? xcloud::Resolution::P720 : xcloud::Resolution::P1080);
+ gssv.setResolution(g_settings.resolution == "720p" ? xcloud::Resolution::P720
+ : g_settings.resolution == "1440p" ? xcloud::Resolution::P1440
+ : xcloud::Resolution::P1080);
const xcloud::Region* region = gssv.session().defaultRegion();
for (const auto& r : gssv.session().regions)
if (r.name == g_settings.region) region = &r;
@@ -420,7 +426,7 @@ int main(int argc, char** argv) {
{
ui::SettingsChoice choice;
choice.language = static_cast<int>(ui::language());
- choice.hd = g_settings.resolution != "720p";
+ choice.resolution = g_settings.resolution == "720p" ? 1 : g_settings.resolution == "1440p" ? 2 : 0;
choice.region = g_settings.region;
g_ui->setSettings(choice);
}
@@ -474,7 +480,8 @@ int main(int argc, char** argv) {
nav.accept = pad.btnA && !prev.btnA;
nav.back = pad.btnB && !prev.btnB;
nav.options = pad.btnOptions && !prev.btnOptions;
- nav.triangle = pad.btnY && !prev.btnY;
+ nav.touchpad = pad.btnTouchpad;
+ nav.nowMs = now;
prev = pad;
ui::UiEvent ev = g_ui->handle(nav);
@@ -498,7 +505,9 @@ int main(int argc, char** argv) {
std::string code = ui::languageCode(static_cast<ui::Language>(ev.settings.language));
languageChanged = code != g_settings.language;
g_settings.language = code;
- g_settings.resolution = ev.settings.hd ? "1080p" : "720p";
+ g_settings.resolution = ev.settings.resolution == 1 ? "720p"
+ : ev.settings.resolution == 2 ? "1440p"
+ : "1080p";
g_settings.region = ev.settings.region;
if (!g_settings.save(settingsPath())) XC_LOGW("could not save settings");
XC_LOGI("settings saved: language %s, %s, region %s", code.c_str(), g_settings.resolution.c_str(),
diff --git a/src/app/settings.cpp b/src/app/settings.cpp
index 717dd10..c5561ad 100644
--- a/src/app/settings.cpp
+++ b/src/app/settings.cpp
@@ -15,7 +15,7 @@ bool Settings::load(const std::string& path) {
language = (*j)["language"].str(language);
resolution = (*j)["resolution"].str(resolution);
region = (*j)["region"].str(region);
- if (resolution != "720p") resolution = "1080p";
+ if (resolution != "720p" && resolution != "1440p") resolution = "1080p";
return true;
}
diff --git a/src/app/settings.h b/src/app/settings.h
index c5b76ae..2ca9ef1 100644
--- a/src/app/settings.h
+++ b/src/app/settings.h
@@ -9,7 +9,7 @@ namespace xc::app {
struct Settings {
std::string language = "en"; // ui::languageCode()
- std::string resolution = "1080p"; // "1080p" or "720p"
+ std::string resolution = "1080p"; // "1080p", "720p" or "1440p" (experimental)
std::string region; // gssv region name; empty = automatic
bool load(const std::string& path);
diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cpp
index 0bb8753..503d6c9 100644
--- a/src/app/stream_player.cpp
+++ b/src/app/stream_player.cpp
@@ -3,13 +3,16 @@
#include "app/stream_player.h"
#include "display/display.h"
+#include "input/controller.h"
#include "media/audio_out.h"
#include "media/decoder.h"
#include "platform/platform.h"
#include "stream/stream_session.h"
#include "util/log.h"
+#include <algorithm>
#include <atomic>
+#include <cstdlib>
#include <cstdio>
#include <condition_variable>
#include <deque>
@@ -163,9 +166,21 @@ struct StreamPlayer::Impl {
if (audioPackets_.size() < 50) audioPackets_.emplace_back(d, d + n);
audioCv.notify_one();
};
+ // xCloud's motors are 0..100 percent, like the web client's
+ // dual-rumble effect (left = strong, right = weak). The trigger
+ // motors have no plain-rumble counterpart on the DualSense.
+ cb.vibration = [](const stream::Vibration& v) {
+ auto scale = [](uint8_t pct) { return static_cast<uint8_t>(std::min<int>(pct, 100) * 255 / 100); };
+ input::setRumble(scale(v.leftMotor), scale(v.rightMotor), v.durationMs);
+ };
cb.closed = [this](const std::string& reason) { end(reason); };
- session = std::make_unique<stream::StreamSession>(gssv, cb);
+ stream::StreamOptions opts;
+ // 1440p is asked for like the xbox.com client does; the service only
+ // grants it where Microsoft has enabled it (not every market).
+ if (gssv.resolution() == xcloud::Resolution::P1440) opts.resolutionAlias = "1440";
+ if (const char* loss = std::getenv("XC_SIM_LOSS")) opts.simulatedVideoLoss = std::atoi(loss);
+ session = std::make_unique<stream::StreamSession>(gssv, cb, opts);
running = true;
if (!platform::startThread(videoThread, [this] { videoLoop(); }) ||
!platform::startThread(audioThread, [this] { audioLoop(); }, 1u << 20)) {
@@ -228,6 +243,7 @@ struct StreamPlayer::Impl {
if (audioThread.joinable()) audioThread.join();
session.reset();
media::audioStop();
+ input::setRumble(0, 0, 0);
}
};
@@ -295,6 +311,15 @@ StreamPlayer::Stats StreamPlayer::stats() const {
st.decodeFailures = impl_->decodeFailures;
st.queueResets = impl_->queueResets;
st.keyframeRequests = impl_->keyframeRequests;
+ if (impl_->session) { // the caller's thread is the one that stops the player
+ const auto& v = impl_->session->videoStats();
+ st.rtpPackets = v.packets;
+ st.rtpLost = v.lost;
+ st.rtpRecovered = v.recovered;
+ st.rtpNacks = v.nacks;
+ st.rtpDroppedFrames = v.framesDropped;
+ st.keyframeRequests += v.keyframeRequests;
+ }
{
std::lock_guard<std::mutex> lock(impl_->mutex);
st.queued = impl_->frames.size();
diff --git a/src/app/stream_player.h b/src/app/stream_player.h
index bde1af3..562c4ed 100644
--- a/src/app/stream_player.h
+++ b/src/app/stream_player.h
@@ -35,6 +35,8 @@ public:
struct Stats {
uint64_t videoFrames = 0, decodedFrames = 0, droppedFrames = 0, audioPackets = 0;
uint64_t decodeFailures = 0, queueResets = 0, keyframeRequests = 0, queued = 0;
+ // RTP: packets lost, recovered by NACK, frames the jitter buffer dropped.
+ uint64_t rtpPackets = 0, rtpLost = 0, rtpRecovered = 0, rtpNacks = 0, rtpDroppedFrames = 0;
};
Stats stats() const;
diff --git a/src/input/controller.cpp b/src/input/controller.cpp
index 2b822f0..073c93f 100644
--- a/src/input/controller.cpp
+++ b/src/input/controller.cpp
@@ -4,10 +4,13 @@
#include "util/log.h"
#include <algorithm>
+#include <atomic>
#include <cmath>
#include <cstddef>
#include <cstring>
+#include "platform/platform.h"
+
#if defined(XCLOUD_PS5)
extern "C" {
@@ -61,6 +64,12 @@ int scePadInit(void);
int scePadOpen(int32_t userId, int32_t type, int32_t index, const void* param);
int scePadClose(int32_t handle);
int scePadReadState(int32_t handle, ScePadData* data);
+
+struct ScePadVibrationParam {
+ uint8_t largeMotor;
+ uint8_t smallMotor;
+};
+int scePadSetVibration(int32_t handle, const ScePadVibrationParam* param);
}
namespace xc::input {
@@ -79,8 +88,36 @@ inline float normStick(uint8_t val) {
inline float normTrigger(uint8_t val) {
return static_cast<float>(val) / 255.0f;
}
+
+// Requested rumble, packed as large << 8 | small, and when it ends (0 = never).
+std::atomic<uint32_t> g_rumbleWanted{0};
+std::atomic<uint64_t> g_rumbleUntilMs{0};
+uint32_t g_rumbleApplied = 0;
+bool g_rumbleErrorLogged = false;
+
+void applyRumble() {
+ uint32_t want = g_rumbleWanted;
+ uint64_t until = g_rumbleUntilMs;
+ if (want && until && platform::nowMs() >= until) {
+ g_rumbleWanted.compare_exchange_strong(want, 0);
+ want = 0;
+ }
+ if (want == g_rumbleApplied) return;
+ ScePadVibrationParam p{static_cast<uint8_t>(want >> 8), static_cast<uint8_t>(want)};
+ int rc = scePadSetVibration(g_padHandle, &p);
+ if (rc != 0 && !g_rumbleErrorLogged) {
+ g_rumbleErrorLogged = true;
+ XC_LOGW("scePadSetVibration failed: 0x%08x", rc);
+ }
+ g_rumbleApplied = want;
+}
} // namespace
+void setRumble(uint8_t large, uint8_t small, uint32_t durationMs) {
+ g_rumbleUntilMs = durationMs ? platform::nowMs() + durationMs : 0;
+ g_rumbleWanted = (uint32_t(large) << 8) | small;
+}
+
bool init() {
int rc = scePadInit();
if (rc != 0) {
@@ -110,6 +147,8 @@ bool init() {
void shutdown() {
if (g_padHandle >= 0) {
+ ScePadVibrationParam off{0, 0};
+ scePadSetVibration(g_padHandle, &off);
scePadClose(g_padHandle);
g_padHandle = -1;
}
@@ -120,6 +159,7 @@ bool poll(ControllerState& out) {
out = {};
return false;
}
+ applyRumble();
ScePadData pad{};
int rc = scePadReadState(g_padHandle, &pad);
if (rc != 0 || !pad.connected) {
@@ -176,6 +216,7 @@ bool poll(ControllerState& out) {
out.connected = true;
return true;
}
+void setRumble(uint8_t, uint8_t, uint32_t) {}
} // namespace xc::input
#endif
diff --git a/src/input/controller.h b/src/input/controller.h
index d05bc95..27b4131 100644
--- a/src/input/controller.h
+++ b/src/input/controller.h
@@ -42,5 +42,8 @@ struct ControllerState {
bool init();
void shutdown();
bool poll(ControllerState& out);
+// Rumble, 0..255 per motor (large = low frequency, small = high frequency),
+// for `durationMs` (0 = until changed). Any thread; poll() applies it.
+void setRumble(uint8_t large, uint8_t small, uint32_t durationMs);
} // namespace xc::input
diff --git a/src/stream/h264_receiver.cpp b/src/stream/h264_receiver.cpp
new file mode 100644
index 0000000..55094f4
--- /dev/null
+++ b/src/stream/h264_receiver.cpp
@@ -0,0 +1,320 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+#include "stream/h264_receiver.h"
+
+#include "platform/platform.h"
+#include "util/log.h"
+
+#include <algorithm>
+
+namespace xc::stream {
+
+namespace {
+
+// How long a hole may wait for its retransmission (a couple of RTTs), how
+// often a NACK is repeated, and how many times.
+constexpr uint64_t kWaitMs = 150;
+constexpr uint64_t kRenackMs = 40;
+constexpr int kMaxNacks = 3;
+constexpr uint32_t kOurSsrc = 0x50534278; // "PSBx": RTCP sender SSRC
+constexpr size_t kMaxBuffered = 4000; // packets (about 4 MB)
+
+constexpr uint8_t kStartCode[] = {0, 0, 0, 1};
+
+// NAL types that begin a decodable access unit after loss.
+bool isKeyNal(uint8_t type) { return type == 5 || type == 7; }
+
+void put16(std::vector<uint8_t>& b, uint16_t v) {
+ b.push_back(static_cast<uint8_t>(v >> 8));
+ b.push_back(static_cast<uint8_t>(v));
+}
+void put32(std::vector<uint8_t>& b, uint32_t v) {
+ for (int s = 24; s >= 0; s -= 8) b.push_back(static_cast<uint8_t>(v >> s));
+}
+
+const std::byte* asBytes(const std::vector<uint8_t>& v) { return reinterpret_cast<const std::byte*>(v.data()); }
+
+} // namespace
+
+H264Receiver::H264Receiver(std::function<void()> onKeyframeNeeded, VideoReceiveStats& stats)
+ : onKeyframeNeeded_(std::move(onKeyframeNeeded)), stats_(stats) {}
+
+int64_t H264Receiver::unwrap(uint16_t seq) {
+ if (highest_ < 0) return seq;
+ int64_t base = highest_ & ~int64_t(0xFFFF);
+ int64_t candidate = base | seq;
+ // Pick the value closest to the highest seen (handles both wrap directions).
+ if (candidate - highest_ > 0x8000) candidate -= 0x10000;
+ else if (highest_ - candidate > 0x8000) candidate += 0x10000;
+ return candidate;
+}
+
+void H264Receiver::sendNack(const std::vector<int64_t>& seqs, const rtc::message_callback& send) {
+ if (seqs.empty() || !mediaSsrc_) return;
+ // Generic NACK (RFC 4585 6.2.1): FCI = PID + bitmask of the next 16.
+ std::vector<std::pair<uint16_t, uint16_t>> fci;
+ for (size_t i = 0; i < seqs.size();) {
+ int64_t pid = seqs[i];
+ uint16_t blp = 0;
+ size_t j = i + 1;
+ while (j < seqs.size() && seqs[j] - pid <= 16) {
+ blp |= static_cast<uint16_t>(1u << (seqs[j] - pid - 1));
+ ++j;
+ }
+ fci.emplace_back(static_cast<uint16_t>(pid), blp);
+ i = j;
+ }
+ std::vector<uint8_t> b;
+ b.push_back(0x81); // V=2, FMT=1
+ b.push_back(205); // RTPFB
+ put16(b, static_cast<uint16_t>(2 + fci.size()));
+ put32(b, kOurSsrc);
+ put32(b, mediaSsrc_);
+ for (auto [pid, blp] : fci) {
+ put16(b, pid);
+ put16(b, blp);
+ }
+ send(rtc::make_message(asBytes(b), asBytes(b) + b.size(), rtc::Message::Control));
+ ++stats_.nacks;
+ if (simulatedLoss_ > 0)
+ for (int64_t s : seqs) {
+ auto h = held_.find(static_cast<uint16_t>(s));
+ if (h == held_.end()) continue;
+ redeliver_.emplace_back(platform::nowMs() + 30, std::move(h->second));
+ held_.erase(h);
+ }
+}
+
+void H264Receiver::sendPli(const rtc::message_callback& send) {
+ if (!mediaSsrc_) return;
+ std::vector<uint8_t> b;
+ b.push_back(0x81); // V=2, FMT=1
+ b.push_back(206); // PSFB
+ put16(b, 2);
+ put32(b, kOurSsrc);
+ put32(b, mediaSsrc_);
+ send(rtc::make_message(asBytes(b), asBytes(b) + b.size(), rtc::Message::Control));
+}
+
+void H264Receiver::askKeyframe(const rtc::message_callback& send) {
+ waitingKeyframe_ = true;
+ uint64_t now = platform::nowMs();
+ if (now - lastKeyframeRequestMs_ < 300) return; // one request per burst
+ lastKeyframeRequestMs_ = now;
+ ++stats_.keyframeRequests;
+ sendPli(send);
+ if (onKeyframeNeeded_) onKeyframeNeeded_();
+}
+
+void H264Receiver::noteGap(int64_t from, int64_t to, uint64_t now, const rtc::message_callback& send) {
+ if (to - from > 512) { // a huge jump: not worth NACKing, resynchronise
+ stats_.lost += static_cast<uint64_t>(to - from);
+ return;
+ }
+ std::vector<int64_t> seqs;
+ for (int64_t s = from; s < to; ++s) {
+ missing_[s] = Missing{now, now, 1};
+ seqs.push_back(s);
+ }
+ stats_.lost += seqs.size();
+ sendNack(seqs, send);
+}
+
+void H264Receiver::resendNacks(uint64_t now, const rtc::message_callback& send) {
+ std::vector<int64_t> seqs;
+ for (auto& [s, m] : missing_)
+ if (m.nacks < kMaxNacks && now - m.lastNackMs >= kRenackMs) {
+ m.lastNackMs = now;
+ ++m.nacks;
+ seqs.push_back(s);
+ }
+ sendNack(seqs, send);
+}
+
+bool H264Receiver::assemble(int64_t first, int64_t last, std::vector<uint8_t>& out, bool& keyframe) const {
+ out.clear();
+ keyframe = false;
+ for (int64_t s = first; s <= last; ++s) {
+ auto it = packets_.find(s);
+ if (it == packets_.end()) return false;
+ const auto& p = it->second.payload;
+ if (p.empty()) continue;
+ uint8_t type = p[0] & 0x1F;
+ if (type >= 1 && type <= 23) { // single NAL unit
+ out.insert(out.end(), kStartCode, kStartCode + 4);
+ out.insert(out.end(), p.begin(), p.end());
+ keyframe |= isKeyNal(type);
+ } else if (type == 24) { // STAP-A
+ size_t i = 1;
+ while (i + 2 <= p.size()) {
+ size_t n = (static_cast<size_t>(p[i]) << 8) | p[i + 1];
+ i += 2;
+ if (n == 0 || i + n > p.size()) break;
+ out.insert(out.end(), kStartCode, kStartCode + 4);
+ out.insert(out.end(), p.begin() + static_cast<long>(i), p.begin() + static_cast<long>(i + n));
+ keyframe |= isKeyNal(p[i] & 0x1F);
+ i += n;
+ }
+ } else if (type == 28 && p.size() > 2) { // FU-A
+ bool start = (p[1] & 0x80) != 0;
+ if (start) {
+ out.insert(out.end(), kStartCode, kStartCode + 4);
+ out.push_back(static_cast<uint8_t>((p[0] & 0xE0) | (p[1] & 0x1F)));
+ keyframe |= isKeyNal(p[1] & 0x1F);
+ }
+ out.insert(out.end(), p.begin() + 2, p.end());
+ }
+ }
+ return !out.empty();
+}
+
+bool H264Receiver::resync(rtc::message_vector& out) {
+ // Find a frame boundary (the packet before is present and is a marker, or
+ // carries another timestamp) followed by a complete key frame.
+ for (auto it = packets_.begin(); it != packets_.end(); ++it) {
+ auto prev = packets_.find(it->first - 1);
+ if (prev == packets_.end()) continue;
+ if (!prev->second.marker && prev->second.timestamp == it->second.timestamp) continue;
+ // Walk to the marker.
+ int64_t s = it->first;
+ auto cur = it;
+ while (cur != packets_.end() && cur->first == s && !cur->second.marker) {
+ ++cur;
+ ++s;
+ }
+ if (cur == packets_.end() || cur->first != s) return false; // incomplete yet
+ std::vector<uint8_t> frame;
+ bool key = false;
+ if (assemble(it->first, s, frame, key) && key) {
+ nextSeq_ = it->first;
+ packets_.erase(packets_.begin(), it); // older junk
+ (void)out;
+ return true;
+ }
+ }
+ return false;
+}
+
+void H264Receiver::drain(uint64_t now, rtc::message_vector& out, const rtc::message_callback& send) {
+ for (;;) {
+ if (nextSeq_ < 0) {
+ if (!resync(out)) return;
+ }
+ // Collect the frame starting at nextSeq_.
+ int64_t s = nextSeq_;
+ auto it = packets_.find(s);
+ int64_t hole = -1;
+ if (it == packets_.end()) {
+ hole = s;
+ } else {
+ while (true) {
+ auto p = packets_.find(s);
+ if (p == packets_.end()) {
+ hole = s;
+ break;
+ }
+ if (p->second.marker) break;
+ ++s;
+ }
+ }
+ if (hole >= 0) {
+ if (hole > highest_) return; // just not here yet
+ auto m = missing_.find(hole);
+ uint64_t since = m != missing_.end() ? m->second.sinceMs : now;
+ if (m == missing_.end()) missing_[hole] = Missing{now, now, 0};
+ if (now - since < kWaitMs) return; // give the retransmission time
+ // Lost for good: drop what we have of this frame and resync on
+ // the next key frame.
+ ++stats_.framesDropped;
+ for (auto e = packets_.begin(); e != packets_.end() && e->first <= hole;) e = packets_.erase(e);
+ for (auto e = missing_.begin(); e != missing_.end() && e->first <= hole;) e = missing_.erase(e);
+ nextSeq_ = -1;
+ askKeyframe(send);
+ continue;
+ }
+ std::vector<uint8_t> frame;
+ bool key = false;
+ bool ok = assemble(nextSeq_, s, frame, key);
+ uint32_t ts = packets_[s].timestamp;
+ for (auto e = packets_.begin(); e != packets_.end() && e->first <= s;) e = packets_.erase(e);
+ for (auto e = missing_.begin(); e != missing_.end() && e->first <= s;) e = missing_.erase(e);
+ nextSeq_ = s + 1;
+ if (!ok) continue;
+ if (waitingKeyframe_ && !key) {
+ ++stats_.framesDropped; // would decode against lost references
+ continue;
+ }
+ if (key) waitingKeyframe_ = false;
+ ++stats_.framesOut;
+ out.push_back(rtc::make_message(asBytes(frame), asBytes(frame) + frame.size(), std::make_shared<rtc::FrameInfo>(ts)));
+ }
+}
+
+void H264Receiver::accept(const uint8_t* d, size_t n, uint64_t now, const rtc::message_callback& send) {
+ if (n < 12 || (d[0] >> 6) != 2) return;
+ uint16_t rawSeq = static_cast<uint16_t>((d[2] << 8) | d[3]);
+ if (simulatedLoss_ > 0) {
+ lossState_ = lossState_ * 1103515245u + 12345u;
+ if ((lossState_ >> 16) % 100 < static_cast<uint32_t>(simulatedLoss_) && !held_.count(rawSeq)) {
+ held_[rawSeq].assign(d, d + n);
+ if (held_.size() > 2000) held_.erase(held_.begin());
+ return;
+ }
+ }
+ size_t off = 12 + 4u * (d[0] & 0x0F);
+ if (d[0] & 0x10) { // header extension
+ if (off + 4 > n) return;
+ off += 4 + 4u * ((static_cast<size_t>(d[off + 2]) << 8) | d[off + 3]);
+ }
+ size_t end = n;
+ if (d[0] & 0x20) { // padding
+ if (d[n - 1] > n) return;
+ end -= d[n - 1];
+ }
+ if (off > end) return;
+ mediaSsrc_ = (uint32_t(d[8]) << 24) | (uint32_t(d[9]) << 16) | (uint32_t(d[10]) << 8) | d[11];
+ ++stats_.packets;
+
+ int64_t seq = unwrap(rawSeq);
+ if (nextSeq_ >= 0 && seq < nextSeq_) return; // too late or duplicate
+ if (packets_.count(seq)) return;
+ if (missing_.erase(seq)) ++stats_.recovered;
+
+ Packet p;
+ p.timestamp = (uint32_t(d[4]) << 24) | (uint32_t(d[5]) << 16) | (uint32_t(d[6]) << 8) | d[7];
+ p.marker = (d[1] & 0x80) != 0;
+ p.payload.assign(d + off, d + end);
+ packets_.emplace(seq, std::move(p));
+
+ if (highest_ >= 0 && seq > highest_ + 1) noteGap(highest_ + 1, seq, now, send);
+ if (seq > highest_) highest_ = seq;
+}
+
+void H264Receiver::incoming(rtc::message_vector& messages, const rtc::message_callback& send) {
+ rtc::message_vector out;
+ uint64_t now = platform::nowMs();
+ for (auto it = redeliver_.begin(); it != redeliver_.end();) {
+ if (it->first > now) {
+ ++it;
+ continue;
+ }
+ std::vector<uint8_t> packet = std::move(it->second);
+ it = redeliver_.erase(it);
+ accept(packet.data(), packet.size(), now, send);
+ }
+ for (auto& message : messages) {
+ if (message->type == rtc::Message::Control) continue; // RTCP: handled down the chain
+ accept(reinterpret_cast<const uint8_t*>(message->data()), message->size(), now, send);
+ }
+ resendNacks(now, send);
+ drain(now, out, send);
+ if (packets_.size() > kMaxBuffered) { // stuck: start over
+ packets_.clear();
+ missing_.clear();
+ nextSeq_ = -1;
+ askKeyframe(send);
+ }
+ messages.swap(out);
+}
+
+} // namespace xc::stream
diff --git a/src/stream/h264_receiver.h b/src/stream/h264_receiver.h
new file mode 100644
index 0000000..59b2939
--- /dev/null
+++ b/src/stream/h264_receiver.h
@@ -0,0 +1,78 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// H.264 RTP receiver: a small jitter buffer that hands the decoder only
+// complete access units, in order.
+//
+// libdatachannel's H264RtpDepacketizer emits a frame as soon as its marker
+// packet arrives, holes and all; the decoder then smears the damage over every
+// following frame until the next key frame (macroblocks, pink/green blocks).
+// Here a hole is answered with an RTCP NACK (the xCloud server retransmits on
+// the same SSRC), the frame waits briefly for the retransmission, and if it
+// never comes the frame is dropped, a key frame is requested (PLI plus the
+// caller's callback) and nothing is shown until that key frame: a short
+// freeze instead of corruption.
+#pragma once
+
+#include "stream/video_stats.h"
+
+#include <rtc/rtc.hpp>
+
+#include <cstdint>
+#include <functional>
+#include <map>
+#include <vector>
+
+namespace xc::stream {
+
+class H264Receiver final : public rtc::MediaHandler {
+public:
+ // `onKeyframeNeeded` runs on libdatachannel's thread.
+ H264Receiver(std::function<void()> onKeyframeNeeded, VideoReceiveStats& stats);
+
+ void incoming(rtc::message_vector& messages, const rtc::message_callback& send) override;
+
+ // Test hook: hold back this percentage of incoming RTP packets and
+ // deliver each one 30 ms after it is NACKed, like a retransmission (a real
+ // retransmission cannot be tested this way: SRTP drops it as a replay).
+ void setSimulatedLoss(int percent) { simulatedLoss_ = percent; }
+
+private:
+ struct Packet {
+ uint32_t timestamp = 0;
+ bool marker = false;
+ std::vector<uint8_t> payload;
+ };
+ struct Missing {
+ uint64_t sinceMs = 0, lastNackMs = 0;
+ int nacks = 0;
+ };
+
+ void accept(const uint8_t* d, size_t n, uint64_t now, const rtc::message_callback& send);
+ int64_t unwrap(uint16_t seq);
+ void noteGap(int64_t from, int64_t to, uint64_t now, const rtc::message_callback& send);
+ void resendNacks(uint64_t now, const rtc::message_callback& send);
+ void sendNack(const std::vector<int64_t>& seqs, const rtc::message_callback& send);
+ void sendPli(const rtc::message_callback& send);
+ void askKeyframe(const rtc::message_callback& send);
+ // Emits every complete frame from nextSeq_ on; gives up on holes older
+ // than the retransmission wait.
+ void drain(uint64_t now, rtc::message_vector& out, const rtc::message_callback& send);
+ bool resync(rtc::message_vector& out);
+ bool assemble(int64_t first, int64_t last, std::vector<uint8_t>& annexB, bool& keyframe) const;
+
+ std::function<void()> onKeyframeNeeded_;
+ VideoReceiveStats& stats_;
+ std::map<int64_t, Packet> packets_;
+ std::map<int64_t, Missing> missing_;
+ int64_t highest_ = -1; // highest extended sequence number seen
+ int64_t nextSeq_ = -1; // first packet of the next frame to emit; -1 = resync
+ bool waitingKeyframe_ = true;
+ uint32_t mediaSsrc_ = 0;
+ uint64_t lastKeyframeRequestMs_ = 0;
+ int simulatedLoss_ = 0;
+ uint32_t lossState_ = 12345;
+ std::map<uint16_t, std::vector<uint8_t>> held_; // simulated loss
+ std::vector<std::pair<uint64_t, std::vector<uint8_t>>> redeliver_; // (due, packet)
+};
+
+} // namespace xc::stream
diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cpp
index c12fa05..12946e1 100644
--- a/src/stream/stream_session.cpp
+++ b/src/stream/stream_session.cpp
@@ -2,6 +2,8 @@
// Copyright (C) 2026 RafaelNGP
#include "stream/stream_session.h"
+#include "stream/h264_receiver.h"
+
#include "platform/platform.h"
#include "util/json.h"
#include "util/log.h"
@@ -50,6 +52,28 @@ std::vector<std::string> midsInOrder(const std::string& sdp) {
return mids;
}
+// a=imageattr after every a=fmtp line: the largest picture we accept. The
+// xbox.com client adds "recv [x=[0:1920],y=[0:1080],fps=[0:60]]" to limit
+// devices that can't do 1440p; announcing 2560x1440 is what allows 1440p.
+std::string advertiseReceiveSize(const std::string& sdp, int w, int h) {
+ if (sdp.find("a=imageattr") != std::string::npos) return sdp;
+ std::string out;
+ size_t pos = 0;
+ while (pos < sdp.size()) {
+ size_t eol = sdp.find('\n', pos);
+ if (eol == std::string::npos) eol = sdp.size() - 1;
+ std::string line = sdp.substr(pos, eol - pos + 1);
+ out += line;
+ if (line.rfind("a=fmtp:", 0) == 0 && line.find("profile-level-id") != std::string::npos) {
+ std::string pt = line.substr(7, line.find(' ') - 7);
+ out += "a=imageattr:" + pt + " recv [x=[0:" + std::to_string(w) + "],y=[0:" + std::to_string(h) +
+ "],fps=[0:60]]\r\n";
+ }
+ pos = eol + 1;
+ }
+ return out;
+}
+
void initRtcLogging() {
static std::once_flag once;
std::call_once(once, [] {
@@ -100,6 +124,7 @@ struct StreamSession::Impl {
std::chrono::steady_clock::time_point epoch = std::chrono::steady_clock::now();
uint64_t lastKeepaliveMs = 0;
uint64_t lastKeyframeMs = 0;
+ VideoReceiveStats videoStats;
Impl(xcloud::GssvClient& g, StreamCallbacks c, StreamOptions o) : gssv(g), cb(std::move(c)), opt(o) {}
@@ -224,6 +249,13 @@ struct StreamSession::Impl {
sendGamepadChanged(0, true);
sendGamepadChanged(0, false);
sendGamepadChanged(0, true);
+ if (!opt.resolutionAlias.empty()) {
+ json::Value res = json::Value::object();
+ res.set("message", "userRequestedResolutionUpdate");
+ res.set("resolutionAlias", opt.resolutionAlias);
+ sendText(control, res.dump());
+ XC_LOGI("requested stream resolution %s", opt.resolutionAlias.c_str());
+ }
sendBinary(input, clientMetadataReport(0, nowMs()));
sendClientConfig();
@@ -352,13 +384,27 @@ struct StreamSession::Impl {
// Video: H.264 only, Main before Constrained Baseline / Baseline.
rtc::Description::Video v("1", rtc::Description::Direction::RecvOnly);
- v.addH264Codec(102, "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f");
+ // Main profile at level 5.1 (0x33): the level that allows 1440p60; with
+ // 3.1 the service tops out at 1080p (it answers level 4.2).
+ v.addH264Codec(102, "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d0033");
v.addH264Codec(104, "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f");
v.addH264Codec(106, "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f");
video = pc->addTrack(v);
- auto videoDepacketizer = std::make_shared<rtc::H264RtpDepacketizer>();
- videoDepacketizer->addToChain(std::make_shared<rtc::RtcpReceivingSession>());
- video->setMediaHandler(videoDepacketizer);
+ // Our jitter buffer (NACK, whole frames only) in place of
+ // H264RtpDepacketizer, which hands over frames with holes in them.
+ auto videoReceiver = std::make_shared<H264Receiver>(
+ [this] {
+ if (!open) return;
+ try {
+ requestKeyframe();
+ } catch (const std::exception& e) {
+ XC_LOGW("keyframe request: %s", e.what());
+ }
+ },
+ videoStats);
+ videoReceiver->setSimulatedLoss(opt.simulatedVideoLoss);
+ videoReceiver->addToChain(std::make_shared<rtc::RtcpReceivingSession>());
+ video->setMediaHandler(videoReceiver);
video->onFrame([this](rtc::binary data, rtc::FrameInfo info) {
if (cb.video) cb.video(reinterpret_cast<const uint8_t*>(data.data()), data.size(), info.timestamp);
});
@@ -392,6 +438,7 @@ struct StreamSession::Impl {
return false;
}
std::string offer = std::string(*local);
+ if (opt.resolutionAlias == "1440") offer = advertiseReceiveSize(offer, 2560, 1440);
XC_LOGD("local offer:\n%s", offer.c_str());
if (!gssv.sendSdpOffer(offer, err)) return false;
@@ -540,5 +587,6 @@ void StreamSession::requestKeyframe() {
}
void StreamSession::tick() { impl_->tick(); }
void StreamSession::close() { impl_->close(); }
+const VideoReceiveStats& StreamSession::videoStats() const { return impl_->videoStats; }
} // namespace xc::stream
diff --git a/src/stream/stream_session.h b/src/stream/stream_session.h
index df07ef1..ccb66ed 100644
--- a/src/stream/stream_session.h
+++ b/src/stream/stream_session.h
@@ -9,6 +9,7 @@
#pragma once
#include "stream/input_packet.h"
+#include "stream/video_stats.h"
#include "xcloud/gssv.h"
#include <cstdint>
@@ -31,6 +32,14 @@ struct StreamOptions {
// The web client asks for a key frame this often to recover from loss
// without NACK; 0 disables.
int keyframeIntervalSec = 5;
+ // Stream tier requested on the control channel after connecting, as the
+ // xbox.com client does ("userRequestedResolutionUpdate"): "720", "720HQ",
+ // "1080", "1080HQ" or "1440" (the HQ tiers and 1440 need Game Pass
+ // Ultimate). Empty: don't send, the service picks.
+ std::string resolutionAlias;
+ // Test hook: drop this percentage of video RTP packets before the jitter
+ // buffer, to exercise NACK / key frame recovery.
+ int simulatedVideoLoss = 0;
};
// "a=candidate:..." with a Teredo (2001::/32) address -> the IPv4 address and
@@ -54,6 +63,8 @@ public:
// second from the thread that owns the GssvClient.
void tick();
void close();
+ // RTP loss / retransmission counters of the video track.
+ const VideoReceiveStats& videoStats() const;
private:
struct Impl;
diff --git a/src/stream/video_stats.h b/src/stream/video_stats.h
new file mode 100644
index 0000000..990665c
--- /dev/null
+++ b/src/stream/video_stats.h
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Copyright (C) 2026 RafaelNGP
+// Counters of the video RTP receiver (see h264_receiver.h).
+#pragma once
+
+#include <atomic>
+#include <cstdint>
+
+namespace xc::stream {
+
+struct VideoReceiveStats {
+ std::atomic<uint64_t> packets{0};
+ std::atomic<uint64_t> lost{0}; // sequence numbers that went missing
+ std::atomic<uint64_t> recovered{0}; // ...and later arrived (retransmitted)
+ std::atomic<uint64_t> nacks{0}; // NACK packets sent
+ std::atomic<uint64_t> framesOut{0};
+ std::atomic<uint64_t> framesDropped{0}; // incomplete, or waiting for a key frame
+ std::atomic<uint64_t> keyframeRequests{0};
+};
+
+} // namespace xc::stream
diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cpp
index 2f17f67..e901462 100644
--- a/src/ui/app_ui.cpp
+++ b/src/ui/app_ui.cpp
@@ -33,7 +33,9 @@ constexpr Color kGreen = rgba(16, 124, 16);
constexpr Color kPanel = rgba(36, 36, 36);
constexpr Color kPlaceholder = rgba(44, 44, 44);
-enum Icon { kIconCross, kIconCircle, kIconOptions, kIconTriangle };
+enum Icon { kIconCross, kIconCircle, kIconOptions, kIconTriangle, kIconTouchpad };
+
+constexpr uint64_t kSignOutHoldMs = 5000;
} // namespace
@@ -198,7 +200,7 @@ void AppUi::changeSetting(int delta) {
settings_.language = (settings_.language + delta + n) % n;
setLanguage(static_cast<Language>(settings_.language)); // the UI switches right away
} else if (settingsRow_ == 1) {
- settings_.hd = !settings_.hd;
+ settings_.resolution = (settings_.resolution + delta + 3) % 3;
} else {
// Index 0 is automatic, then the regions in the login's order.
int n = static_cast<int>(regions_.size()) + 1;
@@ -248,8 +250,7 @@ UiEvent AppUi::handle(const NavInput& in) {
switch (screen_) {
case Screen::Home: {
if (rows_.empty()) {
- if (in.options) ev.action = Action::SignOut;
- if (in.triangle) {
+ if (in.options) {
screen_ = Screen::Settings;
settingsRow_ = 0;
dirty_ = true;
@@ -271,8 +272,7 @@ UiEvent AppUi::handle(const NavInput& in) {
screen_ = Screen::Details;
dirty_ = true;
}
- if (in.options) ev.action = Action::SignOut;
- if (in.triangle) {
+ if (in.options) {
screen_ = Screen::Settings;
settingsRow_ = 0;
dirty_ = true;
@@ -284,7 +284,7 @@ UiEvent AppUi::handle(const NavInput& in) {
if (in.up && settingsRow_ > 0) --settingsRow_, dirty_ = true;
if (in.right || in.accept) changeSetting(+1);
if (in.left) changeSetting(-1);
- if (in.back || in.triangle) {
+ if (in.back || in.options) {
screen_ = Screen::Home;
dirty_ = true;
ev.action = Action::SettingsChanged;
@@ -306,10 +306,24 @@ UiEvent AppUi::handle(const NavInput& in) {
break;
case Screen::Error:
if (in.accept) ev.action = Action::Retry;
- if (in.options) ev.action = Action::SignOut;
break;
default: break;
}
+ // Sign out: hold TOUCHPAD for 5 s on the home or error screen.
+ bool canSignOut = screen_ == Screen::Home || screen_ == Screen::Error;
+ if (canSignOut && in.touchpad && !signOutLatched_) {
+ if (!signOutHoldStart_) signOutHoldStart_ = in.nowMs ? in.nowMs : 1;
+ if (in.nowMs - signOutHoldStart_ >= kSignOutHoldMs) {
+ ev.action = Action::SignOut;
+ signOutHoldStart_ = 0;
+ signOutLatched_ = true;
+ }
+ dirty_ = true;
+ } else if (!in.touchpad || !canSignOut) {
+ if (signOutHoldStart_) dirty_ = true;
+ signOutHoldStart_ = 0;
+ if (!in.touchpad) signOutLatched_ = false;
+ }
return ev;
}
@@ -363,7 +377,12 @@ void AppUi::drawHints(Canvas& c, const std::vector<std::pair<int, const char*>>&
fonts_.semibold.draw(c, it->second, x, y, kPx, kGray);
x -= 10 + 2 * kR;
float cx = x + kR, cy = y + 13;
- if (it->first == kIconOptions) {
+ if (it->first == kIconTouchpad) {
+ Rect pad{x - 18, static_cast<int>(cy) - 10, 2 * kR + 12, 20};
+ c.fillRect(pad, rgba(255, 255, 255, 40), 6);
+ c.strokeRect(pad, kGray, 2, 6);
+ x -= 10;
+ } else if (it->first == kIconOptions) {
c.fillRect({x - 4, static_cast<int>(cy) - 11, 2 * kR + 8, 22}, rgba(255, 255, 255, 40), 11);
for (int k = -1; k <= 1; ++k) c.line(cx - 8, cy + k * 5, cx + 8, cy + k * 5, 2, kGray);
} else {
@@ -493,7 +512,7 @@ void AppUi::drawHome(Canvas& c, uint64_t nowMs) {
if (rows_.empty()) {
drawCentered(c, fonts_.semibold, tr(Str::NoGames), 500, 32, kGray);
- drawHints(c, {{kIconOptions, tr(Str::SignOut)}});
+ drawHints(c, {{kIconOptions, tr(Str::Settings)}, {kIconTouchpad, tr(Str::HoldSignOut)}});
return;
}
@@ -544,7 +563,7 @@ void AppUi::drawHome(Canvas& c, uint64_t nowMs) {
// Fade the rows out under the button hints.
c.gradientV({0, kH - 190, kW, 110}, withAlpha(kBg, 0), withAlpha(kBg, 245));
c.fillRect({0, kH - 80, kW, 80}, withAlpha(kBg, 245));
- drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconTriangle, tr(Str::Settings)}, {kIconOptions, tr(Str::SignOut)}});
+ drawHints(c, {{kIconCross, tr(Str::Select)}, {kIconOptions, tr(Str::Settings)}, {kIconTouchpad, tr(Str::HoldSignOut)}});
drawToast(c, nowMs);
}
@@ -611,7 +630,7 @@ void AppUi::drawError(Canvas& c) {
fonts_.regular.draw(c, line, panel.x + 56, y, 26, kGray);
y += 38;
}
- drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconOptions, tr(Str::SignOut)}});
+ drawHints(c, {{kIconCross, tr(Str::TryAgain)}, {kIconTouchpad, tr(Str::HoldSignOut)}});
}
void AppUi::drawSettings(Canvas& c) {
@@ -626,7 +645,9 @@ void AppUi::drawSettings(Canvas& c) {
? trf(Str::RegionAuto, defaultRegion_.empty() ? "-" : prettyRegion(defaultRegion_))
: prettyRegion(settings_.region);
const Row rows[] = {{tr(Str::Language), languageName(static_cast<Language>(settings_.language))},
- {tr(Str::Resolution), tr(settings_.hd ? Str::Res1080 : Str::Res720)},
+ {tr(Str::Resolution), tr(settings_.resolution == 1 ? Str::Res720
+ : settings_.resolution == 2 ? Str::Res1440
+ : Str::Res1080)},
{tr(Str::Region), region}};
constexpr int kRowW = 1200, kRowH = 92;
int y = 290;
@@ -648,6 +669,26 @@ void AppUi::drawSettings(Canvas& c) {
drawHints(c, {{kIconCross, tr(Str::Change)}, {kIconCircle, tr(Str::Back)}});
}
+void AppUi::drawSignOutHold(Canvas& c, uint64_t nowMs) {
+ if (!signOutHoldStart_) return;
+ float progress = std::min(1.0f, static_cast<float>(nowMs - signOutHoldStart_) / kSignOutHoldMs);
+ int secondsLeft = static_cast<int>((kSignOutHoldMs - std::min<uint64_t>(kSignOutHoldMs, nowMs - signOutHoldStart_) + 999) / 1000);
+ std::string text = trf(Str::SigningOutIn, std::to_string(secondsLeft));
+ int tw = fonts_.semibold.measure(text, 28);
+ Rect panel{(kW - (tw + 170)) / 2, kH - 250, tw + 170, 110};
+ c.fillRect(panel, rgba(30, 30, 30, 240), 55);
+ c.strokeRect(panel, rgba(255, 255, 255, 60), 2, 55);
+ float cx = panel.x + 62, cy = panel.y + panel.h / 2.0f;
+ c.strokeArc(cx, cy, 30, 6, 0, 6.2832f, rgba(255, 255, 255, 50));
+ // Progress ring from 12 o'clock, clockwise, in red as it nears the end.
+ Color ring = progress < 0.8f ? kWhite : rgba(255, 110, 110);
+ if (progress > 0.01f) c.strokeArc(cx, cy, 30, 6, -1.5708f, 6.2832f * progress, ring);
+ fonts_.bold.draw(c, std::to_string(secondsLeft), static_cast<int>(cx) - fonts_.bold.measure(std::to_string(secondsLeft), 26) / 2,
+ static_cast<int>(cy) - 16, 26, kWhite);
+ fonts_.semibold.draw(c, text, panel.x + 120, panel.y + 38, 28, kWhite);
+ animating_ = true;
+}
+
void AppUi::render(Canvas& c, uint64_t nowMs) {
std::lock_guard<std::mutex> lock(mutex_);
float dt = lastRender_ ? std::min(0.1f, (nowMs - lastRender_) / 1000.0f) : 0.0f;
@@ -665,6 +706,7 @@ void AppUi::render(Canvas& c, uint64_t nowMs) {
case Screen::Settings: drawSettings(c); break;
case Screen::Streaming: break;
}
+ if (screen_ == Screen::Home || screen_ == Screen::Error) drawSignOutHold(c, nowMs);
if (!toast_.empty()) animating_ = true; // to expire it
}
diff --git a/src/ui/app_ui.h b/src/ui/app_ui.h
index 49512d9..2645e2c 100644
--- a/src/ui/app_ui.h
+++ b/src/ui/app_ui.h
@@ -40,13 +40,15 @@ enum class Screen { Splash, SignIn, Home, Details, Launching, Streaming, Error,
struct NavInput {
bool up = false, down = false, left = false, right = false;
- bool accept = false, back = false, options = false, triangle = false;
+ bool accept = false, back = false, options = false;
+ bool touchpad = false; // held right now (sign out needs a 5 s hold)
+ uint64_t nowMs = 0;
};
// What the Settings screen edits.
struct SettingsChoice {
int language = 0; // ui::Language
- bool hd = true; // 1080p (else 720p)
+ int resolution = 0; // 0 = 1080p, 1 = 720p, 2 = 1440p (experimental)
std::string region; // gssv region name; empty = automatic
};
@@ -133,6 +135,9 @@ private:
std::vector<std::string> regions_;
std::string defaultRegion_;
int settingsRow_ = 0;
+ uint64_t signOutHoldStart_ = 0; // TOUCHPAD hold in progress
+ bool signOutLatched_ = false; // fired; wait for release
+ void drawSignOutHold(Canvas& c, uint64_t nowMs);
std::string toast_;
uint64_t toastUntil_ = 0;
std::string heroUrl_, prevHeroUrl_;
diff --git a/src/ui/strings.cpp b/src/ui/strings.cpp
index 36cdc5b..ade3b14 100644
--- a/src/ui/strings.cpp
+++ b/src/ui/strings.cpp
@@ -67,8 +67,11 @@ constexpr Column kEnglish = {
"Automatic (%s)", // RegionAuto
"1080p (Full HD)", // Res1080
"720p (uses less data)", // Res720
+ "1440p (experimental, where available)", // Res1440
"Resolution and region apply to the next game you start.", // SettingsNote
"Change", // Change
+ "Hold to sign out", // HoldSignOut
+ "Keep holding to sign out (%s)", // SigningOutIn
"Sign-in failed: %s", // SignInFailed
"Could not load the game list: %s", // LibraryFailed
"Could not start the stream: %s", // StreamFailed
@@ -109,8 +112,11 @@ constexpr Column kPortugueseBR = {
"Automática (%s)",
"1080p (Full HD)",
"720p (usa menos dados)",
+ "1440p (experimental, onde disponível)",
"A resolução e a região valem a partir do próximo jogo.",
"Alterar",
+ "Segure para sair da conta",
+ "Continue segurando para sair da conta (%s)",
"Falha ao entrar: %s",
"Não foi possível carregar a lista de jogos: %s",
"Não foi possível iniciar o streaming: %s",
@@ -151,8 +157,11 @@ constexpr Column kSpanish = {
"Automática (%s)",
"1080p (Full HD)",
"720p (usa menos datos)",
+ "1440p (experimental, donde esté disponible)",
"La resolución y la región se aplican al próximo juego que inicies.",
"Cambiar",
+ "Mantén para cerrar sesión",
+ "Sigue manteniendo para cerrar sesión (%s)",
"Error al iniciar sesión: %s",
"No se pudo cargar la lista de juegos: %s",
"No se pudo iniciar el streaming: %s",
@@ -193,8 +202,11 @@ constexpr Column kFrench = {
"Automatique (%s)",
"1080p (Full HD)",
"720p (consomme moins de données)",
+ "1440p (expérimental, si disponible)",
"La résolution et la région s'appliquent au prochain jeu lancé.",
"Modifier",
+ "Maintenez pour vous déconnecter",
+ "Continuez à maintenir pour vous déconnecter (%s)",
"Échec de la connexion : %s",
"Impossible de charger la liste des jeux : %s",
"Impossible de démarrer le streaming : %s",
@@ -235,8 +247,11 @@ constexpr Column kGerman = {
"Automatisch (%s)",
"1080p (Full HD)",
"720p (verbraucht weniger Daten)",
+ "1440p (experimentell, wo verfügbar)",
"Auflösung und Region gelten ab dem nächsten gestarteten Spiel.",
"Ändern",
+ "Halten zum Abmelden",
+ "Weiter halten zum Abmelden (%s)",
"Anmeldung fehlgeschlagen: %s",
"Die Spieleliste konnte nicht geladen werden: %s",
"Das Streaming konnte nicht gestartet werden: %s",
@@ -277,8 +292,11 @@ constexpr Column kItalian = {
"Automatica (%s)",
"1080p (Full HD)",
"720p (usa meno dati)",
+ "1440p (sperimentale, dove disponibile)",
"Risoluzione e regione valgono dal prossimo gioco avviato.",
"Cambia",
+ "Tieni premuto per uscire",
+ "Continua a tenere premuto per uscire (%s)",
"Accesso non riuscito: %s",
"Impossibile caricare l'elenco dei giochi: %s",
"Impossibile avviare lo streaming: %s",
diff --git a/src/ui/strings.h b/src/ui/strings.h
index 12c1751..3f698cd 100644
--- a/src/ui/strings.h
+++ b/src/ui/strings.h
@@ -44,8 +44,11 @@ enum class Str {
RegionAuto, // "%s" = the account's default region
Res1080,
Res720,
+ Res1440,
SettingsNote,
Change,
+ HoldSignOut,
+ SigningOutIn, // "%s" = seconds left
SignInFailed, // "%s" = technical detail
LibraryFailed, // "%s" = technical detail
StreamFailed, // "%s" = technical detail
diff --git a/src/xcloud/gssv.cpp b/src/xcloud/gssv.cpp
index 229b41c..171da6d 100644
--- a/src/xcloud/gssv.cpp
+++ b/src/xcloud/gssv.cpp
@@ -7,6 +7,7 @@
#include "util/json.h"
#include "util/log.h"
+#include <cstdlib>
#include <ctime>
#include <map>
@@ -18,7 +19,7 @@ constexpr const char* kClientHeader = "XboxComBrowser";
// Sent like the Windows Xbox app does: "Windows" plus a 1080p display is what
// gets a 1080p stream; an Android device with a 720p display gets 720p.
const std::string& deviceInfo(Resolution res) {
- auto build = [](bool hd) {
+ auto build = [](bool hd, int w = 1920, int h = 1080) {
json::Value env = json::Value::object();
env.set("clientAppId", "Microsoft.GamingApp");
env.set("clientAppType", "native");
@@ -37,8 +38,8 @@ const std::string& deviceInfo(Resolution res) {
os.set("ver", hd ? "22631.2715" : "14");
os.set("platform", hd ? "desktop" : "phone");
json::Value dims = json::Value::object();
- dims.set("widthInPixels", hd ? 1920 : 1280);
- dims.set("heightInPixels", hd ? 1080 : 720);
+ dims.set("widthInPixels", hd ? w : 1280);
+ dims.set("heightInPixels", hd ? h : 720);
json::Value dpi = json::Value::object();
dpi.set("dpiX", 1);
dpi.set("dpiY", 1);
@@ -54,8 +55,51 @@ const std::string& deviceInfo(Resolution res) {
v.set("dev", dev);
return v.dump();
};
+ // 1440p: the xbox.com web client (SDK 10.6.62) in Edge on a 1440p display,
+ // field for field as its X-MS-Device-Info interceptor builds it.
+ static const std::string qhd = [] {
+ json::Value env = json::Value::object();
+ env.set("clientAppId", "www.xbox.com");
+ env.set("clientAppType", "browser");
+ env.set("clientAppVersion", "1.0.2609.0802");
+ env.set("clientSdkVersion", "10.6.62");
+ env.set("httpEnvironment", "prod");
+ env.set("sdkInstallId", "");
+ json::Value app = json::Value::object();
+ app.set("env", env);
+ json::Value dims = json::Value::object();
+ dims.set("heightInPixels", 1440);
+ dims.set("widthInPixels", 2560);
+ json::Value dpi = json::Value::object();
+ dpi.set("dpiX", 1);
+ dpi.set("dpiY", 1);
+ json::Value display = json::Value::object();
+ display.set("dimensions", dims);
+ display.set("pixelDensity", dpi);
+ json::Value browser = json::Value::object();
+ browser.set("browserName", "edge");
+ browser.set("browserVersion", "141.0.0.0");
+ json::Value hw = json::Value::object();
+ hw.set("make", "Microsoft");
+ hw.set("model", "Windows");
+ hw.set("platformType", "desktop");
+ hw.set("sdkType", "web");
+ json::Value os = json::Value::object();
+ os.set("name", "windows");
+ os.set("ver", "10.0");
+ os.set("platform", "desktop");
+ json::Value dev = json::Value::object();
+ dev.set("displayInfo", display);
+ dev.set("browser", browser);
+ dev.set("hw", hw);
+ dev.set("os", os);
+ json::Value v = json::Value::object();
+ v.set("appInfo", app);
+ v.set("dev", dev);
+ return v.dump();
+ }();
static const std::string hd = build(true), sd = build(false);
- return res == Resolution::P720 ? sd : hd;
+ return res == Resolution::P720 ? sd : res == Resolution::P1440 ? qhd : hd;
}
std::string describe(const net::Response& r) {
@@ -139,6 +183,12 @@ bool GssvClient::login(const auth::XblToken& gssvXsts, std::string& err) {
if (r.status == 403) err += " (no Game Pass Ultimate, or xCloud is not available in this region)";
return false;
}
+ if (std::getenv("XC_DUMP_LOGIN")) {
+ // Diagnostics: everything except the token itself.
+ json::Value copy = *j;
+ copy.set("gsToken", "<redacted>");
+ XC_LOGI("login response: %s", copy.dump().substr(0, 6000).c_str());
+ }
login_ = {};
login_.gsToken = (*j)["gsToken"].str();
login_.market = (*j)["market"].str();
diff --git a/src/xcloud/gssv.h b/src/xcloud/gssv.h
index 5496090..7467b66 100644
--- a/src/xcloud/gssv.h
+++ b/src/xcloud/gssv.h
@@ -55,7 +55,7 @@ struct IceCandidate {
// Stream resolution the service is asked for. It decides from the device the
// client claims to be: a Windows desktop gets 1080p, other devices 720p.
-enum class Resolution { P1080, P720 };
+enum class Resolution { P1080, P720, P1440 };
class GssvClient {
public: