commit 688f308e9a133b505f7d98d8fa2327d0cb342b77
parent 84f0e312ec4dd3e6dda4e585c236faf57b781473
Author: anon <anon@example.com>
Date: Wed, 11 Nov 2026 03:29:03 +0000
Add standalone phone PNG decoder benchmark
Diffstat:
6 files changed, 391 insertions(+), 0 deletions(-)
diff --git a/tools/client/png_benchmark/README.md b/tools/client/png_benchmark/README.md
@@ -0,0 +1,32 @@
+# Phone PNG benchmark
+
+From the repository root:
+
+```
+python3 tools/client/png_benchmark/prepare.py
+python3 tools/client/png_benchmark/serve.py
+```
+
+Open `https://<server-address>:8444/` on the phone and tap Run benchmark. This is a
+separate HTTPS server using the game's existing certificate. It does not start
+or change the game server. Results go to `local/png-benchmark/results/`.
+The existing local `local/png-decoding/captured.json` corpus is required; it
+contains proprietary PNGs and original decoded pixels and is not committed.
+
+The 180 distinct startup PNGs comprise 137 RGB and 43 RGBA images. The standalone
+libpng wrapper uses the same port and transformations as
+`client/runtime/browser_png.c`, with a memory reader instead of guest stream
+calls. Browser paths include input copying, decoding, pixel readback and packing
+to the same BGR/BGRA layout in WASM. WASM decoding writes its output directly
+into WASM memory. This differs from the earlier desktop benchmark, which copied
+WASM output into JavaScript and did not pack native output back to BGR/BGRA.
+
+All downloads and input staging precede validation and one warm-up pass per
+decoder. Five measured passes rotate decoder order and alternate RGB/RGBA group
+order. Whole batches are timed, rather than individual images, to limit timer
+quantization. Correctness checks are outside measured passes. Unsupported native
+APIs are reported explicitly. Hiding the page stops and discards the run.
+
+The benchmark runs in a dedicated worker, as game PNG decoding does. It measures
+elapsed decode-to-WASM time, not GPU upload, game startup or hardware utilization.
+A native speedup alone cannot establish whether hardware acceleration caused it.
diff --git a/tools/client/png_benchmark/decoder.c b/tools/client/png_benchmark/decoder.c
@@ -0,0 +1,54 @@
+#include <png.h>
+#include <stdlib.h>
+#include <string.h>
+#include <emscripten.h>
+
+struct input { const unsigned char *data; size_t size; };
+static void read_data(png_structp png, png_bytep output, png_size_t size) {
+ struct input *input = png_get_io_ptr(png);
+ if (size > input->size) png_error(png, "truncated PNG");
+ memcpy(output, input->data, size);
+ input->data += size;
+ input->size -= size;
+}
+static unsigned result[4];
+EMSCRIPTEN_KEEPALIVE unsigned *decode(const unsigned char *data, unsigned size) {
+ png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
+ png_infop info = png_create_info_struct(png);
+ struct input input = {data, size};
+ if (setjmp(png_jmpbuf(png))) { png_destroy_read_struct(&png, &info, NULL); return NULL; }
+ png_set_read_fn(png, &input, read_data);
+ png_read_info(png, info);
+ int depth = png_get_bit_depth(png, info);
+ int color = png_get_color_type(png, info);
+ if (depth < 8) png_set_packing(png);
+ if (color == PNG_COLOR_TYPE_GRAY && depth < 8) png_set_expand(png);
+ if (depth == 16) png_set_strip_16(png);
+ png_set_bgr(png);
+ png_set_interlace_handling(png);
+ png_read_update_info(png, info);
+ unsigned width = png_get_image_width(png, info), height = png_get_image_height(png, info);
+ unsigned rowbytes = png_get_rowbytes(png, info);
+ unsigned char *pixels = malloc(rowbytes * height);
+ png_bytep *rows = malloc(height * sizeof(*rows));
+ for (unsigned y = 0; y < height; ++y) rows[y] = pixels + y * rowbytes;
+ png_read_image(png, rows);
+ png_read_end(png, NULL);
+ result[0] = width; result[1] = height; result[2] = rowbytes * 8 / width;
+ result[3] = (unsigned)pixels;
+ free(rows);
+ png_destroy_read_struct(&png, &info, NULL);
+ return result;
+}
+
+/* Browser readback is RGBA; the guest expects packed BGR or BGRA. */
+EMSCRIPTEN_KEEPALIVE void pack_pixels(unsigned char *pixels, unsigned count, unsigned channels) {
+ for (unsigned i = 0; i < count; ++i) {
+ unsigned char r = pixels[i * 4], g = pixels[i * 4 + 1];
+ unsigned char b = pixels[i * 4 + 2], a = pixels[i * 4 + 3];
+ pixels[i * channels] = b;
+ pixels[i * channels + 1] = g;
+ pixels[i * channels + 2] = r;
+ if (channels == 4) pixels[i * channels + 3] = a;
+ }
+}
diff --git a/tools/client/png_benchmark/index.html b/tools/client/png_benchmark/index.html
@@ -0,0 +1,91 @@
+<!doctype html>
+<html lang="en">
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Phone PNG benchmark</title>
+<style>
+ body { font: 16px system-ui; max-width: 800px; margin: 24px auto; padding: 0 16px; color: #18202a; background: #f6f8fb; }
+ button { padding: 12px 20px; font: inherit; cursor: pointer; }
+ table { border-collapse: collapse; width: 100%; font-size: 14px; }
+ th, td { text-align: left; padding: 10px 6px; border-bottom: 1px solid #ccd4dd; }
+ pre { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; }
+</style>
+<h1>Phone PNG benchmark</h1>
+<p>Compare WASM libpng with browser-native decoding on 180 game textures.
+Downloads happen first. Timings include readback and conversion to pixels in WASM,
+but exclude GPU upload and game loading.</p>
+<p>Close the game tab first and keep this page visible while it runs.
+One warm-up and five measured rounds usually take less than a minute.
+Results are saved to the benchmark server automatically.</p>
+<button id="run">Run benchmark</button>
+<p id="status" role="status">Ready.</p>
+<div id="results"></div>
+<details hidden id="details"><summary>Full results</summary><pre id="json"></pre></details>
+<script>
+const button = document.querySelector('#run');
+const status = document.querySelector('#status');
+let worker;
+const median = values => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)];
+button.onclick = () => {
+ button.disabled = true;
+ document.querySelector('#results').replaceChildren();
+ document.querySelector('#details').hidden = true;
+ worker = new Worker('worker.js');
+ const fail = message => {
+ status.textContent = message;
+ worker.terminate();
+ worker = null;
+ button.disabled = false;
+ };
+ worker.onerror = event => fail(`Failed: ${event.message}`);
+ worker.onmessage = async ({data}) => {
+ if (data.status) status.textContent = data.status;
+ if (data.error) { fail(`Failed: ${data.error}`); return; }
+ if (!data.result) return;
+ worker.terminate();
+ worker = null;
+ const result = data.result;
+ const table = document.createElement('table');
+ table.innerHTML = '<tr><th>Decoder</th><th>Median total</th><th>RGB / RGBA</th><th>Images differing</th></tr>';
+ const names = {wasm: 'WASM libpng', bitmap: 'ImageBitmap + canvas', imageDecoder: 'ImageDecoder'};
+ for (const mode of ['wasm', 'bitmap', 'imageDecoder']) {
+ const stats = result.decoders[mode];
+ const row = table.insertRow();
+ row.insertCell().textContent = names[mode];
+ if (stats.unsupported || stats.error) {
+ const cell = row.insertCell();
+ cell.colSpan = 3;
+ cell.textContent = stats.unsupported ? 'Not supported in this browser' : stats.error;
+ continue;
+ }
+ row.insertCell().textContent = median(stats.RGB.ms.map((value, i) => value + stats.RGBA.ms[i])).toFixed(1) + ' ms';
+ row.insertCell().textContent = `${median(stats.RGB.ms).toFixed(1)} / ${median(stats.RGBA.ms).toFixed(1)} ms`;
+ row.insertCell().textContent = `${stats.RGB.mismatchedImages}/137 RGB; ${stats.RGBA.mismatchedImages}/43 RGBA`;
+ }
+ document.querySelector('#results').append(table);
+ document.querySelector('#json').textContent = JSON.stringify(result, null, 2);
+ document.querySelector('#details').hidden = false;
+ status.textContent = 'Benchmark complete. Saving results...';
+ try {
+ const response = await fetch('/results', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(result)});
+ if (!response.ok) throw Error(`HTTP ${response.status}`);
+ const saved = await response.json();
+ status.textContent = `Complete. Results saved (${saved.id}).`;
+ } catch (error) {
+ status.textContent = `Complete, but saving failed: ${error}. Full results are below.`;
+ }
+ button.disabled = false;
+ };
+};
+
+// Background throttling would invalidate a phone timing comparison.
+document.addEventListener('visibilitychange', () => {
+ if (document.hidden && worker) {
+ worker.terminate();
+ worker = null;
+ status.textContent = 'Stopped because the page was hidden. Keep it visible and run again.';
+ button.disabled = false;
+ }
+});
+</script>
+</html>
diff --git a/tools/client/png_benchmark/prepare.py b/tools/client/png_benchmark/prepare.py
@@ -0,0 +1,31 @@
+"""Build the standalone decoder and prepare the locally captured game PNGs."""
+import gzip
+import json
+import pathlib
+import shutil
+import subprocess
+
+root = pathlib.Path(__file__).resolve().parents[3]
+source = pathlib.Path(__file__).resolve().parent
+output = root / 'local/png-benchmark'
+output.mkdir(exist_ok=True)
+
+# The proprietary corpus stays local; preserve the original decoded reference.
+captured = json.loads((root / 'local/png-decoding/captured.json').read_text())
+images = list({image['input']: image for image in captured}.values())
+assert len(images) == 180
+assert {image['bits'] for image in images} == {24, 32}
+corpus = [{key: image[key] for key in ['input', 'pixels', 'width', 'height', 'bits']} for image in images]
+(output / 'corpus.json.gz').write_bytes(gzip.compress(json.dumps(corpus).encode()))
+
+# Use the game's pinned libpng port and its decoder optimization level.
+subprocess.run([
+ str(root / 'toolchains/emsdk/upstream/emscripten/emcc'), str(source / 'decoder.c'),
+ '-O2', '-flto=thin', '-sSUPPORT_LONGJMP=wasm', '-sUSE_LIBPNG=1',
+ '-sALLOW_MEMORY_GROWTH', '-sMODULARIZE', '-sEXPORT_NAME=createPNG',
+ '-sEXPORTED_FUNCTIONS=_decode,_pack_pixels,_malloc,_free',
+ '-sEXPORTED_RUNTIME_METHODS=HEAPU8,HEAPU32', '-o', str(output / 'decoder.js'),
+], check=True)
+for name in ['index.html', 'worker.js']:
+ shutil.copyfile(source / name, output / name)
+print(f'Prepared {len(images)} PNGs in {output}')
diff --git a/tools/client/png_benchmark/serve.py b/tools/client/png_benchmark/serve.py
@@ -0,0 +1,59 @@
+"""Serve the phone benchmark separately from the game, using its trusted certificate."""
+import http.server
+import json
+import pathlib
+import ssl
+import uuid
+
+root = pathlib.Path(__file__).resolve().parents[3]
+directory = root / 'local/png-benchmark'
+
+
+class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ files = {'/': ('index.html', 'text/html'),
+ '/worker.js': ('worker.js', 'text/javascript'),
+ '/decoder.js': ('decoder.js', 'text/javascript'),
+ '/decoder.wasm': ('decoder.wasm', 'application/wasm'),
+ '/corpus.json': ('corpus.json.gz', 'application/json')}
+ if self.path not in files:
+ self.send_error(404)
+ return
+ name, content_type = files[self.path]
+ body = (directory / name).read_bytes()
+ self.send_response(200)
+ self.send_header('Content-Type', content_type)
+ self.send_header('Content-Length', str(len(body)))
+ self.send_header('Cache-Control', 'no-store')
+ if name.endswith('.gz'):
+ self.send_header('Content-Encoding', 'gzip')
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_POST(self):
+ if self.path != '/results':
+ self.send_error(404)
+ return
+ size = int(self.headers.get('Content-Length', 0))
+ if not 0 < size <= 1024 * 1024:
+ self.send_error(413)
+ return
+ result = json.loads(self.rfile.read(size))
+ identity = str(uuid.uuid4())
+ (directory / 'results').mkdir(exist_ok=True)
+ (directory / 'results' / (identity + '.json')).write_text(json.dumps(result, indent=2) + '\n')
+ body = json.dumps({'id': identity}).encode()
+ self.send_response(200)
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+
+if __name__ == '__main__':
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ context.load_cert_chain(root / 'server/data/https/cert.pem', root / 'server/data/https/key.pem')
+ with http.server.ThreadingHTTPServer(('0.0.0.0', 8444), Handler) as server:
+ server.socket = context.wrap_socket(server.socket, server_side=True)
+ print('PNG benchmark listening on HTTPS port 8444', flush=True)
+ server.serve_forever()
diff --git a/tools/client/png_benchmark/worker.js b/tools/client/png_benchmark/worker.js
@@ -0,0 +1,124 @@
+importScripts('decoder.js');
+
+async function run() {
+ postMessage({status: 'Loading the decoder and 180 PNGs. Downloads are not timed.'});
+ const module = await createPNG();
+ const response = await fetch('corpus.json');
+ if (!response.ok) throw Error(`Corpus download failed: ${response.status}`);
+ const corpus = await response.json();
+ const bytes = text => Uint8Array.from(atob(text), char => char.charCodeAt(0));
+ const images = corpus.map(image => {
+ const input = bytes(image.input);
+ const pointer = module._malloc(input.length);
+ module.HEAPU8.set(input, pointer);
+ return {pointer, size: input.length, width: image.width, height: image.height,
+ channels: image.bits / 8, expected: bytes(image.pixels)};
+ });
+ const groups = {RGB: images.filter(image => image.channels === 3),
+ RGBA: images.filter(image => image.channels === 4)};
+ const result = {date: new Date().toISOString(), userAgent: navigator.userAgent,
+ hardwareConcurrency: navigator.hardwareConcurrency, images: images.length,
+ method: 'One validation/warm-up pass, five measured passes, rotating decoder order. Inputs already in WASM; outputs packed BGR/BGRA in WASM. Downloads, validation, game stream calls and GPU upload excluded.',
+ decoders: {}};
+ const modes = ['wasm'];
+ let canvas, context;
+ if (typeof createImageBitmap === 'function' && typeof OffscreenCanvas !== 'undefined') {
+ canvas = new OffscreenCanvas(1, 1);
+ context = canvas.getContext('2d', {willReadFrequently: true});
+ if (context) modes.push('bitmap');
+ }
+ if (!modes.includes('bitmap')) result.decoders.bitmap = {unsupported: true};
+ if (typeof ImageDecoder !== 'undefined' && await ImageDecoder.isTypeSupported('image/png'))
+ modes.push('imageDecoder');
+ else result.decoders.imageDecoder = {unsupported: true};
+
+ // Return equivalent guest-format pixels in WASM, including native readback costs.
+ async function decode(mode, image) {
+ if (mode === 'wasm') {
+ const decoded = module._decode(image.pointer, image.size);
+ if (!decoded) throw Error('libpng decode failed');
+ const values = module.HEAPU32.subarray(decoded >>> 2, (decoded >>> 2) + 4);
+ if (values[0] !== image.width || values[1] !== image.height || values[2] !== image.channels * 8)
+ throw Error('libpng dimensions or format differ');
+ return values[3];
+ }
+ const data = module.HEAPU8.slice(image.pointer, image.pointer + image.size);
+ const output = module._malloc(image.width * image.height * 4);
+ if (mode === 'bitmap') {
+ const bitmap = await createImageBitmap(new Blob([data], {type: 'image/png'}),
+ {premultiplyAlpha: 'none', colorSpaceConversion: 'none'});
+ canvas.width = bitmap.width;
+ canvas.height = bitmap.height;
+ context.drawImage(bitmap, 0, 0);
+ module.HEAPU8.set(context.getImageData(0, 0, bitmap.width, bitmap.height).data, output);
+ bitmap.close();
+ } else {
+ const decoder = new ImageDecoder({data, type: 'image/png',
+ colorSpaceConversion: 'none', premultiplyAlpha: 'none'});
+ const {image: frame} = await decoder.decode();
+ try {
+ await frame.copyTo(module.HEAPU8.subarray(output, output + image.width * image.height * 4), {format: 'RGBA'});
+ } finally {
+ frame.close();
+ decoder.close();
+ }
+ }
+ module._pack_pixels(output, image.width * image.height, image.channels);
+ return output;
+ }
+
+ // Validate once, outside measured passes, against the original guest decoder.
+ for (const mode of modes) {
+ postMessage({status: `Warming up and checking pixels: ${mode}`});
+ result.decoders[mode] = {};
+ try {
+ for (const [group, members] of Object.entries(groups)) {
+ const stats = {images: members.length, ms: [], mismatchedImages: 0,
+ mismatchedBytes: 0, visiblePixelChanges: 0, maxDifference: 0};
+ result.decoders[mode][group] = stats;
+ for (const image of members) {
+ const pointer = await decode(mode, image);
+ let changed = false;
+ for (let pixel = 0; pixel < image.width * image.height; ++pixel) {
+ let pixelChanged = false;
+ for (let channel = 0; channel < image.channels; ++channel) {
+ const index = pixel * image.channels + channel;
+ const difference = Math.abs(module.HEAPU8[pointer + index] - image.expected[index]);
+ if (difference) {
+ changed = pixelChanged = true;
+ ++stats.mismatchedBytes;
+ stats.maxDifference = Math.max(stats.maxDifference, difference);
+ }
+ }
+ if (pixelChanged && (image.channels === 3 || image.expected[pixel * 4 + 3] !== 0))
+ ++stats.visiblePixelChanges;
+ }
+ if (changed) ++stats.mismatchedImages;
+ module._free(pointer);
+ }
+ }
+ } catch (error) {
+ if (mode === 'wasm') throw error;
+ result.decoders[mode] = {error: String(error)};
+ }
+ }
+ if (result.decoders.wasm.RGB.mismatchedImages || result.decoders.wasm.RGBA.mismatchedImages)
+ throw Error('WASM baseline differs from captured pixels; benchmark invalid');
+
+ // Time whole batches, avoiding phone timer quantization on individual images.
+ const supported = modes.filter(mode => !result.decoders[mode].error);
+ for (let round = 0; round < 5; ++round) {
+ const order = supported.slice(round % supported.length).concat(supported.slice(0, round % supported.length));
+ for (const mode of order) {
+ postMessage({status: `Measured round ${round + 1}/5: ${mode}`});
+ for (const group of round % 2 ? ['RGBA', 'RGB'] : ['RGB', 'RGBA']) {
+ const start = performance.now();
+ for (const image of groups[group]) module._free(await decode(mode, image));
+ result.decoders[mode][group].ms.push(performance.now() - start);
+ }
+ }
+ }
+ postMessage({result});
+}
+
+run().catch(error => postMessage({error: String(error)}));