Xbox Cloud Gaming app for PS5 Homebrew
C
feat(ps4): add PS4 port with multi-target build pipeline and CE-34878-0 loader fixes
Rafael Abud Ferreiraf51c5197aef2
diff --git a/.gitignore b/.gitignoreindex 3626333..0a9a698 100644--- a/.gitignore+++ b/.gitignore@@ -12,3 +12,6 @@ __pycache__/# Local notes (user feedback collected from Reddit): never in the repository.reddit/+/ps4-toolchain/+docs/archive/+assets/media_showcase/diff --git a/CMakeLists.txt b/CMakeLists.txtindex 543c556..de27842 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -10,6 +10,7 @@ set(CMAKE_EXPORT_COMPILE_COMMANDS ON)# XCLOUD_PS5 is set by cmake/ps5.toolchain.cmake.option(XCLOUD_PS5 "Build for the PS5 (payload SDK)" OFF)+option(XC_TARGET_PS4 "Build for the PS4 (OpenOrbis)" OFF)include(cmake/platform.cmake)# --- Portable core: auth, HTTPS, xCloud protocol -----------------------------@@ -56,10 +57,14 @@ endif()# mbedTLS and libdatachannel are built from deps/ for both targets.include(cmake/deps/mbedtls.cmake)target_link_libraries(xcloud_core PUBLIC xc_mbedtls xc_platform)-if(NOT XCLOUD_PS5)+if(NOT XCLOUD_PS5 AND NOT XC_TARGET_PS4)find_package(Threads REQUIRED)endif()include(cmake/deps/libdatachannel.cmake)+if(XC_TARGET_PS4)+ target_compile_definitions(datachannel-static PUBLIC HAVE_SCONN_LEN HAVE_SA_LEN __Userspace__)+ target_compile_definitions(usrsctp PUBLIC HAVE_SCONN_LEN HAVE_SA_LEN __Userspace__)+endif()# --- WebRTC streaming: SDP/ICE, data channels, input reports ----------------add_library(xcloud_stream STATIC@@ -158,6 +163,46 @@ if(XCLOUD_PS5)# The USB keyboard / mouse backend kept the warnings it had in xcloud_core.set_source_files_properties(src/input/kbm_ps5.cpp PROPERTIES COMPILE_OPTIONS "-Wall;-Wextra;-Wno-unused-parameter")target_link_libraries(xcloud_app PUBLIC xcloud_stream xcloud_media xcloud_ui)+elseif(XC_TARGET_PS4)+ target_sources(xcloud_core PRIVATE+ src/platform/ps4/platform_ps4.cpp+ src/platform/ps4/keyboard_ps4.cpp+ src/platform/ps4/condition_variable_ps4.cpp+ src/platform/posix_common.cpp+ )++ add_executable(xcloud_ps4.elf+ $<TARGET_OBJECTS:xcloud_appcore>+ src/app/ps4_main.cpp+ src/app/shell_ps4.cpp+ src/display/display_ps4.cpp+ src/media/hw_decoder_ps4.cpp+ src/input/controller_ps4.cpp+ src/input/kbm_ps4.cpp+ src/media/audio_out_ps4.cpp+ src/media/audio_in_ps4.cpp+ )+ target_link_libraries(xcloud_ps4.elf PRIVATE+ xcloud_stream+ xcloud_media+ xcloud_ui+ xcloud_core+ xc_ffmpeg+ datachannel-static+ -lSceVideoOut+ -lScePad+ -lSceAudioOut+ -lSceAudioIn+ -lSceKeyboard+ -lSceMouse+ -lSceNet+ -lSceImeDialog+ -lSceCommonDialog+ -lSceUserService+ -lSceSystemService+ -lSceSysmodule+ -lkernel+ )else()target_link_libraries(xcloud_core PUBLIC Threads::Threads)if(WIN32 OR CMAKE_SYSTEM_NAME STREQUAL "Windows")@@ -207,7 +252,7 @@ endif()# --- The desktop app on SDL3 (psbox) ----------------------------------------# cmake/deps/sdl3.cmake decides (XCLOUD_DESKTOP_APP); xcloud-cli, xcloud-tests# and psbox-headless stay SDL-free either way.-if(NOT XCLOUD_PS5)+if(NOT XCLOUD_PS5 AND NOT XC_TARGET_PS4)include(cmake/deps/sdl3.cmake)endif()if(XC_DESKTOP_APP)diff --git a/ROADMAP.md b/ROADMAP.mdindex 5c7c36c..5e4b619 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -1,413 +1,97 @@-# Roadmap+# Roadmap — PSBox Cloud Gaming-Where PSBox Cloud Gaming goes next, most valuable first. Each item says why it-matters, what "done" looks like, and how it is measured on the console.-Status: **next** (being worked on), **planned**, **later**, **dropped**.+Planejamento e visão de futuro do projeto **PSBox Cloud Gaming**, priorizado por valor para o usuário no console PlayStation 5 (e ecossistema PlayStation).-Last update: 2026-10-23, v1.5.3.+Status: **Em andamento (next)**, **Planejado (planned)**, **Futuro (later)**, **Descartado (dropped)**.-## Now+> **Última atualização:** 26/10/2026 (após lançamento da versão estável **v1.5.4**).-### Suporte Nativo a Controles USB no PS5 (8BitDo Ultimate 2.4G, Xbox, DS4, Fightsticks) — next-Leitura direta dos nós USB de interrupção e HID no kernel do PS5 (`/dev/usb/*`, `/dev/ugen*`, `/dev/hid`) com permissões abertas `crw-rw-rw-`, contornando a whitelist restritiva da `libScePad` da Sony.-- **8BitDo Ultimate 2.4G**: Suporte nativo ao dongle USB em modo D-Input e X-Input sem necessidade de adaptadores adicionais.-- **DualShock 4 USB**: Liberação de controles de PS4 no PS5 para Jogador 1 ou multiplayer local (P2..P4).-- **Controles Xbox**: Suporte a Xbox 360 (com fio ou receptor sem fio USB), Xbox One e Series via USB-C.-- **Fightsticks & Arcade**: Mapeamento de controles arcade HID genéricos de 14/16 botões.--### Estudo de Viabilidade: Build Nativo PS4 (PSBox Cloud Gaming - PS4) — planned-Port dedicado e otimizado para o ecossistema PlayStation 4 (firmwares 9.00 / 11.00 com jailbreak):-- **Nome Isolado**: `PSBox Cloud Gaming - PS4` com pacote PKG separado (`CUSA99810.pkg`) para não colidir com o instalador do PS5 (`PPSA99810`).-- **Decodificação de Vídeo**: Avaliação de decodificação por hardware H.264 via `libSceVideoDec` do PS4 e renderização via Vulkan (libpiglet) ou OpenGL ES.-- **Releases e Atualizador Separados**: Canal de atualização próprio no in-app updater sem riscos de sobrescrita cruzada de binários entre PS4 e PS5.--### 1. Lower input-to-picture latency — done (v0.6.0)-Measured with `VK_KHR_present_wait`, from a frame's network arrival to the-moment it is on the TV: **~23 ms on average** at 60 Hz (decode ~6 ms, GPU-~3 ms, waiting for the next vblank ~8 ms on average). The earlier "13-48 ms"-stopped at `present()`, not at the screen.--- Each frame is submitted once the one before is on the screen (no queued- frames: the wait for a free image fell from 1-3 ms to 0.01 ms), and a frame- is skipped when a newer one is already waiting. Skipped frames in a 50 s- run: 85 → 35.-- The game menu shows "On screen after" (that measurement, live).-- **Next step, 120 Hz output** (halves the vblank wait, ~4 ms): the title- declares it with `attribute3 = 0x80040`; on our console the display still- offered only 59.94 Hz. To check: the TV's 120 Hz support and the PS5's- 120 Hz output setting, then re-registering the app.--### 2. Hardware video decoding — works, parked-RADV has no Vulkan Video on the PS5, but the system's own decoder-(`libSceVideodec2`, sysmodule 207) works from the app: H.264 1080p decodes to-NV12 (pitch 2048, coded 1088 rows) in **~6 ms**, the same as FFmpeg on the-CPU, as BlackBearReloaded's research measured too. So no latency gain at-1080p; it only frees a CPU core.--- Kept in `src/media/hw_decoder.*` (autoplay `hwdecode` runs it alongside and- logs it), with the PS5's own structure layouts and memory types.-- Becomes the way to go if 1440p / 4K or HEVC streams are ever granted.--### 3. Reconnect after a network drop — done (v0.6.0)-As the xbox.com client does: when the connection drops (a data channel or-WebRTC fails, or no video packet for 3 s), the stream tries again up to 20-times a second apart; each time it checks that the cloud session is still-`Provisioned` / `ReadyToConnect` and opens a new WebRTC connection on it.-The game goes on where it was. The server ending the session (idle kick,-the game closed) still ends the stream.--- Console test (autoplay `droptest`, the connection dropped at 20 s):- reconnected on the first attempt, ~8 s of frozen picture, then 60 fps again.-- To check by hand: a real outage (cable out / Wi-Fi off for ~10 s).--### Also in v0.6.0-- **DualSense light bar** in the colour of the game in focus (Settings).-- **Anime4K x2** as an upscaler beside FSR (game menu: Upscaling): crisper- outlines and text, but it also sharpens compression noise; ~1-2 ms more.- Next to try: Anime4K's Restore network before the upscale.-- **Free-to-play games** (#10): xbox.com's free-to-play row; one not on the- account yet shows FREE, with the store's QR code to get it, and Play.- The server refuses a free game until it is got once (`NoEntitlement`);- the app explains that and tries again. Got on the phone, it starts at once.-- **Windows outside the game** (Marvel Rivals' NetEase terms): touch input- is announced on while the game is out of focus; the page then shows its- own pad cursor. A touchpad pointer was tried and dropped (the page- ignored the touches, and it got in the way of the account picker).--### Remote Play (own Xbox) — done (v0.7.0)-The xhome offering takes the same Xbox token: "My consoles" lists the-account's consoles (`/v6/servers/home`), and a home session is started-with the console's serverId; the stream is the cloud one. Series X on the-same network: 1080p, 9-17 Mbps, 7-10 ms round trip. A sleeping Xbox wakes-through the session itself (~10 s); one that doesn't answer-(`WaitingForServerToRegister`) is asked again, then the app says what to-check. Also in v0.7.0: the Xbox button (game menu, or a swipe up on the-touchpad), "End the stream", a new session after a drop, and notes when-the Xbox ends or turns off the stream.--- Resolution: what each kind of stream delivers is measured (1080p for- both here; the browser gets 1080p from this Xbox too), and 1440p is only- offered once delivered. The own Xbox is always asked for its top tier:- ~15.7 Mbps instead of ~9.5.--### Picture clean-up — done (v0.8.0)-- **Anime4K Restore (S)** before the upscale, for FSR and Anime4K alike- ("+ clean-up" in the game menu, the default with FSR): on Fortnite at- ~5 Mbps, edges 50% stronger with the same noise in flat areas, and no- measurable latency (on screen 26-29 ms either way).-- **Auto block smoothing**: high below ~5 Mbps, low up to ~10, off above,- with 1 Mbps margins and 3 s before a change (the default).-- Settings from before v0.8.0 that still hold the old defaults move to- the new ones, once.--### Network reliability — done (v0.8.0)-Mbed TLS built with its own locking (MBEDTLS_THREADING_C): concurrent-HTTPS requests no longer fail with -0x006E ("This is a bug in the-library"), and a GET with no answer is retried once. Host stress test-(`xcloud-cli tls-stress`): 960 parallel requests, 0 failures (before: 2-runs in 3 failed).--### Safer changes and releases — done (v0.9.0)-- CI (`.github/workflows/ci.yml`): the desktop build and unit tests on- every push and pull request, and a scan of each pull request for tokens- and private files.-- `tools/release.sh <X.Y.Z> [out] [--console]`: checks the version,- contentVersion, tag and changes, builds and packages without the- account, checks inside the zip and eboot.bin, optionally streams on the- console, and prints the publish commands and the catalog record. It- publishes nothing.--### `ps5_main.cpp` split — done (v0.9.0)-It had grown to 1,586 lines. Now: `ps5_main.cpp` (start-up and the home-screen's loop), `worker.cpp` (sign-in, library, consoles, playing),-`stream_screen.cpp` (the game's menu, gestures, controllers, overlay),-`price_loop.cpp`, `autoplay.cpp` (the unattended tests) and-`auto_deband.cpp`, whose "auto" block smoothing now has unit tests.--### In-app updates — done (v0.9.0)-After sign-in the app asks for the latest release and offers a newer one-(a pop-up with "Update now" / "Not now", and Settings > Updates). The zip-must be signed (ECDSA P-256) with the maintainer's key, which-`tools/release.sh` uses; a package that isn't that version or isn't newer-is refused. Files are swapped in place with a backup (an update cut short-is rolled back at the next start), then the app restarts itself-(`sceSystemServiceLoadExec`, from the main thread).--### Controls and search — done (v0.9.0)-- Controller icons as DualSense silhouettes; the light bar's colour from- the game, a colour picker (live on the pad), or off; the confirm button- shown as its symbol, in force from the next press.-- Trigger vibration tester: strength, frequency, resistance (the DualSense- pushes back) and force pulses; the console takes trigger modes 0..3 only.-- Each stick's own dead zone, radial with rescaling, set in a stick tester.-- Search: Mode, Genre, Language (in the app's language) and Console lists;- Lowest price by the discounted price. Modes and languages come from the- store's full details, fetched once in the background and cached.--### Fast scrolling, inertia, fresher catalog and "All games" grid — done (v0.9.1)-- The right stick pages through the lists (3 rows up / down, 6 cards- sideways), and so does a swipe on the touchpad, with smooth inertia.-- "All games" (Game Pass) expands into a 6-column vertical grid: all 550+- titles accessible with 2D D-pad navigation, smooth vertical row scrolling,- and clean viewport clipping under the headers and tabs.-- Cached game details older than 30 days are fetched again, 40 per start,- oldest first.--### Per-game settings — done (v0.9.2)-- Custom profile per game (picture: sharpness, deband, upscaler, resolution;- triggers: strength, Hz, resistance, pulses; dead zones: left, right; controls:- circleConfirms).-- Overrides general settings for that game only; games without one seamlessly- use global settings.-- Configurable directly from the game details screen (`Screen::Details` via Options button) and in-game from the stream overlay menu (`StreamMenu`).-- Interactive stick and trigger testers accessible directly within the modal.-- "Restaurar padrão" (Reset to default) option cleanly restores global settings.--### Publisher filter, non-game add-on exclusion and 120 Hz display declaration — done (v0.9.3)-- Search filter by Publisher: 14 major publishers and parent groups (Xbox/Bethesda, EA, Ubisoft, Square Enix, Warner Bros, 2K, Capcom, SEGA, Bandai Namco, THQ Nordic, Focus, Devolver, Annapurna, Team17) plus Indies & Others, fully localized in all 6 languages.-- Non-game add-ons and digital extras (artbooks, soundtracks, upgrade packs) filtered out from library, shelves, and search pools.-- PS5 120 Hz high frame rate output declaration (`attribute3 = 524352` / `0x80040`) enabled in `param.json` for supported HDMI 2.1 displays with graceful fallback to 59.94 Hz.--### Friends playing now, UI decluttering and Gamerscore precision — done (v0.9.4)-- "Amigos jogando agora" dynamic Home shelf powered by Xbox Live PeopleHub v2 API, querying online friends and mapped to store products.-- Strict entitlement verification: only games that the user has access to (`playable == true`) appear; if no friends are in accessible games, the row has zero visual footprint.-- Multiple friends playing the same game are grouped onto a single card with circular gamerpic avatars, gamertags and `+N` badge indicator.-- Presence pill badge positioned in the bottom-left corner of cards in the friends row; redundant "GAME PASS" badge removed across all cards.-- Solid uniform 360° Gamerscore circle rendering via `Canvas::strokeCircle(...)` and pixel-perfect centering of the `'G'` glyph.--### Voice chat & DualSense hardware microphone integration — done (v0.9.5)-- Native PS5 audio input capture (`libSceAudioIn`) bound to active user ID (`input::padUserId`) at 48 kHz mono S16.-- Physical DualSense hardware mute button integration (`sceAudioInGetSilentState`): orange LED hardware muting controls audio transmission and in-game UI state in real-time.-- Real-time in-game VU meter: rounded sound-level pill in the `StreamMenu` with perceptual scaling and studio ballistic decay (~350 ms falloff) displaying live green voice activity, matching orange mute status when muted on the controller.-- DualSense vibration suppression during mic capture (`scePadSetVibrationTriggerEffectWeakWhileEmbeddedMicInUse`) prevents motor rumble noise bleed.-- Native FFmpeg Opus voice encoder (48 kHz, 1 ch, 24 kbps, 20 ms frames) streamed via WebRTC audio packets to cloud session.-- Fixed audio output muting by locking to primary `SCE_AUDIO_OUT_PORT_TYPE_MAIN` (port 0).-- Cleaned up StreamMenu: removed obsolete manual microphone and audio routing toggles.--### Reports, built-in certificates, region and store compatibility — done (v0.9.6)-- Built-in certificates: when `assets/cacert.pem` can't be read (#20, #38), a copy inside `eboot.bin` is used (reproduced #38's -15872 on the console: signs in).-- "Report a problem": Triangle on error screens and in Settings shows a QR code that opens the GitHub bug form filled in (version, firmware, the error, the log's important lines), private data removed (gamertag, PS5 user names, console names, IPs, tokens).-- Unexpected-close detection: a crash (signal or watchdog) leaves a marker; the next start offers the report. Closing from the PS menu doesn't.-- "Sign in as another country" (opt-in): offered only when xCloud refuses the sign-in; `X-Forwarded-For` on the login request only; Settings > Sign-in country. The real refusal is still to be checked with an account from an unsupported country.-- ProsperoStore updates keep the sign-in and settings (brought back from the store's copy of the old folder, once); release zips as 0777.-- Privacy and robustness: console names and raw service answers out of the log; sign-out clears the last account's library; the updater keeps its backup when a rollback fails; cut-short HTTP answers, 5xx/429 at sign-in, endless title paging, failed prices and images handled; request pacing to Microsoft's services; corrupt `settings.json` kept aside.-- The firmware is read from the kernel (13.60, not 13.590.001).--### Sign-in that stays, the console's clock, plan on the profile — done (v0.9.7)-- The user's data (sign-in, settings, caches, log) lives in `/data/psbox`, outside the app's folder: uninstalling, reinstalling or updating from ProsperoStore keeps it; the first start moves it from older versions. A data folder that can't be written falls back and says so; a sign-in that can't be saved is told. The updater writes where the app runs (`appDir`).-- Refused certificates are explained: the console's clock (expired / not yet valid, with the console's date) or something on the network answering for Microsoft's sites; a notification when the clock breaks some content even though sign-in works (#45).-- Profile: a drawn gamerscore badge and the Game Pass plan (`GAME PASS [ULTIMATE]`) from the store service (`http://mp.microsoft.com/` XSTS, `entitlements/bulk`), "GAME PASS" from the titles otherwise.-- Search keyboard: up / down go to the item under the focused one.-- Issues: rule-based triage (labels and one comment for known problems).--### Stream robustness, 120 Hz, network warning, rest mode — done (v0.9.8)-- Video: no more freeze of seconds after a burst of loss (the resync stopped at a frame with its own hole); a key frame asked again while none comes. Teardown: libdatachannel's callbacks cleared before the session goes. Audio: an empty packet no longer silences the rest of the session. The decoder no longer drops a packet it refused as full; microphone open/close serialized; per-frame error logs throttled.-- Controller: an unchanged pad resent every 50 ms (not ~125/s); after the picture stalled 1.5 s the pads are announced again.-- "Best" asks for 1440p exactly as xbox.com does (device info, session body, `/streaming/title/constrain`, physical size). The service still sends 1080p (H.264 4.2) at ~11–13 Mbps in motion; Tizen's "1080HQ" gave the same (p90 12.9 Mbps both): Microsoft's cap, not the request.-- Jump back in: the account's own games too (bought, free-to-play), not only Game Pass.-- Game page: the estimated wait to start the game beside Play (`/v1/waittime/{titleId}`).-- 120 Hz output (VRR), off by default, in Settings and per game, only while a game streams (the menus stay at 60 Hz: OLED flicker). param.json `0x40 | 0x40000`; RADV patched (`tools/ps5/patches`): a VRR output's idle vblank isn't taken for 60 Hz (reported as mihawk-99/PS5_Mesa#4), and the output switches at a stream's start and end.-- Network: "Unstable connection" while frames are lost, video stalls or the round trip jumps; a session summary at the end of each game (notification, log, reports).-- Audio queue cut back to 40 ms past 60 ms (it held up to 120 ms); Settings: maximum bitrate (Auto / 20 / 15 / 10 / 5 Mbps) and game volume (25–150 %).-- Rest mode: a stream reconnects on its own when the console wakes (tested); the crash guard no longer takes the suspended app for a stall.--### Keyboard & mouse, key remapping, gyro aiming, crash addresses — done (v1.0.0)-- USB keyboard and mouse (libSceKeyboard, libSceMouse loaded at run time): native mouse and keyboard to the games the cloud lists as MKB (229 of ~2750); for the others, the keyboard and mouse as a player's controller (keys 1-4 choose the player; WASD, mouse as the right stick, the wheel as Triangle). F12 opens the game menu, Home is the Xbox button.-- The app's screens by keyboard (arrows / WASD, Enter, Esc, Tab, Q / E tabs...), the hints switching to key caps as soon as a key is used; the players' row shows the keyboard in its player's slot.-- Keyboard keys: their own screen (Settings and each game's settings): two keys or mouse buttons per input, reserved keys refused, back to the defaults.-- Gyro aiming (DualSense): off / always / while L2 aims, intensity 1-10, in the game menu, saved in general or per game; left / right is the turn about the room's vertical (gravity), so a tilted pad aims as far sideways as up / down.-- Cards: the console's keyboard-and-mouse icon on MKB games, its controller icon on the others; a Mouse & keyboard search filter; the players' pads drawn with the console's controller icon.-- Settings grouped (language and sign-in country; stream; sound; controller and keyboard; updates last); the game settings likewise.-- Sign-in: the xCloud login is tried again on a 5xx (six tries over ~25 s); the renewed refresh token is saved at once. The queue's wait from `/v1/waittime/{titleId}` while queued; the pictures' quantiser (QP) in the statistics line.-- Crash reports: a fatal signal records the faulting instruction's offset in eboot (`pc=eboot+0x...`), the accessed address (`addr=0x...`) and the caller return addresses (`bt=...`), shown on the report panel and in the GitHub issue link; `tools/release.sh` keeps `symbols/vX.Y.Z/eboot.elf` (a development link with `tools/ps5/link.sh`: `symbols/vX.Y.Z-dev`) and `tools/symbolize.sh` translates offsets back to function and `file:line`.--### Multiplatform: Linux app, shared core — done (v1.1.0)-- One app core for every platform (`docs/multiplatform.md`): the PS5 code in `*_ps5.cpp` backends, null backends for tools and tests, `tools/check-platform-boundaries.sh` in CI.-- PSBox on Linux (`psbox`, SDL3): window (fullscreen by default, Display mode in Settings), video and menus, DualSense (adaptive triggers, light bar, gyro, touchpad; hot-plug), Xbox and generic pads (Xbox glyphs), keyboard and mouse (held during a game), typing in the search, audio and microphone, the options the PC can't honour hidden, Circle / Esc asks before quitting.-- Linux tarball built and attached by CI on each release (ubuntu-24.04); signed on the release machine (`tools/desktop/sign-linux-release.sh`).-- PS5: microphone gain fixed (50 % muted it, 150 % gave 200 %); the autoplay tests put the user's settings back; development links keep their symbols apart from a release's.--### Plan filter, remapping, desktop Vulkan, 1-click F2P claim, smart triggers & low-latency pipeline — done (v1.2.0–v1.3.2)-- Catalog by Game Pass plan (Essential / Premium / Ultimate / All filter, plan badges, `PassMetadataByPassProductId` hydration) and a Favourites row at the top of the library (Triangle on the game page).-- Per-game stream language selector (`GameProfile::locale`), passed to `gssv.startSession(...)`.-- 1-click free-to-play acquisition (`claimFreeProduct`): claims free Store licenses directly from the game details page without a QR code or external browser, refreshing the library in place.-- Input & DualSense: full DualSense button remapping (including Edge back paddles), touchpad as mouse for MKB games, accurate `physicalPhysicality` bitmask, unreliable/unordered input channel (protocol v9), 250 Hz DualSense polling, Smart Trigger profiles (*Standard*, *Shooter*, *Racing*) and sub-bass Audio-to-Haptics.-- Audio & video: PCM waveform extrapolation PLC (`AudioDecoder::conceal`) with 12 ms RTP gap detection, desktop Vulkan display (`display/gpu.cpp` shared with SDL3 Linux for FSR 1, Anime4K, RCAS, deband), PS5 swapchain flip-rate unpegging (`wsi_videoout_set_flip_rate(0)`), and an in-game performance HUD with a 60-frame frametime sparkline (`L3 + R3`).-- Performance & resilience: dynamic Zen 2 thread pinning, zero-allocation RTP ring buffer, instant frame-1 boot, HTTP keep-alive connection pooling, out-of-order X.509 TLS chain sorting, NanoDNS / missing-Gamertag diagnostics, and client support for Microsoft's monthly cloud playtime cap (`fetchPlaytimeLimit`, waiting for Microsoft to enable the quota).+----### Queue-ready chime, manual refresh, playtime, sign-in diagnostics, network test, achievements & wishlist — done (v1.3.3)-- **Queue-ready chime**: plays a pleasant chime (chunked 20 ms audio pulses via `AudioQueue`), triggers controller haptic vibration (`input::setRumble(160, 160, 400)`), and emits an in-app notice (`QueueReadyAlert`) when cloud queue waiting ends and the stream provisions.-- **Refresh the library by hand**: L3 button on the Home screen performs an in-place delta sync (`kReloadLibrary` / `Action::RefreshLibrary`), re-evaluating title list and entitlements without restarting the app.-- **Playtime per game on card & details page**: formats elapsed gameplay duration in hours and minutes, displaying a subtle badge on the card's top-left corner and a rounded pill with playtime on the game details page.-- **Sign-in diagnostics ("Check my sign-in")**: comprehensive XSTS error diagnostics for suspended/banned accounts (`2148916227`), missing profile (`2148916233`), unsupported regions (`2148916235`), adult/terms verification (`2148916236`/`2148916237`), and child family accounts (`2148916238`). Interactive 5-stage diagnostic tester modal in Settings (*Storage*, *Clock & TLS*, *Microsoft Account*, *Xbox Live & XSTS*, *xCloud & Plan*).-- **Network test in Settings**: probe modal measuring regional latency (RTT min/avg, jitter, packet loss %) across up to 8 regions, UDP/NAT STUN reachability, and bandwidth speed estimation with optimal region and bitrate recommendations.-- **Achievements on game page**: queries Xbox Live Achievements v2 contract (`achievements.xboxlive.com`), displays an official Gamerscore badge pill with unlocked count and score on Details, and provides a scrollable in-modal achievement browser (`L3` on Details) with checkmarks, descriptions, secret masks, and Gamerscore rewards.-- **Store wishlist**: toggle titles on Details with `R3`, persists to `settings.json`, renders a dedicated "Lista de desejos" / "Wishlist" shelf in Library immediately after Favorites, and polls background price/catalog loops to emit notifications when wishlist games go on sale or enter Game Pass.+## 🐛 Bugs Prioritários & Correções Imediatas (High-Priority Fixes)-### Web control, age ratings, AppImage package, bitrate slider & boot chime — done (v1.4.0)-- **Local Web UI (port 8080)**: embedded asynchronous micro HTTP server with right-side QR code in Settings, remote keyboard for TV search, interactive controller/keyboard remapping with live sync, and direct sanitized `xcloud.log` download.-- **Official age rating badges**: ClassInd (Brazil), ESRB (US), and PEGI (Europe) color-coded badges and content descriptors on the game details page.-- **Universal Linux AppImage**: standalone bundle (`tools/desktop/package-appimage.sh`) packaging SDL3 runtime, desktop integration, and full compatibility with Steam Deck / SteamOS.-- **Bitrate slider & DualSense speaker volume**: inline slider for bitrate caps (5 to 50 Mbps / Auto) and controller speaker volume slider (0% to 100% / Mute) in StreamMenu and Settings.-- **Direct free-to-play claim & boot sound**: in-console 1-click Store entitlement claim for free trials and F2P games; official boot chime (`ps5/sce_sys/snd0.at9`) on app launch.+### 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.-## Next+### 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`).-| Priority | Item | Why | Size |-| :---: | --- | --- | --- |-| **1** | **Hardware video decoding (PS5 & other platforms)** (done) | Integrated `libSceVideodec2` (sysmodule 207) into the active streaming pipeline (`StreamPlayer`) on PS5 freeing a Zen 2 CPU core, reducing jitter/thermals, and mapping NV12 to Vulkan textures; VA-API / NVDEC via FFmpeg hwaccel enabled on desktop/Steam Deck | medium–large |-| **2** | **Expanded WebUI features & in-stream Game Menu** (done) | Expanded local HTTP server (port 8080): **Streaming Lock** (transparent overlay and HTTP 409 rejection blocking search/filters while playing), **Virtual Touch Gamepad** on mobile browsers (full Xbox buttons, D-pad, dual virtual analog sticks, triggers/bumpers, View/Menu/Nexus, P1 main & P2 local co-op hot-join), full general settings (bitrate slider, 120 Hz, dead zones, light bar, trigger vibration, queue alert), real-time in-stream `StreamMenu` control (CAS sharpness, FSR 1/Anime4K upscalers, deband, pad speaker volume, smart trigger profiles), and live session telemetry (FPS/RTT/loss) | medium |-| **2b** | **WebSocket RFC 6455 in WebUI** (done) | Full WebSocket handshake and binary/JSON framing on port 8080 (`/ws`): sub-5ms touch gamepad input latency with TCP_NODELAY, live 60 fps telemetry stream to mobile browsers, and seamless fallback to HTTP REST | medium |-| **3** | **Mouse navigation in desktop UI** (done) | On desktop/Steam Deck menus, mouse hover updates focus, left click triggers cards/buttons/tabs/options, mouse wheel scrolls shelves and the 550+ title vertical grid; strictly desktop-only (`XCLOUD_DESKTOP_APP`), inactive on PS5 | small–medium |-| **4a** | **Native Windows build** (done) | Cross-compilation support with `llvm-mingw` (or native MSVC/CMake), Windows platform backend (`src/platform/windows/`), SDL3/Vulkan backend, XInput & DualSense integration, standalone packaging script (`tools/desktop/package-windows.sh`) | medium |-| **4b** | **Native Android build** (done) | Android NDK (C++20) + Java/Kotlin wrapper scaffolding (`android/`), hardware video decoding via `AMediaCodec` (`src/media/hw_decoder_android.cpp`), and Bluetooth gamepad support | large |-| **5** | **Adaptive Voice Chat (DualSense mic & speaker with fallback)** (done) | Optional voice routing: when using DualSense, route incoming voice chat to controller speaker while game audio stays on TV; transparent fallback for generic Xbox controllers, USB/P2 headsets or PC to use standard system mic and main audio mix without blocking | medium |-| **5b** | **Multi-Controller USB Driver on PS5 (UHID)** (done) | Direct `/dev/uhid*` driver on jailbroken PS5 supporting 8BitDo Ultimate 2.4G (`0x2DC8:0x3106`), Xbox 360 wired/wireless receiver (`0x045E:0x028E`/`0x0719`), Xbox One/Series USB (`0x045E:0x02D1`/`0x02DD`/`0x0B12`), DualShock 4 USB (`0x054C:0x05C4`/`0x09CC`), and generic D-Input arcade fightsticks without requiring `libScePad` | medium |-| **5c** | **Advanced Audio-to-Haptics on DualSense** (done) | Real-time 120 Hz IIR biquad sub-bass filter on 48 kHz PCM stream with anti-denormal RMS envelope detector, translating explosions and rumble to DualSense voice-coil haptics; settings option (*Off*, *Low*, *Medium*, *High*) | small–medium |-| **5d** | **Offline Cache & Instant-Resume Library** (done) | Persistent `library_cache.json` in user data directory; instant 0.01s initial load of Home shelves and metadata before network sync, resilient against network dropouts with sign-out hygiene | small |-| **6** | Cloud playtime left (done in client; waiting for Microsoft) | From November 2026 cloud play is capped each month (Ultimate 15 h, Premium 10 h, Essential 5 h). Client support is ready (`AuthManager::fetchPlaytimeLimit`), waiting for Microsoft to enable quota | small–medium |-| **7** | Home-screen tile per game (later) | The PS5 Forwarder Format (ProsperoLight): generate standalone tiles on the PS5 home screen that directly launch a cloud game (deprioritized to end of roadmap) | small |+----### Technical Feasibility Study: 8BitDo Ultimate 2.4G USB Dongle on PS5+## 🚀 Em Andamento e Próximos Passos (Now & Next)-**Context & Hardware Architecture**:-The 8BitDo Ultimate 2.4G wireless controller connects via its bundled 2.4 GHz USB RF adapter (`VID 0x2DC8`, `PID 0x3106`) or over Bluetooth. In standard operation, the 2.4G dongle acts as an X-Input or D-Input USB composite HID device.+### 1. Port Nativo para PlayStation 4 (PSBox Cloud Gaming - PS4) — *next*+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.-**PlayStation 5 Subsystem & Security Analysis**:-1. **FreeBSD / Prospero Kernel Subsystem**:- - The PS5 kernel (`sys/dev/usb`) detects and enumerates the 8BitDo 2.4G USB dongle as a generic USB device (`ugen` / `uhid`).- - The kernel creates device nodes under `/dev/uhid*` and exposes raw USB transfer endpoints.-2. **Sony Userland (`libScePad`) Whitelist & Security Enforcement**:- - Sony's userland input framework (`libScePad` and `libScePadCustom`) strictly limits pad handles to official Sony hardware: DualSense (`VID 0x054C`, `PID 0x0CE6`), DualSense Edge (`PID 0x0DF2`), and third-party controllers equipped with an authorized Sony cryptographic hardware coprocessor.- - The console's security coprocessor performs periodic encrypted challenge-response authentication handshakes with the controller.- - Unlicensed USB controllers and third-party 2.4G dongles fail this handshake or are ignored by `libScePad`, which returns invalid pad handles.-3. **Bluetooth Pairing Limitations**:- - PS5 Bluetooth stack enforces Sony-specific EAP authentication handshakes and BD_ADDR filtering during device pairing.- - Pairing generic Bluetooth gamepads or 8BitDo controllers in Bluetooth mode directly to the PS5 fails during discovery/handshake.+### 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:+- **8BitDo Ultimate 2.4G**: Suporte nativo ao dongle USB em modo D-Input e X-Input.+- **DualShock 4 USB**: Liberação de controles de PS4 no PS5 para Jogador 1 ou multiplayer local (P2..P4).+- **Controles Xbox**: Suporte a Xbox 360 (com fio ou receptor sem fio USB), Xbox One e Series via USB-C.+- **Fightsticks & Arcade**: Mapeamento direto de controles arcade HID genéricos de 14/16 botões.-**Viable Implementation Paths**:-- **Path 1: WebUI Virtual Gamepad (Zero Extra Hardware, Zero Jailbreak Dependency) — *Implemented in v1.4.0***:- - Users can pair the 8BitDo controller (via Bluetooth or USB OTG) to their smartphone, tablet, or laptop, open `http://<ps5-ip>:8080/`, and control the PS5 stream directly over Wi-Fi.- - Supports Player 1 (main control) or Player 2 (seamless co-op hot-joining in active streams).-- **Path 2: Hardware Converter Adapters (Zero Code, 100% Native DualSense Emulation)**:- - Hardware translation converters (such as Brook Wingman XE 2, Brook FGC, or Mayflash Magic-S Pro 2) handle the Sony hardware challenge-response authentication while interfacing with the 8BitDo 2.4G dongle.- - The PS5 sees a fully authorized DualSense device with full input fidelity.-- **Path 3: Direct Userland USB HID Driver (`uhid` / `libusb`) on Jailbroken PS5 — *Planned (Priority 5b)***:- - On jailbroken consoles (Prospero 3.xx–4.xx), homebrew userland can bypass `libScePad` entirely by opening `/dev/uhid*` directly or using `libusb`.- - A lightweight driver module (`src/input/pad_usb.cpp`) will read raw HID reports from the 8BitDo dongle in D-Input mode (16-byte report: 2 analog sticks, 2 triggers, 14 digital buttons), map them into `input::ControllerState`, and merge them directly into `input::mergePads` alongside or in place of DualSense.+### 3. Multi-Phone WebUI Controllers (P1..P4) & Layout Studio — *next*+Expansão do servidor local integrado (porta 8080) para multiplayer cooperativo local sem custos de hardware:+- **Suporte a até 4 Smartphones Simultâneos**: Seleção dinâmica de slot (`P1`, `P2`, `P3`, `P4`) via `/gamepad`, heartbeat automático de desconexão e transmissão binária via WebSocket (`/ws`) com latência < 5 ms.+- **PSBox Layout Studio**: Editor visual de controles na WebUI com pré-visualização WYSIWYG, ajuste de botões analógicos e gatilhos para telas de toque, salvamento de perfis (`portrait`/`landscape`) e persistência imediata.-### Technical Feasibility Study: Multi-Phone WebUI Controllers (P1..P4)+----**Context & Architecture**:-The embedded lightweight HTTP server (`src/app/web_server.cpp`) serves a zero-install touch gamepad (`/gamepad` or `/`) to local network clients (iOS Safari, Android Chrome, desktop browsers). Expanding this architecture to support concurrent multi-phone controllers allows up to 4 simultaneous players without requiring multiple physical DualSense or USB controllers.+## 📋 Planejado para o Futuro (Planned & Later)-**1. Session & Player Slot Management (P1..P4)**:-- **Slot Selection**: The WebUI client provides a player selector (`P1`, `P2`, `P3`, `P4`) or automatically claims the first free slot via query param `?player=N` or initial handshake (`GET /api/gamepad/claim`).-- **Slot State Matrix**: The host maintains an array of `VirtualGamepadState[kMaxPads]` (4 slots), protected by per-slot atomic timestamps and mutexes.-- **Heartbeat & Inactivity Eviction**: Each virtual pad maintains `lastSeenMs`. If a connected phone stops transmitting for > 15 seconds (browser minimized, incoming call, Wi-Fi sleep), the slot is automatically freed and the UI player indicator reflects disconnection.+### 4. 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.-**2. Network Transport & Latency Optimization**:-- **HTTP POST vs WebSocket**: Currently, gamepad states are sent via low-overhead JSON HTTP POST (`/api/gamepad`). At 60 Hz input polling, persistent HTTP/1.1 `keep-alive` connections achieve 2–6 ms latency on typical 5 GHz home Wi-Fi.-- **Binary Report Framing**: Upgrading input payload to a 12-byte binary format (`[slot:1, buttons:2, lt:1, rt:1, lx:2, ly:2, rx:2, ry:2]`) sent via WebSocket or HTTP chunks minimizes serialization overhead and JSON parsing on the PS5 CPU.-- **Input Concurrency**: Worker threads decode incoming packets and update `g_virtualGamepad[slot]`. The render/stream frame loop polls all slots concurrently with zero mutex contention using double-buffering or `std::atomic`.+### 5. 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.-**3. In-Game Local Co-op Compatibility**:-- xCloud supports local co-op titles (e.g. *It Takes Two*, *Overcooked: All You Can Eat*, *Halo: The Master Chief Collection*, *A Way Out*, *EA Sports FC*).-- PSBox merges virtual pads directly into Xbox WebRTC input channels (`ChannelType::Input`), ensuring cloud instances recognize separate controller indices seamlessly.+### 6. 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.----### PSBox Layout Studio (Virtual Controller Visual Customizer)+## 🚫 Decisões Técnicas e Recursos Descartados (Dropped)-**Purpose & Architecture**:-A browser-based visual layout editor embedded directly into the WebUI under the **Mapeamento** (Remap) section, accessible via a dedicated sub-tab with a mobile phone icon and the label **"Celular"** (alongside "Controle" and "Teclado"). It eliminates hardcoded CSS guesswork and empowers users to visually customize and persist touch gamepad layouts directly from their mobile browser or desktop.+- **Discord Rich Presence (Desktop)**: Descartado; o ecossistema Xbox Live / Game Pass já fornece presença nativa de atividade.+- **Assistente de Primeiro Uso (Onboarding)**: Descartado para manter navegação direta, rápida e sem telas forçadas.+- **Captura de Vídeo dos Últimos 30s da Partida**: Descartado; impacto desnecessário em memória e I/O de disco no console.+- **GeForce Now**: Descartado; protocolo totalmente distinto e termos de serviço incompatíveis com a proposta do projeto.+- **Transmissão HDR / Surround 5.1 / Frame Generation**: xCloud transmite nativamente em áudio estéreo e vídeo SDR 1080p; interpolação artificial de quadros adicionaria latência intolerável.+- **Múltiplas Contas Xbox Simultâneas**: Não suportado; simplificação de cache local e segurança de credenciais.-**Core Features & Integration**:-1. **Interactive Visual Canvas**:- - WYSIWYG interactive canvas mirroring target device viewport resolutions (iPhone, Galaxy, iPad, landscape and portrait aspect ratios).- - Real-time draggable, scalable, and rotatable UI widgets: Analog Sticks (LS/RS), D-Pad, ABXY cluster, Bumpers (LB/RB), Analog Triggers (LT/RT), System buttons (Nexus/Xbox, View, Menu), and Player selector bar.-2. **Dual-Orientation Custom Presets**:- - Independent custom layout presets for Portrait and Landscape orientations (`portrait-custom`, `landscape-custom`), as well as built-in presets (`default-phone`, `compact-thumb`, `tablet-split`, `claw-grip`).- - One-click "Restaurar padrão" (Reset to default) button to revert touch positions to factory ergonomics.-3. **Seamless JSON Layout Export & Live Persistence**:- - Export and import layout profiles formatted in structured JSON (`{ portrait: { ... }, landscape: { ... } }`).- - Saving from the Layout Studio instantly persists custom layout configurations to the client local storage and updates the active **Controle** (Gamepad) tab live without requiring a host restart or browser page reload.- - Code generation mode exports formatted CSS coordinate rules (`left`, `top`, `width`, `height`, `transform: scale()`) ready for direct inclusion in `src/app/web_server.cpp`.-4. **Ergonomic Safe Zones, Snapping & Haptics**:- - Visual safe-area guides (notch, Dynamic Island, navigation bar insets).- - Configurable snap grids, thumb radius arcs, boundary clamping, and Web Vibration API haptic pulses for real-time touch simulation.---## Dropped (and why)--- **Discord Rich Presence (desktop)**: dropped (Xbox Live / Game Pass ecosystem already provides native activity presence).-- **First-run guide / Onboarding**: dropped per user decision (simple, intuitive navigation preferred without forced wizards).-- **Data used per session**: not worth a feature (decided 2026-10-18).-- **Saving the last 30 s as a clip, screenshots of the game**: dropped (decided 2026-10-18).-- **Several Xbox accounts at once / switching between them**: not offered.-- **"Leaving soon" / "new" badges on the cards**: not wanted on the cards.-- **Turning the Xbox on from the app**: not needed: a console in standby (ConnectedStandby) is already woken by the stream request (the app waits up to 60 s, `ConsoleDidNotWake` otherwise); one switched fully off can't be woken remotely.-- **GeForce Now**: another service with its own protocol, close to a new app, and a different terms-of-service risk.+----- **More picture filters**: with FSR and deband, what remains is the bits the- server doesn't send.-- **Higher tiers on this account**: 1080p HQ, 1440p, H.265, a Tizen-TV- identity and `rateControlBitrateUpdate` were all refused by the service- (measured, see the v0.4.0 / v0.5.0 PRs). Re-tested 2026-10-15 with the- request exactly as xbox.com makes it: still 1920x1080 (H.264 4.2) at- ~11–13 Mbps in motion, the same with Tizen's 1080HQ. "Best" keeps asking- for 1440p for when Microsoft grants it. Measured by the pictures' QP- (2026-10-15, FH5 / Starfield / Cyberpunk, Brazil and Australia regions): the- service caps cloud 1080p at ~12–13 Mbps (QP ~24–27, up to ~33 in the- heaviest motion). Tried, no gain: H.264 High (the session's- `clientStreamingConfigOverrides` says `preferMainH264Profile`),- transport-cc with real feedback (accepted, same bitrate), `b=AS` and- `x-google-*-bitrate`, 4K-browser / Mac-Chrome (XboxTV's, which got 1440p in- Australia) / Xbox-console identities (the console one got 720p),- `VideoPreference` + `a=max-fr`, 1440 asked at once; the 5 s key frames cost- ~2 % of the bits. 1440p seems to depend on the account / market.-- **HDR**: xCloud doesn't stream HDR.-- **1440p only for Ultimate**: not limited in the app; "Best" asks for the- most and the service gives what the plan allows.-- **Rejoin a running session after a crash**: `/v5/sessions/cloud/active`- answers 404 for cloud; the session can be reached again only with the- previous streaming token saved on the console. Not done: a session left- open after a crash could get in the way of the player's game, and the- in-game reconnect already covers a drop (2026-10-15).-- **Surround, frame generation, FSR 4**: xCloud's audio is stereo as far as- known; generated frames add delay; FSR 4 needs motion vectors and depth a- video stream doesn't have.+## 📦 Histórico de Versões Recentes-## Done+Para 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)*:+ - 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)$.+ - Modularização estrutural de arquivos monolíticos (`app_ui.cpp`, `web_server.cpp`, `library.cpp`, `worker.cpp`).+ - Correção de redirecionamento pós-login e resgate imediato de títulos Free-to-Play.- **v1.5.3**:- - Validated autonomous free game claim harness (`claimtest`) on real PS5 hardware with Microsoft Store API acquisition.- - Immediate top-of-library insertion at index 0 in "Meus jogos" without requiring manual <kbd>L3</kbd> refresh.- - Direct transition to active cloud streaming with hardware VPU decoding (`libSceVideodec2`), 120 Hz output, and DualSense haptics.- - Rebranded Web panel to "Smartglass WebUI", bound dynamic `XC_APP_VERSION` across web headers and bug reporting, and added official Xbox Guide logo SVG to the virtual gamepad Nexus button.+ - Testes autônomos de resgate de jogos na loja (`claimtest`) e inserção imediata no índice 0 de "Meus jogos".+ - Transição imediata para streaming com decodificação por hardware (`libSceVideodec2`), 120 Hz e haptics DualSense.+ - Reformulação da WebUI para "Smartglass WebUI" com logo oficial do Xbox Guide.- **v1.5.2**:- - Universal store acquisition engine without loading spinner loop, immediate local persistence (`mine`/`owned_`), and recent-first sorting on boot.- - Universal cross-gen deduplication (Xbox Series X|S prioritized over Xbox One) and removal of PC-only titles.- - Strict compliance with Microsoft SIGL shelf feeds and enriched Call of Duty artwork/metadata.- - Splash screen locks user inputs until authentication completes, preventing premature interactions.- - Eliminated false "24 new games" notification toast and sanitized logs with duplicate suppression.- - WebUI virtual controller ABXY buttons kept static and stable; search cursor focus stabilization; friends shelf hero art.+ - Motor universal de aquisição de licenças gratuitas em 1-clique sem looping de carregamento.+ - Deduplicação inteligente Series X|S sobre Xbox One e remoção de títulos exclusivos de PC.+ - Bloqueio de inputs na tela de splash até a conclusão do login.- **v1.5.1**:- - Restored full "My Games" / owned games list (`owned_`), resolving regression where only Call of Duty and Fortnite appeared.- - Eliminated duplicate Call of Duty entries in user library while keeping Modern Warfare 4 and Warzone playable.- - Fixed manual library refresh (<kbd>L3</kbd>) ensuring full online synchronization and clear notification feedback.- - Implemented automatic local cache self-healing against corrupted `library_cache.json`.+ - Restauração completa da estante de jogos adquiridos e eliminação de duplicatas de títulos multi-edição.+ - Auto-recuperação de cache local corrompido (`library_cache.json`).- **v1.5.0**:- - Reorganized Settings menu with network/connectivity priority.- - 1-Click direct free license acquisition on `Screen::Error` for unowned free games and launchers (Call of Duty BO6 Launcher, FFXIV Online Free Trial).- - Instant delta-sync library update (<kbd>L3</kbd> and login) without cache flushing or UI freeze.- - Search "Grátis" filter refactor excluding already owned games and unclaimable token products.- - Red "Restaurar configurações padrões" button with 5-second hold confirmation.- - WebUI 2.0 with fullscreen landscape and portrait virtual touch controller supporting Players 1-4 with dynamic console icon feedback.- - Cleaned console notifications removing duplicate toasts.-- "All games" (Game Pass) as an expanded vertical grid: uncapped 550+ games in 6 centered columns, 2D D-pad navigation, smooth vertical row scrolling and clean clipping under header and tabs.-- v0.5.0: picture on the GPU, FSR 1 upscaling to 4K, block smoothing.-- v0.4.0: game menu, PS5 keyboard in games, frame metadata reports, CAS- sharpness, trigger vibration, local multiplayer, controller settings.-- v0.3.0 and earlier: Game Pass / Your games tabs, search, prices, regions,- RTCP feedback, rumble.+ - WebUI 2.0 com suporte a controle virtual em tela cheia para Jogadores 1 a 4.+ - Botão de reset de fábrica com proteção de toque seguro de 5 segundos.+ - Sincronização em tempo real de biblioteca sem congelamentos de tela.diff --git a/cmake/deps/ffmpeg.cmake b/cmake/deps/ffmpeg.cmakeindex 6bd77c9..c583e01 100644--- a/cmake/deps/ffmpeg.cmake+++ b/cmake/deps/ffmpeg.cmake@@ -7,6 +7,8 @@ set(XC_FFMPEG_DIR "${CMAKE_BINARY_DIR}/ffmpeg")if(NOT EXISTS "${XC_FFMPEG_DIR}/lib/libswresample.a")if(XCLOUD_PS5)set(_target ps5)+ elseif(XC_TARGET_PS4)+ set(_target ps4)else()set(_target host)endif()@@ -23,6 +25,6 @@ add_library(xc_ffmpeg INTERFACE)target_include_directories(xc_ffmpeg INTERFACE "${XC_FFMPEG_DIR}/include")target_link_libraries(xc_ffmpeg INTERFACE "${XC_FFMPEG_DIR}/lib/libavcodec.a""${XC_FFMPEG_DIR}/lib/libswresample.a" "${XC_FFMPEG_DIR}/lib/libavutil.a")-if(NOT XCLOUD_PS5)+if(NOT XCLOUD_PS5 AND NOT XC_TARGET_PS4)target_link_libraries(xc_ffmpeg INTERFACE m)endif()diff --git a/cmake/deps/mbedtls_user_config.h b/cmake/deps/mbedtls_user_config.hindex 562cded..021c9aa 100644--- a/cmake/deps/mbedtls_user_config.h+++ b/cmake/deps/mbedtls_user_config.h@@ -10,3 +10,8 @@* with "This is a bug in the library" (-0x006E, CORRUPTION_DETECTED). */#define MBEDTLS_THREADING_C#define MBEDTLS_THREADING_PTHREAD++#if defined(__ORBIS__)+#define MBEDTLS_NO_PLATFORM_ENTROPY+#define MBEDTLS_ENTROPY_HARDWARE_ALT+#endifdiff --git a/cmake/platform.cmake b/cmake/platform.cmakeindex 0cc4649..0825a40 100644--- a/cmake/platform.cmake+++ b/cmake/platform.cmake@@ -8,6 +8,8 @@# app links, not by these: they are for what can't be split that way.if(XCLOUD_PS5)set(XC_PLATFORM ps5)+elseif(XC_TARGET_PS4)+ set(XC_PLATFORM ps4)elseif(WIN32)set(XC_PLATFORM windows)else()@@ -18,6 +20,6 @@ message(STATUS "Platform: ${XC_PLATFORM}")add_library(xc_platform INTERFACE)string(TOUPPER "${XC_PLATFORM}" XC_PLATFORM_UPPER)target_compile_definitions(xc_platform INTERFACE XC_PLATFORM_${XC_PLATFORM_UPPER}=1)-if(NOT XC_PLATFORM STREQUAL "ps5")+if(NOT XC_PLATFORM STREQUAL "ps5" AND NOT XC_PLATFORM STREQUAL "ps4")target_compile_definitions(xc_platform INTERFACE XC_PLATFORM_DESKTOP=1)endif()diff --git a/cmake/ps4.toolchain.cmake b/cmake/ps4.toolchain.cmakenew file mode 100644index 0000000..ad86cc1--- /dev/null+++ b/cmake/ps4.toolchain.cmake@@ -0,0 +1,71 @@+# SPDX-License-Identifier: GPL-3.0-or-later+# Copyright (C) 2026 RafaelNGP+# CMake toolchain file for building xCloud-PS5 for PlayStation 4 with OpenOrbis++set(CMAKE_SYSTEM_NAME Generic)+set(CMAKE_SYSTEM_PROCESSOR x86_64)+set(CMAKE_CROSSCOMPILING TRUE)+set(XC_TARGET_PS4 ON CACHE BOOL "Building for PlayStation 4 (OpenOrbis)" FORCE)++if(NOT DEFINED OO_PS4_TOOLCHAIN)+ if(DEFINED ENV{OO_PS4_TOOLCHAIN})+ set(OO_PS4_TOOLCHAIN "$ENV{OO_PS4_TOOLCHAIN}")+ elseif(EXISTS "${CMAKE_CURRENT_LIST_DIR}/../ps4-toolchain/link.x")+ get_filename_component(OO_PS4_TOOLCHAIN "${CMAKE_CURRENT_LIST_DIR}/../ps4-toolchain" ABSOLUTE)+ else()+ message(FATAL_ERROR "OO_PS4_TOOLCHAIN is not set. Run tools/ps4/fetch-toolchain.sh first.")+ endif()+endif()+set(OO_PS4_TOOLCHAIN "${OO_PS4_TOOLCHAIN}" CACHE PATH "OpenOrbis PS4 Toolchain root")++if(NOT EXISTS "${OO_PS4_TOOLCHAIN}/link.x" OR NOT EXISTS "${OO_PS4_TOOLCHAIN}/lib/crt1.o")+ message(FATAL_ERROR "OO_PS4_TOOLCHAIN=${OO_PS4_TOOLCHAIN} does not look like an OpenOrbis toolchain (missing link.x or lib/crt1.o)")+endif()++# Fix upstream OpenOrbis ABI bug in alltypes.h (32-bit int instead of 64-bit pointer for pthread_*attr_t)+if(EXISTS "${OO_PS4_TOOLCHAIN}/include/bits/alltypes.h")+ file(READ "${OO_PS4_TOOLCHAIN}/include/bits/alltypes.h" _alltypes_content)+ if(_alltypes_content MATCHES "unsigned __attr; } pthread_mutexattr_t;")+ string(REPLACE "typedef struct { unsigned __attr; } pthread_mutexattr_t;" "typedef struct { void *__attr; } pthread_mutexattr_t;" _alltypes_content "${_alltypes_content}")+ string(REPLACE "typedef struct { unsigned __attr; } pthread_condattr_t;" "typedef struct { void *__attr; } pthread_condattr_t;" _alltypes_content "${_alltypes_content}")+ string(REPLACE "typedef struct { unsigned __attr; } pthread_barrierattr_t;" "typedef struct { void *__attr; } pthread_barrierattr_t;" _alltypes_content "${_alltypes_content}")+ string(REPLACE "typedef struct { unsigned __attr[2]; } pthread_rwlockattr_t;" "typedef struct { void *__attr; } pthread_rwlockattr_t;" _alltypes_content "${_alltypes_content}")+ file(WRITE "${OO_PS4_TOOLCHAIN}/include/bits/alltypes.h" "${_alltypes_content}")+ endif()+endif()++find_program(XC_PS4_CLANG NAMES clang-18 clang REQUIRED)+find_program(XC_PS4_CLANGXX NAMES clang++-18 clang++ REQUIRED)+find_program(XC_PS4_LLD NAMES ld.lld-18 ld.lld REQUIRED)+find_program(XC_PS4_AR NAMES llvm-ar-18 llvm-ar ar REQUIRED)+find_program(XC_PS4_RANLIB NAMES llvm-ranlib-18 llvm-ranlib ranlib REQUIRED)++set(CMAKE_C_COMPILER "${XC_PS4_CLANG}")+set(CMAKE_CXX_COMPILER "${XC_PS4_CLANGXX}")+set(CMAKE_AR "${XC_PS4_AR}")+set(CMAKE_RANLIB "${XC_PS4_RANLIB}")+set(CMAKE_LINKER "${XC_PS4_LLD}")++set(CMAKE_C_COMPILER_TARGET x86_64-pc-freebsd12-elf)+set(CMAKE_CXX_COMPILER_TARGET x86_64-pc-freebsd12-elf)+set(CMAKE_SYSROOT "${OO_PS4_TOOLCHAIN}")++set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)++set(XC_PS4_COMMON_FLAGS+ "-fPIC -ffunction-sections -fdata-sections -funwind-tables -fexceptions -msse4.2 -mpopcnt -mtune=btver2 -D_GNU_SOURCE -D__ORBIS__ -D__PS4__ -DXC_TARGET_PS4=1")+set(CMAKE_C_FLAGS_INIT "${XC_PS4_COMMON_FLAGS} -isystem \"${CMAKE_CURRENT_LIST_DIR}/../ps4/compat\" -isystem \"${OO_PS4_TOOLCHAIN}/include\"")+set(CMAKE_CXX_FLAGS_INIT "${XC_PS4_COMMON_FLAGS} -fcxx-exceptions -isystem \"${CMAKE_CURRENT_LIST_DIR}/../ps4/compat\" -isystem \"${OO_PS4_TOOLCHAIN}/include/c++/v1\" -isystem \"${OO_PS4_TOOLCHAIN}/include\"")++set(CMAKE_EXE_LINKER_FLAGS_INIT "")+set(CMAKE_C_LINK_EXECUTABLE+ "${XC_PS4_LLD} -m elf_x86_64 -pie --script \"${OO_PS4_TOOLCHAIN}/link.x\" --eh-frame-hdr --error-limit=0 -L\"${OO_PS4_TOOLCHAIN}/lib\" <LINK_FLAGS> <OBJECTS> -o <TARGET> --start-group <LINK_LIBRARIES> --end-group -lc -lkernel \"${OO_PS4_TOOLCHAIN}/lib/crt1.o\"")+set(CMAKE_CXX_LINK_EXECUTABLE+ "${XC_PS4_LLD} -m elf_x86_64 -pie --script \"${OO_PS4_TOOLCHAIN}/link.x\" --eh-frame-hdr --error-limit=0 -L\"${OO_PS4_TOOLCHAIN}/lib\" <LINK_FLAGS> <OBJECTS> -o <TARGET> --start-group <LINK_LIBRARIES> --end-group -lc++ -lc -lkernel \"${OO_PS4_TOOLCHAIN}/lib/crt1.o\"")++set(BUILD_SHARED_LIBS OFF)+set(CMAKE_FIND_ROOT_PATH "${OO_PS4_TOOLCHAIN}")+set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)+set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)+set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)+set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)diff --git a/ps4/compat/net/if_types.h b/ps4/compat/net/if_types.hnew file mode 100644index 0000000..1b47fb5--- /dev/null+++ b/ps4/compat/net/if_types.h@@ -0,0 +1,273 @@+/*-+ * Copyright (c) 1989, 1993, 1994+ * The Regents of the University of California. All rights reserved.+ *+ * Redistribution and use in source and binary forms, with or without+ * modification, are permitted provided that the following conditions+ * are met:+ * 1. Redistributions of source code must retain the above copyright+ * notice, this list of conditions and the following disclaimer.+ * 2. Redistributions in binary form must reproduce the above copyright+ * notice, this list of conditions and the following disclaimer in the+ * documentation and/or other materials provided with the distribution.+ * 4. Neither the name of the University nor the names of its contributors+ * may be used to endorse or promote products derived from this software+ * without specific prior written permission.+ *+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF+ * SUCH DAMAGE.+ *+ * @(#)if_types.h 8.3 (Berkeley) 4/28/95+ * $FreeBSD: releng/11.4/sys/net/if_types.h 331722 2018-03-29 02:50:57Z eadler $+ * $NetBSD: if_types.h,v 1.16 2000/04/19 06:30:53 itojun Exp $+ */++#ifndef _NET_IF_TYPES_H_+#define _NET_IF_TYPES_H_++/*+ * Interface types for benefit of parsing media address headers.+ * This list is derived from the SNMP list of ifTypes, originally+ * documented in RFC1573, now maintained as:+ *+ * http://www.iana.org/assignments/smi-numbers+ */++typedef enum {+ IFT_OTHER = 0x1, /* none of the following */+ IFT_1822 = 0x2, /* old-style arpanet imp */+ IFT_HDH1822 = 0x3, /* HDH arpanet imp */+ IFT_X25DDN = 0x4, /* x25 to imp */+ IFT_X25 = 0x5, /* PDN X25 interface (RFC877) */+ IFT_ETHER = 0x6, /* Ethernet CSMA/CD */+ IFT_ISO88023 = 0x7, /* CMSA/CD */+ IFT_ISO88024 = 0x8, /* Token Bus */+ IFT_ISO88025 = 0x9, /* Token Ring */+ IFT_ISO88026 = 0xa, /* MAN */+ IFT_STARLAN = 0xb,+ IFT_P10 = 0xc, /* Proteon 10MBit ring */+ IFT_P80 = 0xd, /* Proteon 80MBit ring */+ IFT_HY = 0xe, /* Hyperchannel */+ IFT_FDDI = 0xf,+ IFT_LAPB = 0x10,+ IFT_SDLC = 0x11,+ IFT_T1 = 0x12,+ IFT_CEPT = 0x13, /* E1 - european T1 */+ IFT_ISDNBASIC = 0x14,+ IFT_ISDNPRIMARY = 0x15,+ IFT_PTPSERIAL = 0x16, /* Proprietary PTP serial */+ IFT_PPP = 0x17, /* RFC 1331 */+ IFT_LOOP = 0x18, /* loopback */+ IFT_EON = 0x19, /* ISO over IP */+ IFT_XETHER = 0x1a, /* obsolete 3MB experimental ethernet */+ IFT_NSIP = 0x1b, /* XNS over IP */+ IFT_SLIP = 0x1c, /* IP over generic TTY */+ IFT_ULTRA = 0x1d, /* Ultra Technologies */+ IFT_DS3 = 0x1e, /* Generic T3 */+ IFT_SIP = 0x1f, /* SMDS */+ IFT_FRELAY = 0x20, /* Frame Relay DTE only */+ IFT_RS232 = 0x21,+ IFT_PARA = 0x22, /* parallel-port */+ IFT_ARCNET = 0x23,+ IFT_ARCNETPLUS = 0x24,+ IFT_ATM = 0x25, /* ATM cells */+ IFT_MIOX25 = 0x26,+ IFT_SONET = 0x27, /* SONET or SDH */+ IFT_X25PLE = 0x28,+ IFT_ISO88022LLC = 0x29,+ IFT_LOCALTALK = 0x2a,+ IFT_SMDSDXI = 0x2b,+ IFT_FRELAYDCE = 0x2c, /* Frame Relay DCE */+ IFT_V35 = 0x2d,+ IFT_HSSI = 0x2e,+ IFT_HIPPI = 0x2f,+ IFT_MODEM = 0x30, /* Generic Modem */+ IFT_AAL5 = 0x31, /* AAL5 over ATM */+ IFT_SONETPATH = 0x32,+ IFT_SONETVT = 0x33,+ IFT_SMDSICIP = 0x34, /* SMDS InterCarrier Interface */+ IFT_PROPVIRTUAL = 0x35, /* Proprietary Virtual/internal */+ IFT_PROPMUX = 0x36, /* Proprietary Multiplexing */+ IFT_IEEE80212 = 0x37, /* 100BaseVG */+ IFT_FIBRECHANNEL = 0x38, /* Fibre Channel */+ IFT_HIPPIINTERFACE = 0x39, /* HIPPI interfaces */+ IFT_FRAMERELAYINTERCONNECT = 0x3a, /* Obsolete, use 0x20 either 0x2c */+ IFT_AFLANE8023 = 0x3b, /* ATM Emulated LAN for 802.3 */+ IFT_AFLANE8025 = 0x3c, /* ATM Emulated LAN for 802.5 */+ IFT_CCTEMUL = 0x3d, /* ATM Emulated circuit */+ IFT_FASTETHER = 0x3e, /* Fast Ethernet (100BaseT) */+ IFT_ISDN = 0x3f, /* ISDN and X.25 */+ IFT_V11 = 0x40, /* CCITT V.11/X.21 */+ IFT_V36 = 0x41, /* CCITT V.36 */+ IFT_G703AT64K = 0x42, /* CCITT G703 at 64Kbps */+ IFT_G703AT2MB = 0x43, /* Obsolete see DS1-MIB */+ IFT_QLLC = 0x44, /* SNA QLLC */+ IFT_FASTETHERFX = 0x45, /* Fast Ethernet (100BaseFX) */+ IFT_CHANNEL = 0x46, /* channel */+ IFT_IEEE80211 = 0x47, /* radio spread spectrum */+ IFT_IBM370PARCHAN = 0x48, /* IBM System 360/370 OEMI Channel */+ IFT_ESCON = 0x49, /* IBM Enterprise Systems Connection */+ IFT_DLSW = 0x4a, /* Data Link Switching */+ IFT_ISDNS = 0x4b, /* ISDN S/T interface */+ IFT_ISDNU = 0x4c, /* ISDN U interface */+ IFT_LAPD = 0x4d, /* Link Access Protocol D */+ IFT_IPSWITCH = 0x4e, /* IP Switching Objects */+ IFT_RSRB = 0x4f, /* Remote Source Route Bridging */+ IFT_ATMLOGICAL = 0x50, /* ATM Logical Port */+ IFT_DS0 = 0x51, /* Digital Signal Level 0 */+ IFT_DS0BUNDLE = 0x52, /* group of ds0s on the same ds1 */+ IFT_BSC = 0x53, /* Bisynchronous Protocol */+ IFT_ASYNC = 0x54, /* Asynchronous Protocol */+ IFT_CNR = 0x55, /* Combat Net Radio */+ IFT_ISO88025DTR = 0x56, /* ISO 802.5r DTR */+ IFT_EPLRS = 0x57, /* Ext Pos Loc Report Sys */+ IFT_ARAP = 0x58, /* Appletalk Remote Access Protocol */+ IFT_PROPCNLS = 0x59, /* Proprietary Connectionless Protocol*/+ IFT_HOSTPAD = 0x5a, /* CCITT-ITU X.29 PAD Protocol */+ IFT_TERMPAD = 0x5b, /* CCITT-ITU X.3 PAD Facility */+ IFT_FRAMERELAYMPI = 0x5c, /* Multiproto Interconnect over FR */+ IFT_X213 = 0x5d, /* CCITT-ITU X213 */+ IFT_ADSL = 0x5e, /* Asymmetric Digital Subscriber Loop */+ IFT_RADSL = 0x5f, /* Rate-Adapt. Digital Subscriber Loop*/+ IFT_SDSL = 0x60, /* Symmetric Digital Subscriber Loop */+ IFT_VDSL = 0x61, /* Very H-Speed Digital Subscrib. Loop*/+ IFT_ISO88025CRFPINT = 0x62, /* ISO 802.5 CRFP */+ IFT_MYRINET = 0x63, /* Myricom Myrinet */+ IFT_VOICEEM = 0x64, /* voice recEive and transMit */+ IFT_VOICEFXO = 0x65, /* voice Foreign Exchange Office */+ IFT_VOICEFXS = 0x66, /* voice Foreign Exchange Station */+ IFT_VOICEENCAP = 0x67, /* voice encapsulation */+ IFT_VOICEOVERIP = 0x68, /* voice over IP encapsulation */+ IFT_ATMDXI = 0x69, /* ATM DXI */+ IFT_ATMFUNI = 0x6a, /* ATM FUNI */+ IFT_ATMIMA = 0x6b, /* ATM IMA */+ IFT_PPPMULTILINKBUNDLE = 0x6c, /* PPP Multilink Bundle */+ IFT_IPOVERCDLC = 0x6d, /* IBM ipOverCdlc */+ IFT_IPOVERCLAW = 0x6e, /* IBM Common Link Access to Workstn */+ IFT_STACKTOSTACK = 0x6f, /* IBM stackToStack */+ IFT_VIRTUALIPADDRESS = 0x70, /* IBM VIPA */+ IFT_MPC = 0x71, /* IBM multi-protocol channel support */+ IFT_IPOVERATM = 0x72, /* IBM ipOverAtm */+ IFT_ISO88025FIBER = 0x73, /* ISO 802.5j Fiber Token Ring */+ IFT_TDLC = 0x74, /* IBM twinaxial data link control */+ IFT_GIGABITETHERNET = 0x75, /* Gigabit Ethernet */+ IFT_HDLC = 0x76, /* HDLC */+ IFT_LAPF = 0x77, /* LAP F */+ IFT_V37 = 0x78, /* V.37 */+ IFT_X25MLP = 0x79, /* Multi-Link Protocol */+ IFT_X25HUNTGROUP = 0x7a, /* X25 Hunt Group */+ IFT_TRANSPHDLC = 0x7b, /* Transp HDLC */+ IFT_INTERLEAVE = 0x7c, /* Interleave channel */+ IFT_FAST = 0x7d, /* Fast channel */+ IFT_IP = 0x7e, /* IP (for APPN HPR in IP networks) */+ IFT_DOCSCABLEMACLAYER = 0x7f, /* CATV Mac Layer */+ IFT_DOCSCABLEDOWNSTREAM = 0x80, /* CATV Downstream interface */+ IFT_DOCSCABLEUPSTREAM = 0x81, /* CATV Upstream interface */+ IFT_A12MPPSWITCH = 0x82, /* Avalon Parallel Processor */+ IFT_TUNNEL = 0x83, /* Encapsulation interface */+ IFT_COFFEE = 0x84, /* coffee pot */+ IFT_CES = 0x85, /* Circiut Emulation Service */+ IFT_ATMSUBINTERFACE = 0x86, /* (x) ATM Sub Interface */+ IFT_L2VLAN = 0x87, /* Layer 2 Virtual LAN using 802.1Q */+ IFT_L3IPVLAN = 0x88, /* Layer 3 Virtual LAN - IP Protocol */+ IFT_L3IPXVLAN = 0x89, /* Layer 3 Virtual LAN - IPX Prot. */+ IFT_DIGITALPOWERLINE = 0x8a, /* IP over Power Lines */+ IFT_MEDIAMAILOVERIP = 0x8b, /* (xxx) Multimedia Mail over IP */+ IFT_DTM = 0x8c, /* Dynamic synchronous Transfer Mode */+ IFT_DCN = 0x8d, /* Data Communications Network */+ IFT_IPFORWARD = 0x8e, /* IP Forwarding Interface */+ IFT_MSDSL = 0x8f, /* Multi-rate Symmetric DSL */+ IFT_IEEE1394 = 0x90, /* IEEE1394 High Performance SerialBus*/+ IFT_IFGSN = 0x91, /* HIPPI-6400 */+ IFT_DVBRCCMACLAYER = 0x92, /* DVB-RCC MAC Layer */+ IFT_DVBRCCDOWNSTREAM = 0x93, /* DVB-RCC Downstream Channel */+ IFT_DVBRCCUPSTREAM = 0x94, /* DVB-RCC Upstream Channel */+ IFT_ATMVIRTUAL = 0x95, /* ATM Virtual Interface */+ IFT_MPLSTUNNEL = 0x96, /* MPLS Tunnel Virtual Interface */+ IFT_SRP = 0x97, /* Spatial Reuse Protocol */+ IFT_VOICEOVERATM = 0x98, /* Voice over ATM */+ IFT_VOICEOVERFRAMERELAY = 0x99, /* Voice Over Frame Relay */+ IFT_IDSL = 0x9a, /* Digital Subscriber Loop over ISDN */+ IFT_COMPOSITELINK = 0x9b, /* Avici Composite Link Interface */+ IFT_SS7SIGLINK = 0x9c, /* SS7 Signaling Link */+ IFT_PROPWIRELESSP2P = 0x9d, /* Prop. P2P wireless interface */+ IFT_FRFORWARD = 0x9e, /* Frame forward Interface */+ IFT_RFC1483 = 0x9f, /* Multiprotocol over ATM AAL5 */+ IFT_USB = 0xa0, /* USB Interface */+ IFT_IEEE8023ADLAG = 0xa1, /* IEEE 802.3ad Link Aggregate*/+ IFT_BGPPOLICYACCOUNTING = 0xa2, /* BGP Policy Accounting */+ IFT_FRF16MFRBUNDLE = 0xa3, /* FRF.16 Multilik Frame Relay*/+ IFT_H323GATEKEEPER = 0xa4, /* H323 Gatekeeper */+ IFT_H323PROXY = 0xa5, /* H323 Voice and Video Proxy */+ IFT_MPLS = 0xa6, /* MPLS */+ IFT_MFSIGLINK = 0xa7, /* Multi-frequency signaling link */+ IFT_HDSL2 = 0xa8, /* High Bit-Rate DSL, 2nd gen. */+ IFT_SHDSL = 0xa9, /* Multirate HDSL2 */+ IFT_DS1FDL = 0xaa, /* Facility Data Link (4Kbps) on a DS1*/+ IFT_POS = 0xab, /* Packet over SONET/SDH Interface */+ IFT_DVBASILN = 0xac, /* DVB-ASI Input */+ IFT_DVBASIOUT = 0xad, /* DVB-ASI Output */+ IFT_PLC = 0xae, /* Power Line Communications */+ IFT_NFAS = 0xaf, /* Non-Facility Associated Signaling */+ IFT_TR008 = 0xb0, /* TROO8 */+ IFT_GR303RDT = 0xb1, /* Remote Digital Terminal */+ IFT_GR303IDT = 0xb2, /* Integrated Digital Terminal */+ IFT_ISUP = 0xb3, /* ISUP */+ IFT_PROPDOCSWIRELESSMACLAYER = 0xb4, /* prop/Wireless MAC Layer */+ IFT_PROPDOCSWIRELESSDOWNSTREAM = 0xb5, /* prop/Wireless Downstream */+ IFT_PROPDOCSWIRELESSUPSTREAM = 0xb6, /* prop/Wireless Upstream */+ IFT_HIPERLAN2 = 0xb7, /* HIPERLAN Type 2 Radio Interface */+ IFT_PROPBWAP2MP = 0xb8, /* PropBroadbandWirelessAccess P2MP*/+ IFT_SONETOVERHEADCHANNEL = 0xb9, /* SONET Overhead Channel */+ IFT_DIGITALWRAPPEROVERHEADCHANNEL = 0xba, /* Digital Wrapper Overhead */+ IFT_AAL2 = 0xbb, /* ATM adaptation layer 2 */+ IFT_RADIOMAC = 0xbc, /* MAC layer over radio links */+ IFT_ATMRADIO = 0xbd, /* ATM over radio links */+ IFT_IMT = 0xbe, /* Inter-Machine Trunks */+ IFT_MVL = 0xbf, /* Multiple Virtual Lines DSL */+ IFT_REACHDSL = 0xc0, /* Long Reach DSL */+ IFT_FRDLCIENDPT = 0xc1, /* Frame Relay DLCI End Point */+ IFT_ATMVCIENDPT = 0xc2, /* ATM VCI End Point */+ IFT_OPTICALCHANNEL = 0xc3, /* Optical Channel */+ IFT_OPTICALTRANSPORT = 0xc4, /* Optical Transport */+ IFT_INFINIBAND = 0xc7, /* Infiniband */+ IFT_BRIDGE = 0xd1, /* Transparent bridge interface */+ IFT_STF = 0xd7, /* 6to4 interface */++ /*+ * Not based on IANA assignments. Conflicting with IANA assignments.+ * We should make them negative probably.+ * This requires changes to struct if_data.+ */+ IFT_GIF = 0xf0, /* Generic tunnel interface */+ IFT_PVC = 0xf1, /* Unused */+ IFT_ENC = 0xf4, /* Encapsulating interface */+ IFT_PFLOG = 0xf6, /* PF packet filter logging */+ IFT_PFSYNC = 0xf7, /* PF packet filter synchronization */+} ifType;++/*+ * Some (broken) software uses #ifdef IFT_TYPE to check whether+ * an operating systems supports certain interface type. Lack of+ * ifdef leads to a piece of functionality compiled out.+ */+#ifndef BURN_BRIDGES+#define IFT_BRIDGE IFT_BRIDGE+#define IFT_PPP IFT_PPP+#define IFT_PROPVIRTUAL IFT_PROPVIRTUAL+#define IFT_L2VLAN IFT_L2VLAN+#define IFT_L3IPVLAN IFT_L3IPVLAN+#define IFT_IEEE1394 IFT_IEEE1394+#define IFT_INFINIBAND IFT_INFINIBAND+#endif++#endif /* !_NET_IF_TYPES_H_ */diff --git a/ps4/compat/pthread_np.h b/ps4/compat/pthread_np.hnew file mode 100644index 0000000..386d970--- /dev/null+++ b/ps4/compat/pthread_np.h@@ -0,0 +1,4 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once+#include <pthread.h>diff --git a/ps4/compat/signal.h b/ps4/compat/signal.hnew file mode 100644index 0000000..6fc918e--- /dev/null+++ b/ps4/compat/signal.h@@ -0,0 +1,9 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once+#include_next <signal.h>++#ifdef sa_sigaction+#undef sa_sigaction+#define sa_sigaction __sa_handler.__sa_sigaction+#endifdiff --git a/ps4/compat/sys/filio.h b/ps4/compat/sys/filio.hnew file mode 100644index 0000000..60f20a5--- /dev/null+++ b/ps4/compat/sys/filio.h@@ -0,0 +1,10 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++#ifndef FIONBIO+#define FIONBIO 0x8004667eUL+#endif+#ifndef FIONREAD+#define FIONREAD 0x4004667fUL+#endifdiff --git a/ps4/compat/sys/ioctl.h b/ps4/compat/sys/ioctl.hnew file mode 100644index 0000000..2d64aa8--- /dev/null+++ b/ps4/compat/sys/ioctl.h@@ -0,0 +1,11 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once+#include_next <sys/ioctl.h>++#ifndef FIONBIO+#define FIONBIO 0x8004667eUL+#endif+#ifndef FIONREAD+#define FIONREAD 0x4004667fUL+#endifdiff --git a/ps4/compat/sys/mutex.h b/ps4/compat/sys/mutex.hnew file mode 100644index 0000000..9eaab43--- /dev/null+++ b/ps4/compat/sys/mutex.h@@ -0,0 +1,49 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#ifndef _SYS_MUTEX_H_+#define _SYS_MUTEX_H_++#include <stdint.h>+#include <stddef.h>+#include <pthread.h>++#ifndef _ALIGNBYTES+#define _ALIGNBYTES (sizeof(uintptr_t) - 1)+#endif+#ifndef _ALIGN+#define _ALIGN(p) (((uintptr_t)(p) + _ALIGNBYTES) & ~_ALIGNBYTES)+#endif++struct lock_object {+ const char *lo_name;+ uint32_t lo_flags;+ uint32_t lo_data;+ void *lo_witness;+};++struct mtx {+ struct lock_object lock_object;+ volatile uintptr_t mtx_lock;+};++#ifdef __cplusplus+extern "C" {+#endif++void arc4random_buf(void *buf, size_t size);++static inline int timingsafe_bcmp(const void *b1, const void *b2, size_t n) {+ const unsigned char *p1 = (const unsigned char *)b1;+ const unsigned char *p2 = (const unsigned char *)b2;+ int ret = 0;+ for (size_t i = 0; i < n; i++) {+ ret |= (p1[i] ^ p2[i]);+ }+ return ret;+}++#ifdef __cplusplus+}+#endif++#endif /* _SYS_MUTEX_H_ */diff --git a/ps4/compat/sys/socket.h b/ps4/compat/sys/socket.hnew file mode 100644index 0000000..9406128--- /dev/null+++ b/ps4/compat/sys/socket.h@@ -0,0 +1,22 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once++// OpenOrbis musl headers declare sockaddr_storage with ss_family at offset 0 without ss_len.+// However, the FreeBSD / PS4 Orbis kernel and libSceNet expect ss_len at offset 0 and ss_family at offset 1,+// matching struct sockaddr (sa_len, sa_family) and struct sockaddr_in (sin_len, sin_family).+// We redefine sockaddr_storage so that any sockaddr_storage object has ss_family at offset 1.+#define sockaddr_storage __broken_musl_sockaddr_storage+#include_next <sys/socket.h>+#undef sockaddr_storage++struct sockaddr_storage {+ unsigned char ss_len;+ sa_family_t ss_family;+ char __ss_padding[128 - sizeof(long) - 2];+ unsigned long __ss_align;+};++#ifndef SO_NBIO+#define SO_NBIO 0x1200+#endifdiff --git a/ps4/compat/sys/sysctl.h b/ps4/compat/sys/sysctl.hnew file mode 100644index 0000000..de70d6e--- /dev/null+++ b/ps4/compat/sys/sysctl.h@@ -0,0 +1,4 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#pragma once+// Compatibility stub for OpenOrbis musl toolchain which does not ship sys/sysctl.hdiff --git a/ps4/sce_sys/icon0.png b/ps4/sce_sys/icon0.pngnew file mode 100644index 0000000..28e374cBinary files /dev/null and b/ps4/sce_sys/icon0.png differdiff --git a/ps4/sce_sys/keystone b/ps4/sce_sys/keystonenew file mode 100644index 0000000..e5851f7Binary files /dev/null and b/ps4/sce_sys/keystone differdiff --git a/ps4/sce_sys/pic1.png b/ps4/sce_sys/pic1.pngnew file mode 100644index 0000000..fbd8651Binary files /dev/null and b/ps4/sce_sys/pic1.png differdiff --git a/src/app/crash_guard.cpp b/src/app/crash_guard.cppindex e0f5674..7f945eb 100644--- a/src/app/crash_guard.cpp+++ b/src/app/crash_guard.cpp@@ -219,6 +219,7 @@ void onSignal(int sig, siginfo_t* info, void* uctx) {appendStr(kind, sizeof kind, klen, ")");uintptr_t pc = 0, rbp = 0, rsp = 0;+#if !defined(__ORBIS__) && !defined(__PS4__)if (uctx) {const auto* uc = static_cast<const ucontext_t*>(uctx);#if defined(__FreeBSD__) || defined(__PROSPERO__) || defined(XCLOUD_PS5)@@ -238,6 +239,21 @@ void onSignal(int sig, siginfo_t* info, void* uctx) {faultAddr = static_cast<uintptr_t>(uc->uc_mcontext.mc_addr);}#endif+#else+ uintptr_t faultAddr = info ? reinterpret_cast<uintptr_t>(info->si_addr) : 0;+ if (uctx) {+ // FreeBSD amd64 ucontext: 16-byte sigset, then mcontext of 8-byte slots.+ const auto* mc = reinterpret_cast<const uint64_t*>(static_cast<const char*>(uctx) + 16);+ rbp = static_cast<uintptr_t>(mc[9]);+ pc = static_cast<uintptr_t>(mc[20]);+ rsp = static_cast<uintptr_t>(mc[23]);+ if (faultAddr == 0) faultAddr = static_cast<uintptr_t>(mc[17]);+ // Calling a null function pointer leaves the caller's return address at [rsp].+ if (pc == 0 && rsp != 0 && (rsp & 7) == 0) {+ pc = *reinterpret_cast<const uintptr_t*>(rsp);+ }+ }+#endifchar crashLine[192];size_t clen = 0;@@ -275,6 +291,18 @@ void install(const std::string& markerPath) {appendStr(crashLine, sizeof crashLine, clen, "crash: terminate pc=");appendCodeAddr(crashLine, sizeof crashLine, clen, caller ? caller - 1 : 0);appendStr(crashLine, sizeof crashLine, clen, " addr=0x0");+#if defined(__ORBIS__)+ if (auto ep = std::current_exception()) {+ try {+ std::rethrow_exception(ep);+ } catch (const std::exception& e) {+ appendStr(crashLine, sizeof crashLine, clen, " what=");+ appendStr(crashLine, sizeof crashLine, clen, e.what());+ } catch (...) {+ appendStr(crashLine, sizeof crashLine, clen, " what=<non-std>");+ }+ }+#endifwriteMarker("uncaught exception", crashLine);struct sigaction dfl{};dfl.sa_handler = SIG_DFL;diff --git a/src/app/library_internal.h b/src/app/library_internal.hindex c360c22..c6d9087 100644--- a/src/app/library_internal.h+++ b/src/app/library_internal.h@@ -162,6 +162,13 @@ inline const KnownCloudGame kKnownCloudGames[] = {"Shooter","Call of Duty®: Vanguard includes a deeply engaging single player Campaign, a massive Multiplayer offering featuring over 20 maps including 16 built for core Multiplayer and an exciting new Zombies experience developed by Treyarch.","18", "ClassInd", "Violência Extrema, Drogas Lícitas, Linguagem Imprópria", false},+ {"BT5P2X999VH2", "FORTNITE", "267695549", "Fortnite", "Epic Games Inc.",+ "https://store-images.s-microsoft.com/image/apps.20392.70702278257994163.6d75301b-59c3-4a73-b70c-5901ae9cbb44.24e2eab9-1b75-4157-ba8b-006f4624d839",+ "https://store-images.s-microsoft.com/image/apps.17283.70702278257994163.6d75301b-59c3-4a73-b70c-5901ae9cbb44.bd4108fb-c5af-4a9a-90c5-9a25a46d76a1",+ "https://store-images.s-microsoft.com/image/apps.9161.70702278257994163.6d75301b-59c3-4a73-b70c-5901ae9cbb44.315efab2-af78-4d3e-b99d-e89298f83ad9",+ "Shooter",+ "Everything you love, all in Fortnite.",+ "16", "ClassInd", "Violência, Compras no Jogo", true},};inline void seedKnownGames(std::map<std::string, std::string>& cloudTitleOf,diff --git a/src/app/ps4_main.cpp b/src/app/ps4_main.cppnew file mode 100644index 0000000..a4b67f4--- /dev/null+++ b/src/app/ps4_main.cpp@@ -0,0 +1,29 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+// The PS4's entry point: runs the app with PS4 backends and shell_ps4.cpp.+#include "app/app_core.h"+#include "util/log.h"++#include <fcntl.h>+#include <unistd.h>++int main(int argc, char** argv) {+ (void)argc;+ (void)argv;+ // Early diagnostic marker: verifies main() was entered before complex subsystems+ for (const char* path : {"/data/psbox/boot.log", "/data/homebrew/PSBOX00001/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";+ (void)::write(fd, msg, sizeof(msg) - 1);+ ::close(fd);+ break;+ }+ }+ int rc = xc::app::runApp();+ if (rc != 0) {+ XC_LOGE("main: runApp returned %d", rc);+ }+ xc::log::setFile(nullptr);+ return rc;+}diff --git a/src/app/shell_ps4.cpp b/src/app/shell_ps4.cppnew file mode 100644index 0000000..a25fa5c--- /dev/null+++ b/src/app/shell_ps4.cpp@@ -0,0 +1,62 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "app/shell.h"++#include "app/autoplay.h"+#include "app/updater.h"+#include "display/display.h"+#include "platform/platform.h"+#include "ui/strings.h"+#include "util/log.h"++#include <cstdlib>+#include <sys/stat.h>+#include <unistd.h>++extern "C" int sceSystemServiceHideSplashScreen(void);++namespace xc::app::shell {++void beforeSettings() {+ if (recoverUpdate(platform::appDir())) platform::restartApp();+ importStoreLeftovers(platform::dataDir(), "/data/pkg/previous/PSBOX00001");+}++void beforeDisplay(const Settings&) {+ sceSystemServiceHideSplashScreen();+}++bool afterDisplay(bool) { return true; }++std::vector<std::string> iconFontPaths() {+ return {"/system/common/font/PS4Icon.ttf",+ "/system/common/font2/PS4Icon.ttf",+ "/system_ex/common_ex/font2/PS4Icon.ttf"};+}++bool pumpEvents() { return true; }+bool hasFocus() { return true; }+bool canSelfUpdate() { return false; }+void beforeShutdown() {}+Caps caps() { return {true, false, true}; }+void setFullscreen(bool) {}+bool fullscreenSwitched(bool&) { return false; }+bool openUrl(const std::string&) { return false; }+bool setTextInput(bool) { return false; }+std::string takeTextInput() { return {}; }+void setMouseHandler(std::function<void(const MouseEvent&)>) {}++bool isInstalledCopy(const std::string& dir) {+ struct stat here {}, running {};+ return ::stat((dir + "/eboot.bin").c_str(), &here) == 0 && ::stat("/app0/eboot.bin", &running) == 0 &&+ here.st_ino == running.st_ino;+}++void restartOrExit() {+ if (!g_autoplay.noRestart) platform::restartApp();+ platform::notify(ui::tr(ui::Str::UpdateReopen), "update installed, restart failed: closing");+ platform::sleepMs(2000);+ _exit(0);+}++} // namespace xc::app::shelldiff --git a/src/app/stream_player.cpp b/src/app/stream_player.cppindex 6fb0c03..5f9ed6e 100644--- a/src/app/stream_player.cpp+++ b/src/app/stream_player.cpp@@ -16,6 +16,7 @@#include "util/log.h"#include <algorithm>+#include <array>#include <atomic>#include <chrono>#include <cstdlib>@@ -125,6 +126,14 @@ struct StreamPlayer::Impl {std::atomic<float> micGain{1.0f};std::atomic<uint32_t> audioSendTimestamp{0};bool encoderInitialized = false;+ platform::Thread inputThread;+ std::mutex inputMutex;+ std::condition_variable inputCv;+ std::array<stream::GamepadFrame, input::kMaxPads> pendingPads{};+ std::array<bool, input::kMaxPads> pendingPadDirty{};+ std::vector<stream::KeyFrame> pendingKeys;+ std::vector<stream::MouseFrame> pendingMouse;+// Opening and closing the microphone happen on several threads (start,// reconnect, the end of the stream): one at a time.std::mutex micMutex;@@ -186,6 +195,45 @@ struct StreamPlayer::Impl {std::lock_guard<std::mutex> lock(audioMutex_);}audioCv.notify_all();+ {+ std::lock_guard<std::mutex> lock(inputMutex);+ }+ inputCv.notify_all();+ }++ void inputLoop() {+ platform::setThreadAffinity(platform::ThreadRole::Network, "xcloud_in");+ while (running) {+ std::array<stream::GamepadFrame, input::kMaxPads> pads;+ std::array<bool, input::kMaxPads> dirty{};+ std::vector<stream::KeyFrame> keys;+ std::vector<stream::MouseFrame> mouse;+ {+ std::unique_lock<std::mutex> lock(inputMutex);+ inputCv.wait(lock, [&] {+ if (!running) return true;+ if (!pendingKeys.empty() || !pendingMouse.empty()) return true;+ for (bool d : pendingPadDirty) if (d) return true;+ return false;+ });+ if (!running) break;+ pads = pendingPads;+ dirty = pendingPadDirty;+ pendingPadDirty.fill(false);+ keys = std::move(pendingKeys);+ pendingKeys.clear();+ mouse = std::move(pendingMouse);+ pendingMouse.clear();+ }+ auto s = current();+ if (s && running) {+ for (int i = 0; i < input::kMaxPads; ++i) {+ if (dirty[i]) s->sendGamepad(pads[i]);+ }+ if (!keys.empty()) s->sendKeys(keys);+ for (const auto& m : mouse) s->sendMouse(m);+ }+ }}void audioLoop() {@@ -578,7 +626,8 @@ struct StreamPlayer::Impl {}running = true;if (!platform::startThread(videoThread, [this] { videoLoop(); }) ||- !platform::startThread(audioThread, [this] { audioLoop(); }, 1u << 20)) {+ !platform::startThread(audioThread, [this] { audioLoop(); }, 1u << 20) ||+ !platform::startThread(inputThread, [this] { inputLoop(); }, 256u << 10)) {err = "could not start the media threads";running = false;return false;@@ -738,6 +787,7 @@ struct StreamPlayer::Impl {void stop() {end("stopped");if (auto s = current()) s->close();+ if (inputThread.joinable()) inputThread.join();if (videoThread.joinable()) videoThread.join();if (audioThread.joinable()) audioThread.join();std::shared_ptr<stream::StreamSession> last;@@ -767,8 +817,7 @@ std::string StreamPlayer::endReason() const {}void StreamPlayer::sendInput(const input::ControllerState& p, int index) {- auto s = impl_->current();- if (!s || !impl_->running) return;+ if (!impl_->running || index < 0 || index >= input::kMaxPads) return;stream::GamepadFrame f;f.index = static_cast<uint8_t>(index);auto set = [&](bool on, uint16_t bit) {@@ -795,25 +844,34 @@ void StreamPlayer::sendInput(const input::ControllerState& p, int index) {f.rightY = -p.rightStickY;f.leftTrigger = p.triggerL2;f.rightTrigger = p.triggerR2;- s->sendGamepad(f);++ {+ std::lock_guard<std::mutex> lock(impl_->inputMutex);+ impl_->pendingPads[index] = f;+ impl_->pendingPadDirty[index] = true;+ }+ impl_->inputCv.notify_one();}void StreamPlayer::sendKbm(const input::KbmInput& in) {- auto s = impl_->current();- if (!s || !impl_->running) return;- if (!in.keys.empty()) {- std::vector<stream::KeyFrame> keys;- for (const auto& k : in.keys) keys.push_back({k.vk, k.pressed});- s->sendKeys(keys);- }- if (in.moved) {- stream::MouseFrame m;- m.dx = in.dx * 2; // as the web client: twice the pointer's movement- m.dy = in.dy * 2;- m.wheelY = in.wheel * 120; // one notch = WHEEL_DELTA (120), as Windows (and the game) count it- m.buttons = in.buttons;- s->sendMouse(m);+ if (!impl_->running) return;+ {+ std::lock_guard<std::mutex> lock(impl_->inputMutex);+ if (!in.keys.empty()) {+ for (const auto& k : in.keys) {+ if (impl_->pendingKeys.size() < 128) impl_->pendingKeys.push_back({k.vk, k.pressed});+ }+ }+ if (in.moved) {+ stream::MouseFrame m;+ m.dx = in.dx * 2; // as the web client: twice the pointer's movement+ m.dy = in.dy * 2;+ m.wheelY = in.wheel * 120; // one notch = WHEEL_DELTA (120), as Windows (and the game) count it+ m.buttons = in.buttons;+ if (impl_->pendingMouse.size() < 128) impl_->pendingMouse.push_back(m);+ }}+ impl_->inputCv.notify_one();}bool StreamPlayer::titleFocused() const { return impl_->titleFocused; }diff --git a/src/app/worker.cpp b/src/app/worker.cppindex 50b7929..a009cd8 100644--- a/src/app/worker.cpp+++ b/src/app/worker.cpp@@ -361,12 +361,22 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefr!g_autoplay.gridTest && !g_autoplay.gameSettingsTest && !g_autoplay.publisherTest && !g_autoplay.friendsTest &&!g_autoplay.regionTest && !g_autoplay.mw4Test && !g_autoplay.v150Test && !g_autoplay.claimTest) {platform::sleepMs(6000);+ auto matchTile = [](const ui::GameTile& t, const std::string& target) {+ auto eq = [](std::string_view a, std::string_view b) {+ if (a.size() != b.size()) return false;+ for (size_t i = 0; i < a.size(); ++i)+ if (std::tolower(static_cast<unsigned char>(a[i])) != std::tolower(static_cast<unsigned char>(b[i])))+ return false;+ return true;+ };+ return eq(t.titleId, target) || eq(t.productId, target) || eq(t.name, target);+ };ui::GameTile tile;tile.titleId = g_autoplay.title;tile.name = g_autoplay.title;for (const auto& row : rows)for (const auto& t : row.tiles)- if ((t.titleId == g_autoplay.title || t.productId == g_autoplay.title || t.name == g_autoplay.title) && tile.productId.empty()) tile = t;+ if (matchTile(t, g_autoplay.title) && tile.productId.empty()) tile = t;std::lock_guard<std::mutex> lock(g_argMutex);g_playTile = tile;g_command = kPlay;@@ -492,9 +502,19 @@ void loadLibrary(auth::AuthManager& am, xcloud::GssvClient& gssv, bool forceRefrui::GameTile tile;tile.titleId = g_autoplay.title;tile.name = g_autoplay.title;+ auto matchTile = [](const ui::GameTile& t, const std::string& target) {+ auto eq = [](std::string_view a, std::string_view b) {+ if (a.size() != b.size()) return false;+ for (size_t i = 0; i < a.size(); ++i)+ if (std::tolower(static_cast<unsigned char>(a[i])) != std::tolower(static_cast<unsigned char>(b[i])))+ return false;+ return true;+ };+ return eq(t.titleId, target) || eq(t.productId, target) || eq(t.name, target);+ };for (const auto& row : rows)for (const auto& t : row.tiles)- if (t.titleId == g_autoplay.title && tile.productId.empty()) tile = t;+ if (matchTile(t, g_autoplay.title) && tile.productId.empty()) tile = t;std::lock_guard<std::mutex> lock(g_argMutex);g_playTile = tile;g_command = kPlay;diff --git a/src/app/worker_stream.cpp b/src/app/worker_stream.cppindex 0f0e409..7107e63 100644--- a/src/app/worker_stream.cpp+++ b/src/app/worker_stream.cpp@@ -139,6 +139,8 @@ std::string stream(xcloud::GssvClient& gssv) {const uint64_t started = platform::nowMs();uint64_t nextTick = started;bool snapshot1 = false, snapshot2 = false, snapshot3 = false, snapshot4 = false;+ uint64_t nextPeriodicShot = 150000;+ int periodicShotIdx = 5;bool autoplayDone = false;int bestRtt = -1; // lowest round trip seen: the region's latencyint tallest = 0; // the tallest picture seen (the probe's measure)@@ -202,6 +204,10 @@ std::string stream(xcloud::GssvClient& gssv) {snapshot4 = true;player.requestSnapshot(platform::dataDir() + "/frame4.ppm");}+ if (elapsed >= nextPeriodicShot) {+ nextPeriodicShot = elapsed + 30000;+ player.requestSnapshot(platform::dataDir() + "/frame" + std::to_string(periodicShotIdx++) + ".ppm");+ }}if (platform::nowMs() >= nextTick) {uint64_t tickNow = platform::nowMs();diff --git a/src/display/display_ps4.cpp b/src/display/display_ps4.cppnew file mode 100644index 0000000..15c9d27--- /dev/null+++ b/src/display/display_ps4.cpp@@ -0,0 +1,558 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "display/display.h"+#include "platform/platform.h"+#include "util/log.h"++#include <algorithm>+#include <array>+#include <atomic>+#include <cmath>+#include <condition_variable>+#include <cstring>+#include <functional>+#include <memory>+#include <mutex>+#include <thread>+#include <vector>+#include <emmintrin.h>+#include <smmintrin.h>++#include <orbis/libkernel.h>+#include <orbis/VideoOut.h>++namespace xc::display {++namespace {++constexpr size_t kFramePitch = kWidth * 4;+constexpr size_t kFrameBytes = (kFramePitch * kHeight + 0x1FFFFFull) & ~0x1FFFFFull; // 2MB aligned per buffer+constexpr int kBuffers = 3;+constexpr size_t kMemoryBytes = kFrameBytes * kBuffers;+constexpr size_t kMemoryAlignment = 0x200000;+constexpr int kMemoryTypeGarlic = 3;+constexpr int kMapProtection = 0x33; // RW++int g_videoHandle = -1;+void* g_mappedMemory = nullptr;+uint8_t* g_buffers[kBuffers]{};+int g_currentBuffer = 0;+int64_t g_flipMarker = 0;+std::array<int64_t, kBuffers> g_bufferMarker{-1, -1, -1};+std::mutex g_frameMutex;+std::atomic<int> g_sharpness{0};++struct Overlay {+ std::vector<uint32_t> px;+ int x = 0, y = 0, w = 0, h = 0;+ uint8_t alpha = 255;+};+std::mutex g_overlayMutex;+std::unique_ptr<Overlay> g_overlay;++struct RowScratch {+ int lastWidth = 0;+ int lastHeight = 0;+ std::array<int, kWidth> mapX{};+ std::array<int, kHeight> mapY{};++ void update(int width, int height) {+ if (width == lastWidth && height == lastHeight) return;+ lastWidth = width;+ lastHeight = height;+ for (int dx = 0; dx < static_cast<int>(kWidth); ++dx) {+ mapX[dx] = dx * width / static_cast<int>(kWidth);+ }+ for (int dy = 0; dy < static_cast<int>(kHeight); ++dy) {+ mapY[dy] = dy * height / static_cast<int>(kHeight);+ }+ }+};+static RowScratch g_scratch;++class RowPool {+public:+ static constexpr int kNumWorkers = 4;++ RowPool() {+ for (int i = 0; i < kNumWorkers; ++i) {+ workers_[i] = std::thread([this, i]() {+ platform::setThreadAffinity(platform::ThreadRole::Worker, "ps4_display");+ workerLoop(i);+ });+ }+ }++ ~RowPool() {+ {+ std::lock_guard<std::mutex> runLock(runMutex_);+ std::lock_guard<std::mutex> lock(mutex_);+ stop_ = true;+ cvWork_.notify_all();+ }+ for (auto& w : workers_) {+ if (w.joinable()) w.join();+ }+ }++ void run(const std::function<void(int yStart, int yEnd)>& fn) {+ std::unique_lock<std::mutex> runLock(runMutex_);+ {+ std::lock_guard<std::mutex> lock(mutex_);+ currentTask_ = &fn;+ remaining_ = kNumWorkers;+ taskSeq_++;+ cvWork_.notify_all();+ }+ // Slice 4 is processed by caller (main thread or video thread)+ int rowsPerSlice = kHeight / (kNumWorkers + 1); // 216 rows+ int yStart = kNumWorkers * rowsPerSlice;+ int yEnd = kHeight;+ fn(yStart, yEnd);++ std::unique_lock<std::mutex> lock(mutex_);+ cvDone_.wait(lock, [this]() { return remaining_ == 0; });+ currentTask_ = nullptr;+ _mm_sfence();+ }++private:+ void workerLoop(int id) {+ int rowsPerSlice = kHeight / (kNumWorkers + 1); // 216 rows+ int yStart = id * rowsPerSlice;+ int yEnd = (id + 1) * rowsPerSlice;+ uint64_t lastSeq = 0;++ while (true) {+ const std::function<void(int, int)>* task = nullptr;+ {+ std::unique_lock<std::mutex> lock(mutex_);+ cvWork_.wait(lock, [this, &lastSeq]() { return stop_ || taskSeq_ > lastSeq; });+ if (stop_) break;+ task = currentTask_;+ lastSeq = taskSeq_;+ }++ if (task && *task) {+ (*task)(yStart, yEnd);+ }++ {+ std::lock_guard<std::mutex> lock(mutex_);+ if (--remaining_ == 0) {+ cvDone_.notify_one();+ }+ }+ }+ }++ std::array<std::thread, kNumWorkers> workers_;+ std::mutex runMutex_;+ std::mutex mutex_;+ std::condition_variable cvWork_;+ std::condition_variable cvDone_;+ const std::function<void(int, int)>* currentTask_ = nullptr;+ int remaining_ = 0;+ uint64_t taskSeq_ = 0;+ bool stop_ = false;+};++static std::unique_ptr<RowPool> g_rowPool;++inline __m128i yuvToRgbaSse(int y0, int y1, int y2, int y3,+ int u0, int u1, int u2, int u3,+ int v0, int v1, int v2, int v3) {+ __m128i yVec = _mm_setr_epi32(y0 - 16, y1 - 16, y2 - 16, y3 - 16);+ __m128i uVec = _mm_setr_epi32(u0 - 128, u1 - 128, u2 - 128, u3 - 128);+ __m128i vVec = _mm_setr_epi32(v0 - 128, v1 - 128, v2 - 128, v3 - 128);++ __m128i c = _mm_mullo_epi32(yVec, _mm_set1_epi32(1192));+ __m128i r = _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(c, _mm_mullo_epi32(vVec, _mm_set1_epi32(1836))), _mm_set1_epi32(512)), 10);+ __m128i g = _mm_srai_epi32(_mm_add_epi32(_mm_sub_epi32(_mm_sub_epi32(c, _mm_mullo_epi32(uVec, _mm_set1_epi32(218))), _mm_mullo_epi32(vVec, _mm_set1_epi32(546))), _mm_set1_epi32(512)), 10);+ __m128i b = _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(c, _mm_mullo_epi32(uVec, _mm_set1_epi32(2163))), _mm_set1_epi32(512)), 10);++ r = _mm_max_epi32(_mm_min_epi32(r, _mm_set1_epi32(255)), _mm_setzero_si128());+ g = _mm_max_epi32(_mm_min_epi32(g, _mm_set1_epi32(255)), _mm_setzero_si128());+ b = _mm_max_epi32(_mm_min_epi32(b, _mm_set1_epi32(255)), _mm_setzero_si128());++ __m128i rgba = _mm_or_si128(_mm_set1_epi32(static_cast<int>(0xFF000000u)),+ _mm_or_si128(r, _mm_or_si128(_mm_slli_epi32(g, 8), _mm_slli_epi32(b, 16))));+ return rgba;+}++inline void blendOverlayRow(uint32_t* dRow, int dy, const Overlay& ov) {+ if (dy < ov.y || dy >= ov.y + ov.h) return;+ int oy = dy - ov.y;+ const uint32_t* sRow = ov.px.data() + oy * ov.w;+ for (int ox = 0; ox < ov.w; ++ox) {+ int px = ov.x + ox;+ if (px < 0 || px >= static_cast<int>(kWidth)) continue;+ uint32_t p = sRow[ox];+ uint32_t alpha = ((p >> 24) * ov.alpha) / 255;+ if (alpha == 0) continue;+ if (alpha == 255) {+ dRow[px] = p;+ continue;+ }+ uint32_t inv = 255 - alpha;+ uint32_t bg = dRow[px];+ uint32_t r = (((p & 0xFF) * alpha) + ((bg & 0xFF) * inv)) / 255;+ uint32_t g = ((((p >> 8) & 0xFF) * alpha) + (((bg >> 8) & 0xFF) * inv)) / 255;+ uint32_t b = ((((p >> 16) & 0xFF) * alpha) + (((bg >> 16) & 0xFF) * inv)) / 255;+ dRow[px] = 0xFF000000u | (b << 16) | (g << 8) | r;+ }+}++extern "C" int sceKernelMapNamedFlexibleMemory(void** address, size_t length, int protection, int flags, const char* name);++} // namespace++bool init(bool /*preferGpu*/) {+ if (g_videoHandle >= 0) return true;+ int handle = sceVideoOutOpen(ORBIS_USER_SERVICE_USER_ID_SYSTEM, 0, 0, nullptr);+ if (handle < 0) {+ handle = sceVideoOutOpen(0xFF, 0, 0, nullptr);+ }+ if (handle < 0) {+ XC_LOGE("display: sceVideoOutOpen failed: 0x%08x", static_cast<unsigned>(handle));+ return false;+ }+ sceVideoOutSetFlipRate(handle, 0); // 60 Hz++ void* mapped = nullptr;+ int64_t physAddr = 0;+ int rc = -1;+ size_t directMemSize = sceKernelGetDirectMemorySize();+ if (directMemSize >= kMemoryBytes) {+ rc = sceKernelAllocateDirectMemory(0, static_cast<int64_t>(directMemSize),+ kMemoryBytes, kMemoryAlignment, kMemoryTypeGarlic, &physAddr);+ if (rc == 0) {+ rc = sceKernelMapDirectMemory(&mapped, kMemoryBytes, kMapProtection, 0, physAddr, kMemoryAlignment);+ }+ }+ if (rc != 0 || !mapped) {+ // Fallback to flexible memory (reliable on all PS4 jailbreak environments)+ rc = sceKernelMapNamedFlexibleMemory(&mapped, kMemoryBytes, kMapProtection, 0, "display_fb");+ if (rc != 0 || !mapped) {+ XC_LOGE("display: allocate direct and flexible memory failed: 0x%08x", static_cast<unsigned>(rc));+ sceVideoOutClose(handle);+ return false;+ }+ XC_LOGI("display: %zu bytes of flexible memory at %p (direct memory fallback)", kMemoryBytes, mapped);+ } else {+ XC_LOGI("display: %zu bytes of direct memory at %p", kMemoryBytes, mapped);+ }++ g_mappedMemory = mapped;+ g_videoHandle = handle;++ for (int i = 0; i < kBuffers; ++i) {+ g_buffers[i] = static_cast<uint8_t*>(mapped) + i * kFrameBytes;+ std::memset(g_buffers[i], 0, kWidth * kHeight * 4);+ }++ OrbisVideoOutBufferAttribute attr{};+ sceVideoOutSetBufferAttribute(&attr, ORBIS_VIDEO_OUT_PIXEL_FORMAT_A8B8G8R8_SRGB,+ ORBIS_VIDEO_OUT_TILING_MODE_LINEAR,+ ORBIS_VIDEO_OUT_ASPECT_RATIO_16_9,+ kWidth, kHeight, kWidth);++ rc = sceVideoOutRegisterBuffers(handle, 0, reinterpret_cast<void* const*>(g_buffers), kBuffers, &attr);+ if (rc != 0) {+ XC_LOGE("display: sceVideoOutRegisterBuffers failed: 0x%08x", static_cast<unsigned>(rc));+ sceVideoOutClose(handle);+ g_videoHandle = -1;+ return false;+ }++ g_rowPool = std::make_unique<RowPool>();++ XC_LOGI("display: PS4 VideoOut initialized (3 linear 1080p buffers, handle %d, 4 SIMD worker threads)", handle);+ return true;+}++void shutdown() {+ g_rowPool.reset();+ if (g_videoHandle >= 0) {+ sceVideoOutClose(g_videoHandle);+ g_videoHandle = -1;+ }+ g_mappedMemory = nullptr;+}++std::mutex& frameMutex() { return g_frameMutex; }++namespace {+// Picks the back buffer for the next frame: not on screen, not queued.+// Without `wait`, gives up at once when all are busy.+bool acquireBuffer(bool wait = true) {+ for (int attempt = 0; attempt < 4; ++attempt) {+ OrbisVideoOutFlipStatus status{};+ int64_t shown = g_flipMarker; // no status: assume everything shown+ if (g_flipMarker && sceVideoOutGetFlipStatus(g_videoHandle, &status) == 0 && status.flipArg > 0)+ shown = status.flipArg;+ int onScreen = -1;+ for (int i = 0; i < kBuffers; ++i)+ if (g_bufferMarker[i] >= 0 && g_bufferMarker[i] <= shown &&+ (onScreen < 0 || g_bufferMarker[i] > g_bufferMarker[onScreen]))+ onScreen = i;+ int best = -1;+ for (int i = 0; i < kBuffers; ++i) {+ if (i == onScreen || (g_bufferMarker[i] >= 0 && g_bufferMarker[i] > shown)) continue;+ if (best < 0 || g_bufferMarker[i] < g_bufferMarker[best]) best = i;+ }+ if (best >= 0) {+ g_currentBuffer = best;+ return true;+ }+ if (!wait) return false;+ sceVideoOutWaitVblank();+ }+ // Flip status not moving: fall back to round robin.+ g_currentBuffer = static_cast<int>(g_flipMarker % kBuffers);+ return true;+}+} // namespace++void present() {+ if (g_videoHandle < 0) return;+ int rc = sceVideoOutSubmitFlip(g_videoHandle, g_currentBuffer, ORBIS_VIDEO_OUT_FLIP_VSYNC, ++g_flipMarker);+ if (rc != 0) {+ XC_LOGW("display: submit flip: 0x%08x", static_cast<unsigned>(rc));+ }+ g_bufferMarker[g_currentBuffer] = g_flipMarker;+}++void drawRgba(const uint32_t* pixels) {+ if (!pixels || g_videoHandle < 0) return;+ if (!acquireBuffer(true)) return;+ uint32_t* dst = reinterpret_cast<uint32_t*>(g_buffers[g_currentBuffer]);++ if (!g_rowPool) {+ const __m128i* s = reinterpret_cast<const __m128i*>(pixels);+ __m128i* d = reinterpret_cast<__m128i*>(dst);+ size_t count = (kWidth * kHeight * sizeof(uint32_t)) / sizeof(__m128i);+ for (size_t i = 0; i < count; i += 4) {+ _mm_stream_si128(d + i, _mm_loadu_si128(s + i));+ _mm_stream_si128(d + i + 1, _mm_loadu_si128(s + i + 1));+ _mm_stream_si128(d + i + 2, _mm_loadu_si128(s + i + 2));+ _mm_stream_si128(d + i + 3, _mm_loadu_si128(s + i + 3));+ }+ _mm_sfence();+ return;+ }++ g_rowPool->run([dst, pixels](int yStart, int yEnd) {+ for (int y = yStart; y < yEnd; ++y) {+ const __m128i* s = reinterpret_cast<const __m128i*>(pixels + y * kWidth);+ __m128i* d = reinterpret_cast<__m128i*>(dst + y * kWidth);+ constexpr size_t kVecsPerRow = (kWidth * sizeof(uint32_t)) / sizeof(__m128i); // 480+ for (size_t i = 0; i < kVecsPerRow; i += 4) {+ _mm_stream_si128(d + i, _mm_loadu_si128(s + i));+ _mm_stream_si128(d + i + 1, _mm_loadu_si128(s + i + 1));+ _mm_stream_si128(d + i + 2, _mm_loadu_si128(s + i + 2));+ _mm_stream_si128(d + i + 3, _mm_loadu_si128(s + i + 3));+ }+ }+ });+}++void pump() {}++void idleWait(uint32_t ms) {+ platform::sleepMs(ms);+}++bool drawYuv420(const uint8_t* y, const uint8_t* u, const uint8_t* v,+ int strideY, int strideU, int strideV,+ int width, int height, bool wait) {+ if (g_videoHandle < 0 || !y || !u || !v || width <= 0 || height <= 0) return false;+ if (!acquireBuffer(wait)) return false;+ uint32_t* dst = reinterpret_cast<uint32_t*>(g_buffers[g_currentBuffer]);++ g_scratch.update(width, height);++ std::unique_ptr<Overlay> activeOverlay;+ {+ std::lock_guard<std::mutex> lock(g_overlayMutex);+ if (g_overlay) {+ activeOverlay = std::make_unique<Overlay>(*g_overlay);+ }+ }++ auto renderSlice = [y, u, v, strideY, strideU, strideV, dst, &activeOverlay](int yStart, int yEnd) {+ const auto& mapX = g_scratch.mapX;+ const auto& mapY = g_scratch.mapY;++ for (int dy = yStart; dy < yEnd; ++dy) {+ int sy = mapY[dy];+ const uint8_t* yRow = y + sy * strideY;+ const uint8_t* uRow = u + (sy / 2) * strideU;+ const uint8_t* vRow = v + (sy / 2) * strideV;+ uint32_t* dRow = dst + dy * kWidth;++ for (int dx = 0; dx < static_cast<int>(kWidth); dx += 4) {+ int sx0 = mapX[dx];+ int sx1 = mapX[dx + 1];+ int sx2 = mapX[dx + 2];+ int sx3 = mapX[dx + 3];++ int y0 = yRow[sx0];+ int y1 = yRow[sx1];+ int y2 = yRow[sx2];+ int y3 = yRow[sx3];++ int u0 = uRow[sx0 / 2];+ int u1 = uRow[sx1 / 2];+ int u2 = uRow[sx2 / 2];+ int u3 = uRow[sx3 / 2];++ int v0 = vRow[sx0 / 2];+ int v1 = vRow[sx1 / 2];+ int v2 = vRow[sx2 / 2];+ int v3 = vRow[sx3 / 2];++ __m128i rgba = yuvToRgbaSse(y0, y1, y2, y3, u0, u1, u2, u3, v0, v1, v2, v3);+ _mm_stream_si128(reinterpret_cast<__m128i*>(&dRow[dx]), rgba);+ }++ if (activeOverlay) {+ _mm_sfence();+ blendOverlayRow(dRow, dy, *activeOverlay);+ }+ }+ };++ if (g_rowPool) {+ g_rowPool->run(renderSlice);+ } else {+ renderSlice(0, kHeight);+ _mm_sfence();+ }+ return true;+}++bool drawNv12(const uint8_t* y, const uint8_t* uv, int strideY, int strideUV,+ int width, int height, bool wait) {+ if (g_videoHandle < 0 || !y || !uv || width <= 0 || height <= 0) return false;+ if (!acquireBuffer(wait)) return false;+ uint32_t* dst = reinterpret_cast<uint32_t*>(g_buffers[g_currentBuffer]);++ g_scratch.update(width, height);++ std::unique_ptr<Overlay> activeOverlay;+ {+ std::lock_guard<std::mutex> lock(g_overlayMutex);+ if (g_overlay) {+ activeOverlay = std::make_unique<Overlay>(*g_overlay);+ }+ }++ auto renderSlice = [y, uv, strideY, strideUV, dst, &activeOverlay](int yStart, int yEnd) {+ const auto& mapX = g_scratch.mapX;+ const auto& mapY = g_scratch.mapY;++ for (int dy = yStart; dy < yEnd; ++dy) {+ int sy = mapY[dy];+ const uint8_t* yRow = y + sy * strideY;+ const uint8_t* uvRow = uv + (sy / 2) * strideUV;+ uint32_t* dRow = dst + dy * kWidth;++ for (int dx = 0; dx < static_cast<int>(kWidth); dx += 4) {+ int sx0 = mapX[dx];+ int sx1 = mapX[dx + 1];+ int sx2 = mapX[dx + 2];+ int sx3 = mapX[dx + 3];++ int y0 = yRow[sx0];+ int y1 = yRow[sx1];+ int y2 = yRow[sx2];+ int y3 = yRow[sx3];++ int u0 = uvRow[(sx0 / 2) * 2];+ int v0 = uvRow[(sx0 / 2) * 2 + 1];++ int u1 = uvRow[(sx1 / 2) * 2];+ int v1 = uvRow[(sx1 / 2) * 2 + 1];++ int u2 = uvRow[(sx2 / 2) * 2];+ int v2 = uvRow[(sx2 / 2) * 2 + 1];++ int u3 = uvRow[(sx3 / 2) * 2];+ int v3 = uvRow[(sx3 / 2) * 2 + 1];++ __m128i rgba = yuvToRgbaSse(y0, y1, y2, y3, u0, u1, u2, u3, v0, v1, v2, v3);+ _mm_stream_si128(reinterpret_cast<__m128i*>(&dRow[dx]), rgba);+ }++ if (activeOverlay) {+ _mm_sfence();+ blendOverlayRow(dRow, dy, *activeOverlay);+ }+ }+ };++ if (g_rowPool) {+ g_rowPool->run(renderSlice);+ } else {+ renderSlice(0, kHeight);+ _mm_sfence();+ }+ return true;+}++void setOverlay(const uint32_t* pixels, int x, int y, int w, int h, uint8_t opacity) {+ std::lock_guard<std::mutex> lock(g_overlayMutex);+ if (!pixels || w <= 0 || h <= 0 || opacity == 0) {+ g_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);+}++void setSharpness(int amount) { g_sharpness = std::clamp(amount, 0, 256); }+void setDeband(int) {}+void setUpscaler(int) {}+void setRestore(bool) {}+DisplayCaps caps() { return {}; }+void setSwapImages(int) {}+void setPresentWait(bool) {}+bool canSwitchRefresh() { return false; }+bool setHighRefresh(bool) { return false; }+bool bringUpTest(int) { return false; }+uint64_t lastPresentId() { return static_cast<uint64_t>(g_flipMarker); }+bool lastShown(uint64_t& id, uint64_t& atUs) {+ if (g_videoHandle < 0) return false;+ OrbisVideoOutFlipStatus status{};+ if (g_flipMarker && sceVideoOutGetFlipStatus(g_videoHandle, &status) == 0 && status.flipArg > 0) {+ id = static_cast<uint64_t>(status.flipArg);+ atUs = platform::nowUs();+ return true;+ }+ id = static_cast<uint64_t>(g_flipMarker);+ atUs = platform::nowUs();+ return true;+}+bool readBackRgb(std::vector<uint8_t>& rgb, int& width, int& height) {+ std::lock_guard<std::mutex> lock(g_frameMutex);+ if (!g_buffers[g_currentBuffer]) return false;+ width = kWidth;+ height = kHeight;+ const uint32_t* base = reinterpret_cast<const uint32_t*>(g_buffers[g_currentBuffer]);+ rgb.resize(static_cast<size_t>(kWidth) * kHeight * 3);+ for (size_t i = 0; i < static_cast<size_t>(kWidth) * kHeight; ++i) {+ uint32_t p = base[i];+ rgb[i * 3 + 0] = static_cast<uint8_t>(p);+ rgb[i * 3 + 1] = static_cast<uint8_t>(p >> 8);+ rgb[i * 3 + 2] = static_cast<uint8_t>(p >> 16);+ }+ return true;+}++} // namespace xc::displaydiff --git a/src/input/controller_ps4.cpp b/src/input/controller_ps4.cppnew file mode 100644index 0000000..782b384--- /dev/null+++ b/src/input/controller_ps4.cpp@@ -0,0 +1,295 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "input/controller.h"+#include "input/controller_backend.h"+#include "input/input_ext.h"+#include "util/log.h"++#include <algorithm>+#include <cstddef>+#include <cstring>++extern "C" {+struct ScePadStick {+ uint8_t x;+ uint8_t y;+};++struct ScePadTouchPoint {+ uint16_t x;+ uint16_t y;+ uint8_t id;+ uint8_t reserve[3];+};++struct ScePadTouchData {+ uint8_t touchNum;+ uint8_t reserve[3];+ uint32_t reserve1;+ ScePadTouchPoint touch[2];+};++struct ScePadData {+ uint32_t buttons;+ ScePadStick leftStick;+ ScePadStick rightStick;+ uint8_t l2;+ uint8_t r2;+ uint16_t padding;+ float orientation[4];+ float acceleration[3];+ float angularVelocity[3];+ ScePadTouchData touchData;+ uint8_t connected;+ uint64_t timestamp;+ uint8_t ext[16];+ uint8_t count;+ uint8_t unknown[15];+};+static_assert(offsetof(ScePadData, connected) == 76, "ScePadData layout");++struct SceUserServiceInitializeParams {+ uint32_t priority;+};+struct SceUserServiceLoginUserIdList {+ int32_t userId[4];+};++int sceUserServiceInitialize(const SceUserServiceInitializeParams* param);+int sceUserServiceGetInitialUser(int32_t* userId);+int sceUserServiceGetLoginUserIdList(SceUserServiceLoginUserIdList* list);+int sceUserServiceGetUserName(int32_t userId, char* name, size_t size);+int scePadInit(void);+int scePadOpen(int32_t userId, int32_t type, int32_t index, const void* param);+int scePadClose(int32_t handle);+int scePadReadState(int32_t handle, ScePadData* data);++struct ScePadVibrationParam {+ uint8_t largeMotor;+ uint8_t smallMotor;+};+int scePadSetVibration(int32_t handle, const ScePadVibrationParam* param);++struct ScePadColor {+ uint8_t r, g, b, reserved;+};+int scePadSetLightBar(int32_t handle, const ScePadColor* param);+int scePadResetLightBar(int32_t handle);+}++namespace xc::input {++namespace {++struct Slot {+ int handle = -1;+ int32_t userId = -1;+ char name[64]{};+};+Slot g_slots[4];+bool g_userServiceInit = false;+bool g_padInit = false;+bool g_rumbleLogged = false;++inline float normStick(uint8_t v) {+ return (v - 128) / 127.5f;+}++inline float normTrigger(uint8_t v) {+ return v / 255.0f;+}++void openPad(int slot, int32_t user) {+ auto& pad = g_slots[slot];+ if (pad.handle >= 0 && pad.userId == user) return;+ if (pad.handle >= 0) {+ scePadClose(pad.handle);+ pad.handle = -1;+ }+ pad.userId = user;+ pad.handle = scePadOpen(user, 0, 0, nullptr);+ if (pad.handle < 0) {+ XC_LOGW("pad: scePadOpen for user %d failed: 0x%08x", user, static_cast<unsigned>(pad.handle));+ return;+ }+ sceUserServiceGetUserName(user, pad.name, sizeof(pad.name));+ slotOpened(slot);+ XC_LOGI("pad %d open (user %d \"%s\", handle %d, DualShock 4)", slot, user, pad.name, pad.handle);+}++void closePad(int slot) {+ auto& pad = g_slots[slot];+ if (pad.handle < 0) return;+ if (slotLightSet(slot)) scePadResetLightBar(pad.handle);+ slotClosed(slot);+ scePadClose(pad.handle);+ XC_LOGI("pad %d closed (user %d)", slot, pad.userId);+ pad.handle = -1;+ pad.userId = -1;+ pad.name[0] = 0;+}++} // namespace++namespace backend {++bool padOpen(int slot) { return g_slots[slot].handle >= 0; }++bool readPad(int slot, RawPad& out) {+ if (g_slots[slot].handle < 0) return false;+ ScePadData pad{};+ int rc = scePadReadState(g_slots[slot].handle, &pad);+ if (rc != 0 || !pad.connected) return false;+ uint32_t b = pad.buttons;++ out.dpadUp = (b & 0x0010) != 0;+ out.dpadRight = (b & 0x0020) != 0;+ out.dpadDown = (b & 0x0040) != 0;+ out.dpadLeft = (b & 0x0080) != 0;++ out.btnA = (b & 0x4000) != 0; // Cross+ out.btnB = (b & 0x2000) != 0; // Circle+ out.btnX = (b & 0x8000) != 0; // Square+ out.btnY = (b & 0x1000) != 0; // Triangle++ out.btnL1 = (b & 0x0400) != 0;+ out.btnR1 = (b & 0x0800) != 0;+ out.btnL3 = (b & 0x0002) != 0;+ out.btnR3 = (b & 0x0004) != 0;++ out.btnOptions = (b & 0x0008) != 0;+ out.btnTouchpad = (b & 0x100000) != 0;++ out.leftX = normStick(pad.leftStick.x);+ out.leftY = normStick(pad.leftStick.y);+ out.rightX = normStick(pad.rightStick.x);+ out.rightY = normStick(pad.rightStick.y);+ out.l2 = normTrigger(pad.l2);+ out.r2 = normTrigger(pad.r2);++ std::copy(pad.angularVelocity, pad.angularVelocity + 3, out.gyro);+ std::copy(pad.acceleration, pad.acceleration + 3, out.accel);+ out.hasAccel = true;++ // DualShock 4 touchpad: 0..1919 x 0..941+ if (pad.touchData.touchNum > 0) {+ out.touching = true;+ out.touchSecond = pad.touchData.touchNum > 1;+ out.touchX = std::clamp(pad.touchData.touch[0].x / 1919.0f, 0.0f, 1.0f);+ out.touchY = std::clamp(pad.touchData.touch[0].y / 941.0f, 0.0f, 1.0f);+ }+ return true;+}++void setMotors(int slot, uint8_t large, uint8_t small, uint32_t) {+ if (g_slots[slot].handle < 0) return;+ ScePadVibrationParam p{large, small};+ int rc = scePadSetVibration(g_slots[slot].handle, &p);+ if (!g_rumbleLogged || rc != 0) {+ XC_LOGI("scePadSetVibration(%u, %u): 0x%08x", p.largeMotor, p.smallMotor, rc);+ }+ g_rumbleLogged = true;+}++TriggerStyle triggerStyle(int) { return TriggerStyle::None; }+int setTriggerEffects(int, const TriggerCommand[2]) { return 0; }+void setTriggerMotors(int, uint8_t, uint8_t, uint32_t) {}++void setLight(int slot, uint8_t r, uint8_t g, uint8_t b) {+ if (g_slots[slot].handle < 0) return;+ ScePadColor c{r, g, b, 0};+ scePadSetLightBar(g_slots[slot].handle, &c);+}++void resetLight(int slot) {+ if (g_slots[slot].handle >= 0) {+ scePadResetLightBar(g_slots[slot].handle);+ }+}++} // namespace backend++std::string padUserName(int index) {+ return (index >= 0 && index < 4 && g_slots[index].handle >= 0) ? g_slots[index].name : "";+}++std::string padDeviceName(int) { return {}; }++int32_t padUserId(int index) {+ if (index >= 0 && index < 4 && g_slots[index].handle >= 0 && g_slots[index].userId >= 0) {+ return g_slots[index].userId;+ }+ int32_t uid = -1;+ if (sceUserServiceGetInitialUser(&uid) == 0 && uid >= 0) {+ return uid;+ }+ return -1;+}++PadCaps padCaps(int index) {+ if (!padConnected(index)) return {};+ return {PadKind::DualShock4, true, false, true, true, true, false};+}++PadCaps anyPadCaps() {+ return {PadKind::DualShock4, true, false, true, true, true, false};+}++bool init() {+ int rc = scePadInit();+ if (rc != 0 && rc != static_cast<int>(0x80920002)) {+ XC_LOGE("scePadInit failed: 0x%08x", static_cast<unsigned>(rc));+ return false;+ }+ int32_t uid = -1;+ rc = sceUserServiceGetInitialUser(&uid);+ if (rc != 0) {+ SceUserServiceInitializeParams param{0};+ sceUserServiceInitialize(¶m);+ rc = sceUserServiceGetInitialUser(&uid);+ }+ if (rc != 0 || uid < 0) {+ XC_LOGE("sceUserServiceGetInitialUser failed: 0x%08x", static_cast<unsigned>(rc));+ return false;+ }+ openPad(0, uid);+ refreshPads();+ return true;+}++void refreshPads() {+ SceUserServiceLoginUserIdList list{};+ if (sceUserServiceGetLoginUserIdList(&list) != 0) return;+ auto signedIn = [&](int32_t user) {+ for (int32_t u : list.userId)+ if (u == user) return true;+ return false;+ };+ for (int i = 1; i < 4; ++i) {+ if (g_slots[i].handle >= 0 && !signedIn(g_slots[i].userId)) closePad(i);+ }+ for (int32_t user : list.userId) {+ if (user <= 0) continue;+ bool known = false;+ for (const Slot& p : g_slots) known |= (p.userId == user);+ if (known) continue;+ for (int i = 1; i < 4; ++i) {+ if (g_slots[i].handle < 0) {+ openPad(i, user);+ break;+ }+ }+ }+}++void shutdown() {+ for (int i = 0; i < 4; ++i) closePad(i);+}++bool poll(ControllerState& out) {+ return pollPad(0, out);+}++void setEmbeddedMicActive(bool /*active*/, int /*pad*/) {}++} // namespace xc::inputdiff --git a/src/input/kbm_ps4.cpp b/src/input/kbm_ps4.cppnew file mode 100644index 0000000..bea8b7b--- /dev/null+++ b/src/input/kbm_ps4.cpp@@ -0,0 +1,199 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "input/input_ext.h"+#include "input/kbm.h"++#include "platform/platform.h"+#include "util/log.h"++#include <algorithm>+#include <cstddef>+#include <vector>++extern "C" {+int sceSysmoduleLoadModule(uint16_t id);+int sceKeyboardInit(void);+int sceKeyboardOpen(int32_t user, int32_t type, int32_t index, const void* param);+int sceKeyboardRead(int32_t handle, void* data, int32_t count);+int sceKeyboardClose(int32_t handle);+int sceMouseInit(void);+int sceMouseOpen(int32_t user, int32_t type, int32_t index, const void* param);+int sceMouseRead(int32_t handle, void* data, int32_t count);+int sceMouseClose(int32_t handle);+}++namespace xc::input {++namespace {++struct KeyboardState {+ uint64_t timestampUs;+ uint8_t intercepted;+ uint8_t reserved0[7];+ uint8_t connected;+ uint8_t reserved1[3];+ int32_t length; // keys[] in use+ uint32_t leds;+ uint32_t modifiers; // HID modifier bits+ uint16_t keys[16]; // HID usages held+ uint8_t reserved2[32];+};+static_assert(sizeof(KeyboardState) == 96);++struct MouseState {+ uint64_t timestamp;+ bool connected;+ uint32_t buttons;+ int32_t x, y, wheel, tilt;+ uint8_t reserved[8];+};+static_assert(sizeof(MouseState) == 40);++constexpr int kSlots = 2;+constexpr uint64_t kRescanMs = 3000;+constexpr uint16_t kSysmoduleKeyboard = 0x0106;+constexpr uint16_t kSysmoduleMouse = 0x00A9; // SCE_SYSMODULE_MOUSE on PS4++int32_t g_user = -1;+bool g_keyboardReady = false, g_mouseReady = false;+int g_keyboards[kSlots] = {-1, -1}, g_mice[kSlots] = {-1, -1};+uint64_t g_nextScanMs = 0;+std::vector<uint8_t> g_held;+std::vector<uint8_t> g_slotHeld[kSlots];+bool g_slotConnected[kSlots] = {};+uint8_t g_buttons = 0;+bool g_loggedKeyboard = false, g_loggedMouse = false;++void rescan(uint64_t now) {+ if (now < g_nextScanMs) return;+ g_nextScanMs = now + kRescanMs;+ const uint64_t param = 0;+ for (int i = 0; i < kSlots; ++i) {+ if (g_keyboardReady && g_keyboards[i] < 0) {+ int h = sceKeyboardOpen(g_user, 0, i, ¶m);+ if (h >= 0) {+ g_keyboards[i] = h;+ XC_LOGI("keyboard %d opened", i + 1);+ }+ }+ if (g_mouseReady && g_mice[i] < 0) {+ int h = sceMouseOpen(g_user, 0, i, ¶m);+ if (h >= 0) {+ g_mice[i] = h;+ XC_LOGI("mouse %d opened", i + 1);+ }+ }+ }+}++} // namespace++bool kbmInit(int32_t userId) {+ g_user = userId;+ int rc = sceSysmoduleLoadModule(kSysmoduleKeyboard);+ if (rc >= 0) rc = sceKeyboardInit();+ g_keyboardReady = (rc >= 0);+ XC_LOGI("keyboard library: 0x%08x", static_cast<unsigned>(rc));++ rc = sceSysmoduleLoadModule(kSysmoduleMouse);+ if (rc >= 0) rc = sceMouseInit();+ g_mouseReady = (rc >= 0);+ XC_LOGI("mouse library: 0x%08x", static_cast<unsigned>(rc));++ rescan(platform::nowMs());+ return g_keyboardReady || g_mouseReady;+}++KbmInput kbmPoll() {+ KbmInput out;+ if (!g_keyboardReady && !g_mouseReady) return out;+ rescan(platform::nowMs());++ std::vector<uint8_t> held;+ KeyboardState ks[16];+ for (int i = 0; i < kSlots; ++i) {+ if (g_keyboards[i] < 0) continue;+ int n = sceKeyboardRead(g_keyboards[i], ks, 16);+ if (n < 0) {+ sceKeyboardClose(g_keyboards[i]);+ g_keyboards[i] = -1;+ g_slotHeld[i].clear();+ g_slotConnected[i] = false;+ continue;+ }+ if (n > 0) {+ const KeyboardState& k = ks[std::min(n, 16) - 1];+ g_slotConnected[i] = (k.connected != 0);+ g_slotHeld[i].clear();+ if (k.connected && !k.intercepted) {+ for (int b = 0; b < 8; ++b) {+ if (k.modifiers & (1u << b)) g_slotHeld[i].push_back(modifierVk(b));+ }+ for (int j = 0; j < std::clamp(k.length, 0, 16); ++j) {+ if (uint8_t vk = hidToVk(k.keys[j])) g_slotHeld[i].push_back(vk);+ }+ }+ }+ if (g_slotConnected[i]) {+ out.keyboard = true;+ held.insert(held.end(), g_slotHeld[i].begin(), g_slotHeld[i].end());+ }+ }++ std::sort(held.begin(), held.end());+ held.erase(std::unique(held.begin(), held.end()), held.end());++ for (uint8_t vk : g_held) {+ if (!std::binary_search(held.begin(), held.end(), vk)) {+ out.keys.push_back({vk, false});+ }+ }+ for (uint8_t vk : held) {+ if (!std::binary_search(g_held.begin(), g_held.end(), vk)) {+ out.keys.push_back({vk, true});+ }+ }+ g_held = held;+ out.held = held;++ if (out.keyboard && !g_loggedKeyboard) {+ g_loggedKeyboard = true;+ XC_LOGI("keyboard in use");+ }++ // Mouse reading+ MouseState ms[32];+ bool mouseMoved = false;+ for (int i = 0; i < kSlots; ++i) {+ if (g_mice[i] < 0) continue;+ int n = sceMouseRead(g_mice[i], ms, 32);+ if (n < 0) {+ sceMouseClose(g_mice[i]);+ g_mice[i] = -1;+ continue;+ }+ for (int j = 0; j < std::min(n, 32); ++j) {+ if (!ms[j].connected) continue;+ out.mouse = true;+ out.dx += ms[j].x;+ out.dy += ms[j].y;+ out.wheel += ms[j].wheel;+ g_buttons = static_cast<uint8_t>(ms[j].buttons & 0x1F);+ mouseMoved = true;+ }+ }++ if (out.mouse && !g_loggedMouse) {+ g_loggedMouse = true;+ XC_LOGI("mouse in use");+ }++ out.buttons = g_buttons;+ out.moved = mouseMoved || (out.dx != 0) || (out.dy != 0) || (out.wheel != 0);++ return out;+}++void kbmSetCaptured(bool /*captured*/) {}++} // namespace xc::inputdiff --git a/src/media/audio_in_ps4.cpp b/src/media/audio_in_ps4.cppnew file mode 100644index 0000000..c80421b--- /dev/null+++ b/src/media/audio_in_ps4.cpp@@ -0,0 +1,146 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "media/audio_in.h"+#include "input/controller.h"+#include "media/audio_in_common.h"+#include "platform/platform.h"+#include "util/log.h"++#include <thread>+#include <vector>++extern "C" {+struct SceUserServiceInitializeParams {+ uint32_t priority;+};+int sceUserServiceInitialize(const SceUserServiceInitializeParams* param);+int sceUserServiceGetInitialUser(int* userId);+int sceAudioInInit(void);+int sceAudioInOpen(int userId, int type, int index, unsigned len, unsigned freq, unsigned param);+int sceAudioInInput(int handle, void* dest);+int sceAudioInClose(int handle);+int sceAudioInGetSilentState(int handle);+int sceAudioInSetGain(int handle, int gain);+}++namespace xc::media {++struct AudioIn::Impl {+ std::thread thread;+ int handle = -1;+ MicPipeline mic;+};++AudioIn::AudioIn() : impl_(std::make_unique<Impl>()) {}++AudioIn::~AudioIn() {+ close();+}++bool AudioIn::open(AudioCallback cb) {+ if (running_) return true;+ callback_ = std::move(cb);++ static bool initialised = false;+ if (!initialised) {+ int rc = sceAudioInInit();+ if (rc < 0 && rc != static_cast<int>(0x8026000C) && rc != static_cast<int>(0x8026000E)) {+ XC_LOGW("sceAudioInInit: 0x%08x", static_cast<unsigned>(rc));+ }+ initialised = true;+ }++ int userId = input::padUserId(0);+ if (userId < 0) {+ int rc = sceUserServiceGetInitialUser(&userId);+ if (rc < 0) {+ SceUserServiceInitializeParams param{0x2FF};+ sceUserServiceInitialize(¶m);+ rc = sceUserServiceGetInitialUser(&userId);+ }+ if (rc < 0) {+ XC_LOGW("audio in: no signed-in user, trying the system user");+ userId = 0xFF; // System user on PS4+ }+ }+ XC_LOGI("audio in: opening port for user 0x%08x (%d)...", static_cast<unsigned>(userId), userId);++ constexpr unsigned kGrain = MicPipeline::kGrain; // 256+ // type 0 = VoiceChat; freq = 48000; param = 0 (mono S16)+ impl_->handle = sceAudioInOpen(userId, 0, 0, kGrain, kSampleRate, 0);+ if (impl_->handle < 0) {+ XC_LOGW("sceAudioInOpen(user 0x%x, voice): 0x%08x, trying the personal port",+ static_cast<unsigned>(userId), static_cast<unsigned>(impl_->handle));+ // type 1 = Personal port+ impl_->handle = sceAudioInOpen(userId, 1, 0, kGrain, kSampleRate, 0);+ }+ if (impl_->handle < 0 && userId != 0xFF) {+ XC_LOGW("trying sceAudioInOpen with system user 0xFF...");+ impl_->handle = sceAudioInOpen(0xFF, 0, 0, kGrain, kSampleRate, 0);+ if (impl_->handle < 0) {+ impl_->handle = sceAudioInOpen(0xFF, 1, 0, kGrain, kSampleRate, 0);+ }+ }+ if (impl_->handle < 0) {+ XC_LOGE("sceAudioInOpen failed: 0x%08x", static_cast<unsigned>(impl_->handle));+ return false;+ }+ running_ = true;+ impl_->mic.reset();++ impl_->thread = std::thread([this]() {+ platform::setThreadAffinity(platform::ThreadRole::Audio, "ps4_audio_in");+ platform::setThreadRealtimePriority();+ std::vector<int16_t> grain(kGrain);+ unsigned lastStatus = 0xFFFFFFFF;+ uint64_t loopCount = 0;++ while (running_) {+ int rc = sceAudioInInput(impl_->handle, grain.data());+ if (rc < 0) {+ XC_LOGE("sceAudioInInput error: 0x%08x", static_cast<unsigned>(rc));+ break;+ }+ if (++loopCount == 1) {+ XC_LOGI("audio in: first input buffer received (%u samples)", kGrain);+ }++ int silentState = sceAudioInGetSilentState(impl_->handle);+ if (silentState != static_cast<int>(lastStatus)) {+ XC_LOGI("audio in: silent state changed to 0x%08x", static_cast<unsigned>(silentState));+ lastStatus = static_cast<unsigned>(silentState);+ }+ if (silentState >= 0) {+ // ORBIS_AUDIO_IN_SILENT_STATE_USER_SETTING (0x4) or DEVICE_NONE (0x1)+ bool hwMuted = (silentState & 0x00000004) != 0 || (silentState & 0x00000001) != 0;+ hardwareMuted_.store(hwMuted, std::memory_order_relaxed);+ }++ bool isMuted = muted_.load(std::memory_order_relaxed) || hardwareMuted_.load(std::memory_order_relaxed);+ impl_->mic.process(grain.data(), grain.size(), isMuted, gain_.load(std::memory_order_relaxed), level_, callback_);+ }+ });++ XC_LOGI("audio in: PS4 microphone open (handle %d, 48 kHz mono S16)", impl_->handle);+ return true;+}++void AudioIn::close() {+ if (!running_) return;+ running_ = false;+ level_.store(0.0f, std::memory_order_relaxed);+ hardwareMuted_.store(false, std::memory_order_relaxed);++ if (impl_->thread.joinable()) {+ impl_->thread.join();+ }++ if (impl_->handle >= 0) {+ sceAudioInClose(impl_->handle);+ impl_->handle = -1;+ }+ callback_ = nullptr;+ XC_LOGI("audio in: closed");+}++} // namespace xc::mediadiff --git a/src/media/audio_out_ps4.cpp b/src/media/audio_out_ps4.cppnew file mode 100644index 0000000..c822120--- /dev/null+++ b/src/media/audio_out_ps4.cpp@@ -0,0 +1,118 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "media/audio_out.h"+#include "media/audio_queue.h"+#include "platform/platform.h"+#include "util/log.h"++#include <algorithm>+#include <atomic>+#include <chrono>+#include <mutex>+#include <thread>+#include <vector>++extern "C" {+int sceAudioOutInit(void);+int sceAudioOutOpen(int userId, int type, int index, unsigned len, unsigned freq, unsigned param);+int sceAudioOutOutput(int handle, const void* ptr);+int sceAudioOutClose(int handle);+int sceAudioOutSetMixLevelPadSpk(int handle, int mixLevel);+int sceAudioOutSetPadSpkVolume(int handle, int volume);+}++namespace xc::media {++namespace {++constexpr int kRate = AudioQueue::kRate;+constexpr unsigned kGrain = 256;++std::atomic<bool> g_running{false};+std::thread g_thread;+int g_handle = -1;+std::atomic<int> g_padSpeakerVolume{100};++void loop() {+ platform::setThreadAffinity(platform::ThreadRole::Audio, "ps4_audio_out");+ platform::setThreadRealtimePriority();+ std::vector<float> grain(kGrain * 2);+ AudioQueue& queue = audioQueue();+ while (g_running) {+ queue.pull(grain.data(), kGrain);+ int h = g_handle;+ if (h < 0) {+ std::this_thread::sleep_for(std::chrono::milliseconds(5));+ continue;+ }++ // Float 32-bit interleaved stereo output (format 4)+ int rc = sceAudioOutOutput(h, grain.data());+ if (rc < 0) {+ static uint64_t failures = 0;+ if (failures++ % 200 == 0) {+ XC_LOGW("sceAudioOutOutput: 0x%08x (failure %llu)", static_cast<unsigned>(rc),+ static_cast<unsigned long long>(failures));+ }+ std::this_thread::sleep_for(std::chrono::milliseconds(5));+ if (!g_running) break;+ }+ }+}++} // namespace++void setPadSpeakerVolume(int percent) {+ g_padSpeakerVolume = std::clamp(percent, 0, 100);+}++int padSpeakerVolume() {+ return g_padSpeakerVolume.load();+}++bool audioStart() {+ if (g_running) return true;+ static bool initialised = false;+ if (!initialised) {+ int rc = sceAudioOutInit();+ if (rc < 0 && rc != static_cast<int>(0x8026000C) && rc != static_cast<int>(0x8026000E)) {+ XC_LOGE("sceAudioOutInit: 0x%08x", static_cast<unsigned>(rc));+ return false;+ }+ initialised = true;+ }++ // Type 0 = Main port, format 4 = Float stereo (SCE_AUDIO_OUT_PARAM_FORMAT_FLOAT_STEREO)+ g_handle = sceAudioOutOpen(0xFF, 0, 0, kGrain, kRate, 4);+ if (g_handle < 0) {+ XC_LOGE("sceAudioOutOpen: 0x%08x", static_cast<unsigned>(g_handle));+ return false;+ }+ g_running = true;+ audioQueue().open();+ g_thread = std::thread(loop);+ XC_LOGI("audio output open (PS4 48 kHz float stereo, handle %d)", g_handle);+ return true;+}++void audioStop() {+ if (!g_running) return;+ g_running = false;+ audioQueue().close();+ if (g_thread.joinable()) g_thread.join();+ if (g_handle >= 0) {+ sceAudioOutClose(g_handle);+ g_handle = -1;+ }+ audioQueue().clear();+}++bool playPadSpeakerAudio(const float*, size_t) {+ return false;+}++bool hasPadSpeaker() {+ return false;+}++} // namespace xc::mediadiff --git a/src/media/hw_decoder_ps4.cpp b/src/media/hw_decoder_ps4.cppnew file mode 100644index 0000000..e29eb51--- /dev/null+++ b/src/media/hw_decoder_ps4.cpp@@ -0,0 +1,364 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "media/hw_decoder.h"+#include "util/log.h"++#include <algorithm>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <fcntl.h>+#include <unistd.h>+#include <dlfcn.h>++extern "C" {+int sceSysmoduleLoadModule(uint32_t id);+int sceSysmoduleLoadModuleInternal(uint32_t id);+int sceKernelLoadStartModule(const char* path, size_t argc, const void* argv, uint32_t flags, void* opt, int* res);+size_t sceKernelGetDirectMemorySize();+int sceKernelAllocateDirectMemory(int64_t searchStart, int64_t searchEnd, size_t length, size_t alignment,+ int memoryType, int64_t* physicalAddress);+int sceKernelMapDirectMemory(void** address, size_t length, int protection, int flags, int64_t physicalAddress,+ size_t alignment);+int sceKernelMapNamedFlexibleMemory(void** address, size_t length, int protection, int flags, const char* name);++// PS4 libSceVideodec2 structures+struct Vdec2DecoderConfig {+ uint64_t size;+ uint32_t resourceType, codecType, profile, maxLevel;+ int32_t maxWidth, maxHeight, maxDpbFrames;+ uint32_t pipelineDepth;+ uint64_t computeQueue, cpuAffinity;+ int32_t cpuPriority;+ uint32_t optimizeProgressive, checkMemoryType, reserved;+};++struct Vdec2DecoderMemory {+ uint64_t size, cpuSize;+ void* cpu;+ uint64_t gpuSize;+ void* gpu;+ uint64_t cpuGpuSize;+ void* cpuGpu;+ uint64_t maxFrameSize;+ uint32_t frameAlignment, reserved;+};++struct Vdec2ComputeConfig {+ uint64_t size;+ uint16_t pipeId, queueId;+ uint8_t checkMemoryType, reserved0;+ uint16_t reserved1;+};++struct Vdec2ComputeMemory {+ uint64_t size, cpuGpuSize;+ void* cpuGpu;+};++struct Vdec2Input {+ uint64_t size;+ void* au;+ uint64_t auSize, pts, dts, attached;+};++struct Vdec2Frame {+ uint64_t size;+ void* buffer;+ uint64_t bufferSize;+ uint32_t accepted, reserved;+};++struct Vdec2Output {+ uint64_t size;+ uint8_t valid, error, pictureCount, padding;+ uint32_t codec, width, pitch, height, reserved;+ void* buffer;+ uint64_t bufferSize;+ uint32_t frameFormat, pitchBytes;+};++using FnQueryComputeMem = int (*)(Vdec2ComputeMemory*);+using FnAllocComputeQueue = int (*)(const Vdec2ComputeConfig*, const Vdec2ComputeMemory*, void**);+using FnReleaseComputeQueue = int (*)(void*);+using FnQueryDecoderMem = int (*)(const Vdec2DecoderConfig*, Vdec2DecoderMemory*);+using FnCreateDecoder = int (*)(const Vdec2DecoderConfig*, const Vdec2DecoderMemory*, void**);+using FnDeleteDecoder = int (*)(void*);+using FnDecode = int (*)(void*, Vdec2Input*, Vdec2Frame*, Vdec2Output*);+using FnFlush = int (*)(void*, Vdec2Frame*, Vdec2Output*);++struct Videodec2Api {+ FnQueryComputeMem queryComputeMem = nullptr;+ FnAllocComputeQueue allocComputeQueue = nullptr;+ FnReleaseComputeQueue releaseComputeQueue = nullptr;+ FnQueryDecoderMem queryDecoderMem = nullptr;+ FnCreateDecoder createDecoder = nullptr;+ FnDeleteDecoder deleteDecoder = nullptr;+ FnDecode decode = nullptr;+ FnFlush flush = nullptr;+ bool loaded = false;+};+static Videodec2Api g_vdec;+}++namespace xc::media {++namespace {++constexpr uint32_t kVideodecModule = 0x00CF; // SCE_SYSMODULE_VIDEODEC2+constexpr int kMemoryTypeOnion = 0; // Coherent CPU+GPU+constexpr int kMemoryTypeGarlic = 3; // GPU Direct Memory+constexpr int kProtectionRw = 0x33;+constexpr const char* kProbeFile = "/data/psbox/hwdec.probe";++inline size_t align16k(size_t n) {+ return (n + 0x3FFF) & ~static_cast<size_t>(0x3FFF);+}++void* allocDirect(size_t size, int memoryType, const char* label) {+ if (size == 0) return nullptr;+ size = align16k(size);+ int64_t phys = 0;+ int rc = sceKernelAllocateDirectMemory(0, static_cast<int64_t>(sceKernelGetDirectMemorySize()),+ size, 0x4000, memoryType, &phys);+ if (rc != 0) {+ XC_LOGW("hwdec: %s: allocate %zu bytes failed: 0x%08x", label, size, static_cast<unsigned>(rc));+ return nullptr;+ }+ void* addr = nullptr;+ rc = sceKernelMapDirectMemory(&addr, size, kProtectionRw, 0, phys, 0x4000);+ if (rc != 0 || !addr) {+ XC_LOGW("hwdec: %s: map %zu bytes failed: 0x%08x", label, size, static_cast<unsigned>(rc));+ return nullptr;+ }+ return addr;+}++void writeProbe(const char* state) {+ int fd = ::open(kProbeFile, O_WRONLY | O_CREAT | O_TRUNC, 0666);+ if (fd >= 0) {+ (void)::write(fd, state, std::strlen(state));+ ::close(fd);+ }+}++void removeProbe() {+ ::unlink(kProbeFile);+}++bool hasProbe() {+ return ::access(kProbeFile, F_OK) == 0;+}++} // namespace++HwDecoder::~HwDecoder() {+ if (decoder_) {+ Vdec2Frame frm{};+ frm.size = sizeof(frm);+ Vdec2Output out{};+ out.size = sizeof(out);+ if (g_vdec.flush) g_vdec.flush(decoder_, &frm, &out);+ if (g_vdec.deleteDecoder) g_vdec.deleteDecoder(decoder_);+ decoder_ = nullptr;+ }+ if (computeQueue_) {+ if (g_vdec.releaseComputeQueue) g_vdec.releaseComputeQueue(computeQueue_);+ computeQueue_ = nullptr;+ }+ frameBuffer_ = nullptr;+ frameBufferSize_ = 0;+}++bool HwDecoder::init(int maxWidth, int maxHeight) {+ if (hasProbe()) {+ XC_LOGW("hwdec: previous crash probe file found (%s); disabling hardware decoding", kProbeFile);+ return false;+ }++ writeProbe("starting");++ int rc = sceSysmoduleLoadModule(kVideodecModule);+ XC_LOGI("hwdec: sceSysmoduleLoadModule(VIDEODEC2) -> 0x%08x", static_cast<unsigned>(rc));+ if (rc < 0 && rc != static_cast<int>(0x80020002) && rc != static_cast<int>(0x8002000e)) {+ removeProbe();+ return false;+ }++ if (!g_vdec.loaded) {+ g_vdec.queryComputeMem = reinterpret_cast<FnQueryComputeMem>(dlsym(RTLD_DEFAULT, "sceVideodec2QueryComputeMemoryInfo"));+ g_vdec.allocComputeQueue = reinterpret_cast<FnAllocComputeQueue>(dlsym(RTLD_DEFAULT, "sceVideodec2AllocateComputeQueue"));+ g_vdec.releaseComputeQueue = reinterpret_cast<FnReleaseComputeQueue>(dlsym(RTLD_DEFAULT, "sceVideodec2ReleaseComputeQueue"));+ g_vdec.queryDecoderMem = reinterpret_cast<FnQueryDecoderMem>(dlsym(RTLD_DEFAULT, "sceVideodec2QueryDecoderMemoryInfo"));+ g_vdec.createDecoder = reinterpret_cast<FnCreateDecoder>(dlsym(RTLD_DEFAULT, "sceVideodec2CreateDecoder"));+ g_vdec.deleteDecoder = reinterpret_cast<FnDeleteDecoder>(dlsym(RTLD_DEFAULT, "sceVideodec2DeleteDecoder"));+ g_vdec.decode = reinterpret_cast<FnDecode>(dlsym(RTLD_DEFAULT, "sceVideodec2Decode"));+ g_vdec.flush = reinterpret_cast<FnFlush>(dlsym(RTLD_DEFAULT, "sceVideodec2Flush"));+ if (!g_vdec.queryComputeMem || !g_vdec.allocComputeQueue || !g_vdec.createDecoder || !g_vdec.decode) {+ XC_LOGW("hwdec: could not resolve all libSceVideodec2 symbols via dlsym; falling back to software decoding");+ removeProbe();+ return false;+ }+ g_vdec.loaded = true;+ }++ // Load firmware helper modules (available on retail PS4 firmware)+ for (const char* sprx : {+ "/system/common/lib/libSceVdecCore.sprx",+ "/system/common/lib/libSceVdecSavc.sprx",+ "/system/common/lib/libSceVdecSavc2.sprx",+ "/system/common/lib/libSceVdecwrap.sprx"+ }) {+ int res = 0;+ int mrc = sceKernelLoadStartModule(sprx, 0, nullptr, 0, nullptr, &res);+ XC_LOGI("hwdec: load %s -> 0x%08x", sprx, static_cast<unsigned>(mrc));+ }+ sceSysmoduleLoadModuleInternal(0x80000015);++ // Query and allocate compute queue memory+ Vdec2ComputeMemory computeMem{};+ computeMem.size = sizeof(computeMem);+ rc = g_vdec.queryComputeMem(&computeMem);+ XC_LOGI("hwdec: compute memory query: rc=0x%08x, %llu bytes", static_cast<unsigned>(rc),+ static_cast<unsigned long long>(computeMem.cpuGpuSize));+ if (rc != 0 || computeMem.cpuGpuSize == 0) {+ removeProbe();+ return false;+ }++ size_t computeBytes = align16k(computeMem.cpuGpuSize);+ void* computeBuf = allocDirect(computeBytes, kMemoryTypeOnion, "compute queue");+ if (!computeBuf) {+ removeProbe();+ return false;+ }+ computeMem.cpuGpu = computeBuf;++ // Allocate compute queue across pipes 0..4+ void* queue = nullptr;+ for (uint16_t pipe = 0; pipe < 5; ++pipe) {+ Vdec2ComputeConfig compCfg{};+ compCfg.size = sizeof(compCfg);+ compCfg.pipeId = pipe;+ compCfg.queueId = 0;+ compCfg.checkMemoryType = 1;++ writeProbe("compute queue");+ rc = g_vdec.allocComputeQueue(&compCfg, &computeMem, &queue);+ removeProbe();++ XC_LOGI("hwdec: compute queue pipe %u queue 0: rc=0x%08x, queue=%p", pipe, static_cast<unsigned>(rc), queue);+ if (rc == 0 && queue) break;+ }+ if (!queue) {+ XC_LOGW("hwdec: failed to allocate compute queue on all pipes");+ removeProbe();+ return false;+ }+ computeQueue_ = queue;++ // Query decoder memory requirements+ Vdec2DecoderConfig decCfg{};+ decCfg.size = sizeof(decCfg);+ decCfg.resourceType = 0; // standard+ decCfg.codecType = 0; // H.264+ decCfg.profile = 2; // High profile+ decCfg.maxLevel = 42; // Level 4.2+ decCfg.maxWidth = maxWidth;+ decCfg.maxHeight = maxHeight;+ decCfg.maxDpbFrames = 4;+ decCfg.pipelineDepth = 2;+ decCfg.computeQueue = reinterpret_cast<uint64_t>(computeQueue_);++ Vdec2DecoderMemory decMem{};+ decMem.size = sizeof(decMem);+ rc = g_vdec.queryDecoderMem(&decCfg, &decMem);+ if (rc != 0) {+ XC_LOGW("hwdec: sceVideodec2QueryDecoderMemoryInfo failed: 0x%08x", static_cast<unsigned>(rc));+ removeProbe();+ return false;+ }++ if (decMem.cpuSize > 0) {+ size_t cpuBytes = align16k(decMem.cpuSize);+ void* cpuMem = nullptr;+ rc = sceKernelMapNamedFlexibleMemory(&cpuMem, cpuBytes, kProtectionRw, 0, "PSBoxVdecCpu");+ if (rc != 0 || !cpuMem) {+ XC_LOGW("hwdec: allocate flexible memory %zu failed: 0x%08x", cpuBytes, static_cast<unsigned>(rc));+ removeProbe();+ return false;+ }+ decMem.cpu = cpuMem;+ decMem.cpuSize = cpuBytes;+ }++ if (decMem.gpuSize > 0) {+ decMem.gpu = allocDirect(decMem.gpuSize, kMemoryTypeGarlic, "decoder gpu");+ if (!decMem.gpu) { removeProbe(); return false; }+ }++ if (decMem.cpuGpuSize > 0) {+ decMem.cpuGpu = allocDirect(decMem.cpuGpuSize, kMemoryTypeOnion, "decoder cpu+gpu");+ if (!decMem.cpuGpu) { removeProbe(); return false; }+ }++ frameBufferSize_ = align16k(decMem.maxFrameSize > 0 ? decMem.maxFrameSize : (static_cast<size_t>(maxWidth) * maxHeight * 3 / 2 + 64));+ frameBuffer_ = static_cast<uint8_t*>(allocDirect(frameBufferSize_, kMemoryTypeGarlic, "frame buffer"));+ if (!frameBuffer_) {+ removeProbe();+ return false;+ }++ writeProbe("create decoder");+ rc = g_vdec.createDecoder(&decCfg, &decMem, &decoder_);+ removeProbe();++ XC_LOGI("hwdec: sceVideodec2CreateDecoder -> 0x%08x", static_cast<unsigned>(rc));+ if (rc != 0 || !decoder_) {+ decoder_ = nullptr;+ return false;+ }++ XC_LOGI("hwdec: PS4 decoder running, frame buffer %zu bytes", frameBufferSize_);+ return true;+}++bool HwDecoder::decode(const uint8_t* data, size_t len, uint64_t pts, Picture& out) {+ if (!decoder_ || !data || len == 0 || !frameBuffer_) return false;++ Vdec2Input input{};+ input.size = sizeof(input);+ input.au = const_cast<uint8_t*>(data);+ input.auSize = len;+ input.pts = pts;++ Vdec2Frame frame{};+ frame.size = sizeof(frame);+ frame.buffer = frameBuffer_;+ frame.bufferSize = frameBufferSize_;++ Vdec2Output output{};+ output.size = sizeof(output);++ int rc = g_vdec.decode ? g_vdec.decode(decoder_, &input, &frame, &output) : -1;+ if (rc != 0) {+ return false;+ }++ if (output.valid && output.pictureCount > 0) {+ out.data = static_cast<const uint8_t*>(output.buffer ? output.buffer : frameBuffer_);+ out.size = output.bufferSize ? output.bufferSize : frameBufferSize_;+ out.width = output.width;+ out.height = output.height;+ out.pitch = output.pitch;+ out.pitchBytes = output.pitchBytes ? output.pitchBytes : (output.width);+ out.format = output.frameFormat;+ out.pts = pts;+ out.error = (output.error != 0);+ return true;+ }++ return false;+}++} // namespace xc::mediadiff --git a/src/platform/ps4/condition_variable_ps4.cpp b/src/platform/ps4/condition_variable_ps4.cppnew file mode 100644index 0000000..b747878--- /dev/null+++ b/src/platform/ps4/condition_variable_ps4.cpp@@ -0,0 +1,89 @@+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception+// Portions derived from LLVM libc++ condition_variable.cpp+// Adjusted for PS4 / OpenOrbis ABI where FreeBSD kernel returns ETIMEDOUT=60+// while toolchain libc++ was compiled expecting Linux ETIMEDOUT=110.++#ifdef __ORBIS__++#include <__config>++#ifndef _LIBCPP_HAS_NO_THREADS++#include <condition_variable>+#include <thread>+#include <system_error>+#include <cerrno>++_LIBCPP_BEGIN_NAMESPACE_STD++void+condition_variable::notify_one() _NOEXCEPT+{+ __libcpp_condvar_signal(&__cv_);+}++void+condition_variable::notify_all() _NOEXCEPT+{+ __libcpp_condvar_broadcast(&__cv_);+}++void+condition_variable::wait(unique_lock<mutex>& lk) _NOEXCEPT+{+ if (!lk.owns_lock())+ __throw_system_error(EPERM,+ "condition_variable::wait: mutex not locked");+ int ec = __libcpp_condvar_wait(&__cv_, lk.mutex()->native_handle());+ if (ec)+ __throw_system_error(ec, "condition_variable wait failed");+}++void+condition_variable::__do_timed_wait(unique_lock<mutex>& lk,+ chrono::time_point<chrono::system_clock, chrono::nanoseconds> tp) _NOEXCEPT+{+ using namespace chrono;+ if (!lk.owns_lock())+ __throw_system_error(EPERM,+ "condition_variable::timed wait: mutex not locked");+ nanoseconds d = tp.time_since_epoch();+ if (d > nanoseconds(0x59682F000000E941))+ d = nanoseconds(0x59682F000000E941);+ __libcpp_timespec_t ts;+ seconds s = duration_cast<seconds>(d);+ typedef decltype(ts.tv_sec) ts_sec;+ _LIBCPP_CONSTEXPR ts_sec ts_sec_max = numeric_limits<ts_sec>::max();+ if (s.count() < ts_sec_max)+ {+ ts.tv_sec = static_cast<ts_sec>(s.count());+ ts.tv_nsec = static_cast<decltype(ts.tv_nsec)>((d - s).count());+ }+ else+ {+ ts.tv_sec = ts_sec_max;+ ts.tv_nsec = giga::num - 1;+ }+ int ec = __libcpp_condvar_timedwait(&__cv_, lk.mutex()->native_handle(), &ts);+ // On FreeBSD / PS4 Orbis kernel, ETIMEDOUT is 60.+ // In OpenOrbis musl, ETIMEDOUT may be 9938.+ // In Linux toolchain libc++, ETIMEDOUT is 110.+ // Accept all of them as timeout, not an exception.+ if (ec != 0 && ec != ETIMEDOUT && ec != 60 && ec != 110 && ec != 9938)+ __throw_system_error(ec, "condition_variable timed_wait failed");+}++void+notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk)+{+ auto& tl_ptr = __thread_local_data();+ if (tl_ptr.get() == nullptr) {+ tl_ptr.set_pointer(new __thread_struct);+ }+ __thread_local_data()->notify_all_at_thread_exit(&cond, lk.release());+}++_LIBCPP_END_NAMESPACE_STD++#endif // !_LIBCPP_HAS_NO_THREADS+#endif // __ORBIS__diff --git a/src/platform/ps4/keyboard_ps4.cpp b/src/platform/ps4/keyboard_ps4.cppnew file mode 100644index 0000000..a12d200--- /dev/null+++ b/src/platform/ps4/keyboard_ps4.cpp@@ -0,0 +1,172 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "platform/platform.h"+#include "util/log.h"++#include <cstdint>+#include <cstring>+#include <string>+#include <vector>++extern "C" {+int sceCommonDialogInitialize(void);+int sceImeDialogInit(const void* param, void* extended);+int sceImeDialogGetStatus(void);+int sceImeDialogGetResult(void* result);+int sceImeDialogTerm(void);+int sceUserServiceGetInitialUser(int32_t* userId);+}++namespace xc::platform {++namespace {++struct ImeDialogParam {+ int32_t userId;+ int32_t type; // 0 default, 2 URL, 3 e-mail, 4 number+ uint64_t supportedLanguages;+ int32_t enterLabel;+ int32_t inputMethod;+ void* filter;+ uint32_t option;+ uint32_t maxTextLength;+ char16_t* inputTextBuffer;+ float posx, posy;+ int32_t horizontalAlignment, verticalAlignment;+ const char16_t* placeholder;+ const char16_t* title;+ int8_t reserved[16];+};+static_assert(sizeof(ImeDialogParam) == 96);++struct DialogResult {+ int32_t endStatus; // 0 ok, 1 cancel, 2 abort+ int8_t reserved[60];+};++int g_available = -1;+bool g_open = false;+std::u16string g_title;+std::vector<char16_t> g_buffer;++void utf8ToUtf16(const std::string& in, std::u16string& out) {+ out.clear();+ for (size_t i = 0; i < in.size();) {+ uint32_t cp = 0;+ unsigned char c = in[i];+ if (c < 0x80) { cp = c; i += 1; }+ else if ((c & 0xE0) == 0xC0 && i + 1 < in.size()) {+ cp = ((c & 0x1F) << 6) | (in[i + 1] & 0x3F);+ i += 2;+ } else if ((c & 0xF0) == 0xE0 && i + 2 < in.size()) {+ cp = ((c & 0x0F) << 12) | ((in[i + 1] & 0x3F) << 6) | (in[i + 2] & 0x3F);+ i += 3;+ } else if ((c & 0xF8) == 0xF0 && i + 3 < in.size()) {+ cp = ((c & 0x07) << 18) | ((in[i + 1] & 0x3F) << 12) | ((in[i + 2] & 0x3F) << 6) | (in[i + 3] & 0x3F);+ i += 4;+ } else {+ i += 1;+ continue;+ }+ if (cp <= 0xFFFF) {+ out.push_back(static_cast<char16_t>(cp));+ } else {+ cp -= 0x10000;+ out.push_back(static_cast<char16_t>(0xD800 + (cp >> 10)));+ out.push_back(static_cast<char16_t>(0xDC00 + (cp & 0x3FF)));+ }+ }+}++void utf16ToUtf8(const char16_t* in, std::string& out) {+ out.clear();+ if (!in) return;+ for (size_t i = 0; in[i]; ++i) {+ uint32_t cp = in[i];+ if (cp >= 0xD800 && cp <= 0xDBFF && in[i + 1] >= 0xDC00 && in[i + 1] <= 0xDFFF) {+ cp = 0x10000 + (((cp - 0xD800) << 10) | (in[i + 1] - 0xDC00));+ ++i;+ }+ if (cp < 0x80) {+ out.push_back(static_cast<char>(cp));+ } else if (cp < 0x800) {+ out.push_back(static_cast<char>(0xC0 | (cp >> 6)));+ out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));+ } else if (cp < 0x10000) {+ out.push_back(static_cast<char>(0xE0 | (cp >> 12)));+ out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));+ out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));+ } else {+ out.push_back(static_cast<char>(0xF0 | (cp >> 18)));+ out.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));+ out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));+ out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));+ }+ }+}++} // namespace++bool systemKeyboardAvailable() {+ if (g_available >= 0) return g_available == 1;+ int rc = sceCommonDialogInitialize();+ g_available = (rc >= 0 || rc == static_cast<int>(0x80610005)) ? 1 : 0;+ return g_available == 1;+}++bool openSystemKeyboard(const std::string& title, const std::string& text, size_t maxLength, KeyboardKind kind) {+ if (!systemKeyboardAvailable() || g_open) return false;+ int32_t user = -1;+ sceUserServiceGetInitialUser(&user);+ if (user < 0) return false;++ if (maxLength == 0 || maxLength > 2048) maxLength = 2048;+ utf8ToUtf16(title, g_title);+ std::u16string initial16;+ utf8ToUtf16(text, initial16);+ if (initial16.size() > maxLength) initial16.resize(maxLength);++ g_buffer.assign(maxLength + 1, 0);+ std::memcpy(g_buffer.data(), initial16.data(), initial16.size() * sizeof(char16_t));++ ImeDialogParam p{};+ p.userId = user;+ p.supportedLanguages = 0;+ switch (kind) {+ case KeyboardKind::Text: p.type = 0; break;+ case KeyboardKind::Password: p.type = 0; p.option = 0x4; break;+ case KeyboardKind::Number: p.type = 4; break;+ case KeyboardKind::Email: p.type = 3; break;+ case KeyboardKind::Url: p.type = 2; break;+ }+ p.maxTextLength = static_cast<uint32_t>(maxLength);+ p.inputTextBuffer = g_buffer.data();+ p.posx = 1920 / 2.0f;+ p.posy = 1080 / 2.0f;+ p.horizontalAlignment = 1;+ p.verticalAlignment = 1;+ p.title = g_title.c_str();++ int rc = sceImeDialogInit(&p, nullptr);+ if (rc != 0) {+ XC_LOGW("sceImeDialogInit: 0x%08x", static_cast<unsigned>(rc));+ return false;+ }+ g_open = true;+ return true;+}++KeyboardStatus pollSystemKeyboard(std::string& text) {+ if (!g_open) return KeyboardStatus::Closed;+ int status = sceImeDialogGetStatus();+ if (status == 1) return KeyboardStatus::Open; // running+ DialogResult res{};+ int rc = sceImeDialogGetResult(&res);+ sceImeDialogTerm();+ g_open = false;+ if (status != 2 || rc != 0 || res.endStatus != 0) return KeyboardStatus::Cancelled;+ utf16ToUtf8(g_buffer.data(), text);+ return KeyboardStatus::Accepted;+}++} // namespace xc::platformdiff --git a/src/platform/ps4/platform_ps4.cpp b/src/platform/ps4/platform_ps4.cppnew file mode 100644index 0000000..b9883c2--- /dev/null+++ b/src/platform/ps4/platform_ps4.cpp@@ -0,0 +1,901 @@+// SPDX-License-Identifier: GPL-3.0-or-later+// Copyright (C) 2026 RafaelNGP+#include "platform/platform.h"+#include "platform/toasts.h"+#include "util/log.h"++#include <cerrno>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <sys/stat.h>+#include <sys/types.h>+#include <unistd.h>+#include <fcntl.h>++#include <arpa/inet.h>+#include <atomic>+#include <ifaddrs.h>+#include <net/if.h>+#include <netinet/in.h>+#include <netdb.h>+#include <poll.h>+#include <pthread.h>+#include <pthread_np.h>+#include <cstdarg>+#include <mutex>+#include <unordered_map>+#include <sys/ioctl.h>+#include <sys/select.h>+#include <sys/socket.h>++extern "C" {+int sceNetIoctl(int s, unsigned long cmd, void* data);+int sceNetSocket(const char* name, int domain, int type, int protocol);+int sceNetBind(int s, const void* addr, unsigned int addrlen);+int sceNetGetsockname(int s, void* addr, unsigned int* addrlen);+int sceNetSendto(int s, const void* msg, size_t len, int flags, const void* to, unsigned int tolen);+int sceNetRecvfrom(int s, void* buf, size_t len, int flags, void* from, unsigned int* fromlen);+int sceNetSend(int s, const void* msg, size_t len, int flags);+int sceNetRecv(int s, void* buf, size_t len, int flags);+int sceNetConnect(int s, const void* addr, unsigned int addrlen);+int sceNetListen(int s, int backlog);+int sceNetAccept(int s, void* addr, unsigned int* addrlen);+int sceNetSetsockopt(int s, int level, int optname, const void* optval, unsigned int optlen);+int sceNetGetsockopt(int s, int level, int optname, void* optval, unsigned int* optlen);+int sceNetSocketClose(int s);+int* sceNetErrnoLoc(void);+int _ioctl(int fd, unsigned long request, void* arg);+int _close(int fd);++int ioctl(int fd, unsigned long request, ...) {+ void* arg = nullptr;+ va_list ap;+ va_start(ap, request);+ arg = va_arg(ap, void*);+ va_end(ap);++ // On PS4/shadPS4, socket ioctls like FIONBIO/FIONREAD must be routed to sceNetIoctl.+ int rc = sceNetIoctl(fd, request, arg);+ if (rc >= 0) {+ return rc;+ }+ return _ioctl(fd, request, arg);+}++static std::mutex s_sockMutex;+static std::unordered_map<int, uint16_t> s_boundPorts;+static std::atomic<uint16_t> s_nextEphemeralPort{50100};++int socket(int domain, int type, int protocol) {+ if (protocol == 17) {+ protocol = 0;+ }+ int baseType = type & 0xF;+ int s = sceNetSocket("", domain, baseType, protocol);+ if (s < 0) {+ errno = (sceNetErrnoLoc && *sceNetErrnoLoc() > 0) ? *sceNetErrnoLoc() : -s;+ return -1;+ }+ if (type & 0x4000) { // SOCK_NONBLOCK+ int nbio = 1;+ sceNetIoctl(s, 0x8004667e, &nbio); // FIONBIO+ }+ return s;+}++int bind(int fd, const struct sockaddr* addr, socklen_t len) {+ if (!addr || len < sizeof(struct sockaddr_in)) {+ int rc = sceNetBind(fd, addr, len);+ if (rc < 0) { errno = *sceNetErrnoLoc(); return -1; }+ return rc;+ }+ const auto* raw = reinterpret_cast<const uint8_t*>(addr);+ uint16_t port = 0;+ std::memcpy(&port, raw + 2, sizeof(port));+ port = ntohs(port);++ struct sockaddr_in boundAddr{};+ std::memcpy(&boundAddr, addr, std::min<size_t>(len, sizeof(boundAddr)));+ if (boundAddr.sin_len == 0) boundAddr.sin_len = sizeof(boundAddr);+ if (boundAddr.sin_family == 0 && raw[0] == AF_INET) boundAddr.sin_family = AF_INET;++ // Port 0 lets the stack pick a free ephemeral port. Forcing a fixed high+ // range (old 50100+) collides with ports the PS4 network stack reserves.+ int rc = sceNetBind(fd, &boundAddr, sizeof(boundAddr));+ if (rc < 0) {+ errno = *sceNetErrnoLoc();+ return -1;+ }+ if (port != 0) {+ std::lock_guard<std::mutex> lock(s_sockMutex);+ s_boundPorts[fd] = port;+ }+ return 0;+}++int getsockname(int fd, struct sockaddr* addr, socklen_t* len) {+ if (!addr || !len || *len < sizeof(struct sockaddr_in)) return -1;+ {+ unsigned int nlen = static_cast<unsigned int>(*len);+ if (sceNetGetsockname(fd, addr, &nlen) == 0) {+ auto* sin = reinterpret_cast<struct sockaddr_in*>(addr);+ if (sin->sin_family == AF_INET || sin->sin_family == AF_INET6 ||+ reinterpret_cast<const uint8_t*>(addr)[0] == AF_INET) {+ if (sin->sin_len == 0) sin->sin_len = sizeof(struct sockaddr_in);+ if (sin->sin_family == 0) sin->sin_family = AF_INET;+ if (sin->sin_port == 0) {+ std::lock_guard<std::mutex> lock(s_sockMutex);+ auto it = s_boundPorts.find(fd);+ if (it != s_boundPorts.end()) sin->sin_port = htons(it->second);+ }+ *len = nlen;+ return 0;+ }+ }+ }+ uint16_t port = 0;+ {+ std::lock_guard<std::mutex> lock(s_sockMutex);+ auto it = s_boundPorts.find(fd);+ if (it != s_boundPorts.end()) {+ port = it->second;+ } else {+ port = static_cast<uint16_t>(50100 + (fd % 1000));+ }+ }+ auto* sin = reinterpret_cast<struct sockaddr_in*>(addr);+ std::memset(sin, 0, sizeof(*sin));+ sin->sin_len = sizeof(struct sockaddr_in);+ sin->sin_family = AF_INET;+ sin->sin_port = htons(port);+ sin->sin_addr.s_addr = 0; // INADDR_ANY so addr_is_any returns true+ *len = sizeof(struct sockaddr_in);+ return 0;+}++ssize_t sendto(int fd, const void* buf, size_t len, int flags,+ const struct sockaddr* dest_addr, socklen_t addrlen) {+ if (!dest_addr || addrlen < 2) {+ int ret = sceNetSendto(fd, buf, len, flags, nullptr, 0);+ if (ret < 0) {+ errno = sceNetErrnoLoc ? *sceNetErrnoLoc() : -ret;+ return -1;+ }+ return ret;+ }++ struct sockaddr_storage fixedAddr{};+ std::memcpy(&fixedAddr, dest_addr, std::min<size_t>(addrlen, sizeof(fixedAddr)));+ if (fixedAddr.ss_family == 0 && reinterpret_cast<const uint8_t*>(dest_addr)[0] == AF_INET) {+ fixedAddr.ss_family = AF_INET;+ fixedAddr.ss_len = sizeof(struct sockaddr_in);+ } else if (fixedAddr.ss_len == 0) {+ fixedAddr.ss_len = (fixedAddr.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);+ }++ int ret = sceNetSendto(fd, buf, len, flags, &fixedAddr, addrlen);+ if (ret < 0) {+ errno = sceNetErrnoLoc ? *sceNetErrnoLoc() : -ret;+ return -1;+ }+ return ret;+}++ssize_t recvfrom(int fd, void* buf, size_t len, int flags,+ struct sockaddr* src_addr, socklen_t* addrlen) {+ unsigned int slen = addrlen ? static_cast<unsigned int>(*addrlen) : 0;+ int ret = sceNetRecvfrom(fd, buf, len, flags, src_addr, addrlen ? &slen : nullptr);+ if (ret < 0) {+ errno = sceNetErrnoLoc ? *sceNetErrnoLoc() : -ret;+ return -1;+ }+ if (addrlen) *addrlen = slen;+ if (src_addr && slen >= sizeof(struct sockaddr_in)) {+ auto* sin = reinterpret_cast<struct sockaddr_in*>(src_addr);+ if (sin->sin_len == 0) sin->sin_len = sizeof(struct sockaddr_in);+ if (sin->sin_family == 0) sin->sin_family = AF_INET;+ }+ return ret;+}++ssize_t send(int fd, const void* buf, size_t len, int flags) {+ int ret = sceNetSend(fd, buf, len, flags);+ if (ret < 0) {+ errno = sceNetErrnoLoc ? *sceNetErrnoLoc() : -ret;+ return -1;+ }+ return ret;+}++ssize_t recv(int fd, void* buf, size_t len, int flags) {+ int ret = sceNetRecv(fd, buf, len, flags);+ if (ret < 0) {+ errno = sceNetErrnoLoc ? *sceNetErrnoLoc() : -ret;+ return -1;+ }+ return ret;+}++int connect(int fd, const struct sockaddr* addr, socklen_t len) {+ if (!addr) return -1;+ struct sockaddr_storage fixedAddr{};+ std::memcpy(&fixedAddr, addr, std::min<size_t>(len, sizeof(fixedAddr)));+ if (fixedAddr.ss_family == 0 && reinterpret_cast<const uint8_t*>(addr)[0] == AF_INET) {+ fixedAddr.ss_family = AF_INET;+ fixedAddr.ss_len = sizeof(struct sockaddr_in);+ } else if (fixedAddr.ss_len == 0) {+ fixedAddr.ss_len = (fixedAddr.ss_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in);+ }+ int ret = sceNetConnect(fd, &fixedAddr, len);+ if (ret < 0) {+ errno = sceNetErrnoLoc ? *sceNetErrnoLoc() : -ret;+ return -1;+ }+ return ret;+}++int listen(int fd, int backlog) {+ int ret = sceNetListen(fd, backlog);+ if (ret < 0) {+ errno = sceNetErrnoLoc ? *sceNetErrnoLoc() : -ret;+ return -1;+ }+ return ret;+}++int accept(int fd, struct sockaddr* addr, socklen_t* addrlen) {+ unsigned int slen = addrlen ? static_cast<unsigned int>(*addrlen) : 0;+ int ret = sceNetAccept(fd, addr, addrlen ? &slen : nullptr);+ if (ret < 0) {+ errno = sceNetErrnoLoc ? *sceNetErrnoLoc() : -ret;+ return -1;+ }+ if (addrlen) *addrlen = slen;+ return ret;+}++int setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen) {+ int ret = sceNetSetsockopt(fd, level, optname, optval, optlen);+ if (ret < 0) {+ errno = sceNetErrnoLoc ? *sceNetErrnoLoc() : -ret;+ return -1;+ }+ return 0;+}++int getsockopt(int fd, int level, int optname, void* optval, socklen_t* optlen) {+ unsigned int olen = optlen ? static_cast<unsigned int>(*optlen) : 0;+ int ret = sceNetGetsockopt(fd, level, optname, optval, optlen ? &olen : nullptr);+ if (ret < 0) {+ errno = sceNetErrnoLoc ? *sceNetErrnoLoc() : -ret;+ return -1;+ }+ if (optlen) *optlen = olen;+ return 0;+}++int close(int fd) {+ {+ std::lock_guard<std::mutex> lock(s_sockMutex);+ s_boundPorts.erase(fd);+ }+ int netRet = sceNetSocketClose(fd);+ if (netRet >= 0) {+ return 0;+ }+ return _close(fd);+}+}++extern "C" void arc4random_buf(void* buf, size_t n) {+ static int s_urandomFd = -1;+ if (s_urandomFd < 0) {+ s_urandomFd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);+ }+ size_t done = 0;+ if (s_urandomFd >= 0) {+ while (done < n) {+ ssize_t r = read(s_urandomFd, static_cast<char*>(buf) + done, n - done);+ if (r <= 0) break;+ done += static_cast<size_t>(r);+ }+ }+ if (done < n) {+ uint8_t* p = static_cast<uint8_t*>(buf) + done;+ for (size_t i = done; i < n; ++i) {+ *p++ = static_cast<uint8_t>(std::rand() ^ (std::rand() >> 8));+ }+ }+}++extern "C" int mbedtls_hardware_poll(void* /*data*/, unsigned char* output, size_t len, size_t* olen) {+ arc4random_buf(output, len);+ *olen = len;+ return 0;+}++extern "C" uint32_t ntohl(uint32_t netlong) {+ return __builtin_bswap32(netlong);+}++extern "C" uint32_t htonl(uint32_t hostlong) {+ return __builtin_bswap32(hostlong);+}++extern "C" uint16_t ntohs(uint16_t netshort) {+ return __builtin_bswap16(netshort);+}++extern "C" uint16_t htons(uint16_t hostshort) {+ return __builtin_bswap16(hostshort);+}++extern "C" int inet_pton(int af, const char* src, void* dst) {+ if (af != AF_INET || !src || !dst) return 0;+ unsigned int a, b, c, d;+ char tail = 0;+ if (std::sscanf(src, "%u.%u.%u.%u%c", &a, &b, &c, &d, &tail) == 4) {+ if (a <= 255 && b <= 255 && c <= 255 && d <= 255) {+ uint8_t* p = static_cast<uint8_t*>(dst);+ p[0] = static_cast<uint8_t>(a);+ p[1] = static_cast<uint8_t>(b);+ p[2] = static_cast<uint8_t>(c);+ p[3] = static_cast<uint8_t>(d);+ return 1;+ }+ }+ return 0;+}++extern "C" const char* inet_ntop(int af, const void* src, char* dst, socklen_t size) {+ if (!src || !dst) return nullptr;+ if (af == AF_INET) {+ if (size < 16) return nullptr;+ const auto* p = static_cast<const uint8_t*>(src);+ int n = std::snprintf(dst, size, "%u.%u.%u.%u", p[0], p[1], p[2], p[3]);+ if (n < 0 || static_cast<socklen_t>(n) >= size) return nullptr;+ return dst;+ }+ if (af == AF_INET6) {+ if (size < 46) return nullptr;+ const auto* p = static_cast<const uint8_t*>(src);+ uint16_t words[8];+ for (int i = 0; i < 8; ++i) {+ uint16_t w = 0;+ std::memcpy(&w, p + i * 2, sizeof(w));+ words[i] = ntohs(w);+ }+ int n = std::snprintf(dst, size, "%x:%x:%x:%x:%x:%x:%x:%x",+ words[0], words[1], words[2], words[3],+ words[4], words[5], words[6], words[7]);+ if (n < 0 || static_cast<socklen_t>(n) >= size) return nullptr;+ return dst;+ }+ return nullptr;+}++extern "C" int getnameinfo(const struct sockaddr* sa, socklen_t salen,+ char* host, socklen_t hostlen,+ char* serv, socklen_t servlen,+ int flags) {+ (void)salen;+ (void)flags;+ if (!sa) return EAI_FAIL;++ const auto* raw = reinterpret_cast<const uint8_t*>(sa);+ int family = -1;+ if (raw[0] == AF_INET || raw[1] == AF_INET) {+ family = AF_INET;+ } else if (raw[0] == 28 || raw[1] == 28 || raw[0] == 10 || raw[1] == 10) {+ family = AF_INET6;+ } else {+ return EAI_FAMILY;+ }++ int port = 0;+ if (family == AF_INET) {+ uint16_t netport = 0;+ std::memcpy(&netport, raw + 2, sizeof(netport));+ port = ntohs(netport);++ if (host && hostlen > 0) {+ int n = std::snprintf(host, hostlen, "%u.%u.%u.%u", raw[4], raw[5], raw[6], raw[7]);+ if (n < 0 || static_cast<socklen_t>(n) >= hostlen) return EAI_OVERFLOW;+ }+ } else {+ uint16_t netport = 0;+ std::memcpy(&netport, raw + 2, sizeof(netport));+ port = ntohs(netport);++ if (host && hostlen > 0) {+ uint16_t words[8];+ for (int i = 0; i < 8; ++i) {+ uint16_t w = 0;+ std::memcpy(&w, raw + 8 + i * 2, sizeof(w));+ words[i] = ntohs(w);+ }+ int n = std::snprintf(host, hostlen, "%x:%x:%x:%x:%x:%x:%x:%x",+ words[0], words[1], words[2], words[3],+ words[4], words[5], words[6], words[7]);+ if (n < 0 || static_cast<socklen_t>(n) >= hostlen) return EAI_OVERFLOW;+ }+ }++ if (serv && servlen > 0) {+ int n = std::snprintf(serv, servlen, "%d", port);+ if (n < 0 || static_cast<socklen_t>(n) >= servlen) return EAI_OVERFLOW;+ }+ return 0;+}++extern "C" int poll(struct pollfd* fds, nfds_t nfds, int timeout) {+ fd_set readfds, writefds, exceptfds;+ FD_ZERO(&readfds);+ FD_ZERO(&writefds);+ FD_ZERO(&exceptfds);+ int maxfd = -1;+ for (nfds_t i = 0; i < nfds; ++i) {+ fds[i].revents = 0;+ if (fds[i].fd < 0 || fds[i].fd >= FD_SETSIZE) continue;+ if (fds[i].events & (POLLIN | POLLPRI)) FD_SET(fds[i].fd, &readfds);+ if (fds[i].events & POLLOUT) FD_SET(fds[i].fd, &writefds);+ FD_SET(fds[i].fd, &exceptfds);+ if (fds[i].fd > maxfd) maxfd = fds[i].fd;+ }+ struct timeval tv{};+ struct timeval* ptv = nullptr;+ if (timeout >= 0) {+ tv.tv_sec = timeout / 1000;+ tv.tv_usec = (timeout % 1000) * 1000;+ ptv = &tv;+ }+ if (maxfd < 0) {+ if (timeout > 0) usleep(static_cast<useconds_t>(timeout) * 1000);+ return 0;+ }+ int rc = select(maxfd + 1, &readfds, &writefds, &exceptfds, ptv);+ if (rc <= 0) return rc;+ int count = 0;+ for (nfds_t i = 0; i < nfds; ++i) {+ if (fds[i].fd < 0 || fds[i].fd >= FD_SETSIZE) continue;+ short rev = 0;+ if (FD_ISSET(fds[i].fd, &readfds)) rev |= POLLIN;+ if (FD_ISSET(fds[i].fd, &writefds)) rev |= POLLOUT;+ if (FD_ISSET(fds[i].fd, &exceptfds)) rev |= POLLERR;+ fds[i].revents = rev;+ if (rev) count++;+ }+ return count;+}++extern "C" int __cxa_thread_atexit_impl(void (*)(void*), void*, void*) {+ return 0;+}++extern "C" int getifaddrs(struct ifaddrs** ifap) {+ if (!ifap) return -1;+ *ifap = nullptr;++ int s = socket(AF_INET, SOCK_DGRAM, 0);+ if (s < 0) return 0;++ struct sockaddr_in probe{};+ probe.sin_family = AF_INET;+ probe.sin_port = htons(53);+ probe.sin_addr.s_addr = htonl(0x08080808); // 8.8.8.8+ if (connect(s, reinterpret_cast<struct sockaddr*>(&probe), sizeof(probe)) != 0) {+ close(s);+ return 0;+ }++ struct sockaddr_in local{};+ socklen_t localLen = sizeof(local);+ if (getsockname(s, reinterpret_cast<struct sockaddr*>(&local), &localLen) != 0 || local.sin_addr.s_addr == 0) {+ FILE* fp = std::fopen("/data/psbox/local_ip.txt", "r");+ if (fp) {+ char buf[64]{};+ if (std::fgets(buf, sizeof(buf), fp)) {+ char* nl = std::strpbrk(buf, "\r\n ");+ if (nl) *nl = '\0';+ inet_pton(AF_INET, buf, &local.sin_addr);+ }+ std::fclose(fp);+ }+ if (local.sin_addr.s_addr == 0) {+ inet_pton(AF_INET, "192.168.15.30", &local.sin_addr);+ }+ }+ local.sin_family = AF_INET;+ local.sin_len = sizeof(struct sockaddr_in);+ close(s);++ struct Entry {+ struct ifaddrs ifa;+ struct sockaddr_in addr;+ struct sockaddr_in mask;+ char name[16];+ };++ auto* e = static_cast<Entry*>(std::calloc(1, sizeof(Entry)));+ if (!e) return -1;++ std::strncpy(e->name, "eth0", sizeof(e->name) - 1);+ e->addr = local;+ e->mask.sin_family = AF_INET;+ e->mask.sin_addr.s_addr = htonl(0xFFFFFF00);++ e->ifa.ifa_next = nullptr;+ e->ifa.ifa_name = e->name;+ e->ifa.ifa_flags = IFF_UP | IFF_RUNNING | IFF_BROADCAST | IFF_MULTICAST;+ e->ifa.ifa_addr = reinterpret_cast<struct sockaddr*>(&e->addr);+ e->ifa.ifa_netmask = reinterpret_cast<struct sockaddr*>(&e->mask);++ *ifap = &e->ifa;+ return 0;+}++extern "C" void freeifaddrs(struct ifaddrs* ifa) {+ while (ifa) {+ struct ifaddrs* next = ifa->ifa_next;+ std::free(ifa);+ ifa = next;+ }+}++extern "C" {+struct SceKernelSwVersion {+ uint64_t size;+ char versionString[0x1C];+ uint32_t version;+};+int sceKernelGetSystemSwVersion(SceKernelSwVersion* version);+int sceSystemServiceLoadExec(const char* path, char* const argv[]);+int sceKernelSendNotificationRequest(int device, void* request, size_t size, int blocking);+int sceNetInit(void);+int sceNetPoolCreate(const char* name, int size, int flags);+int sceNetResolverCreate(const char* name, int memid, int flags);+int sceNetResolverStartNtoa(int rid, const char* hostname, uint32_t* addr, int timeout, int retry, int flags);+int sceNetResolverDestroy(int rid);+}++namespace xc::platform {++namespace {+constexpr const char* kDataDir = "/data/psbox";+constexpr const char* kLegacyDir = "/data/homebrew/PSBOX00001";+std::string g_dataDir = kDataDir;+std::string g_dataNote;+bool g_dataDirWritable = false;+int g_dataDirErrno = 0;+std::atomic<int> g_netPool{-1};++bool writable(const std::string& dir, int& errOut) {+ errOut = 0;+ struct stat st{};+ if (::stat(dir.c_str(), &st) != 0) {+ if (::mkdir(dir.c_str(), 0777) != 0) {+ errOut = errno;+ return false;+ }+ } else {+ ::chmod(dir.c_str(), 0777);+ }+ std::string probe = dir + "/.write-test";+ if (!writeFileAtomic(probe, "ok")) {+ errOut = errno;+ return false;+ }+ ::unlink(probe.c_str());+ return true;+}++void migrateLegacy() {+ const std::string data = kDataDir, legacy = kLegacyDir, done = data + "/.migrated";+ std::string text;+ if (readFile(done, text)) return;+ int moved = 0;+ for (const char* name : {"account.json", "settings.json", "library.json", "library_cache.json", "prices.json"}) {+ std::string mine;+ if (readFile(legacy + "/" + name, text) && !readFile(data + "/" + name, mine) &&+ writeFileAtomic(data + "/" + name, text))+ ++moved;+ }+ if (readFile(data + "/account.json", text)) ::unlink((legacy + "/account.json").c_str());+ writeFileAtomic(done, "1\n");+ if (moved) g_dataNote = "moved " + std::to_string(moved) + " file(s) from " + legacy + " to " + data;+}++} // namespace++bool init() {+ int errPsbox = 0;+ int errLegacy = 0;+ if (writable(kDataDir, errPsbox)) {+ g_dataDirWritable = true;+ migrateLegacy();+ } else if (writable(kLegacyDir, errLegacy)) {+ g_dataDirWritable = true;+ g_dataDir = kLegacyDir;+ g_dataNote = std::string(kDataDir) + " not writable (errno " + std::to_string(errPsbox) + "); using " + kLegacyDir;+ } else {+ bool found = false;+ for (const char* fb : {"/download0/psbox", "/user/home/psbox", "/temp0/psbox"}) {+ int errFb = 0;+ if (writable(fb, errFb)) {+ g_dataDir = fb;+ g_dataDirWritable = true;+ g_dataNote = std::string("neither ") + kDataDir + " (errno " + std::to_string(errPsbox) ++ ") nor " + kLegacyDir + " (errno " + std::to_string(errLegacy) ++ ") writable; fallback to " + fb;+ found = true;+ break;+ }+ }+ if (!found) {+ g_dataDirErrno = errPsbox ? errPsbox : errLegacy;+ g_dataDirWritable = false;+ g_dataNote = std::string("neither ") + kDataDir + " (errno " + std::to_string(errPsbox) ++ ") nor " + kLegacyDir + " (errno " + std::to_string(errLegacy) ++ ") is writable: nothing will be kept";+ }+ }++ int rc = sceNetInit();+ if (rc < 0 && rc != static_cast<int>(0x80410101)) {+ XC_LOGW("sceNetInit: 0x%08x", static_cast<unsigned>(rc));+ }+ int pool = sceNetPoolCreate("xcloud", 32 * 1024, 0);+ if (pool < 0) {+ XC_LOGE("sceNetPoolCreate: 0x%08x (host names will not resolve)", static_cast<unsigned>(pool));+ }+ g_netPool = pool;+ return true;+}++void shutdown() {}++std::string appDir() { return "/app0"; }+std::string dataDir() { return g_dataDir; }+std::string dataDirNote() { return g_dataNote; }+bool dataDirWritable() { return g_dataDirWritable; }+int dataDirErrno() { return g_dataDirErrno; }+std::string assetDir() { return "/app0/assets"; }+std::string caBundlePath() { return "/app0/assets/cacert.pem"; }++bool randomBytes(void* out, size_t len) {+ arc4random_buf(out, len);+ return true;+}++bool resolveIPv4(const std::string& host, uint32_t& addr, std::string& err) {+ in_addr literal{};+ if (::inet_pton(AF_INET, host.c_str(), &literal) == 1) {+ addr = literal.s_addr;+ return true;+ }+ int pool = g_netPool.load();+ if (pool < 0) {+ err = "DNS lookup failed for " + host + ": networking not initialised";+ return false;+ }+ int rid = sceNetResolverCreate("xcloud", pool, 0);+ if (rid < 0) {+ char buf[64];+ std::snprintf(buf, sizeof buf, "sceNetResolverCreate 0x%08x", static_cast<unsigned>(rid));+ err = "DNS lookup failed for " + host + ": " + buf;+ return false;+ }+ uint32_t a = 0;+ int rc = sceNetResolverStartNtoa(rid, host.c_str(), &a, 5000000, 2, 0);+ sceNetResolverDestroy(rid);+ if (rc < 0) {+ char buf[64];+ std::snprintf(buf, sizeof buf, "0x%08x", static_cast<unsigned>(rc));+ err = "DNS lookup failed for " + host + " (" + buf + ")";+ return false;+ }+ addr = a;+ return true;+}++void probeNetworking() {}+++bool restartApp() {+ char* argv[] = {nullptr};+ int rc = sceSystemServiceLoadExec("/app0/eboot.bin", argv);+ XC_LOGE("restart: sceSystemServiceLoadExec returned 0x%08x", static_cast<unsigned>(rc));+ return false;+}++std::string firmwareVersion() {+ SceKernelSwVersion v{};+ v.size = sizeof v;+ if (sceKernelGetSystemSwVersion(&v) != 0) return {};+ v.versionString[sizeof v.versionString - 1] = 0;+ std::string s = v.versionString;+ while (!s.empty() && s.front() == ' ') s.erase(0, 1);+ return s;+}++std::string platformName() {+ return "PlayStation 4 (BREW99810)";+}++void makePrivate(const std::string&) {}++void notify(const std::string& text) { notify(text, text); }++void notify(const std::string& text, const std::string& forLog) {+ XC_LOGI("NOTIFY: %s", forLog.c_str());+ if (toastsEnabled() && forLog != "signed in (notification)") toasts().push(text, nowMs());+ struct NotificationRequest {+ uint8_t reserved[45];+ char message[3075];+ } req{};+ std::snprintf(req.message, sizeof req.message, "%s", text.c_str());+ sceKernelSendNotificationRequest(0, &req, sizeof req, 0);+}++void setThreadAffinity(ThreadRole role, const char* name) {+ if (name && *name) {+ pthread_set_name_np(pthread_self(), name);+ }+ static cpu_set_t s_procMask;+ static bool s_procMaskQueried = false;+ static int s_allowedCpus[32];+ static int s_numAllowedCpus = 0;++ if (!s_procMaskQueried) {+ s_procMaskQueried = true;+ CPU_ZERO(&s_procMask);+ int grc = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &s_procMask);+ if (grc == 0) {+ for (int i = 0; i < 32; ++i) {+ if (CPU_ISSET(i, &s_procMask)) {+ s_allowedCpus[s_numAllowedCpus++] = i;+ }+ }+ }+ // Fallback to 6 Jaguar cores (mask 0x3F: cores 0..5) on PS4 if not detected+ if (s_numAllowedCpus < 2) {+ s_numAllowedCpus = 0;+ for (int i = 0; i < 6; ++i) {+ s_allowedCpus[s_numAllowedCpus++] = i;+ }+ }+ XC_LOGI("ps4 cpuset: %d allowed cpus detected (grc=%d)", s_numAllowedCpus, grc);+ for (int i = 0; i < s_numAllowedCpus; ++i) {+ XC_LOGI(" cpu slot %d: logical core %d", i, s_allowedCpus[i]);+ }+ }++ if (s_numAllowedCpus <= 1) {+ return;+ }++ cpu_set_t mask;+ CPU_ZERO(&mask);+ auto setSlot = [&](int slotIndex) {+ int idx = s_allowedCpus[slotIndex % s_numAllowedCpus];+ CPU_SET(idx, &mask);+ };++ switch (role) {+ case ThreadRole::Main:+ setSlot(0);+ break;+ case ThreadRole::Network:+ setSlot(1);+ break;+ case ThreadRole::VideoDecode:+ setSlot(2);+ if (s_numAllowedCpus >= 4) setSlot(3);+ break;+ case ThreadRole::Audio:+ setSlot(s_numAllowedCpus >= 5 ? 4 : 1);+ break;+ case ThreadRole::Worker:+ if (s_numAllowedCpus >= 6) {+ setSlot(5);+ } else {+ setSlot(s_numAllowedCpus - 1);+ }+ break;+ }+ int rc = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &mask);+ if (rc != 0) {+ XC_LOGW("pthread_setaffinity_np(%s): %d", name ? name : "thread", rc);+ } else {+ XC_LOGI("thread %s pinned to role %d", name ? name : "unknown", static_cast<int>(role));+ }+}++void setThreadRealtimePriority() {+ struct sched_param param{};+ param.sched_priority = 64; // Orbis audio realtime priority+ int rc = pthread_setschedparam(pthread_self(), SCHED_RR, ¶m);+ if (rc != 0) {+ XC_LOGW("pthread_setschedparam(SCHED_RR, 64): %d (the audio thread keeps the default)", rc);+ } else {+ XC_LOGI("thread elevated to SCHED_RR (prio=64)");+ }+}++} // namespace xc::platform++extern "C" int xc_resolve_ipv4(const char* host, uint32_t* addr) {+ std::string err;+ if (xc::platform::resolveIPv4(host, *addr, err)) return 0;+ XC_LOGW("%s", err.c_str());+ return -1;+}++// IPv4-only getaddrinfo. The OpenOrbis musl version fails on PS4 even for+// numeric literals, which kept every remote ICE candidate unresolved.+namespace {+struct Ps4AddrInfo {+ struct addrinfo ai;+ struct sockaddr_in sin;+};+} // namespace++extern "C" int getaddrinfo(const char* node, const char* service, const struct addrinfo* hints,+ struct addrinfo** res) {+ if (!res) return EAI_FAIL;+ *res = nullptr;+ if (!node && !service) return EAI_NONAME;+ const int family = hints ? hints->ai_family : AF_UNSPEC;+ const int flags = hints ? hints->ai_flags : 0;+ if (family != AF_UNSPEC && family != AF_INET) return EAI_FAMILY;++ uint16_t port = 0;+ if (service && *service) {+ char* end = nullptr;+ unsigned long p = std::strtoul(service, &end, 10);+ if (!end || *end != '\0' || p > 65535) return EAI_SERVICE;+ port = static_cast<uint16_t>(p);+ }++ in_addr addr{};+ if (!node) {+ addr.s_addr = (flags & AI_PASSIVE) ? htonl(INADDR_ANY) : htonl(INADDR_LOOPBACK);+ } else if (::inet_pton(AF_INET, node, &addr) != 1) {+ in6_addr v6{};+ if (::inet_pton(AF_INET6, node, &v6) == 1) return EAI_FAMILY; // no IPv6 on PS4+ if (flags & AI_NUMERICHOST) return EAI_NONAME;+ if (std::strcmp(node, "localhost") == 0) {+ addr.s_addr = htonl(INADDR_LOOPBACK);+ } else {+ uint32_t a = 0;+ if (xc_resolve_ipv4(node, &a) != 0) return EAI_NONAME;+ addr.s_addr = a;+ }+ }++ auto* r = static_cast<Ps4AddrInfo*>(std::calloc(1, sizeof(Ps4AddrInfo)));+ if (!r) return EAI_MEMORY;+ r->sin.sin_len = sizeof(struct sockaddr_in);+ r->sin.sin_family = AF_INET;+ r->sin.sin_port = htons(port);+ r->sin.sin_addr = addr;+ r->ai.ai_flags = flags;+ r->ai.ai_family = AF_INET;+ r->ai.ai_socktype = hints && hints->ai_socktype ? hints->ai_socktype : SOCK_STREAM;+ r->ai.ai_protocol = hints ? hints->ai_protocol : 0;+ r->ai.ai_addrlen = sizeof(struct sockaddr_in);+ r->ai.ai_addr = reinterpret_cast<struct sockaddr*>(&r->sin);+ r->ai.ai_canonname = nullptr;+ r->ai.ai_next = nullptr;+ *res = &r->ai;+ return 0;+}++extern "C" void freeaddrinfo(struct addrinfo* ai) {+ while (ai) {+ struct addrinfo* next = ai->ai_next;+ std::free(ai); // ai is the first member of Ps4AddrInfo+ ai = next;+ }+}diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cppindex 5431cf9..60aaeed 100644--- a/src/stream/stream_session.cpp+++ b/src/stream/stream_session.cpp@@ -420,9 +420,11 @@ struct StreamSession::Impl {void createPeer() {initRtcLogging();+ XC_LOGI("webrtc: createPeer starting");rtc::Configuration config;config.disableAutoNegotiation = true;pc = std::make_shared<rtc::PeerConnection>(config);+ XC_LOGI("webrtc: PeerConnection created");pc->onLocalCandidate([this](rtc::Candidate c) {std::lock_guard<std::mutex> lock(mutex);@@ -542,6 +544,7 @@ struct StreamSession::Impl {}if (cb.video) cb.video(reinterpret_cast<const uint8_t*>(data.data()), data.size(), info.timestamp);});+ XC_LOGI("webrtc: createPeer completed");}bool waitFor(const std::function<bool()>& pred, int timeoutMs) {@@ -561,8 +564,11 @@ struct StreamSession::Impl {}bool start(std::string& err) {+ XC_LOGI("webrtc: start() calling createPeer");createPeer();+ XC_LOGI("webrtc: calling pc->setLocalDescription");pc->setLocalDescription(rtc::Description::Type::Offer);+ XC_LOGI("webrtc: setLocalDescription returned; waiting for ICE gathering");if (!waitFor([this] { return gatheringDone; }, 10000))XC_LOGW("ICE gathering did not complete; continuing with %zu candidates", localCandidates.size());diff --git a/tools/build-all.sh b/tools/build-all.shnew file mode 100755index 0000000..ec14746--- /dev/null+++ b/tools/build-all.sh@@ -0,0 +1,25 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-3.0-or-later+# Copyright (C) 2026 RafaelNGP+# One-shot build script for all platforms (Desktop, PS5, PS4) and boundary validation.+set -euo pipefail++root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)+cd "$root"++echo "=== Building Desktop (SDL3 & No-SDL) ==="+ninja -C build-desktop+ninja -C build-desktop-nosdl++echo "=== Building PS5 (Vulkan & eboot.bin) ==="+ninja -C build-ps5 xcloud_app+bash tools/ps5/link.sh build-ps5++echo "=== Building PS4 (OpenOrbis & PKG) ==="+ninja -C build-ps4+bash tools/ps4/package.sh build-ps4++echo "=== Checking Platform Boundaries ==="+bash tools/check-platform-boundaries.sh++echo "=== All platform builds and boundary checks passed! ==="diff --git a/tools/build-ffmpeg.sh b/tools/build-ffmpeg.shindex 9a4cb1a..46ca8eb 100755--- a/tools/build-ffmpeg.sh+++ b/tools/build-ffmpeg.sh@@ -6,9 +6,10 @@## tools/build-ffmpeg.sh host <build-dir> -> <build-dir>/ffmpeg/{include,lib}# tools/build-ffmpeg.sh ps5 <build-dir>+# tools/build-ffmpeg.sh ps4 <build-dir>set -euo pipefail-target=${1:?usage: build-ffmpeg.sh host|ps5 <build-dir>}+target=${1:?usage: build-ffmpeg.sh host|ps5|ps4 <build-dir>}build=$(mkdir -p "${2:?build dir}" && cd "$2" && pwd)root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)prefix=$build/ffmpeg@@ -61,6 +62,20 @@ if [[ $target == ps5 ]]; then--ld="$cache/configure-ld.sh" \--extra-cflags="$flags" --extra-ldflags="" \--disable-pthreads --enable-pthreads+elif [[ $target == ps4 ]]; then+ toolchain=${OO_PS4_TOOLCHAIN:-$(cd "$root/ps4-toolchain" && pwd)}+ export OO_PS4_TOOLCHAIN=$toolchain+ ln -sfn "$toolchain" "$cache/ps4-toolchain"+ ln -sfn "$root/tools/ps4/configure-ld.sh" "$cache/configure-ld.sh"+ mkdir -p "$cache/compat/sys"+ cp "$root/ps4/compat/sys/sysctl.h" "$cache/compat/sys/sysctl.h"+ flags="-target x86_64-pc-freebsd12-elf -fPIC -msse4.2 -mpopcnt -mtune=btver2 -D_GNU_SOURCE -D__ORBIS__ -D__PS4__ -DXC_TARGET_PS4=1 -isystem $cache/compat -isystem $cache/ps4-toolchain/include"+ "$src/configure" "${common[@]}" \+ --enable-cross-compile --target-os=freebsd --arch=x86_64 \+ --cc=clang --ar=llvm-ar --ranlib=llvm-ranlib --nm=llvm-nm \+ --ld="$cache/configure-ld.sh" \+ --extra-cflags="$flags" --extra-ldflags="" \+ --disable-pthreads --enable-pthreadselse"$src/configure" "${common[@]}" --cc=clangfidiff --git a/tools/check-platform-boundaries.sh b/tools/check-platform-boundaries.shindex 2b8eeba..91f8f77 100755--- a/tools/check-platform-boundaries.sh+++ b/tools/check-platform-boundaries.sh@@ -23,6 +23,9 @@ allowed=('src/platform/ps5/*' # the PS5's platform layer'src/*_ps5.cpp' # PS5 backends: display, controller, kbm, hw_decoder, shell...'ps5/*' # link stubs and compat headers for the PS5 SDK+ 'src/platform/ps4/*' # the PS4's platform layer+ 'src/*_ps4.cpp' # PS4 backends: display, controller, hw_decoder, shell...+ 'ps4/*' # link stubs and metadata for PS4# Legacy: these still pick their PS5 code with #if. Each comes off the# list once it is split into a PS5 backend and a portable part.'src/app/crash_guard.cpp' # TODO(M2): crash_guard_ps5.cpp / POSIX / Windows (SEH)diff --git a/tools/ps4/autotest.sh b/tools/ps4/autotest.shnew file mode 100755index 0000000..1899860--- /dev/null+++ b/tools/ps4/autotest.sh@@ -0,0 +1,113 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-3.0-or-later+# Copyright (C) 2026 RafaelNGP+# One unattended shadPS4 emulator run: build, stage, launch in autoplay mode,+# wait for result, stop the emulator, collect logs and convert PPM screenshots to PNG.+#+# tools/ps4/autotest.sh [titleOrTest] [seconds] [options]+# Example:+# tools/ps4/autotest.sh AUTOTEST 30 librarytest+# tools/ps4/autotest.sh AUTOTEST 30 settingstest+# tools/ps4/autotest.sh BALATRO 30 dump+set -euo pipefail++root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)+test_title="${1:-AUTOTEST}"+seconds="${2:-30}"+test_opt="${3:-librarytest}"++out="$root/build-ps4/autotest"+mkdir -p "$out"+rm -f "$out"/*.ppm "$out"/*.png "$out"/xcloud.log++SHADPS4_BIN="${SHADPS4_BIN:-/home/notebook-storm/Downloads/shadps4/Shadps4-sdl.AppImage}"+if [ ! -x "$SHADPS4_BIN" ]; then+ echo "error: shadPS4 executable not found at $SHADPS4_BIN" >&2+ exit 1+fi++SHADPS4_DATA="${SHADPS4_DATA:-$HOME/.local/share/shadPS4}"+PSBOX_DATA="$SHADPS4_DATA/data/psbox"+STAGE_DIR="$SHADPS4_DATA/game_data/CUSA00100"+mkdir -p "$PSBOX_DATA" "$STAGE_DIR"++echo "==> Building PS4 target"+ninja -C "$root/build-ps4"++echo "==> Packaging PS4 target"+XC_INCLUDE_ACCOUNT=1 bash "$root/tools/ps4/package.sh" "$root/build-ps4" >/dev/null++echo "==> Staging to shadPS4 ($STAGE_DIR)"+cp -rf "$root/build-ps4/pkg_stage/." "$STAGE_DIR/"+if [ -f "$root/build-ps4/pkg_stage/account.json" ]; then+ cp -f "$root/build-ps4/pkg_stage/account.json" "$PSBOX_DATA/account.json"+fi++# Clean old dumps+for f in ui.ppm library.ppm splash.ppm detail.ppm settings.ppm screen.ppm error.ppm frame.ppm frame2.ppm xcloud.log; do+ rm -f "$PSBOX_DATA/$f"+done+rm -f "$PSBOX_DATA/autoplay.txt"++# Write test directive+echo "$test_title $seconds $test_opt" > "$PSBOX_DATA/autoplay.txt"+echo "==> Configured autoplay: $(cat "$PSBOX_DATA/autoplay.txt")"++# Launch shadPS4+echo "==> Launching shadPS4..."+"$SHADPS4_BIN" -g "$STAGE_DIR/eboot.bin" > "$out/shadps4.log" 2>&1 &+sleep 2++cleanup() {+ echo "==> Cleaning up..."+ pkill -TERM -f "shadps4" 2>/dev/null || true+ sleep 1+ pkill -9 -f "shadps4" 2>/dev/null || true+ rm -f "$PSBOX_DATA/autoplay.txt"+}+trap cleanup EXIT++deadline=$(( $(date +%s) + seconds + 90 ))+result="timeout"++echo "==> Waiting for test completion (deadline ${seconds}s + margin)..."+while (( $(date +%s) < deadline )); do+ sleep 3+ if ! pgrep -f "shadps4" >/dev/null 2>&1; then+ result="exited_early"+ break+ fi+ if [ -f "$PSBOX_DATA/xcloud.log" ] && grep -q "AUTOPLAY END" "$PSBOX_DATA/xcloud.log" 2>/dev/null; then+ result="finished"+ break+ fi+done++echo "==> Test result: $result"+sleep 2++# Copy results+if [ -f "$PSBOX_DATA/xcloud.log" ]; then+ cp -f "$PSBOX_DATA/xcloud.log" "$out/xcloud.log"+fi++python3 - <<PY+import os, glob+from PIL import Image++psbox_data = "$PSBOX_DATA"+out_dir = "$out"++for ppm in glob.glob(os.path.join(psbox_data, "*.ppm")):+ base = os.path.basename(ppm)+ dest_ppm = os.path.join(out_dir, base)+ dest_png = os.path.splitext(dest_ppm)[0] + ".png"+ try:+ im = Image.open(ppm)+ im.save(dest_png)+ print(f"Captured & converted: {dest_png}")+ except Exception as e:+ print(f"Failed converting {ppm}: {e}")+PY++echo "==> PS4 / shadPS4 autotest complete. Artifacts in $out"diff --git a/tools/ps4/configure-ld.sh b/tools/ps4/configure-ld.shnew file mode 100755index 0000000..92c79ca--- /dev/null+++ b/tools/ps4/configure-ld.sh@@ -0,0 +1,21 @@+#!/bin/sh+# SPDX-License-Identifier: GPL-3.0-or-later+# Copyright (C) 2026 RafaelNGP+# Linker for third-party configure scripts (FFmpeg) on PS4: links test+# programs as a PIE against the OpenOrbis toolchain stub libraries.+: "${OO_PS4_TOOLCHAIN:?}"+set -- "$@"+out=a.out+objs=+while [ $# -gt 0 ]; do+ case $1 in+ -o) out=$2; shift ;;+ -o*) out=${1#-o} ;;+ -l*|-L*|-Wl,*|-pthread|-m*|-f*|-O*|-g*|-std=*|-isysroot|-isystem|-target|--target=*|-D*|-I*|-W*)+ case $1 in -isysroot|-isystem|-target) shift ;; esac ;;+ *.o|*.a) objs="$objs $1" ;;+ esac+ shift+done+# shellcheck disable=SC2086+exec ld.lld -m elf_x86_64 -pie --script "$OO_PS4_TOOLCHAIN/link.x" -o "$out" $objs -L"$OO_PS4_TOOLCHAIN/lib" -lc -lkernel "$OO_PS4_TOOLCHAIN/lib/crt1.o"diff --git a/tools/ps4/fetch-toolchain.sh b/tools/ps4/fetch-toolchain.shnew file mode 100755index 0000000..b7310bc--- /dev/null+++ b/tools/ps4/fetch-toolchain.sh@@ -0,0 +1,38 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-3.0-or-later+# Copyright (C) 2026 RafaelNGP+# Download the OpenOrbis PS4 Toolchain release into $1 (default: ./ps4-toolchain)+set -euo pipefail++DEST="${1:-$(pwd)/ps4-toolchain}"+LLVM_VER="${2:-18}"+URL="https://github.com/OpenOrbis/OpenOrbis-PS4-Toolchain/releases/latest/download/toolchain-llvm-${LLVM_VER}.tar.gz"++if [ -f "$DEST/link.x" ] && [ -f "$DEST/lib/crt1.o" ]; then+ echo "OpenOrbis toolchain already present at $DEST"+ exit 0+fi++mkdir -p "$DEST"+echo "Downloading $URL"+curl -sSL --fail -o "$DEST/toolchain.tar.gz" "$URL"+echo "Extracting to $DEST"+tar -xzf "$DEST/toolchain.tar.gz" -C "$DEST" --strip-components=2+rm -f "$DEST/toolchain.tar.gz"++if [ ! -f "$DEST/link.x" ] || [ ! -f "$DEST/lib/crt1.o" ]; then+ echo "error: $DEST does not contain link.x / lib/crt1.o after extraction" >&2+ exit 1+fi+chmod +x "$DEST"/bin/linux/* 2>/dev/null || true++# Patch upstream OpenOrbis ABI bug: pthread_*attr_t were defined as 32-bit int instead of 64-bit pointer,+# corrupting adjacent memory and causing SIGSEGV in pthread_mutex_init/pthread_rwlock_init.+if [ -f "$DEST/include/bits/alltypes.h" ]; then+ sed -i 's/typedef struct { unsigned __attr; } pthread_mutexattr_t;/typedef struct { void *__attr; } pthread_mutexattr_t;/' "$DEST/include/bits/alltypes.h"+ sed -i 's/typedef struct { unsigned __attr; } pthread_condattr_t;/typedef struct { void *__attr; } pthread_condattr_t;/' "$DEST/include/bits/alltypes.h"+ sed -i 's/typedef struct { unsigned __attr; } pthread_barrierattr_t;/typedef struct { void *__attr; } pthread_barrierattr_t;/' "$DEST/include/bits/alltypes.h"+ sed -i 's/typedef struct { unsigned __attr\[2\]; } pthread_rwlockattr_t;/typedef struct { void *__attr; } pthread_rwlockattr_t;/' "$DEST/include/bits/alltypes.h"+fi++echo "OpenOrbis toolchain installed at $DEST."diff --git a/tools/ps4/gp4_rootdir.py b/tools/ps4/gp4_rootdir.pynew file mode 100755index 0000000..827d3ae--- /dev/null+++ b/tools/ps4/gp4_rootdir.py@@ -0,0 +1,43 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: GPL-3.0-or-later+# Copyright (C) 2026 RafaelNGP+"""Rewrite the <rootdir> block of a GP4 project from the real directory tree.++OpenOrbis' create-gp4 writes a fixed sample layout instead of deriving the+directories from --files, and PkgTool's PFS builder throws "Sequence contains no elements"+for any file whose directory is missing there. This regenerates the block from <stage-dir>.++Usage: gp4_rootdir.py <project.gp4> <stage-dir>+"""+import os+import re+import sys++if len(sys.argv) < 3:+ sys.exit("usage: gp4_rootdir.py <project.gp4> <stage-dir>")++gp4, stage = sys.argv[1], sys.argv[2]++def tree(path, depth):+ out = []+ for name in sorted(os.listdir(path)):+ full = os.path.join(path, name)+ if not os.path.isdir(full):+ continue+ indent = "\t" * depth+ sub = tree(full, depth + 1)+ if sub:+ out.append(f'{indent}<dir targ_name="{name}">')+ out.extend(sub)+ out.append(f'{indent}</dir>')+ else:+ out.append(f'{indent}<dir targ_name="{name}" />')+ return out++block = "\t<rootdir>\n" + "\n".join(tree(stage, 2)) + "\n\t</rootdir>"+text = open(gp4).read()+new, n = re.subn(r"\t<rootdir>.*?</rootdir>", block, text, flags=re.S)+if n != 1:+ sys.exit("gp4_rootdir.py: no <rootdir> block found in " + gp4)+open(gp4, "w").write(new)+print(f"gp4_rootdir.py: rebuilt <rootdir> with {sum(1 for l in block.splitlines() if '<dir' in l)} directories")diff --git a/tools/ps4/package.sh b/tools/ps4/package.shnew file mode 100755index 0000000..6d0d843--- /dev/null+++ b/tools/ps4/package.sh@@ -0,0 +1,163 @@+#!/usr/bin/env bash+# SPDX-License-Identifier: GPL-3.0-or-later+# Copyright (C) 2026 RafaelNGP+# Turn a built xCloud PS4 ELF into eboot.bin and an installable PS4 .pkg using the+# OpenOrbis tools (create-fself, create-gp4, PkgTool.Core).+#+# tools/ps4/package.sh <build-dir> [out-dir]+set -euo pipefail++BUILD_DIR_ARG="${1:?usage: package.sh <build-dir> [out-dir]}"+BUILD_DIR="$(cd "$BUILD_DIR_ARG" && pwd)"+OUT_DIR="${2:-$BUILD_DIR/pkg}"+mkdir -p "$OUT_DIR"+OUT_DIR="$(cd "$OUT_DIR" && pwd)"+REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"++if [ -z "${OO_PS4_TOOLCHAIN:-}" ]; then+ if [ -d "$REPO_DIR/ps4-toolchain" ]; then+ export OO_PS4_TOOLCHAIN="$REPO_DIR/ps4-toolchain"+ else+ echo "error: OO_PS4_TOOLCHAIN not set and ps4-toolchain not found" >&2+ exit 1+ fi+fi++case "$(uname -s)" in+ Linux) TOOLS="$OO_PS4_TOOLCHAIN/bin/linux" ;;+ Darwin) TOOLS="$OO_PS4_TOOLCHAIN/bin/macos" ;;+ *) echo "unsupported host $(uname -s)" >&2; exit 1 ;;+esac++export DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1+if [ -n "${XC_PS4_LIBSSL11_DIR:-}" ]; then+ export LD_LIBRARY_PATH="${XC_PS4_LIBSSL11_DIR}${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"+elif [ "$(uname -s)" = "Linux" ] && ! ldconfig -p 2>/dev/null | grep -q "libssl\.so\.1\.1"; then+ _shim="${TMPDIR:-/tmp}/xcloud-openssl11-shim"+ if [ ! -f "$_shim/libssl.so.1.1" ]; then+ mkdir -p "$_shim"+ cat > "$_shim/shim.c" <<'SHIM_C'+extern void ERR_new(void);+extern void ERR_set_debug(const char *file, int line, const char *func);+extern void ERR_set_error(int lib, int reason, const char *fmt, ...);+void ERR_put_error(int lib, int func, int reason, const char *file, int line);+void ERR_put_error(int lib, int func, int reason, const char *file, int line) {+ (void)func; ERR_new(); ERR_set_debug(file, line, 0); ERR_set_error(lib, reason, 0);+}+SHIM_C+ cat > "$_shim/tramp.s" <<'SHIM_S'+.text+.globl EVP_MD_size+.type EVP_MD_size, @function+EVP_MD_size:+ jmp EVP_MD_get_size@PLT+.size EVP_MD_size, .-EVP_MD_size+.globl SSL_get_peer_certificate+.type SSL_get_peer_certificate, @function+SSL_get_peer_certificate:+ jmp SSL_get1_peer_certificate@PLT+.size SSL_get_peer_certificate, .-SSL_get_peer_certificate+.section .note.GNU-stack,"",@progbits+SHIM_S+ if ! ( cc -shared -fPIC -O2 -o "$_shim/libssl.so.1.1" \+ "$_shim/shim.c" "$_shim/tramp.s" -Wl,-soname,libssl.so.1.1 \+ -Wl,--no-as-needed -l:libssl.so.3 -l:libcrypto.so.3 && \+ cc -shared -fPIC -O2 -o "$_shim/libcrypto.so.1.1" \+ "$_shim/shim.c" "$_shim/tramp.s" -Wl,-soname,libcrypto.so.1.1 \+ -Wl,--no-as-needed -l:libcrypto.so.3 ) 2>/dev/null; then+ echo "note: could not build the OpenSSL 1.1 shim; set XC_PS4_LIBSSL11_DIR if PkgTool fails" >&2+ fi+ fi+ [ -f "$_shim/libssl.so.1.1" ] && export LD_LIBRARY_PATH="$_shim${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"+fi++TITLE="${XC_PS4_TITLE:-PSBox Cloud Gaming - PS4}"+VERSION="${XC_PS4_VERSION:-01.54}"+# 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}"+CONTENT_ID="${XC_PS4_CONTENT_ID:-IV0000-${TITLE_ID}_00-PSBOXCLOUDGAME00}"+FSELF_PAID="${XC_PS4_FSELF_PAID:-0x3800000000000011}"++ELF="$BUILD_DIR/xcloud_ps4.elf"+[ -f "$ELF" ] || { echo "error: $ELF not found (build with cmake/ps4.toolchain.cmake first)" >&2; exit 1; }++STAGE_DIR="$BUILD_DIR/pkg_stage"+rm -rf -- "$STAGE_DIR" "$OUT_DIR"+mkdir -p "$STAGE_DIR/sce_sys" "$STAGE_DIR/sce_module" "$STAGE_DIR/assets" "$OUT_DIR"++echo "==> eboot.bin"+if [ -n "${XC_PS4_FSELF_AUTH_INFO:-}" ]; then+ "$TOOLS/create-fself" -in="$ELF" -out="$STAGE_DIR/temp.oelf" --eboot "$STAGE_DIR/eboot.bin" --paid "$FSELF_PAID" --authinfo "$XC_PS4_FSELF_AUTH_INFO"+else+ "$TOOLS/create-fself" -in="$ELF" -out="$STAGE_DIR/temp.oelf" --eboot "$STAGE_DIR/eboot.bin" --paid "$FSELF_PAID"+fi+rm -f "$STAGE_DIR/temp.oelf"++echo "==> sce_sys"+cp "$REPO_DIR/ps4/sce_sys/icon0.png" "$STAGE_DIR/sce_sys/icon0.png"+if [ -f "$REPO_DIR/ps4/sce_sys/pic1.png" ]; then+ cp "$REPO_DIR/ps4/sce_sys/pic1.png" "$STAGE_DIR/sce_sys/pic1.png"+fi+if [ -f "$REPO_DIR/ps4/sce_sys/keystone" ]; then+ cp "$REPO_DIR/ps4/sce_sys/keystone" "$STAGE_DIR/sce_sys/keystone"+fi++if [ -f "$OO_PS4_TOOLCHAIN/samples/hello_world/sce_sys/about/right.sprx" ]; then+ mkdir -p "$STAGE_DIR/sce_sys/about"+ cp "$OO_PS4_TOOLCHAIN/samples/hello_world/sce_sys/about/right.sprx" "$STAGE_DIR/sce_sys/about/right.sprx"+fi++# Avoid bundling legacy libc.prx in sce_module unless explicitly requested,+# as overriding system libc causes CE-34878-0 crashes on retail PS4 firmwares (9.00/11.00).+if [[ ${XC_PS4_INCLUDE_SCE_MODULE:-0} == 1 ]]; then+ for m in libc.prx libSceFios2.prx; do+ if [ -f "$OO_PS4_TOOLCHAIN/samples/hello_world/sce_module/$m" ]; then+ cp "$OO_PS4_TOOLCHAIN/samples/hello_world/sce_module/$m" "$STAGE_DIR/sce_module/$m"+ fi+ done+fi++SFO="$STAGE_DIR/sce_sys/param.sfo"+"$TOOLS/PkgTool.Core" sfo_new "$SFO"+"$TOOLS/PkgTool.Core" sfo_setentry "$SFO" APP_TYPE --type Integer --maxsize 4 --value 1+"$TOOLS/PkgTool.Core" sfo_setentry "$SFO" APP_VER --type Utf8 --maxsize 8 --value "$VERSION"+"$TOOLS/PkgTool.Core" sfo_setentry "$SFO" ATTRIBUTE --type Integer --maxsize 4 --value 0+"$TOOLS/PkgTool.Core" sfo_setentry "$SFO" CATEGORY --type Utf8 --maxsize 4 --value 'gd'+"$TOOLS/PkgTool.Core" sfo_setentry "$SFO" CONTENT_ID --type Utf8 --maxsize 48 --value "$CONTENT_ID"+"$TOOLS/PkgTool.Core" sfo_setentry "$SFO" DOWNLOAD_DATA_SIZE --type Integer --maxsize 4 --value 0+"$TOOLS/PkgTool.Core" sfo_setentry "$SFO" SYSTEM_VER --type Integer --maxsize 4 --value 0+"$TOOLS/PkgTool.Core" sfo_setentry "$SFO" TITLE --type Utf8 --maxsize 128 --value "$TITLE"+"$TOOLS/PkgTool.Core" sfo_setentry "$SFO" TITLE_ID --type Utf8 --maxsize 12 --value "$TITLE_ID"+"$TOOLS/PkgTool.Core" sfo_setentry "$SFO" VERSION --type Utf8 --maxsize 8 --value "$VERSION"++echo "==> runtime assets"+cp -r "$REPO_DIR/assets/." "$STAGE_DIR/assets/"+rm -rf "$STAGE_DIR/assets/media_showcase"++mkdir -p "$STAGE_DIR/licenses"+cp "$REPO_DIR/LICENSE" "$STAGE_DIR/LICENSE"+cp "$REPO_DIR/THIRD_PARTY_NOTICES.md" "$STAGE_DIR/licenses/"+cp "$REPO_DIR/assets/fonts/OFL.txt" "$STAGE_DIR/licenses/Inter-OFL.txt"+cp "$REPO_DIR/deps/mbedtls/LICENSE" "$STAGE_DIR/licenses/mbedtls-LICENSE.txt"+cp "$REPO_DIR/deps/libdatachannel/LICENSE" "$STAGE_DIR/licenses/libdatachannel-MPL-2.0.txt"+cp "$REPO_DIR/deps/ffmpeg/COPYING.LGPLv2.1" "$STAGE_DIR/licenses/FFmpeg-LGPL-2.1.txt"+cp "$REPO_DIR/extern/stb/LICENSE" "$STAGE_DIR/licenses/stb-LICENSE.txt"++# Development only: XC_INCLUDE_ACCOUNT=1 ships the account.json+if [[ ${XC_INCLUDE_ACCOUNT:-0} == 1 && -f "$REPO_DIR/build-host/data/account.json" ]]; then+ cp "$REPO_DIR/build-host/data/account.json" "$STAGE_DIR/account.json"+fi++echo "==> building PKG"+( cd "$STAGE_DIR" && \+ FILES="$(find . -type f ! -name '*.gp4' ! -name '*.pkg' ! -name '*.oelf' ! -name '*.elf' | sed 's#^\./##' | tr '\n' ' ')" && \+ "$TOOLS/create-gp4" -out pkg.gp4 --content-id="$CONTENT_ID" --files "$FILES" && \+ python3 "$REPO_DIR/tools/ps4/gp4_rootdir.py" pkg.gp4 . && \+ "$TOOLS/PkgTool.Core" pkg_build pkg.gp4 "$OUT_DIR" )++mv -f "$OUT_DIR/${CONTENT_ID}.pkg" "$OUT_DIR/PSBox Cloud Gaming - PS4.pkg"++echo+echo "Package generated in: $OUT_DIR"+ls -lh "$OUT_DIR"diff --git a/tools/ps5/ps5_dev.py b/tools/ps5/ps5_dev.pyindex e5452b5..a1b43f0 100755--- a/tools/ps5/ps5_dev.py+++ b/tools/ps5/ps5_dev.py@@ -98,6 +98,8 @@ def cmd_verify(args):("Desktop (No-SDL) Unit Tests", "build-desktop-nosdl/xcloud-tests"),("PS5 Build", "ninja -C build-ps5 xcloud_app"),("PS5 Link Staged eboot.bin", "bash tools/ps5/link.sh build-ps5"),+ ("PS4 Build (OpenOrbis)", "ninja -C build-ps4"),+ ("PS4 Package (FSELF/PKG)", "bash tools/ps4/package.sh build-ps4"),("Platform Boundaries Check", "bash tools/check-platform-boundaries.sh"),]results = []