aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit 41d033f77e89e86f3c20619642e7dce1c8472297
parent b955cbd36a6bbe2a9d6f24a72b1560f89fa7907b
Author: anon <anon@example.com>
Date:   Sat, 17 Oct 2026 15:30:52 +0000

Prefetch related browser sounds without blocking playback

Diffstat:
Msrc/runtime/browser_fetch.js | 58+++++++++++++++++++++++++++++++++++++++++++++++++++-------
Asrc/tests/browser_prefetch.mjs | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 118 insertions(+), 7 deletions(-)

diff --git a/src/runtime/browser_fetch.js b/src/runtime/browser_fetch.js @@ -4,6 +4,52 @@ addToLibrary({ ], _wasmfs_create_fetch_backend_js: async function(backend) { const files = new Map(); + // File URLs are valid only after their WasmFS constructor has returned. + const allocatedFiles = new Set(), prefetchedFamilies = new Set(), prefetchQueue = []; + let prefetching = 0, soundGroups = null; + + // FetchFS joins its base and path with two slashes; avoid a server redirect. + function fileURL(handle) { + const url = new URL(UTF8ToString(__wasmfs_fetch_get_file_url(handle))); + url.pathname = url.pathname.replace(/\/+/g, '/'); + return url.href; + } + + function pumpPrefetch() { + while (prefetching < 2 && prefetchQueue.length) { + const handle = prefetchQueue.shift(); + if (!allocatedFiles.has(handle) || files.has(handle)) continue; + ++prefetching; + // Failed speculation is retried if the game later requests this file. + getFile(handle).catch(() => {}).finally(() => { + --prefetching; + pumpPrefetch(); + }); + } + } + + function prefetchSounds(url) { + const match = /^(.*\/sound\/.*?)(\d+)\.wav$/i.exec(url); + if (!match || prefetchedFamilies.has(match[1])) return; + prefetchedFamilies.add(match[1]); + // Return the requested sound first; find and fetch siblings in the background. + setTimeout(() => { + if (!soundGroups) { + // Sound reads begin after browser_initialize has built the remote file tree. + soundGroups = new Map(); + for (const handle of allocatedFiles) { + const other = /^(.*\/sound\/.*?)(\d+)\.wav$/i.exec(fileURL(handle)); + if (!other) continue; + if (!soundGroups.has(other[1])) soundGroups.set(other[1], []); + soundGroups.get(other[1]).push(handle); + } + } + for (const handle of soundGroups.get(match[1]) || []) + if (!files.has(handle)) prefetchQueue.push(handle); + pumpPrefetch(); + }); + } + let cache; function disableCache(error) { cache = null; @@ -86,14 +132,12 @@ addToLibrary({ // Share the first request and cached chunks between concurrent readers. function getFile(handle) { if (!files.has(handle)) { - // FetchFS joins its base and path with two slashes; avoid a server redirect. - const url = new URL(UTF8ToString(__wasmfs_fetch_get_file_url(handle))); - url.pathname = url.pathname.replace(/\/+/g, '/'); + const url = fileURL(handle); const file = { - url: url.href, + url, chunkSize: __wasmfs_fetch_get_chunk_size(handle), chunks: [] }; - const pending = cacheReady.then(() => fetchChunks(file, 0, 0)).then(() => file); + const pending = cacheReady.then(() => fetchChunks(file, 0, 0)).then(() => { prefetchSounds(url); return file; }); files.set(handle, pending); pending.catch(() => files.delete(handle)); } @@ -101,8 +145,8 @@ addToLibrary({ } wasmFS$backends[backend] = { - allocFile: async () => {}, - freeFile: async (file) => { files.delete(file); }, + allocFile: async (file) => { allocatedFiles.add(file); soundGroups = null; }, + freeFile: async (file) => { allocatedFiles.delete(file); files.delete(file); soundGroups = null; }, write: async () => -{{{ cDefs.EROFS }}}, getSize: async (handle) => { try { diff --git a/src/tests/browser_prefetch.mjs b/src/tests/browser_prefetch.mjs @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; + +const names = new Map([[1,'boots_sand_01.wav'],[2,'boots_sand_02.wav'],[3,'boots_sand_03.wav'], + [4,'boots_sand_04.wav'],[5,'boots_sand_05.wav'],[6,'boots_con_01.wav']]); +const requests = [], pending = [], timers = []; +let library; +const context = vm.createContext({Map, Set, URL, Response, Uint8Array, console, + HEAPU8:new Uint8Array(64), UTF8ToString: value => value, + __wasmfs_fetch_get_file_url: handle => { + assert(names.has(handle), 'Must not inspect a freed file'); + return 'http://example.test/browser-assets//cd_image/sound/sfx/foots/' + names.get(handle); + }, + __wasmfs_fetch_get_chunk_size: () => 1048576, + wasmFS$backends:{}, addToLibrary:value => { library = value; }, + setTimeout:callback => timers.push(callback), + fetch:url => new Promise(resolve => { + requests.push(url.split('/').at(-1)); + pending.push(status => resolve(new Response(status === 206 ? 'abcd' : null, + {status,headers:{'Content-Range':'bytes 0-3/4',ETag:'"one"'}}))); + }) +}); +let source = fs.readFileSync(new URL('../runtime/browser_fetch.js', import.meta.url),'utf8'); +for (const [name,value] of Object.entries({EROFS:69,ENOENT:44,EBADF:8})) + source = source.replaceAll('{{{ cDefs.' + name + ' }}}',String(value)); +vm.runInContext(source,context); +await library._wasmfs_create_fetch_backend_js(1); +const backend = context.wasmFS$backends[1]; +for (const handle of names.keys()) await backend.allocFile(handle); +const settle = () => new Promise(setImmediate); + +// Fetch one sound, then run its deferred family scan. +const first = backend.getSize(1); +await settle(); +pending[0](206); +assert.equal(await first,4); +assert.equal(timers.length,1); +timers.shift()(); +await settle(); +assert.deepEqual(requests,['boots_sand_01.wav','boots_sand_02.wav','boots_sand_03.wav']); + +// Foreground reads join pending prefetch; queued freed files are skipped. +await backend.freeFile(4); +names.delete(4); +const foreground = backend.read(2,0,4,0); +await settle(); +assert.equal(requests.length,3); +pending[1](206); +assert.equal(await foreground,4); +assert.equal(new TextDecoder().decode(context.HEAPU8.subarray(0,4)),'abcd'); +await settle(); +assert.equal(requests.at(-1),'boots_sand_05.wav'); + +// A failed speculative fetch is retried on demand, without repeating the scan. +pending[2](404); +pending[3](206); +await settle(); +const retried = backend.getSize(3); +await settle(); +assert.equal(requests.at(-1),'boots_sand_03.wav'); +pending[4](206); +assert.equal(await retried,4); +assert.equal(requests.length,5); +assert.equal(timers.length,0); +assert.equal(requests.includes('boots_con_01.wav'), false); +console.log('PASS: bounded prefetch, shared foreground request, freed-file skip and retry');