Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

Merge branch 'feat/trophy-sync' into perf/linux-desktop

Rafael Abud Ferreirafd7530ad52e9
diff --cc CMakeLists.txt
index 8925621,297b95b..2b7bccd
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@@ -171,9 -169,9 +175,10 @@@ if(XCLOUD_PS5
src/media/hw_decoder_ps5.cpp
src/input/controller_ps5.cpp
src/input/kbm_ps5.cpp
+ src/input/pad_usb_ps5.cpp
src/media/audio_out_ps5.cpp
src/media/audio_in_ps5.cpp
+ src/platform/ps5/trophy_backend_ps5.cpp
)
target_sources(xcloud_core PRIVATE src/platform/posix_common.cpp)
target_include_directories(xcloud_app PRIVATE "${PS5_RADV}/include")
@@@ -198,11 -196,7 +203,12 @@@ elseif(XC_TARGET_PS4
src/input/kbm_ps4.cpp
src/media/audio_out_ps4.cpp
src/media/audio_in_ps4.cpp
+ src/platform/ps4/trophy_backend_ps4.cpp
+ # In the executable itself, so its definitions always replace libkernel's.
+ src/platform/ps4/pthread_abi_ps4.c
+ # H.264 SPS parser and colour policy from XCloud4 (GPL-3.0-only).
+ src/platform/ps4/xcloud4/stream_sps.c
+ src/platform/ps4/xcloud4/stream_color_policy.c
)
target_link_libraries(xcloud_ps4.elf PRIVATE
xcloud_stream
diff --cc src/app/autoplay.cpp
index 37b7e9d,3b83c81..d287d8a
--- a/src/app/autoplay.cpp
+++ b/src/app/autoplay.cpp
@@@ -36,8 -37,8 +38,9 @@@ bool settingsShot = false; // "setting
bool bitrateShot = false; // "bitratetest": save the screen now
bool donationShot = false; // "donationtest": save the screen now
bool reportShot = false; // "reporttest": save report.ppm now
+const char* cloudTimeShot = nullptr; // "cloudtimetest": save this capture now
bool signInCheckShot = false; // "checksignintest": save the screen now
+ bool trophySettingsShot = false, trophySyncedShot = false; // "trophytest": save screenshots
bool freeUiShot = false, freeDetailsShot = false; // "freetest": save free account screenshots
const char* keysShot = nullptr; // "keystest": the screen to save now
uint64_t homeSince = 0, launchSince = 0;
diff --cc src/app/worker.cpp
index b4c5b12,f413831..412e1dc
--- a/src/app/worker.cpp
+++ b/src/app/worker.cpp
@@@ -556,19 -549,51 +557,59 @@@ void requestQuit()
}
bool waitForWorker(uint32_t ms) {
- std::unique_lock<std::mutex> lock(g_workerStateMutex);
- return g_workerStateCv.wait_for(lock, std::chrono::milliseconds(ms), [] { return g_workerState != 1; });
+ bool done = false;
+ {
+ std::unique_lock<std::mutex> lock(g_workerStateMutex);
+ done = g_workerStateCv.wait_for(lock, std::chrono::milliseconds(ms), [] { return g_workerState != 1; });
+ }
+ if (done && g_workerThread.joinable()) {
+ g_workerThread.join();
+ }
+ return done;
}
+ void runTrophySync(auth::AuthManager& am, xcloud::GssvClient& gssv) {
+ std::string err;
+ if (!keepSignedIn(am, gssv, err)) {
+ XC_LOGW("trophy sync: keepSignedIn failed: %s", err.c_str());
+ std::string failMsg = err.empty() ? "Sign-in required" : err;
+ if (!shell::caps().console) g_ui->showToast(failMsg);
+ platform::notify(failMsg);
+ return;
+ }
+ std::string xblAuth, xuid;
+ {
+ std::lock_guard<std::mutex> lock(g_argMutex);
+ xblAuth = g_xblAuth;
+ xuid = g_xuid;
+ }
+ if (xblAuth.empty()) {
+ xblAuth = am.profile().xblAuthorization;
+ xuid = am.profile().xuid;
+ }
+ if (xblAuth.empty()) {
+ XC_LOGW("trophy sync: sign-in required");
+ return;
+ }
+
+ XC_LOGI("trophy sync: starting single-title test for Fortnite (267695549)...");
+ if (g_ui) g_ui->setLoading(true, 0, 1);
+
+ int newlyUnlocked = 0;
+ std::string syncErr;
+ bool ok = trophy::syncEngine().syncTitleAchievements(xblAuth, xuid, "267695549", "Fortnite",
+ newlyUnlocked, syncErr);
+ if (g_ui) g_ui->setLoading(false, 1, 1);
+ if (!ok) {
+ XC_LOGW("trophy sync failed for Fortnite: %s", syncErr.c_str());
+ return;
+ }
+
+ XC_LOGI("trophy sync finished for Fortnite: %d trophies unlocked", newlyUnlocked);
+ }
+
void worker() {
+ platform::setThreadAffinity(platform::ThreadRole::Worker, "xcloud_worker");
if (g_autoplay.title == "BENCH") {
platform::Thread t; // same big stack as the stream's video thread
platform::startThread(t, runDecodeBench);
diff --cc src/app/worker_stream.cpp
index 70cfbc2,2737d0f..ed0fd87
--- a/src/app/worker_stream.cpp
+++ b/src/app/worker_stream.cpp
@@@ -16,13 -14,12 +16,15 @@@
#include "util/log.h"
#include "xcloud/catalog.h"
#include "xcloud/regions.h"
+ #include "trophy/trophy_sync.h"
+ #include "trophy/trophy_registry.h"
#include <algorithm>
+#include <atomic>
#include <cmath>
+#include <cstdio>
#include <cstdlib>
+#include <iterator>
#include <vector>
namespace xc::app {
@@@ -86,9 -83,11 +88,11 @@@ namespace
// Streams until the player ends or the user leaves; returns a status line.
// The cloud title being played, for crash markers (set by play()).
std::string g_stageTitle;
+ std::string g_stageGameName;
std::string g_stageProduct;
+ std::string g_stageXboxTitleId;
-std::string stream(xcloud::GssvClient& gssv) {
+std::string stream(xcloud::GssvClient& gssv, const auth::CloudTimeQuery& cloudQuery) {
crash::setStage(gssv.isHome() ? "streaming own Xbox" : ("streaming " + g_stageTitle).c_str());
g_gameClosedOnServer = false;
app::StreamPlayer player(gssv);
@@@ -144,44 -142,7 +148,45 @@@
const uint64_t started = platform::nowMs();
uint64_t nextTick = started;
+ // The account's cloud time (a limited account's, in the cloud): counted
+ // down for the game menu, a notice at 15 and at 5 minutes left (Xbox
+ // ends the stream at none, issue #342), and the service asked again every
+ // 10 minutes from a thread of its own (the loop never waits on it).
+ ui::CloudTimeClock cloud;
+ const bool cloudTest = g_autoplay.cloudLeft >= 0;
+ if (!gssv.isHome()) cloud.start(cloudTest ? g_autoplay.cloudLeft : s_playtimeRemainingSeconds, started);
+ if (cloud.limited()) XC_LOGI("cloud time: %s left at the start", ui::formatCloudTime(cloud.left(started)).c_str());
+ struct CloudAsk {
+ platform::Thread thread;
+ std::atomic<bool> done{false};
+ std::atomic<int64_t> remaining{-1};
+ } ask;
+ const uint64_t kAskEveryMs = cloudTest ? 20000 : 600000;
+ uint64_t nextAsk = started + kAskEveryMs;
+ auto cloudTimeStep = [&](uint64_t nowMs) {
+ if (!cloud.limited()) return;
+ if (const int64_t due = cloud.noticeDue(nowMs); due > 0)
+ platform::notify(ui::trf(ui::Str::CloudTimeWarn, ui::formatCloudTime(due)),
+ "cloud time: " + ui::formatCloudTime(due) + " left (notification)");
+ if (ask.done) {
+ ask.thread.join();
+ ask.done = false;
+ const int64_t counted = cloud.left(nowMs);
+ cloud.answer(ask.remaining, nowMs);
+ XC_LOGI("cloud time: the service says %s, counted %s: %s left",
+ ask.remaining < 0 ? "no limit or nothing" : ui::formatCloudTime(ask.remaining).c_str(),
+ ui::formatCloudTime(counted).c_str(), ui::formatCloudTime(cloud.left(nowMs)).c_str());
+ }
+ if (!ask.thread.joinable() && nowMs >= nextAsk && !cloudQuery.marketplace.token.empty()) {
+ nextAsk = nowMs + kAskEveryMs;
+ platform::startThread(ask.thread, [&ask, cloudQuery] {
+ auth::ContentAccessPlaytime t;
+ ask.remaining = auth::queryCloudTime(cloudQuery, t, 8000) ? t.accountRemaining : -1;
+ ask.done = true;
+ }, 1u << 20);
+ }
+ };
+ uint64_t lastTrophyPollAt = started;
bool snapshot1 = false, snapshot2 = false, snapshot3 = false, snapshot4 = false;
uint64_t nextPeriodicShot = 150000;
int periodicShotIdx = 5;
diff --cc src/ui/i18n/strings_de.inc
index 30ff313,5cbc0fb..2384eca
--- a/src/ui/i18n/strings_de.inc
+++ b/src/ui/i18n/strings_de.inc
@@@ -415,11 -415,8 +415,25 @@@ constexpr Column kGerman =
"In Warteschlange (geschätzte Wartezeit: %s • wartet seit %s)", // InQueueEstimated
"Um kostenlose Spiele außer Fortnite ohne Game Pass zu streamen, aktivieren Sie 'Preview-Funktionen' in den App-Einstellungen und auf xbox.com/play.", // F2pPreviewRequiredDesc
"Dieses Konto muss 'Preview-Funktionen' im Profil auf xbox.com/play aktivieren, um werbefinanziertes Free-to-Play-Streaming freizuschalten.", // F2pPreviewAccountNeededDesc
+ "Spieler", // MenuPlayer
+ "Ihre Xbox-Cloud-Spielzeit ist aufgebraucht, deshalb hat der Xbox-Dienst die Sitzung beendet. Seit November 2026 begrenzt Xbox das Cloud-Gaming pro Monat: 15 Std. mit Game Pass Ultimate, 10 Std. mit Premium und 5 Std. mit Essential. Mehr Zeit: Ihre Optionen finden Sie auf xbox.com, oder Sie warten auf die Stunden des nächsten Monats.", // CloudTimeUp
+ "Die Sitzung wurde wegen Inaktivität beendet", // EndedIdle
+ "%s verbleibend", // CloudTimeLeft
+ "von %s", // CloudTimeOf
+ "Unbegrenzte Cloud-Zeit", // CloudTimeUnlimited
+ "Noch %s Xbox-Cloud-Spielzeit in diesem Monat", // CloudTimeWarn
+ "Trophäen synchronisieren", // SyncTrophies
+ "Synchronisiert alle Xbox-Erfolge Ihres Kontos und weist entsprechende Trophäen Ihrem PlayStation-Profil zu.", // SettingDescSyncTrophies
+ "Sync", // RunSyncTrophies
+ "Synchronisierung abgeschlossen: %s Trophäe(n) in %s Titel(n) deinem Profil hinzugefügt!", // TrophiesSyncedToast
++ "Trophäen-Warnung", // TrophiesDisclaimerTitle
++ "Das Aktivieren der Trophäen-Konvertierung fügt Trophäen Ihrem PlayStation-Profil hinzu. Wenn Sie dieses Konto mit dem PlayStation Network verbinden, besteht Bann-Gefahr. Aktivieren Sie dies nur auf einem lokalen Profil oder wenn Sie sich nicht mehr mit dem PSN verbinden.", // TrophiesDisclaimerBody
++ "Ich verstehe", // TrophiesDisclaimerAware
++ "Abbrechen", // TrophiesDisclaimerCancel
++ "Synchronisierte Trophäen entfernen", // RemoveTrophies
++ "Entfernt alle von PSBox hinzugefügten Trophäen aus diesem lokalen Profil, um ein PSN-Bannrisiko auszuschließen. Sie können sie jederzeit wieder über Ihr Xbox-Konto synchronisieren.", // SettingDescRemoveTrophies
++ "Synchronisierte Trophäen entfernen?", // RemoveTrophiesConfirmTitle
++ "Dies löscht die lokalen Trophäenpakete von PSBox für dieses Profil. Ihre Erfolge bleiben auf Ihrem Microsoft/Xbox-Konto sicher gespeichert.", // RemoveTrophiesConfirmBody
++ "Entfernen", // RemoveTrophiesConfirm
++ "%s Trophäen-Titel aus diesem Profil entfernt.", // TrophiesRemovedToast
};
diff --cc src/ui/i18n/strings_en.inc
index 02ef942,91a30c3..0088565
--- a/src/ui/i18n/strings_en.inc
+++ b/src/ui/i18n/strings_en.inc
@@@ -415,11 -415,8 +415,25 @@@ constexpr Column kEnglish =
"In queue (estimated wait: %s • waiting for %s)", // InQueueEstimated
"To stream free-to-play games beyond Fortnite without Game Pass, enable 'Preview Features' in app Settings and on xbox.com/play.", // F2pPreviewRequiredDesc
"This account needs to enable 'Preview Features' in its profile on xbox.com/play to unlock ad-supported free-to-play streaming.", // F2pPreviewAccountNeededDesc
+ "Player", // MenuPlayer
+ "Your Xbox cloud gaming time has run out, so the Xbox service ended the session. Since November 2026, Xbox limits cloud play each month: 15 h with Game Pass Ultimate, 10 h with Premium and 5 h with Essential. To get more time, see your options at xbox.com, or new hours come next month.", // CloudTimeUp
+ "The stream ended after a while without input", // EndedIdle
+ "%s left", // CloudTimeLeft
+ "of %s", // CloudTimeOf
+ "Unlimited cloud time", // CloudTimeUnlimited
+ "%s of your Xbox cloud gaming time left this month", // CloudTimeWarn
+ "Sync Trophies", // SyncTrophies
+ "Synchronizes all Xbox achievements from your account and awards matching trophies to your PlayStation profile.", // SettingDescSyncTrophies
+ "Sync", // RunSyncTrophies
+ "Sync complete: %s trophy(ies) across %s title(s) awarded to your profile!", // TrophiesSyncedToast
++ "Trophy Sync Warning", // TrophiesDisclaimerTitle
++ "Enabling trophy conversion adds trophies directly to your PlayStation profile. If you connect this account to PlayStation Network, syncing may risk an account ban. Only enable this on an offline/local profile, or if you do not plan to connect to PSN.", // TrophiesDisclaimerBody
++ "I understand", // TrophiesDisclaimerAware
++ "Cancel", // TrophiesDisclaimerCancel
++ "Remove Synced Trophies", // RemoveTrophies
++ "Removes all trophies added by PSBox from this local profile, eliminating ban risk. You can re-sync them anytime from your Xbox account.", // SettingDescRemoveTrophies
++ "Remove Synced Trophies?", // RemoveTrophiesConfirmTitle
++ "This will delete local trophy packages added by PSBox for this profile. Your achievements remain safe on your Microsoft/Xbox account.", // RemoveTrophiesConfirmBody
++ "Remove", // RemoveTrophiesConfirm
++ "Removed %s trophy title(s) from this profile.", // TrophiesRemovedToast
};
diff --cc src/ui/i18n/strings_es.inc
index 78fef26,2110164..c77d190
--- a/src/ui/i18n/strings_es.inc
+++ b/src/ui/i18n/strings_es.inc
@@@ -415,11 -415,8 +415,25 @@@ constexpr Column kSpanish =
"En cola (tiempo estimado: %s • esperando desde hace %s)", // InQueueEstimated
"Para transmitir juegos gratuitos además de Fortnite en cuentas sin Game Pass, activa 'Funciones Preview' en Ajustes y en xbox.com/play.", // F2pPreviewRequiredDesc
"Esta cuenta necesita habilitar 'Funciones Preview' en su perfil en xbox.com/play para desbloquear el streaming con anuncios de juegos gratuitos.", // F2pPreviewAccountNeededDesc
+ "Jugador", // MenuPlayer
- "Se acabó tu tiempo de juego en la nube de Xbox, así que el servicio de Xbox cerró la sesión. Desde noviembre de 2026, Xbox limita el juego en la nube cada mes: 15 h con Game Pass Ultimate, 10 h con Premium y 5 h con Essential. Para tener más tiempo, mira las opciones en xbox.com, o espera las horas del próximo mes.", // CloudTimeUp
++ "Se acabó tu tiempo de juego en la nube de Xbox, así que el servicio de Xbox cerró la sesión. Desde noviembre de 2026, Xbox limita el juego en la nube cada mes: 15 h con Game Pass Ultimate, 10 h con Premium e 5 h con Essential. Para tener más tiempo, mira las opciones en xbox.com, o espera las horas del próximo mes.", // CloudTimeUp
+ "La sesión terminó por inactividad", // EndedIdle
+ "%s restantes", // CloudTimeLeft
+ "de %s", // CloudTimeOf
+ "Tiempo en la nube ilimitado", // CloudTimeUnlimited
+ "Te quedan %s de tu tiempo de juego en la nube de Xbox este mes", // CloudTimeWarn
+ "Sincronizar Trofeos", // SyncTrophies
+ "Sincroniza todos los logros de Xbox de tu cuenta y otorga los trofeos correspondientes en tu perfil de PlayStation.", // SettingDescSyncTrophies
+ "Sincronizar", // RunSyncTrophies
+ "¡Sincronización completada: %s trofeo(s) en %s título(s) otorgados a tu perfil!", // TrophiesSyncedToast
++ "Aviso sobre Trofeos", // TrophiesDisclaimerTitle
++ "Habilitar la conversión de trofeos añade trofeos directamente a tu perfil de PlayStation. Si conectas esta cuenta a PlayStation Network para sincronizar, existen posibilidades de que la cuenta sea baneada. Activa esto solo en un perfil local o si no planeas conectarte a PSN.", // TrophiesDisclaimerBody
++ "Estoy al tanto", // TrophiesDisclaimerAware
++ "Cancelar", // TrophiesDisclaimerCancel
++ "Eliminar Trofeos Sincronizados", // RemoveTrophies
++ "Elimina todos los trofeos añadidos por PSBox del perfil local para evitar riesgos con PSN. Podrás volver a sincronizarlos cuando quieras desde tu cuenta Xbox.", // SettingDescRemoveTrophies
++ "¿Eliminar Trofeos Sincronizados?", // RemoveTrophiesConfirmTitle
++ "Esto borrará los paquetes locales de trofeos de PSBox para este perfil. Tus logros permanecen seguros en tu cuenta Microsoft/Xbox.", // RemoveTrophiesConfirmBody
++ "Eliminar", // RemoveTrophiesConfirm
++ "Se han eliminado %s título(s) de trofeos de este perfil.", // TrophiesRemovedToast
};
diff --cc src/ui/i18n/strings_fr.inc
index 180a611,1e246ed..9de39ba
--- a/src/ui/i18n/strings_fr.inc
+++ b/src/ui/i18n/strings_fr.inc
@@@ -415,11 -415,8 +415,25 @@@ constexpr Column kFrench =
"En file d'attente (temps estimé : %s • attente depuis %s)", // InQueueEstimated
"Pour jouer aux jeux gratuits autres que Fortnite sans Game Pass, activez les 'Fonctionnalités Preview' dans les Paramètres et sur xbox.com/play.", // F2pPreviewRequiredDesc
"Ce compte doit activer les 'Fonctionnalités Preview' sur son profil sur xbox.com/play pour débloquer le streaming gratuit avec publicités.", // F2pPreviewAccountNeededDesc
+ "Joueur", // MenuPlayer
+ "Votre temps de jeu dans le cloud Xbox est écoulé : le service Xbox a fermé la session. Depuis novembre 2026, Xbox limite le jeu dans le cloud chaque mois : 15 h avec le Game Pass Ultimate, 10 h avec Premium et 5 h avec Essential. Pour avoir plus de temps, consultez les options sur xbox.com, ou attendez les heures du mois prochain.", // CloudTimeUp
+ "La session s’est terminée pour inactivité", // EndedIdle
+ "%s restantes", // CloudTimeLeft
+ "sur %s", // CloudTimeOf
+ "Temps cloud illimité", // CloudTimeUnlimited
+ "Il vous reste %s de temps de jeu dans le cloud Xbox ce mois-ci", // CloudTimeWarn
+ "Synchroniser les trophées", // SyncTrophies
+ "Synchronise tous les succès Xbox de votre compte et attribue les trophées correspondants à votre profil PlayStation.", // SettingDescSyncTrophies
+ "Synchroniser", // RunSyncTrophies
+ "Synchronisation terminée : %s trophée(s) sur %s titre(s) ajoutés à votre profil !", // TrophiesSyncedToast
++ "Avertissement sur les trophées", // TrophiesDisclaimerTitle
++ "L'activation de la conversion des trophées ajoute des trophées à votre profil PlayStation. Si vous connectez ce compte au PlayStation Network pour synchroniser, il existe des risques de bannissement. N'activez cette option que sur un profil local ou si vous ne prévoyez plus de vous connecter au PSN.", // TrophiesDisclaimerBody
++ "Je comprends", // TrophiesDisclaimerAware
++ "Annuler", // TrophiesDisclaimerCancel
++ "Supprimer les trophées synchronisés", // RemoveTrophies
++ "Supprime tous les trophées ajoutés par PSBox de ce profil local pour éliminer le risque de bannissement sur le PSN. Vous pourrez les synchroniser à nouveau depuis votre compte Xbox.", // SettingDescRemoveTrophies
++ "Supprimer les trophées synchronisés ?", // RemoveTrophiesConfirmTitle
++ "Cela supprimera les packs de trophées locaux de PSBox pour ce profil. Vos succès restent enregistrés sur votre compte Microsoft/Xbox.", // RemoveTrophiesConfirmBody
++ "Supprimer", // RemoveTrophiesConfirm
++ "%s titre(s) de trophées supprimé(s) de ce profil.", // TrophiesRemovedToast
};
diff --cc src/ui/i18n/strings_it.inc
index 2e77a44,00aed04..dc318d6
--- a/src/ui/i18n/strings_it.inc
+++ b/src/ui/i18n/strings_it.inc
@@@ -415,11 -415,8 +415,25 @@@ constexpr Column kItalian =
"In coda (tempo stimato: %s • in attesa da %s)", // InQueueEstimated
"Per giocare a titoli gratuiti oltre a Fortnite senza Game Pass, abilita 'Funzionalità Preview' nelle Impostazioni e su xbox.com/play.", // F2pPreviewRequiredDesc
"Questo account deve abilitare le 'Funzionalità Preview' nel profilo su xbox.com/play per sbloccare lo streaming gratuito supportato da annunci.", // F2pPreviewAccountNeededDesc
+ "Giocatore", // MenuPlayer
+ "Il tuo tempo di gioco nel cloud Xbox è esaurito, quindi il servizio Xbox ha chiuso la sessione. Da novembre 2026 Xbox limita il gioco nel cloud ogni mese: 15 ore con Game Pass Ultimate, 10 con Premium e 5 con Essential. Per avere più tempo, vedi le opzioni su xbox.com, o attendi le ore del mese prossimo.", // CloudTimeUp
+ "La sessione è terminata per inattività", // EndedIdle
+ "%s rimanenti", // CloudTimeLeft
+ "di %s", // CloudTimeOf
+ "Tempo cloud illimitato", // CloudTimeUnlimited
+ "Restano %s del tuo tempo di gioco nel cloud Xbox questo mese", // CloudTimeWarn
+ "Sincronizza trofei", // SyncTrophies
+ "Sincronizza tutti gli obiettivi Xbox del tuo account e assegna i trofei corrispondenti al tuo profilo PlayStation.", // SettingDescSyncTrophies
+ "Sincronizza", // RunSyncTrophies
+ "Sincronizzazione completata: %s trofeo/i su %s titolo/i assegnati al tuo profilo!", // TrophiesSyncedToast
++ "Avviso sui trofei", // TrophiesDisclaimerTitle
++ "L'abilitazione della conversione dei trofei aggiunge i trofei direttamente al tuo profilo PlayStation. Se colleghi questo account a PlayStation Network per sincronizzare, rischi un ban dell'account. Attiva questa opzione solo su un profilo locale o se non intendi più connetterti a PSN.", // TrophiesDisclaimerBody
++ "Ho capito", // TrophiesDisclaimerAware
++ "Annulla", // TrophiesDisclaimerCancel
++ "Rimuovi trofei sincronizzati", // RemoveTrophies
++ "Rimuove tutti i trofei aggiunti da PSBox da questo profilo locale, evitando rischi di ban su PSN. Potrai risincronizzarli in qualsiasi momento dal tuo account Xbox.", // SettingDescRemoveTrophies
++ "Rimuovere i trofei sincronizzati?", // RemoveTrophiesConfirmTitle
++ "Questo cancellerà i pacchetti di trofei locali di PSBox per questo profilo. I tuoi obiettivi rimangono al sicuro sul tuo account Microsoft/Xbox.", // RemoveTrophiesConfirmBody
++ "Rimuovi", // RemoveTrophiesConfirm
++ "Rimossi %s titoli di trofei da questo profilo.", // TrophiesRemovedToast
};
diff --cc src/ui/i18n/strings_pt_br.inc
index d639a8c,4b2c9d6..0cb9e1e
--- a/src/ui/i18n/strings_pt_br.inc
+++ b/src/ui/i18n/strings_pt_br.inc
@@@ -415,11 -415,8 +415,25 @@@ constexpr Column kPortugueseBR =
"Na fila (tempo estimado: %s • aguardando há %s)", // InQueueEstimated
"Para transmitir jogos gratuitos além de Fortnite em contas sem Game Pass, ative os 'Recursos Preview' nas Configurações do app e no site xbox.com/play.", // F2pPreviewRequiredDesc
"Esta conta precisa habilitar os 'Recursos Preview' no perfil em xbox.com/play para liberar o streaming com anúncios de jogos gratuitos.", // F2pPreviewAccountNeededDesc
+ "Jogador", // MenuPlayer
+ "Seu tempo de jogo na nuvem do Xbox acabou, então o serviço do Xbox encerrou a sessão. Desde novembro de 2026, o Xbox limita o jogo na nuvem por mês: 15 h no Game Pass Ultimate, 10 h no Premium e 5 h no Essential. Para ter mais tempo, veja as opções em xbox.com, ou espere as horas do próximo mês.", // CloudTimeUp
+ "O streaming foi encerrado por inatividade", // EndedIdle
+ "%s restantes", // CloudTimeLeft
+ "de %s", // CloudTimeOf
+ "Tempo de nuvem ilimitado", // CloudTimeUnlimited
+ "Restam %s do seu tempo de jogo na nuvem do Xbox neste mês", // CloudTimeWarn
+ "Sincronizar Troféus", // SyncTrophies
+ "Sincroniza todas as conquistas do Xbox da sua conta e atribui os troféus correspondentes ao perfil do PlayStation.", // SettingDescSyncTrophies
+ "Sincronizar", // RunSyncTrophies
+ "Sincronização concluída: %s troféu(s) em %s título(s) atribuídos ao seu perfil!", // TrophiesSyncedToast
++ "Aviso sobre Troféus", // TrophiesDisclaimerTitle
++ "A sincronização de troféus adiciona conquistas do Xbox diretamente ao seu perfil do PlayStation. Se você conectar esta conta à PSN para sincronizar, há chances de a conta ser banida. Ligue esta opção apenas em uma conta local (sem PSN) ou caso não pretenda mais se conectar à PSN.", // TrophiesDisclaimerBody
++ "Estou ciente", // TrophiesDisclaimerAware
++ "Cancelar", // TrophiesDisclaimerCancel
++ "Remover Troféus Sincronizados", // RemoveTrophies
++ "Remove todos os troféus adicionados pelo PSBox da conta local, evitando o risco de banimento. Você poderá adicioná-los novamente quando quiser a partir da conta Xbox.", // SettingDescRemoveTrophies
++ "Remover Troféus Sincronizados?", // RemoveTrophiesConfirmTitle
++ "Isso apagará os pacotes locais de troféus adicionados pelo PSBox para este perfil. Suas conquistas continuam salvas na sua conta Microsoft/Xbox.", // RemoveTrophiesConfirmBody
++ "Remover", // RemoveTrophiesConfirm
++ "Removido(s) %s título(s) de troféus deste perfil.", // TrophiesRemovedToast
};
diff --cc src/ui/strings.h
index 9edb6b4,dcbbffd..8d05ed4
--- a/src/ui/strings.h
+++ b/src/ui/strings.h
@@@ -424,13 -424,10 +424,27 @@@ enum class Str
InQueueEstimated,
F2pPreviewRequiredDesc,
F2pPreviewAccountNeededDesc,
+ MenuPlayer, // game menu, a USB controller's: the player it plays as
+ CloudTimeUp, // the server ended the stream: the account's (or game's) cloud time ran out
+ EndedIdle, // toast: the server ended the stream after a while without input
+ CloudTimeLeft, // top bar / game menu: "%s" = the cloud time left ("4 h 10 min")
+ CloudTimeOf, // top bar, after CloudTimeLeft: "%s" = the month's hours
+ CloudTimeUnlimited, // top bar: the account has no cloud time limit
+ CloudTimeWarn, // notification while streaming: "%s" = the cloud time left
+ SyncTrophies,
+ SettingDescSyncTrophies,
+ RunSyncTrophies,
+ TrophiesSyncedToast,
++ TrophiesDisclaimerTitle,
++ TrophiesDisclaimerBody,
++ TrophiesDisclaimerAware,
++ TrophiesDisclaimerCancel,
++ RemoveTrophies,
++ SettingDescRemoveTrophies,
++ RemoveTrophiesConfirmTitle,
++ RemoveTrophiesConfirmBody,
++ RemoveTrophiesConfirm,
++ TrophiesRemovedToast,
Count
};
diff --cc tests/test_main.cpp
index 0635fa4,65655f4..0401e32
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@@ -6914,221 -6771,373 +6922,587 @@@ static void testReleaseV155Features()
std::system(("rm -rf " + testDir).c_str());
}
+#if defined(__x86_64__) || defined(_M_X64)
+#include <emmintrin.h>
+#endif
+
+static void testPs4VideoPipelineAndSse2Converter() {
+ using namespace xc;
+ // 1. HwDecoder::Picture default state including pending flag
+ media::HwDecoder::Picture hp;
+ CHECK(!hp.error);
+ CHECK(!hp.pending);
+ CHECK(hp.data == nullptr);
+
+ // 1b. Verify PS4 HW decoder ring buffer slot progression during decode and flush
+ constexpr size_t kOutputSlots = 6;
+ auto simulateSlotAdvance = [](size_t currentSlot, bool decodeAccepted, bool needsFlush, bool flushAccepted) -> size_t {
+ size_t slot = currentSlot;
+ size_t outSlotUsed = slot;
+ if (decodeAccepted) {
+ slot = (outSlotUsed + 1) % kOutputSlots;
+ }
+ if (needsFlush) {
+ size_t flushSlot = slot;
+ if (flushAccepted) {
+ slot = (flushSlot + 1) % kOutputSlots;
+ }
+ }
+ return slot;
+ };
+ // Case A: decode accepted buffer, valid frame immediately (no flush needed) -> advances 1
+ CHECK(simulateSlotAdvance(0, true, false, false) == 1);
+ // Case B: decode accepted buffer, !valid -> flush accepts next slot -> advances 2
+ CHECK(simulateSlotAdvance(0, true, true, true) == 2);
+ // Case C: decode accepted buffer, !valid -> flush flushes without accepting new buffer -> advances 1
+ CHECK(simulateSlotAdvance(0, true, true, false) == 1);
+ // Case D: decode did not accept buffer, !valid -> flush accepts buffer -> advances 1
+ CHECK(simulateSlotAdvance(0, false, true, true) == 1);
+ // Case E: neither accepts buffer -> advances 0
+ CHECK(simulateSlotAdvance(0, false, true, false) == 0);
+ // Case F: wrap-around at ring boundary (slot 5 + 2 -> slot 1)
+ CHECK(simulateSlotAdvance(5, true, true, true) == 1);
+
+ // 2. ImageCache::stop() idempotency (called in coreShutdown before destructor)
+ {
+ ui::ImageCache cache([] {}, 4u << 20);
+ cache.stop();
+ cache.stop();
+ }
+
+#if defined(__x86_64__) || defined(_M_X64)
+ // 3. Verify 8-pixel 16-bit SSE2 BT.709 Limited Range kernel and 3/2 (720p->1080p) shuffle
+ auto colorRgbEightTest = [](__m128i y16, __m128i u16, __m128i v16, __m128i& p_lo, __m128i& p_hi) {
+ const __m128i y_bias = _mm_set1_epi16(16);
+ const __m128i uv_bias = _mm_set1_epi16(128);
+ const __m128i zero16 = _mm_setzero_si128();
+ const __m128i round = _mm_set1_epi32(128);
+ const __m128i k_y_r = _mm_set1_epi32((403 << 16) | (298 & 0xFFFF));
+ const __m128i k_y_b = _mm_set1_epi32((541 << 16) | (298 & 0xFFFF));
+ const __m128i k_y_gu = _mm_set1_epi32(((-55 & 0xFFFF) << 16) | (298 & 0xFFFF));
+ const __m128i k_gv_0 = _mm_set1_epi32(-137 & 0xFFFF);
+ const __m128i alpha = _mm_set1_epi16(static_cast<short>(0xFF00));
+
+ __m128i c = _mm_max_epi16(_mm_sub_epi16(y16, y_bias), zero16);
+ __m128i d = _mm_sub_epi16(u16, uv_bias);
+ __m128i e = _mm_sub_epi16(v16, uv_bias);
+
+ __m128i ce_lo = _mm_unpacklo_epi16(c, e);
+ __m128i ce_hi = _mm_unpackhi_epi16(c, e);
+ __m128i cd_lo = _mm_unpacklo_epi16(c, d);
+ __m128i cd_hi = _mm_unpackhi_epi16(c, d);
+ __m128i e0_lo = _mm_unpacklo_epi16(e, zero16);
+ __m128i e0_hi = _mm_unpackhi_epi16(e, zero16);
+
+ __m128i r_lo = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(ce_lo, k_y_r), round), 8);
+ __m128i r_hi = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(ce_hi, k_y_r), round), 8);
+
+ __m128i g_lo = _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(_mm_madd_epi16(cd_lo, k_y_gu), _mm_madd_epi16(e0_lo, k_gv_0)), round), 8);
+ __m128i g_hi = _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(_mm_madd_epi16(cd_hi, k_y_gu), _mm_madd_epi16(e0_hi, k_gv_0)), round), 8);
+
+ __m128i b_lo = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(cd_lo, k_y_b), round), 8);
+ __m128i b_hi = _mm_srai_epi32(_mm_add_epi32(_mm_madd_epi16(cd_hi, k_y_b), round), 8);
+
+ __m128i r16 = _mm_packs_epi32(r_lo, r_hi);
+ __m128i g16 = _mm_packs_epi32(g_lo, g_hi);
+ __m128i b16 = _mm_packs_epi32(b_lo, b_hi);
+
+ __m128i r8 = _mm_packus_epi16(r16, r16);
+ __m128i g8 = _mm_packus_epi16(g16, g16);
+ __m128i b8 = _mm_packus_epi16(b16, b16);
+
+ __m128i rg = _mm_unpacklo_epi8(r8, g8);
+ __m128i ba = _mm_or_si128(_mm_unpacklo_epi8(b8, zero16), alpha);
+ p_lo = _mm_unpacklo_epi16(rg, ba);
+ p_hi = _mm_unpackhi_epi16(rg, ba);
+ };
+
+ // Test boundary Y values: Y=0 (sub-black), Y=16 (black), Y=235 (white), Y=255 (super-white) with neutral UV=128
+ __m128i y16 = _mm_setr_epi16(0, 16, 235, 255, 16, 235, 0, 255);
+ __m128i u16 = _mm_set1_epi16(128);
+ __m128i v16 = _mm_set1_epi16(128);
+ __m128i p_lo, p_hi;
+ colorRgbEightTest(y16, u16, v16, p_lo, p_hi);
+ alignas(16) uint32_t px[8] = {};
+ _mm_store_si128(reinterpret_cast<__m128i*>(px), p_lo);
+ _mm_store_si128(reinterpret_cast<__m128i*>(px + 4), p_hi);
+ CHECK(px[0] == 0xFF000000u); // Y=0 clamped to black
+ CHECK(px[1] == 0xFF000000u); // Y=16 -> black
+ CHECK(px[2] == 0xFFFFFFFFu); // Y=235 -> white
+ CHECK(px[3] == 0xFFFFFFFFu); // Y=255 clamped to white
+
+ // Test 3/2 horizontal register shuffle ([0, 0, 1, 2], [2, 3, 4, 4], [5, 6, 6, 7])
+ __m128i s_lo = _mm_setr_epi32(10, 20, 30, 40);
+ __m128i s_hi = _mm_setr_epi32(50, 60, 70, 80);
+ __m128i out0 = _mm_shuffle_epi32(s_lo, _MM_SHUFFLE(2, 1, 0, 0));
+ __m128i p23 = _mm_srli_si128(s_lo, 8);
+ __m128i p44 = _mm_shuffle_epi32(s_hi, _MM_SHUFFLE(0, 0, 0, 0));
+ __m128i out1 = _mm_unpacklo_epi64(p23, p44);
+ __m128i out2 = _mm_shuffle_epi32(s_hi, _MM_SHUFFLE(3, 2, 2, 1));
+ alignas(16) uint32_t scaled[12] = {};
+ _mm_store_si128(reinterpret_cast<__m128i*>(scaled + 0), out0);
+ _mm_store_si128(reinterpret_cast<__m128i*>(scaled + 4), out1);
+ _mm_store_si128(reinterpret_cast<__m128i*>(scaled + 8), out2);
+ const uint32_t expected[12] = {10, 10, 20, 30, 30, 40, 50, 50, 60, 70, 70, 80};
+ for (int i = 0; i < 12; ++i) {
+ CHECK(scaled[i] == expected[i]);
+ }
+
+ // Test unpackNv12UvEight and red conversion (verifying V channel is preserved, not zeroed)
+ auto unpackNv12UvEightTest = [](const uint8_t* uvPtr, __m128i& u16, __m128i& v16) {
+ const __m128i mask_low = _mm_set1_epi16(0x00FF);
+ __m128i uv_bytes = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(uvPtr));
+ __m128i uv_dup = _mm_unpacklo_epi16(uv_bytes, uv_bytes);
+ u16 = _mm_and_si128(uv_dup, mask_low);
+ v16 = _mm_srli_epi16(uv_dup, 8);
+ };
+
+ alignas(16) const uint8_t sampleUv[8] = {10, 20, 30, 40, 50, 60, 70, 80};
+ __m128i testU16, testV16;
+ unpackNv12UvEightTest(sampleUv, testU16, testV16);
+ alignas(16) uint16_t uArr[8] = {};
+ alignas(16) uint16_t vArr[8] = {};
+ _mm_store_si128(reinterpret_cast<__m128i*>(uArr), testU16);
+ _mm_store_si128(reinterpret_cast<__m128i*>(vArr), testV16);
+ const uint16_t expectedU[8] = {10, 10, 30, 30, 50, 50, 70, 70};
+ const uint16_t expectedV[8] = {20, 20, 40, 40, 60, 60, 80, 80};
+ for (int i = 0; i < 8; ++i) {
+ CHECK(uArr[i] == expectedU[i]);
+ CHECK(vArr[i] == expectedV[i]);
+ }
+
+ // Pure Red (BT.709): Y=54, U=100, V=239. Must convert to vibrant red (R > 200), not green/cyan (R=0)!
+ alignas(16) const uint8_t redUv[8] = {100, 239, 100, 239, 100, 239, 100, 239};
+ __m128i redY16 = _mm_set1_epi16(54);
+ __m128i redU16, redV16, redP_lo, redP_hi;
+ unpackNv12UvEightTest(redUv, redU16, redV16);
+ colorRgbEightTest(redY16, redU16, redV16, redP_lo, redP_hi);
+ alignas(16) uint32_t redPx[8] = {};
+ _mm_store_si128(reinterpret_cast<__m128i*>(redPx), redP_lo);
+ _mm_store_si128(reinterpret_cast<__m128i*>(redPx + 4), redP_hi);
+ uint32_t rVal = redPx[0] & 0xFF;
+ uint32_t gVal = (redPx[0] >> 8) & 0xFF;
+ uint32_t bVal = (redPx[0] >> 16) & 0xFF;
+ CHECK(rVal > 200);
+ CHECK(gVal < 40);
+ CHECK(bVal < 40);
+#endif
+
+ // 4. Verify per-flip ptime timestamp resolution & stale observation rejection after >1s stall
+ auto resolveFlipShownUs = [](int64_t flipArg, uint64_t ptime, uint64_t nowUs, uint64_t procNowUs,
+ int64_t subMarker, uint64_t subUs, uint64_t subProcUs) -> uint64_t {
+ uint64_t shownUs = 0;
+ if (subMarker == flipArg && subUs > 0) {
+ if (ptime > 0 && ptime >= subProcUs && ptime <= procNowUs) {
+ shownUs = subUs + (ptime - subProcUs);
+ } else if (nowUs >= subUs && (nowUs - subUs) <= 50000ULL) {
+ shownUs = nowUs;
+ }
+ }
+ return shownUs;
+ };
+ // Case A: Flip submitted at t=100,000 us, flipped at ptime=108,333 us (+8.33ms), but observed 2.05s later
+ // after a network stall (t=2,156,400 us). Must resolve to 108,333 us (8.33ms), NOT 2,156,400 us!
+ CHECK(resolveFlipShownUs(42, 108333ULL, 2156400ULL, 2156400ULL, 42, 100000ULL, 100000ULL) == 108333ULL);
+ // Case B: Emulator/invalid ptime (0) observed 2.05s later after a stall -> must be rejected (0), never 2,156,400 us!
+ CHECK(resolveFlipShownUs(42, 0ULL, 2156400ULL, 2156400ULL, 42, 100000ULL, 100000ULL) == 0ULL);
+ // Case C: Emulator/invalid ptime (0) observed promptly within 8ms -> accepted as nowUs
+ CHECK(resolveFlipShownUs(42, 0ULL, 108000ULL, 108000ULL, 42, 100000ULL, 100000ULL) == 108000ULL);
+
+ // 5. Verify 1080p coded height (1920x1088) framebuffer sizing covers full 1088 luma + 540 chroma rows
+ const size_t minCoded1088 = static_cast<size_t>(1920) * 1088 * 3 / 2 + 64;
+ const size_t underSized1080 = static_cast<size_t>(1920) * 1080 * 3 / 2;
+ const size_t rawFrameSize = std::max<size_t>(underSized1080, minCoded1088);
+ const size_t alignedFrameSize = (rawFrameSize + 0x4000 - 1) & ~(static_cast<size_t>(0x4000) - 1);
+ const size_t requiredNv12OffsetEnd = static_cast<size_t>(1920) * 1088 + static_cast<size_t>(1920) * (1080 / 2);
+ CHECK(alignedFrameSize >= requiredNv12OffsetEnd);
+
+ // 6. Verify SWAR Canvas::gradientV and opaque Canvas::drawImage alpha blending
+ {
+ ui::Canvas c(32, 16);
+ c.clear(ui::rgba(20, 40, 60, 255));
+ c.gradientV({0, 0, 32, 16}, ui::rgba(0, 0, 0, 0), ui::rgba(10, 20, 30, 200));
+ CHECK((c.data()[0] & 0x00FFFFFFu) == (ui::rgba(20, 40, 60, 255) & 0x00FFFFFFu));
+ ui::Image img;
+ img.w = 16;
+ img.h = 16;
+ img.opaque = true;
+ img.px.assign(16 * 16, ui::rgba(200, 100, 50, 255));
+ c.drawImage(img, 0, 0, 128, 0);
+ uint32_t blended = c.data()[0];
+ CHECK(((blended >> 24) & 0xFF) == 0xFF);
+ CHECK((blended & 0xFF) > 100 && (blended & 0xFF) < 120);
+ }
+}
+
+ static void testTrophySystem() {
+ using namespace xc::trophy;
+
+ // 1. Gamerscore to Trophy grade conversion rules
+ // <= 50G -> Bronze
+ CHECK(scoreToGrade(0) == TrophyGrade::Bronze);
+ CHECK(scoreToGrade(5) == TrophyGrade::Bronze);
+ CHECK(scoreToGrade(20) == TrophyGrade::Bronze);
+ CHECK(scoreToGrade(50) == TrophyGrade::Bronze);
+ // 55G..99G -> Silver
+ CHECK(scoreToGrade(55) == TrophyGrade::Silver);
+ CHECK(scoreToGrade(75) == TrophyGrade::Silver);
+ CHECK(scoreToGrade(99) == TrophyGrade::Silver);
+ // >= 100G -> Gold
+ CHECK(scoreToGrade(100) == TrophyGrade::Gold);
+ CHECK(scoreToGrade(150) == TrophyGrade::Gold);
+ CHECK(scoreToGrade(200) == TrophyGrade::Gold);
+
+ // Grade to string & points
+ CHECK(std::string(gradeToString(TrophyGrade::Bronze)) == "Bronze");
+ CHECK(std::string(gradeToString(TrophyGrade::Silver)) == "Silver");
+ CHECK(std::string(gradeToString(TrophyGrade::Gold)) == "Gold");
+ CHECK(std::string(gradeToString(TrophyGrade::Platinum)) == "Platinum");
+
+ CHECK(gradeToPoints(TrophyGrade::Bronze) == 15);
+ CHECK(gradeToPoints(TrophyGrade::Silver) == 30);
+ CHECK(gradeToPoints(TrophyGrade::Gold) == 90);
+ CHECK(gradeToPoints(TrophyGrade::Platinum) == 300);
+
+ // Platinum automatic award calculation
+ CHECK(!hasEarnedPlatinum(0, 0));
+ CHECK(!hasEarnedPlatinum(0, 10));
+ CHECK(!hasEarnedPlatinum(9, 10));
+ CHECK(hasEarnedPlatinum(10, 10));
+ CHECK(hasEarnedPlatinum(11, 10));
+
+ // 2. Known cross-platform titles (Scenario A: Fortnite pilot, etc.)
+ const auto* fortnite = findKnownTitle("267695549", "");
+ CHECK(fortnite != nullptr);
+ CHECK(fortnite->titleName == "Fortnite");
+ CHECK(fortnite->npCommId == "NPWR20561_00");
+ CHECK(fortnite->sonyTitleId == "PPSA01922");
+ CHECK(fortnite->productId == "BT5P2X999VH2");
+
+ const auto* fortniteByProd = findKnownTitle("", "BT5P2X999VH2");
+ CHECK(fortniteByProd == fortnite);
+
+ const auto* minecraft = findKnownTitle("1828326430", "");
+ CHECK(minecraft != nullptr);
+ CHECK(minecraft->npCommId == "NPWR18283_00");
+
+ // 3. Mapping for titles without fixed known entry
+ std::string haloNp = generateNpCommId("2144722883");
+ std::string haloSony = generateSonyTitleId("2144722883");
+ CHECK(haloNp.rfind("NPWR", 0) == 0);
+ CHECK(haloNp.size() == 12); // NPWRXXXXX_00
+ CHECK(haloNp.substr(haloNp.size() - 3) == "_00");
+ CHECK(haloSony.rfind("PPSA", 0) == 0);
+ // Deterministic: same input gives exact same output
+ CHECK(haloNp == generateNpCommId("2144722883"));
+ CHECK(haloSony == generateSonyTitleId("2144722883"));
+
+ // 4. resolveTitleSet mapping
+ std::vector<xcloud::Achievement> achs;
+ xcloud::Achievement a1;
+ a1.id = "1";
+ a1.name = "Gunsmith";
+ a1.gamerscore = 20;
+ a1.unlocked = true;
+ achs.push_back(a1);
+
+ xcloud::Achievement a2;
+ a2.id = "2";
+ a2.name = "Hero";
+ a2.gamerscore = 60;
+ a2.unlocked = false;
+ achs.push_back(a2);
+
+ xcloud::Achievement a3;
+ a3.id = "3";
+ a3.name = "Legend";
+ a3.gamerscore = 100;
+ a3.unlocked = false;
+ achs.push_back(a3);
+
+ TitleTrophySet titleSet = resolveTitleSet("267695549", "BT5P2X999VH2", "Fortnite", achs);
+ CHECK(titleSet.npCommId == "NPWR20561_00");
+ CHECK(titleSet.totalCount == 3);
+ CHECK(titleSet.unlockedCount == 1);
+ CHECK(titleSet.items.size() == 3);
+ CHECK(titleSet.items[0].grade == TrophyGrade::Bronze);
+ CHECK(titleSet.items[1].grade == TrophyGrade::Silver);
+ CHECK(titleSet.items[2].grade == TrophyGrade::Gold);
+
+ // Name normalization
+ CHECK(normalizeTrophyName("Gunsmith") == "gunsmith");
+ CHECK(normalizeTrophyName("Take Out 10 Enemies!") == "takeout10enemies");
+
+ // 4b. Test buildUcp and buildTrpTitleDat
+ std::vector<uint8_t> ucpBytes;
+ std::vector<uint8_t> sha1;
+ CHECK(buildUcp(titleSet, ucpBytes, &sha1));
+ CHECK(ucpBytes.size() > 1024);
+ CHECK(ucpBytes[0] == 0xb2 && ucpBytes[1] == 0x28 && ucpBytes[2] == 0xc6 && ucpBytes[3] == 0x0a);
+ CHECK(sha1.size() == 20);
+ // UCP header at 0x1c must contain genuine SHA-1 digest
+ CHECK(memcmp(ucpBytes.data() + 0x1c, sha1.data(), 20) == 0);
+
+ std::vector<uint8_t> datBytes;
+ CHECK(buildTrpTitleDat(titleSet, 0x1ea2f4da, datBytes, sha1.data()));
+ CHECK(datBytes.size() > 2048);
+ CHECK(memcmp(datBytes.data(), "T2PD", 4) == 0);
+ CHECK(memcmp(datBytes.data() + 0x40, "T2TD", 4) == 0);
+ // Tag 0x0100 in TRPTITLE.DAT must match genuine UCP SHA-1 digest
+ CHECK(memcmp(datBytes.data() + 0x250, sha1.data(), 20) == 0);
+
+ // 4c. Test buildParamJson for Fortnite and general titles
+ std::string fnParam = buildParamJson("PPSA01922", "Fortnite");
+ CHECK(fnParam.find("\"titleId\": \"PPSA01922\"") != std::string::npos);
+ CHECK(fnParam.find("\"contentId\": \"UP1477-PPSA01922_00-FORTNITECORE0001\"") != std::string::npos);
+ CHECK(fnParam.find("\"conceptId\": \"210118\"") != std::string::npos);
+ CHECK(fnParam.find("\"appType\": 1") != std::string::npos);
+ CHECK(fnParam.find("\"attribute3\": 1835012") != std::string::npos);
+ CHECK(fnParam.find("\"titleName\": \"Fortnite\"") != std::string::npos);
+
+ std::string genericParam = buildParamJson("PPSA12345", "Custom Game");
+ CHECK(genericParam.find("\"titleId\": \"PPSA12345\"") != std::string::npos);
+
+ // 4d. Full official Fortnite Save the World 45-achievement set mapping
+ std::vector<xcloud::Achievement> fnAchs;
+ for (int i = 1; i <= 45; ++i) {
+ xcloud::Achievement ach;
+ ach.id = std::to_string(i);
+ ach.name = "Fortnite Achievement " + std::to_string(i);
+ ach.gamerscore = (i == 29 || i == 40 || i == 44) ? 50 : 20;
+ fnAchs.push_back(ach);
+ }
+ fnAchs[28].name = "All Tied Up"; // ID 29 (0-indexed 28)
+ fnAchs[39].name = "Anjo da Guarda"; // ID 40 (0-indexed 39)
+ fnAchs[43].name = "Plays Well with Others"; // ID 44 (0-indexed 43)
+ fnAchs[22].name = "Plankerton livre"; // ID 23
+ fnAchs[25].name = "Amped for Expansion"; // ID 26
+ fnAchs[26].name = "Desencana!"; // ID 27
+ fnAchs[27].name = "Into the Night"; // ID 28
+ fnAchs[36].name = "Coisas malvadas com uns dentões"; // ID 37
+ fnAchs[37].name = "Talented Builder"; // ID 38
+ fnAchs[38].name = "Vai Gnomo!"; // ID 39
+ fnAchs[40].name = "Loot Legend"; // ID 41
+ fnAchs[41].name = "World Explorer"; // ID 42
+ fnAchs[42].name = "Horrores Inenarráveis"; // ID 43
+
+ TitleTrophySet fnSet = resolveTitleSet("267695549", "BT5P2X999VH2", "Fortnite", fnAchs);
+ CHECK(fnSet.npCommId == "NPWR20561_00");
+ CHECK(fnSet.totalCount == 45);
+ int goldCount = 0, silverCount = 0, bronzeCount = 0;
+ for (const auto& item : fnSet.items) {
+ if (item.grade == TrophyGrade::Gold) goldCount++;
+ else if (item.grade == TrophyGrade::Silver) silverCount++;
+ else if (item.grade == TrophyGrade::Bronze) bronzeCount++;
+ }
+ CHECK(goldCount == 3);
+ CHECK(silverCount == 10);
+ CHECK(bronzeCount == 32);
+
+ // Test UTF-8 Portuguese accent folding in normalizeTrophyName
+ CHECK(normalizeTrophyName("Coisas malvadas com uns dent\u00f5es") == "coisasmalvadascomunsdentoes");
+ CHECK(normalizeTrophyName("Horrores Inenarr\u00e1veis") == "horroresinenarraveis");
+ CHECK(normalizeTrophyName("Vai, Gnomo!") == "vaignomo");
+
+ // Test single-item Fortnite grade resolution by ID and by name (regardless of totalCount)
+ std::vector<xcloud::Achievement> singleAch;
+ xcloud::Achievement ach29;
+ ach29.id = "29";
+ ach29.name = "Coisas malvadas com uns dent\u00f5es"; // Silver
+ ach29.gamerscore = 20;
+ singleAch.push_back(ach29);
+ TitleTrophySet singleSet = resolveTitleSet("267695549", "BT5P2X999VH2", "Fortnite", singleAch);
+ CHECK(singleSet.items.size() == 1);
+ CHECK(singleSet.items[0].grade == TrophyGrade::Silver);
+
+ // Verify UCP builds with Platinum metadata
+ std::vector<uint8_t> fnUcp;
+ CHECK(buildUcp(fnSet, fnUcp));
+ std::string ucpStr(reinterpret_cast<const char*>(fnUcp.data()), fnUcp.size());
+ CHECK(ucpStr.find("Hero of the Storm") != std::string::npos);
+ CHECK(ucpStr.find("Her\u00f3i da Tempestade") != std::string::npos);
+
+ // Test convertTo512Png helper with a minimal valid 1x1 PNG
+ static const uint8_t kTinyPng[67] = {
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
+ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
+ 0x89, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x00, 0x01, 0x00, 0x00,
+ 0x05, 0x00, 0x01, 0x0d, 0x0a, 0x2d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
+ 0x42, 0x60, 0x82
+ };
+ CHECK(!is512x512Png(kTinyPng, sizeof(kTinyPng)));
+ std::vector<uint8_t> dummyPng;
+ CHECK(convertTo512Png(kTinyPng, sizeof(kTinyPng), dummyPng));
+ CHECK(is512x512Png(dummyPng.data(), dummyPng.size()));
+ CHECK(genericParam.find("\"contentId\": \"UP0001-PPSA12345_00-0000000000000000\"") != std::string::npos);
+ CHECK(genericParam.find("\"titleName\": \"Custom Game\"") != std::string::npos);
+
+ // 4d. Test buildNpTitleDat
+ std::vector<uint8_t> npTitle;
+ CHECK(buildNpTitleDat("PPSA01922", npTitle));
+ CHECK(npTitle.size() == 160);
+ CHECK(memcmp(npTitle.data(), "NPTD", 4) == 0);
+ CHECK(memcmp(npTitle.data() + 0x10, "PPSA01922_00", 12) == 0);
+
+ // 4e. Test buildTrpTitleDat append-only merging & timestamp preservation
+ // Setup initial DAT where trophy 1 is unlocked with custom timestamp
+ TitleTrophySet initialSet = titleSet;
+ initialSet.items[0].unlocked = true;
+ initialSet.items[1].unlocked = false;
+ initialSet.items[2].unlocked = false;
+ std::vector<uint8_t> initialDat;
+ CHECK(buildTrpTitleDat(initialSet, 0x1ea2f4da, initialDat, sha1.data()));
+
+ std::map<uint32_t, ExistingTrophyRecord> parsedInitial;
+ CHECK(parseTrpTitleDat(initialDat.data(), initialDat.size(), parsedInitial));
+ CHECK(parsedInitial.count(1) > 0);
+ CHECK(parsedInitial[1].state == 1);
+ uint64_t t1OriginalTs = parsedInitial[1].timestamp;
+
+ // Simulate new sync where Xbox reports trophy 2 unlocked, but trophy 1 is offline/missing (unlocked=false)
+ TitleTrophySet nextSet = titleSet;
+ nextSet.items[0].unlocked = false; // missing in current sync!
+ nextSet.items[1].unlocked = true; // newly unlocked
+ nextSet.items[2].unlocked = false;
+
+ std::vector<uint8_t> mergedDat;
+ CHECK(buildTrpTitleDat(nextSet, 0x1ea2f4da, mergedDat, sha1.data(), &initialDat));
+
+ std::map<uint32_t, ExistingTrophyRecord> parsedMerged;
+ CHECK(parseTrpTitleDat(mergedDat.data(), mergedDat.size(), parsedMerged));
+ // Trophy 1 MUST be preserved 100% with original timestamp!
+ CHECK(parsedMerged.count(1) > 0);
+ CHECK(parsedMerged[1].state == 1);
+ CHECK(parsedMerged[1].timestamp == t1OriginalTs);
+ // Trophy 2 MUST be newly unlocked
+ CHECK(parsedMerged.count(2) > 0);
+ CHECK(parsedMerged[2].state == 1);
+ CHECK(parsedMerged[2].timestamp > 0);
+ // Trophy 3 remains locked
+ CHECK(parsedMerged.count(3) > 0);
+ CHECK(parsedMerged[3].state == 0);
+
+
+ // 5. Mock ITrophyBackend & TrophySyncEngine integration
+ class TestBackend : public ITrophyBackend {
+ public:
+ bool init(uint32_t uid) override {
+ userId = uid;
+ return true;
+ }
+ bool registerTitle(const TitleTrophySet& set) override {
+ registered = true;
+ return true;
+ }
+ bool unlockTrophy(const std::string& npComm, int tid, TrophyGrade g, const std::string& n) override {
+ for (const auto& u : unlocked) {
+ if (u.npCommId == npComm && u.trophyId == tid) return true;
+ }
+ unlocked.push_back({npComm, tid, g});
+ return true;
+ }
+ bool isTrophyUnlocked(const std::string& npComm, int tid) override {
+ for (const auto& u : unlocked) {
+ if (u.npCommId == npComm && u.trophyId == tid) return true;
+ }
+ return false;
+ }
+ std::string name() const override { return "TestBackend"; }
+
+ struct UnlockedItem {
+ std::string npCommId;
+ int trophyId;
+ TrophyGrade grade;
+ };
+ uint32_t userId = 0;
+ bool registered = false;
+ std::vector<UnlockedItem> unlocked;
+ };
+
+ auto backendPtr = std::make_unique<TestBackend>();
+ TestBackend* rawBackend = backendPtr.get();
+ TrophySyncEngine engine(std::move(backendPtr));
+ CHECK(engine.init(0x1ea2f4da));
+ CHECK(rawBackend->userId == 0x1ea2f4da);
+
+ std::string baseDir = platform::dataDir();
+ if (baseDir.empty()) baseDir = ".";
+ std::string cacheFile = baseDir + "/trophies/267695549.json";
+ ::unlink(cacheFile.c_str());
+
+ // Mock network transport for achievements
+ net::setTestTransport([&](const net::Request& req) -> net::Response {
+ net::Response res;
+ if (req.url.find("achievements.xboxlive.com") != std::string::npos) {
+ res.status = 200;
+ res.body = R"({
+ "achievements": [
+ {
+ "id": "101",
+ "name": "First Step",
+ "description": "Completed first step",
+ "progressState": "Achieved",
+ "rewards": [{"type": "Gamerscore", "value": "20"}],
+ "mediaAssets": [{"name": "Icon", "url": "https://img/icon1.png"}]
+ },
+ {
+ "id": "102",
+ "name": "Big Step",
+ "description": "Completed big step",
+ "progressState": "Achieved",
+ "rewards": [{"type": "Gamerscore", "value": "100"}],
+ "mediaAssets": [{"name": "Icon", "url": "https://img/icon2.png"}]
+ }
+ ],
+ "pagingInfo": {"totalItems": 2}
+ })";
+ return res;
+ }
+ res.status = 404;
+ return res;
+ });
+
+ int newlyUnlocked = 0;
+ std::string syncErr;
+ bool syncOk = engine.syncTitleAchievements("Bearer mockToken", "25332749", "267695549", "Fortnite",
+ newlyUnlocked, syncErr);
+ CHECK(syncOk);
+ // Both 101 and 102 were unlocked (2 achievements = 100% -> awards Platinum too: total 3!)
+ CHECK(newlyUnlocked == 3);
+ CHECK(rawBackend->unlocked.size() == 3);
+ CHECK(rawBackend->unlocked[0].grade == TrophyGrade::Bronze);
+ CHECK(rawBackend->unlocked[0].trophyId == 1);
+ CHECK(rawBackend->unlocked[1].grade == TrophyGrade::Gold);
+ CHECK(rawBackend->unlocked[1].trophyId == 2);
+ CHECK(rawBackend->unlocked[2].grade == TrophyGrade::Platinum);
+ CHECK(rawBackend->unlocked[2].trophyId == kPlatinumTrophyId); // Trophy ID 0
+
+ // Verify rich JSON cache persistence
+ std::string cacheSaved;
+ CHECK(platform::readFile(cacheFile, cacheSaved));
+ auto jCache = json::parse(cacheSaved);
+ CHECK(jCache && jCache->isObject());
+ CHECK((*jCache)["xboxTitleId"].str() == "267695549");
+ CHECK((*jCache)["unlockedCount"].asInt() == 2);
+ CHECK((*jCache)["trophies"].isArray());
+ CHECK((*jCache)["trophies"].items().size() == 2);
+
+ // Repeat sync: snapshot is cached, 0 newly unlocked
+ newlyUnlocked = 0;
+ syncOk = engine.syncTitleAchievements("Bearer mockToken", "25332749", "267695549", "Fortnite",
+ newlyUnlocked, syncErr);
+ CHECK(syncOk);
+ CHECK(newlyUnlocked == 0); // No duplicate unlocks!
+ CHECK(rawBackend->unlocked.size() == 3);
+
+ // Clean up
+ net::setTestTransport({});
+ ::unlink(cacheFile.c_str());
+ }
+
int main() {
+ testPs4VideoPipelineAndSse2Converter();
+ testTrophySystem();
testReleaseV155Features();
testSizedUrl();
testPhase1BugFixesAndPhase2Optimizations();