diff --git a/README.md b/README.md
index 3a9fc15..23cb8a2 100644
--- a/README.md
+++ b/README.md
@@ -17,6 +17,7 @@ Download the latest **Dissidia Recomp** from the [Releases page](https://github.
- **Frame rates** above the PSP's 30: any multiple of 30 up to 240, with game logic, UI and EX Burst timing scaled to match ([docs/frame-rate.md](psprecomp/games/dissidia/docs/frame-rate.md)).
- **HD textures** from community packs (on by default when present) and **undub audio** (Japanese voices and movies extracted from an undub disc) ([texture packs](psprecomp/games/dissidia/docs/texture-packs.md), [audio](psprecomp/games/dissidia/docs/audio.md)).
- **Cloud save sync** between devices through a folder, WebDAV or Google Drive ([docs/cloud-sync.md](psprecomp/games/dissidia/docs/cloud-sync.md)).
+- **Discord Rich Presence**: your Discord profile shows the mode, the fighters and the stage ([docs/discord.md](psprecomp/games/dissidia/docs/discord.md)).
- **Cross-region saves** and **internet multiplayer** (below).
- A headless battle test harness for checking moves at different frame rates ([docs/testing.md](psprecomp/games/dissidia/docs/testing.md)).
diff --git a/psprecomp/ARCHITECTURE.md b/psprecomp/ARCHITECTURE.md
index 17fe78c..5353eb9 100644
--- a/psprecomp/ARCHITECTURE.md
+++ b/psprecomp/ARCHITECTURE.md
@@ -169,6 +169,7 @@ All under `runtime/` (headers in `runtime/include/`, sources in `runtime/src/`):
| Settings menu | `psp_settings.{h,cpp}`, `src/hle/psp_settings_render.inc` (via `psp_savedata_dialog.cpp`), `include/psp_touch.h` | In-game menu (Esc / F1, Guide, L3+R3, the touch menu button, or `psp_settings_request_open()` from a game module's own menu entry). A category sidebar (Display, Graphics, Image, Effects, Controls (only with a touch screen), Network, Cloud, System, Drivers (only where `psp_gpu::supported`), Debug), a scrolling list of captioned rows (toggles, choices, sliders, actions, text fields, sub-menus: Image > HDR, Effects > Ray Tracing) and a description panel whose text scrolls by itself when long. `psp_settings.cpp` owns the state, applies and persists choices (`settings.ini`, exported as `PSPRECOMP_*` at the top of `main()`), and turns the page's `Row`s into a `psp_sddialog::SetScene`; `SettingsView` (`psp_settings_render.inc`, same painter, fonts and `SdTheme` as the save dialog) draws it at ~60 fps with animation (iris open / close, staggered panel slide, gliding selection and sliders, value pulses, drifting crystal motes) into the second overlay slot that `overlay_fetch` prefers, and remembers the geometry it drew (`SetGeom`) so pad, keyboard, mouse (hover, click, wheel, scroll-bar and slider drags, right click = Back) and touch (tap, drag-scroll with fling, sliders) hit-test the exact same rectangles; pointer positions are mapped through the picture rectangle (`ge_draw_overlay_rect`). While the menu is open the on-screen touch controls are hidden and let go (`psp_touch.cpp`), so fingers drive the menu directly. The frosted panels are drawn once per canvas scale into cached premultiplied layers and composited per frame, and the canvas scale drops automatically when a frame takes over 20 ms. Text entry (server, room, peers, sync folder, WebDAV) is an on-screen keyboard modal (pad, mouse, touch, or the host keyboard typing directly). While open the game is paused (guest threads wait in the vblank HLE, `psp_settings_guest_wait`), sees no input (and none until released after closing; the close animation keeps the game paused until it ends), and the main thread presents the last frame plus the menu (`ge_draw_present_overlay_now`). Render-scale changes resize every pool target in place, keeping its picture (`ge_draw_set_render_scale`), once a guest thread has parked, so no display list is mid-way. Frame rate is a game capability: a module registers `PspFrameRateHook` (Dissidia: `games/dissidia/runtime/framerate.cpp`); without one the row is hidden. Host test: `runtime/tests/run_settings_ui.sh` (`DUMP_SETTINGS=
` writes PPM frames). Game modules open it from the game's own menus (Dissidia: `games/dissidia/runtime/menu_settings.cpp`, which adds rows to the title, start and pause menus); elements they add to the game's screens are drawn on the game layer (`ge_draw_set_game_layer`, `psp_ge_draw.h`), a translucent image over the PSP picture under dialogs and touch controls that expires 0.15 s after the module stops sending it, with optional copies of parts of the game's own picture under it (`ge_draw_set_game_layer_copies`); `psp_texpack_watch` hands a module the HD image (either pack kind) the game got for a texture so added elements match the active texture pack |
| VFPU | `psp_vfpu_ops.cpp`, `psp_vfpu_core.cpp`, `vfpu_ppsspp/` | VFPU entry points called by recompiled code. `psp_vfpu_ops.cpp` builds the PSP opcode word from the emitter's decoded fields and runs PPSSPP's `InterpreterVFPU` (vendored in `vfpu_ppsspp/`, see its README) on a pointer view of `recomp_context`, so prefix lifetime, last-lane quirks, hardware min/max/sin/rcp/dot and conversions match the PSP. Replaced hand-written per-op files whose untested paths had diverged. `tests/run_vfpu_semantics.sh` diffs every entry point bit for bit against an unmodified PPSSPP checkout |
| Cloud sync | `src/hle/psp_cloudsync.{h,cpp}`, `psp_cloud_providers.{h,cpp}`, `psp_http.{h,cpp}`, `psp_cloud_service.{h,cpp}`, `psp_cloud_glue.{h,cpp}`, `assets/ca/`, `cmake/psp_mbedtls.cmake` | Keeps save folders in step between installs through a pluggable `Provider` (flat store of small named objects: a folder, WebDAV, Google Drive (a folder created in My Drive, `drive.file` scope)). Per slot, keyed by the region-neutral suffix, the cloud holds `.save` (container of the files that travel) and `.meta` (content hash of the data files, container checksum, mtime, device, disc ID; written last). `sync_all` is three-way against the hash recorded at the last sync: one side changed -> copy it, both changed or no history -> a conflict that is never resolved silently (`resolve_conflict`), nothing is ever deleted; pulls retarget and re-sign `PARAM.SFO` through `psp_savemgr::copy_save` and move the replaced save to `SAVEDATA_BACKUP`. `psp_http` is a blocking HTTP/1.1 client (HTTPS via mbedTLS 3.6 with the embedded Mozilla CA bundle, full certificate and host name verification; mbedTLS is optional at build time, without it https reports an error); `psp_cloud_service` owns `cloud.ini` (mode 0600, secrets), a worker thread and the status, and runs a full sync at start-up, one a few seconds after each save (debounced), and one on request. The savedata HLE waits for the start-up sync before the first save dialog (`psp_cloud_glue`) and the Manage saves screen and Settings > Cloud page are thin clients of the service. Decisions: secrets stay out of `settings.ini`; the CA bundle is embedded so Windows, Linux and Android verify identically; a conflict needs the user because a silent newest-wins loses progress. Usage and setup: [games/dissidia/docs/cloud-sync.md](games/dissidia/docs/cloud-sync.md) |
+| Discord Rich Presence | `include/psp_discord.h`, `src/psp_discord.cpp` | Speaks the Discord desktop app's local IPC directly (Unix socket `discord-ipc-N` / Windows named pipe; length-prefixed JSON frames: handshake, `SET_ACTIVITY`, ping / pong), no SDK. One background thread owns the connection, polls the game module's `psp_discord::Provider` once a second and sends only changes, at most one per 4 s (Discord's rate limit), reconnecting with back-off when Discord is absent or restarts; the activity is cleared on quit (`main()`) and when switched off (Settings > Network, `discord=`). The provider runs on that thread, so it may only read guest RAM words and atomics. The game decides the content and the Discord application id (Dissidia: `games/dissidia/runtime/discord_presence.cpp`). No-op on Android (no Discord IPC there). Decision: a raw IPC client instead of the Discord SDK keeps the build free of a closed binary and works the same on Linux, Windows and macOS. Details: [games/dissidia/docs/discord.md](games/dissidia/docs/discord.md) |
| Ad-hoc networking | `include/hle/psp_hle_adhoc.h`, `src/hle/psp_hle_adhoc.cpp` | Emulates the PSP ad-hoc stack over UDP: `sceNetAdhocctl*` (groups, peers, handlers), `sceNetAdhocMatching*` (the lobby state machine), `sceNetAdhoc` PDP datagrams and PTP streams, plus the Wlan/net MAC helpers. Registered after the utility module so it overrides that module's no-op `sceNet*` stubs (`PSPRECOMP_ADHOC=0` leaves the stubs). One UDP socket and one network thread; state shared with guest threads is behind a single mutex. Two modes: **LAN** (beacons to local ports, the broadcast address, `PSPRECOMP_ADHOC_PEERS` and gossiped addresses) and **Internet** (the default: every packet goes to a relay server, `tools/adhoc_relay`, which registers the client into a room with a cookie handshake and forwards beacons to the room and other packets by destination MAC; only the server's address is accepted as a source). A peer expires after 4 s. `psp_adhoc_configure()` / `psp_adhoc_status()` let the settings menu switch mode, server and room at run time. The virtual MAC is random per launch. PTP is a small TCP-like stream: every packet carries a connection id, SYN with no listener is refused, sends are partial like `send()`. Recompiled-code callbacks (adhocctl handlers, the matching callback) must run on a guest thread, so the network thread only queues them and `psp_adhoc_pump()` runs them from `sceKernelCheckCallback` and the vblank wait, saving and restoring the caller's argument registers. Exposes `psp_adhoc_group_fps_cap()` / `psp_adhoc_set_local_fps()` so a game module can run a session at the lowest frame rate any player wants (used by `games/dissidia/runtime/framerate.cpp`). The module is generic; the title only decides frame rate. Usage, options and protocol: [games/dissidia/docs/multiplayer.md](games/dissidia/docs/multiplayer.md) |
| Debug socket | `psp_debug_socket.cpp` | TCP server on port 9999, multiple concurrent clients, OK/ERR-framed line protocol: memory read/write, runtime-info JSON, button injection, screenshots (serviced by the render thread), fast-forward. Protocol reference: DEBUGGING.md §6 |
| Game clock | `hle/psp_hle_display.cpp` | The 60 Hz vblank timeline the game is paced by (`sceDisplayWaitVblankStart` sleeps to the next boundary) and the vcount / system time it reads (`psp_hle_kernel_thread.cpp`). Both are the host clock plus a skew that only grows: fast-forward (`FF`) advances the skew to the next boundary instead of sleeping, so the game runs as fast as frames render and time never goes back when it stops (`FF x` gives each frame at least 1/x of the game time it covers on the host clock: at most x times real time, for screens with idle timers). A movie keeps its own pace: its picture follows its sound, which plays in real time. `PSPRECOMP_VCLOCK=1` replaces the clock with one that advances a vblank per wait |
diff --git a/psprecomp/games/dissidia/docs/README.md b/psprecomp/games/dissidia/docs/README.md
index 30f4e46..5c900a0 100644
--- a/psprecomp/games/dissidia/docs/README.md
+++ b/psprecomp/games/dissidia/docs/README.md
@@ -16,6 +16,7 @@ Everything about the game itself, the native build and the modding tools, in one
- [multiplayer.md](multiplayer.md): Communications mode over UDP (LAN, one machine, internet), options, how the ad-hoc stack is emulated.
- [savedata.md](savedata.md): saves between regions: `savemgr` list / import / export.
- [cloud-sync.md](cloud-sync.md): saves between devices through a folder, WebDAV or Google Drive.
+- [discord.md](discord.md): Discord Rich Presence (mode, fighters, stage, the other players on your Discord profile).
- [testing.md](testing.md): the battle test harness, frame-rate parity tests, testing on a phone or a Deck.
## Making characters
diff --git a/psprecomp/games/dissidia/docs/discord.md b/psprecomp/games/dissidia/docs/discord.md
new file mode 100644
index 0000000..720d044
--- /dev/null
+++ b/psprecomp/games/dissidia/docs/discord.md
@@ -0,0 +1,71 @@
+# Discord Rich Presence
+
+With the Discord desktop app running on the same computer, your Discord profile shows what you are doing in the game:
+
+```
+Playing Dissidia 012 Duodecim
+Quick Battle (1-on-1) · Order's Sanctuary
+Squall vs. Kefka (2 of 2)
+03:12 elapsed
+[ Dissidia Recomp on GitHub ]
+```
+
+| Where you are | First line | Second line | Timer |
+|---|---|---|---|
+| Title screen | Title Screen | | since the game started |
+| Start menu (and its Battle Mode / Communications lists) | Main Menu | | since the game started |
+| After choosing a mode | the mode: Story Mode, Quick Battle (1-on-1), Quick Battle (Party), Arcade Mode, Labyrinth, Communications Mode, PP Catalog, Collection, Data Config, Options | | since the game started |
+| In a fight | the mode · the stage | your fighter vs. the opponent (manikins by their own names: Transient Lion, ...) | since the fight started |
+| In a Communications Mode group (lobby, room) | Communications Mode | With Zack (or "With Zack, Cloud and 2 others") plus "(n of n)" | as above |
+| One-on-one against another player | Communications Mode · the stage | Ender (Lightning) vs. Zack (Laguna) | since the fight started |
+
+The large picture is the game's icon; hovering it shows the Dissidia Recomp version, or in a group every player's name ("Players: Ender
+and Zack"). Players are named by the player name of their save (Data Config > Player Name): each copy of the game sends it to the
+others as its ad-hoc nickname (it was "Player" before), so the game's own lists of nearby players show it too. Everyone in one room gets
+the same Discord party, so Discord shows them together. Your Discord name is never sent to other players. Characters added with `roster.txt` show their
+`nm=` name (else their code). Stages without a confirmed name (labyrinth floors, a few story-only arenas) are left out.
+
+## Turning it off
+
+Settings > Network > **Discord Status** (On / Off, saved as `discord=` in `settings.ini`). The **Discord** row under it says whether the
+app was found ("Connected as ...", "Discord is not running", ...). Turning it off clears what Discord shows at once. Nothing is sent
+anywhere but to the Discord app on this computer, and Discord only shows it while the game runs.
+
+| Option | Effect |
+|---|---|
+| `PSPRECOMP_DISCORD=0` | off (the saved setting wins) |
+| `PSPRECOMP_DISCORD_APP_ID=` | another Discord application (its name is the "Playing ..." line) |
+| `PSPRECOMP_DISCORD_LOG=1` | log every message to and from Discord |
+| `PSPRECOMP_DISCORD_IPC=` | use this socket / pipe instead of searching (tests) |
+
+Not on Android: the Discord phone app has no local connection for games. On a Steam Deck it works in Desktop Mode with Discord running;
+in Game Mode only if Discord runs in the background.
+
+## How it works
+
+`runtime/src/psp_discord.cpp` (generic, no Discord SDK) talks to the desktop app over its local IPC: a Unix socket `discord-ipc-0..9`
+in `$XDG_RUNTIME_DIR`, `$TMPDIR` or `/tmp` (also the Flatpak, Snap and Vesktop sub-folders), or the named pipe
+`\\.\pipe\discord-ipc-0..9` on Windows. Frames are `{u32 opcode, u32 length, JSON}`: a handshake with the application id, then
+`SET_ACTIVITY` commands; pings are answered. One background thread owns the connection. Once a second it asks the game module what to
+show and sends it when it changed, at most once every 4 s (Discord drops more than 5 updates in 20 s; the newest state always goes out).
+If Discord is not running, quits or restarts, the thread looks again after 5 s, doubling up to 60 s; the game never waits for it. On quit
+and when turned off the activity is cleared.
+
+`games/dissidia/runtime/discord_presence.cpp` decides what to show:
+
+- **Menus.** `menu_settings.cpp` reports every frame the title screen, the start menu (`ovl_menu` FUN_089E45E8; cursor at state +0xA28
+ +4) or its sub-list (FUN_089E4A60; group at state +0xA88, cursor at +0xA58 +4) updates. The rows they were on when the start menu was
+ left are the chosen mode, kept until the start menu shows again.
+- **Fights.** `framerate.cpp` keeps the fighters on stage; each fighter's object record (actor +0x2F8) gives its charId (+6) and model
+ type (+8, 5 = manikin), and the brain (actor +0x5C4, +0x54 != 0) tells which one a person drives. charIds follow the EBOOT code
+ table at 0x089D6CA8 (one100 .. sev120). The stage is `psp_stage_id()` (the battle setup word, hooks_main.cpp), named from the game's
+ own text (`text/en/mess_pk_loading_0.bin` entry 3).
+- **Online.** The save's player name is UTF-16 at 0x08BCEB40 (EBOOT BSS; found by changing it in RAM and watching Data Config follow,
+ the copy at 0x08BDC4BC is a stale duplicate). The start menu hands it to `psp_adhoc_set_nickname` (every Communications session starts
+ there; `PSPRECOMP_ADHOC_NICK` still wins). `psp_adhoc_group_size()` / `psp_adhoc_group_nicks()` give the other players, and
+ `psp_adhoc_group_key()` (room + the game's group name) a party id everyone in the room shares. Which fighter is yours: actor +0x5B0
+ bit 0x04 (…35 against …31; found by diffing two copies in one Group Battle, the same in single player). The brain's human mode is set
+ for the other players' fighters too, so it is only the fallback.
+
+Test: `runtime/tests/test_discord.cpp` (ctest `discord`) checks the JSON and runs a whole session against a fake Discord app on a Unix
+socket: handshake, first activity, rate limit, ping, off / on, Discord restarting, clearing on quit.
diff --git a/psprecomp/games/dissidia/docs/multiplayer.md b/psprecomp/games/dissidia/docs/multiplayer.md
index 0593e4e..04af54b 100644
--- a/psprecomp/games/dissidia/docs/multiplayer.md
+++ b/psprecomp/games/dissidia/docs/multiplayer.md
@@ -91,7 +91,7 @@ both run at 30. It returns to the player's own setting when the group ends. A me
| `PSPRECOMP_ADHOC_PORT=` | LAN mode: first UDP port (default 27312) |
| `PSPRECOMP_ADHOC_SPAN=` | how many consecutive ports are tried and probed (default 16, up to 64) |
| `PSPRECOMP_ADHOC_PEERS=a,b` | LAN mode: extra peers to contact directly: `host` or `host:port` (a bare host probes the whole port span) |
-| `PSPRECOMP_ADHOC_NICK=` | nickname other adhocctl clients see (the in-game player name comes from the save) |
+| `PSPRECOMP_ADHOC_NICK=` | nickname other adhocctl clients see (default: the save's player name once a save is loaded, else "Player"; Discord status names players by it) |
| `PSPRECOMP_ADHOC_MAC=aa:bb:cc:dd:ee:ff` | virtual MAC; default is random per launch (a host-name hash collides: every Steam Deck is called `steamdeck`) |
| `PSPRECOMP_ADHOC_LOG=1` | log every call and event with arguments, results and the first bytes of each message |
| `PSPRECOMP_PAD_BACKGROUND=1` | let controllers act while the window is unfocused |
diff --git a/psprecomp/games/dissidia/docs/settings-menu.md b/psprecomp/games/dissidia/docs/settings-menu.md
index 40b3f8b..9d16c84 100644
--- a/psprecomp/games/dissidia/docs/settings-menu.md
+++ b/psprecomp/games/dissidia/docs/settings-menu.md
@@ -32,6 +32,9 @@ Changes marked **Next start** ask "Restart now / Later" when the menu is closed.
The **Mods** category lists mod folders with a `mod.json` (the repo's `mods/`, `PSPRECOMP_MODS_SRC`, and the game's mods folder) and extra
characters from the mods folder's `roster.txt`. A switch writes `"enabled"` into `mod.json`, or puts `#off# ` in front of the roster line.
+The **Network** category also has a **Discord** section (not on Android): **Discord Status** On / Off (applies at once, saved) and a
+connection line; see [discord.md](discord.md).
+
The screen is drawn by up to 8 threads in horizontal bands (`PSPRECOMP_SETTINGS_THREADS=N` to change, 1 = one thread);
`PSPRECOMP_SETTINGS_PROFILE=1` logs the drawing time per part.
diff --git a/psprecomp/games/dissidia/runtime/discord_presence.cpp b/psprecomp/games/dissidia/runtime/discord_presence.cpp
new file mode 100644
index 0000000..6c11de5
--- /dev/null
+++ b/psprecomp/games/dissidia/runtime/discord_presence.cpp
@@ -0,0 +1,275 @@
+// games/dissidia/runtime/discord_presence.cpp — what Discord shows while Dissidia 012 runs (Rich Presence, runtime/src/psp_discord.cpp).
+//
+// Dissidia 012 Duodecim <- the Discord application's name
+// Quick Battle (1-on-1) · Order's Sanctuary
+// Squall vs. Kefka (2 of 2 when in a Communications Mode group)
+// 03:12 elapsed <- since the fight started; outside fights since the game started
+//
+// Where the player is comes from the start menu's own cursors (menu_settings.cpp reports them every frame the start menu or its
+// sub-list updates): leaving the start menu with the cursor on Story Mode, Battle Mode > Arcade Mode, ... sets the mode until the
+// start menu shows again. The title screen reports itself the same way. In a fight (battle overlay with fighters, framerate.cpp
+// keeps the list) the fighters' characters (actor -> object record charId / type, 5 = manikin) and the stage (psp_stage_id) are
+// added. All of it is read on the presence thread once a second: guest RAM words and atomics only.
+//
+// Names: the game's own English text (text/en/mess_pk_loading_0.bin entries 1 and 3). charId order = the EBOOT code table at
+// 0x089D6CA8 (one100 .. sev120); characters added with roster.txt use their nm= label. Stage ids (the battle setup word read by
+// hooks_main.cpp's dissidia_stage_id) were matched to maps in the issue #2 stage runs (docs/rendering notes); ids without a
+// confirmed map (2, 13, 14, labyrinth floors) show no stage.
+#include "psp_discord.h"
+#include "psp_screenfx.h"
+#include "psp_settings.h"
+#include "hle/psp_hle_adhoc.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+int dissidia_live_fighters(uint32_t* out, int max); // framerate.cpp
+int dissidia_fighter_char_id(uint32_t actor);
+int dissidia_fighter_model_type(uint32_t actor);
+bool dissidia_fighter_human(uint32_t actor);
+uint32_t dissidia_fighter_brain_mode(uint32_t actor);
+bool dissidia_fighter_local(uint32_t actor);
+std::string dissidia_roster_name(int char_id); // roster.cpp
+std::string psp_release_version(); // runtime/src/psp_ge_draw.cpp
+
+namespace {
+
+// The Discord application ("Dissidia 012 Duodecim", developer portal). Its name is the first line Discord shows.
+// PSPRECOMP_DISCORD_APP_ID overrides it.
+constexpr const char* kAppId = "1571969529272213605";
+constexpr const char* kIcon = "https://raw.githubusercontent.com/schindlershadow/dissidia/main/psprecomp/games/dissidia/icon/icon.png";
+constexpr const char* kProjectUrl = "https://github.com/schindlershadow/dissidia";
+
+constexpr uint32_t OVL_BASE = 0x089DD4C0u; // loaded overlay id: 1 battle, 2 menu
+uint8_t* g_ram = nullptr;
+uint32_t r32(uint32_t a) { uint32_t v; std::memcpy(&v, g_ram + (a & 0x07FFFFFFu), 4); return v; }
+
+// charId (1..33) -> name; the manikin ("type 5" model) of the same character
+const char* const kChars[34] = {nullptr,
+ "Warrior of Light", "Garland", "Firion", "The Emperor", "Onion Knight", "Cloud of Darkness", "Cecil", "Golbez", "Bartz", "Exdeath",
+ "Terra", "Kefka", "Cloud", "Sephiroth", "Squall", "Ultimecia", "Zidane", "Kuja", "Tidus", "Jecht", "Shantotto", "Gabranth", "Chaos",
+ "Kain", "Gilgamesh", "Tifa", "Laguna", "Yuna", "Prishe", "Vaan", "Lightning", "Feral Chaos", "Aerith"};
+const char* const kManikins[34] = {nullptr,
+ "False Hero", "False Stalwart", "Imitation Liegeman", "Imitation Despot", "Counterfeit Youth", "Counterfeit Wraith", "Delusory Knight",
+ "Delusory Warlock", "Fallacious Wanderer", "Fallacious Tree", "Phantasmal Girl", "Phantasmal Harlequin", "Imaginary Soldier",
+ "Imaginary Champion", "Transient Lion", "Transient Witch", "Capricious Thief", "Capricious Reaper", "Ephemeral Vision",
+ "Ephemeral Phantom", "Lady of Antiquity", "Warrior of Antiquity", nullptr, "Delusory Dragoon", "Fallacious Giant", "Imaginary Brawler",
+ "Transient Gunner", "Ephemeral Summoner", "Horror of Antiquity", "Idle Sky Pirate", "Fleeting Flash", nullptr, nullptr};
+
+// battle setup stage id -> stage
+const char* stage_name(int id) {
+ switch (id) {
+ case 0: return "Old Chaos Shrine";
+ case 1: return "Pandaemonium";
+ case 3: return "World of Darkness";
+ case 4: return "Lunar Subterrane";
+ case 5: return "The Rift";
+ case 6: return "Kefka's Tower";
+ case 7: return "Planet's Core";
+ case 8: return "Ultimecia's Castle";
+ case 9: return "Crystal World";
+ case 10: return "Dream's End";
+ case 11: return "Edge of Madness";
+ case 12: return "Order's Sanctuary";
+ case 15: return "Empyreal Paradox";
+ case 16: return "Sky Fortress Bahamut";
+ case 17: return "Orphan's Cradle";
+ case 18: return "Phantom Train";
+ case 19: return "M.S. Prima Vista";
+ case 20: return "Crystal Tower";
+ case 21: return "Pandaemonium - Top Floor";
+ default: return nullptr;
+ }
+}
+
+std::string fighter_name(uint32_t actor) {
+ const int id = dissidia_fighter_char_id(actor);
+ if (id < 1) return "";
+ const std::string mod = dissidia_roster_name(id);
+ if (!mod.empty()) return mod;
+ if (id >= 34) return "";
+ if (dissidia_fighter_model_type(actor) == 5 && kManikins[id]) return kManikins[id];
+ return kChars[id] ? kChars[id] : "";
+}
+
+// ---- the player's name: the save's player name (Data Config > Player Name), UTF-16 at a fixed EBOOT BSS address; found by
+// changing it in RAM and watching Data Config follow (the copy at 0x08BDC4BC is a stale duplicate). Empty before a save is loaded.
+constexpr uint32_t PLAYER_NAME = 0x08BCEB40u;
+constexpr int kNameUnits = 16;
+std::string player_name() {
+ std::string out;
+ for (int i = 0; i < kNameUnits; i++) {
+ uint16_t c;
+ std::memcpy(&c, g_ram + ((PLAYER_NAME + 2u * i) & 0x07FFFFFFu), 2);
+ if (c == 0) break;
+ if (c < 0x20 || (c >= 0xD800 && c <= 0xDFFF) || c == 0xFFFF) return ""; // not text: no save loaded (or not this layout)
+ if (c < 0x80) out += char(c);
+ else if (c < 0x800) { out += char(0xC0 | (c >> 6)); out += char(0x80 | (c & 0x3F)); }
+ else { out += char(0xE0 | (c >> 12)); out += char(0x80 | ((c >> 6) & 0x3F)); out += char(0x80 | (c & 0x3F)); }
+ }
+ while (!out.empty() && out.back() == ' ') out.pop_back();
+ return out;
+}
+// Other players see this name (the ad-hoc nickname, "Player" until a save is loaded). Called on the game thread from the start menu
+// (every Communications Mode session starts there, and a name changed in Data Config comes back through it).
+void update_nickname() {
+ static std::string last = "\x01";
+ const std::string n = player_name();
+ if (n == last) return;
+ last = n;
+ psp_adhoc_set_nickname(n.c_str());
+}
+
+// "Bob", "Bob and Carl", "Bob, Carl and Dan", ... cut to fit `max` bytes ("and 2 others").
+std::string name_list(const std::vector& names, size_t max) {
+ for (size_t shown = names.size(); shown > 0; shown--) {
+ std::string s;
+ for (size_t i = 0; i < shown; i++) {
+ if (i) s += (i + 1 == shown && shown == names.size()) ? " and " : ", ";
+ s += names[i];
+ }
+ if (shown < names.size()) s += " and " + std::to_string(names.size() - shown) + (names.size() - shown == 1 ? " other" : " others");
+ if (s.size() <= max) return s;
+ }
+ return std::to_string(names.size()) + " players";
+}
+
+uint64_t fnv1a(const std::string& s) {
+ uint64_t h = 1469598103934665603ull;
+ for (unsigned char c : s) { h ^= c; h *= 1099511628211ull; }
+ return h;
+}
+
+// ---- where the player is (menu_settings.cpp reports, the presence thread reads) ----
+int64_t now_ms() {
+ return std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()).count();
+}
+std::atomic g_title_ms{0}, g_main_ms{0}, g_sub_ms{0};
+std::atomic g_top{-1}, g_group{0}, g_sub{-1};
+int64_t g_session_start = 0; // unix seconds
+
+// Top-level rows of the start menu (mess_pk_start_menu entries; row 7 is this port's Settings) and Battle Mode's sub-list.
+const char* const kTop[7] = {"Story Mode", "Battle Mode", "Communications Mode", "PP Catalog", "Collection", "Data Config", "Options"};
+const char* const kBattleRows[4] = {"Quick Battle (1-on-1)", "Quick Battle (Party)", "Arcade Mode", "Labyrinth"};
+
+// The mode chosen when the start menu was left (nullptr: none / unknown).
+const char* chosen_mode() {
+ const int top = g_top.load();
+ if (top == 1 && g_group.load() == 1 && g_sub_ms.load() + 500 >= g_main_ms.load()) {
+ const int s = g_sub.load();
+ if (s >= 0 && s < 4) return kBattleRows[s];
+ }
+ return top >= 0 && top < 7 ? kTop[top] : nullptr;
+}
+
+// The current fight, kept while the battle overlay stays loaded (the fighter list goes stale while the game's pause menu is up).
+struct Fight { bool on = false; int64_t start = 0; std::string a, b; int stage = -1; std::string log; };
+Fight g_fight;
+
+bool provide(psp_discord::Activity* out) {
+ if (!g_ram) return false;
+ const int64_t t = now_ms();
+ out->large_image = kIcon;
+ out->large_text = "Dissidia Recomp " + psp_release_version();
+ out->buttons = {{"Dissidia Recomp on GitHub", kProjectUrl}};
+ const int group = psp_adhoc_group_size();
+ std::vector others;
+ if (group >= 2) {
+ others = psp_adhoc_group_nicks();
+ char id[32];
+ std::snprintf(id, sizeof id, "dissidia-%016llx", static_cast(fnv1a(psp_adhoc_group_key())));
+ out->party_id = id; // the same for everyone in the room: Discord shows them as one party
+ out->party_size = group; out->party_max = group;
+ std::string me = player_name();
+ std::vector all{me.empty() ? std::string("You") : me};
+ all.insert(all.end(), others.begin(), others.end());
+ out->large_text = "Players: " + name_list(all, 118);
+ }
+ out->start = g_session_start;
+
+ const uint32_t ovl = r32(OVL_BASE);
+ if (ovl != 1) g_fight = Fight{};
+ if (t - g_title_ms.load() < 1500) { out->details = "Title Screen"; return true; }
+ if (ovl == 2 && (t - g_main_ms.load() < 1500 || t - g_sub_ms.load() < 1500)) { out->details = "Main Menu"; return true; }
+
+ const char* mode = chosen_mode();
+ std::string details = mode ? mode : (group >= 2 ? "Communications Mode" : "");
+ if (ovl == 1) {
+ uint32_t f[4];
+ const int n = dissidia_live_fighters(f, 4);
+ if (n >= 2) {
+ if (!g_fight.on) { g_fight.on = true; g_fight.start = std::time(nullptr); }
+ // The player's side: the fighter this copy's player drives (online the other players' fighters are pad-driven too), else the
+ // first human-driven one. Both are set during the intro, so the names wait for them (the intro at normal speed takes over 6 s;
+ // a CPU-only fight is named after 30 s in list order).
+ int me = -1;
+ for (int i = 0; i < n && me < 0; i++) if (dissidia_fighter_local(f[i])) me = i;
+ for (int i = 0; i < n && me < 0; i++) if (dissidia_fighter_human(f[i])) me = i;
+ static const bool log = std::getenv("PSPRECOMP_DISCORD_LOG") != nullptr;
+ if (log) { // which fighter is whose (online: is the remote player's fighter "human" too?)
+ std::string l;
+ char b[96];
+ for (int i = 0; i < n; i++) {
+ std::snprintf(b, sizeof b, " [%08X char %d type %d brain %X local %d]", f[i], dissidia_fighter_char_id(f[i]), dissidia_fighter_model_type(f[i]),
+ dissidia_fighter_brain_mode(f[i]), dissidia_fighter_local(f[i]) ? 1 : 0);
+ l += b;
+ }
+ if (l != g_fight.log) { g_fight.log = l; std::fprintf(stderr, "[DISCORD] fighters:%s me %d\n", l.c_str(), me); }
+ }
+ if (me < 0 && std::time(nullptr) - g_fight.start >= 30) me = 0;
+ if (me >= 0) {
+ const std::string a = fighter_name(f[me]), b = fighter_name(f[me == 0 ? 1 : 0]);
+ if (!a.empty()) g_fight.a = a;
+ if (!b.empty()) g_fight.b = b;
+ }
+ g_fight.stage = psp_stage_id();
+ }
+ if (g_fight.on) {
+ if (const char* st = stage_name(g_fight.stage)) details += (details.empty() ? "" : " \xC2\xB7 ") + std::string(st); // " · "
+ if (!g_fight.a.empty() && !g_fight.b.empty()) {
+ out->state = g_fight.a + " vs. " + g_fight.b;
+ const std::string me = player_name();
+ if (others.size() == 1 && !me.empty()) { // one on one online: who is who
+ const std::string named = me + " (" + g_fight.a + ") vs. " + others[0] + " (" + g_fight.b + ")";
+ if (named.size() <= 128) out->state = named;
+ }
+ }
+ out->start = g_fight.start;
+ }
+ }
+ if (details.empty()) details = "In the menus";
+ if (out->state.empty() && !others.empty()) out->state = "With " + name_list(others, 123);
+ out->details = details;
+ return true;
+}
+
+} // namespace
+
+// menu_settings.cpp: the title screen / the start menu's top level / its sub-list updated this frame.
+void dissidia_presence_title() { g_title_ms.store(now_ms()); }
+void dissidia_presence_main(uint32_t state) {
+ if (!g_ram || !state) return;
+ g_top.store(int(r32(state + 0xA28u + 4u)));
+ update_nickname();
+ g_main_ms.store(now_ms());
+}
+void dissidia_presence_sub(uint32_t state) {
+ if (!g_ram || !state) return;
+ g_group.store(int(r32(state + 0xA88u)));
+ g_sub.store(int(r32(state + 0xA58u + 4u)));
+ g_sub_ms.store(now_ms());
+}
+
+void dissidia_discord_install(uint8_t* rdram) {
+ g_ram = rdram;
+ g_session_start = std::time(nullptr);
+ psp_discord::start(kAppId, provide);
+}
diff --git a/psprecomp/games/dissidia/runtime/framerate.cpp b/psprecomp/games/dissidia/runtime/framerate.cpp
index 57d0c54..417f64f 100644
--- a/psprecomp/games/dissidia/runtime/framerate.cpp
+++ b/psprecomp/games/dissidia/runtime/framerate.cpp
@@ -2000,6 +2000,38 @@ uint32_t dissidia_player_actor() {
return last && ok(last) && g_ram[(last + 0x542u) & 0x07FFFFFFu] == 0 ? last : 0u;
}
+// The fighters on stage now (updated within the last 2 s), for discord_presence.cpp: fills up to `max` actors, returns the count.
+// Safe to call from another thread (it only reads words that the game thread writes whole).
+int dissidia_live_fighters(uint32_t* out, int max) {
+ int n = 0;
+ if (overlay_id() != 1) return 0;
+ for (int i = 0; i < 4 && n < max; i++) {
+ const uint32_t a = g_fighters[i];
+ if (!a || !ok(a) || g_tick - g_fighter_seen[i] > 120 || g_ram[(a + 0x542u) & 0x07FFFFFFu] != 0) continue;
+ out[n++] = a;
+ }
+ return n;
+}
+// charId of a fighter (-99 = unknown) and the object-table type of its model (actor +0x2F8 -> its object record: +6 charId,
+// +8 type: 0 player, 5 manikin), and whether a person drives it (brain +0x54 != 0, as dissidia_player_actor).
+int dissidia_fighter_char_id(uint32_t a) { return ok(a) ? fighter_char(a) : -99; }
+int dissidia_fighter_model_type(uint32_t a) {
+ const uint32_t info = ok(a) ? r32(a + 0x2F8u) : 0u;
+ return ok(info) ? g_ram[(info + 8u) & 0x07FFFFFFu] : -1;
+}
+// The fighter this copy's player drives: actor +0x5B0 bit 0x04 (0x...35 vs 0x...31; +0x760 is only set on it too). Unlike the brain's
+// human mode (+0x54, set for every pad-driven fighter, the remote players' too) it tells the local player apart in Communications Mode
+// (found by diffing two copies in one Group Battle; the same in a single-player Quick Battle).
+bool dissidia_fighter_local(uint32_t a) { return ok(a) && (r32(a + 0x5B0u) & 0x4u) != 0; }
+uint32_t dissidia_fighter_brain_mode(uint32_t a) { // brain +0x54 (0 = CPU), for logs
+ const uint32_t brain = ok(a) ? r32(a + 0x5C4u) : 0u;
+ return ok(brain) ? r32(brain + 0x54u) : 0xFFFFFFFFu;
+}
+bool dissidia_fighter_human(uint32_t a) {
+ const uint32_t brain = ok(a) ? r32(a + 0x5C4u) : 0u;
+ return ok(brain) && r32(brain + 0x54u) != 0;
+}
+
// Ticks (1/60 s) one game frame advances: 2 at 30 Hz, 1 at 60 Hz, 2/3 at 90 Hz, 0.5 at 120 Hz.
float dissidia_frame_ticks() { return g_ticks; }
// Factor for a value the game keeps as "ticks per 30 Hz frame" (the actor own clock): 1 at 30 Hz, 0.5 at 60 Hz.
diff --git a/psprecomp/games/dissidia/runtime/hooks_main.cpp b/psprecomp/games/dissidia/runtime/hooks_main.cpp
index 89e0497..e47433d 100644
--- a/psprecomp/games/dissidia/runtime/hooks_main.cpp
+++ b/psprecomp/games/dissidia/runtime/hooks_main.cpp
@@ -59,6 +59,7 @@ extern void dissidia_wpnp_install();
// camera.cpp: analogue right-stick battle camera.
extern void dissidia_camera_install(uint8_t* rdram);
extern void dissidia_menu_settings_install(uint8_t* rdram);
+extern void dissidia_discord_install(uint8_t* rdram); // discord_presence.cpp
// direct_battle.cpp: test-only, skips the menus (PSPRECOMP_TEST_DIRECT_BATTLE=1).
extern void dissidia_direct_battle_install(uint8_t* rdram);
// input.cpp: continuous analogue stick direction (the game's own processing is 8-way).
@@ -356,6 +357,7 @@ void dissidia_register_hooks(uint8_t* rdram) {
dissidia_direct_battle_install(rdram); // direct_battle.cpp
dissidia_camera_install(rdram); // camera.cpp (wraps a battle-overlay function too)
dissidia_menu_settings_install(rdram); // menu_settings.cpp: Settings entries in the title / start menu / pause menu
+ dissidia_discord_install(rdram); // discord_presence.cpp: Discord Rich Presence
dissidia_input_install(rdram); // input.cpp
dissidia_framerate_install(rdram); // framerate.cpp (wraps a battle-overlay function too)
diff --git a/psprecomp/games/dissidia/runtime/menu_settings.cpp b/psprecomp/games/dissidia/runtime/menu_settings.cpp
index 91c7883..8736cf0 100644
--- a/psprecomp/games/dissidia/runtime/menu_settings.cpp
+++ b/psprecomp/games/dissidia/runtime/menu_settings.cpp
@@ -38,6 +38,9 @@ std::string dissidia_package_dir(); // hooks_io.cpp
std::string dissidia_mods_dir();
extern FuncPtr ovl_battle_lookup(uint32_t vaddr);
extern FuncPtr ovl_menu_lookup(uint32_t vaddr);
+void dissidia_presence_title(); // discord_presence.cpp: where the player is
+void dissidia_presence_main(uint32_t state);
+void dissidia_presence_sub(uint32_t state);
namespace {
@@ -294,6 +297,7 @@ void main_tick_hook(uint8_t* rdram, recomp_context* ctx) {
}
g_main_state = state;
g_main_seen_frames = 0;
+ dissidia_presence_main(state);
if (state && r32(cur + 4) == 7 && r32(cur + 36) == 7 && !psp_settings_menu_open() && confirm_pressed(rdram, ctx)) {
call(g_play_se, rdram, ctx, {2});
std::fprintf(stderr, "[MENUSET] Settings chosen in the start menu\n");
@@ -315,6 +319,18 @@ void main_tick_hook(uint8_t* rdram, recomp_context* ctx) {
}
+// The start menu's sub-lists (group at state + 0xA88: 1 Battle Mode, 2 Communications Mode; cursor helper at state + 0xA58, +4 index)
+// are updated by ovl_menu FUN_089E4A60; the row the cursor is on is reported for Discord (discord_presence.cpp).
+constexpr uint32_t SUB_TICK = 0x089E4A60u;
+FuncPtr g_orig_sub_tick = nullptr;
+void sub_tick_hook(uint8_t* rdram, recomp_context* ctx) {
+ if (overlay_id() != 2) { if (FuncPtr f = ovl_battle_lookup(SUB_TICK)) f(rdram, ctx); return; }
+ const uint32_t menu = static_cast(ctx->r[4]);
+ dissidia_presence_sub(r32(menu + 320));
+ g_orig_sub_tick(rdram, ctx);
+}
+
+
// ---- Title screen ----------------------------------------------------------------------------------------------------
// NEW GAME / LOAD GAME / EXTRAS are artwork rows (ovl_menu FUN_089DF14C, state T = [title + 476]: cursor T + 76, row count
// T + 0x3FAA8, row instances T + 56 + 4 * row, the selection bar and hand = instance T + 52). Their layout is entry 0 of
@@ -435,6 +451,7 @@ void draw_title_row(float nx, float ny, float srcx, float srcy) {
void title_tick_hook(uint8_t* rdram, recomp_context* ctx) {
if (overlay_id() != 2) { if (FuncPtr f = ovl_battle_lookup(TITLE_TICK)) f(rdram, ctx); return; }
+ dissidia_presence_title();
const uint32_t title = static_cast(ctx->r[4]);
const uint32_t st = r32(title + 476);
const bool menu_up = st && r32(st + 12) == 0 && r32(st + 0x3FAA8) == 3 && r32(st + 64) != 0;
@@ -533,6 +550,8 @@ void dissidia_menu_settings_install(uint8_t* rdram) {
if (g_orig_main_tick && g_pad_obj && g_play_se) {
dissidia_add_asset_patch(kStartSeq, edit_start_seq);
psp_dispatch_register(MAIN_TICK, main_tick_hook);
+ g_orig_sub_tick = ovl_menu_lookup(SUB_TICK);
+ if (g_orig_sub_tick) psp_dispatch_register(SUB_TICK, sub_tick_hook);
} else {
std::fprintf(stderr, "[MENUSET] start menu hooks not installed (a function is missing)\n");
}
diff --git a/psprecomp/games/dissidia/runtime/roster.cpp b/psprecomp/games/dissidia/runtime/roster.cpp
index 547403a..678122a 100644
--- a/psprecomp/games/dissidia/runtime/roster.cpp
+++ b/psprecomp/games/dissidia/runtime/roster.cpp
@@ -28,6 +28,7 @@
#include
#include
+#include
#include
#include
#include
@@ -5678,3 +5679,16 @@ int dissidia_test_action(uint8_t* rdram, recomp_context* ctx, uint32_t actor, in
*ctx = after;
return okv ? 1 : 0;
}
+
+// Display name of a roster.txt character (its nm= label, else its code in capitals), "" for a charId the roster does not set
+// (discord_presence.cpp names retail characters itself). Read-only after load_config, so any thread may ask.
+std::string dissidia_roster_name(int char_id) {
+ for (const Entry& e : g_entries) {
+ if (e.charId != char_id) continue;
+ if (!e.label.empty()) return e.label;
+ std::string up = e.code;
+ for (char& c : up) c = static_cast(std::toupper(static_cast(c)));
+ return up;
+ }
+ return "";
+}
diff --git a/psprecomp/runtime/CMakeLists.txt b/psprecomp/runtime/CMakeLists.txt
index 3b70a21..d5dd780 100644
--- a/psprecomp/runtime/CMakeLists.txt
+++ b/psprecomp/runtime/CMakeLists.txt
@@ -258,6 +258,7 @@ set(RUNTIME_SOURCES
src/psp_screenfx.cpp
src/psp_refl_table.cpp
src/psp_debug_socket.cpp
+ src/psp_discord.cpp # Discord Rich Presence (local IPC; no-op on Android)
src/psp_gl_stats.cpp
src/psp_gpu_driver.cpp # custom Vulkan drivers (Android/Adreno); the list + zip parts build everywhere
${PSP_VKGL_SOURCES}
@@ -472,6 +473,10 @@ add_test(NAME tex_pack_ppsspp COMMAND test_tex_pack_ppsspp)
add_executable(test_refl_table tests/test_refl_table.cpp src/psp_refl_table.cpp)
target_include_directories(test_refl_table PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
add_test(NAME refl_table COMMAND test_refl_table)
+add_executable(test_discord tests/test_discord.cpp src/psp_discord.cpp)
+target_include_directories(test_discord PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
+target_link_libraries(test_discord PRIVATE $<$>:pthread>)
+add_test(NAME discord COMMAND test_discord)
add_executable(test_savedata_dialog tests/test_savedata_dialog.cpp src/hle/psp_savedata_dialog.cpp ${PSP_UI_FONTS_CPP})
target_include_directories(test_savedata_dialog PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_include_directories(test_savedata_dialog PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
diff --git a/psprecomp/runtime/include/hle/psp_hle_adhoc.h b/psprecomp/runtime/include/hle/psp_hle_adhoc.h
index 9c01e23..ce8ffa6 100644
--- a/psprecomp/runtime/include/hle/psp_hle_adhoc.h
+++ b/psprecomp/runtime/include/hle/psp_hle_adhoc.h
@@ -13,11 +13,14 @@
// PSPRECOMP_ADHOC_ROOM= room on the server; players in one room see each other (default: the public room)
// PSPRECOMP_ADHOC_PORT= first UDP port to try (default 27312; tries n..n+7)
// PSPRECOMP_ADHOC_PEERS=a,b LAN mode: extra peers to contact directly: host or host:port, comma separated
-// PSPRECOMP_ADHOC_NICK= nickname shown to other players (default "Player")
+// PSPRECOMP_ADHOC_NICK= nickname shown to other players (default: what the game module passes to psp_adhoc_set_nickname
+// (Dissidia: the save's player name), else "Player")
// PSPRECOMP_ADHOC_MAC=aa:bb:.. override the virtual MAC (default: random per launch)
// PSPRECOMP_ADHOC_LOG=1 log every packet-level event
#include
#include
+#include
+#include
struct recomp_context;
@@ -37,6 +40,15 @@ int psp_adhoc_group_fps_cap();
/// True while this instance is in an ad-hoc group with at least one other player.
bool psp_adhoc_in_session();
bool psp_adhoc_connected();
+/// Players in this instance's ad-hoc group, itself included; 0 when not in a group (the Discord party size).
+int psp_adhoc_group_size();
+/// The nicknames of the other players in this instance's group (UTF-8, as they sent them).
+std::vector psp_adhoc_group_nicks();
+/// A string every member of the group gets the same (room + group name), "" when not in a group (the Discord party id).
+std::string psp_adhoc_group_key();
+/// The nickname other players see: a game module passes the player name of the save (UTF-8, cut to 31 bytes). Empty = "Player".
+/// PSPRECOMP_ADHOC_NICK, when set, wins.
+void psp_adhoc_set_nickname(const char* utf8);
/// Change the network setup at run time (the settings menu). `internet` selects relay-server mode;
/// `server`/`room` apply to it, `peers` (comma separated) to LAN mode. Takes effect within a few
diff --git a/psprecomp/runtime/include/psp_discord.h b/psprecomp/runtime/include/psp_discord.h
new file mode 100644
index 0000000..27131b8
--- /dev/null
+++ b/psprecomp/runtime/include/psp_discord.h
@@ -0,0 +1,62 @@
+// psp_discord.h — Discord Rich Presence ("Playing ... / Quick Battle / Squall vs. Kefka") over Discord's local IPC.
+//
+// No Discord SDK: the desktop client listens on a local socket (Linux / macOS: discord-ipc-0..9 in $XDG_RUNTIME_DIR, $TMPDIR or
+// /tmp, including the Flatpak, Snap and Vesktop sub-folders; Windows: the named pipe \\.\pipe\discord-ipc-0..9) and speaks
+// length-prefixed JSON frames: {u32 opcode, u32 length, JSON}. Opcodes 0 handshake, 1 frame, 2 close, 3 ping, 4 pong.
+//
+// A background thread owns the connection. Once a second it asks the game module's provider what the player is doing and, when
+// that changed, sends SET_ACTIVITY (at most one every 4 s: Discord drops more than 5 updates in 20 s; the newest one always goes
+// out). Discord not running, closed or restarted is normal: the thread retries with a growing pause (5 s .. 60 s) and never
+// blocks the game. Nothing is sent before the provider has something to show, and the activity is cleared on quit and when the
+// player turns it off. Android has no Discord IPC: there everything here is a no-op.
+//
+// Settings: Network > Discord Status (saved as discord=0|1, exported as PSPRECOMP_DISCORD; default on).
+// Environment: PSPRECOMP_DISCORD=0 off, PSPRECOMP_DISCORD_APP_ID= another Discord application, PSPRECOMP_DISCORD_LOG=1 log
+// every frame sent and received, PSPRECOMP_DISCORD_IPC= one socket / pipe path instead of the search (tests).
+#pragma once
+#include
+#include
+#include
+#include
+
+namespace psp_discord {
+
+struct Activity {
+ std::string details; // first line under the game name ("Quick Battle (1-on-1)")
+ std::string state; // second line ("Squall vs. Kefka")
+ int64_t start = 0; // unix seconds: "xx:xx elapsed" counts from here (0 = no timer)
+ std::string large_image; // asset key of the Discord application, or an https:// image URL
+ std::string large_text; // tooltip of the large image
+ std::string small_image, small_text;
+ std::string party_id; // with party_size / party_max > 0: "(2 of 4)" after the state line
+ int party_size = 0, party_max = 0;
+ std::vector> buttons; // up to 2 {label, https URL}, shown to other people
+};
+
+/// The game module's view of the player: fill `out` and return true, or return false for "nothing to show" (the activity is
+/// cleared). Called on the presence thread about once a second, so it must only read state that is safe to read from another
+/// thread (guest RAM words, atomics).
+using Provider = bool (*)(Activity* out);
+
+/// Start the presence thread for this Discord application id. Does nothing on Android, without an id, or when the player turned
+/// it off (it can be turned on later with set_enabled).
+void start(const std::string& app_id, Provider provider);
+/// Clear the activity and close the connection (waits up to ~1 s). Safe to call when start() did nothing.
+void stop();
+
+/// Live on / off switch (the settings menu). Off clears the activity at once and closes the connection.
+void set_enabled(bool on);
+bool enabled();
+/// False where there is no Discord IPC (Android) or start() was never called: the settings menu hides its rows.
+bool available();
+/// One line for the settings menu: "Off", "Discord is not running", "Connected (name)", ...
+std::string status();
+
+// ---- exposed for tests ----
+/// SET_ACTIVITY payload for `a` (nullptr = clear) with the strings checked against Discord's limits.
+std::string activity_json(const Activity* a, int64_t pid, const std::string& nonce);
+/// Escape a UTF-8 string for a JSON string literal; invalid UTF-8 bytes become U+FFFD, the result is cut at `max_bytes` on a
+/// character boundary (0 = no limit).
+std::string json_string(const std::string& s, size_t max_bytes = 0);
+
+} // namespace psp_discord
diff --git a/psprecomp/runtime/include/psp_settings.h b/psprecomp/runtime/include/psp_settings.h
index 888af3e..7a585d2 100644
--- a/psprecomp/runtime/include/psp_settings.h
+++ b/psprecomp/runtime/include/psp_settings.h
@@ -8,7 +8,7 @@
// the saved values win over PSPRECOMP_FULLSCREEN / PSPRECOMP_SCALE / PSPRECOMP_WINDOW / PSPRECOMP_RENDER_SCALE / PSPRECOMP_FPS.
//
// Categories (L / R shoulder, Q / E or Tab, the sidebar): Display, Graphics, Image (colour; sub-menu HDR), Effects (lighting; sub-menu Ray
-// Tracing), Controls (touch screens only), Network (applied at once through psp_adhoc_configure), Cloud, System, Drivers (Android, Adreno)
+// Tracing), Controls (touch screens only), Network (applied at once through psp_adhoc_configure; Discord status, psp_discord.h), Cloud, System, Drivers (Android, Adreno)
// and Debug.
//
// Open / close: Esc or F1 on the keyboard; Guide, or both stick buttons (L3 + R3), on a game controller; the touch controls' menu button;
diff --git a/psprecomp/runtime/src/hle/psp_hle_adhoc.cpp b/psprecomp/runtime/src/hle/psp_hle_adhoc.cpp
index 13d7ad9..1c8949f 100644
--- a/psprecomp/runtime/src/hle/psp_hle_adhoc.cpp
+++ b/psprecomp/runtime/src/hle/psp_hle_adhoc.cpp
@@ -164,6 +164,7 @@ int g_span = 16; // ports tried / probed: base..base+span-1 (several instances
uint16_t g_my_port = 0;
Mac g_mac{};
char g_nick[32] = {0};
+std::string g_game_nick; // psp_adhoc_set_nickname (the game's player name); PSPRECOMP_ADHOC_NICK wins over it
std::thread g_thread;
std::vector g_extra_peers;
std::map g_peers;
@@ -895,7 +896,10 @@ bool ensure_net() {
g_mac = Mac{0x02, (uint8_t)(r1 >> 24), (uint8_t)(r1 >> 16), (uint8_t)(r1 >> 8), (uint8_t)r1, (uint8_t)r2};
}
const char* nick = std::getenv("PSPRECOMP_ADHOC_NICK");
- std::snprintf(g_nick, sizeof g_nick, "%s", nick && *nick ? nick : "Player");
+ {
+ std::lock_guard lk(g_mu);
+ std::snprintf(g_nick, sizeof g_nick, "%s", nick && *nick ? nick : (!g_game_nick.empty() ? g_game_nick.c_str() : "Player"));
+ }
g_cfg_dirty = true; // the network thread resolves the server / peers
g_net_ready = true;
ANOTE("ready: UDP %u, MAC %s, nick \"%s\", %s", g_my_port, mac_str(g_mac).c_str(), g_nick,
@@ -1567,6 +1571,53 @@ bool psp_adhoc_in_session() {
return false;
}
+// UTF-8 cut to at most `max` bytes on a character boundary (a beacon carries 31 bytes of nickname).
+static std::string utf8_cut(const std::string& s, size_t max) {
+ if (s.size() <= max) return s;
+ size_t n = max;
+ while (n > 0 && (static_cast(s[n]) & 0xC0) == 0x80) n--;
+ return s.substr(0, n);
+}
+
+void psp_adhoc_set_nickname(const char* utf8) {
+ const char* forced = std::getenv("PSPRECOMP_ADHOC_NICK");
+ std::lock_guard lk(g_mu);
+ g_game_nick = utf8_cut(utf8 ? utf8 : "", 31);
+ if (forced && *forced) return;
+ const std::string n = g_game_nick.empty() ? std::string("Player") : g_game_nick;
+ if (n == g_nick) return;
+ std::snprintf(g_nick, sizeof g_nick, "%s", n.c_str());
+ if (g_net_ready) ANOTE("nickname \"%s\"", g_nick);
+}
+
+std::vector psp_adhoc_group_nicks() {
+ std::vector out;
+ std::lock_guard lk(g_mu);
+ if (!g_connected) return out;
+ for (auto& [m, p] : g_peers)
+ if (p.in_group && !std::strncmp(p.group, g_group, 8)) out.emplace_back(p.nick);
+ return out;
+}
+
+std::string psp_adhoc_group_key() {
+ std::lock_guard lk(g_mu);
+ if (!g_connected) return "";
+ // the same for every member: where they meet (server + room, or LAN) and the game's group name
+ std::string k = g_relay_mode ? g_cfg_server + "/" + g_cfg_room : std::string("lan");
+ k += '/';
+ k.append(g_group, strnlen(g_group, 8));
+ return k;
+}
+
+int psp_adhoc_group_size() {
+ std::lock_guard lk(g_mu);
+ if (!g_connected) return 0;
+ int n = 1;
+ for (auto& [m, p] : g_peers)
+ if (p.in_group && !std::strncmp(p.group, g_group, 8)) n++;
+ return n;
+}
+
void psp_adhoc_pump(uint8_t* rdram, recomp_context* ctx) {
if (!g_net_ready) return;
if (g_pumping.exchange(true)) return;
diff --git a/psprecomp/runtime/src/main.cpp b/psprecomp/runtime/src/main.cpp
index 4274f65..e8dc873 100644
--- a/psprecomp/runtime/src/main.cpp
+++ b/psprecomp/runtime/src/main.cpp
@@ -19,6 +19,7 @@
#include "psp_debug_socket.h"
#include "psp_game_module.h"
#include "psp_settings.h"
+#include "psp_discord.h"
#include "hle/psp_cloud_boot.h"
#include "psp_vfpu.h" // vfpu_init_context — VFPU prefix reset default
@@ -485,6 +486,7 @@ int main(int argc, char* argv[]) {
ge_texture_shutdown();
ge_shutdown();
psp_cloud_glue_shutdown(); // lets a running upload finish
+ psp_discord::stop(); // takes the Discord activity down
psp_runtime_shutdown();
// Game threads that did not stop within the scheduler's 2 s join (blocked in a wait that never sees the exit flag: ffst_thread, the
diff --git a/psprecomp/runtime/src/psp_discord.cpp b/psprecomp/runtime/src/psp_discord.cpp
new file mode 100644
index 0000000..8528c12
--- /dev/null
+++ b/psprecomp/runtime/src/psp_discord.cpp
@@ -0,0 +1,490 @@
+// psp_discord.cpp — Discord Rich Presence over the desktop client's local IPC (see psp_discord.h).
+#include "psp_discord.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#if defined(_WIN32)
+# ifndef WIN32_LEAN_AND_MEAN
+# define WIN32_LEAN_AND_MEAN
+# endif
+# include
+#elif !defined(__ANDROID__)
+# include
+# include
+# include
+# include
+# include
+#endif
+
+namespace psp_discord {
+
+// ---- JSON ------------------------------------------------------------------------------------------------------------
+
+std::string json_string(const std::string& s, size_t max_bytes) {
+ std::string out;
+ out.reserve(s.size() + 2);
+ size_t used = 0; // bytes of `s` content written (escapes count as their source character)
+ size_t i = 0;
+ while (i < s.size()) {
+ const unsigned char c = static_cast(s[i]);
+ size_t len = 1;
+ bool valid = true;
+ if (c >= 0x80) {
+ len = (c & 0xE0) == 0xC0 ? 2 : (c & 0xF0) == 0xE0 ? 3 : (c & 0xF8) == 0xF0 ? 4 : 0;
+ if (len == 0 || c == 0xC0 || c == 0xC1 || c > 0xF4 || i + len > s.size()) valid = false;
+ for (size_t k = 1; valid && k < len; k++)
+ if ((static_cast(s[i + k]) & 0xC0) != 0x80) valid = false;
+ if (!valid) len = 1;
+ }
+ const size_t cost = valid ? len : 3; // U+FFFD is 3 bytes
+ if (max_bytes && used + cost > max_bytes) break;
+ used += cost;
+ if (!valid) out += "\xEF\xBF\xBD";
+ else if (c == '"') out += "\\\"";
+ else if (c == '\\') out += "\\\\";
+ else if (c == '\n') out += "\\n";
+ else if (c == '\t') out += "\\t";
+ else if (c < 0x20 || c == 0x7F) { char b[8]; std::snprintf(b, sizeof b, "\\u%04x", c); out += b; }
+ else out.append(s, i, len);
+ i += len;
+ }
+ return out;
+}
+
+namespace {
+
+std::string trimmed(const std::string& s) {
+ size_t a = 0, b = s.size();
+ while (a < b && (s[a] == ' ' || s[a] == '\t' || s[a] == '\n')) a++;
+ while (b > a && (s[b - 1] == ' ' || s[b - 1] == '\t' || s[b - 1] == '\n')) b--;
+ return s.substr(a, b - a);
+}
+
+// "key":"value", with Discord's length rules: details / state / image texts need 2..128 characters (shorter ones are left out:
+// Discord rejects the whole activity otherwise), image keys / URLs up to 256 bytes.
+void field(std::string& o, bool& first, const char* key, const std::string& raw, size_t max_bytes, size_t min_chars = 2) {
+ const std::string v = trimmed(raw);
+ if (v.size() < min_chars) return;
+ if (!first) o += ',';
+ first = false;
+ o += '"'; o += key; o += "\":\""; o += json_string(v, max_bytes); o += '"';
+}
+
+} // namespace
+
+std::string activity_json(const Activity* a, int64_t pid, const std::string& nonce) {
+ std::string o = "{\"cmd\":\"SET_ACTIVITY\",\"args\":{\"pid\":" + std::to_string(pid) + ",\"activity\":";
+ if (!a) {
+ o += "null";
+ } else {
+ o += "{\"type\":0,\"instance\":false";
+ bool first = false;
+ field(o, first, "details", a->details, 128);
+ field(o, first, "state", a->state, 128);
+ if (a->start > 0) o += ",\"timestamps\":{\"start\":" + std::to_string(a->start * 1000) + "}"; // milliseconds
+ std::string as = "{";
+ bool afirst = true;
+ field(as, afirst, "large_image", a->large_image, 256, 1);
+ field(as, afirst, "large_text", a->large_text, 128);
+ field(as, afirst, "small_image", a->small_image, 256, 1);
+ field(as, afirst, "small_text", a->small_text, 128);
+ if (!afirst) o += ",\"assets\":" + as + "}";
+ if (a->party_size > 0 && a->party_max >= a->party_size) {
+ const std::string id = trimmed(a->party_id).empty() ? std::string("party") : trimmed(a->party_id);
+ o += ",\"party\":{\"id\":\"" + json_string(id, 128) + "\",\"size\":[" + std::to_string(a->party_size) + "," +
+ std::to_string(a->party_max) + "]}";
+ }
+ std::string bs;
+ int nb = 0;
+ for (const auto& b : a->buttons) {
+ const std::string label = trimmed(b.first), url = trimmed(b.second);
+ if (nb == 2 || label.empty() || url.size() > 512 || url.rfind("https://", 0) != 0) continue;
+ bs += nb ? "," : "";
+ bs += "{\"label\":\"" + json_string(label, 32) + "\",\"url\":\"" + json_string(url) + "\"}";
+ nb++;
+ }
+ if (nb) o += ",\"buttons\":[" + bs + "]";
+ o += "}";
+ }
+ o += "},\"nonce\":\"" + json_string(nonce) + "\"}";
+ return o;
+}
+
+#if defined(__ANDROID__)
+
+void start(const std::string&, Provider) {}
+void stop() {}
+void set_enabled(bool) {}
+bool enabled() { return false; }
+bool available() { return false; }
+std::string status() { return "Not available"; }
+
+#else
+
+namespace {
+
+enum Op : uint32_t { OP_HANDSHAKE = 0, OP_FRAME = 1, OP_CLOSE = 2, OP_PING = 3, OP_PONG = 4 };
+
+std::mutex g_mu; // g_status, g_user; the condition variable
+std::condition_variable g_cv;
+std::thread g_thread;
+std::atomic g_quit{false}, g_on{true}, g_started{false}, g_done{false};
+std::string g_app_id;
+Provider g_provider = nullptr;
+std::string g_status = "Off";
+bool g_log = false;
+
+void set_status(const std::string& s) {
+ std::lock_guard l(g_mu);
+ if (g_status != s && g_log) std::fprintf(stderr, "[DISCORD] status: %s\n", s.c_str());
+ g_status = s;
+}
+
+using Clock = std::chrono::steady_clock;
+double now_s() { return std::chrono::duration(Clock::now().time_since_epoch()).count(); }
+
+// One connection to the client: a Unix socket or a Windows named pipe.
+class Conn {
+public:
+ ~Conn() { close(); }
+ bool is_open() const {
+#if defined(_WIN32)
+ return h_ != INVALID_HANDLE_VALUE;
+#else
+ return fd_ >= 0;
+#endif
+ }
+ bool open(const std::string& path) {
+ close();
+#if defined(_WIN32)
+ h_ = CreateFileA(path.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr);
+ return h_ != INVALID_HANDLE_VALUE;
+#else
+ sockaddr_un sa{};
+ if (path.size() >= sizeof(sa.sun_path)) return false;
+ fd_ = ::socket(AF_UNIX, SOCK_STREAM, 0);
+ if (fd_ < 0) return false;
+ ::fcntl(fd_, F_SETFD, FD_CLOEXEC);
+# ifdef SO_NOSIGPIPE
+ int one = 1;
+ ::setsockopt(fd_, SOL_SOCKET, SO_NOSIGPIPE, &one, sizeof one);
+# endif
+ timeval tv{2, 0}; // a client that stops reading must not hang the thread for long
+ ::setsockopt(fd_, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof tv);
+ sa.sun_family = AF_UNIX;
+ std::memcpy(sa.sun_path, path.c_str(), path.size() + 1);
+ if (::connect(fd_, reinterpret_cast(&sa), sizeof sa) != 0) { close(); return false; }
+ return true;
+#endif
+ }
+ void close() {
+#if defined(_WIN32)
+ if (h_ != INVALID_HANDLE_VALUE) CloseHandle(h_);
+ h_ = INVALID_HANDLE_VALUE;
+#else
+ if (fd_ >= 0) ::close(fd_);
+ fd_ = -1;
+#endif
+ }
+ bool write_all(const void* data, size_t n) {
+ const char* p = static_cast(data);
+ while (n > 0 && is_open()) {
+#if defined(_WIN32)
+ DWORD w = 0;
+ if (!WriteFile(h_, p, DWORD(n), &w, nullptr) || w == 0) { close(); return false; }
+#else
+# ifdef MSG_NOSIGNAL
+ const ssize_t w = ::send(fd_, p, n, MSG_NOSIGNAL);
+# else
+ const ssize_t w = ::send(fd_, p, n, 0);
+# endif
+ if (w <= 0) { close(); return false; }
+#endif
+ p += w; n -= size_t(w);
+ }
+ return n == 0;
+ }
+ // 1 = bytes are waiting, 0 = nothing within `timeout_ms`, -1 = closed / error (the connection is closed).
+ int readable(int timeout_ms) {
+ if (!is_open()) return -1;
+#if defined(_WIN32)
+ const double until = now_s() + timeout_ms / 1000.0;
+ for (;;) {
+ DWORD avail = 0;
+ if (!PeekNamedPipe(h_, nullptr, 0, nullptr, &avail, nullptr)) { close(); return -1; }
+ if (avail > 0) return 1;
+ if (now_s() >= until) return 0;
+ Sleep(10);
+ }
+#else
+ pollfd p{fd_, POLLIN, 0};
+ const int r = ::poll(&p, 1, timeout_ms);
+ if (r < 0) { close(); return -1; }
+ if (r == 0) return 0;
+ if (p.revents & POLLIN) return 1;
+ close(); // POLLHUP / POLLERR without data
+ return -1;
+#endif
+ }
+ // Reads exactly n bytes, giving up after `timeout_ms` or when the presence thread is told to quit.
+ bool read_all(void* data, size_t n, int timeout_ms) {
+ char* p = static_cast(data);
+ const double until = now_s() + timeout_ms / 1000.0;
+ while (n > 0) {
+ if (g_quit.load() || now_s() > until) return false;
+ const int r = readable(100);
+ if (r < 0) return false;
+ if (r == 0) continue;
+#if defined(_WIN32)
+ DWORD avail = 0, got = 0; // never ask for more than is there: ReadFile would block until it all came
+ if (!PeekNamedPipe(h_, nullptr, 0, nullptr, &avail, nullptr)) { close(); return false; }
+ if (!ReadFile(h_, p, std::min(DWORD(n), avail), &got, nullptr) || got == 0) { close(); return false; }
+#else
+ const ssize_t got = ::recv(fd_, p, n, 0);
+ if (got <= 0) { close(); return false; }
+#endif
+ p += got; n -= size_t(got);
+ }
+ return true;
+ }
+
+private:
+#if defined(_WIN32)
+ HANDLE h_ = INVALID_HANDLE_VALUE;
+#else
+ int fd_ = -1;
+#endif
+};
+
+bool send_frame(Conn& c, uint32_t op, const std::string& json) {
+ if (g_log) std::fprintf(stderr, "[DISCORD] -> op %u %s\n", op, json.c_str());
+ const uint32_t len = uint32_t(json.size());
+ unsigned char h[8] = {uint8_t(op), uint8_t(op >> 8), uint8_t(op >> 16), uint8_t(op >> 24),
+ uint8_t(len), uint8_t(len >> 8), uint8_t(len >> 16), uint8_t(len >> 24)};
+ std::string buf(reinterpret_cast(h), 8);
+ buf += json;
+ return c.write_all(buf.data(), buf.size());
+}
+
+bool read_frame(Conn& c, uint32_t* op, std::string* json, int timeout_ms) {
+ unsigned char h[8];
+ if (!c.read_all(h, 8, timeout_ms)) return false;
+ *op = uint32_t(h[0]) | uint32_t(h[1]) << 8 | uint32_t(h[2]) << 16 | uint32_t(h[3]) << 24;
+ const uint32_t len = uint32_t(h[4]) | uint32_t(h[5]) << 8 | uint32_t(h[6]) << 16 | uint32_t(h[7]) << 24;
+ if (len > (1u << 20)) { c.close(); return false; } // not a Discord frame
+ json->assign(len, '\0');
+ if (len && !c.read_all(&(*json)[0], len, timeout_ms)) return false;
+ if (g_log) std::fprintf(stderr, "[DISCORD] <- op %u %s\n", *op, json->c_str());
+ return true;
+}
+
+// The string value of the first "key":"..." after `from` (no full JSON parser needed for READY / ERROR / CLOSE).
+std::string json_field(const std::string& j, const char* key, size_t from = 0) {
+ const std::string pat = std::string("\"") + key + "\":";
+ size_t p = j.find(pat, from);
+ if (p == std::string::npos) return "";
+ p += pat.size();
+ while (p < j.size() && j[p] == ' ') p++;
+ if (p >= j.size() || j[p] != '"') return "";
+ std::string v;
+ for (++p; p < j.size() && j[p] != '"'; ++p) {
+ if (j[p] == '\\' && p + 1 < j.size()) {
+ ++p;
+ if (j[p] == 'u') { v += '?'; p += 4; continue; }
+ v += j[p] == 'n' ? '\n' : j[p];
+ } else v += j[p];
+ }
+ return v;
+}
+
+std::vector candidates() {
+ std::vector out;
+ if (const char* p = std::getenv("PSPRECOMP_DISCORD_IPC"); p && *p) { out.push_back(p); return out; }
+#if defined(_WIN32)
+ for (int i = 0; i < 10; i++) out.push_back("\\\\.\\pipe\\discord-ipc-" + std::to_string(i));
+#else
+ std::vector bases;
+ for (const char* e : {"XDG_RUNTIME_DIR", "TMPDIR", "TMP", "TEMP"})
+ if (const char* v = std::getenv(e); v && *v) bases.push_back(v);
+ bases.push_back("/tmp");
+ // The client itself, then the sandboxed packages (Flatpak, Snap) and Vesktop, which put their socket in a sub-folder.
+ static const char* const subs[] = {"", "app/com.discordapp.Discord/", "app/com.discordapp.DiscordCanary/", "app/com.discordapp.DiscordPTB/",
+ "snap.discord/", "snap.discord-canary/", ".flatpak/dev.vencord.Vesktop/xdg-run/",
+ "app/dev.vencord.Vesktop/"};
+ std::vector seen;
+ for (std::string b : bases) {
+ while (b.size() > 1 && b.back() == '/') b.pop_back();
+ if (std::find(seen.begin(), seen.end(), b) != seen.end()) continue;
+ seen.push_back(b);
+ for (const char* s : subs)
+ for (int i = 0; i < 10; i++) out.push_back(b + "/" + s + "discord-ipc-" + std::to_string(i));
+ }
+#endif
+ return out;
+}
+
+int64_t self_pid() {
+#if defined(_WIN32)
+ return int64_t(GetCurrentProcessId());
+#else
+ return int64_t(::getpid());
+#endif
+}
+
+// Open the first socket that answers the handshake with READY. Returns false with a status line for the settings menu.
+bool connect_client(Conn& c, std::string* why, bool* refused) {
+ *refused = false;
+ *why = "Discord is not running";
+ for (const std::string& path : candidates()) {
+ if (g_quit.load() || !g_on.load()) return false;
+ if (!c.open(path)) continue;
+ if (!send_frame(c, OP_HANDSHAKE, "{\"v\":1,\"client_id\":\"" + json_string(g_app_id, 64) + "\"}")) continue;
+ uint32_t op = 0;
+ std::string j;
+ if (!read_frame(c, &op, &j, 5000)) { c.close(); continue; }
+ if (op == OP_FRAME && j.find("\"READY\"") != std::string::npos) {
+ const size_t u = j.find("\"user\"");
+ std::string name = u == std::string::npos ? "" : json_field(j, "global_name", u);
+ if (name.empty() && u != std::string::npos) name = json_field(j, "username", u);
+ std::fprintf(stderr, "[DISCORD] connected (%s)%s%s\n", path.c_str(), name.empty() ? "" : " as ", name.c_str());
+ *why = name.empty() ? "Connected" : "Connected as " + name;
+ return true;
+ }
+ // CLOSE (op 2): e.g. {"code":4000,"message":"Invalid Client ID"}; the next socket would say the same
+ const std::string msg = json_field(j, "message");
+ std::fprintf(stderr, "[DISCORD] %s refused the connection: %s\n", path.c_str(), j.c_str());
+ *why = "Discord refused: " + (msg.empty() ? std::string("unknown reason") : msg);
+ *refused = true;
+ c.close();
+ return false;
+ }
+ return false;
+}
+
+void worker() {
+ Conn c;
+ double next_try = 0, backoff = 5, last_send = -1e9;
+ std::string last_body; // the activity last sent (payload without nonce); "" = nothing sent on this connection
+ bool shown = false; // an activity is up on this connection (so turning off / quitting clears it)
+ uint64_t nonce = 0;
+ const int64_t pid = self_pid();
+ auto drop = [&](const std::string& why, double retry_in) {
+ c.close();
+ last_body.clear();
+ shown = false;
+ next_try = now_s() + retry_in;
+ set_status(why);
+ };
+ auto send_activity = [&](const Activity* a, const std::string& body) {
+ if (!send_frame(c, OP_FRAME, activity_json(a, pid, std::to_string(++nonce)))) { drop("Discord is not running", 2); return; }
+ last_body = body;
+ shown = a != nullptr;
+ last_send = now_s();
+ };
+ while (!g_quit.load()) {
+ {
+ std::unique_lock l(g_mu);
+ g_cv.wait_for(l, std::chrono::seconds(1));
+ }
+ if (g_quit.load()) break;
+ if (!g_on.load()) {
+ set_status("Off");
+ if (c.is_open()) {
+ if (shown) send_activity(nullptr, "");
+ c.close();
+ std::fprintf(stderr, "[DISCORD] turned off\n");
+ }
+ last_body.clear(); shown = false; next_try = 0; backoff = 5;
+ continue;
+ }
+ if (!c.is_open()) {
+ if (now_s() < next_try) continue;
+ std::string why;
+ bool refused = false;
+ if (!connect_client(c, &why, &refused)) {
+ if (g_quit.load()) break;
+ if (!g_on.load()) continue;
+ next_try = now_s() + (refused ? 300.0 : backoff);
+ backoff = std::min(backoff * 2, 60.0);
+ set_status(why);
+ continue;
+ }
+ backoff = 5;
+ last_body.clear();
+ shown = false;
+ set_status(why);
+ }
+ // what the client sent meanwhile: pings, errors, a close
+ uint32_t op = 0;
+ std::string j;
+ while (c.is_open() && c.readable(0) == 1 && read_frame(c, &op, &j, 1000)) {
+ if (op == OP_PING) send_frame(c, OP_PONG, j);
+ else if (op == OP_CLOSE) { std::fprintf(stderr, "[DISCORD] the client closed the connection: %s\n", j.c_str()); c.close(); }
+ else if (op == OP_FRAME && j.find("\"ERROR\"") != std::string::npos) std::fprintf(stderr, "[DISCORD] error: %s\n", j.c_str());
+ }
+ if (!c.is_open()) { std::fprintf(stderr, "[DISCORD] disconnected\n"); drop("Discord is not running", 2); continue; }
+ Activity a;
+ const bool has = g_provider && g_provider(&a);
+ const std::string body = activity_json(has ? &a : nullptr, pid, "");
+ if (body == last_body || (!has && !shown)) continue;
+ if (now_s() - last_send < 4.0) continue; // Discord's limit is 5 per 20 s; the newest state goes out on a later round
+ send_activity(has ? &a : nullptr, body);
+ }
+ if (c.is_open() && shown) send_activity(nullptr, ""); // quit: take the activity down at once (the client would after a few s)
+ c.close();
+ g_done.store(true);
+}
+
+} // namespace
+
+void start(const std::string& app_id, Provider provider) {
+ if (g_started.exchange(true)) return;
+ g_app_id = app_id;
+ g_provider = provider;
+ if (const char* id = std::getenv("PSPRECOMP_DISCORD_APP_ID"); id && *id) g_app_id = id;
+ g_log = std::getenv("PSPRECOMP_DISCORD_LOG") != nullptr;
+ const char* e = std::getenv("PSPRECOMP_DISCORD");
+ g_on.store(!(e && e[0] == '0'));
+ if (g_app_id.empty()) { // nothing to talk to Discord as
+ g_on.store(false);
+ g_started.store(false);
+ set_status("Not available");
+ return;
+ }
+ set_status(g_on.load() ? "Looking for Discord" : "Off");
+ g_thread = std::thread(worker);
+}
+
+void stop() {
+ if (!g_thread.joinable()) return;
+ g_quit.store(true);
+ g_cv.notify_all();
+ const double until = now_s() + 1.5;
+ while (!g_done.load() && now_s() < until) std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ if (g_done.load()) g_thread.join();
+ else g_thread.detach(); // stuck in a write to a client that stopped reading: the process is ending anyway
+}
+
+void set_enabled(bool on) {
+ g_on.store(on);
+ set_status(on ? "Looking for Discord" : "Off");
+ g_cv.notify_all();
+}
+bool enabled() { return g_on.load(); }
+bool available() { return g_started.load(); }
+std::string status() {
+ std::lock_guard l(g_mu);
+ return g_status;
+}
+
+#endif // !__ANDROID__
+
+} // namespace psp_discord
diff --git a/psprecomp/runtime/src/psp_ge_draw.cpp b/psprecomp/runtime/src/psp_ge_draw.cpp
index 1f5c726..c7118ed 100644
--- a/psprecomp/runtime/src/psp_ge_draw.cpp
+++ b/psprecomp/runtime/src/psp_ge_draw.cpp
@@ -4727,7 +4727,7 @@ static int perf_rss_mb() {
#ifndef PSPRECOMP_RELEASE_VERSION
#define PSPRECOMP_RELEASE_VERSION "dev"
#endif
-static std::string psp_release_version() { return PSPRECOMP_RELEASE_VERSION; }
+std::string psp_release_version() { return PSPRECOMP_RELEASE_VERSION; } // also read by games/dissidia/runtime/discord_presence.cpp
// ---- system information for the performance overlay (Linux; elsewhere the fields read "n/a") ----
struct SysInfo {
diff --git a/psprecomp/runtime/src/psp_settings.cpp b/psprecomp/runtime/src/psp_settings.cpp
index 9471a13..dd57f21 100644
--- a/psprecomp/runtime/src/psp_settings.cpp
+++ b/psprecomp/runtime/src/psp_settings.cpp
@@ -15,6 +15,7 @@
#include "hle/psp_cloud_service.h"
#include "psp_gpu_driver.h"
#include "psp_gl_window.h"
+#include "psp_discord.h"
#include
#if defined(PSPRECOMP_HAVE_VKGL)
@@ -157,7 +158,7 @@ bool texpack_choice();
bool texpack_at_start();
enum Row { ROW_DISPLAY, ROW_RES, ROW_SCALE, ROW_FPS, ROW_FPSCOUNT, ROW_VSYNC, ROW_WIDE, ROW_TALL, ROW_SOFT, ROW_RENDERER, ROW_AA, ROW_SHARP, ROW_BRIGHT, ROW_CONTRAST, ROW_SAT, ROW_HDR, ROW_HDR_BOOST, ROW_HDR_GAMUT, ROW_HDR_PEAK, ROW_HDR_PAPER, ROW_HDR_SCENE, ROW_SSAO, ROW_CONTACT, ROW_RT, ROW_RT_SOFT, ROW_RT_REFL, ROW_RT_REFL_FX, ROW_SSR, ROW_ANISO, ROW_UPSCALE, ROW_VOICE, ROW_TEXPACK, ROW_TOUCH, ROW_TOUCH_EDIT, ROW_UPDATES, ROW_QUIT,
- ROW_NET_MODE, ROW_NET_SERVER, ROW_NET_ROOM, ROW_NET_PEERS, ROW_NET_STATUS, // Network page
+ ROW_NET_MODE, ROW_NET_SERVER, ROW_NET_ROOM, ROW_NET_PEERS, ROW_NET_STATUS, ROW_DISCORD, ROW_DISCORD_STATUS, // Network page
ROW_CLOUD_PROVIDER, ROW_CLOUD_FOLDER, ROW_CLOUD_URL, ROW_CLOUD_USER, ROW_CLOUD_PASS, ROW_CLOUD_GOOGLE,
ROW_CLOUD_AUTO, ROW_CLOUD_REPLAYS, ROW_CLOUD_NOW, ROW_CLOUD_STATUS, // Cloud page
ROW_PERF, ROW_FX, ROW_SYNC, ROW_RING, ROW_GLOWSOFT, ROW_GLOWPASS, ROW_FXL_INT, ROW_FXL_RAD, // Debug page
@@ -168,7 +169,7 @@ enum Row { ROW_DISPLAY, ROW_RES, ROW_SCALE, ROW_FPS, ROW_FPSCOUNT, ROW_VSYNC, RO
ROW_ENV0, ROW_ENV_END = ROW_ENV0 + 63, // a developer-options category page: one row per environment variable
ROW_MOD0, ROW_MOD_END = ROW_MOD0 + 31, ROW_MODS_NONE, // Mods page: one toggle per mod folder, or a note when there are none
ROW_SEC_WINDOW, ROW_SEC_PERF, ROW_SEC_QUALITY, ROW_SEC_AA, ROW_SEC_TEX, ROW_SEC_ENGINE, ROW_SEC_COLOUR, ROW_SEC_HDR, ROW_SEC_LIGHT,
- ROW_SEC_RT, ROW_SEC_TOUCH, ROW_SEC_GAME, ROW_SEC_SESSION, ROW_SEC_REFL, ROW_SEC_SERVER, ROW_SEC_SYNC, ROW_SEC_DRIVER, ROW_SEC_MODS, ROW_SEC_DEV, // section captions (not selectable)
+ ROW_SEC_RT, ROW_SEC_TOUCH, ROW_SEC_GAME, ROW_SEC_SESSION, ROW_SEC_REFL, ROW_SEC_SERVER, ROW_SEC_SYNC, ROW_SEC_DRIVER, ROW_SEC_MODS, ROW_SEC_DEV, ROW_SEC_DISCORD, // section captions (not selectable)
ROW_COUNT };
static_assert(ROW_COUNT < psp_sddialog::SET_MAX_IDS, "row ids are animation slots");
bool is_section(Row r) { return r >= ROW_SEC_WINDOW && r < ROW_COUNT; }
@@ -303,7 +304,7 @@ constexpr int k_max_rs = 16; // 16x = 7680x4352 (8K); the draw layer clamps to
// ---- Network page --------------------------------------------------------------------------------------
constexpr const char* NET_DEFAULT_SERVER = "party.schindlershadow.com:27500";
bool g_net_internet = true;
-std::string g_net_server = NET_DEFAULT_SERVER, g_net_room, g_net_peers, g_net_status;
+std::string g_net_server = NET_DEFAULT_SERVER, g_net_room, g_net_peers, g_net_status, g_discord_status;
bool g_net_loaded = false;
int64_t g_status_next = 0;
@@ -802,6 +803,20 @@ std::vector make_rows() {
m.value = g_net_status.empty() ? "..." : g_net_status;
m.help = "Network status\nWhether the server answers and how many players are in your room (or nearby, on a LAN). Communications mode starts the connection.";
break;
+ case ROW_DISCORD: {
+ const bool on = psp_discord::enabled();
+ m.label = "Discord Status";
+ m.value = on ? "On" : "Off";
+ m.can_dec = on;
+ m.can_inc = !on;
+ m.help = "Discord Rich Presence\nShows what you are playing on your Discord profile: the mode, the fighters and the stage, and how long you have been at it. Needs the Discord desktop app running on this computer. Nothing is sent anywhere else. Saved.";
+ break;
+ }
+ case ROW_DISCORD_STATUS:
+ m.label = "Discord";
+ m.value = g_discord_status.empty() ? "..." : g_discord_status;
+ m.help = "Discord connection\nWhether the Discord app was found. It is looked for again every few seconds, so it can be started at any time.";
+ break;
case ROW_CLOUD_PROVIDER:
m.label = "Cloud Sync";
m.value = psp_cloud_svc::provider_name(g_cloud.provider);
@@ -958,6 +973,7 @@ std::vector make_rows() {
case ROW_SEC_SESSION: m.label = "Session"; break;
case ROW_SEC_REFL: m.label = "Reflections"; break;
case ROW_SEC_SERVER: m.label = "Connection"; break;
+ case ROW_SEC_DISCORD: m.label = "Discord"; break;
case ROW_SEC_SYNC: m.label = "Sync"; break;
case ROW_SEC_DRIVER: m.label = "Driver"; break;
case ROW_COUNT: break;
@@ -1282,7 +1298,7 @@ psp_sddialog::SetKind row_kind(Row r) {
if (const EnvOpt* o = env_row_opt(r)) return o->type == 'c' ? K::Choice : K::Toggle;
switch (r) {
case ROW_RT_REFL_FX:
- case ROW_FPSCOUNT: case ROW_VSYNC: case ROW_WIDE: case ROW_TALL: case ROW_SOFT: case ROW_TEXPACK: case ROW_UPDATES: case ROW_HDR: case ROW_HDR_SCENE: case ROW_CLOUD_AUTO:
+ case ROW_FPSCOUNT: case ROW_VSYNC: case ROW_WIDE: case ROW_TALL: case ROW_SOFT: case ROW_TEXPACK: case ROW_UPDATES: case ROW_DISCORD: case ROW_HDR: case ROW_HDR_SCENE: case ROW_CLOUD_AUTO:
case ROW_CLOUD_REPLAYS: case ROW_PERF: case ROW_FX: case ROW_GLOWSOFT: case ROW_GLOWPASS:
case ROW_DBG0: case ROW_DBG1: case ROW_DBG2: case ROW_DBG3: case ROW_DBG4: case ROW_DBG5:
return K::Toggle;
@@ -1291,7 +1307,7 @@ psp_sddialog::SetKind row_kind(Row r) {
case ROW_QUIT: return K::Danger;
case ROW_SUB_HDR: case ROW_SUB_RT: return K::Submenu;
case ROW_NET_SERVER: case ROW_NET_ROOM: case ROW_NET_PEERS: case ROW_CLOUD_FOLDER: case ROW_CLOUD_URL: case ROW_CLOUD_USER: case ROW_CLOUD_PASS: return K::Text;
- case ROW_NET_STATUS: case ROW_CLOUD_STATUS: case ROW_MODS_NONE: return K::Info;
+ case ROW_NET_STATUS: case ROW_DISCORD_STATUS: case ROW_CLOUD_STATUS: case ROW_MODS_NONE: return K::Info;
default: return is_section(r) ? K::Header : K::Choice;
}
}
@@ -1489,6 +1505,13 @@ bool updates_choice() {
return !(e && e[0] == '0');
}
void apply_updates(bool on) { save("check_updates", on ? "1" : "0"); }
+// Discord Rich Presence: applies at once (psp_discord), saved as discord=0|1 (exported as PSPRECOMP_DISCORD at the next start).
+void apply_discord(bool on) {
+ if (on == psp_discord::enabled()) return;
+ psp_discord::set_enabled(on);
+ save("discord", on ? "1" : "0");
+ g_discord_status = psp_discord::status();
+}
void build_rows();
@@ -1553,6 +1576,7 @@ void change(int d) { // left / right on the selected row
case ROW_VOICE: apply_voice(d > 0); break; // left: English, right: Japanese
case ROW_TEXPACK: apply_texpack(d > 0); break;
case ROW_UPDATES: apply_updates(d > 0); break;
+ case ROW_DISCORD: apply_discord(d > 0); break;
case ROW_TOUCH: {
const int t = std::clamp(psp_touch_mode() + d, 0, 2);
psp_touch_set_mode(t);
@@ -1568,7 +1592,7 @@ void change(int d) { // left / right on the selected row
build_rows(); // the rows differ: server and room, or direct peers
}
break;
- case ROW_NET_SERVER: case ROW_NET_ROOM: case ROW_NET_PEERS: case ROW_NET_STATUS: break;
+ case ROW_NET_SERVER: case ROW_NET_ROOM: case ROW_NET_PEERS: case ROW_NET_STATUS: case ROW_DISCORD_STATUS: break;
case ROW_CLOUD_PROVIDER: {
const int cur = int(g_cloud.provider), nx = std::clamp(cur + d, 0, 3);
if (nx != cur) {
@@ -1818,6 +1842,7 @@ void build_rows() {
if (g_net_internet) { add(ROW_NET_SERVER); add(ROW_NET_ROOM); }
else add(ROW_NET_PEERS);
add(ROW_NET_STATUS);
+ if (psp_discord::available()) { add(ROW_SEC_DISCORD); add(ROW_DISCORD); add(ROW_DISCORD_STATUS); }
break;
case PAGE_CLOUD:
cloud_load();
@@ -2096,6 +2121,8 @@ void confirm_row() {
case ROW_VOICE: apply_voice(!voice_jp_choice()); break;
case ROW_TEXPACK: apply_texpack(!texpack_choice()); break;
case ROW_UPDATES: apply_updates(!updates_choice()); break;
+ case ROW_DISCORD: apply_discord(!psp_discord::enabled()); break;
+ case ROW_DISCORD_STATUS: break;
case ROW_TOUCH: change(psp_touch_mode() >= 2 ? -2 : 1); return;
case ROW_TOUCH_EDIT: psp_touch_edit_begin(); return;
case ROW_NET_MODE: change(g_net_internet ? 1 : -1); return;
@@ -2446,6 +2473,7 @@ void psp_settings_load_early() {
put("PSPRECOMP_VOICE", it->second);
if ((it = g_saved.find("hd_textures")) != g_saved.end() && (it->second == "0" || it->second == "1"))
put("PSPRECOMP_TEX_REPLACE", it->second);
+ if ((it = g_saved.find("discord")) != g_saved.end() && (it->second == "0" || it->second == "1")) put("PSPRECOMP_DISCORD", it->second);
if ((it = g_saved.find("renderer")) != g_saved.end() && (it->second == "gl" || it->second == "vulkan")) put("PSPRECOMP_RENDERER", it->second);
if ((it = g_saved.find("gpu_driver")) != g_saved.end()) {
if (it->second.empty()) psp_plat::unsetenv_("PSPRECOMP_GPU_DRIVER");
@@ -2674,6 +2702,8 @@ void psp_settings_tick() {
char st[128];
psp_adhoc_status(st, sizeof st);
if (g_net_status != st) { g_net_status = st; g_dirty = true; }
+ const std::string ds = psp_discord::status();
+ if (g_discord_status != ds) { g_discord_status = ds; g_dirty = true; }
}
if (page_id() == PAGE_GPU && !g_edit.active) { // the list / download run on a worker thread
if (!g_gpu_list_asked) { g_gpu_list_asked = true; psp_gpu::refresh(); } // load the live list the first time the page is seen
diff --git a/psprecomp/runtime/tests/test_discord.cpp b/psprecomp/runtime/tests/test_discord.cpp
new file mode 100644
index 0000000..803cc2c
--- /dev/null
+++ b/psprecomp/runtime/tests/test_discord.cpp
@@ -0,0 +1,283 @@
+// Discord Rich Presence (psp_discord.cpp): the JSON it builds, and a whole session against a fake Discord client on a Unix socket:
+// handshake, first activity, rate limit (the newest state wins), ping / pong, turning off and on, the client going away, quit.
+#include "psp_discord.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#if defined(_WIN32)
+#include
+#else
+#include
+#include
+#include
+#include
+#endif
+
+static int failures = 0;
+#define CHECK(c) do { if (!(c)) { std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); failures++; } } while (0)
+
+using psp_discord::Activity;
+
+static bool has(const std::string& s, const std::string& sub) { return s.find(sub) != std::string::npos; }
+
+static void json_tests() {
+ CHECK(psp_discord::json_string("a\"b\\c\nd") == "a\\\"b\\\\c\\nd");
+ CHECK(psp_discord::json_string(std::string("x\x01y")) == "x\\u0001y");
+ CHECK(psp_discord::json_string("Ω stage") == "Ω stage"); // UTF-8 kept
+ CHECK(psp_discord::json_string(std::string("a\xFF" "b")) == "a\xEF\xBF\xBD" "b"); // invalid byte -> U+FFFD
+ CHECK(psp_discord::json_string("abcΩ", 4) == "abc"); // never cuts a character in two
+ CHECK(psp_discord::json_string("abcΩ", 5) == "abcΩ");
+
+ const std::string clear = psp_discord::activity_json(nullptr, 42, "7");
+ CHECK(clear == "{\"cmd\":\"SET_ACTIVITY\",\"args\":{\"pid\":42,\"activity\":null},\"nonce\":\"7\"}");
+
+ Activity a;
+ a.details = "Quick Battle (1-on-1)";
+ a.state = "Squall vs. Kefka";
+ a.start = 1700000000;
+ a.large_image = "https://example.org/icon.png";
+ a.large_text = "x"; // too short for Discord: left out
+ a.party_size = 2; a.party_max = 2; a.party_id = "room";
+ a.buttons = {{"Get it", "https://example.org"}, {"Bad", "http://insecure"}, {"Third", "https://c"}, {"Fourth", "https://d"}};
+ const std::string j = psp_discord::activity_json(&a, 1, "n");
+ CHECK(has(j, "\"details\":\"Quick Battle (1-on-1)\""));
+ CHECK(has(j, "\"state\":\"Squall vs. Kefka\""));
+ CHECK(has(j, "\"timestamps\":{\"start\":1700000000000}"));
+ CHECK(has(j, "\"assets\":{\"large_image\":\"https://example.org/icon.png\"}"));
+ CHECK(!has(j, "large_text"));
+ CHECK(has(j, "\"party\":{\"id\":\"room\",\"size\":[2,2]}"));
+ CHECK(has(j, "\"buttons\":[{\"label\":\"Get it\",\"url\":\"https://example.org\"},{\"label\":\"Third\",\"url\":\"https://c\"}]"));
+ CHECK(!has(j, "insecure") && !has(j, "Fourth"));
+
+ Activity b;
+ b.details = std::string(300, 'x');
+ b.state = " "; // blank: left out
+ b.party_size = 3; b.party_max = 2; // inconsistent: left out
+ const std::string k = psp_discord::activity_json(&b, 1, "n");
+ CHECK(has(k, "\"details\":\"" + std::string(128, 'x') + "\""));
+ CHECK(!has(k, "\"state\"") && !has(k, "party") && !has(k, "assets") && !has(k, "timestamps") && !has(k, "buttons"));
+}
+
+// ---- a fake Discord client (Unix socket, or a named pipe on Windows) ----
+static std::mutex g_mu;
+static Activity g_act;
+static bool g_have = true;
+static bool provider(Activity* out) {
+ std::lock_guard l(g_mu);
+ *out = g_act;
+ return g_have;
+}
+static void set_act(const std::string& details, bool have = true) {
+ std::lock_guard l(g_mu);
+ g_act.details = details;
+ g_act.state = "state line";
+ g_have = have;
+}
+static double now() { return std::chrono::duration(std::chrono::steady_clock::now().time_since_epoch()).count(); }
+
+#if defined(_WIN32)
+using Fd = HANDLE;
+static const Fd kNone = INVALID_HANDLE_VALUE;
+static std::string g_pipe;
+static bool read_n(Fd fd, void* p, size_t n, int ms) {
+ char* c = static_cast(p);
+ const double until = now() + ms / 1000.0;
+ while (n) {
+ DWORD avail = 0;
+ if (!PeekNamedPipe(fd, nullptr, 0, nullptr, &avail, nullptr)) return false;
+ if (!avail) { if (now() > until) return false; Sleep(5); continue; }
+ DWORD got = 0;
+ if (!ReadFile(fd, c, DWORD(std::min(n, avail)), &got, nullptr) || !got) return false;
+ c += got; n -= got;
+ }
+ return true;
+}
+static void send_raw(Fd fd, const std::string& b) { DWORD w = 0; WriteFile(fd, b.data(), DWORD(b.size()), &w, nullptr); }
+static void close_fd(Fd fd) { DisconnectNamedPipe(fd); CloseHandle(fd); }
+// a fresh pipe instance, waiting for the runtime to open it
+static Fd accept_client(int ms) {
+ Fd h = CreateNamedPipeA(g_pipe.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
+ PIPE_UNLIMITED_INSTANCES, 65536, 65536, 0, nullptr);
+ if (h == INVALID_HANDLE_VALUE) return kNone;
+ OVERLAPPED ov{};
+ ov.hEvent = CreateEventA(nullptr, TRUE, FALSE, nullptr);
+ BOOL ok = ConnectNamedPipe(h, &ov);
+ DWORD err = GetLastError();
+ bool connected = (!ok && err == ERROR_PIPE_CONNECTED);
+ if (!connected && !ok && err == ERROR_IO_PENDING) connected = WaitForSingleObject(ov.hEvent, DWORD(ms)) == WAIT_OBJECT_0;
+ CloseHandle(ov.hEvent);
+ if (!connected) { CancelIo(h); CloseHandle(h); return kNone; }
+ return h;
+}
+#else
+using Fd = int;
+static const Fd kNone = -1;
+static int g_srv = -1;
+static bool read_n(Fd fd, void* p, size_t n, int ms) {
+ char* c = static_cast(p);
+ while (n) {
+ pollfd pf{fd, POLLIN, 0};
+ if (::poll(&pf, 1, ms) <= 0) return false;
+ const ssize_t r = ::recv(fd, c, n, 0);
+ if (r <= 0) return false;
+ c += r; n -= size_t(r);
+ }
+ return true;
+}
+static void send_raw(Fd fd, const std::string& b) { (void)!::send(fd, b.data(), b.size(), MSG_NOSIGNAL); }
+static void close_fd(Fd fd) { ::close(fd); }
+static Fd accept_client(int ms) {
+ pollfd pf{g_srv, POLLIN, 0};
+ if (::poll(&pf, 1, ms) <= 0) return kNone;
+ return ::accept(g_srv, nullptr, nullptr);
+}
+#endif
+
+static bool read_frame(Fd fd, uint32_t* op, std::string* j, int ms) {
+ uint32_t h[2];
+ if (!read_n(fd, h, 8, ms)) return false;
+ *op = h[0];
+ j->assign(h[1], '\0');
+ return h[1] == 0 || read_n(fd, &(*j)[0], h[1], ms);
+}
+static void write_frame(Fd fd, uint32_t op, const std::string& j) {
+ uint32_t h[2] = {op, uint32_t(j.size())};
+ std::string b(reinterpret_cast(h), 8);
+ b += j;
+ send_raw(fd, b);
+}
+// accept + handshake; returns the client or kNone
+static Fd handshake(int ms) {
+ const Fd fd = accept_client(ms);
+ if (fd == kNone) return kNone;
+ uint32_t op = 99;
+ std::string j;
+ CHECK(read_frame(fd, &op, &j, 3000));
+ CHECK(op == 0);
+ CHECK(has(j, "\"client_id\":\"123456\"") && has(j, "\"v\":1"));
+ write_frame(fd, 1, "{\"cmd\":\"DISPATCH\",\"data\":{\"v\":1,\"user\":{\"id\":\"1\",\"username\":\"tester\",\"global_name\":\"Tester\"}},\"evt\":\"READY\",\"nonce\":null}");
+ return fd;
+}
+// the next SET_ACTIVITY frame (answered like Discord does)
+static bool next_activity(Fd fd, std::string* j, int ms) {
+ uint32_t op = 0;
+ while (read_frame(fd, &op, j, ms)) {
+ if (op == 1 && has(*j, "SET_ACTIVITY")) {
+ write_frame(fd, 1, "{\"cmd\":\"SET_ACTIVITY\",\"data\":null,\"evt\":null,\"nonce\":\"x\"}");
+ return true;
+ }
+ }
+ return false;
+}
+
+static void session_test() {
+ std::string cleanup_dir, path;
+#if defined(_WIN32)
+ g_pipe = "\\\\.\\pipe\\psp-discord-test-" + std::to_string(GetCurrentProcessId());
+ path = g_pipe;
+ _putenv_s("PSPRECOMP_DISCORD_IPC", path.c_str());
+ _putenv_s("PSPRECOMP_DISCORD", "");
+ _putenv_s("PSPRECOMP_DISCORD_APP_ID", "");
+#else
+ char dir[] = "/tmp/psp_discord_testXXXXXX";
+ if (!::mkdtemp(dir)) { CHECK(false); return; }
+ cleanup_dir = dir;
+ path = cleanup_dir + "/discord-ipc-0";
+ g_srv = ::socket(AF_UNIX, SOCK_STREAM, 0);
+ sockaddr_un sa{};
+ sa.sun_family = AF_UNIX;
+ std::strcpy(sa.sun_path, path.c_str());
+ CHECK(::bind(g_srv, reinterpret_cast(&sa), sizeof sa) == 0);
+ CHECK(::listen(g_srv, 4) == 0);
+ ::setenv("PSPRECOMP_DISCORD_IPC", path.c_str(), 1);
+ ::unsetenv("PSPRECOMP_DISCORD");
+ ::unsetenv("PSPRECOMP_DISCORD_APP_ID");
+#endif
+
+ set_act("first");
+ psp_discord::start("123456", provider);
+ CHECK(psp_discord::available() && psp_discord::enabled());
+
+ Fd fd = handshake(5000);
+ CHECK(fd != kNone);
+ if (fd == kNone) return;
+ std::string j;
+ CHECK(next_activity(fd, &j, 5000));
+ CHECK(has(j, "\"details\":\"first\"") && has(j, "\"pid\":"));
+ CHECK(psp_discord::status() == "Connected as Tester");
+
+ // rate limit: two changes in a row -> one frame, at least ~4 s after the last, with the newest state
+ const double t0 = now();
+ set_act("second");
+ std::this_thread::sleep_for(std::chrono::milliseconds(1200));
+ set_act("third");
+ CHECK(next_activity(fd, &j, 8000));
+ CHECK(now() - t0 >= 2.5);
+ CHECK(has(j, "\"details\":\"third\""));
+
+ // ping -> pong
+ write_frame(fd, 3, "{\"p\":1}");
+ uint32_t op = 0;
+ std::string pong;
+ CHECK(read_frame(fd, &op, &pong, 3000));
+ CHECK(op == 4 && pong == "{\"p\":1}");
+
+ // off: the activity is cleared and the connection closed
+ psp_discord::set_enabled(false);
+ CHECK(next_activity(fd, &j, 3000));
+ CHECK(has(j, "\"activity\":null"));
+ CHECK(!read_frame(fd, &op, &pong, 2000)); // EOF
+ close_fd(fd);
+ CHECK(psp_discord::status() == "Off");
+
+ // on again: a new connection, the activity is shown again
+ psp_discord::set_enabled(true);
+ fd = handshake(5000);
+ CHECK(fd != kNone);
+ CHECK(next_activity(fd, &j, 6000));
+ CHECK(has(j, "\"details\":\"third\""));
+
+ // the client goes away (Discord restarted): the runtime comes back on its own and shows the activity again
+ close_fd(fd);
+ fd = handshake(8000);
+ CHECK(fd != kNone);
+ CHECK(next_activity(fd, &j, 6000));
+ CHECK(has(j, "\"details\":\"third\""));
+
+ // nothing to show: cleared
+ set_act("", false);
+ CHECK(next_activity(fd, &j, 7000));
+ CHECK(has(j, "\"activity\":null"));
+ set_act("back");
+ CHECK(next_activity(fd, &j, 7000));
+ CHECK(has(j, "\"details\":\"back\""));
+
+ // quit: cleared before the thread ends
+ std::thread t([] { psp_discord::stop(); });
+ CHECK(next_activity(fd, &j, 3000));
+ CHECK(has(j, "\"activity\":null"));
+ t.join();
+ close_fd(fd);
+#if !defined(_WIN32)
+ ::close(g_srv);
+ ::unlink(path.c_str());
+ ::rmdir(cleanup_dir.c_str());
+#endif
+}
+
+int main() {
+ json_tests();
+ session_test();
+ if (failures) { std::printf("%d failure(s)\n", failures); return 1; }
+ std::printf("discord: all tests passed\n");
+ return 0;
+}