From 836654c1d4bffd14b2ee18984cba88255f83417b Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Thu, 10 Sep 2026 20:42:34 -0500 Subject: [PATCH 1/9] fix(streaming): prefer PCSX2's embedded screenshot over the browser frame PCSX2 embeds a screenshot in every .p2s savestate, already in hand from the state download with no extra round-trip or framebuffer readback risk. pull_state_to_library() tried the browser-captured frame first regardless, which produced black thumbnails when that capture missed the live canvas. Extract the embedded screenshot first for PCSX2 and fall back to the browser frame only when it's unavailable; behavior for every other emulator is unchanged since extract_state_screenshot() always returns None for them. --- backend/handler/streaming/states.py | 15 +++++--- backend/tests/endpoints/test_streaming.py | 45 +++++++++++++++++++++++ 2 files changed, 54 insertions(+), 6 deletions(-) diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index 2d0ff1a54..e95e2ce44 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -434,13 +434,16 @@ 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) + # PCSX2's embedded frame comes first: it was already downloaded as part + # of the state content above, so using it costs nothing extra and it + # can never be a stale/blank capture off the player's video sink. For + # every other emulator this is always None, so the browser frame is + # preferred next: 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. + screenshot = extract_state_screenshot(emulator, content) if screenshot is None: - screenshot = extract_state_screenshot(emulator, content) + screenshot = await take_state_frame(user_id, rom_id) if screenshot is None: screenshot = await asyncio.to_thread( fetch_state_screenshot, container, slot diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 3e9b3b4d1..3f69f7a3f 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2772,6 +2772,51 @@ def test_pull_state_prefers_browser_frame(rom: Rom, admin_user: User): fetch_shot.assert_not_called() +def test_pull_state_prefers_embedded_pcsx2_screenshot(rom: Rom, admin_user: User): + """PCSX2's own embedded frame beats a browser capture: it's already in + hand from the state download and can't be a stale/blank canvas grab.""" + container = {**_container_for(rom), "label": "PCSX2"} + scanned = _state_for(rom, admin_user, "Game.05.p2s", "pcsx2") + scanned_shot = Screenshot( + file_name="Game.05.p2s.png", + file_name_no_tags="Game.05.p2s", + file_name_no_ext="Game.05.p2s", + file_extension="png", + file_path=f"{rom.platform_slug}/screenshots", + file_size_bytes=len(_PNG), + ) + browser_frame = b"\x89PNG\r\n\x1a\n" + b"browser-frame" + with ( + patch( + "handler.streaming.states.fetch_state_file", + return_value=("Game.05.p2s", _p2s_bytes(_PNG)), + ), + 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 + take_frame.assert_not_called() + fetch_shot.assert_not_called() + 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") From 2b77526a81b5ec49b706beeeaf7120100b2906eb Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Fri, 11 Sep 2026 01:46:58 -0500 Subject: [PATCH 2/9] fix(streaming): prefer RetroArch's own screenshot over the browser frame The browser-captured canvas frame is a lagging, lossy copy of the video stream and can hold a torn or missing keyframe right after a scene change (e.g. pausing), producing a corrupted save-state thumbnail even though the state itself is fine. RetroArch already writes its own thumbnail off the core's real framebuffer at save time, so prefer that for RetroArch and fall back to the browser frame only if it's missing. Other emulators, which write no thumbnail of their own, are unaffected. --- backend/handler/streaming/states.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index e95e2ce44..ac561e45e 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -436,12 +436,24 @@ async def pull_state_to_library( return False # PCSX2's embedded frame comes first: it was already downloaded as part # of the state content above, so using it costs nothing extra and it - # can never be a stale/blank capture off the player's video sink. For - # every other emulator this is always None, so the browser frame is - # preferred next: 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. + # can never be a stale/blank capture off the player's video sink. + # + # RetroArch writes its own thumbnail off the core's real framebuffer + # at the moment of the save, which the browser-captured canvas frame + # cannot match: that canvas is a lagging, lossy copy of the video + # stream, and a save taken right after a scene change (e.g. pausing) + # can catch it holding a torn or missing keyframe. The broker's own + # screenshot is preferred for RetroArch for that reason. + # + # Every other emulator writes no thumbnail of its own, so 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. screenshot = extract_state_screenshot(emulator, content) + if screenshot is None and emulator == "retroarch": + screenshot = await asyncio.to_thread( + fetch_state_screenshot, container, slot + ) if screenshot is None: screenshot = await take_state_frame(user_id, rom_id) if screenshot is None: From 95a71a6539eb8397db069d2fdccd7953a0b53ab4 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 12 Sep 2026 20:33:14 -0400 Subject: [PATCH 3/9] fix(streaming): drain the stashed frame and ask the broker once Apply the code-review pass over the screenshot preference order. take_state_frame() was the only consumer that deletes the Redis key, so once an emulator's own frame won, a stashed browser frame survived its save and could become a later one's thumbnail. Drain it on every pull. For RetroArch the unguarded final fallback re-issued the identical /state-screenshot GET, a second blocking 60s request held while the container reservation is still out. The retroarch literal moves to a module-level _BROKER_FRAME_EMULATORS, next to the other per-emulator tables, and extract_state_screenshot() catches anything the zip read raises so a corrupt embedded PNG costs the thumbnail, not the state. Tests cover the RetroArch broker preference, its fallback to the browser frame, and the single broker request when neither source exists. Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/streaming/states.py | 43 ++++---- backend/tests/endpoints/test_streaming.py | 129 +++++++++++++++++++++- 2 files changed, 146 insertions(+), 26 deletions(-) diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index ac561e45e..9a857770f 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -207,9 +207,10 @@ def extract_state_screenshot(emulator: str, state_content: bytes) -> bytes | Non 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 Exception as exc: + # No screenshot entry, or the state is not a readable zip. Never fatal, + # a corrupt entry (zlib.error, a truncated member) must cost the + # thumbnail only: the state itself still syncs. log.warning("could not extract state screenshot, %s", exc) return None if not data or len(data) > SCREENSHOT_MAX_BYTES: @@ -248,6 +249,13 @@ async def take_state_frame(user_id: int, rom_id: int) -> bytes | None: return None +# Emulators whose broker writes the save's thumbnail off the core's own +# framebuffer as the state is written, so its frame beats the browser capture. +# Every other broker has to read that frame back from the GPU on demand, which +# deadlocks some cores, so there the browser frame goes first. +_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 @@ -434,29 +442,22 @@ async def pull_state_to_library( except ValueError: log.warning("broker returned invalid state filename") return False - # PCSX2's embedded frame comes first: it was already downloaded as part - # of the state content above, so using it costs nothing extra and it - # can never be a stale/blank capture off the player's video sink. - # - # RetroArch writes its own thumbnail off the core's real framebuffer - # at the moment of the save, which the browser-captured canvas frame - # cannot match: that canvas is a lagging, lossy copy of the video - # stream, and a save taken right after a scene change (e.g. pausing) - # can catch it holding a torn or missing keyframe. The broker's own - # screenshot is preferred for RetroArch for that reason. - # - # Every other emulator writes no thumbnail of its own, so 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. + # An embedded frame comes first: it arrived with the state above, so it + # costs no round-trip and can never be a stale capture. The browser + # frame and the broker's own then follow in the order this emulator + # earns, since the loser of the two is still better than no thumbnail. + prefers_broker_frame = emulator in _BROKER_FRAME_EMULATORS screenshot = extract_state_screenshot(emulator, content) - if screenshot is None and emulator == "retroarch": + if screenshot is None and prefers_broker_frame: screenshot = await asyncio.to_thread( fetch_state_screenshot, container, slot ) + # Drained on every pull even when it goes unused: a frame left in the + # stash outlives its save and becomes a later one's wrong thumbnail. + browser_frame = await take_state_frame(user_id, rom_id) if screenshot is None: - screenshot = await take_state_frame(user_id, rom_id) - if screenshot is None: + screenshot = browser_frame + if screenshot is None and not prefers_broker_frame: screenshot = await asyncio.to_thread( fetch_state_screenshot, container, slot ) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 3f69f7a3f..ae9fa49e5 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2785,7 +2785,7 @@ def test_pull_state_prefers_embedded_pcsx2_screenshot(rom: Rom, admin_user: User file_path=f"{rom.platform_slug}/screenshots", file_size_bytes=len(_PNG), ) - browser_frame = b"\x89PNG\r\n\x1a\n" + b"browser-frame" + browser_frame = states.PNG_MAGIC + b"browser-frame" with ( patch( "handler.streaming.states.fetch_state_file", @@ -2796,9 +2796,7 @@ def test_pull_state_prefers_embedded_pcsx2_screenshot(rom: Rom, admin_user: User 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.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", @@ -2809,8 +2807,129 @@ def test_pull_state_prefers_embedded_pcsx2_screenshot(rom: Rom, admin_user: User states.pull_state_to_library(admin_user.id, rom.id, _resolved(container), 5) ) assert ok is True - take_frame.assert_not_called() 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 writes its thumbnail off the core's framebuffer at save time, + which beats the browser's lagging canvas capture.""" + container = {**_container_for(rom), "label": "RetroArch"} + scanned = _state_for(rom, admin_user, "Game.state3", "retroarch") + scanned_shot = Screenshot( + file_name="Game.state3.png", + file_name_no_tags="Game.state3", + file_name_no_ext="Game.state3", + file_extension="png", + file_path=f"{rom.platform_slug}/screenshots", + file_size_bytes=len(_PNG), + ) + 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, + 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), 3) + ) + 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_the_retroarch_broker_for_a_screenshot_once( + rom: Rom, admin_user: User +): + """With neither a broker thumbnail nor a browser frame the state still + syncs, and the broker is not asked the same question twice.""" + 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.take_state_frame", + new=AsyncMock(return_value=None), + ), + 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_falls_back_to_the_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( + file_name="Game.state4.png", + file_name_no_tags="Game.state4", + file_name_no_ext="Game.state4", + file_extension="png", + file_path=f"{rom.platform_slug}/screenshots", + file_size_bytes=len(_PNG), + ) + 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") ) From 1250b1231f4b2dd504a1c7be30e030da4984d358 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 12 Sep 2026 20:42:16 -0400 Subject: [PATCH 4/9] refactor(streaming): collapse the screenshot source selection Apply the simplify pass. The selection ran four interleaved "is None" guards over a preference boolean and called the broker from two identical sites. Draining the stash up front makes the whole order one guard: ask the broker when nothing better is in hand, then fall back to the browser frame. Tests get a _screenshot_for() builder next to _state_for(), replacing seven copies of the same seven-field Screenshot construction. Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/streaming/states.py | 30 +++------ backend/tests/endpoints/test_streaming.py | 75 ++++++----------------- 2 files changed, 29 insertions(+), 76 deletions(-) diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index 9a857770f..b4b0816ad 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -208,9 +208,8 @@ def extract_state_screenshot(emulator: str, state_content: bytes) -> bytes | Non with zf.open(_SCREENSHOT_ZIP_ENTRY) as entry: data = entry.read(SCREENSHOT_MAX_BYTES + 1) except Exception as exc: - # No screenshot entry, or the state is not a readable zip. Never fatal, - # a corrupt entry (zlib.error, a truncated member) must cost the - # thumbnail only: the state itself still syncs. + # Never fatal: a missing entry, an unreadable zip or a corrupt member + # costs the thumbnail only, the state itself still syncs. log.warning("could not extract state screenshot, %s", exc) return None if not data or len(data) > SCREENSHOT_MAX_BYTES: @@ -249,10 +248,8 @@ async def take_state_frame(user_id: int, rom_id: int) -> bytes | None: return None -# Emulators whose broker writes the save's thumbnail off the core's own -# framebuffer as the state is written, so its frame beats the browser capture. -# Every other broker has to read that frame back from the GPU on demand, which -# deadlocks some cores, so there the browser frame goes first. +# 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"}) @@ -442,25 +439,18 @@ async def pull_state_to_library( except ValueError: log.warning("broker returned invalid state filename") return False - # An embedded frame comes first: it arrived with the state above, so it - # costs no round-trip and can never be a stale capture. The browser - # frame and the broker's own then follow in the order this emulator - # earns, since the loser of the two is still better than no thumbnail. - prefers_broker_frame = emulator in _BROKER_FRAME_EMULATORS + # 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) - if screenshot is None and prefers_broker_frame: + 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 ) - # Drained on every pull even when it goes unused: a frame left in the - # stash outlives its save and becomes a later one's wrong thumbnail. - browser_frame = await take_state_frame(user_id, rom_id) if screenshot is None: screenshot = browser_frame - if screenshot is None and not prefers_broker_frame: - screenshot = await asyncio.to_thread( - fetch_state_screenshot, container, slot - ) try: await store_state_asset( user, rom, emulator, filename, content, screenshot, disc_file_id diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index ae9fa49e5..e44715fa5 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2317,6 +2317,18 @@ def _state_for(rom: Rom, user: User, file_name: str, emulator: str) -> State: ) +def _screenshot_for(rom: Rom, state_stem: str) -> Screenshot: + """The thumbnail scan_screenshot() returns for a pulled state.""" + return Screenshot( + file_name=f"{state_stem}.png", + file_name_no_tags=state_stem, + file_name_no_ext=state_stem, + file_extension="png", + file_path=f"{rom.platform_slug}/screenshots", + file_size_bytes=7, + ) + + 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.""" @@ -2700,14 +2712,7 @@ def test_pull_state_falls_back_to_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", @@ -2740,14 +2745,7 @@ 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, - ) + scanned_shot = _screenshot_for(rom, "Game.s04") with ( patch( "handler.streaming.states.fetch_state_file", @@ -2777,14 +2775,7 @@ def test_pull_state_prefers_embedded_pcsx2_screenshot(rom: Rom, admin_user: User hand from the state download and can't be a stale/blank canvas grab.""" container = {**_container_for(rom), "label": "PCSX2"} scanned = _state_for(rom, admin_user, "Game.05.p2s", "pcsx2") - scanned_shot = Screenshot( - file_name="Game.05.p2s.png", - file_name_no_tags="Game.05.p2s", - file_name_no_ext="Game.05.p2s", - file_extension="png", - file_path=f"{rom.platform_slug}/screenshots", - file_size_bytes=len(_PNG), - ) + scanned_shot = _screenshot_for(rom, "Game.05.p2s") browser_frame = states.PNG_MAGIC + b"browser-frame" with ( patch( @@ -2821,14 +2812,7 @@ def test_pull_state_prefers_broker_screenshot_for_retroarch(rom: Rom, admin_user which beats the browser's lagging canvas capture.""" container = {**_container_for(rom), "label": "RetroArch"} scanned = _state_for(rom, admin_user, "Game.state3", "retroarch") - scanned_shot = Screenshot( - file_name="Game.state3.png", - file_name_no_tags="Game.state3", - file_name_no_ext="Game.state3", - file_extension="png", - file_path=f"{rom.platform_slug}/screenshots", - file_size_bytes=len(_PNG), - ) + scanned_shot = _screenshot_for(rom, "Game.state3") browser_frame = states.PNG_MAGIC + b"browser-frame" with ( patch( @@ -2898,14 +2882,7 @@ def test_pull_state_falls_back_to_the_browser_frame_for_retroarch( """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( - file_name="Game.state4.png", - file_name_no_tags="Game.state4", - file_name_no_ext="Game.state4", - file_extension="png", - file_path=f"{rom.platform_slug}/screenshots", - file_size_bytes=len(_PNG), - ) + scanned_shot = _screenshot_for(rom, "Game.state4") with ( patch( "handler.streaming.states.fetch_state_file", @@ -3243,14 +3220,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( @@ -3292,14 +3262,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( From f739fa4877c7a536dba5b6a579d0650df6f157b7 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Sat, 12 Sep 2026 20:45:40 -0400 Subject: [PATCH 5/9] test(streaming): trim the new state-screenshot test docstrings Apply the review-polish pass: one-line docstrings and names without the articles, matching the sibling pull-state tests in the same cluster. Co-Authored-By: Claude Opus 5 (1M context) --- backend/tests/endpoints/test_streaming.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index e44715fa5..6269dee92 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2771,8 +2771,7 @@ def test_pull_state_prefers_browser_frame(rom: Rom, admin_user: User): def test_pull_state_prefers_embedded_pcsx2_screenshot(rom: Rom, admin_user: User): - """PCSX2's own embedded frame beats a browser capture: it's already in - hand from the state download and can't be a stale/blank canvas grab.""" + """PCSX2 embeds its own frame, so the browser capture is never needed.""" container = {**_container_for(rom), "label": "PCSX2"} scanned = _state_for(rom, admin_user, "Game.05.p2s", "pcsx2") scanned_shot = _screenshot_for(rom, "Game.05.p2s") @@ -2808,8 +2807,7 @@ def test_pull_state_prefers_embedded_pcsx2_screenshot(rom: Rom, admin_user: User def test_pull_state_prefers_broker_screenshot_for_retroarch(rom: Rom, admin_user: User): - """RetroArch writes its thumbnail off the core's framebuffer at save time, - which beats the browser's lagging canvas capture.""" + """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") @@ -2845,11 +2843,10 @@ def test_pull_state_prefers_broker_screenshot_for_retroarch(rom: Rom, admin_user assert shot_call.kwargs["file"] == _PNG -def test_pull_state_asks_the_retroarch_broker_for_a_screenshot_once( +def test_pull_state_asks_retroarch_broker_for_screenshot_once( rom: Rom, admin_user: User ): - """With neither a broker thumbnail nor a browser frame the state still - syncs, and the broker is not asked the same question twice.""" + """Neither source has a frame: the state still syncs, on one broker call.""" container = {**_container_for(rom), "label": "RetroArch"} scanned = _state_for(rom, admin_user, "Game.state5", "retroarch") with ( @@ -2876,7 +2873,7 @@ def test_pull_state_asks_the_retroarch_broker_for_a_screenshot_once( scan_shot.assert_not_awaited() -def test_pull_state_falls_back_to_the_browser_frame_for_retroarch( +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.""" From a9aef8a8e9d4c7110b8780d91da045661fc393bb Mon Sep 17 00:00:00 2001 From: Zach Clendenen Date: Sun, 13 Sep 2026 21:33:09 -0500 Subject: [PATCH 6/9] 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. --- backend/endpoints/responses/streaming.py | 5 - backend/endpoints/streaming.py | 46 ----- backend/handler/streaming/states.py | 64 +----- backend/tests/endpoints/test_streaming.py | 192 ++++-------------- frontend/src/__generated__/index.ts | 1 - .../models/StateFrameResponse.ts | 9 - frontend/src/services/api/streaming.ts | 9 - .../src/v2/components/Player/StreamStage.vue | 59 ------ frontend/src/v2/views/Player/Stream.vue | 15 -- 9 files changed, 49 insertions(+), 351 deletions(-) delete mode 100644 frontend/src/__generated__/models/StateFrameResponse.ts diff --git a/backend/endpoints/responses/streaming.py b/backend/endpoints/responses/streaming.py index 7be63774d..788440612 100644 --- a/backend/endpoints/responses/streaming.py +++ b/backend/endpoints/responses/streaming.py @@ -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.""" diff --git a/backend/endpoints/streaming.py b/backend/endpoints/streaming.py index 9b3765ef1..d57d9115e 100644 --- a/backend/endpoints/streaming.py +++ b/backend/endpoints/streaming.py @@ -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] ) diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index b4b0816ad..af9f2246a 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -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 diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 6269dee92..081838607 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -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 ( diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 7e30397da..880aa7b54 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -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'; diff --git a/frontend/src/__generated__/models/StateFrameResponse.ts b/frontend/src/__generated__/models/StateFrameResponse.ts deleted file mode 100644 index 90da109fa..000000000 --- a/frontend/src/__generated__/models/StateFrameResponse.ts +++ /dev/null @@ -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; -}; - diff --git a/frontend/src/services/api/streaming.ts b/frontend/src/services/api/streaming.ts index d16a43f75..d44f8c00d 100644 --- a/frontend/src/services/api/streaming.ts +++ b/frontend/src/services/api/streaming.ts @@ -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, diff --git a/frontend/src/v2/components/Player/StreamStage.vue b/frontend/src/v2/components/Player/StreamStage.vue index 562422453..f7dc175a2 100644 --- a/frontend/src/v2/components/Player/StreamStage.vue +++ b/frontend/src/v2/components/Player/StreamStage.vue @@ -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 { - 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, diff --git a/frontend/src/v2/views/Player/Stream.vue b/frontend/src/v2/views/Player/Stream.vue index 50e89fa63..0d9545402 100644 --- a/frontend/src/v2/views/Player/Stream.vue +++ b/frontend/src/v2/views/Player/Stream.vue @@ -900,19 +900,6 @@ async function handleStop(): Promise { 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 { - 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 { 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 { 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 { 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); From 63129edb30fc9b9bba10f0c7a81b238ffe6e6a9c Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 15 Sep 2026 07:30:06 -0400 Subject: [PATCH 7/9] fix(streaming): reject a non-PNG broker frame and inflate off the loop The broker's screenshot now shadows the frame PCSX2 embeds in its own state, so a 200 that is not a PNG has to read as no frame rather than as an unusable one, or the state lands with no thumbnail at all. Extraction moves onto a thread alongside the fetch it falls back from, since the body it inflates runs to hundreds of megabytes. From the pr-ready code-review pass. Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/streaming/states.py | 22 +++++++++-- backend/tests/endpoints/test_streaming.py | 47 ++++++++++++++++------- 2 files changed, 52 insertions(+), 17 deletions(-) diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index af9f2246a..db75fb362 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -12,6 +12,9 @@ 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 @@ -196,8 +199,8 @@ PNG_MAGIC = b"\x89PNG\r\n\x1a\n" 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, + and it is reached only when /state-screenshot served nothing.""" if emulator != "pcsx2": return None try: @@ -225,7 +228,14 @@ def fetch_state_screenshot(container: ResolvedContainer, slot: int) -> bytes | N max_bytes=SCREENSHOT_MAX_BYTES, timeout=broker.TRANSFER_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 anything that + # is not a PNG has to read as no frame rather than as an unusable one. + if not result[1].startswith(PNG_MAGIC): + log.warning("broker state screenshot for slot %d is not a PNG", slot) + return None + return result[1] async def store_state_screenshot( @@ -404,7 +414,11 @@ async def pull_state_to_library( # 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 = extract_state_screenshot(emulator, content) + # Off the loop as well: the state body it inflates from runs to + # hundreds of megabytes. + screenshot = await asyncio.to_thread( + extract_state_screenshot, emulator, content + ) try: await store_state_asset( user, rom, emulator, filename, content, screenshot, disc_file_id diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index 081838607..f69c96223 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2317,18 +2317,27 @@ def _state_for(rom: Rom, user: User, file_name: str, emulator: str) -> State: ) -def _screenshot_for(rom: Rom, state_stem: str) -> Screenshot: - """The thumbnail scan_screenshot() returns for a pulled 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"{state_stem}.png", - file_name_no_tags=state_stem, - file_name_no_ext=state_stem, + 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.""" @@ -2768,10 +2777,7 @@ def test_pull_state_prefers_broker_screenshot_over_embedded(rom: Rom, admin_user ) 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 + assert _written_screenshot(wf) == _PNG def test_pull_state_falls_back_to_embedded_screenshot(rom: Rom, admin_user: User): @@ -2799,10 +2805,7 @@ def test_pull_state_falls_back_to_embedded_screenshot(rom: Rom, admin_user: User ) 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 + assert _written_screenshot(wf) == _PNG def test_pull_state_asks_the_broker_for_a_screenshot_once(rom: Rom, admin_user: User): @@ -3025,6 +3028,24 @@ 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_returns_the_broker_png(rom: Rom): + with patch( + "handler.streaming.broker.get_binary_safe", + return_value=(MagicMock(), _PNG), + ): + assert states.fetch_state_screenshot(_resolved(_container_for(rom)), 3) == _PNG + + +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 From ef9983fc02c0616d8c385c578754d7629d9cd0af Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 15 Sep 2026 07:37:33 -0400 Subject: [PATCH 8/9] refactor(streaming): one home for the PNG check, one deadline for the frame The magic-byte test moves behind `_is_png`, so the two places that need it (the broker body, where the answer decides whether the embedded frame is tried, and the filesystem sink) read as one rule instead of two. Narrowing the extract catch back to the failures a savestate archive can raise keeps a programming error loud rather than logging it as a missing thumbnail. The frame fetch gets its own 10s deadline: it runs while the claim is still held and the player waits on the exit screen, and a thumbnail does not need the archive-transfer budget. From the pr-ready simplify pass. Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/streaming/broker.py | 4 ++++ backend/handler/streaming/states.py | 27 +++++++++++++---------- backend/tests/endpoints/test_streaming.py | 12 ++-------- 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/backend/handler/streaming/broker.py b/backend/handler/streaming/broker.py index ffecaefa4..40da4357e 100644 --- a/backend/handler/streaming/broker.py +++ b/backend/handler/streaming/broker.py @@ -38,6 +38,10 @@ TRANSFER_TIMEOUT = 60 SWAP_DISC_TIMEOUT = 120 CARD_HYDRATE_TIMEOUT = 120 CARD_TEARDOWN_TIMEOUT = 30 +# A state thumbnail, fetched while the claim is still held and the player waits +# on the exit screen. It is optional, so it gets a deadline of its own rather +# than 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 diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index db75fb362..b48599d89 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -22,6 +22,7 @@ import io import os import re import zipfile +import zlib from datetime import datetime, timezone from urllib.parse import quote @@ -197,6 +198,10 @@ 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, @@ -207,9 +212,8 @@ def extract_state_screenshot(emulator: str, state_content: bytes) -> bytes | Non 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 Exception as exc: - # Never fatal: a missing entry, an unreadable zip or a corrupt member - # costs the thumbnail only, the state itself still syncs. + 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: @@ -226,13 +230,13 @@ def fetch_state_screenshot(container: ResolvedContainer, slot: int) -> bytes | N 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, ) if result is None: return None - # This source shadows the frame a state embeds for itself, so anything that - # is not a PNG has to read as no frame rather than as an unusable one. - if not result[1].startswith(PNG_MAGIC): + # 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] @@ -247,9 +251,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 @@ -414,8 +418,7 @@ async def pull_state_to_library( # 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: the state body it inflates from runs to - # hundreds of megabytes. + # Off the loop as well: reading the zip copies the whole state body. screenshot = await asyncio.to_thread( extract_state_screenshot, emulator, content ) diff --git a/backend/tests/endpoints/test_streaming.py b/backend/tests/endpoints/test_streaming.py index f69c96223..518cc47f0 100644 --- a/backend/tests/endpoints/test_streaming.py +++ b/backend/tests/endpoints/test_streaming.py @@ -2755,7 +2755,7 @@ def test_pull_state_prefers_broker_screenshot_over_embedded(rom: Rom, admin_user 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") + scanned_shot = _screenshot_for(rom, "Game.05") embedded = states.PNG_MAGIC + b"embedded-frame" with ( patch( @@ -2784,7 +2784,7 @@ 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") + scanned_shot = _screenshot_for(rom, "Game.06") with ( patch( "handler.streaming.states.fetch_state_file", @@ -3028,14 +3028,6 @@ 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_returns_the_broker_png(rom: Rom): - with patch( - "handler.streaming.broker.get_binary_safe", - return_value=(MagicMock(), _PNG), - ): - assert states.fetch_state_screenshot(_resolved(_container_for(rom)), 3) == _PNG - - 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.""" From 62b6a7596bc489bddcd1f5771abde970e6012c06 Mon Sep 17 00:00:00 2001 From: Georges-Antoine Assi Date: Tue, 15 Sep 2026 07:41:22 -0400 Subject: [PATCH 9/9] docs(streaming): trim the state-screenshot comments Co-Authored-By: Claude Opus 5 (1M context) --- backend/handler/streaming/broker.py | 5 ++--- backend/handler/streaming/states.py | 11 ++++------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/backend/handler/streaming/broker.py b/backend/handler/streaming/broker.py index 40da4357e..cd76ee399 100644 --- a/backend/handler/streaming/broker.py +++ b/backend/handler/streaming/broker.py @@ -38,9 +38,8 @@ TRANSFER_TIMEOUT = 60 SWAP_DISC_TIMEOUT = 120 CARD_HYDRATE_TIMEOUT = 120 CARD_TEARDOWN_TIMEOUT = 30 -# A state thumbnail, fetched while the claim is still held and the player waits -# on the exit screen. It is optional, so it gets a deadline of its own rather -# than the archive budget. +# 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 diff --git a/backend/handler/streaming/states.py b/backend/handler/streaming/states.py index b48599d89..558e885b5 100644 --- a/backend/handler/streaming/states.py +++ b/backend/handler/streaming/states.py @@ -191,8 +191,7 @@ 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), which -# is the fallback for a container that captured no frame of its own. +# under this entry name (pcsx2/SaveState.cpp: EntryFilename_Screenshot). _SCREENSHOT_ZIP_ENTRY = "Screenshot.png" SCREENSHOT_MAX_BYTES = 16 * 1024 * 1024 PNG_MAGIC = b"\x89PNG\r\n\x1a\n" @@ -204,8 +203,7 @@ def _is_png(data: bytes | None) -> bool: 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, - and it is reached only when /state-screenshot served nothing.""" + format carries no embedded screenshot. Only PCSX2 (.p2s zip) embeds one.""" if emulator != "pcsx2": return None try: @@ -222,9 +220,8 @@ def extract_state_screenshot(emulator: str, state_content: bytes) -> bytes | Non def fetch_state_screenshot(container: ResolvedContainer, slot: int) -> bytes | None: - """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.""" + """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}"),