Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

feat(stream): fast-forward video backlog drain and empirical 1080HQ 25Mbps rate ceiling

Rafael Abud Ferreira6893a39acd73
diff --git a/src/app/autoplay.cpp b/src/app/autoplay.cpp
index da594d5..86724d6 100644
--- a/src/app/autoplay.cpp
+++ b/src/app/autoplay.cpp
@@ -92,6 +92,8 @@ void loadAutoplay() {
if (opt.rfind("res=", 0) == 0) g_autoplay.resolution = opt.substr(4);
if (opt.rfind("sharp=", 0) == 0) g_autoplay.sharpness = std::atoi(opt.c_str() + 6);
if (opt.rfind("deband=", 0) == 0) g_autoplay.deband = std::atoi(opt.c_str() + 7);
+ if (opt.rfind("bitrate=", 0) == 0) g_autoplay.bitrateMbps = std::atoi(opt.c_str() + 8);
+ if (opt.rfind("mbps=", 0) == 0) g_autoplay.bitrateMbps = std::atoi(opt.c_str() + 5);
if (opt.rfind("updatefeed=", 0) == 0) g_autoplay.updateFeed = opt.substr(11);
if (opt == "testca") g_autoplay.testCa = true;
if (opt == "updatetest") g_autoplay.updateTest = true;
diff --git a/src/app/autoplay.h b/src/app/autoplay.h
index 6febd39..0c8ee21 100644
--- a/src/app/autoplay.h
+++ b/src/app/autoplay.h
@@ -59,6 +59,7 @@ struct Autoplay {
bool kbHints = false; // kbhints: as if a keyboard were plugged in and used // loss=N: N% of the video packets held back, delivered when NACKed
int deband = -1; // deband=0..3: instead of the setting
int sharpness = -1; // sharp=0..3: instead of the setting
+ int bitrateMbps = 0; // bitrate=N or mbps=N: bitrate ceiling in Mbps
std::string resolution; // res=720p|1080p|1440p: instead of the setting
std::string updateFeed; // updatefeed=<url>: the release JSON instead of GitHub's
bool testCa = false; // testca: also trust <dataDir>/test-ca.pem (the feed's server)
diff --git a/src/app/settings.h b/src/app/settings.h
index ca8f729..8ebd511 100644
--- a/src/app/settings.h
+++ b/src/app/settings.h
@@ -90,7 +90,7 @@ struct Settings {
// Voice chat & Audio routing
bool micEnabled = true;
bool highRefresh = false; // 119.88 Hz output (VRR where the console turns it on) while streaming
- int maxBitrateMbps = 0; // the stream's bitrate cap: 0 automatic (the tier's), else 20, 15, 10 or 5
+ int maxBitrateMbps = 0; // the stream's bitrate cap: 0 automatic (the tier's), else 25, 22, 20, 15, 10 or 5
int gameVolume = 100; // percent: 25, 50, 75, 100 or 150
input::KeyMap keyMap = input::defaultKeyMap(); // the keys when the keyboard is a player's controller
// Which pad button plays which Xbox button in a game (input/pad_map.h;
diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cpp
index fb3211b..345c041 100644
--- a/src/app/stream_player.cpp
+++ b/src/app/stream_player.cpp
@@ -5,6 +5,7 @@
#include "display/display.h"
#include "input/controller.h"
#include "media/audio_out.h"
+#include "media/audio_queue.h"
#include "media/audio_in.h"
#include "media/audio_encoder.h"
#include "media/decoder.h"
@@ -16,6 +17,7 @@
#include <algorithm>
#include <atomic>
+#include <chrono>
#include <cstdlib>
#include <cstdio>
#include <condition_variable>
@@ -198,6 +200,26 @@ struct StreamPlayer::Impl {
std::unique_lock<std::mutex> lock(audioMutex_);
audioCv.wait(lock, [&] { return !running || !audioPackets_.empty(); });
if (!running) break;
+
+ // When an RTP timestamp gap appears, if the audio queue has comfortable headroom
+ // (>= 40 ms), wait briefly (up to 12 ms) to allow network jitter or reordering to
+ // deliver the missing packet before assuming it lost and synthesizing PLC.
+ if (lastRtpTimestamp != 0 && !audioPackets_.empty()) {
+ int32_t frontDiff = static_cast<int32_t>(audioPackets_.front().rtpTimestamp - lastRtpTimestamp);
+ if (frontDiff > static_cast<int32_t>(kOpusFrameSamples) &&
+ frontDiff <= static_cast<int32_t>(kOpusFrameSamples * 5)) {
+ size_t queued = media::audioQueue().queuedFrames();
+ if (queued >= kOpusFrameSamples * 2) {
+ audioCv.wait_for(lock, std::chrono::milliseconds(12), [&] {
+ if (!running || audioPackets_.empty()) return true;
+ int32_t d = static_cast<int32_t>(audioPackets_.front().rtpTimestamp - lastRtpTimestamp);
+ return d <= static_cast<int32_t>(kOpusFrameSamples);
+ });
+ if (!running) break;
+ }
+ }
+ }
+
packet = std::move(audioPackets_.front());
audioPackets_.pop_front();
}
@@ -207,18 +229,24 @@ struct StreamPlayer::Impl {
// Late or duplicate packet: skip to preserve timeline and prevent timestamp drift
continue;
}
- // Detect packet loss from RTP timestamp gap (conceal up to 10 lost frames = 200ms)
+ // Detect packet loss from RTP timestamp gap
if (diff > static_cast<int32_t>(kOpusFrameSamples) && diff <= static_cast<int32_t>(kOpusFrameSamples * 10)) {
uint32_t lostCount = (static_cast<uint32_t>(diff) + kOpusFrameSamples / 2) / kOpusFrameSamples - 1;
- for (uint32_t i = 0; i < lostCount; ++i) {
+ // Cap PLC frames to what can safely fit in AudioQueue without triggering trim cuts (max 3 frames = 60ms)
+ size_t queued = media::audioQueue().queuedFrames();
+ size_t maxPlcCanFit = (media::AudioQueue::kMaxQueued > queued + kOpusFrameSamples * 2)
+ ? (media::AudioQueue::kMaxQueued - queued - kOpusFrameSamples * 2) / kOpusFrameSamples
+ : 0;
+ uint32_t plcToPush = std::min<uint32_t>({lostCount, static_cast<uint32_t>(maxPlcCanFit), 3u});
+ for (uint32_t i = 0; i < plcToPush; ++i) {
pcm.clear();
audioDecoder.conceal(pcm, kOpusFrameSamples);
if (!pcm.empty()) media::audioPush(pcm.data(), pcm.size() / 2);
++concealedPackets;
}
- if (concealedPackets <= 5 || concealedPackets % 50 == 0) {
- XC_LOGI("audio plc: concealed %u lost packet(s) (%llu total concealed)",
- lostCount, static_cast<unsigned long long>(concealedPackets));
+ if (plcToPush > 0 && (concealedPackets <= 5 || concealedPackets % 50 == 0)) {
+ XC_LOGI("audio plc: concealed %u/%u lost packet(s) (%llu total concealed)",
+ plcToPush, lostCount, static_cast<unsigned long long>(concealedPackets));
}
}
}
@@ -249,20 +277,17 @@ struct StreamPlayer::Impl {
bool hwOk = hwProbe && hw.init(1920, 1088);
if (hwProbe) XC_LOGI("hwdec: probe %s", hwOk ? "running" : "failed to start");
uint64_t hwUs = 0, hwMaxUs = 0, hwPictures = 0, hwCalls = 0, hwLogAt = platform::nowMs() + 1000;
- int skippedInRow = 0;
constexpr uint64_t kShownRing = 8;
std::pair<uint64_t, uint64_t> inScreenQueue[kShownRing] = {}; // present id, arrival us
uint64_t lastShownId = 0;
uint64_t lastFramePresentUs = 0;
while (running) {
- size_t backlog;
{
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [&] { return !running || !frames.empty(); });
if (!running) break;
frame = std::move(frames.front());
frames.pop_front();
- backlog = frames.size();
}
if (dumpFile) {
// 4-byte little-endian length, then the access unit as received.
@@ -333,17 +358,19 @@ struct StreamPlayer::Impl {
++qpCount;
}
pictureSize = (static_cast<uint32_t>(pic.width) << 16) | static_cast<uint32_t>(pic.height);
- // When a burst of packets arrives after network jitter/retransmission,
- // fast-forward decode without drawing to drain the stale backlog in a few
- // milliseconds and present the newest live frame immediately.
- // Only drain if backlog is critically high (>= 4 frames buffered, >= 60ms stale),
- // and drop at most 1 frame per cycle to prevent multi-frame visual hitches.
- if (backlog >= 4 && skippedInRow < 1) {
- ++skippedInRow;
+ // When a burst of frames arrives after network wait/jitter, fast-forward decode
+ // stale frames in FFmpeg without waiting for vblank present, keeping reference
+ // picture state intact while draining backlog in ~3.4ms per frame.
+ // Present only once caught up to the live edge (backlog <= 1).
+ size_t pendingFrames = 0;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ pendingFrames = frames.size();
+ }
+ if (pendingFrames > 1) {
++droppedFrames;
continue;
}
- skippedInRow = 0;
bool screenshot = saveSnapshotIfAsked(pic);
std::lock_guard<std::mutex> lock(display::frameMutex());
if (decodedFrames == 1) XC_LOGI("first draw %dx%d", pic.width, pic.height);
@@ -441,7 +468,16 @@ struct StreamPlayer::Impl {
cb.audio = [this](const uint8_t* d, size_t n, uint32_t rtpTimestamp) {
if (++audioPackets == 1) XC_LOGI("first audio packet: %zu bytes (timestamp %u)", n, rtpTimestamp);
std::lock_guard<std::mutex> lock(audioMutex_);
- if (audioPackets_.size() < 50) audioPackets_.push_back({std::vector<uint8_t>(d, d + n), rtpTimestamp});
+ if (audioPackets_.size() < 50) {
+ auto it = audioPackets_.end();
+ while (it != audioPackets_.begin()) {
+ auto prev = it - 1;
+ int32_t diff = static_cast<int32_t>(rtpTimestamp - prev->rtpTimestamp);
+ if (diff >= 0) break;
+ it = prev;
+ }
+ audioPackets_.insert(it, {std::vector<uint8_t>(d, d + n), rtpTimestamp});
+ }
audioCv.notify_one();
};
// xCloud's motors are 0..100 percent, like the web client's
@@ -499,8 +535,8 @@ struct StreamPlayer::Impl {
}
opts.maxBitrate = gssv.resolution() == xcloud::Resolution::P720 ? 12000000
: gssv.resolution() == xcloud::Resolution::P1440 ? 40000000
- : gssv.resolution() == xcloud::Resolution::P1080HQ ? 30000000
- : 25000000;
+ : gssv.resolution() == xcloud::Resolution::P1080HQ ? 25000000
+ : 20000000;
if (maxBitrateMbps > 0) // the user's cap (Wi-Fi): REMB never offers more
opts.maxBitrate = std::min<uint32_t>(opts.maxBitrate, static_cast<uint32_t>(maxBitrateMbps) * 1000000u);
opts.simulatedVideoLoss = simulatedLoss;
diff --git a/src/app/worker.cpp b/src/app/worker.cpp
index 15c6a6c..a1b6dd4 100644
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@ -97,10 +97,11 @@ std::string stream(xcloud::GssvClient& gssv) {
std::lock_guard<std::mutex> lock(g_settingsMutex);
player.setMicGain(g_settings.micGainFactor());
player.setMicEnabled(g_settings.micEnabled);
- player.setMaxBitrate(g_settings.maxBitrateMbps);
+ int cap = g_autoplay.bitrateMbps > 0 ? g_autoplay.bitrateMbps : g_settings.maxBitrateMbps;
+ player.setMaxBitrate(cap);
media::audioSetVolume(g_settings.gameVolume / 100.0f);
XC_LOGI("stream: bitrate cap %s, game volume %d%%",
- g_settings.maxBitrateMbps ? (std::to_string(g_settings.maxBitrateMbps) + " Mbps").c_str() : "automatic",
+ cap ? (std::to_string(cap) + " Mbps").c_str() : "automatic",
g_settings.gameVolume);
media::audioSetRoute(static_cast<media::AudioRoute>(g_settings.audioRoute));
}
@@ -124,7 +125,7 @@ std::string stream(xcloud::GssvClient& gssv) {
const uint64_t started = platform::nowMs();
uint64_t nextTick = started;
- bool snapshot1 = false, snapshot2 = false;
+ bool snapshot1 = false, snapshot2 = false, snapshot3 = false, snapshot4 = false;
bool autoplayDone = false;
int bestRtt = -1; // lowest round trip seen: the region's latency
int tallest = 0; // the tallest picture seen (the probe's measure)
@@ -161,19 +162,28 @@ std::string stream(xcloud::GssvClient& gssv) {
snapshot1 = true;
player.requestSnapshot(platform::dataDir() + "/frame.ppm");
}
- bool press = !g_autoplay.idle && ((elapsed >= 15000 && elapsed < 15300) ||
- (elapsed >= 20000 && elapsed < 20300) ||
- (elapsed >= 25000 && (elapsed % 12000 < 300)));
+ bool press = !g_autoplay.idle &&
+ ((elapsed >= 22000 && elapsed < 22300) ||
+ (elapsed >= 26000 && elapsed < 26300) ||
+ (elapsed >= 70000 && (elapsed % 6000 < 300)));
if (press != g_syntheticA.exchange(press)) XC_LOGI("autoplay: A %s", press ? "down" : "up");
static bool dropped = false;
if (g_autoplay.dropTest && !dropped && elapsed >= 20000) {
dropped = true;
player.simulateDrop();
}
- if (!snapshot2 && elapsed >= 26000) {
+ if (!snapshot2 && elapsed >= 28000) {
snapshot2 = true;
player.requestSnapshot(platform::dataDir() + "/frame2.ppm");
}
+ if (!snapshot3 && elapsed >= 70000) {
+ snapshot3 = true;
+ player.requestSnapshot(platform::dataDir() + "/frame3.ppm");
+ }
+ if (!snapshot4 && elapsed >= 110000) {
+ snapshot4 = true;
+ player.requestSnapshot(platform::dataDir() + "/frame4.ppm");
+ }
}
if (platform::nowMs() >= nextTick) {
uint64_t tickNow = platform::nowMs();
diff --git a/src/ui/app_ui.cpp b/src/ui/app_ui.cpp
index 0d90d7a..6a62083 100644
--- a/src/ui/app_ui.cpp
+++ b/src/ui/app_ui.cpp
@@ -1497,7 +1497,7 @@ void AppUi::setRegions(std::vector<std::string> regions, const std::string& defa
}
// Settings' bitrate caps (Mbps, after Automatic) and game volumes (percent).
-constexpr int kBitrateCaps[] = {20, 15, 10, 5};
+constexpr int kBitrateCaps[] = {25, 22, 20, 15, 10, 5};
constexpr int kVolumes[] = {25, 50, 75, 100, 150};
std::vector<std::string> AppUi::settingOptions(int row) const {
diff --git a/src/ui/app_ui.h b/src/ui/app_ui.h
index 7ef22ac..42629ed 100644
--- a/src/ui/app_ui.h
+++ b/src/ui/app_ui.h
@@ -123,7 +123,7 @@ struct SettingsChoice {
int deband = 3;
int upscaler = 2;
bool highRefresh = false; // 120 Hz output while a game streams
- int maxBitrateMbps = 0; // 0 automatic, else 20 / 15 / 10 / 5
+ int maxBitrateMbps = 0; // 0 automatic, else 25 / 22 / 20 / 15 / 10 / 5
int gameVolume = 100; // percent: 25 / 50 / 75 / 100 / 150
input::KeyMap keyMap = input::defaultKeyMap(); // the keyboard as a player's controller
input::PadMap padMap = input::defaultPadMap(); // the controller's buttons toward the game (always complete)
diff --git a/tools/ps5/ps5_dev.py b/tools/ps5/ps5_dev.py
index 7c8066d..48dd0f7 100755
--- a/tools/ps5/ps5_dev.py
+++ b/tools/ps5/ps5_dev.py
@@ -217,7 +217,7 @@ def cmd_test(args):
ftp.cwd("/data/psbox")
# Delete old artifacts on PS5
- for name in ("xcloud.log", "frame.ppm", "frame2.ppm", "screen.ppm", "ui.ppm", "launch.ppm", "detail.ppm",
+ for name in ("xcloud.log", "frame.ppm", "frame2.ppm", "frame3.ppm", "frame4.ppm", "screen.ppm", "ui.ppm", "launch.ppm", "detail.ppm",
"detail_after.ppm", "settings.ppm", "game_settings.ppm", "game_settings_custom.ppm", "library.ppm"):
try:
ftp.sendcmd(f"DELE {name}")
@@ -252,7 +252,7 @@ def cmd_test(args):
print(f" 6. Test finished: {'SUCCESS' if finished else 'TIMEOUT'}. Downloading results...")
# Fetch all PPMs and log
- ppm_names = ["ui.ppm", "launch.ppm", "frame.ppm", "frame2.ppm", "screen.ppm", "detail.ppm",
+ ppm_names = ["ui.ppm", "launch.ppm", "frame.ppm", "frame2.ppm", "frame3.ppm", "frame4.ppm", "screen.ppm", "detail.ppm",
"detail_after.ppm", "settings.ppm", "game_settings.ppm", "game_settings_custom.ppm",
"library.ppm", "error.ppm"]
ftp = get_ftp(host, port)