mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 02:24:09 +01:00
Merge pull request #4478 from LoneAngelFayt/feat/streaming-webstation
fix(streaming): prefer the emulator's own screenshot for save-state thumbnails
This commit is contained in:
@@ -163,11 +163,6 @@ class SwapDiscResponse(BaseModel):
|
||||
platform: str
|
||||
|
||||
|
||||
class StateFrameResponse(BaseModel):
|
||||
status: Literal["ok"]
|
||||
platform: str
|
||||
|
||||
|
||||
class JoinableSessionSchema(BaseModel):
|
||||
"""A session its host opened to other players, plus enough of the ROM to
|
||||
draw a cover tile without a second request per session."""
|
||||
|
||||
@@ -36,7 +36,6 @@ from endpoints.responses.streaming import (
|
||||
SaveAndExitResponse,
|
||||
SaveStateResponse,
|
||||
SessionStatusSchema,
|
||||
StateFrameResponse,
|
||||
StreamingConfigSchema,
|
||||
SwapDiscResponse,
|
||||
VolumeResponse,
|
||||
@@ -227,26 +226,6 @@ async def _session_status(platform: str, request: Request) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
async def _read_capped_body(request: Request, max_bytes: int) -> bytes | None:
|
||||
"""The request body, or None once it goes past `max_bytes`.
|
||||
|
||||
`Request.body()` buffers everything the client sends before any check can
|
||||
look at the size, so the cap is applied as the chunks arrive instead.
|
||||
"""
|
||||
declared = request.headers.get("content-length")
|
||||
if declared is not None and declared.isdigit() and int(declared) > max_bytes:
|
||||
return None
|
||||
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
return None
|
||||
chunks.append(chunk)
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
def _joinable_container_label(
|
||||
grouped: dict[str, list[ResolvedContainer]], container_key: str
|
||||
) -> str | None:
|
||||
@@ -1075,31 +1054,6 @@ async def save_state(
|
||||
return SaveStateResponse(status="saving", slot=req.slot, platform=platform)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.post, "/sessions/{platform}/state-frame", [Scope.ROMS_USER_WRITE]
|
||||
)
|
||||
async def put_state_frame(request: Request, platform: str) -> StateFrameResponse:
|
||||
"""Stash a frame the browser grabbed off the stream canvas, for the state
|
||||
save that follows it to pick up as its thumbnail."""
|
||||
_, session_key, session = await access.resolve_owned_session(platform, request)
|
||||
|
||||
image = await _read_capped_body(request, states.SCREENSHOT_MAX_BYTES)
|
||||
if image is None:
|
||||
raise HTTPException(status_code=413, detail="Frame too large")
|
||||
if not image.startswith(states.PNG_MAGIC):
|
||||
raise HTTPException(status_code=400, detail="Frame must be a PNG")
|
||||
|
||||
rom_id = session.get("rom_id")
|
||||
if not isinstance(rom_id, int):
|
||||
raise HTTPException(status_code=409, detail="Session has no rom")
|
||||
|
||||
await states.stash_state_frame(
|
||||
access.session_owner_id(session, request), rom_id, image
|
||||
)
|
||||
await refresh_session(session_key)
|
||||
return StateFrameResponse(status="ok", platform=platform)
|
||||
|
||||
|
||||
@protected_route(
|
||||
router.post, "/sessions/{platform}/load-state", [Scope.ROMS_USER_WRITE]
|
||||
)
|
||||
|
||||
@@ -38,6 +38,9 @@ TRANSFER_TIMEOUT = 60
|
||||
SWAP_DISC_TIMEOUT = 120
|
||||
CARD_HYDRATE_TIMEOUT = 120
|
||||
CARD_TEARDOWN_TIMEOUT = 30
|
||||
# An optional thumbnail, fetched while the claim is still held and the player
|
||||
# waits on the exit screen, so it does not get the archive budget.
|
||||
STATE_SCREENSHOT_TIMEOUT = 10
|
||||
|
||||
# A pulled save archive can be large (PCSX2 ships whole 8 MB memory cards, a
|
||||
# Wii NAND can hold many titles); 256 MB is generous for every emulator that
|
||||
|
||||
@@ -12,14 +12,17 @@ Broker file API (secret-protected, stdlib on the broker side):
|
||||
save is in flight, so no clock coupling between
|
||||
hosts. Returns raw bytes + X-State-Filename.
|
||||
PUT /state-file?filename=NAME - write NAME into the emulator's state dir.
|
||||
GET /state-screenshot?slot=N - the container's own capture of the stream at
|
||||
the moment of that save, used as the thumbnail.
|
||||
404 when it captured nothing.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import zipfile
|
||||
import zlib
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import quote
|
||||
|
||||
@@ -34,7 +37,6 @@ from handler.database import (
|
||||
db_user_handler,
|
||||
)
|
||||
from handler.filesystem import fs_asset_handler
|
||||
from handler.redis_handler import async_cache
|
||||
from handler.streaming import broker, commands
|
||||
from handler.streaming.config import ResolvedContainer
|
||||
from handler.streaming.session_store import set_session_disc
|
||||
@@ -190,26 +192,26 @@ def push_state_file(
|
||||
|
||||
# PCSX2 embeds a PNG of the moment of save inside every .p2s savestate zip
|
||||
# under this entry name (pcsx2/SaveState.cpp: EntryFilename_Screenshot).
|
||||
# Extracting it gives each pulled state a thumbnail with no broker round-trip,
|
||||
# mirroring how in-browser EmulatorJS states carry a screenshot.
|
||||
_SCREENSHOT_ZIP_ENTRY = "Screenshot.png"
|
||||
SCREENSHOT_MAX_BYTES = 16 * 1024 * 1024
|
||||
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
|
||||
def _is_png(data: bytes | None) -> bool:
|
||||
return data is not None and data.startswith(PNG_MAGIC)
|
||||
|
||||
|
||||
def extract_state_screenshot(emulator: str, state_content: bytes) -> bytes | None:
|
||||
"""Pull the embedded frame PNG out of a savestate archive, or None when the
|
||||
format carries no embedded screenshot. Only PCSX2 (.p2s zip) embeds one;
|
||||
the others write the frame as its own file, served by /state-screenshot."""
|
||||
format carries no embedded screenshot. Only PCSX2 (.p2s zip) embeds one."""
|
||||
if emulator != "pcsx2":
|
||||
return None
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(state_content)) as zf:
|
||||
with zf.open(_SCREENSHOT_ZIP_ENTRY) as entry:
|
||||
data = entry.read(SCREENSHOT_MAX_BYTES + 1)
|
||||
except (KeyError, zipfile.BadZipFile, OSError) as exc:
|
||||
# No screenshot entry, or the state is not a readable zip. Not fatal:
|
||||
# the state still syncs, it just has no thumbnail.
|
||||
except (KeyError, zipfile.BadZipFile, zlib.error, EOFError, OSError) as exc:
|
||||
# Never fatal: the state still syncs, it just has no thumbnail.
|
||||
log.warning("could not extract state screenshot, %s", exc)
|
||||
return None
|
||||
if not data or len(data) > SCREENSHOT_MAX_BYTES:
|
||||
@@ -217,49 +219,24 @@ def extract_state_screenshot(emulator: str, state_content: bytes) -> bytes | Non
|
||||
return data
|
||||
|
||||
|
||||
_FRAME_KEY_PREFIX = "romm:streaming:frame:"
|
||||
# Long enough to cover the broker's state write plus the pull retries, short
|
||||
# enough that a frame never outlives the save it was captured for.
|
||||
_FRAME_TTL_SECONDS = 120
|
||||
|
||||
|
||||
def _frame_redis_key(user_id: int, rom_id: int) -> str:
|
||||
return f"{_FRAME_KEY_PREFIX}{user_id}:{rom_id}"
|
||||
|
||||
|
||||
async def stash_state_frame(user_id: int, rom_id: int, image: bytes) -> None:
|
||||
"""Hold a browser-captured frame until the state it belongs to is pulled."""
|
||||
await async_cache.set(
|
||||
_frame_redis_key(user_id, rom_id),
|
||||
base64.b64encode(image),
|
||||
ex=_FRAME_TTL_SECONDS,
|
||||
)
|
||||
|
||||
|
||||
async def take_state_frame(user_id: int, rom_id: int) -> bytes | None:
|
||||
key = _frame_redis_key(user_id, rom_id)
|
||||
raw = await async_cache.get(key)
|
||||
await async_cache.delete(key)
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return base64.b64decode(raw)
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def fetch_state_screenshot(container: ResolvedContainer, slot: int) -> bytes | None:
|
||||
"""GET /state-screenshot from the broker, for emulators whose state files
|
||||
carry no frame of their own. A 404 is the normal "this broker does not
|
||||
capture frames" answer, so it is not logged."""
|
||||
"""GET /state-screenshot from the broker, the container's own capture of the
|
||||
stream as the state was saved. A 404 means no frame, so it is not logged."""
|
||||
result = broker.get_binary_safe(
|
||||
container,
|
||||
container.protocol.transfer_route(f"/state-screenshot?slot={slot}"),
|
||||
"state-screenshot GET",
|
||||
max_bytes=SCREENSHOT_MAX_BYTES,
|
||||
timeout=broker.TRANSFER_TIMEOUT,
|
||||
timeout=broker.STATE_SCREENSHOT_TIMEOUT,
|
||||
)
|
||||
return result[1] if result else None
|
||||
if result is None:
|
||||
return None
|
||||
# This source shadows the frame a state embeds for itself, so a body that is
|
||||
# not a PNG has to read as no frame rather than as an unusable one.
|
||||
if not _is_png(result[1]):
|
||||
log.warning("broker state screenshot for slot %d is not a PNG", slot)
|
||||
return None
|
||||
return result[1]
|
||||
|
||||
|
||||
async def store_state_screenshot(
|
||||
@@ -271,9 +248,9 @@ async def store_state_screenshot(
|
||||
stem with a .png extension. is_gallery stays False (the default) so it never
|
||||
shows in the user's screenshot gallery.
|
||||
"""
|
||||
# Both sources are unverified bytes: a zip entry that only claims to be a
|
||||
# PNG, or whatever the broker returned. Guard here so one check covers both.
|
||||
if not image.startswith(PNG_MAGIC):
|
||||
# The zip entry only claims to be a PNG. The broker's body is checked where
|
||||
# it is chosen, since there the answer decides whether this one is tried.
|
||||
if not _is_png(image):
|
||||
log.warning("state screenshot for %s is not a PNG, skipping", state_filename)
|
||||
return
|
||||
|
||||
@@ -434,16 +411,13 @@ async def pull_state_to_library(
|
||||
except ValueError:
|
||||
log.warning("broker returned invalid state filename")
|
||||
return False
|
||||
# The browser frame is preferred: it is what the player actually saw,
|
||||
# and capturing it never asks the emulator to read back its own
|
||||
# framebuffer, which is what deadlocks GPU-rendered cores. PCSX2 embeds
|
||||
# a frame in the state file; the rest write one beside it.
|
||||
screenshot = await take_state_frame(user_id, rom_id)
|
||||
if screenshot is None:
|
||||
screenshot = extract_state_screenshot(emulator, content)
|
||||
# The container's capture is the frame the player saw, and it is the
|
||||
# same route for every emulator; an embedded frame only fills a 404.
|
||||
screenshot = await asyncio.to_thread(fetch_state_screenshot, container, slot)
|
||||
if screenshot is None:
|
||||
# Off the loop as well: reading the zip copies the whole state body.
|
||||
screenshot = await asyncio.to_thread(
|
||||
fetch_state_screenshot, container, slot
|
||||
extract_state_screenshot, emulator, content
|
||||
)
|
||||
try:
|
||||
await store_state_asset(
|
||||
|
||||
@@ -2317,6 +2317,27 @@ def _state_for(rom: Rom, user: User, file_name: str, emulator: str) -> State:
|
||||
)
|
||||
|
||||
|
||||
def _screenshot_for(rom: Rom, stem: str) -> Screenshot:
|
||||
"""A scan_screenshot() stand-in on `stem`, the name State.screenshot matches."""
|
||||
return Screenshot(
|
||||
file_name=f"{stem}.png",
|
||||
file_name_no_tags=stem,
|
||||
file_name_no_ext=stem,
|
||||
file_extension="png",
|
||||
file_path=f"{rom.platform_slug}/screenshots",
|
||||
file_size_bytes=7,
|
||||
)
|
||||
|
||||
|
||||
def _written_screenshot(write_file: AsyncMock) -> bytes:
|
||||
"""The bytes stored under the state's .png, from a patched write_file."""
|
||||
calls = [
|
||||
c for c in write_file.await_args_list if c.kwargs["filename"].endswith(".png")
|
||||
]
|
||||
assert len(calls) == 1, "expected exactly one screenshot write"
|
||||
return calls[0].kwargs["file"]
|
||||
|
||||
|
||||
def test_claim_spawns_state_hydration(client, access_token, rom: Rom):
|
||||
"""Claiming a session must schedule a background hydration of the
|
||||
container's save-state slots from the user's stored states."""
|
||||
@@ -2696,18 +2717,11 @@ def test_pull_state_to_library_stores_state(rom: Rom, admin_user: User):
|
||||
assert db_state.emulator == "pcsx2"
|
||||
|
||||
|
||||
def test_pull_state_falls_back_to_broker_screenshot(rom: Rom, admin_user: User):
|
||||
def test_pull_state_takes_the_broker_screenshot(rom: Rom, admin_user: User):
|
||||
"""Dolphin states embed no frame, so the pull takes the broker's capture."""
|
||||
container = {**_container_for(rom), "label": "Dolphin"}
|
||||
scanned = _state_for(rom, admin_user, "Game.s03", "dolphin")
|
||||
scanned_shot = Screenshot(
|
||||
file_name="Game.s03.png",
|
||||
file_name_no_tags="Game.s03",
|
||||
file_name_no_ext="Game.s03",
|
||||
file_extension="png",
|
||||
file_path=f"{rom.platform_slug}/screenshots",
|
||||
file_size_bytes=7,
|
||||
)
|
||||
scanned_shot = _screenshot_for(rom, "Game.s03")
|
||||
with (
|
||||
patch(
|
||||
"handler.streaming.states.fetch_state_file",
|
||||
@@ -2736,29 +2750,22 @@ def test_pull_state_falls_back_to_broker_screenshot(rom: Rom, admin_user: User):
|
||||
assert db_state.screenshot is not None
|
||||
|
||||
|
||||
def test_pull_state_prefers_browser_frame(rom: Rom, admin_user: User):
|
||||
"""A frame the browser grabbed off the canvas beats asking the broker."""
|
||||
container = {**_container_for(rom), "label": "Dolphin"}
|
||||
scanned = _state_for(rom, admin_user, "Game.s04", "dolphin")
|
||||
scanned_shot = Screenshot(
|
||||
file_name="Game.s04.png",
|
||||
file_name_no_tags="Game.s04",
|
||||
file_name_no_ext="Game.s04",
|
||||
file_extension="png",
|
||||
file_path=f"{rom.platform_slug}/screenshots",
|
||||
file_size_bytes=7,
|
||||
)
|
||||
def test_pull_state_prefers_broker_screenshot_over_embedded(rom: Rom, admin_user: User):
|
||||
"""The container's capture is the frame the player saw, so it beats the one
|
||||
PCSX2 embedded in the state."""
|
||||
container = {**_container_for(rom), "label": "PCSX2"}
|
||||
scanned = _state_for(rom, admin_user, "Game.05.p2s", "pcsx2")
|
||||
scanned_shot = _screenshot_for(rom, "Game.05")
|
||||
embedded = states.PNG_MAGIC + b"embedded-frame"
|
||||
with (
|
||||
patch(
|
||||
"handler.streaming.states.fetch_state_file",
|
||||
return_value=("Game.s04", b"state-bytes"),
|
||||
return_value=("Game.05.p2s", _p2s_bytes(embedded)),
|
||||
),
|
||||
patch(
|
||||
"handler.streaming.states.take_state_frame",
|
||||
new=AsyncMock(return_value=_PNG),
|
||||
),
|
||||
patch("handler.streaming.states.fetch_state_screenshot") as fetch_shot,
|
||||
patch("handler.asset_store.fs_asset_handler.write_file", new=AsyncMock()),
|
||||
"handler.streaming.states.fetch_state_screenshot", return_value=_PNG
|
||||
) as fetch_shot,
|
||||
patch("handler.asset_store.fs_asset_handler.write_file", new=AsyncMock()) as wf,
|
||||
patch("handler.asset_store.scan_state", new=AsyncMock(return_value=scanned)),
|
||||
patch(
|
||||
"handler.asset_store.scan_screenshot",
|
||||
@@ -2766,41 +2773,63 @@ def test_pull_state_prefers_browser_frame(rom: Rom, admin_user: User):
|
||||
),
|
||||
):
|
||||
ok = asyncio.run(
|
||||
states.pull_state_to_library(admin_user.id, rom.id, _resolved(container), 4)
|
||||
states.pull_state_to_library(admin_user.id, rom.id, _resolved(container), 5)
|
||||
)
|
||||
assert ok is True
|
||||
fetch_shot.assert_not_called()
|
||||
fetch_shot.assert_called_once()
|
||||
assert _written_screenshot(wf) == _PNG
|
||||
|
||||
|
||||
def test_state_frame_stashes_capture(client, access_token):
|
||||
"""The endpoint holds the frame for the save that follows it."""
|
||||
rom = _rom_on("ps2")
|
||||
with _streaming(_container_for(rom)):
|
||||
_claim_ok(client, access_token, rom.id)
|
||||
with patch(
|
||||
"handler.streaming.states.stash_state_frame", new=AsyncMock()
|
||||
) as stash:
|
||||
r = client.post(
|
||||
f"/api/streaming/sessions/{rom.platform_slug}/state-frame",
|
||||
content=_PNG,
|
||||
headers={**_auth(access_token), "Content-Type": "image/png"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
stash.assert_awaited_once()
|
||||
assert stash.await_args_list[0].args[2] == _PNG
|
||||
|
||||
|
||||
def test_state_frame_rejects_non_png(client, access_token):
|
||||
"""Only PNG survives the asset pipeline, so anything else is refused here."""
|
||||
rom = _rom_on("ps2")
|
||||
with _streaming(_container_for(rom)):
|
||||
_claim_ok(client, access_token, rom.id)
|
||||
r = client.post(
|
||||
f"/api/streaming/sessions/{rom.platform_slug}/state-frame",
|
||||
content=b"GIF89a-not-a-png",
|
||||
headers={**_auth(access_token), "Content-Type": "image/png"},
|
||||
def test_pull_state_falls_back_to_embedded_screenshot(rom: Rom, admin_user: User):
|
||||
"""A container that captured no frame leaves PCSX2's embedded one."""
|
||||
container = {**_container_for(rom), "label": "PCSX2"}
|
||||
scanned = _state_for(rom, admin_user, "Game.06.p2s", "pcsx2")
|
||||
scanned_shot = _screenshot_for(rom, "Game.06")
|
||||
with (
|
||||
patch(
|
||||
"handler.streaming.states.fetch_state_file",
|
||||
return_value=("Game.06.p2s", _p2s_bytes(_PNG)),
|
||||
),
|
||||
patch(
|
||||
"handler.streaming.states.fetch_state_screenshot", return_value=None
|
||||
) as fetch_shot,
|
||||
patch("handler.asset_store.fs_asset_handler.write_file", new=AsyncMock()) as wf,
|
||||
patch("handler.asset_store.scan_state", new=AsyncMock(return_value=scanned)),
|
||||
patch(
|
||||
"handler.asset_store.scan_screenshot",
|
||||
new=AsyncMock(return_value=scanned_shot),
|
||||
),
|
||||
):
|
||||
ok = asyncio.run(
|
||||
states.pull_state_to_library(admin_user.id, rom.id, _resolved(container), 6)
|
||||
)
|
||||
assert r.status_code == 400
|
||||
assert ok is True
|
||||
fetch_shot.assert_called_once()
|
||||
assert _written_screenshot(wf) == _PNG
|
||||
|
||||
|
||||
def test_pull_state_asks_the_broker_for_a_screenshot_once(rom: Rom, admin_user: User):
|
||||
"""No frame from either source: the state still syncs, on one broker call."""
|
||||
container = {**_container_for(rom), "label": "RetroArch"}
|
||||
scanned = _state_for(rom, admin_user, "Game.state5", "retroarch")
|
||||
with (
|
||||
patch(
|
||||
"handler.streaming.states.fetch_state_file",
|
||||
return_value=("Game.state5", b"state-bytes"),
|
||||
),
|
||||
patch(
|
||||
"handler.streaming.states.fetch_state_screenshot", return_value=None
|
||||
) as fetch_shot,
|
||||
patch("handler.asset_store.fs_asset_handler.write_file", new=AsyncMock()),
|
||||
patch("handler.asset_store.scan_state", new=AsyncMock(return_value=scanned)),
|
||||
patch("handler.asset_store.scan_screenshot", new=AsyncMock()) as scan_shot,
|
||||
):
|
||||
ok = asyncio.run(
|
||||
states.pull_state_to_library(admin_user.id, rom.id, _resolved(container), 5)
|
||||
)
|
||||
assert ok is True
|
||||
fetch_shot.assert_called_once()
|
||||
scan_shot.assert_not_awaited()
|
||||
|
||||
|
||||
def test_pull_state_rejects_unsanitizable_filename(rom: Rom, admin_user: User):
|
||||
@@ -2999,6 +3028,16 @@ def test_extract_state_screenshot_not_a_zip_returns_none():
|
||||
assert states.extract_state_screenshot("pcsx2", b"not-a-zip") is None
|
||||
|
||||
|
||||
def test_fetch_state_screenshot_rejects_a_non_png_body(rom: Rom):
|
||||
"""A body that is not a PNG has to read as no frame, or it would shadow the
|
||||
frame a state embeds for itself and leave the state with no thumbnail."""
|
||||
with patch(
|
||||
"handler.streaming.broker.get_binary_safe",
|
||||
return_value=(MagicMock(), b"GIF89a-not-a-png"),
|
||||
):
|
||||
assert states.fetch_state_screenshot(_resolved(_container_for(rom)), 3) is None
|
||||
|
||||
|
||||
def test_state_transfer_limits_default_for_an_unlisted_emulator():
|
||||
assert state_transfer_limits("pcsx2") == DEFAULT_STATE_TRANSFER
|
||||
|
||||
@@ -3079,14 +3118,7 @@ def test_store_state_screenshot_binds_to_state(admin_user: User, rom: Rom):
|
||||
"""A stored state screenshot lands in the screenshots dir under the state's
|
||||
stem, so State.screenshot resolves it as the resume-picker thumbnail."""
|
||||
db_state_handler.add_state(_state_for(rom, admin_user, "Game.03.p2s", "pcsx2"))
|
||||
scanned = Screenshot(
|
||||
file_name="Game.03.png",
|
||||
file_name_no_tags="Game.03",
|
||||
file_name_no_ext="Game.03",
|
||||
file_extension="png",
|
||||
file_path=f"{rom.platform_slug}/screenshots",
|
||||
file_size_bytes=7,
|
||||
)
|
||||
scanned = _screenshot_for(rom, "Game.03")
|
||||
with (
|
||||
patch("handler.asset_store.fs_asset_handler.write_file", new=AsyncMock()) as wf,
|
||||
patch(
|
||||
@@ -3128,14 +3160,7 @@ def test_store_state_screenshot_rejects_non_png(admin_user: User, rom: Rom):
|
||||
def test_store_state_asset_binds_screenshot(admin_user: User, rom: Rom):
|
||||
"""End to end: storing a state with a frame binds it as the thumbnail."""
|
||||
scanned_state = _state_for(rom, admin_user, "Game.03.p2s", "pcsx2")
|
||||
scanned_shot = Screenshot(
|
||||
file_name="Game.03.png",
|
||||
file_name_no_tags="Game.03",
|
||||
file_name_no_ext="Game.03",
|
||||
file_extension="png",
|
||||
file_path=f"{rom.platform_slug}/screenshots",
|
||||
file_size_bytes=7,
|
||||
)
|
||||
scanned_shot = _screenshot_for(rom, "Game.03")
|
||||
with (
|
||||
patch("handler.asset_store.fs_asset_handler.write_file", new=AsyncMock()),
|
||||
patch(
|
||||
|
||||
1
frontend/src/__generated__/index.ts
generated
1
frontend/src/__generated__/index.ts
generated
@@ -224,7 +224,6 @@ export type { SlotSummarySchema } from './models/SlotSummarySchema';
|
||||
export type { SmartCollectionSchema } from './models/SmartCollectionSchema';
|
||||
export type { SoundtrackTrackMetaSchema } from './models/SoundtrackTrackMetaSchema';
|
||||
export type { SSAgeRating } from './models/SSAgeRating';
|
||||
export type { StateFrameResponse } from './models/StateFrameResponse';
|
||||
export type { StateSchema } from './models/StateSchema';
|
||||
export type { StatsReturn } from './models/StatsReturn';
|
||||
export type { SteamPlatforms } from './models/SteamPlatforms';
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
/* generated using openapi-typescript-codegen -- do not edit */
|
||||
/* istanbul ignore file */
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
export type StateFrameResponse = {
|
||||
status: string;
|
||||
platform: string;
|
||||
};
|
||||
|
||||
@@ -174,14 +174,6 @@ async function saveState(platform: string, slot = 1) {
|
||||
return api.post(`/streaming/sessions/${platform}/save-state`, { slot });
|
||||
}
|
||||
|
||||
// The frame the browser grabbed off the stream canvas, held server-side until
|
||||
// the state save that follows claims it as its thumbnail.
|
||||
async function putStateFrame(platform: string, frame: Blob) {
|
||||
return api.post(`/streaming/sessions/${platform}/state-frame`, frame, {
|
||||
headers: { "Content-Type": "image/png" },
|
||||
});
|
||||
}
|
||||
|
||||
async function loadState(platform: string, slot = 1) {
|
||||
return api.post(`/streaming/sessions/${platform}/load-state`, { slot });
|
||||
}
|
||||
@@ -249,7 +241,6 @@ export default {
|
||||
setVolume,
|
||||
setMute,
|
||||
saveState,
|
||||
putStateFrame,
|
||||
loadState,
|
||||
swapDisc,
|
||||
adminListSessions,
|
||||
|
||||
@@ -141,64 +141,6 @@ function sameOriginFrames(win: Window | null, found: Window[] = []): Window[] {
|
||||
return found;
|
||||
}
|
||||
|
||||
// Selkies paints the session into a 2D canvas it creates itself, falling back
|
||||
// to a video element on the WebRTC path. Neither is tainted, so a same-origin
|
||||
// container lets the frame be read straight out of the page. This is the only
|
||||
// capture that cannot stall the emulator: asking it to grab its own framebuffer
|
||||
// is what deadlocks a GPU-rendered core.
|
||||
const STREAM_CANVAS_ID = "videoCanvas";
|
||||
const STREAM_VIDEO_ID = "stream";
|
||||
// Long edge of the captured image. It is a thumbnail, and a full-resolution
|
||||
// PNG of the stream is several megabytes per save.
|
||||
const CAPTURE_MAX_EDGE = 960;
|
||||
|
||||
function streamSurface(): HTMLCanvasElement | HTMLVideoElement | null {
|
||||
// Elements come from another frame's realm, where `instanceof` against this
|
||||
// document's constructors is always false, so match on the tag instead.
|
||||
for (const win of sameOriginFrames(
|
||||
streamFrame.value?.contentWindow ?? null,
|
||||
)) {
|
||||
const el = win.document.getElementById(STREAM_CANVAS_ID);
|
||||
if (el?.tagName === "CANVAS") {
|
||||
const canvas = el as HTMLCanvasElement;
|
||||
if (canvas.width > 0) return canvas;
|
||||
}
|
||||
const videoEl = win.document.getElementById(STREAM_VIDEO_ID);
|
||||
if (videoEl?.tagName === "VIDEO") {
|
||||
const video = videoEl as HTMLVideoElement;
|
||||
if (video.videoWidth > 0) return video;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// PNG because that is what the states API stores and what the backend's
|
||||
// thumbnail guard checks the magic bytes for.
|
||||
async function captureFrame(): Promise<Blob | null> {
|
||||
const surface = streamSurface();
|
||||
if (!surface) return null;
|
||||
const isVideo = surface.tagName === "VIDEO";
|
||||
const video = surface as HTMLVideoElement;
|
||||
const canvas = surface as HTMLCanvasElement;
|
||||
const sw = isVideo ? video.videoWidth : canvas.width;
|
||||
const sh = isVideo ? video.videoHeight : canvas.height;
|
||||
if (!sw || !sh) return null;
|
||||
|
||||
const scale = Math.min(1, CAPTURE_MAX_EDGE / Math.max(sw, sh));
|
||||
const out = document.createElement("canvas");
|
||||
out.width = Math.round(sw * scale);
|
||||
out.height = Math.round(sh * scale);
|
||||
const ctx = out.getContext("2d");
|
||||
if (!ctx) return null;
|
||||
try {
|
||||
ctx.drawImage(surface, 0, 0, out.width, out.height);
|
||||
} catch {
|
||||
// A surface mid-resize has no drawable frame yet.
|
||||
return null;
|
||||
}
|
||||
return new Promise((resolve) => out.toBlob(resolve, "image/png"));
|
||||
}
|
||||
|
||||
// The container's own client applies volume and mute to the gain node in front
|
||||
// of its audio output, and it drops any message whose origin is not its own.
|
||||
// Same origin is what makes that reachable, so the bar can move this viewer's
|
||||
@@ -363,7 +305,6 @@ onBeforeUnmount(() => {
|
||||
// parent drives imperatively is exposed here.
|
||||
defineExpose({
|
||||
focusStream,
|
||||
captureFrame,
|
||||
postToStream,
|
||||
enterFullscreen,
|
||||
leaveFullscreen,
|
||||
|
||||
@@ -900,19 +900,6 @@ async function handleStop(): Promise<void> {
|
||||
backToRom();
|
||||
}
|
||||
|
||||
// The thumbnail for the state about to be written. Best effort: without it the
|
||||
// state falls back to whatever frame the emulator can produce for itself, and
|
||||
// some cores cannot produce one at all without deadlocking.
|
||||
async function pushStreamFrame(): Promise<void> {
|
||||
if (!rom.value) return;
|
||||
try {
|
||||
const frame = await stage.value?.captureFrame();
|
||||
if (frame) await streamingApi.putStateFrame(rom.value.platform_slug, frame);
|
||||
} catch (err) {
|
||||
console.warn("[streaming] Could not capture stream frame:", err);
|
||||
}
|
||||
}
|
||||
|
||||
async function performSaveAndExit(): Promise<void> {
|
||||
if (!rom.value || playerState.value !== "playing") return;
|
||||
// The broker's save+kill runs for seconds with the player still on screen,
|
||||
@@ -929,7 +916,6 @@ async function performSaveAndExit(): Promise<void> {
|
||||
let saved: boolean | undefined;
|
||||
let released = false;
|
||||
try {
|
||||
await pushStreamFrame();
|
||||
const result = await streamingStore.saveAndExit(
|
||||
rom.value.platform_slug,
|
||||
capabilities.value.autosaveSlot,
|
||||
@@ -972,7 +958,6 @@ async function handleSaveState(): Promise<void> {
|
||||
if (isSavingState.value) return;
|
||||
isSavingState.value = true;
|
||||
try {
|
||||
await pushStreamFrame();
|
||||
await streamingApi.saveState(rom.value.platform_slug, streamSlot.value);
|
||||
} catch (err) {
|
||||
console.warn("[streaming] Could not save state:", err);
|
||||
|
||||
Reference in New Issue
Block a user