PINE: add statistics and settings opcodes, plus a gsctl client

Debugging a GS performance problem meant restarting the emulator and reloading a
savestate for every "did you try setting X?", and the only way to read the
statistics that drive that decision was to look at the OSD. PINE already
provides a unix socket, a thread, framing, a config key and the RunOnCPUThread
marshalling pattern, but its opcodes stop at guest-RAM peek/poke plus savestates
and game identity -- no host statistics, no settings.

Adds four ARMSX2-local opcodes at 0x10+ (upstream PINE ends at 0xF, so a generic
client will never send them):

  MsgGetStats     PerformanceMetrics, all GSPerfMon counters and the texture
                  cache memory figures, as JSON.
  MsgGetSetting   read a setting by section/key.
  MsgSetSetting   write a setting, apply it, and report whether the key forces a
                  GS device reopen.
  MsgFrameAdvance step a paused VM.

MsgSetSetting writes the persisted key rather than poking EmuConfig directly,
because a direct poke is silently reverted by the next ApplySettings, which
re-derives EmuConfig from the INI layer stack. The restart_required answer comes
from a new GSOptions::IsRestartOption, sitting next to RestartOptionsAreEqual so
the two lists stay in sync.

Statistics are gathered on the PINE thread. PerformanceMetrics and g_perfmon are
benign scalar reads, but GSgetMemoryStats dereferences g_texture_cache and
g_gs_device, which are GS-thread owned, so that one is marshalled through
RunOnGSThread.

tools/gsctl.py is a stdlib-only client emitting JSON on stdout.

Verified against a headless gsrunner replay: toggling accurate_blending_unit
between 0 and 5 over the socket moves barriers 1.0 <-> 91.5 and draw calls
55.5 <-> 101.5, repeatably, with no restart.
This commit is contained in:
Brian Degenhardt
2026-07-22 21:16:45 -07:00
parent e0f1d4962a
commit 4fc1fa7c5f
4 changed files with 435 additions and 0 deletions
+5
View File
@@ -1007,6 +1007,11 @@ struct Pcsx2Config
/// (i.e. renderer change, swap chain mode change, etc.)
bool RestartOptionsAreEqual(const GSOptions& right) const;
/// Whether changing this INI key forces a GS device teardown, i.e. whether it is
/// one of the fields RestartOptionsAreEqual compares. Lets a caller mutating a
/// setting by name report the cost without diffing two whole configs.
static bool IsRestartOption(const char* ini_key);
/// Returns false if any options need to be applied to the MTGS.
bool OptionsAreEqual(const GSOptions& right) const;
+165
View File
@@ -5,11 +5,16 @@
#include "Common.h"
#include "Host.h"
#include "Elfheader.h"
#include "GS.h"
#include "GS/GSPerfMon.h"
#include "MTGS.h"
#include "PerformanceMetrics.h"
#include "SaveState.h"
#include "PINE.h"
#include "VMManager.h"
#include "vtlb.h"
#include "common/Error.h"
#include "common/SettingsInterface.h"
#include "common/Threading.h"
#include <atomic>
@@ -159,6 +164,14 @@ namespace PINEServer
MsgUUID = 0xD, /**< Returns the game UUID. */
MsgGameVersion = 0xE, /**< Returns the game verion. */
MsgStatus = 0xF, /**< Returns the emulator status. */
// ARMSX2-local extensions. Upstream PINE stops at 0xF; these are private to
// this fork, so a generic PINE client will simply never send them.
MsgGetStats = 0x10, /**< Returns host-side performance statistics as JSON. */
MsgGetSetting = 0x11, /**< Reads a setting by section/key. */
MsgSetSetting = 0x12, /**< Writes a setting by section/key and applies it. */
MsgFrameAdvance = 0x13, /**< Advances a paused VM by one frame. */
MsgUnimplemented = 0xFF /**< Unimplemented IPC message. */
};
@@ -258,6 +271,85 @@ namespace PINEServer
return !((command_len + command_size) > buf_size ||
(reply_len + reply_size) >= MAX_IPC_RETURN_SIZE);
}
/**
* Reads a length-prefixed ([u32 len][len bytes], no NUL) string argument, advancing
* buf_cnt past it. Returns false if the declared length runs off the end of the
* request, in which case the caller must fail the command.
*/
static bool ReadLengthPrefixedString(std::span<u8> buf, u32& buf_cnt, u32 buf_size, std::string* out)
{
if ((buf_cnt + 4) > buf_size)
return false;
const u32 len = FromSpan<u32>(buf, buf_cnt);
buf_cnt += 4;
// Bound the allocation by what the request could actually contain.
if (len > buf_size || (buf_cnt + len) > buf_size)
return false;
out->assign(reinterpret_cast<const char*>(&buf[buf_cnt]), len);
buf_cnt += len;
return true;
}
/**
* Builds the host-side statistics document. Called on the PINE thread.
*
* PerformanceMetrics and g_perfmon are plain scalar reads -- racy against the GS
* thread but benign, since every field is an independently-meaningful number and a
* torn sample only costs one stale stat. GSgetStats/GSgetMemoryStats are NOT safe
* here: they dereference g_texture_cache and g_gs_device, which are GS-thread
* owned, so the texture-cache memory figures are gathered via RunOnGSThread.
*/
static std::string BuildStatsJson()
{
SmallString gs_memory;
if (MTGS::IsOpen())
{
MTGS::RunOnGSThread([&gs_memory]() { GSgetMemoryStats(gs_memory); });
MTGS::WaitGS(false);
}
const auto counter = [](GSPerfMon::counter_t c) { return g_perfmon.Get(c); };
return fmt::format(
"{{"
"\"fps\":{:.3f},\"internal_fps\":{:.3f},\"speed\":{:.3f},"
"\"frame_ms_avg\":{:.3f},\"frame_ms_min\":{:.3f},\"frame_ms_max\":{:.3f},"
"\"cpu_thread_pct\":{:.3f},\"cpu_thread_ms\":{:.3f},"
"\"gs_thread_pct\":{:.3f},\"gs_thread_ms\":{:.3f},"
"\"vu_thread_pct\":{:.3f},\"vu_thread_ms\":{:.3f},"
"\"gpu_pct\":{:.3f},\"gpu_ms_avg\":{:.3f},\"gpu_ms_last\":{:.3f},"
"\"gpu_vs_invocations\":{:.0f},\"gpu_ps_invocations\":{:.0f},"
"\"prims\":{:.1f},\"draws\":{:.1f},\"draw_calls\":{:.1f},"
"\"render_passes\":{:.1f},\"barriers\":{:.1f},\"readbacks\":{:.1f},"
"\"texture_copies\":{:.1f},\"texture_uploads\":{:.1f},"
"\"draw_calls_rov\":{:.1f},\"barriers_rov\":{:.1f},\"texture_copies_rov\":{:.1f},"
"\"tc_source_hit\":{:.1f},\"tc_source_miss\":{:.1f},"
"\"tc_target_hit\":{:.1f},\"tc_target_miss\":{:.1f},"
"\"hash_cache_hit\":{:.1f},\"hash_cache_miss\":{:.1f},"
"\"gs_memory\":\"{}\",\"frame_number\":{}"
"}}",
PerformanceMetrics::GetFPS(), PerformanceMetrics::GetInternalFPS(), PerformanceMetrics::GetSpeed(),
PerformanceMetrics::GetAverageFrameTime(), PerformanceMetrics::GetMinimumFrameTime(),
PerformanceMetrics::GetMaximumFrameTime(),
PerformanceMetrics::GetCPUThreadUsage(), PerformanceMetrics::GetCPUThreadAverageTime(),
PerformanceMetrics::GetGSThreadUsage(), PerformanceMetrics::GetGSThreadAverageTime(),
PerformanceMetrics::GetVUThreadUsage(), PerformanceMetrics::GetVUThreadAverageTime(),
PerformanceMetrics::GetGPUUsage(), PerformanceMetrics::GetGPUAverageTime(),
PerformanceMetrics::GetLastGPUTime(),
PerformanceMetrics::GetGPUAverageVSInvocations(), PerformanceMetrics::GetGPUAveragePSInvocations(),
counter(GSPerfMon::Prim), counter(GSPerfMon::Draw), counter(GSPerfMon::DrawCalls),
counter(GSPerfMon::RenderPasses), counter(GSPerfMon::Barriers), counter(GSPerfMon::Readbacks),
counter(GSPerfMon::TextureCopies), counter(GSPerfMon::TextureUploads),
counter(GSPerfMon::DrawCallsROV), counter(GSPerfMon::BarriersROV), counter(GSPerfMon::TextureCopiesROV),
counter(GSPerfMon::TCSourceHit), counter(GSPerfMon::TCSourceMiss),
counter(GSPerfMon::TCTargetHit), counter(GSPerfMon::TCTargetMiss),
counter(GSPerfMon::HashCacheHit), counter(GSPerfMon::HashCacheMiss),
gs_memory.view(), PerformanceMetrics::GetFrameNumber());
}
} // namespace PINEServer
bool PINEServer::Initialize(int slot)
@@ -746,6 +838,79 @@ PINEServer::IPCBuffer PINEServer::ParseCommand(std::span<u8> buf, std::vector<u8
ret_cnt += 4;
break;
}
case MsgGetStats:
{
const std::string stats = BuildStatsJson();
const u32 size = stats.size() + 1;
if (!SafetyChecks(buf_cnt, 0, ret_cnt, size + 4, buf_size)) [[unlikely]]
goto error;
ToResultVector(ret_buffer, size, ret_cnt);
ret_cnt += 4;
memcpy(&ret_buffer[ret_cnt], stats.c_str(), size);
ret_cnt += size;
break;
}
case MsgGetSetting:
{
std::string section, key;
if (!ReadLengthPrefixedString(buf, buf_cnt, buf_size, &section) ||
!ReadLengthPrefixedString(buf, buf_cnt, buf_size, &key)) [[unlikely]]
goto error;
std::string value;
{
auto lock = Host::GetSettingsLock();
value = Host::GetSettingsInterface()->GetStringValue(section.c_str(), key.c_str(), "");
}
const u32 size = value.size() + 1;
if (!SafetyChecks(buf_cnt, 0, ret_cnt, size + 4, buf_size)) [[unlikely]]
goto error;
ToResultVector(ret_buffer, size, ret_cnt);
ret_cnt += 4;
memcpy(&ret_buffer[ret_cnt], value.c_str(), size);
ret_cnt += size;
break;
}
case MsgSetSetting:
{
std::string section, key, value;
if (!ReadLengthPrefixedString(buf, buf_cnt, buf_size, &section) ||
!ReadLengthPrefixedString(buf, buf_cnt, buf_size, &key) ||
!ReadLengthPrefixedString(buf, buf_cnt, buf_size, &value)) [[unlikely]]
goto error;
// Whether this change tears down the GS device, so the caller knows
// whether it just paid for a reopen. Everything outside this set is
// applied in place by GSUpdateConfig.
const bool restart_required = Pcsx2Config::GSOptions::IsRestartOption(key.c_str());
// Write the persisted key rather than poking EmuConfig directly: a direct
// poke is silently reverted by the next ApplySettings, which re-derives
// EmuConfig from the INI layer stack.
Host::SetBaseStringSettingValue(section.c_str(), key.c_str(), value.c_str());
Host::CommitBaseSettingChanges();
Host::RunOnCPUThread([]() { VMManager::ApplySettings(); });
const std::string reply = fmt::format("{{\"restart_required\":{}}}", restart_required ? "true" : "false");
const u32 size = reply.size() + 1;
if (!SafetyChecks(buf_cnt, 0, ret_cnt, size + 4, buf_size)) [[unlikely]]
goto error;
ToResultVector(ret_buffer, size, ret_cnt);
ret_cnt += 4;
memcpy(&ret_buffer[ret_cnt], reply.c_str(), size);
ret_cnt += size;
break;
}
case MsgFrameAdvance:
{
if (!VMManager::HasValidVM())
goto error;
if (!SafetyChecks(buf_cnt, 0, ret_cnt, 0, buf_size)) [[unlikely]]
goto error;
Host::RunOnCPUThread([]() { VMManager::FrameAdvance(1); });
break;
}
default:
{
error:
+31
View File
@@ -929,6 +929,37 @@ bool Pcsx2Config::GSOptions::operator!=(const GSOptions& right) const
return !operator==(right);
}
bool Pcsx2Config::GSOptions::IsRestartOption(const char* ini_key)
{
// INI key names for the fields compared in RestartOptionsAreEqual below; keep the
// two in sync. Names match the field names except BackThreadMode, which is stored
// as "GSBackThreadMode".
static constexpr const char* keys[] = {
"Renderer",
"Adapter",
"UseDebugDevice",
"UseBlitSwapChain",
"DisableShaderCache",
"DisableFramebufferFetch",
"DisablePS2DepthQuantization",
"DisableVertexShaderExpand",
"EnableAdrenoFramebufferFetch",
"ForceMaliFramebufferFetch",
"OverrideTextureBarriers",
"DepthFeedbackMode",
"GSBackThreadMode",
"HWAA1",
"ExclusiveFullscreenControl",
};
for (const char* key : keys)
{
if (StringUtil::Strcasecmp(key, ini_key) == 0)
return true;
}
return false;
}
bool Pcsx2Config::GSOptions::RestartOptionsAreEqual(const GSOptions& right) const
{
return OpEqu(Renderer) &&
+234
View File
@@ -0,0 +1,234 @@
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 ARMSX2 Contributors
# SPDX-License-Identifier: GPL-3.0+
"""Query and control a running ARMSX2 instance over its PINE socket.
Built for GS performance work: read the statistics that normally only appear on
the OSD, and toggle settings without restarting the emulator. Most GS settings
apply in place, so a whole settings sweep can run against one booted instance
sitting on a savestate.
Requires `EmuCore/EnablePINE = true` in the INI (or the Big Picture UI toggle).
Examples:
gsctl.py stats
gsctl.py stats --watch 1.0
gsctl.py get EmuCore/GS accurate_blending_unit
gsctl.py set EmuCore/GS accurate_blending_unit 3
gsctl.py loadstate 2
gsctl.py frameadvance
Pure stdlib; no build step. Output is JSON on stdout so it composes with jq.
"""
import argparse
import json
import os
import socket
import struct
import sys
import time
DEFAULT_SLOT = 28011
# Opcodes. 0x00-0x0F are upstream PINE; 0x10+ are ARMSX2-local extensions.
MSG_SAVE_STATE = 0x09
MSG_LOAD_STATE = 0x0A
MSG_TITLE = 0x0B
MSG_STATUS = 0x0F
MSG_GET_STATS = 0x10
MSG_GET_SETTING = 0x11
MSG_SET_SETTING = 0x12
MSG_FRAME_ADVANCE = 0x13
IPC_OK = 0
STATUS_NAMES = {0: "running", 1: "paused", 2: "shutdown"}
class PineError(Exception):
pass
def socket_path(slot):
"""Mirrors PINEServer::Initialize. Note the emulator name is still 'pcsx2'."""
if sys.platform == "darwin":
base = os.environ.get("TMPDIR", "/tmp")
else:
base = os.environ.get("XDG_RUNTIME_DIR", "/tmp")
name = "pcsx2.sock" if slot == DEFAULT_SLOT else "pcsx2.sock.%d" % slot
return os.path.join(base, name)
def lp_string(s):
"""Length-prefixed string argument: [u32 len][bytes], no NUL."""
raw = s.encode("utf-8")
return struct.pack("<I", len(raw)) + raw
class Pine:
def __init__(self, slot=DEFAULT_SLOT, timeout=10.0):
self.slot = slot
if sys.platform == "win32":
self.sock = socket.create_connection(("127.0.0.1", slot), timeout=timeout)
else:
path = socket_path(slot)
if not os.path.exists(path):
raise PineError(
"no PINE socket at %s -- is the emulator running with "
"EmuCore/EnablePINE=true?" % path
)
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.settimeout(timeout)
self.sock.connect(path)
def close(self):
self.sock.close()
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()
def _recv_exactly(self, n):
buf = b""
while len(buf) < n:
chunk = self.sock.recv(n - len(buf))
if not chunk:
raise PineError("connection closed by emulator")
buf += chunk
return buf
def request(self, opcode, payload=b""):
"""Send one command, return its reply payload (after the result byte)."""
body = struct.pack("<B", opcode) + payload
packet = struct.pack("<I", len(body) + 4) + body
self.sock.sendall(packet)
(reply_len,) = struct.unpack("<I", self._recv_exactly(4))
if reply_len < 5:
raise PineError("malformed reply length %d" % reply_len)
rest = self._recv_exactly(reply_len - 4)
if rest[0] != IPC_OK:
raise PineError(
"emulator rejected opcode 0x%02X (no VM running, or "
"unsupported by this build)" % opcode
)
return rest[1:]
@staticmethod
def _read_string(payload):
(size,) = struct.unpack("<I", payload[:4])
# size includes the trailing NUL.
return payload[4 : 4 + size - 1].decode("utf-8", "replace")
def stats(self):
return json.loads(self._read_string(self.request(MSG_GET_STATS)))
def title(self):
return self._read_string(self.request(MSG_TITLE))
def status(self):
(raw,) = struct.unpack("<I", self.request(MSG_STATUS)[:4])
return STATUS_NAMES.get(raw, "unknown(%d)" % raw)
def get_setting(self, section, key):
return self._read_string(
self.request(MSG_GET_SETTING, lp_string(section) + lp_string(key))
)
def set_setting(self, section, key, value):
payload = lp_string(section) + lp_string(key) + lp_string(str(value))
return json.loads(self._read_string(self.request(MSG_SET_SETTING, payload)))
def load_state(self, slot):
self.request(MSG_LOAD_STATE, struct.pack("<B", slot))
def save_state(self, slot):
self.request(MSG_SAVE_STATE, struct.pack("<B", slot))
def frame_advance(self):
self.request(MSG_FRAME_ADVANCE)
def split_section_key(arg):
"""'EmuCore/GS/Key' or a separate section and key. Sections contain slashes."""
if "/" not in arg:
raise PineError("expected <Section>/<Key>, got '%s'" % arg)
section, _, key = arg.rpartition("/")
return section, key
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--slot", type=int, default=DEFAULT_SLOT, help="PINE slot (default %d)" % DEFAULT_SLOT)
sub = ap.add_subparsers(dest="cmd", required=True)
p = sub.add_parser("stats", help="dump performance/GS statistics as JSON")
p.add_argument("--watch", type=float, metavar="SECONDS",
help="poll forever at this interval, one JSON object per line")
sub.add_parser("status", help="running / paused / shutdown")
sub.add_parser("title", help="current game title")
sub.add_parser("frameadvance", help="advance a paused VM by one frame")
p = sub.add_parser("get", help="read a setting")
p.add_argument("section")
p.add_argument("key", nargs="?")
p = sub.add_parser("set", help="write a setting and apply it")
p.add_argument("section")
p.add_argument("key")
p.add_argument("value", nargs="?")
p = sub.add_parser("loadstate", help="load a savestate slot")
p.add_argument("slot", type=int)
p = sub.add_parser("savestate", help="save to a savestate slot")
p.add_argument("slot", type=int)
args = ap.parse_args()
try:
with Pine(args.slot) as pine:
if args.cmd == "stats":
if args.watch:
while True:
print(json.dumps(pine.stats()), flush=True)
time.sleep(args.watch)
else:
print(json.dumps(pine.stats(), indent=2))
elif args.cmd == "status":
print(pine.status())
elif args.cmd == "title":
print(pine.title())
elif args.cmd == "frameadvance":
pine.frame_advance()
elif args.cmd == "get":
# Accept both 'get EmuCore/GS Key' and 'get EmuCore/GS/Key'.
section, key = (args.section, args.key) if args.key else split_section_key(args.section)
print(pine.get_setting(section, key))
elif args.cmd == "set":
if args.value is None:
section, key = split_section_key(args.section)
value = args.key
else:
section, key, value = args.section, args.key, args.value
result = pine.set_setting(section, key, value)
print(json.dumps(result))
if result.get("restart_required"):
print("note: this key forces a GS device reopen", file=sys.stderr)
elif args.cmd == "loadstate":
pine.load_state(args.slot)
elif args.cmd == "savestate":
pine.save_state(args.slot)
except KeyboardInterrupt:
pass
except (PineError, OSError) as e:
print("gsctl: %s" % e, file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())