PS2 games in the browser: static recompilation to WebAssembly with a native runtime
C++
Benchmark from save states, state export and import in the page
Samir Nuria307c776a2a2
diff --git a/host/main.cpp b/host/main.cppindex 9e5e1e4..2fdf426 100644--- a/host/main.cpp+++ b/host/main.cpp@@ -20,7 +20,7 @@ namespace {int usage() {std::fprintf(stderr,- "usage: ps2run <elf> [--arg text]... [--frames n] [--ntsc] [--misses file]\n"+ "usage: ps2run <elf> [--arg text]... [--frames n] [--run n] [--ntsc] [--misses file]\n"" [--disc image.iso] [--memcard card.ps2] [--pal | --ntsc] [--trace-syscalls] [--trace-io] [--trace-threads]\n"" [--trace-iop] [--trace-iop-hle] [--frames-dir dir] [--frame-every n]\n"" [--press frame:button[+button][:frames]]... [--window] [--fullscreen]\n"@@ -35,10 +35,12 @@ int main(int argc, char **argv) {std::vector<std::string> args{argv[1]};[[maybe_unused]] bool window = false, fullscreen = false;std::string load_path;+ std::uint64_t run_frames = 0;for (int i = 2; i < argc; ++i) {const std::string a = argv[i];if (a == "--arg" && i + 1 < argc) args.push_back(argv[++i]);else if (a == "--frames" && i + 1 < argc) ps2::g_options.max_frames = std::strtoull(argv[++i], nullptr, 10);+ else if (a == "--run" && i + 1 < argc) run_frames = std::strtoull(argv[++i], nullptr, 10);else if (a == "--ntsc" || a == "--pal") {ps2::g_options.pal = a == "--pal";ps2::g_options.rate_forced = true;@@ -95,6 +97,7 @@ int main(int argc, char **argv) {}ps2::boot(entry, args);if (!load_path.empty() && !ps2::load_state(load_path)) return 1;+ if (run_frames) ps2::g_options.max_frames = ps2::frame_count() + run_frames;#ifdef PS2_PROFILEconst char *profile = std::getenv("PS2_PROFILE");const char *profile_from = std::getenv("PS2_PROFILE_FROM");diff --git a/runtime/src/system.cpp b/runtime/src/system.cppindex 3a89572..488d7bd 100644--- a/runtime/src/system.cpp+++ b/runtime/src/system.cpp@@ -137,7 +137,7 @@ void apply_presses() {void time_frames() {static const char *spec = std::getenv("PS2_TIME");if (!spec) return;- static const std::uint64_t from = std::strtoull(spec, nullptr, 10);+ static const std::uint64_t from = (spec[0] == '+' ? g_frames : 0) + std::strtoull(spec + (spec[0] == '+'), nullptr, 10);static const std::uint64_t count = std::strchr(spec, ',') ? std::strtoull(std::strchr(spec, ',') + 1, nullptr, 10) : 500;static std::chrono::steady_clock::time_point start;if (g_frames == from) {diff --git a/scripts/bench.sh b/scripts/bench.shnew file mode 100755index 0000000..bfeaf08--- /dev/null+++ b/scripts/bench.sh@@ -0,0 +1,45 @@+#!/bin/bash+# Measures a recompiled game natively from save states: CPU time per frame,+# where that time goes, and the GPU time per frame.+# usage: scripts/bench.sh <game folder under games/> <state>... [--frames n] [--scale n] [--gpu]+set -e+here=$(cd "$(dirname "$0")/.." && pwd)+[ $# -ge 2 ] || { sed -n 2,4p "$0" | sed 's/^# //'; exit 2; }+game=$1+shift+frames=600 scale=1 gpu=0 states=()+while [ $# -gt 0 ]; do+ case "$1" in+ --frames) frames=$2; shift ;;+ --scale) scale=$2; shift ;;+ --gpu) gpu=1 ;;+ *) states+=("$(realpath "$1")") ;;+ esac+ shift+done+dir="$here/games/$game"+run="$here/build/native-$game/ps2run"+boot=$(sed -n 's/^BOOT2 *= *//p' "$dir/disc/SYSTEM.CNF" | tr -d '\r')+elf=$(ls "$dir/patched/"* 2>/dev/null | head -1)+[ -n "$elf" ] || elf="$dir/core.elf"+if [ ! -f "$elf" ]; then+ name=${boot#*\\}+ elf="$dir/disc/${name%;*}"+fi+out=$(mktemp -d)+trap 'rm -rf "$out"' EXIT+cd "$dir"+for state in "${states[@]}"; do+ echo "== $(basename "$state"), $frames frames at ${scale}x"+ log="$out/run.log"+ PS2_SCALE=$scale PS2_TIME="+60,$frames" nice "$run" "$elf" --disc disc.iso --load-state "$state" --run $((frames + 61)) > "$log" 2>&1 || true+ grep -E '^\[time\]' "$log" || { tail -5 "$log"; continue; }+ start=$(sed -n 's/^\[state\] loaded frame //p' "$log")+ PS2_SCALE=$scale PS2_PROFILE="$out/cpu.prof" PS2_PROFILE_FROM=$((start + 60)) nice "$run" "$elf" --disc disc.iso --load-state "$state" --run $((frames + 61)) > /dev/null 2>&1 || true+ python3 -I "$here/scripts/profile_report.py" "$run" "$out/cpu.prof" 15+ if [ "$gpu" = 1 ]; then+ PS2_SCALE=$scale PS2_GPU_PROFILE="$((start + 60)),$((start + 60 + frames)),$out/gpu.prof" nice "$run" "$elf" --disc disc.iso --load-state "$state" --run $((frames + 61)) > /dev/null 2>&1 || true+ python3 -I "$here/scripts/gpu_profile.py" "$out/gpu.prof" 10+ fi+ echo+donediff --git a/scripts/profile_report.py b/scripts/profile_report.pynew file mode 100644index 0000000..fc45520--- /dev/null+++ b/scripts/profile_report.py@@ -0,0 +1,73 @@+import bisect+import collections+import re+import subprocess+import sys+++def symbols(binary):+ out = subprocess.run(['nm', '-C', binary], capture_output=True, text=True, check=True).stdout+ table = []+ for line in out.splitlines():+ parts = line.split(' ', 2)+ if len(parts) == 3 and parts[0] and parts[1] in 'tTwW':+ table.append((int(parts[0], 16), parts[2]))+ table.sort()+ return [a for a, _ in table], [n for _, n in table]+++def group(name):+ module = re.match(r'gen::m_([A-Za-z0-9_]+?)_unit_', name)+ if module:+ return 'game code: module ' + module.group(1)+ if name.startswith('gen::'):+ return 'game code: main program'+ if name.startswith('ps2::vu') or 'vu1_' in name:+ return 'runtime: VU'+ if name.startswith('ps2::gs') or name.startswith('ps2::gif'):+ return 'runtime: GS'+ if name.startswith('ps2::iop'):+ return 'runtime: IOP'+ return 'runtime: other'+++def main():+ if len(sys.argv) < 3:+ print('usage: profile_report.py <ps2run binary> <file written by PS2_PROFILE> [rows]')+ return 1+ rows = int(sys.argv[3]) if len(sys.argv) > 3 else 20+ addrs, names = symbols(sys.argv[1])+ functions = collections.Counter()+ groups = collections.Counter()+ outside = []+ total = 0+ for line in open(sys.argv[2]):+ if line.startswith('#') or line.startswith('^'):+ continue+ if line.startswith('@'):+ outside.append(line.split(None, 2)[1:])+ continue+ address, hits = line.split()+ hits = int(hits)+ i = bisect.bisect_right(addrs, int(address, 16)) - 1+ name = names[i].split('(')[0] if i >= 0 else '?'+ functions[name] += hits+ groups[group(name)] += hits+ total += hits+ for hits, library in outside:+ groups['outside the binary'] += int(hits)+ total += int(hits)+ if not total:+ print('no samples')+ return 1+ print('%d samples' % total)+ for name, hits in groups.most_common():+ print('%6.1f%% %s' % (hits * 100 / total, name))+ print()+ for name, hits in functions.most_common(rows):+ print('%6.1f%% %s' % (hits * 100 / total, name[:110]))+ return 0+++if __name__ == '__main__':+ sys.exit(main())diff --git a/web/shell.html b/web/shell.htmlindex b35d64e..37cdc53 100644--- a/web/shell.html+++ b/web/shell.html@@ -141,6 +141,9 @@</select><button id="save-state" class="host-only" type="button" disabled title="Save the game to this device">Save state</button><button id="load-state" class="host-only" type="button" disabled title="Load the quick save from this device">Load state</button>+ <button id="export-state" class="host-only" type="button" title="Download the quick save as a .state file">Export state</button>+ <button id="import-state" class="host-only" type="button" title="Make a .state file the quick save">Import state</button>+ <input id="import-state-file" type="file" accept=".state" hidden><label id="aa-label" class="host-only" title="Smooth jagged edges, applied immediately"><input id="aa" type="checkbox" disabled> Smooth edges</label><label id="stats-label"><input id="stats-toggle" type="checkbox"> Show stats</label><button id="controls-toggle" type="button" hidden>Hide controls</button>@@ -216,6 +219,7 @@ importInput.addEventListener('change', async () => {storeCard(() => location.reload());});const statsEl = document.getElementById('stats');+const statsLog = new URLSearchParams(location.search).has('statslog');const statsToggle = document.getElementById('stats-toggle');let showStats = !(matchMedia('(pointer: coarse)').matches || /[?&]touch\b/.test(location.search));try { const stored = localStorage.getItem('ps2web-stats'); if (stored) showStats = stored === '1'; } catch (e) {}@@ -433,6 +437,33 @@ async function loadState() {saveStateButton.addEventListener('click', saveState);loadStateButton.addEventListener('click', loadState);+document.getElementById('export-state').addEventListener('click', async () => {+ try {+ const record = await stateSlot();+ if (!record) throw new Error('No quick save yet.');+ const link = document.createElement('a');+ link.href = URL.createObjectURL(new Blob([record.bytes], { type: 'application/octet-stream' }));+ link.download = 'quicksave-' + new Date(record.savedAt).toISOString().replace(/[:.]/g, '-') + '.state';+ link.click();+ setTimeout(() => URL.revokeObjectURL(link.href), 10000);+ } catch (error) {+ note(error.message);+ }+});+const importStateInput = document.getElementById('import-state-file');+document.getElementById('import-state').addEventListener('click', () => importStateInput.click());+importStateInput.addEventListener('change', async () => {+ const file = importStateInput.files[0];+ importStateInput.value = '';+ if (!file) return;+ try {+ const bytes = new Uint8Array(await file.arrayBuffer());+ await stateSlot({ bytes, digest: await stateDigest(bytes), savedAt: Date.now() });+ note('Imported ' + file.name + ' as the quick save. Load state to use it.');+ } catch (error) {+ note(error.name === 'QuotaExceededError' ? 'Not enough device storage.' : error.message);+ }+});// Edge antialiasing is a display option, so it lives outside the save state// and takes effect on the next presented frame.const aaInput = document.getElementById('aa');@@ -1116,6 +1147,7 @@ var Module = {'% gs ' + ((renderIdle - lastRenderIdle) / span * 100).toFixed(0) +'% heap ' + memory + ' MB audio ' + Module.audioQueuedMs().toFixed(0) + ' ms' +(interpreted > lastInterpreted ? ' vu1 interpreted ' + Math.round((interpreted - lastInterpreted) * 1000 / span) + '/s' : '');+ if (statsLog) console.log('[stats] ' + statsEl.textContent.replace(/\s+/g, ' '));lastInterpreted = interpreted;lastEmuIdle = emuIdle;lastRenderIdle = renderIdle;