aorecomp

Anarchy Online classic in the browser

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


commit 441a79a1710b5ae1829251a4d799f67baf2ec396
parent d239b7175e5f993f309fd0643169cb20b037733a
Author: anon <anon@example.com>
Date:   Mon, 19 Oct 2026 20:09:46 +0000

Reduce browser texture memory and precompute resource lookups

Release uploaded managed and video-memory pixel buffers, restore them only for locks or eviction, and retain matching decoded audio without conversion copies.

Serve a versioned compact resource-prefetch index from the server and binary-search it in clients. Add buffer-lifetime, rendering, audio, index and cache regressions with measured startup-memory results.

Diffstat:
Aserver/browser_resources.go | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/browser_resources_test.go | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/main.go | 1+
Msrc/Makefile.linux | 2+-
Msrc/runtime/browser_fetch.js | 50++++++++++++++++++++++----------------------------
Msrc/runtime/gl_renderer.c | 3++-
Msrc/runtime/gl_renderer.h | 1+
Msrc/runtime/linux_audio.c | 55+++++++++++++++++++++++++++++++++----------------------
Msrc/runtime/linux_graphics.c | 30+++++++++++++++++++++++-------
Msrc/tests/audio.c | 24+++++++++++++++++++++---
Msrc/tests/browser_resource_prefetch.mjs | 59+++++++++++++++++++++++++++++++++++++++++++++++------------
Msrc/tests/graphics.c | 4++--
Msrc/tests/surfaces.c | 37+++++++++++++++++++++++++++++++++++++
13 files changed, 398 insertions(+), 76 deletions(-)

diff --git a/server/browser_resources.go b/server/browser_resources.go @@ -0,0 +1,90 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "io" + "net/http" + "os" + "sort" + "sync" +) + +var browserResourceCache struct { + sync.Mutex + version string + offsets []byte +} + +func loadBrowserResourceOffsets(file *os.File, version string) ([]byte, error) { + browserResourceCache.Lock() + defer browserResourceCache.Unlock() + if browserResourceCache.version == version { + return browserResourceCache.offsets, nil + } + // Build the prefetch table once per asset version, outside the client process. + data, err := io.ReadAll(file) + if err != nil { + return nil, err + } + if len(data) < 76 { + return nil, fmt.Errorf("resource index header is truncated") + } + var records [][3]uint32 + seen := make(map[uint32]bool) + for block := binary.LittleEndian.Uint32(data[72:]); block != 0; block = binary.LittleEndian.Uint32(data[block:]) { + if seen[block] || uint64(block)+10 > uint64(len(data)) { + return nil, fmt.Errorf("invalid resource index block %d", block) + } + seen[block] = true + count := binary.LittleEndian.Uint16(data[block+8:]) + if uint64(block)+18+uint64(count)*12 > uint64(len(data)) { + return nil, fmt.Errorf("truncated resource index block %d", block) + } + for entry := uint32(0); entry < uint32(count); entry++ { + offset := block + 18 + entry*12 + records = append(records, [3]uint32{ + binary.BigEndian.Uint32(data[offset+4:]), + binary.BigEndian.Uint32(data[offset+8:]), + binary.LittleEndian.Uint32(data[offset:]), + }) + } + } + // Stable ordering preserves the last entry for duplicate identities. + sort.SliceStable(records, func(i, j int) bool { + return records[i][0] < records[j][0] || records[i][0] == records[j][0] && records[i][1] < records[j][1] + }) + offsets := make([]byte, len(records)*12) + for i, record := range records { + for j, value := range record { + binary.LittleEndian.PutUint32(offsets[i*12+j*4:], value) + } + } + browserResourceCache.version, browserResourceCache.offsets = version, offsets + return offsets, nil +} + +func browserResourceIndex(w http.ResponseWriter, r *http.Request) { + file, err := os.Open("anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.idx") + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer file.Close() + info, err := file.Stat() + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + version := browserAssetVersion(info) + offsets, err := loadBrowserResourceOffsets(file, version) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("ETag", version) + http.ServeContent(w, r, "resource-offsets.bin", info.ModTime(), bytes.NewReader(offsets)) +} diff --git a/server/browser_resources_test.go b/server/browser_resources_test.go @@ -0,0 +1,118 @@ +package main + +import ( + "encoding/binary" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" +) + +func resourceIndexFixture(t *testing.T) ([]byte, string) { + t.Helper() + t.Chdir(t.TempDir()) + path := "anarchy-assets-14.9.1/cd_image/data/db/ResourceDatabase.idx" + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + t.Fatal(err) + } + data := make([]byte, 256) + binary.LittleEndian.PutUint32(data[72:], 128) + binary.LittleEndian.PutUint16(data[136:], 4) + for i, record := range [][3]uint32{{5, 20, 100}, {1, 3, 200}, {5, 20, 300}, {0xffffffff, 0xffffffff, 400}} { + offset := 146 + i*12 + binary.LittleEndian.PutUint32(data[offset:], record[2]) + binary.BigEndian.PutUint32(data[offset+4:], record[0]) + binary.BigEndian.PutUint32(data[offset+8:], record[1]) + } + return data, path +} + +func TestBrowserResourceIndexServesSortedOffsets(t *testing.T) { + data, path := resourceIndexFixture(t) + if err := os.WriteFile(path, data, 0644); err != nil { + t.Fatal(err) + } + response := httptest.NewRecorder() + + browserResourceIndex(response, httptest.NewRequest("GET", "/browser-resource-index", nil)) + + if response.Code != http.StatusOK || response.Body.Len() != 48 { + t.Fatalf("resource offsets: %d %q", response.Code, response.Body.String()) + } + for i, expected := range []uint32{1, 3, 200, 5, 20, 100, 5, 20, 300, 0xffffffff, 0xffffffff, 400} { + if actual := binary.LittleEndian.Uint32(response.Body.Bytes()[i*4:]); actual != expected { + t.Fatalf("offset word %d: got %d, want %d", i, actual, expected) + } + } + if response.Header().Get("ETag") == "" || response.Header().Get("Cache-Control") != "no-cache" { + t.Fatalf("cache headers: %v", response.Header()) + } +} + +func TestBrowserResourceIndexTracksAssetVersion(t *testing.T) { + data, path := resourceIndexFixture(t) + if err := os.WriteFile(path, data, 0644); err != nil { + t.Fatal(err) + } + first := httptest.NewRecorder() + browserResourceIndex(first, httptest.NewRequest("GET", "/browser-resource-index", nil)) + request := httptest.NewRequest("GET", "/browser-resource-index", nil) + request.Header.Set("If-None-Match", first.Header().Get("ETag")) + revalidated := httptest.NewRecorder() + stale := httptest.NewRecorder() + updated := httptest.NewRecorder() + + browserResourceIndex(revalidated, request) + binary.LittleEndian.PutUint32(data[158:], 999) + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data, 0644); err != nil { + t.Fatal(err) + } + stamp := info.ModTime().Add(time.Nanosecond) + if err := os.Chtimes(path, stamp, stamp); err != nil { + t.Fatal(err) + } + request = httptest.NewRequest("GET", "/browser-resource-index", nil) + request.Header.Set("If-Match", first.Header().Get("ETag")) + browserResourceIndex(stale, request) + browserResourceIndex(updated, httptest.NewRequest("GET", "/browser-resource-index", nil)) + + if revalidated.Code != http.StatusNotModified || stale.Code != http.StatusPreconditionFailed { + t.Fatalf("version responses: unchanged %d, stale %d", revalidated.Code, stale.Code) + } + if updated.Code != http.StatusOK || updated.Header().Get("ETag") == first.Header().Get("ETag") || + binary.LittleEndian.Uint32(updated.Body.Bytes()[8:]) != 999 { + t.Fatalf("updated offsets: %d %v %x", updated.Code, updated.Header(), updated.Body.Bytes()) + } +} + +func TestBrowserResourceIndexRejectsInvalidBlocks(t *testing.T) { + for _, scenario := range []string{"header", "truncated", "cycle"} { + t.Run(scenario, func(t *testing.T) { + data, path := resourceIndexFixture(t) + switch scenario { + case "header": + data = data[:20] + case "truncated": + binary.LittleEndian.PutUint16(data[136:], 100) + case "cycle": + binary.LittleEndian.PutUint32(data[128:], 128) + } + if err := os.WriteFile(path, data, 0644); err != nil { + t.Fatal(err) + } + response := httptest.NewRecorder() + + browserResourceIndex(response, httptest.NewRequest("GET", "/browser-resource-index", nil)) + + if response.Code != http.StatusInternalServerError { + t.Fatalf("invalid index: %d", response.Code) + } + }) + } +} diff --git a/server/main.go b/server/main.go @@ -58,6 +58,7 @@ func main() { http.HandleFunc("GET /browser-world", server.browserWorld) http.HandleFunc("GET /browser-chat", server.browserChat) http.HandleFunc("GET /browser-manifest", browserManifest) + http.HandleFunc("GET /browser-resource-index", browserResourceIndex) http.HandleFunc("POST /browser-profile/{session}", browserProfile) http.HandleFunc("GET /wasm/", browserClient) http.HandleFunc("GET /{$}", browserClient) diff --git a/src/Makefile.linux b/src/Makefile.linux @@ -343,7 +343,7 @@ test: build/linux/fonts build/linux/audio: tests/audio.c runtime/linux_audio.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_audio.h runtime/guest_heap.h runtime/guest_memory.h runtime/recomp_types.h runtime/linux_path.c runtime/linux_path.h mkdir -p $(@D) - $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -lSDL2 -lsndfile -lm -Wl,--wrap=SDL_OpenAudioDevice,--wrap=sf_open -o $@ + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -lSDL2 -lsndfile -lm -Wl,--wrap=SDL_OpenAudioDevice,--wrap=sf_open,--wrap=SDL_NewAudioStream -o $@ test: build/linux/audio diff --git a/src/runtime/browser_fetch.js b/src/runtime/browser_fetch.js @@ -238,35 +238,18 @@ addToLibrary({ let resourceIndex, databaseHandle, resourceReads = 0; const resources = []; async function readResourceIndex() { - let handle; + let indexURL; for (const file of allocatedFiles) { const url = fileURL(file); - if (url.endsWith('/ResourceDatabase.idx')) handle = file; + if (url.endsWith('/ResourceDatabase.idx')) indexURL = url; if (url.endsWith('/ResourceDatabase.dat')) databaseHandle = file; } - const file = await getFile(handle); - const bytes = new Uint8Array(file.size); - ++file.readers; - try { - await ensureChunks(file, 0, Math.ceil(file.size / file.chunkSize) - 1); - for (let chunk = 0; chunk < file.chunks.length; ++chunk) - bytes.set(file.chunks[chunk], chunk * file.chunkSize); - } finally { - --file.readers; - trimChunks(); - } - - // Index leaves contain a little-endian data offset and big-endian identity. - const view = new DataView(bytes.buffer), records = new Map(), seen = new Set(); - for (let block = view.getUint32(72, true); block; block = view.getUint32(block, true)) { - if (seen.has(block)) throw new Error('Resource index block cycle'); - seen.add(block); - for (let entry = 0; entry < view.getUint16(block + 8, true); ++entry) { - const offset = block + 18 + entry * 12; - records.set(`${view.getUint32(offset + 4)}:${view.getUint32(offset + 8)}`, - view.getUint32(offset, true)); - } - } + const info = await fileMetadata(indexURL); + const response = await fetch(new URL('/browser-resource-index', indexURL).href, + {headers: {'If-Match': info.version}}); + if (!response.ok) throw new Error(`Resource prefetch index: HTTP ${response.status}`); + const records = new DataView(await response.arrayBuffer()); + if (records.byteLength % 12) throw new Error('Invalid resource prefetch index'); return records; } @@ -289,15 +272,26 @@ addToLibrary({ } AOResourcePrefetch.request = (kind, identity) => { + kind >>>= 0; + identity >>>= 0; if (!resourceIndex) resourceIndex = readResourceIndex().catch(error => { console.warn('Resource prefetch unavailable; continuing with demand reads', error); return null; }); resourceIndex.then(records => { if (!records) return; - const offset = records.get(`${kind}:${identity}`); - if (offset !== undefined) { - resources.push(offset); + // The server sorts fixed-size uint32 triples; no string-keyed map is needed. + let first = 0, last = records.byteLength / 12; + while (first < last) { + const middle = (first + last) >>> 1; + const recordKind = records.getUint32(middle * 12, true); + const recordIdentity = records.getUint32(middle * 12 + 4, true); + if (recordKind < kind || (recordKind === kind && recordIdentity <= identity)) first = middle + 1; + else last = middle; + } + const offset = (first - 1) * 12; + if (first && records.getUint32(offset, true) === kind && records.getUint32(offset + 4, true) === identity) { + resources.push(records.getUint32(offset + 8, true)); pumpResources(); } }); diff --git a/src/runtime/gl_renderer.c b/src/runtime/gl_renderer.c @@ -376,7 +376,8 @@ void gl_target_evict(struct gl_target *target, const unsigned char *rgba) if (target->saved_pixels) return; unsigned char *pixels = malloc((size_t)target->width * target->height * 4); if (!pixels) abort(); - memcpy(pixels, rgba, (size_t)target->width * target->height * 4); + if (rgba) memcpy(pixels, rgba, (size_t)target->width * target->height * 4); + else gl_target_read(target, pixels); glDeleteFramebuffers(1, &target->framebuffer); glDeleteTextures(1, &target->color); target->framebuffer = target->color = 0; diff --git a/src/runtime/gl_renderer.h b/src/runtime/gl_renderer.h @@ -40,6 +40,7 @@ void gl_renderer_shutdown(void); struct gl_target *gl_target_create(unsigned width, unsigned height, int with_depth); void gl_target_destroy(struct gl_target *target); void gl_target_set_mip(struct gl_target *target, struct gl_target *mip); +/* NULL preserves the GPU contents without an existing CPU copy. */ void gl_target_evict(struct gl_target *target, const unsigned char *rgba); struct gl_depth *gl_depth_create(unsigned width, unsigned height, unsigned bits); void gl_depth_destroy(struct gl_depth *depth); diff --git a/src/runtime/linux_audio.c b/src/runtime/linux_audio.c @@ -110,17 +110,23 @@ static void *load_audio(void *unused) if (sf_close(file)) abort(); if (frames > 0 && !error) { /* A fixed base rate lets pitch changes work before decoding completes. */ - SDL_AudioStream *conversion = SDL_NewAudioStream(AUDIO_F32SYS, info.channels, info.samplerate, - AUDIO_F32SYS, info.channels, 44100); - if (!conversion || SDL_AudioStreamPut(conversion, decoded, frames * info.channels * sizeof(float)) || - SDL_AudioStreamFlush(conversion)) abort(); - int size = SDL_AudioStreamAvailable(conversion); - if (size < 0 || size % (sizeof(float) * info.channels)) abort(); - asset->samples = malloc(size ? size : 1); - if (!asset->samples || SDL_AudioStreamGet(conversion, asset->samples, size) != size) abort(); - SDL_FreeAudioStream(conversion); + if (info.samplerate == 44100) { + asset->samples = decoded; + asset->frames = frames; + decoded = NULL; + } else { + SDL_AudioStream *conversion = SDL_NewAudioStream(AUDIO_F32SYS, info.channels, info.samplerate, + AUDIO_F32SYS, info.channels, 44100); + if (!conversion || SDL_AudioStreamPut(conversion, decoded, frames * info.channels * sizeof(float)) || + SDL_AudioStreamFlush(conversion)) abort(); + int size = SDL_AudioStreamAvailable(conversion); + if (size < 0 || size % (sizeof(float) * info.channels)) abort(); + asset->samples = malloc(size ? size : 1); + if (!asset->samples || SDL_AudioStreamGet(conversion, asset->samples, size) != size) abort(); + SDL_FreeAudioStream(conversion); + asset->frames = size / sizeof(float) / info.channels; + } asset->channels = info.channels; - asset->frames = size / sizeof(float) / info.channels; state = asset->frames ? 1 : -1; } free(decoded); @@ -550,7 +556,7 @@ static void open_stream(void) if (pthread_mutex_unlock(&audio_mutex)) abort(); double profile_start = ao_profile_begin("music load/decode"); - /* Decode the file once; SDL converts its channels/rate into driver-format floats. */ + /* Retain decoded floats directly when they already match the mixer. */ char *path = linux_path((const char *)ADDR(filename)); SF_INFO info = {0}; SNDFILE *file = sf_open(path, SFM_READ, &info); @@ -562,19 +568,24 @@ static void open_stream(void) sf_count_t frames = sf_readf_float(file, decoded, info.frames); if (frames < 0 || sf_error(file)) abort(); if (sf_close(file)) abort(); - SDL_AudioStream *conversion = SDL_NewAudioStream(AUDIO_F32SYS, info.channels, info.samplerate, - AUDIO_F32SYS, channels, rate); - if (!conversion || SDL_AudioStreamPut(conversion, decoded, frames * info.channels * sizeof(float)) || - SDL_AudioStreamFlush(conversion)) abort(); - free(decoded); - int size = SDL_AudioStreamAvailable(conversion); - if (size < 0 || size % (sizeof(float) * channels)) abort(); struct audio_stream *stream = calloc(1, sizeof(*stream)); if (!stream) abort(); - stream->samples = malloc(size ? size : 1); - if (!stream->samples || SDL_AudioStreamGet(conversion, stream->samples, size) != size) abort(); - SDL_FreeAudioStream(conversion); - stream->frames = size / sizeof(float) / channels; + if (info.channels == channels && info.samplerate == rate) { + stream->samples = decoded; + stream->frames = frames; + } else { + SDL_AudioStream *conversion = SDL_NewAudioStream(AUDIO_F32SYS, info.channels, info.samplerate, + AUDIO_F32SYS, channels, rate); + if (!conversion || SDL_AudioStreamPut(conversion, decoded, frames * info.channels * sizeof(float)) || + SDL_AudioStreamFlush(conversion)) abort(); + free(decoded); + int size = SDL_AudioStreamAvailable(conversion); + if (size < 0 || size % (sizeof(float) * channels)) abort(); + stream->samples = malloc(size ? size : 1); + if (!stream->samples || SDL_AudioStreamGet(conversion, stream->samples, size) != size) abort(); + SDL_FreeAudioStream(conversion); + stream->frames = size / sizeof(float) / channels; + } stream->status = 2; stream->volume = 127; fprintf(stderr, "[linux-audio] decoded %s: %u frames\n", path, stream->frames); diff --git a/src/runtime/linux_graphics.c b/src/runtime/linux_graphics.c @@ -1332,12 +1332,18 @@ static void transfer_surface_pixels(struct surface_object *surface, enum surface static void evict_managed_textures(void) { struct draw_object *owner = find_object(MEM32(g_esp + 4)); - /* Managed surfaces retain authoritative CPU pixels, including blit updates. */ + /* Preserve managed contents on the CPU only while GPU storage is evicted. */ for (struct surface_object *surface = surfaces; surface; surface = surface->next) { if (surface->owner != owner || !(surface->caps2 & 0x10)) continue; - swap_surface_channels(surface); - transfer_surface_pixels(surface, SURFACE_EVICT); - swap_surface_channels(surface); + if (surface->pixels) { + swap_surface_channels(surface); + transfer_surface_pixels(surface, SURFACE_EVICT); + swap_surface_channels(surface); + } else gl_target_evict(surface->target, NULL); + if (!surface->locked) { + guest_free(surface->pixels); + surface->pixels = 0; + } } g_eax = 0; g_esp += 8; @@ -1361,9 +1367,10 @@ static void surface_lock(void) if (rect) memcpy(rectangle, (void *)ADDR(rect), 16); if (rectangle[0] < 0 || rectangle[1] < 0 || rectangle[2] < rectangle[0] || rectangle[3] < rectangle[1] || rectangle[2] > (int32_t)surface->width || rectangle[3] > (int32_t)surface->height) return; + int readback = !surface->pixels || !(surface->caps & 0x800); if (!surface->pixels) surface->pixels = guest_malloc(surface->pitch * surface->height); if (!surface->pixels) { g_eax = 0x8007000eu; return; } - if (!(surface->caps & 0x800)) { + if (readback) { transfer_surface_pixels(surface, SURFACE_READ); swap_surface_channels(surface); } @@ -1383,12 +1390,18 @@ static void surface_unlock(void) if (!surface->locked || (rect && memcmp((void *)ADDR(rect), surface->lock_rectangle, 16))) { g_eax = 0x88760248u; return; } + int temporary = !(surface->caps & 0x800) || (surface->caps2 & 0x10); if (!(surface->lock_flags & 0x10)) { swap_surface_channels(surface); transfer_surface_pixels(surface, SURFACE_WRITE); - swap_surface_channels(surface); + if (!temporary) swap_surface_channels(surface); } surface->locked = 0; + /* GPU-backed pixels are temporary; ordinary system-memory surfaces retain them. */ + if (temporary) { + guest_free(surface->pixels); + surface->pixels = 0; + } g_eax = 0; } @@ -1443,7 +1456,10 @@ static void surface_blit(void) } } else if (to[0] < 0 || to[1] < 0 || to[2] > (int32_t)target->width || to[3] > (int32_t)target->height) return; gl_target_blit(source->target, target->target, from, to); - if (target->caps & 0x800) { + if (target->caps2 & 0x10) { + guest_free(target->pixels); + target->pixels = 0; + } else if (target->caps & 0x800) { transfer_surface_pixels(target, SURFACE_READ); swap_surface_channels(target); } diff --git a/src/tests/audio.c b/src/tests/audio.c @@ -22,6 +22,18 @@ static SDL_AudioCallback device_callback; static void *device_userdata; static _Atomic int capture, nonzero_samples, bad_samples; static _Atomic int block_audio_open, audio_open_entered; +#ifndef __EMSCRIPTEN__ +static _Atomic unsigned audio_conversions; + +SDL_AudioStream *__real_SDL_NewAudioStream(SDL_AudioFormat, Uint8, int, SDL_AudioFormat, Uint8, int); +SDL_AudioStream *__wrap_SDL_NewAudioStream(SDL_AudioFormat source_format, Uint8 source_channels, int source_rate, + SDL_AudioFormat destination_format, Uint8 destination_channels, int destination_rate) +{ + ++audio_conversions; + return __real_SDL_NewAudioStream(source_format, source_channels, source_rate, + destination_format, destination_channels, destination_rate); +} +#endif /* Hold the loader inside file I/O until playback controls have been exercised. */ SNDFILE *__real_sf_open(const char *, int, SF_INFO *); @@ -666,11 +678,11 @@ static void stream_playback(uint32_t scratch) char path[] = "/tmp/ao-audio-XXXXXX"; int descriptor = mkstemp(path); assert(descriptor >= 0); - SF_INFO info = {.samplerate = 44100, .channels = 1, .format = SF_FORMAT_WAV | SF_FORMAT_PCM_16}; + SF_INFO info = {.samplerate = 44100, .channels = 2, .format = SF_FORMAT_WAV | SF_FORMAT_PCM_16}; SNDFILE *file = sf_open_fd(descriptor, SFM_WRITE, &info, 1); assert(file); - float samples[4410]; - for (unsigned i = 0; i < 4410; ++i) samples[i] = 0.25f; + float samples[8820]; + for (unsigned i = 0; i < 8820; ++i) samples[i] = 0.25f; assert(sf_writef_float(file, samples, 4410) == 4410 && !sf_close(file)); uint16_t format[] = {1, 2, 44100, 0, 45328, 2, 4, 16}; memcpy(POINTER(scratch + 16), format, sizeof(format)); @@ -679,6 +691,9 @@ static void stream_playback(uint32_t scratch) uint32_t driver = MEM32(scratch); strcpy(POINTER(scratch + 64), path); uint32_t open[] = {driver, scratch + 64, 0}; +#ifndef __EMSCRIPTEN__ + unsigned conversions_before = audio_conversions; +#endif uint32_t stream = call("_AIL_open_stream@12", 3, open); assert(stream && call("_AIL_stream_status@4", 1, &stream) == 2); @@ -694,6 +709,9 @@ static void stream_playback(uint32_t scratch) assert(call("_AIL_stream_status@4", 1, &stream) == 2); assert(nonzero_samples == 8820 && !bad_samples); +#ifndef __EMSCRIPTEN__ + assert(audio_conversions == conversions_before); +#endif call("_AIL_stream_ms_position@12", 3, position); assert(MEM32(scratch + 132) == 100 && MEM32(scratch + 136) == 100); assert(MEM32(scratch + 128) == 0xa5a5a5a5 && MEM32(scratch + 140) == 0xa5a5a5a5); diff --git a/src/tests/browser_resource_prefetch.mjs b/src/tests/browser_resource_prefetch.mjs @@ -2,18 +2,19 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import vm from 'node:vm'; -const index = new Uint8Array(256), view = new DataView(index.buffer); -view.setUint32(72, 128, true); -view.setUint16(136, 7, true); -for (const [entry, identity, offset] of [[0,17,64],[1,18,128],[2,19,192], - [3,20,256],[4,21,320],[5,22,384],[6,23,448]]) { - view.setUint32(146 + entry * 12, offset, true); - view.setUint32(150 + entry * 12, 1010004); - view.setUint32(154 + entry * 12, identity); +let index = new Uint8Array(120); +const view = new DataView(index.buffer); +for (const [entry, kind, identity, offset] of [[0,1,0,64], [1,1010004,17,64], + [2,1010004,18,96], [3,1010004,18,128], [4,1010004,19,192], + [5,1010004,20,256], [6,1010004,21,320], [7,1010004,22,384], + [8,1010004,23,448], [9,0xffffffff,0xffffffff,448]]) { + view.setUint32(entry * 12, kind, true); + view.setUint32(entry * 12 + 4, identity, true); + view.setUint32(entry * 12 + 8, offset, true); } const database = Uint8Array.from({length:512}, (_, i) => i % 251); const requests = [], pending = new Map(), warnings = []; -let library, ready = 0; +let library, ready = 0, indexStatus = 200; const context = vm.createContext({ AOProfile: {begin: () => 0, end: () => {}},Map, Set, URL, Response, Uint8Array, DataView, HEAPU8:new Uint8Array(64), AOResourcePrefetch:{}, wasmFS$backends:{}, @@ -29,7 +30,12 @@ const context = vm.createContext({ 'cd_image/data/db/ResourceDatabase.idx':{size:256,version:'"one"'}, 'cd_image/data/db/ResourceDatabase.dat':{size:512,version:'"one"'}, }); - const bytes = url.endsWith('.idx') ? index : database; + if (url.endsWith('/browser-resource-index')) { + assert.equal(options.headers['If-Match'], '"one"'); + return new Response(index, {status: indexStatus}); + } + assert.equal(url.endsWith('.idx'), false); + const bytes = database; const [start, end] = options.headers.Range.slice(6).split('-').map(Number); if (bytes === database) { requests.push(start); @@ -91,7 +97,19 @@ assert.equal(requests.filter(offset => offset === 128).length, 1); assert.deepEqual(warnings, []); console.log('PASS: resource index hints, bounded byte prefetch, joined demand reads, failure retry and freed-file skip'); -view.setUint32(128, 128, true); +await backend.allocFile(2); +requests.length = 0; + +library.browser_prefetch_resource_js(1, 0); +library.browser_prefetch_resource_js(-1, -1); +await settle(); + +assert.deepEqual(requests, [0,64,448]); +for (const resolve of pending.values()) resolve(206); +await settle(); +console.log('PASS: first and last keys, unsigned identities and last duplicate offset'); + +index = new Uint8Array(1); await library._wasmfs_create_fetch_backend_js(2); const invalidIndex = context.wasmFS$backends[2]; await invalidIndex.allocFile(1); @@ -107,5 +125,22 @@ assert.equal(ordinaryRead, 1); assert.equal(context.HEAPU8[0], 0); assert.deepEqual(requests, [0]); assert.equal(warnings.length, 1); -assert.equal(warnings[0][1].message, 'Resource index block cycle'); +assert.equal(warnings[0][1].message, 'Invalid resource prefetch index'); console.log('PASS: invalid speculative index falls back to ordinary demand reads'); + +indexStatus = 404; +await library._wasmfs_create_fetch_backend_js(3); +const oldServer = context.wasmFS$backends[3]; +await oldServer.allocFile(1); +await oldServer.allocFile(2); +requests.length = 0; + +library.browser_prefetch_resource_js(1010004, 17); +await settle(); +const oldServerRead = await oldServer.read(2, 0, 1, 0); + +assert.equal(oldServerRead, 1); +assert.deepEqual(requests, [0]); +assert.equal(warnings.length, 2); +assert.equal(warnings[1][1].message, 'Resource prefetch index: HTTP 404'); +console.log('PASS: older servers keep ordinary asset reads when prefetch is unavailable'); diff --git a/src/tests/graphics.c b/src/tests/graphics.c @@ -745,8 +745,8 @@ static void eviction_releases_gpu_storage_and_restores_pixels(void) glGetIntegerv(GL_TEXTURE_BINDING_2D, &name); assert(glIsTexture(name)); - gl_target_evict(texture, input); - gl_target_evict(texture, input); + gl_target_evict(texture, NULL); + gl_target_evict(texture, NULL); assert(!glIsTexture(name)); gl_target_read(texture, output); diff --git a/src/tests/surfaces.c b/src/tests/surfaces.c @@ -14,6 +14,7 @@ static uint32_t scratch[1024]; #include "linux_graphics.h" #include "linux_window.h" #include "guest_memory.h" +#include "guest_heap.h" #include <SDL2/SDL.h> recomp_func_t recomp_lookup(uint32_t address) { @@ -198,6 +199,38 @@ static void surface_pixels_round_trip(uint32_t caps) assert(!invoke(surface, 2, 1) && !invoke(draw, 2, 1)); } +#ifndef _WIN32 +static void uploaded_surface_releases_temporary_pixels(uint32_t caps2) +{ + uint32_t draw = create_draw(); + uint32_t desc = workspace() + 128; + const uint32_t format[] = {32, 0x40, 0, 32, 0xff0000, 0xff00, 0xff, 0}; + memset(memory(desc), 0, 124); + *memory(desc) = 124; *memory(desc + 4) = 0x1007; + *memory(desc + 8) = 16; *memory(desc + 12) = 32; + memcpy(memory(desc + 72), format, sizeof(format)); + *memory(desc + 104) = 0x1000; *memory(desc + 108) = caps2; + assert(!invoke(draw, 6, 4, desc, workspace(), 0u)); + uint32_t surface = *memory(workspace()); + *memory(desc) = 124; + assert(!invoke(surface, 25, 5, 0u, desc, 0x21u, 0u)); + uint32_t pixels = *memory(desc + 36); + for (unsigned i = 0; i < 512; ++i) *memory(pixels + i * 4) = 0x00112233; + + assert(!invoke(surface, 32, 2, 0u)); + uint32_t reused = guest_malloc(2048); + memset(memory(reused), 0x55, 2048); + assert(!invoke(surface, 25, 5, 0u, desc, 0x11u, 0u)); + + assert(reused == pixels); + for (unsigned i = 0; i < 512; ++i) + assert((*memory(*memory(desc + 36) + i * 4) & 0xffffff) == 0x00112233); + assert(!invoke(surface, 32, 2, 0u)); + guest_free(reused); + assert(!invoke(surface, 2, 1) && !invoke(draw, 2, 1)); +} +#endif + static void rectangle_locks_preserve_surrounding_pixels(uint32_t caps) { uint32_t draw = create_draw(), surface = create_surface(draw, caps); @@ -739,6 +772,10 @@ int main(void) surface_lifetime_and_description(); surface_pixels_round_trip(0x2040); surface_pixels_round_trip(0x840); +#ifndef _WIN32 + uploaded_surface_releases_temporary_pixels(0); + uploaded_surface_releases_temporary_pixels(0x10); +#endif rectangle_locks_preserve_surrounding_pixels(0x2040); rectangle_locks_preserve_surrounding_pixels(0x840); clipper_attachment_retains_objects();