Play your Steam library's Windows games on a jailbroken PS5.
C++
feat(artwork): disk cache, banner fallback and framing
sain.sajid2249c2ada4d
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex 2646f66..db20c51 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -259,7 +259,7 @@ add_library(playden_homebrew_artwork STATICtarget_compile_features(playden_homebrew_artwork PUBLIC cxx_std_20)target_include_directories(playden_homebrew_artwork PUBLIC "${CMAKE_SOURCE_DIR}/src"PRIVATE "${PLAYDEN_STB_IMAGE_INCLUDE_DIR}" "${CMAKE_SOURCE_DIR}/third_party/ps5-homebrew-ui/third_party/stb")-target_link_libraries(playden_homebrew_artwork PUBLIC playden_library playden_steam_http)+target_link_libraries(playden_homebrew_artwork PUBLIC playden_library playden_steam_http playden_managed_directory)add_library(playden_homebrew_artwork_cache STATIC "${CMAKE_SOURCE_DIR}/src/homebrew/artwork_cache.cpp")target_compile_features(playden_homebrew_artwork_cache PUBLIC cxx_std_20)diff --git a/src/homebrew/artwork_backend.cpp b/src/homebrew/artwork_backend.cppindex 5529022..9cf392d 100644--- a/src/homebrew/artwork_backend.cpp+++ b/src/homebrew/artwork_backend.cpp@@ -1,16 +1,24 @@#include "homebrew/artwork_backend.hpp"+#include "platform/managed_directory.h"#include "steam/backend/http_client.h"#include <algorithm>+#include <atomic>#include <climits>#include <cstddef>#include <cstdlib>#include <cstdint>+#include <ctime>+#include <filesystem>#include <limits>#include <memory>+#include <mutex>#include <string>#include <utility>+#include <vector>+#include <sys/stat.h>+#include <unistd.h>namespace {@@ -112,6 +120,8 @@ namespace playden::homebrew {namespace {constexpr std::uint32_t kArtworkTimeoutMs = 10'000;+// Cached artwork expires after 14 days so updated Steam covers refresh.+constexpr std::time_t kArtworkCacheTtlSeconds = 14 * 24 * 3600;bool CheckedImageBytes(int width, int height, std::size_t& bytes) {if (width <= 0 || height <= 0 ||@@ -136,8 +146,81 @@ bool CanonicalKey(const ArtworkKey& key) {return false;}+std::string CacheFileName(const ArtworkKey& key) {+ if (key.account_generation == 0 || !key.game_id.valid() || key.source.empty()) return {};+ const std::string id = ToKey(key.game_id);+ if (id.empty()) return {};+ if (key.source.find("library_600x900.jpg") != std::string::npos) return id + "_600x900.jpg";+ if (key.source.find("library_hero.jpg") != std::string::npos) return id + "_hero.jpg";+ if (key.source.find("logo.png") != std::string::npos) return id + "_logo.png";+ return {};+}++ArtworkImage FrameToPortrait(const ArtworkImage& src, std::uint32_t target_w = 600, std::uint32_t target_h = 900) {+ if (src.width == 0 || src.height == 0 || src.width <= src.height) return src;+ ArtworkImage out;+ out.width = target_w;+ out.height = target_h;+ out.rgba.resize(target_w * target_h * 4, 0);++ const int banner_h = static_cast<int>(target_w * src.height / src.width);+ const int offset_y = static_cast<int>((target_h - banner_h) / 2);+ const int bottom_margin = static_cast<int>(target_h) - (offset_y + banner_h);++ for (std::uint32_t y = 0; y < target_h; ++y) {+ for (std::uint32_t x = 0; x < target_w; ++x) {+ const std::size_t out_idx = (y * target_w + x) * 4;+ if (static_cast<int>(y) >= offset_y && static_cast<int>(y) < offset_y + banner_h) {+ const std::uint32_t sx = std::min(x * src.width / target_w, src.width - 1);+ const std::uint32_t sy = std::min((y - offset_y) * src.height / banner_h, src.height - 1);+ const std::size_t in_idx = (sy * src.width + sx) * 4;+ out.rgba[out_idx] = src.rgba[in_idx];+ out.rgba[out_idx + 1] = src.rgba[in_idx + 1];+ out.rgba[out_idx + 2] = src.rgba[in_idx + 2];+ out.rgba[out_idx + 3] = 255;+ } else {+ const std::uint32_t sx = std::min(x * src.width / target_w, src.width - 1);+ const std::uint32_t sy = (static_cast<int>(y) < offset_y) ? 0 : (src.height - 1);+ const std::size_t in_idx = (sy * src.width + sx) * 4;+ const float factor = (static_cast<int>(y) < offset_y)+ ? (offset_y > 0 ? (0.4f * static_cast<float>(y) / static_cast<float>(offset_y)) : 0.0f)+ : (bottom_margin > 0 ? (0.4f * static_cast<float>(target_h - 1 - y) / static_cast<float>(bottom_margin)) : 0.0f);+ out.rgba[out_idx] = static_cast<std::uint8_t>(src.rgba[in_idx] * factor);+ out.rgba[out_idx + 1] = static_cast<std::uint8_t>(src.rgba[in_idx + 1] * factor);+ out.rgba[out_idx + 2] = static_cast<std::uint8_t>(src.rgba[in_idx + 2] * factor);+ out.rgba[out_idx + 3] = 255;+ }+ }+ }+ return out;+}+} // namespace+struct HttpArtworkBackend::Cache {+ std::mutex mutex;+ std::optional<platform::ManagedDirectory> dir;++ bool EnsureDir(const std::string& path) {+ if (dir && dir->Validate()) return true;+ if (path.empty()) return false;+ const std::filesystem::path target = std::filesystem::path(path).lexically_normal();+ dir = platform::ManagedDirectory::Open(target, platform::DirectoryPolicy::kPrivate);+ if (dir) return true;++ const auto parent_path = target.parent_path();+ const auto child_name = target.filename().string();+ auto parent = platform::ManagedDirectory::Open(parent_path, platform::DirectoryPolicy::kApprovedTree);+ if (!parent) parent = platform::ManagedDirectory::Open(parent_path, platform::DirectoryPolicy::kPrivateTraversable);+ if (!parent) parent = platform::ManagedDirectory::Open(parent_path, platform::DirectoryPolicy::kPrivate);+ if (parent) {+ dir = parent->OpenChild(child_name, platform::DirectoryPolicy::kPrivate, /*create=*/true, 0700);+ if (dir) return true;+ }+ return false;+ }+};+std::optional<ArtworkImage> artwork_internal::DecodeArtworkWithAllocationBudget(const std::vector<std::uint8_t>& encoded, std::size_t allocation_limit) {if (encoded.empty() || encoded.size() > kMaxArtworkTransferBytes ||@@ -180,8 +263,11 @@ std::optional<ArtworkImage> DecodeArtwork(encoded, kMaxArtworkDecodeAllocationBytes);}-HttpArtworkBackend::HttpArtworkBackend(std::string ca_bundle)- : ca_bundle_(std::move(ca_bundle)) {}+HttpArtworkBackend::HttpArtworkBackend(std::string ca_bundle, std::string cache_dir)+ : ca_bundle_(std::move(ca_bundle)),+ cache_dir_(std::move(cache_dir)),+ http_(std::make_unique<steam::HttpClient>(ca_bundle_)),+ cache_(cache_dir_.empty() ? nullptr : std::make_unique<Cache>()) {}HttpArtworkBackend::~HttpArtworkBackend() = default;@@ -191,14 +277,144 @@ std::optional<ArtworkImage> HttpArtworkBackend::Load(return std::nullopt;if (!http_) http_ = std::make_unique<steam::HttpClient>(ca_bundle_);+ const std::string file_name = CacheFileName(key);+ bool cache_expired = false;++ // 1. Check persistent on-disk cache under ManagedDirectory+ if (!file_name.empty() && cache_) {+ std::lock_guard<std::mutex> lock(cache_->mutex);+ if (cache_->EnsureDir(cache_dir_)) {+ struct stat st{};+ if (cache_->dir->InspectChild(file_name, &st) && S_ISREG(st.st_mode) &&+ st.st_size > 0 && static_cast<std::size_t>(st.st_size) <= kMaxArtworkTransferBytes) {+ const std::time_t now = std::time(nullptr);+ cache_expired = (now >= st.st_mtime && (now - st.st_mtime) >= kArtworkCacheTtlSeconds);+ if (!cache_expired) {+ const int fd = cache_->dir->OpenRegularFile(file_name);+ if (fd >= 0) {+ std::vector<std::uint8_t> bytes(static_cast<std::size_t>(st.st_size));+ std::size_t offset = 0;+ bool read_ok = true;+ while (offset < bytes.size()) {+ const auto count = read(fd, bytes.data() + offset, bytes.size() - offset);+ if (count < 0 && errno == EINTR) continue;+ if (count <= 0) { read_ok = false; break; }+ offset += static_cast<std::size_t>(count);+ }+ close(fd);+ if (read_ok && offset == bytes.size()) {+ auto image = DecodeArtwork(bytes);+ if (image) {+ if (key.source.find("library_600x900.jpg") != std::string::npos &&+ image->width > image->height) {+ image = FrameToPortrait(*image);+ }+ return image;+ }+ }+ }+ }+ }+ }+ }++ if (cancel.load(std::memory_order_acquire)) return std::nullopt;++ // 2. Fetch from Steam CDNsteam::HttpRequest request;request.method = steam::HttpMethod::kGet;request.url = key.source;request.timeout_ms = kArtworkTimeoutMs;request.max_response_bytes = kMaxArtworkTransferBytes;auto response = http_->Perform(request, cancel);- if (!response.ok() || response.status_code != 200) return std::nullopt;- return DecodeArtwork(response.body);++ // If library_600x900.jpg returned 404, fallback to header.jpg (standard Steam banner)+ if ((!response.ok() || response.status_code != 200) &&+ key.source.find("library_600x900.jpg") != std::string::npos &&+ !cancel.load(std::memory_order_acquire)) {+ const std::string base = "https://cdn.cloudflare.steamstatic.com/steam/apps/" ++ ToKey(key.game_id) + "/";+ steam::HttpRequest fallback_req = request;+ fallback_req.url = base + "header.jpg";+ auto fallback_resp = http_->Perform(fallback_req, cancel);+ if (fallback_resp.ok() && fallback_resp.status_code == 200) {+ response = std::move(fallback_resp);+ }+ }++ if (!response.ok() || response.status_code != 200) {+ // Offline / network failure fallback to existing cached image if expired+ if (cache_expired && !file_name.empty() && cache_) {+ std::lock_guard<std::mutex> lock(cache_->mutex);+ if (cache_->EnsureDir(cache_dir_)) {+ struct stat st{};+ if (cache_->dir->InspectChild(file_name, &st) && st.st_size > 0 &&+ static_cast<std::size_t>(st.st_size) <= kMaxArtworkTransferBytes) {+ const int fd = cache_->dir->OpenRegularFile(file_name);+ if (fd >= 0) {+ std::vector<std::uint8_t> bytes(static_cast<std::size_t>(st.st_size));+ std::size_t offset = 0;+ bool read_ok = true;+ while (offset < bytes.size()) {+ const auto count = read(fd, bytes.data() + offset, bytes.size() - offset);+ if (count < 0 && errno == EINTR) continue;+ if (count <= 0) { read_ok = false; break; }+ offset += static_cast<std::size_t>(count);+ }+ close(fd);+ if (read_ok && offset == bytes.size()) {+ auto img = DecodeArtwork(bytes);+ if (img) {+ if (key.source.find("library_600x900.jpg") != std::string::npos &&+ img->width > img->height) {+ img = FrameToPortrait(*img);+ }+ return img;+ }+ }+ }+ }+ }+ }+ return std::nullopt;+ }++ // 3. Atomically write downloaded cover to cache via ManagedDirectory+ if (!file_name.empty() && cache_ && !response.body.empty() &&+ response.body.size() <= kMaxArtworkTransferBytes) {+ std::lock_guard<std::mutex> lock(cache_->mutex);+ if (cache_->EnsureDir(cache_dir_)) {+ static std::atomic<std::uint64_t> sequence{0};+ const std::string temp_name = "." + file_name + "." + std::to_string(getpid()) + "." ++ std::to_string(sequence.fetch_add(1)) + ".tmp";+ const int fd = cache_->dir->CreateExclusiveFile(temp_name, 0600);+ if (fd >= 0) {+ std::size_t offset = 0;+ bool write_ok = true;+ while (offset < response.body.size()) {+ const auto count = write(fd, response.body.data() + offset, response.body.size() - offset);+ if (count < 0 && errno == EINTR) continue;+ if (count <= 0) { write_ok = false; break; }+ offset += static_cast<std::size_t>(count);+ }+ const bool synced = write_ok && (fsync(fd) == 0);+ const bool closed = (close(fd) == 0);+ if (synced && closed) {+ cache_->dir->RenameChild(temp_name, *cache_->dir, file_name, /*replace_existing=*/true);+ cache_->dir->Sync();+ } else {+ if (!closed) close(fd);+ cache_->dir->RemoveRegularFile(temp_name);+ }+ }+ }+ }++ auto image = DecodeArtwork(response.body);+ if (image && key.source.find("library_600x900.jpg") != std::string::npos && image->width > image->height) {+ image = FrameToPortrait(*image);+ }+ return image;}} // namespace playden::homebrewdiff --git a/src/homebrew/artwork_backend.hpp b/src/homebrew/artwork_backend.hppindex 522d9e7..f7f17a7 100644--- a/src/homebrew/artwork_backend.hpp+++ b/src/homebrew/artwork_backend.hpp@@ -29,7 +29,7 @@ std::optional<ArtworkImage> DecodeArtworkWithAllocationBudget(class HttpArtworkBackend final : public ArtworkBackend {public:- explicit HttpArtworkBackend(std::string ca_bundle);+ explicit HttpArtworkBackend(std::string ca_bundle, std::string cache_dir = "");~HttpArtworkBackend() override;HttpArtworkBackend(const HttpArtworkBackend&) = delete;HttpArtworkBackend& operator=(const HttpArtworkBackend&) = delete;@@ -37,9 +37,14 @@ class HttpArtworkBackend final : public ArtworkBackend {std::optional<ArtworkImage> Load(const ArtworkKey&, const std::atomic<bool>& cancel) override;+ const std::string& cache_dir() const noexcept { return cache_dir_; }+private:+ struct Cache;std::string ca_bundle_;+ std::string cache_dir_;std::unique_ptr<steam::HttpClient> http_;+ std::unique_ptr<Cache> cache_;};} // namespace playden::homebrewdiff --git a/src/homebrew/host.cpp b/src/homebrew/host.cppindex b86c534..22b4114 100644--- a/src/homebrew/host.cpp+++ b/src/homebrew/host.cpp@@ -676,7 +676,8 @@ int main(int argc, char** argv) {}if (!options->simulation) {- artwork_backend = std::make_unique<playden::homebrew::HttpArtworkBackend>(PLAYDEN_HOMEBREW_CA_BUNDLE);+ const std::string art_cache_dir = (options->data_directory / "art").string();+ artwork_backend = std::make_unique<playden::homebrew::HttpArtworkBackend>(PLAYDEN_HOMEBREW_CA_BUNDLE, art_cache_dir);artwork = std::make_unique<playden::homebrew::ArtworkService>(*artwork_backend);}auto render = std::make_unique<playden::homebrew::Render>(PLAYDEN_HOMEBREW_ASSETS_DIR, artwork.get());diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex 9fec7db..a75fe4f 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -242,6 +242,7 @@ int main() {// After the grant, user data, logs and games live outside the app folder (0.6 layout).log_root = playden::ps5::EffectiveLogRoot(paths);const std::string user_root = playden::ps5::EffectiveUserRoot(paths);+ const std::string art_cache_dir = paths.runtime_data_root.empty() ? std::string{} : (paths.runtime_data_root + "/art");// Startup checkpoints: a launch that never shows its first frame can be told// apart from one that never opened the display.playden::app::AppendLogLine(log_root, "launch.log", "display open width=" + std::to_string(display.width()) +@@ -525,12 +526,12 @@ int main() {std::fclose(file);if (!bytes.empty()) generic_icon = std::move(bytes);}- config.title_icon = [trust = paths.trust_store, generic_icon](const playden::GameId& game) -> std::optional<std::string> {+ config.title_icon = [trust = paths.trust_store, art_cache_dir, generic_icon](const playden::GameId& game) -> std::optional<std::string> {// A store with no cover for the game (an imported one) gets the generic icon.const auto source = playden::homebrew::CoverUrl(game);std::optional<playden::homebrew::ArtworkImage> cover;if (!source.empty()) {- playden::homebrew::HttpArtworkBackend backend(trust);+ playden::homebrew::HttpArtworkBackend backend(trust, art_cache_dir);const std::atomic<bool> cancel{false};cover = backend.Load({1, game, source}, cancel);}@@ -764,7 +765,7 @@ int main() {#if PLAYDEN_UI_SIMULATIONplayden::homebrew::Render renderer(paths.assets_root);#else- playden::homebrew::HttpArtworkBackend artwork_backend(paths.trust_store);+ playden::homebrew::HttpArtworkBackend artwork_backend(paths.trust_store, art_cache_dir);playden::homebrew::ArtworkService artwork(artwork_backend);playden::homebrew::Render renderer(paths.assets_root, &artwork);#endifdiff --git a/tests/homebrew_artwork_backend_test.cpp b/tests/homebrew_artwork_backend_test.cppindex 3c52320..d781476 100644--- a/tests/homebrew_artwork_backend_test.cpp+++ b/tests/homebrew_artwork_backend_test.cpp@@ -1,11 +1,14 @@#include "homebrew/artwork_backend.hpp"+#include "platform/managed_directory.h"#include <atomic>#include <cassert>#include <cstdio>#include <cstdint>+#include <filesystem>#include <string>#include <vector>+#include <unistd.h>#include "steam_id.h"using namespace playden::homebrew;@@ -162,6 +165,36 @@ void InvalidHttpIdentityIsRejectedWithoutTransport() {assert(!backend.Load({1, SteamId(42), "https://cdn.cloudflare.steamstatic.com/steam/apps/42/header.jpg"}, cancel));}+void ReadsFromManagedDiskCache() {+ char pattern[] = "/tmp/playden-art-cache-XXXXXX";+ if (::mkdtemp(pattern)) {+ const std::filesystem::path root = std::filesystem::canonical(pattern);+ const std::filesystem::path art_dir = root / "art";+ auto parent = playden::platform::ManagedDirectory::Open(root, playden::platform::DirectoryPolicy::kApprovedTree);+ assert(parent);+ auto managed = parent->OpenChild("art", playden::platform::DirectoryPolicy::kPrivate, true, 0700);+ assert(managed);++ const int fd = managed->CreateExclusiveFile("42_600x900.jpg", 0600);+ assert(fd >= 0);+ const auto jpeg = SmallJpeg();+ assert(::write(fd, jpeg.data(), jpeg.size()) == static_cast<ssize_t>(jpeg.size()));+ assert(::fsync(fd) == 0 && ::close(fd) == 0);+ assert(managed->Sync());++ HttpArtworkBackend backend("unused-ca.pem", art_dir.string());+ assert(backend.cache_dir() == art_dir.string());+ std::atomic<bool> cancel{false};+ const auto image = backend.Load(+ {1, SteamId(42),+ "https://cdn.cloudflare.steamstatic.com/steam/apps/42/library_600x900.jpg"},+ cancel);+ assert(image && image->width > 0 && image->height > 0);++ std::filesystem::remove_all(root);+ }+}+} // namespaceint main(int argc, char** argv) {@@ -183,4 +216,5 @@ int main(int argc, char** argv) {RejectsEmptyCorruptAndTransferOverflow();RejectsOversizedPngDimensionsBeforePixelAllocation();InvalidHttpIdentityIsRejectedWithoutTransport();+ ReadsFromManagedDiskCache();}