aorecomp

Anarchy Online classic in the browser

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


commit 191fa4bdeac666a84d012c1d9c126b45a16fe3bb
parent 6ecdc2b5063171c96e18f5d8501a32c2b0e0ab25
Author: anon <anon@example.com>
Date:   Sat, 17 Oct 2026 17:41:19 +0000

Load portable sound effects on a background worker

Diffstat:
Msrc/Makefile.linux | 2+-
Msrc/Makefile.wasm | 2+-
Msrc/game/mmr.dll/lifted-0001.c | 8++++++++
Msrc/game/mmr.dll/lifted-0003.c | 7+++++++
Msrc/runtime/browser_audio.c | 8++++----
Msrc/runtime/browser_fetch.js | 36+++++++++++++++++++++---------------
Msrc/runtime/browser_host.js | 21+++++++++++++++++++--
Msrc/runtime/linux_audio.c | 224++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Msrc/runtime/linux_audio.h | 1+
Msrc/tests/audio.c | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/tests/browser_fetch.mjs | 14++++++++++++++
Msrc/tests/browser_prefetch.mjs | 9++++++---
Asrc/tests/browser_sound_metadata.mjs | 41+++++++++++++++++++++++++++++++++++++++++
13 files changed, 487 insertions(+), 46 deletions(-)

diff --git a/src/Makefile.linux b/src/Makefile.linux @@ -311,7 +311,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 -o $@ + $(CC) $(CPPFLAGS) $(CFLAGS) $(filter %.c,$^) -pthread -lSDL2 -lsndfile -lm -Wl,--wrap=SDL_OpenAudioDevice,--wrap=sf_open -o $@ test: build/linux/audio diff --git a/src/Makefile.wasm b/src/Makefile.wasm @@ -65,7 +65,7 @@ build/wasm/web/mixer-test.html: tests/browser_mixer.html build/wasm/web/mixer-te build/wasm/web/mixer-test.js: tests/audio.c runtime/linux_audio.c runtime/browser_audio.c runtime/guest_heap.c runtime/guest_memory.c runtime/recomp_state.c runtime/linux_path.c runtime/browser_audio.h runtime/browser_audio.js runtime/linux_audio.h runtime/guest_heap.h runtime/guest_memory.h runtime/recomp_types.h runtime/linux_path.h Makefile.wasm @mkdir -p $(@D) - $(CC) $(CPPFLAGS) $(CFLAGS) -I../local/wasm/deps/include -sUSE_SDL=2 $(filter %.c,$^) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS --js-library runtime/browser_audio.js -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -Wl,--wrap=audio_output_open -o $@ + $(CC) $(CPPFLAGS) $(CFLAGS) -I../local/wasm/deps/include -sUSE_SDL=2 $(filter %.c,$^) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS --js-library runtime/browser_audio.js -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=4 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sALLOW_MEMORY_GROWTH -Wl,--wrap=audio_output_open,--wrap=sf_open -o $@ build/wasm/terrain-line.js: tests/terrain_line.c game/llr.dll/lifted-0023.c runtime/guest_memory.c runtime/recomp_state.c runtime/recomp_types.h runtime/guest_memory.h @mkdir -p $(@D) diff --git a/src/game/mmr.dll/lifted-0001.c b/src/game/mmr.dll/lifted-0001.c @@ -5805,8 +5805,16 @@ L_3A00567A: ecx = ebp + (-0x28); /* 0x3A0056EA: lea ecx, [ebp - 0x28] */ PUSH32(esp, ecx); /* 0x3A0056ED: push ecx */ PUSH32(esp, edi); /* 0x3A0056EE: push edi */ +#ifdef __EMSCRIPTEN__ + /* Cache accounting must not lock a file while the audio worker downloads it. */ + extern int ao_sound_file_size(const char *filename); + int sound_size = ao_sound_file_size((const char *)ADDR(edi)); + MEM32(ebp - 0x14) = sound_size; + eax = sound_size < 0 ? UINT32_MAX : 0; +#else RECOMP_ICALL(MEM32(0x3A00A038)); /* 0x3A0056EF: call dword ptr [0x3a00a038] */ RECOMP_FLAGS_IN(); +#endif _flag_a = (uint32_t)(esp); _flag_b = (uint32_t)(0x18u); _cf = (uint32_t)((uint32_t)(_flag_a + _flag_b) < (uint32_t)_flag_a); esp = esp + 0x18u; /* 0x3A0056F5: add esp, 0x18 */ diff --git a/src/game/mmr.dll/lifted-0003.c b/src/game/mmr.dll/lifted-0003.c @@ -1,5 +1,8 @@ #define RECOMP_GENERATED_CODE #include "recomp_types.h" +#if defined(RECOMP_PORTABLE) && !defined(_WIN32) +#include "linux_audio.h" +#endif #include <math.h> #include <stdio.h> #include <stdlib.h> @@ -286,6 +289,9 @@ L_3A008420: } void sub_3A008430(void) { +#if defined(RECOMP_PORTABLE) && !defined(_WIN32) + linux_audio_load_sound(); +#else int _fpu_cmp = 0; uint32_t _cf = 0; int _df = 1; @@ -446,6 +452,7 @@ L_3A00852C: ebp = POP32_VAL(esp); /* 0x3A00852F: pop ebp */ RECOMP_FLAGS_OUT(); esp += 16; { RECOMP_REGS_OUT(); return; } /* 0x3A008530: ret 0xc */ RECOMP_REGS_OUT(); +#endif } void sub_3A008540(void) { diff --git a/src/runtime/browser_audio.c b/src/runtime/browser_audio.c @@ -25,6 +25,8 @@ static void *mix_audio(void *argument) unsigned char *buffer = malloc(output->format.size); if (!buffer) abort(); for (;;) { + /* Browser calls can wait for its UI thread, so keep them outside the mixer lock. */ + int ready = ao_audio_ready(output->handle); /* Only workers take this lock; the browser receives completed PCM blocks. */ if (pthread_mutex_lock(&output->mutex)) abort(); while (output->paused && !output->closed) @@ -33,12 +35,10 @@ static void *mix_audio(void *argument) if (pthread_mutex_unlock(&output->mutex)) abort(); break; } - double delay = 10; - if (ao_audio_ready(output->handle)) { + if (ready) output->format.callback(output->format.userdata, buffer, output->format.size); - delay = ao_audio_submit(output->handle, buffer, output->format.samples); - } if (pthread_mutex_unlock(&output->mutex)) abort(); + double delay = ready ? ao_audio_submit(output->handle, buffer, output->format.samples) : 10; usleep((unsigned)(delay * 1000)); } free(buffer); diff --git a/src/runtime/browser_fetch.js b/src/runtime/browser_fetch.js @@ -137,6 +137,21 @@ addToLibrary({ } } + // Validate all file versions together; size queries need no asset bytes. + async function fileMetadata(url) { + if (!metadata) { + metadata = fetch(new URL('/browser-manifest', url).href, { + cache: 'no-store', headers: {Accept: 'application/json'} + }).then(response => { + if (!response.ok) throw response; + return response.json(); + }); + } + const listing = await metadata; + const name = decodeURIComponent(new URL(url).pathname).slice('/browser-assets/'.length); + return listing[name]; + } + // Share the first request and cached chunks between concurrent readers. function getFile(handle) { if (!files.has(handle)) { @@ -145,20 +160,10 @@ addToLibrary({ url, chunkSize: __wasmfs_fetch_get_chunk_size(handle), chunks: [] }; - // Validate all file versions together instead of spending a round trip per file. - if (!metadata) { - metadata = fetch(new URL('/browser-manifest', url).href, { - cache: 'no-store', headers: {Accept: 'application/json'} - }).then(response => { - if (!response.ok) throw response; - return response.json(); - }); - } - const pending = Promise.all([cacheReady, metadata]).then(async ([, listing]) => { - const name = decodeURIComponent(new URL(url).pathname).slice('/browser-assets/'.length); - if (listing[name]) { - file.size = listing[name].size; - file.version = listing[name].version; + const pending = Promise.all([cacheReady, fileMetadata(url)]).then(async ([, info]) => { + if (info) { + file.size = info.size; + file.version = info.version; if (file.size) await loadChunks(file, 0, 0); } else { await fetchChunks(file, 0, 0); @@ -178,7 +183,8 @@ addToLibrary({ write: async () => -{{{ cDefs.EROFS }}}, getSize: async (handle) => { try { - return (await getFile(handle)).size; + const info = await fileMetadata(fileURL(handle)); + return info ? info.size : (await getFile(handle)).size; } catch (error) { return 0; } diff --git a/src/runtime/browser_host.js b/src/runtime/browser_host.js @@ -10,14 +10,31 @@ addToLibrary({ AOPresentation.resume = resolve; AOPresentation.channel.port2.postMessage(0); }), - ao_asset_manifest__deps: ['$stringToNewUTF8', '$UTF8ToString'], + $AOSoundSizes: {}, + ao_asset_manifest__deps: ['$stringToNewUTF8', '$UTF8ToString', '$AOSoundSizes'], ao_asset_manifest: (base) => { // This call runs on the game worker, where synchronous XHR may block safely. const request = new XMLHttpRequest(); request.open('GET', new URL('/browser-manifest', UTF8ToString(base)).href, false); request.send(); if (request.status !== 200) throw new Error(`Asset manifest: HTTP ${request.status}`); - return stringToNewUTF8(request.responseText); + const listing = request.responseText; + + // Keep sound cache accounting independent of files being read by the loader. + request.open('GET', new URL('/browser-manifest', UTF8ToString(base)).href, false); + request.setRequestHeader('Accept', 'application/json'); + request.send(); + if (request.status !== 200) throw new Error(`Asset metadata: HTTP ${request.status}`); + for (const [name, metadata] of Object.entries(JSON.parse(request.responseText))) { + if (name.toLowerCase().startsWith('cd_image/sound/')) + AOSoundSizes[name.toLowerCase()] = metadata.size; + } + return stringToNewUTF8(listing); + }, + ao_sound_file_size__deps: ['$AOSoundSizes', '$UTF8ToString'], + ao_sound_file_size: (filename) => { + const name = UTF8ToString(filename).replaceAll('\\', '/').replace(/^\.\//, '').toLowerCase(); + return AOSoundSizes[name] ?? -1; }, ao_asset_base_url__deps: ['$stringToNewUTF8'], ao_asset_base_url__proxy: 'sync', diff --git a/src/runtime/linux_audio.c b/src/runtime/linux_audio.c @@ -7,6 +7,7 @@ #include <sndfile.h> #include <limits.h> #include <math.h> +#include <stdatomic.h> #ifdef __EMSCRIPTEN__ #include "browser_audio.h" @@ -24,11 +25,27 @@ static int miles_started, sample_capacity = 64; static uint32_t redist_directory, next_driver = 0xf6000000; static uint32_t next_stream = 0xf6800000; static uint32_t next_sample = 0xf7000000; +/* Immutable decoded assets outlive both queued work and individual voices. */ +struct audio_asset { + uint32_t handle, frames; + unsigned references; + int channels; + _Atomic int state; + char *filename; + float *samples; + struct audio_asset *next, *queued; +}; +static struct audio_asset *assets, *load_head, *load_tail; +static uint32_t next_asset = 0xf7800000; +static pthread_cond_t load_condition = PTHREAD_COND_INITIALIZER; +static pthread_once_t loader_once = PTHREAD_ONCE_INIT; + struct audio_sample { uint32_t handle, frames; int status, volume, rate, channels, loops; double position; float *samples; + struct audio_asset *asset; struct audio_sample *next; }; struct audio_stream { @@ -49,12 +66,134 @@ static struct audio_driver { struct audio_sample *samples; } *drivers; +/* Callers hold audio_mutex; the worker owns a reference until publication. */ +static void release_asset_locked(struct audio_asset *asset) +{ + if (--asset->references) return; + struct audio_asset **link = &assets; + while (*link != asset) link = &(*link)->next; + *link = asset->next; + free(asset->samples); + free(asset->filename); + free(asset); +} + +static void *load_audio(void *unused) +{ + for (;;) { + if (pthread_mutex_lock(&audio_mutex)) abort(); + while (!load_head) + if (pthread_cond_wait(&load_condition, &audio_mutex)) abort(); + struct audio_asset *asset = load_head; + load_head = asset->queued; + if (!load_head) load_tail = NULL; + int canceled = asset->references == 1; + if (pthread_mutex_unlock(&audio_mutex)) abort(); + + /* File access, decoding and resampling never hold a playback lock. */ + int state = -1; + if (!canceled) { + char *path = linux_path(asset->filename); + SF_INFO info = {0}; + SNDFILE *file = sf_open(path, SFM_READ, &info); + if (file) { + if (info.frames < 0 || info.channels < 1 || info.channels > 2 || + info.frames > INT_MAX / (int)sizeof(float) / info.channels) abort(); + float *decoded = malloc(info.frames ? info.frames * info.channels * sizeof(float) : 1); + if (!decoded) abort(); + sf_count_t frames = sf_readf_float(file, decoded, info.frames); + int error = sf_error(file); + 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); + asset->channels = info.channels; + asset->frames = size / sizeof(float) / info.channels; + state = asset->frames ? 1 : -1; + } + free(decoded); + } else fprintf(stderr, "[linux-audio] sound %s: %s\n", path, sf_strerror(NULL)); + free(path); + } + + atomic_store_explicit(&asset->state, state, memory_order_release); + if (pthread_mutex_lock(&audio_mutex)) abort(); + release_asset_locked(asset); + if (pthread_mutex_unlock(&audio_mutex)) abort(); + } + return NULL; +} + +static void start_audio_loader(void) +{ + pthread_t thread; + if (pthread_create(&thread, NULL, load_audio, NULL) || pthread_detach(thread)) abort(); +} + +/* mmr.dll sub_3A008430: return the ordinary 20-byte sound object immediately. + Its data and allocation slots carry a host asset handle, never a partial RIFF. */ +void linux_audio_load_sound(void) +{ + uint32_t output = MEM32(g_esp + 4), filename = MEM32(g_esp + 8); + unsigned priority = MEM8(g_esp + 12); + MEM32(output) = 0; + g_esp += 16; + if (!MEM8(g_ecx + 0x10) || !MEM32(g_ecx + 0xc)) return; + uint32_t sound = guest_malloc(20); + if (!sound) abort(); + struct audio_asset *asset = calloc(1, sizeof(*asset)); + if (!asset) abort(); + asset->filename = strdup((const char *)ADDR(filename)); + if (!asset->filename) abort(); + atomic_init(&asset->state, 0); + if (pthread_once(&loader_once, start_audio_loader)) abort(); + if (pthread_mutex_lock(&audio_mutex)) abort(); + if (next_asset >= 0xf8000000u) abort(); + asset->handle = next_asset++; + asset->references = 2; + asset->next = assets; + assets = asset; + if (load_tail) load_tail->queued = asset; + else load_head = asset; + load_tail = asset; + if (pthread_cond_signal(&load_condition)) abort(); + if (pthread_mutex_unlock(&audio_mutex)) abort(); + MEM32(sound) = 0; + MEM32(sound + 4) = MEM32(sound + 8) = asset->handle; + MEM32(sound + 12) = priority; + MEM32(sound + 16) = 44100; + MEM32(output) = sound; +} + +/* The device lock protects voice state; publication does not touch voices. */ +static void adopt_sample_locked(struct audio_sample *sample) +{ + if (!sample->asset || sample->samples) return; + int state = atomic_load_explicit(&sample->asset->state, memory_order_acquire); + if (state < 0) { if (sample->status == 4) sample->status = 2; } + else if (state > 0) { + sample->samples = sample->asset->samples; + sample->frames = sample->asset->frames; + sample->channels = sample->asset->channels; + } +} + /* The output worker holds its device lock; this callback never enters guest code. */ static void render_audio(void *userdata, Uint8 *output, int length) { struct audio_driver *driver = userdata; int bytes = SDL_AUDIO_BITSIZE(driver->format.format) / 8; int frames = length / (bytes * driver->format.channels); + for (struct audio_sample *voice = driver->samples; voice; voice = voice->next) + adopt_sample_locked(voice); for (int frame = 0; frame < frames; ++frame) { for (int channel = 0; channel < driver->format.channels; ++channel) { float sample = 0; @@ -63,7 +202,7 @@ static void render_audio(void *userdata, Uint8 *output, int length) sample += stream->samples[stream->position * driver->format.channels + channel] * (stream->volume / 127.0f) * (driver->volume / 127.0f); for (struct audio_sample *voice = driver->samples; voice; voice = voice->next) { - if (voice->status != 4) continue; + if (voice->status != 4 || !voice->frames) continue; unsigned index = voice->position; unsigned next = index + 1 < voice->frames ? index + 1 : index; float fraction = voice->position - index; @@ -92,7 +231,7 @@ static void render_audio(void *userdata, Uint8 *output, int length) for (struct audio_stream *stream = driver->streams; stream; stream = stream->next) if (stream->status == 4 && ++stream->position == stream->frames) stream->status = 2; for (struct audio_sample *voice = driver->samples; voice; voice = voice->next) { - if (voice->status != 4) continue; + if (voice->status != 4 || !voice->frames) continue; voice->position += (double)voice->rate / driver->format.freq; while (voice->position >= voice->frames) { if (voice->loops == 1) { voice->status = 2; voice->position = voice->frames; break; } @@ -115,7 +254,8 @@ static void destroy_driver_locked(struct audio_driver *driver) while (driver->samples) { struct audio_sample *sample = driver->samples; driver->samples = sample->next; - free(sample->samples); + if (sample->asset) release_asset_locked(sample->asset); + else free(sample->samples); free(sample); } free(driver); @@ -319,6 +459,8 @@ static void open_stream(void) struct audio_driver *driver = drivers; while (driver && driver->handle != handle) driver = driver->next; if (!driver) abort(); + int channels = driver->format.channels, rate = driver->format.freq; + if (pthread_mutex_unlock(&audio_mutex)) abort(); /* Decode the file once; SDL converts its channels/rate into driver-format floats. */ char *path = linux_path((const char *)ADDR(filename)); @@ -333,30 +475,40 @@ static void open_stream(void) 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, driver->format.channels, driver->format.freq); + 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) * driver->format.channels)) abort(); + if (size < 0 || size % (sizeof(float) * channels)) abort(); struct audio_stream *stream = calloc(1, sizeof(*stream)); - if (!stream || next_stream >= 0xf7000000u) abort(); + if (!stream) abort(); stream->samples = malloc(size ? size : 1); if (!stream->samples || SDL_AudioStreamGet(conversion, stream->samples, size) != size) abort(); SDL_FreeAudioStream(conversion); - stream->handle = next_stream++; - stream->frames = size / sizeof(float) / driver->format.channels; + stream->frames = size / sizeof(float) / channels; stream->status = 2; stream->volume = 127; - audio_output_lock(driver->device); - stream->next = driver->streams; - driver->streams = stream; - audio_output_unlock(driver->device); - g_eax = stream->handle; - fprintf(stderr, "[linux-audio] decoded %s: %u frames\n", path, stream->frames); + /* The driver may have closed while file I/O ran independently. */ + if (pthread_mutex_lock(&audio_mutex)) abort(); + driver = drivers; + while (driver && driver->handle != handle) driver = driver->next; + if (driver) { + if (next_stream >= 0xf7000000u) abort(); + stream->handle = next_stream++; + audio_output_lock(driver->device); + stream->next = driver->streams; + driver->streams = stream; + audio_output_unlock(driver->device); + g_eax = stream->handle; + fprintf(stderr, "[linux-audio] decoded %s: %u frames\n", path, stream->frames); + } else { + free(stream->samples); + free(stream); + } + if (pthread_mutex_unlock(&audio_mutex)) abort(); } else fprintf(stderr, "[linux-audio] stream %s: %s\n", path, sf_strerror(NULL)); free(path); - if (pthread_mutex_unlock(&audio_mutex)) abort(); } static void file_read(void) @@ -438,7 +590,15 @@ static void file_type(void) static void mem_free_lock(void) { - guest_free(MEM32(g_esp + 4)); + uint32_t handle = MEM32(g_esp + 4); + if (handle >= 0xf7800000u && handle < 0xf8000000u) { + if (pthread_mutex_lock(&audio_mutex)) abort(); + struct audio_asset *asset = assets; + while (asset && asset->handle != handle) asset = asset->next; + if (!asset) abort(); + release_asset_locked(asset); + if (pthread_mutex_unlock(&audio_mutex)) abort(); + } else guest_free(handle); g_esp += 8; } @@ -512,7 +672,9 @@ static void decompress_asi(void) static void init_sample_locked(struct audio_sample *sample) { - free(sample->samples); + if (sample->asset) release_asset_locked(sample->asset); + else free(sample->samples); + sample->asset = NULL; sample->samples = NULL; sample->frames = 0; sample->position = 0; @@ -573,6 +735,7 @@ static void sample_control(enum sample_operation operation, unsigned arguments) } if (!sample) abort(); audio_output_lock(driver->device); + adopt_sample_locked(sample); if (operation == SAMPLE_INIT) init_sample_locked(sample); else if (operation == SAMPLE_RELEASE) { init_sample_locked(sample); sample->status = 1; } else if (operation == SAMPLE_STATUS) g_eax = sample->status; @@ -584,9 +747,28 @@ static void sample_control(enum sample_operation operation, unsigned arguments) else if (operation == SAMPLE_LOOPS) sample->loops = value; else if (operation == SAMPLE_END) { if (sample->status != 1) sample->status = 2; } else if (operation == SAMPLE_START) { - if (sample->status != 1 && sample->frames) { sample->position = 0; sample->status = 4; } + if (sample->status != 1 && (sample->frames || sample->asset)) { + sample->position = 0; + sample->status = 4; + adopt_sample_locked(sample); + } } else if (operation == SAMPLE_FILE) { - if (value && MEM32(value) == 0x46464952 && MEM32(value + 8) == 0x45564157) { + if (value >= 0xf7800000u && value < 0xf8000000u) { + struct audio_asset *asset = assets; + while (asset && asset->handle != value) asset = asset->next; + if (!asset) abort(); + ++asset->references; + if (sample->asset) release_asset_locked(sample->asset); + else free(sample->samples); + sample->asset = asset; + sample->samples = NULL; + sample->frames = 0; + sample->position = 0; + sample->rate = 44100; + sample->status = 2; + adopt_sample_locked(sample); + g_eax = 1; + } else if (value && MEM32(value) == 0x46464952 && MEM32(value + 8) == 0x45564157) { struct audio_memory memory = {(const unsigned char *)ADDR(value), (uint64_t)MEM32(value + 4) + 8, 0}; SF_VIRTUAL_IO io = {audio_length, audio_seek, audio_read, NULL, audio_tell}; SF_INFO info = {0}; @@ -598,7 +780,9 @@ static void sample_control(enum sample_operation operation, unsigned arguments) if (!decoded) abort(); sf_count_t frames = sf_readf_float(file, decoded, info.frames); if (frames > 0 && !sf_error(file)) { - free(sample->samples); + if (sample->asset) release_asset_locked(sample->asset); + else free(sample->samples); + sample->asset = NULL; sample->samples = decoded; sample->frames = frames; sample->channels = info.channels; diff --git a/src/runtime/linux_audio.h b/src/runtime/linux_audio.h @@ -1,5 +1,6 @@ #ifndef LINUX_AUDIO_H #define LINUX_AUDIO_H #include "recomp_types.h" +void linux_audio_load_sound(void); recomp_func_t linux_audio_lookup(const char *dll, const char *name); #endif diff --git a/src/tests/audio.c b/src/tests/audio.c @@ -11,14 +11,28 @@ static HMODULE miles; #else #include "linux_audio.h" #include "guest_memory.h" +#include "guest_heap.h" #include <SDL2/SDL.h> #include <sndfile.h> #include <stdatomic.h> +#include <pthread.h> #include <unistd.h> #define POINTER(p) ((void *)ADDR(p)) 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; + +/* Hold the loader inside file I/O until playback controls have been exercised. */ +SNDFILE *__real_sf_open(const char *, int, SF_INFO *); +SNDFILE *__wrap_sf_open(const char *path, int mode, SF_INFO *info) +{ + if (block_audio_open) { + audio_open_entered = 1; + while (block_audio_open) SDL_Delay(1); + } + return __real_sf_open(path, mode, info); +} /* Capture actual output from the public playback path and output worker. */ static void capture_audio(void *userdata, Uint8 *output, int length) @@ -461,6 +475,150 @@ static void stream_seek(uint32_t scratch) } #ifndef _WIN32 +static void *open_blocked_stream(void *argument) +{ + const uint32_t *args = argument; + g_esp = 0x5000f000; + MEM32(g_esp + 4) = args[0]; + MEM32(g_esp + 8) = args[1]; + MEM32(g_esp + 12) = 0; + linux_audio_lookup("mss32.dll", "_AIL_open_stream@12")(); + return (void *)(uintptr_t)g_eax; +} + +static void asynchronous_sound(uint32_t scratch) +{ + char path[] = "/tmp/ao-async-audio-XXXXXX"; + int descriptor = mkstemp(path); + assert(descriptor >= 0); + SF_INFO info = {.samplerate = 44100, .channels = 1, .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; + 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)); + uint32_t args[] = {scratch, 0, UINT32_MAX, scratch + 16}; + assert(!call("_AIL_waveOutOpen@16", 4, args)); + uint32_t driver = MEM32(scratch); + uint32_t voice = call("_AIL_allocate_sample_handle@4", 1, &driver); + strcpy(POINTER(scratch + 64), path); + MEM32(scratch + 512 + 12) = driver; + MEM8(scratch + 512 + 16) = 1; + block_audio_open = 1; + audio_open_entered = 0; + + g_ecx = scratch + 512; + g_esp = 0x5000ff00; + MEM32(g_esp + 4) = scratch + 128; + MEM32(g_esp + 8) = scratch + 64; + MEM32(g_esp + 12) = 42; + linux_audio_load_sound(); + uint32_t sound = MEM32(scratch + 128); + assert(g_esp == 0x5000ff10 && sound && MEM8(sound + 12) == 42); + for (unsigned i = 0; !audio_open_entered && i < 1000; ++i) SDL_Delay(1); + uint32_t sample_file[] = {voice, MEM32(sound + 4), 1}; + assert(call("_AIL_set_sample_file@12", 3, sample_file)); + nonzero_samples = bad_samples = 0; + capture = 1; + call("_AIL_start_sample@4", 1, &voice); + SDL_Delay(30); + + assert(audio_open_entered && !nonzero_samples); + assert(call("_AIL_sample_status@4", 1, &voice) == 4); + assert(call("_AIL_sample_playback_rate@4", 1, &voice) == 44100); + call("_AIL_end_sample@4", 1, &voice); + assert(call("_AIL_sample_status@4", 1, &voice) == 2); + call("_AIL_release_sample_handle@4", 1, &voice); + uint32_t allocation = MEM32(sound + 8); + call("_AIL_mem_free_lock@4", 1, &allocation); + guest_free(sound); + assert(call("_AIL_allocate_sample_handle@4", 1, &driver) == voice); + + /* Reuse the stopped voice while its previous asset is still being loaded. */ + g_ecx = scratch + 512; + g_esp = 0x5000ff00; + MEM32(g_esp + 4) = scratch + 128; + MEM32(g_esp + 8) = scratch + 64; + MEM32(g_esp + 12) = 0; + linux_audio_load_sound(); + sound = MEM32(scratch + 128); + sample_file[1] = MEM32(sound + 4); + assert(call("_AIL_set_sample_file@12", 3, sample_file)); + uint32_t rate[] = {voice, 22050}, loops[] = {voice, 2}; + call("_AIL_set_sample_playback_rate@8", 2, rate); + call("_AIL_set_sample_loop_count@8", 2, loops); + call("_AIL_start_sample@4", 1, &voice); + block_audio_open = 0; + for (unsigned i = 0; call("_AIL_sample_status@4", 1, &voice) == 4 && i < 2000; ++i) SDL_Delay(1); + assert(call("_AIL_sample_status@4", 1, &voice) == 2); + assert(nonzero_samples == 35280 && !bad_samples); + assert(call("_AIL_sample_playback_rate@4", 1, &voice) == 22050); + + /* Freeing the guest cache entry leaves a playing voice's decoded data alive. */ + allocation = MEM32(sound + 8); + call("_AIL_mem_free_lock@4", 1, &allocation); + guest_free(sound); + nonzero_samples = 0; + call("_AIL_start_sample@4", 1, &voice); + for (unsigned i = 0; call("_AIL_sample_status@4", 1, &voice) == 4 && i < 1000; ++i) SDL_Delay(1); + assert(nonzero_samples == 17640 && !bad_samples); + capture = 0; + call("_AIL_release_sample_handle@4", 1, &voice); + + /* A music load also cannot hold the common playback lock during file I/O. */ + block_audio_open = 1; + audio_open_entered = 0; + uint32_t open[] = {driver, scratch + 64}; + pthread_t music; + assert(!pthread_create(&music, NULL, open_blocked_stream, open)); + for (unsigned i = 0; !audio_open_entered && i < 1000; ++i) SDL_Delay(1); + assert(audio_open_entered); + voice = call("_AIL_allocate_sample_handle@4", 1, &driver); + assert(voice && call("_AIL_sample_status@4", 1, &voice) == 2); + call("_AIL_waveOutClose@4", 1, &driver); + block_audio_open = 0; + void *result; + assert(!pthread_join(music, &result) && !result); + assert(!unlink(path)); + fprintf(stderr, "Async sound: blocked I/O, immediate stop, voice reuse, playback and cache ownership passed.\n"); +} + +static void failed_sound(uint32_t scratch) +{ + uint16_t format[] = {1, 2, 44100, 0, 45328, 2, 4, 16}; + memcpy(POINTER(scratch + 16), format, sizeof(format)); + uint32_t args[] = {scratch, 0, UINT32_MAX, scratch + 16}; + assert(!call("_AIL_waveOutOpen@16", 4, args)); + uint32_t driver = MEM32(scratch); + uint32_t voice = call("_AIL_allocate_sample_handle@4", 1, &driver); + strcpy(POINTER(scratch + 64), "/no-such-ao-audio-test.wav"); + MEM32(scratch + 512 + 12) = driver; + MEM8(scratch + 512 + 16) = 1; + + g_ecx = scratch + 512; + g_esp = 0x5000ff00; + MEM32(g_esp + 4) = scratch + 128; + MEM32(g_esp + 8) = scratch + 64; + MEM32(g_esp + 12) = 0; + linux_audio_load_sound(); + uint32_t sound = MEM32(scratch + 128); + uint32_t sample_file[] = {voice, MEM32(sound + 4), 1}; + assert(call("_AIL_set_sample_file@12", 3, sample_file)); + call("_AIL_start_sample@4", 1, &voice); + for (unsigned i = 0; call("_AIL_sample_status@4", 1, &voice) == 4 && i < 1000; ++i) SDL_Delay(1); + + assert(call("_AIL_sample_status@4", 1, &voice) == 2); + call("_AIL_start_sample@4", 1, &voice); + assert(call("_AIL_sample_status@4", 1, &voice) == 2); + call("_AIL_waveOutClose@4", 1, &driver); + uint32_t allocation = MEM32(sound + 8); + call("_AIL_mem_free_lock@4", 1, &allocation); + guest_free(sound); + fprintf(stderr, "Async sound: missing file completes without leaving a voice busy.\n"); +} + static void stream_playback(uint32_t scratch) { char path[] = "/tmp/ao-audio-XXXXXX"; @@ -632,6 +790,8 @@ int main(int argc, char **argv) adpcm_sample(address); stream_seek(address); stream_playback(address); + asynchronous_sound(address); + failed_sound(address); fprintf(stderr, "Audio output: device enumeration and 4 PCM format open/close/shutdown cases passed.\n"); #endif assert(call("_AIL_set_preference@8", 2, preference) == 64); diff --git a/src/tests/browser_fetch.mjs b/src/tests/browser_fetch.mjs @@ -72,6 +72,19 @@ async function overlappingReads() { assert.equal(requests.length, 4); } +async function metadataOnlySizes() { + const {backend, requests, manifests} = await fixture(new TextEncoder().encode('abcdef')); + + const sizes = await Promise.all([backend.getSize(1), backend.getSize(2), backend.getSize(1)]); + + assert.deepEqual(sizes, [6, 6, 6]); + assert.deepEqual(requests, []); + assert.equal(manifests.length, 1); + assert.equal(await backend.read(1, 0, 4, 0), 4); + assert.deepEqual(requests, ['bytes=0-3']); + assert.equal(manifests.length, 1); +} + async function concurrentReads() { const {backend, requests, heap} = await fixture(new TextEncoder().encode('abcdefghijkl')); @@ -122,6 +135,7 @@ async function emptyAndMissingFiles() { } await overlappingReads(); +await metadataOnlySizes(); await concurrentReads(); await mediumFileBoundary(); await wholeFileResponse(); diff --git a/src/tests/browser_prefetch.mjs b/src/tests/browser_prefetch.mjs @@ -34,7 +34,10 @@ 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); +assert.equal(await backend.getSize(1),4); +assert.deepEqual(requests,[]); +assert.equal(timers.length,0); +const first = backend.read(1,0,4,0); await settle(); pending[0](206); assert.equal(await first,4); @@ -59,7 +62,7 @@ assert.equal(requests.at(-1),'boots_sand_05.wav'); pending[2](404); pending[3](206); await settle(); -const retried = backend.getSize(3); +const retried = backend.read(3,0,4,0); await settle(); assert.equal(requests.at(-1),'boots_sand_03.wav'); pending[4](206); @@ -80,7 +83,7 @@ await library._wasmfs_create_fetch_backend_js(2); const footwear = context.wasmFS$backends[2]; for (const handle of names.keys()) await footwear.allocFile(handle); -const concrete = footwear.getSize(1); +const concrete = footwear.read(1,0,4,0); await settle(); pending[0](206); assert.equal(await concrete,4); diff --git a/src/tests/browser_sound_metadata.mjs b/src/tests/browser_sound_metadata.mjs @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; + +let library, requests = 0; +const context = vm.createContext({ + URL, UTF8ToString: value => value, stringToNewUTF8: value => value, + addToLibrary: value => { library = value; }, + XMLHttpRequest: class { + open(method, url) { + assert.equal(method, 'GET'); + assert.equal(url, 'http://example.test/browser-manifest'); + } + setRequestHeader(name, value) { + assert.equal(name, 'Accept'); + assert.equal(value, 'application/json'); + this.json = true; + } + send() { + ++requests; + this.status = 200; + this.responseText = this.json ? JSON.stringify({ + 'cd_image/sound/Test.wav': {size: 1234, version: 'one'}, + 'cd_image/data/file.dat': {size: 999, version: 'two'} + }) : 'cd_image/\ncd_image/sound/\ncd_image/sound/Test.wav\nPrefs/\n'; + } + } +}); +vm.runInContext(fs.readFileSync(new URL('../runtime/browser_host.js', import.meta.url), 'utf8'), context); +context.AOSoundSizes = library.$AOSoundSizes; + +const listing = library.ao_asset_manifest('http://example.test/browser-assets'); +const initializedRequests = requests; +const sizes = ['cd_image/sound/Test.wav', '.\\CD_IMAGE\\SOUND\\TEST.WAV', + 'cd_image/sound/missing.wav'].map(library.ao_sound_file_size); + +assert.equal(listing, 'cd_image/\ncd_image/sound/\ncd_image/sound/Test.wav\nPrefs/\n'); +assert.deepEqual(sizes, [1234, 1234, -1]); +assert.equal(requests, initializedRequests); +assert.equal(requests, 2); +console.log('PASS: sound sizes use startup metadata without filesystem access or later requests');