From a6e8cd75ed747e97256a5559935088ff67448619 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Wed, 8 Jul 2026 17:38:04 -0500 Subject: [PATCH 01/14] feat(streaming): add emulator streaming backend Add /api/streaming endpoints for session claim/release, ROM launch, save states, volume control, and save-and-exit against per-platform emulator broker containers. Sessions are stored in Redis with atomic SET NX claims, owner-bound, and admin force-releasable. Config comes from config.yml (streaming.enabled + containers list) with a STREAMING_SAVE_TIMEOUT env override for slow-saving brokers. Includes 19 endpoint tests covering auth scopes, claim races, ownership, broker failure paths, and force-release. --- backend/config/config_manager.py | 21 + backend/endpoints/streaming.py | 675 ++++++++++++++++++++++ backend/main.py | 2 + backend/tests/endpoints/test_streaming.py | 374 ++++++++++++ env.template | 4 + examples/config.example.yml | 22 + 6 files changed, 1098 insertions(+) create mode 100644 backend/endpoints/streaming.py create mode 100644 backend/tests/endpoints/test_streaming.py diff --git a/backend/config/config_manager.py b/backend/config/config_manager.py index 80ea2068c..f6249f0ad 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 @@ -135,6 +142,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) @@ -447,6 +456,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]: @@ -717,6 +730,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..cba426834 --- /dev/null +++ b/backend/endpoints/streaming.py @@ -0,0 +1,675 @@ +import asyncio +import json +import logging +import os +import urllib.error +import urllib.request +from datetime import datetime, timezone +from typing import Annotated, Any +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 +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:" + + +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 + + +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 _container_key(container: dict[str, Any]) -> str: + """Stable unique key for a container, derived the same way as the broker URL.""" + broker_host = container.get("broker_host", "").rstrip("/") + if broker_host: + return broker_host + # Derive from stream host the same way _broker_url does: replace port with 8000 + stream_host = container.get("host", "").rstrip("/") + try: + parsed = urlparse(stream_host) + return urlunparse(parsed._replace(netloc=f"{parsed.hostname}:8000")).rstrip("/") + except ValueError: + return stream_host + + +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): + # Range 1-9 covers PCSX2 (slots 1-9) and Dolphin (slots 1-8). + # The broker enforces the per-emulator ceiling; the frontend further limits + # the slot selector via platformCapabilities(). + slot: Annotated[int, Field(ge=1, le=9)] = 1 + + +class LoadStateRequest(BaseModel): + # Range 1-10 covers PCSX2 (slots 1-9 + slot 10 autosave) and Dolphin (1-8). + # The broker enforces the per-emulator ceiling. + slot: Annotated[int, Field(ge=1, le=10)] = 1 + + +def _get_streaming_config() -> dict[str, Any]: + """Extract streaming config from the parsed Config object""" + try: + cfg = cm.get_config() + + enabled = getattr(cfg, "STREAMING_ENABLED", False) + containers = getattr(cfg, "STREAMING_CONTAINERS", []) + + return {"enabled": enabled, "containers": containers} + + except Exception: + log.exception( + "streaming: failed to read streaming config - check the streaming " + "section of config.yml; treating streaming as disabled" + ) + return {"enabled": False, "containers": []} + + +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 entry.get("platform", "").lower() == lower: + 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 = container.get("broker_host", "").rstrip("/") + + if not broker_host: + # Derive broker URL from stream host - replace port with 8000 + stream_host = container.get("host", "").rstrip("/") + # Parse out just the scheme + hostname, replace port + # e.g. http://192.168.1.51:3000 → http://192.168.1.51:8000 + try: + parsed = urlparse(stream_host) + broker_host = urlunparse(parsed._replace(netloc=f"{parsed.hostname}:8000")) + except Exception: + broker_host = stream_host + + return f"{broker_host}{path}" + + +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. Uses only Python stdlib urllib - no extra dependencies. + + Raises HTTPException if the broker is unreachable or returns an error. + """ + url = _broker_url(container, "/launch") + secret = os.environ.get("BROKER_SECRET", container.get("broker_secret", "")) + + payload = json.dumps( + { + "rom_path": rom_path, + "rom_name": rom_name, + } + ).encode() + + req = urllib.request.Request( + url, + data=payload, + method="POST", + headers={ + "Content-Type": "application/json", + "Content-Length": str(len(payload)), + **({"X-Broker-Secret": secret} if secret else {}), + }, + ) + + try: + with urllib.request.urlopen(req, timeout=10) as resp: # nosec B310 + body = json.loads(resp.read()) + log.info("streaming: broker launched ROM - %s", body) + except urllib.error.HTTPError as exc: + error_body = exc.read().decode(errors="replace") + log.error("streaming: 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("streaming: 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. + """ + url = _broker_url(container, "/save-and-exit") + secret = os.environ.get("BROKER_SECRET", container.get("broker_secret", "")) + payload = json.dumps({"slot": slot, "wait": wait}).encode() + req = urllib.request.Request( + url, + data=payload, + method="POST", + headers={ + "Content-Type": "application/json", + "Content-Length": str(len(payload)), + **({"X-Broker-Secret": secret} if secret else {}), + }, + ) + # 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. + if wait: + try: + timeout = float(os.environ.get("STREAMING_SAVE_TIMEOUT", "45")) + except ValueError: + timeout = 45.0 + else: + timeout = 5.0 + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310 + body = json.loads(resp.read()) + saved = bool(body.get("saved", False)) + log.info( + "streaming: broker save-and-exit - saved=%s slot=%d wait=%s", + saved, + slot, + wait, + ) + return saved + except Exception as exc: + log.warning("streaming: broker save-and-exit failed - %s", exc) + return False + + +def _volume_broker(container: dict[str, Any], level: int) -> bool: + """POST /volume to the broker. Best-effort - logs but never raises.""" + url = _broker_url(container, "/volume") + secret = os.environ.get("BROKER_SECRET", container.get("broker_secret", "")) + payload = json.dumps({"level": level}).encode() + req = urllib.request.Request( + url, + data=payload, + method="POST", + headers={ + "Content-Type": "application/json", + "Content-Length": str(len(payload)), + **({"X-Broker-Secret": secret} if secret else {}), + }, + ) + try: + with urllib.request.urlopen(req, timeout=5) as resp: # nosec B310 + body = json.loads(resp.read()) + log.debug("streaming: broker volume set to %d - %s", level, body) + return body.get("status") == "ok" + except Exception as exc: + log.warning("streaming: broker volume failed - %s", exc) + return False + + +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.""" + url = _broker_url(container, "/mute") + secret = os.environ.get("BROKER_SECRET", container.get("broker_secret", "")) + body_dict: dict[str, Any] = {} if mute is None else {"mute": mute} + payload = json.dumps(body_dict).encode() + req = urllib.request.Request( + url, + data=payload, + method="POST", + headers={ + "Content-Type": "application/json", + "Content-Length": str(len(payload)), + **({"X-Broker-Secret": secret} if secret else {}), + }, + ) + try: + with urllib.request.urlopen(req, timeout=5) as resp: # nosec B310 + body = json.loads(resp.read()) + confirmed = body.get("mute") + log.debug("streaming: broker mute - %s", body) + return confirmed + except Exception as exc: + log.warning("streaming: broker mute failed - %s", exc) + return 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.""" + url = _broker_url(container, "/save-state") + secret = os.environ.get("BROKER_SECRET", container.get("broker_secret", "")) + payload = json.dumps({"slot": slot}).encode() + req = urllib.request.Request( + url, + data=payload, + method="POST", + headers={ + "Content-Type": "application/json", + "Content-Length": str(len(payload)), + **({"X-Broker-Secret": secret} if secret else {}), + }, + ) + try: + with urllib.request.urlopen(req, timeout=5) as resp: # nosec B310 + body = json.loads(resp.read()) + log.debug("streaming: broker save-state slot=%d - %s", slot, body) + return body.get("status") == "saving" + except Exception as exc: + log.warning("streaming: broker save-state failed - %s", exc) + return False + + +def _load_state_broker(container: dict[str, Any], slot: int) -> bool: + """POST /load-state to the broker. Returns True if broker confirmed success.""" + url = _broker_url(container, "/load-state") + secret = os.environ.get("BROKER_SECRET", container.get("broker_secret", "")) + payload = json.dumps({"slot": slot}).encode() + req = urllib.request.Request( + url, + data=payload, + method="POST", + headers={ + "Content-Type": "application/json", + "Content-Length": str(len(payload)), + **({"X-Broker-Secret": secret} if secret else {}), + }, + ) + try: + with urllib.request.urlopen( + req, timeout=60 + ) as resp: # nosec B310 - worst-case: 9 slot cycles × ~5s xdotool timeout + body = json.loads(resp.read()) + loaded = bool(body.get("loaded", False)) + log.debug("streaming: broker load-state slot=%d loaded=%s", slot, loaded) + return loaded + except Exception as exc: + log.warning("streaming: broker load-state failed - %s", exc) + return False + + +def _stop_broker(container: dict[str, Any]) -> None: + """Tell the broker to stop emulator. Best-effort - don't raise on failure.""" + url = _broker_url(container, "/launch") + secret = os.environ.get("BROKER_SECRET", container.get("broker_secret", "")) + req = urllib.request.Request( + url, + method="DELETE", + headers={**({"X-Broker-Secret": secret} if secret else {})}, + ) + try: + with urllib.request.urlopen(req, timeout=5): # nosec B310 + pass + except Exception as exc: + log.warning("streaming: could not stop broker session - %s", exc) + + +# ── 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("streaming: container missing platform/host - skipping: %s", c) + continue + + safe_containers.append( + { + "platform": c.get("platform"), + "host": c.get("host"), + "label": c.get("label") or c.get("platform", "").upper(), + } + ) + + 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") + + platform = rom.platform_slug + container = _container_for_platform(platform) + if container is None: + raise HTTPException( + status_code=404, + detail=f"No streaming container configured for platform '{platform}'", + ) + + # 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. + claimed = await async_cache.set( + _session_redis_key(session_key), json.dumps(session), nx=True + ) + 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("streaming: session claimed - platform=%s rom=%s", platform, rom_name) + + return JSONResponse( + { + "platform": platform, + "host": container["host"], + "label": container.get("label", platform.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 + ) + + await async_cache.delete(_session_redis_key(session_key)) + log.info("streaming: 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, _, _ = 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") + + 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, _, _ = 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") + + 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 slot (1-9) without stopping the emulator.""" + container, _, _ = await _resolve_owned_session(platform, request) + + 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") + + 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 slot (1-10). Slot 10 is the autosave.""" + container, _, _ = await _resolve_owned_session(platform, request) + + 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") + + 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("streaming: 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: + """Admin - 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("streaming: 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..65d4f89ce --- /dev/null +++ b/backend/tests/endpoints/test_streaming.py @@ -0,0 +1,374 @@ +import asyncio +import logging +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 + + +@pytest.fixture +def access_token(admin_user: User): + return oauth_handler.create_access_token( + data={ + "sub": admin_user.username, + "iss": "romm:oauth", + "scopes": " ".join(admin_user.oauth_scopes), + }, + expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS), + ) + + +@pytest.fixture +def viewer_access_token(viewer_user: User): + return oauth_handler.create_access_token( + data={ + "sub": viewer_user.username, + "iss": "romm:oauth", + "scopes": " ".join(viewer_user.oauth_scopes), + }, + expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS), + ) + + +def _mock_cm(enabled=True, containers=None): + """Return a mock config_manager that yields the given streaming config.""" + if containers is None: + containers = [] + cfg = MagicMock() + cfg.STREAMING_ENABLED = enabled + cfg.STREAMING_CONTAINERS = containers + return cfg + + +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 _claim(client, token, rom_id): + return client.post( + "/api/streaming/sessions", + json={"rom_id": rom_id}, + headers={"Authorization": f"Bearer {token}"}, + ) + + +# ── /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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[bad_container]), + ): + with caplog.at_level(logging.WARNING, logger="romm"): + response = client.get( + "/api/streaming/config", + headers={"Authorization": f"Bearer {access_token}"}, + ) + finally: + romm_logger.removeHandler(caplog.handler) + assert response.status_code == 200 + assert response.json()["containers"] == [] + assert "missing platform/host" in caplog.text + + +# ── 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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[_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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[]), + ): + r = _claim(client, access_token, 999999) + assert r.status_code == 404 + + +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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[_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" + containers = [ + _container_for(rom, broker_host=shared_broker), + _container_for(rom2, broker_host=shared_broker), + ] + with patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=containers), + ): + 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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[_container_for(rom)]), + ): + with patch( + "endpoints.streaming._call_broker", + side_effect=HTTPException(status_code=503, detail="unreachable"), + ): + r1 = _claim(client, access_token, rom.id) + with patch("endpoints.streaming._call_broker"): + r2 = _claim(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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[_container_for(rom)]), + ): + with patch("endpoints.streaming._call_broker"): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="http://test" + ) as ac: + headers = {"Authorization": f"Bearer {access_token}"} + r1, r2 = await asyncio.gather( + ac.post( + "/api/streaming/sessions", + json={"rom_id": rom.id}, + headers=headers, + ), + ac.post( + "/api/streaming/sessions", + json={"rom_id": rom.id}, + headers=headers, + ), + ) + 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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[_container_for(rom)]), + ): + with patch("endpoints.streaming._call_broker"): + _claim(client, access_token, rom.id) + with patch("endpoints.streaming._stop_broker"): + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers={"Authorization": f"Bearer {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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[_container_for(rom)]), + ): + with patch("endpoints.streaming._call_broker"): + # viewer claims the session; admin could override, a viewer cannot + r_claim = _claim(client, access_token, rom.id) + r = client.delete( + f"/api/streaming/sessions/{rom.platform_slug}", + headers={"Authorization": f"Bearer {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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[_container_for(rom)]), + ): + with patch("endpoints.streaming._call_broker"): + _claim(client, access_token, rom.id) + r = client.post( + f"/api/streaming/sessions/{rom.platform_slug}/save-state", + json={"slot": 1}, + headers={"Authorization": f"Bearer {viewer_access_token}"}, + ) + assert r.status_code == 403 + + +def test_save_and_exit_releases_session(client, access_token, rom: Rom): + with patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[_container_for(rom)]), + ): + with patch("endpoints.streaming._call_broker"): + _claim(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={"Authorization": f"Bearer {access_token}"}, + ) + # Container must be claimable again after save-and-exit. + with patch("endpoints.streaming._call_broker"): + r2 = _claim(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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[_container_for(rom)]), + ): + with patch("endpoints.streaming._call_broker"): + _claim(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={"Authorization": f"Bearer {access_token}"}, + ) + with patch("endpoints.streaming._call_broker"): + r2 = _claim(client, access_token, rom.id) + assert r.status_code == 200 + assert r.json()["saved"] is False + assert r2.status_code == 200 + + +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 patch( + "endpoints.streaming.cm.get_config", + return_value=_mock_cm(containers=[_container_for(rom)]), + ): + with patch("endpoints.streaming._call_broker"): + _claim(client, access_token, rom.id) + with patch("endpoints.streaming._stop_broker") as stop_broker: + r = client.delete( + "/api/streaming/sessions", + headers={"Authorization": f"Bearer {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={"Authorization": f"Bearer {viewer_access_token}"}, + ) + assert r.status_code == 403 diff --git a/env.template b/env.template index af6828cc2..79c2df532 100644 --- a/env.template +++ b/env.template @@ -139,3 +139,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 Broker Integration +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 From d94c5b66ee29d6423830fc831156a3964d79e970 Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Wed, 8 Jul 2026 17:38:15 -0500 Subject: [PATCH 02/14] feat(streaming): add streaming player frontend Add a Pinia streaming store (config fetch, session lifecycle, broker controls), a v1 player view at rom/:rom/stream with save state and volume controls, and a cast button on PlayBtn for platforms with a configured streaming container. The route registers a v2 named view via v2For so the v2 fallback screen shows until a v2 player lands. --- .../src/components/common/Game/PlayBtn.vue | 17 + frontend/src/layouts/Main.vue | 3 + frontend/src/plugins/router.ts | 9 + frontend/src/stores/streaming.ts | 258 ++++++ frontend/src/views/Player/Stream/Player.vue | 852 ++++++++++++++++++ 5 files changed, 1139 insertions(+) create mode 100644 frontend/src/stores/streaming.ts create mode 100644 frontend/src/views/Player/Stream/Player.vue diff --git a/frontend/src/components/common/Game/PlayBtn.vue b/frontend/src/components/common/Game/PlayBtn.vue index 368f5ec18..35f5ec939 100644 --- a/frontend/src/components/common/Game/PlayBtn.vue +++ b/frontend/src/components/common/Game/PlayBtn.vue @@ -11,6 +11,7 @@ import { ROUTES } from "@/plugins/router"; import storeConfig from "@/stores/config"; import storeHeartbeat from "@/stores/heartbeat"; import storeRoms, { type SimpleRom } from "@/stores/roms"; +import { useStreamingStore } from "@/stores/streaming"; import type { Events } from "@/types/emitter"; import { isEJSEmulationSupported, isRuffleEmulationSupported } from "@/utils"; @@ -23,6 +24,10 @@ const router = useRouter(); const { config } = storeToRefs(configStore); const { value: heartbeat } = storeToRefs(heartbeatStore); const emitter = inject>("emitter"); +const streamingStore = useStreamingStore(); +const streamingContainer = computed(() => + streamingStore.containerForPlatform(props.rom.platform_slug), +); const isAprilFools = computed(() => { const today = new Date(); @@ -98,4 +103,16 @@ async function goToPlayer(rom: SimpleRom) { mdi-play + + + mdi-cast + diff --git a/frontend/src/layouts/Main.vue b/frontend/src/layouts/Main.vue index 46b161fab..37e928bfb 100644 --- a/frontend/src/layouts/Main.vue +++ b/frontend/src/layouts/Main.vue @@ -29,11 +29,13 @@ import TryV2Banner from "@/components/common/TryV2Banner.vue"; import storeCollections from "@/stores/collections"; import storeNavigation from "@/stores/navigation"; import storePlatforms from "@/stores/platforms"; +import { useStreamingStore } from "@/stores/streaming"; import type { Events } from "@/types/emitter"; const navigationStore = storeNavigation(); const platformsStore = storePlatforms(); const collectionsStore = storeCollections(); +const streamingStore = useStreamingStore(); const emitter = inject>("emitter"); emitter?.on("refreshDrawer", async () => { @@ -66,6 +68,7 @@ onBeforeMount(async () => { if (showVirtualCollections) { collectionsStore.fetchVirtualCollections(virtualCollectionTypeRef.value); } + streamingStore.fetchConfig(); navigationStore.reset(); }); diff --git a/frontend/src/plugins/router.ts b/frontend/src/plugins/router.ts index 96fd50160..c03f5e1b9 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/Player/Stream/Player.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/stores/streaming.ts b/frontend/src/stores/streaming.ts new file mode 100644 index 000000000..8d1d70f9c --- /dev/null +++ b/frontend/src/stores/streaming.ts @@ -0,0 +1,258 @@ +import { isAxiosError } from "axios"; +import { defineStore } from "pinia"; +import { ref, computed } from "vue"; +import api from "@/services/api"; + +// ── Types ───────────────────────────────────────────────────────────────────── + +export interface StreamingContainer { + platform: string; // e.g. "ps2" + host: string; // browser-facing URL, e.g. "http://192.168.1.50:3000" + label: string; // e.g. "PCSX2" +} + +export interface StreamingConfig { + enabled: boolean; + containers: StreamingContainer[]; +} + +export interface ActiveSession { + platform: string; + host: string; + label: string; + rom_name: string; + claimed_at: string; +} + +// ── 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. + * Case-insensitive so "PS2" and "ps2" both match. + */ + 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. + * + * maxSlots - number of user-accessible save slots (slot selector range) + * hasAutosave - whether a dedicated "load autosave" action is available + * + * Dolphin (ngc, wii, wiiu): slots 1-7 user-accessible; slot 8 reserved for auto-save. + * PCSX2 (ps2), xemu (xbox): 9 slots + slot 10 autosave. + * Eden (switch) and unknown platforms: no save state UI - a platform gets + * slots only once its broker's slot semantics are known. + */ + function platformCapabilities(slug: string | null | undefined): { + maxSlots: number; + hasAutosave: boolean; + autosaveSlot: number; + } { + const lower = (slug ?? "").toLowerCase(); + if (lower === "ngc" || lower === "wii" || lower === "wiiu") { + return { maxSlots: 7, hasAutosave: true, autosaveSlot: 8 }; + } + if (lower === "switch") { + return { maxSlots: 0, hasAutosave: false, autosaveSlot: 0 }; + } + if (lower === "ps2" || lower === "xbox") { + return { maxSlots: 9, hasAutosave: true, autosaveSlot: 10 }; + } + return { maxSlots: 0, hasAutosave: false, autosaveSlot: 0 }; + } + + /** + * Fetch streaming config from the backend once on app load. + * Non-fatal - if it fails, streaming stays disabled and no buttons appear. + */ + async function fetchConfig(): Promise { + loading.value = true; + error.value = null; + try { + const { data } = await api.get("/streaming/config", { + headers: { "Cache-Control": "no-cache" }, + }); + 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 { + try { + const { data } = await api.post("/streaming/sessions", { + rom_id: romId, + }); + activeSession.value = data; + return data; + } catch (e) { + const response = isAxiosError(e) ? e.response : undefined; + const detail = response?.data?.detail; + const err = Object.assign( + new Error(detail?.message ?? `HTTP ${response?.status}`), + { status: response?.status, detail }, + ); + throw err; + } + } + + /** + * Release the active session when the user leaves the player page. + * Best-effort - never throws. + */ + async function releaseSession(platform: string): Promise { + if (!platform) return; + activeSession.value = null; + try { + await api.delete(`/streaming/sessions/${platform}`); + } catch (err) { + console.warn("[streaming] Could not release session:", err); + } + } + + /** + * 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. + * Best-effort - never throws. + */ + async function saveAndExit( + platform: string, + slot = 0, + wait = true, + ): Promise { + if (!platform) return false; + activeSession.value = null; + try { + const { data } = await api.post( + `/streaming/sessions/${platform}/save-and-exit`, + { slot, wait }, + ); + return data.saved ?? false; + } catch (err) { + console.warn("[streaming] Could not save-and-exit:", err); + return false; + } + } + + /** + * Set emulator volume (0-100). Best-effort - never throws. + */ + async function setVolume(platform: string, level: number): Promise { + if (!platform) return; + try { + await api.post(`/streaming/sessions/${platform}/volume`, { + level: Math.round(level), + }); + } catch (err) { + console.warn("[streaming] Could not set volume:", err); + } + } + + /** + * Toggle or explicitly set mute. Pass true/false to set, omit for toggle. + * Best-effort - never throws. + */ + async function setMute(platform: string, mute?: boolean): Promise { + if (!platform) return; + try { + await api.post( + `/streaming/sessions/${platform}/mute`, + mute !== undefined ? { mute } : {}, + ); + } catch (err) { + console.warn("[streaming] Could not set mute:", err); + } + } + + /** + * Save game state to a slot (1-9) without stopping the emulator. + * The broker fires the save in the background and returns immediately. + * Best-effort - never throws. + */ + async function saveState(platform: string, slot = 1): Promise { + if (!platform) return false; + try { + const { data } = await api.post( + `/streaming/sessions/${platform}/save-state`, + { slot }, + ); + return data.status === "saving"; + } catch (err) { + console.warn("[streaming] Could not save state:", err); + return false; + } + } + + /** + * Load game state from a slot (1-10). Slot 10 is the autosave slot on xemu and rpcs3. + * Best-effort - never throws. + */ + async function loadState(platform: string, slot = 1): Promise { + if (!platform) return false; + try { + const { data } = await api.post( + `/streaming/sessions/${platform}/load-state`, + { slot }, + ); + return data.loaded ?? false; + } catch (err) { + console.warn("[streaming] Could not load state:", err); + return false; + } + } + + return { + config, + activeSession, + loading, + error, + isEnabled, + containerForPlatform, + platformCapabilities, + fetchConfig, + claimSession, + releaseSession, + saveAndExit, + setVolume, + setMute, + saveState, + loadState, + }; +}); diff --git a/frontend/src/views/Player/Stream/Player.vue b/frontend/src/views/Player/Stream/Player.vue new file mode 100644 index 000000000..ca56981e2 --- /dev/null +++ b/frontend/src/views/Player/Stream/Player.vue @@ -0,0 +1,852 @@ +