Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

Streaming works on the PS5: 1080p60 video, audio and controller input

Rafael Abud Ferreira6d94ca82c5e8
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8b2e678..fb0e764 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -49,7 +49,7 @@ add_library(xcloud_media STATIC src/media/decoder.cpp src/media/audio_out.cpp)
target_link_libraries(xcloud_media PUBLIC xcloud_core PRIVATE xc_ffmpeg)
if(XCLOUD_PS5)
- target_sources(xcloud_core PRIVATE src/platform/ps5/platform_ps5.cpp src/platform/ps5/libc_compat.c)
+ target_sources(xcloud_core PRIVATE src/platform/ps5/platform_ps5.cpp src/platform/ps5/libc_compat.c src/platform/ps5/net_probe.cpp)
# The app itself: linked into eboot.bin by tools/ps5/link.sh.
add_library(xcloud_app STATIC
diff --git a/README.md b/README.md
index 7d5d0a8..9d87e6f 100644
--- a/README.md
+++ b/README.md
@@ -8,9 +8,37 @@ Cliente nativo de Xbox Cloud Gaming (xCloud) para PS5 com homebrew.
| --- | --- | --- |
| Interface na tela, DualSense nos menus | — | testado |
| Login (conta salva), lista de jogos, sessão, fila | testado | testado |
-| WebRTC (SDP/ICE, DTLS-SRTP, canais de dados) | testado: 1080p60 H.264 + Opus | falhava no ICE (`getaddrinfo`); correção ainda não testada |
-| Decodificação H.264/Opus (FFmpeg) | testado (5,4 ms/quadro com SIMD) | não testado |
-| Vídeo na tela, áudio, DualSense → controle Xbox | — | não testado |
+| WebRTC (SDP/ICE, DTLS-SRTP, canais de dados) | testado | testado |
+| Vídeo 1080p60 H.264 (FFmpeg, 3,1 ms/quadro no PS5) | testado | testado: 3 min, 99,6% dos quadros exibidos |
+| Áudio Opus → sceAudioOut | decodificação testada | decodificado e enviado à saída (falta confirmar de ouvido) |
+| DualSense → controle Xbox no jogo | — | testado (autoplay aperta A no Balatro) |
+
+## Teste automático no console
+
+`tools/ps5/autotest.sh` compila, faz o deploy, abre o app pelo agente
+`ps5vkctl` do PS5_Vulkan e espera o resultado. O app, ao achar
+`autoplay.txt`, entra no jogo sozinho, aperta A aos 15 s e 20 s, registra
+estatísticas por segundo e salva quadros em `frame.ppm`/`frame2.ppm`.
+
+```bash
+PS5_HOST=<ip> tools/ps5/autotest.sh BALATRO 60 # streaming
+PS5_HOST=<ip> tools/ps5/autotest.sh BALATRO 30 dump # + grava stream.aus (H.264 recebido)
+XC_SAMPLE=amostra.h264 PS5_HOST=<ip> tools/ps5/autotest.sh BENCH 30 # só o decoder
+build-host/xcloud-cli bench-decode build-ps5/autotest/stream.aus # reproduz no PC
+```
+
+Resultados em `build-ps5/autotest/`.
+
+## Particularidades do PS5 (sandbox do app)
+
+- `getaddrinfo` não funciona (e o link do PS5_Vulkan o troca por um stub que
+ sempre falha): `libc_compat.c` implementa `getaddrinfo`/`getnameinfo` com
+ `sceNetResolver`, e o `link.sh` remove o redirecionamento.
+- `ioctl(FIONBIO)`/`fcntl(O_NONBLOCK)` em sockets dão `EACCES`;
+ `setsockopt(SO_NBIO)` funciona (`ioctl` é embrulhado via `ps5/compat/ps5_lfs.h`).
+- O callback de log padrão do FFmpeg derruba o app: o log vai para o nosso logger.
+- O depacketizador H.264 às vezes entrega unidades vazias, que o libavcodec
+ entende como fim de stream: são descartadas.
## Build
diff --git a/ps5/compat/ps5_lfs.h b/ps5/compat/ps5_lfs.h
index 9807d14..5bda1f4 100644
--- a/ps5/compat/ps5_lfs.h
+++ b/ps5/compat/ps5_lfs.h
@@ -16,3 +16,10 @@
#define pread64 pread
#define pwrite64 pwrite
#define off64_t off_t
+
+/*
+ * The app sandbox refuses ioctl(FIONBIO) and fcntl(O_NONBLOCK) on sockets
+ * (EACCES); setsockopt(SO_NBIO) works. Every ioctl call goes through
+ * xc_ioctl (src/platform/ps5/libc_compat.c), which translates FIONBIO.
+ */
+#define ioctl xc_ioctl
diff --git a/src/app/cli_main.cpp b/src/app/cli_main.cpp
index aa34670..5b48db4 100644
--- a/src/app/cli_main.cpp
+++ b/src/app/cli_main.cpp
@@ -208,28 +208,19 @@ int cmdBenchDecode(const char* path, int threads) {
XC_LOGE("cannot read %s", path);
return 1;
}
- // Access units start at each SPS or non-IDR/IDR slice with first_mb == 0;
- // the stream from xCloud starts every AU with an AUD or SPS, so splitting
- // at AUD (type 9) or SPS (type 7) not preceded by an AUD is enough.
std::vector<std::pair<size_t, size_t>> aus;
- size_t start = std::string::npos;
- int prevType = -1;
- for (size_t i = 0; i + 4 < data.size(); ++i) {
- if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) {
- int type = data[i + 3] & 0x1f;
- size_t sc = (i > 0 && data[i - 1] == 0) ? i - 1 : i;
- bool boundary = type == 9 || (type == 7 && prevType != 9) ||
- ((type == 1 || type == 5) && prevType != 7 && prevType != 8 && prevType != 9 &&
- prevType != 6 && (static_cast<uint8_t>(data[i + 4]) & 0x80));
- if (boundary) {
- if (start != std::string::npos) aus.emplace_back(start, sc - start);
- start = sc;
- }
- prevType = type;
- i += 3;
+ if (std::string(path).size() > 4 && std::string(path).substr(std::string(path).size() - 4) == ".aus") {
+ // Length-prefixed access units as received on the console.
+ for (size_t p = 0; p + 4 <= data.size();) {
+ uint32_t n;
+ std::memcpy(&n, data.data() + p, 4);
+ if (p + 4 + n > data.size()) break;
+ aus.emplace_back(p + 4, n);
+ p += 4 + n;
}
+ } else {
+ aus = media::splitAccessUnits(reinterpret_cast<const uint8_t*>(data.data()), data.size());
}
- if (start != std::string::npos) aus.emplace_back(start, data.size() - start);
media::VideoDecoder dec;
if (!dec.init(threads)) return 1;
diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cpp
index ad80ec2..e01624c 100644
--- a/src/app/ps5_main.cpp
+++ b/src/app/ps5_main.cpp
@@ -7,12 +7,14 @@
#include "auth/auth_manager.h"
#include "display/display.h"
#include "input/controller.h"
+#include "media/decoder.h"
#include "net/http.h"
#include "platform/platform.h"
#include "util/log.h"
#include "xcloud/gssv.h"
#include <algorithm>
+#include <cstdio>
#include <atomic>
#include <mutex>
#include <string>
@@ -82,9 +84,64 @@ app::StreamPlayer* g_player = nullptr;
void setSession(const std::string& text, bool running);
+// Unattended test mode (tools/ps5/autotest.sh): <dataDir>/autoplay.txt holds
+// "<titleId> <seconds>". The app signs in, plays that title for that long,
+// saves a decoded frame as frame.ppm and logs "AUTOPLAY END".
+std::string g_autoplayTitle;
+int g_autoplaySeconds = 0;
+// Autoplay presses A at 15 s and 20 s into the stream (input check).
+std::atomic<bool> g_syntheticA{false};
+bool g_autoplayDump = false;
+
+void loadAutoplay() {
+ std::string text;
+ if (!platform::readFile(platform::dataDir() + "/autoplay.txt", text)) return;
+ char title[128] = {};
+ char option[64] = {};
+ int seconds = 0;
+ if (std::sscanf(text.c_str(), "%127s %d %63s", title, &seconds, option) >= 1) {
+ if (std::string(option) == "nosimd") media::disableSimd();
+ g_autoplayDump = std::string(option) == "dump";
+ g_autoplayTitle = title;
+ g_autoplaySeconds = seconds > 0 ? seconds : 60;
+ XC_LOGI("AUTOPLAY %s for %ds", title, g_autoplaySeconds);
+ platform::probeNetworking();
+ }
+}
+
+// Autoplay "BENCH": decode <dataDir>/sample.h264 without any network, to test
+// FFmpeg on the console in isolation.
+void runDecodeBench() {
+ std::string data;
+ if (!platform::readFile(platform::dataDir() + "/sample.h264", data)) {
+ XC_LOGE("AUTOPLAY END: no sample.h264");
+ return;
+ }
+ auto aus = media::splitAccessUnits(reinterpret_cast<const uint8_t*>(data.data()), data.size());
+ XC_LOGI("bench: %zu bytes, %zu access units", data.size(), aus.size());
+ media::VideoDecoder dec;
+ if (!dec.init(1)) {
+ XC_LOGE("AUTOPLAY END: decoder init failed");
+ return;
+ }
+ media::Picture pic;
+ int pictures = 0;
+ uint64_t t0 = platform::nowMs();
+ for (size_t i = 0; i < aus.size(); ++i) {
+ if (i < 3) XC_LOGI("bench: decode AU %zu (%zu bytes)", i, aus[i].second);
+ bool ok = dec.decode(reinterpret_cast<const uint8_t*>(data.data()) + aus[i].first, aus[i].second, pic);
+ if (ok) ++pictures;
+ if (i < 3) XC_LOGI("bench: AU %zu done ok=%d", i, ok);
+ }
+ uint64_t ms = platform::nowMs() - t0;
+ XC_LOGI("AUTOPLAY END: bench %d pictures (%dx%d) in %llu ms = %.2f ms/picture", pictures, pic.width,
+ pic.height, static_cast<unsigned long long>(ms), pictures ? double(ms) / pictures : 0.0);
+}
+
void play(xcloud::GssvClient& gssv, std::string& result) {
setSession("Conectando o stream...", true);
app::StreamPlayer player(gssv);
+ if (g_autoplayDump) player.dumpVideo(platform::dataDir() + "/stream.aus", 20);
std::string err;
if (!player.start(err)) {
result = "ERRO ao conectar o stream: " + err;
@@ -97,14 +154,33 @@ void play(xcloud::GssvClient& gssv, std::string& result) {
updateUi([](Ui& ui) { ui.screen = Screen::Streaming; });
platform::notify("Segure OPTIONS + TOUCHPAD para sair do jogo");
uint64_t nextTick = platform::nowMs();
+ const uint64_t started = nextTick;
+ bool snapshotAsked = false, snapshot2Asked = false;
while (player.running() && !g_cancel) {
+ uint64_t elapsed = platform::nowMs() - started;
+ if (!g_autoplayTitle.empty()) {
+ if (elapsed >= static_cast<uint64_t>(g_autoplaySeconds) * 1000u) break;
+ if (!snapshotAsked && elapsed >= 10000) {
+ snapshotAsked = true;
+ player.requestSnapshot(platform::dataDir() + "/frame.ppm");
+ }
+ bool press = (elapsed >= 15000 && elapsed < 15300) || (elapsed >= 20000 && elapsed < 20300);
+ if (press != g_syntheticA.exchange(press)) XC_LOGI("autoplay: A %s", press ? "down" : "up");
+ if (!snapshot2Asked && elapsed >= 26000) {
+ snapshot2Asked = true;
+ player.requestSnapshot(platform::dataDir() + "/frame2.ppm");
+ }
+ }
if (platform::nowMs() >= nextTick) {
nextTick += 1000;
player.tick();
auto st = player.stats();
- XC_LOGD("stream: %llu frames, %llu decoded, %llu skipped, %llu audio",
+ XC_LOGI("stream: %llu frames, %llu decoded, %llu skipped, %llu failed, %llu resets, %llu kf req, "
+ "%llu queued, %llu audio",
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.audioPackets));
+ 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));
}
platform::sleepMs(100);
}
@@ -112,7 +188,7 @@ void play(xcloud::GssvClient& gssv, std::string& result) {
std::lock_guard<std::mutex> lock(g_playerMutex);
g_player = nullptr;
}
- std::string reason = g_cancel ? "voce saiu do jogo" : player.endReason();
+ std::string reason = g_cancel ? "voce saiu do jogo" : player.running() ? "fim do autoplay" : player.endReason();
player.stop();
auto st = player.stats();
result = "Stream encerrado (" + reason + "). " + std::to_string(st.decodedFrames) + " quadros exibidos.";
@@ -129,6 +205,7 @@ void doSignIn(auth::AuthManager& am, xcloud::GssvClient& gssv) {
};
if (!am.signIn(gssv, onCode, err, &g_cancel)) {
setError("Falha no login: " + err);
+ if (!g_autoplayTitle.empty()) XC_LOGI("AUTOPLAY END: login failed");
return;
}
updateUi([&](Ui& ui) {
@@ -153,6 +230,11 @@ void doSignIn(auth::AuthManager& am, xcloud::GssvClient& gssv) {
ui.titles = std::move(titles);
ui.screen = Screen::Titles;
});
+ if (!g_autoplayTitle.empty()) {
+ std::lock_guard<std::mutex> lock(g_argMutex);
+ g_provisionTitle = g_autoplayTitle;
+ g_command = kProvision;
+ }
}
void setSession(const std::string& text, bool running) {
@@ -205,9 +287,16 @@ void doProvision(auth::AuthManager& am, xcloud::GssvClient& gssv, const std::str
if (g_cancel && result.rfind("Stream", 0) != 0) result = "Cancelado";
gssv.stopSession();
setSession(result, false);
+ if (!g_autoplayTitle.empty()) XC_LOGI("AUTOPLAY END: %s", result.c_str());
}
void worker() {
+ if (g_autoplayTitle == "BENCH") {
+ platform::Thread t; // same big stack as the stream's video thread
+ platform::startThread(t, runDecodeBench);
+ t.join();
+ for (;;) platform::sleepMs(1000);
+ }
auth::AuthManager am(platform::dataDir() + "/account.json");
xcloud::GssvClient gssv;
for (;;) {
@@ -329,6 +418,7 @@ int main(int argc, char** argv) {
platform::init();
log::setFile((platform::dataDir() + "/xcloud.log").c_str());
XC_LOGI("=== xCloud PS5 starting ===");
+ loadAutoplay();
sceSystemServiceHideSplashScreen();
bool haveDisplay = display::init();
@@ -392,7 +482,11 @@ int main(int argc, char** argv) {
case Screen::Streaming: {
{
std::lock_guard<std::mutex> lock(g_playerMutex);
- if (g_player) g_player->sendInput(pad);
+ if (g_player) {
+ input::ControllerState sent = pad;
+ if (g_syntheticA) sent.btnA = true;
+ g_player->sendInput(sent);
+ }
}
// OPTIONS + TOUCHPAD held for a second leaves the game.
if (pad.btnOptions && pad.btnTouchpad) {
diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cpp
index bffde68..22ec545 100644
--- a/src/app/stream_player.cpp
+++ b/src/app/stream_player.cpp
@@ -8,6 +8,7 @@
#include "util/log.h"
#include <atomic>
+#include <cstdio>
#include <condition_variable>
#include <deque>
#include <mutex>
@@ -29,12 +30,20 @@ struct StreamPlayer::Impl {
std::deque<std::vector<uint8_t>> frames;
std::atomic<bool> running{false};
std::string endReason;
- std::thread videoThread;
+ platform::Thread videoThread, audioThread;
+ std::deque<std::vector<uint8_t>> audioPackets_;
+ std::condition_variable audioCv;
media::AudioDecoder audioDecoder;
std::vector<float> pcm;
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};
+ bool loggedFirstDecode = false;
+ FILE* dumpFile = nullptr;
+ uint64_t dumpUntilMs = 0;
+ std::mutex snapshotMutex;
+ std::string snapshotPath;
uint64_t lastKeyframeRequestMs = 0;
explicit Impl(xcloud::GssvClient& g) : gssv(g) {}
@@ -46,6 +55,27 @@ struct StreamPlayer::Impl {
}
running = false;
cv.notify_all();
+ audioCv.notify_all();
+ }
+
+ void audioLoop() {
+ std::vector<uint8_t> packet;
+ bool first = true;
+ while (running) {
+ {
+ std::unique_lock<std::mutex> lock(mutex);
+ audioCv.wait(lock, [&] { return !running || !audioPackets_.empty(); });
+ if (!running) break;
+ packet = std::move(audioPackets_.front());
+ audioPackets_.pop_front();
+ }
+ pcm.clear();
+ if (audioDecoder.decode(packet.data(), packet.size(), pcm)) media::audioPush(pcm.data(), pcm.size() / 2);
+ if (first) {
+ first = false;
+ XC_LOGI("first audio packet decoded: %zu samples", pcm.size() / 2);
+ }
+ }
}
void videoLoop() {
@@ -65,19 +95,42 @@ struct StreamPlayer::Impl {
frames.pop_front();
backlog = frames.size();
}
+ if (dumpFile) {
+ // 4-byte little-endian length, then the access unit as received.
+ uint32_t n = static_cast<uint32_t>(au.size());
+ std::fwrite(&n, 4, 1, dumpFile);
+ std::fwrite(au.data(), 1, au.size(), dumpFile);
+ if (platform::nowMs() >= dumpUntilMs) {
+ std::fclose(dumpFile);
+ dumpFile = nullptr;
+ XC_LOGI("video dump complete");
+ }
+ }
media::Picture pic;
+ const bool first = decodedFrames == 0 && !loggedFirstDecode;
+ if (first) XC_LOGI("first video decode: %zu bytes", au.size());
bool ok = decoder.decode(au.data(), au.size(), pic);
+ if (first) {
+ loggedFirstDecode = true;
+ XC_LOGI("first video decode done: ok=%d", ok);
+ }
if (decoder.needsKeyframe()) keyframeWanted = true;
requestKeyframeIfWanted();
- if (!ok) continue;
+ if (!ok) {
+ ++decodeFailures;
+ continue;
+ }
++decodedFrames;
+ saveSnapshotIfAsked(pic);
if (backlog > 2) { // behind: skip drawing to catch up
++droppedFrames;
continue;
}
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);
display::present();
+ if (decodedFrames == 1) XC_LOGI("first frame presented");
}
}
@@ -87,10 +140,15 @@ struct StreamPlayer::Impl {
stream::StreamCallbacks cb;
cb.video = [this](const uint8_t* d, size_t n, uint32_t) {
- ++videoFrames;
+ if (n == 0) { // the depacketizer emits these after loss
+ keyframeWanted = true;
+ return;
+ }
+ if (++videoFrames == 1) XC_LOGI("first video frame received: %zu bytes", n);
std::lock_guard<std::mutex> lock(mutex);
if (frames.size() >= kMaxQueuedFrames) {
// Hopelessly behind: start over from the next key frame.
+ ++queueResets;
frames.clear();
keyframeWanted = true;
}
@@ -98,15 +156,21 @@ struct StreamPlayer::Impl {
cv.notify_one();
};
cb.audio = [this](const uint8_t* d, size_t n, uint32_t) {
- ++audioPackets;
- pcm.clear(); // audio callbacks come from a single thread
- if (audioDecoder.decode(d, n, pcm)) media::audioPush(pcm.data(), pcm.size() / 2);
+ if (++audioPackets == 1) XC_LOGI("first audio packet: %zu bytes", n);
+ std::lock_guard<std::mutex> lock(mutex);
+ if (audioPackets_.size() < 50) audioPackets_.emplace_back(d, d + n);
+ audioCv.notify_one();
};
cb.closed = [this](const std::string& reason) { end(reason); };
session = std::make_unique<stream::StreamSession>(gssv, cb);
running = true;
- videoThread = std::thread([this] { videoLoop(); });
+ if (!platform::startThread(videoThread, [this] { videoLoop(); }) ||
+ !platform::startThread(audioThread, [this] { audioLoop(); }, 1u << 20)) {
+ err = "could not start the media threads";
+ running = false;
+ return false;
+ }
if (!session->start(err)) {
end(err);
return false;
@@ -114,12 +178,39 @@ struct StreamPlayer::Impl {
return true;
}
+ void saveSnapshotIfAsked(const media::Picture& pic) {
+ std::string path;
+ {
+ std::lock_guard<std::mutex> lock(snapshotMutex);
+ path.swap(snapshotPath);
+ }
+ if (path.empty()) return;
+ int w = pic.width / 2, h = pic.height / 2;
+ std::vector<uint8_t> rgb(static_cast<size_t>(w) * h * 3);
+ for (int y = 0; y < h; ++y)
+ for (int x = 0; x < w; ++x) {
+ int c = (pic.y[(2 * y) * pic.strideY + 2 * x] - 16) * 1192;
+ int d = pic.u[y * pic.strideU + x] - 128;
+ int e = pic.v[y * pic.strideV + x] - 128;
+ auto clamp = [](int v) { return static_cast<uint8_t>(v < 0 ? 0 : v > 255 ? 255 : v); };
+ uint8_t* o = &rgb[(static_cast<size_t>(y) * w + x) * 3];
+ o[0] = clamp((c + 1836 * e + 512) >> 10);
+ o[1] = clamp((c - 218 * d - 546 * e + 512) >> 10);
+ o[2] = clamp((c + 2163 * d + 512) >> 10);
+ }
+ std::string data = "P6\n" + std::to_string(w) + " " + std::to_string(h) + "\n255\n";
+ data.append(reinterpret_cast<const char*>(rgb.data()), rgb.size());
+ bool ok = platform::writeFileAtomic(path, data);
+ XC_LOGI("snapshot %dx%d -> %s: %s", w, h, path.c_str(), ok ? "ok" : "failed");
+ }
+
// Video thread only (data channel sends are thread-safe).
void requestKeyframeIfWanted() {
uint64_t now = platform::nowMs();
if (keyframeWanted && now - lastKeyframeRequestMs > 500 && session) {
keyframeWanted = false;
lastKeyframeRequestMs = now;
+ ++keyframeRequests;
session->requestKeyframe();
}
}
@@ -132,6 +223,7 @@ struct StreamPlayer::Impl {
end("stopped");
if (session) session->close();
if (videoThread.joinable()) videoThread.join();
+ if (audioThread.joinable()) audioThread.join();
session.reset();
media::audioStop();
}
@@ -178,10 +270,34 @@ void StreamPlayer::sendInput(const input::ControllerState& p) {
}
void StreamPlayer::tick() { impl_->tick(); }
+
+void StreamPlayer::dumpVideo(const std::string& path, int seconds) {
+ // Before start(): only the video thread touches the file afterwards.
+ impl_->dumpFile = std::fopen(path.c_str(), "wb");
+ impl_->dumpUntilMs = platform::nowMs() + static_cast<uint64_t>(seconds) * 1000u;
+ XC_LOGI("dumping video to %s: %s", path.c_str(), impl_->dumpFile ? "ok" : "failed");
+}
+
+void StreamPlayer::requestSnapshot(const std::string& path) {
+ std::lock_guard<std::mutex> lock(impl_->snapshotMutex);
+ impl_->snapshotPath = path;
+}
void StreamPlayer::stop() { impl_->stop(); }
StreamPlayer::Stats StreamPlayer::stats() const {
- return {impl_->videoFrames, impl_->decodedFrames, impl_->droppedFrames, impl_->audioPackets};
+ Stats st;
+ st.videoFrames = impl_->videoFrames;
+ st.decodedFrames = impl_->decodedFrames;
+ st.droppedFrames = impl_->droppedFrames;
+ st.audioPackets = impl_->audioPackets;
+ st.decodeFailures = impl_->decodeFailures;
+ st.queueResets = impl_->queueResets;
+ st.keyframeRequests = impl_->keyframeRequests;
+ {
+ std::lock_guard<std::mutex> lock(impl_->mutex);
+ st.queued = impl_->frames.size();
+ }
+ return st;
}
} // namespace xc::app
diff --git a/src/app/stream_player.h b/src/app/stream_player.h
index e75a43f..1d7c1c6 100644
--- a/src/app/stream_player.h
+++ b/src/app/stream_player.h
@@ -25,9 +25,14 @@ public:
// Keepalives etc.; about once a second from the thread owning `gssv`.
void tick();
void stop();
+ // Appends every received access unit to `path` for `seconds` (diagnostics).
+ void dumpVideo(const std::string& path, int seconds);
+ // Writes the next decoded picture, half size, as a binary PPM.
+ void requestSnapshot(const std::string& path);
struct Stats {
uint64_t videoFrames = 0, decodedFrames = 0, droppedFrames = 0, audioPackets = 0;
+ uint64_t decodeFailures = 0, queueResets = 0, keyframeRequests = 0, queued = 0;
};
Stats stats() const;
diff --git a/src/display/display.cpp b/src/display/display.cpp
index 5095011..5758763 100644
--- a/src/display/display.cpp
+++ b/src/display/display.cpp
@@ -1,4 +1,5 @@
#include "display/display.h"
+#include "platform/platform.h"
#include "util/log.h"
#include <algorithm>
@@ -302,7 +303,10 @@ class TilePool {
public:
TilePool() {
unsigned n = std::max(1u, std::min(4u, std::thread::hardware_concurrency() / 2));
- for (unsigned i = 0; i < n; ++i) workers_.emplace_back([this, i, n] { loop(i, n); });
+ for (unsigned i = 0; i < n; ++i) {
+ workers_.emplace_back();
+ platform::startThread(workers_.back(), [this, i, n] { loop(i, n); }, 256u << 10);
+ }
}
void run(const YuvJob& job) {
{
@@ -334,7 +338,7 @@ private:
}
}
- std::vector<std::thread> workers_;
+ std::vector<platform::Thread> workers_;
std::mutex m_;
std::condition_variable cv_, done_;
const YuvJob* job_ = nullptr;
diff --git a/src/media/decoder.cpp b/src/media/decoder.cpp
index 4ff1855..2c551a3 100644
--- a/src/media/decoder.cpp
+++ b/src/media/decoder.cpp
@@ -5,10 +5,17 @@
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/channel_layout.h>
+#include <libavutil/cpu.h>
+#include <libavutil/log.h>
#include <libavutil/error.h>
}
#include <algorithm>
+#include <cstdarg>
+#include <cstdio>
+#include <cstring>
+#include <atomic>
+#include <mutex>
#include <string>
namespace xc::media {
@@ -21,6 +28,28 @@ std::string averr(int rc) {
return buf;
}
+// FFmpeg's default log callback probes the terminal (isatty, getenv) and
+// writes to stderr, which the console's sandbox does not support: route its
+// messages to our log instead.
+void ffmpegLog(void*, int level, const char* fmt, va_list ap) {
+ if (level > AV_LOG_WARNING) return;
+ char line[512];
+ std::vsnprintf(line, sizeof line, fmt, ap);
+ size_t n = std::strlen(line);
+ while (n && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = 0;
+ // The first messages at info level (diagnostics), the rest at debug.
+ static std::atomic<int> shown{0};
+ if (shown++ < 40)
+ XC_LOGI("ffmpeg: %s", line);
+ else
+ XC_LOGD("ffmpeg: %s", line);
+}
+
+void installLogCallback() {
+ static std::once_flag once;
+ std::call_once(once, [] { av_log_set_callback(ffmpegLog); });
+}
+
void freeAll(AVCodecContext*& ctx, AVFrame*& frame, AVPacket*& packet) {
avcodec_free_context(&ctx);
av_frame_free(&frame);
@@ -29,11 +58,40 @@ void freeAll(AVCodecContext*& ctx, AVFrame*& frame, AVPacket*& packet) {
} // namespace
+std::vector<std::pair<size_t, size_t>> splitAccessUnits(const uint8_t* data, size_t size) {
+ std::vector<std::pair<size_t, size_t>> aus;
+ size_t start = SIZE_MAX;
+ int prevType = -1;
+ for (size_t i = 0; i + 4 < size; ++i) {
+ if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) {
+ int type = data[i + 3] & 0x1f;
+ size_t sc = (i > 0 && data[i - 1] == 0) ? i - 1 : i;
+ bool boundary = type == 9 || (type == 7 && prevType != 9) ||
+ ((type == 1 || type == 5) && prevType != 7 && prevType != 8 && prevType != 9 &&
+ prevType != 6 && (data[i + 4] & 0x80));
+ if (boundary) {
+ if (start != SIZE_MAX) aus.emplace_back(start, sc - start);
+ start = sc;
+ }
+ prevType = type;
+ i += 3;
+ }
+ }
+ if (start != SIZE_MAX) aus.emplace_back(start, size - start);
+ return aus;
+}
+
+void disableSimd() {
+ av_force_cpu_flags(0);
+ XC_LOGW("FFmpeg SIMD disabled (cpu flags 0)");
+}
+
// --- Video --------------------------------------------------------------------
VideoDecoder::~VideoDecoder() { freeAll(ctx_, frame_, packet_); }
bool VideoDecoder::init(int threads) {
+ installLogCallback();
const AVCodec* codec = avcodec_find_decoder(AV_CODEC_ID_H264);
if (!codec) {
XC_LOGE("no H.264 decoder in this FFmpeg build");
@@ -47,6 +105,7 @@ bool VideoDecoder::init(int threads) {
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());
int rc = avcodec_open2(ctx_, codec, nullptr);
if (rc < 0) {
XC_LOGE("avcodec_open2(h264): %s", averr(rc).c_str());
@@ -56,18 +115,29 @@ bool VideoDecoder::init(int threads) {
}
bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out) {
- if (!ctx_) return false;
+ // 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.
+ if (!ctx_ || len == 0) return false;
packet_->data = const_cast<uint8_t*>(data);
packet_->size = static_cast<int>(len);
int rc = avcodec_send_packet(ctx_, packet_);
+ if (rc == AVERROR_EOF) {
+ // Drained anyway: reset and retry once.
+ avcodec_flush_buffers(ctx_);
+ rc = avcodec_send_packet(ctx_, packet_);
+ }
if (rc < 0 && rc != AVERROR(EAGAIN)) {
needsKeyframe_ = true;
- XC_LOGD("h264 send: %s", averr(rc).c_str());
+ if (failuresLogged_++ < 20) XC_LOGI("h264 send failed: %s (%zu bytes)", averr(rc).c_str(), len);
return false;
}
+ int sent = rc;
rc = avcodec_receive_frame(ctx_, frame_);
if (rc < 0) {
if (rc != AVERROR(EAGAIN)) 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);
return false;
}
if (frame_->decode_error_flags || (frame_->flags & AV_FRAME_FLAG_CORRUPT)) {
@@ -95,6 +165,7 @@ bool VideoDecoder::decode(const uint8_t* data, size_t len, Picture& out) {
AudioDecoder::~AudioDecoder() { freeAll(ctx_, frame_, packet_); }
bool AudioDecoder::init() {
+ installLogCallback();
const AVCodec* codec = avcodec_find_decoder(AV_CODEC_ID_OPUS);
if (!codec) {
XC_LOGE("no Opus decoder in this FFmpeg build");
diff --git a/src/media/decoder.h b/src/media/decoder.h
index 893bb1f..258efda 100644
--- a/src/media/decoder.h
+++ b/src/media/decoder.h
@@ -3,6 +3,7 @@
#include <cstddef>
#include <cstdint>
+#include <utility>
#include <vector>
struct AVCodecContext;
@@ -21,6 +22,13 @@ struct Picture {
int width = 0, height = 0;
};
+// Splits an Annex-B H.264 stream into access units (offset, length): at AUD
+// or SPS NALs and at first slices not preceded by parameter sets/SEI.
+std::vector<std::pair<size_t, size_t>> splitAccessUnits(const uint8_t* data, size_t size);
+
+// Restricts FFmpeg to plain C code paths (diagnostics); call before init().
+void disableSimd();
+
class VideoDecoder {
public:
VideoDecoder() = default;
@@ -42,6 +50,7 @@ private:
AVFrame* frame_ = nullptr;
AVPacket* packet_ = nullptr;
bool needsKeyframe_ = true;
+ int failuresLogged_ = 0;
};
class AudioDecoder {
diff --git a/src/platform/host/platform_host.cpp b/src/platform/host/platform_host.cpp
index b703570..3ce6353 100644
--- a/src/platform/host/platform_host.cpp
+++ b/src/platform/host/platform_host.cpp
@@ -76,6 +76,8 @@ bool resolveIPv4(const std::string& host, uint32_t& addr, std::string& err) {
return true;
}
+void probeNetworking() {}
+
void notify(const std::string& text) { std::printf("\n>>> %s\n\n", text.c_str()); }
} // namespace xc::platform
diff --git a/src/platform/platform.h b/src/platform/platform.h
index dd70673..34b6960 100644
--- a/src/platform/platform.h
+++ b/src/platform/platform.h
@@ -5,6 +5,7 @@
#include <cstddef>
#include <cstdint>
+#include <functional>
#include <string>
namespace xc::platform {
@@ -27,6 +28,18 @@ bool resolveIPv4(const std::string& host, uint32_t& addr, std::string& err);
uint64_t nowMs(); // monotonic
void sleepMs(uint32_t ms);
+// Logs which socket operations work (PS5 diagnostics; no-op on the host).
+void probeNetworking();
+
+// Starts a joinable thread with an explicit stack size (the console's default
+// thread stack is too small for the H.264 decoder). Returns false on failure.
+struct Thread {
+ void* handle = nullptr;
+ bool joinable() const { return handle != nullptr; }
+ void join();
+};
+bool startThread(Thread& t, std::function<void()> fn, size_t stackBytes = 8u << 20);
+
// Short on-screen message (PS5 system notification / host stdout).
void notify(const std::string& text);
diff --git a/src/platform/posix_common.cpp b/src/platform/posix_common.cpp
index f3bc9a5..52d55c3 100644
--- a/src/platform/posix_common.cpp
+++ b/src/platform/posix_common.cpp
@@ -2,6 +2,7 @@
#include "platform/platform.h"
#include <cstdio>
+#include <pthread.h>
#include <time.h>
#include <unistd.h>
@@ -38,6 +39,40 @@ uint64_t nowMs() {
return static_cast<uint64_t>(ts.tv_sec) * 1000u + static_cast<uint64_t>(ts.tv_nsec) / 1000000u;
}
+namespace {
+void* threadEntry(void* arg) {
+ auto* fn = static_cast<std::function<void()>*>(arg);
+ (*fn)();
+ delete fn;
+ return nullptr;
+}
+} // namespace
+
+bool startThread(Thread& t, std::function<void()> fn, size_t stackBytes) {
+ pthread_attr_t attr;
+ pthread_attr_init(&attr);
+ pthread_attr_setstacksize(&attr, stackBytes);
+ auto* heap = new std::function<void()>(std::move(fn));
+ auto* tid = new pthread_t;
+ int rc = pthread_create(tid, &attr, threadEntry, heap);
+ pthread_attr_destroy(&attr);
+ if (rc != 0) {
+ delete heap;
+ delete tid;
+ return false;
+ }
+ t.handle = tid;
+ return true;
+}
+
+void Thread::join() {
+ if (!handle) return;
+ auto* tid = static_cast<pthread_t*>(handle);
+ pthread_join(*tid, nullptr);
+ delete tid;
+ handle = nullptr;
+}
+
void sleepMs(uint32_t ms) { usleep(static_cast<useconds_t>(ms) * 1000u); }
} // namespace xc::platform
diff --git a/src/platform/ps5/libc_compat.c b/src/platform/ps5/libc_compat.c
index d8a8c2b..49d465f 100644
--- a/src/platform/ps5/libc_compat.c
+++ b/src/platform/ps5/libc_compat.c
@@ -149,3 +149,23 @@ int getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host, size_t h
if (serv && servlen) snprintf(serv, servlen, "%d", port);
return 0;
}
+
+/* --- Non-blocking sockets (see ps5/compat/ps5_lfs.h) ------------------------ */
+#include <sys/ioctl.h>
+#undef ioctl
+/* sys/ioctl.h declared it as xc_ioctl (the forced compat header). */
+int ioctl(int fd, unsigned long request, ...);
+
+#define XC_SO_NBIO 0x1200
+
+int xc_ioctl(int fd, unsigned long request, ...) {
+ va_list ap;
+ va_start(ap, request);
+ void *arg = va_arg(ap, void *);
+ va_end(ap);
+ if (request == FIONBIO && arg) {
+ int on = *(const int *)arg ? 1 : 0;
+ if (setsockopt(fd, SOL_SOCKET, XC_SO_NBIO, &on, sizeof on) == 0) return 0;
+ }
+ return ioctl(fd, request, arg);
+}
diff --git a/src/platform/ps5/net_probe.cpp b/src/platform/ps5/net_probe.cpp
new file mode 100644
index 0000000..231a9b1
--- /dev/null
+++ b/src/platform/ps5/net_probe.cpp
@@ -0,0 +1,96 @@
+// Logs which socket operations the app sandbox allows (autoplay runs only):
+// the WebRTC stack (libjuice) needs non-blocking UDP, pipes and poll.
+#include "util/log.h"
+
+#include <arpa/inet.h>
+#include <cerrno>
+#include <cstring>
+#include <fcntl.h>
+#include <ifaddrs.h>
+#include <netinet/in.h>
+#include <poll.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+namespace xc::platform {
+
+void probeNetworking() {
+ auto res = [](const char* what, int rc) { XC_LOGI("probe %-28s rc=%d errno=%d", what, rc, rc < 0 ? errno : 0); };
+
+ int s = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ res("socket(UDP)", s);
+ if (s >= 0) {
+ int one = 1;
+ errno = 0;
+ res("ioctl(FIONBIO)", ::ioctl(s, FIONBIO, &one));
+ errno = 0;
+ int fl = ::fcntl(s, F_GETFL, 0);
+ res("fcntl(F_GETFL)", fl);
+ errno = 0;
+ res("fcntl(F_SETFL,O_NONBLOCK)", ::fcntl(s, F_SETFL, (fl < 0 ? 0 : fl) | O_NONBLOCK));
+ errno = 0;
+ res("setsockopt(SO_NBIO 0x1200)", ::setsockopt(s, SOL_SOCKET, 0x1200, &one, sizeof one));
+ int buf = 1 << 20;
+ errno = 0;
+ res("setsockopt(SO_RCVBUF)", ::setsockopt(s, SOL_SOCKET, SO_RCVBUF, &buf, sizeof buf));
+ sockaddr_in a{};
+ a.sin_len = sizeof a;
+ a.sin_family = AF_INET;
+ errno = 0;
+ res("bind(0.0.0.0:0)", ::bind(s, reinterpret_cast<sockaddr*>(&a), sizeof a));
+ socklen_t len = sizeof a;
+ errno = 0;
+ res("getsockname", ::getsockname(s, reinterpret_cast<sockaddr*>(&a), &len));
+ XC_LOGI("probe bound port %u", ntohs(a.sin_port));
+ char tmp[1];
+ errno = 0;
+ res("recvfrom (nonblocking?)", static_cast<int>(::recvfrom(s, tmp, 1, MSG_DONTWAIT, nullptr, nullptr)));
+ sockaddr_in dst{};
+ dst.sin_len = sizeof dst;
+ dst.sin_family = AF_INET;
+ dst.sin_port = htons(3478);
+ ::inet_pton(AF_INET, "20.0.0.1", &dst.sin_addr);
+ errno = 0;
+ res("sendto", static_cast<int>(::sendto(s, "x", 1, 0, reinterpret_cast<sockaddr*>(&dst), sizeof dst)));
+ pollfd p{s, POLLIN, 0};
+ errno = 0;
+ res("poll(udp, 10ms)", ::poll(&p, 1, 10));
+ ::close(s);
+ }
+
+ int fds[2] = {-1, -1};
+ errno = 0;
+ res("pipe", ::pipe(fds));
+ if (fds[0] >= 0) {
+ errno = 0;
+ res("fcntl(pipe,O_NONBLOCK)", ::fcntl(fds[0], F_SETFL, O_NONBLOCK));
+ errno = 0;
+ res("write(pipe)", static_cast<int>(::write(fds[1], "x", 1)));
+ pollfd p{fds[0], POLLIN, 0};
+ errno = 0;
+ res("poll(pipe)", ::poll(&p, 1, 10));
+ ::close(fds[0]);
+ ::close(fds[1]);
+ }
+ int sp[2] = {-1, -1};
+ errno = 0;
+ res("socketpair(AF_UNIX,DGRAM)", ::socketpair(AF_UNIX, SOCK_DGRAM, 0, sp));
+ if (sp[0] >= 0) {
+ ::close(sp[0]);
+ ::close(sp[1]);
+ }
+
+ ifaddrs* ifa = nullptr;
+ errno = 0;
+ res("getifaddrs", ::getifaddrs(&ifa));
+ for (ifaddrs* i = ifa; i; i = i->ifa_next) {
+ if (!i->ifa_addr || i->ifa_addr->sa_family != AF_INET) continue;
+ char ip[32];
+ ::inet_ntop(AF_INET, &reinterpret_cast<sockaddr_in*>(i->ifa_addr)->sin_addr, ip, sizeof ip);
+ XC_LOGI("probe interface %s %s", i->ifa_name, ip);
+ }
+ if (ifa) ::freeifaddrs(ifa);
+}
+
+} // namespace xc::platform
diff --git a/tools/ps5/autotest.sh b/tools/ps5/autotest.sh
new file mode 100755
index 0000000..45b1697
--- /dev/null
+++ b/tools/ps5/autotest.sh
@@ -0,0 +1,97 @@
+#!/usr/bin/env bash
+# One unattended console run: build, deploy, launch in autoplay mode, wait for
+# the result, close the app and fetch its log (and frame.ppm when present).
+#
+# PS5_HOST=<ip> tools/ps5/autotest.sh [titleId] [seconds] [option]
+# (option: nosimd = FFmpeg without SIMD; output in build-ps5/autotest)
+#
+# Needs PS5_Vulkan's ps5vkctl payload running on the console (launch/kill).
+set -euo pipefail
+
+root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
+vk=${PS5_VULKAN:-$(cd "$root/../../WoW-PS5/deps/PS5_Vulkan" && pwd)}
+title_id=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["titleId"])' "$root/ps5/sce_sys/param.json")
+game=${1:-BALATRO}
+seconds=${2:-45}
+out=$root/build-ps5/autotest
+option=${3:-} # e.g. nosimd
+: "${PS5_HOST:?set PS5_HOST to the console IP}"
+export PS5_HOST
+ctl() { (cd "$vk" && python3 tools/ps5_console.py "$@"); }
+
+mkdir -p "$out"
+rm -f "$out"/frame*.ppm "$out"/xcloud.log "$out"/stream.aus
+ninja -C "$root/build-ps5" xcloud_app >/dev/null
+bash "$root/tools/ps5/link.sh" "$root/build-ps5" | tail -1
+bash "$root/tools/ps5/package.sh" "$root/build-ps5" >/dev/null
+
+ctl kill "$title_id" >/dev/null 2>&1 || true
+sleep 2
+python3 "$vk/tools/deploy-title-folder.py" "$root/build-ps5/pkg/$title_id" | tail -1
+
+# Fresh log, the autoplay request, no stale frame.
+python3 - "$PS5_HOST" "${FTP_PORT:-2121}" "/data/homebrew/$title_id" "$game $seconds $option" <<'PY'
+import io, sys
+from ftplib import FTP, error_perm, error_reply
+host, port, d, line = sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4]
+f = FTP(); f.connect(host, port, timeout=15); f.login(); f.cwd(d)
+for name in ("xcloud.log", "frame.ppm", "frame2.ppm", "stream.aus"):
+ try: f.sendcmd(f"DELE {name}")
+ except (error_perm, error_reply): pass
+f.storbinary("STOR autoplay.txt", io.BytesIO(line.encode() + b"\n"))
+import os
+sample = os.environ.get("XC_SAMPLE")
+if line.startswith("BENCH") and sample:
+ with open(sample, "rb") as src: f.storbinary("STOR sample.h264", src)
+f.quit()
+PY
+
+ctl launch "$title_id" | tail -1
+deadline=$(( $(date +%s) + seconds + 180 ))
+fetch() {
+ python3 - "$PS5_HOST" "${FTP_PORT:-2121}" "/data/homebrew/$title_id" "$out" "$@" <<'PY'
+import os, sys
+from ftplib import FTP, error_perm
+host, port, d, out, names = sys.argv[1], int(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5:]
+f = FTP(); f.connect(host, port, timeout=15); f.login(); f.cwd(d)
+for name in names:
+ try:
+ with open(os.path.join(out, name + ".part"), "wb") as o: f.retrbinary(f"RETR {name}", o.write)
+ os.replace(os.path.join(out, name + ".part"), os.path.join(out, name))
+ except error_perm:
+ try: os.remove(os.path.join(out, name + ".part"))
+ except FileNotFoundError: pass
+f.quit()
+PY
+}
+result=timeout
+while (( $(date +%s) < deadline )); do
+ sleep 5
+ fetch xcloud.log || continue
+ if grep -q "AUTOPLAY END" "$out/xcloud.log" 2>/dev/null; then result=finished; break; fi
+ # The process is gone without finishing: a crash.
+ if ! ctl payload 2>/dev/null | grep -q "$title_id"; then
+ status=$( (cd "$vk" && python3 - <<'PY'
+import socket, os
+s = socket.create_connection((os.environ["PS5_HOST"], 9111), timeout=5)
+s.sendall(b"status\n"); print(s.recv(4096).decode(errors="replace").strip())
+PY
+) 2>/dev/null || true)
+ if [[ $status != *"$title_id"* ]]; then result=crashed; break; fi
+ fi
+done
+fetch xcloud.log frame.ppm frame2.ppm stream.aus || true
+ctl kill "$title_id" >/dev/null 2>&1 || true
+# Remove the request so a manual launch behaves normally.
+python3 - "$PS5_HOST" "${FTP_PORT:-2121}" "/data/homebrew/$title_id" <<'PY'
+import sys
+from ftplib import FTP, error_perm, error_reply
+f = FTP(); f.connect(sys.argv[1], int(sys.argv[2]), timeout=15); f.login(); f.cwd(sys.argv[3])
+try: f.sendcmd("DELE autoplay.txt")
+except (error_perm, error_reply): pass
+f.quit()
+PY
+echo "RESULT: $result"
+rm -f "$out"/frame*.png
+for f in "$out"/frame*.ppm; do [[ -f $f ]] && echo "frame: $f"; done
+echo "log: $out/xcloud.log"