How it works · write-up
Browser (WASM) build performance
Updated 2026-10-07. Covers the Emscripten build only: how to measure a slow browser session, what the 2026-09-20 investigation and the 2026-10-07 profile of hi-res/high-fps play found, which fixes landed, and what still costs time. For the Python autopilot's own profiling see PROFILING.MD; for how the browser loop is structured (VBL slices instead of Asyncify) see remove-asyncify.md.
Symptom that started this
On a phone (Samsung Galaxy S23, Android 16, Chrome 152, battery saver on) the game ran at 32-35 emulated VBL/s instead of 50, so music and gameplay were both slow, and the in-game options menu animated at ~18 fps even though it draws almost nothing. Three hypotheses were on the table: a debug rather than release build, wrong host/browser timing, and unnecessary work. Only the third one was real -- the numbers below are why.
Measuring: the PERF line
--xenon-perf-stats on (URL: ?perf=1) prints one line per second into the
browser console and a pinned overlay at the bottom of the page that follows the
game tile into fullscreen
(Module.hatariPerfReport in src/emscripten_shell.html). Implementation:
src/xenonPerf.c, called from Main_WasmRunSlice (src/sdl/main_sdl.c);
the JS-side counters live in Module.hatariPerf (web/src/bridge.ts).
PERF @vbl 14817 (+1152): 60.0 VBL/s (11.3 ms/VBL) | slice avg 11.3 max 15.1 ms x61
(ingest avg 0.06 ms x61) | gap avg 0.3 max 3.2 ms, rearm 0 | raf avg 0.22 ms x61
| busy 69% | audio swallow 0 underruns 3
| Field | Meaning |
|---|---|
@vbl N (+M) |
Hatari's VBL counter, and VBLs since the first report (i.e. since the restored --memstate). Per-VBL cost depends on what the game is doing, so compare runs at similar +M, not at similar wall time. |
VBL/s |
Emulated VBLs completed per wall second. 60 = real time: the emulated ST runs at 60 Hz throughout, intro included (the bundled TOS 1.04 is the US version). (paused) / (benchmark) mark the mode. |
ms/VBL |
Main-thread time inside the emulation slice per emulated VBL. This is the throughput number -- unlike VBL/s it does not move with browser scheduling. Budget: 16.7 ms at the emulated ST's 60 Hz (the bundled TOS 1.04 is the US version). |
slice avg/max xN |
Wall time of each Main_WasmRunSlice callback (emulation + ScreenTraceList_UpdateWindows + the synchronous JS ingest it triggers) and how many ran. |
ingest avg xN |
Time inside the onXxxFrame calls in bridge.ts -- heap copies and texture uploads. Already included in slice; shown separately to split C emulation from JS/GPU upload work. |
gap avg/max |
How late each callback fired relative to its setTimeout due time. Large values mean the main thread was busy with something else (rAF work, ingest) or the browser throttled timers. |
rearm |
Callbacks that arrived before Timing_GetHostDelayMs() reached zero and had to be re-armed. |
raf avg xN |
Time per requestAnimationFrame tick in bridge.ts (all views' renderFrame()), and ticks per second. Reads 0 in embedders that do not fire rAF for hidden panes. |
busy |
(slice + raf) / wall -- how close the single browser thread is to saturation. |
audio swallow / underruns |
pulse_swallowing_count (audio-sync pacing correction) and audio callbacks that ran short of generated samples in the last second. |
Benchmark mode
?bench=1 adds --benchmark: Timing_WaitOnVbl never waits, and
Main_WasmRunSlice runs VBL slices back-to-back in ~40 ms bursts before
yielding, so the setTimeout floor (4 ms in Chrome) cannot cap the result. The
ms/VBL figure then is raw emulation cost. The game plays unattended, so it
drifts through phases; sample 30-40 s and compare medians at similar +M.
A/B switches (URL parameters on /play/)
All of these are handled in src/emscripten_shell.html and map to Hatari
options parsed in src/options.c. None are player-facing.
| Parameter | Option | Effect |
|---|---|---|
perf=1 |
--xenon-perf-stats on |
PERF line + overlay |
diagnostics=1 |
--xenon-diagnostics on |
the per-frame sprite-stream and rendering diagnostics in the console (src/includes/wasmDiagnostics.h); off by default |
bench=1 |
--benchmark (+ perf) |
unthrottled throughput, see above |
nodebugviews=1 |
--xenon-debug-views off |
do not create the four developer views (VRAM x2, masked sprites, memory map) at all |
nomemtrace=1 |
--xenon-mem-trace off |
never record the per-access rings/maps (browser default is auto, see below) |
noaudio=1 |
--sound off |
no sound generation and no audio-sync pacing |
noauthentic=1 |
--disable-video on |
never convert/blit the authentic ST display |
nowaitshortcut=1 |
--xenon-wait-shortcut off |
interpret every iteration of the game's wait for its next update instead of skipping them (see "The game's wait loop" below) |
What the investigation found
Median ms/VBL in benchmark mode, before the fixes. Desktop = Windows PC in
the Claude desktop app's embedded browser pane; phone = Galaxy S23 with
battery saver on.
| Configuration | Desktop | Phone |
|---|---|---|
| baseline | 13.9 | 20.2 |
nomemtrace |
~10.4 | 17.0 |
nodebugviews |
5.2 | 7.7 |
nodebugviews + nomemtrace + noauthentic |
4.3 | 5.3 |
The phone's real-time baseline was 32-35 VBL/s at 21 ms/VBL with the main thread 97% busy, an 8-10 ms scheduling gap and 25-28 audio underruns/s. With all switches on it ran at 60 VBL/s, 11 ms/VBL, <2 ms gap, 68% busy.
So the 68000 emulation plus the sprite-stream reconstruction cost ~5 ms/VBL on the phone; everything above that was work for hidden developer views:
- Per VBL, JS ingest (~9 ms on the phone):
ScreenTraceList_UpdateWindowsbuilt and submitted frames for all five views regardless of visibility. The memory-map view alone copied 1 MB + 3 x 4 MB out of the wasm heap and uploaded four 1024x1024 textures (~13 MB) every VBL (web/src/views/memoryMapView.ts). - Per rAF (5.7 ms x ~50/s on the phone):
bridge.tscalledrenderFrame()on every view, andneedsRenderwas never cleared, so the hidden 1024x1024 memory-map shader (fourtexelFetchper pixel) and the other debug views re-rendered todisplay:nonecanvases on every frame. - Per memory access (~3 ms/VBL): every CPU read/write/fetch pushed into
the read/write/execute access rings and updated each trace's
address/pixel maps (
ScreenTrace_LogRead/LogWrite,src/screentrace.c). - Per VBL, authentic display (~1-2 ms):
Screen_Drawconverted and blitted the ST frame to the hidden#canvas. - Options menu at ~18 fps: not rendering cost (0.5 ms per redraw) but the
paused poll interval,
WASM_PAUSED_POLL_MS = 50insrc/sdl/main_sdl.c.
What was not the cause: the build is compiled -O3 (link at -O1 affects
only binaryen passes), and the browser timer "gap" was a symptom of the
saturated main thread, not of setTimeout clamping -- it fell to <1 ms once
the waste was gone. One real timing wrinkle remains: with battery saver on,
single 10 ms slices cost about twice what the same work costs in sustained
40 ms benchmark bursts (11 vs 5.4 ms/VBL), because the CPU governor keeps
clocks low for bursty work.
Fixes that landed (2026-09-20)
| Area | Change |
|---|---|
src/screentrace.c ScreenTraceList_UpdateWindows |
Developer views are only built/submitted while RenderView_IsVisible (new, src/renderView.c); the sprite stream always updates. A re-shown view picks up on the next VBL or paused poll. |
web/src/bridge.ts, views/*.ts |
The rAF loop skips hidden tiles; needsRender is cleared after each render, so a view renders once per ingested frame. |
src/screentrace.c, src/options.c |
--xenon-mem-trace on|off|auto (ScreenTraceMemTraceMode). Default auto: the rings/maps are recorded only while a developer view is visible, evaluated once per VBL into a single flag the hot path reads. Native also defaults to auto since 2026-10-01; tooling that dumps the rings with every view hidden must explicitly request on. |
src/conv_st.c ConvST_DrawFrame, src/sdl/screen.c |
Browser-only (Screen_IsAuthenticDrawSkipped): skip the authentic display's conversion/blit while hidden, unless frame capture or AVI recording needs the frames; Screen_SetWindowVisible(true) forces a full update. Desktop unchanged (screenshots/paired AVIs of the hidden window are relied upon). Pitfall found the hard way: STRGBPalette[] -- the palette the sprite stream uses for the hit-flash tint, stars and the weapon meter -- is only filled as a side effect of that conversion, so the skip path must still run Convert_PaletteOnly(); without it the flashed ship rendered as a black silhouette and the starfield vanished. |
src/webRenderBackend.c |
Honours RenderViewDesc.startHidden so the tile state matches RenderView_IsVisible from the first frame. |
src/sdl/main_sdl.c |
WASM_PAUSED_POLL_MS 50 -> 16: the options menu animates at display rate. |
Result on the phone with no URL switches: 60 VBL/s (full speed), 10.5 ms/VBL,
gap <1 ms, rAF 0.25 ms, 65% busy, 3-5 audio underruns/s; ?hires=1&highfps=1
is the same. Showing the memory-map view from the developer menu drops the
phone to ~40 VBL/s while it is open (expected -- it is a desktop diagnostic).
What must never be gated
ScreenTrace_LogRead(..., instruction=true) and ScreenTrace_LogWrite are the
entry points for two different things. The instruction-fetch hooks
(DrawCommandStream_On*InstructionFetch, XenonControl_OnInstructionFetch)
and DrawCommandStream_OnMemoryWrite are what capture the sprite stream --
the update procedures the reconstruction is built from. They run
unconditionally on every access, in every mode. Only what follows them
(AccessLog_Push into g_memoryAccessLog, AddressMap_LogTouch,
PixelMap_TouchAt) is subject to --xenon-mem-trace. The consumers of that
data are: the four developer views, their paused-replay animation
(src/animationState.c), the memory-map click inspector
(src/xenonRender.c), the F-key / XENON_MSG ring dumps, and one debugger
command. Nothing on the play path.
Hi-res/high-fps profile (2026-10-07)
Profiling the browser build
The PERF line splits a slice from rendering; a CPU profile says what inside them costs the time.
xenon_tools/wasm_cpu_profile.mjs drives a browser over the DevTools protocol: start Edge (or
Chrome) with its own profile folder and --remote-debugging-port=9333 (headless works:
--headless=new --enable-gpu --use-angle=d3d11 gives it the real GPU, and
--autoplay-policy=no-user-gesture-required lets the game start without a click), serve the
site, then
node xenon_tools/wasm_cpu_profile.mjs --port 9333 --autopilot --out run \
--url "http://localhost:8748/play/?hires=1&highfps=1&skipintro=1&perf=1"
python xenon_tools/analyze_wasm_profile.py run.cpuprofile out/build/wasm-release/src/hatari.html.symbols
--autopilot lets the game's own C autopilot play, so the profile covers real gameplay; its
xap_* functions show what it costs on top. The delivered hatari.wasm has no name section;
analyze_wasm_profile.py names its functions from the build's symbol map, so use the map of the
build that was profiled. For A/B comparisons add bench=1 to the URL and compare the .json
files with xenon_tools/compare_wasm_bench.py, which averages each run over the same window of
emulated VBLs (gameplay runs drift in phase; the autopilot from the same snapshot keeps them
comparable). Single real-time runs differ by more than some of the effects measured here.
Caveat for these numbers: the PC was used over Remote Desktop, whose 32 Hz display also capped the headless browser's rAF at 32 per second, so frame pacing at 60 Hz was not measured; per-VBL and per-frame costs are unaffected. They are from a Windows PC with an RTX 4090; the phone was not connected.
What it found
Hi-res and high fps cost almost nothing on the CPU: a rendered frame took 0.15-0.25 ms of
JavaScript, interpolation was 0.3% of the busy time, and classic mode was no cheaper. Nearly all
the main thread's time was emulation (Main_WasmRunSlice, 95% of the busy time), about 3 ms per
VBL in real time (19% busy). Two parts of that were waste:
- The frame lookup scanned the whole draw ring (21% of the busy time).
DrawCommandStream_ForEachInFrametested all 65,536 slots of the command ring to find the few hundred entries of one frame, every VBL, for the sprite build (and again for the autopilot and the recorder). A frame's entries form one contiguous run, so it now walks back from the newest entry to that run (commit a68406f4). Benchmark, hi-res/high-fps with the autopilot, same 13,900 VBLs: 2.72 -> 2.26 ms/VBL. - The game's wait loop was 87% of all executed instructions. See below. Benchmark, same 6,500 VBLs: 2.46 -> 0.81 ms/VBL; in real time 1.2-1.4 ms/VBL, and the main thread was busy 1.39 s of every 20 instead of 3.77 s before both fixes.
Instruction-fetch histogram used to find (2): about 74,000 instruction words per VBL, 86.6% of
them the seven words at $28E2-$28EE, about 9,000 loop iterations per VBL. Each word fetch also
calls the 18 capture hooks in ScreenTrace_LogRead, which is why those hooks were another
20-40% of the busy time before the fix.
The game's wait loop
Xenon 2 runs its game logic once every four VBLs at 60 Hz (every three at 50 Hz, see
XENON2.MD §8.1) and waits for the next update in ST_WaitAndSwapScreens ($28DC):
$28E2 move.w $041c,d0 the VBL counter that the game's VBL interrupt advances
$28E6 sub.w $0404,d0 its value at the last update
$28EA cmp.w $0410,d0 VBLs per update (4 at 60 Hz)
$28EE bcs.s $28E2
It only reads RAM, and only an interrupt changes what it reads, so every iteration leaves the
machine exactly as the previous one did, a fixed number of cycles later.
M68000_XenonWaitShortcut (src/m68000.c, called by m68k_run_2_000 at $28EE) therefore adds
the cycles of as many whole iterations as finish before the next scheduled event when the branch
is about to loop again: registers, flags and the instruction-pairing state are those of an
iteration's end already, no event runs in between, and the next one fires at the same cycle.
The cycles of an iteration are measured (two consecutive arrivals the same number of cycles
apart), not taken from tables. It checks the seven code words first, and stands aside while
anything would see the skipped instructions: the debugger and the CPU profiler (both keep
regs.spcflags set), CPU tracing, the developer views' memory trace. --xenon-wait-shortcut off
(nowaitshortcut=1 in the browser) turns it off. It applies to the desktop build too.
Proof that it changes nothing: desktop Hatari (Debug), the same snapshot, the same 1,500 game
frames (6,000 VBLs) of pseudo-random input stepped through the control port in fast-forward,
once without and once with the shortcut. At every checkpoint the CPU cycle count was identical to
the cycle, and all of RAM was identical except 20 bytes at $99CB-$99E8, the zoom-text
interstitial's palette backup, which differs just the same between two runs without the shortcut.
The run took 13.2 s instead of 25.7 s.
What is left
After both fixes, in the same real-time autopilot run: the autopilot's
xap_prepare_navigation_grid 30% of the busy time (only while the autopilot plays), the 68000
core 25%, the capture hooks 13% (ScreenTrace_LogRead with its callees), browser overhead and
garbage collection 13%, the sprite build and render bridge the rest.
On the phone
Galaxy S23 (Adreno 740), Android 16, Chrome, battery saver on, on battery, 26 °C at the start;
?hires=1&highfps=1&skipintro=1&perf=1 with the autopilot, both fixes in the build, the wait
shortcut switched off with nowaitshortcut=1 for the comparison. The emulated ST runs at 60 Hz
(the bundled TOS 1.04 is the US version), so full speed is 60 VBL/s.
| Run | Shortcut on | Shortcut off |
|---|---|---|
| Real time, 20 s: VBL/s | 60.0 | 60.0 |
| Real time: ms/VBL (range) | 6.6 (4.9-7.9) | 10.5 (9.2-11.5) |
| Real time: main thread busy | 41% | 64% |
| Real time: audio underruns/s | 0 | 0.4 |
| Benchmark, same VBLs +3,669..+8,558: ms/VBL | 1.85 | 5.71 |
The benchmark gain (3.1x) matches the desktop (3.0x). Real time costs 3.5x the benchmark per VBL because the CPU governor keeps clocks low for short bursts, more so with battery saver (see the 2026-09-20 findings above), so the saving shows mostly as idle time: about a third less main thread work, which is battery.
Profile of the real-time run with the shortcut (15 s): the autopilot's navigation grid 21% of the
busy time, the capture hooks 21% (ScreenTrace_LogRead with its callees, about 1.7 ms/VBL here
against 0.15 on the desktop), the 68000 core 21%, browser overhead 8%. The longest slices,
41-44 ms, were each about 30 ms of xap_prepare_navigation_grid in a single VBL; they are the
only frames that missed the display (20 of 1,179 rAF intervals over 20 ms). They come from the
autopilot, not from the game.
Hidden page: paused (2026-10-07)
When the page is hidden -- the phone's screen locked, the browser or another app in front, another
tab selected -- browsers throttle its timers (Chrome to one callback a second, then a minute) and
may suspend its audio, so the game ran on unseen in slow motion. Now src/sdl/main_sdl.c listens
for visibilitychange (emscripten_set_visibilitychange_callback) and on hiding calls
XenonOptionsMenu_PauseForBackground, which opens the options menu: the menu's usual pause, sound
off. Main_WasmRunSlice then stops rescheduling itself, so a hidden page runs no slices at all,
not even the paused poll; showing the page schedules the next one. The player comes back to the
paused menu and continues from it. A pause someone else owns (a save slot loading) is left to that
owner: no menu, but the slices stop all the same. A page that starts hidden pauses at its first
slice.
Testing on a phone from the PC
Android only; Chrome exposes the DevTools protocol over adb. The same profiler runs against the phone's Chrome: pair and connect (step 1 below), then
adb reverse tcp:8748 tcp:8748
adb forward tcp:9222 localabstract:chrome_devtools_remote
adb shell am start -a android.intent.action.VIEW -d http://localhost:8748/ com.android.chrome
node xenon_tools/wasm_cpu_profile.mjs --port 9222 --tab http://localhost:8748/ --autopilot \
--out phone --url "http://localhost:8748/play/?hires=1&highfps=1&skipintro=1&perf=1"
--tab attaches to the tab opened by am start and leaves the phone's other tabs alone. The
script presses the Start button with a protocol click (a user gesture) and holds a screen wake
lock, so the screen stays on without changing the phone's settings. Wireless adb can drop in
the middle of a run; that also removes the forwards, and the tab may then stop answering the
protocol even though the game keeps running. Reconnect (adb connect <ip>:<port>), restore both
forwards, close that tab (http://127.0.0.1:9222/json/close/<id>) and open a new one.
- Developer options -> Wireless debugging -> "Pair device with pairing code".
adb pair <ip>:<pairing-port> <code>; the connection port is discovered by mDNS (adb mdns services, thenadb devicesshows it). adb lives inE:\platform-toolson the dev PC (Google's platform-tools zip). - Serve the site:
python site/serve.pybinds all interfaces on 8732, so the phone openshttp://<pc-ip>:8732/play/?perf=1. Open it from the PC withadb shell am start -a android.intent.action.VIEW -d "<url>" com.android.chrome. adb forward tcp:9222 localabstract:chrome_devtools_remote, thenhttp://localhost:9222/jsonlists tabs with awebSocketDebuggerUrl. A 20-line Node 22 script (WebSocketis built in) sendsRuntime.evaluateand readsdocument.getElementById('perf_overlay').textContentonce a second; the menu can be driven withModule.ccall('XenonOptionsMenu_OnPointerEvent', null, ['number','number'], [x, y])in logical 320x200 coordinates (options icon at 306,12; rows at y = 41 + 22*i, x = 50 -- first tap selects, second tap toggles).- Keep the screen on for the run (
settings put system screen_off_timeout), and note the battery-saver state (settings get global low_power) with the numbers.
Still open
- Capture-hook dispatch: every fetched instruction word still calls the 18 hooks in
ScreenTrace_LogRead, each returning after one to three address checks; 13% of the busy time after the wait-loop shortcut (about 0.15 ms/VBL on the desktop). Every hook watches fixed addresses (plus the intro's range), so a 32 KB bitmap of watched addresses checked first would remove almost all of it, but each hook's addresses would have to be registered there and a missed one silently breaks capture. Not done; worth it if phones need it. On the S23 the hooks are 21% of the busy time, but the phone runs at full speed with 59% idle. -
Autopilot navigation grid:
xap_prepare_navigation_gridis 30% of the busy time while the autopilot plays (nothing for a human player); rebuilding it only when the terrain changes is the candidate. On the phone a single rebuild can take 30 ms and drops a displayed frame. -
Audio: 3-5 underruns/s remain at full speed. The SDL2 Emscripten audio callback runs on the main thread and the mix window is small;
-sAUDIO_WORKLETor a largerSoundBufferSizeare the candidates. Measure with theunderrunsfield before and after. - Battery saver / clocks: the 2x per-slice penalty above. Running more than one VBL per callback when behind (catch-up) would keep the CPU busier in longer bursts, but changes pacing; only worth it if a phone drops below full speed (60 VBL/s) with the fixes.
- Console volume: the sprite-stream diagnostics emit two lines per real
game frame (~8000 lines/minute). They are now off unless
?diagnostics=1asks for them; see also the "Diagnostic-output overhead" item in remove-asyncify.md. Video_ScreenCounter_ReadBytewas about a third of a 3 ms callback in an early profile (same doc). With the waste gone it is worth a proper bottom-up profile on the phone (chrome://inspect-> Performance; DWARF symbols are already emitted withHATARI_WASM_DEBUG_SYMBOLS=ON).- Link-time
-O3:src/CMakeLists.txtlinks at-O1to keep link time down. Untested; expected single-digit percent, not a priority. - Developer views on phones: opening the memory map costs ~10 ms/VBL of uploads. Fine as a diagnostic; if it should ever be usable on a phone, upload only the rows that changed or downsample.