diff --git a/backend/config/__init__.py b/backend/config/__init__.py index 0d0d38275..059753728 100644 --- a/backend/config/__init__.py +++ b/backend/config/__init__.py @@ -277,6 +277,12 @@ TINFOIL_WELCOME_MESSAGE: Final[str] = _get_env( "TINFOIL_WELCOME_MESSAGE", "RomM Switch Library" ) +# EMULATOR STREAMING +STREAMING_BROKER_SECRET: Final[str] = _get_env("STREAMING_BROKER_SECRET", "") +STREAMING_SAVE_TIMEOUT: Final[int] = safe_int( + _get_env("STREAMING_SAVE_TIMEOUT"), 45 +) # 45 seconds + # SENTRY SENTRY_DSN: Final[str | None] = _get_env("SENTRY_DSN") diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index a57685de6..97503862a 100644 --- a/backend/config/config_manager.py +++ b/backend/config/config_manager.py @@ -104,6 +104,13 @@ class NetplayICEServer(TypedDict): credential: NotRequired[str] +class StreamingContainer(TypedDict): + platform: str + host: str + broker_host: str + label: str + + class Config: CONFIG_FILE_MOUNTED: bool CONFIG_FILE_WRITABLE: bool @@ -136,6 +143,8 @@ class Config: SCAN_MEDIA: list[str] GAMELIST_MEDIA_THUMBNAIL: MetadataMediaType GAMELIST_MEDIA_IMAGE: MetadataMediaType + STREAMING_ENABLED: bool + STREAMING_CONTAINERS: list[StreamingContainer] def __init__(self, **entries): self.__dict__.update(entries) @@ -456,6 +465,10 @@ class ConfigManager: PEGASUS_AUTO_EXPORT_ON_SCAN=pydash.get( self._raw_config, "scan.pegasus.export", False ), + STREAMING_ENABLED=pydash.get(self._raw_config, "streaming.enabled", False), + STREAMING_CONTAINERS=pydash.get( + self._raw_config, "streaming.containers", [] + ), ) def _get_ejs_controls(self) -> dict[str, EjsControls]: @@ -726,6 +739,14 @@ class ConfigManager: ) self.config.GAMELIST_MEDIA_IMAGE = MetadataMediaType.SCREENSHOT + if not isinstance(self.config.STREAMING_ENABLED, bool): + log.critical("Invalid config.yml: streaming.enabled must be a boolean") + sys.exit(3) + + if not isinstance(self.config.STREAMING_CONTAINERS, list): + log.critical("Invalid config.yml: streaming.containers must be a list") + sys.exit(3) + def get_config(self) -> Config: try: with open(self.config_file, "r") as config_file: diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py new file mode 100644 index 000000000..2fee36aff --- /dev/null +++ b/backend/endpoints/streaming.py @@ -0,0 +1,747 @@ +import asyncio +import json +import logging +import urllib.error +import urllib.request +from datetime import datetime, timezone +from typing import Annotated, Any, TypedDict +from urllib.parse import urlparse, urlunparse + +from fastapi import Body, HTTPException, Request +from fastapi.responses import JSONResponse +from pydantic import BaseModel, Field + +from config import LIBRARY_BASE_PATH, STREAMING_BROKER_SECRET, STREAMING_SAVE_TIMEOUT +from config.config_manager import config_manager as cm +from decorators.auth import protected_route +from handler.auth.constants import Scope +from handler.database import db_rom_handler +from handler.redis_handler import async_cache +from models.user import Role +from utils.router import APIRouter + +log = logging.getLogger("romm") + +router = APIRouter(prefix="/streaming", tags=["streaming"]) + +# Sessions are stored in Redis so they are shared across uvicorn workers and +# survive backend restarts (the emulator container keeps running either way). +# Claiming uses SET NX, which is atomic in Redis. Two concurrent claims for +# the same container cannot both succeed, with no in-process locking needed. +_SESSION_KEY_PREFIX = "romm:streaming:session:" + +# An active session is long-lived (a game can run for hours), but the key +# must not live forever: if the broker container dies or the backend +# crashes mid-session, the TTL ensures the container is eventually +# reclaimable instead of wedged until an admin force-releases. Control +# calls (save-state / volume / mute / save-and-exit) refresh the TTL so a +# session in active use never expires. +SESSION_TTL_SECONDS = 6 * 60 * 60 + +# When save-and-exit runs with wait=false the broker is still killing the +# emulator in the background when the route returns. A short drain TTL +# keeps the key briefly so a concurrent new claim can't /launch on top of +# a not-yet-dead emulator (which would lose the in-flight save). The key +# expires on its own; no explicit DELETE. +SESSION_DRAIN_SECONDS = 5 + + +def _session_redis_key(session_key: str) -> str: + return f"{_SESSION_KEY_PREFIX}{session_key}" + + +async def _get_session(session_key: str) -> dict[str, Any] | None: + raw = await async_cache.get(_session_redis_key(session_key)) + if raw is None: + return None + try: + return json.loads(raw) + except (TypeError, json.JSONDecodeError): + # Corrupt entry, drop it rather than wedging the container forever. + await async_cache.delete(_session_redis_key(session_key)) + return None + + +async def _refresh_session(session_key: str) -> None: + """Reset the session TTL back to the full window. Called after every + successful control op so a session in active use never expires; only an + abandoned one (broker dead / backend crashed) ages out.""" + await async_cache.expire(_session_redis_key(session_key), SESSION_TTL_SECONDS) + + +def _assert_session_owner(session: dict[str, Any], request: Request) -> None: + """Only the user who claimed a session (or an admin) may control it.""" + if session.get("user_id") == request.user.id: + return + if request.user.role == Role.ADMIN: + return + raise HTTPException(status_code=403, detail="Session is claimed by another user") + + +def _parse_host_url(host: str) -> str | None: + """Validate a configured host/broker_host string and return it stripped, + or None when it has no scheme (urlparse yields hostname=None for a bare + 'host:port', which would produce the broken '//None:8000/...' string). + Operators must write a scheme, matching the documented config examples.""" + host = host.strip().rstrip("/") + if not host: + return None + parsed = urlparse(host) + if not parsed.scheme or not parsed.hostname: + return None + return host + + +def _derive_broker_host(container: dict[str, Any]) -> str | None: + """Resolve the broker API host for a container: broker_host if set, + otherwise the stream host with its port swapped to 8000. Returns None + when neither resolves to a usable scheme-bearing URL.""" + broker_host = _parse_host_url(container.get("broker_host", "")) + if broker_host: + return broker_host.rstrip("/") + stream_host = _parse_host_url(container.get("host", "")) + if not stream_host: + return None + parsed = urlparse(stream_host) + return urlunparse(parsed._replace(netloc=f"{parsed.hostname}:8000")).rstrip("/") + + +def _container_key(container: dict[str, Any]) -> str: + """Stable unique key for a container, derived the same way as the broker URL.""" + return _derive_broker_host(container) or "" + + +# Per-platform save-state capabilities, the single source of truth for how +# many save slots each emulator exposes. The broker enforces its own ceiling; +# this table lets RomM reject an out-of-range slot before calling the broker +# (a clean 422 instead of a broker 502) and ships the same numbers to the +# frontend via /config, so the slot selector is not a second hardcoded copy. + + +class PlatformCapabilities(TypedDict): + max_slots: int # manual save slots, selectable as 1..max_slots + has_autosave: bool # whether a dedicated autosave slot can be loaded + autosave_slot: int # that slot's index (loadable, not savable), 0 if none + + +# Keyed by platform slug (lowercase). A platform absent here gets no save-state +# UI until its broker's slot semantics are known. +_PLATFORM_CAPABILITIES: dict[str, PlatformCapabilities] = { + # Dolphin (ngc, wii, wiiu): slots 1-7 manual, slot 8 autosave. + "ngc": {"max_slots": 7, "has_autosave": True, "autosave_slot": 8}, + "wii": {"max_slots": 7, "has_autosave": True, "autosave_slot": 8}, + "wiiu": {"max_slots": 7, "has_autosave": True, "autosave_slot": 8}, + # PCSX2 (ps2) and xemu (xbox): slots 1-9 manual, slot 10 autosave. + "ps2": {"max_slots": 9, "has_autosave": True, "autosave_slot": 10}, + "xbox": {"max_slots": 9, "has_autosave": True, "autosave_slot": 10}, +} + +_NO_CAPABILITIES: PlatformCapabilities = { + "max_slots": 0, + "has_autosave": False, + "autosave_slot": 0, +} + + +def platform_capabilities(platform: str) -> PlatformCapabilities: + """Save-state capabilities for a platform slug, or a no-slots default.""" + return _PLATFORM_CAPABILITIES.get(platform.lower(), _NO_CAPABILITIES) + + +# Coarse request-body bounds, derived from the table so the slot ranges live in +# exactly one place. The per-platform check in the routes is the tighter, +# authoritative guard; these just reject obviously out-of-range input up front. +_MAX_SAVE_SLOT = max( + (c["max_slots"] for c in _PLATFORM_CAPABILITIES.values()), default=1 +) +_MAX_LOAD_SLOT = max( + (max(c["max_slots"], c["autosave_slot"]) for c in _PLATFORM_CAPABILITIES.values()), + default=1, +) + + +def _assert_valid_slot(platform: str, slot: int, *, allow_autosave: bool) -> None: + """Reject a slot the platform does not expose before hitting the broker.""" + caps = platform_capabilities(platform) + valid = 1 <= slot <= caps["max_slots"] + if allow_autosave and caps["has_autosave"] and slot == caps["autosave_slot"]: + valid = True + if not valid: + raise HTTPException( + status_code=422, + detail=f"Slot {slot} is not available for platform '{platform}'", + ) + + +class ClaimSessionRequest(BaseModel): + rom_id: Annotated[int, Field(ge=1)] + + +class SaveAndExitRequest(BaseModel): + slot: Annotated[int, Field(ge=0, le=10)] = 0 + wait: bool = True + + +class VolumeRequest(BaseModel): + level: Annotated[int, Field(ge=0, le=100)] + + +class MuteRequest(BaseModel): + mute: bool | None = None # None = toggle, True/False = explicit set + + +class SaveStateRequest(BaseModel): + # Coarse union bound; the route validates the exact per-platform ceiling + # against _PLATFORM_CAPABILITIES. + slot: Annotated[int, Field(ge=1, le=_MAX_SAVE_SLOT)] = 1 + + +class LoadStateRequest(BaseModel): + # Coarse union bound (widest is the autosave slot); the route validates the + # exact per-platform ceiling against _PLATFORM_CAPABILITIES. + slot: Annotated[int, Field(ge=1, le=_MAX_LOAD_SLOT)] = 1 + + +def _get_streaming_config() -> dict[str, Any]: + """Extract streaming config from the parsed Config object""" + cfg = cm.get_config() + + return {"enabled": cfg.STREAMING_ENABLED, "containers": cfg.STREAMING_CONTAINERS} + + +# ── Routes ──────────────────────────────────────────────────────────────────── + + +def _container_for_platform(platform: str) -> dict[str, Any] | None: + cfg = _get_streaming_config() + if not cfg.get("enabled", False): + return None + lower = platform.lower() + for entry in cfg.get("containers", []): + if not isinstance(entry, dict): + continue + # An entry needs both a platform and a scheme-bearing host. + # Skipping a malformed entry here means claim / control routes raise + # a clean 404 instead of a 500 on container["host"]. + if entry.get("platform", "").lower() != lower: + continue + if not _parse_host_url(entry.get("host", "")): + log.warning( + "container for platform '%s' missing a scheme-bearing " + "host, skipping: %s", + platform, + entry, + ) + continue + return entry + return None + + +async def _resolve_owned_session( + platform: str, request: Request +) -> tuple[dict[str, Any], str, dict[str, Any]]: + """Map platform → container, fetch its active session, verify ownership. + + Returns (container, session_key, session). Raises 404 when the platform has + no configured container or no active session, 403 when the session belongs + to a different user. + """ + container = _container_for_platform(platform) + if container is None: + raise HTTPException( + status_code=404, + detail=f"No streaming container configured for platform '{platform}'", + ) + session_key = _container_key(container) + session = await _get_session(session_key) + if session is None: + raise HTTPException( + status_code=404, detail=f"No active session for platform '{platform}'" + ) + _assert_session_owner(session, request) + return container, session_key, session + + +# ── Broker communication ──────────────────────────────────────────────────────────────────── + + +def _broker_url(container: dict[str, Any], path: str) -> str: + """ + Build the URL for the ROM broker API. + + The broker runs inside the emulator container on BROKER_PORT (default 8000). + `broker_host` in config.yml is the host:port of the broker endpoint - + separate from `host` which is the browser-facing stream URL. + + If broker_host is not set, we assume it is on the same host and swap the port. + Example: + host: http://192.168.1.51:3000 (Selkies web UI, browser-facing) + broker_host: http://192.168.1.51:8000 (broker API, server-to-server) + """ + broker_host = _derive_broker_host(container) + if not broker_host: + # No usable broker host, raise a 502 with a clear cause so the + # operator sees the misconfiguration instead of an opaque KeyError. + raise HTTPException( + status_code=502, + detail=( + "Streaming container has no usable broker_host/host. " + "Set broker_host (or host with a scheme, e.g. http://...) " + "in the streaming.containers config." + ), + ) + + return f"{broker_host}{path}" + + +def _broker_secret(container: dict[str, Any]) -> str: + return STREAMING_BROKER_SECRET or container.get("broker_secret", "") + + +def _broker_request( + container: dict[str, Any], + path: str, + *, + method: str = "POST", + body: dict[str, Any] | None = None, + timeout: float, +) -> Any: + """ + Send a signed request to the broker and return its parsed JSON body (an + empty dict when the broker replies with no content). Uses only Python + stdlib urllib, no extra dependencies. Raises the underlying urllib/OS + error; callers decide whether to surface or swallow it. + """ + url = _broker_url(container, path) + secret = _broker_secret(container) + headers = {"X-Broker-Secret": secret} if secret else {} + data = None + if body is not None: + data = json.dumps(body).encode() + headers["Content-Type"] = "application/json" + headers["Content-Length"] = str(len(data)) + req = urllib.request.Request(url, data=data, method=method, headers=headers) + with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310 + raw = resp.read() + return json.loads(raw) if raw else {} + + +def _broker_request_safe( + container: dict[str, Any], + path: str, + label: str, + *, + method: str = "POST", + body: dict[str, Any] | None = None, + timeout: float, +) -> Any | None: + """ + Best-effort variant of _broker_request: returns the parsed body, or None if + the broker is unreachable or errors. Never raises, control ops must not 500 + on a broker hiccup. + """ + try: + return _broker_request( + container, path, method=method, body=body, timeout=timeout + ) + except Exception as exc: + log.warning("broker %s failed, %s", label, exc) + return None + + +def _call_broker(container: dict[str, Any], rom_path: str, rom_name: str) -> None: + """ + POST to the broker's /launch endpoint to tell the emulator container to + load a ROM. + + Raises HTTPException if the broker is unreachable or returns an error. + """ + url = _broker_url(container, "/launch") + try: + body = _broker_request( + container, + "/launch", + body={"rom_path": rom_path, "rom_name": rom_name}, + timeout=10, + ) + log.info("broker launched ROM, %s", body) + except urllib.error.HTTPError as exc: + error_body = exc.read().decode(errors="replace") + log.error("broker HTTP error %d: %s", exc.code, error_body) + try: + detail = json.loads(error_body) + except Exception: + detail = error_body + raise HTTPException( + status_code=502, + detail=f"Broker returned {exc.code}: {detail}", + ) from exc + except (urllib.error.URLError, OSError) as exc: + log.error("broker unreachable at %s: %s", url, exc) + raise HTTPException( + status_code=503, + detail=( + f"Could not reach ROM broker at {url}. " + "Check that broker.py is running inside the emulator container " + "and that port 8000 is reachable from the RomM host." + ), + ) from exc + + +def _save_and_exit_broker( + container: dict[str, Any], slot: int = 0, wait: bool = True +) -> bool: + """ + POST /save-and-exit to the broker. Best-effort, logs but never raises. + With wait=True the call blocks until save+kill completes (use for button press). + With wait=False the broker fires save+kill in the background (use for navigation away). + Returns True if the broker reported a successful save. + """ + # Waiting brokers can legitimately block for a while: rpcs3 polls the + # savestate write for up to SAVE_WAIT (30s default) and xemu's QMP + # save + reset path can approach that too. Time out past the slowest + # broker so a slow-but-successful save is not reported as saved=False. + # Overridable for operators who raise SAVE_WAIT on a broker. + body = _broker_request_safe( + container, + "/save-and-exit", + "save-and-exit", + body={"slot": slot, "wait": wait}, + timeout=STREAMING_SAVE_TIMEOUT if wait else 5, + ) + saved = bool(body and body.get("saved", False)) + log.info("broker save-and-exit, saved=%s slot=%d wait=%s", saved, slot, wait) + return saved + + +def _volume_broker(container: dict[str, Any], level: int) -> bool: + """POST /volume to the broker. Best-effort, logs but never raises.""" + body = _broker_request_safe( + container, "/volume", "volume", body={"level": level}, timeout=5 + ) + return bool(body and body.get("status") == "ok") + + +def _mute_broker(container: dict[str, Any], mute: bool | None) -> bool | None: + """POST /mute to the broker. Returns confirmed mute state, or None on error.""" + body = _broker_request_safe( + container, + "/mute", + "mute", + body={} if mute is None else {"mute": mute}, + timeout=5, + ) + return body.get("mute") if body is not None else None + + +def _save_state_broker(container: dict[str, Any], slot: int) -> bool: + """POST /save-state to the broker. Returns True if the request was accepted.""" + body = _broker_request_safe( + container, "/save-state", "save-state", body={"slot": slot}, timeout=5 + ) + return bool(body and body.get("status") == "saving") + + +def _load_state_broker(container: dict[str, Any], slot: int) -> bool: + """POST /load-state to the broker. Returns True if broker confirmed success.""" + # Timeout covers the worst case: 9 slot cycles x ~5s xdotool timeout. + body = _broker_request_safe( + container, "/load-state", "load-state", body={"slot": slot}, timeout=60 + ) + return bool(body and body.get("loaded", False)) + + +def _stop_broker(container: dict[str, Any]) -> None: + """Tell the broker to stop emulator. Best-effort, don't raise on failure.""" + _broker_request_safe(container, "/launch", "stop", method="DELETE", timeout=5) + + +# ── Routes ──────────────────────────────────────────────────────────────────── + + +@protected_route(router.get, "/config", [Scope.ROMS_READ]) +async def get_config(request: Request) -> JSONResponse: + """Return streaming configuration to the frontend""" + cfg = _get_streaming_config() + + safe_containers = [] + for c in cfg.get("containers", []): + if not c.get("platform") or not c.get("host"): + log.warning("container missing platform/host, skipping: %s", c) + continue + + platform = c.get("platform", "") + safe_containers.append( + { + "platform": platform, + "host": c.get("host"), + "label": c.get("label") or platform.upper(), + # Ship slot capabilities so the frontend selector reads them + # instead of keeping its own hardcoded per-platform copy. + "capabilities": platform_capabilities(platform), + } + ) + + return JSONResponse( + { + "enabled": cfg.get("enabled", False), + "containers": safe_containers, + } + ) + + +@protected_route(router.post, "/sessions", [Scope.ROMS_READ]) +async def claim_session( + request: Request, req: Annotated[ClaimSessionRequest, Body()] +) -> JSONResponse: + """ + Claim a streaming session and tell the broker to load the ROM. + + The ROM's filesystem path is derived server-side from its database row - + the client only supplies a ROM id, never a path. + Returns 404 if the ROM doesn't exist or no container serves its platform. + Returns 409 if the container is already occupied. + Returns 502/503 if the broker rejects the launch or is unreachable. + """ + rom = db_rom_handler.get_rom(req.rom_id) + if rom is None: + raise HTTPException(status_code=404, detail="ROM not found") + + container = _container_for_platform(rom.platform_slug) + if container is None: + raise HTTPException( + status_code=404, + detail=f"No streaming container configured for platform '{rom.platform_slug}'", + ) + + # The emulator containers mount the RomM library at the same path the + # backend uses (LIBRARY_BASE_PATH, /romm/library by default), so the + # backend-side path is valid inside the broker container too. + rom_path = f"{LIBRARY_BASE_PATH}/{rom.full_path}" + rom_name = rom.name or rom.fs_name_no_ext + + session_key = _container_key(container) + now = datetime.now(timezone.utc).isoformat() + session = { + "rom_id": rom.id, + "rom_name": rom_name, + "claimed_at": now, + "user_id": request.user.id, + } + + # SET NX is atomic: exactly one concurrent claim wins the key. The TTL + # bounds how long an abandoned session (broker dead / backend crashed) + # can hold the container; control calls refresh it while in active use. + claimed = await async_cache.set( + _session_redis_key(session_key), + json.dumps(session), + nx=True, + ex=SESSION_TTL_SECONDS, + ) + if not claimed: + existing = await _get_session(session_key) or {} + raise HTTPException( + status_code=409, + detail={ + "message": "Session in use", + "rom_name": existing.get("rom_name"), + "claimed_at": existing.get("claimed_at"), + }, + ) + + try: + # Tell the broker to load the ROM, raises HTTPException on failure. + # Wrapped in asyncio.to_thread because urllib is synchronous. + await asyncio.to_thread(_call_broker, container, rom_path, rom_name) + except Exception: + # Launch failed, free the claim so the container isn't wedged. + await async_cache.delete(_session_redis_key(session_key)) + raise + + log.info("session claimed, platform=%s rom=%s", rom.platform_slug, rom_name) + + return JSONResponse( + { + "platform": rom.platform_slug, + "host": container.get("host", ""), + "label": container.get("label", rom.platform_slug.upper()), + "rom_name": rom_name, + "claimed_at": now, + } + ) + + +@protected_route(router.post, "/sessions/{platform}/save-and-exit", [Scope.ROMS_READ]) +async def save_and_exit_session( + request: Request, platform: str, req: Annotated[SaveAndExitRequest, Body()] +) -> JSONResponse: + """ + Save game state then release the session. + wait=true (default): blocks until broker confirms save+kill complete. + wait=false: broker fires save+kill in background, returns immediately. + """ + container, session_key, _ = await _resolve_owned_session(platform, request) + + saved = await asyncio.to_thread( + _save_and_exit_broker, container, slot=req.slot, wait=req.wait + ) + + if req.wait: + # Broker confirmed the save+kill is done, the key can go now. + await async_cache.delete(_session_redis_key(session_key)) + else: + # Broker is still killing the emulator in the background. Drop the + # key to a short drain TTL instead of deleting it outright: a + # concurrent new claim is briefly blocked so it can't /launch on + # top of a not-yet-dead emulator (which would lose the in-flight + # save). The marker is JSON so _get_session leaves it in place + # (a bare string would parse as corrupt and be deleted, ending + # the drain early). The key expires on its own once the window passes. + await async_cache.set( + _session_redis_key(session_key), + json.dumps({"draining": True}), + ex=SESSION_DRAIN_SECONDS, + ) + log.info("save-and-exit, platform=%s saved=%s", platform, saved) + return JSONResponse({"status": "ok", "saved": saved, "platform": platform}) + + +@protected_route(router.post, "/sessions/{platform}/volume", [Scope.ROMS_READ]) +async def set_volume( + request: Request, platform: str, req: Annotated[VolumeRequest, Body()] +) -> JSONResponse: + """Set emulator audio volume (0-100).""" + container, session_key, _ = await _resolve_owned_session(platform, request) + + ok = await asyncio.to_thread(_volume_broker, container, req.level) + if not ok: + raise HTTPException(status_code=502, detail="Broker failed to set volume") + + await _refresh_session(session_key) + return JSONResponse({"status": "ok", "level": req.level, "platform": platform}) + + +@protected_route(router.post, "/sessions/{platform}/mute", [Scope.ROMS_READ]) +async def set_mute( + request: Request, platform: str, req: Annotated[MuteRequest, Body()] +) -> JSONResponse: + """Toggle or explicitly set mute state. Omit body to toggle.""" + container, session_key, _ = await _resolve_owned_session(platform, request) + + confirmed = await asyncio.to_thread(_mute_broker, container, req.mute) + if confirmed is None: + raise HTTPException(status_code=502, detail="Broker failed to set mute state") + + await _refresh_session(session_key) + return JSONResponse({"status": "ok", "mute": confirmed, "platform": platform}) + + +@protected_route(router.post, "/sessions/{platform}/save-state", [Scope.ROMS_READ]) +async def save_state( + request: Request, platform: str, req: Annotated[SaveStateRequest, Body()] +) -> JSONResponse: + """Save game state to a manual slot without stopping the emulator.""" + container, session_key, _ = await _resolve_owned_session(platform, request) + _assert_valid_slot(platform, req.slot, allow_autosave=False) + + ok = await asyncio.to_thread(_save_state_broker, container, req.slot) + if not ok: + raise HTTPException(status_code=502, detail="Broker failed to save state") + + await _refresh_session(session_key) + return JSONResponse({"status": "saving", "slot": req.slot, "platform": platform}) + + +@protected_route(router.post, "/sessions/{platform}/load-state", [Scope.ROMS_READ]) +async def load_state( + request: Request, platform: str, req: Annotated[LoadStateRequest, Body()] +) -> JSONResponse: + """Load game state from a manual slot or the platform's autosave slot.""" + container, session_key, _ = await _resolve_owned_session(platform, request) + _assert_valid_slot(platform, req.slot, allow_autosave=True) + + ok = await asyncio.to_thread(_load_state_broker, container, req.slot) + if not ok: + raise HTTPException(status_code=502, detail="Broker failed to load state") + + await _refresh_session(session_key) + return JSONResponse( + {"status": "ok", "loaded": True, "slot": req.slot, "platform": platform} + ) + + +@protected_route(router.delete, "/sessions/{platform}", [Scope.ROMS_READ]) +async def release_session(request: Request, platform: str) -> JSONResponse: + """Release a session and tell the broker to stop the emulator.""" + container = _container_for_platform(platform) + if container is None: + # Streaming disabled or platform unconfigured, nothing to release. + return JSONResponse({"status": "not_found", "platform": platform}) + + session_key = _container_key(container) + session = await _get_session(session_key) + if session is None: + return JSONResponse({"status": "not_found", "platform": platform}) + + _assert_session_owner(session, request) + await async_cache.delete(_session_redis_key(session_key)) + + # Best-effort stop, don't block the user on broker errors. + await asyncio.to_thread(_stop_broker, container) + + log.info("session released, platform=%s", platform) + return JSONResponse({"status": "released", "platform": platform}) + + +@protected_route(router.get, "/sessions", [Scope.ROMS_READ]) +async def list_sessions(request: Request) -> JSONResponse: + """Admin debug view, active sessions keyed by broker URL.""" + if request.user.role != Role.ADMIN: + raise HTTPException(status_code=403, detail="Forbidden") + + sessions: dict[str, Any] = {} + async for key in async_cache.scan_iter(match=f"{_SESSION_KEY_PREFIX}*"): + raw = await async_cache.get(key) + if raw is None: + continue + try: + s = json.loads(raw) + except (TypeError, json.JSONDecodeError): + continue + # scan_iter yields bytes unless the client decodes responses. + key_str = key.decode() if isinstance(key, bytes) else key + sessions[key_str.removeprefix(_SESSION_KEY_PREFIX)] = { + "rom_name": s.get("rom_name"), + "claimed_at": s.get("claimed_at"), + "user_id": s.get("user_id"), + } + return JSONResponse(sessions) + + +@protected_route(router.delete, "/sessions", [Scope.ROMS_READ]) +async def force_release_all(request: Request) -> JSONResponse: + """Force-release all active sessions.""" + if request.user.role != Role.ADMIN: + raise HTTPException(status_code=403, detail="Forbidden") + + # Map container keys back to configs so each broker can be told to stop - + # deleting only the Redis keys would leave the games running. + containers_by_key = { + _container_key(c): c + for c in _get_streaming_config().get("containers", []) + if isinstance(c, dict) + } + + released = [] + async for key in async_cache.scan_iter(match=f"{_SESSION_KEY_PREFIX}*"): + await async_cache.delete(key) + # scan_iter yields bytes unless the client decodes responses. + key_str = key.decode() if isinstance(key, bytes) else key + container_key = key_str.removeprefix(_SESSION_KEY_PREFIX) + container = containers_by_key.get(container_key) + if container is not None: + # Best-effort stop; a broker error must not abort the sweep. + await asyncio.to_thread(_stop_broker, container) + released.append(container_key) + log.info("all sessions force-released by admin, %s", released) + return JSONResponse({"status": "released", "platforms": released}) diff --git a/backend/main.py b/backend/main.py index 54d0dc3f8..e9f12072c 100644 --- a/backend/main.py +++ b/backend/main.py @@ -50,6 +50,7 @@ from endpoints.screenshots import router as screenshots_router from endpoints.search import router as search_router from endpoints.states import router as states_router from endpoints.stats import router as stats_router +from endpoints.streaming import router as streaming_router from endpoints.sync import router as sync_router from endpoints.tasks import router as tasks_router from endpoints.user import router as user_router @@ -175,6 +176,7 @@ app.include_router(collections_router, prefix="/api") app.include_router(export_router, prefix="/api") app.include_router(netplay_router, prefix="/api") app.include_router(permissions_router, prefix="/api") +app.include_router(streaming_router, prefix="/api") app.mount("/ws", socket_handler.socket_app) app.mount("/netplay", netplay_socket_handler.socket_app) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py new file mode 100644 index 000000000..a0111d77e --- /dev/null +++ b/backend/tests/endpoints/test_streaming.py @@ -0,0 +1,473 @@ +import asyncio +import logging +from contextlib import contextmanager +from datetime import timedelta +from unittest.mock import MagicMock, patch + +import httpx +import pytest +from fastapi.testclient import TestClient +from main import app + +from config import LIBRARY_BASE_PATH, OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS +from handler.auth import oauth_handler +from handler.database import db_platform_handler, db_rom_handler +from handler.redis_handler import async_cache +from models.platform import Platform +from models.rom import Rom +from models.user import User + + +@pytest.fixture +def client(): + with TestClient(app) as client: + yield client + + +@pytest.fixture(autouse=True) +def clear_streaming_sessions(): + """Streaming sessions live in Redis (fakeredis under pytest) - start clean.""" + asyncio.run(async_cache.flushall()) + yield + + +def _access_token(user: User): + return oauth_handler.create_access_token( + data={ + "sub": user.username, + "iss": "romm:oauth", + "scopes": " ".join(user.oauth_scopes), + }, + expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS), + ) + + +@pytest.fixture +def access_token(admin_user: User): + return _access_token(admin_user) + + +@pytest.fixture +def viewer_access_token(viewer_user: User): + return _access_token(viewer_user) + + +def _mock_cm(enabled=True, containers=None): + """Return a mock config_manager that yields the given streaming config.""" + cfg = MagicMock() + cfg.STREAMING_ENABLED = enabled + cfg.STREAMING_CONTAINERS = containers or [] + return cfg + + +@contextmanager +def _streaming(*containers, enabled=True): + """Patch the streaming config to serve exactly the given containers.""" + with patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(enabled=enabled, containers=list(containers)), + ): + yield + + +def _container_for(rom: Rom, broker_host="http://192.168.1.10:8000"): + return { + "platform": rom.platform_slug, + "host": "http://192.168.1.10:3000", + "broker_host": broker_host, + } + + +def _rom_on(slug: str) -> Rom: + """Create a platform with the given slug and a ROM on it.""" + platform = db_platform_handler.add_platform( + Platform(name=slug, slug=slug, fs_slug=slug) + ) + return db_rom_handler.add_rom( + Rom( + platform_id=platform.id, + name=f"{slug}-rom", + slug=f"{slug}-rom", + fs_name=f"{slug}.zip", + fs_name_no_tags=slug, + fs_name_no_ext=slug, + fs_extension="zip", + fs_path=f"{slug}/roms", + ) + ) + + +def _auth(token): + return {"Authorization": f"Bearer {token}"} + + +def _claim(client, token, rom_id): + return client.post( + "/api/streaming/sessions", json={"rom_id": rom_id}, headers=_auth(token) + ) + + +def _claim_ok(client, token, rom_id): + """Claim with the broker launch stubbed - the common happy-path setup.""" + with patch("endpoints.streaming._call_broker"): + return _claim(client, token, rom_id) + + +# ── /config ─────────────────────────────────────────────────────────────────── + + +def test_get_config_requires_auth(client): + assert client.get("/api/streaming/config").status_code == 403 + + +def test_get_config_warns_on_missing_platform(client, access_token, caplog): + # The "romm" logger has propagate=False, so caplog's handler must be + # added directly to it rather than relying on root-logger propagation. + bad_container = {"host": "http://192.168.1.10:3000"} # no "platform" + romm_logger = logging.getLogger("romm") + romm_logger.addHandler(caplog.handler) + try: + with _streaming(bad_container): + with caplog.at_level(logging.WARNING, logger="romm"): + response = client.get( + "/api/streaming/config", headers=_auth(access_token) + ) + finally: + romm_logger.removeHandler(caplog.handler) + assert response.status_code == 200 + assert response.json()["containers"] == [] + assert "missing platform/host" in caplog.text + + +def test_get_config_ships_platform_capabilities(client, access_token): + """The slot capabilities the frontend selector reads come from /config, so + they are not a second hardcoded copy.""" + container = {"platform": "ps2", "host": "http://192.168.1.10:3000"} + with _streaming(container): + r = client.get("/api/streaming/config", headers=_auth(access_token)) + assert r.status_code == 200 + assert r.json()["containers"][0]["capabilities"] == { + "max_slots": 9, + "has_autosave": True, + "autosave_slot": 10, + } + + +# ── Claiming ────────────────────────────────────────────────────────────────── + + +def test_claim_derives_rom_path_server_side(client, access_token, rom: Rom): + """The broker must receive a path built from the DB row, not client input.""" + with _streaming(_container_for(rom)): + with patch("endpoints.streaming._call_broker") as call_broker: + r = _claim(client, access_token, rom.id) + assert r.status_code == 200 + assert r.json()["rom_name"] == rom.name + _, rom_path, _ = call_broker.call_args[0] + assert rom_path == f"{LIBRARY_BASE_PATH}/{rom.full_path}" + + +def test_claim_unknown_rom_returns_404(client, access_token): + with _streaming(): + r = _claim(client, access_token, 999999) + assert r.status_code == 404 + + +def test_claim_skips_container_with_schemeless_host(client, access_token, rom: Rom): + """A container whose host has no scheme would produce a broken broker URL + and a colliding session key; it must be skipped (404), not a 500 KeyError.""" + bad = {"platform": rom.platform_slug, "host": "192.168.1.10:3000"} + with _streaming(bad): + r = _claim(client, access_token, rom.id) + assert r.status_code == 404 + + +def test_claim_skips_container_missing_host(client, access_token, rom: Rom): + """An entry with platform set but host missing must not KeyError into a 500.""" + bad = {"platform": rom.platform_slug, "broker_host": "http://192.168.1.10:8000"} + with _streaming(bad): + r = _claim(client, access_token, rom.id) + assert r.status_code == 404 + + +@pytest.mark.asyncio +async def test_claim_sets_session_ttl(access_token, rom: Rom): + """A claimed session must carry a TTL so an abandoned one eventually frees + the container instead of wedging it forever.""" + from endpoints.streaming import SESSION_TTL_SECONDS, _session_redis_key + + with _streaming(_container_for(rom)): + with patch("endpoints.streaming._call_broker"): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as ac: + r = await ac.post( + "/api/streaming/sessions", + json={"rom_id": rom.id}, + headers=_auth(access_token), + ) + assert r.status_code == 200 + ttl = await async_cache.ttl(_session_redis_key(_container_for(rom)["broker_host"])) + assert ttl > 0 + assert ttl <= SESSION_TTL_SECONDS + + +def test_second_claim_on_same_container_rejected(client, access_token, rom: Rom): + """The container is single-tenant: a second claim must 409 with the holder.""" + with _streaming(_container_for(rom)): + with patch("endpoints.streaming._call_broker"): + r1 = _claim(client, access_token, rom.id) + r2 = _claim(client, access_token, rom.id) + assert r1.status_code == 200 + assert r2.status_code == 409 + assert r2.json()["detail"]["rom_name"] == rom.name + + +def test_claim_session_same_container_two_platforms_rejected( + client, access_token, admin_user: User, rom: Rom +): + """Dolphin serves ngc and wii from one broker - second claim must be 409.""" + platform2 = db_platform_handler.add_platform( + Platform(name="p2", slug="p2_slug", fs_slug="p2_slug") + ) + rom2 = db_rom_handler.add_rom( + Rom( + platform_id=platform2.id, + name="rom2", + slug="rom2", + fs_name="rom2.zip", + fs_name_no_tags="rom2", + fs_name_no_ext="rom2", + fs_extension="zip", + fs_path=f"{platform2.slug}/roms", + ) + ) + shared_broker = "http://192.168.1.10:8000" + with _streaming( + _container_for(rom, broker_host=shared_broker), + _container_for(rom2, broker_host=shared_broker), + ): + with patch("endpoints.streaming._call_broker"): + r1 = _claim(client, access_token, rom.id) + r2 = _claim(client, access_token, rom2.id) + assert r1.status_code == 200 + assert r2.status_code == 409 + + +def test_failed_broker_launch_frees_the_claim(client, access_token, rom: Rom): + """If the broker rejects the launch, the container must not stay claimed.""" + from fastapi import HTTPException + + with _streaming(_container_for(rom)): + with patch( + "endpoints.streaming._call_broker", + side_effect=HTTPException(status_code=503, detail="unreachable"), + ): + r1 = _claim(client, access_token, rom.id) + r2 = _claim_ok(client, access_token, rom.id) + assert r1.status_code == 503 + assert r2.status_code == 200 + + +@pytest.mark.asyncio +async def test_concurrent_claim_only_one_succeeds(access_token, rom: Rom): + """Two concurrent claims on one container: exactly one 200 and one 409.""" + with _streaming(_container_for(rom)): + with patch("endpoints.streaming._call_broker"): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as ac: + r1, r2 = await asyncio.gather( + ac.post( + "/api/streaming/sessions", + json={"rom_id": rom.id}, + headers=_auth(access_token), + ), + ac.post( + "/api/streaming/sessions", + json={"rom_id": rom.id}, + headers=_auth(access_token), + ), + ) + assert sorted([r1.status_code, r2.status_code]) == [200, 409] + + +# ── Release / ownership ─────────────────────────────────────────────────────── + + +def test_release_uses_container_key_not_platform(client, access_token, rom: Rom): + """release_session must find the session by broker_host, not platform string.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch("endpoints.streaming._stop_broker"): + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["status"] == "released" + + +def test_release_by_other_user_is_forbidden( + client, access_token, viewer_access_token, rom: Rom +): + """A session claimed by one user cannot be released by another non-admin.""" + with _streaming(_container_for(rom)): + # viewer claims the session; admin could override, a viewer cannot + r_claim = _claim_ok(client, access_token, rom.id) + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers=_auth(viewer_access_token), + ) + assert r_claim.status_code == 200 + assert r.status_code == 403 + + +def test_save_state_by_other_user_is_forbidden( + client, access_token, viewer_access_token, rom: Rom +): + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-state", + json={"slot": 1}, + headers=_auth(viewer_access_token), + ) + assert r.status_code == 403 + + +def test_save_state_rejects_slot_above_platform_max(client, access_token): + """Dolphin exposes 7 manual slots; slot 8 clears the coarse union bound + (<=9) but must be rejected against the platform's real ceiling.""" + rom = _rom_on("ngc") + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + r = client.post( + "/api/streaming/sessions/ngc/save-state", + json={"slot": 8}, + headers=_auth(access_token), + ) + assert r.status_code == 422 + + +def test_load_state_allows_platform_autosave_slot(client, access_token): + """Dolphin's slot 8 is not manually savable but is loadable as the autosave.""" + rom = _rom_on("wii") + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch("endpoints.streaming._load_state_broker", return_value=True): + r = client.post( + "/api/streaming/sessions/wii/load-state", + json={"slot": 8}, + headers=_auth(access_token), + ) + assert r.status_code == 200 + assert r.json()["loaded"] is True + + +def test_load_state_rejects_slot_between_max_and_autosave(client, access_token): + """Dolphin: slot 9 is neither a manual slot (1-7) nor the autosave (8).""" + rom = _rom_on("wiiu") + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + r = client.post( + "/api/streaming/sessions/wiiu/load-state", + json={"slot": 9}, + headers=_auth(access_token), + ) + assert r.status_code == 422 + + +def test_save_and_exit_releases_session(client, access_token, rom: Rom): + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch("endpoints.streaming._save_and_exit_broker", return_value=True): + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 10, "wait": True}, + headers=_auth(access_token), + ) + # Container must be claimable again after save-and-exit. + r2 = _claim_ok(client, access_token, rom.id) + assert r.status_code == 200 + assert r.json()["saved"] is True + assert r2.status_code == 200 + + +def test_save_and_exit_failure_still_releases_session(client, access_token, rom: Rom): + """A failed save is reported as saved=False, but the session is still + released - the container must not stay claimed by a dead session.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch("endpoints.streaming._save_and_exit_broker", return_value=False): + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 10, "wait": True}, + headers=_auth(access_token), + ) + r2 = _claim_ok(client, access_token, rom.id) + assert r.status_code == 200 + assert r.json()["saved"] is False + assert r2.status_code == 200 + + +def test_save_and_exit_wait_false_drains_instead_of_freeing( + client, access_token, rom: Rom +): + """wait=false means the broker is still killing in the background; the + session key must briefly block a re-claim (drain) rather than be deleted + immediately, so a new launch can't land on a not-yet-dead emulator.""" + from endpoints.streaming import SESSION_DRAIN_SECONDS, _session_redis_key + + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch("endpoints.streaming._save_and_exit_broker", return_value=True): + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-and-exit", + json={"slot": 0, "wait": False}, + headers=_auth(access_token), + ) + # The drain key briefly holds the container. + r2 = _claim_ok(client, access_token, rom.id) + assert r.status_code == 200 + # Re-claim during the drain window is rejected (409), not accepted (200). + assert r2.status_code == 409 + # Drain TTL is bounded to the short window, not the full session TTL. + ttl = asyncio.run( + async_cache.ttl(_session_redis_key(_container_for(rom)["broker_host"])) + ) + assert 0 < ttl <= SESSION_DRAIN_SECONDS + + +def test_force_release_all_stops_brokers(client, access_token, rom: Rom): + """Force-release must tell each broker to stop, not just clear Redis.""" + with _streaming(_container_for(rom)): + _claim_ok(client, access_token, rom.id) + with patch("endpoints.streaming._stop_broker") as stop_broker: + r = client.delete("/api/streaming/sessions", headers=_auth(access_token)) + assert r.status_code == 200 + assert stop_broker.call_count == 1 + + +# ── Auth guards ─────────────────────────────────────────────────────────────── + + +def test_claim_session_requires_auth(client): + assert client.post("/api/streaming/sessions", json={"rom_id": 1}).status_code == 403 + + +def test_release_session_requires_auth(client): + assert client.delete("/api/streaming/sessions/ps2").status_code == 403 + + +def test_force_release_all_requires_auth(client): + assert client.delete("/api/streaming/sessions").status_code == 403 + + +def test_list_sessions_requires_auth(client): + assert client.get("/api/streaming/sessions").status_code == 403 + + +def test_list_sessions_requires_admin(client, viewer_access_token): + r = client.get("/api/streaming/sessions", headers=_auth(viewer_access_token)) + assert r.status_code == 403 diff --git a/env.template b/env.template index 2dd583793..c7c980ece 100644 --- a/env.template +++ b/env.template @@ -143,3 +143,7 @@ POSTGRES_USER=authentik # Postgres user for the Authentik dev stack POSTGRES_PASSWORD=authentik # Postgres password for the Authentik dev stack AUTHENTIK_SECRET_KEY= # Authentik secret key AUTHENTIK_BOOTSTRAP_PASSWORD= # Initial Authentik admin bootstrap password + +# Emulator Streaming +STREAMING_BROKER_SECRET= +STREAMING_SAVE_TIMEOUT=45 # Seconds to wait for a broker save-and-exit (raise if a broker has SAVE_WAIT > 45) diff --git a/examples/config.example.yml b/examples/config.example.yml index 8d539c0f0..0c4745ba8 100644 --- a/examples/config.example.yml +++ b/examples/config.example.yml @@ -176,3 +176,25 @@ # 1: # Player 2 # 2: # Player 3 # 3: # Player 4 + +# streaming: +# enabled: true +# containers: +# - platform: ps2 +# # Browser-facing Selkies web UI, MUST be served over https +# # (use a reverse proxy or the built in self signed cert for linuxserver) +# # can also be a FQDN eg. https://your.example.com +# host: https://192.168.1.51:3001 +# +# # server-to-broker URL does NOT need to be served over https +# # If pcsx2 emulator is on a different host, use its LAN IP. +# # If on the same Docker network, use the container name: http://pcsx2:8000 +# broker_host: http://192.168.1.51:8000 +# # what shows up on the play button +# label: PCSX2 +# +# # Add more emulator containers here as needed: +# # - platform: psx +# # host: http://192.168.1.51:3002 +# # broker_host: http://192.168.1.51:8001 +# # label: DuckStation diff --git a/frontend/src/locales/bg_BG/play.json b/frontend/src/locales/bg_BG/play.json index 819b599f7..d018526b0 100644 --- a/frontend/src/locales/bg_BG/play.json +++ b/frontend/src/locales/bg_BG/play.json @@ -28,5 +28,29 @@ "select-save": "Избери запис", "select-state": "Избери бърз запис", "slot": "Слот", - "start-fresh-hint": "Избери един по-долу, за да продължиш, или натисни Играй, за да започнеш отначало." + "start-fresh-hint": "Избери един по-долу, за да продължиш, или натисни Играй, за да започнеш отначало.", + "stream-error-generic": "Възникна неочаквана грешка.", + "stream-error-load-rom": "Данните за ROM не можаха да се заредят.", + "stream-error-not-configured": "Няма конфигуриран стрийминг контейнер за {platform}.", + "stream-error-rom-not-found": "Този ROM не може да бъде намерен. Възможно е да е бил премахнат.", + "stream-exit-fullscreen": "Изход от цял екран", + "stream-frame-title": "Стрийм на играта", + "stream-fullscreen": "Цял екран", + "stream-load-autosave": "Зареждане на автоматично записване", + "stream-load-state": "Зареждане на състояние", + "stream-mute": "Заглушаване", + "stream-occupied-body": "{rom} се играе от {time}.", + "stream-occupied-fallback": "В момента играе някой друг. Опитайте отново по-късно.", + "stream-occupied-title": "Сесията е заета", + "stream-save-and-exit": "Запис и изход", + "stream-save-slot": "Слот за запис", + "stream-save-state": "Запис на състояние", + "stream-save-unconfirmed": "Емулаторът не потвърди записа. Скорошният напредък може да бъде загубен.", + "stream-slot-n": "Слот {n}", + "stream-stop": "Спиране", + "stream-subtitle": "Стрийминг", + "stream-try-again": "Опитайте отново", + "stream-unknown-game": "Неизвестна игра", + "stream-unmute": "Включване на звука", + "stream-volume": "Сила на звука" } diff --git a/frontend/src/locales/cs_CZ/play.json b/frontend/src/locales/cs_CZ/play.json index c6007e62d..d867faef1 100644 --- a/frontend/src/locales/cs_CZ/play.json +++ b/frontend/src/locales/cs_CZ/play.json @@ -28,5 +28,29 @@ "select-save": "Vybrat uloženou pozici", "select-state": "Vybrat stav", "slot": "Slot", - "start-fresh-hint": "Vyberte níže pro pokračování, nebo stiskněte Hrát pro nový začátek." + "start-fresh-hint": "Vyberte níže pro pokračování, nebo stiskněte Hrát pro nový začátek.", + "stream-error-generic": "Došlo k neočekávané chybě.", + "stream-error-load-rom": "Podrobnosti o ROM se nepodařilo načíst.", + "stream-error-not-configured": "Pro platformu {platform} není nakonfigurován žádný streamovací kontejner.", + "stream-error-rom-not-found": "Tento ROM nebyl nalezen. Možná byl odstraněn.", + "stream-exit-fullscreen": "Ukončit celou obrazovku", + "stream-frame-title": "Stream hry", + "stream-fullscreen": "Celá obrazovka", + "stream-load-autosave": "Načíst automatické uložení", + "stream-load-state": "Načíst stav", + "stream-mute": "Ztlumit", + "stream-occupied-body": "{rom} se hraje od {time}.", + "stream-occupied-fallback": "Právě hraje někdo jiný. Zkuste to později.", + "stream-occupied-title": "Relace se používá", + "stream-save-and-exit": "Uložit a ukončit", + "stream-save-slot": "Slot uložení", + "stream-save-state": "Uložit stav", + "stream-save-unconfirmed": "Emulátor nepotvrdil uložení. Nedávný postup může být ztracen.", + "stream-slot-n": "Slot {n}", + "stream-stop": "Zastavit", + "stream-subtitle": "Streamování", + "stream-try-again": "Zkusit znovu", + "stream-unknown-game": "Neznámá hra", + "stream-unmute": "Zrušit ztlumení", + "stream-volume": "Hlasitost" } diff --git a/frontend/src/locales/de_DE/play.json b/frontend/src/locales/de_DE/play.json index eccce09b8..6fe61bfdf 100644 --- a/frontend/src/locales/de_DE/play.json +++ b/frontend/src/locales/de_DE/play.json @@ -28,5 +28,29 @@ "select-save": "Speicherstand auswählen", "select-state": "Speicherstand auswählen", "slot": "Slot", - "start-fresh-hint": "Wähle unten einen, um fortzufahren, oder klicke auf Play, um neu zu starten." + "start-fresh-hint": "Wähle unten einen, um fortzufahren, oder klicke auf Play, um neu zu starten.", + "stream-error-generic": "Ein unerwarteter Fehler ist aufgetreten.", + "stream-error-load-rom": "ROM-Details konnten nicht geladen werden.", + "stream-error-not-configured": "Für {platform} ist kein Streaming-Container konfiguriert.", + "stream-error-rom-not-found": "Dieses ROM konnte nicht gefunden werden. Möglicherweise wurde es entfernt.", + "stream-exit-fullscreen": "Vollbild beenden", + "stream-frame-title": "Spiel-Stream", + "stream-fullscreen": "Vollbild", + "stream-load-autosave": "Automatische Speicherung laden", + "stream-load-state": "Spielstand laden", + "stream-mute": "Stummschalten", + "stream-occupied-body": "{rom} wird seit {time} gespielt.", + "stream-occupied-fallback": "Jemand anderes spielt gerade. Versuchen Sie es später erneut.", + "stream-occupied-title": "Sitzung in Benutzung", + "stream-save-and-exit": "Speichern und beenden", + "stream-save-slot": "Speicherplatz", + "stream-save-state": "Spielstand speichern", + "stream-save-unconfirmed": "Der Emulator hat die Speicherung nicht bestätigt. Der letzte Fortschritt könnte verloren gehen.", + "stream-slot-n": "Platz {n}", + "stream-stop": "Stopp", + "stream-subtitle": "Streaming", + "stream-try-again": "Erneut versuchen", + "stream-unknown-game": "Unbekanntes Spiel", + "stream-unmute": "Stummschaltung aufheben", + "stream-volume": "Lautstärke" } diff --git a/frontend/src/locales/en_GB/play.json b/frontend/src/locales/en_GB/play.json index 9ed1c0dee..aa78dfaec 100644 --- a/frontend/src/locales/en_GB/play.json +++ b/frontend/src/locales/en_GB/play.json @@ -28,5 +28,29 @@ "select-save": "Select save", "select-state": "Select state", "slot": "Slot", - "start-fresh-hint": "Pick one below to resume, or hit Play to start fresh." + "start-fresh-hint": "Pick one below to resume, or hit Play to start fresh.", + "stream-error-generic": "An unexpected error occurred.", + "stream-error-load-rom": "Could not load ROM details.", + "stream-error-not-configured": "No streaming container is configured for {platform}.", + "stream-error-rom-not-found": "This ROM could not be found. It may have been removed.", + "stream-exit-fullscreen": "Exit fullscreen", + "stream-frame-title": "Game stream", + "stream-fullscreen": "Fullscreen", + "stream-load-autosave": "Load autosave", + "stream-load-state": "Load state", + "stream-mute": "Mute", + "stream-occupied-body": "{rom} has been playing since {time}.", + "stream-occupied-fallback": "Someone else is currently playing. Try again later.", + "stream-occupied-title": "Session in use", + "stream-save-and-exit": "Save and exit", + "stream-save-slot": "Save slot", + "stream-save-state": "Save state", + "stream-save-unconfirmed": "The emulator did not confirm the save. Recent progress may be lost.", + "stream-slot-n": "Slot {n}", + "stream-stop": "Stop", + "stream-subtitle": "Streaming", + "stream-try-again": "Try Again", + "stream-unknown-game": "Unknown Game", + "stream-unmute": "Unmute", + "stream-volume": "Volume" } diff --git a/frontend/src/locales/en_US/play.json b/frontend/src/locales/en_US/play.json index 9ed1c0dee..aa78dfaec 100644 --- a/frontend/src/locales/en_US/play.json +++ b/frontend/src/locales/en_US/play.json @@ -28,5 +28,29 @@ "select-save": "Select save", "select-state": "Select state", "slot": "Slot", - "start-fresh-hint": "Pick one below to resume, or hit Play to start fresh." + "start-fresh-hint": "Pick one below to resume, or hit Play to start fresh.", + "stream-error-generic": "An unexpected error occurred.", + "stream-error-load-rom": "Could not load ROM details.", + "stream-error-not-configured": "No streaming container is configured for {platform}.", + "stream-error-rom-not-found": "This ROM could not be found. It may have been removed.", + "stream-exit-fullscreen": "Exit fullscreen", + "stream-frame-title": "Game stream", + "stream-fullscreen": "Fullscreen", + "stream-load-autosave": "Load autosave", + "stream-load-state": "Load state", + "stream-mute": "Mute", + "stream-occupied-body": "{rom} has been playing since {time}.", + "stream-occupied-fallback": "Someone else is currently playing. Try again later.", + "stream-occupied-title": "Session in use", + "stream-save-and-exit": "Save and exit", + "stream-save-slot": "Save slot", + "stream-save-state": "Save state", + "stream-save-unconfirmed": "The emulator did not confirm the save. Recent progress may be lost.", + "stream-slot-n": "Slot {n}", + "stream-stop": "Stop", + "stream-subtitle": "Streaming", + "stream-try-again": "Try Again", + "stream-unknown-game": "Unknown Game", + "stream-unmute": "Unmute", + "stream-volume": "Volume" } diff --git a/frontend/src/locales/es_ES/play.json b/frontend/src/locales/es_ES/play.json index fc3902665..e1f1e4110 100644 --- a/frontend/src/locales/es_ES/play.json +++ b/frontend/src/locales/es_ES/play.json @@ -28,5 +28,29 @@ "select-save": "Seleccionar guardado", "select-state": "Seleccionar estado", "slot": "Ranura", - "start-fresh-hint": "Empezar desde cero — sin partidas guardadas." + "start-fresh-hint": "Empezar desde cero — sin partidas guardadas.", + "stream-error-generic": "Se produjo un error inesperado.", + "stream-error-load-rom": "No se pudieron cargar los detalles de la ROM.", + "stream-error-not-configured": "No hay ningún contenedor de streaming configurado para {platform}.", + "stream-error-rom-not-found": "No se pudo encontrar esta ROM. Es posible que haya sido eliminada.", + "stream-exit-fullscreen": "Salir de pantalla completa", + "stream-frame-title": "Transmisión del juego", + "stream-fullscreen": "Pantalla completa", + "stream-load-autosave": "Cargar guardado automático", + "stream-load-state": "Cargar estado", + "stream-mute": "Silenciar", + "stream-occupied-body": "{rom} se está jugando desde las {time}.", + "stream-occupied-fallback": "Otra persona está jugando en este momento. Inténtalo de nuevo más tarde.", + "stream-occupied-title": "Sesión en uso", + "stream-save-and-exit": "Guardar y salir", + "stream-save-slot": "Ranura de guardado", + "stream-save-state": "Guardar estado", + "stream-save-unconfirmed": "El emulador no confirmó el guardado. El progreso reciente podría perderse.", + "stream-slot-n": "Ranura {n}", + "stream-stop": "Detener", + "stream-subtitle": "Transmisión", + "stream-try-again": "Intentar de nuevo", + "stream-unknown-game": "Juego desconocido", + "stream-unmute": "Activar sonido", + "stream-volume": "Volumen" } diff --git a/frontend/src/locales/fr_FR/play.json b/frontend/src/locales/fr_FR/play.json index f19d7b936..cd1086494 100644 --- a/frontend/src/locales/fr_FR/play.json +++ b/frontend/src/locales/fr_FR/play.json @@ -28,5 +28,29 @@ "select-save": "Sélectionner la sauvegarde", "select-state": "Sélectionner l'état", "slot": "Emplacement", - "start-fresh-hint": "Choisissez-en un ci-dessous pour reprendre, ou appuyez sur Jouer pour démarrer une nouvelle partie." + "start-fresh-hint": "Choisissez-en un ci-dessous pour reprendre, ou appuyez sur Jouer pour démarrer une nouvelle partie.", + "stream-error-generic": "Une erreur inattendue s'est produite.", + "stream-error-load-rom": "Impossible de charger les détails de la ROM.", + "stream-error-not-configured": "Aucun conteneur de streaming n'est configuré pour {platform}.", + "stream-error-rom-not-found": "Cette ROM est introuvable. Elle a peut-être été supprimée.", + "stream-exit-fullscreen": "Quitter le plein écran", + "stream-frame-title": "Flux du jeu", + "stream-fullscreen": "Plein écran", + "stream-load-autosave": "Charger la sauvegarde automatique", + "stream-load-state": "Charger l'état", + "stream-mute": "Couper le son", + "stream-occupied-body": "{rom} est en cours de partie depuis {time}.", + "stream-occupied-fallback": "Quelqu'un d'autre joue actuellement. Réessayez plus tard.", + "stream-occupied-title": "Session en cours d'utilisation", + "stream-save-and-exit": "Enregistrer et quitter", + "stream-save-slot": "Emplacement de sauvegarde", + "stream-save-state": "Enregistrer l'état", + "stream-save-unconfirmed": "L'émulateur n'a pas confirmé la sauvegarde. La progression récente pourrait être perdue.", + "stream-slot-n": "Emplacement {n}", + "stream-stop": "Arrêter", + "stream-subtitle": "Streaming", + "stream-try-again": "Réessayer", + "stream-unknown-game": "Jeu inconnu", + "stream-unmute": "Rétablir le son", + "stream-volume": "Volume" } diff --git a/frontend/src/locales/hu_HU/play.json b/frontend/src/locales/hu_HU/play.json index 49f786211..df1e8dc71 100644 --- a/frontend/src/locales/hu_HU/play.json +++ b/frontend/src/locales/hu_HU/play.json @@ -28,5 +28,29 @@ "select-save": "Mentés kiválasztása", "select-state": "Állás kiválasztása", "slot": "Hely", - "start-fresh-hint": "Válassz egyet az alábbiak közül a folytatáshoz, vagy nyomd meg az Indítást egy új játékhoz." + "start-fresh-hint": "Válassz egyet az alábbiak közül a folytatáshoz, vagy nyomd meg az Indítást egy új játékhoz.", + "stream-error-generic": "Váratlan hiba történt.", + "stream-error-load-rom": "A ROM adatait nem sikerült betölteni.", + "stream-error-not-configured": "Nincs streaming konténer konfigurálva a következőhöz: {platform}.", + "stream-error-rom-not-found": "Ez a ROM nem található. Lehet, hogy eltávolították.", + "stream-exit-fullscreen": "Kilépés a teljes képernyőből", + "stream-frame-title": "Játék streamje", + "stream-fullscreen": "Teljes képernyő", + "stream-load-autosave": "Automatikus mentés betöltése", + "stream-load-state": "Állás betöltése", + "stream-mute": "Némítás", + "stream-occupied-body": "A(z) {rom} játékban van {time} óta.", + "stream-occupied-fallback": "Jelenleg valaki más játszik. Próbálja meg később.", + "stream-occupied-title": "A munkamenet használatban van", + "stream-save-and-exit": "Mentés és kilépés", + "stream-save-slot": "Mentési hely", + "stream-save-state": "Állás mentése", + "stream-save-unconfirmed": "Az emulátor nem erősítette meg a mentést. A legutóbbi előrehaladás elveszhet.", + "stream-slot-n": "{n}. hely", + "stream-stop": "Leállítás", + "stream-subtitle": "Streamelés", + "stream-try-again": "Próbálja újra", + "stream-unknown-game": "Ismeretlen játék", + "stream-unmute": "Némítás feloldása", + "stream-volume": "Hangerő" } diff --git a/frontend/src/locales/it_IT/play.json b/frontend/src/locales/it_IT/play.json index ccd979f4e..2cf6c3395 100644 --- a/frontend/src/locales/it_IT/play.json +++ b/frontend/src/locales/it_IT/play.json @@ -28,5 +28,29 @@ "select-save": "Seleziona Salvataggio", "select-state": "Seleziona Stato", "slot": "Slot", - "start-fresh-hint": "Scegline uno qui sotto per riprendere, oppure premi Gioca per iniziare da capo." + "start-fresh-hint": "Scegline uno qui sotto per riprendere, oppure premi Gioca per iniziare da capo.", + "stream-error-generic": "Si è verificato un errore imprevisto.", + "stream-error-load-rom": "Impossibile caricare i dettagli della ROM.", + "stream-error-not-configured": "Nessun contenitore di streaming configurato per {platform}.", + "stream-error-rom-not-found": "Impossibile trovare questa ROM. Potrebbe essere stata rimossa.", + "stream-exit-fullscreen": "Esci da schermo intero", + "stream-frame-title": "Stream del gioco", + "stream-fullscreen": "Schermo intero", + "stream-load-autosave": "Carica salvataggio automatico", + "stream-load-state": "Carica stato", + "stream-mute": "Disattiva audio", + "stream-occupied-body": "{rom} è in gioco da {time}.", + "stream-occupied-fallback": "Qualcun altro sta giocando in questo momento. Riprova più tardi.", + "stream-occupied-title": "Sessione in uso", + "stream-save-and-exit": "Salva ed esci", + "stream-save-slot": "Slot di salvataggio", + "stream-save-state": "Salva stato", + "stream-save-unconfirmed": "L'emulatore non ha confermato il salvataggio. I progressi recenti potrebbero andare persi.", + "stream-slot-n": "Slot {n}", + "stream-stop": "Ferma", + "stream-subtitle": "Streaming", + "stream-try-again": "Riprova", + "stream-unknown-game": "Gioco sconosciuto", + "stream-unmute": "Riattiva audio", + "stream-volume": "Volume" } diff --git a/frontend/src/locales/ja_JP/play.json b/frontend/src/locales/ja_JP/play.json index 85cb0f058..dd9f44599 100644 --- a/frontend/src/locales/ja_JP/play.json +++ b/frontend/src/locales/ja_JP/play.json @@ -28,5 +28,29 @@ "select-save": "セーブデータを選択", "select-state": "ステートを選択", "slot": "スロット", - "start-fresh-hint": "下から選んで再開するか、Playを押して最初から始めてください。" + "start-fresh-hint": "下から選んで再開するか、Playを押して最初から始めてください。", + "stream-error-generic": "予期しないエラーが発生しました。", + "stream-error-load-rom": "ROMの詳細を読み込めませんでした。", + "stream-error-not-configured": "{platform} 用のストリーミングコンテナが構成されていません。", + "stream-error-rom-not-found": "このROMが見つかりませんでした。削除された可能性があります。", + "stream-exit-fullscreen": "全画面表示を終了", + "stream-frame-title": "ゲームストリーム", + "stream-fullscreen": "全画面表示", + "stream-load-autosave": "オートセーブを読み込む", + "stream-load-state": "ステートをロード", + "stream-mute": "ミュート", + "stream-occupied-body": "{rom} は {time} からプレイされています。", + "stream-occupied-fallback": "現在、他の人がプレイ中です。後でもう一度お試しください。", + "stream-occupied-title": "セッション使用中", + "stream-save-and-exit": "保存して終了", + "stream-save-slot": "セーブスロット", + "stream-save-state": "ステートをセーブ", + "stream-save-unconfirmed": "エミュレーターが保存を確認できませんでした。最近の進行状況が失われる可能性があります。", + "stream-slot-n": "スロット {n}", + "stream-stop": "停止", + "stream-subtitle": "ストリーミング", + "stream-try-again": "再試行", + "stream-unknown-game": "不明なゲーム", + "stream-unmute": "ミュート解除", + "stream-volume": "音量" } diff --git a/frontend/src/locales/ko_KR/play.json b/frontend/src/locales/ko_KR/play.json index 1b4d40cca..b65197420 100644 --- a/frontend/src/locales/ko_KR/play.json +++ b/frontend/src/locales/ko_KR/play.json @@ -28,5 +28,29 @@ "select-save": "세이브 선택", "select-state": "상태 선택", "slot": "슬롯", - "start-fresh-hint": "아래에서 하나를 선택하여 이어 하거나, 실행을 눌러 새로 시작하세요." + "start-fresh-hint": "아래에서 하나를 선택하여 이어 하거나, 실행을 눌러 새로 시작하세요.", + "stream-error-generic": "예기치 않은 오류가 발생했습니다.", + "stream-error-load-rom": "ROM 세부 정보를 불러올 수 없습니다.", + "stream-error-not-configured": "{platform}에 대해 구성된 스트리밍 컨테이너가 없습니다.", + "stream-error-rom-not-found": "이 ROM을 찾을 수 없습니다. 삭제되었을 수 있습니다.", + "stream-exit-fullscreen": "전체 화면 종료", + "stream-frame-title": "게임 스트림", + "stream-fullscreen": "전체 화면", + "stream-load-autosave": "자동 저장 불러오기", + "stream-load-state": "상태 불러오기", + "stream-mute": "음소거", + "stream-occupied-body": "{rom}을(를) {time}부터 플레이하고 있습니다.", + "stream-occupied-fallback": "현재 다른 사람이 플레이 중입니다. 나중에 다시 시도하세요.", + "stream-occupied-title": "세션 사용 중", + "stream-save-and-exit": "저장 후 종료", + "stream-save-slot": "저장 슬롯", + "stream-save-state": "상태 저장", + "stream-save-unconfirmed": "에뮬레이터가 저장을 확인하지 못했습니다. 최근 진행 상황이 손실될 수 있습니다.", + "stream-slot-n": "슬롯 {n}", + "stream-stop": "중지", + "stream-subtitle": "스트리밍", + "stream-try-again": "다시 시도", + "stream-unknown-game": "알 수 없는 게임", + "stream-unmute": "음소거 해제", + "stream-volume": "볼륨" } diff --git a/frontend/src/locales/pl_PL/play.json b/frontend/src/locales/pl_PL/play.json index f8b8202ef..7e5f7163e 100644 --- a/frontend/src/locales/pl_PL/play.json +++ b/frontend/src/locales/pl_PL/play.json @@ -28,5 +28,29 @@ "select-save": "Wybierz zapis", "select-state": "Wybierz stan", "slot": "Slot", - "start-fresh-hint": "Wybierz jeden poniżej, aby wznowić, lub naciśnij Graj, aby zacząć od nowa." + "start-fresh-hint": "Wybierz jeden poniżej, aby wznowić, lub naciśnij Graj, aby zacząć od nowa.", + "stream-error-generic": "Wystąpił nieoczekiwany błąd.", + "stream-error-load-rom": "Nie można załadować szczegółów ROM.", + "stream-error-not-configured": "Nie skonfigurowano kontenera strumieniowego dla {platform}.", + "stream-error-rom-not-found": "Nie można znaleźć tego ROM-u. Mógł zostać usunięty.", + "stream-exit-fullscreen": "Wyjdź z trybu pełnoekranowego", + "stream-frame-title": "Transmisja gry", + "stream-fullscreen": "Pełny ekran", + "stream-load-autosave": "Wczytaj autozapis", + "stream-load-state": "Wczytaj stan", + "stream-mute": "Wycisz", + "stream-occupied-body": "{rom} jest w grze od {time}.", + "stream-occupied-fallback": "Ktoś inny obecnie gra. Spróbuj ponownie później.", + "stream-occupied-title": "Sesja w użyciu", + "stream-save-and-exit": "Zapisz i wyjdź", + "stream-save-slot": "Slot zapisu", + "stream-save-state": "Zapisz stan", + "stream-save-unconfirmed": "Emulator nie potwierdził zapisu. Ostatnie postępy mogą zostać utracone.", + "stream-slot-n": "Slot {n}", + "stream-stop": "Zatrzymaj", + "stream-subtitle": "Transmisja", + "stream-try-again": "Spróbuj ponownie", + "stream-unknown-game": "Nieznana gra", + "stream-unmute": "Wyłącz wyciszenie", + "stream-volume": "Głośność" } diff --git a/frontend/src/locales/pt_BR/play.json b/frontend/src/locales/pt_BR/play.json index a5aa1ee2c..f677861bb 100644 --- a/frontend/src/locales/pt_BR/play.json +++ b/frontend/src/locales/pt_BR/play.json @@ -28,5 +28,29 @@ "select-save": "Selecionar save", "select-state": "Selecionar estado", "slot": "Slot", - "start-fresh-hint": "Escolha um abaixo para retomar, ou clique em Jogar para começar do zero." + "start-fresh-hint": "Escolha um abaixo para retomar, ou clique em Jogar para começar do zero.", + "stream-error-generic": "Ocorreu um erro inesperado.", + "stream-error-load-rom": "Não foi possível carregar os detalhes da ROM.", + "stream-error-not-configured": "Nenhum contêiner de streaming está configurado para {platform}.", + "stream-error-rom-not-found": "Esta ROM não foi encontrada. Ela pode ter sido removida.", + "stream-exit-fullscreen": "Sair da tela cheia", + "stream-frame-title": "Transmissão do jogo", + "stream-fullscreen": "Tela cheia", + "stream-load-autosave": "Carregar salvamento automático", + "stream-load-state": "Carregar estado", + "stream-mute": "Silenciar", + "stream-occupied-body": "{rom} está sendo jogado desde {time}.", + "stream-occupied-fallback": "Outra pessoa está jogando no momento. Tente novamente mais tarde.", + "stream-occupied-title": "Sessão em uso", + "stream-save-and-exit": "Salvar e sair", + "stream-save-slot": "Slot de salvamento", + "stream-save-state": "Salvar estado", + "stream-save-unconfirmed": "O emulador não confirmou o salvamento. O progresso recente pode ser perdido.", + "stream-slot-n": "Slot {n}", + "stream-stop": "Parar", + "stream-subtitle": "Transmissão", + "stream-try-again": "Tentar novamente", + "stream-unknown-game": "Jogo desconhecido", + "stream-unmute": "Ativar som", + "stream-volume": "Volume" } diff --git a/frontend/src/locales/ro_RO/play.json b/frontend/src/locales/ro_RO/play.json index 4d1d72ff7..b27fe688a 100644 --- a/frontend/src/locales/ro_RO/play.json +++ b/frontend/src/locales/ro_RO/play.json @@ -28,5 +28,29 @@ "select-save": "Selectează salvare", "select-state": "Selectează stare", "slot": "Slot", - "start-fresh-hint": "Alege una mai jos pentru a relua sau apasă Joacă pentru a începe de la zero." + "start-fresh-hint": "Alege una mai jos pentru a relua sau apasă Joacă pentru a începe de la zero.", + "stream-error-generic": "A apărut o eroare neașteptată.", + "stream-error-load-rom": "Detaliile ROM-ului nu au putut fi încărcate.", + "stream-error-not-configured": "Niciun container de streaming nu este configurat pentru {platform}.", + "stream-error-rom-not-found": "Acest ROM nu a putut fi găsit. Este posibil să fi fost eliminat.", + "stream-exit-fullscreen": "Ieșire din ecran complet", + "stream-frame-title": "Streamul jocului", + "stream-fullscreen": "Ecran complet", + "stream-load-autosave": "Încarcă salvarea automată", + "stream-load-state": "Încarcă starea", + "stream-mute": "Dezactivează sunetul", + "stream-occupied-body": "{rom} este jucat din {time}.", + "stream-occupied-fallback": "Altcineva joacă în acest moment. Încercați din nou mai târziu.", + "stream-occupied-title": "Sesiune în uz", + "stream-save-and-exit": "Salvează și ieși", + "stream-save-slot": "Slot de salvare", + "stream-save-state": "Salvează starea", + "stream-save-unconfirmed": "Emulatorul nu a confirmat salvarea. Progresul recent ar putea fi pierdut.", + "stream-slot-n": "Slot {n}", + "stream-stop": "Oprește", + "stream-subtitle": "Streaming", + "stream-try-again": "Încearcă din nou", + "stream-unknown-game": "Joc necunoscut", + "stream-unmute": "Activează sunetul", + "stream-volume": "Volum" } diff --git a/frontend/src/locales/ru_RU/play.json b/frontend/src/locales/ru_RU/play.json index e1851a5c0..4a911a638 100644 --- a/frontend/src/locales/ru_RU/play.json +++ b/frontend/src/locales/ru_RU/play.json @@ -28,5 +28,29 @@ "select-save": "Выбрать сохранение", "select-state": "Выбрать состояние", "slot": "Слот", - "start-fresh-hint": "Выберите одно из ниже, чтобы продолжить, или нажмите «Играть», чтобы начать заново." + "start-fresh-hint": "Выберите одно из ниже, чтобы продолжить, или нажмите «Играть», чтобы начать заново.", + "stream-error-generic": "Произошла непредвиденная ошибка.", + "stream-error-load-rom": "Не удалось загрузить сведения о ROM.", + "stream-error-not-configured": "Для {platform} не настроен контейнер потоковой передачи.", + "stream-error-rom-not-found": "Этот ROM не найден. Возможно, он был удалён.", + "stream-exit-fullscreen": "Выйти из полноэкранного режима", + "stream-frame-title": "Трансляция игры", + "stream-fullscreen": "Полный экран", + "stream-load-autosave": "Загрузить автосохранение", + "stream-load-state": "Загрузить состояние", + "stream-mute": "Отключить звук", + "stream-occupied-body": "В {rom} играют с {time}.", + "stream-occupied-fallback": "Сейчас играет кто-то другой. Повторите попытку позже.", + "stream-occupied-title": "Сеанс занят", + "stream-save-and-exit": "Сохранить и выйти", + "stream-save-slot": "Слот сохранения", + "stream-save-state": "Сохранить состояние", + "stream-save-unconfirmed": "Эмулятор не подтвердил сохранение. Недавний прогресс может быть потерян.", + "stream-slot-n": "Слот {n}", + "stream-stop": "Остановить", + "stream-subtitle": "Трансляция", + "stream-try-again": "Повторить попытку", + "stream-unknown-game": "Неизвестная игра", + "stream-unmute": "Включить звук", + "stream-volume": "Громкость" } diff --git a/frontend/src/locales/tr_TR/play.json b/frontend/src/locales/tr_TR/play.json index bc5e985e5..d39fbc5dc 100644 --- a/frontend/src/locales/tr_TR/play.json +++ b/frontend/src/locales/tr_TR/play.json @@ -28,5 +28,29 @@ "select-save": "Kayıt seç", "select-state": "Durum kaydı seç", "slot": "Slot", - "start-fresh-hint": "Devam etmek için aşağıdan birini seçin veya baştan başlamak için Oyna'ya basın." + "start-fresh-hint": "Devam etmek için aşağıdan birini seçin veya baştan başlamak için Oyna'ya basın.", + "stream-error-generic": "Beklenmeyen bir hata oluştu.", + "stream-error-load-rom": "ROM ayrıntıları yüklenemedi.", + "stream-error-not-configured": "{platform} için yapılandırılmış bir yayın konteyneri yok.", + "stream-error-rom-not-found": "Bu ROM bulunamadı. Kaldırılmış olabilir.", + "stream-exit-fullscreen": "Tam ekrandan çık", + "stream-frame-title": "Oyun yayını", + "stream-fullscreen": "Tam ekran", + "stream-load-autosave": "Otomatik kaydı yükle", + "stream-load-state": "Durumu yükle", + "stream-mute": "Sessize al", + "stream-occupied-body": "{rom} {time} saatinden beri oynanıyor.", + "stream-occupied-fallback": "Şu anda başka biri oynuyor. Daha sonra tekrar deneyin.", + "stream-occupied-title": "Oturum kullanımda", + "stream-save-and-exit": "Kaydet ve çık", + "stream-save-slot": "Kayıt yuvası", + "stream-save-state": "Durumu kaydet", + "stream-save-unconfirmed": "Emülatör kaydı onaylamadı. Son ilerleme kaybolabilir.", + "stream-slot-n": "Yuva {n}", + "stream-stop": "Durdur", + "stream-subtitle": "Yayın", + "stream-try-again": "Tekrar dene", + "stream-unknown-game": "Bilinmeyen oyun", + "stream-unmute": "Sesi aç", + "stream-volume": "Ses düzeyi" } diff --git a/frontend/src/locales/zh_CN/play.json b/frontend/src/locales/zh_CN/play.json index de6705c6a..781b42a3f 100644 --- a/frontend/src/locales/zh_CN/play.json +++ b/frontend/src/locales/zh_CN/play.json @@ -28,5 +28,29 @@ "select-save": "选择存档", "select-state": "选择状态", "slot": "存档位", - "start-fresh-hint": "选择下方任一项继续,或点击开始从头开始。" + "start-fresh-hint": "选择下方任一项继续,或点击开始从头开始。", + "stream-error-generic": "发生意外错误。", + "stream-error-load-rom": "无法加载 ROM 详细信息。", + "stream-error-not-configured": "未为 {platform} 配置流式容器。", + "stream-error-rom-not-found": "找不到此 ROM。它可能已被删除。", + "stream-exit-fullscreen": "退出全屏", + "stream-frame-title": "游戏串流", + "stream-fullscreen": "全屏", + "stream-load-autosave": "加载自动存档", + "stream-load-state": "加载状态", + "stream-mute": "静音", + "stream-occupied-body": "{rom} 自 {time} 起一直在游玩。", + "stream-occupied-fallback": "当前有其他人正在游玩。请稍后再试。", + "stream-occupied-title": "会话使用中", + "stream-save-and-exit": "保存并退出", + "stream-save-slot": "存档槽", + "stream-save-state": "保存状态", + "stream-save-unconfirmed": "模拟器未确认保存。最近的进度可能会丢失。", + "stream-slot-n": "槽位 {n}", + "stream-stop": "停止", + "stream-subtitle": "串流", + "stream-try-again": "重试", + "stream-unknown-game": "未知游戏", + "stream-unmute": "取消静音", + "stream-volume": "音量" } diff --git a/frontend/src/locales/zh_TW/play.json b/frontend/src/locales/zh_TW/play.json index 5c308e49b..701409118 100644 --- a/frontend/src/locales/zh_TW/play.json +++ b/frontend/src/locales/zh_TW/play.json @@ -28,5 +28,29 @@ "select-save": "選擇存檔", "select-state": "選擇即時存檔", "slot": "存檔槽", - "start-fresh-hint": "從下方選擇一項繼續遊玩,或按下 Play 重新開始。" + "start-fresh-hint": "從下方選擇一項繼續遊玩,或按下 Play 重新開始。", + "stream-error-generic": "發生意外錯誤。", + "stream-error-load-rom": "無法載入 ROM 詳細資訊。", + "stream-error-not-configured": "未為 {platform} 設定串流容器。", + "stream-error-rom-not-found": "找不到此 ROM。它可能已被移除。", + "stream-exit-fullscreen": "退出全螢幕", + "stream-frame-title": "遊戲串流", + "stream-fullscreen": "全螢幕", + "stream-load-autosave": "載入自動存檔", + "stream-load-state": "載入狀態", + "stream-mute": "靜音", + "stream-occupied-body": "{rom} 自 {time} 起一直在遊玩。", + "stream-occupied-fallback": "目前有其他人正在遊玩。請稍後再試。", + "stream-occupied-title": "工作階段使用中", + "stream-save-and-exit": "儲存並退出", + "stream-save-slot": "存檔槽", + "stream-save-state": "儲存狀態", + "stream-save-unconfirmed": "模擬器未確認儲存。最近的進度可能會遺失。", + "stream-slot-n": "插槽 {n}", + "stream-stop": "停止", + "stream-subtitle": "串流", + "stream-try-again": "重試", + "stream-unknown-game": "未知遊戲", + "stream-unmute": "取消靜音", + "stream-volume": "音量" } diff --git a/frontend/src/plugins/router.ts b/frontend/src/plugins/router.ts index 96fd50160..957246a74 100644 --- a/frontend/src/plugins/router.ts +++ b/frontend/src/plugins/router.ts @@ -32,6 +32,7 @@ export const ROUTES = { ROM: "rom", EMULATORJS: "emulatorjs", RUFFLE: "ruffle", + STREAM: "stream", SCAN: "scan", UPLOAD: "upload", ACTIVITY: "activity", @@ -268,6 +269,14 @@ const routes = [ v2: v2For(ROUTES.APRIL_FOOLS), }, }, + { + path: "rom/:rom/stream", + name: ROUTES.STREAM, + components: { + default: () => import("@/views/Home.vue"), + v2: v2For(ROUTES.STREAM), + }, + }, // Settings group — every settings route shares the same v2 // sub-layout (sidebar + content panel). Library Tools (Scan / // Upload / Patcher) live here too so they share the settings diff --git a/frontend/src/services/api/streaming.ts b/frontend/src/services/api/streaming.ts new file mode 100644 index 000000000..147a53a44 --- /dev/null +++ b/frontend/src/services/api/streaming.ts @@ -0,0 +1,84 @@ +import api from "@/services/api"; + +// ── Types ───────────────────────────────────────────────────────────────────── + +export interface PlatformCapabilities { + max_slots: number; // manual save slots, selectable as 1..max_slots + has_autosave: boolean; // whether a dedicated autosave slot can be loaded + autosave_slot: number; // that slot's index (loadable, not savable), 0 if none +} + +export interface StreamingContainer { + platform: string; // "ps2" + host: string; // "http://192.168.1.50:3000" + label: string; // "PCSX2" + capabilities: PlatformCapabilities; +} + +export interface StreamingConfig { + enabled: boolean; + containers: StreamingContainer[]; +} + +export interface ActiveSession { + platform: string; + host: string; + label: string; + rom_name: string; + claimed_at: string; +} + +// ── Requests ────────────────────────────────────────────────────────────────── + +async function fetchConfig() { + return api.get("/streaming/config", { + headers: { "Cache-Control": "no-cache" }, + }); +} + +async function claimSession(romId: number) { + return api.post("/streaming/sessions", { rom_id: romId }); +} + +async function releaseSession(platform: string) { + return api.delete(`/streaming/sessions/${platform}`); +} + +async function saveAndExit(platform: string, slot = 0, wait = true) { + return api.post(`/streaming/sessions/${platform}/save-and-exit`, { + slot, + wait, + }); +} + +async function setVolume(platform: string, level: number) { + return api.post(`/streaming/sessions/${platform}/volume`, { + level: Math.round(level), + }); +} + +async function setMute(platform: string, mute?: boolean) { + return api.post( + `/streaming/sessions/${platform}/mute`, + mute !== undefined ? { mute } : {}, + ); +} + +async function saveState(platform: string, slot = 1) { + return api.post(`/streaming/sessions/${platform}/save-state`, { slot }); +} + +async function loadState(platform: string, slot = 1) { + return api.post(`/streaming/sessions/${platform}/load-state`, { slot }); +} + +export default { + fetchConfig, + claimSession, + releaseSession, + saveAndExit, + setVolume, + setMute, + saveState, + loadState, +}; diff --git a/frontend/src/stores/streaming.ts b/frontend/src/stores/streaming.ts new file mode 100644 index 000000000..bb408b79e --- /dev/null +++ b/frontend/src/stores/streaming.ts @@ -0,0 +1,166 @@ +import { defineStore } from "pinia"; +import { ref, computed } from "vue"; +import streamingApi from "@/services/api/streaming"; +import type { + ActiveSession, + StreamingConfig, + StreamingContainer, +} from "@/services/api/streaming"; + +export type { + ActiveSession, + PlatformCapabilities, + StreamingConfig, + StreamingContainer, +} from "@/services/api/streaming"; + +const NO_CAPABILITIES = { + maxSlots: 0, + hasAutosave: false, + autosaveSlot: 0, +} as const; + +// ── Store ───────────────────────────────────────────────────────────────────── + +export const useStreamingStore = defineStore("streaming", () => { + const config = ref({ enabled: false, containers: [] }); + const activeSession = ref(null); + const loading = ref(false); + const error = ref(null); + + const isEnabled = computed(() => config.value.enabled); + + // ── Actions ──────────────────────────────────────────────────────────────── + + /** + * Returns the streaming container for a given platform slug, or null if + * streaming is disabled or no container is configured for that platform. + */ + function containerForPlatform( + slug: string | null | undefined, + ): StreamingContainer | null { + if (!slug || !config.value.enabled) return null; + const lower = slug.toLowerCase(); + return ( + config.value.containers.find((c) => c.platform.toLowerCase() === lower) ?? + null + ); + } + + /** + * Returns per-platform save-state capabilities for the streaming player UI, + * sourced from the container config the backend ships in /config (the single + * source of truth). Platforms with no configured container, or none the + * backend gives slots to, get an empty capability set (no save-state UI). + * + * maxSlots - number of user-accessible save slots (slot selector range) + * hasAutosave - whether a dedicated "load autosave" action is available + * autosaveSlot - the slot index used for autosave (0 when none) + */ + function platformCapabilities(slug: string | null | undefined): { + maxSlots: number; + hasAutosave: boolean; + autosaveSlot: number; + } { + const caps = containerForPlatform(slug)?.capabilities; + if (!caps) return { ...NO_CAPABILITIES }; + return { + maxSlots: caps.max_slots, + hasAutosave: caps.has_autosave, + autosaveSlot: caps.autosave_slot, + }; + } + + /** + * Fetch streaming config from the backend once on app load. + * If it fails, streaming stays disabled and no buttons appear. + */ + async function fetchConfig(): Promise { + loading.value = true; + error.value = null; + try { + const { data } = await streamingApi.fetchConfig(); + config.value = { + enabled: data.enabled ?? false, + containers: data.containers ?? [], + }; + } catch (err) { + error.value = String(err); + console.warn("[streaming] Could not fetch config:", err); + } finally { + loading.value = false; + } + } + + /** + * Claim a streaming session for a ROM. The backend derives the platform, + * filesystem path, and display name from the ROM id - the client never + * sends a path. + * Returns the session data (including the container host URL) on success. + * Throws an error with a `status` property on failure: + * 409 session in use - error has who/what is playing + * 404 - ROM or platform container not configured + * 503 - broker/unreachable + */ + async function claimSession(romId: number): Promise { + const { data } = await streamingApi.claimSession(romId); + activeSession.value = data; + return data; + } + + /** + * Release the active session when the user leaves the player page. + * Returns true when the backend acknowledged the release + * (the local session record is dropped); false when the call + * failed (the session is still held server-side, so the record is kept so + * the user can retry instead of being wedged behind their own session). + */ + async function releaseSession(platform: string): Promise { + if (!platform) return false; + try { + await streamingApi.releaseSession(platform); + activeSession.value = null; + return true; + } catch (err) { + console.warn("[streaming] Could not release session:", err); + return false; + } + } + + /** + * Save game state then release the session. + * wait=true (default): blocks until broker confirms save+kill - use for explicit button press. + * wait=false: broker fires save+kill in background, returns immediately - use for navigation away. + * Drops the local session record only on a confirmed release so a failed + * call doesn't leave the user wedged behind their own still-held session. + */ + async function saveAndExit( + platform: string, + slot = 0, + wait = true, + ): Promise { + if (!platform) return false; + try { + const { data } = await streamingApi.saveAndExit(platform, slot, wait); + activeSession.value = null; + return data.saved ?? false; + } catch (err) { + console.warn("[streaming] Could not save-and-exit:", err); + return false; + } + } + + return { + config, + activeSession, + loading, + error, + isEnabled, + containerForPlatform, + platformCapabilities, + fetchConfig, + claimSession, + releaseSession, + saveAndExit, + }; +}); diff --git a/frontend/src/v2/composables/useGameActions/index.ts b/frontend/src/v2/composables/useGameActions/index.ts index 54f5c0886..c976b9ebc 100644 --- a/frontend/src/v2/composables/useGameActions/index.ts +++ b/frontend/src/v2/composables/useGameActions/index.ts @@ -19,6 +19,7 @@ import romApi from "@/services/api/rom"; import storeAuth from "@/stores/auth"; import storeRoms from "@/stores/roms"; import type { SimpleRom } from "@/stores/roms"; +import { useStreamingStore } from "@/stores/streaming"; import type { Events } from "@/types/emitter"; import type { PlayingStatus } from "@/utils"; import { getDownloadLink, getDownloadPath, isNintendoDSRom } from "@/utils"; @@ -53,7 +54,19 @@ export function useGameActions( const canCreateCollection = useCan("collection.create"); const canEditCollection = useCan("collection.edit"); const { isFavorite, toggleFavorite } = useFavoriteToggle(emitter); - const { canPlay, canPlayEJS, canPlayRuffle } = useCanPlay(getRom); + const { canPlayEJS, canPlayRuffle } = useCanPlay(getRom); + const streamingStore = useStreamingStore(); + + // Streaming is the preferred way to play where a container is + // configured for the platform — the native emulator runs in a + // separate container and RomM streams it back. Wins over in-browser + // EJS/Ruffle when both are available. + const canPlayStream = computed(() => + Boolean(streamingStore.containerForPlatform(getRom()?.platform_slug)), + ); + const canPlay = computed( + () => canPlayStream.value || canPlayEJS.value || canPlayRuffle.value, + ); const isFavorited = computed(() => { const rom = getRom(); @@ -182,7 +195,8 @@ export function useGameActions( // player view itself — see EmulatorJS's onPlay — so navigation is // immediate here. let path: string | null = null; - if (canPlayEJS.value) path = `/rom/${rom.id}/ejs`; + if (canPlayStream.value) path = `/rom/${rom.id}/stream`; + else if (canPlayEJS.value) path = `/rom/${rom.id}/ejs`; else if (canPlayRuffle.value) path = `/rom/${rom.id}/ruffle`; if (!path) return; const target = path; @@ -352,6 +366,7 @@ export function useGameActions( canManageCollections, canShareQR, canPlay, + canPlayStream, canRemoveFromContinuePlaying, currentStatusKey, setStatus, diff --git a/frontend/src/v2/composables/useGlobalHotkeys/index.ts b/frontend/src/v2/composables/useGlobalHotkeys/index.ts index ca9630c82..982b54753 100644 --- a/frontend/src/v2/composables/useGlobalHotkeys/index.ts +++ b/frontend/src/v2/composables/useGlobalHotkeys/index.ts @@ -9,10 +9,12 @@ // g c → collections index // // Two-key sequences (Gmail-style) have a 1.2s idle timeout. Everything is -// guarded against input fields and contenteditable. +// guarded against input fields, contenteditable, and a running game +// (the playing store flag), so hotkeys never fire mid-session. import { onBeforeUnmount } from "vue"; import { useRouter } from "vue-router"; import { ROUTES } from "@/plugins/router"; +import storePlaying from "@/stores/playing"; let installed = false; @@ -35,6 +37,7 @@ export function useGlobalHotkeys() { installed = true; const router = useRouter(); + const playingStore = storePlaying(); let pendingPrefix: string | null = null; let pendingAt = 0; const PREFIX_IDLE_MS = 1200; @@ -42,6 +45,10 @@ export function useGlobalHotkeys() { function onKey(e: KeyboardEvent) { if (e.metaKey || e.ctrlKey || e.altKey) return; if (isEditable(e.target)) return; + // While a game is running the emulator owns the keyboard. "g" and + // "h" are common game keys; without this gate a two-key sequence + // (or "/") would navigate away and kill the session. + if (playingStore.playing) return; const now = performance.now(); if (pendingPrefix && now - pendingAt > PREFIX_IDLE_MS) { diff --git a/frontend/src/v2/layouts/AppLayout.vue b/frontend/src/v2/layouts/AppLayout.vue index e05ef1365..d3ac931be 100644 --- a/frontend/src/v2/layouts/AppLayout.vue +++ b/frontend/src/v2/layouts/AppLayout.vue @@ -20,6 +20,7 @@ import { import { useRouter } from "vue-router"; import storeCollections from "@/stores/collections"; import storePlatforms from "@/stores/platforms"; +import { useStreamingStore } from "@/stores/streaming"; import AppNav from "@/v2/components/AppShell/AppNav.vue"; import BackgroundArt from "@/v2/components/AppShell/BackgroundArt.vue"; import BottomNav from "@/v2/components/AppShell/BottomNav.vue"; @@ -66,6 +67,7 @@ watch( const collectionsStore = storeCollections(); const platformsStore = storePlatforms(); +const streamingStore = useStreamingStore(); // Developer debug overlay — opt-in via Settings → Developer (per-device). // Lazily loaded so its chunk (and the vueuse perf hooks it pulls in) is only @@ -144,6 +146,9 @@ onMounted(() => { } else { prefetchPlatformIcons(platformsStore.allPlatforms.map((p) => p.slug)); } + + // Streaming config is fetched once on app load + void streamingStore.fetchConfig(); }); onBeforeUnmount(() => { diff --git a/frontend/src/v2/router/routes.ts b/frontend/src/v2/router/routes.ts index 68d33279b..854b692fa 100644 --- a/frontend/src/v2/router/routes.ts +++ b/frontend/src/v2/router/routes.ts @@ -37,6 +37,7 @@ export const v2RouteComponents: Partial> = { // Wave 5 — Players emulatorjs: () => import("@/v2/views/Player/EmulatorJS.vue"), ruffle: () => import("@/v2/views/Player/Ruffle.vue"), + stream: () => import("@/v2/views/Player/Stream.vue"), // Wave 6 — Library Tools (Scan / Upload) + Pair scan: () => import("@/v2/views/Scan.vue"), upload: () => import("@/v2/views/Upload.vue"), diff --git a/frontend/src/v2/views/Player/EmulatorJS.vue b/frontend/src/v2/views/Player/EmulatorJS.vue index 58a0ddce7..b49f68642 100644 --- a/frontend/src/v2/views/Player/EmulatorJS.vue +++ b/frontend/src/v2/views/Player/EmulatorJS.vue @@ -468,6 +468,9 @@ onBeforeUnmount(() => { // the user never exited the game to the config screen first. stopActivityHeartbeat(); emitActivityStop(); + // Hand the keyboard and gamepad back to the UI; the flag otherwise + // stays true and pad/hotkey navigation is dead until a reload. + playing.value = false; window.EJS_emulator?.callEvent("exit"); removeIOSFullscreenShim.value?.(); removeIOSFullscreenShim.value = null; diff --git a/frontend/src/v2/views/Player/Ruffle.vue b/frontend/src/v2/views/Player/Ruffle.vue index 0ee8e5031..f8512e5ef 100644 --- a/frontend/src/v2/views/Player/Ruffle.vue +++ b/frontend/src/v2/views/Player/Ruffle.vue @@ -4,11 +4,19 @@ // `src/views/Player/RuffleRS/Base.vue` so playback stays identical; only the // chrome is v2. No shared state with EJS — Flash has its own config. import { RBtn, RCard, RIcon, RSwitch } from "@v2/lib"; -import { computed, nextTick, onMounted, ref, watch } from "vue"; +import { + computed, + nextTick, + onBeforeUnmount, + onMounted, + ref, + watch, +} from "vue"; import { useI18n } from "vue-i18n"; import { useRoute, useRouter } from "vue-router"; import { ROUTES } from "@/plugins/router"; import romApi from "@/services/api/rom"; +import storePlaying from "@/stores/playing"; import storeRoms, { type DetailedRom, type SimpleRom } from "@/stores/roms"; import type { RuffleSourceAPI } from "@/types/ruffle"; import { getDownloadPath } from "@/utils"; @@ -25,6 +33,7 @@ const { t } = useI18n(); const route = useRoute(); const router = useRouter(); const { fullscreenOnPlay } = useFullscreenPref(); +const playingStore = storePlaying(); const rom = ref(null); const gameRunning = ref(false); @@ -106,6 +115,9 @@ const platformLabel = computed( function onPlay() { gameRunning.value = true; + // Flash games are keyboard-driven; flag the session so global hotkeys + // and pad-to-UI translation stay muted while the game owns input. + playingStore.setPlaying(true); nextTick(() => { if (!rom.value) return; @@ -182,6 +194,11 @@ onMounted(async () => { }; document.body.appendChild(script); }); + +onBeforeUnmount(() => { + // Hand the keyboard and gamepad back to the UI on any exit path. + playingStore.setPlaying(false); +});