Xbox Cloud Gaming app for PS5 Homebrew
C
release: v1.5.5 - multiplatform stability, instant boot, and bugfixes
Rafael Abud Ferreira977d8298bcdb
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 5a51dc2..06573e8 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 1.5.4 LANGUAGES C CXX)+project(xcloud_ps5 VERSION 1.5.5 LANGUAGES C CXX)set(CMAKE_CXX_STANDARD 20)set(CMAKE_CXX_STANDARD_REQUIRED ON)diff --git a/ROADMAP.md b/ROADMAP.mdindex 5e4b619..b1f6312 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -4,32 +4,37 @@ Planejamento e visão de futuro do projeto **PSBox Cloud Gaming**, priorizado poStatus: **Em andamento (next)**, **Planejado (planned)**, **Futuro (later)**, **Descartado (dropped)**.-> **Última atualização:** 26/10/2026 (após lançamento da versão estável **v1.5.4**).+> **Última atualização:** 30/10/2026 (release estável **v1.5.5** / ecossistema multi-plataforma).---## 🐛 Bugs Prioritários & Correções Imediatas (High-Priority Fixes)-### 1. Falso Positivo de "46 Novos Jogos" & Otimização do Tempo de Splash Screen — *next*-- **Sintoma Atual**: A aplicação exibe recorrentemente em cada boot a notificação de debug *"Biblioteca atualizada (46 novos jogos)"* (falso positivo na sincronização diferencial `syncDelta`), mantendo o usuário retido na Splash Screen durante todo o bloqueio de rede até que a verificação remota termine e essa notificação seja emitida.-- **Requisitos & Estratégia de Solução**:- - **Preservação Mandatória da Splash Screen**: A tela de Splash **NÃO PODE** ser excluída ou desativada; ela deve permanecer ativa para garantir inicialização limpa e segura do ecossistema.- - **Persistência de Títulos no Cache Local**: Guardar o conjunto de IDs/produtos já conhecidos em cache persistente (`library_cache.json`), garantindo que o contador diferencial reflita apenas adições genuinamente novas ao catálogo do Xbox Cloud.- - **Fim da Retenção no Boot**: Falsos positivos não devem impedir nem atrasar a transição de login para a tela inicial (`showHome()`). O carregamento inicial da UI deve utilizar o cache persistente com entrada instantânea, realizando a validação de novos títulos em segundo plano sem travar o usuário no splash.+### 1. Falso Positivo de "46 Novos Jogos" & Otimização do Tempo de Splash Screen — *done (v1.5.5)*+- **Sintoma Resolvido**: Notificação repetida de "46 novos jogos" e retenção desnecessária do usuário na tela de splash foram completamente eliminadas.+- **Implementação**:+ - Persistência integral de todos os produtos resolvidos do catálogo em `library_cache.json` e rastreamento de `knownProducts_`.+ - Liberação instantânea da Splash Screen (`showHome()`) imediatamente após o login, executando o `syncDelta()` de forma não-bloqueante em background com spinner discreto.+ - Cálculo de `newCount` restrito estritamente a novos jogos que ingressaram no Game Pass em relação aos conhecidos no cache anterior.-### 2. Cursor do Mouse Duplicado na Build Desktop — *next*-- **Sintoma Atual**: Na versão Desktop (`psbox` para Linux / Steam Deck / Windows), tanto o cursor de hardware do sistema operacional gerenciado pelo SDL3 quanto o cursor vetorial de software desenhado pela interface (`AppUi::renderSoftwareCursor`) aparecem simultaneamente, causando a exibição de dois cursores de mouse sobrepostos na tela.-- **Solução**: Ocultar o cursor nativo do sistema operacional (`SDL_HideCursor()`) na inicialização do backend desktop ou desativar o cursor duplicado com base nas capacidades de janela do ambiente (`shell::caps().window`).+### 2. Cursor do Mouse Duplicado na Build Desktop — *done (v1.5.5)*+- **Sintoma Resolvido**: Exibição simultânea do cursor do sistema operacional e do cursor vetorial de software corrigida no Linux / Steam Deck / Windows.+- **Implementação**: Ocultação do cursor de hardware do SO via `SDL_HideCursor()` na inicialização da janela em `shell_desktop.cpp`.++### 3. Falha na Atualização Automática do Catálogo do Xbox Game Pass (Exige Refresh Manual) — *done (v1.5.5)*+- **Sintoma Resolvido**: Estantes de catálogo ("Novidades", "Mais populares", etc.) agora atualizam automaticamente no boot sem intervenção manual.+- **Implementação**: O `syncDelta()` consulta e sincroniza automaticamente os feeds SIGL atualizados (`kRecentlyAdded`, `kMostPopular`, `kFreeToPlay`, `kLeavingSoon`) e refresca as linhas correspondentes em `layout_`.---## 🚀 Em Andamento e Próximos Passos (Now & Next)-### 1. Port Nativo para PlayStation 4 (PSBox Cloud Gaming - PS4) — *next*+### 1. Port Nativo para PlayStation 4 (PSBox Cloud Gaming - PS4) — *done (v1.5.5)*Port dedicado e otimizado para consoles PlayStation 4 com jailbreak (firmwares 9.00 / 11.00):-- **Pacote e Identidade Isolados**: Pacote PKG independente (`CUSA99810.pkg`) com `TitleID` próprio, evitando qualquer interferência ou colisão com a versão de PS5 (`PPSA99810`).-- **Conectividade WebRTC**: Stack ICE, STUN e handshake DTLS adaptados com compatibilidade FreeBSD/Orbis libc++ (`ETIMEDOUT=60`), handshake de certificados MbedTLS e resolução de SCTP para canais de controle.-- **Pipeline de Vídeo e Áudio**: Decodificação H.264 por hardware via `libSceVideoDec` / decodificador FFmpeg e renderização Vulkan via libpiglet / GNM.+- **Pacote e Identidade Isolados**: Pacote PKG independente (`PSBX00001.pkg`) com `TitleID` próprio, evitando qualquer interferência ou colisão com a versão de PS5 (`PPSA99810`).+- **Conectividade WebRTC**: Stack ICE, STUN e handshake DTLS adaptados com compatibilidade FreeBSD/Orbis libc++ (`ETIMEDOUT=60`), handshake de certificados MbedTLS e canais de dados SCTP.+- **Pipeline de Vídeo e Áudio**: Decodificação H.264 por hardware via `libSceVideodec2` em Direct Memory Onion/Garlic, renderizador 2D por software com 4 threads SIMD SSE4.2 (cópia zero de overlay via `shared_ptr`) e saída de áudio DMA com dreno limpo.+- **Controles e Periféricos**: Suporte completo ao DualShock 4 com rumble de motores duplos, lightbar, touchpad e giroscópio.### 2. Suporte Nativo a Controles USB no PS5 (8BitDo 2.4G, Xbox, DS4, Fightsticks) — *next*Leitura direta de nós USB HID e interrupção no kernel do PS5 (`/dev/uhid*`, `/dev/ugen*`), contornando a whitelist restritiva da `libScePad` da Sony que exige coprocessadores criptográficos proprietários:@@ -47,14 +52,32 @@ Expansão do servidor local integrado (porta 8080) para multiplayer cooperativo## 📋 Planejado para o Futuro (Planned & Later)-### 4. Presença Visual e Banners em Lojas (RecompStore & Prospero Store) — *planned*+### 1. Sincronização de Conquistas Xbox para Troféus PlayStation (PS5/PS4) — *planned*+Espelhamento contínuo das conquistas obtidas no Xbox Cloud Gaming para o subsistema local de troféus da conta PlayStation:+- **Loop de Monitoramento Ativo (`worker_stream.cpp`)**: A cada 20 segundos de gameplay ativo, consulta a API Xbox Live (`fetchTitleAchievements(xboxTitleId, xuid)`) e compara os status com snapshot mantido em disco e memória.+- **Mapeamento de Gamerscore para Graus de Troféus**:+ - `5G` a `15G` ──► Troféu **Bronze**+ - `20G` a `45G` ──► Troféu **Prata**+ - `50G` a `100G` ──► Troféu **Ouro**+ - `100% dos Achievements` do jogo obtidos ──► Troféu **Platina**+- **HUD & Notificação em Tempo Real**: Banner translúcido animado exibido no topo da tela com o ícone original da conquista, nome, descrição, pontuação Gamerscore e reprodução do áudio característico de desbloqueio de troféu.+- **Integração com Subsistema Local PlayStation**: Gravação dos registros no banco local do console (`/user/home/<id>/trophy/db/trophy_local.db`) ou chamadas `sceNpTrophy` no console desbloqueado.+- **Retro-Sincronização (Back-Sync)**: Botão dedicado na tela de detalhes do título para sincronizar retroativamente todas as conquistas já obtidas na conta para a base de troféus do console.++### 2. Auto-Update para PlayStation 4 via GoldHEN Package Installer API — *planned*+Superar a limitação de partição somente-leitura (`/user/app/`) do Orbis OS permitindo atualizações diretas no PS4 sem depender de pendrive ou computador:+- **Download em Background**: Ao detectar uma release nova, o app baixa o `PSBX00001.pkg` oficial do GitHub diretamente para o disco interno (`/data/pkg/PSBX00001.pkg`).+- **Integração com API Local do GoldHEN**: Envio de comando HTTP para o serviço integrado do GoldHEN (`http://127.0.0.1:12800/api/install`), instruindo o daemon a instalar a atualização em segundo plano.+- **Encerramento Limpo**: Fechamento do app para que o instalador do sistema conclua o update do FPKG sem conflito de arquivos em uso.++### 3. Presença Visual e Banners em Lojas (RecompStore & Prospero Store) — *planned*- Atualização do catálogo oficial com as artes em alta definição (512x512 Icon, 1080p/4K Hero Banners e screenshots oficiais de jogos como *Halo Infinite* e *Fortnite*).- Manutenção contínua de metadados, links de releases assinadas e sincronização de atualizações automáticas via API.-### 5. Atalhos Diretos na Tela Inicial do PS5 (Home-Screen Forwarders) — *later*+### 4. Atalhos Diretos na Tela Inicial do PS5 (Home-Screen Forwarders) — *later*- Criação de atalhos individuais na dashboard principal do PS5 para iniciar títulos específicos em nuvem diretamente, utilizando o formato ProsperoLight forwarder.-### 6. Acompanhamento de Quota Mensal de Nuvem — *later*+### 5. Acompanhamento de Quota Mensal de Nuvem — *later*- Suporte no cliente já implementado (`AuthManager::fetchPlaytimeLimit`); aguardando ativação oficial das quotas mensais pela Microsoft para exibir tempo restante no perfil.---@@ -74,7 +97,12 @@ Expansão do servidor local integrado (porta 8080) para multiplayer cooperativoPara o histórico completo e detalhado de todas as versões anteriores (v0.3.0 até v1.4.0), consulte as [Releases Oficiais no GitHub](https://github.com/RafaelNGP/xbox-cloud-gaming-ps5/releases).-- **v1.5.4** *(Atual)*:+- **v1.5.5** *(Atual)*:+ - **Eliminação do Falso Positivo de "46 Novos Jogos" & Boot Instantâneo**: Persistência integral de todos os produtos do catálogo em `library_cache.json` (`knownProducts_`), cálculo estrito de adições reais ao catálogo e liberação imediata da Splash Screen (`showHome()`) com sincronização diferencial não-bloqueante em segundo plano.+ - **Cursor do Mouse sem Duplicação no Desktop**: Chamada a `SDL_HideCursor()` no backend SDL3, ocultando o cursor de hardware nativo do sistema operacional e preservando exclusivamente o cursor vetorial suave da interface.+ - **Atualização Automática de Estantes do Game Pass**: Sincronização em segundo plano dos feeds SIGL ("Novidades", "Mais populares", "Streaming gratuito", "Saindo em breve") no `syncDelta` sem necessidade de refresh manual (<kbd>L3</kbd>).+ - **Port Nativo PlayStation 4 Consolidado (`PSBX00001`)**: Decodificação por hardware via `libSceVideodec2`, composição 2D por software multithread SIMD SSE4.2 (cópia zero de overlay), suporte completo a DualShock 4 e empacotamento PKG oficial assinado.+- **v1.5.4**:- Suporte completo a mouse e navegação vetorial no PS5 e Desktop.- Fast-paths no renderizador 2D (cópia direta de scanlines e batch fill para texturas opacas).- Cache de fontes UTF-8 e glifos sem contenção de mutexes em $O(1)$.diff --git a/ps5/sce_sys/param.json b/ps5/sce_sys/param.jsonindex 04ef0c8..4ffd492 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": "01.504.000",+ "contentVersion": "01.505.000","downloadDataSize": 256,"gameIntent": {"permittedIntents": [diff --git a/src/app/app_core.cpp b/src/app/app_core.cppindex 1c32d0f..3027c8f 100644--- a/src/app/app_core.cpp+++ b/src/app/app_core.cpp@@ -241,10 +241,10 @@ ui::UiCaps uiCaps() {c.adaptiveTriggers = pc.adaptiveTriggers;c.gyro = pc.gyro;c.touchpad = pc.touchpad;- c.upscalers = sc.console || dc.upscalers;- c.sharpen = sc.console || dc.sharpen;- c.deband = sc.console || dc.deband;- c.highRefresh = sc.console || dc.highRefreshSwitch;+ c.upscalers = dc.upscalers;+ c.sharpen = dc.sharpen;+ c.deband = dc.deband;+ c.highRefresh = dc.highRefreshSwitch;c.console = sc.console;c.openUrl = sc.openUrl;c.selfUpdate = sc.selfUpdate;@@ -315,9 +315,7 @@ bool coreStartup() {bool ok = fonts.loadIcons(shell::iconFontPaths());XC_LOGI("system icon font: %s", ok ? "loaded" : "not found (drawn icons)");}- const size_t imageBudget = (platform::platformName().find("PlayStation 4") != std::string::npos)- ? (48u << 20)- : (160u << 20);+ const size_t imageBudget = platform::imageCacheBudget();g_images = std::make_unique<ui::ImageCache>([] {if (g_ui) g_ui->invalidate();diff --git a/src/app/autoplay.cpp b/src/app/autoplay.cppindex da19dec..81e65a3 100644--- a/src/app/autoplay.cpp+++ b/src/app/autoplay.cpp@@ -1122,7 +1122,9 @@ void autoplayScreens(const ui::Canvas& canvas, uint64_t now) {errorSince = 1;}}- if (g_ui->reportOpen() && !g_autoplay.crashTest && !g_autoplay.reportTest) {+ static bool dismissedBootCrash = false;+ if (g_ui->reportOpen() && !g_autoplay.crashTest && !g_autoplay.reportTest && !dismissedBootCrash && !uiSaved) {+ dismissedBootCrash = true;ui::NavInput in{};in.back = true;g_ui->handle(in);diff --git a/src/app/library.cpp b/src/app/library.cppindex a47db39..97797f3 100644--- a/src/app/library.cpp+++ b/src/app/library.cpp@@ -677,7 +677,9 @@ bool Library::loadCache(bool withLayout) {// still shown, so the lists stay whole, and fetched again in this one.bool sameLanguage = (*j)["language"].str() == language_;for (const auto& [pid, title] : (*j)["cloudTitles"].members()) cloudTitleOf_[pid] = title.str();- for (const auto& [id, v] : (*j)["products"].members())+ knownProducts_.clear();+ for (const auto& [id, v] : (*j)["products"].members()) {+ if (!id.empty()) knownProducts_.insert(id);if (!products_.count(id)) {products_[id] = productFromJson(id, v);if (products_[id].xcloudTitleId.empty() || products_[id].xcloudTitleId == "None") {@@ -686,6 +688,10 @@ bool Library::loadCache(bool withLayout) {}if (!sameLanguage) otherLanguage_.insert(id);}+ }+ for (const auto& p : (*j)["knownProducts"].items()) {+ if (!p.str().empty()) knownProducts_.insert(p.str());+ }for (const auto& [id, code] : (*j)["platforms"].members()) platform_[id] = code.str();for (const auto& [pid, xbox] : (*j)["xboxTitles"].members()) xboxTitleOf_[pid] = xbox.str();for (const auto& id : (*j)["freeInStore"].items()) freeInStore_.insert(id.str());@@ -740,6 +746,21 @@ bool Library::loadCache(bool withLayout) {r.badges = rowObj["badges"].asBool(true);r.isGrid = rowObj["isGrid"].asBool(false);r.recent = rowObj["recent"].asBool(false);+ r.siglId = rowObj["siglId"].str();+ if (r.siglId.empty()) {+ if (r.isGrid) {+ r.siglId = xcloud::sigl::kAllGames;+ } else if (!r.recent) {+ size_t shelfIdx = 0;+ for (const auto& existing : layout_) {+ if (!existing.recent && !existing.isGrid) ++shelfIdx;+ }+ if (shelfIdx == 0) r.siglId = xcloud::sigl::kRecentlyAdded;+ else if (shelfIdx == 1) r.siglId = xcloud::sigl::kMostPopular;+ else if (shelfIdx == 2) r.siglId = xcloud::sigl::kFreeToPlay;+ else if (shelfIdx == 3) r.siglId = xcloud::sigl::kLeavingSoon;+ }+ }for (const auto& it : rowObj["items"].items()) {r.items.emplace_back(it["p"].str(), it["t"].str());}@@ -878,25 +899,28 @@ void Library::saveCache() const {rowObj.set("badges", r.badges);rowObj.set("isGrid", r.isGrid);rowObj.set("recent", r.recent);+ if (!r.siglId.empty()) rowObj.set("siglId", r.siglId);rowObj.set("items", itemsToJson(r.items));layoutArr.push(std::move(rowObj));}root.set("layout", layoutArr);- // Details of everything on the home screen, in "Your games" and in the- // Game Pass search: the next launch shows them, hero art and all, before- // the network answers, and the search's filters (play modes, languages)- // work without asking again.+ // Details of everything on the home screen, in "Your games", in the+ // Game Pass catalog, and all catalog products resolved: the next launch+ // shows them without re-fetching, and prevents false-positive new title alerts.json::Value details = json::Value::object();- auto keep = [&](const std::string& pid) {- auto it = products_.find(pid);- if (it != products_.end()) details.set(pid, productToJson(it->second));- };- for (const auto& r : layout_)- for (const auto& item : r.items) keep(item.first);- for (const auto* list : {&owned_, &purchasable_})- for (const auto& [pid, tid] : *list) keep(pid);- for (const auto& pid : allGames_) keep(pid);+ for (const auto& [pid, prod] : products_) {+ details.set(pid, productToJson(prod));+ }root.set("products", details);+ std::set<std::string> allKnown = knownProducts_;+ for (const auto& [pid, _] : products_) {+ if (!pid.empty()) allKnown.insert(pid);+ }+ json::Value kp = json::Value::array();+ for (const auto& p : allKnown) {+ if (!p.empty()) kp.push(p);+ }+ root.set("knownProducts", kp);json::Value platforms = json::Value::object(), xboxTitles = json::Value::object(), cloudTitles = json::Value::object();for (const auto& [id, code] : platform_) platforms.set(id, code);for (const auto& [pid, xbox] : xboxTitleOf_) xboxTitles.set(pid, xbox);diff --git a/src/app/library.h b/src/app/library.hindex b40d72a..b0e34e5 100644--- a/src/app/library.h+++ b/src/app/library.h@@ -125,6 +125,7 @@ private:bool isGrid = false;std::vector<Item> items;bool recent = false; // "Jump back in"+ std::string siglId;};std::vector<ui::GameTile> tiles(const std::vector<Item>& items) const;bool isPcOnly(const std::string& productId) const;@@ -151,6 +152,7 @@ private:bool gamePassMember_ = false;bool ownershipFresh_ = false; // the account's list of this start (not the cache's) is instd::set<std::string> knownGamePass_; // the Game Pass catalog at the last start (cache)+ std::set<std::string> knownProducts_; // all products known at the last start (cache)std::set<std::string> ownedTitles_, ownedProducts_;std::set<std::string> acquiredTitles_, acquiredProducts_;std::map<std::string, uint64_t> playtime_;diff --git a/src/app/library_sync.cpp b/src/app/library_sync.cppindex 7b3d250..7df01de 100644--- a/src/app/library_sync.cpp+++ b/src/app/library_sync.cpp@@ -57,6 +57,8 @@ size_t Library::syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std:}}}++ // 1. Fetch All Games catalog feedxcloud::ProductList allSigl;std::string siglErr;if (xcloud::fetchList(xcloud::sigl::kAllGames, market_, language_, allSigl, siglErr)) {@@ -70,6 +72,92 @@ size_t Library::syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std:}}}++ // 2. Fetch updated shelf feeds (Recently Added, Most Popular, Free to Play, Leaving Soon)+ const struct ShelfSpec {+ const char* sigl;+ size_t limit;+ } shelfSpecs[] = {+ {xcloud::sigl::kRecentlyAdded, 40},+ {xcloud::sigl::kMostPopular, 40},+ {xcloud::sigl::kFreeToPlay, 40},+ {xcloud::sigl::kLeavingSoon, 40}+ };++ struct FetchedShelf {+ std::string siglId;+ xcloud::ProductList list;+ bool ok = false;+ };+ std::vector<FetchedShelf> fetchedShelves;++ uint8_t myPlan = xcloud::planTier(subscription_);++ for (const auto& spec : shelfSpecs) {+ FetchedShelf fs;+ fs.siglId = spec.sigl;+ std::string e;+ if (xcloud::fetchList(spec.sigl, market_, language_, fs.list, e)) {+ fs.ok = true;+ if (spec.sigl == xcloud::sigl::kRecentlyAdded) {+ const char* const kNewCod[] = {"9NCPSQQD1Z66", "9N201KQXS5BM"};+ for (const char* pid : kNewCod) {+ auto it = std::find(fs.list.productIds.begin(), fs.list.productIds.end(), pid);+ if (it != fs.list.productIds.end()) {+ fs.list.productIds.erase(it);+ size_t insertAt = std::min<size_t>(1, fs.list.productIds.size());+ fs.list.productIds.insert(fs.list.productIds.begin() + static_cast<long>(insertAt), pid);+ }+ }+ } else if (spec.sigl == xcloud::sigl::kMostPopular) {+ popular_ = fs.list.productIds;+ const char* const kTopCod[] = {"9NCPSQQD1Z66", "9N201KQXS5BM", "9NNFG8BQRCXL"};+ for (const char* pid : kTopCod) {+ auto it = std::find(fs.list.productIds.begin(), fs.list.productIds.end(), pid);+ if (it != fs.list.productIds.end()) {+ fs.list.productIds.erase(it);+ size_t insertAt = std::min<size_t>(2, fs.list.productIds.size());+ fs.list.productIds.insert(fs.list.productIds.begin() + static_cast<long>(insertAt), pid);+ }+ }+ }+ bool freeToPlay = spec.sigl == xcloud::sigl::kFreeToPlay;+ if (freeToPlay) {+ freeInStore_.insert(fs.list.productIds.begin(), fs.list.productIds.end());+ }+ bool isMostPopular = spec.sigl == xcloud::sigl::kMostPopular;+ if (!gamePass_.empty() && !freeToPlay && !isMostPopular) {+ fs.list.productIds.erase(std::remove_if(fs.list.productIds.begin(), fs.list.productIds.end(),+ [&](const std::string& id) {+ if (!gamePass_.count(id)) return true;+ if (myPlan > 0 && myPlan < xcloud::kPlanUltimate &&+ !ownedProducts_.count(id) && !freeInStore_.count(id)) {+ auto it = products_.find(id);+ if (it != products_.end() &&+ !xcloud::planIncludes(myPlan, it->second.plan, false))+ return true;+ }+ return false;+ }),+ fs.list.productIds.end());+ }+ fs.list.productIds.erase(std::remove_if(fs.list.productIds.begin(), fs.list.productIds.end(),+ [&](const std::string& id) {+ return isPcOnly(id);+ }),+ fs.list.productIds.end());+ if (spec.limit > 0 && fs.list.productIds.size() > spec.limit) {+ fs.list.productIds.resize(spec.limit);+ }+ for (const auto& pid : fs.list.productIds) {+ if (!pid.empty() && !products_.count(pid)) {+ newProducts.push_back(pid);+ }+ }+ }+ fetchedShelves.push_back(std::move(fs));+ }+std::sort(newProducts.begin(), newProducts.end());newProducts.erase(std::unique(newProducts.begin(), newProducts.end()), newProducts.end());@@ -82,7 +170,10 @@ size_t Library::syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std:for (const auto& pid : newProducts) {auto it = products_.find(pid);if (it != products_.end() && !it->second.title.empty()) {- actuallyAdded.push_back(pid);+ bool isCatalogAddition = !gamePass_.empty() && gamePass_.count(pid);+ if (isCatalogAddition && !knownGamePass_.count(pid) && !knownProducts_.count(pid)) {+ actuallyAdded.push_back(pid);+ }} else {products_[pid].productId = pid;products_[pid].detailedAt = platform::nowMs();@@ -90,6 +181,7 @@ size_t Library::syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std:}newCount = actuallyAdded.size();}+allGames_.erase(std::remove_if(allGames_.begin(), allGames_.end(),[&](const std::string& id) {return isPcOnly(id);@@ -99,8 +191,55 @@ size_t Library::syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std:if (isPcOnly(*it)) it = gamePass_.erase(it);else ++it;}++ // Refresh shelf rows in layout_+ for (const auto& fs : fetchedShelves) {+ if (!fs.ok) continue;+ bool found = false;+ for (auto& row : layout_) {+ if (row.isGrid || row.recent) continue;+ if ((!row.siglId.empty() && row.siglId == fs.siglId) ||+ (row.siglId.empty() && row.title == fs.list.title)) {+ row.siglId = fs.siglId;+ if (row.title.empty() && !fs.list.title.empty()) row.title = fs.list.title;+ row.items.clear();+ for (const auto& pid : fs.list.productIds) {+ std::string tid = cloudTitleOf_.count(pid) ? cloudTitleOf_[pid] : "";+ row.items.emplace_back(pid, tid);+ }+ found = true;+ break;+ }+ }+ if (!found) {+ size_t shelfIdx = 0;+ if (fs.siglId == xcloud::sigl::kRecentlyAdded) shelfIdx = 0;+ else if (fs.siglId == xcloud::sigl::kMostPopular) shelfIdx = 1;+ else if (fs.siglId == xcloud::sigl::kFreeToPlay) shelfIdx = 2;+ else if (fs.siglId == xcloud::sigl::kLeavingSoon) shelfIdx = 3;++ size_t curShelf = 0;+ for (auto& row : layout_) {+ if (row.isGrid || row.recent) continue;+ if (curShelf == shelfIdx) {+ row.siglId = fs.siglId;+ if (row.title.empty() && !fs.list.title.empty()) row.title = fs.list.title;+ row.items.clear();+ for (const auto& pid : fs.list.productIds) {+ std::string tid = cloudTitleOf_.count(pid) ? cloudTitleOf_[pid] : "";+ row.items.emplace_back(pid, tid);+ }+ found = true;+ break;+ }+ ++curShelf;+ }+ }+ }+for (auto& row : layout_) {if (row.isGrid) {+ row.siglId = xcloud::sigl::kAllGames;row.items.clear();for (const auto& pid : allGames_) {std::string tid = cloudTitleOf_.count(pid) ? cloudTitleOf_[pid] : "";@@ -114,6 +253,10 @@ size_t Library::syncDelta(xcloud::GssvClient& gssv, const Changed& changed, std:row.items.end());}}++ for (const auto& pid : allGames_) knownGamePass_.insert(pid);+ for (const auto& [pid, _] : products_) knownProducts_.insert(pid);+loadOwned(gssv, changed, nullptr, &titles);loadCatalogNames(changed, nullptr);saveCache();@@ -134,6 +277,7 @@ bool Library::load(xcloud::GssvClient& gssv, const std::string& language, constownershipKnown_ = false;ownershipFresh_ = false;knownGamePass_.clear();+ knownProducts_.clear();ownedTitles_.clear();ownedProducts_.clear();owned_.clear();@@ -297,6 +441,7 @@ bool Library::load(xcloud::GssvClient& gssv, const std::string& language, constlastErr = e;}RowIds r{list.title, !freeToPlay, isAllGames, {}};+ r.siglId = spec.sigl;for (const auto& id : list.productIds) r.items.emplace_back(id, std::string());layout_.push_back(std::move(r));changed();@@ -305,6 +450,9 @@ bool Library::load(xcloud::GssvClient& gssv, const std::string& language, consterr = lastErr.empty() ? "no games found" : lastErr;return false;}+ for (const auto& pid : allGames_) knownGamePass_.insert(pid);+ for (const auto& [pid, _] : products_) knownProducts_.insert(pid);+ saveCache();return true;}diff --git a/src/app/ps4_main.cpp b/src/app/ps4_main.cppindex 1e73ad6..694dfac 100644--- a/src/app/ps4_main.cpp+++ b/src/app/ps4_main.cpp@@ -14,7 +14,7 @@ int main(int argc, char** argv) {(void)argv;::mkdir("/data/psbox", 0777);// Early diagnostic marker: verifies main() was entered before complex subsystems- for (const char* path : {"/data/psbox/boot.log", "/data/homebrew/PSBOX00001/boot.log"}) {+ for (const char* path : {"/data/psbox/boot.log", "/data/homebrew/PSBX00001/boot.log"}) {int fd = ::open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);if (fd >= 0) {const char msg[] = "PSBox Cloud Gaming - PS4 main() entered successfully\n";diff --git a/src/app/ps5_main.cpp b/src/app/ps5_main.cppindex bfa8632..146e67d 100644--- a/src/app/ps5_main.cpp+++ b/src/app/ps5_main.cpp@@ -4,9 +4,16 @@// PS5 backends and shell_ps5.cpp. Never returns: the app is closed from the// home screen.#include "app/app_core.h"+#include "util/log.h"++#include <cstdio>+#include <unistd.h>int main(int argc, char** argv) {(void)argc;(void)argv;- return xc::app::runApp();+ int rc = xc::app::runApp();+ xc::log::setFile(nullptr);+ std::fflush(nullptr);+ _exit(rc);}diff --git a/src/app/report.cpp b/src/app/report.cppindex 2bb360f..be3394f 100644--- a/src/app/report.cpp+++ b/src/app/report.cpp@@ -158,6 +158,15 @@ std::string issueUrl(const Info& info, size_t maxLength) {} else if (!info.platform.empty()) {platHeader = "[Platform: " + info.platform + "]\n";}+ if (log.size() > maxLength) {+ size_t start = log.size() - maxLength;+ size_t nl = log.find('\n', start);+ if (nl != std::string::npos) {+ log = "...\n" + log.substr(nl + 1);+ } else {+ log = "...\n" + log.substr(start);+ }+ }for (;;) {std::string fullLog = platHeader + log;std::string url = head + encode(fullLog);diff --git a/src/app/shell_desktop.cpp b/src/app/shell_desktop.cppindex b36137e..f0456c4 100644--- a/src/app/shell_desktop.cpp+++ b/src/app/shell_desktop.cpp@@ -58,6 +58,7 @@ bool afterDisplay(bool haveDisplay) {return false;}input::sdlInputInit(display::sdlWindow());+ SDL_HideCursor();return true;}diff --git a/src/app/shell_ps4.cpp b/src/app/shell_ps4.cppindex a25fa5c..4c372ae 100644--- a/src/app/shell_ps4.cpp+++ b/src/app/shell_ps4.cpp@@ -13,13 +13,35 @@#include <sys/stat.h>#include <unistd.h>+#include <csignal>+extern "C" int sceSystemServiceHideSplashScreen(void);+namespace {+volatile std::sig_atomic_t g_shutdownSignal = 0;++void onSignal(int sig) {+ g_shutdownSignal = sig;+}++void installSignalHandlers() {+ struct sigaction sa {};+ sa.sa_handler = onSignal;+ sigemptyset(&sa.sa_mask);+ sa.sa_flags = 0;+ sigaction(SIGTERM, &sa, nullptr);+ sigaction(SIGINT, &sa, nullptr);+ sigaction(SIGHUP, &sa, nullptr);+ std::signal(SIGPIPE, SIG_IGN);+}+} // namespace+namespace xc::app::shell {void beforeSettings() {+ installSignalHandlers();if (recoverUpdate(platform::appDir())) platform::restartApp();- importStoreLeftovers(platform::dataDir(), "/data/pkg/previous/PSBOX00001");+ importStoreLeftovers(platform::dataDir(), "/data/pkg/previous/PSBX00001");}void beforeDisplay(const Settings&) {@@ -34,11 +56,24 @@ std::vector<std::string> iconFontPaths() {"/system_ex/common_ex/font2/PS4Icon.ttf"};}-bool pumpEvents() { return true; }+bool pumpEvents() {+ if (g_shutdownSignal != 0) {+ XC_LOGI("shell: received signal %d, initiating graceful shutdown", static_cast<int>(g_shutdownSignal));+ return false;+ }+ return true;+}bool hasFocus() { return true; }bool canSelfUpdate() { return false; }void beforeShutdown() {}-Caps caps() { return {true, false, true}; }+Caps caps() {+ Caps c;+ c.console = true;+ c.openUrl = false;+ c.selfUpdate = false;+ c.window = false;+ return c;+}void setFullscreen(bool) {}bool fullscreenSwitched(bool&) { return false; }bool openUrl(const std::string&) { return false; }diff --git a/src/app/shell_ps5.cpp b/src/app/shell_ps5.cppindex 8a87cc7..cf1d9e5 100644--- a/src/app/shell_ps5.cpp+++ b/src/app/shell_ps5.cpp@@ -12,14 +12,35 @@#include <cstdlib>#include <sys/stat.h>+#include <csignal>#include <unistd.h>extern "C" int sceSystemServiceHideSplashScreen(void);extern "C" const char* sceKernelGetFsSandboxRandomWord(void);+namespace {+volatile std::sig_atomic_t g_shutdownSignal = 0;++void onSignal(int sig) {+ g_shutdownSignal = sig;+}++void installSignalHandlers() {+ struct sigaction sa {};+ sa.sa_handler = onSignal;+ sigemptyset(&sa.sa_mask);+ sa.sa_flags = 0;+ sigaction(SIGTERM, &sa, nullptr);+ sigaction(SIGINT, &sa, nullptr);+ sigaction(SIGHUP, &sa, nullptr);+ std::signal(SIGPIPE, SIG_IGN);+}+} // namespace+namespace xc::app::shell {void beforeSettings() {+ installSignalHandlers();// An update cut short: the old files went back, and the old eboot.bin// is the one to run.if (recoverUpdate(platform::appDir())) platform::restartApp();@@ -53,12 +74,17 @@ std::vector<std::string> iconFontPaths() {sandbox + "_ex/common_ex/font2/PS4Icon.ttf"};}-// The system closes the app (from the home screen): nothing to read here.-bool pumpEvents() { return true; }+// The system closes the app (from the home screen): handle SIGTERM/SIGINT for clean shutdown.+bool pumpEvents() {+ if (g_shutdownSignal != 0) {+ XC_LOGI("shell: received signal %d, initiating graceful shutdown", static_cast<int>(g_shutdownSignal));+ return false;+ }+ return true;+}bool hasFocus() { return true; }bool canSelfUpdate() { return true; }-// Never called: the PS5's loop doesn't end.void beforeShutdown() {}Caps caps() { return {true, false, true}; }void setFullscreen(bool) {}diff --git a/src/app/update_check.cpp b/src/app/update_check.cppindex 12f31b0..c025b8a 100644--- a/src/app/update_check.cpp+++ b/src/app/update_check.cpp@@ -64,11 +64,16 @@ bool findLatestRelease(Release& out, std::string& err, const std::string& feedUrconst auto& assets = (*j)["assets"];for (size_t i = 0; i < assets.size(); ++i) {const auto& a = assets[i];- if (a["name"].str() == "PPSA99810.zip") {- out.zipUrl = a["browser_download_url"].str();- out.zipSize = static_cast<long>(a["size"].asInt(-1));- } else if (a["name"].str() == "PPSA99810.zip.sig") {- out.sigUrl = a["browser_download_url"].str();+ std::string name = a["name"].str();+ if (name == "PPSA99810.zip" || (name.find("PS5") != std::string::npos && name.size() >= 4 && name.rfind(".zip") == name.size() - 4)) {+ if (out.zipUrl.empty() || name == "PPSA99810.zip") {+ out.zipUrl = a["browser_download_url"].str();+ out.zipSize = static_cast<long>(a["size"].asInt(-1));+ }+ } else if (name == "PPSA99810.zip.sig" || (name.find("PS5") != std::string::npos && name.size() >= 8 && name.rfind(".zip.sig") == name.size() - 8)) {+ if (out.sigUrl.empty() || name == "PPSA99810.zip.sig") {+ out.sigUrl = a["browser_download_url"].str();+ }}}return true;diff --git a/src/app/worker.cpp b/src/app/worker.cppindex a009cd8..6a98aea 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -299,7 +299,7 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefrexistingLib = s_library;}- if (!forceRefresh && existingLib && existingLib->ownedKnown()) {+ if (!forceRefresh && existingLib && (existingLib->ownedKnown() || !existingLib->rows().empty())) {stopHydration();existingLib->setSubscription(g_subscription);{@@ -310,10 +310,9 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefrsetQueueClient(&gssv);XC_LOGI("library: delta-sync against active library (forceRefresh=%d)", forceRefresh);if (g_ui->screen() == ui::Screen::Splash || g_ui->screen() == ui::Screen::SignIn) {- g_ui->showSplash(ui::tr(ui::Str::LoadingGames));- } else {- g_ui->setLoading(true, 0, 0);+ g_ui->showHome();}+ g_ui->setLoading(true, 0, 0);auto publish = [](const app::Library& lib) {auto p = lib.progress();g_ui->setCatalogState(lib.rows(), lib.owned(), lib.purchasable(), lib.ownedKnown(),@@ -333,9 +332,6 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefrif (!shell::caps().console) g_ui->showToast(msg);platform::notify(msg);}- if (g_ui->screen() == ui::Screen::Splash || g_ui->screen() == ui::Screen::SignIn) {- g_ui->showHome();- }std::vector<ui::GameRow> rows = existingLib->rows();g_stopHydration = false;@@ -743,7 +739,7 @@ void worker() {} else if (isDnsOrSinkholeError(result)) {g_ui->showError(ui::tr(ui::Str::DnsBlockedNanoDns));} else {- g_ui->showError(result.rfind("ERROR: ", 0) == 0 ? result.substr(7) : result);+ g_ui->showPlayError(result.rfind("ERROR: ", 0) == 0 ? result.substr(7) : result, tile);}}elsediff --git a/src/app/worker_stream.cpp b/src/app/worker_stream.cppindex 799277e..c4cbafe 100644--- a/src/app/worker_stream.cpp+++ b/src/app/worker_stream.cpp@@ -356,9 +356,13 @@ std::string stream(xcloud::GssvClient& gssv) {details, static_cast<unsigned long long>(session.badSeconds),static_cast<unsigned long long>(st.rtpDroppedFrames), static_cast<unsigned long long>(st.rtpRecovered));}- // Ended before a single frame: the game never started (e.g. it closed on- // the server); say so on the error screen instead of going back quietly.- if (st.decodedFrames == 0 && !g_cancel && !autoplayDone) {+ // An abnormal stream end (connection lost, WebRTC failure, decoder failure):+ // report it as an error so the user sees the error screen and can report or retry.+ bool normalEnd = g_cancel || autoplayDone || reason == "stopped" ||+ reason.find("KickForStopCommand") != std::string::npos ||+ reason.find("KickByNewSession") != std::string::npos ||+ reason.find("KickForServerShutdown") != std::string::npos;+ if (!normalEnd) {g_gameClosedOnServer = reason.rfind("the game closed on the server", 0) == 0;return "ERROR: " + ui::trf(ui::Str::StreamFailed, reason);}diff --git a/src/display/display_ps4.cpp b/src/display/display_ps4.cppindex d8099f2..25185c9 100644--- a/src/display/display_ps4.cpp+++ b/src/display/display_ps4.cpp@@ -48,7 +48,7 @@ struct Overlay {uint8_t alpha = 255;};std::mutex g_overlayMutex;-std::unique_ptr<Overlay> g_overlay;+std::shared_ptr<const Overlay> g_overlay;struct RowScratch {int lastWidth = 0;@@ -377,12 +377,10 @@ bool drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v,g_scratch.update(width, height);- std::unique_ptr<Overlay> activeOverlay;+ std::shared_ptr<const Overlay> activeOverlay;{std::lock_guard<std::mutex> lock(g_overlayMutex);- if (g_overlay) {- activeOverlay = std::make_unique<Overlay>(*g_overlay);- }+ activeOverlay = g_overlay;}auto renderSlice = [y, u, v, strideY, strideU, strideV, dst, &activeOverlay](int yStart, int yEnd) {@@ -445,12 +443,10 @@ bool drawNv12(const uint8_t* y, const uint8_t* uv, int strideY, int strideUV,g_scratch.update(width, height);- std::unique_ptr<Overlay> activeOverlay;+ std::shared_ptr<const Overlay> activeOverlay;{std::lock_guard<std::mutex> lock(g_overlayMutex);- if (g_overlay) {- activeOverlay = std::make_unique<Overlay>(*g_overlay);- }+ activeOverlay = g_overlay;}auto renderSlice = [y, uv, strideY, strideUV, dst, &activeOverlay](int yStart, int yEnd) {@@ -512,13 +508,14 @@ void setOverlay(const uint32_t* pixels, int x, int y, int w, int h, uint8_t opacg_overlay.reset();return;}- g_overlay = std::make_unique<Overlay>();- g_overlay->x = x;- g_overlay->y = y;- g_overlay->w = w;- g_overlay->h = h;- g_overlay->alpha = opacity;- g_overlay->px.assign(pixels, pixels + static_cast<size_t>(w) * h);+ auto overlay = std::make_shared<Overlay>();+ overlay->x = x;+ overlay->y = y;+ overlay->w = w;+ overlay->h = h;+ overlay->alpha = opacity;+ overlay->px.assign(pixels, pixels + static_cast<size_t>(w) * h);+ g_overlay = std::move(overlay);}void setSharpness(int amount) { g_sharpness = std::clamp(amount, 0, 256); }diff --git a/src/input/controller_ps4.cpp b/src/input/controller_ps4.cppindex 4fede57..464ddc8 100644--- a/src/input/controller_ps4.cpp+++ b/src/input/controller_ps4.cpp@@ -226,11 +226,11 @@ int32_t padUserId(int index) {PadCaps padCaps(int index) {if (!padConnected(index)) return {};- return {PadKind::DualShock4, true, false, true, true, true, false};+ return {PadKind::DualShock4, true, false, false, true, true, true};}PadCaps anyPadCaps() {- return {PadKind::DualShock4, true, false, true, true, true, false};+ return {PadKind::DualShock4, true, false, false, true, true, true};}bool init() {diff --git a/src/net/http.cpp b/src/net/http.cppindex 7eb3bc8..cfeb87a 100644--- a/src/net/http.cpp+++ b/src/net/http.cpp@@ -80,7 +80,7 @@ std::string lower(std::string s) {int bioSend(void* ctx, const unsigned char* buf, size_t len) {int fd = *static_cast<int*>(ctx);int flags = 0;-#if defined(MSG_NOSIGNAL) && (MSG_NOSIGNAL != 0) && !defined(__PS4__)+#if defined(MSG_NOSIGNAL) && (MSG_NOSIGNAL != 0)flags = MSG_NOSIGNAL; // a connection the server dropped: an error, not SIGPIPE#endifssize_t n = ::send(fd, buf, len, flags);diff --git a/src/platform/android/platform_android.cpp b/src/platform/android/platform_android.cppindex 93b27cb..2e9c71f 100644--- a/src/platform/android/platform_android.cpp+++ b/src/platform/android/platform_android.cpp@@ -118,6 +118,7 @@ bool restartApp() { return false; }std::string firmwareVersion() { return {}; }std::string diagnostics() { return {}; }std::string platformName() { return "Android"; }+size_t imageCacheBudget() { return 96u << 20; }void setThreadAffinity(ThreadRole, const char*) {}void setThreadRealtimePriority() {}diff --git a/src/platform/linux/platform_linux.cpp b/src/platform/linux/platform_linux.cppindex ea91578..a49997a 100644--- a/src/platform/linux/platform_linux.cpp+++ b/src/platform/linux/platform_linux.cpp@@ -170,6 +170,7 @@ bool restartApp() { return false; }std::string firmwareVersion() { return {}; }std::string diagnostics() { return {}; }std::string platformName() { return "Linux"; }+size_t imageCacheBudget() { return 160u << 20; }void setThreadAffinity(ThreadRole role, const char* name) {if (name && *name) {diff --git a/src/platform/platform.h b/src/platform/platform.hindex f39147b..cb3cc96 100644--- a/src/platform/platform.h+++ b/src/platform/platform.h@@ -102,6 +102,9 @@ std::string diagnostics();// Platform description ("PlayStation 4", "PlayStation 5", "Linux", etc.).std::string platformName();+// Suggested image cache budget in bytes for this platform's RAM constraints.+size_t imageCacheBudget();+bool readFile(const std::string& path, std::string& out);bool writeFileAtomic(const std::string& path, const std::string& data);// A file holding the sign-in, once written: readable by this user only on adiff --git a/src/platform/ps4/platform_ps4.cpp b/src/platform/ps4/platform_ps4.cppindex 89ec961..0dc38c7 100644--- a/src/platform/ps4/platform_ps4.cpp+++ b/src/platform/ps4/platform_ps4.cpp@@ -818,8 +818,8 @@ extern "C" int getifaddrs(struct ifaddrs** ifap) {// 4. Default fallback: ensure libjuice never receives an empty interface listif (local.sin_addr.s_addr == 0) {- inet_pton(AF_INET, "192.168.15.30", &local.sin_addr);- src = "fallback-default";+ inet_pton(AF_INET, "127.0.0.1", &local.sin_addr);+ src = "loopback-default";}static const char* s_lastIfSrc = nullptr;if (s_lastIfSrc != src) {@@ -884,7 +884,7 @@ namespace xc::platform {namespace {constexpr const char* kDataDir = "/data/psbox";-constexpr const char* kLegacyDir = "/data/homebrew/PSBOX00001";+constexpr const char* kLegacyDir = "/data/homebrew/PSBX00001";std::string g_dataDir = kDataDir;std::string g_dataNote;bool g_dataDirWritable = false;@@ -1054,6 +1054,10 @@ std::string platformName() {return "PlayStation 4";}+size_t imageCacheBudget() {+ return 48u << 20;+}+std::string diagnostics() {size_t flex = 0;sceKernelAvailableFlexibleMemorySize(&flex);diff --git a/src/platform/ps5/platform_ps5.cpp b/src/platform/ps5/platform_ps5.cppindex c18c3b6..5d58f54 100644--- a/src/platform/ps5/platform_ps5.cpp+++ b/src/platform/ps5/platform_ps5.cpp@@ -247,6 +247,10 @@ std::string platformName() {return "PlayStation 5";}+size_t imageCacheBudget() {+ return 160u << 20;+}+// One user per app sandbox: nothing to hide the sign-in from.void makePrivate(const std::string&) {}diff --git a/src/platform/windows/platform_windows.cpp b/src/platform/windows/platform_windows.cppindex 0e2934c..fb2df1b 100644--- a/src/platform/windows/platform_windows.cpp+++ b/src/platform/windows/platform_windows.cpp@@ -333,6 +333,7 @@ bool restartApp() { return false; }std::string firmwareVersion() { return {}; }std::string diagnostics() { return {}; }std::string platformName() { return "Windows"; }+size_t imageCacheBudget() { return 160u << 20; }bool readFile(const std::string& path, std::string& out) {FILE* f = std::fopen(path.c_str(), "rb");diff --git a/src/ui/app_ui_internal.h b/src/ui/app_ui_internal.hindex 3964a0b..a2d156e 100644--- a/src/ui/app_ui_internal.h+++ b/src/ui/app_ui_internal.h@@ -312,26 +312,58 @@ inline void drawFaceButton(Canvas& c, const Font& letters, int icon, float cx, f// about `target` px of code; the card's rect (empty when it can't be encoded).inline Rect drawQr(Canvas& c, const std::string& url, int right, int top, int target,qrcodegen_Ecc ecc = qrcodegen_Ecc_MEDIUM) {- static std::string s_cachedUrl;- static qrcodegen_Ecc s_cachedEcc = qrcodegen_Ecc_MEDIUM;- static uint8_t s_qr[qrcodegen_BUFFER_LEN_MAX]{};- static bool s_valid = false;- if (url != s_cachedUrl || ecc != s_cachedEcc) {+ if (url.empty()) return {};+ struct CachedQr {+ std::string url;+ qrcodegen_Ecc ecc = qrcodegen_Ecc_MEDIUM;+ uint8_t qr[qrcodegen_BUFFER_LEN_MAX]{};+ bool valid = false;+ bool attempted = false;+ uint64_t lastUsed = 0;+ };+ constexpr size_t kCacheSlots = 4;+ static CachedQr s_cache[kCacheSlots];+ static uint64_t s_usageCounter = 0;++ CachedQr* entry = nullptr;+ for (size_t i = 0; i < kCacheSlots; ++i) {+ if (s_cache[i].attempted && s_cache[i].url == url && s_cache[i].ecc == ecc) {+ entry = &s_cache[i];+ break;+ }+ }+ if (!entry) {+ size_t lruIndex = 0;+ uint64_t minUsed = s_cache[0].lastUsed;+ for (size_t i = 1; i < kCacheSlots; ++i) {+ if (!s_cache[i].attempted) {+ lruIndex = i;+ break;+ }+ if (s_cache[i].lastUsed < minUsed) {+ minUsed = s_cache[i].lastUsed;+ lruIndex = i;+ }+ }+ entry = &s_cache[lruIndex];uint8_t tmp[qrcodegen_BUFFER_LEN_MAX];- s_valid = qrcodegen_encodeText(url.c_str(), tmp, s_qr, ecc, qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX,- qrcodegen_Mask_AUTO, true);- s_cachedUrl = url;- s_cachedEcc = ecc;+ entry->valid = qrcodegen_encodeText(url.c_str(), tmp, entry->qr, ecc,+ qrcodegen_VERSION_MIN, qrcodegen_VERSION_MAX,+ qrcodegen_Mask_AUTO, true);+ entry->attempted = true;+ entry->url = url;+ entry->ecc = ecc;}- if (!s_valid) return {};- int n = qrcodegen_getSize(s_qr);+ entry->lastUsed = ++s_usageCounter;+ if (!entry->valid) return {};+ int n = qrcodegen_getSize(entry->qr);int module = target / (n + 2), size = module * (n + 2);Rect box{right - size - 40, top, size + 40, size + 40};c.fillRect(box, kWhite, 20);int ox = box.x + 20 + module, oy = box.y + 20 + module;for (int yy = 0; yy < n; ++yy)for (int xx = 0; xx < n; ++xx)- if (qrcodegen_getModule(s_qr, xx, yy)) c.fillRect({ox + xx * module, oy + yy * module, module, module}, kBg);+ if (qrcodegen_getModule(entry->qr, xx, yy)) c.fillRect({ox + xx * module, oy + yy * module, module, module}, kBg);return box;}diff --git a/src/xcloud/catalog.cpp b/src/xcloud/catalog.cppindex f8743f3..82b5080 100644--- a/src/xcloud/catalog.cpp+++ b/src/xcloud/catalog.cpp@@ -62,18 +62,26 @@ bool fetchList(const std::string& siglId, const std::string& market, const std::{"calling-app-version", "0.1"}};auto r = net::perform(req);auto j = json::parse(r.body);- if (!r.ok() || !j || !j->isArray()) {+ if (!r.ok() || !j || (!j->isArray() && !(j->isObject() && j->has("productIds")))) {err = "catalog list " + siglId + ": " + describe(r);return false;}out = {};- // Element 0 describes the list; the rest are {"id": "<product id>"}.- for (size_t i = 0; i < j->size(); ++i) {- const auto& item = (*j)[i];- if (item.has("siglId")) {- out.title = item["title"].str();- } else if (auto id = item["id"].str(); !id.empty()) {- out.productIds.push_back(id);+ if (j->isArray()) {+ // Element 0 describes the list; the rest are {"id": "<product id>"}.+ for (size_t i = 0; i < j->size(); ++i) {+ const auto& item = (*j)[i];+ if (item.has("siglId")) {+ out.title = item["title"].str();+ } else if (auto id = item["id"].str(); !id.empty()) {+ out.productIds.push_back(id);+ }+ }+ } else {+ out.title = (*j)["title"].str();+ for (const auto& item : (*j)["productIds"].items()) {+ std::string id = item.isString() ? item.str() : item["id"].str();+ if (!id.empty()) out.productIds.push_back(id);}}return true;diff --git a/src/xcloud/gssv.cpp b/src/xcloud/gssv.cppindex 36a59b9..cedab0a 100644--- a/src/xcloud/gssv.cpp+++ b/src/xcloud/gssv.cpp@@ -641,7 +641,9 @@ bool GssvClient::pollIceCandidates(std::vector<IceCandidate>& out, std::string&}bool GssvClient::keepalive(std::string& err) {- auto r = net::perform(authed(resolution_, previewFeatures_, login_, "POST", sessionUrl("/keepalive")));+ auto req = authed(resolution_, previewFeatures_, login_, "POST", sessionUrl("/keepalive"));+ req.timeoutMs = 5000;+ auto r = net::perform(req);if (!r.ok()) {err = "keepalive failed: " + describe(r);return false;@@ -651,7 +653,9 @@ bool GssvClient::keepalive(std::string& err) {void GssvClient::stopSession() {if (sessionPath_.empty()) return;- auto r = net::perform(authed(resolution_, previewFeatures_, login_, "DELETE", sessionUrl("")));+ auto req = authed(resolution_, previewFeatures_, login_, "DELETE", sessionUrl(""));+ req.timeoutMs = 3000;+ auto r = net::perform(req);XC_LOGI("session stopped (%s)", r.ok() ? "ok" : describe(r).c_str());sessionPath_.clear();}diff --git a/tests/test_main.cpp b/tests/test_main.cppindex 2afaccd..8b5b2ab 100644--- a/tests/test_main.cpp+++ b/tests/test_main.cpp@@ -32,6 +32,7 @@#include "ui/input_mode.h"#include "ui/stream_menu.h"#include "ui/strings.h"+#include "ui/app_ui_internal.h"#include "util/json.h"#include "util/log.h"#include "auth/auth_manager.h"@@ -937,6 +938,16 @@ static void testReport() {CHECK(url.find("number+199") != std::string::npos && url.find("number+0%0A") == std::string::npos);CHECK(url.find("release=0.9.6") != std::string::npos && url.find("title=Error:+certificates") != std::string::npos);CHECK(url.find("pc%3Deboot%2B0x1a2b3c") != std::string::npos && url.find("(v0.9.6)") != std::string::npos);+ CHECK(xc::platform::imageCacheBudget() >= (48u << 20));++ // QR code generation and 4-slot LRU caching+ ui::Canvas canvas(300, 300);+ auto qr1 = ui::drawQr(canvas, url, 280, 20, 200, qrcodegen_Ecc_LOW);+ CHECK(qr1.w > 0 && qr1.h > 0);+ auto qr1_cached = ui::drawQr(canvas, url, 280, 20, 200, qrcodegen_Ecc_LOW);+ CHECK(qr1_cached.w == qr1.w && qr1_cached.h == qr1.h);+ auto qr_empty = ui::drawQr(canvas, "", 280, 20, 200);+ CHECK(qr_empty.w == 0 && qr_empty.h == 0);}[[gnu::noinline]] static void triggerNullWriteCrash() {@@ -2193,6 +2204,34 @@ static void testVisibleSettingsRows() {xbox.triggerRumble = true;auto x = ids(ui::visibleSettingsRows(xbox));CHECK(std::find(x.begin(), x.end(), 4) != x.end() && std::find(x.begin(), x.end(), 6) == x.end());+ // PS4 console UI caps: DualShock 4 (touchpad/gyro/lightbar, no adaptive triggers) and no PS5 display features (120Hz, FSR1, deband).+ ui::UiCaps ps4;+ ps4.console = true;+ ps4.openUrl = false;+ ps4.selfUpdate = false;+ ps4.desktopWindow = false;+ ps4.lightBar = true;+ ps4.gyro = true;+ ps4.touchpad = true;+ ps4.triggerRumble = false;+ ps4.adaptiveTriggers = false;+ ps4.upscalers = false;+ ps4.sharpen = false;+ ps4.deband = false;+ ps4.highRefresh = false;+ auto ps4Rows = ids(ui::visibleSettingsRows(ps4));+ CHECK(std::find(ps4Rows.begin(), ps4Rows.end(), 9) == ps4Rows.end());+ CHECK(std::find(ps4Rows.begin(), ps4Rows.end(), 4) == ps4Rows.end());+ CHECK(std::find(ps4Rows.begin(), ps4Rows.end(), 21) == ps4Rows.end());+ CHECK(std::find(ps4Rows.begin(), ps4Rows.end(), 6) != ps4Rows.end());+ CHECK(std::find(ps4Rows.begin(), ps4Rows.end(), 15) != ps4Rows.end());+ auto ps4Game = ids(ui::visibleGameSettingsRows(ps4, true, true));+ CHECK(std::find(ps4Game.begin(), ps4Game.end(), 1) == ps4Game.end());+ CHECK(std::find(ps4Game.begin(), ps4Game.end(), 2) == ps4Game.end());+ CHECK(std::find(ps4Game.begin(), ps4Game.end(), 3) == ps4Game.end());+ CHECK(std::find(ps4Game.begin(), ps4Game.end(), 6) == ps4Game.end());+ CHECK(std::find(ps4Game.begin(), ps4Game.end(), 8) == ps4Game.end());+ CHECK(std::find(ps4Game.begin(), ps4Game.end(), 13) != ps4Game.end());// A game's settings.CHECK((ids(ui::visibleGameSettingsRows(ps5, true, false)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 9, 10}));CHECK((ids(ui::visibleGameSettingsRows(ps5, true, true)) == std::vector<int>{0, 4, 8, 15, 14, 1, 2, 3, 5, 6, 16, 7, 12, 11, 13, 9, 10}));@@ -6579,7 +6618,153 @@ static void testSizedUrl() {"https://images-eds-ssl.xboxlive.com/image.png");}+static void testReleaseV155Features() {+ std::string testDir = "/tmp/test-v155-features";+ std::system(("rm -rf " + testDir + " && mkdir -p " + testDir).c_str());+ std::string cacheFile = testDir + "/library_cache.json";++ // 1. Verify shelf auto-refresh & knownProducts persistence in library_cache.json+ {+ std::map<std::string, std::string> siglFeeds;+ siglFeeds[xcloud::sigl::kAllGames] = R"([{"siglId":"all","title":"All Games"},{"id":"GP_GAME_1"},{"id":"GP_GAME_2"}])";+ siglFeeds[xcloud::sigl::kRecentlyAdded] = R"([{"siglId":"recent","title":"Recently Added"},{"id":"GP_GAME_1"}])";+ siglFeeds[xcloud::sigl::kMostPopular] = R"([{"siglId":"pop","title":"Most Popular"},{"id":"GP_GAME_2"}])";+ siglFeeds[xcloud::sigl::kFreeToPlay] = R"([{"siglId":"f2p","title":"Free to Play"},{"id":"F2P_GAME_1"}])";+ siglFeeds[xcloud::sigl::kLeavingSoon] = R"([{"siglId":"leaving","title":"Leaving Soon"}])";++ std::string titlesBody = R"({+ "results": [+ {+ "titleId": "TITLE_CLOUD_SPECIAL",+ "details": {+ "productId": "PROD_CLOUD_SPECIAL",+ "hasEntitlement": false,+ "isFreeInStore": false,+ "userPrograms": []+ }+ }+ ]+ })";++ std::map<std::string, std::string> productTitles;+ productTitles["GP_GAME_1"] = "Game One";+ productTitles["GP_GAME_2"] = "Game Two";+ productTitles["F2P_GAME_1"] = "Free Shooter";+ productTitles["PROD_CLOUD_SPECIAL"] = "Special Cloud Offering";++ net::setTestTransport([&](const net::Request& req) {+ net::Response r;+ r.status = 200;+ if (req.url.find("sigls") != std::string::npos) {+ for (const auto& [siglId, body] : siglFeeds) {+ if (req.url.find("id=" + siglId) != std::string::npos) {+ r.body = body;+ return r;+ }+ }+ r.body = "[]";+ return r;+ } else if (req.url.find("titles") != std::string::npos) {+ r.body = titlesBody;+ return r;+ } else if (req.url.find("products") != std::string::npos) {+ json::Value root = json::Value::object();+ json::Value prods = json::Value::object();+ for (const auto& [id, name] : productTitles) {+ json::Value item = json::Value::object();+ item.set("ProductTitle", name);+ item.set("XCloudTitleId", "T_" + id);+ prods.set(id, std::move(item));+ }+ root.set("Products", std::move(prods));+ r.body = root.dump();+ return r;+ }+ r.status = 404;+ return r;+ });++ app::Library lib;+ lib.setCachePath(cacheFile);+ lib.setSubscription("Ultimate");+ xcloud::GssvClient gssv;+ std::string err;++ // Load initial catalog+ CHECK(lib.load(gssv, "en-US", [] {}, err));+ CHECK(lib.rows().size() >= 4);++ // First syncDelta on this fresh instance+ size_t newAdded = lib.syncDelta(gssv, [] {}, err);+ // Special cloud title outside Game Pass must NOT be reported as new Game Pass game+ CHECK(newAdded == 0);++ // Verify cache was saved and contains PROD_CLOUD_SPECIAL in products and knownProducts+ std::string cacheContent;+ CHECK(platform::readFile(cacheFile, cacheContent));+ auto j = json::parse(cacheContent);+ CHECK(j.has_value());+ CHECK((*j)["products"].has("PROD_CLOUD_SPECIAL"));+ size_t countInKp = 0;+ for (const auto& p : (*j)["knownProducts"].items()) {+ if (p.str() == "PROD_CLOUD_SPECIAL") countInKp++;+ }+ CHECK(countInKp == 1); // Verified deduplicated: serialized exactly once!++ // 2. Simulate subsequent boot with pre-existing cache+ app::Library libBoot2;+ libBoot2.setCachePath(cacheFile);+ CHECK(libBoot2.loadCache(true));++ // syncDelta on boot 2: must NOT have false positive of new games!+ size_t countBoot2 = libBoot2.syncDelta(gssv, [] {}, err);+ CHECK(countBoot2 == 0);++ // 3. Now simulate Microsoft adding a new Game Pass game to Recently Added feed+ siglFeeds[xcloud::sigl::kRecentlyAdded] = R"([{"siglId":"recent","title":"Recently Added"},{"id":"GP_GAME_3"},{"id":"GP_GAME_1"}])";+ siglFeeds[xcloud::sigl::kAllGames] = R"([{"siglId":"all","title":"All Games"},{"id":"GP_GAME_1"},{"id":"GP_GAME_2"},{"id":"GP_GAME_3"}])";+ productTitles["GP_GAME_3"] = "Game Three";++ size_t countBoot3 = libBoot2.syncDelta(gssv, [] {}, err);+ // Genuine new Game Pass game should be counted+ CHECK(countBoot3 == 1);++ // Check that "Recently Added" shelf in layout_ now automatically has GP_GAME_3 without manual L3 refresh!+ bool foundInShelf = false;+ for (const auto& row : libBoot2.rows()) {+ if (row.title == "Recently Added") {+ for (const auto& tile : row.tiles) {+ if (tile.productId == "GP_GAME_3") foundInShelf = true;+ }+ }+ }+ CHECK(foundInShelf);++ // 4. Test SIGL object-format parsing (both string IDs and object IDs {"id": "..."})+ xcloud::ProductList objList;+ std::string objErr;+ siglFeeds["test_obj_format"] = R"({"title":"Object Shelves","productIds":["GP_GAME_1",{"id":"GP_GAME_2"}]})";+ CHECK(xcloud::fetchList("test_obj_format", "US", "en-US", objList, objErr));+ CHECK(objList.title == "Object Shelves");+ CHECK(objList.productIds.size() == 2);+ CHECK(objList.productIds[0] == "GP_GAME_1");+ CHECK(objList.productIds[1] == "GP_GAME_2");++ // 5. Test resilience against corrupted or truncated cache+ std::string corruptCache = testDir + "/corrupt.json";+ platform::writeFileAtomic(corruptCache, "{ \"version\": 2, \"knownProducts\": [\"\", 123, null], \"products\": {");+ app::Library corruptLib;+ corruptLib.setCachePath(corruptCache);+ CHECK(!corruptLib.loadCache(true));++ net::setTestTransport({});+ }++ std::system(("rm -rf " + testDir).c_str());+}+int main() {+ testReleaseV155Features();testSizedUrl();testPhase1BugFixesAndPhase2Optimizations();testBlock4OwnershipAndRecents();diff --git a/tools/check-platform-boundaries.sh b/tools/check-platform-boundaries.shindex 91f8f77..2fa0243 100755--- a/tools/check-platform-boundaries.sh+++ b/tools/check-platform-boundaries.sh@@ -56,7 +56,7 @@ use warnings;my @rules = (qr/\bsce[A-Z][A-Za-z0-9_]*/,qr/^\s*#\s*include\s*[<"](?:ps5platform|orbis)\//,- qr/\b(?:XCLOUD_PS5|XC_PLATFORM_PS5|__PROSPERO__|__ORBIS__)\b/,+ qr/\b(?:XCLOUD_PS5|XC_PLATFORM_PS5|XC_PLATFORM_PS4|XC_TARGET_PS4|__PROSPERO__|__ORBIS__|__PS4__)\b/,qr/^\s*#\s*(?:if|ifdef|ifndef|elif|elifdef|elifndef)\b.*\b__FreeBSD__\b/,qr/^\s*#\s*(?:ifndef|elifndef)\s+XC_PLATFORM_DESKTOP\b/,qr/^\s*#\s*(?:if|elif)\b.*!\s*(?:defined\s*\(?\s*)?XC_PLATFORM_DESKTOP\b/,diff --git a/tools/ps4/package.sh b/tools/ps4/package.shindex b6b3cd4..d744ce4 100755--- a/tools/ps4/package.sh+++ b/tools/ps4/package.sh@@ -72,7 +72,7 @@ SHIM_SfiTITLE="${XC_PS4_TITLE:-PSBox Cloud Gaming - PS4}"-VERSION="${XC_PS4_VERSION:-01.54}"+VERSION="${XC_PS4_VERSION:-01.55}"# PS5 backward-compatibility checks every PS4 PKG against Sony's Category1 whitelist.# Using a whitelisted Title ID (like CUSA00100) allows the PS4 PKG to run on PS5 backward compatibility.TITLE_ID="${XC_PS4_TITLE_ID:-PSBX00001}"