Xbox Cloud Gaming app for PS5 Homebrew
C
v0.2.0: proper RTCP feedback, triple buffering, working rumble
Rafael Abud Ferreiracf7f2f6d78a5
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 34a8970..38b6b05 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -1,7 +1,7 @@# SPDX-License-Identifier: GPL-3.0-or-later# Copyright (C) 2026 RafaelNGPcmake_minimum_required(VERSION 3.20)-project(xcloud_ps5 VERSION 0.1.0 LANGUAGES C CXX)+project(xcloud_ps5 VERSION 0.2.0 LANGUAGES C CXX)set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)@@ -40,6 +40,7 @@ include(cmake/deps/libdatachannel.cmake)add_library(xcloud_stream STATICsrc/stream/h264_receiver.cppsrc/stream/input_packet.cpp+ src/stream/rtcp_reporter.cppsrc/stream/stream_session.cpp)target_link_libraries(xcloud_stream PUBLIC xcloud_core PRIVATE datachannel-static)diff --git a/ps5/sce_sys/param.json b/ps5/sce_sys/param.jsonindex 1530da4..10dd1a7 100644--- a/ps5/sce_sys/param.json+++ b/ps5/sce_sys/param.json@@ -10,7 +10,7 @@"conceptId": "99810","contentBadgeType": 1,"contentId": "UP9000-PPSA99810_00-XCLOUDPS5CLI0000",- "contentVersion": "00.100.000",+ "contentVersion": "00.200.000","downloadDataSize": 256,"gameIntent": {"permittedIntents": [diff --git a/src/app/cli_main.cpp b/src/app/cli_main.cppindex 0b49598..8214711 100644--- a/src/app/cli_main.cpp+++ b/src/app/cli_main.cpp@@ -187,7 +187,7 @@ int cmdStream(auth::AuthManager& am, const std::string& titleId, int seconds, coif (audioDecoder.decode(d, n, pcm)) audioSamples += pcm.size() / 2;};cb.vibration = [](const stream::Vibration& v) {- XC_LOGD("rumble %u/%u for %ums", v.leftMotor, v.rightMotor, v.durationMs);+ XC_LOGI("rumble %u/%u for %ums", v.leftMotor, v.rightMotor, v.durationMs);};cb.closed = [&](const std::string&) { closed = true; };@@ -209,7 +209,7 @@ int cmdStream(auth::AuthManager& am, const std::string& titleId, int seconds, cosession.tick();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",+ "rtp %llu pkts, %llu lost, %llu recovered, %llu nacks, %llu dropped, %llu kf req, %u kbps (remb %u)\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()),@@ -219,7 +219,8 @@ int cmdStream(auth::AuthManager& am, const std::string& titleId, int seconds, costatic_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()));+ static_cast<unsigned long long>(rtp.keyframeRequests.load()),+ rtp.receiveRate.load() / 1000, rtp.estimate.load() / 1000);std::fflush(stdout);}platform::sleepMs(16);diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex c99dc5c..3e2208f 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -68,13 +68,17 @@ app::StreamPlayer* g_player = nullptr;// --- Unattended test mode (tools/ps5/autotest.sh) ----------------------------// <dataDir>/autoplay.txt holds "<titleId> <seconds> [option]". The app signs// in, plays that title for that long (pressing A at 15 s and 20 s), saves-// decoded frames and logs "AUTOPLAY END". Options: nosimd, dump, repeat.+// decoded frames and logs "AUTOPLAY END". Options, comma-separated: nosimd,+// dump, repeat, idle (no A presses), threads=N (H.264 decoder threads),+// rumbletest (rumbles the pad for 1.5 s at start).// The title "BENCH" decodes <dataDir>/sample.h264 instead.std::string g_autoplayTitle;int g_autoplaySeconds = 0;bool g_autoplayDump = false;int g_autoplayRuns = 1;+bool g_autoplayIdle = false;+int g_decodeThreads = 1;std::atomic<bool> g_syntheticA{false};void loadAutoplay() {@@ -84,10 +88,19 @@ void loadAutoplay() {char option[64] = {};int seconds = 0;if (std::sscanf(text.c_str(), "%127s %d %63s", title, &seconds, option) < 1) return;- std::string opt = option;- if (opt == "nosimd") media::disableSimd();- g_autoplayDump = opt == "dump";- if (opt == "repeat") g_autoplayRuns = 2;+ std::string options = option; // comma-separated+ for (size_t start = 0; start <= options.size();) {+ size_t comma = options.find(',', start);+ if (comma == std::string::npos) comma = options.size();+ std::string opt = options.substr(start, comma - start);+ start = comma + 1;+ if (opt == "nosimd") media::disableSimd();+ if (opt == "dump") g_autoplayDump = true;+ if (opt == "repeat") g_autoplayRuns = 2;+ if (opt == "idle") g_autoplayIdle = true;+ if (opt == "rumbletest") input::setRumble(200, 200, 1500);+ if (opt.rfind("threads=", 0) == 0) g_decodeThreads = std::atoi(opt.c_str() + 8);+ }g_autoplayTitle = title;g_autoplaySeconds = seconds > 0 ? seconds : 60;XC_LOGI("AUTOPLAY %s for %ds %s", title, g_autoplaySeconds, option);@@ -139,6 +152,7 @@ std::string formatWait(int seconds) {std::string stream(xcloud::GssvClient& gssv) {app::StreamPlayer player(gssv);if (g_autoplayDump) player.dumpVideo(platform::dataDir() + "/stream.aus", 20);+ player.setDecodeThreads(g_decodeThreads);std::string err;if (!player.start(err)) return "ERROR: " + ui::trf(ui::Str::StreamFailed, err);{@@ -163,7 +177,7 @@ std::string stream(xcloud::GssvClient& gssv) {snapshot1 = true;player.requestSnapshot(platform::dataDir() + "/frame.ppm");}- bool press = (elapsed >= 15000 && elapsed < 15300) || (elapsed >= 20000 && elapsed < 20300);+ bool press = !g_autoplayIdle && ((elapsed >= 15000 && elapsed < 15300) || (elapsed >= 20000 && elapsed < 20300));if (press != g_syntheticA.exchange(press)) XC_LOGI("autoplay: A %s", press ? "down" : "up");if (!snapshot2 && elapsed >= 26000) {snapshot2 = true;@@ -176,14 +190,17 @@ std::string stream(xcloud::GssvClient& gssv) {auto st = player.stats();XC_LOGI("stream: %llu frames, %llu decoded, %llu skipped, %llu failed, %llu resets, %llu kf req, ""%llu queued, %llu audio; rtp %llu pkts, %llu lost, %llu recovered, %llu nacks, "- "%llu frames dropped",+ "%llu frames dropped; %llu kbps (remb %llu); %llu rumble; decode %.1f/%.1f ms, draw %.1f/%.1f ms, %llu late",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.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));+ static_cast<unsigned long long>(st.rtpDroppedFrames), static_cast<unsigned long long>(st.rtpKbps),+ static_cast<unsigned long long>(st.rembKbps), static_cast<unsigned long long>(st.vibrations),+ st.decodeAvgUs / 1000.0, st.decodeMaxUs / 1000.0, st.drawAvgUs / 1000.0, st.drawMaxUs / 1000.0,+ static_cast<unsigned long long>(st.lateFrames));}platform::sleepMs(100);}@@ -561,7 +578,7 @@ int main(int argc, char** argv) {std::lock_guard<std::mutex> lock(display::frameMutex());if (g_ui->screen() != ui::Screen::Streaming) {display::drawRgba(canvas.data());- display::present(); // waits for vblank+ display::present(); // paced by the next draw waiting for a free buffer}} else {platform::sleepMs(8);diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cppindex 503d6c9..d57c496 100644--- a/src/app/stream_player.cpp+++ b/src/app/stream_player.cpp@@ -23,7 +23,11 @@namespace xc::app {namespace {-constexpr size_t kMaxQueuedFrames = 8; // beyond this, decode without drawing+// Beyond this, start over from a key frame. Generous: the jitter buffer+// hands over several frames at once after waiting for a retransmission, and+// decoding without drawing catches up with those in a few milliseconds.+constexpr size_t kMaxQueuedFrames = 30;+constexpr int kMaxFullStreak = 30; // frames shown one refresh late before dropping one}struct StreamPlayer::Impl {@@ -44,6 +48,15 @@ struct StreamPlayer::Impl {std::atomic<uint64_t> videoFrames{0}, decodedFrames{0}, droppedFrames{0}, audioPackets{0};std::atomic<uint64_t> decodeFailures{0}, queueResets{0}, keyframeRequests{0};std::atomic<bool> keyframeWanted{false};+ std::atomic<uint64_t> vibrations{0}, lateFrames{0};+ std::atomic<uint64_t> decodeUs{0}, decodeCalls{0}, decodeMaxUs{0}, drawUs{0}, drawCalls{0}, drawMaxUs{0};+ int decodeThreads = 1;++ static void atomicMax(std::atomic<uint64_t>& a, uint64_t v) {+ uint64_t cur = a;+ while (v > cur && !a.compare_exchange_weak(cur, v)) {+ }+ }bool loggedFirstDecode = false;FILE* dumpFile = nullptr;uint64_t dumpUntilMs = 0;@@ -85,11 +98,12 @@ struct StreamPlayer::Impl {void videoLoop() {media::VideoDecoder decoder;- if (!decoder.init(1)) {+ if (!decoder.init(decodeThreads)) {end("could not start the H.264 decoder");return;}std::vector<uint8_t> au;+ int fullStreak = 0;while (running) {size_t backlog;{@@ -114,7 +128,12 @@ struct StreamPlayer::Impl {media::Picture pic;const bool first = decodedFrames == 0 && !loggedFirstDecode;if (first) XC_LOGI("first video decode: %zu bytes", au.size());+ uint64_t t0 = platform::nowUs();bool ok = decoder.decode(au.data(), au.size(), pic);+ uint64_t t1 = platform::nowUs();+ decodeUs += t1 - t0;+ ++decodeCalls;+ atomicMax(decodeMaxUs, t1 - t0);if (first) {loggedFirstDecode = true;XC_LOGI("first video decode done: ok=%d", ok);@@ -122,7 +141,7 @@ struct StreamPlayer::Impl {if (decoder.needsKeyframe()) keyframeWanted = true;requestKeyframeIfWanted();if (!ok) {- ++decodeFailures;+ if (!decoder.pending()) ++decodeFailures;continue;}++decodedFrames;@@ -133,8 +152,31 @@ struct StreamPlayer::Impl {}std::lock_guard<std::mutex> lock(display::frameMutex());if (decodedFrames == 1) XC_LOGI("first draw %dx%d", pic.width, pic.height);- display::drawYuv420(pic.y, pic.u, pic.v, pic.strideY, pic.strideU, pic.strideV, pic.width, pic.height);+ uint64_t t2 = platform::nowUs();+ // Both flips queued means the picture shows a frame later than+ // it could. Arrival jitter does that now and then; it is waited+ // out (the queue then stays full: stream and display both run at+ // 60 Hz). After half a second of that, a frame is dropped to get+ // the latency back.+ bool drawn = display::drawYuv420(pic.y, pic.u, pic.v, pic.strideY, pic.strideU, pic.strideV,+ pic.width, pic.height, false);+ if (drawn) {+ fullStreak = 0;+ } else if (++fullStreak < kMaxFullStreak) {+ drawn = display::drawYuv420(pic.y, pic.u, pic.v, pic.strideY, pic.strideU, pic.strideV,+ pic.width, pic.height, true);+ } else {+ fullStreak = 0;+ }+ if (!drawn) {+ ++lateFrames;+ continue;+ }display::present();+ uint64_t t3 = platform::nowUs();+ drawUs += t3 - t2;+ ++drawCalls;+ atomicMax(drawMaxUs, t3 - t2);if (decodedFrames == 1) XC_LOGI("first frame presented");}}@@ -169,7 +211,10 @@ struct StreamPlayer::Impl {// 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) {+ cb.vibration = [this](const stream::Vibration& v) {+ if (++vibrations <= 5)+ XC_LOGI("vibration %u/%u/%u/%u for %ums", v.leftMotor, v.rightMotor, v.leftTrigger, v.rightTrigger,+ v.durationMs);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);};@@ -179,6 +224,9 @@ struct StreamPlayer::Impl {// 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";+ opts.maxBitrate = gssv.resolution() == xcloud::Resolution::P720 ? 12000000+ : gssv.resolution() == xcloud::Resolution::P1440 ? 40000000+ : 25000000;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;@@ -302,6 +350,8 @@ void StreamPlayer::requestSnapshot(const std::string& path) {}void StreamPlayer::stop() { impl_->stop(); }+void StreamPlayer::setDecodeThreads(int threads) { impl_->decodeThreads = std::max(1, threads); }+StreamPlayer::Stats StreamPlayer::stats() const {Stats st;st.videoFrames = impl_->videoFrames;@@ -311,6 +361,15 @@ StreamPlayer::Stats StreamPlayer::stats() const {st.decodeFailures = impl_->decodeFailures;st.queueResets = impl_->queueResets;st.keyframeRequests = impl_->keyframeRequests;+ st.vibrations = impl_->vibrations;+ st.lateFrames = impl_->lateFrames;+ // Timings since the previous call.+ uint64_t dc = impl_->decodeCalls.exchange(0), du = impl_->decodeUs.exchange(0);+ uint64_t rc = impl_->drawCalls.exchange(0), ru = impl_->drawUs.exchange(0);+ st.decodeAvgUs = dc ? du / dc : 0;+ st.decodeMaxUs = impl_->decodeMaxUs.exchange(0);+ st.drawAvgUs = rc ? ru / rc : 0;+ st.drawMaxUs = impl_->drawMaxUs.exchange(0);if (impl_->session) { // the caller's thread is the one that stops the playerconst auto& v = impl_->session->videoStats();st.rtpPackets = v.packets;@@ -319,6 +378,8 @@ StreamPlayer::Stats StreamPlayer::stats() const {st.rtpNacks = v.nacks;st.rtpDroppedFrames = v.framesDropped;st.keyframeRequests += v.keyframeRequests;+ st.rtpKbps = v.receiveRate / 1000;+ st.rembKbps = v.estimate / 1000;}{std::lock_guard<std::mutex> lock(impl_->mutex);diff --git a/src/app/stream_player.h b/src/app/stream_player.hindex 562c4ed..f41a681 100644--- a/src/app/stream_player.h+++ b/src/app/stream_player.h@@ -37,8 +37,14 @@ public: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;+ uint64_t rtpKbps = 0, rembKbps = 0, vibrations = 0;+ uint64_t lateFrames = 0; // decoded, not drawn: both flips still queued+ // Since the previous stats() call (so call it from one place only).+ uint64_t decodeAvgUs = 0, decodeMaxUs = 0, drawAvgUs = 0, drawMaxUs = 0;};Stats stats() const;+ // Before start(): H.264 decoder threads (more than 1 = frame threading).+ void setDecodeThreads(int threads);private:struct Impl;diff --git a/src/display/display.cpp b/src/display/display.cppindex 44c7970..ba6fab5 100644--- a/src/display/display.cpp+++ b/src/display/display.cpp@@ -37,13 +37,16 @@ int sceVideoOutRegisterBuffers2(int32_t handle, int32_t set_index,int sceVideoOutSubmitFlip(int32_t handle, int32_t buffer_index,uint32_t flip_mode, int64_t flip_argument);int sceVideoOutWaitVblank(int32_t handle);+// 16 64-bit words; word 3 is the argument of the latest flip shown.+int sceVideoOutGetFlipStatus(int32_t handle, uint64_t status[16]);}namespace xc::display {namespace {-constexpr size_t kFrameBytes = 0x1000000; // 16MB-constexpr size_t kMemoryBytes = kFrameBytes * 2; // double buffer+constexpr size_t kFrameBytes = 0xA00000; // 10 MB: 15x9 macro tiles, 2 MB aligned+constexpr int kBuffers = 3;+constexpr size_t kMemoryBytes = kFrameBytes * kBuffers;constexpr size_t kMemoryAlignment = 0x200000;constexpr int kMemoryTypeGarlic = 3;constexpr int kMapProtection = 0x33;@@ -59,6 +62,13 @@ struct VideoBuffer {int g_videoHandle = -1;void* g_mappedMemory = nullptr;int g_currentBuffer = 0;+// Triple buffering: each flip carries an increasing marker, VideoOut reports+// the marker of the flip on screen. A buffer can be drawn into once a later+// flip than its own has shown; with three, one normally is, so drawing+// never waits for vblank (it did with two, which made a 60 fps stream fall+// behind whenever two frames arrived within one refresh).+int64_t g_flipMarker = 0;+std::array<int64_t, kBuffers> g_bufferMarker{};// PS5 VideoOut swizzled 64KB macro-tile mappingconstexpr size_t tiledByteOffset(unsigned x, unsigned y) {@@ -111,23 +121,21 @@ bool init() {return false;}- auto* secondFrame = static_cast<uint8_t*>(g_mappedMemory) + kFrameBytes;- std::array<VideoBuffer, 2> buffers{{- {g_mappedMemory, nullptr, nullptr, nullptr},- {secondFrame, nullptr, nullptr, nullptr}- }};+ std::array<VideoBuffer, kBuffers> buffers{};+ for (int i = 0; i < kBuffers; ++i)+ buffers[i] = {static_cast<uint8_t*>(g_mappedMemory) + i * kFrameBytes, nullptr, nullptr, nullptr};uint8_t attr[80]{};sceVideoOutSetFlipRate(g_videoHandle, 0);sceVideoOutSetBufferAttribute2(attr, kPixelFormatRGBA8, 0, kWidth, kHeight, 0, 0, 0);- rc = sceVideoOutRegisterBuffers2(g_videoHandle, 0, 0, buffers.data(), 2, attr, 0, nullptr);+ rc = sceVideoOutRegisterBuffers2(g_videoHandle, 0, 0, buffers.data(), kBuffers, attr, 0, nullptr);if (rc < 0) {XC_LOGE("sceVideoOutRegisterBuffers2 failed: 0x%08x", rc);return false;}- XC_LOGI("PS5 Display initialized (1080p, double buffered)");+ XC_LOGI("PS5 Display initialized (1080p, triple buffered)");return true;}@@ -143,13 +151,43 @@ void shutdown() {}}+namespace {+// Picks the back buffer for the next frame: not on screen, not queued.+// Without `wait`, gives up at once when all are busy.+bool acquireBuffer(bool wait = true) {+ for (int attempt = 0; attempt < 4; ++attempt) {+ uint64_t status[16] = {};+ int64_t shown = g_flipMarker; // no status: assume everything shown+ if (g_flipMarker && sceVideoOutGetFlipStatus(g_videoHandle, status) == 0)+ shown = static_cast<int64_t>(status[3]);+ int onScreen = -1;+ for (int i = 0; i < kBuffers; ++i)+ if (g_bufferMarker[i] <= shown && (onScreen < 0 || g_bufferMarker[i] > g_bufferMarker[onScreen]))+ onScreen = i;+ int best = -1;+ for (int i = 0; i < kBuffers; ++i) {+ if (i == onScreen || g_bufferMarker[i] > shown) continue;+ if (best < 0 || g_bufferMarker[i] < g_bufferMarker[best]) best = i;+ }+ if (best >= 0) {+ g_currentBuffer = best;+ return true;+ }+ if (!wait) return false;+ sceVideoOutWaitVblank(g_videoHandle);+ }+ // Flip status not moving: fall back to round robin.+ g_currentBuffer = static_cast<int>(g_flipMarker % kBuffers);+ return true;+}+} // namespace+void present() {if (g_videoHandle < 0 || !g_mappedMemory) return;uint8_t* base = static_cast<uint8_t*>(g_mappedMemory) + (g_currentBuffer * kFrameBytes);flushRange(base, kUsedBytes);- sceVideoOutSubmitFlip(g_videoHandle, g_currentBuffer, 1, 1);- sceVideoOutWaitVblank(g_videoHandle);- g_currentBuffer = 1 - g_currentBuffer;+ g_bufferMarker[g_currentBuffer] = ++g_flipMarker;+ sceVideoOutSubmitFlip(g_videoHandle, g_currentBuffer, 1, g_flipMarker);}namespace {@@ -264,6 +302,7 @@ TilePool& tilePool() {void drawRgba(const uint32_t* pixels) {if (!g_mappedMemory) return;+ acquireBuffer();uint8_t* base = static_cast<uint8_t*>(g_mappedMemory) + (g_currentBuffer * kFrameBytes);tilePool().run([pixels, base](unsigned first, unsigned last) {const TileOrder& order = tileOrder();@@ -278,9 +317,10 @@ void drawRgba(const uint32_t* pixels) {});}-void drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v, int strideY, int strideU, int strideV,- int width, int height) {- if (!g_mappedMemory || width <= 0 || height <= 0) return;+bool drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v, int strideY, int strideU, int strideV,+ int width, int height, bool wait) {+ if (!g_mappedMemory || width <= 0 || height <= 0) return false;+ if (!acquireBuffer(wait)) return false;static YuvJob job;if (job.width != width || job.height != height) {job.srcX.resize(kWidth);@@ -299,6 +339,7 @@ void drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v, int stridejob.height = height;job.base = static_cast<uint8_t*>(g_mappedMemory) + (g_currentBuffer * kFrameBytes);tilePool().run([](unsigned first, unsigned last) { convertTiles(job, first, last); });+ return true;}} // namespace xc::display@@ -314,7 +355,7 @@ std::mutex& frameMutex() {bool init() { return true; }void shutdown() {}void present() {}-void drawYuv420(const uint8_t*, const uint8_t*, const uint8_t*, int, int, int, int, int) {}+bool drawYuv420(const uint8_t*, const uint8_t*, const uint8_t*, int, int, int, int, int, bool) { return true; }void drawRgba(const uint32_t*) {}} // namespace xc::displaydiff --git a/src/display/display.h b/src/display/display.hindex eaf5376..dc5f369 100644--- a/src/display/display.h+++ b/src/display/display.h@@ -23,7 +23,9 @@ void drawRgba(const uint32_t* pixels);// Converts a BT.709 limited-range YUV 4:2:0 picture to the back buffer,// scaled to the full screen (multi-threaded). Call present() afterwards.-void drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v, int strideY, int strideU, int strideV,- int width, int height);+// With two flips still queued it waits for a vblank, or, without `wait`,+// returns false and draws nothing.+bool drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v, int strideY, int strideU, int strideV,+ int width, int height, bool wait);} // namespace xc::displaydiff --git a/src/input/controller.cpp b/src/input/controller.cppindex 073c93f..446d2ce 100644--- a/src/input/controller.cpp+++ b/src/input/controller.cpp@@ -70,6 +70,7 @@ struct ScePadVibrationParam {uint8_t smallMotor;};int scePadSetVibration(int32_t handle, const ScePadVibrationParam* param);+int scePadSetVibrationMode(int32_t handle, int32_t mode);}namespace xc::input {@@ -105,9 +106,11 @@ void applyRumble() {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);+ if (!g_rumbleErrorLogged) { // the first call, and the first failure+ g_rumbleErrorLogged = rc != 0;+ static bool firstLogged = false;+ if (!firstLogged || rc != 0) XC_LOGI("scePadSetVibration(%u, %u): 0x%08x", p.largeMotor, p.smallMotor, rc);+ firstLogged = true;}g_rumbleApplied = want;}@@ -141,7 +144,11 @@ bool init() {XC_LOGE("scePadOpen failed: 0x%08x", g_padHandle);return false;}- XC_LOGI("DualSense pad opened successfully (handle: %d, user: %d)", g_padHandle, g_userId);+ // The DualSense starts in haptics mode, where scePadSetVibration succeeds+ // and does nothing; mode 2 is classic two-motor rumble (as ProsperoEden).+ int mode = scePadSetVibrationMode(g_padHandle, 2);+ XC_LOGI("DualSense pad opened successfully (handle: %d, user: %d, rumble mode: 0x%08x)", g_padHandle, g_userId,+ mode);return true;}diff --git a/src/media/decoder.cpp b/src/media/decoder.cppindex e332d11..91911c3 100644--- a/src/media/decoder.cpp+++ b/src/media/decoder.cpp@@ -103,11 +103,18 @@ bool VideoDecoder::init(int threads) {frame_ = av_frame_alloc();packet_ = av_packet_alloc();if (!ctx_ || !frame_ || !packet_) return false;- ctx_->flags |= AV_CODEC_FLAG_LOW_DELAY;ctx_->flags2 |= AV_CODEC_FLAG2_FAST;ctx_->thread_count = std::max(1, threads);- ctx_->thread_type = FF_THREAD_SLICE;- XC_LOGI("h264 decoder: cpu flags 0x%x", av_get_cpu_flags());+ if (threads > 1) {+ // xCloud sends one slice per picture, so slice threads would idle:+ // decode several pictures at once instead, one frame of latency per+ // extra thread. (LOW_DELAY would turn frame threading off.)+ ctx_->thread_type = FF_THREAD_FRAME;+ } else {+ ctx_->flags |= AV_CODEC_FLAG_LOW_DELAY;+ ctx_->thread_type = FF_THREAD_SLICE;+ }+ XC_LOGI("h264 decoder: cpu flags 0x%x, %d thread(s)", av_get_cpu_flags(), ctx_->thread_count);int rc = avcodec_open2(ctx_, codec, nullptr);if (rc < 0) {XC_LOGE("avcodec_open2(h264): %s", averr(rc).c_str());@@ -119,6 +126,7 @@ bool VideoDecoder::init(int threads) {bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out) {// An empty packet means "end of stream" to libavcodec and would switch it// to draining for good; the RTP depacketizer emits them after packet loss.+ pending_ = false;if (!ctx_ || len == 0) return false;packet_->data = const_cast<uint8_t*>(data);packet_->size = static_cast<int>(len);@@ -135,8 +143,12 @@ bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out) {}int sent = rc;rc = avcodec_receive_frame(ctx_, frame_);+ if (rc == AVERROR(EAGAIN)) {+ pending_ = true;+ return false;+ }if (rc < 0) {- if (rc != AVERROR(EAGAIN)) needsKeyframe_ = true;+ needsKeyframe_ = true;if (failuresLogged_++ < 20)XC_LOGI("h264 no picture: send=%d receive=%s (%zu bytes, first NAL type %d)", sent, averr(rc).c_str(),len, len > 4 ? data[4] & 0x1f : -1);diff --git a/src/media/decoder.h b/src/media/decoder.hindex 6958fa9..2854566 100644--- a/src/media/decoder.h+++ b/src/media/decoder.h@@ -46,12 +46,16 @@ public:bool decode(const uint8_t* data, size_t len, Picture& out);// True after a decode error: the caller should ask for a key frame.bool needsKeyframe() const { return needsKeyframe_; }+ // The last decode() returned no picture without an error: the decoder+ // wants more input (frame threads still busy, or no reference yet).+ bool pending() const { return pending_; }private:AVCodecContext* ctx_ = nullptr;AVFrame* frame_ = nullptr;AVPacket* packet_ = nullptr;bool needsKeyframe_ = true;+ bool pending_ = false;int failuresLogged_ = 0;};diff --git a/src/platform/platform.h b/src/platform/platform.hindex 70049b3..65949a2 100644--- a/src/platform/platform.h+++ b/src/platform/platform.h@@ -30,6 +30,7 @@ bool randomBytes(void* out, size_t len);// getaddrinfo. Returns false (with a message in `err`) on failure.bool resolveIPv4(const std::string& host, uint32_t& addr, std::string& err);uint64_t nowMs(); // monotonic+uint64_t nowUs(); // monotonicvoid sleepMs(uint32_t ms);// Logs which socket operations work (PS5 diagnostics; no-op on the host).diff --git a/src/platform/posix_common.cpp b/src/platform/posix_common.cppindex d5bb61e..c6ebda0 100644--- a/src/platform/posix_common.cpp+++ b/src/platform/posix_common.cpp@@ -41,6 +41,12 @@ uint64_t nowMs() {return static_cast<uint64_t>(ts.tv_sec) * 1000u + static_cast<uint64_t>(ts.tv_nsec) / 1000000u;}+uint64_t nowUs() {+ timespec ts{};+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return static_cast<uint64_t>(ts.tv_sec) * 1000000u + static_cast<uint64_t>(ts.tv_nsec) / 1000u;+}+namespace {void* threadEntry(void* arg) {auto* fn = static_cast<std::function<void()>*>(arg);diff --git a/src/stream/h264_receiver.cpp b/src/stream/h264_receiver.cppindex 55094f4..e2492f2 100644--- a/src/stream/h264_receiver.cpp+++ b/src/stream/h264_receiver.cpp@@ -2,6 +2,8 @@// Copyright (C) 2026 RafaelNGP#include "stream/h264_receiver.h"+#include "stream/rtcp_reporter.h"+#include "platform/platform.h"#include "util/log.h"@@ -16,7 +18,6 @@ namespace {constexpr uint64_t kWaitMs = 150;constexpr uint64_t kRenackMs = 40;constexpr int kMaxNacks = 3;-constexpr uint32_t kOurSsrc = 0x50534278; // "PSBx": RTCP sender SSRCconstexpr size_t kMaxBuffered = 4000; // packets (about 4 MB)constexpr uint8_t kStartCode[] = {0, 0, 0, 1};@@ -68,7 +69,7 @@ void H264Receiver::sendNack(const std::vector<int64_t>& seqs, const rtc::messageb.push_back(0x81); // V=2, FMT=1b.push_back(205); // RTPFBput16(b, static_cast<uint16_t>(2 + fci.size()));- put32(b, kOurSsrc);+ put32(b, kReceiverSsrc);put32(b, mediaSsrc_);for (auto [pid, blp] : fci) {put16(b, pid);@@ -91,7 +92,7 @@ void H264Receiver::sendPli(const rtc::message_callback& send) {b.push_back(0x81); // V=2, FMT=1b.push_back(206); // PSFBput16(b, 2);- put32(b, kOurSsrc);+ put32(b, kReceiverSsrc);put32(b, mediaSsrc_);send(rtc::make_message(asBytes(b), asBytes(b) + b.size(), rtc::Message::Control));}diff --git a/src/stream/rtcp_reporter.cpp b/src/stream/rtcp_reporter.cppnew file mode 100644index 0000000..55e9cf5--- /dev/null+++ b/src/stream/rtcp_reporter.cpp@@ -0,0 +1,179 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "stream/rtcp_reporter.h"++#include <algorithm>+#include <chrono>+#include <vector>++namespace xc::stream {++namespace {++constexpr uint64_t kReportIntervalUs = 500000;+constexpr uint32_t kMinBitrate = 1500000;++uint64_t nowUs() {+ return static_cast<uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(+ std::chrono::steady_clock::now().time_since_epoch())+ .count());+}++uint16_t get16(const uint8_t* p) { return static_cast<uint16_t>((p[0] << 8) | p[1]); }+uint32_t get32(const uint8_t* p) {+ return (uint32_t(p[0]) << 24) | (uint32_t(p[1]) << 16) | (uint32_t(p[2]) << 8) | p[3];+}+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));+}++} // namespace++RtcpReporter::RtcpReporter(uint32_t clockRate, uint32_t maxBitrate)+ : clockRate_(clockRate), maxBitrate_(maxBitrate) {+ estimate_ = maxBitrate;+}++void RtcpReporter::onRtp(const uint8_t* d, size_t n, uint64_t now) {+ uint32_t ssrc = get32(d + 8);+ uint16_t seq = get16(d + 2);+ if (!started_ || ssrc != mediaSsrc_) { // RFC 3550 A.1, without probation+ started_ = true;+ mediaSsrc_ = ssrc;+ baseSeq_ = seq;+ maxSeq_ = seq;+ cycles_ = 0;+ received_ = expectedPrior_ = receivedPrior_ = 0;+ haveTransit_ = false;+ jitter_ = 0;+ } else {+ uint16_t delta = static_cast<uint16_t>(seq - maxSeq_);+ if (delta < 0x8000) { // in order, maybe with a gap+ if (seq < maxSeq_) cycles_ += 0x10000;+ maxSeq_ = seq;+ }+ // Older packets (reordered, retransmitted) only count as received.+ }+ ++received_;+ bytesSinceReport_ += n;++ // Interarrival jitter (A.8), in RTP clock units. Like libwebrtc, only+ // the first packet of each frame counts: the packets of one frame share a+ // timestamp but are sent over several milliseconds.+ uint32_t ts = get32(d + 4);+ if (haveTransit_ && ts == lastTimestamp_) return;+ int64_t arrival = static_cast<int64_t>(now * clockRate_ / 1000000u);+ int64_t transit = arrival - static_cast<int64_t>(ts);+ if (haveTransit_) {+ int64_t dt = transit - lastTransit_;+ if (dt < 0) dt = -dt;+ if (dt < static_cast<int64_t>(clockRate_)) jitter_ += (static_cast<double>(dt) - jitter_) / 16.0;+ }+ lastTransit_ = transit;+ lastTimestamp_ = ts;+ haveTransit_ = true;+}++void RtcpReporter::onRtcp(const uint8_t* d, size_t n, uint64_t now) {+ // A compound packet: walk it for the sender report.+ for (size_t off = 0; off + 4 <= n;) {+ uint8_t pt = d[off + 1];+ size_t len = (static_cast<size_t>(get16(d + off + 2)) + 1) * 4;+ if (off + len > n) break;+ if (pt == 200 && len >= 28) {+ lastSr_ = (get32(d + off + 8) << 16) | (get32(d + off + 12) >> 16);+ lastSrArrivalUs_ = now;+ }+ off += len;+ }+}++void RtcpReporter::report(uint64_t now, const rtc::message_callback& send) {+ uint64_t intervalUs = lastReportUs_ ? now - lastReportUs_ : kReportIntervalUs;+ lastReportUs_ = now;++ uint32_t extMax = cycles_ + maxSeq_;+ uint32_t expected = extMax - baseSeq_ + 1;+ int64_t lost = static_cast<int64_t>(expected) - received_;+ lost = std::clamp<int64_t>(lost, -0x800000, 0x7FFFFF);+ uint32_t expectedInterval = expected - expectedPrior_;+ uint32_t receivedInterval = received_ - receivedPrior_;+ expectedPrior_ = expected;+ receivedPrior_ = received_;+ int64_t lostInterval = static_cast<int64_t>(expectedInterval) - receivedInterval;+ uint8_t fraction = 0;+ if (expectedInterval > 0 && lostInterval > 0)+ fraction = static_cast<uint8_t>(std::min<int64_t>(255, (lostInterval << 8) / expectedInterval));+ uint32_t dlsr = 0;+ if (lastSrArrivalUs_) dlsr = static_cast<uint32_t>((now - lastSrArrivalUs_) * 65536 / 1000000);++ std::vector<uint8_t> b;+ b.reserve(64);+ b.push_back(0x81); // V=2, one report block+ b.push_back(201); // RR+ put16(b, 7);+ put32(b, kReceiverSsrc);+ put32(b, mediaSsrc_);+ put32(b, (uint32_t(fraction) << 24) | (static_cast<uint32_t>(lost) & 0xFFFFFF));+ put32(b, extMax);+ put32(b, static_cast<uint32_t>(jitter_));+ put32(b, lastSr_);+ put32(b, lastSr_ ? dlsr : 0);++ if (maxBitrate_) {+ uint32_t rate = intervalUs ? static_cast<uint32_t>(bytesSinceReport_ * 8 * 1000000 / intervalUs) : 0;+ receiveRate_ = rate;+ // Like a receive-side estimator, much simplified: back off below+ // what arrives when the network drops packets, otherwise climb back+ // to the ceiling.+ double loss = fraction / 256.0;+ uint32_t est = estimate_;+ if (loss > 0.10)+ est = std::max<uint32_t>(kMinBitrate, static_cast<uint32_t>(rate * (1.0 - 0.5 * loss)));+ else if (loss < 0.02)+ est = std::min<uint32_t>(maxBitrate_, std::max<uint32_t>(est, kMinBitrate) + maxBitrate_ / 20);+ estimate_ = est;++ uint8_t exp = 0;+ uint32_t mantissa = est;+ while (mantissa >= (1u << 18)) {+ mantissa >>= 1;+ ++exp;+ }+ b.push_back(0x8F); // V=2, FMT=15 (application layer feedback)+ b.push_back(206); // PSFB+ put16(b, 5);+ put32(b, kReceiverSsrc);+ put32(b, 0);+ b.insert(b.end(), {'R', 'E', 'M', 'B'});+ put32(b, (1u << 24) | (uint32_t(exp) << 18) | mantissa);+ put32(b, mediaSsrc_);+ }+ bytesSinceReport_ = 0;++ auto* p = reinterpret_cast<const std::byte*>(b.data());+ send(rtc::make_message(p, p + b.size(), rtc::Message::Control));+}++void RtcpReporter::incoming(rtc::message_vector& messages, const rtc::message_callback& send) {+ uint64_t now = nowUs();+ rtc::message_vector rtp;+ for (auto& message : messages) {+ const auto* d = reinterpret_cast<const uint8_t*>(message->data());+ size_t n = message->size();+ if (message->type == rtc::Message::Control) {+ onRtcp(d, n, now);+ } else if (message->type == rtc::Message::Binary && n >= 12 && (d[0] >> 6) == 2) {+ onRtp(d, n, now);+ rtp.push_back(std::move(message));+ }+ }+ messages.swap(rtp);+ if (started_ && now - lastReportUs_ >= kReportIntervalUs) report(now, send);+}++} // namespace xc::streamdiff --git a/src/stream/rtcp_reporter.h b/src/stream/rtcp_reporter.hnew file mode 100644index 0000000..e780f2b--- /dev/null+++ b/src/stream/rtcp_reporter.h@@ -0,0 +1,57 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// RTCP receiver side of a track: RFC 3550 receiver reports (loss, jitter,+// LSR/DLSR for the sender's RTT) and, for video, REMB bandwidth estimates.+//+// The xCloud server negotiates only goog-remb for congestion control, like+// Chrome receiving from it; it sizes the stream from these reports.+// libdatachannel's RtcpReceivingSession reports a highest sequence number of+// 0, no loss and no jitter, and sends REMB only if asked: the server then+// shows the "slow connection" icon and keeps the bitrate low.+#pragma once++#include <rtc/rtc.hpp>++#include <atomic>+#include <cstdint>++namespace xc::stream {++// SSRC of our RTCP packets (receiver reports, NACK, PLI, REMB).+constexpr uint32_t kReceiverSsrc = 0x50534278; // "PSBx"++class RtcpReporter final : public rtc::MediaHandler {+public:+ // `clockRate`: RTP clock of the track (90000 video, 48000 Opus).+ // `maxBitrate`: bits/s offered with REMB; 0 = no REMB (audio).+ RtcpReporter(uint32_t clockRate, uint32_t maxBitrate);++ void incoming(rtc::message_vector& messages, const rtc::message_callback& send) override;++ // Last REMB estimate and the measured receive rate, bits/s.+ uint32_t estimate() const { return estimate_; }+ uint32_t receiveRate() const { return receiveRate_; }++private:+ void onRtp(const uint8_t* d, size_t n, uint64_t nowUs);+ void onRtcp(const uint8_t* d, size_t n, uint64_t nowUs);+ void report(uint64_t nowUs, const rtc::message_callback& send);++ const uint32_t clockRate_, maxBitrate_;+ uint32_t mediaSsrc_ = 0;+ bool started_ = false;+ uint16_t maxSeq_ = 0;+ uint32_t cycles_ = 0, baseSeq_ = 0;+ uint32_t received_ = 0, expectedPrior_ = 0, receivedPrior_ = 0;+ double jitter_ = 0;+ int64_t lastTransit_ = 0;+ uint32_t lastTimestamp_ = 0;+ bool haveTransit_ = false;+ uint32_t lastSr_ = 0; // middle 32 bits of the last SR's NTP time+ uint64_t lastSrArrivalUs_ = 0;+ uint64_t lastReportUs_ = 0;+ uint64_t bytesSinceReport_ = 0;+ std::atomic<uint32_t> estimate_{0}, receiveRate_{0};+};++} // namespace xc::streamdiff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cppindex 12946e1..d312cf4 100644--- a/src/stream/stream_session.cpp+++ b/src/stream/stream_session.cpp@@ -3,6 +3,7 @@#include "stream/stream_session.h"#include "stream/h264_receiver.h"+#include "stream/rtcp_reporter.h"#include "platform/platform.h"#include "util/json.h"@@ -125,6 +126,8 @@ struct StreamSession::Impl {uint64_t lastKeepaliveMs = 0;uint64_t lastKeyframeMs = 0;VideoReceiveStats videoStats;+ std::shared_ptr<RtcpReporter> videoReporter;+ std::atomic<int> otherInputReports{0};Impl(xcloud::GssvClient& g, StreamCallbacks c, StreamOptions o) : gssv(g), cb(std::move(c)), opt(o) {}@@ -368,6 +371,8 @@ struct StreamSession::Impl {if (cb.vibration) cb.vibration(v);} else if (parseServerMetadata(d, b->size(), w, h)) {XC_LOGI("server video size %ux%u", w, h);+ } else if (b->size() >= 2 && ++otherInputReports <= 5) {+ XC_LOGI("input channel: report type %u, %zu bytes", d[0], b->size());}});@@ -376,7 +381,7 @@ struct StreamSession::Impl {a.addOpusCodec(111, "minptime=10;useinbandfec=1;stereo=1");audio = pc->addTrack(a);auto audioDepacketizer = std::make_shared<rtc::OpusRtpDepacketizer>();- audioDepacketizer->addToChain(std::make_shared<rtc::RtcpReceivingSession>());+ audioDepacketizer->addToChain(std::make_shared<RtcpReporter>(48000, 0));audio->setMediaHandler(audioDepacketizer);audio->onFrame([this](rtc::binary data, rtc::FrameInfo info) {if (cb.audio) cb.audio(reinterpret_cast<const uint8_t*>(data.data()), data.size(), info.timestamp);@@ -403,7 +408,8 @@ struct StreamSession::Impl {},videoStats);videoReceiver->setSimulatedLoss(opt.simulatedVideoLoss);- videoReceiver->addToChain(std::make_shared<rtc::RtcpReceivingSession>());+ videoReporter = std::make_shared<RtcpReporter>(90000, opt.maxBitrate);+ videoReceiver->addToChain(videoReporter);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);@@ -587,6 +593,12 @@ void StreamSession::requestKeyframe() {}void StreamSession::tick() { impl_->tick(); }void StreamSession::close() { impl_->close(); }-const VideoReceiveStats& StreamSession::videoStats() const { return impl_->videoStats; }+const VideoReceiveStats& StreamSession::videoStats() const {+ if (impl_->videoReporter) {+ impl_->videoStats.receiveRate = impl_->videoReporter->receiveRate();+ impl_->videoStats.estimate = impl_->videoReporter->estimate();+ }+ return impl_->videoStats;+}} // namespace xc::streamdiff --git a/src/stream/stream_session.h b/src/stream/stream_session.hindex ccb66ed..479f654 100644--- a/src/stream/stream_session.h+++ b/src/stream/stream_session.h@@ -40,6 +40,8 @@ struct StreamOptions {// Test hook: drop this percentage of video RTP packets before the jitter// buffer, to exercise NACK / key frame recovery.int simulatedVideoLoss = 0;+ // Ceiling of the bandwidth estimate sent to the server (REMB), bits/s.+ uint32_t maxBitrate = 25000000;};// "a=candidate:..." with a Teredo (2001::/32) address -> the IPv4 address anddiff --git a/src/stream/video_stats.h b/src/stream/video_stats.hindex 990665c..e2a0dc4 100644--- a/src/stream/video_stats.h+++ b/src/stream/video_stats.h@@ -16,6 +16,8 @@ struct VideoReceiveStats {std::atomic<uint64_t> framesOut{0};std::atomic<uint64_t> framesDropped{0}; // incomplete, or waiting for a key framestd::atomic<uint64_t> keyframeRequests{0};+ std::atomic<uint32_t> receiveRate{0}; // bits/s, last report interval+ std::atomic<uint32_t> estimate{0}; // bits/s offered to the server (REMB)};} // namespace xc::stream