feat(streaming): per-platform RetroArch core in the streaming config

This commit is contained in:
Zach Clendenen
2026-09-27 09:49:01 -05:00
parent 0afe3d2176
commit cdf2aba0da
4 changed files with 244 additions and 11 deletions

View File

@@ -423,6 +423,11 @@ class StreamingPlatformOverride(TypedDict):
label: NotRequired[str]
memory_card_sync: NotRequired[bool]
clears_stale_saves: NotRequired[bool]
# RetroArch only: the libretro core to boot instead of the broker's
# default, e.g. "bsnes". Shorthand: `snes: retroarch:bsnes`.
core: NotRequired[str]
# Lets a core the broker lists as known broken run anyway.
experimental_cores: NotRequired[bool]
class StreamingContainer(TypedDict):
@@ -448,6 +453,12 @@ class StreamingContainer(TypedDict):
# Whether this broker empties the save tree before restoring an archive,
# which is what lets the launch screen offer a save other than the newest.
clears_stale_saves: NotRequired[bool]
# A single-platform entry's RetroArch core. Beside `platforms` it is
# ignored: set it on the platform instead.
core: NotRequired[str]
# Default for every platform this container serves; a platform block's
# own value wins.
experimental_cores: NotRequired[bool]
# Broker dialect. Omitted (or "broker") is the per-emulator mod contract;
# "webstation" is the LSIO webstation container's activate/exit contract.
protocol: NotRequired[str]

View File

@@ -11,6 +11,7 @@ from __future__ import annotations
import hashlib
import json
import re
import secrets
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
@@ -44,8 +45,15 @@ PLATFORM_OVERRIDE_KEYS = (
"label",
"memory_card_sync",
"clears_stale_saves",
"core",
"experimental_cores",
)
# A libretro core as the broker's catalog names it, e.g. "parallel_n64". Only
# the shape is checked here: the broker owns the list and refuses an unknown
# core at activate with the options.
_CORE_NAME = re.compile(r"^[a-z0-9_]+$")
# Play-button text per emulator, used when a platform block sets no `label`
# of its own. Keyed by emulator name as the broker registers it (lowercase).
_EMULATOR_DISPLAY_NAMES: dict[str, str] = {
@@ -135,13 +143,19 @@ def emulator_labels() -> dict[str, str]:
return dict(_EMULATOR_DISPLAY_NAMES)
def emulator_display_label(emulator: str, platform: str) -> str:
def emulator_display_label(
emulator: str, platform: str, core: str | None = None
) -> str:
"""Play-button text for an emulator serving a platform, e.g. "PCSX2" or
"RA PPSSPP". Unknown emulators fall back to their configured name."""
"RA PPSSPP". A configured RetroArch core names itself, since the default's
display name would be wrong. Unknown emulators fall back to their
configured name."""
key = emulator.strip().lower()
if key == "retroarch":
core = _RETROARCH_CORE_NAMES.get(platform.lower(), platform.upper())
return f"RA {core}"
if core:
return f"RA {core}"
name = _RETROARCH_CORE_NAMES.get(platform.lower(), platform.upper())
return f"RA {name}"
return _EMULATOR_DISPLAY_NAMES.get(key, emulator.strip())
@@ -177,6 +191,10 @@ class ResolvedContainer:
"""Where the container sees the ROM library, when it differs from RomM's."""
capabilities: PlatformCapabilities
state_transfer: StateTransferLimits
core: str | None = None
"""The libretro core the platform asks for, None for the broker's default."""
experimental_cores: bool = False
"""Whether a core the broker lists as known broken may run anyway."""
@property
def is_webstation(self) -> bool:
@@ -211,6 +229,10 @@ class ResolvedContainer:
# Same-origin pool members are each proxied at their own path, so
# they never carry the same protocol object.
and self.protocol.name == other.protocol.name
# A member on another core would boot the game on it and file its
# states where the rest of the pool never looks.
and self.core == other.core
and self.experimental_cores == other.experimental_cores
)
def memory_card_route(self) -> str:
@@ -326,6 +348,22 @@ def _emulator_namespace(entry: dict[str, Any]) -> str:
return str(value).strip().lower()
def _core_problem(emulator: str, core: Any) -> str | None:
"""Why a configured core can't go to the broker, or None when it can.
Worded to follow "container platform '<slug>'" in a warning.
"""
if core is None or (isinstance(core, str) and not core.strip()):
return "sets an empty core"
if not isinstance(core, str):
return "sets a core that is not a name"
if emulator.strip().lower() != "retroarch":
return f"sets core '{core.strip()}' but only retroarch takes a core"
if not _CORE_NAME.match(core.strip()):
return f"sets core '{core.strip()}', which must match {_CORE_NAME.pattern}"
return None
def _resolve_one(
entry: dict[str, Any], platform: str, container_label: Any
) -> ResolvedContainer:
@@ -374,6 +412,7 @@ def _resolve_one(
capabilities = {**capabilities, "supports_disc_swap": False}
label = entry.get("label")
core = entry.get("core") or None
return ResolvedContainer(
key=broker_host or "",
host=raw_host,
@@ -381,7 +420,7 @@ def _resolve_one(
protocol=protocol,
platform=platform,
emulator=emulator,
label=str(label) if label else emulator_display_label(emulator, platform),
label=str(label) if label else emulator_display_label(emulator, platform, core),
container_label=container_label if isinstance(container_label, str) else None,
memory_card_sync=card_sync,
clears_stale_saves=clears_stale_saves,
@@ -389,6 +428,10 @@ def _resolve_one(
library_path=str(entry.get("library_path") or LIBRARY_BASE_PATH).rstrip("/"),
capabilities=capabilities,
state_transfer=state_transfer_limits(emulator),
core=core,
# Only a real boolean opts in: this runs cores known to be broken, and
# a quoted "false" is truthy to bool().
experimental_cores=entry.get("experimental_cores") is True,
)
@@ -406,6 +449,12 @@ def _platform_entries(entry: dict[str, Any]) -> list[tuple[dict[str, Any], str]]
"container missing platform/host, skipping: %s", _loggable(entry)
)
return []
if "core" in entry:
problem = _core_problem(_emulator_namespace(entry), entry["core"])
if problem is not None:
log.warning("container platform '%s' %s, skipping", platform, problem)
return []
entry = {**entry, "core": entry["core"].strip()}
return [(entry, platform)]
if not isinstance(platforms, dict):
@@ -422,7 +471,15 @@ def _platform_entries(entry: dict[str, Any]) -> list[tuple[dict[str, Any], str]]
_loggable(entry),
)
base = {k: v for k, v in entry.items() if k != "platforms"}
if "core" in entry:
# One core serves one platform; inheriting it would boot every
# platform in the map on it.
log.warning(
"container sets `core` beside `platforms`, ignoring it; set it on "
"the platform instead: %s",
_loggable(entry),
)
base = {k: v for k, v in entry.items() if k not in ("platforms", "core")}
rows: list[tuple[dict[str, Any], str]] = []
for platform, options in platforms.items():
if not isinstance(platform, str) or not platform.strip():
@@ -441,16 +498,22 @@ def _platform_overrides(
`options` is either the emulator name or a block overriding container keys.
"""
core: Any = None
if isinstance(options, str):
emulator = options.strip()
# "retroarch:bsnes" is shorthand for a block naming both.
name, colon, core = options.partition(":")
emulator = name.strip()
has_core = bool(colon)
overrides: dict[str, Any] = {}
elif isinstance(options, dict):
raw = options.get("emulator")
emulator = raw.strip() if isinstance(raw, str) else ""
has_core = "core" in options
core = options.get("core")
overrides = {
k: v
for k, v in options.items()
if k in PLATFORM_OVERRIDE_KEYS and k != "emulator"
if k in PLATFORM_OVERRIDE_KEYS and k not in ("emulator", "core")
}
for key in options:
if key not in PLATFORM_OVERRIDE_KEYS:
@@ -473,16 +536,28 @@ def _platform_overrides(
log.warning("container platform '%s' has no emulator, skipping", platform)
return None
if has_core:
problem = _core_problem(emulator, core)
if problem is not None:
log.warning("container platform '%s' %s, skipping", platform, problem)
return None
core = core.strip()
else:
core = None
# A platform block's own `label` wins; otherwise the emulator names the
# button, not the container, so "Stream on PCSX2" rather than the box.
label = overrides.get("label") or emulator_display_label(emulator, platform)
return {
label = overrides.get("label") or emulator_display_label(emulator, platform, core)
row = {
**base,
**overrides,
"platform": platform,
"emulator": emulator,
"label": label,
}
if core is not None:
row["core"] = core
return row
def resolve_entry(entry: dict[str, Any]) -> ResolvedContainer | None:

View File

@@ -430,6 +430,140 @@ def test_a_platform_entry_wins_over_the_emulator_fallback():
assert streaming.platform_capabilities("ngc")["max_slots"] == 7
# ── RetroArch core override ──────────────────────────────────────────────────
def _snes(value, **container) -> ResolvedContainer:
"""The snes record of a webstation container serving snes as `value`."""
return _resolved(_webstation(platforms={"snes": value}, **container))
def _warnings_of(caplog, build):
"""Run `build` with the romm logger captured, returning its result."""
romm_logger = logging.getLogger("romm")
romm_logger.addHandler(caplog.handler)
try:
with caplog.at_level(logging.WARNING, logger="romm"):
return build()
finally:
romm_logger.removeHandler(caplog.handler)
def test_the_shorthand_names_the_emulator_and_the_core():
container = _snes("retroarch:bsnes")
assert (container.emulator, container.core) == ("retroarch", "bsnes")
assert container.label == "RA bsnes"
def test_the_shorthand_tolerates_spaces_around_the_colon():
assert _snes(" retroarch : bsnes ").core == "bsnes"
def test_the_block_form_names_the_core():
container = _snes({"emulator": "retroarch", "core": "parallel_n64"})
assert (container.emulator, container.core) == ("retroarch", "parallel_n64")
def test_a_platform_label_wins_over_the_core_label():
assert (
_snes({"emulator": "retroarch", "core": "bsnes", "label": "SNES"}).label
== "SNES"
)
def test_no_core_leaves_the_record_as_it_was():
container = _snes("retroarch")
assert (container.core, container.experimental_cores) == (None, False)
assert container.label == "RA Snes9x"
def test_a_flat_entry_takes_a_core():
entry = {
"platform": "snes",
"protocol": "webstation",
"host": "http://192.168.1.10:3000",
"broker_host": "http://192.168.1.10:8000",
"emulator": "retroarch",
"core": "bsnes",
}
assert _resolved(entry).core == "bsnes"
@pytest.mark.parametrize(
("value", "reason"),
[
("pcsx2:bsnes", "only retroarch takes a core"),
("retroarch:", "sets an empty core"),
("retroarch:BSNES", "must match"),
({"emulator": "dolphin", "core": "bsnes"}, "only retroarch takes a core"),
({"emulator": "retroarch", "core": ""}, "sets an empty core"),
({"emulator": "retroarch", "core": None}, "sets an empty core"),
({"emulator": "retroarch", "core": 5}, "not a name"),
({"emulator": "retroarch", "core": "../x"}, "must match"),
],
)
def test_a_bad_core_skips_the_platform_with_a_warning(caplog, value, reason):
"""Booting the default instead would hide the typo behind a working game."""
resolved = _warnings_of(
caplog, lambda: resolve_entry(_webstation(platforms={"snes": value}))
)
assert resolved is None
assert "container platform 'snes'" in caplog.text
assert reason in caplog.text
def test_a_bad_core_on_a_flat_entry_skips_it(caplog):
entry = {
"platform": "snes",
"host": "http://192.168.1.10:3000",
"emulator": "retroarch",
"core": "Bad Name",
}
assert _warnings_of(caplog, lambda: resolve_entry(entry)) is None
assert "must match" in caplog.text
def test_a_container_level_core_is_ignored_beside_platforms(caplog):
"""Review Focus 5: one core serves one platform, so inheriting it would
boot every platform in the map on it."""
container = _warnings_of(caplog, lambda: _snes("retroarch", core="bsnes"))
assert container.core is None
assert "`core` beside `platforms`" in caplog.text
def test_a_quoted_false_does_not_opt_in():
"""Review Focus 4: bool("false") is True, and this opt-in runs cores
known to be broken."""
container = _snes(
{"emulator": "retroarch", "core": "bsnes", "experimental_cores": "false"}
)
assert container.experimental_cores is False
def test_the_platform_opt_in_wins_over_the_container():
inherited = _snes("retroarch:bsnes", experimental_cores=True)
overridden = _snes(
{"emulator": "retroarch", "core": "bsnes", "experimental_cores": False},
experimental_cores=True,
)
assert inherited.experimental_cores is True
assert overridden.experimental_cores is False
def test_containers_on_different_cores_are_not_one_pool():
"""Review Focus 2: a claim landing on either would boot a different core
and file its states where the other never looks."""
assert not _snes("retroarch:bsnes").interchangeable_with(_snes("retroarch"))
assert _snes("retroarch:bsnes").interchangeable_with(_snes("retroarch:bsnes"))
opted = _snes("retroarch:bsnes", experimental_cores=True)
assert not opted.interchangeable_with(_snes("retroarch:bsnes"))
def test_emulator_display_label_names_a_configured_core():
assert emulator_display_label("retroarch", "snes", "bsnes") == "RA bsnes"
assert emulator_display_label("retroarch", "snes", None) == "RA Snes9x"
def test_an_unconfigured_platform_still_has_no_states():
"""The fallback keys off a configured container, so a platform nobody
streams stays out of the save-state UI."""

View File

@@ -221,7 +221,8 @@
# containers:
# # One container can serve many platforms. Container keys are defaults
# # for every platform it serves; a platform block may override emulator,
# # label, memory_card_sync, and clears_stale_saves.
# # label, memory_card_sync, clears_stale_saves, core and
# # experimental_cores.
# - protocol: webstation
# host: https://192.168.1.56:3010 # browser-facing UI, must be https
# subfolder: /streaming # matches the container's SUBFOLDER
@@ -241,3 +242,15 @@
# wii:
# emulator: dolphin
# clears_stale_saves: true
# # RetroArch boots the broker's best-tested core for each platform.
# # To pick another libretro core, name it after the emulator...
# gba: retroarch:gpsp
# # ...or set `core` in a block. The broker refuses a core it doesn't
# # know and warns about one nobody has tested yet; see
# # https://github.com/romm-streaming/romm-broker (retroarch-cores docs).
# n64:
# emulator: retroarch
# core: parallel_n64
# # Lets a core the broker lists as known broken run anyway. Also
# # allowed on the container, as a default for every platform.
# # experimental_cores: true