fix(streaming): take state thumbnails from the broker's frame

The browser capture read #videoCanvas by id, but the default path routes
frames through a MediaStreamTrackGenerator into a hidden #videoStream, so
drawImage returned a transparent bitmap. That still carries PNG magic, so
the backend accepted it and filed a blank thumbnail against a good state.

pull_state_to_library now asks the broker for the container's own capture
first, which is the same route for every emulator, and falls back to an
embedded frame (PCSX2) only when the broker answers 404. The browser
capture, its Redis stash, and the /state-frame endpoint are gone.
This commit is contained in:
Zach Clendenen
2026-09-13 21:33:09 -05:00
parent f739fa4877
commit a9aef8a8e9
9 changed files with 49 additions and 351 deletions

View File

@@ -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."""

View File

@@ -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]
)

View File

@@ -15,7 +15,6 @@ Broker file API (secret-protected, stdlib on the broker side):
"""
import asyncio
import base64
import io
import os
import re
@@ -34,7 +33,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
@@ -189,9 +187,8 @@ 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.
# under this entry name (pcsx2/SaveState.cpp: EntryFilename_Screenshot), which
# is the fallback for a container that captured no frame of its own.
_SCREENSHOT_ZIP_ENTRY = "Screenshot.png"
SCREENSHOT_MAX_BYTES = 16 * 1024 * 1024
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
@@ -217,46 +214,10 @@ 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
# Emulators whose broker writes the thumbnail as the state is saved, rather
# than reading the framebuffer back on demand, which deadlocks GPU cores.
_BROKER_FRAME_EMULATORS = frozenset({"retroarch"})
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, taken as the state was saved. A 404 means this state has no frame,
so it is not logged."""
result = broker.get_binary_safe(
container,
container.protocol.transfer_route(f"/state-screenshot?slot={slot}"),
@@ -439,18 +400,11 @@ async def pull_state_to_library(
except ValueError:
log.warning("broker returned invalid state filename")
return False
# An embedded frame arrived with the state, so it wins. The stash is
# drained either way: a leftover frame becomes a later save's thumbnail.
screenshot = extract_state_screenshot(emulator, content)
browser_frame = await take_state_frame(user_id, rom_id)
if screenshot is None and (
browser_frame is None or emulator in _BROKER_FRAME_EMULATORS
):
screenshot = await asyncio.to_thread(
fetch_state_screenshot, container, slot
)
# 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:
screenshot = browser_frame
screenshot = extract_state_screenshot(emulator, content)
try:
await store_state_asset(
user, rom, emulator, filename, content, screenshot, disc_file_id

View File

@@ -2708,7 +2708,7 @@ 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")
@@ -2741,86 +2741,18 @@ 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_for(rom, "Game.s04")
with (
patch(
"handler.streaming.states.fetch_state_file",
return_value=("Game.s04", b"state-bytes"),
),
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()),
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), 4)
)
assert ok is True
fetch_shot.assert_not_called()
def test_pull_state_prefers_embedded_pcsx2_screenshot(rom: Rom, admin_user: User):
"""PCSX2 embeds its own frame, so the browser capture is never needed."""
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.p2s")
browser_frame = states.PNG_MAGIC + b"browser-frame"
embedded = states.PNG_MAGIC + b"embedded-frame"
with (
patch(
"handler.streaming.states.fetch_state_file",
return_value=("Game.05.p2s", _p2s_bytes(_PNG)),
return_value=("Game.05.p2s", _p2s_bytes(embedded)),
),
patch(
"handler.streaming.states.take_state_frame",
new=AsyncMock(return_value=browser_frame),
) as take_frame,
patch("handler.streaming.states.fetch_state_screenshot") 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), 5)
)
assert ok is True
fetch_shot.assert_not_called()
# Still drained, so it cannot become a later save's thumbnail.
take_frame.assert_awaited_once()
shot_call = next(
c for c in wf.await_args_list if c.kwargs["filename"].endswith(".png")
)
assert shot_call.kwargs["file"] == _PNG
def test_pull_state_prefers_broker_screenshot_for_retroarch(rom: Rom, admin_user: User):
"""RetroArch's broker writes the frame at save time, so it beats the canvas."""
container = {**_container_for(rom), "label": "RetroArch"}
scanned = _state_for(rom, admin_user, "Game.state3", "retroarch")
scanned_shot = _screenshot_for(rom, "Game.state3")
browser_frame = states.PNG_MAGIC + b"browser-frame"
with (
patch(
"handler.streaming.states.fetch_state_file",
return_value=("Game.state3", b"state-bytes"),
),
patch(
"handler.streaming.states.take_state_frame",
new=AsyncMock(return_value=browser_frame),
) as take_frame,
patch(
"handler.streaming.states.fetch_state_screenshot", return_value=_PNG
) as fetch_shot,
@@ -2832,21 +2764,49 @@ def test_pull_state_prefers_broker_screenshot_for_retroarch(rom: Rom, admin_user
),
):
ok = asyncio.run(
states.pull_state_to_library(admin_user.id, rom.id, _resolved(container), 3)
states.pull_state_to_library(admin_user.id, rom.id, _resolved(container), 5)
)
assert ok is True
fetch_shot.assert_called_once()
take_frame.assert_awaited_once()
shot_call = next(
c for c in wf.await_args_list if c.kwargs["filename"].endswith(".png")
)
assert shot_call.kwargs["file"] == _PNG
def test_pull_state_asks_retroarch_broker_for_screenshot_once(
rom: Rom, admin_user: User
):
"""Neither source has a frame: the state still syncs, on one broker call."""
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.p2s")
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 ok is True
fetch_shot.assert_called_once()
shot_call = next(
c for c in wf.await_args_list if c.kwargs["filename"].endswith(".png")
)
assert shot_call.kwargs["file"] == _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 (
@@ -2854,10 +2814,6 @@ def test_pull_state_asks_retroarch_broker_for_screenshot_once(
"handler.streaming.states.fetch_state_file",
return_value=("Game.state5", b"state-bytes"),
),
patch(
"handler.streaming.states.take_state_frame",
new=AsyncMock(return_value=None),
),
patch(
"handler.streaming.states.fetch_state_screenshot", return_value=None
) as fetch_shot,
@@ -2873,74 +2829,6 @@ def test_pull_state_asks_retroarch_broker_for_screenshot_once(
scan_shot.assert_not_awaited()
def test_pull_state_falls_back_to_browser_frame_for_retroarch(
rom: Rom, admin_user: User
):
"""A broker with no thumbnail for the save leaves the browser frame."""
container = {**_container_for(rom), "label": "RetroArch"}
scanned = _state_for(rom, admin_user, "Game.state4", "retroarch")
scanned_shot = _screenshot_for(rom, "Game.state4")
with (
patch(
"handler.streaming.states.fetch_state_file",
return_value=("Game.state4", b"state-bytes"),
),
patch(
"handler.streaming.states.take_state_frame",
new=AsyncMock(return_value=_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), 4)
)
assert ok is True
fetch_shot.assert_called_once()
shot_call = next(
c for c in wf.await_args_list if c.kwargs["filename"].endswith(".png")
)
assert shot_call.kwargs["file"] == _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"},
)
assert r.status_code == 400
def test_pull_state_rejects_unsanitizable_filename(rom: Rom, admin_user: User):
"""A broker filename that sanitizes to nothing must be dropped, not stored."""
with (

View File

@@ -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';

View File

@@ -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;
};

View File

@@ -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,

View File

@@ -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,

View File

@@ -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);